5e2ace721166b56df19e176eac99ad169364f297
[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
73 #include <fcntl.h>
74 #include "gdb_string.h"
75 #include "gdb_assert.h"
76 #include <sys/types.h>
77
78 typedef struct symbol *symbolp;
79 DEF_VEC_P (symbolp);
80
81 /* When non-zero, print basic high level tracing messages.
82    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
83 static int dwarf2_read_debug = 0;
84
85 /* When non-zero, dump DIEs after they are read in.  */
86 static unsigned int dwarf2_die_debug = 0;
87
88 /* When non-zero, cross-check physname against demangler.  */
89 static int check_physname = 0;
90
91 /* When non-zero, do not reject deprecated .gdb_index sections.  */
92 static int use_deprecated_index_sections = 0;
93
94 static const struct objfile_data *dwarf2_objfile_data_key;
95
96 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
97
98 static int dwarf2_locexpr_index;
99 static int dwarf2_loclist_index;
100 static int dwarf2_locexpr_block_index;
101 static int dwarf2_loclist_block_index;
102
103 /* A descriptor for dwarf sections.
104
105    S.ASECTION, SIZE are typically initialized when the objfile is first
106    scanned.  BUFFER, READIN are filled in later when the section is read.
107    If the section contained compressed data then SIZE is updated to record
108    the uncompressed size of the section.
109
110    DWP file format V2 introduces a wrinkle that is easiest to handle by
111    creating the concept of virtual sections contained within a real section.
112    In DWP V2 the sections of the input DWO files are concatenated together
113    into one section, but section offsets are kept relative to the original
114    input section.
115    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
116    the real section this "virtual" section is contained in, and BUFFER,SIZE
117    describe the virtual section.  */
118
119 struct dwarf2_section_info
120 {
121   union
122   {
123     /* If this is a real section, the bfd section.  */
124     asection *asection;
125     /* If this is a virtual section, pointer to the containing ("real")
126        section.  */
127     struct dwarf2_section_info *containing_section;
128   } s;
129   /* Pointer to section data, only valid if readin.  */
130   const gdb_byte *buffer;
131   /* The size of the section, real or virtual.  */
132   bfd_size_type size;
133   /* If this is a virtual section, the offset in the real section.
134      Only valid if is_virtual.  */
135   bfd_size_type virtual_offset;
136   /* True if we have tried to read this section.  */
137   char readin;
138   /* True if this is a virtual section, False otherwise.
139      This specifies which of s.asection and s.containing_section to use.  */
140   char is_virtual;
141 };
142
143 typedef struct dwarf2_section_info dwarf2_section_info_def;
144 DEF_VEC_O (dwarf2_section_info_def);
145
146 /* All offsets in the index are of this type.  It must be
147    architecture-independent.  */
148 typedef uint32_t offset_type;
149
150 DEF_VEC_I (offset_type);
151
152 /* Ensure only legit values are used.  */
153 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
154   do { \
155     gdb_assert ((unsigned int) (value) <= 1); \
156     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
157   } while (0)
158
159 /* Ensure only legit values are used.  */
160 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
161   do { \
162     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
163                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
164     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
165   } while (0)
166
167 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
168 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
169   do { \
170     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
171     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
172   } while (0)
173
174 /* A description of the mapped index.  The file format is described in
175    a comment by the code that writes the index.  */
176 struct mapped_index
177 {
178   /* Index data format version.  */
179   int version;
180
181   /* The total length of the buffer.  */
182   off_t total_size;
183
184   /* A pointer to the address table data.  */
185   const gdb_byte *address_table;
186
187   /* Size of the address table data in bytes.  */
188   offset_type address_table_size;
189
190   /* The symbol table, implemented as a hash table.  */
191   const offset_type *symbol_table;
192
193   /* Size in slots, each slot is 2 offset_types.  */
194   offset_type symbol_table_slots;
195
196   /* A pointer to the constant pool.  */
197   const char *constant_pool;
198 };
199
200 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
201 DEF_VEC_P (dwarf2_per_cu_ptr);
202
203 /* Collection of data recorded per objfile.
204    This hangs off of dwarf2_objfile_data_key.  */
205
206 struct dwarf2_per_objfile
207 {
208   struct dwarf2_section_info info;
209   struct dwarf2_section_info abbrev;
210   struct dwarf2_section_info line;
211   struct dwarf2_section_info loc;
212   struct dwarf2_section_info macinfo;
213   struct dwarf2_section_info macro;
214   struct dwarf2_section_info str;
215   struct dwarf2_section_info ranges;
216   struct dwarf2_section_info addr;
217   struct dwarf2_section_info frame;
218   struct dwarf2_section_info eh_frame;
219   struct dwarf2_section_info gdb_index;
220
221   VEC (dwarf2_section_info_def) *types;
222
223   /* Back link.  */
224   struct objfile *objfile;
225
226   /* Table of all the compilation units.  This is used to locate
227      the target compilation unit of a particular reference.  */
228   struct dwarf2_per_cu_data **all_comp_units;
229
230   /* The number of compilation units in ALL_COMP_UNITS.  */
231   int n_comp_units;
232
233   /* The number of .debug_types-related CUs.  */
234   int n_type_units;
235
236   /* The .debug_types-related CUs (TUs).
237      This is stored in malloc space because we may realloc it.  */
238   struct signatured_type **all_type_units;
239
240   /* The number of entries in all_type_unit_groups.  */
241   int n_type_unit_groups;
242
243   /* Table of type unit groups.
244      This exists to make it easy to iterate over all CUs and TU groups.  */
245   struct type_unit_group **all_type_unit_groups;
246
247   /* Table of struct type_unit_group objects.
248      The hash key is the DW_AT_stmt_list value.  */
249   htab_t type_unit_groups;
250
251   /* A table mapping .debug_types signatures to its signatured_type entry.
252      This is NULL if the .debug_types section hasn't been read in yet.  */
253   htab_t signatured_types;
254
255   /* Type unit statistics, to see how well the scaling improvements
256      are doing.  */
257   struct tu_stats
258   {
259     int nr_uniq_abbrev_tables;
260     int nr_symtabs;
261     int nr_symtab_sharers;
262     int nr_stmt_less_type_units;
263   } tu_stats;
264
265   /* A chain of compilation units that are currently read in, so that
266      they can be freed later.  */
267   struct dwarf2_per_cu_data *read_in_chain;
268
269   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
270      This is NULL if the table hasn't been allocated yet.  */
271   htab_t dwo_files;
272
273   /* Non-zero if we've check for whether there is a DWP file.  */
274   int dwp_checked;
275
276   /* The DWP file if there is one, or NULL.  */
277   struct dwp_file *dwp_file;
278
279   /* The shared '.dwz' file, if one exists.  This is used when the
280      original data was compressed using 'dwz -m'.  */
281   struct dwz_file *dwz_file;
282
283   /* A flag indicating wether this objfile has a section loaded at a
284      VMA of 0.  */
285   int has_section_at_zero;
286
287   /* True if we are using the mapped index,
288      or we are faking it for OBJF_READNOW's sake.  */
289   unsigned char using_index;
290
291   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
292   struct mapped_index *index_table;
293
294   /* When using index_table, this keeps track of all quick_file_names entries.
295      TUs typically share line table entries with a CU, so we maintain a
296      separate table of all line table entries to support the sharing.
297      Note that while there can be way more TUs than CUs, we've already
298      sorted all the TUs into "type unit groups", grouped by their
299      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
300      CU and its associated TU group if there is one.  */
301   htab_t quick_file_names_table;
302
303   /* Set during partial symbol reading, to prevent queueing of full
304      symbols.  */
305   int reading_partial_symbols;
306
307   /* Table mapping type DIEs to their struct type *.
308      This is NULL if not allocated yet.
309      The mapping is done via (CU/TU + DIE offset) -> type.  */
310   htab_t die_type_hash;
311
312   /* The CUs we recently read.  */
313   VEC (dwarf2_per_cu_ptr) *just_read_cus;
314 };
315
316 static struct dwarf2_per_objfile *dwarf2_per_objfile;
317
318 /* Default names of the debugging sections.  */
319
320 /* Note that if the debugging section has been compressed, it might
321    have a name like .zdebug_info.  */
322
323 static const struct dwarf2_debug_sections dwarf2_elf_names =
324 {
325   { ".debug_info", ".zdebug_info" },
326   { ".debug_abbrev", ".zdebug_abbrev" },
327   { ".debug_line", ".zdebug_line" },
328   { ".debug_loc", ".zdebug_loc" },
329   { ".debug_macinfo", ".zdebug_macinfo" },
330   { ".debug_macro", ".zdebug_macro" },
331   { ".debug_str", ".zdebug_str" },
332   { ".debug_ranges", ".zdebug_ranges" },
333   { ".debug_types", ".zdebug_types" },
334   { ".debug_addr", ".zdebug_addr" },
335   { ".debug_frame", ".zdebug_frame" },
336   { ".eh_frame", NULL },
337   { ".gdb_index", ".zgdb_index" },
338   23
339 };
340
341 /* List of DWO/DWP sections.  */
342
343 static const struct dwop_section_names
344 {
345   struct dwarf2_section_names abbrev_dwo;
346   struct dwarf2_section_names info_dwo;
347   struct dwarf2_section_names line_dwo;
348   struct dwarf2_section_names loc_dwo;
349   struct dwarf2_section_names macinfo_dwo;
350   struct dwarf2_section_names macro_dwo;
351   struct dwarf2_section_names str_dwo;
352   struct dwarf2_section_names str_offsets_dwo;
353   struct dwarf2_section_names types_dwo;
354   struct dwarf2_section_names cu_index;
355   struct dwarf2_section_names tu_index;
356 }
357 dwop_section_names =
358 {
359   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
360   { ".debug_info.dwo", ".zdebug_info.dwo" },
361   { ".debug_line.dwo", ".zdebug_line.dwo" },
362   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
363   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
364   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
365   { ".debug_str.dwo", ".zdebug_str.dwo" },
366   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
367   { ".debug_types.dwo", ".zdebug_types.dwo" },
368   { ".debug_cu_index", ".zdebug_cu_index" },
369   { ".debug_tu_index", ".zdebug_tu_index" },
370 };
371
372 /* local data types */
373
374 /* The data in a compilation unit header, after target2host
375    translation, looks like this.  */
376 struct comp_unit_head
377 {
378   unsigned int length;
379   short version;
380   unsigned char addr_size;
381   unsigned char signed_addr_p;
382   sect_offset abbrev_offset;
383
384   /* Size of file offsets; either 4 or 8.  */
385   unsigned int offset_size;
386
387   /* Size of the length field; either 4 or 12.  */
388   unsigned int initial_length_size;
389
390   /* Offset to the first byte of this compilation unit header in the
391      .debug_info section, for resolving relative reference dies.  */
392   sect_offset offset;
393
394   /* Offset to first die in this cu from the start of the cu.
395      This will be the first byte following the compilation unit header.  */
396   cu_offset first_die_offset;
397 };
398
399 /* Type used for delaying computation of method physnames.
400    See comments for compute_delayed_physnames.  */
401 struct delayed_method_info
402 {
403   /* The type to which the method is attached, i.e., its parent class.  */
404   struct type *type;
405
406   /* The index of the method in the type's function fieldlists.  */
407   int fnfield_index;
408
409   /* The index of the method in the fieldlist.  */
410   int index;
411
412   /* The name of the DIE.  */
413   const char *name;
414
415   /*  The DIE associated with this method.  */
416   struct die_info *die;
417 };
418
419 typedef struct delayed_method_info delayed_method_info;
420 DEF_VEC_O (delayed_method_info);
421
422 /* Internal state when decoding a particular compilation unit.  */
423 struct dwarf2_cu
424 {
425   /* The objfile containing this compilation unit.  */
426   struct objfile *objfile;
427
428   /* The header of the compilation unit.  */
429   struct comp_unit_head header;
430
431   /* Base address of this compilation unit.  */
432   CORE_ADDR base_address;
433
434   /* Non-zero if base_address has been set.  */
435   int base_known;
436
437   /* The language we are debugging.  */
438   enum language language;
439   const struct language_defn *language_defn;
440
441   const char *producer;
442
443   /* The generic symbol table building routines have separate lists for
444      file scope symbols and all all other scopes (local scopes).  So
445      we need to select the right one to pass to add_symbol_to_list().
446      We do it by keeping a pointer to the correct list in list_in_scope.
447
448      FIXME: The original dwarf code just treated the file scope as the
449      first local scope, and all other local scopes as nested local
450      scopes, and worked fine.  Check to see if we really need to
451      distinguish these in buildsym.c.  */
452   struct pending **list_in_scope;
453
454   /* The abbrev table for this CU.
455      Normally this points to the abbrev table in the objfile.
456      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
457   struct abbrev_table *abbrev_table;
458
459   /* Hash table holding all the loaded partial DIEs
460      with partial_die->offset.SECT_OFF as hash.  */
461   htab_t partial_dies;
462
463   /* Storage for things with the same lifetime as this read-in compilation
464      unit, including partial DIEs.  */
465   struct obstack comp_unit_obstack;
466
467   /* When multiple dwarf2_cu structures are living in memory, this field
468      chains them all together, so that they can be released efficiently.
469      We will probably also want a generation counter so that most-recently-used
470      compilation units are cached...  */
471   struct dwarf2_per_cu_data *read_in_chain;
472
473   /* Backlink to our per_cu entry.  */
474   struct dwarf2_per_cu_data *per_cu;
475
476   /* How many compilation units ago was this CU last referenced?  */
477   int last_used;
478
479   /* A hash table of DIE cu_offset for following references with
480      die_info->offset.sect_off as hash.  */
481   htab_t die_hash;
482
483   /* Full DIEs if read in.  */
484   struct die_info *dies;
485
486   /* A set of pointers to dwarf2_per_cu_data objects for compilation
487      units referenced by this one.  Only set during full symbol processing;
488      partial symbol tables do not have dependencies.  */
489   htab_t dependencies;
490
491   /* Header data from the line table, during full symbol processing.  */
492   struct line_header *line_header;
493
494   /* A list of methods which need to have physnames computed
495      after all type information has been read.  */
496   VEC (delayed_method_info) *method_list;
497
498   /* To be copied to symtab->call_site_htab.  */
499   htab_t call_site_htab;
500
501   /* Non-NULL if this CU came from a DWO file.
502      There is an invariant here that is important to remember:
503      Except for attributes copied from the top level DIE in the "main"
504      (or "stub") file in preparation for reading the DWO file
505      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
506      Either there isn't a DWO file (in which case this is NULL and the point
507      is moot), or there is and either we're not going to read it (in which
508      case this is NULL) or there is and we are reading it (in which case this
509      is non-NULL).  */
510   struct dwo_unit *dwo_unit;
511
512   /* The DW_AT_addr_base attribute if present, zero otherwise
513      (zero is a valid value though).
514      Note this value comes from the stub CU/TU's DIE.  */
515   ULONGEST addr_base;
516
517   /* The DW_AT_ranges_base attribute if present, zero otherwise
518      (zero is a valid value though).
519      Note this value comes from the stub CU/TU's DIE.
520      Also note that the value is zero in the non-DWO case so this value can
521      be used without needing to know whether DWO files are in use or not.
522      N.B. This does not apply to DW_AT_ranges appearing in
523      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
524      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
525      DW_AT_ranges_base *would* have to be applied, and we'd have to care
526      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
527   ULONGEST ranges_base;
528
529   /* Mark used when releasing cached dies.  */
530   unsigned int mark : 1;
531
532   /* This CU references .debug_loc.  See the symtab->locations_valid field.
533      This test is imperfect as there may exist optimized debug code not using
534      any location list and still facing inlining issues if handled as
535      unoptimized code.  For a future better test see GCC PR other/32998.  */
536   unsigned int has_loclist : 1;
537
538   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
539      if all the producer_is_* fields are valid.  This information is cached
540      because profiling CU expansion showed excessive time spent in
541      producer_is_gxx_lt_4_6.  */
542   unsigned int checked_producer : 1;
543   unsigned int producer_is_gxx_lt_4_6 : 1;
544   unsigned int producer_is_gcc_lt_4_3 : 1;
545   unsigned int producer_is_icc : 1;
546
547   /* When set, the file that we're processing is known to have
548      debugging info for C++ namespaces.  GCC 3.3.x did not produce
549      this information, but later versions do.  */
550
551   unsigned int processing_has_namespace_info : 1;
552 };
553
554 /* Persistent data held for a compilation unit, even when not
555    processing it.  We put a pointer to this structure in the
556    read_symtab_private field of the psymtab.  */
557
558 struct dwarf2_per_cu_data
559 {
560   /* The start offset and length of this compilation unit.
561      NOTE: Unlike comp_unit_head.length, this length includes
562      initial_length_size.
563      If the DIE refers to a DWO file, this is always of the original die,
564      not the DWO file.  */
565   sect_offset offset;
566   unsigned int length;
567
568   /* Flag indicating this compilation unit will be read in before
569      any of the current compilation units are processed.  */
570   unsigned int queued : 1;
571
572   /* This flag will be set when reading partial DIEs if we need to load
573      absolutely all DIEs for this compilation unit, instead of just the ones
574      we think are interesting.  It gets set if we look for a DIE in the
575      hash table and don't find it.  */
576   unsigned int load_all_dies : 1;
577
578   /* Non-zero if this CU is from .debug_types.
579      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
580      this is non-zero.  */
581   unsigned int is_debug_types : 1;
582
583   /* Non-zero if this CU is from the .dwz file.  */
584   unsigned int is_dwz : 1;
585
586   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
587      This flag is only valid if is_debug_types is true.
588      We can't read a CU directly from a DWO file: There are required
589      attributes in the stub.  */
590   unsigned int reading_dwo_directly : 1;
591
592   /* Non-zero if the TU has been read.
593      This is used to assist the "Stay in DWO Optimization" for Fission:
594      When reading a DWO, it's faster to read TUs from the DWO instead of
595      fetching them from random other DWOs (due to comdat folding).
596      If the TU has already been read, the optimization is unnecessary
597      (and unwise - we don't want to change where gdb thinks the TU lives
598      "midflight").
599      This flag is only valid if is_debug_types is true.  */
600   unsigned int tu_read : 1;
601
602   /* The section this CU/TU lives in.
603      If the DIE refers to a DWO file, this is always the original die,
604      not the DWO file.  */
605   struct dwarf2_section_info *section;
606
607   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
608      of the CU cache it gets reset to NULL again.  */
609   struct dwarf2_cu *cu;
610
611   /* The corresponding objfile.
612      Normally we can get the objfile from dwarf2_per_objfile.
613      However we can enter this file with just a "per_cu" handle.  */
614   struct objfile *objfile;
615
616   /* When using partial symbol tables, the 'psymtab' field is active.
617      Otherwise the 'quick' field is active.  */
618   union
619   {
620     /* The partial symbol table associated with this compilation unit,
621        or NULL for unread partial units.  */
622     struct partial_symtab *psymtab;
623
624     /* Data needed by the "quick" functions.  */
625     struct dwarf2_per_cu_quick_data *quick;
626   } v;
627
628   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
629      while reading psymtabs, used to compute the psymtab dependencies,
630      and then cleared.  Then it is filled in again while reading full
631      symbols, and only deleted when the objfile is destroyed.
632
633      This is also used to work around a difference between the way gold
634      generates .gdb_index version <=7 and the way gdb does.  Arguably this
635      is a gold bug.  For symbols coming from TUs, gold records in the index
636      the CU that includes the TU instead of the TU itself.  This breaks
637      dw2_lookup_symbol: It assumes that if the index says symbol X lives
638      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
639      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
640      we need to look in TU Z to find X.  Fortunately, this is akin to
641      DW_TAG_imported_unit, so we just use the same mechanism: For
642      .gdb_index version <=7 this also records the TUs that the CU referred
643      to.  Concurrently with this change gdb was modified to emit version 8
644      indices so we only pay a price for gold generated indices.
645      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
646   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
647 };
648
649 /* Entry in the signatured_types hash table.  */
650
651 struct signatured_type
652 {
653   /* The "per_cu" object of this type.
654      This struct is used iff per_cu.is_debug_types.
655      N.B.: This is the first member so that it's easy to convert pointers
656      between them.  */
657   struct dwarf2_per_cu_data per_cu;
658
659   /* The type's signature.  */
660   ULONGEST signature;
661
662   /* Offset in the TU of the type's DIE, as read from the TU header.
663      If this TU is a DWO stub and the definition lives in a DWO file
664      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
665   cu_offset type_offset_in_tu;
666
667   /* Offset in the section of the type's DIE.
668      If the definition lives in a DWO file, this is the offset in the
669      .debug_types.dwo section.
670      The value is zero until the actual value is known.
671      Zero is otherwise not a valid section offset.  */
672   sect_offset type_offset_in_section;
673
674   /* Type units are grouped by their DW_AT_stmt_list entry so that they
675      can share them.  This points to the containing symtab.  */
676   struct type_unit_group *type_unit_group;
677
678   /* The type.
679      The first time we encounter this type we fully read it in and install it
680      in the symbol tables.  Subsequent times we only need the type.  */
681   struct type *type;
682
683   /* Containing DWO unit.
684      This field is valid iff per_cu.reading_dwo_directly.  */
685   struct dwo_unit *dwo_unit;
686 };
687
688 typedef struct signatured_type *sig_type_ptr;
689 DEF_VEC_P (sig_type_ptr);
690
691 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
692    This includes type_unit_group and quick_file_names.  */
693
694 struct stmt_list_hash
695 {
696   /* The DWO unit this table is from or NULL if there is none.  */
697   struct dwo_unit *dwo_unit;
698
699   /* Offset in .debug_line or .debug_line.dwo.  */
700   sect_offset line_offset;
701 };
702
703 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
704    an object of this type.  */
705
706 struct type_unit_group
707 {
708   /* dwarf2read.c's main "handle" on a TU symtab.
709      To simplify things we create an artificial CU that "includes" all the
710      type units using this stmt_list so that the rest of the code still has
711      a "per_cu" handle on the symtab.
712      This PER_CU is recognized by having no section.  */
713 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
714   struct dwarf2_per_cu_data per_cu;
715
716   /* The TUs that share this DW_AT_stmt_list entry.
717      This is added to while parsing type units to build partial symtabs,
718      and is deleted afterwards and not used again.  */
719   VEC (sig_type_ptr) *tus;
720
721   /* The primary symtab.
722      Type units in a group needn't all be defined in the same source file,
723      so we create an essentially anonymous symtab as the primary symtab.  */
724   struct symtab *primary_symtab;
725
726   /* The data used to construct the hash key.  */
727   struct stmt_list_hash hash;
728
729   /* The number of symtabs from the line header.
730      The value here must match line_header.num_file_names.  */
731   unsigned int num_symtabs;
732
733   /* The symbol tables for this TU (obtained from the files listed in
734      DW_AT_stmt_list).
735      WARNING: The order of entries here must match the order of entries
736      in the line header.  After the first TU using this type_unit_group, the
737      line header for the subsequent TUs is recreated from this.  This is done
738      because we need to use the same symtabs for each TU using the same
739      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
740      there's no guarantee the line header doesn't have duplicate entries.  */
741   struct symtab **symtabs;
742 };
743
744 /* These sections are what may appear in a (real or virtual) DWO file.  */
745
746 struct dwo_sections
747 {
748   struct dwarf2_section_info abbrev;
749   struct dwarf2_section_info line;
750   struct dwarf2_section_info loc;
751   struct dwarf2_section_info macinfo;
752   struct dwarf2_section_info macro;
753   struct dwarf2_section_info str;
754   struct dwarf2_section_info str_offsets;
755   /* In the case of a virtual DWO file, these two are unused.  */
756   struct dwarf2_section_info info;
757   VEC (dwarf2_section_info_def) *types;
758 };
759
760 /* CUs/TUs in DWP/DWO files.  */
761
762 struct dwo_unit
763 {
764   /* Backlink to the containing struct dwo_file.  */
765   struct dwo_file *dwo_file;
766
767   /* The "id" that distinguishes this CU/TU.
768      .debug_info calls this "dwo_id", .debug_types calls this "signature".
769      Since signatures came first, we stick with it for consistency.  */
770   ULONGEST signature;
771
772   /* The section this CU/TU lives in, in the DWO file.  */
773   struct dwarf2_section_info *section;
774
775   /* Same as dwarf2_per_cu_data:{offset,length} but in the DWO section.  */
776   sect_offset offset;
777   unsigned int length;
778
779   /* For types, offset in the type's DIE of the type defined by this TU.  */
780   cu_offset type_offset_in_tu;
781 };
782
783 /* include/dwarf2.h defines the DWP section codes.
784    It defines a max value but it doesn't define a min value, which we
785    use for error checking, so provide one.  */
786
787 enum dwp_v2_section_ids
788 {
789   DW_SECT_MIN = 1
790 };
791
792 /* Data for one DWO file.
793
794    This includes virtual DWO files (a virtual DWO file is a DWO file as it
795    appears in a DWP file).  DWP files don't really have DWO files per se -
796    comdat folding of types "loses" the DWO file they came from, and from
797    a high level view DWP files appear to contain a mass of random types.
798    However, to maintain consistency with the non-DWP case we pretend DWP
799    files contain virtual DWO files, and we assign each TU with one virtual
800    DWO file (generally based on the line and abbrev section offsets -
801    a heuristic that seems to work in practice).  */
802
803 struct dwo_file
804 {
805   /* The DW_AT_GNU_dwo_name attribute.
806      For virtual DWO files the name is constructed from the section offsets
807      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
808      from related CU+TUs.  */
809   const char *dwo_name;
810
811   /* The DW_AT_comp_dir attribute.  */
812   const char *comp_dir;
813
814   /* The bfd, when the file is open.  Otherwise this is NULL.
815      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
816   bfd *dbfd;
817
818   /* The sections that make up this DWO file.
819      Remember that for virtual DWO files in DWP V2, these are virtual
820      sections (for lack of a better name).  */
821   struct dwo_sections sections;
822
823   /* The CU in the file.
824      We only support one because having more than one requires hacking the
825      dwo_name of each to match, which is highly unlikely to happen.
826      Doing this means all TUs can share comp_dir: We also assume that
827      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
828   struct dwo_unit *cu;
829
830   /* Table of TUs in the file.
831      Each element is a struct dwo_unit.  */
832   htab_t tus;
833 };
834
835 /* These sections are what may appear in a DWP file.  */
836
837 struct dwp_sections
838 {
839   /* These are used by both DWP version 1 and 2.  */
840   struct dwarf2_section_info str;
841   struct dwarf2_section_info cu_index;
842   struct dwarf2_section_info tu_index;
843
844   /* These are only used by DWP version 2 files.
845      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
846      sections are referenced by section number, and are not recorded here.
847      In DWP version 2 there is at most one copy of all these sections, each
848      section being (effectively) comprised of the concatenation of all of the
849      individual sections that exist in the version 1 format.
850      To keep the code simple we treat each of these concatenated pieces as a
851      section itself (a virtual section?).  */
852   struct dwarf2_section_info abbrev;
853   struct dwarf2_section_info info;
854   struct dwarf2_section_info line;
855   struct dwarf2_section_info loc;
856   struct dwarf2_section_info macinfo;
857   struct dwarf2_section_info macro;
858   struct dwarf2_section_info str_offsets;
859   struct dwarf2_section_info types;
860 };
861
862 /* These sections are what may appear in a virtual DWO file in DWP version 1.
863    A virtual DWO file is a DWO file as it appears in a DWP file.  */
864
865 struct virtual_v1_dwo_sections
866 {
867   struct dwarf2_section_info abbrev;
868   struct dwarf2_section_info line;
869   struct dwarf2_section_info loc;
870   struct dwarf2_section_info macinfo;
871   struct dwarf2_section_info macro;
872   struct dwarf2_section_info str_offsets;
873   /* Each DWP hash table entry records one CU or one TU.
874      That is recorded here, and copied to dwo_unit.section.  */
875   struct dwarf2_section_info info_or_types;
876 };
877
878 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
879    In version 2, the sections of the DWO files are concatenated together
880    and stored in one section of that name.  Thus each ELF section contains
881    several "virtual" sections.  */
882
883 struct virtual_v2_dwo_sections
884 {
885   bfd_size_type abbrev_offset;
886   bfd_size_type abbrev_size;
887
888   bfd_size_type line_offset;
889   bfd_size_type line_size;
890
891   bfd_size_type loc_offset;
892   bfd_size_type loc_size;
893
894   bfd_size_type macinfo_offset;
895   bfd_size_type macinfo_size;
896
897   bfd_size_type macro_offset;
898   bfd_size_type macro_size;
899
900   bfd_size_type str_offsets_offset;
901   bfd_size_type str_offsets_size;
902
903   /* Each DWP hash table entry records one CU or one TU.
904      That is recorded here, and copied to dwo_unit.section.  */
905   bfd_size_type info_or_types_offset;
906   bfd_size_type info_or_types_size;
907 };
908
909 /* Contents of DWP hash tables.  */
910
911 struct dwp_hash_table
912 {
913   uint32_t version, nr_columns;
914   uint32_t nr_units, nr_slots;
915   const gdb_byte *hash_table, *unit_table;
916   union
917   {
918     struct
919     {
920       const gdb_byte *indices;
921     } v1;
922     struct
923     {
924       /* This is indexed by column number and gives the id of the section
925          in that column.  */
926 #define MAX_NR_V2_DWO_SECTIONS \
927   (1 /* .debug_info or .debug_types */ \
928    + 1 /* .debug_abbrev */ \
929    + 1 /* .debug_line */ \
930    + 1 /* .debug_loc */ \
931    + 1 /* .debug_str_offsets */ \
932    + 1 /* .debug_macro or .debug_macinfo */)
933       int section_ids[MAX_NR_V2_DWO_SECTIONS];
934       const gdb_byte *offsets;
935       const gdb_byte *sizes;
936     } v2;
937   } section_pool;
938 };
939
940 /* Data for one DWP file.  */
941
942 struct dwp_file
943 {
944   /* Name of the file.  */
945   const char *name;
946
947   /* File format version.  */
948   int version;
949
950   /* The bfd.  */
951   bfd *dbfd;
952
953   /* Section info for this file.  */
954   struct dwp_sections sections;
955
956   /* Table of CUs in the file.  */
957   const struct dwp_hash_table *cus;
958
959   /* Table of TUs in the file.  */
960   const struct dwp_hash_table *tus;
961
962   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
963   htab_t loaded_cus;
964   htab_t loaded_tus;
965
966   /* Table to map ELF section numbers to their sections.
967      This is only needed for the DWP V1 file format.  */
968   unsigned int num_sections;
969   asection **elf_sections;
970 };
971
972 /* This represents a '.dwz' file.  */
973
974 struct dwz_file
975 {
976   /* A dwz file can only contain a few sections.  */
977   struct dwarf2_section_info abbrev;
978   struct dwarf2_section_info info;
979   struct dwarf2_section_info str;
980   struct dwarf2_section_info line;
981   struct dwarf2_section_info macro;
982   struct dwarf2_section_info gdb_index;
983
984   /* The dwz's BFD.  */
985   bfd *dwz_bfd;
986 };
987
988 /* Struct used to pass misc. parameters to read_die_and_children, et
989    al.  which are used for both .debug_info and .debug_types dies.
990    All parameters here are unchanging for the life of the call.  This
991    struct exists to abstract away the constant parameters of die reading.  */
992
993 struct die_reader_specs
994 {
995   /* The bfd of die_section.  */
996   bfd* abfd;
997
998   /* The CU of the DIE we are parsing.  */
999   struct dwarf2_cu *cu;
1000
1001   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1002   struct dwo_file *dwo_file;
1003
1004   /* The section the die comes from.
1005      This is either .debug_info or .debug_types, or the .dwo variants.  */
1006   struct dwarf2_section_info *die_section;
1007
1008   /* die_section->buffer.  */
1009   const gdb_byte *buffer;
1010
1011   /* The end of the buffer.  */
1012   const gdb_byte *buffer_end;
1013
1014   /* The value of the DW_AT_comp_dir attribute.  */
1015   const char *comp_dir;
1016 };
1017
1018 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1019 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1020                                       const gdb_byte *info_ptr,
1021                                       struct die_info *comp_unit_die,
1022                                       int has_children,
1023                                       void *data);
1024
1025 /* The line number information for a compilation unit (found in the
1026    .debug_line section) begins with a "statement program header",
1027    which contains the following information.  */
1028 struct line_header
1029 {
1030   unsigned int total_length;
1031   unsigned short version;
1032   unsigned int header_length;
1033   unsigned char minimum_instruction_length;
1034   unsigned char maximum_ops_per_instruction;
1035   unsigned char default_is_stmt;
1036   int line_base;
1037   unsigned char line_range;
1038   unsigned char opcode_base;
1039
1040   /* standard_opcode_lengths[i] is the number of operands for the
1041      standard opcode whose value is i.  This means that
1042      standard_opcode_lengths[0] is unused, and the last meaningful
1043      element is standard_opcode_lengths[opcode_base - 1].  */
1044   unsigned char *standard_opcode_lengths;
1045
1046   /* The include_directories table.  NOTE!  These strings are not
1047      allocated with xmalloc; instead, they are pointers into
1048      debug_line_buffer.  If you try to free them, `free' will get
1049      indigestion.  */
1050   unsigned int num_include_dirs, include_dirs_size;
1051   const char **include_dirs;
1052
1053   /* The file_names table.  NOTE!  These strings are not allocated
1054      with xmalloc; instead, they are pointers into debug_line_buffer.
1055      Don't try to free them directly.  */
1056   unsigned int num_file_names, file_names_size;
1057   struct file_entry
1058   {
1059     const char *name;
1060     unsigned int dir_index;
1061     unsigned int mod_time;
1062     unsigned int length;
1063     int included_p; /* Non-zero if referenced by the Line Number Program.  */
1064     struct symtab *symtab; /* The associated symbol table, if any.  */
1065   } *file_names;
1066
1067   /* The start and end of the statement program following this
1068      header.  These point into dwarf2_per_objfile->line_buffer.  */
1069   const gdb_byte *statement_program_start, *statement_program_end;
1070 };
1071
1072 /* When we construct a partial symbol table entry we only
1073    need this much information.  */
1074 struct partial_die_info
1075   {
1076     /* Offset of this DIE.  */
1077     sect_offset offset;
1078
1079     /* DWARF-2 tag for this DIE.  */
1080     ENUM_BITFIELD(dwarf_tag) tag : 16;
1081
1082     /* Assorted flags describing the data found in this DIE.  */
1083     unsigned int has_children : 1;
1084     unsigned int is_external : 1;
1085     unsigned int is_declaration : 1;
1086     unsigned int has_type : 1;
1087     unsigned int has_specification : 1;
1088     unsigned int has_pc_info : 1;
1089     unsigned int may_be_inlined : 1;
1090
1091     /* Flag set if the SCOPE field of this structure has been
1092        computed.  */
1093     unsigned int scope_set : 1;
1094
1095     /* Flag set if the DIE has a byte_size attribute.  */
1096     unsigned int has_byte_size : 1;
1097
1098     /* Flag set if any of the DIE's children are template arguments.  */
1099     unsigned int has_template_arguments : 1;
1100
1101     /* Flag set if fixup_partial_die has been called on this die.  */
1102     unsigned int fixup_called : 1;
1103
1104     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1105     unsigned int is_dwz : 1;
1106
1107     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1108     unsigned int spec_is_dwz : 1;
1109
1110     /* The name of this DIE.  Normally the value of DW_AT_name, but
1111        sometimes a default name for unnamed DIEs.  */
1112     const char *name;
1113
1114     /* The linkage name, if present.  */
1115     const char *linkage_name;
1116
1117     /* The scope to prepend to our children.  This is generally
1118        allocated on the comp_unit_obstack, so will disappear
1119        when this compilation unit leaves the cache.  */
1120     const char *scope;
1121
1122     /* Some data associated with the partial DIE.  The tag determines
1123        which field is live.  */
1124     union
1125     {
1126       /* The location description associated with this DIE, if any.  */
1127       struct dwarf_block *locdesc;
1128       /* The offset of an import, for DW_TAG_imported_unit.  */
1129       sect_offset offset;
1130     } d;
1131
1132     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1133     CORE_ADDR lowpc;
1134     CORE_ADDR highpc;
1135
1136     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1137        DW_AT_sibling, if any.  */
1138     /* NOTE: This member isn't strictly necessary, read_partial_die could
1139        return DW_AT_sibling values to its caller load_partial_dies.  */
1140     const gdb_byte *sibling;
1141
1142     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1143        DW_AT_specification (or DW_AT_abstract_origin or
1144        DW_AT_extension).  */
1145     sect_offset spec_offset;
1146
1147     /* Pointers to this DIE's parent, first child, and next sibling,
1148        if any.  */
1149     struct partial_die_info *die_parent, *die_child, *die_sibling;
1150   };
1151
1152 /* This data structure holds the information of an abbrev.  */
1153 struct abbrev_info
1154   {
1155     unsigned int number;        /* number identifying abbrev */
1156     enum dwarf_tag tag;         /* dwarf tag */
1157     unsigned short has_children;                /* boolean */
1158     unsigned short num_attrs;   /* number of attributes */
1159     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1160     struct abbrev_info *next;   /* next in chain */
1161   };
1162
1163 struct attr_abbrev
1164   {
1165     ENUM_BITFIELD(dwarf_attribute) name : 16;
1166     ENUM_BITFIELD(dwarf_form) form : 16;
1167   };
1168
1169 /* Size of abbrev_table.abbrev_hash_table.  */
1170 #define ABBREV_HASH_SIZE 121
1171
1172 /* Top level data structure to contain an abbreviation table.  */
1173
1174 struct abbrev_table
1175 {
1176   /* Where the abbrev table came from.
1177      This is used as a sanity check when the table is used.  */
1178   sect_offset offset;
1179
1180   /* Storage for the abbrev table.  */
1181   struct obstack abbrev_obstack;
1182
1183   /* Hash table of abbrevs.
1184      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1185      It could be statically allocated, but the previous code didn't so we
1186      don't either.  */
1187   struct abbrev_info **abbrevs;
1188 };
1189
1190 /* Attributes have a name and a value.  */
1191 struct attribute
1192   {
1193     ENUM_BITFIELD(dwarf_attribute) name : 16;
1194     ENUM_BITFIELD(dwarf_form) form : 15;
1195
1196     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1197        field should be in u.str (existing only for DW_STRING) but it is kept
1198        here for better struct attribute alignment.  */
1199     unsigned int string_is_canonical : 1;
1200
1201     union
1202       {
1203         const char *str;
1204         struct dwarf_block *blk;
1205         ULONGEST unsnd;
1206         LONGEST snd;
1207         CORE_ADDR addr;
1208         ULONGEST signature;
1209       }
1210     u;
1211   };
1212
1213 /* This data structure holds a complete die structure.  */
1214 struct die_info
1215   {
1216     /* DWARF-2 tag for this DIE.  */
1217     ENUM_BITFIELD(dwarf_tag) tag : 16;
1218
1219     /* Number of attributes */
1220     unsigned char num_attrs;
1221
1222     /* True if we're presently building the full type name for the
1223        type derived from this DIE.  */
1224     unsigned char building_fullname : 1;
1225
1226     /* Abbrev number */
1227     unsigned int abbrev;
1228
1229     /* Offset in .debug_info or .debug_types section.  */
1230     sect_offset offset;
1231
1232     /* The dies in a compilation unit form an n-ary tree.  PARENT
1233        points to this die's parent; CHILD points to the first child of
1234        this node; and all the children of a given node are chained
1235        together via their SIBLING fields.  */
1236     struct die_info *child;     /* Its first child, if any.  */
1237     struct die_info *sibling;   /* Its next sibling, if any.  */
1238     struct die_info *parent;    /* Its parent, if any.  */
1239
1240     /* An array of attributes, with NUM_ATTRS elements.  There may be
1241        zero, but it's not common and zero-sized arrays are not
1242        sufficiently portable C.  */
1243     struct attribute attrs[1];
1244   };
1245
1246 /* Get at parts of an attribute structure.  */
1247
1248 #define DW_STRING(attr)    ((attr)->u.str)
1249 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1250 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1251 #define DW_BLOCK(attr)     ((attr)->u.blk)
1252 #define DW_SND(attr)       ((attr)->u.snd)
1253 #define DW_ADDR(attr)      ((attr)->u.addr)
1254 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1255
1256 /* Blocks are a bunch of untyped bytes.  */
1257 struct dwarf_block
1258   {
1259     size_t size;
1260
1261     /* Valid only if SIZE is not zero.  */
1262     const gdb_byte *data;
1263   };
1264
1265 #ifndef ATTR_ALLOC_CHUNK
1266 #define ATTR_ALLOC_CHUNK 4
1267 #endif
1268
1269 /* Allocate fields for structs, unions and enums in this size.  */
1270 #ifndef DW_FIELD_ALLOC_CHUNK
1271 #define DW_FIELD_ALLOC_CHUNK 4
1272 #endif
1273
1274 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1275    but this would require a corresponding change in unpack_field_as_long
1276    and friends.  */
1277 static int bits_per_byte = 8;
1278
1279 /* The routines that read and process dies for a C struct or C++ class
1280    pass lists of data member fields and lists of member function fields
1281    in an instance of a field_info structure, as defined below.  */
1282 struct field_info
1283   {
1284     /* List of data member and baseclasses fields.  */
1285     struct nextfield
1286       {
1287         struct nextfield *next;
1288         int accessibility;
1289         int virtuality;
1290         struct field field;
1291       }
1292      *fields, *baseclasses;
1293
1294     /* Number of fields (including baseclasses).  */
1295     int nfields;
1296
1297     /* Number of baseclasses.  */
1298     int nbaseclasses;
1299
1300     /* Set if the accesibility of one of the fields is not public.  */
1301     int non_public_fields;
1302
1303     /* Member function fields array, entries are allocated in the order they
1304        are encountered in the object file.  */
1305     struct nextfnfield
1306       {
1307         struct nextfnfield *next;
1308         struct fn_field fnfield;
1309       }
1310      *fnfields;
1311
1312     /* Member function fieldlist array, contains name of possibly overloaded
1313        member function, number of overloaded member functions and a pointer
1314        to the head of the member function field chain.  */
1315     struct fnfieldlist
1316       {
1317         const char *name;
1318         int length;
1319         struct nextfnfield *head;
1320       }
1321      *fnfieldlists;
1322
1323     /* Number of entries in the fnfieldlists array.  */
1324     int nfnfields;
1325
1326     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1327        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1328     struct typedef_field_list
1329       {
1330         struct typedef_field field;
1331         struct typedef_field_list *next;
1332       }
1333     *typedef_field_list;
1334     unsigned typedef_field_list_count;
1335   };
1336
1337 /* One item on the queue of compilation units to read in full symbols
1338    for.  */
1339 struct dwarf2_queue_item
1340 {
1341   struct dwarf2_per_cu_data *per_cu;
1342   enum language pretend_language;
1343   struct dwarf2_queue_item *next;
1344 };
1345
1346 /* The current queue.  */
1347 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1348
1349 /* Loaded secondary compilation units are kept in memory until they
1350    have not been referenced for the processing of this many
1351    compilation units.  Set this to zero to disable caching.  Cache
1352    sizes of up to at least twenty will improve startup time for
1353    typical inter-CU-reference binaries, at an obvious memory cost.  */
1354 static int dwarf2_max_cache_age = 5;
1355 static void
1356 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1357                            struct cmd_list_element *c, const char *value)
1358 {
1359   fprintf_filtered (file, _("The upper bound on the age of cached "
1360                             "dwarf2 compilation units is %s.\n"),
1361                     value);
1362 }
1363 \f
1364 /* local function prototypes */
1365
1366 static const char *get_section_name (const struct dwarf2_section_info *);
1367
1368 static const char *get_section_file_name (const struct dwarf2_section_info *);
1369
1370 static void dwarf2_locate_sections (bfd *, asection *, void *);
1371
1372 static void dwarf2_find_base_address (struct die_info *die,
1373                                       struct dwarf2_cu *cu);
1374
1375 static struct partial_symtab *create_partial_symtab
1376   (struct dwarf2_per_cu_data *per_cu, const char *name);
1377
1378 static void dwarf2_build_psymtabs_hard (struct objfile *);
1379
1380 static void scan_partial_symbols (struct partial_die_info *,
1381                                   CORE_ADDR *, CORE_ADDR *,
1382                                   int, struct dwarf2_cu *);
1383
1384 static void add_partial_symbol (struct partial_die_info *,
1385                                 struct dwarf2_cu *);
1386
1387 static void add_partial_namespace (struct partial_die_info *pdi,
1388                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1389                                    int need_pc, struct dwarf2_cu *cu);
1390
1391 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1392                                 CORE_ADDR *highpc, int need_pc,
1393                                 struct dwarf2_cu *cu);
1394
1395 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1396                                      struct dwarf2_cu *cu);
1397
1398 static void add_partial_subprogram (struct partial_die_info *pdi,
1399                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1400                                     int need_pc, struct dwarf2_cu *cu);
1401
1402 static void dwarf2_read_symtab (struct partial_symtab *,
1403                                 struct objfile *);
1404
1405 static void psymtab_to_symtab_1 (struct partial_symtab *);
1406
1407 static struct abbrev_info *abbrev_table_lookup_abbrev
1408   (const struct abbrev_table *, unsigned int);
1409
1410 static struct abbrev_table *abbrev_table_read_table
1411   (struct dwarf2_section_info *, sect_offset);
1412
1413 static void abbrev_table_free (struct abbrev_table *);
1414
1415 static void abbrev_table_free_cleanup (void *);
1416
1417 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1418                                  struct dwarf2_section_info *);
1419
1420 static void dwarf2_free_abbrev_table (void *);
1421
1422 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1423
1424 static struct partial_die_info *load_partial_dies
1425   (const struct die_reader_specs *, const gdb_byte *, int);
1426
1427 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1428                                          struct partial_die_info *,
1429                                          struct abbrev_info *,
1430                                          unsigned int,
1431                                          const gdb_byte *);
1432
1433 static struct partial_die_info *find_partial_die (sect_offset, int,
1434                                                   struct dwarf2_cu *);
1435
1436 static void fixup_partial_die (struct partial_die_info *,
1437                                struct dwarf2_cu *);
1438
1439 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1440                                        struct attribute *, struct attr_abbrev *,
1441                                        const gdb_byte *);
1442
1443 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1444
1445 static int read_1_signed_byte (bfd *, const gdb_byte *);
1446
1447 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1448
1449 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1450
1451 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1452
1453 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1454                                unsigned int *);
1455
1456 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1457
1458 static LONGEST read_checked_initial_length_and_offset
1459   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1460    unsigned int *, unsigned int *);
1461
1462 static LONGEST read_offset (bfd *, const gdb_byte *,
1463                             const struct comp_unit_head *,
1464                             unsigned int *);
1465
1466 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1467
1468 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1469                                        sect_offset);
1470
1471 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1472
1473 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1474
1475 static const char *read_indirect_string (bfd *, const gdb_byte *,
1476                                          const struct comp_unit_head *,
1477                                          unsigned int *);
1478
1479 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1480
1481 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1482
1483 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1484
1485 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1486                                               const gdb_byte *,
1487                                               unsigned int *);
1488
1489 static const char *read_str_index (const struct die_reader_specs *reader,
1490                                    struct dwarf2_cu *cu, ULONGEST str_index);
1491
1492 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1493
1494 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1495                                       struct dwarf2_cu *);
1496
1497 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1498                                                 unsigned int);
1499
1500 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1501                                struct dwarf2_cu *cu);
1502
1503 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1504
1505 static struct die_info *die_specification (struct die_info *die,
1506                                            struct dwarf2_cu **);
1507
1508 static void free_line_header (struct line_header *lh);
1509
1510 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1511                                                      struct dwarf2_cu *cu);
1512
1513 static void dwarf_decode_lines (struct line_header *, const char *,
1514                                 struct dwarf2_cu *, struct partial_symtab *,
1515                                 int);
1516
1517 static void dwarf2_start_subfile (const char *, const char *, const char *);
1518
1519 static void dwarf2_start_symtab (struct dwarf2_cu *,
1520                                  const char *, const char *, CORE_ADDR);
1521
1522 static struct symbol *new_symbol (struct die_info *, struct type *,
1523                                   struct dwarf2_cu *);
1524
1525 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1526                                        struct dwarf2_cu *, struct symbol *);
1527
1528 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1529                                 struct dwarf2_cu *);
1530
1531 static void dwarf2_const_value_attr (const struct attribute *attr,
1532                                      struct type *type,
1533                                      const char *name,
1534                                      struct obstack *obstack,
1535                                      struct dwarf2_cu *cu, LONGEST *value,
1536                                      const gdb_byte **bytes,
1537                                      struct dwarf2_locexpr_baton **baton);
1538
1539 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1540
1541 static int need_gnat_info (struct dwarf2_cu *);
1542
1543 static struct type *die_descriptive_type (struct die_info *,
1544                                           struct dwarf2_cu *);
1545
1546 static void set_descriptive_type (struct type *, struct die_info *,
1547                                   struct dwarf2_cu *);
1548
1549 static struct type *die_containing_type (struct die_info *,
1550                                          struct dwarf2_cu *);
1551
1552 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1553                                      struct dwarf2_cu *);
1554
1555 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1556
1557 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1558
1559 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1560
1561 static char *typename_concat (struct obstack *obs, const char *prefix,
1562                               const char *suffix, int physname,
1563                               struct dwarf2_cu *cu);
1564
1565 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1566
1567 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1568
1569 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1570
1571 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1572
1573 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1574
1575 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1576                                struct dwarf2_cu *, struct partial_symtab *);
1577
1578 static int dwarf2_get_pc_bounds (struct die_info *,
1579                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1580                                  struct partial_symtab *);
1581
1582 static void get_scope_pc_bounds (struct die_info *,
1583                                  CORE_ADDR *, CORE_ADDR *,
1584                                  struct dwarf2_cu *);
1585
1586 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1587                                         CORE_ADDR, struct dwarf2_cu *);
1588
1589 static void dwarf2_add_field (struct field_info *, struct die_info *,
1590                               struct dwarf2_cu *);
1591
1592 static void dwarf2_attach_fields_to_type (struct field_info *,
1593                                           struct type *, struct dwarf2_cu *);
1594
1595 static void dwarf2_add_member_fn (struct field_info *,
1596                                   struct die_info *, struct type *,
1597                                   struct dwarf2_cu *);
1598
1599 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1600                                              struct type *,
1601                                              struct dwarf2_cu *);
1602
1603 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1604
1605 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1606
1607 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1608
1609 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1610
1611 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1612
1613 static struct type *read_module_type (struct die_info *die,
1614                                       struct dwarf2_cu *cu);
1615
1616 static const char *namespace_name (struct die_info *die,
1617                                    int *is_anonymous, struct dwarf2_cu *);
1618
1619 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1620
1621 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1622
1623 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1624                                                        struct dwarf2_cu *);
1625
1626 static struct die_info *read_die_and_siblings_1
1627   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1628    struct die_info *);
1629
1630 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1631                                                const gdb_byte *info_ptr,
1632                                                const gdb_byte **new_info_ptr,
1633                                                struct die_info *parent);
1634
1635 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1636                                         struct die_info **, const gdb_byte *,
1637                                         int *, int);
1638
1639 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1640                                       struct die_info **, const gdb_byte *,
1641                                       int *);
1642
1643 static void process_die (struct die_info *, struct dwarf2_cu *);
1644
1645 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1646                                              struct obstack *);
1647
1648 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1649
1650 static const char *dwarf2_full_name (const char *name,
1651                                      struct die_info *die,
1652                                      struct dwarf2_cu *cu);
1653
1654 static const char *dwarf2_physname (const char *name, struct die_info *die,
1655                                     struct dwarf2_cu *cu);
1656
1657 static struct die_info *dwarf2_extension (struct die_info *die,
1658                                           struct dwarf2_cu **);
1659
1660 static const char *dwarf_tag_name (unsigned int);
1661
1662 static const char *dwarf_attr_name (unsigned int);
1663
1664 static const char *dwarf_form_name (unsigned int);
1665
1666 static char *dwarf_bool_name (unsigned int);
1667
1668 static const char *dwarf_type_encoding_name (unsigned int);
1669
1670 static struct die_info *sibling_die (struct die_info *);
1671
1672 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1673
1674 static void dump_die_for_error (struct die_info *);
1675
1676 static void dump_die_1 (struct ui_file *, int level, int max_level,
1677                         struct die_info *);
1678
1679 /*static*/ void dump_die (struct die_info *, int max_level);
1680
1681 static void store_in_ref_table (struct die_info *,
1682                                 struct dwarf2_cu *);
1683
1684 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1685
1686 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1687
1688 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1689                                                const struct attribute *,
1690                                                struct dwarf2_cu **);
1691
1692 static struct die_info *follow_die_ref (struct die_info *,
1693                                         const struct attribute *,
1694                                         struct dwarf2_cu **);
1695
1696 static struct die_info *follow_die_sig (struct die_info *,
1697                                         const struct attribute *,
1698                                         struct dwarf2_cu **);
1699
1700 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1701                                          struct dwarf2_cu *);
1702
1703 static struct type *get_DW_AT_signature_type (struct die_info *,
1704                                               const struct attribute *,
1705                                               struct dwarf2_cu *);
1706
1707 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1708
1709 static void read_signatured_type (struct signatured_type *);
1710
1711 static struct type_unit_group *get_type_unit_group
1712     (struct dwarf2_cu *, const struct attribute *);
1713
1714 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1715
1716 /* memory allocation interface */
1717
1718 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1719
1720 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1721
1722 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1723                                  const char *, int);
1724
1725 static int attr_form_is_block (const struct attribute *);
1726
1727 static int attr_form_is_section_offset (const struct attribute *);
1728
1729 static int attr_form_is_constant (const struct attribute *);
1730
1731 static int attr_form_is_ref (const struct attribute *);
1732
1733 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1734                                    struct dwarf2_loclist_baton *baton,
1735                                    const struct attribute *attr);
1736
1737 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1738                                          struct symbol *sym,
1739                                          struct dwarf2_cu *cu,
1740                                          int is_block);
1741
1742 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1743                                      const gdb_byte *info_ptr,
1744                                      struct abbrev_info *abbrev);
1745
1746 static void free_stack_comp_unit (void *);
1747
1748 static hashval_t partial_die_hash (const void *item);
1749
1750 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1751
1752 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1753   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1754
1755 static void init_one_comp_unit (struct dwarf2_cu *cu,
1756                                 struct dwarf2_per_cu_data *per_cu);
1757
1758 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1759                                    struct die_info *comp_unit_die,
1760                                    enum language pretend_language);
1761
1762 static void free_heap_comp_unit (void *);
1763
1764 static void free_cached_comp_units (void *);
1765
1766 static void age_cached_comp_units (void);
1767
1768 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1769
1770 static struct type *set_die_type (struct die_info *, struct type *,
1771                                   struct dwarf2_cu *);
1772
1773 static void create_all_comp_units (struct objfile *);
1774
1775 static int create_all_type_units (struct objfile *);
1776
1777 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1778                                  enum language);
1779
1780 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1781                                     enum language);
1782
1783 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1784                                     enum language);
1785
1786 static void dwarf2_add_dependence (struct dwarf2_cu *,
1787                                    struct dwarf2_per_cu_data *);
1788
1789 static void dwarf2_mark (struct dwarf2_cu *);
1790
1791 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1792
1793 static struct type *get_die_type_at_offset (sect_offset,
1794                                             struct dwarf2_per_cu_data *);
1795
1796 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1797
1798 static void dwarf2_release_queue (void *dummy);
1799
1800 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1801                              enum language pretend_language);
1802
1803 static void process_queue (void);
1804
1805 static void find_file_and_directory (struct die_info *die,
1806                                      struct dwarf2_cu *cu,
1807                                      const char **name, const char **comp_dir);
1808
1809 static char *file_full_name (int file, struct line_header *lh,
1810                              const char *comp_dir);
1811
1812 static const gdb_byte *read_and_check_comp_unit_head
1813   (struct comp_unit_head *header,
1814    struct dwarf2_section_info *section,
1815    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1816    int is_debug_types_section);
1817
1818 static void init_cutu_and_read_dies
1819   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1820    int use_existing_cu, int keep,
1821    die_reader_func_ftype *die_reader_func, void *data);
1822
1823 static void init_cutu_and_read_dies_simple
1824   (struct dwarf2_per_cu_data *this_cu,
1825    die_reader_func_ftype *die_reader_func, void *data);
1826
1827 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1828
1829 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1830
1831 static struct dwo_unit *lookup_dwo_unit_in_dwp
1832   (struct dwp_file *dwp_file, const char *comp_dir,
1833    ULONGEST signature, int is_debug_types);
1834
1835 static struct dwp_file *get_dwp_file (void);
1836
1837 static struct dwo_unit *lookup_dwo_comp_unit
1838   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1839
1840 static struct dwo_unit *lookup_dwo_type_unit
1841   (struct signatured_type *, const char *, const char *);
1842
1843 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1844
1845 static void free_dwo_file_cleanup (void *);
1846
1847 static void process_cu_includes (void);
1848
1849 static void check_producer (struct dwarf2_cu *cu);
1850 \f
1851 /* Various complaints about symbol reading that don't abort the process.  */
1852
1853 static void
1854 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1855 {
1856   complaint (&symfile_complaints,
1857              _("statement list doesn't fit in .debug_line section"));
1858 }
1859
1860 static void
1861 dwarf2_debug_line_missing_file_complaint (void)
1862 {
1863   complaint (&symfile_complaints,
1864              _(".debug_line section has line data without a file"));
1865 }
1866
1867 static void
1868 dwarf2_debug_line_missing_end_sequence_complaint (void)
1869 {
1870   complaint (&symfile_complaints,
1871              _(".debug_line section has line "
1872                "program sequence without an end"));
1873 }
1874
1875 static void
1876 dwarf2_complex_location_expr_complaint (void)
1877 {
1878   complaint (&symfile_complaints, _("location expression too complex"));
1879 }
1880
1881 static void
1882 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1883                                               int arg3)
1884 {
1885   complaint (&symfile_complaints,
1886              _("const value length mismatch for '%s', got %d, expected %d"),
1887              arg1, arg2, arg3);
1888 }
1889
1890 static void
1891 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1892 {
1893   complaint (&symfile_complaints,
1894              _("debug info runs off end of %s section"
1895                " [in module %s]"),
1896              get_section_name (section),
1897              get_section_file_name (section));
1898 }
1899
1900 static void
1901 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1902 {
1903   complaint (&symfile_complaints,
1904              _("macro debug info contains a "
1905                "malformed macro definition:\n`%s'"),
1906              arg1);
1907 }
1908
1909 static void
1910 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1911 {
1912   complaint (&symfile_complaints,
1913              _("invalid attribute class or form for '%s' in '%s'"),
1914              arg1, arg2);
1915 }
1916 \f
1917 #if WORDS_BIGENDIAN
1918
1919 /* Convert VALUE between big- and little-endian.  */
1920 static offset_type
1921 byte_swap (offset_type value)
1922 {
1923   offset_type result;
1924
1925   result = (value & 0xff) << 24;
1926   result |= (value & 0xff00) << 8;
1927   result |= (value & 0xff0000) >> 8;
1928   result |= (value & 0xff000000) >> 24;
1929   return result;
1930 }
1931
1932 #define MAYBE_SWAP(V)  byte_swap (V)
1933
1934 #else
1935 #define MAYBE_SWAP(V) (V)
1936 #endif /* WORDS_BIGENDIAN */
1937
1938 /* The suffix for an index file.  */
1939 #define INDEX_SUFFIX ".gdb-index"
1940
1941 /* Try to locate the sections we need for DWARF 2 debugging
1942    information and return true if we have enough to do something.
1943    NAMES points to the dwarf2 section names, or is NULL if the standard
1944    ELF names are used.  */
1945
1946 int
1947 dwarf2_has_info (struct objfile *objfile,
1948                  const struct dwarf2_debug_sections *names)
1949 {
1950   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1951   if (!dwarf2_per_objfile)
1952     {
1953       /* Initialize per-objfile state.  */
1954       struct dwarf2_per_objfile *data
1955         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1956
1957       memset (data, 0, sizeof (*data));
1958       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1959       dwarf2_per_objfile = data;
1960
1961       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1962                              (void *) names);
1963       dwarf2_per_objfile->objfile = objfile;
1964     }
1965   return (!dwarf2_per_objfile->info.is_virtual
1966           && dwarf2_per_objfile->info.s.asection != NULL
1967           && !dwarf2_per_objfile->abbrev.is_virtual
1968           && dwarf2_per_objfile->abbrev.s.asection != NULL);
1969 }
1970
1971 /* Return the containing section of virtual section SECTION.  */
1972
1973 static struct dwarf2_section_info *
1974 get_containing_section (const struct dwarf2_section_info *section)
1975 {
1976   gdb_assert (section->is_virtual);
1977   return section->s.containing_section;
1978 }
1979
1980 /* Return the bfd owner of SECTION.  */
1981
1982 static struct bfd *
1983 get_section_bfd_owner (const struct dwarf2_section_info *section)
1984 {
1985   if (section->is_virtual)
1986     {
1987       section = get_containing_section (section);
1988       gdb_assert (!section->is_virtual);
1989     }
1990   return section->s.asection->owner;
1991 }
1992
1993 /* Return the bfd section of SECTION.
1994    Returns NULL if the section is not present.  */
1995
1996 static asection *
1997 get_section_bfd_section (const struct dwarf2_section_info *section)
1998 {
1999   if (section->is_virtual)
2000     {
2001       section = get_containing_section (section);
2002       gdb_assert (!section->is_virtual);
2003     }
2004   return section->s.asection;
2005 }
2006
2007 /* Return the name of SECTION.  */
2008
2009 static const char *
2010 get_section_name (const struct dwarf2_section_info *section)
2011 {
2012   asection *sectp = get_section_bfd_section (section);
2013
2014   gdb_assert (sectp != NULL);
2015   return bfd_section_name (get_section_bfd_owner (section), sectp);
2016 }
2017
2018 /* Return the name of the file SECTION is in.  */
2019
2020 static const char *
2021 get_section_file_name (const struct dwarf2_section_info *section)
2022 {
2023   bfd *abfd = get_section_bfd_owner (section);
2024
2025   return bfd_get_filename (abfd);
2026 }
2027
2028 /* Return the id of SECTION.
2029    Returns 0 if SECTION doesn't exist.  */
2030
2031 static int
2032 get_section_id (const struct dwarf2_section_info *section)
2033 {
2034   asection *sectp = get_section_bfd_section (section);
2035
2036   if (sectp == NULL)
2037     return 0;
2038   return sectp->id;
2039 }
2040
2041 /* Return the flags of SECTION.
2042    SECTION (or containing section if this is a virtual section) must exist.  */
2043
2044 static int
2045 get_section_flags (const struct dwarf2_section_info *section)
2046 {
2047   asection *sectp = get_section_bfd_section (section);
2048
2049   gdb_assert (sectp != NULL);
2050   return bfd_get_section_flags (sectp->owner, sectp);
2051 }
2052
2053 /* When loading sections, we look either for uncompressed section or for
2054    compressed section names.  */
2055
2056 static int
2057 section_is_p (const char *section_name,
2058               const struct dwarf2_section_names *names)
2059 {
2060   if (names->normal != NULL
2061       && strcmp (section_name, names->normal) == 0)
2062     return 1;
2063   if (names->compressed != NULL
2064       && strcmp (section_name, names->compressed) == 0)
2065     return 1;
2066   return 0;
2067 }
2068
2069 /* This function is mapped across the sections and remembers the
2070    offset and size of each of the debugging sections we are interested
2071    in.  */
2072
2073 static void
2074 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
2075 {
2076   const struct dwarf2_debug_sections *names;
2077   flagword aflag = bfd_get_section_flags (abfd, sectp);
2078
2079   if (vnames == NULL)
2080     names = &dwarf2_elf_names;
2081   else
2082     names = (const struct dwarf2_debug_sections *) vnames;
2083
2084   if ((aflag & SEC_HAS_CONTENTS) == 0)
2085     {
2086     }
2087   else if (section_is_p (sectp->name, &names->info))
2088     {
2089       dwarf2_per_objfile->info.s.asection = sectp;
2090       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
2091     }
2092   else if (section_is_p (sectp->name, &names->abbrev))
2093     {
2094       dwarf2_per_objfile->abbrev.s.asection = sectp;
2095       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
2096     }
2097   else if (section_is_p (sectp->name, &names->line))
2098     {
2099       dwarf2_per_objfile->line.s.asection = sectp;
2100       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
2101     }
2102   else if (section_is_p (sectp->name, &names->loc))
2103     {
2104       dwarf2_per_objfile->loc.s.asection = sectp;
2105       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
2106     }
2107   else if (section_is_p (sectp->name, &names->macinfo))
2108     {
2109       dwarf2_per_objfile->macinfo.s.asection = sectp;
2110       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
2111     }
2112   else if (section_is_p (sectp->name, &names->macro))
2113     {
2114       dwarf2_per_objfile->macro.s.asection = sectp;
2115       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
2116     }
2117   else if (section_is_p (sectp->name, &names->str))
2118     {
2119       dwarf2_per_objfile->str.s.asection = sectp;
2120       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
2121     }
2122   else if (section_is_p (sectp->name, &names->addr))
2123     {
2124       dwarf2_per_objfile->addr.s.asection = sectp;
2125       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
2126     }
2127   else if (section_is_p (sectp->name, &names->frame))
2128     {
2129       dwarf2_per_objfile->frame.s.asection = sectp;
2130       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
2131     }
2132   else if (section_is_p (sectp->name, &names->eh_frame))
2133     {
2134       dwarf2_per_objfile->eh_frame.s.asection = sectp;
2135       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
2136     }
2137   else if (section_is_p (sectp->name, &names->ranges))
2138     {
2139       dwarf2_per_objfile->ranges.s.asection = sectp;
2140       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
2141     }
2142   else if (section_is_p (sectp->name, &names->types))
2143     {
2144       struct dwarf2_section_info type_section;
2145
2146       memset (&type_section, 0, sizeof (type_section));
2147       type_section.s.asection = sectp;
2148       type_section.size = bfd_get_section_size (sectp);
2149
2150       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
2151                      &type_section);
2152     }
2153   else if (section_is_p (sectp->name, &names->gdb_index))
2154     {
2155       dwarf2_per_objfile->gdb_index.s.asection = sectp;
2156       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
2157     }
2158
2159   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
2160       && bfd_section_vma (abfd, sectp) == 0)
2161     dwarf2_per_objfile->has_section_at_zero = 1;
2162 }
2163
2164 /* A helper function that decides whether a section is empty,
2165    or not present.  */
2166
2167 static int
2168 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2169 {
2170   if (section->is_virtual)
2171     return section->size == 0;
2172   return section->s.asection == NULL || section->size == 0;
2173 }
2174
2175 /* Read the contents of the section INFO.
2176    OBJFILE is the main object file, but not necessarily the file where
2177    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2178    of the DWO file.
2179    If the section is compressed, uncompress it before returning.  */
2180
2181 static void
2182 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2183 {
2184   asection *sectp;
2185   bfd *abfd;
2186   gdb_byte *buf, *retbuf;
2187
2188   if (info->readin)
2189     return;
2190   info->buffer = NULL;
2191   info->readin = 1;
2192
2193   if (dwarf2_section_empty_p (info))
2194     return;
2195
2196   sectp = get_section_bfd_section (info);
2197
2198   /* If this is a virtual section we need to read in the real one first.  */
2199   if (info->is_virtual)
2200     {
2201       struct dwarf2_section_info *containing_section =
2202         get_containing_section (info);
2203
2204       gdb_assert (sectp != NULL);
2205       if ((sectp->flags & SEC_RELOC) != 0)
2206         {
2207           error (_("Dwarf Error: DWP format V2 with relocations is not"
2208                    " supported in section %s [in module %s]"),
2209                  get_section_name (info), get_section_file_name (info));
2210         }
2211       dwarf2_read_section (objfile, containing_section);
2212       /* Other code should have already caught virtual sections that don't
2213          fit.  */
2214       gdb_assert (info->virtual_offset + info->size
2215                   <= containing_section->size);
2216       /* If the real section is empty or there was a problem reading the
2217          section we shouldn't get here.  */
2218       gdb_assert (containing_section->buffer != NULL);
2219       info->buffer = containing_section->buffer + info->virtual_offset;
2220       return;
2221     }
2222
2223   /* If the section has relocations, we must read it ourselves.
2224      Otherwise we attach it to the BFD.  */
2225   if ((sectp->flags & SEC_RELOC) == 0)
2226     {
2227       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2228       return;
2229     }
2230
2231   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
2232   info->buffer = buf;
2233
2234   /* When debugging .o files, we may need to apply relocations; see
2235      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2236      We never compress sections in .o files, so we only need to
2237      try this when the section is not compressed.  */
2238   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2239   if (retbuf != NULL)
2240     {
2241       info->buffer = retbuf;
2242       return;
2243     }
2244
2245   abfd = get_section_bfd_owner (info);
2246   gdb_assert (abfd != NULL);
2247
2248   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2249       || bfd_bread (buf, info->size, abfd) != info->size)
2250     {
2251       error (_("Dwarf Error: Can't read DWARF data"
2252                " in section %s [in module %s]"),
2253              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2254     }
2255 }
2256
2257 /* A helper function that returns the size of a section in a safe way.
2258    If you are positive that the section has been read before using the
2259    size, then it is safe to refer to the dwarf2_section_info object's
2260    "size" field directly.  In other cases, you must call this
2261    function, because for compressed sections the size field is not set
2262    correctly until the section has been read.  */
2263
2264 static bfd_size_type
2265 dwarf2_section_size (struct objfile *objfile,
2266                      struct dwarf2_section_info *info)
2267 {
2268   if (!info->readin)
2269     dwarf2_read_section (objfile, info);
2270   return info->size;
2271 }
2272
2273 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2274    SECTION_NAME.  */
2275
2276 void
2277 dwarf2_get_section_info (struct objfile *objfile,
2278                          enum dwarf2_section_enum sect,
2279                          asection **sectp, const gdb_byte **bufp,
2280                          bfd_size_type *sizep)
2281 {
2282   struct dwarf2_per_objfile *data
2283     = objfile_data (objfile, dwarf2_objfile_data_key);
2284   struct dwarf2_section_info *info;
2285
2286   /* We may see an objfile without any DWARF, in which case we just
2287      return nothing.  */
2288   if (data == NULL)
2289     {
2290       *sectp = NULL;
2291       *bufp = NULL;
2292       *sizep = 0;
2293       return;
2294     }
2295   switch (sect)
2296     {
2297     case DWARF2_DEBUG_FRAME:
2298       info = &data->frame;
2299       break;
2300     case DWARF2_EH_FRAME:
2301       info = &data->eh_frame;
2302       break;
2303     default:
2304       gdb_assert_not_reached ("unexpected section");
2305     }
2306
2307   dwarf2_read_section (objfile, info);
2308
2309   *sectp = get_section_bfd_section (info);
2310   *bufp = info->buffer;
2311   *sizep = info->size;
2312 }
2313
2314 /* A helper function to find the sections for a .dwz file.  */
2315
2316 static void
2317 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2318 {
2319   struct dwz_file *dwz_file = arg;
2320
2321   /* Note that we only support the standard ELF names, because .dwz
2322      is ELF-only (at the time of writing).  */
2323   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2324     {
2325       dwz_file->abbrev.s.asection = sectp;
2326       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2327     }
2328   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2329     {
2330       dwz_file->info.s.asection = sectp;
2331       dwz_file->info.size = bfd_get_section_size (sectp);
2332     }
2333   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2334     {
2335       dwz_file->str.s.asection = sectp;
2336       dwz_file->str.size = bfd_get_section_size (sectp);
2337     }
2338   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2339     {
2340       dwz_file->line.s.asection = sectp;
2341       dwz_file->line.size = bfd_get_section_size (sectp);
2342     }
2343   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2344     {
2345       dwz_file->macro.s.asection = sectp;
2346       dwz_file->macro.size = bfd_get_section_size (sectp);
2347     }
2348   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2349     {
2350       dwz_file->gdb_index.s.asection = sectp;
2351       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2352     }
2353 }
2354
2355 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2356    there is no .gnu_debugaltlink section in the file.  Error if there
2357    is such a section but the file cannot be found.  */
2358
2359 static struct dwz_file *
2360 dwarf2_get_dwz_file (void)
2361 {
2362   bfd *dwz_bfd;
2363   char *data;
2364   struct cleanup *cleanup;
2365   const char *filename;
2366   struct dwz_file *result;
2367   unsigned long buildid;
2368
2369   if (dwarf2_per_objfile->dwz_file != NULL)
2370     return dwarf2_per_objfile->dwz_file;
2371
2372   bfd_set_error (bfd_error_no_error);
2373   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2374                                       &buildid);
2375   if (data == NULL)
2376     {
2377       if (bfd_get_error () == bfd_error_no_error)
2378         return NULL;
2379       error (_("could not read '.gnu_debugaltlink' section: %s"),
2380              bfd_errmsg (bfd_get_error ()));
2381     }
2382   cleanup = make_cleanup (xfree, data);
2383
2384   filename = (const char *) data;
2385   if (!IS_ABSOLUTE_PATH (filename))
2386     {
2387       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2388       char *rel;
2389
2390       make_cleanup (xfree, abs);
2391       abs = ldirname (abs);
2392       make_cleanup (xfree, abs);
2393
2394       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2395       make_cleanup (xfree, rel);
2396       filename = rel;
2397     }
2398
2399   /* The format is just a NUL-terminated file name, followed by the
2400      build-id.  For now, though, we ignore the build-id.  */
2401   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2402   if (dwz_bfd == NULL)
2403     error (_("could not read '%s': %s"), filename,
2404            bfd_errmsg (bfd_get_error ()));
2405
2406   if (!bfd_check_format (dwz_bfd, bfd_object))
2407     {
2408       gdb_bfd_unref (dwz_bfd);
2409       error (_("file '%s' was not usable: %s"), filename,
2410              bfd_errmsg (bfd_get_error ()));
2411     }
2412
2413   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2414                            struct dwz_file);
2415   result->dwz_bfd = dwz_bfd;
2416
2417   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2418
2419   do_cleanups (cleanup);
2420
2421   dwarf2_per_objfile->dwz_file = result;
2422   return result;
2423 }
2424 \f
2425 /* DWARF quick_symbols_functions support.  */
2426
2427 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2428    unique line tables, so we maintain a separate table of all .debug_line
2429    derived entries to support the sharing.
2430    All the quick functions need is the list of file names.  We discard the
2431    line_header when we're done and don't need to record it here.  */
2432 struct quick_file_names
2433 {
2434   /* The data used to construct the hash key.  */
2435   struct stmt_list_hash hash;
2436
2437   /* The number of entries in file_names, real_names.  */
2438   unsigned int num_file_names;
2439
2440   /* The file names from the line table, after being run through
2441      file_full_name.  */
2442   const char **file_names;
2443
2444   /* The file names from the line table after being run through
2445      gdb_realpath.  These are computed lazily.  */
2446   const char **real_names;
2447 };
2448
2449 /* When using the index (and thus not using psymtabs), each CU has an
2450    object of this type.  This is used to hold information needed by
2451    the various "quick" methods.  */
2452 struct dwarf2_per_cu_quick_data
2453 {
2454   /* The file table.  This can be NULL if there was no file table
2455      or it's currently not read in.
2456      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2457   struct quick_file_names *file_names;
2458
2459   /* The corresponding symbol table.  This is NULL if symbols for this
2460      CU have not yet been read.  */
2461   struct symtab *symtab;
2462
2463   /* A temporary mark bit used when iterating over all CUs in
2464      expand_symtabs_matching.  */
2465   unsigned int mark : 1;
2466
2467   /* True if we've tried to read the file table and found there isn't one.
2468      There will be no point in trying to read it again next time.  */
2469   unsigned int no_file_data : 1;
2470 };
2471
2472 /* Utility hash function for a stmt_list_hash.  */
2473
2474 static hashval_t
2475 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2476 {
2477   hashval_t v = 0;
2478
2479   if (stmt_list_hash->dwo_unit != NULL)
2480     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2481   v += stmt_list_hash->line_offset.sect_off;
2482   return v;
2483 }
2484
2485 /* Utility equality function for a stmt_list_hash.  */
2486
2487 static int
2488 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2489                     const struct stmt_list_hash *rhs)
2490 {
2491   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2492     return 0;
2493   if (lhs->dwo_unit != NULL
2494       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2495     return 0;
2496
2497   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2498 }
2499
2500 /* Hash function for a quick_file_names.  */
2501
2502 static hashval_t
2503 hash_file_name_entry (const void *e)
2504 {
2505   const struct quick_file_names *file_data = e;
2506
2507   return hash_stmt_list_entry (&file_data->hash);
2508 }
2509
2510 /* Equality function for a quick_file_names.  */
2511
2512 static int
2513 eq_file_name_entry (const void *a, const void *b)
2514 {
2515   const struct quick_file_names *ea = a;
2516   const struct quick_file_names *eb = b;
2517
2518   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2519 }
2520
2521 /* Delete function for a quick_file_names.  */
2522
2523 static void
2524 delete_file_name_entry (void *e)
2525 {
2526   struct quick_file_names *file_data = e;
2527   int i;
2528
2529   for (i = 0; i < file_data->num_file_names; ++i)
2530     {
2531       xfree ((void*) file_data->file_names[i]);
2532       if (file_data->real_names)
2533         xfree ((void*) file_data->real_names[i]);
2534     }
2535
2536   /* The space for the struct itself lives on objfile_obstack,
2537      so we don't free it here.  */
2538 }
2539
2540 /* Create a quick_file_names hash table.  */
2541
2542 static htab_t
2543 create_quick_file_names_table (unsigned int nr_initial_entries)
2544 {
2545   return htab_create_alloc (nr_initial_entries,
2546                             hash_file_name_entry, eq_file_name_entry,
2547                             delete_file_name_entry, xcalloc, xfree);
2548 }
2549
2550 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2551    have to be created afterwards.  You should call age_cached_comp_units after
2552    processing PER_CU->CU.  dw2_setup must have been already called.  */
2553
2554 static void
2555 load_cu (struct dwarf2_per_cu_data *per_cu)
2556 {
2557   if (per_cu->is_debug_types)
2558     load_full_type_unit (per_cu);
2559   else
2560     load_full_comp_unit (per_cu, language_minimal);
2561
2562   gdb_assert (per_cu->cu != NULL);
2563
2564   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2565 }
2566
2567 /* Read in the symbols for PER_CU.  */
2568
2569 static void
2570 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2571 {
2572   struct cleanup *back_to;
2573
2574   /* Skip type_unit_groups, reading the type units they contain
2575      is handled elsewhere.  */
2576   if (IS_TYPE_UNIT_GROUP (per_cu))
2577     return;
2578
2579   back_to = make_cleanup (dwarf2_release_queue, NULL);
2580
2581   if (dwarf2_per_objfile->using_index
2582       ? per_cu->v.quick->symtab == NULL
2583       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2584     {
2585       queue_comp_unit (per_cu, language_minimal);
2586       load_cu (per_cu);
2587
2588       /* If we just loaded a CU from a DWO, and we're working with an index
2589          that may badly handle TUs, load all the TUs in that DWO as well.
2590          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2591       if (!per_cu->is_debug_types
2592           && per_cu->cu->dwo_unit != NULL
2593           && dwarf2_per_objfile->index_table != NULL
2594           && dwarf2_per_objfile->index_table->version <= 7
2595           /* DWP files aren't supported yet.  */
2596           && get_dwp_file () == NULL)
2597         queue_and_load_all_dwo_tus (per_cu);
2598     }
2599
2600   process_queue ();
2601
2602   /* Age the cache, releasing compilation units that have not
2603      been used recently.  */
2604   age_cached_comp_units ();
2605
2606   do_cleanups (back_to);
2607 }
2608
2609 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2610    the objfile from which this CU came.  Returns the resulting symbol
2611    table.  */
2612
2613 static struct symtab *
2614 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2615 {
2616   gdb_assert (dwarf2_per_objfile->using_index);
2617   if (!per_cu->v.quick->symtab)
2618     {
2619       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2620       increment_reading_symtab ();
2621       dw2_do_instantiate_symtab (per_cu);
2622       process_cu_includes ();
2623       do_cleanups (back_to);
2624     }
2625   return per_cu->v.quick->symtab;
2626 }
2627
2628 /* Return the CU given its index.
2629
2630    This is intended for loops like:
2631
2632    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2633                     + dwarf2_per_objfile->n_type_units); ++i)
2634      {
2635        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2636
2637        ...;
2638      }
2639 */
2640
2641 static struct dwarf2_per_cu_data *
2642 dw2_get_cu (int index)
2643 {
2644   if (index >= dwarf2_per_objfile->n_comp_units)
2645     {
2646       index -= dwarf2_per_objfile->n_comp_units;
2647       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2648       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2649     }
2650
2651   return dwarf2_per_objfile->all_comp_units[index];
2652 }
2653
2654 /* Return the primary CU given its index.
2655    The difference between this function and dw2_get_cu is in the handling
2656    of type units (TUs).  Here we return the type_unit_group object.
2657
2658    This is intended for loops like:
2659
2660    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2661                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2662      {
2663        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2664
2665        ...;
2666      }
2667 */
2668
2669 static struct dwarf2_per_cu_data *
2670 dw2_get_primary_cu (int index)
2671 {
2672   if (index >= dwarf2_per_objfile->n_comp_units)
2673     {
2674       index -= dwarf2_per_objfile->n_comp_units;
2675       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2676       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2677     }
2678
2679   return dwarf2_per_objfile->all_comp_units[index];
2680 }
2681
2682 /* A helper for create_cus_from_index that handles a given list of
2683    CUs.  */
2684
2685 static void
2686 create_cus_from_index_list (struct objfile *objfile,
2687                             const gdb_byte *cu_list, offset_type n_elements,
2688                             struct dwarf2_section_info *section,
2689                             int is_dwz,
2690                             int base_offset)
2691 {
2692   offset_type i;
2693
2694   for (i = 0; i < n_elements; i += 2)
2695     {
2696       struct dwarf2_per_cu_data *the_cu;
2697       ULONGEST offset, length;
2698
2699       gdb_static_assert (sizeof (ULONGEST) >= 8);
2700       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2701       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2702       cu_list += 2 * 8;
2703
2704       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2705                                struct dwarf2_per_cu_data);
2706       the_cu->offset.sect_off = offset;
2707       the_cu->length = length;
2708       the_cu->objfile = objfile;
2709       the_cu->section = section;
2710       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2711                                         struct dwarf2_per_cu_quick_data);
2712       the_cu->is_dwz = is_dwz;
2713       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2714     }
2715 }
2716
2717 /* Read the CU list from the mapped index, and use it to create all
2718    the CU objects for this objfile.  */
2719
2720 static void
2721 create_cus_from_index (struct objfile *objfile,
2722                        const gdb_byte *cu_list, offset_type cu_list_elements,
2723                        const gdb_byte *dwz_list, offset_type dwz_elements)
2724 {
2725   struct dwz_file *dwz;
2726
2727   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2728   dwarf2_per_objfile->all_comp_units
2729     = obstack_alloc (&objfile->objfile_obstack,
2730                      dwarf2_per_objfile->n_comp_units
2731                      * sizeof (struct dwarf2_per_cu_data *));
2732
2733   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2734                               &dwarf2_per_objfile->info, 0, 0);
2735
2736   if (dwz_elements == 0)
2737     return;
2738
2739   dwz = dwarf2_get_dwz_file ();
2740   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2741                               cu_list_elements / 2);
2742 }
2743
2744 /* Create the signatured type hash table from the index.  */
2745
2746 static void
2747 create_signatured_type_table_from_index (struct objfile *objfile,
2748                                          struct dwarf2_section_info *section,
2749                                          const gdb_byte *bytes,
2750                                          offset_type elements)
2751 {
2752   offset_type i;
2753   htab_t sig_types_hash;
2754
2755   dwarf2_per_objfile->n_type_units = elements / 3;
2756   dwarf2_per_objfile->all_type_units
2757     = xmalloc (dwarf2_per_objfile->n_type_units
2758                * sizeof (struct signatured_type *));
2759
2760   sig_types_hash = allocate_signatured_type_table (objfile);
2761
2762   for (i = 0; i < elements; i += 3)
2763     {
2764       struct signatured_type *sig_type;
2765       ULONGEST offset, type_offset_in_tu, signature;
2766       void **slot;
2767
2768       gdb_static_assert (sizeof (ULONGEST) >= 8);
2769       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2770       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2771                                                     BFD_ENDIAN_LITTLE);
2772       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2773       bytes += 3 * 8;
2774
2775       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2776                                  struct signatured_type);
2777       sig_type->signature = signature;
2778       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2779       sig_type->per_cu.is_debug_types = 1;
2780       sig_type->per_cu.section = section;
2781       sig_type->per_cu.offset.sect_off = offset;
2782       sig_type->per_cu.objfile = objfile;
2783       sig_type->per_cu.v.quick
2784         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2785                           struct dwarf2_per_cu_quick_data);
2786
2787       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2788       *slot = sig_type;
2789
2790       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2791     }
2792
2793   dwarf2_per_objfile->signatured_types = sig_types_hash;
2794 }
2795
2796 /* Read the address map data from the mapped index, and use it to
2797    populate the objfile's psymtabs_addrmap.  */
2798
2799 static void
2800 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2801 {
2802   const gdb_byte *iter, *end;
2803   struct obstack temp_obstack;
2804   struct addrmap *mutable_map;
2805   struct cleanup *cleanup;
2806   CORE_ADDR baseaddr;
2807
2808   obstack_init (&temp_obstack);
2809   cleanup = make_cleanup_obstack_free (&temp_obstack);
2810   mutable_map = addrmap_create_mutable (&temp_obstack);
2811
2812   iter = index->address_table;
2813   end = iter + index->address_table_size;
2814
2815   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2816
2817   while (iter < end)
2818     {
2819       ULONGEST hi, lo, cu_index;
2820       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2821       iter += 8;
2822       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2823       iter += 8;
2824       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2825       iter += 4;
2826
2827       if (lo > hi)
2828         {
2829           complaint (&symfile_complaints,
2830                      _(".gdb_index address table has invalid range (%s - %s)"),
2831                      hex_string (lo), hex_string (hi));
2832           continue;
2833         }
2834
2835       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2836         {
2837           complaint (&symfile_complaints,
2838                      _(".gdb_index address table has invalid CU number %u"),
2839                      (unsigned) cu_index);
2840           continue;
2841         }
2842
2843       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2844                          dw2_get_cu (cu_index));
2845     }
2846
2847   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2848                                                     &objfile->objfile_obstack);
2849   do_cleanups (cleanup);
2850 }
2851
2852 /* The hash function for strings in the mapped index.  This is the same as
2853    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2854    implementation.  This is necessary because the hash function is tied to the
2855    format of the mapped index file.  The hash values do not have to match with
2856    SYMBOL_HASH_NEXT.
2857    
2858    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2859
2860 static hashval_t
2861 mapped_index_string_hash (int index_version, const void *p)
2862 {
2863   const unsigned char *str = (const unsigned char *) p;
2864   hashval_t r = 0;
2865   unsigned char c;
2866
2867   while ((c = *str++) != 0)
2868     {
2869       if (index_version >= 5)
2870         c = tolower (c);
2871       r = r * 67 + c - 113;
2872     }
2873
2874   return r;
2875 }
2876
2877 /* Find a slot in the mapped index INDEX for the object named NAME.
2878    If NAME is found, set *VEC_OUT to point to the CU vector in the
2879    constant pool and return 1.  If NAME cannot be found, return 0.  */
2880
2881 static int
2882 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2883                           offset_type **vec_out)
2884 {
2885   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2886   offset_type hash;
2887   offset_type slot, step;
2888   int (*cmp) (const char *, const char *);
2889
2890   if (current_language->la_language == language_cplus
2891       || current_language->la_language == language_java
2892       || current_language->la_language == language_fortran)
2893     {
2894       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2895          not contain any.  */
2896       const char *paren = strchr (name, '(');
2897
2898       if (paren)
2899         {
2900           char *dup;
2901
2902           dup = xmalloc (paren - name + 1);
2903           memcpy (dup, name, paren - name);
2904           dup[paren - name] = 0;
2905
2906           make_cleanup (xfree, dup);
2907           name = dup;
2908         }
2909     }
2910
2911   /* Index version 4 did not support case insensitive searches.  But the
2912      indices for case insensitive languages are built in lowercase, therefore
2913      simulate our NAME being searched is also lowercased.  */
2914   hash = mapped_index_string_hash ((index->version == 4
2915                                     && case_sensitivity == case_sensitive_off
2916                                     ? 5 : index->version),
2917                                    name);
2918
2919   slot = hash & (index->symbol_table_slots - 1);
2920   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2921   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2922
2923   for (;;)
2924     {
2925       /* Convert a slot number to an offset into the table.  */
2926       offset_type i = 2 * slot;
2927       const char *str;
2928       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2929         {
2930           do_cleanups (back_to);
2931           return 0;
2932         }
2933
2934       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2935       if (!cmp (name, str))
2936         {
2937           *vec_out = (offset_type *) (index->constant_pool
2938                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2939           do_cleanups (back_to);
2940           return 1;
2941         }
2942
2943       slot = (slot + step) & (index->symbol_table_slots - 1);
2944     }
2945 }
2946
2947 /* A helper function that reads the .gdb_index from SECTION and fills
2948    in MAP.  FILENAME is the name of the file containing the section;
2949    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2950    ok to use deprecated sections.
2951
2952    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2953    out parameters that are filled in with information about the CU and
2954    TU lists in the section.
2955
2956    Returns 1 if all went well, 0 otherwise.  */
2957
2958 static int
2959 read_index_from_section (struct objfile *objfile,
2960                          const char *filename,
2961                          int deprecated_ok,
2962                          struct dwarf2_section_info *section,
2963                          struct mapped_index *map,
2964                          const gdb_byte **cu_list,
2965                          offset_type *cu_list_elements,
2966                          const gdb_byte **types_list,
2967                          offset_type *types_list_elements)
2968 {
2969   const gdb_byte *addr;
2970   offset_type version;
2971   offset_type *metadata;
2972   int i;
2973
2974   if (dwarf2_section_empty_p (section))
2975     return 0;
2976
2977   /* Older elfutils strip versions could keep the section in the main
2978      executable while splitting it for the separate debug info file.  */
2979   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
2980     return 0;
2981
2982   dwarf2_read_section (objfile, section);
2983
2984   addr = section->buffer;
2985   /* Version check.  */
2986   version = MAYBE_SWAP (*(offset_type *) addr);
2987   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2988      causes the index to behave very poorly for certain requests.  Version 3
2989      contained incomplete addrmap.  So, it seems better to just ignore such
2990      indices.  */
2991   if (version < 4)
2992     {
2993       static int warning_printed = 0;
2994       if (!warning_printed)
2995         {
2996           warning (_("Skipping obsolete .gdb_index section in %s."),
2997                    filename);
2998           warning_printed = 1;
2999         }
3000       return 0;
3001     }
3002   /* Index version 4 uses a different hash function than index version
3003      5 and later.
3004
3005      Versions earlier than 6 did not emit psymbols for inlined
3006      functions.  Using these files will cause GDB not to be able to
3007      set breakpoints on inlined functions by name, so we ignore these
3008      indices unless the user has done
3009      "set use-deprecated-index-sections on".  */
3010   if (version < 6 && !deprecated_ok)
3011     {
3012       static int warning_printed = 0;
3013       if (!warning_printed)
3014         {
3015           warning (_("\
3016 Skipping deprecated .gdb_index section in %s.\n\
3017 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3018 to use the section anyway."),
3019                    filename);
3020           warning_printed = 1;
3021         }
3022       return 0;
3023     }
3024   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3025      of the TU (for symbols coming from TUs).  It's just a performance bug, and
3026      we can't distinguish gdb-generated indices from gold-generated ones, so
3027      nothing to do here.  */
3028
3029   /* Indexes with higher version than the one supported by GDB may be no
3030      longer backward compatible.  */
3031   if (version > 8)
3032     return 0;
3033
3034   map->version = version;
3035   map->total_size = section->size;
3036
3037   metadata = (offset_type *) (addr + sizeof (offset_type));
3038
3039   i = 0;
3040   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3041   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3042                        / 8);
3043   ++i;
3044
3045   *types_list = addr + MAYBE_SWAP (metadata[i]);
3046   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3047                            - MAYBE_SWAP (metadata[i]))
3048                           / 8);
3049   ++i;
3050
3051   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3052   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3053                              - MAYBE_SWAP (metadata[i]));
3054   ++i;
3055
3056   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3057   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3058                               - MAYBE_SWAP (metadata[i]))
3059                              / (2 * sizeof (offset_type)));
3060   ++i;
3061
3062   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3063
3064   return 1;
3065 }
3066
3067
3068 /* Read the index file.  If everything went ok, initialize the "quick"
3069    elements of all the CUs and return 1.  Otherwise, return 0.  */
3070
3071 static int
3072 dwarf2_read_index (struct objfile *objfile)
3073 {
3074   struct mapped_index local_map, *map;
3075   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3076   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3077   struct dwz_file *dwz;
3078
3079   if (!read_index_from_section (objfile, objfile_name (objfile),
3080                                 use_deprecated_index_sections,
3081                                 &dwarf2_per_objfile->gdb_index, &local_map,
3082                                 &cu_list, &cu_list_elements,
3083                                 &types_list, &types_list_elements))
3084     return 0;
3085
3086   /* Don't use the index if it's empty.  */
3087   if (local_map.symbol_table_slots == 0)
3088     return 0;
3089
3090   /* If there is a .dwz file, read it so we can get its CU list as
3091      well.  */
3092   dwz = dwarf2_get_dwz_file ();
3093   if (dwz != NULL)
3094     {
3095       struct mapped_index dwz_map;
3096       const gdb_byte *dwz_types_ignore;
3097       offset_type dwz_types_elements_ignore;
3098
3099       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3100                                     1,
3101                                     &dwz->gdb_index, &dwz_map,
3102                                     &dwz_list, &dwz_list_elements,
3103                                     &dwz_types_ignore,
3104                                     &dwz_types_elements_ignore))
3105         {
3106           warning (_("could not read '.gdb_index' section from %s; skipping"),
3107                    bfd_get_filename (dwz->dwz_bfd));
3108           return 0;
3109         }
3110     }
3111
3112   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3113                          dwz_list_elements);
3114
3115   if (types_list_elements)
3116     {
3117       struct dwarf2_section_info *section;
3118
3119       /* We can only handle a single .debug_types when we have an
3120          index.  */
3121       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3122         return 0;
3123
3124       section = VEC_index (dwarf2_section_info_def,
3125                            dwarf2_per_objfile->types, 0);
3126
3127       create_signatured_type_table_from_index (objfile, section, types_list,
3128                                                types_list_elements);
3129     }
3130
3131   create_addrmap_from_index (objfile, &local_map);
3132
3133   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
3134   *map = local_map;
3135
3136   dwarf2_per_objfile->index_table = map;
3137   dwarf2_per_objfile->using_index = 1;
3138   dwarf2_per_objfile->quick_file_names_table =
3139     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3140
3141   return 1;
3142 }
3143
3144 /* A helper for the "quick" functions which sets the global
3145    dwarf2_per_objfile according to OBJFILE.  */
3146
3147 static void
3148 dw2_setup (struct objfile *objfile)
3149 {
3150   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
3151   gdb_assert (dwarf2_per_objfile);
3152 }
3153
3154 /* die_reader_func for dw2_get_file_names.  */
3155
3156 static void
3157 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3158                            const gdb_byte *info_ptr,
3159                            struct die_info *comp_unit_die,
3160                            int has_children,
3161                            void *data)
3162 {
3163   struct dwarf2_cu *cu = reader->cu;
3164   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3165   struct objfile *objfile = dwarf2_per_objfile->objfile;
3166   struct dwarf2_per_cu_data *lh_cu;
3167   struct line_header *lh;
3168   struct attribute *attr;
3169   int i;
3170   const char *name, *comp_dir;
3171   void **slot;
3172   struct quick_file_names *qfn;
3173   unsigned int line_offset;
3174
3175   gdb_assert (! this_cu->is_debug_types);
3176
3177   /* Our callers never want to match partial units -- instead they
3178      will match the enclosing full CU.  */
3179   if (comp_unit_die->tag == DW_TAG_partial_unit)
3180     {
3181       this_cu->v.quick->no_file_data = 1;
3182       return;
3183     }
3184
3185   lh_cu = this_cu;
3186   lh = NULL;
3187   slot = NULL;
3188   line_offset = 0;
3189
3190   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3191   if (attr)
3192     {
3193       struct quick_file_names find_entry;
3194
3195       line_offset = DW_UNSND (attr);
3196
3197       /* We may have already read in this line header (TU line header sharing).
3198          If we have we're done.  */
3199       find_entry.hash.dwo_unit = cu->dwo_unit;
3200       find_entry.hash.line_offset.sect_off = line_offset;
3201       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3202                              &find_entry, INSERT);
3203       if (*slot != NULL)
3204         {
3205           lh_cu->v.quick->file_names = *slot;
3206           return;
3207         }
3208
3209       lh = dwarf_decode_line_header (line_offset, cu);
3210     }
3211   if (lh == NULL)
3212     {
3213       lh_cu->v.quick->no_file_data = 1;
3214       return;
3215     }
3216
3217   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
3218   qfn->hash.dwo_unit = cu->dwo_unit;
3219   qfn->hash.line_offset.sect_off = line_offset;
3220   gdb_assert (slot != NULL);
3221   *slot = qfn;
3222
3223   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
3224
3225   qfn->num_file_names = lh->num_file_names;
3226   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
3227                                    lh->num_file_names * sizeof (char *));
3228   for (i = 0; i < lh->num_file_names; ++i)
3229     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
3230   qfn->real_names = NULL;
3231
3232   free_line_header (lh);
3233
3234   lh_cu->v.quick->file_names = qfn;
3235 }
3236
3237 /* A helper for the "quick" functions which attempts to read the line
3238    table for THIS_CU.  */
3239
3240 static struct quick_file_names *
3241 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3242 {
3243   /* This should never be called for TUs.  */
3244   gdb_assert (! this_cu->is_debug_types);
3245   /* Nor type unit groups.  */
3246   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3247
3248   if (this_cu->v.quick->file_names != NULL)
3249     return this_cu->v.quick->file_names;
3250   /* If we know there is no line data, no point in looking again.  */
3251   if (this_cu->v.quick->no_file_data)
3252     return NULL;
3253
3254   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3255
3256   if (this_cu->v.quick->no_file_data)
3257     return NULL;
3258   return this_cu->v.quick->file_names;
3259 }
3260
3261 /* A helper for the "quick" functions which computes and caches the
3262    real path for a given file name from the line table.  */
3263
3264 static const char *
3265 dw2_get_real_path (struct objfile *objfile,
3266                    struct quick_file_names *qfn, int index)
3267 {
3268   if (qfn->real_names == NULL)
3269     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3270                                       qfn->num_file_names, sizeof (char *));
3271
3272   if (qfn->real_names[index] == NULL)
3273     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3274
3275   return qfn->real_names[index];
3276 }
3277
3278 static struct symtab *
3279 dw2_find_last_source_symtab (struct objfile *objfile)
3280 {
3281   int index;
3282
3283   dw2_setup (objfile);
3284   index = dwarf2_per_objfile->n_comp_units - 1;
3285   return dw2_instantiate_symtab (dw2_get_cu (index));
3286 }
3287
3288 /* Traversal function for dw2_forget_cached_source_info.  */
3289
3290 static int
3291 dw2_free_cached_file_names (void **slot, void *info)
3292 {
3293   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3294
3295   if (file_data->real_names)
3296     {
3297       int i;
3298
3299       for (i = 0; i < file_data->num_file_names; ++i)
3300         {
3301           xfree ((void*) file_data->real_names[i]);
3302           file_data->real_names[i] = NULL;
3303         }
3304     }
3305
3306   return 1;
3307 }
3308
3309 static void
3310 dw2_forget_cached_source_info (struct objfile *objfile)
3311 {
3312   dw2_setup (objfile);
3313
3314   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3315                           dw2_free_cached_file_names, NULL);
3316 }
3317
3318 /* Helper function for dw2_map_symtabs_matching_filename that expands
3319    the symtabs and calls the iterator.  */
3320
3321 static int
3322 dw2_map_expand_apply (struct objfile *objfile,
3323                       struct dwarf2_per_cu_data *per_cu,
3324                       const char *name, const char *real_path,
3325                       int (*callback) (struct symtab *, void *),
3326                       void *data)
3327 {
3328   struct symtab *last_made = objfile->symtabs;
3329
3330   /* Don't visit already-expanded CUs.  */
3331   if (per_cu->v.quick->symtab)
3332     return 0;
3333
3334   /* This may expand more than one symtab, and we want to iterate over
3335      all of them.  */
3336   dw2_instantiate_symtab (per_cu);
3337
3338   return iterate_over_some_symtabs (name, real_path, callback, data,
3339                                     objfile->symtabs, last_made);
3340 }
3341
3342 /* Implementation of the map_symtabs_matching_filename method.  */
3343
3344 static int
3345 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3346                                    const char *real_path,
3347                                    int (*callback) (struct symtab *, void *),
3348                                    void *data)
3349 {
3350   int i;
3351   const char *name_basename = lbasename (name);
3352
3353   dw2_setup (objfile);
3354
3355   /* The rule is CUs specify all the files, including those used by
3356      any TU, so there's no need to scan TUs here.  */
3357
3358   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3359     {
3360       int j;
3361       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3362       struct quick_file_names *file_data;
3363
3364       /* We only need to look at symtabs not already expanded.  */
3365       if (per_cu->v.quick->symtab)
3366         continue;
3367
3368       file_data = dw2_get_file_names (per_cu);
3369       if (file_data == NULL)
3370         continue;
3371
3372       for (j = 0; j < file_data->num_file_names; ++j)
3373         {
3374           const char *this_name = file_data->file_names[j];
3375           const char *this_real_name;
3376
3377           if (compare_filenames_for_search (this_name, name))
3378             {
3379               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3380                                         callback, data))
3381                 return 1;
3382               continue;
3383             }
3384
3385           /* Before we invoke realpath, which can get expensive when many
3386              files are involved, do a quick comparison of the basenames.  */
3387           if (! basenames_may_differ
3388               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3389             continue;
3390
3391           this_real_name = dw2_get_real_path (objfile, file_data, j);
3392           if (compare_filenames_for_search (this_real_name, name))
3393             {
3394               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3395                                         callback, data))
3396                 return 1;
3397               continue;
3398             }
3399
3400           if (real_path != NULL)
3401             {
3402               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3403               gdb_assert (IS_ABSOLUTE_PATH (name));
3404               if (this_real_name != NULL
3405                   && FILENAME_CMP (real_path, this_real_name) == 0)
3406                 {
3407                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3408                                             callback, data))
3409                     return 1;
3410                   continue;
3411                 }
3412             }
3413         }
3414     }
3415
3416   return 0;
3417 }
3418
3419 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3420
3421 struct dw2_symtab_iterator
3422 {
3423   /* The internalized form of .gdb_index.  */
3424   struct mapped_index *index;
3425   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3426   int want_specific_block;
3427   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3428      Unused if !WANT_SPECIFIC_BLOCK.  */
3429   int block_index;
3430   /* The kind of symbol we're looking for.  */
3431   domain_enum domain;
3432   /* The list of CUs from the index entry of the symbol,
3433      or NULL if not found.  */
3434   offset_type *vec;
3435   /* The next element in VEC to look at.  */
3436   int next;
3437   /* The number of elements in VEC, or zero if there is no match.  */
3438   int length;
3439 };
3440
3441 /* Initialize the index symtab iterator ITER.
3442    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3443    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3444
3445 static void
3446 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3447                       struct mapped_index *index,
3448                       int want_specific_block,
3449                       int block_index,
3450                       domain_enum domain,
3451                       const char *name)
3452 {
3453   iter->index = index;
3454   iter->want_specific_block = want_specific_block;
3455   iter->block_index = block_index;
3456   iter->domain = domain;
3457   iter->next = 0;
3458
3459   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3460     iter->length = MAYBE_SWAP (*iter->vec);
3461   else
3462     {
3463       iter->vec = NULL;
3464       iter->length = 0;
3465     }
3466 }
3467
3468 /* Return the next matching CU or NULL if there are no more.  */
3469
3470 static struct dwarf2_per_cu_data *
3471 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3472 {
3473   for ( ; iter->next < iter->length; ++iter->next)
3474     {
3475       offset_type cu_index_and_attrs =
3476         MAYBE_SWAP (iter->vec[iter->next + 1]);
3477       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3478       struct dwarf2_per_cu_data *per_cu;
3479       int want_static = iter->block_index != GLOBAL_BLOCK;
3480       /* This value is only valid for index versions >= 7.  */
3481       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3482       gdb_index_symbol_kind symbol_kind =
3483         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3484       /* Only check the symbol attributes if they're present.
3485          Indices prior to version 7 don't record them,
3486          and indices >= 7 may elide them for certain symbols
3487          (gold does this).  */
3488       int attrs_valid =
3489         (iter->index->version >= 7
3490          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3491
3492       /* Don't crash on bad data.  */
3493       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3494                        + dwarf2_per_objfile->n_type_units))
3495         {
3496           complaint (&symfile_complaints,
3497                      _(".gdb_index entry has bad CU index"
3498                        " [in module %s]"),
3499                      objfile_name (dwarf2_per_objfile->objfile));
3500           continue;
3501         }
3502
3503       per_cu = dw2_get_cu (cu_index);
3504
3505       /* Skip if already read in.  */
3506       if (per_cu->v.quick->symtab)
3507         continue;
3508
3509       if (attrs_valid
3510           && iter->want_specific_block
3511           && want_static != is_static)
3512         continue;
3513
3514       /* Only check the symbol's kind if it has one.  */
3515       if (attrs_valid)
3516         {
3517           switch (iter->domain)
3518             {
3519             case VAR_DOMAIN:
3520               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3521                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3522                   /* Some types are also in VAR_DOMAIN.  */
3523                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3524                 continue;
3525               break;
3526             case STRUCT_DOMAIN:
3527               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3528                 continue;
3529               break;
3530             case LABEL_DOMAIN:
3531               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3532                 continue;
3533               break;
3534             default:
3535               break;
3536             }
3537         }
3538
3539       ++iter->next;
3540       return per_cu;
3541     }
3542
3543   return NULL;
3544 }
3545
3546 static struct symtab *
3547 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3548                    const char *name, domain_enum domain)
3549 {
3550   struct symtab *stab_best = NULL;
3551   struct mapped_index *index;
3552
3553   dw2_setup (objfile);
3554
3555   index = dwarf2_per_objfile->index_table;
3556
3557   /* index is NULL if OBJF_READNOW.  */
3558   if (index)
3559     {
3560       struct dw2_symtab_iterator iter;
3561       struct dwarf2_per_cu_data *per_cu;
3562
3563       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3564
3565       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3566         {
3567           struct symbol *sym = NULL;
3568           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3569
3570           /* Some caution must be observed with overloaded functions
3571              and methods, since the index will not contain any overload
3572              information (but NAME might contain it).  */
3573           if (stab->primary)
3574             {
3575               struct blockvector *bv = BLOCKVECTOR (stab);
3576               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3577
3578               sym = lookup_block_symbol (block, name, domain);
3579             }
3580
3581           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3582             {
3583               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3584                 return stab;
3585
3586               stab_best = stab;
3587             }
3588
3589           /* Keep looking through other CUs.  */
3590         }
3591     }
3592
3593   return stab_best;
3594 }
3595
3596 static void
3597 dw2_print_stats (struct objfile *objfile)
3598 {
3599   int i, total, count;
3600
3601   dw2_setup (objfile);
3602   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3603   count = 0;
3604   for (i = 0; i < total; ++i)
3605     {
3606       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3607
3608       if (!per_cu->v.quick->symtab)
3609         ++count;
3610     }
3611   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3612   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3613 }
3614
3615 /* This dumps minimal information about the index.
3616    It is called via "mt print objfiles".
3617    One use is to verify .gdb_index has been loaded by the
3618    gdb.dwarf2/gdb-index.exp testcase.  */
3619
3620 static void
3621 dw2_dump (struct objfile *objfile)
3622 {
3623   dw2_setup (objfile);
3624   gdb_assert (dwarf2_per_objfile->using_index);
3625   printf_filtered (".gdb_index:");
3626   if (dwarf2_per_objfile->index_table != NULL)
3627     {
3628       printf_filtered (" version %d\n",
3629                        dwarf2_per_objfile->index_table->version);
3630     }
3631   else
3632     printf_filtered (" faked for \"readnow\"\n");
3633   printf_filtered ("\n");
3634 }
3635
3636 static void
3637 dw2_relocate (struct objfile *objfile,
3638               const struct section_offsets *new_offsets,
3639               const struct section_offsets *delta)
3640 {
3641   /* There's nothing to relocate here.  */
3642 }
3643
3644 static void
3645 dw2_expand_symtabs_for_function (struct objfile *objfile,
3646                                  const char *func_name)
3647 {
3648   struct mapped_index *index;
3649
3650   dw2_setup (objfile);
3651
3652   index = dwarf2_per_objfile->index_table;
3653
3654   /* index is NULL if OBJF_READNOW.  */
3655   if (index)
3656     {
3657       struct dw2_symtab_iterator iter;
3658       struct dwarf2_per_cu_data *per_cu;
3659
3660       /* Note: It doesn't matter what we pass for block_index here.  */
3661       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3662                             func_name);
3663
3664       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3665         dw2_instantiate_symtab (per_cu);
3666     }
3667 }
3668
3669 static void
3670 dw2_expand_all_symtabs (struct objfile *objfile)
3671 {
3672   int i;
3673
3674   dw2_setup (objfile);
3675
3676   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3677                    + dwarf2_per_objfile->n_type_units); ++i)
3678     {
3679       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3680
3681       dw2_instantiate_symtab (per_cu);
3682     }
3683 }
3684
3685 static void
3686 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3687                                   const char *fullname)
3688 {
3689   int i;
3690
3691   dw2_setup (objfile);
3692
3693   /* We don't need to consider type units here.
3694      This is only called for examining code, e.g. expand_line_sal.
3695      There can be an order of magnitude (or more) more type units
3696      than comp units, and we avoid them if we can.  */
3697
3698   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3699     {
3700       int j;
3701       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3702       struct quick_file_names *file_data;
3703
3704       /* We only need to look at symtabs not already expanded.  */
3705       if (per_cu->v.quick->symtab)
3706         continue;
3707
3708       file_data = dw2_get_file_names (per_cu);
3709       if (file_data == NULL)
3710         continue;
3711
3712       for (j = 0; j < file_data->num_file_names; ++j)
3713         {
3714           const char *this_fullname = file_data->file_names[j];
3715
3716           if (filename_cmp (this_fullname, fullname) == 0)
3717             {
3718               dw2_instantiate_symtab (per_cu);
3719               break;
3720             }
3721         }
3722     }
3723 }
3724
3725 static void
3726 dw2_map_matching_symbols (struct objfile *objfile,
3727                           const char * name, domain_enum namespace,
3728                           int global,
3729                           int (*callback) (struct block *,
3730                                            struct symbol *, void *),
3731                           void *data, symbol_compare_ftype *match,
3732                           symbol_compare_ftype *ordered_compare)
3733 {
3734   /* Currently unimplemented; used for Ada.  The function can be called if the
3735      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3736      does not look for non-Ada symbols this function should just return.  */
3737 }
3738
3739 static void
3740 dw2_expand_symtabs_matching
3741   (struct objfile *objfile,
3742    int (*file_matcher) (const char *, void *, int basenames),
3743    int (*name_matcher) (const char *, void *),
3744    enum search_domain kind,
3745    void *data)
3746 {
3747   int i;
3748   offset_type iter;
3749   struct mapped_index *index;
3750
3751   dw2_setup (objfile);
3752
3753   /* index_table is NULL if OBJF_READNOW.  */
3754   if (!dwarf2_per_objfile->index_table)
3755     return;
3756   index = dwarf2_per_objfile->index_table;
3757
3758   if (file_matcher != NULL)
3759     {
3760       struct cleanup *cleanup;
3761       htab_t visited_found, visited_not_found;
3762
3763       visited_found = htab_create_alloc (10,
3764                                          htab_hash_pointer, htab_eq_pointer,
3765                                          NULL, xcalloc, xfree);
3766       cleanup = make_cleanup_htab_delete (visited_found);
3767       visited_not_found = htab_create_alloc (10,
3768                                              htab_hash_pointer, htab_eq_pointer,
3769                                              NULL, xcalloc, xfree);
3770       make_cleanup_htab_delete (visited_not_found);
3771
3772       /* The rule is CUs specify all the files, including those used by
3773          any TU, so there's no need to scan TUs here.  */
3774
3775       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3776         {
3777           int j;
3778           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3779           struct quick_file_names *file_data;
3780           void **slot;
3781
3782           per_cu->v.quick->mark = 0;
3783
3784           /* We only need to look at symtabs not already expanded.  */
3785           if (per_cu->v.quick->symtab)
3786             continue;
3787
3788           file_data = dw2_get_file_names (per_cu);
3789           if (file_data == NULL)
3790             continue;
3791
3792           if (htab_find (visited_not_found, file_data) != NULL)
3793             continue;
3794           else if (htab_find (visited_found, file_data) != NULL)
3795             {
3796               per_cu->v.quick->mark = 1;
3797               continue;
3798             }
3799
3800           for (j = 0; j < file_data->num_file_names; ++j)
3801             {
3802               const char *this_real_name;
3803
3804               if (file_matcher (file_data->file_names[j], data, 0))
3805                 {
3806                   per_cu->v.quick->mark = 1;
3807                   break;
3808                 }
3809
3810               /* Before we invoke realpath, which can get expensive when many
3811                  files are involved, do a quick comparison of the basenames.  */
3812               if (!basenames_may_differ
3813                   && !file_matcher (lbasename (file_data->file_names[j]),
3814                                     data, 1))
3815                 continue;
3816
3817               this_real_name = dw2_get_real_path (objfile, file_data, j);
3818               if (file_matcher (this_real_name, data, 0))
3819                 {
3820                   per_cu->v.quick->mark = 1;
3821                   break;
3822                 }
3823             }
3824
3825           slot = htab_find_slot (per_cu->v.quick->mark
3826                                  ? visited_found
3827                                  : visited_not_found,
3828                                  file_data, INSERT);
3829           *slot = file_data;
3830         }
3831
3832       do_cleanups (cleanup);
3833     }
3834
3835   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3836     {
3837       offset_type idx = 2 * iter;
3838       const char *name;
3839       offset_type *vec, vec_len, vec_idx;
3840
3841       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3842         continue;
3843
3844       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3845
3846       if (! (*name_matcher) (name, data))
3847         continue;
3848
3849       /* The name was matched, now expand corresponding CUs that were
3850          marked.  */
3851       vec = (offset_type *) (index->constant_pool
3852                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3853       vec_len = MAYBE_SWAP (vec[0]);
3854       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3855         {
3856           struct dwarf2_per_cu_data *per_cu;
3857           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3858           gdb_index_symbol_kind symbol_kind =
3859             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3860           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3861           /* Only check the symbol attributes if they're present.
3862              Indices prior to version 7 don't record them,
3863              and indices >= 7 may elide them for certain symbols
3864              (gold does this).  */
3865           int attrs_valid =
3866             (index->version >= 7
3867              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3868
3869           /* Only check the symbol's kind if it has one.  */
3870           if (attrs_valid)
3871             {
3872               switch (kind)
3873                 {
3874                 case VARIABLES_DOMAIN:
3875                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3876                     continue;
3877                   break;
3878                 case FUNCTIONS_DOMAIN:
3879                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3880                     continue;
3881                   break;
3882                 case TYPES_DOMAIN:
3883                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3884                     continue;
3885                   break;
3886                 default:
3887                   break;
3888                 }
3889             }
3890
3891           /* Don't crash on bad data.  */
3892           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3893                            + dwarf2_per_objfile->n_type_units))
3894             {
3895               complaint (&symfile_complaints,
3896                          _(".gdb_index entry has bad CU index"
3897                            " [in module %s]"), objfile_name (objfile));
3898               continue;
3899             }
3900
3901           per_cu = dw2_get_cu (cu_index);
3902           if (file_matcher == NULL || per_cu->v.quick->mark)
3903             dw2_instantiate_symtab (per_cu);
3904         }
3905     }
3906 }
3907
3908 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3909    symtab.  */
3910
3911 static struct symtab *
3912 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3913 {
3914   int i;
3915
3916   if (BLOCKVECTOR (symtab) != NULL
3917       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3918     return symtab;
3919
3920   if (symtab->includes == NULL)
3921     return NULL;
3922
3923   for (i = 0; symtab->includes[i]; ++i)
3924     {
3925       struct symtab *s = symtab->includes[i];
3926
3927       s = recursively_find_pc_sect_symtab (s, pc);
3928       if (s != NULL)
3929         return s;
3930     }
3931
3932   return NULL;
3933 }
3934
3935 static struct symtab *
3936 dw2_find_pc_sect_symtab (struct objfile *objfile,
3937                          struct minimal_symbol *msymbol,
3938                          CORE_ADDR pc,
3939                          struct obj_section *section,
3940                          int warn_if_readin)
3941 {
3942   struct dwarf2_per_cu_data *data;
3943   struct symtab *result;
3944
3945   dw2_setup (objfile);
3946
3947   if (!objfile->psymtabs_addrmap)
3948     return NULL;
3949
3950   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3951   if (!data)
3952     return NULL;
3953
3954   if (warn_if_readin && data->v.quick->symtab)
3955     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3956              paddress (get_objfile_arch (objfile), pc));
3957
3958   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3959   gdb_assert (result != NULL);
3960   return result;
3961 }
3962
3963 static void
3964 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3965                           void *data, int need_fullname)
3966 {
3967   int i;
3968   struct cleanup *cleanup;
3969   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3970                                       NULL, xcalloc, xfree);
3971
3972   cleanup = make_cleanup_htab_delete (visited);
3973   dw2_setup (objfile);
3974
3975   /* The rule is CUs specify all the files, including those used by
3976      any TU, so there's no need to scan TUs here.
3977      We can ignore file names coming from already-expanded CUs.  */
3978
3979   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3980     {
3981       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3982
3983       if (per_cu->v.quick->symtab)
3984         {
3985           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3986                                         INSERT);
3987
3988           *slot = per_cu->v.quick->file_names;
3989         }
3990     }
3991
3992   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3993     {
3994       int j;
3995       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3996       struct quick_file_names *file_data;
3997       void **slot;
3998
3999       /* We only need to look at symtabs not already expanded.  */
4000       if (per_cu->v.quick->symtab)
4001         continue;
4002
4003       file_data = dw2_get_file_names (per_cu);
4004       if (file_data == NULL)
4005         continue;
4006
4007       slot = htab_find_slot (visited, file_data, INSERT);
4008       if (*slot)
4009         {
4010           /* Already visited.  */
4011           continue;
4012         }
4013       *slot = file_data;
4014
4015       for (j = 0; j < file_data->num_file_names; ++j)
4016         {
4017           const char *this_real_name;
4018
4019           if (need_fullname)
4020             this_real_name = dw2_get_real_path (objfile, file_data, j);
4021           else
4022             this_real_name = NULL;
4023           (*fun) (file_data->file_names[j], this_real_name, data);
4024         }
4025     }
4026
4027   do_cleanups (cleanup);
4028 }
4029
4030 static int
4031 dw2_has_symbols (struct objfile *objfile)
4032 {
4033   return 1;
4034 }
4035
4036 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4037 {
4038   dw2_has_symbols,
4039   dw2_find_last_source_symtab,
4040   dw2_forget_cached_source_info,
4041   dw2_map_symtabs_matching_filename,
4042   dw2_lookup_symbol,
4043   dw2_print_stats,
4044   dw2_dump,
4045   dw2_relocate,
4046   dw2_expand_symtabs_for_function,
4047   dw2_expand_all_symtabs,
4048   dw2_expand_symtabs_with_fullname,
4049   dw2_map_matching_symbols,
4050   dw2_expand_symtabs_matching,
4051   dw2_find_pc_sect_symtab,
4052   dw2_map_symbol_filenames
4053 };
4054
4055 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4056    file will use psymtabs, or 1 if using the GNU index.  */
4057
4058 int
4059 dwarf2_initialize_objfile (struct objfile *objfile)
4060 {
4061   /* If we're about to read full symbols, don't bother with the
4062      indices.  In this case we also don't care if some other debug
4063      format is making psymtabs, because they are all about to be
4064      expanded anyway.  */
4065   if ((objfile->flags & OBJF_READNOW))
4066     {
4067       int i;
4068
4069       dwarf2_per_objfile->using_index = 1;
4070       create_all_comp_units (objfile);
4071       create_all_type_units (objfile);
4072       dwarf2_per_objfile->quick_file_names_table =
4073         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4074
4075       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4076                        + dwarf2_per_objfile->n_type_units); ++i)
4077         {
4078           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4079
4080           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4081                                             struct dwarf2_per_cu_quick_data);
4082         }
4083
4084       /* Return 1 so that gdb sees the "quick" functions.  However,
4085          these functions will be no-ops because we will have expanded
4086          all symtabs.  */
4087       return 1;
4088     }
4089
4090   if (dwarf2_read_index (objfile))
4091     return 1;
4092
4093   return 0;
4094 }
4095
4096 \f
4097
4098 /* Build a partial symbol table.  */
4099
4100 void
4101 dwarf2_build_psymtabs (struct objfile *objfile)
4102 {
4103   volatile struct gdb_exception except;
4104
4105   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4106     {
4107       init_psymbol_list (objfile, 1024);
4108     }
4109
4110   TRY_CATCH (except, RETURN_MASK_ERROR)
4111     {
4112       /* This isn't really ideal: all the data we allocate on the
4113          objfile's obstack is still uselessly kept around.  However,
4114          freeing it seems unsafe.  */
4115       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
4116
4117       dwarf2_build_psymtabs_hard (objfile);
4118       discard_cleanups (cleanups);
4119     }
4120   if (except.reason < 0)
4121     exception_print (gdb_stderr, except);
4122 }
4123
4124 /* Return the total length of the CU described by HEADER.  */
4125
4126 static unsigned int
4127 get_cu_length (const struct comp_unit_head *header)
4128 {
4129   return header->initial_length_size + header->length;
4130 }
4131
4132 /* Return TRUE if OFFSET is within CU_HEADER.  */
4133
4134 static inline int
4135 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
4136 {
4137   sect_offset bottom = { cu_header->offset.sect_off };
4138   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
4139
4140   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
4141 }
4142
4143 /* Find the base address of the compilation unit for range lists and
4144    location lists.  It will normally be specified by DW_AT_low_pc.
4145    In DWARF-3 draft 4, the base address could be overridden by
4146    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4147    compilation units with discontinuous ranges.  */
4148
4149 static void
4150 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4151 {
4152   struct attribute *attr;
4153
4154   cu->base_known = 0;
4155   cu->base_address = 0;
4156
4157   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4158   if (attr)
4159     {
4160       cu->base_address = DW_ADDR (attr);
4161       cu->base_known = 1;
4162     }
4163   else
4164     {
4165       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4166       if (attr)
4167         {
4168           cu->base_address = DW_ADDR (attr);
4169           cu->base_known = 1;
4170         }
4171     }
4172 }
4173
4174 /* Read in the comp unit header information from the debug_info at info_ptr.
4175    NOTE: This leaves members offset, first_die_offset to be filled in
4176    by the caller.  */
4177
4178 static const gdb_byte *
4179 read_comp_unit_head (struct comp_unit_head *cu_header,
4180                      const gdb_byte *info_ptr, bfd *abfd)
4181 {
4182   int signed_addr;
4183   unsigned int bytes_read;
4184
4185   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4186   cu_header->initial_length_size = bytes_read;
4187   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4188   info_ptr += bytes_read;
4189   cu_header->version = read_2_bytes (abfd, info_ptr);
4190   info_ptr += 2;
4191   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
4192                                              &bytes_read);
4193   info_ptr += bytes_read;
4194   cu_header->addr_size = read_1_byte (abfd, info_ptr);
4195   info_ptr += 1;
4196   signed_addr = bfd_get_sign_extend_vma (abfd);
4197   if (signed_addr < 0)
4198     internal_error (__FILE__, __LINE__,
4199                     _("read_comp_unit_head: dwarf from non elf file"));
4200   cu_header->signed_addr_p = signed_addr;
4201
4202   return info_ptr;
4203 }
4204
4205 /* Helper function that returns the proper abbrev section for
4206    THIS_CU.  */
4207
4208 static struct dwarf2_section_info *
4209 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4210 {
4211   struct dwarf2_section_info *abbrev;
4212
4213   if (this_cu->is_dwz)
4214     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4215   else
4216     abbrev = &dwarf2_per_objfile->abbrev;
4217
4218   return abbrev;
4219 }
4220
4221 /* Subroutine of read_and_check_comp_unit_head and
4222    read_and_check_type_unit_head to simplify them.
4223    Perform various error checking on the header.  */
4224
4225 static void
4226 error_check_comp_unit_head (struct comp_unit_head *header,
4227                             struct dwarf2_section_info *section,
4228                             struct dwarf2_section_info *abbrev_section)
4229 {
4230   bfd *abfd = get_section_bfd_owner (section);
4231   const char *filename = get_section_file_name (section);
4232
4233   if (header->version != 2 && header->version != 3 && header->version != 4)
4234     error (_("Dwarf Error: wrong version in compilation unit header "
4235            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4236            filename);
4237
4238   if (header->abbrev_offset.sect_off
4239       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4240     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4241            "(offset 0x%lx + 6) [in module %s]"),
4242            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4243            filename);
4244
4245   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4246      avoid potential 32-bit overflow.  */
4247   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4248       > section->size)
4249     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4250            "(offset 0x%lx + 0) [in module %s]"),
4251            (long) header->length, (long) header->offset.sect_off,
4252            filename);
4253 }
4254
4255 /* Read in a CU/TU header and perform some basic error checking.
4256    The contents of the header are stored in HEADER.
4257    The result is a pointer to the start of the first DIE.  */
4258
4259 static const gdb_byte *
4260 read_and_check_comp_unit_head (struct comp_unit_head *header,
4261                                struct dwarf2_section_info *section,
4262                                struct dwarf2_section_info *abbrev_section,
4263                                const gdb_byte *info_ptr,
4264                                int is_debug_types_section)
4265 {
4266   const gdb_byte *beg_of_comp_unit = info_ptr;
4267   bfd *abfd = get_section_bfd_owner (section);
4268
4269   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4270
4271   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4272
4273   /* If we're reading a type unit, skip over the signature and
4274      type_offset fields.  */
4275   if (is_debug_types_section)
4276     info_ptr += 8 /*signature*/ + header->offset_size;
4277
4278   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4279
4280   error_check_comp_unit_head (header, section, abbrev_section);
4281
4282   return info_ptr;
4283 }
4284
4285 /* Read in the types comp unit header information from .debug_types entry at
4286    types_ptr.  The result is a pointer to one past the end of the header.  */
4287
4288 static const gdb_byte *
4289 read_and_check_type_unit_head (struct comp_unit_head *header,
4290                                struct dwarf2_section_info *section,
4291                                struct dwarf2_section_info *abbrev_section,
4292                                const gdb_byte *info_ptr,
4293                                ULONGEST *signature,
4294                                cu_offset *type_offset_in_tu)
4295 {
4296   const gdb_byte *beg_of_comp_unit = info_ptr;
4297   bfd *abfd = get_section_bfd_owner (section);
4298
4299   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4300
4301   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4302
4303   /* If we're reading a type unit, skip over the signature and
4304      type_offset fields.  */
4305   if (signature != NULL)
4306     *signature = read_8_bytes (abfd, info_ptr);
4307   info_ptr += 8;
4308   if (type_offset_in_tu != NULL)
4309     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4310                                                header->offset_size);
4311   info_ptr += header->offset_size;
4312
4313   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4314
4315   error_check_comp_unit_head (header, section, abbrev_section);
4316
4317   return info_ptr;
4318 }
4319
4320 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4321
4322 static sect_offset
4323 read_abbrev_offset (struct dwarf2_section_info *section,
4324                     sect_offset offset)
4325 {
4326   bfd *abfd = get_section_bfd_owner (section);
4327   const gdb_byte *info_ptr;
4328   unsigned int length, initial_length_size, offset_size;
4329   sect_offset abbrev_offset;
4330
4331   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4332   info_ptr = section->buffer + offset.sect_off;
4333   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4334   offset_size = initial_length_size == 4 ? 4 : 8;
4335   info_ptr += initial_length_size + 2 /*version*/;
4336   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4337   return abbrev_offset;
4338 }
4339
4340 /* Allocate a new partial symtab for file named NAME and mark this new
4341    partial symtab as being an include of PST.  */
4342
4343 static void
4344 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4345                                struct objfile *objfile)
4346 {
4347   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4348
4349   if (!IS_ABSOLUTE_PATH (subpst->filename))
4350     {
4351       /* It shares objfile->objfile_obstack.  */
4352       subpst->dirname = pst->dirname;
4353     }
4354
4355   subpst->section_offsets = pst->section_offsets;
4356   subpst->textlow = 0;
4357   subpst->texthigh = 0;
4358
4359   subpst->dependencies = (struct partial_symtab **)
4360     obstack_alloc (&objfile->objfile_obstack,
4361                    sizeof (struct partial_symtab *));
4362   subpst->dependencies[0] = pst;
4363   subpst->number_of_dependencies = 1;
4364
4365   subpst->globals_offset = 0;
4366   subpst->n_global_syms = 0;
4367   subpst->statics_offset = 0;
4368   subpst->n_static_syms = 0;
4369   subpst->symtab = NULL;
4370   subpst->read_symtab = pst->read_symtab;
4371   subpst->readin = 0;
4372
4373   /* No private part is necessary for include psymtabs.  This property
4374      can be used to differentiate between such include psymtabs and
4375      the regular ones.  */
4376   subpst->read_symtab_private = NULL;
4377 }
4378
4379 /* Read the Line Number Program data and extract the list of files
4380    included by the source file represented by PST.  Build an include
4381    partial symtab for each of these included files.  */
4382
4383 static void
4384 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4385                                struct die_info *die,
4386                                struct partial_symtab *pst)
4387 {
4388   struct line_header *lh = NULL;
4389   struct attribute *attr;
4390
4391   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4392   if (attr)
4393     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4394   if (lh == NULL)
4395     return;  /* No linetable, so no includes.  */
4396
4397   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4398   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4399
4400   free_line_header (lh);
4401 }
4402
4403 static hashval_t
4404 hash_signatured_type (const void *item)
4405 {
4406   const struct signatured_type *sig_type = item;
4407
4408   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4409   return sig_type->signature;
4410 }
4411
4412 static int
4413 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4414 {
4415   const struct signatured_type *lhs = item_lhs;
4416   const struct signatured_type *rhs = item_rhs;
4417
4418   return lhs->signature == rhs->signature;
4419 }
4420
4421 /* Allocate a hash table for signatured types.  */
4422
4423 static htab_t
4424 allocate_signatured_type_table (struct objfile *objfile)
4425 {
4426   return htab_create_alloc_ex (41,
4427                                hash_signatured_type,
4428                                eq_signatured_type,
4429                                NULL,
4430                                &objfile->objfile_obstack,
4431                                hashtab_obstack_allocate,
4432                                dummy_obstack_deallocate);
4433 }
4434
4435 /* A helper function to add a signatured type CU to a table.  */
4436
4437 static int
4438 add_signatured_type_cu_to_table (void **slot, void *datum)
4439 {
4440   struct signatured_type *sigt = *slot;
4441   struct signatured_type ***datap = datum;
4442
4443   **datap = sigt;
4444   ++*datap;
4445
4446   return 1;
4447 }
4448
4449 /* Create the hash table of all entries in the .debug_types
4450    (or .debug_types.dwo) section(s).
4451    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4452    otherwise it is NULL.
4453
4454    The result is a pointer to the hash table or NULL if there are no types.
4455
4456    Note: This function processes DWO files only, not DWP files.  */
4457
4458 static htab_t
4459 create_debug_types_hash_table (struct dwo_file *dwo_file,
4460                                VEC (dwarf2_section_info_def) *types)
4461 {
4462   struct objfile *objfile = dwarf2_per_objfile->objfile;
4463   htab_t types_htab = NULL;
4464   int ix;
4465   struct dwarf2_section_info *section;
4466   struct dwarf2_section_info *abbrev_section;
4467
4468   if (VEC_empty (dwarf2_section_info_def, types))
4469     return NULL;
4470
4471   abbrev_section = (dwo_file != NULL
4472                     ? &dwo_file->sections.abbrev
4473                     : &dwarf2_per_objfile->abbrev);
4474
4475   if (dwarf2_read_debug)
4476     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4477                         dwo_file ? ".dwo" : "",
4478                         get_section_file_name (abbrev_section));
4479
4480   for (ix = 0;
4481        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4482        ++ix)
4483     {
4484       bfd *abfd;
4485       const gdb_byte *info_ptr, *end_ptr;
4486
4487       dwarf2_read_section (objfile, section);
4488       info_ptr = section->buffer;
4489
4490       if (info_ptr == NULL)
4491         continue;
4492
4493       /* We can't set abfd until now because the section may be empty or
4494          not present, in which case the bfd is unknown.  */
4495       abfd = get_section_bfd_owner (section);
4496
4497       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4498          because we don't need to read any dies: the signature is in the
4499          header.  */
4500
4501       end_ptr = info_ptr + section->size;
4502       while (info_ptr < end_ptr)
4503         {
4504           sect_offset offset;
4505           cu_offset type_offset_in_tu;
4506           ULONGEST signature;
4507           struct signatured_type *sig_type;
4508           struct dwo_unit *dwo_tu;
4509           void **slot;
4510           const gdb_byte *ptr = info_ptr;
4511           struct comp_unit_head header;
4512           unsigned int length;
4513
4514           offset.sect_off = ptr - section->buffer;
4515
4516           /* We need to read the type's signature in order to build the hash
4517              table, but we don't need anything else just yet.  */
4518
4519           ptr = read_and_check_type_unit_head (&header, section,
4520                                                abbrev_section, ptr,
4521                                                &signature, &type_offset_in_tu);
4522
4523           length = get_cu_length (&header);
4524
4525           /* Skip dummy type units.  */
4526           if (ptr >= info_ptr + length
4527               || peek_abbrev_code (abfd, ptr) == 0)
4528             {
4529               info_ptr += length;
4530               continue;
4531             }
4532
4533           if (types_htab == NULL)
4534             {
4535               if (dwo_file)
4536                 types_htab = allocate_dwo_unit_table (objfile);
4537               else
4538                 types_htab = allocate_signatured_type_table (objfile);
4539             }
4540
4541           if (dwo_file)
4542             {
4543               sig_type = NULL;
4544               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4545                                        struct dwo_unit);
4546               dwo_tu->dwo_file = dwo_file;
4547               dwo_tu->signature = signature;
4548               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4549               dwo_tu->section = section;
4550               dwo_tu->offset = offset;
4551               dwo_tu->length = length;
4552             }
4553           else
4554             {
4555               /* N.B.: type_offset is not usable if this type uses a DWO file.
4556                  The real type_offset is in the DWO file.  */
4557               dwo_tu = NULL;
4558               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4559                                          struct signatured_type);
4560               sig_type->signature = signature;
4561               sig_type->type_offset_in_tu = type_offset_in_tu;
4562               sig_type->per_cu.objfile = objfile;
4563               sig_type->per_cu.is_debug_types = 1;
4564               sig_type->per_cu.section = section;
4565               sig_type->per_cu.offset = offset;
4566               sig_type->per_cu.length = length;
4567             }
4568
4569           slot = htab_find_slot (types_htab,
4570                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4571                                  INSERT);
4572           gdb_assert (slot != NULL);
4573           if (*slot != NULL)
4574             {
4575               sect_offset dup_offset;
4576
4577               if (dwo_file)
4578                 {
4579                   const struct dwo_unit *dup_tu = *slot;
4580
4581                   dup_offset = dup_tu->offset;
4582                 }
4583               else
4584                 {
4585                   const struct signatured_type *dup_tu = *slot;
4586
4587                   dup_offset = dup_tu->per_cu.offset;
4588                 }
4589
4590               complaint (&symfile_complaints,
4591                          _("debug type entry at offset 0x%x is duplicate to"
4592                            " the entry at offset 0x%x, signature %s"),
4593                          offset.sect_off, dup_offset.sect_off,
4594                          hex_string (signature));
4595             }
4596           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4597
4598           if (dwarf2_read_debug)
4599             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4600                                 offset.sect_off,
4601                                 hex_string (signature));
4602
4603           info_ptr += length;
4604         }
4605     }
4606
4607   return types_htab;
4608 }
4609
4610 /* Create the hash table of all entries in the .debug_types section,
4611    and initialize all_type_units.
4612    The result is zero if there is an error (e.g. missing .debug_types section),
4613    otherwise non-zero.  */
4614
4615 static int
4616 create_all_type_units (struct objfile *objfile)
4617 {
4618   htab_t types_htab;
4619   struct signatured_type **iter;
4620
4621   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4622   if (types_htab == NULL)
4623     {
4624       dwarf2_per_objfile->signatured_types = NULL;
4625       return 0;
4626     }
4627
4628   dwarf2_per_objfile->signatured_types = types_htab;
4629
4630   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4631   dwarf2_per_objfile->all_type_units
4632     = xmalloc (dwarf2_per_objfile->n_type_units
4633                * sizeof (struct signatured_type *));
4634   iter = &dwarf2_per_objfile->all_type_units[0];
4635   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4636   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4637               == dwarf2_per_objfile->n_type_units);
4638
4639   return 1;
4640 }
4641
4642 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4643    Fill in SIG_ENTRY with DWO_ENTRY.  */
4644
4645 static void
4646 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4647                                   struct signatured_type *sig_entry,
4648                                   struct dwo_unit *dwo_entry)
4649 {
4650   /* Make sure we're not clobbering something we don't expect to.  */
4651   gdb_assert (! sig_entry->per_cu.queued);
4652   gdb_assert (sig_entry->per_cu.cu == NULL);
4653   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4654   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4655   gdb_assert (sig_entry->signature == dwo_entry->signature);
4656   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4657   gdb_assert (sig_entry->type_unit_group == NULL);
4658   gdb_assert (sig_entry->dwo_unit == NULL);
4659
4660   sig_entry->per_cu.section = dwo_entry->section;
4661   sig_entry->per_cu.offset = dwo_entry->offset;
4662   sig_entry->per_cu.length = dwo_entry->length;
4663   sig_entry->per_cu.reading_dwo_directly = 1;
4664   sig_entry->per_cu.objfile = objfile;
4665   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4666   sig_entry->dwo_unit = dwo_entry;
4667 }
4668
4669 /* Subroutine of lookup_signatured_type.
4670    If we haven't read the TU yet, create the signatured_type data structure
4671    for a TU to be read in directly from a DWO file, bypassing the stub.
4672    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4673    using .gdb_index, then when reading a CU we want to stay in the DWO file
4674    containing that CU.  Otherwise we could end up reading several other DWO
4675    files (due to comdat folding) to process the transitive closure of all the
4676    mentioned TUs, and that can be slow.  The current DWO file will have every
4677    type signature that it needs.
4678    We only do this for .gdb_index because in the psymtab case we already have
4679    to read all the DWOs to build the type unit groups.  */
4680
4681 static struct signatured_type *
4682 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4683 {
4684   struct objfile *objfile = dwarf2_per_objfile->objfile;
4685   struct dwo_file *dwo_file;
4686   struct dwo_unit find_dwo_entry, *dwo_entry;
4687   struct signatured_type find_sig_entry, *sig_entry;
4688
4689   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4690
4691   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4692      dwo_unit of the TU itself.  */
4693   dwo_file = cu->dwo_unit->dwo_file;
4694
4695   /* We only ever need to read in one copy of a signatured type.
4696      Just use the global signatured_types array.  If this is the first time
4697      we're reading this type, replace the recorded data from .gdb_index with
4698      this TU.  */
4699
4700   if (dwarf2_per_objfile->signatured_types == NULL)
4701     return NULL;
4702   find_sig_entry.signature = sig;
4703   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4704   if (sig_entry == NULL)
4705     return NULL;
4706
4707   /* We can get here with the TU already read, *or* in the process of being
4708      read.  Don't reassign it if that's the case.  Also note that if the TU is
4709      already being read, it may not have come from a DWO, the program may be
4710      a mix of Fission-compiled code and non-Fission-compiled code.  */
4711   /* Have we already tried to read this TU?  */
4712   if (sig_entry->per_cu.tu_read)
4713     return sig_entry;
4714
4715   /* Ok, this is the first time we're reading this TU.  */
4716   if (dwo_file->tus == NULL)
4717     return NULL;
4718   find_dwo_entry.signature = sig;
4719   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4720   if (dwo_entry == NULL)
4721     return NULL;
4722
4723   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4724   sig_entry->per_cu.tu_read = 1;
4725   return sig_entry;
4726 }
4727
4728 /* Subroutine of lookup_dwp_signatured_type.
4729    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4730
4731 static struct signatured_type *
4732 add_type_unit (ULONGEST sig)
4733 {
4734   struct objfile *objfile = dwarf2_per_objfile->objfile;
4735   int n_type_units = dwarf2_per_objfile->n_type_units;
4736   struct signatured_type *sig_type;
4737   void **slot;
4738
4739   ++n_type_units;
4740   dwarf2_per_objfile->all_type_units =
4741     xrealloc (dwarf2_per_objfile->all_type_units,
4742               n_type_units * sizeof (struct signatured_type *));
4743   dwarf2_per_objfile->n_type_units = n_type_units;
4744   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4745                              struct signatured_type);
4746   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4747   sig_type->signature = sig;
4748   sig_type->per_cu.is_debug_types = 1;
4749   sig_type->per_cu.v.quick =
4750     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4751                     struct dwarf2_per_cu_quick_data);
4752   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4753                          sig_type, INSERT);
4754   gdb_assert (*slot == NULL);
4755   *slot = sig_type;
4756   /* The rest of sig_type must be filled in by the caller.  */
4757   return sig_type;
4758 }
4759
4760 /* Subroutine of lookup_signatured_type.
4761    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4762    then try the DWP file.
4763    Normally this "can't happen", but if there's a bug in signature
4764    generation and/or the DWP file is built incorrectly, it can happen.
4765    Using the type directly from the DWP file means we don't have the stub
4766    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4767    not critical.  [Eventually the stub may go away for type units anyway.]  */
4768
4769 static struct signatured_type *
4770 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4771 {
4772   struct objfile *objfile = dwarf2_per_objfile->objfile;
4773   struct dwp_file *dwp_file = get_dwp_file ();
4774   struct dwo_unit *dwo_entry;
4775   struct signatured_type find_sig_entry, *sig_entry;
4776
4777   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4778   gdb_assert (dwp_file != NULL);
4779
4780   if (dwarf2_per_objfile->signatured_types != NULL)
4781     {
4782       find_sig_entry.signature = sig;
4783       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4784                              &find_sig_entry);
4785       if (sig_entry != NULL)
4786         return sig_entry;
4787     }
4788
4789   /* This is the "shouldn't happen" case.
4790      Try the DWP file and hope for the best.  */
4791   if (dwp_file->tus == NULL)
4792     return NULL;
4793   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
4794                                       sig, 1 /* is_debug_types */);
4795   if (dwo_entry == NULL)
4796     return NULL;
4797
4798   sig_entry = add_type_unit (sig);
4799   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4800
4801   /* The caller will signal a complaint if we return NULL.
4802      Here we don't return NULL but we still want to complain.  */
4803   complaint (&symfile_complaints,
4804              _("Bad type signature %s referenced by %s at 0x%x,"
4805                " coping by using copy in DWP [in module %s]"),
4806              hex_string (sig),
4807              cu->per_cu->is_debug_types ? "TU" : "CU",
4808              cu->per_cu->offset.sect_off,
4809              objfile_name (objfile));
4810
4811   return sig_entry;
4812 }
4813
4814 /* Lookup a signature based type for DW_FORM_ref_sig8.
4815    Returns NULL if signature SIG is not present in the table.
4816    It is up to the caller to complain about this.  */
4817
4818 static struct signatured_type *
4819 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4820 {
4821   if (cu->dwo_unit
4822       && dwarf2_per_objfile->using_index)
4823     {
4824       /* We're in a DWO/DWP file, and we're using .gdb_index.
4825          These cases require special processing.  */
4826       if (get_dwp_file () == NULL)
4827         return lookup_dwo_signatured_type (cu, sig);
4828       else
4829         return lookup_dwp_signatured_type (cu, sig);
4830     }
4831   else
4832     {
4833       struct signatured_type find_entry, *entry;
4834
4835       if (dwarf2_per_objfile->signatured_types == NULL)
4836         return NULL;
4837       find_entry.signature = sig;
4838       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4839       return entry;
4840     }
4841 }
4842 \f
4843 /* Low level DIE reading support.  */
4844
4845 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4846
4847 static void
4848 init_cu_die_reader (struct die_reader_specs *reader,
4849                     struct dwarf2_cu *cu,
4850                     struct dwarf2_section_info *section,
4851                     struct dwo_file *dwo_file)
4852 {
4853   gdb_assert (section->readin && section->buffer != NULL);
4854   reader->abfd = get_section_bfd_owner (section);
4855   reader->cu = cu;
4856   reader->dwo_file = dwo_file;
4857   reader->die_section = section;
4858   reader->buffer = section->buffer;
4859   reader->buffer_end = section->buffer + section->size;
4860   reader->comp_dir = NULL;
4861 }
4862
4863 /* Subroutine of init_cutu_and_read_dies to simplify it.
4864    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4865    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4866    already.
4867
4868    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4869    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4870    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4871    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4872    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4873    COMP_DIR must be non-NULL.
4874    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4875    are filled in with the info of the DIE from the DWO file.
4876    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4877    provided an abbrev table to use.
4878    The result is non-zero if a valid (non-dummy) DIE was found.  */
4879
4880 static int
4881 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4882                         struct dwo_unit *dwo_unit,
4883                         int abbrev_table_provided,
4884                         struct die_info *stub_comp_unit_die,
4885                         const char *stub_comp_dir,
4886                         struct die_reader_specs *result_reader,
4887                         const gdb_byte **result_info_ptr,
4888                         struct die_info **result_comp_unit_die,
4889                         int *result_has_children)
4890 {
4891   struct objfile *objfile = dwarf2_per_objfile->objfile;
4892   struct dwarf2_cu *cu = this_cu->cu;
4893   struct dwarf2_section_info *section;
4894   bfd *abfd;
4895   const gdb_byte *begin_info_ptr, *info_ptr;
4896   const char *comp_dir_string;
4897   ULONGEST signature; /* Or dwo_id.  */
4898   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4899   int i,num_extra_attrs;
4900   struct dwarf2_section_info *dwo_abbrev_section;
4901   struct attribute *attr;
4902   struct attribute comp_dir_attr;
4903   struct die_info *comp_unit_die;
4904
4905   /* Both can't be provided.  */
4906   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4907
4908   /* These attributes aren't processed until later:
4909      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4910      However, the attribute is found in the stub which we won't have later.
4911      In order to not impose this complication on the rest of the code,
4912      we read them here and copy them to the DWO CU/TU die.  */
4913
4914   stmt_list = NULL;
4915   low_pc = NULL;
4916   high_pc = NULL;
4917   ranges = NULL;
4918   comp_dir = NULL;
4919
4920   if (stub_comp_unit_die != NULL)
4921     {
4922       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4923          DWO file.  */
4924       if (! this_cu->is_debug_types)
4925         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4926       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4927       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4928       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4929       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4930
4931       /* There should be a DW_AT_addr_base attribute here (if needed).
4932          We need the value before we can process DW_FORM_GNU_addr_index.  */
4933       cu->addr_base = 0;
4934       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4935       if (attr)
4936         cu->addr_base = DW_UNSND (attr);
4937
4938       /* There should be a DW_AT_ranges_base attribute here (if needed).
4939          We need the value before we can process DW_AT_ranges.  */
4940       cu->ranges_base = 0;
4941       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4942       if (attr)
4943         cu->ranges_base = DW_UNSND (attr);
4944     }
4945   else if (stub_comp_dir != NULL)
4946     {
4947       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4948       comp_dir = (struct attribute *)
4949         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4950       comp_dir->name = DW_AT_comp_dir;
4951       comp_dir->form = DW_FORM_string;
4952       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4953       DW_STRING (comp_dir) = stub_comp_dir;
4954     }
4955
4956   /* Set up for reading the DWO CU/TU.  */
4957   cu->dwo_unit = dwo_unit;
4958   section = dwo_unit->section;
4959   dwarf2_read_section (objfile, section);
4960   abfd = get_section_bfd_owner (section);
4961   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4962   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4963   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4964
4965   if (this_cu->is_debug_types)
4966     {
4967       ULONGEST header_signature;
4968       cu_offset type_offset_in_tu;
4969       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4970
4971       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4972                                                 dwo_abbrev_section,
4973                                                 info_ptr,
4974                                                 &header_signature,
4975                                                 &type_offset_in_tu);
4976       /* This is not an assert because it can be caused by bad debug info.  */
4977       if (sig_type->signature != header_signature)
4978         {
4979           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4980                    " TU at offset 0x%x [in module %s]"),
4981                  hex_string (sig_type->signature),
4982                  hex_string (header_signature),
4983                  dwo_unit->offset.sect_off,
4984                  bfd_get_filename (abfd));
4985         }
4986       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4987       /* For DWOs coming from DWP files, we don't know the CU length
4988          nor the type's offset in the TU until now.  */
4989       dwo_unit->length = get_cu_length (&cu->header);
4990       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4991
4992       /* Establish the type offset that can be used to lookup the type.
4993          For DWO files, we don't know it until now.  */
4994       sig_type->type_offset_in_section.sect_off =
4995         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4996     }
4997   else
4998     {
4999       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5000                                                 dwo_abbrev_section,
5001                                                 info_ptr, 0);
5002       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5003       /* For DWOs coming from DWP files, we don't know the CU length
5004          until now.  */
5005       dwo_unit->length = get_cu_length (&cu->header);
5006     }
5007
5008   /* Replace the CU's original abbrev table with the DWO's.
5009      Reminder: We can't read the abbrev table until we've read the header.  */
5010   if (abbrev_table_provided)
5011     {
5012       /* Don't free the provided abbrev table, the caller of
5013          init_cutu_and_read_dies owns it.  */
5014       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5015       /* Ensure the DWO abbrev table gets freed.  */
5016       make_cleanup (dwarf2_free_abbrev_table, cu);
5017     }
5018   else
5019     {
5020       dwarf2_free_abbrev_table (cu);
5021       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5022       /* Leave any existing abbrev table cleanup as is.  */
5023     }
5024
5025   /* Read in the die, but leave space to copy over the attributes
5026      from the stub.  This has the benefit of simplifying the rest of
5027      the code - all the work to maintain the illusion of a single
5028      DW_TAG_{compile,type}_unit DIE is done here.  */
5029   num_extra_attrs = ((stmt_list != NULL)
5030                      + (low_pc != NULL)
5031                      + (high_pc != NULL)
5032                      + (ranges != NULL)
5033                      + (comp_dir != NULL));
5034   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5035                               result_has_children, num_extra_attrs);
5036
5037   /* Copy over the attributes from the stub to the DIE we just read in.  */
5038   comp_unit_die = *result_comp_unit_die;
5039   i = comp_unit_die->num_attrs;
5040   if (stmt_list != NULL)
5041     comp_unit_die->attrs[i++] = *stmt_list;
5042   if (low_pc != NULL)
5043     comp_unit_die->attrs[i++] = *low_pc;
5044   if (high_pc != NULL)
5045     comp_unit_die->attrs[i++] = *high_pc;
5046   if (ranges != NULL)
5047     comp_unit_die->attrs[i++] = *ranges;
5048   if (comp_dir != NULL)
5049     comp_unit_die->attrs[i++] = *comp_dir;
5050   comp_unit_die->num_attrs += num_extra_attrs;
5051
5052   if (dwarf2_die_debug)
5053     {
5054       fprintf_unfiltered (gdb_stdlog,
5055                           "Read die from %s@0x%x of %s:\n",
5056                           get_section_name (section),
5057                           (unsigned) (begin_info_ptr - section->buffer),
5058                           bfd_get_filename (abfd));
5059       dump_die (comp_unit_die, dwarf2_die_debug);
5060     }
5061
5062   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5063      TUs by skipping the stub and going directly to the entry in the DWO file.
5064      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5065      to get it via circuitous means.  Blech.  */
5066   if (comp_dir != NULL)
5067     result_reader->comp_dir = DW_STRING (comp_dir);
5068
5069   /* Skip dummy compilation units.  */
5070   if (info_ptr >= begin_info_ptr + dwo_unit->length
5071       || peek_abbrev_code (abfd, info_ptr) == 0)
5072     return 0;
5073
5074   *result_info_ptr = info_ptr;
5075   return 1;
5076 }
5077
5078 /* Subroutine of init_cutu_and_read_dies to simplify it.
5079    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5080    Returns NULL if the specified DWO unit cannot be found.  */
5081
5082 static struct dwo_unit *
5083 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5084                  struct die_info *comp_unit_die)
5085 {
5086   struct dwarf2_cu *cu = this_cu->cu;
5087   struct attribute *attr;
5088   ULONGEST signature;
5089   struct dwo_unit *dwo_unit;
5090   const char *comp_dir, *dwo_name;
5091
5092   gdb_assert (cu != NULL);
5093
5094   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5095   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5096   gdb_assert (attr != NULL);
5097   dwo_name = DW_STRING (attr);
5098   comp_dir = NULL;
5099   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5100   if (attr)
5101     comp_dir = DW_STRING (attr);
5102
5103   if (this_cu->is_debug_types)
5104     {
5105       struct signatured_type *sig_type;
5106
5107       /* Since this_cu is the first member of struct signatured_type,
5108          we can go from a pointer to one to a pointer to the other.  */
5109       sig_type = (struct signatured_type *) this_cu;
5110       signature = sig_type->signature;
5111       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5112     }
5113   else
5114     {
5115       struct attribute *attr;
5116
5117       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5118       if (! attr)
5119         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5120                  " [in module %s]"),
5121                dwo_name, objfile_name (this_cu->objfile));
5122       signature = DW_UNSND (attr);
5123       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5124                                        signature);
5125     }
5126
5127   return dwo_unit;
5128 }
5129
5130 /* Subroutine of init_cutu_and_read_dies to simplify it.
5131    Read a TU directly from a DWO file, bypassing the stub.  */
5132
5133 static void
5134 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
5135                            die_reader_func_ftype *die_reader_func,
5136                            void *data)
5137 {
5138   struct dwarf2_cu *cu;
5139   struct signatured_type *sig_type;
5140   struct cleanup *cleanups, *free_cu_cleanup;
5141   struct die_reader_specs reader;
5142   const gdb_byte *info_ptr;
5143   struct die_info *comp_unit_die;
5144   int has_children;
5145
5146   /* Verify we can do the following downcast, and that we have the
5147      data we need.  */
5148   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5149   sig_type = (struct signatured_type *) this_cu;
5150   gdb_assert (sig_type->dwo_unit != NULL);
5151
5152   cleanups = make_cleanup (null_cleanup, NULL);
5153
5154   gdb_assert (this_cu->cu == NULL);
5155   cu = xmalloc (sizeof (*cu));
5156   init_one_comp_unit (cu, this_cu);
5157   /* If an error occurs while loading, release our storage.  */
5158   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5159
5160   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5161                               0 /* abbrev_table_provided */,
5162                               NULL /* stub_comp_unit_die */,
5163                               sig_type->dwo_unit->dwo_file->comp_dir,
5164                               &reader, &info_ptr,
5165                               &comp_unit_die, &has_children) == 0)
5166     {
5167       /* Dummy die.  */
5168       do_cleanups (cleanups);
5169       return;
5170     }
5171
5172   /* All the "real" work is done here.  */
5173   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5174
5175   /* This duplicates some code in init_cutu_and_read_dies,
5176      but the alternative is making the latter more complex.
5177      This function is only for the special case of using DWO files directly:
5178      no point in overly complicating the general case just to handle this.  */
5179   if (keep)
5180     {
5181       /* We've successfully allocated this compilation unit.  Let our
5182          caller clean it up when finished with it.  */
5183       discard_cleanups (free_cu_cleanup);
5184
5185       /* We can only discard free_cu_cleanup and all subsequent cleanups.
5186          So we have to manually free the abbrev table.  */
5187       dwarf2_free_abbrev_table (cu);
5188
5189       /* Link this CU into read_in_chain.  */
5190       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5191       dwarf2_per_objfile->read_in_chain = this_cu;
5192     }
5193   else
5194     do_cleanups (free_cu_cleanup);
5195
5196   do_cleanups (cleanups);
5197 }
5198
5199 /* Initialize a CU (or TU) and read its DIEs.
5200    If the CU defers to a DWO file, read the DWO file as well.
5201
5202    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5203    Otherwise the table specified in the comp unit header is read in and used.
5204    This is an optimization for when we already have the abbrev table.
5205
5206    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5207    Otherwise, a new CU is allocated with xmalloc.
5208
5209    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5210    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5211
5212    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5213    linker) then DIE_READER_FUNC will not get called.  */
5214
5215 static void
5216 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5217                          struct abbrev_table *abbrev_table,
5218                          int use_existing_cu, int keep,
5219                          die_reader_func_ftype *die_reader_func,
5220                          void *data)
5221 {
5222   struct objfile *objfile = dwarf2_per_objfile->objfile;
5223   struct dwarf2_section_info *section = this_cu->section;
5224   bfd *abfd = get_section_bfd_owner (section);
5225   struct dwarf2_cu *cu;
5226   const gdb_byte *begin_info_ptr, *info_ptr;
5227   struct die_reader_specs reader;
5228   struct die_info *comp_unit_die;
5229   int has_children;
5230   struct attribute *attr;
5231   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5232   struct signatured_type *sig_type = NULL;
5233   struct dwarf2_section_info *abbrev_section;
5234   /* Non-zero if CU currently points to a DWO file and we need to
5235      reread it.  When this happens we need to reread the skeleton die
5236      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5237   int rereading_dwo_cu = 0;
5238
5239   if (dwarf2_die_debug)
5240     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5241                         this_cu->is_debug_types ? "type" : "comp",
5242                         this_cu->offset.sect_off);
5243
5244   if (use_existing_cu)
5245     gdb_assert (keep);
5246
5247   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5248      file (instead of going through the stub), short-circuit all of this.  */
5249   if (this_cu->reading_dwo_directly)
5250     {
5251       /* Narrow down the scope of possibilities to have to understand.  */
5252       gdb_assert (this_cu->is_debug_types);
5253       gdb_assert (abbrev_table == NULL);
5254       gdb_assert (!use_existing_cu);
5255       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5256       return;
5257     }
5258
5259   cleanups = make_cleanup (null_cleanup, NULL);
5260
5261   /* This is cheap if the section is already read in.  */
5262   dwarf2_read_section (objfile, section);
5263
5264   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5265
5266   abbrev_section = get_abbrev_section_for_cu (this_cu);
5267
5268   if (use_existing_cu && this_cu->cu != NULL)
5269     {
5270       cu = this_cu->cu;
5271
5272       /* If this CU is from a DWO file we need to start over, we need to
5273          refetch the attributes from the skeleton CU.
5274          This could be optimized by retrieving those attributes from when we
5275          were here the first time: the previous comp_unit_die was stored in
5276          comp_unit_obstack.  But there's no data yet that we need this
5277          optimization.  */
5278       if (cu->dwo_unit != NULL)
5279         rereading_dwo_cu = 1;
5280     }
5281   else
5282     {
5283       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5284       gdb_assert (this_cu->cu == NULL);
5285
5286       cu = xmalloc (sizeof (*cu));
5287       init_one_comp_unit (cu, this_cu);
5288
5289       /* If an error occurs while loading, release our storage.  */
5290       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5291     }
5292
5293   /* Get the header.  */
5294   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5295     {
5296       /* We already have the header, there's no need to read it in again.  */
5297       info_ptr += cu->header.first_die_offset.cu_off;
5298     }
5299   else
5300     {
5301       if (this_cu->is_debug_types)
5302         {
5303           ULONGEST signature;
5304           cu_offset type_offset_in_tu;
5305
5306           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5307                                                     abbrev_section, info_ptr,
5308                                                     &signature,
5309                                                     &type_offset_in_tu);
5310
5311           /* Since per_cu is the first member of struct signatured_type,
5312              we can go from a pointer to one to a pointer to the other.  */
5313           sig_type = (struct signatured_type *) this_cu;
5314           gdb_assert (sig_type->signature == signature);
5315           gdb_assert (sig_type->type_offset_in_tu.cu_off
5316                       == type_offset_in_tu.cu_off);
5317           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5318
5319           /* LENGTH has not been set yet for type units if we're
5320              using .gdb_index.  */
5321           this_cu->length = get_cu_length (&cu->header);
5322
5323           /* Establish the type offset that can be used to lookup the type.  */
5324           sig_type->type_offset_in_section.sect_off =
5325             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5326         }
5327       else
5328         {
5329           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5330                                                     abbrev_section,
5331                                                     info_ptr, 0);
5332
5333           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5334           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5335         }
5336     }
5337
5338   /* Skip dummy compilation units.  */
5339   if (info_ptr >= begin_info_ptr + this_cu->length
5340       || peek_abbrev_code (abfd, info_ptr) == 0)
5341     {
5342       do_cleanups (cleanups);
5343       return;
5344     }
5345
5346   /* If we don't have them yet, read the abbrevs for this compilation unit.
5347      And if we need to read them now, make sure they're freed when we're
5348      done.  Note that it's important that if the CU had an abbrev table
5349      on entry we don't free it when we're done: Somewhere up the call stack
5350      it may be in use.  */
5351   if (abbrev_table != NULL)
5352     {
5353       gdb_assert (cu->abbrev_table == NULL);
5354       gdb_assert (cu->header.abbrev_offset.sect_off
5355                   == abbrev_table->offset.sect_off);
5356       cu->abbrev_table = abbrev_table;
5357     }
5358   else if (cu->abbrev_table == NULL)
5359     {
5360       dwarf2_read_abbrevs (cu, abbrev_section);
5361       make_cleanup (dwarf2_free_abbrev_table, cu);
5362     }
5363   else if (rereading_dwo_cu)
5364     {
5365       dwarf2_free_abbrev_table (cu);
5366       dwarf2_read_abbrevs (cu, abbrev_section);
5367     }
5368
5369   /* Read the top level CU/TU die.  */
5370   init_cu_die_reader (&reader, cu, section, NULL);
5371   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5372
5373   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5374      from the DWO file.
5375      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5376      DWO CU, that this test will fail (the attribute will not be present).  */
5377   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5378   if (attr)
5379     {
5380       struct dwo_unit *dwo_unit;
5381       struct die_info *dwo_comp_unit_die;
5382
5383       if (has_children)
5384         {
5385           complaint (&symfile_complaints,
5386                      _("compilation unit with DW_AT_GNU_dwo_name"
5387                        " has children (offset 0x%x) [in module %s]"),
5388                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5389         }
5390       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5391       if (dwo_unit != NULL)
5392         {
5393           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5394                                       abbrev_table != NULL,
5395                                       comp_unit_die, NULL,
5396                                       &reader, &info_ptr,
5397                                       &dwo_comp_unit_die, &has_children) == 0)
5398             {
5399               /* Dummy die.  */
5400               do_cleanups (cleanups);
5401               return;
5402             }
5403           comp_unit_die = dwo_comp_unit_die;
5404         }
5405       else
5406         {
5407           /* Yikes, we couldn't find the rest of the DIE, we only have
5408              the stub.  A complaint has already been logged.  There's
5409              not much more we can do except pass on the stub DIE to
5410              die_reader_func.  We don't want to throw an error on bad
5411              debug info.  */
5412         }
5413     }
5414
5415   /* All of the above is setup for this call.  Yikes.  */
5416   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5417
5418   /* Done, clean up.  */
5419   if (free_cu_cleanup != NULL)
5420     {
5421       if (keep)
5422         {
5423           /* We've successfully allocated this compilation unit.  Let our
5424              caller clean it up when finished with it.  */
5425           discard_cleanups (free_cu_cleanup);
5426
5427           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5428              So we have to manually free the abbrev table.  */
5429           dwarf2_free_abbrev_table (cu);
5430
5431           /* Link this CU into read_in_chain.  */
5432           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5433           dwarf2_per_objfile->read_in_chain = this_cu;
5434         }
5435       else
5436         do_cleanups (free_cu_cleanup);
5437     }
5438
5439   do_cleanups (cleanups);
5440 }
5441
5442 /* Read CU/TU THIS_CU in section SECTION,
5443    but do not follow DW_AT_GNU_dwo_name if present.
5444    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5445    to have already done the lookup to find the DWO/DWP file).
5446
5447    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5448    THIS_CU->is_debug_types, but nothing else.
5449
5450    We fill in THIS_CU->length.
5451
5452    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5453    linker) then DIE_READER_FUNC will not get called.
5454
5455    THIS_CU->cu is always freed when done.
5456    This is done in order to not leave THIS_CU->cu in a state where we have
5457    to care whether it refers to the "main" CU or the DWO CU.  */
5458
5459 static void
5460 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5461                                    struct dwarf2_section_info *abbrev_section,
5462                                    struct dwo_file *dwo_file,
5463                                    die_reader_func_ftype *die_reader_func,
5464                                    void *data)
5465 {
5466   struct objfile *objfile = dwarf2_per_objfile->objfile;
5467   struct dwarf2_section_info *section = this_cu->section;
5468   bfd *abfd = get_section_bfd_owner (section);
5469   struct dwarf2_cu cu;
5470   const gdb_byte *begin_info_ptr, *info_ptr;
5471   struct die_reader_specs reader;
5472   struct cleanup *cleanups;
5473   struct die_info *comp_unit_die;
5474   int has_children;
5475
5476   if (dwarf2_die_debug)
5477     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5478                         this_cu->is_debug_types ? "type" : "comp",
5479                         this_cu->offset.sect_off);
5480
5481   gdb_assert (this_cu->cu == NULL);
5482
5483   /* This is cheap if the section is already read in.  */
5484   dwarf2_read_section (objfile, section);
5485
5486   init_one_comp_unit (&cu, this_cu);
5487
5488   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5489
5490   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5491   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5492                                             abbrev_section, info_ptr,
5493                                             this_cu->is_debug_types);
5494
5495   this_cu->length = get_cu_length (&cu.header);
5496
5497   /* Skip dummy compilation units.  */
5498   if (info_ptr >= begin_info_ptr + this_cu->length
5499       || peek_abbrev_code (abfd, info_ptr) == 0)
5500     {
5501       do_cleanups (cleanups);
5502       return;
5503     }
5504
5505   dwarf2_read_abbrevs (&cu, abbrev_section);
5506   make_cleanup (dwarf2_free_abbrev_table, &cu);
5507
5508   init_cu_die_reader (&reader, &cu, section, dwo_file);
5509   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5510
5511   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5512
5513   do_cleanups (cleanups);
5514 }
5515
5516 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5517    does not lookup the specified DWO file.
5518    This cannot be used to read DWO files.
5519
5520    THIS_CU->cu is always freed when done.
5521    This is done in order to not leave THIS_CU->cu in a state where we have
5522    to care whether it refers to the "main" CU or the DWO CU.
5523    We can revisit this if the data shows there's a performance issue.  */
5524
5525 static void
5526 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5527                                 die_reader_func_ftype *die_reader_func,
5528                                 void *data)
5529 {
5530   init_cutu_and_read_dies_no_follow (this_cu,
5531                                      get_abbrev_section_for_cu (this_cu),
5532                                      NULL,
5533                                      die_reader_func, data);
5534 }
5535 \f
5536 /* Type Unit Groups.
5537
5538    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5539    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5540    so that all types coming from the same compilation (.o file) are grouped
5541    together.  A future step could be to put the types in the same symtab as
5542    the CU the types ultimately came from.  */
5543
5544 static hashval_t
5545 hash_type_unit_group (const void *item)
5546 {
5547   const struct type_unit_group *tu_group = item;
5548
5549   return hash_stmt_list_entry (&tu_group->hash);
5550 }
5551
5552 static int
5553 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5554 {
5555   const struct type_unit_group *lhs = item_lhs;
5556   const struct type_unit_group *rhs = item_rhs;
5557
5558   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5559 }
5560
5561 /* Allocate a hash table for type unit groups.  */
5562
5563 static htab_t
5564 allocate_type_unit_groups_table (void)
5565 {
5566   return htab_create_alloc_ex (3,
5567                                hash_type_unit_group,
5568                                eq_type_unit_group,
5569                                NULL,
5570                                &dwarf2_per_objfile->objfile->objfile_obstack,
5571                                hashtab_obstack_allocate,
5572                                dummy_obstack_deallocate);
5573 }
5574
5575 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5576    partial symtabs.  We combine several TUs per psymtab to not let the size
5577    of any one psymtab grow too big.  */
5578 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5579 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5580
5581 /* Helper routine for get_type_unit_group.
5582    Create the type_unit_group object used to hold one or more TUs.  */
5583
5584 static struct type_unit_group *
5585 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5586 {
5587   struct objfile *objfile = dwarf2_per_objfile->objfile;
5588   struct dwarf2_per_cu_data *per_cu;
5589   struct type_unit_group *tu_group;
5590
5591   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5592                              struct type_unit_group);
5593   per_cu = &tu_group->per_cu;
5594   per_cu->objfile = objfile;
5595
5596   if (dwarf2_per_objfile->using_index)
5597     {
5598       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5599                                         struct dwarf2_per_cu_quick_data);
5600     }
5601   else
5602     {
5603       unsigned int line_offset = line_offset_struct.sect_off;
5604       struct partial_symtab *pst;
5605       char *name;
5606
5607       /* Give the symtab a useful name for debug purposes.  */
5608       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5609         name = xstrprintf ("<type_units_%d>",
5610                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5611       else
5612         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5613
5614       pst = create_partial_symtab (per_cu, name);
5615       pst->anonymous = 1;
5616
5617       xfree (name);
5618     }
5619
5620   tu_group->hash.dwo_unit = cu->dwo_unit;
5621   tu_group->hash.line_offset = line_offset_struct;
5622
5623   return tu_group;
5624 }
5625
5626 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5627    STMT_LIST is a DW_AT_stmt_list attribute.  */
5628
5629 static struct type_unit_group *
5630 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5631 {
5632   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5633   struct type_unit_group *tu_group;
5634   void **slot;
5635   unsigned int line_offset;
5636   struct type_unit_group type_unit_group_for_lookup;
5637
5638   if (dwarf2_per_objfile->type_unit_groups == NULL)
5639     {
5640       dwarf2_per_objfile->type_unit_groups =
5641         allocate_type_unit_groups_table ();
5642     }
5643
5644   /* Do we need to create a new group, or can we use an existing one?  */
5645
5646   if (stmt_list)
5647     {
5648       line_offset = DW_UNSND (stmt_list);
5649       ++tu_stats->nr_symtab_sharers;
5650     }
5651   else
5652     {
5653       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5654          We can do various things here like create one group per TU or
5655          spread them over multiple groups to split up the expansion work.
5656          To avoid worst case scenarios (too many groups or too large groups)
5657          we, umm, group them in bunches.  */
5658       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5659                      | (tu_stats->nr_stmt_less_type_units
5660                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5661       ++tu_stats->nr_stmt_less_type_units;
5662     }
5663
5664   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5665   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5666   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5667                          &type_unit_group_for_lookup, INSERT);
5668   if (*slot != NULL)
5669     {
5670       tu_group = *slot;
5671       gdb_assert (tu_group != NULL);
5672     }
5673   else
5674     {
5675       sect_offset line_offset_struct;
5676
5677       line_offset_struct.sect_off = line_offset;
5678       tu_group = create_type_unit_group (cu, line_offset_struct);
5679       *slot = tu_group;
5680       ++tu_stats->nr_symtabs;
5681     }
5682
5683   return tu_group;
5684 }
5685
5686 /* Struct used to sort TUs by their abbreviation table offset.  */
5687
5688 struct tu_abbrev_offset
5689 {
5690   struct signatured_type *sig_type;
5691   sect_offset abbrev_offset;
5692 };
5693
5694 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5695
5696 static int
5697 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5698 {
5699   const struct tu_abbrev_offset * const *a = ap;
5700   const struct tu_abbrev_offset * const *b = bp;
5701   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5702   unsigned int boff = (*b)->abbrev_offset.sect_off;
5703
5704   return (aoff > boff) - (aoff < boff);
5705 }
5706
5707 /* A helper function to add a type_unit_group to a table.  */
5708
5709 static int
5710 add_type_unit_group_to_table (void **slot, void *datum)
5711 {
5712   struct type_unit_group *tu_group = *slot;
5713   struct type_unit_group ***datap = datum;
5714
5715   **datap = tu_group;
5716   ++*datap;
5717
5718   return 1;
5719 }
5720
5721 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5722    each one passing FUNC,DATA.
5723
5724    The efficiency is because we sort TUs by the abbrev table they use and
5725    only read each abbrev table once.  In one program there are 200K TUs
5726    sharing 8K abbrev tables.
5727
5728    The main purpose of this function is to support building the
5729    dwarf2_per_objfile->type_unit_groups table.
5730    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5731    can collapse the search space by grouping them by stmt_list.
5732    The savings can be significant, in the same program from above the 200K TUs
5733    share 8K stmt_list tables.
5734
5735    FUNC is expected to call get_type_unit_group, which will create the
5736    struct type_unit_group if necessary and add it to
5737    dwarf2_per_objfile->type_unit_groups.  */
5738
5739 static void
5740 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5741 {
5742   struct objfile *objfile = dwarf2_per_objfile->objfile;
5743   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5744   struct cleanup *cleanups;
5745   struct abbrev_table *abbrev_table;
5746   sect_offset abbrev_offset;
5747   struct tu_abbrev_offset *sorted_by_abbrev;
5748   struct type_unit_group **iter;
5749   int i;
5750
5751   /* It's up to the caller to not call us multiple times.  */
5752   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5753
5754   if (dwarf2_per_objfile->n_type_units == 0)
5755     return;
5756
5757   /* TUs typically share abbrev tables, and there can be way more TUs than
5758      abbrev tables.  Sort by abbrev table to reduce the number of times we
5759      read each abbrev table in.
5760      Alternatives are to punt or to maintain a cache of abbrev tables.
5761      This is simpler and efficient enough for now.
5762
5763      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5764      symtab to use).  Typically TUs with the same abbrev offset have the same
5765      stmt_list value too so in practice this should work well.
5766
5767      The basic algorithm here is:
5768
5769       sort TUs by abbrev table
5770       for each TU with same abbrev table:
5771         read abbrev table if first user
5772         read TU top level DIE
5773           [IWBN if DWO skeletons had DW_AT_stmt_list]
5774         call FUNC  */
5775
5776   if (dwarf2_read_debug)
5777     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5778
5779   /* Sort in a separate table to maintain the order of all_type_units
5780      for .gdb_index: TU indices directly index all_type_units.  */
5781   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5782                               dwarf2_per_objfile->n_type_units);
5783   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5784     {
5785       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5786
5787       sorted_by_abbrev[i].sig_type = sig_type;
5788       sorted_by_abbrev[i].abbrev_offset =
5789         read_abbrev_offset (sig_type->per_cu.section,
5790                             sig_type->per_cu.offset);
5791     }
5792   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5793   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5794          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5795
5796   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5797      called any number of times, so we don't reset tu_stats here.  */
5798
5799   abbrev_offset.sect_off = ~(unsigned) 0;
5800   abbrev_table = NULL;
5801   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5802
5803   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5804     {
5805       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5806
5807       /* Switch to the next abbrev table if necessary.  */
5808       if (abbrev_table == NULL
5809           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5810         {
5811           if (abbrev_table != NULL)
5812             {
5813               abbrev_table_free (abbrev_table);
5814               /* Reset to NULL in case abbrev_table_read_table throws
5815                  an error: abbrev_table_free_cleanup will get called.  */
5816               abbrev_table = NULL;
5817             }
5818           abbrev_offset = tu->abbrev_offset;
5819           abbrev_table =
5820             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5821                                      abbrev_offset);
5822           ++tu_stats->nr_uniq_abbrev_tables;
5823         }
5824
5825       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5826                                func, data);
5827     }
5828
5829   /* type_unit_groups can be NULL if there is an error in the debug info.
5830      Just create an empty table so the rest of gdb doesn't have to watch
5831      for this error case.  */
5832   if (dwarf2_per_objfile->type_unit_groups == NULL)
5833     {
5834       dwarf2_per_objfile->type_unit_groups =
5835         allocate_type_unit_groups_table ();
5836       dwarf2_per_objfile->n_type_unit_groups = 0;
5837     }
5838
5839   /* Create a vector of pointers to primary type units to make it easy to
5840      iterate over them and CUs.  See dw2_get_primary_cu.  */
5841   dwarf2_per_objfile->n_type_unit_groups =
5842     htab_elements (dwarf2_per_objfile->type_unit_groups);
5843   dwarf2_per_objfile->all_type_unit_groups =
5844     obstack_alloc (&objfile->objfile_obstack,
5845                    dwarf2_per_objfile->n_type_unit_groups
5846                    * sizeof (struct type_unit_group *));
5847   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5848   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5849                           add_type_unit_group_to_table, &iter);
5850   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5851               == dwarf2_per_objfile->n_type_unit_groups);
5852
5853   do_cleanups (cleanups);
5854
5855   if (dwarf2_read_debug)
5856     {
5857       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5858       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5859                           dwarf2_per_objfile->n_type_units);
5860       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5861                           tu_stats->nr_uniq_abbrev_tables);
5862       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5863                           tu_stats->nr_symtabs);
5864       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5865                           tu_stats->nr_symtab_sharers);
5866       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5867                           tu_stats->nr_stmt_less_type_units);
5868     }
5869 }
5870 \f
5871 /* Partial symbol tables.  */
5872
5873 /* Create a psymtab named NAME and assign it to PER_CU.
5874
5875    The caller must fill in the following details:
5876    dirname, textlow, texthigh.  */
5877
5878 static struct partial_symtab *
5879 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5880 {
5881   struct objfile *objfile = per_cu->objfile;
5882   struct partial_symtab *pst;
5883
5884   pst = start_psymtab_common (objfile, objfile->section_offsets,
5885                               name, 0,
5886                               objfile->global_psymbols.next,
5887                               objfile->static_psymbols.next);
5888
5889   pst->psymtabs_addrmap_supported = 1;
5890
5891   /* This is the glue that links PST into GDB's symbol API.  */
5892   pst->read_symtab_private = per_cu;
5893   pst->read_symtab = dwarf2_read_symtab;
5894   per_cu->v.psymtab = pst;
5895
5896   return pst;
5897 }
5898
5899 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5900    type.  */
5901
5902 struct process_psymtab_comp_unit_data
5903 {
5904   /* True if we are reading a DW_TAG_partial_unit.  */
5905
5906   int want_partial_unit;
5907
5908   /* The "pretend" language that is used if the CU doesn't declare a
5909      language.  */
5910
5911   enum language pretend_language;
5912 };
5913
5914 /* die_reader_func for process_psymtab_comp_unit.  */
5915
5916 static void
5917 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5918                                   const gdb_byte *info_ptr,
5919                                   struct die_info *comp_unit_die,
5920                                   int has_children,
5921                                   void *data)
5922 {
5923   struct dwarf2_cu *cu = reader->cu;
5924   struct objfile *objfile = cu->objfile;
5925   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5926   struct attribute *attr;
5927   CORE_ADDR baseaddr;
5928   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5929   struct partial_symtab *pst;
5930   int has_pc_info;
5931   const char *filename;
5932   struct process_psymtab_comp_unit_data *info = data;
5933
5934   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5935     return;
5936
5937   gdb_assert (! per_cu->is_debug_types);
5938
5939   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5940
5941   cu->list_in_scope = &file_symbols;
5942
5943   /* Allocate a new partial symbol table structure.  */
5944   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5945   if (attr == NULL || !DW_STRING (attr))
5946     filename = "";
5947   else
5948     filename = DW_STRING (attr);
5949
5950   pst = create_partial_symtab (per_cu, filename);
5951
5952   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5953   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5954   if (attr != NULL)
5955     pst->dirname = DW_STRING (attr);
5956
5957   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5958
5959   dwarf2_find_base_address (comp_unit_die, cu);
5960
5961   /* Possibly set the default values of LOWPC and HIGHPC from
5962      `DW_AT_ranges'.  */
5963   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5964                                       &best_highpc, cu, pst);
5965   if (has_pc_info == 1 && best_lowpc < best_highpc)
5966     /* Store the contiguous range if it is not empty; it can be empty for
5967        CUs with no code.  */
5968     addrmap_set_empty (objfile->psymtabs_addrmap,
5969                        best_lowpc + baseaddr,
5970                        best_highpc + baseaddr - 1, pst);
5971
5972   /* Check if comp unit has_children.
5973      If so, read the rest of the partial symbols from this comp unit.
5974      If not, there's no more debug_info for this comp unit.  */
5975   if (has_children)
5976     {
5977       struct partial_die_info *first_die;
5978       CORE_ADDR lowpc, highpc;
5979
5980       lowpc = ((CORE_ADDR) -1);
5981       highpc = ((CORE_ADDR) 0);
5982
5983       first_die = load_partial_dies (reader, info_ptr, 1);
5984
5985       scan_partial_symbols (first_die, &lowpc, &highpc,
5986                             ! has_pc_info, cu);
5987
5988       /* If we didn't find a lowpc, set it to highpc to avoid
5989          complaints from `maint check'.  */
5990       if (lowpc == ((CORE_ADDR) -1))
5991         lowpc = highpc;
5992
5993       /* If the compilation unit didn't have an explicit address range,
5994          then use the information extracted from its child dies.  */
5995       if (! has_pc_info)
5996         {
5997           best_lowpc = lowpc;
5998           best_highpc = highpc;
5999         }
6000     }
6001   pst->textlow = best_lowpc + baseaddr;
6002   pst->texthigh = best_highpc + baseaddr;
6003
6004   pst->n_global_syms = objfile->global_psymbols.next -
6005     (objfile->global_psymbols.list + pst->globals_offset);
6006   pst->n_static_syms = objfile->static_psymbols.next -
6007     (objfile->static_psymbols.list + pst->statics_offset);
6008   sort_pst_symbols (objfile, pst);
6009
6010   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6011     {
6012       int i;
6013       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6014       struct dwarf2_per_cu_data *iter;
6015
6016       /* Fill in 'dependencies' here; we fill in 'users' in a
6017          post-pass.  */
6018       pst->number_of_dependencies = len;
6019       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6020                                          len * sizeof (struct symtab *));
6021       for (i = 0;
6022            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6023                         i, iter);
6024            ++i)
6025         pst->dependencies[i] = iter->v.psymtab;
6026
6027       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6028     }
6029
6030   /* Get the list of files included in the current compilation unit,
6031      and build a psymtab for each of them.  */
6032   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6033
6034   if (dwarf2_read_debug)
6035     {
6036       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6037
6038       fprintf_unfiltered (gdb_stdlog,
6039                           "Psymtab for %s unit @0x%x: %s - %s"
6040                           ", %d global, %d static syms\n",
6041                           per_cu->is_debug_types ? "type" : "comp",
6042                           per_cu->offset.sect_off,
6043                           paddress (gdbarch, pst->textlow),
6044                           paddress (gdbarch, pst->texthigh),
6045                           pst->n_global_syms, pst->n_static_syms);
6046     }
6047 }
6048
6049 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6050    Process compilation unit THIS_CU for a psymtab.  */
6051
6052 static void
6053 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6054                            int want_partial_unit,
6055                            enum language pretend_language)
6056 {
6057   struct process_psymtab_comp_unit_data info;
6058
6059   /* If this compilation unit was already read in, free the
6060      cached copy in order to read it in again.  This is
6061      necessary because we skipped some symbols when we first
6062      read in the compilation unit (see load_partial_dies).
6063      This problem could be avoided, but the benefit is unclear.  */
6064   if (this_cu->cu != NULL)
6065     free_one_cached_comp_unit (this_cu);
6066
6067   gdb_assert (! this_cu->is_debug_types);
6068   info.want_partial_unit = want_partial_unit;
6069   info.pretend_language = pretend_language;
6070   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6071                            process_psymtab_comp_unit_reader,
6072                            &info);
6073
6074   /* Age out any secondary CUs.  */
6075   age_cached_comp_units ();
6076 }
6077
6078 /* Reader function for build_type_psymtabs.  */
6079
6080 static void
6081 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6082                             const gdb_byte *info_ptr,
6083                             struct die_info *type_unit_die,
6084                             int has_children,
6085                             void *data)
6086 {
6087   struct objfile *objfile = dwarf2_per_objfile->objfile;
6088   struct dwarf2_cu *cu = reader->cu;
6089   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6090   struct signatured_type *sig_type;
6091   struct type_unit_group *tu_group;
6092   struct attribute *attr;
6093   struct partial_die_info *first_die;
6094   CORE_ADDR lowpc, highpc;
6095   struct partial_symtab *pst;
6096
6097   gdb_assert (data == NULL);
6098   gdb_assert (per_cu->is_debug_types);
6099   sig_type = (struct signatured_type *) per_cu;
6100
6101   if (! has_children)
6102     return;
6103
6104   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6105   tu_group = get_type_unit_group (cu, attr);
6106
6107   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6108
6109   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6110   cu->list_in_scope = &file_symbols;
6111   pst = create_partial_symtab (per_cu, "");
6112   pst->anonymous = 1;
6113
6114   first_die = load_partial_dies (reader, info_ptr, 1);
6115
6116   lowpc = (CORE_ADDR) -1;
6117   highpc = (CORE_ADDR) 0;
6118   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6119
6120   pst->n_global_syms = objfile->global_psymbols.next -
6121     (objfile->global_psymbols.list + pst->globals_offset);
6122   pst->n_static_syms = objfile->static_psymbols.next -
6123     (objfile->static_psymbols.list + pst->statics_offset);
6124   sort_pst_symbols (objfile, pst);
6125 }
6126
6127 /* Traversal function for build_type_psymtabs.  */
6128
6129 static int
6130 build_type_psymtab_dependencies (void **slot, void *info)
6131 {
6132   struct objfile *objfile = dwarf2_per_objfile->objfile;
6133   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6134   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6135   struct partial_symtab *pst = per_cu->v.psymtab;
6136   int len = VEC_length (sig_type_ptr, tu_group->tus);
6137   struct signatured_type *iter;
6138   int i;
6139
6140   gdb_assert (len > 0);
6141   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6142
6143   pst->number_of_dependencies = len;
6144   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6145                                      len * sizeof (struct psymtab *));
6146   for (i = 0;
6147        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6148        ++i)
6149     {
6150       gdb_assert (iter->per_cu.is_debug_types);
6151       pst->dependencies[i] = iter->per_cu.v.psymtab;
6152       iter->type_unit_group = tu_group;
6153     }
6154
6155   VEC_free (sig_type_ptr, tu_group->tus);
6156
6157   return 1;
6158 }
6159
6160 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6161    Build partial symbol tables for the .debug_types comp-units.  */
6162
6163 static void
6164 build_type_psymtabs (struct objfile *objfile)
6165 {
6166   if (! create_all_type_units (objfile))
6167     return;
6168
6169   build_type_unit_groups (build_type_psymtabs_reader, NULL);
6170
6171   /* Now that all TUs have been processed we can fill in the dependencies.  */
6172   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6173                           build_type_psymtab_dependencies, NULL);
6174 }
6175
6176 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6177
6178 static void
6179 psymtabs_addrmap_cleanup (void *o)
6180 {
6181   struct objfile *objfile = o;
6182
6183   objfile->psymtabs_addrmap = NULL;
6184 }
6185
6186 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6187
6188 static void
6189 set_partial_user (struct objfile *objfile)
6190 {
6191   int i;
6192
6193   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6194     {
6195       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6196       struct partial_symtab *pst = per_cu->v.psymtab;
6197       int j;
6198
6199       if (pst == NULL)
6200         continue;
6201
6202       for (j = 0; j < pst->number_of_dependencies; ++j)
6203         {
6204           /* Set the 'user' field only if it is not already set.  */
6205           if (pst->dependencies[j]->user == NULL)
6206             pst->dependencies[j]->user = pst;
6207         }
6208     }
6209 }
6210
6211 /* Build the partial symbol table by doing a quick pass through the
6212    .debug_info and .debug_abbrev sections.  */
6213
6214 static void
6215 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6216 {
6217   struct cleanup *back_to, *addrmap_cleanup;
6218   struct obstack temp_obstack;
6219   int i;
6220
6221   if (dwarf2_read_debug)
6222     {
6223       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6224                           objfile_name (objfile));
6225     }
6226
6227   dwarf2_per_objfile->reading_partial_symbols = 1;
6228
6229   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6230
6231   /* Any cached compilation units will be linked by the per-objfile
6232      read_in_chain.  Make sure to free them when we're done.  */
6233   back_to = make_cleanup (free_cached_comp_units, NULL);
6234
6235   build_type_psymtabs (objfile);
6236
6237   create_all_comp_units (objfile);
6238
6239   /* Create a temporary address map on a temporary obstack.  We later
6240      copy this to the final obstack.  */
6241   obstack_init (&temp_obstack);
6242   make_cleanup_obstack_free (&temp_obstack);
6243   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6244   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6245
6246   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6247     {
6248       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6249
6250       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6251     }
6252
6253   set_partial_user (objfile);
6254
6255   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6256                                                     &objfile->objfile_obstack);
6257   discard_cleanups (addrmap_cleanup);
6258
6259   do_cleanups (back_to);
6260
6261   if (dwarf2_read_debug)
6262     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6263                         objfile_name (objfile));
6264 }
6265
6266 /* die_reader_func for load_partial_comp_unit.  */
6267
6268 static void
6269 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6270                                const gdb_byte *info_ptr,
6271                                struct die_info *comp_unit_die,
6272                                int has_children,
6273                                void *data)
6274 {
6275   struct dwarf2_cu *cu = reader->cu;
6276
6277   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6278
6279   /* Check if comp unit has_children.
6280      If so, read the rest of the partial symbols from this comp unit.
6281      If not, there's no more debug_info for this comp unit.  */
6282   if (has_children)
6283     load_partial_dies (reader, info_ptr, 0);
6284 }
6285
6286 /* Load the partial DIEs for a secondary CU into memory.
6287    This is also used when rereading a primary CU with load_all_dies.  */
6288
6289 static void
6290 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6291 {
6292   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6293                            load_partial_comp_unit_reader, NULL);
6294 }
6295
6296 static void
6297 read_comp_units_from_section (struct objfile *objfile,
6298                               struct dwarf2_section_info *section,
6299                               unsigned int is_dwz,
6300                               int *n_allocated,
6301                               int *n_comp_units,
6302                               struct dwarf2_per_cu_data ***all_comp_units)
6303 {
6304   const gdb_byte *info_ptr;
6305   bfd *abfd = get_section_bfd_owner (section);
6306
6307   if (dwarf2_read_debug)
6308     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6309                         get_section_name (section),
6310                         get_section_file_name (section));
6311
6312   dwarf2_read_section (objfile, section);
6313
6314   info_ptr = section->buffer;
6315
6316   while (info_ptr < section->buffer + section->size)
6317     {
6318       unsigned int length, initial_length_size;
6319       struct dwarf2_per_cu_data *this_cu;
6320       sect_offset offset;
6321
6322       offset.sect_off = info_ptr - section->buffer;
6323
6324       /* Read just enough information to find out where the next
6325          compilation unit is.  */
6326       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6327
6328       /* Save the compilation unit for later lookup.  */
6329       this_cu = obstack_alloc (&objfile->objfile_obstack,
6330                                sizeof (struct dwarf2_per_cu_data));
6331       memset (this_cu, 0, sizeof (*this_cu));
6332       this_cu->offset = offset;
6333       this_cu->length = length + initial_length_size;
6334       this_cu->is_dwz = is_dwz;
6335       this_cu->objfile = objfile;
6336       this_cu->section = section;
6337
6338       if (*n_comp_units == *n_allocated)
6339         {
6340           *n_allocated *= 2;
6341           *all_comp_units = xrealloc (*all_comp_units,
6342                                       *n_allocated
6343                                       * sizeof (struct dwarf2_per_cu_data *));
6344         }
6345       (*all_comp_units)[*n_comp_units] = this_cu;
6346       ++*n_comp_units;
6347
6348       info_ptr = info_ptr + this_cu->length;
6349     }
6350 }
6351
6352 /* Create a list of all compilation units in OBJFILE.
6353    This is only done for -readnow and building partial symtabs.  */
6354
6355 static void
6356 create_all_comp_units (struct objfile *objfile)
6357 {
6358   int n_allocated;
6359   int n_comp_units;
6360   struct dwarf2_per_cu_data **all_comp_units;
6361   struct dwz_file *dwz;
6362
6363   n_comp_units = 0;
6364   n_allocated = 10;
6365   all_comp_units = xmalloc (n_allocated
6366                             * sizeof (struct dwarf2_per_cu_data *));
6367
6368   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6369                                 &n_allocated, &n_comp_units, &all_comp_units);
6370
6371   dwz = dwarf2_get_dwz_file ();
6372   if (dwz != NULL)
6373     read_comp_units_from_section (objfile, &dwz->info, 1,
6374                                   &n_allocated, &n_comp_units,
6375                                   &all_comp_units);
6376
6377   dwarf2_per_objfile->all_comp_units
6378     = obstack_alloc (&objfile->objfile_obstack,
6379                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6380   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6381           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6382   xfree (all_comp_units);
6383   dwarf2_per_objfile->n_comp_units = n_comp_units;
6384 }
6385
6386 /* Process all loaded DIEs for compilation unit CU, starting at
6387    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6388    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6389    DW_AT_ranges).  If NEED_PC is set, then this function will set
6390    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6391    and record the covered ranges in the addrmap.  */
6392
6393 static void
6394 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6395                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6396 {
6397   struct partial_die_info *pdi;
6398
6399   /* Now, march along the PDI's, descending into ones which have
6400      interesting children but skipping the children of the other ones,
6401      until we reach the end of the compilation unit.  */
6402
6403   pdi = first_die;
6404
6405   while (pdi != NULL)
6406     {
6407       fixup_partial_die (pdi, cu);
6408
6409       /* Anonymous namespaces or modules have no name but have interesting
6410          children, so we need to look at them.  Ditto for anonymous
6411          enums.  */
6412
6413       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6414           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6415           || pdi->tag == DW_TAG_imported_unit)
6416         {
6417           switch (pdi->tag)
6418             {
6419             case DW_TAG_subprogram:
6420               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6421               break;
6422             case DW_TAG_constant:
6423             case DW_TAG_variable:
6424             case DW_TAG_typedef:
6425             case DW_TAG_union_type:
6426               if (!pdi->is_declaration)
6427                 {
6428                   add_partial_symbol (pdi, cu);
6429                 }
6430               break;
6431             case DW_TAG_class_type:
6432             case DW_TAG_interface_type:
6433             case DW_TAG_structure_type:
6434               if (!pdi->is_declaration)
6435                 {
6436                   add_partial_symbol (pdi, cu);
6437                 }
6438               break;
6439             case DW_TAG_enumeration_type:
6440               if (!pdi->is_declaration)
6441                 add_partial_enumeration (pdi, cu);
6442               break;
6443             case DW_TAG_base_type:
6444             case DW_TAG_subrange_type:
6445               /* File scope base type definitions are added to the partial
6446                  symbol table.  */
6447               add_partial_symbol (pdi, cu);
6448               break;
6449             case DW_TAG_namespace:
6450               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6451               break;
6452             case DW_TAG_module:
6453               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6454               break;
6455             case DW_TAG_imported_unit:
6456               {
6457                 struct dwarf2_per_cu_data *per_cu;
6458
6459                 /* For now we don't handle imported units in type units.  */
6460                 if (cu->per_cu->is_debug_types)
6461                   {
6462                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6463                              " supported in type units [in module %s]"),
6464                            objfile_name (cu->objfile));
6465                   }
6466
6467                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6468                                                            pdi->is_dwz,
6469                                                            cu->objfile);
6470
6471                 /* Go read the partial unit, if needed.  */
6472                 if (per_cu->v.psymtab == NULL)
6473                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6474
6475                 VEC_safe_push (dwarf2_per_cu_ptr,
6476                                cu->per_cu->imported_symtabs, per_cu);
6477               }
6478               break;
6479             default:
6480               break;
6481             }
6482         }
6483
6484       /* If the die has a sibling, skip to the sibling.  */
6485
6486       pdi = pdi->die_sibling;
6487     }
6488 }
6489
6490 /* Functions used to compute the fully scoped name of a partial DIE.
6491
6492    Normally, this is simple.  For C++, the parent DIE's fully scoped
6493    name is concatenated with "::" and the partial DIE's name.  For
6494    Java, the same thing occurs except that "." is used instead of "::".
6495    Enumerators are an exception; they use the scope of their parent
6496    enumeration type, i.e. the name of the enumeration type is not
6497    prepended to the enumerator.
6498
6499    There are two complexities.  One is DW_AT_specification; in this
6500    case "parent" means the parent of the target of the specification,
6501    instead of the direct parent of the DIE.  The other is compilers
6502    which do not emit DW_TAG_namespace; in this case we try to guess
6503    the fully qualified name of structure types from their members'
6504    linkage names.  This must be done using the DIE's children rather
6505    than the children of any DW_AT_specification target.  We only need
6506    to do this for structures at the top level, i.e. if the target of
6507    any DW_AT_specification (if any; otherwise the DIE itself) does not
6508    have a parent.  */
6509
6510 /* Compute the scope prefix associated with PDI's parent, in
6511    compilation unit CU.  The result will be allocated on CU's
6512    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6513    field.  NULL is returned if no prefix is necessary.  */
6514 static const char *
6515 partial_die_parent_scope (struct partial_die_info *pdi,
6516                           struct dwarf2_cu *cu)
6517 {
6518   const char *grandparent_scope;
6519   struct partial_die_info *parent, *real_pdi;
6520
6521   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6522      then this means the parent of the specification DIE.  */
6523
6524   real_pdi = pdi;
6525   while (real_pdi->has_specification)
6526     real_pdi = find_partial_die (real_pdi->spec_offset,
6527                                  real_pdi->spec_is_dwz, cu);
6528
6529   parent = real_pdi->die_parent;
6530   if (parent == NULL)
6531     return NULL;
6532
6533   if (parent->scope_set)
6534     return parent->scope;
6535
6536   fixup_partial_die (parent, cu);
6537
6538   grandparent_scope = partial_die_parent_scope (parent, cu);
6539
6540   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6541      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6542      Work around this problem here.  */
6543   if (cu->language == language_cplus
6544       && parent->tag == DW_TAG_namespace
6545       && strcmp (parent->name, "::") == 0
6546       && grandparent_scope == NULL)
6547     {
6548       parent->scope = NULL;
6549       parent->scope_set = 1;
6550       return NULL;
6551     }
6552
6553   if (pdi->tag == DW_TAG_enumerator)
6554     /* Enumerators should not get the name of the enumeration as a prefix.  */
6555     parent->scope = grandparent_scope;
6556   else if (parent->tag == DW_TAG_namespace
6557       || parent->tag == DW_TAG_module
6558       || parent->tag == DW_TAG_structure_type
6559       || parent->tag == DW_TAG_class_type
6560       || parent->tag == DW_TAG_interface_type
6561       || parent->tag == DW_TAG_union_type
6562       || parent->tag == DW_TAG_enumeration_type)
6563     {
6564       if (grandparent_scope == NULL)
6565         parent->scope = parent->name;
6566       else
6567         parent->scope = typename_concat (&cu->comp_unit_obstack,
6568                                          grandparent_scope,
6569                                          parent->name, 0, cu);
6570     }
6571   else
6572     {
6573       /* FIXME drow/2004-04-01: What should we be doing with
6574          function-local names?  For partial symbols, we should probably be
6575          ignoring them.  */
6576       complaint (&symfile_complaints,
6577                  _("unhandled containing DIE tag %d for DIE at %d"),
6578                  parent->tag, pdi->offset.sect_off);
6579       parent->scope = grandparent_scope;
6580     }
6581
6582   parent->scope_set = 1;
6583   return parent->scope;
6584 }
6585
6586 /* Return the fully scoped name associated with PDI, from compilation unit
6587    CU.  The result will be allocated with malloc.  */
6588
6589 static char *
6590 partial_die_full_name (struct partial_die_info *pdi,
6591                        struct dwarf2_cu *cu)
6592 {
6593   const char *parent_scope;
6594
6595   /* If this is a template instantiation, we can not work out the
6596      template arguments from partial DIEs.  So, unfortunately, we have
6597      to go through the full DIEs.  At least any work we do building
6598      types here will be reused if full symbols are loaded later.  */
6599   if (pdi->has_template_arguments)
6600     {
6601       fixup_partial_die (pdi, cu);
6602
6603       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6604         {
6605           struct die_info *die;
6606           struct attribute attr;
6607           struct dwarf2_cu *ref_cu = cu;
6608
6609           /* DW_FORM_ref_addr is using section offset.  */
6610           attr.name = 0;
6611           attr.form = DW_FORM_ref_addr;
6612           attr.u.unsnd = pdi->offset.sect_off;
6613           die = follow_die_ref (NULL, &attr, &ref_cu);
6614
6615           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6616         }
6617     }
6618
6619   parent_scope = partial_die_parent_scope (pdi, cu);
6620   if (parent_scope == NULL)
6621     return NULL;
6622   else
6623     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6624 }
6625
6626 static void
6627 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6628 {
6629   struct objfile *objfile = cu->objfile;
6630   CORE_ADDR addr = 0;
6631   const char *actual_name = NULL;
6632   CORE_ADDR baseaddr;
6633   char *built_actual_name;
6634
6635   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6636
6637   built_actual_name = partial_die_full_name (pdi, cu);
6638   if (built_actual_name != NULL)
6639     actual_name = built_actual_name;
6640
6641   if (actual_name == NULL)
6642     actual_name = pdi->name;
6643
6644   switch (pdi->tag)
6645     {
6646     case DW_TAG_subprogram:
6647       if (pdi->is_external || cu->language == language_ada)
6648         {
6649           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6650              of the global scope.  But in Ada, we want to be able to access
6651              nested procedures globally.  So all Ada subprograms are stored
6652              in the global scope.  */
6653           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6654              mst_text, objfile); */
6655           add_psymbol_to_list (actual_name, strlen (actual_name),
6656                                built_actual_name != NULL,
6657                                VAR_DOMAIN, LOC_BLOCK,
6658                                &objfile->global_psymbols,
6659                                0, pdi->lowpc + baseaddr,
6660                                cu->language, objfile);
6661         }
6662       else
6663         {
6664           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6665              mst_file_text, objfile); */
6666           add_psymbol_to_list (actual_name, strlen (actual_name),
6667                                built_actual_name != NULL,
6668                                VAR_DOMAIN, LOC_BLOCK,
6669                                &objfile->static_psymbols,
6670                                0, pdi->lowpc + baseaddr,
6671                                cu->language, objfile);
6672         }
6673       break;
6674     case DW_TAG_constant:
6675       {
6676         struct psymbol_allocation_list *list;
6677
6678         if (pdi->is_external)
6679           list = &objfile->global_psymbols;
6680         else
6681           list = &objfile->static_psymbols;
6682         add_psymbol_to_list (actual_name, strlen (actual_name),
6683                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6684                              list, 0, 0, cu->language, objfile);
6685       }
6686       break;
6687     case DW_TAG_variable:
6688       if (pdi->d.locdesc)
6689         addr = decode_locdesc (pdi->d.locdesc, cu);
6690
6691       if (pdi->d.locdesc
6692           && addr == 0
6693           && !dwarf2_per_objfile->has_section_at_zero)
6694         {
6695           /* A global or static variable may also have been stripped
6696              out by the linker if unused, in which case its address
6697              will be nullified; do not add such variables into partial
6698              symbol table then.  */
6699         }
6700       else if (pdi->is_external)
6701         {
6702           /* Global Variable.
6703              Don't enter into the minimal symbol tables as there is
6704              a minimal symbol table entry from the ELF symbols already.
6705              Enter into partial symbol table if it has a location
6706              descriptor or a type.
6707              If the location descriptor is missing, new_symbol will create
6708              a LOC_UNRESOLVED symbol, the address of the variable will then
6709              be determined from the minimal symbol table whenever the variable
6710              is referenced.
6711              The address for the partial symbol table entry is not
6712              used by GDB, but it comes in handy for debugging partial symbol
6713              table building.  */
6714
6715           if (pdi->d.locdesc || pdi->has_type)
6716             add_psymbol_to_list (actual_name, strlen (actual_name),
6717                                  built_actual_name != NULL,
6718                                  VAR_DOMAIN, LOC_STATIC,
6719                                  &objfile->global_psymbols,
6720                                  0, addr + baseaddr,
6721                                  cu->language, objfile);
6722         }
6723       else
6724         {
6725           /* Static Variable.  Skip symbols without location descriptors.  */
6726           if (pdi->d.locdesc == NULL)
6727             {
6728               xfree (built_actual_name);
6729               return;
6730             }
6731           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6732              mst_file_data, objfile); */
6733           add_psymbol_to_list (actual_name, strlen (actual_name),
6734                                built_actual_name != NULL,
6735                                VAR_DOMAIN, LOC_STATIC,
6736                                &objfile->static_psymbols,
6737                                0, addr + baseaddr,
6738                                cu->language, objfile);
6739         }
6740       break;
6741     case DW_TAG_typedef:
6742     case DW_TAG_base_type:
6743     case DW_TAG_subrange_type:
6744       add_psymbol_to_list (actual_name, strlen (actual_name),
6745                            built_actual_name != NULL,
6746                            VAR_DOMAIN, LOC_TYPEDEF,
6747                            &objfile->static_psymbols,
6748                            0, (CORE_ADDR) 0, cu->language, objfile);
6749       break;
6750     case DW_TAG_namespace:
6751       add_psymbol_to_list (actual_name, strlen (actual_name),
6752                            built_actual_name != NULL,
6753                            VAR_DOMAIN, LOC_TYPEDEF,
6754                            &objfile->global_psymbols,
6755                            0, (CORE_ADDR) 0, cu->language, objfile);
6756       break;
6757     case DW_TAG_class_type:
6758     case DW_TAG_interface_type:
6759     case DW_TAG_structure_type:
6760     case DW_TAG_union_type:
6761     case DW_TAG_enumeration_type:
6762       /* Skip external references.  The DWARF standard says in the section
6763          about "Structure, Union, and Class Type Entries": "An incomplete
6764          structure, union or class type is represented by a structure,
6765          union or class entry that does not have a byte size attribute
6766          and that has a DW_AT_declaration attribute."  */
6767       if (!pdi->has_byte_size && pdi->is_declaration)
6768         {
6769           xfree (built_actual_name);
6770           return;
6771         }
6772
6773       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6774          static vs. global.  */
6775       add_psymbol_to_list (actual_name, strlen (actual_name),
6776                            built_actual_name != NULL,
6777                            STRUCT_DOMAIN, LOC_TYPEDEF,
6778                            (cu->language == language_cplus
6779                             || cu->language == language_java)
6780                            ? &objfile->global_psymbols
6781                            : &objfile->static_psymbols,
6782                            0, (CORE_ADDR) 0, cu->language, objfile);
6783
6784       break;
6785     case DW_TAG_enumerator:
6786       add_psymbol_to_list (actual_name, strlen (actual_name),
6787                            built_actual_name != NULL,
6788                            VAR_DOMAIN, LOC_CONST,
6789                            (cu->language == language_cplus
6790                             || cu->language == language_java)
6791                            ? &objfile->global_psymbols
6792                            : &objfile->static_psymbols,
6793                            0, (CORE_ADDR) 0, cu->language, objfile);
6794       break;
6795     default:
6796       break;
6797     }
6798
6799   xfree (built_actual_name);
6800 }
6801
6802 /* Read a partial die corresponding to a namespace; also, add a symbol
6803    corresponding to that namespace to the symbol table.  NAMESPACE is
6804    the name of the enclosing namespace.  */
6805
6806 static void
6807 add_partial_namespace (struct partial_die_info *pdi,
6808                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6809                        int need_pc, struct dwarf2_cu *cu)
6810 {
6811   /* Add a symbol for the namespace.  */
6812
6813   add_partial_symbol (pdi, cu);
6814
6815   /* Now scan partial symbols in that namespace.  */
6816
6817   if (pdi->has_children)
6818     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6819 }
6820
6821 /* Read a partial die corresponding to a Fortran module.  */
6822
6823 static void
6824 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6825                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6826 {
6827   /* Now scan partial symbols in that module.  */
6828
6829   if (pdi->has_children)
6830     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6831 }
6832
6833 /* Read a partial die corresponding to a subprogram and create a partial
6834    symbol for that subprogram.  When the CU language allows it, this
6835    routine also defines a partial symbol for each nested subprogram
6836    that this subprogram contains.
6837
6838    DIE my also be a lexical block, in which case we simply search
6839    recursively for suprograms defined inside that lexical block.
6840    Again, this is only performed when the CU language allows this
6841    type of definitions.  */
6842
6843 static void
6844 add_partial_subprogram (struct partial_die_info *pdi,
6845                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6846                         int need_pc, struct dwarf2_cu *cu)
6847 {
6848   if (pdi->tag == DW_TAG_subprogram)
6849     {
6850       if (pdi->has_pc_info)
6851         {
6852           if (pdi->lowpc < *lowpc)
6853             *lowpc = pdi->lowpc;
6854           if (pdi->highpc > *highpc)
6855             *highpc = pdi->highpc;
6856           if (need_pc)
6857             {
6858               CORE_ADDR baseaddr;
6859               struct objfile *objfile = cu->objfile;
6860
6861               baseaddr = ANOFFSET (objfile->section_offsets,
6862                                    SECT_OFF_TEXT (objfile));
6863               addrmap_set_empty (objfile->psymtabs_addrmap,
6864                                  pdi->lowpc + baseaddr,
6865                                  pdi->highpc - 1 + baseaddr,
6866                                  cu->per_cu->v.psymtab);
6867             }
6868         }
6869
6870       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6871         {
6872           if (!pdi->is_declaration)
6873             /* Ignore subprogram DIEs that do not have a name, they are
6874                illegal.  Do not emit a complaint at this point, we will
6875                do so when we convert this psymtab into a symtab.  */
6876             if (pdi->name)
6877               add_partial_symbol (pdi, cu);
6878         }
6879     }
6880
6881   if (! pdi->has_children)
6882     return;
6883
6884   if (cu->language == language_ada)
6885     {
6886       pdi = pdi->die_child;
6887       while (pdi != NULL)
6888         {
6889           fixup_partial_die (pdi, cu);
6890           if (pdi->tag == DW_TAG_subprogram
6891               || pdi->tag == DW_TAG_lexical_block)
6892             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6893           pdi = pdi->die_sibling;
6894         }
6895     }
6896 }
6897
6898 /* Read a partial die corresponding to an enumeration type.  */
6899
6900 static void
6901 add_partial_enumeration (struct partial_die_info *enum_pdi,
6902                          struct dwarf2_cu *cu)
6903 {
6904   struct partial_die_info *pdi;
6905
6906   if (enum_pdi->name != NULL)
6907     add_partial_symbol (enum_pdi, cu);
6908
6909   pdi = enum_pdi->die_child;
6910   while (pdi)
6911     {
6912       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6913         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6914       else
6915         add_partial_symbol (pdi, cu);
6916       pdi = pdi->die_sibling;
6917     }
6918 }
6919
6920 /* Return the initial uleb128 in the die at INFO_PTR.  */
6921
6922 static unsigned int
6923 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6924 {
6925   unsigned int bytes_read;
6926
6927   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6928 }
6929
6930 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6931    Return the corresponding abbrev, or NULL if the number is zero (indicating
6932    an empty DIE).  In either case *BYTES_READ will be set to the length of
6933    the initial number.  */
6934
6935 static struct abbrev_info *
6936 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6937                  struct dwarf2_cu *cu)
6938 {
6939   bfd *abfd = cu->objfile->obfd;
6940   unsigned int abbrev_number;
6941   struct abbrev_info *abbrev;
6942
6943   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6944
6945   if (abbrev_number == 0)
6946     return NULL;
6947
6948   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6949   if (!abbrev)
6950     {
6951       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6952              abbrev_number, bfd_get_filename (abfd));
6953     }
6954
6955   return abbrev;
6956 }
6957
6958 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6959    Returns a pointer to the end of a series of DIEs, terminated by an empty
6960    DIE.  Any children of the skipped DIEs will also be skipped.  */
6961
6962 static const gdb_byte *
6963 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6964 {
6965   struct dwarf2_cu *cu = reader->cu;
6966   struct abbrev_info *abbrev;
6967   unsigned int bytes_read;
6968
6969   while (1)
6970     {
6971       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6972       if (abbrev == NULL)
6973         return info_ptr + bytes_read;
6974       else
6975         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6976     }
6977 }
6978
6979 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6980    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6981    abbrev corresponding to that skipped uleb128 should be passed in
6982    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6983    children.  */
6984
6985 static const gdb_byte *
6986 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6987               struct abbrev_info *abbrev)
6988 {
6989   unsigned int bytes_read;
6990   struct attribute attr;
6991   bfd *abfd = reader->abfd;
6992   struct dwarf2_cu *cu = reader->cu;
6993   const gdb_byte *buffer = reader->buffer;
6994   const gdb_byte *buffer_end = reader->buffer_end;
6995   const gdb_byte *start_info_ptr = info_ptr;
6996   unsigned int form, i;
6997
6998   for (i = 0; i < abbrev->num_attrs; i++)
6999     {
7000       /* The only abbrev we care about is DW_AT_sibling.  */
7001       if (abbrev->attrs[i].name == DW_AT_sibling)
7002         {
7003           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7004           if (attr.form == DW_FORM_ref_addr)
7005             complaint (&symfile_complaints,
7006                        _("ignoring absolute DW_AT_sibling"));
7007           else
7008             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
7009         }
7010
7011       /* If it isn't DW_AT_sibling, skip this attribute.  */
7012       form = abbrev->attrs[i].form;
7013     skip_attribute:
7014       switch (form)
7015         {
7016         case DW_FORM_ref_addr:
7017           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7018              and later it is offset sized.  */
7019           if (cu->header.version == 2)
7020             info_ptr += cu->header.addr_size;
7021           else
7022             info_ptr += cu->header.offset_size;
7023           break;
7024         case DW_FORM_GNU_ref_alt:
7025           info_ptr += cu->header.offset_size;
7026           break;
7027         case DW_FORM_addr:
7028           info_ptr += cu->header.addr_size;
7029           break;
7030         case DW_FORM_data1:
7031         case DW_FORM_ref1:
7032         case DW_FORM_flag:
7033           info_ptr += 1;
7034           break;
7035         case DW_FORM_flag_present:
7036           break;
7037         case DW_FORM_data2:
7038         case DW_FORM_ref2:
7039           info_ptr += 2;
7040           break;
7041         case DW_FORM_data4:
7042         case DW_FORM_ref4:
7043           info_ptr += 4;
7044           break;
7045         case DW_FORM_data8:
7046         case DW_FORM_ref8:
7047         case DW_FORM_ref_sig8:
7048           info_ptr += 8;
7049           break;
7050         case DW_FORM_string:
7051           read_direct_string (abfd, info_ptr, &bytes_read);
7052           info_ptr += bytes_read;
7053           break;
7054         case DW_FORM_sec_offset:
7055         case DW_FORM_strp:
7056         case DW_FORM_GNU_strp_alt:
7057           info_ptr += cu->header.offset_size;
7058           break;
7059         case DW_FORM_exprloc:
7060         case DW_FORM_block:
7061           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7062           info_ptr += bytes_read;
7063           break;
7064         case DW_FORM_block1:
7065           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7066           break;
7067         case DW_FORM_block2:
7068           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7069           break;
7070         case DW_FORM_block4:
7071           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7072           break;
7073         case DW_FORM_sdata:
7074         case DW_FORM_udata:
7075         case DW_FORM_ref_udata:
7076         case DW_FORM_GNU_addr_index:
7077         case DW_FORM_GNU_str_index:
7078           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7079           break;
7080         case DW_FORM_indirect:
7081           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7082           info_ptr += bytes_read;
7083           /* We need to continue parsing from here, so just go back to
7084              the top.  */
7085           goto skip_attribute;
7086
7087         default:
7088           error (_("Dwarf Error: Cannot handle %s "
7089                    "in DWARF reader [in module %s]"),
7090                  dwarf_form_name (form),
7091                  bfd_get_filename (abfd));
7092         }
7093     }
7094
7095   if (abbrev->has_children)
7096     return skip_children (reader, info_ptr);
7097   else
7098     return info_ptr;
7099 }
7100
7101 /* Locate ORIG_PDI's sibling.
7102    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7103
7104 static const gdb_byte *
7105 locate_pdi_sibling (const struct die_reader_specs *reader,
7106                     struct partial_die_info *orig_pdi,
7107                     const gdb_byte *info_ptr)
7108 {
7109   /* Do we know the sibling already?  */
7110
7111   if (orig_pdi->sibling)
7112     return orig_pdi->sibling;
7113
7114   /* Are there any children to deal with?  */
7115
7116   if (!orig_pdi->has_children)
7117     return info_ptr;
7118
7119   /* Skip the children the long way.  */
7120
7121   return skip_children (reader, info_ptr);
7122 }
7123
7124 /* Expand this partial symbol table into a full symbol table.  SELF is
7125    not NULL.  */
7126
7127 static void
7128 dwarf2_read_symtab (struct partial_symtab *self,
7129                     struct objfile *objfile)
7130 {
7131   if (self->readin)
7132     {
7133       warning (_("bug: psymtab for %s is already read in."),
7134                self->filename);
7135     }
7136   else
7137     {
7138       if (info_verbose)
7139         {
7140           printf_filtered (_("Reading in symbols for %s..."),
7141                            self->filename);
7142           gdb_flush (gdb_stdout);
7143         }
7144
7145       /* Restore our global data.  */
7146       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
7147
7148       /* If this psymtab is constructed from a debug-only objfile, the
7149          has_section_at_zero flag will not necessarily be correct.  We
7150          can get the correct value for this flag by looking at the data
7151          associated with the (presumably stripped) associated objfile.  */
7152       if (objfile->separate_debug_objfile_backlink)
7153         {
7154           struct dwarf2_per_objfile *dpo_backlink
7155             = objfile_data (objfile->separate_debug_objfile_backlink,
7156                             dwarf2_objfile_data_key);
7157
7158           dwarf2_per_objfile->has_section_at_zero
7159             = dpo_backlink->has_section_at_zero;
7160         }
7161
7162       dwarf2_per_objfile->reading_partial_symbols = 0;
7163
7164       psymtab_to_symtab_1 (self);
7165
7166       /* Finish up the debug error message.  */
7167       if (info_verbose)
7168         printf_filtered (_("done.\n"));
7169     }
7170
7171   process_cu_includes ();
7172 }
7173 \f
7174 /* Reading in full CUs.  */
7175
7176 /* Add PER_CU to the queue.  */
7177
7178 static void
7179 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7180                  enum language pretend_language)
7181 {
7182   struct dwarf2_queue_item *item;
7183
7184   per_cu->queued = 1;
7185   item = xmalloc (sizeof (*item));
7186   item->per_cu = per_cu;
7187   item->pretend_language = pretend_language;
7188   item->next = NULL;
7189
7190   if (dwarf2_queue == NULL)
7191     dwarf2_queue = item;
7192   else
7193     dwarf2_queue_tail->next = item;
7194
7195   dwarf2_queue_tail = item;
7196 }
7197
7198 /* If PER_CU is not yet queued, add it to the queue.
7199    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7200    dependency.
7201    The result is non-zero if PER_CU was queued, otherwise the result is zero
7202    meaning either PER_CU is already queued or it is already loaded.
7203
7204    N.B. There is an invariant here that if a CU is queued then it is loaded.
7205    The caller is required to load PER_CU if we return non-zero.  */
7206
7207 static int
7208 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7209                        struct dwarf2_per_cu_data *per_cu,
7210                        enum language pretend_language)
7211 {
7212   /* We may arrive here during partial symbol reading, if we need full
7213      DIEs to process an unusual case (e.g. template arguments).  Do
7214      not queue PER_CU, just tell our caller to load its DIEs.  */
7215   if (dwarf2_per_objfile->reading_partial_symbols)
7216     {
7217       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7218         return 1;
7219       return 0;
7220     }
7221
7222   /* Mark the dependence relation so that we don't flush PER_CU
7223      too early.  */
7224   if (dependent_cu != NULL)
7225     dwarf2_add_dependence (dependent_cu, per_cu);
7226
7227   /* If it's already on the queue, we have nothing to do.  */
7228   if (per_cu->queued)
7229     return 0;
7230
7231   /* If the compilation unit is already loaded, just mark it as
7232      used.  */
7233   if (per_cu->cu != NULL)
7234     {
7235       per_cu->cu->last_used = 0;
7236       return 0;
7237     }
7238
7239   /* Add it to the queue.  */
7240   queue_comp_unit (per_cu, pretend_language);
7241
7242   return 1;
7243 }
7244
7245 /* Process the queue.  */
7246
7247 static void
7248 process_queue (void)
7249 {
7250   struct dwarf2_queue_item *item, *next_item;
7251
7252   if (dwarf2_read_debug)
7253     {
7254       fprintf_unfiltered (gdb_stdlog,
7255                           "Expanding one or more symtabs of objfile %s ...\n",
7256                           objfile_name (dwarf2_per_objfile->objfile));
7257     }
7258
7259   /* The queue starts out with one item, but following a DIE reference
7260      may load a new CU, adding it to the end of the queue.  */
7261   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7262     {
7263       if (dwarf2_per_objfile->using_index
7264           ? !item->per_cu->v.quick->symtab
7265           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7266         {
7267           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7268           char buf[100];
7269
7270           if (per_cu->is_debug_types)
7271             {
7272               struct signatured_type *sig_type =
7273                 (struct signatured_type *) per_cu;
7274
7275               sprintf (buf, "TU %s at offset 0x%x",
7276                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7277             }
7278           else
7279             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7280
7281           if (dwarf2_read_debug)
7282             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7283
7284           if (per_cu->is_debug_types)
7285             process_full_type_unit (per_cu, item->pretend_language);
7286           else
7287             process_full_comp_unit (per_cu, item->pretend_language);
7288
7289           if (dwarf2_read_debug)
7290             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7291         }
7292
7293       item->per_cu->queued = 0;
7294       next_item = item->next;
7295       xfree (item);
7296     }
7297
7298   dwarf2_queue_tail = NULL;
7299
7300   if (dwarf2_read_debug)
7301     {
7302       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7303                           objfile_name (dwarf2_per_objfile->objfile));
7304     }
7305 }
7306
7307 /* Free all allocated queue entries.  This function only releases anything if
7308    an error was thrown; if the queue was processed then it would have been
7309    freed as we went along.  */
7310
7311 static void
7312 dwarf2_release_queue (void *dummy)
7313 {
7314   struct dwarf2_queue_item *item, *last;
7315
7316   item = dwarf2_queue;
7317   while (item)
7318     {
7319       /* Anything still marked queued is likely to be in an
7320          inconsistent state, so discard it.  */
7321       if (item->per_cu->queued)
7322         {
7323           if (item->per_cu->cu != NULL)
7324             free_one_cached_comp_unit (item->per_cu);
7325           item->per_cu->queued = 0;
7326         }
7327
7328       last = item;
7329       item = item->next;
7330       xfree (last);
7331     }
7332
7333   dwarf2_queue = dwarf2_queue_tail = NULL;
7334 }
7335
7336 /* Read in full symbols for PST, and anything it depends on.  */
7337
7338 static void
7339 psymtab_to_symtab_1 (struct partial_symtab *pst)
7340 {
7341   struct dwarf2_per_cu_data *per_cu;
7342   int i;
7343
7344   if (pst->readin)
7345     return;
7346
7347   for (i = 0; i < pst->number_of_dependencies; i++)
7348     if (!pst->dependencies[i]->readin
7349         && pst->dependencies[i]->user == NULL)
7350       {
7351         /* Inform about additional files that need to be read in.  */
7352         if (info_verbose)
7353           {
7354             /* FIXME: i18n: Need to make this a single string.  */
7355             fputs_filtered (" ", gdb_stdout);
7356             wrap_here ("");
7357             fputs_filtered ("and ", gdb_stdout);
7358             wrap_here ("");
7359             printf_filtered ("%s...", pst->dependencies[i]->filename);
7360             wrap_here ("");     /* Flush output.  */
7361             gdb_flush (gdb_stdout);
7362           }
7363         psymtab_to_symtab_1 (pst->dependencies[i]);
7364       }
7365
7366   per_cu = pst->read_symtab_private;
7367
7368   if (per_cu == NULL)
7369     {
7370       /* It's an include file, no symbols to read for it.
7371          Everything is in the parent symtab.  */
7372       pst->readin = 1;
7373       return;
7374     }
7375
7376   dw2_do_instantiate_symtab (per_cu);
7377 }
7378
7379 /* Trivial hash function for die_info: the hash value of a DIE
7380    is its offset in .debug_info for this objfile.  */
7381
7382 static hashval_t
7383 die_hash (const void *item)
7384 {
7385   const struct die_info *die = item;
7386
7387   return die->offset.sect_off;
7388 }
7389
7390 /* Trivial comparison function for die_info structures: two DIEs
7391    are equal if they have the same offset.  */
7392
7393 static int
7394 die_eq (const void *item_lhs, const void *item_rhs)
7395 {
7396   const struct die_info *die_lhs = item_lhs;
7397   const struct die_info *die_rhs = item_rhs;
7398
7399   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7400 }
7401
7402 /* die_reader_func for load_full_comp_unit.
7403    This is identical to read_signatured_type_reader,
7404    but is kept separate for now.  */
7405
7406 static void
7407 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7408                             const gdb_byte *info_ptr,
7409                             struct die_info *comp_unit_die,
7410                             int has_children,
7411                             void *data)
7412 {
7413   struct dwarf2_cu *cu = reader->cu;
7414   enum language *language_ptr = data;
7415
7416   gdb_assert (cu->die_hash == NULL);
7417   cu->die_hash =
7418     htab_create_alloc_ex (cu->header.length / 12,
7419                           die_hash,
7420                           die_eq,
7421                           NULL,
7422                           &cu->comp_unit_obstack,
7423                           hashtab_obstack_allocate,
7424                           dummy_obstack_deallocate);
7425
7426   if (has_children)
7427     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7428                                                   &info_ptr, comp_unit_die);
7429   cu->dies = comp_unit_die;
7430   /* comp_unit_die is not stored in die_hash, no need.  */
7431
7432   /* We try not to read any attributes in this function, because not
7433      all CUs needed for references have been loaded yet, and symbol
7434      table processing isn't initialized.  But we have to set the CU language,
7435      or we won't be able to build types correctly.
7436      Similarly, if we do not read the producer, we can not apply
7437      producer-specific interpretation.  */
7438   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7439 }
7440
7441 /* Load the DIEs associated with PER_CU into memory.  */
7442
7443 static void
7444 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7445                      enum language pretend_language)
7446 {
7447   gdb_assert (! this_cu->is_debug_types);
7448
7449   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7450                            load_full_comp_unit_reader, &pretend_language);
7451 }
7452
7453 /* Add a DIE to the delayed physname list.  */
7454
7455 static void
7456 add_to_method_list (struct type *type, int fnfield_index, int index,
7457                     const char *name, struct die_info *die,
7458                     struct dwarf2_cu *cu)
7459 {
7460   struct delayed_method_info mi;
7461   mi.type = type;
7462   mi.fnfield_index = fnfield_index;
7463   mi.index = index;
7464   mi.name = name;
7465   mi.die = die;
7466   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7467 }
7468
7469 /* A cleanup for freeing the delayed method list.  */
7470
7471 static void
7472 free_delayed_list (void *ptr)
7473 {
7474   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7475   if (cu->method_list != NULL)
7476     {
7477       VEC_free (delayed_method_info, cu->method_list);
7478       cu->method_list = NULL;
7479     }
7480 }
7481
7482 /* Compute the physnames of any methods on the CU's method list.
7483
7484    The computation of method physnames is delayed in order to avoid the
7485    (bad) condition that one of the method's formal parameters is of an as yet
7486    incomplete type.  */
7487
7488 static void
7489 compute_delayed_physnames (struct dwarf2_cu *cu)
7490 {
7491   int i;
7492   struct delayed_method_info *mi;
7493   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7494     {
7495       const char *physname;
7496       struct fn_fieldlist *fn_flp
7497         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7498       physname = dwarf2_physname (mi->name, mi->die, cu);
7499       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7500     }
7501 }
7502
7503 /* Go objects should be embedded in a DW_TAG_module DIE,
7504    and it's not clear if/how imported objects will appear.
7505    To keep Go support simple until that's worked out,
7506    go back through what we've read and create something usable.
7507    We could do this while processing each DIE, and feels kinda cleaner,
7508    but that way is more invasive.
7509    This is to, for example, allow the user to type "p var" or "b main"
7510    without having to specify the package name, and allow lookups
7511    of module.object to work in contexts that use the expression
7512    parser.  */
7513
7514 static void
7515 fixup_go_packaging (struct dwarf2_cu *cu)
7516 {
7517   char *package_name = NULL;
7518   struct pending *list;
7519   int i;
7520
7521   for (list = global_symbols; list != NULL; list = list->next)
7522     {
7523       for (i = 0; i < list->nsyms; ++i)
7524         {
7525           struct symbol *sym = list->symbol[i];
7526
7527           if (SYMBOL_LANGUAGE (sym) == language_go
7528               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7529             {
7530               char *this_package_name = go_symbol_package_name (sym);
7531
7532               if (this_package_name == NULL)
7533                 continue;
7534               if (package_name == NULL)
7535                 package_name = this_package_name;
7536               else
7537                 {
7538                   if (strcmp (package_name, this_package_name) != 0)
7539                     complaint (&symfile_complaints,
7540                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7541                                (SYMBOL_SYMTAB (sym)
7542                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7543                                 : objfile_name (cu->objfile)),
7544                                this_package_name, package_name);
7545                   xfree (this_package_name);
7546                 }
7547             }
7548         }
7549     }
7550
7551   if (package_name != NULL)
7552     {
7553       struct objfile *objfile = cu->objfile;
7554       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7555                                                       package_name,
7556                                                       strlen (package_name));
7557       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7558                                      saved_package_name, objfile);
7559       struct symbol *sym;
7560
7561       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7562
7563       sym = allocate_symbol (objfile);
7564       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7565       SYMBOL_SET_NAMES (sym, saved_package_name,
7566                         strlen (saved_package_name), 0, objfile);
7567       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7568          e.g., "main" finds the "main" module and not C's main().  */
7569       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7570       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7571       SYMBOL_TYPE (sym) = type;
7572
7573       add_symbol_to_list (sym, &global_symbols);
7574
7575       xfree (package_name);
7576     }
7577 }
7578
7579 /* Return the symtab for PER_CU.  This works properly regardless of
7580    whether we're using the index or psymtabs.  */
7581
7582 static struct symtab *
7583 get_symtab (struct dwarf2_per_cu_data *per_cu)
7584 {
7585   return (dwarf2_per_objfile->using_index
7586           ? per_cu->v.quick->symtab
7587           : per_cu->v.psymtab->symtab);
7588 }
7589
7590 /* A helper function for computing the list of all symbol tables
7591    included by PER_CU.  */
7592
7593 static void
7594 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7595                                 htab_t all_children, htab_t all_type_symtabs,
7596                                 struct dwarf2_per_cu_data *per_cu,
7597                                 struct symtab *immediate_parent)
7598 {
7599   void **slot;
7600   int ix;
7601   struct symtab *symtab;
7602   struct dwarf2_per_cu_data *iter;
7603
7604   slot = htab_find_slot (all_children, per_cu, INSERT);
7605   if (*slot != NULL)
7606     {
7607       /* This inclusion and its children have been processed.  */
7608       return;
7609     }
7610
7611   *slot = per_cu;
7612   /* Only add a CU if it has a symbol table.  */
7613   symtab = get_symtab (per_cu);
7614   if (symtab != NULL)
7615     {
7616       /* If this is a type unit only add its symbol table if we haven't
7617          seen it yet (type unit per_cu's can share symtabs).  */
7618       if (per_cu->is_debug_types)
7619         {
7620           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7621           if (*slot == NULL)
7622             {
7623               *slot = symtab;
7624               VEC_safe_push (symtab_ptr, *result, symtab);
7625               if (symtab->user == NULL)
7626                 symtab->user = immediate_parent;
7627             }
7628         }
7629       else
7630         {
7631           VEC_safe_push (symtab_ptr, *result, symtab);
7632           if (symtab->user == NULL)
7633             symtab->user = immediate_parent;
7634         }
7635     }
7636
7637   for (ix = 0;
7638        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7639        ++ix)
7640     {
7641       recursively_compute_inclusions (result, all_children,
7642                                       all_type_symtabs, iter, symtab);
7643     }
7644 }
7645
7646 /* Compute the symtab 'includes' fields for the symtab related to
7647    PER_CU.  */
7648
7649 static void
7650 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7651 {
7652   gdb_assert (! per_cu->is_debug_types);
7653
7654   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7655     {
7656       int ix, len;
7657       struct dwarf2_per_cu_data *per_cu_iter;
7658       struct symtab *symtab_iter;
7659       VEC (symtab_ptr) *result_symtabs = NULL;
7660       htab_t all_children, all_type_symtabs;
7661       struct symtab *symtab = get_symtab (per_cu);
7662
7663       /* If we don't have a symtab, we can just skip this case.  */
7664       if (symtab == NULL)
7665         return;
7666
7667       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7668                                         NULL, xcalloc, xfree);
7669       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7670                                             NULL, xcalloc, xfree);
7671
7672       for (ix = 0;
7673            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7674                         ix, per_cu_iter);
7675            ++ix)
7676         {
7677           recursively_compute_inclusions (&result_symtabs, all_children,
7678                                           all_type_symtabs, per_cu_iter,
7679                                           symtab);
7680         }
7681
7682       /* Now we have a transitive closure of all the included symtabs.  */
7683       len = VEC_length (symtab_ptr, result_symtabs);
7684       symtab->includes
7685         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7686                          (len + 1) * sizeof (struct symtab *));
7687       for (ix = 0;
7688            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7689            ++ix)
7690         symtab->includes[ix] = symtab_iter;
7691       symtab->includes[len] = NULL;
7692
7693       VEC_free (symtab_ptr, result_symtabs);
7694       htab_delete (all_children);
7695       htab_delete (all_type_symtabs);
7696     }
7697 }
7698
7699 /* Compute the 'includes' field for the symtabs of all the CUs we just
7700    read.  */
7701
7702 static void
7703 process_cu_includes (void)
7704 {
7705   int ix;
7706   struct dwarf2_per_cu_data *iter;
7707
7708   for (ix = 0;
7709        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7710                     ix, iter);
7711        ++ix)
7712     {
7713       if (! iter->is_debug_types)
7714         compute_symtab_includes (iter);
7715     }
7716
7717   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7718 }
7719
7720 /* Generate full symbol information for PER_CU, whose DIEs have
7721    already been loaded into memory.  */
7722
7723 static void
7724 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7725                         enum language pretend_language)
7726 {
7727   struct dwarf2_cu *cu = per_cu->cu;
7728   struct objfile *objfile = per_cu->objfile;
7729   CORE_ADDR lowpc, highpc;
7730   struct symtab *symtab;
7731   struct cleanup *back_to, *delayed_list_cleanup;
7732   CORE_ADDR baseaddr;
7733   struct block *static_block;
7734
7735   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7736
7737   buildsym_init ();
7738   back_to = make_cleanup (really_free_pendings, NULL);
7739   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7740
7741   cu->list_in_scope = &file_symbols;
7742
7743   cu->language = pretend_language;
7744   cu->language_defn = language_def (cu->language);
7745
7746   /* Do line number decoding in read_file_scope () */
7747   process_die (cu->dies, cu);
7748
7749   /* For now fudge the Go package.  */
7750   if (cu->language == language_go)
7751     fixup_go_packaging (cu);
7752
7753   /* Now that we have processed all the DIEs in the CU, all the types 
7754      should be complete, and it should now be safe to compute all of the
7755      physnames.  */
7756   compute_delayed_physnames (cu);
7757   do_cleanups (delayed_list_cleanup);
7758
7759   /* Some compilers don't define a DW_AT_high_pc attribute for the
7760      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7761      it, by scanning the DIE's below the compilation unit.  */
7762   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7763
7764   static_block
7765     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7766
7767   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7768      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7769      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7770      addrmap to help ensure it has an accurate map of pc values belonging to
7771      this comp unit.  */
7772   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7773
7774   symtab = end_symtab_from_static_block (static_block, objfile,
7775                                          SECT_OFF_TEXT (objfile), 0);
7776
7777   if (symtab != NULL)
7778     {
7779       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7780
7781       /* Set symtab language to language from DW_AT_language.  If the
7782          compilation is from a C file generated by language preprocessors, do
7783          not set the language if it was already deduced by start_subfile.  */
7784       if (!(cu->language == language_c && symtab->language != language_c))
7785         symtab->language = cu->language;
7786
7787       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7788          produce DW_AT_location with location lists but it can be possibly
7789          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7790          there were bugs in prologue debug info, fixed later in GCC-4.5
7791          by "unwind info for epilogues" patch (which is not directly related).
7792
7793          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7794          needed, it would be wrong due to missing DW_AT_producer there.
7795
7796          Still one can confuse GDB by using non-standard GCC compilation
7797          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7798          */ 
7799       if (cu->has_loclist && gcc_4_minor >= 5)
7800         symtab->locations_valid = 1;
7801
7802       if (gcc_4_minor >= 5)
7803         symtab->epilogue_unwind_valid = 1;
7804
7805       symtab->call_site_htab = cu->call_site_htab;
7806     }
7807
7808   if (dwarf2_per_objfile->using_index)
7809     per_cu->v.quick->symtab = symtab;
7810   else
7811     {
7812       struct partial_symtab *pst = per_cu->v.psymtab;
7813       pst->symtab = symtab;
7814       pst->readin = 1;
7815     }
7816
7817   /* Push it for inclusion processing later.  */
7818   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7819
7820   do_cleanups (back_to);
7821 }
7822
7823 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7824    already been loaded into memory.  */
7825
7826 static void
7827 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7828                         enum language pretend_language)
7829 {
7830   struct dwarf2_cu *cu = per_cu->cu;
7831   struct objfile *objfile = per_cu->objfile;
7832   struct symtab *symtab;
7833   struct cleanup *back_to, *delayed_list_cleanup;
7834   struct signatured_type *sig_type;
7835
7836   gdb_assert (per_cu->is_debug_types);
7837   sig_type = (struct signatured_type *) per_cu;
7838
7839   buildsym_init ();
7840   back_to = make_cleanup (really_free_pendings, NULL);
7841   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7842
7843   cu->list_in_scope = &file_symbols;
7844
7845   cu->language = pretend_language;
7846   cu->language_defn = language_def (cu->language);
7847
7848   /* The symbol tables are set up in read_type_unit_scope.  */
7849   process_die (cu->dies, cu);
7850
7851   /* For now fudge the Go package.  */
7852   if (cu->language == language_go)
7853     fixup_go_packaging (cu);
7854
7855   /* Now that we have processed all the DIEs in the CU, all the types 
7856      should be complete, and it should now be safe to compute all of the
7857      physnames.  */
7858   compute_delayed_physnames (cu);
7859   do_cleanups (delayed_list_cleanup);
7860
7861   /* TUs share symbol tables.
7862      If this is the first TU to use this symtab, complete the construction
7863      of it with end_expandable_symtab.  Otherwise, complete the addition of
7864      this TU's symbols to the existing symtab.  */
7865   if (sig_type->type_unit_group->primary_symtab == NULL)
7866     {
7867       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7868       sig_type->type_unit_group->primary_symtab = symtab;
7869
7870       if (symtab != NULL)
7871         {
7872           /* Set symtab language to language from DW_AT_language.  If the
7873              compilation is from a C file generated by language preprocessors,
7874              do not set the language if it was already deduced by
7875              start_subfile.  */
7876           if (!(cu->language == language_c && symtab->language != language_c))
7877             symtab->language = cu->language;
7878         }
7879     }
7880   else
7881     {
7882       augment_type_symtab (objfile,
7883                            sig_type->type_unit_group->primary_symtab);
7884       symtab = sig_type->type_unit_group->primary_symtab;
7885     }
7886
7887   if (dwarf2_per_objfile->using_index)
7888     per_cu->v.quick->symtab = symtab;
7889   else
7890     {
7891       struct partial_symtab *pst = per_cu->v.psymtab;
7892       pst->symtab = symtab;
7893       pst->readin = 1;
7894     }
7895
7896   do_cleanups (back_to);
7897 }
7898
7899 /* Process an imported unit DIE.  */
7900
7901 static void
7902 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7903 {
7904   struct attribute *attr;
7905
7906   /* For now we don't handle imported units in type units.  */
7907   if (cu->per_cu->is_debug_types)
7908     {
7909       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7910                " supported in type units [in module %s]"),
7911              objfile_name (cu->objfile));
7912     }
7913
7914   attr = dwarf2_attr (die, DW_AT_import, cu);
7915   if (attr != NULL)
7916     {
7917       struct dwarf2_per_cu_data *per_cu;
7918       struct symtab *imported_symtab;
7919       sect_offset offset;
7920       int is_dwz;
7921
7922       offset = dwarf2_get_ref_die_offset (attr);
7923       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7924       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7925
7926       /* If necessary, add it to the queue and load its DIEs.  */
7927       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7928         load_full_comp_unit (per_cu, cu->language);
7929
7930       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7931                      per_cu);
7932     }
7933 }
7934
7935 /* Process a die and its children.  */
7936
7937 static void
7938 process_die (struct die_info *die, struct dwarf2_cu *cu)
7939 {
7940   switch (die->tag)
7941     {
7942     case DW_TAG_padding:
7943       break;
7944     case DW_TAG_compile_unit:
7945     case DW_TAG_partial_unit:
7946       read_file_scope (die, cu);
7947       break;
7948     case DW_TAG_type_unit:
7949       read_type_unit_scope (die, cu);
7950       break;
7951     case DW_TAG_subprogram:
7952     case DW_TAG_inlined_subroutine:
7953       read_func_scope (die, cu);
7954       break;
7955     case DW_TAG_lexical_block:
7956     case DW_TAG_try_block:
7957     case DW_TAG_catch_block:
7958       read_lexical_block_scope (die, cu);
7959       break;
7960     case DW_TAG_GNU_call_site:
7961       read_call_site_scope (die, cu);
7962       break;
7963     case DW_TAG_class_type:
7964     case DW_TAG_interface_type:
7965     case DW_TAG_structure_type:
7966     case DW_TAG_union_type:
7967       process_structure_scope (die, cu);
7968       break;
7969     case DW_TAG_enumeration_type:
7970       process_enumeration_scope (die, cu);
7971       break;
7972
7973     /* These dies have a type, but processing them does not create
7974        a symbol or recurse to process the children.  Therefore we can
7975        read them on-demand through read_type_die.  */
7976     case DW_TAG_subroutine_type:
7977     case DW_TAG_set_type:
7978     case DW_TAG_array_type:
7979     case DW_TAG_pointer_type:
7980     case DW_TAG_ptr_to_member_type:
7981     case DW_TAG_reference_type:
7982     case DW_TAG_string_type:
7983       break;
7984
7985     case DW_TAG_base_type:
7986     case DW_TAG_subrange_type:
7987     case DW_TAG_typedef:
7988       /* Add a typedef symbol for the type definition, if it has a
7989          DW_AT_name.  */
7990       new_symbol (die, read_type_die (die, cu), cu);
7991       break;
7992     case DW_TAG_common_block:
7993       read_common_block (die, cu);
7994       break;
7995     case DW_TAG_common_inclusion:
7996       break;
7997     case DW_TAG_namespace:
7998       cu->processing_has_namespace_info = 1;
7999       read_namespace (die, cu);
8000       break;
8001     case DW_TAG_module:
8002       cu->processing_has_namespace_info = 1;
8003       read_module (die, cu);
8004       break;
8005     case DW_TAG_imported_declaration:
8006     case DW_TAG_imported_module:
8007       cu->processing_has_namespace_info = 1;
8008       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8009                                  || cu->language != language_fortran))
8010         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8011                    dwarf_tag_name (die->tag));
8012       read_import_statement (die, cu);
8013       break;
8014
8015     case DW_TAG_imported_unit:
8016       process_imported_unit_die (die, cu);
8017       break;
8018
8019     default:
8020       new_symbol (die, NULL, cu);
8021       break;
8022     }
8023 }
8024 \f
8025 /* DWARF name computation.  */
8026
8027 /* A helper function for dwarf2_compute_name which determines whether DIE
8028    needs to have the name of the scope prepended to the name listed in the
8029    die.  */
8030
8031 static int
8032 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8033 {
8034   struct attribute *attr;
8035
8036   switch (die->tag)
8037     {
8038     case DW_TAG_namespace:
8039     case DW_TAG_typedef:
8040     case DW_TAG_class_type:
8041     case DW_TAG_interface_type:
8042     case DW_TAG_structure_type:
8043     case DW_TAG_union_type:
8044     case DW_TAG_enumeration_type:
8045     case DW_TAG_enumerator:
8046     case DW_TAG_subprogram:
8047     case DW_TAG_member:
8048       return 1;
8049
8050     case DW_TAG_variable:
8051     case DW_TAG_constant:
8052       /* We only need to prefix "globally" visible variables.  These include
8053          any variable marked with DW_AT_external or any variable that
8054          lives in a namespace.  [Variables in anonymous namespaces
8055          require prefixing, but they are not DW_AT_external.]  */
8056
8057       if (dwarf2_attr (die, DW_AT_specification, cu))
8058         {
8059           struct dwarf2_cu *spec_cu = cu;
8060
8061           return die_needs_namespace (die_specification (die, &spec_cu),
8062                                       spec_cu);
8063         }
8064
8065       attr = dwarf2_attr (die, DW_AT_external, cu);
8066       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8067           && die->parent->tag != DW_TAG_module)
8068         return 0;
8069       /* A variable in a lexical block of some kind does not need a
8070          namespace, even though in C++ such variables may be external
8071          and have a mangled name.  */
8072       if (die->parent->tag ==  DW_TAG_lexical_block
8073           || die->parent->tag ==  DW_TAG_try_block
8074           || die->parent->tag ==  DW_TAG_catch_block
8075           || die->parent->tag == DW_TAG_subprogram)
8076         return 0;
8077       return 1;
8078
8079     default:
8080       return 0;
8081     }
8082 }
8083
8084 /* Retrieve the last character from a mem_file.  */
8085
8086 static void
8087 do_ui_file_peek_last (void *object, const char *buffer, long length)
8088 {
8089   char *last_char_p = (char *) object;
8090
8091   if (length > 0)
8092     *last_char_p = buffer[length - 1];
8093 }
8094
8095 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8096    compute the physname for the object, which include a method's:
8097    - formal parameters (C++/Java),
8098    - receiver type (Go),
8099    - return type (Java).
8100
8101    The term "physname" is a bit confusing.
8102    For C++, for example, it is the demangled name.
8103    For Go, for example, it's the mangled name.
8104
8105    For Ada, return the DIE's linkage name rather than the fully qualified
8106    name.  PHYSNAME is ignored..
8107
8108    The result is allocated on the objfile_obstack and canonicalized.  */
8109
8110 static const char *
8111 dwarf2_compute_name (const char *name,
8112                      struct die_info *die, struct dwarf2_cu *cu,
8113                      int physname)
8114 {
8115   struct objfile *objfile = cu->objfile;
8116
8117   if (name == NULL)
8118     name = dwarf2_name (die, cu);
8119
8120   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
8121      compute it by typename_concat inside GDB.  */
8122   if (cu->language == language_ada
8123       || (cu->language == language_fortran && physname))
8124     {
8125       /* For Ada unit, we prefer the linkage name over the name, as
8126          the former contains the exported name, which the user expects
8127          to be able to reference.  Ideally, we want the user to be able
8128          to reference this entity using either natural or linkage name,
8129          but we haven't started looking at this enhancement yet.  */
8130       struct attribute *attr;
8131
8132       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8133       if (attr == NULL)
8134         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8135       if (attr && DW_STRING (attr))
8136         return DW_STRING (attr);
8137     }
8138
8139   /* These are the only languages we know how to qualify names in.  */
8140   if (name != NULL
8141       && (cu->language == language_cplus || cu->language == language_java
8142           || cu->language == language_fortran))
8143     {
8144       if (die_needs_namespace (die, cu))
8145         {
8146           long length;
8147           const char *prefix;
8148           struct ui_file *buf;
8149
8150           prefix = determine_prefix (die, cu);
8151           buf = mem_fileopen ();
8152           if (*prefix != '\0')
8153             {
8154               char *prefixed_name = typename_concat (NULL, prefix, name,
8155                                                      physname, cu);
8156
8157               fputs_unfiltered (prefixed_name, buf);
8158               xfree (prefixed_name);
8159             }
8160           else
8161             fputs_unfiltered (name, buf);
8162
8163           /* Template parameters may be specified in the DIE's DW_AT_name, or
8164              as children with DW_TAG_template_type_param or
8165              DW_TAG_value_type_param.  If the latter, add them to the name
8166              here.  If the name already has template parameters, then
8167              skip this step; some versions of GCC emit both, and
8168              it is more efficient to use the pre-computed name.
8169
8170              Something to keep in mind about this process: it is very
8171              unlikely, or in some cases downright impossible, to produce
8172              something that will match the mangled name of a function.
8173              If the definition of the function has the same debug info,
8174              we should be able to match up with it anyway.  But fallbacks
8175              using the minimal symbol, for instance to find a method
8176              implemented in a stripped copy of libstdc++, will not work.
8177              If we do not have debug info for the definition, we will have to
8178              match them up some other way.
8179
8180              When we do name matching there is a related problem with function
8181              templates; two instantiated function templates are allowed to
8182              differ only by their return types, which we do not add here.  */
8183
8184           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8185             {
8186               struct attribute *attr;
8187               struct die_info *child;
8188               int first = 1;
8189
8190               die->building_fullname = 1;
8191
8192               for (child = die->child; child != NULL; child = child->sibling)
8193                 {
8194                   struct type *type;
8195                   LONGEST value;
8196                   const gdb_byte *bytes;
8197                   struct dwarf2_locexpr_baton *baton;
8198                   struct value *v;
8199
8200                   if (child->tag != DW_TAG_template_type_param
8201                       && child->tag != DW_TAG_template_value_param)
8202                     continue;
8203
8204                   if (first)
8205                     {
8206                       fputs_unfiltered ("<", buf);
8207                       first = 0;
8208                     }
8209                   else
8210                     fputs_unfiltered (", ", buf);
8211
8212                   attr = dwarf2_attr (child, DW_AT_type, cu);
8213                   if (attr == NULL)
8214                     {
8215                       complaint (&symfile_complaints,
8216                                  _("template parameter missing DW_AT_type"));
8217                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
8218                       continue;
8219                     }
8220                   type = die_type (child, cu);
8221
8222                   if (child->tag == DW_TAG_template_type_param)
8223                     {
8224                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
8225                       continue;
8226                     }
8227
8228                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8229                   if (attr == NULL)
8230                     {
8231                       complaint (&symfile_complaints,
8232                                  _("template parameter missing "
8233                                    "DW_AT_const_value"));
8234                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8235                       continue;
8236                     }
8237
8238                   dwarf2_const_value_attr (attr, type, name,
8239                                            &cu->comp_unit_obstack, cu,
8240                                            &value, &bytes, &baton);
8241
8242                   if (TYPE_NOSIGN (type))
8243                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8244                        changed, this can use value_print instead.  */
8245                     c_printchar (value, type, buf);
8246                   else
8247                     {
8248                       struct value_print_options opts;
8249
8250                       if (baton != NULL)
8251                         v = dwarf2_evaluate_loc_desc (type, NULL,
8252                                                       baton->data,
8253                                                       baton->size,
8254                                                       baton->per_cu);
8255                       else if (bytes != NULL)
8256                         {
8257                           v = allocate_value (type);
8258                           memcpy (value_contents_writeable (v), bytes,
8259                                   TYPE_LENGTH (type));
8260                         }
8261                       else
8262                         v = value_from_longest (type, value);
8263
8264                       /* Specify decimal so that we do not depend on
8265                          the radix.  */
8266                       get_formatted_print_options (&opts, 'd');
8267                       opts.raw = 1;
8268                       value_print (v, buf, &opts);
8269                       release_value (v);
8270                       value_free (v);
8271                     }
8272                 }
8273
8274               die->building_fullname = 0;
8275
8276               if (!first)
8277                 {
8278                   /* Close the argument list, with a space if necessary
8279                      (nested templates).  */
8280                   char last_char = '\0';
8281                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8282                   if (last_char == '>')
8283                     fputs_unfiltered (" >", buf);
8284                   else
8285                     fputs_unfiltered (">", buf);
8286                 }
8287             }
8288
8289           /* For Java and C++ methods, append formal parameter type
8290              information, if PHYSNAME.  */
8291
8292           if (physname && die->tag == DW_TAG_subprogram
8293               && (cu->language == language_cplus
8294                   || cu->language == language_java))
8295             {
8296               struct type *type = read_type_die (die, cu);
8297
8298               c_type_print_args (type, buf, 1, cu->language,
8299                                  &type_print_raw_options);
8300
8301               if (cu->language == language_java)
8302                 {
8303                   /* For java, we must append the return type to method
8304                      names.  */
8305                   if (die->tag == DW_TAG_subprogram)
8306                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8307                                      0, 0, &type_print_raw_options);
8308                 }
8309               else if (cu->language == language_cplus)
8310                 {
8311                   /* Assume that an artificial first parameter is
8312                      "this", but do not crash if it is not.  RealView
8313                      marks unnamed (and thus unused) parameters as
8314                      artificial; there is no way to differentiate
8315                      the two cases.  */
8316                   if (TYPE_NFIELDS (type) > 0
8317                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8318                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8319                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8320                                                                         0))))
8321                     fputs_unfiltered (" const", buf);
8322                 }
8323             }
8324
8325           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8326                                        &length);
8327           ui_file_delete (buf);
8328
8329           if (cu->language == language_cplus)
8330             {
8331               const char *cname
8332                 = dwarf2_canonicalize_name (name, cu,
8333                                             &objfile->objfile_obstack);
8334
8335               if (cname != NULL)
8336                 name = cname;
8337             }
8338         }
8339     }
8340
8341   return name;
8342 }
8343
8344 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8345    If scope qualifiers are appropriate they will be added.  The result
8346    will be allocated on the objfile_obstack, or NULL if the DIE does
8347    not have a name.  NAME may either be from a previous call to
8348    dwarf2_name or NULL.
8349
8350    The output string will be canonicalized (if C++/Java).  */
8351
8352 static const char *
8353 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8354 {
8355   return dwarf2_compute_name (name, die, cu, 0);
8356 }
8357
8358 /* Construct a physname for the given DIE in CU.  NAME may either be
8359    from a previous call to dwarf2_name or NULL.  The result will be
8360    allocated on the objfile_objstack or NULL if the DIE does not have a
8361    name.
8362
8363    The output string will be canonicalized (if C++/Java).  */
8364
8365 static const char *
8366 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8367 {
8368   struct objfile *objfile = cu->objfile;
8369   struct attribute *attr;
8370   const char *retval, *mangled = NULL, *canon = NULL;
8371   struct cleanup *back_to;
8372   int need_copy = 1;
8373
8374   /* In this case dwarf2_compute_name is just a shortcut not building anything
8375      on its own.  */
8376   if (!die_needs_namespace (die, cu))
8377     return dwarf2_compute_name (name, die, cu, 1);
8378
8379   back_to = make_cleanup (null_cleanup, NULL);
8380
8381   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8382   if (!attr)
8383     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8384
8385   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8386      has computed.  */
8387   if (attr && DW_STRING (attr))
8388     {
8389       char *demangled;
8390
8391       mangled = DW_STRING (attr);
8392
8393       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8394          type.  It is easier for GDB users to search for such functions as
8395          `name(params)' than `long name(params)'.  In such case the minimal
8396          symbol names do not match the full symbol names but for template
8397          functions there is never a need to look up their definition from their
8398          declaration so the only disadvantage remains the minimal symbol
8399          variant `long name(params)' does not have the proper inferior type.
8400          */
8401
8402       if (cu->language == language_go)
8403         {
8404           /* This is a lie, but we already lie to the caller new_symbol_full.
8405              new_symbol_full assumes we return the mangled name.
8406              This just undoes that lie until things are cleaned up.  */
8407           demangled = NULL;
8408         }
8409       else
8410         {
8411           demangled = gdb_demangle (mangled,
8412                                     (DMGL_PARAMS | DMGL_ANSI
8413                                      | (cu->language == language_java
8414                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8415                                         : DMGL_RET_DROP)));
8416         }
8417       if (demangled)
8418         {
8419           make_cleanup (xfree, demangled);
8420           canon = demangled;
8421         }
8422       else
8423         {
8424           canon = mangled;
8425           need_copy = 0;
8426         }
8427     }
8428
8429   if (canon == NULL || check_physname)
8430     {
8431       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8432
8433       if (canon != NULL && strcmp (physname, canon) != 0)
8434         {
8435           /* It may not mean a bug in GDB.  The compiler could also
8436              compute DW_AT_linkage_name incorrectly.  But in such case
8437              GDB would need to be bug-to-bug compatible.  */
8438
8439           complaint (&symfile_complaints,
8440                      _("Computed physname <%s> does not match demangled <%s> "
8441                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8442                      physname, canon, mangled, die->offset.sect_off,
8443                      objfile_name (objfile));
8444
8445           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8446              is available here - over computed PHYSNAME.  It is safer
8447              against both buggy GDB and buggy compilers.  */
8448
8449           retval = canon;
8450         }
8451       else
8452         {
8453           retval = physname;
8454           need_copy = 0;
8455         }
8456     }
8457   else
8458     retval = canon;
8459
8460   if (need_copy)
8461     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8462
8463   do_cleanups (back_to);
8464   return retval;
8465 }
8466
8467 /* Read the import statement specified by the given die and record it.  */
8468
8469 static void
8470 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8471 {
8472   struct objfile *objfile = cu->objfile;
8473   struct attribute *import_attr;
8474   struct die_info *imported_die, *child_die;
8475   struct dwarf2_cu *imported_cu;
8476   const char *imported_name;
8477   const char *imported_name_prefix;
8478   const char *canonical_name;
8479   const char *import_alias;
8480   const char *imported_declaration = NULL;
8481   const char *import_prefix;
8482   VEC (const_char_ptr) *excludes = NULL;
8483   struct cleanup *cleanups;
8484
8485   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8486   if (import_attr == NULL)
8487     {
8488       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8489                  dwarf_tag_name (die->tag));
8490       return;
8491     }
8492
8493   imported_cu = cu;
8494   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8495   imported_name = dwarf2_name (imported_die, imported_cu);
8496   if (imported_name == NULL)
8497     {
8498       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8499
8500         The import in the following code:
8501         namespace A
8502           {
8503             typedef int B;
8504           }
8505
8506         int main ()
8507           {
8508             using A::B;
8509             B b;
8510             return b;
8511           }
8512
8513         ...
8514          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8515             <52>   DW_AT_decl_file   : 1
8516             <53>   DW_AT_decl_line   : 6
8517             <54>   DW_AT_import      : <0x75>
8518          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8519             <59>   DW_AT_name        : B
8520             <5b>   DW_AT_decl_file   : 1
8521             <5c>   DW_AT_decl_line   : 2
8522             <5d>   DW_AT_type        : <0x6e>
8523         ...
8524          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8525             <76>   DW_AT_byte_size   : 4
8526             <77>   DW_AT_encoding    : 5        (signed)
8527
8528         imports the wrong die ( 0x75 instead of 0x58 ).
8529         This case will be ignored until the gcc bug is fixed.  */
8530       return;
8531     }
8532
8533   /* Figure out the local name after import.  */
8534   import_alias = dwarf2_name (die, cu);
8535
8536   /* Figure out where the statement is being imported to.  */
8537   import_prefix = determine_prefix (die, cu);
8538
8539   /* Figure out what the scope of the imported die is and prepend it
8540      to the name of the imported die.  */
8541   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8542
8543   if (imported_die->tag != DW_TAG_namespace
8544       && imported_die->tag != DW_TAG_module)
8545     {
8546       imported_declaration = imported_name;
8547       canonical_name = imported_name_prefix;
8548     }
8549   else if (strlen (imported_name_prefix) > 0)
8550     canonical_name = obconcat (&objfile->objfile_obstack,
8551                                imported_name_prefix, "::", imported_name,
8552                                (char *) NULL);
8553   else
8554     canonical_name = imported_name;
8555
8556   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8557
8558   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8559     for (child_die = die->child; child_die && child_die->tag;
8560          child_die = sibling_die (child_die))
8561       {
8562         /* DWARF-4: A Fortran use statement with a “rename list” may be
8563            represented by an imported module entry with an import attribute
8564            referring to the module and owned entries corresponding to those
8565            entities that are renamed as part of being imported.  */
8566
8567         if (child_die->tag != DW_TAG_imported_declaration)
8568           {
8569             complaint (&symfile_complaints,
8570                        _("child DW_TAG_imported_declaration expected "
8571                          "- DIE at 0x%x [in module %s]"),
8572                        child_die->offset.sect_off, objfile_name (objfile));
8573             continue;
8574           }
8575
8576         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8577         if (import_attr == NULL)
8578           {
8579             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8580                        dwarf_tag_name (child_die->tag));
8581             continue;
8582           }
8583
8584         imported_cu = cu;
8585         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8586                                               &imported_cu);
8587         imported_name = dwarf2_name (imported_die, imported_cu);
8588         if (imported_name == NULL)
8589           {
8590             complaint (&symfile_complaints,
8591                        _("child DW_TAG_imported_declaration has unknown "
8592                          "imported name - DIE at 0x%x [in module %s]"),
8593                        child_die->offset.sect_off, objfile_name (objfile));
8594             continue;
8595           }
8596
8597         VEC_safe_push (const_char_ptr, excludes, imported_name);
8598
8599         process_die (child_die, cu);
8600       }
8601
8602   cp_add_using_directive (import_prefix,
8603                           canonical_name,
8604                           import_alias,
8605                           imported_declaration,
8606                           excludes,
8607                           0,
8608                           &objfile->objfile_obstack);
8609
8610   do_cleanups (cleanups);
8611 }
8612
8613 /* Cleanup function for handle_DW_AT_stmt_list.  */
8614
8615 static void
8616 free_cu_line_header (void *arg)
8617 {
8618   struct dwarf2_cu *cu = arg;
8619
8620   free_line_header (cu->line_header);
8621   cu->line_header = NULL;
8622 }
8623
8624 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8625    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8626    this, it was first present in GCC release 4.3.0.  */
8627
8628 static int
8629 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8630 {
8631   if (!cu->checked_producer)
8632     check_producer (cu);
8633
8634   return cu->producer_is_gcc_lt_4_3;
8635 }
8636
8637 static void
8638 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8639                          const char **name, const char **comp_dir)
8640 {
8641   struct attribute *attr;
8642
8643   *name = NULL;
8644   *comp_dir = NULL;
8645
8646   /* Find the filename.  Do not use dwarf2_name here, since the filename
8647      is not a source language identifier.  */
8648   attr = dwarf2_attr (die, DW_AT_name, cu);
8649   if (attr)
8650     {
8651       *name = DW_STRING (attr);
8652     }
8653
8654   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8655   if (attr)
8656     *comp_dir = DW_STRING (attr);
8657   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8658            && IS_ABSOLUTE_PATH (*name))
8659     {
8660       char *d = ldirname (*name);
8661
8662       *comp_dir = d;
8663       if (d != NULL)
8664         make_cleanup (xfree, d);
8665     }
8666   if (*comp_dir != NULL)
8667     {
8668       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8669          directory, get rid of it.  */
8670       char *cp = strchr (*comp_dir, ':');
8671
8672       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8673         *comp_dir = cp + 1;
8674     }
8675
8676   if (*name == NULL)
8677     *name = "<unknown>";
8678 }
8679
8680 /* Handle DW_AT_stmt_list for a compilation unit.
8681    DIE is the DW_TAG_compile_unit die for CU.
8682    COMP_DIR is the compilation directory.
8683    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8684
8685 static void
8686 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8687                         const char *comp_dir) /* ARI: editCase function */
8688 {
8689   struct attribute *attr;
8690
8691   gdb_assert (! cu->per_cu->is_debug_types);
8692
8693   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8694   if (attr)
8695     {
8696       unsigned int line_offset = DW_UNSND (attr);
8697       struct line_header *line_header
8698         = dwarf_decode_line_header (line_offset, cu);
8699
8700       if (line_header)
8701         {
8702           cu->line_header = line_header;
8703           make_cleanup (free_cu_line_header, cu);
8704           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8705         }
8706     }
8707 }
8708
8709 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8710
8711 static void
8712 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8713 {
8714   struct objfile *objfile = dwarf2_per_objfile->objfile;
8715   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8716   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8717   CORE_ADDR highpc = ((CORE_ADDR) 0);
8718   struct attribute *attr;
8719   const char *name = NULL;
8720   const char *comp_dir = NULL;
8721   struct die_info *child_die;
8722   bfd *abfd = objfile->obfd;
8723   CORE_ADDR baseaddr;
8724
8725   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8726
8727   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8728
8729   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8730      from finish_block.  */
8731   if (lowpc == ((CORE_ADDR) -1))
8732     lowpc = highpc;
8733   lowpc += baseaddr;
8734   highpc += baseaddr;
8735
8736   find_file_and_directory (die, cu, &name, &comp_dir);
8737
8738   prepare_one_comp_unit (cu, die, cu->language);
8739
8740   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8741      standardised yet.  As a workaround for the language detection we fall
8742      back to the DW_AT_producer string.  */
8743   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8744     cu->language = language_opencl;
8745
8746   /* Similar hack for Go.  */
8747   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8748     set_cu_language (DW_LANG_Go, cu);
8749
8750   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8751
8752   /* Decode line number information if present.  We do this before
8753      processing child DIEs, so that the line header table is available
8754      for DW_AT_decl_file.  */
8755   handle_DW_AT_stmt_list (die, cu, comp_dir);
8756
8757   /* Process all dies in compilation unit.  */
8758   if (die->child != NULL)
8759     {
8760       child_die = die->child;
8761       while (child_die && child_die->tag)
8762         {
8763           process_die (child_die, cu);
8764           child_die = sibling_die (child_die);
8765         }
8766     }
8767
8768   /* Decode macro information, if present.  Dwarf 2 macro information
8769      refers to information in the line number info statement program
8770      header, so we can only read it if we've read the header
8771      successfully.  */
8772   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8773   if (attr && cu->line_header)
8774     {
8775       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8776         complaint (&symfile_complaints,
8777                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8778
8779       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8780     }
8781   else
8782     {
8783       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8784       if (attr && cu->line_header)
8785         {
8786           unsigned int macro_offset = DW_UNSND (attr);
8787
8788           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8789         }
8790     }
8791
8792   do_cleanups (back_to);
8793 }
8794
8795 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8796    Create the set of symtabs used by this TU, or if this TU is sharing
8797    symtabs with another TU and the symtabs have already been created
8798    then restore those symtabs in the line header.
8799    We don't need the pc/line-number mapping for type units.  */
8800
8801 static void
8802 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8803 {
8804   struct objfile *objfile = dwarf2_per_objfile->objfile;
8805   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8806   struct type_unit_group *tu_group;
8807   int first_time;
8808   struct line_header *lh;
8809   struct attribute *attr;
8810   unsigned int i, line_offset;
8811   struct signatured_type *sig_type;
8812
8813   gdb_assert (per_cu->is_debug_types);
8814   sig_type = (struct signatured_type *) per_cu;
8815
8816   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8817
8818   /* If we're using .gdb_index (includes -readnow) then
8819      per_cu->type_unit_group may not have been set up yet.  */
8820   if (sig_type->type_unit_group == NULL)
8821     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8822   tu_group = sig_type->type_unit_group;
8823
8824   /* If we've already processed this stmt_list there's no real need to
8825      do it again, we could fake it and just recreate the part we need
8826      (file name,index -> symtab mapping).  If data shows this optimization
8827      is useful we can do it then.  */
8828   first_time = tu_group->primary_symtab == NULL;
8829
8830   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8831      debug info.  */
8832   lh = NULL;
8833   if (attr != NULL)
8834     {
8835       line_offset = DW_UNSND (attr);
8836       lh = dwarf_decode_line_header (line_offset, cu);
8837     }
8838   if (lh == NULL)
8839     {
8840       if (first_time)
8841         dwarf2_start_symtab (cu, "", NULL, 0);
8842       else
8843         {
8844           gdb_assert (tu_group->symtabs == NULL);
8845           restart_symtab (0);
8846         }
8847       /* Note: The primary symtab will get allocated at the end.  */
8848       return;
8849     }
8850
8851   cu->line_header = lh;
8852   make_cleanup (free_cu_line_header, cu);
8853
8854   if (first_time)
8855     {
8856       dwarf2_start_symtab (cu, "", NULL, 0);
8857
8858       tu_group->num_symtabs = lh->num_file_names;
8859       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8860
8861       for (i = 0; i < lh->num_file_names; ++i)
8862         {
8863           const char *dir = NULL;
8864           struct file_entry *fe = &lh->file_names[i];
8865
8866           if (fe->dir_index)
8867             dir = lh->include_dirs[fe->dir_index - 1];
8868           dwarf2_start_subfile (fe->name, dir, NULL);
8869
8870           /* Note: We don't have to watch for the main subfile here, type units
8871              don't have DW_AT_name.  */
8872
8873           if (current_subfile->symtab == NULL)
8874             {
8875               /* NOTE: start_subfile will recognize when it's been passed
8876                  a file it has already seen.  So we can't assume there's a
8877                  simple mapping from lh->file_names to subfiles,
8878                  lh->file_names may contain dups.  */
8879               current_subfile->symtab = allocate_symtab (current_subfile->name,
8880                                                          objfile);
8881             }
8882
8883           fe->symtab = current_subfile->symtab;
8884           tu_group->symtabs[i] = fe->symtab;
8885         }
8886     }
8887   else
8888     {
8889       restart_symtab (0);
8890
8891       for (i = 0; i < lh->num_file_names; ++i)
8892         {
8893           struct file_entry *fe = &lh->file_names[i];
8894
8895           fe->symtab = tu_group->symtabs[i];
8896         }
8897     }
8898
8899   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8900      so they don't have a "real" (so to speak) symtab anyway.
8901      There is later code that will assign the main symtab to all symbols
8902      that don't have one.  We need to handle the case of a symbol with a
8903      missing symtab (DW_AT_decl_file) anyway.  */
8904 }
8905
8906 /* Process DW_TAG_type_unit.
8907    For TUs we want to skip the first top level sibling if it's not the
8908    actual type being defined by this TU.  In this case the first top
8909    level sibling is there to provide context only.  */
8910
8911 static void
8912 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8913 {
8914   struct die_info *child_die;
8915
8916   prepare_one_comp_unit (cu, die, language_minimal);
8917
8918   /* Initialize (or reinitialize) the machinery for building symtabs.
8919      We do this before processing child DIEs, so that the line header table
8920      is available for DW_AT_decl_file.  */
8921   setup_type_unit_groups (die, cu);
8922
8923   if (die->child != NULL)
8924     {
8925       child_die = die->child;
8926       while (child_die && child_die->tag)
8927         {
8928           process_die (child_die, cu);
8929           child_die = sibling_die (child_die);
8930         }
8931     }
8932 }
8933 \f
8934 /* DWO/DWP files.
8935
8936    http://gcc.gnu.org/wiki/DebugFission
8937    http://gcc.gnu.org/wiki/DebugFissionDWP
8938
8939    To simplify handling of both DWO files ("object" files with the DWARF info)
8940    and DWP files (a file with the DWOs packaged up into one file), we treat
8941    DWP files as having a collection of virtual DWO files.  */
8942
8943 static hashval_t
8944 hash_dwo_file (const void *item)
8945 {
8946   const struct dwo_file *dwo_file = item;
8947   hashval_t hash;
8948
8949   hash = htab_hash_string (dwo_file->dwo_name);
8950   if (dwo_file->comp_dir != NULL)
8951     hash += htab_hash_string (dwo_file->comp_dir);
8952   return hash;
8953 }
8954
8955 static int
8956 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8957 {
8958   const struct dwo_file *lhs = item_lhs;
8959   const struct dwo_file *rhs = item_rhs;
8960
8961   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8962     return 0;
8963   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8964     return lhs->comp_dir == rhs->comp_dir;
8965   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8966 }
8967
8968 /* Allocate a hash table for DWO files.  */
8969
8970 static htab_t
8971 allocate_dwo_file_hash_table (void)
8972 {
8973   struct objfile *objfile = dwarf2_per_objfile->objfile;
8974
8975   return htab_create_alloc_ex (41,
8976                                hash_dwo_file,
8977                                eq_dwo_file,
8978                                NULL,
8979                                &objfile->objfile_obstack,
8980                                hashtab_obstack_allocate,
8981                                dummy_obstack_deallocate);
8982 }
8983
8984 /* Lookup DWO file DWO_NAME.  */
8985
8986 static void **
8987 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8988 {
8989   struct dwo_file find_entry;
8990   void **slot;
8991
8992   if (dwarf2_per_objfile->dwo_files == NULL)
8993     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8994
8995   memset (&find_entry, 0, sizeof (find_entry));
8996   find_entry.dwo_name = dwo_name;
8997   find_entry.comp_dir = comp_dir;
8998   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8999
9000   return slot;
9001 }
9002
9003 static hashval_t
9004 hash_dwo_unit (const void *item)
9005 {
9006   const struct dwo_unit *dwo_unit = item;
9007
9008   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9009   return dwo_unit->signature;
9010 }
9011
9012 static int
9013 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9014 {
9015   const struct dwo_unit *lhs = item_lhs;
9016   const struct dwo_unit *rhs = item_rhs;
9017
9018   /* The signature is assumed to be unique within the DWO file.
9019      So while object file CU dwo_id's always have the value zero,
9020      that's OK, assuming each object file DWO file has only one CU,
9021      and that's the rule for now.  */
9022   return lhs->signature == rhs->signature;
9023 }
9024
9025 /* Allocate a hash table for DWO CUs,TUs.
9026    There is one of these tables for each of CUs,TUs for each DWO file.  */
9027
9028 static htab_t
9029 allocate_dwo_unit_table (struct objfile *objfile)
9030 {
9031   /* Start out with a pretty small number.
9032      Generally DWO files contain only one CU and maybe some TUs.  */
9033   return htab_create_alloc_ex (3,
9034                                hash_dwo_unit,
9035                                eq_dwo_unit,
9036                                NULL,
9037                                &objfile->objfile_obstack,
9038                                hashtab_obstack_allocate,
9039                                dummy_obstack_deallocate);
9040 }
9041
9042 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9043
9044 struct create_dwo_cu_data
9045 {
9046   struct dwo_file *dwo_file;
9047   struct dwo_unit dwo_unit;
9048 };
9049
9050 /* die_reader_func for create_dwo_cu.  */
9051
9052 static void
9053 create_dwo_cu_reader (const struct die_reader_specs *reader,
9054                       const gdb_byte *info_ptr,
9055                       struct die_info *comp_unit_die,
9056                       int has_children,
9057                       void *datap)
9058 {
9059   struct dwarf2_cu *cu = reader->cu;
9060   struct objfile *objfile = dwarf2_per_objfile->objfile;
9061   sect_offset offset = cu->per_cu->offset;
9062   struct dwarf2_section_info *section = cu->per_cu->section;
9063   struct create_dwo_cu_data *data = datap;
9064   struct dwo_file *dwo_file = data->dwo_file;
9065   struct dwo_unit *dwo_unit = &data->dwo_unit;
9066   struct attribute *attr;
9067
9068   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9069   if (attr == NULL)
9070     {
9071       complaint (&symfile_complaints,
9072                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9073                    " its dwo_id [in module %s]"),
9074                  offset.sect_off, dwo_file->dwo_name);
9075       return;
9076     }
9077
9078   dwo_unit->dwo_file = dwo_file;
9079   dwo_unit->signature = DW_UNSND (attr);
9080   dwo_unit->section = section;
9081   dwo_unit->offset = offset;
9082   dwo_unit->length = cu->per_cu->length;
9083
9084   if (dwarf2_read_debug)
9085     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9086                         offset.sect_off, hex_string (dwo_unit->signature));
9087 }
9088
9089 /* Create the dwo_unit for the lone CU in DWO_FILE.
9090    Note: This function processes DWO files only, not DWP files.  */
9091
9092 static struct dwo_unit *
9093 create_dwo_cu (struct dwo_file *dwo_file)
9094 {
9095   struct objfile *objfile = dwarf2_per_objfile->objfile;
9096   struct dwarf2_section_info *section = &dwo_file->sections.info;
9097   bfd *abfd;
9098   htab_t cu_htab;
9099   const gdb_byte *info_ptr, *end_ptr;
9100   struct create_dwo_cu_data create_dwo_cu_data;
9101   struct dwo_unit *dwo_unit;
9102
9103   dwarf2_read_section (objfile, section);
9104   info_ptr = section->buffer;
9105
9106   if (info_ptr == NULL)
9107     return NULL;
9108
9109   /* We can't set abfd until now because the section may be empty or
9110      not present, in which case section->asection will be NULL.  */
9111   abfd = get_section_bfd_owner (section);
9112
9113   if (dwarf2_read_debug)
9114     {
9115       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9116                           get_section_name (section),
9117                           get_section_file_name (section));
9118     }
9119
9120   create_dwo_cu_data.dwo_file = dwo_file;
9121   dwo_unit = NULL;
9122
9123   end_ptr = info_ptr + section->size;
9124   while (info_ptr < end_ptr)
9125     {
9126       struct dwarf2_per_cu_data per_cu;
9127
9128       memset (&create_dwo_cu_data.dwo_unit, 0,
9129               sizeof (create_dwo_cu_data.dwo_unit));
9130       memset (&per_cu, 0, sizeof (per_cu));
9131       per_cu.objfile = objfile;
9132       per_cu.is_debug_types = 0;
9133       per_cu.offset.sect_off = info_ptr - section->buffer;
9134       per_cu.section = section;
9135
9136       init_cutu_and_read_dies_no_follow (&per_cu,
9137                                          &dwo_file->sections.abbrev,
9138                                          dwo_file,
9139                                          create_dwo_cu_reader,
9140                                          &create_dwo_cu_data);
9141
9142       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
9143         {
9144           /* If we've already found one, complain.  We only support one
9145              because having more than one requires hacking the dwo_name of
9146              each to match, which is highly unlikely to happen.  */
9147           if (dwo_unit != NULL)
9148             {
9149               complaint (&symfile_complaints,
9150                          _("Multiple CUs in DWO file %s [in module %s]"),
9151                          dwo_file->dwo_name, objfile_name (objfile));
9152               break;
9153             }
9154
9155           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9156           *dwo_unit = create_dwo_cu_data.dwo_unit;
9157         }
9158
9159       info_ptr += per_cu.length;
9160     }
9161
9162   return dwo_unit;
9163 }
9164
9165 /* DWP file .debug_{cu,tu}_index section format:
9166    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9167
9168    DWP Version 1:
9169
9170    Both index sections have the same format, and serve to map a 64-bit
9171    signature to a set of section numbers.  Each section begins with a header,
9172    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9173    indexes, and a pool of 32-bit section numbers.  The index sections will be
9174    aligned at 8-byte boundaries in the file.
9175
9176    The index section header consists of:
9177
9178     V, 32 bit version number
9179     -, 32 bits unused
9180     N, 32 bit number of compilation units or type units in the index
9181     M, 32 bit number of slots in the hash table
9182
9183    Numbers are recorded using the byte order of the application binary.
9184
9185    The hash table begins at offset 16 in the section, and consists of an array
9186    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9187    order of the application binary).  Unused slots in the hash table are 0.
9188    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9189
9190    The parallel table begins immediately after the hash table
9191    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9192    array of 32-bit indexes (using the byte order of the application binary),
9193    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9194    table contains a 32-bit index into the pool of section numbers.  For unused
9195    hash table slots, the corresponding entry in the parallel table will be 0.
9196
9197    The pool of section numbers begins immediately following the hash table
9198    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9199    section numbers consists of an array of 32-bit words (using the byte order
9200    of the application binary).  Each item in the array is indexed starting
9201    from 0.  The hash table entry provides the index of the first section
9202    number in the set.  Additional section numbers in the set follow, and the
9203    set is terminated by a 0 entry (section number 0 is not used in ELF).
9204
9205    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9206    section must be the first entry in the set, and the .debug_abbrev.dwo must
9207    be the second entry. Other members of the set may follow in any order.
9208
9209    ---
9210
9211    DWP Version 2:
9212
9213    DWP Version 2 combines all the .debug_info, etc. sections into one,
9214    and the entries in the index tables are now offsets into these sections.
9215    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9216    section.
9217
9218    Index Section Contents:
9219     Header
9220     Hash Table of Signatures   dwp_hash_table.hash_table
9221     Parallel Table of Indices  dwp_hash_table.unit_table
9222     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9223     Table of Section Sizes     dwp_hash_table.v2.sizes
9224
9225    The index section header consists of:
9226
9227     V, 32 bit version number
9228     L, 32 bit number of columns in the table of section offsets
9229     N, 32 bit number of compilation units or type units in the index
9230     M, 32 bit number of slots in the hash table
9231
9232    Numbers are recorded using the byte order of the application binary.
9233
9234    The hash table has the same format as version 1.
9235    The parallel table of indices has the same format as version 1,
9236    except that the entries are origin-1 indices into the table of sections
9237    offsets and the table of section sizes.
9238
9239    The table of offsets begins immediately following the parallel table
9240    (at offset 16 + 12 * M from the beginning of the section).  The table is
9241    a two-dimensional array of 32-bit words (using the byte order of the
9242    application binary), with L columns and N+1 rows, in row-major order.
9243    Each row in the array is indexed starting from 0.  The first row provides
9244    a key to the remaining rows: each column in this row provides an identifier
9245    for a debug section, and the offsets in the same column of subsequent rows
9246    refer to that section.  The section identifiers are:
9247
9248     DW_SECT_INFO         1  .debug_info.dwo
9249     DW_SECT_TYPES        2  .debug_types.dwo
9250     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9251     DW_SECT_LINE         4  .debug_line.dwo
9252     DW_SECT_LOC          5  .debug_loc.dwo
9253     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9254     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9255     DW_SECT_MACRO        8  .debug_macro.dwo
9256
9257    The offsets provided by the CU and TU index sections are the base offsets
9258    for the contributions made by each CU or TU to the corresponding section
9259    in the package file.  Each CU and TU header contains an abbrev_offset
9260    field, used to find the abbreviations table for that CU or TU within the
9261    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9262    be interpreted as relative to the base offset given in the index section.
9263    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9264    should be interpreted as relative to the base offset for .debug_line.dwo,
9265    and offsets into other debug sections obtained from DWARF attributes should
9266    also be interpreted as relative to the corresponding base offset.
9267
9268    The table of sizes begins immediately following the table of offsets.
9269    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9270    with L columns and N rows, in row-major order.  Each row in the array is
9271    indexed starting from 1 (row 0 is shared by the two tables).
9272
9273    ---
9274
9275    Hash table lookup is handled the same in version 1 and 2:
9276
9277    We assume that N and M will not exceed 2^32 - 1.
9278    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9279
9280    Given a 64-bit compilation unit signature or a type signature S, an entry
9281    in the hash table is located as follows:
9282
9283    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9284       the low-order k bits all set to 1.
9285
9286    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9287
9288    3) If the hash table entry at index H matches the signature, use that
9289       entry.  If the hash table entry at index H is unused (all zeroes),
9290       terminate the search: the signature is not present in the table.
9291
9292    4) Let H = (H + H') modulo M. Repeat at Step 3.
9293
9294    Because M > N and H' and M are relatively prime, the search is guaranteed
9295    to stop at an unused slot or find the match.  */
9296
9297 /* Create a hash table to map DWO IDs to their CU/TU entry in
9298    .debug_{info,types}.dwo in DWP_FILE.
9299    Returns NULL if there isn't one.
9300    Note: This function processes DWP files only, not DWO files.  */
9301
9302 static struct dwp_hash_table *
9303 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9304 {
9305   struct objfile *objfile = dwarf2_per_objfile->objfile;
9306   bfd *dbfd = dwp_file->dbfd;
9307   const gdb_byte *index_ptr, *index_end;
9308   struct dwarf2_section_info *index;
9309   uint32_t version, nr_columns, nr_units, nr_slots;
9310   struct dwp_hash_table *htab;
9311
9312   if (is_debug_types)
9313     index = &dwp_file->sections.tu_index;
9314   else
9315     index = &dwp_file->sections.cu_index;
9316
9317   if (dwarf2_section_empty_p (index))
9318     return NULL;
9319   dwarf2_read_section (objfile, index);
9320
9321   index_ptr = index->buffer;
9322   index_end = index_ptr + index->size;
9323
9324   version = read_4_bytes (dbfd, index_ptr);
9325   index_ptr += 4;
9326   if (version == 2)
9327     nr_columns = read_4_bytes (dbfd, index_ptr);
9328   else
9329     nr_columns = 0;
9330   index_ptr += 4;
9331   nr_units = read_4_bytes (dbfd, index_ptr);
9332   index_ptr += 4;
9333   nr_slots = read_4_bytes (dbfd, index_ptr);
9334   index_ptr += 4;
9335
9336   if (version != 1 && version != 2)
9337     {
9338       error (_("Dwarf Error: unsupported DWP file version (%s)"
9339                " [in module %s]"),
9340              pulongest (version), dwp_file->name);
9341     }
9342   if (nr_slots != (nr_slots & -nr_slots))
9343     {
9344       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9345                " is not power of 2 [in module %s]"),
9346              pulongest (nr_slots), dwp_file->name);
9347     }
9348
9349   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9350   htab->version = version;
9351   htab->nr_columns = nr_columns;
9352   htab->nr_units = nr_units;
9353   htab->nr_slots = nr_slots;
9354   htab->hash_table = index_ptr;
9355   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9356
9357   /* Exit early if the table is empty.  */
9358   if (nr_slots == 0 || nr_units == 0
9359       || (version == 2 && nr_columns == 0))
9360     {
9361       /* All must be zero.  */
9362       if (nr_slots != 0 || nr_units != 0
9363           || (version == 2 && nr_columns != 0))
9364         {
9365           complaint (&symfile_complaints,
9366                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
9367                        " all zero [in modules %s]"),
9368                      dwp_file->name);
9369         }
9370       return htab;
9371     }
9372
9373   if (version == 1)
9374     {
9375       htab->section_pool.v1.indices =
9376         htab->unit_table + sizeof (uint32_t) * nr_slots;
9377       /* It's harder to decide whether the section is too small in v1.
9378          V1 is deprecated anyway so we punt.  */
9379     }
9380   else
9381     {
9382       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
9383       int *ids = htab->section_pool.v2.section_ids;
9384       /* Reverse map for error checking.  */
9385       int ids_seen[DW_SECT_MAX + 1];
9386       int i;
9387
9388       if (nr_columns < 2)
9389         {
9390           error (_("Dwarf Error: bad DWP hash table, too few columns"
9391                    " in section table [in module %s]"),
9392                  dwp_file->name);
9393         }
9394       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
9395         {
9396           error (_("Dwarf Error: bad DWP hash table, too many columns"
9397                    " in section table [in module %s]"),
9398                  dwp_file->name);
9399         }
9400       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9401       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9402       for (i = 0; i < nr_columns; ++i)
9403         {
9404           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
9405
9406           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
9407             {
9408               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
9409                        " in section table [in module %s]"),
9410                      id, dwp_file->name);
9411             }
9412           if (ids_seen[id] != -1)
9413             {
9414               error (_("Dwarf Error: bad DWP hash table, duplicate section"
9415                        " id %d in section table [in module %s]"),
9416                      id, dwp_file->name);
9417             }
9418           ids_seen[id] = i;
9419           ids[i] = id;
9420         }
9421       /* Must have exactly one info or types section.  */
9422       if (((ids_seen[DW_SECT_INFO] != -1)
9423            + (ids_seen[DW_SECT_TYPES] != -1))
9424           != 1)
9425         {
9426           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
9427                    " DWO info/types section [in module %s]"),
9428                  dwp_file->name);
9429         }
9430       /* Must have an abbrev section.  */
9431       if (ids_seen[DW_SECT_ABBREV] == -1)
9432         {
9433           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
9434                    " section [in module %s]"),
9435                  dwp_file->name);
9436         }
9437       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
9438       htab->section_pool.v2.sizes =
9439         htab->section_pool.v2.offsets + (sizeof (uint32_t)
9440                                          * nr_units * nr_columns);
9441       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
9442                                           * nr_units * nr_columns))
9443           > index_end)
9444         {
9445           error (_("Dwarf Error: DWP index section is corrupt (too small)"
9446                    " [in module %s]"),
9447                  dwp_file->name);
9448         }
9449     }
9450
9451   return htab;
9452 }
9453
9454 /* Update SECTIONS with the data from SECTP.
9455
9456    This function is like the other "locate" section routines that are
9457    passed to bfd_map_over_sections, but in this context the sections to
9458    read comes from the DWP V1 hash table, not the full ELF section table.
9459
9460    The result is non-zero for success, or zero if an error was found.  */
9461
9462 static int
9463 locate_v1_virtual_dwo_sections (asection *sectp,
9464                                 struct virtual_v1_dwo_sections *sections)
9465 {
9466   const struct dwop_section_names *names = &dwop_section_names;
9467
9468   if (section_is_p (sectp->name, &names->abbrev_dwo))
9469     {
9470       /* There can be only one.  */
9471       if (sections->abbrev.s.asection != NULL)
9472         return 0;
9473       sections->abbrev.s.asection = sectp;
9474       sections->abbrev.size = bfd_get_section_size (sectp);
9475     }
9476   else if (section_is_p (sectp->name, &names->info_dwo)
9477            || section_is_p (sectp->name, &names->types_dwo))
9478     {
9479       /* There can be only one.  */
9480       if (sections->info_or_types.s.asection != NULL)
9481         return 0;
9482       sections->info_or_types.s.asection = sectp;
9483       sections->info_or_types.size = bfd_get_section_size (sectp);
9484     }
9485   else if (section_is_p (sectp->name, &names->line_dwo))
9486     {
9487       /* There can be only one.  */
9488       if (sections->line.s.asection != NULL)
9489         return 0;
9490       sections->line.s.asection = sectp;
9491       sections->line.size = bfd_get_section_size (sectp);
9492     }
9493   else if (section_is_p (sectp->name, &names->loc_dwo))
9494     {
9495       /* There can be only one.  */
9496       if (sections->loc.s.asection != NULL)
9497         return 0;
9498       sections->loc.s.asection = sectp;
9499       sections->loc.size = bfd_get_section_size (sectp);
9500     }
9501   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9502     {
9503       /* There can be only one.  */
9504       if (sections->macinfo.s.asection != NULL)
9505         return 0;
9506       sections->macinfo.s.asection = sectp;
9507       sections->macinfo.size = bfd_get_section_size (sectp);
9508     }
9509   else if (section_is_p (sectp->name, &names->macro_dwo))
9510     {
9511       /* There can be only one.  */
9512       if (sections->macro.s.asection != NULL)
9513         return 0;
9514       sections->macro.s.asection = sectp;
9515       sections->macro.size = bfd_get_section_size (sectp);
9516     }
9517   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9518     {
9519       /* There can be only one.  */
9520       if (sections->str_offsets.s.asection != NULL)
9521         return 0;
9522       sections->str_offsets.s.asection = sectp;
9523       sections->str_offsets.size = bfd_get_section_size (sectp);
9524     }
9525   else
9526     {
9527       /* No other kind of section is valid.  */
9528       return 0;
9529     }
9530
9531   return 1;
9532 }
9533
9534 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9535    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9536    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9537    This is for DWP version 1 files.  */
9538
9539 static struct dwo_unit *
9540 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
9541                            uint32_t unit_index,
9542                            const char *comp_dir,
9543                            ULONGEST signature, int is_debug_types)
9544 {
9545   struct objfile *objfile = dwarf2_per_objfile->objfile;
9546   const struct dwp_hash_table *dwp_htab =
9547     is_debug_types ? dwp_file->tus : dwp_file->cus;
9548   bfd *dbfd = dwp_file->dbfd;
9549   const char *kind = is_debug_types ? "TU" : "CU";
9550   struct dwo_file *dwo_file;
9551   struct dwo_unit *dwo_unit;
9552   struct virtual_v1_dwo_sections sections;
9553   void **dwo_file_slot;
9554   char *virtual_dwo_name;
9555   struct dwarf2_section_info *cutu;
9556   struct cleanup *cleanups;
9557   int i;
9558
9559   gdb_assert (dwp_file->version == 1);
9560
9561   if (dwarf2_read_debug)
9562     {
9563       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
9564                           kind,
9565                           pulongest (unit_index), hex_string (signature),
9566                           dwp_file->name);
9567     }
9568
9569   /* Fetch the sections of this DWO unit.
9570      Put a limit on the number of sections we look for so that bad data
9571      doesn't cause us to loop forever.  */
9572
9573 #define MAX_NR_V1_DWO_SECTIONS \
9574   (1 /* .debug_info or .debug_types */ \
9575    + 1 /* .debug_abbrev */ \
9576    + 1 /* .debug_line */ \
9577    + 1 /* .debug_loc */ \
9578    + 1 /* .debug_str_offsets */ \
9579    + 1 /* .debug_macro or .debug_macinfo */ \
9580    + 1 /* trailing zero */)
9581
9582   memset (&sections, 0, sizeof (sections));
9583   cleanups = make_cleanup (null_cleanup, 0);
9584
9585   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
9586     {
9587       asection *sectp;
9588       uint32_t section_nr =
9589         read_4_bytes (dbfd,
9590                       dwp_htab->section_pool.v1.indices
9591                       + (unit_index + i) * sizeof (uint32_t));
9592
9593       if (section_nr == 0)
9594         break;
9595       if (section_nr >= dwp_file->num_sections)
9596         {
9597           error (_("Dwarf Error: bad DWP hash table, section number too large"
9598                    " [in module %s]"),
9599                  dwp_file->name);
9600         }
9601
9602       sectp = dwp_file->elf_sections[section_nr];
9603       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
9604         {
9605           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9606                    " [in module %s]"),
9607                  dwp_file->name);
9608         }
9609     }
9610
9611   if (i < 2
9612       || dwarf2_section_empty_p (&sections.info_or_types)
9613       || dwarf2_section_empty_p (&sections.abbrev))
9614     {
9615       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9616                " [in module %s]"),
9617              dwp_file->name);
9618     }
9619   if (i == MAX_NR_V1_DWO_SECTIONS)
9620     {
9621       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9622                " [in module %s]"),
9623              dwp_file->name);
9624     }
9625
9626   /* It's easier for the rest of the code if we fake a struct dwo_file and
9627      have dwo_unit "live" in that.  At least for now.
9628
9629      The DWP file can be made up of a random collection of CUs and TUs.
9630      However, for each CU + set of TUs that came from the same original DWO
9631      file, we can combine them back into a virtual DWO file to save space
9632      (fewer struct dwo_file objects to allocate).  Remember that for really
9633      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9634
9635   virtual_dwo_name =
9636     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9637                 get_section_id (&sections.abbrev),
9638                 get_section_id (&sections.line),
9639                 get_section_id (&sections.loc),
9640                 get_section_id (&sections.str_offsets));
9641   make_cleanup (xfree, virtual_dwo_name);
9642   /* Can we use an existing virtual DWO file?  */
9643   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9644   /* Create one if necessary.  */
9645   if (*dwo_file_slot == NULL)
9646     {
9647       if (dwarf2_read_debug)
9648         {
9649           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9650                               virtual_dwo_name);
9651         }
9652       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9653       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9654                                           virtual_dwo_name,
9655                                           strlen (virtual_dwo_name));
9656       dwo_file->comp_dir = comp_dir;
9657       dwo_file->sections.abbrev = sections.abbrev;
9658       dwo_file->sections.line = sections.line;
9659       dwo_file->sections.loc = sections.loc;
9660       dwo_file->sections.macinfo = sections.macinfo;
9661       dwo_file->sections.macro = sections.macro;
9662       dwo_file->sections.str_offsets = sections.str_offsets;
9663       /* The "str" section is global to the entire DWP file.  */
9664       dwo_file->sections.str = dwp_file->sections.str;
9665       /* The info or types section is assigned below to dwo_unit,
9666          there's no need to record it in dwo_file.
9667          Also, we can't simply record type sections in dwo_file because
9668          we record a pointer into the vector in dwo_unit.  As we collect more
9669          types we'll grow the vector and eventually have to reallocate space
9670          for it, invalidating all copies of pointers into the previous
9671          contents.  */
9672       *dwo_file_slot = dwo_file;
9673     }
9674   else
9675     {
9676       if (dwarf2_read_debug)
9677         {
9678           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9679                               virtual_dwo_name);
9680         }
9681       dwo_file = *dwo_file_slot;
9682     }
9683   do_cleanups (cleanups);
9684
9685   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9686   dwo_unit->dwo_file = dwo_file;
9687   dwo_unit->signature = signature;
9688   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9689                                      sizeof (struct dwarf2_section_info));
9690   *dwo_unit->section = sections.info_or_types;
9691   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9692
9693   return dwo_unit;
9694 }
9695
9696 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
9697    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
9698    piece within that section used by a TU/CU, return a virtual section
9699    of just that piece.  */
9700
9701 static struct dwarf2_section_info
9702 create_dwp_v2_section (struct dwarf2_section_info *section,
9703                        bfd_size_type offset, bfd_size_type size)
9704 {
9705   struct dwarf2_section_info result;
9706   asection *sectp;
9707
9708   gdb_assert (section != NULL);
9709   gdb_assert (!section->is_virtual);
9710
9711   memset (&result, 0, sizeof (result));
9712   result.s.containing_section = section;
9713   result.is_virtual = 1;
9714
9715   if (size == 0)
9716     return result;
9717
9718   sectp = get_section_bfd_section (section);
9719
9720   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
9721      bounds of the real section.  This is a pretty-rare event, so just
9722      flag an error (easier) instead of a warning and trying to cope.  */
9723   if (sectp == NULL
9724       || offset + size > bfd_get_section_size (sectp))
9725     {
9726       bfd *abfd = sectp->owner;
9727
9728       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
9729                " in section %s [in module %s]"),
9730              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
9731              objfile_name (dwarf2_per_objfile->objfile));
9732     }
9733
9734   result.virtual_offset = offset;
9735   result.size = size;
9736   return result;
9737 }
9738
9739 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9740    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9741    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9742    This is for DWP version 2 files.  */
9743
9744 static struct dwo_unit *
9745 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
9746                            uint32_t unit_index,
9747                            const char *comp_dir,
9748                            ULONGEST signature, int is_debug_types)
9749 {
9750   struct objfile *objfile = dwarf2_per_objfile->objfile;
9751   const struct dwp_hash_table *dwp_htab =
9752     is_debug_types ? dwp_file->tus : dwp_file->cus;
9753   bfd *dbfd = dwp_file->dbfd;
9754   const char *kind = is_debug_types ? "TU" : "CU";
9755   struct dwo_file *dwo_file;
9756   struct dwo_unit *dwo_unit;
9757   struct virtual_v2_dwo_sections sections;
9758   void **dwo_file_slot;
9759   char *virtual_dwo_name;
9760   struct dwarf2_section_info *cutu;
9761   struct cleanup *cleanups;
9762   int i;
9763
9764   gdb_assert (dwp_file->version == 2);
9765
9766   if (dwarf2_read_debug)
9767     {
9768       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
9769                           kind,
9770                           pulongest (unit_index), hex_string (signature),
9771                           dwp_file->name);
9772     }
9773
9774   /* Fetch the section offsets of this DWO unit.  */
9775
9776   memset (&sections, 0, sizeof (sections));
9777   cleanups = make_cleanup (null_cleanup, 0);
9778
9779   for (i = 0; i < dwp_htab->nr_columns; ++i)
9780     {
9781       uint32_t offset = read_4_bytes (dbfd,
9782                                       dwp_htab->section_pool.v2.offsets
9783                                       + (((unit_index - 1) * dwp_htab->nr_columns
9784                                           + i)
9785                                          * sizeof (uint32_t)));
9786       uint32_t size = read_4_bytes (dbfd,
9787                                     dwp_htab->section_pool.v2.sizes
9788                                     + (((unit_index - 1) * dwp_htab->nr_columns
9789                                         + i)
9790                                        * sizeof (uint32_t)));
9791
9792       switch (dwp_htab->section_pool.v2.section_ids[i])
9793         {
9794         case DW_SECT_INFO:
9795         case DW_SECT_TYPES:
9796           sections.info_or_types_offset = offset;
9797           sections.info_or_types_size = size;
9798           break;
9799         case DW_SECT_ABBREV:
9800           sections.abbrev_offset = offset;
9801           sections.abbrev_size = size;
9802           break;
9803         case DW_SECT_LINE:
9804           sections.line_offset = offset;
9805           sections.line_size = size;
9806           break;
9807         case DW_SECT_LOC:
9808           sections.loc_offset = offset;
9809           sections.loc_size = size;
9810           break;
9811         case DW_SECT_STR_OFFSETS:
9812           sections.str_offsets_offset = offset;
9813           sections.str_offsets_size = size;
9814           break;
9815         case DW_SECT_MACINFO:
9816           sections.macinfo_offset = offset;
9817           sections.macinfo_size = size;
9818           break;
9819         case DW_SECT_MACRO:
9820           sections.macro_offset = offset;
9821           sections.macro_size = size;
9822           break;
9823         }
9824     }
9825
9826   /* It's easier for the rest of the code if we fake a struct dwo_file and
9827      have dwo_unit "live" in that.  At least for now.
9828
9829      The DWP file can be made up of a random collection of CUs and TUs.
9830      However, for each CU + set of TUs that came from the same original DWO
9831      file, we can combine them back into a virtual DWO file to save space
9832      (fewer struct dwo_file objects to allocate).  Remember that for really
9833      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9834
9835   virtual_dwo_name =
9836     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
9837                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
9838                 (long) (sections.line_size ? sections.line_offset : 0),
9839                 (long) (sections.loc_size ? sections.loc_offset : 0),
9840                 (long) (sections.str_offsets_size
9841                         ? sections.str_offsets_offset : 0));
9842   make_cleanup (xfree, virtual_dwo_name);
9843   /* Can we use an existing virtual DWO file?  */
9844   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9845   /* Create one if necessary.  */
9846   if (*dwo_file_slot == NULL)
9847     {
9848       if (dwarf2_read_debug)
9849         {
9850           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9851                               virtual_dwo_name);
9852         }
9853       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9854       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9855                                           virtual_dwo_name,
9856                                           strlen (virtual_dwo_name));
9857       dwo_file->comp_dir = comp_dir;
9858       dwo_file->sections.abbrev =
9859         create_dwp_v2_section (&dwp_file->sections.abbrev,
9860                                sections.abbrev_offset, sections.abbrev_size);
9861       dwo_file->sections.line =
9862         create_dwp_v2_section (&dwp_file->sections.line,
9863                                sections.line_offset, sections.line_size);
9864       dwo_file->sections.loc =
9865         create_dwp_v2_section (&dwp_file->sections.loc,
9866                                sections.loc_offset, sections.loc_size);
9867       dwo_file->sections.macinfo =
9868         create_dwp_v2_section (&dwp_file->sections.macinfo,
9869                                sections.macinfo_offset, sections.macinfo_size);
9870       dwo_file->sections.macro =
9871         create_dwp_v2_section (&dwp_file->sections.macro,
9872                                sections.macro_offset, sections.macro_size);
9873       dwo_file->sections.str_offsets =
9874         create_dwp_v2_section (&dwp_file->sections.str_offsets,
9875                                sections.str_offsets_offset,
9876                                sections.str_offsets_size);
9877       /* The "str" section is global to the entire DWP file.  */
9878       dwo_file->sections.str = dwp_file->sections.str;
9879       /* The info or types section is assigned below to dwo_unit,
9880          there's no need to record it in dwo_file.
9881          Also, we can't simply record type sections in dwo_file because
9882          we record a pointer into the vector in dwo_unit.  As we collect more
9883          types we'll grow the vector and eventually have to reallocate space
9884          for it, invalidating all copies of pointers into the previous
9885          contents.  */
9886       *dwo_file_slot = dwo_file;
9887     }
9888   else
9889     {
9890       if (dwarf2_read_debug)
9891         {
9892           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9893                               virtual_dwo_name);
9894         }
9895       dwo_file = *dwo_file_slot;
9896     }
9897   do_cleanups (cleanups);
9898
9899   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9900   dwo_unit->dwo_file = dwo_file;
9901   dwo_unit->signature = signature;
9902   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9903                                      sizeof (struct dwarf2_section_info));
9904   *dwo_unit->section = create_dwp_v2_section (is_debug_types
9905                                               ? &dwp_file->sections.types
9906                                               : &dwp_file->sections.info,
9907                                               sections.info_or_types_offset,
9908                                               sections.info_or_types_size);
9909   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9910
9911   return dwo_unit;
9912 }
9913
9914 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
9915    Returns NULL if the signature isn't found.  */
9916
9917 static struct dwo_unit *
9918 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
9919                         ULONGEST signature, int is_debug_types)
9920 {
9921   const struct dwp_hash_table *dwp_htab =
9922     is_debug_types ? dwp_file->tus : dwp_file->cus;
9923   bfd *dbfd = dwp_file->dbfd;
9924   uint32_t mask = dwp_htab->nr_slots - 1;
9925   uint32_t hash = signature & mask;
9926   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9927   unsigned int i;
9928   void **slot;
9929   struct dwo_unit find_dwo_cu, *dwo_cu;
9930
9931   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9932   find_dwo_cu.signature = signature;
9933   slot = htab_find_slot (is_debug_types
9934                          ? dwp_file->loaded_tus
9935                          : dwp_file->loaded_cus,
9936                          &find_dwo_cu, INSERT);
9937
9938   if (*slot != NULL)
9939     return *slot;
9940
9941   /* Use a for loop so that we don't loop forever on bad debug info.  */
9942   for (i = 0; i < dwp_htab->nr_slots; ++i)
9943     {
9944       ULONGEST signature_in_table;
9945
9946       signature_in_table =
9947         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
9948       if (signature_in_table == signature)
9949         {
9950           uint32_t unit_index =
9951             read_4_bytes (dbfd,
9952                           dwp_htab->unit_table + hash * sizeof (uint32_t));
9953
9954           if (dwp_file->version == 1)
9955             {
9956               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
9957                                                  comp_dir, signature,
9958                                                  is_debug_types);
9959             }
9960           else
9961             {
9962               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
9963                                                  comp_dir, signature,
9964                                                  is_debug_types);
9965             }
9966           return *slot;
9967         }
9968       if (signature_in_table == 0)
9969         return NULL;
9970       hash = (hash + hash2) & mask;
9971     }
9972
9973   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9974            " [in module %s]"),
9975          dwp_file->name);
9976 }
9977
9978 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9979    Open the file specified by FILE_NAME and hand it off to BFD for
9980    preliminary analysis.  Return a newly initialized bfd *, which
9981    includes a canonicalized copy of FILE_NAME.
9982    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9983    SEARCH_CWD is true if the current directory is to be searched.
9984    It will be searched before debug-file-directory.
9985    If unable to find/open the file, return NULL.
9986    NOTE: This function is derived from symfile_bfd_open.  */
9987
9988 static bfd *
9989 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9990 {
9991   bfd *sym_bfd;
9992   int desc, flags;
9993   char *absolute_name;
9994   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9995      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9996      to debug_file_directory.  */
9997   char *search_path;
9998   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9999
10000   if (search_cwd)
10001     {
10002       if (*debug_file_directory != '\0')
10003         search_path = concat (".", dirname_separator_string,
10004                               debug_file_directory, NULL);
10005       else
10006         search_path = xstrdup (".");
10007     }
10008   else
10009     search_path = xstrdup (debug_file_directory);
10010
10011   flags = OPF_RETURN_REALPATH;
10012   if (is_dwp)
10013     flags |= OPF_SEARCH_IN_PATH;
10014   desc = openp (search_path, flags, file_name,
10015                 O_RDONLY | O_BINARY, &absolute_name);
10016   xfree (search_path);
10017   if (desc < 0)
10018     return NULL;
10019
10020   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
10021   xfree (absolute_name);
10022   if (sym_bfd == NULL)
10023     return NULL;
10024   bfd_set_cacheable (sym_bfd, 1);
10025
10026   if (!bfd_check_format (sym_bfd, bfd_object))
10027     {
10028       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
10029       return NULL;
10030     }
10031
10032   return sym_bfd;
10033 }
10034
10035 /* Try to open DWO file FILE_NAME.
10036    COMP_DIR is the DW_AT_comp_dir attribute.
10037    The result is the bfd handle of the file.
10038    If there is a problem finding or opening the file, return NULL.
10039    Upon success, the canonicalized path of the file is stored in the bfd,
10040    same as symfile_bfd_open.  */
10041
10042 static bfd *
10043 open_dwo_file (const char *file_name, const char *comp_dir)
10044 {
10045   bfd *abfd;
10046
10047   if (IS_ABSOLUTE_PATH (file_name))
10048     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10049
10050   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10051
10052   if (comp_dir != NULL)
10053     {
10054       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
10055
10056       /* NOTE: If comp_dir is a relative path, this will also try the
10057          search path, which seems useful.  */
10058       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
10059       xfree (path_to_try);
10060       if (abfd != NULL)
10061         return abfd;
10062     }
10063
10064   /* That didn't work, try debug-file-directory, which, despite its name,
10065      is a list of paths.  */
10066
10067   if (*debug_file_directory == '\0')
10068     return NULL;
10069
10070   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10071 }
10072
10073 /* This function is mapped across the sections and remembers the offset and
10074    size of each of the DWO debugging sections we are interested in.  */
10075
10076 static void
10077 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10078 {
10079   struct dwo_sections *dwo_sections = dwo_sections_ptr;
10080   const struct dwop_section_names *names = &dwop_section_names;
10081
10082   if (section_is_p (sectp->name, &names->abbrev_dwo))
10083     {
10084       dwo_sections->abbrev.s.asection = sectp;
10085       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10086     }
10087   else if (section_is_p (sectp->name, &names->info_dwo))
10088     {
10089       dwo_sections->info.s.asection = sectp;
10090       dwo_sections->info.size = bfd_get_section_size (sectp);
10091     }
10092   else if (section_is_p (sectp->name, &names->line_dwo))
10093     {
10094       dwo_sections->line.s.asection = sectp;
10095       dwo_sections->line.size = bfd_get_section_size (sectp);
10096     }
10097   else if (section_is_p (sectp->name, &names->loc_dwo))
10098     {
10099       dwo_sections->loc.s.asection = sectp;
10100       dwo_sections->loc.size = bfd_get_section_size (sectp);
10101     }
10102   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10103     {
10104       dwo_sections->macinfo.s.asection = sectp;
10105       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10106     }
10107   else if (section_is_p (sectp->name, &names->macro_dwo))
10108     {
10109       dwo_sections->macro.s.asection = sectp;
10110       dwo_sections->macro.size = bfd_get_section_size (sectp);
10111     }
10112   else if (section_is_p (sectp->name, &names->str_dwo))
10113     {
10114       dwo_sections->str.s.asection = sectp;
10115       dwo_sections->str.size = bfd_get_section_size (sectp);
10116     }
10117   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10118     {
10119       dwo_sections->str_offsets.s.asection = sectp;
10120       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10121     }
10122   else if (section_is_p (sectp->name, &names->types_dwo))
10123     {
10124       struct dwarf2_section_info type_section;
10125
10126       memset (&type_section, 0, sizeof (type_section));
10127       type_section.s.asection = sectp;
10128       type_section.size = bfd_get_section_size (sectp);
10129       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10130                      &type_section);
10131     }
10132 }
10133
10134 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10135    by PER_CU.  This is for the non-DWP case.
10136    The result is NULL if DWO_NAME can't be found.  */
10137
10138 static struct dwo_file *
10139 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10140                         const char *dwo_name, const char *comp_dir)
10141 {
10142   struct objfile *objfile = dwarf2_per_objfile->objfile;
10143   struct dwo_file *dwo_file;
10144   bfd *dbfd;
10145   struct cleanup *cleanups;
10146
10147   dbfd = open_dwo_file (dwo_name, comp_dir);
10148   if (dbfd == NULL)
10149     {
10150       if (dwarf2_read_debug)
10151         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10152       return NULL;
10153     }
10154   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10155   dwo_file->dwo_name = dwo_name;
10156   dwo_file->comp_dir = comp_dir;
10157   dwo_file->dbfd = dbfd;
10158
10159   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10160
10161   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
10162
10163   dwo_file->cu = create_dwo_cu (dwo_file);
10164
10165   dwo_file->tus = create_debug_types_hash_table (dwo_file,
10166                                                  dwo_file->sections.types);
10167
10168   discard_cleanups (cleanups);
10169
10170   if (dwarf2_read_debug)
10171     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10172
10173   return dwo_file;
10174 }
10175
10176 /* This function is mapped across the sections and remembers the offset and
10177    size of each of the DWP debugging sections common to version 1 and 2 that
10178    we are interested in.  */
10179
10180 static void
10181 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10182                                    void *dwp_file_ptr)
10183 {
10184   struct dwp_file *dwp_file = dwp_file_ptr;
10185   const struct dwop_section_names *names = &dwop_section_names;
10186   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10187
10188   /* Record the ELF section number for later lookup: this is what the
10189      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10190   gdb_assert (elf_section_nr < dwp_file->num_sections);
10191   dwp_file->elf_sections[elf_section_nr] = sectp;
10192
10193   /* Look for specific sections that we need.  */
10194   if (section_is_p (sectp->name, &names->str_dwo))
10195     {
10196       dwp_file->sections.str.s.asection = sectp;
10197       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10198     }
10199   else if (section_is_p (sectp->name, &names->cu_index))
10200     {
10201       dwp_file->sections.cu_index.s.asection = sectp;
10202       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10203     }
10204   else if (section_is_p (sectp->name, &names->tu_index))
10205     {
10206       dwp_file->sections.tu_index.s.asection = sectp;
10207       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10208     }
10209 }
10210
10211 /* This function is mapped across the sections and remembers the offset and
10212    size of each of the DWP version 2 debugging sections that we are interested
10213    in.  This is split into a separate function because we don't know if we
10214    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10215
10216 static void
10217 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10218 {
10219   struct dwp_file *dwp_file = dwp_file_ptr;
10220   const struct dwop_section_names *names = &dwop_section_names;
10221   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10222
10223   /* Record the ELF section number for later lookup: this is what the
10224      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10225   gdb_assert (elf_section_nr < dwp_file->num_sections);
10226   dwp_file->elf_sections[elf_section_nr] = sectp;
10227
10228   /* Look for specific sections that we need.  */
10229   if (section_is_p (sectp->name, &names->abbrev_dwo))
10230     {
10231       dwp_file->sections.abbrev.s.asection = sectp;
10232       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10233     }
10234   else if (section_is_p (sectp->name, &names->info_dwo))
10235     {
10236       dwp_file->sections.info.s.asection = sectp;
10237       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10238     }
10239   else if (section_is_p (sectp->name, &names->line_dwo))
10240     {
10241       dwp_file->sections.line.s.asection = sectp;
10242       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10243     }
10244   else if (section_is_p (sectp->name, &names->loc_dwo))
10245     {
10246       dwp_file->sections.loc.s.asection = sectp;
10247       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10248     }
10249   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10250     {
10251       dwp_file->sections.macinfo.s.asection = sectp;
10252       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10253     }
10254   else if (section_is_p (sectp->name, &names->macro_dwo))
10255     {
10256       dwp_file->sections.macro.s.asection = sectp;
10257       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10258     }
10259   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10260     {
10261       dwp_file->sections.str_offsets.s.asection = sectp;
10262       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10263     }
10264   else if (section_is_p (sectp->name, &names->types_dwo))
10265     {
10266       dwp_file->sections.types.s.asection = sectp;
10267       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10268     }
10269 }
10270
10271 /* Hash function for dwp_file loaded CUs/TUs.  */
10272
10273 static hashval_t
10274 hash_dwp_loaded_cutus (const void *item)
10275 {
10276   const struct dwo_unit *dwo_unit = item;
10277
10278   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10279   return dwo_unit->signature;
10280 }
10281
10282 /* Equality function for dwp_file loaded CUs/TUs.  */
10283
10284 static int
10285 eq_dwp_loaded_cutus (const void *a, const void *b)
10286 {
10287   const struct dwo_unit *dua = a;
10288   const struct dwo_unit *dub = b;
10289
10290   return dua->signature == dub->signature;
10291 }
10292
10293 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10294
10295 static htab_t
10296 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10297 {
10298   return htab_create_alloc_ex (3,
10299                                hash_dwp_loaded_cutus,
10300                                eq_dwp_loaded_cutus,
10301                                NULL,
10302                                &objfile->objfile_obstack,
10303                                hashtab_obstack_allocate,
10304                                dummy_obstack_deallocate);
10305 }
10306
10307 /* Try to open DWP file FILE_NAME.
10308    The result is the bfd handle of the file.
10309    If there is a problem finding or opening the file, return NULL.
10310    Upon success, the canonicalized path of the file is stored in the bfd,
10311    same as symfile_bfd_open.  */
10312
10313 static bfd *
10314 open_dwp_file (const char *file_name)
10315 {
10316   bfd *abfd;
10317
10318   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
10319   if (abfd != NULL)
10320     return abfd;
10321
10322   /* Work around upstream bug 15652.
10323      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10324      [Whether that's a "bug" is debatable, but it is getting in our way.]
10325      We have no real idea where the dwp file is, because gdb's realpath-ing
10326      of the executable's path may have discarded the needed info.
10327      [IWBN if the dwp file name was recorded in the executable, akin to
10328      .gnu_debuglink, but that doesn't exist yet.]
10329      Strip the directory from FILE_NAME and search again.  */
10330   if (*debug_file_directory != '\0')
10331     {
10332       /* Don't implicitly search the current directory here.
10333          If the user wants to search "." to handle this case,
10334          it must be added to debug-file-directory.  */
10335       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
10336                                  0 /*search_cwd*/);
10337     }
10338
10339   return NULL;
10340 }
10341
10342 /* Initialize the use of the DWP file for the current objfile.
10343    By convention the name of the DWP file is ${objfile}.dwp.
10344    The result is NULL if it can't be found.  */
10345
10346 static struct dwp_file *
10347 open_and_init_dwp_file (void)
10348 {
10349   struct objfile *objfile = dwarf2_per_objfile->objfile;
10350   struct dwp_file *dwp_file;
10351   char *dwp_name;
10352   bfd *dbfd;
10353   struct cleanup *cleanups;
10354
10355   /* Try to find first .dwp for the binary file before any symbolic links
10356      resolving.  */
10357   dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
10358   cleanups = make_cleanup (xfree, dwp_name);
10359
10360   dbfd = open_dwp_file (dwp_name);
10361   if (dbfd == NULL
10362       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
10363     {
10364       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
10365       dwp_name = xstrprintf ("%s.dwp", objfile_name (objfile));
10366       make_cleanup (xfree, dwp_name);
10367       dbfd = open_dwp_file (dwp_name);
10368     }
10369
10370   if (dbfd == NULL)
10371     {
10372       if (dwarf2_read_debug)
10373         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
10374       do_cleanups (cleanups);
10375       return NULL;
10376     }
10377   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
10378   dwp_file->name = bfd_get_filename (dbfd);
10379   dwp_file->dbfd = dbfd;
10380   do_cleanups (cleanups);
10381
10382   /* +1: section 0 is unused */
10383   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
10384   dwp_file->elf_sections =
10385     OBSTACK_CALLOC (&objfile->objfile_obstack,
10386                     dwp_file->num_sections, asection *);
10387
10388   bfd_map_over_sections (dbfd, dwarf2_locate_common_dwp_sections, dwp_file);
10389
10390   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
10391
10392   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
10393
10394   /* The DWP file version is stored in the hash table.  Oh well.  */
10395   if (dwp_file->cus->version != dwp_file->tus->version)
10396     {
10397       /* Technically speaking, we should try to limp along, but this is
10398          pretty bizarre.  */
10399       error (_("Dwarf Error: DWP file CU version %d doesn't match"
10400                " TU version %d [in DWP file %s]"),
10401              dwp_file->cus->version, dwp_file->tus->version, dwp_name);
10402     }
10403   dwp_file->version = dwp_file->cus->version;
10404
10405   if (dwp_file->version == 2)
10406     bfd_map_over_sections (dbfd, dwarf2_locate_v2_dwp_sections, dwp_file);
10407
10408   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
10409   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
10410
10411   if (dwarf2_read_debug)
10412     {
10413       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
10414       fprintf_unfiltered (gdb_stdlog,
10415                           "    %s CUs, %s TUs\n",
10416                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
10417                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
10418     }
10419
10420   return dwp_file;
10421 }
10422
10423 /* Wrapper around open_and_init_dwp_file, only open it once.  */
10424
10425 static struct dwp_file *
10426 get_dwp_file (void)
10427 {
10428   if (! dwarf2_per_objfile->dwp_checked)
10429     {
10430       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
10431       dwarf2_per_objfile->dwp_checked = 1;
10432     }
10433   return dwarf2_per_objfile->dwp_file;
10434 }
10435
10436 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
10437    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
10438    or in the DWP file for the objfile, referenced by THIS_UNIT.
10439    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
10440    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
10441
10442    This is called, for example, when wanting to read a variable with a
10443    complex location.  Therefore we don't want to do file i/o for every call.
10444    Therefore we don't want to look for a DWO file on every call.
10445    Therefore we first see if we've already seen SIGNATURE in a DWP file,
10446    then we check if we've already seen DWO_NAME, and only THEN do we check
10447    for a DWO file.
10448
10449    The result is a pointer to the dwo_unit object or NULL if we didn't find it
10450    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
10451
10452 static struct dwo_unit *
10453 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
10454                  const char *dwo_name, const char *comp_dir,
10455                  ULONGEST signature, int is_debug_types)
10456 {
10457   struct objfile *objfile = dwarf2_per_objfile->objfile;
10458   const char *kind = is_debug_types ? "TU" : "CU";
10459   void **dwo_file_slot;
10460   struct dwo_file *dwo_file;
10461   struct dwp_file *dwp_file;
10462
10463   /* First see if there's a DWP file.
10464      If we have a DWP file but didn't find the DWO inside it, don't
10465      look for the original DWO file.  It makes gdb behave differently
10466      depending on whether one is debugging in the build tree.  */
10467
10468   dwp_file = get_dwp_file ();
10469   if (dwp_file != NULL)
10470     {
10471       const struct dwp_hash_table *dwp_htab =
10472         is_debug_types ? dwp_file->tus : dwp_file->cus;
10473
10474       if (dwp_htab != NULL)
10475         {
10476           struct dwo_unit *dwo_cutu =
10477             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
10478                                     signature, is_debug_types);
10479
10480           if (dwo_cutu != NULL)
10481             {
10482               if (dwarf2_read_debug)
10483                 {
10484                   fprintf_unfiltered (gdb_stdlog,
10485                                       "Virtual DWO %s %s found: @%s\n",
10486                                       kind, hex_string (signature),
10487                                       host_address_to_string (dwo_cutu));
10488                 }
10489               return dwo_cutu;
10490             }
10491         }
10492     }
10493   else
10494     {
10495       /* No DWP file, look for the DWO file.  */
10496
10497       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
10498       if (*dwo_file_slot == NULL)
10499         {
10500           /* Read in the file and build a table of the CUs/TUs it contains.  */
10501           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
10502         }
10503       /* NOTE: This will be NULL if unable to open the file.  */
10504       dwo_file = *dwo_file_slot;
10505
10506       if (dwo_file != NULL)
10507         {
10508           struct dwo_unit *dwo_cutu = NULL;
10509
10510           if (is_debug_types && dwo_file->tus)
10511             {
10512               struct dwo_unit find_dwo_cutu;
10513
10514               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
10515               find_dwo_cutu.signature = signature;
10516               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
10517             }
10518           else if (!is_debug_types && dwo_file->cu)
10519             {
10520               if (signature == dwo_file->cu->signature)
10521                 dwo_cutu = dwo_file->cu;
10522             }
10523
10524           if (dwo_cutu != NULL)
10525             {
10526               if (dwarf2_read_debug)
10527                 {
10528                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
10529                                       kind, dwo_name, hex_string (signature),
10530                                       host_address_to_string (dwo_cutu));
10531                 }
10532               return dwo_cutu;
10533             }
10534         }
10535     }
10536
10537   /* We didn't find it.  This could mean a dwo_id mismatch, or
10538      someone deleted the DWO/DWP file, or the search path isn't set up
10539      correctly to find the file.  */
10540
10541   if (dwarf2_read_debug)
10542     {
10543       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
10544                           kind, dwo_name, hex_string (signature));
10545     }
10546
10547   /* This is a warning and not a complaint because it can be caused by
10548      pilot error (e.g., user accidentally deleting the DWO).  */
10549   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
10550              " [in module %s]"),
10551            kind, dwo_name, hex_string (signature),
10552            this_unit->is_debug_types ? "TU" : "CU",
10553            this_unit->offset.sect_off, objfile_name (objfile));
10554   return NULL;
10555 }
10556
10557 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
10558    See lookup_dwo_cutu_unit for details.  */
10559
10560 static struct dwo_unit *
10561 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
10562                       const char *dwo_name, const char *comp_dir,
10563                       ULONGEST signature)
10564 {
10565   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
10566 }
10567
10568 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
10569    See lookup_dwo_cutu_unit for details.  */
10570
10571 static struct dwo_unit *
10572 lookup_dwo_type_unit (struct signatured_type *this_tu,
10573                       const char *dwo_name, const char *comp_dir)
10574 {
10575   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
10576 }
10577
10578 /* Traversal function for queue_and_load_all_dwo_tus.  */
10579
10580 static int
10581 queue_and_load_dwo_tu (void **slot, void *info)
10582 {
10583   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
10584   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
10585   ULONGEST signature = dwo_unit->signature;
10586   struct signatured_type *sig_type =
10587     lookup_dwo_signatured_type (per_cu->cu, signature);
10588
10589   if (sig_type != NULL)
10590     {
10591       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
10592
10593       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
10594          a real dependency of PER_CU on SIG_TYPE.  That is detected later
10595          while processing PER_CU.  */
10596       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
10597         load_full_type_unit (sig_cu);
10598       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
10599     }
10600
10601   return 1;
10602 }
10603
10604 /* Queue all TUs contained in the DWO of PER_CU to be read in.
10605    The DWO may have the only definition of the type, though it may not be
10606    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
10607    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
10608
10609 static void
10610 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
10611 {
10612   struct dwo_unit *dwo_unit;
10613   struct dwo_file *dwo_file;
10614
10615   gdb_assert (!per_cu->is_debug_types);
10616   gdb_assert (get_dwp_file () == NULL);
10617   gdb_assert (per_cu->cu != NULL);
10618
10619   dwo_unit = per_cu->cu->dwo_unit;
10620   gdb_assert (dwo_unit != NULL);
10621
10622   dwo_file = dwo_unit->dwo_file;
10623   if (dwo_file->tus != NULL)
10624     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
10625 }
10626
10627 /* Free all resources associated with DWO_FILE.
10628    Close the DWO file and munmap the sections.
10629    All memory should be on the objfile obstack.  */
10630
10631 static void
10632 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
10633 {
10634   int ix;
10635   struct dwarf2_section_info *section;
10636
10637   /* Note: dbfd is NULL for virtual DWO files.  */
10638   gdb_bfd_unref (dwo_file->dbfd);
10639
10640   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
10641 }
10642
10643 /* Wrapper for free_dwo_file for use in cleanups.  */
10644
10645 static void
10646 free_dwo_file_cleanup (void *arg)
10647 {
10648   struct dwo_file *dwo_file = (struct dwo_file *) arg;
10649   struct objfile *objfile = dwarf2_per_objfile->objfile;
10650
10651   free_dwo_file (dwo_file, objfile);
10652 }
10653
10654 /* Traversal function for free_dwo_files.  */
10655
10656 static int
10657 free_dwo_file_from_slot (void **slot, void *info)
10658 {
10659   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
10660   struct objfile *objfile = (struct objfile *) info;
10661
10662   free_dwo_file (dwo_file, objfile);
10663
10664   return 1;
10665 }
10666
10667 /* Free all resources associated with DWO_FILES.  */
10668
10669 static void
10670 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
10671 {
10672   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
10673 }
10674 \f
10675 /* Read in various DIEs.  */
10676
10677 /* qsort helper for inherit_abstract_dies.  */
10678
10679 static int
10680 unsigned_int_compar (const void *ap, const void *bp)
10681 {
10682   unsigned int a = *(unsigned int *) ap;
10683   unsigned int b = *(unsigned int *) bp;
10684
10685   return (a > b) - (b > a);
10686 }
10687
10688 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
10689    Inherit only the children of the DW_AT_abstract_origin DIE not being
10690    already referenced by DW_AT_abstract_origin from the children of the
10691    current DIE.  */
10692
10693 static void
10694 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
10695 {
10696   struct die_info *child_die;
10697   unsigned die_children_count;
10698   /* CU offsets which were referenced by children of the current DIE.  */
10699   sect_offset *offsets;
10700   sect_offset *offsets_end, *offsetp;
10701   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
10702   struct die_info *origin_die;
10703   /* Iterator of the ORIGIN_DIE children.  */
10704   struct die_info *origin_child_die;
10705   struct cleanup *cleanups;
10706   struct attribute *attr;
10707   struct dwarf2_cu *origin_cu;
10708   struct pending **origin_previous_list_in_scope;
10709
10710   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10711   if (!attr)
10712     return;
10713
10714   /* Note that following die references may follow to a die in a
10715      different cu.  */
10716
10717   origin_cu = cu;
10718   origin_die = follow_die_ref (die, attr, &origin_cu);
10719
10720   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
10721      symbols in.  */
10722   origin_previous_list_in_scope = origin_cu->list_in_scope;
10723   origin_cu->list_in_scope = cu->list_in_scope;
10724
10725   if (die->tag != origin_die->tag
10726       && !(die->tag == DW_TAG_inlined_subroutine
10727            && origin_die->tag == DW_TAG_subprogram))
10728     complaint (&symfile_complaints,
10729                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
10730                die->offset.sect_off, origin_die->offset.sect_off);
10731
10732   child_die = die->child;
10733   die_children_count = 0;
10734   while (child_die && child_die->tag)
10735     {
10736       child_die = sibling_die (child_die);
10737       die_children_count++;
10738     }
10739   offsets = xmalloc (sizeof (*offsets) * die_children_count);
10740   cleanups = make_cleanup (xfree, offsets);
10741
10742   offsets_end = offsets;
10743   child_die = die->child;
10744   while (child_die && child_die->tag)
10745     {
10746       /* For each CHILD_DIE, find the corresponding child of
10747          ORIGIN_DIE.  If there is more than one layer of
10748          DW_AT_abstract_origin, follow them all; there shouldn't be,
10749          but GCC versions at least through 4.4 generate this (GCC PR
10750          40573).  */
10751       struct die_info *child_origin_die = child_die;
10752       struct dwarf2_cu *child_origin_cu = cu;
10753
10754       while (1)
10755         {
10756           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
10757                               child_origin_cu);
10758           if (attr == NULL)
10759             break;
10760           child_origin_die = follow_die_ref (child_origin_die, attr,
10761                                              &child_origin_cu);
10762         }
10763
10764       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10765          counterpart may exist.  */
10766       if (child_origin_die != child_die)
10767         {
10768           if (child_die->tag != child_origin_die->tag
10769               && !(child_die->tag == DW_TAG_inlined_subroutine
10770                    && child_origin_die->tag == DW_TAG_subprogram))
10771             complaint (&symfile_complaints,
10772                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10773                          "different tags"), child_die->offset.sect_off,
10774                        child_origin_die->offset.sect_off);
10775           if (child_origin_die->parent != origin_die)
10776             complaint (&symfile_complaints,
10777                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10778                          "different parents"), child_die->offset.sect_off,
10779                        child_origin_die->offset.sect_off);
10780           else
10781             *offsets_end++ = child_origin_die->offset;
10782         }
10783       child_die = sibling_die (child_die);
10784     }
10785   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10786          unsigned_int_compar);
10787   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10788     if (offsetp[-1].sect_off == offsetp->sect_off)
10789       complaint (&symfile_complaints,
10790                  _("Multiple children of DIE 0x%x refer "
10791                    "to DIE 0x%x as their abstract origin"),
10792                  die->offset.sect_off, offsetp->sect_off);
10793
10794   offsetp = offsets;
10795   origin_child_die = origin_die->child;
10796   while (origin_child_die && origin_child_die->tag)
10797     {
10798       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10799       while (offsetp < offsets_end
10800              && offsetp->sect_off < origin_child_die->offset.sect_off)
10801         offsetp++;
10802       if (offsetp >= offsets_end
10803           || offsetp->sect_off > origin_child_die->offset.sect_off)
10804         {
10805           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10806           process_die (origin_child_die, origin_cu);
10807         }
10808       origin_child_die = sibling_die (origin_child_die);
10809     }
10810   origin_cu->list_in_scope = origin_previous_list_in_scope;
10811
10812   do_cleanups (cleanups);
10813 }
10814
10815 static void
10816 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10817 {
10818   struct objfile *objfile = cu->objfile;
10819   struct context_stack *new;
10820   CORE_ADDR lowpc;
10821   CORE_ADDR highpc;
10822   struct die_info *child_die;
10823   struct attribute *attr, *call_line, *call_file;
10824   const char *name;
10825   CORE_ADDR baseaddr;
10826   struct block *block;
10827   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10828   VEC (symbolp) *template_args = NULL;
10829   struct template_symbol *templ_func = NULL;
10830
10831   if (inlined_func)
10832     {
10833       /* If we do not have call site information, we can't show the
10834          caller of this inlined function.  That's too confusing, so
10835          only use the scope for local variables.  */
10836       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10837       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10838       if (call_line == NULL || call_file == NULL)
10839         {
10840           read_lexical_block_scope (die, cu);
10841           return;
10842         }
10843     }
10844
10845   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10846
10847   name = dwarf2_name (die, cu);
10848
10849   /* Ignore functions with missing or empty names.  These are actually
10850      illegal according to the DWARF standard.  */
10851   if (name == NULL)
10852     {
10853       complaint (&symfile_complaints,
10854                  _("missing name for subprogram DIE at %d"),
10855                  die->offset.sect_off);
10856       return;
10857     }
10858
10859   /* Ignore functions with missing or invalid low and high pc attributes.  */
10860   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10861     {
10862       attr = dwarf2_attr (die, DW_AT_external, cu);
10863       if (!attr || !DW_UNSND (attr))
10864         complaint (&symfile_complaints,
10865                    _("cannot get low and high bounds "
10866                      "for subprogram DIE at %d"),
10867                    die->offset.sect_off);
10868       return;
10869     }
10870
10871   lowpc += baseaddr;
10872   highpc += baseaddr;
10873
10874   /* If we have any template arguments, then we must allocate a
10875      different sort of symbol.  */
10876   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10877     {
10878       if (child_die->tag == DW_TAG_template_type_param
10879           || child_die->tag == DW_TAG_template_value_param)
10880         {
10881           templ_func = allocate_template_symbol (objfile);
10882           templ_func->base.is_cplus_template_function = 1;
10883           break;
10884         }
10885     }
10886
10887   new = push_context (0, lowpc);
10888   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10889                                (struct symbol *) templ_func);
10890
10891   /* If there is a location expression for DW_AT_frame_base, record
10892      it.  */
10893   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10894   if (attr)
10895     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10896
10897   cu->list_in_scope = &local_symbols;
10898
10899   if (die->child != NULL)
10900     {
10901       child_die = die->child;
10902       while (child_die && child_die->tag)
10903         {
10904           if (child_die->tag == DW_TAG_template_type_param
10905               || child_die->tag == DW_TAG_template_value_param)
10906             {
10907               struct symbol *arg = new_symbol (child_die, NULL, cu);
10908
10909               if (arg != NULL)
10910                 VEC_safe_push (symbolp, template_args, arg);
10911             }
10912           else
10913             process_die (child_die, cu);
10914           child_die = sibling_die (child_die);
10915         }
10916     }
10917
10918   inherit_abstract_dies (die, cu);
10919
10920   /* If we have a DW_AT_specification, we might need to import using
10921      directives from the context of the specification DIE.  See the
10922      comment in determine_prefix.  */
10923   if (cu->language == language_cplus
10924       && dwarf2_attr (die, DW_AT_specification, cu))
10925     {
10926       struct dwarf2_cu *spec_cu = cu;
10927       struct die_info *spec_die = die_specification (die, &spec_cu);
10928
10929       while (spec_die)
10930         {
10931           child_die = spec_die->child;
10932           while (child_die && child_die->tag)
10933             {
10934               if (child_die->tag == DW_TAG_imported_module)
10935                 process_die (child_die, spec_cu);
10936               child_die = sibling_die (child_die);
10937             }
10938
10939           /* In some cases, GCC generates specification DIEs that
10940              themselves contain DW_AT_specification attributes.  */
10941           spec_die = die_specification (spec_die, &spec_cu);
10942         }
10943     }
10944
10945   new = pop_context ();
10946   /* Make a block for the local symbols within.  */
10947   block = finish_block (new->name, &local_symbols, new->old_blocks,
10948                         lowpc, highpc, objfile);
10949
10950   /* For C++, set the block's scope.  */
10951   if ((cu->language == language_cplus || cu->language == language_fortran)
10952       && cu->processing_has_namespace_info)
10953     block_set_scope (block, determine_prefix (die, cu),
10954                      &objfile->objfile_obstack);
10955
10956   /* If we have address ranges, record them.  */
10957   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10958
10959   /* Attach template arguments to function.  */
10960   if (! VEC_empty (symbolp, template_args))
10961     {
10962       gdb_assert (templ_func != NULL);
10963
10964       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10965       templ_func->template_arguments
10966         = obstack_alloc (&objfile->objfile_obstack,
10967                          (templ_func->n_template_arguments
10968                           * sizeof (struct symbol *)));
10969       memcpy (templ_func->template_arguments,
10970               VEC_address (symbolp, template_args),
10971               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10972       VEC_free (symbolp, template_args);
10973     }
10974
10975   /* In C++, we can have functions nested inside functions (e.g., when
10976      a function declares a class that has methods).  This means that
10977      when we finish processing a function scope, we may need to go
10978      back to building a containing block's symbol lists.  */
10979   local_symbols = new->locals;
10980   using_directives = new->using_directives;
10981
10982   /* If we've finished processing a top-level function, subsequent
10983      symbols go in the file symbol list.  */
10984   if (outermost_context_p ())
10985     cu->list_in_scope = &file_symbols;
10986 }
10987
10988 /* Process all the DIES contained within a lexical block scope.  Start
10989    a new scope, process the dies, and then close the scope.  */
10990
10991 static void
10992 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10993 {
10994   struct objfile *objfile = cu->objfile;
10995   struct context_stack *new;
10996   CORE_ADDR lowpc, highpc;
10997   struct die_info *child_die;
10998   CORE_ADDR baseaddr;
10999
11000   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11001
11002   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11003   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11004      as multiple lexical blocks?  Handling children in a sane way would
11005      be nasty.  Might be easier to properly extend generic blocks to
11006      describe ranges.  */
11007   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11008     return;
11009   lowpc += baseaddr;
11010   highpc += baseaddr;
11011
11012   push_context (0, lowpc);
11013   if (die->child != NULL)
11014     {
11015       child_die = die->child;
11016       while (child_die && child_die->tag)
11017         {
11018           process_die (child_die, cu);
11019           child_die = sibling_die (child_die);
11020         }
11021     }
11022   new = pop_context ();
11023
11024   if (local_symbols != NULL || using_directives != NULL)
11025     {
11026       struct block *block
11027         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
11028                         highpc, objfile);
11029
11030       /* Note that recording ranges after traversing children, as we
11031          do here, means that recording a parent's ranges entails
11032          walking across all its children's ranges as they appear in
11033          the address map, which is quadratic behavior.
11034
11035          It would be nicer to record the parent's ranges before
11036          traversing its children, simply overriding whatever you find
11037          there.  But since we don't even decide whether to create a
11038          block until after we've traversed its children, that's hard
11039          to do.  */
11040       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11041     }
11042   local_symbols = new->locals;
11043   using_directives = new->using_directives;
11044 }
11045
11046 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
11047
11048 static void
11049 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11050 {
11051   struct objfile *objfile = cu->objfile;
11052   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11053   CORE_ADDR pc, baseaddr;
11054   struct attribute *attr;
11055   struct call_site *call_site, call_site_local;
11056   void **slot;
11057   int nparams;
11058   struct die_info *child_die;
11059
11060   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11061
11062   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11063   if (!attr)
11064     {
11065       complaint (&symfile_complaints,
11066                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
11067                    "DIE 0x%x [in module %s]"),
11068                  die->offset.sect_off, objfile_name (objfile));
11069       return;
11070     }
11071   pc = DW_ADDR (attr) + baseaddr;
11072
11073   if (cu->call_site_htab == NULL)
11074     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11075                                                NULL, &objfile->objfile_obstack,
11076                                                hashtab_obstack_allocate, NULL);
11077   call_site_local.pc = pc;
11078   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11079   if (*slot != NULL)
11080     {
11081       complaint (&symfile_complaints,
11082                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
11083                    "DIE 0x%x [in module %s]"),
11084                  paddress (gdbarch, pc), die->offset.sect_off,
11085                  objfile_name (objfile));
11086       return;
11087     }
11088
11089   /* Count parameters at the caller.  */
11090
11091   nparams = 0;
11092   for (child_die = die->child; child_die && child_die->tag;
11093        child_die = sibling_die (child_die))
11094     {
11095       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11096         {
11097           complaint (&symfile_complaints,
11098                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
11099                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11100                      child_die->tag, child_die->offset.sect_off,
11101                      objfile_name (objfile));
11102           continue;
11103         }
11104
11105       nparams++;
11106     }
11107
11108   call_site = obstack_alloc (&objfile->objfile_obstack,
11109                              (sizeof (*call_site)
11110                               + (sizeof (*call_site->parameter)
11111                                  * (nparams - 1))));
11112   *slot = call_site;
11113   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11114   call_site->pc = pc;
11115
11116   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11117     {
11118       struct die_info *func_die;
11119
11120       /* Skip also over DW_TAG_inlined_subroutine.  */
11121       for (func_die = die->parent;
11122            func_die && func_die->tag != DW_TAG_subprogram
11123            && func_die->tag != DW_TAG_subroutine_type;
11124            func_die = func_die->parent);
11125
11126       /* DW_AT_GNU_all_call_sites is a superset
11127          of DW_AT_GNU_all_tail_call_sites.  */
11128       if (func_die
11129           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11130           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11131         {
11132           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11133              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11134              both the initial caller containing the real return address PC and
11135              the final callee containing the current PC of a chain of tail
11136              calls do not need to have the tail call list complete.  But any
11137              function candidate for a virtual tail call frame searched via
11138              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11139              determined unambiguously.  */
11140         }
11141       else
11142         {
11143           struct type *func_type = NULL;
11144
11145           if (func_die)
11146             func_type = get_die_type (func_die, cu);
11147           if (func_type != NULL)
11148             {
11149               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11150
11151               /* Enlist this call site to the function.  */
11152               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11153               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11154             }
11155           else
11156             complaint (&symfile_complaints,
11157                        _("Cannot find function owning DW_TAG_GNU_call_site "
11158                          "DIE 0x%x [in module %s]"),
11159                        die->offset.sect_off, objfile_name (objfile));
11160         }
11161     }
11162
11163   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11164   if (attr == NULL)
11165     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11166   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11167   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11168     /* Keep NULL DWARF_BLOCK.  */;
11169   else if (attr_form_is_block (attr))
11170     {
11171       struct dwarf2_locexpr_baton *dlbaton;
11172
11173       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
11174       dlbaton->data = DW_BLOCK (attr)->data;
11175       dlbaton->size = DW_BLOCK (attr)->size;
11176       dlbaton->per_cu = cu->per_cu;
11177
11178       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11179     }
11180   else if (attr_form_is_ref (attr))
11181     {
11182       struct dwarf2_cu *target_cu = cu;
11183       struct die_info *target_die;
11184
11185       target_die = follow_die_ref (die, attr, &target_cu);
11186       gdb_assert (target_cu->objfile == objfile);
11187       if (die_is_declaration (target_die, target_cu))
11188         {
11189           const char *target_physname = NULL;
11190           struct attribute *target_attr;
11191
11192           /* Prefer the mangled name; otherwise compute the demangled one.  */
11193           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
11194           if (target_attr == NULL)
11195             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
11196                                        target_cu);
11197           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
11198             target_physname = DW_STRING (target_attr);
11199           else
11200             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11201           if (target_physname == NULL)
11202             complaint (&symfile_complaints,
11203                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11204                          "physname, for referencing DIE 0x%x [in module %s]"),
11205                        die->offset.sect_off, objfile_name (objfile));
11206           else
11207             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11208         }
11209       else
11210         {
11211           CORE_ADDR lowpc;
11212
11213           /* DW_AT_entry_pc should be preferred.  */
11214           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
11215             complaint (&symfile_complaints,
11216                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11217                          "low pc, for referencing DIE 0x%x [in module %s]"),
11218                        die->offset.sect_off, objfile_name (objfile));
11219           else
11220             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
11221         }
11222     }
11223   else
11224     complaint (&symfile_complaints,
11225                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
11226                  "block nor reference, for DIE 0x%x [in module %s]"),
11227                die->offset.sect_off, objfile_name (objfile));
11228
11229   call_site->per_cu = cu->per_cu;
11230
11231   for (child_die = die->child;
11232        child_die && child_die->tag;
11233        child_die = sibling_die (child_die))
11234     {
11235       struct call_site_parameter *parameter;
11236       struct attribute *loc, *origin;
11237
11238       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11239         {
11240           /* Already printed the complaint above.  */
11241           continue;
11242         }
11243
11244       gdb_assert (call_site->parameter_count < nparams);
11245       parameter = &call_site->parameter[call_site->parameter_count];
11246
11247       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
11248          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
11249          register is contained in DW_AT_GNU_call_site_value.  */
11250
11251       loc = dwarf2_attr (child_die, DW_AT_location, cu);
11252       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
11253       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
11254         {
11255           sect_offset offset;
11256
11257           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
11258           offset = dwarf2_get_ref_die_offset (origin);
11259           if (!offset_in_cu_p (&cu->header, offset))
11260             {
11261               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
11262                  binding can be done only inside one CU.  Such referenced DIE
11263                  therefore cannot be even moved to DW_TAG_partial_unit.  */
11264               complaint (&symfile_complaints,
11265                          _("DW_AT_abstract_origin offset is not in CU for "
11266                            "DW_TAG_GNU_call_site child DIE 0x%x "
11267                            "[in module %s]"),
11268                          child_die->offset.sect_off, objfile_name (objfile));
11269               continue;
11270             }
11271           parameter->u.param_offset.cu_off = (offset.sect_off
11272                                               - cu->header.offset.sect_off);
11273         }
11274       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
11275         {
11276           complaint (&symfile_complaints,
11277                      _("No DW_FORM_block* DW_AT_location for "
11278                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11279                      child_die->offset.sect_off, objfile_name (objfile));
11280           continue;
11281         }
11282       else
11283         {
11284           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
11285             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
11286           if (parameter->u.dwarf_reg != -1)
11287             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
11288           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
11289                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
11290                                              &parameter->u.fb_offset))
11291             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
11292           else
11293             {
11294               complaint (&symfile_complaints,
11295                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
11296                            "for DW_FORM_block* DW_AT_location is supported for "
11297                            "DW_TAG_GNU_call_site child DIE 0x%x "
11298                            "[in module %s]"),
11299                          child_die->offset.sect_off, objfile_name (objfile));
11300               continue;
11301             }
11302         }
11303
11304       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
11305       if (!attr_form_is_block (attr))
11306         {
11307           complaint (&symfile_complaints,
11308                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
11309                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11310                      child_die->offset.sect_off, objfile_name (objfile));
11311           continue;
11312         }
11313       parameter->value = DW_BLOCK (attr)->data;
11314       parameter->value_size = DW_BLOCK (attr)->size;
11315
11316       /* Parameters are not pre-cleared by memset above.  */
11317       parameter->data_value = NULL;
11318       parameter->data_value_size = 0;
11319       call_site->parameter_count++;
11320
11321       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
11322       if (attr)
11323         {
11324           if (!attr_form_is_block (attr))
11325             complaint (&symfile_complaints,
11326                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
11327                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11328                        child_die->offset.sect_off, objfile_name (objfile));
11329           else
11330             {
11331               parameter->data_value = DW_BLOCK (attr)->data;
11332               parameter->data_value_size = DW_BLOCK (attr)->size;
11333             }
11334         }
11335     }
11336 }
11337
11338 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
11339    Return 1 if the attributes are present and valid, otherwise, return 0.
11340    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
11341
11342 static int
11343 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
11344                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
11345                     struct partial_symtab *ranges_pst)
11346 {
11347   struct objfile *objfile = cu->objfile;
11348   struct comp_unit_head *cu_header = &cu->header;
11349   bfd *obfd = objfile->obfd;
11350   unsigned int addr_size = cu_header->addr_size;
11351   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11352   /* Base address selection entry.  */
11353   CORE_ADDR base;
11354   int found_base;
11355   unsigned int dummy;
11356   const gdb_byte *buffer;
11357   CORE_ADDR marker;
11358   int low_set;
11359   CORE_ADDR low = 0;
11360   CORE_ADDR high = 0;
11361   CORE_ADDR baseaddr;
11362
11363   found_base = cu->base_known;
11364   base = cu->base_address;
11365
11366   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11367   if (offset >= dwarf2_per_objfile->ranges.size)
11368     {
11369       complaint (&symfile_complaints,
11370                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
11371                  offset);
11372       return 0;
11373     }
11374   buffer = dwarf2_per_objfile->ranges.buffer + offset;
11375
11376   /* Read in the largest possible address.  */
11377   marker = read_address (obfd, buffer, cu, &dummy);
11378   if ((marker & mask) == mask)
11379     {
11380       /* If we found the largest possible address, then
11381          read the base address.  */
11382       base = read_address (obfd, buffer + addr_size, cu, &dummy);
11383       buffer += 2 * addr_size;
11384       offset += 2 * addr_size;
11385       found_base = 1;
11386     }
11387
11388   low_set = 0;
11389
11390   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11391
11392   while (1)
11393     {
11394       CORE_ADDR range_beginning, range_end;
11395
11396       range_beginning = read_address (obfd, buffer, cu, &dummy);
11397       buffer += addr_size;
11398       range_end = read_address (obfd, buffer, cu, &dummy);
11399       buffer += addr_size;
11400       offset += 2 * addr_size;
11401
11402       /* An end of list marker is a pair of zero addresses.  */
11403       if (range_beginning == 0 && range_end == 0)
11404         /* Found the end of list entry.  */
11405         break;
11406
11407       /* Each base address selection entry is a pair of 2 values.
11408          The first is the largest possible address, the second is
11409          the base address.  Check for a base address here.  */
11410       if ((range_beginning & mask) == mask)
11411         {
11412           /* If we found the largest possible address, then
11413              read the base address.  */
11414           base = read_address (obfd, buffer + addr_size, cu, &dummy);
11415           found_base = 1;
11416           continue;
11417         }
11418
11419       if (!found_base)
11420         {
11421           /* We have no valid base address for the ranges
11422              data.  */
11423           complaint (&symfile_complaints,
11424                      _("Invalid .debug_ranges data (no base address)"));
11425           return 0;
11426         }
11427
11428       if (range_beginning > range_end)
11429         {
11430           /* Inverted range entries are invalid.  */
11431           complaint (&symfile_complaints,
11432                      _("Invalid .debug_ranges data (inverted range)"));
11433           return 0;
11434         }
11435
11436       /* Empty range entries have no effect.  */
11437       if (range_beginning == range_end)
11438         continue;
11439
11440       range_beginning += base;
11441       range_end += base;
11442
11443       /* A not-uncommon case of bad debug info.
11444          Don't pollute the addrmap with bad data.  */
11445       if (range_beginning + baseaddr == 0
11446           && !dwarf2_per_objfile->has_section_at_zero)
11447         {
11448           complaint (&symfile_complaints,
11449                      _(".debug_ranges entry has start address of zero"
11450                        " [in module %s]"), objfile_name (objfile));
11451           continue;
11452         }
11453
11454       if (ranges_pst != NULL)
11455         addrmap_set_empty (objfile->psymtabs_addrmap,
11456                            range_beginning + baseaddr,
11457                            range_end - 1 + baseaddr,
11458                            ranges_pst);
11459
11460       /* FIXME: This is recording everything as a low-high
11461          segment of consecutive addresses.  We should have a
11462          data structure for discontiguous block ranges
11463          instead.  */
11464       if (! low_set)
11465         {
11466           low = range_beginning;
11467           high = range_end;
11468           low_set = 1;
11469         }
11470       else
11471         {
11472           if (range_beginning < low)
11473             low = range_beginning;
11474           if (range_end > high)
11475             high = range_end;
11476         }
11477     }
11478
11479   if (! low_set)
11480     /* If the first entry is an end-of-list marker, the range
11481        describes an empty scope, i.e. no instructions.  */
11482     return 0;
11483
11484   if (low_return)
11485     *low_return = low;
11486   if (high_return)
11487     *high_return = high;
11488   return 1;
11489 }
11490
11491 /* Get low and high pc attributes from a die.  Return 1 if the attributes
11492    are present and valid, otherwise, return 0.  Return -1 if the range is
11493    discontinuous, i.e. derived from DW_AT_ranges information.  */
11494
11495 static int
11496 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
11497                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
11498                       struct partial_symtab *pst)
11499 {
11500   struct attribute *attr;
11501   struct attribute *attr_high;
11502   CORE_ADDR low = 0;
11503   CORE_ADDR high = 0;
11504   int ret = 0;
11505
11506   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11507   if (attr_high)
11508     {
11509       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11510       if (attr)
11511         {
11512           low = DW_ADDR (attr);
11513           if (attr_high->form == DW_FORM_addr
11514               || attr_high->form == DW_FORM_GNU_addr_index)
11515             high = DW_ADDR (attr_high);
11516           else
11517             high = low + DW_UNSND (attr_high);
11518         }
11519       else
11520         /* Found high w/o low attribute.  */
11521         return 0;
11522
11523       /* Found consecutive range of addresses.  */
11524       ret = 1;
11525     }
11526   else
11527     {
11528       attr = dwarf2_attr (die, DW_AT_ranges, cu);
11529       if (attr != NULL)
11530         {
11531           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11532              We take advantage of the fact that DW_AT_ranges does not appear
11533              in DW_TAG_compile_unit of DWO files.  */
11534           int need_ranges_base = die->tag != DW_TAG_compile_unit;
11535           unsigned int ranges_offset = (DW_UNSND (attr)
11536                                         + (need_ranges_base
11537                                            ? cu->ranges_base
11538                                            : 0));
11539
11540           /* Value of the DW_AT_ranges attribute is the offset in the
11541              .debug_ranges section.  */
11542           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
11543             return 0;
11544           /* Found discontinuous range of addresses.  */
11545           ret = -1;
11546         }
11547     }
11548
11549   /* read_partial_die has also the strict LOW < HIGH requirement.  */
11550   if (high <= low)
11551     return 0;
11552
11553   /* When using the GNU linker, .gnu.linkonce. sections are used to
11554      eliminate duplicate copies of functions and vtables and such.
11555      The linker will arbitrarily choose one and discard the others.
11556      The AT_*_pc values for such functions refer to local labels in
11557      these sections.  If the section from that file was discarded, the
11558      labels are not in the output, so the relocs get a value of 0.
11559      If this is a discarded function, mark the pc bounds as invalid,
11560      so that GDB will ignore it.  */
11561   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
11562     return 0;
11563
11564   *lowpc = low;
11565   if (highpc)
11566     *highpc = high;
11567   return ret;
11568 }
11569
11570 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
11571    its low and high PC addresses.  Do nothing if these addresses could not
11572    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
11573    and HIGHPC to the high address if greater than HIGHPC.  */
11574
11575 static void
11576 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
11577                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
11578                                  struct dwarf2_cu *cu)
11579 {
11580   CORE_ADDR low, high;
11581   struct die_info *child = die->child;
11582
11583   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
11584     {
11585       *lowpc = min (*lowpc, low);
11586       *highpc = max (*highpc, high);
11587     }
11588
11589   /* If the language does not allow nested subprograms (either inside
11590      subprograms or lexical blocks), we're done.  */
11591   if (cu->language != language_ada)
11592     return;
11593
11594   /* Check all the children of the given DIE.  If it contains nested
11595      subprograms, then check their pc bounds.  Likewise, we need to
11596      check lexical blocks as well, as they may also contain subprogram
11597      definitions.  */
11598   while (child && child->tag)
11599     {
11600       if (child->tag == DW_TAG_subprogram
11601           || child->tag == DW_TAG_lexical_block)
11602         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
11603       child = sibling_die (child);
11604     }
11605 }
11606
11607 /* Get the low and high pc's represented by the scope DIE, and store
11608    them in *LOWPC and *HIGHPC.  If the correct values can't be
11609    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
11610
11611 static void
11612 get_scope_pc_bounds (struct die_info *die,
11613                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
11614                      struct dwarf2_cu *cu)
11615 {
11616   CORE_ADDR best_low = (CORE_ADDR) -1;
11617   CORE_ADDR best_high = (CORE_ADDR) 0;
11618   CORE_ADDR current_low, current_high;
11619
11620   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
11621     {
11622       best_low = current_low;
11623       best_high = current_high;
11624     }
11625   else
11626     {
11627       struct die_info *child = die->child;
11628
11629       while (child && child->tag)
11630         {
11631           switch (child->tag) {
11632           case DW_TAG_subprogram:
11633             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
11634             break;
11635           case DW_TAG_namespace:
11636           case DW_TAG_module:
11637             /* FIXME: carlton/2004-01-16: Should we do this for
11638                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
11639                that current GCC's always emit the DIEs corresponding
11640                to definitions of methods of classes as children of a
11641                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
11642                the DIEs giving the declarations, which could be
11643                anywhere).  But I don't see any reason why the
11644                standards says that they have to be there.  */
11645             get_scope_pc_bounds (child, &current_low, &current_high, cu);
11646
11647             if (current_low != ((CORE_ADDR) -1))
11648               {
11649                 best_low = min (best_low, current_low);
11650                 best_high = max (best_high, current_high);
11651               }
11652             break;
11653           default:
11654             /* Ignore.  */
11655             break;
11656           }
11657
11658           child = sibling_die (child);
11659         }
11660     }
11661
11662   *lowpc = best_low;
11663   *highpc = best_high;
11664 }
11665
11666 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
11667    in DIE.  */
11668
11669 static void
11670 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
11671                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
11672 {
11673   struct objfile *objfile = cu->objfile;
11674   struct attribute *attr;
11675   struct attribute *attr_high;
11676
11677   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11678   if (attr_high)
11679     {
11680       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11681       if (attr)
11682         {
11683           CORE_ADDR low = DW_ADDR (attr);
11684           CORE_ADDR high;
11685           if (attr_high->form == DW_FORM_addr
11686               || attr_high->form == DW_FORM_GNU_addr_index)
11687             high = DW_ADDR (attr_high);
11688           else
11689             high = low + DW_UNSND (attr_high);
11690
11691           record_block_range (block, baseaddr + low, baseaddr + high - 1);
11692         }
11693     }
11694
11695   attr = dwarf2_attr (die, DW_AT_ranges, cu);
11696   if (attr)
11697     {
11698       bfd *obfd = objfile->obfd;
11699       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11700          We take advantage of the fact that DW_AT_ranges does not appear
11701          in DW_TAG_compile_unit of DWO files.  */
11702       int need_ranges_base = die->tag != DW_TAG_compile_unit;
11703
11704       /* The value of the DW_AT_ranges attribute is the offset of the
11705          address range list in the .debug_ranges section.  */
11706       unsigned long offset = (DW_UNSND (attr)
11707                               + (need_ranges_base ? cu->ranges_base : 0));
11708       const gdb_byte *buffer;
11709
11710       /* For some target architectures, but not others, the
11711          read_address function sign-extends the addresses it returns.
11712          To recognize base address selection entries, we need a
11713          mask.  */
11714       unsigned int addr_size = cu->header.addr_size;
11715       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11716
11717       /* The base address, to which the next pair is relative.  Note
11718          that this 'base' is a DWARF concept: most entries in a range
11719          list are relative, to reduce the number of relocs against the
11720          debugging information.  This is separate from this function's
11721          'baseaddr' argument, which GDB uses to relocate debugging
11722          information from a shared library based on the address at
11723          which the library was loaded.  */
11724       CORE_ADDR base = cu->base_address;
11725       int base_known = cu->base_known;
11726
11727       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11728       if (offset >= dwarf2_per_objfile->ranges.size)
11729         {
11730           complaint (&symfile_complaints,
11731                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
11732                      offset);
11733           return;
11734         }
11735       buffer = dwarf2_per_objfile->ranges.buffer + offset;
11736
11737       for (;;)
11738         {
11739           unsigned int bytes_read;
11740           CORE_ADDR start, end;
11741
11742           start = read_address (obfd, buffer, cu, &bytes_read);
11743           buffer += bytes_read;
11744           end = read_address (obfd, buffer, cu, &bytes_read);
11745           buffer += bytes_read;
11746
11747           /* Did we find the end of the range list?  */
11748           if (start == 0 && end == 0)
11749             break;
11750
11751           /* Did we find a base address selection entry?  */
11752           else if ((start & base_select_mask) == base_select_mask)
11753             {
11754               base = end;
11755               base_known = 1;
11756             }
11757
11758           /* We found an ordinary address range.  */
11759           else
11760             {
11761               if (!base_known)
11762                 {
11763                   complaint (&symfile_complaints,
11764                              _("Invalid .debug_ranges data "
11765                                "(no base address)"));
11766                   return;
11767                 }
11768
11769               if (start > end)
11770                 {
11771                   /* Inverted range entries are invalid.  */
11772                   complaint (&symfile_complaints,
11773                              _("Invalid .debug_ranges data "
11774                                "(inverted range)"));
11775                   return;
11776                 }
11777
11778               /* Empty range entries have no effect.  */
11779               if (start == end)
11780                 continue;
11781
11782               start += base + baseaddr;
11783               end += base + baseaddr;
11784
11785               /* A not-uncommon case of bad debug info.
11786                  Don't pollute the addrmap with bad data.  */
11787               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11788                 {
11789                   complaint (&symfile_complaints,
11790                              _(".debug_ranges entry has start address of zero"
11791                                " [in module %s]"), objfile_name (objfile));
11792                   continue;
11793                 }
11794
11795               record_block_range (block, start, end - 1);
11796             }
11797         }
11798     }
11799 }
11800
11801 /* Check whether the producer field indicates either of GCC < 4.6, or the
11802    Intel C/C++ compiler, and cache the result in CU.  */
11803
11804 static void
11805 check_producer (struct dwarf2_cu *cu)
11806 {
11807   const char *cs;
11808   int major, minor, release;
11809
11810   if (cu->producer == NULL)
11811     {
11812       /* For unknown compilers expect their behavior is DWARF version
11813          compliant.
11814
11815          GCC started to support .debug_types sections by -gdwarf-4 since
11816          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11817          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11818          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11819          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11820     }
11821   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11822     {
11823       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11824
11825       cs = &cu->producer[strlen ("GNU ")];
11826       while (*cs && !isdigit (*cs))
11827         cs++;
11828       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11829         {
11830           /* Not recognized as GCC.  */
11831         }
11832       else
11833         {
11834           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11835           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11836         }
11837     }
11838   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11839     cu->producer_is_icc = 1;
11840   else
11841     {
11842       /* For other non-GCC compilers, expect their behavior is DWARF version
11843          compliant.  */
11844     }
11845
11846   cu->checked_producer = 1;
11847 }
11848
11849 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11850    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11851    during 4.6.0 experimental.  */
11852
11853 static int
11854 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11855 {
11856   if (!cu->checked_producer)
11857     check_producer (cu);
11858
11859   return cu->producer_is_gxx_lt_4_6;
11860 }
11861
11862 /* Return the default accessibility type if it is not overriden by
11863    DW_AT_accessibility.  */
11864
11865 static enum dwarf_access_attribute
11866 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11867 {
11868   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11869     {
11870       /* The default DWARF 2 accessibility for members is public, the default
11871          accessibility for inheritance is private.  */
11872
11873       if (die->tag != DW_TAG_inheritance)
11874         return DW_ACCESS_public;
11875       else
11876         return DW_ACCESS_private;
11877     }
11878   else
11879     {
11880       /* DWARF 3+ defines the default accessibility a different way.  The same
11881          rules apply now for DW_TAG_inheritance as for the members and it only
11882          depends on the container kind.  */
11883
11884       if (die->parent->tag == DW_TAG_class_type)
11885         return DW_ACCESS_private;
11886       else
11887         return DW_ACCESS_public;
11888     }
11889 }
11890
11891 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11892    offset.  If the attribute was not found return 0, otherwise return
11893    1.  If it was found but could not properly be handled, set *OFFSET
11894    to 0.  */
11895
11896 static int
11897 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11898                              LONGEST *offset)
11899 {
11900   struct attribute *attr;
11901
11902   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11903   if (attr != NULL)
11904     {
11905       *offset = 0;
11906
11907       /* Note that we do not check for a section offset first here.
11908          This is because DW_AT_data_member_location is new in DWARF 4,
11909          so if we see it, we can assume that a constant form is really
11910          a constant and not a section offset.  */
11911       if (attr_form_is_constant (attr))
11912         *offset = dwarf2_get_attr_constant_value (attr, 0);
11913       else if (attr_form_is_section_offset (attr))
11914         dwarf2_complex_location_expr_complaint ();
11915       else if (attr_form_is_block (attr))
11916         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11917       else
11918         dwarf2_complex_location_expr_complaint ();
11919
11920       return 1;
11921     }
11922
11923   return 0;
11924 }
11925
11926 /* Add an aggregate field to the field list.  */
11927
11928 static void
11929 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11930                   struct dwarf2_cu *cu)
11931 {
11932   struct objfile *objfile = cu->objfile;
11933   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11934   struct nextfield *new_field;
11935   struct attribute *attr;
11936   struct field *fp;
11937   const char *fieldname = "";
11938
11939   /* Allocate a new field list entry and link it in.  */
11940   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11941   make_cleanup (xfree, new_field);
11942   memset (new_field, 0, sizeof (struct nextfield));
11943
11944   if (die->tag == DW_TAG_inheritance)
11945     {
11946       new_field->next = fip->baseclasses;
11947       fip->baseclasses = new_field;
11948     }
11949   else
11950     {
11951       new_field->next = fip->fields;
11952       fip->fields = new_field;
11953     }
11954   fip->nfields++;
11955
11956   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11957   if (attr)
11958     new_field->accessibility = DW_UNSND (attr);
11959   else
11960     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11961   if (new_field->accessibility != DW_ACCESS_public)
11962     fip->non_public_fields = 1;
11963
11964   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11965   if (attr)
11966     new_field->virtuality = DW_UNSND (attr);
11967   else
11968     new_field->virtuality = DW_VIRTUALITY_none;
11969
11970   fp = &new_field->field;
11971
11972   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11973     {
11974       LONGEST offset;
11975
11976       /* Data member other than a C++ static data member.  */
11977
11978       /* Get type of field.  */
11979       fp->type = die_type (die, cu);
11980
11981       SET_FIELD_BITPOS (*fp, 0);
11982
11983       /* Get bit size of field (zero if none).  */
11984       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11985       if (attr)
11986         {
11987           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11988         }
11989       else
11990         {
11991           FIELD_BITSIZE (*fp) = 0;
11992         }
11993
11994       /* Get bit offset of field.  */
11995       if (handle_data_member_location (die, cu, &offset))
11996         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11997       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11998       if (attr)
11999         {
12000           if (gdbarch_bits_big_endian (gdbarch))
12001             {
12002               /* For big endian bits, the DW_AT_bit_offset gives the
12003                  additional bit offset from the MSB of the containing
12004                  anonymous object to the MSB of the field.  We don't
12005                  have to do anything special since we don't need to
12006                  know the size of the anonymous object.  */
12007               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12008             }
12009           else
12010             {
12011               /* For little endian bits, compute the bit offset to the
12012                  MSB of the anonymous object, subtract off the number of
12013                  bits from the MSB of the field to the MSB of the
12014                  object, and then subtract off the number of bits of
12015                  the field itself.  The result is the bit offset of
12016                  the LSB of the field.  */
12017               int anonymous_size;
12018               int bit_offset = DW_UNSND (attr);
12019
12020               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12021               if (attr)
12022                 {
12023                   /* The size of the anonymous object containing
12024                      the bit field is explicit, so use the
12025                      indicated size (in bytes).  */
12026                   anonymous_size = DW_UNSND (attr);
12027                 }
12028               else
12029                 {
12030                   /* The size of the anonymous object containing
12031                      the bit field must be inferred from the type
12032                      attribute of the data member containing the
12033                      bit field.  */
12034                   anonymous_size = TYPE_LENGTH (fp->type);
12035                 }
12036               SET_FIELD_BITPOS (*fp,
12037                                 (FIELD_BITPOS (*fp)
12038                                  + anonymous_size * bits_per_byte
12039                                  - bit_offset - FIELD_BITSIZE (*fp)));
12040             }
12041         }
12042
12043       /* Get name of field.  */
12044       fieldname = dwarf2_name (die, cu);
12045       if (fieldname == NULL)
12046         fieldname = "";
12047
12048       /* The name is already allocated along with this objfile, so we don't
12049          need to duplicate it for the type.  */
12050       fp->name = fieldname;
12051
12052       /* Change accessibility for artificial fields (e.g. virtual table
12053          pointer or virtual base class pointer) to private.  */
12054       if (dwarf2_attr (die, DW_AT_artificial, cu))
12055         {
12056           FIELD_ARTIFICIAL (*fp) = 1;
12057           new_field->accessibility = DW_ACCESS_private;
12058           fip->non_public_fields = 1;
12059         }
12060     }
12061   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12062     {
12063       /* C++ static member.  */
12064
12065       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12066          is a declaration, but all versions of G++ as of this writing
12067          (so through at least 3.2.1) incorrectly generate
12068          DW_TAG_variable tags.  */
12069
12070       const char *physname;
12071
12072       /* Get name of field.  */
12073       fieldname = dwarf2_name (die, cu);
12074       if (fieldname == NULL)
12075         return;
12076
12077       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12078       if (attr
12079           /* Only create a symbol if this is an external value.
12080              new_symbol checks this and puts the value in the global symbol
12081              table, which we want.  If it is not external, new_symbol
12082              will try to put the value in cu->list_in_scope which is wrong.  */
12083           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12084         {
12085           /* A static const member, not much different than an enum as far as
12086              we're concerned, except that we can support more types.  */
12087           new_symbol (die, NULL, cu);
12088         }
12089
12090       /* Get physical name.  */
12091       physname = dwarf2_physname (fieldname, die, cu);
12092
12093       /* The name is already allocated along with this objfile, so we don't
12094          need to duplicate it for the type.  */
12095       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
12096       FIELD_TYPE (*fp) = die_type (die, cu);
12097       FIELD_NAME (*fp) = fieldname;
12098     }
12099   else if (die->tag == DW_TAG_inheritance)
12100     {
12101       LONGEST offset;
12102
12103       /* C++ base class field.  */
12104       if (handle_data_member_location (die, cu, &offset))
12105         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12106       FIELD_BITSIZE (*fp) = 0;
12107       FIELD_TYPE (*fp) = die_type (die, cu);
12108       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
12109       fip->nbaseclasses++;
12110     }
12111 }
12112
12113 /* Add a typedef defined in the scope of the FIP's class.  */
12114
12115 static void
12116 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
12117                     struct dwarf2_cu *cu)
12118 {
12119   struct objfile *objfile = cu->objfile;
12120   struct typedef_field_list *new_field;
12121   struct attribute *attr;
12122   struct typedef_field *fp;
12123   char *fieldname = "";
12124
12125   /* Allocate a new field list entry and link it in.  */
12126   new_field = xzalloc (sizeof (*new_field));
12127   make_cleanup (xfree, new_field);
12128
12129   gdb_assert (die->tag == DW_TAG_typedef);
12130
12131   fp = &new_field->field;
12132
12133   /* Get name of field.  */
12134   fp->name = dwarf2_name (die, cu);
12135   if (fp->name == NULL)
12136     return;
12137
12138   fp->type = read_type_die (die, cu);
12139
12140   new_field->next = fip->typedef_field_list;
12141   fip->typedef_field_list = new_field;
12142   fip->typedef_field_list_count++;
12143 }
12144
12145 /* Create the vector of fields, and attach it to the type.  */
12146
12147 static void
12148 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
12149                               struct dwarf2_cu *cu)
12150 {
12151   int nfields = fip->nfields;
12152
12153   /* Record the field count, allocate space for the array of fields,
12154      and create blank accessibility bitfields if necessary.  */
12155   TYPE_NFIELDS (type) = nfields;
12156   TYPE_FIELDS (type) = (struct field *)
12157     TYPE_ALLOC (type, sizeof (struct field) * nfields);
12158   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
12159
12160   if (fip->non_public_fields && cu->language != language_ada)
12161     {
12162       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12163
12164       TYPE_FIELD_PRIVATE_BITS (type) =
12165         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12166       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
12167
12168       TYPE_FIELD_PROTECTED_BITS (type) =
12169         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12170       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
12171
12172       TYPE_FIELD_IGNORE_BITS (type) =
12173         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12174       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
12175     }
12176
12177   /* If the type has baseclasses, allocate and clear a bit vector for
12178      TYPE_FIELD_VIRTUAL_BITS.  */
12179   if (fip->nbaseclasses && cu->language != language_ada)
12180     {
12181       int num_bytes = B_BYTES (fip->nbaseclasses);
12182       unsigned char *pointer;
12183
12184       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12185       pointer = TYPE_ALLOC (type, num_bytes);
12186       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
12187       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
12188       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
12189     }
12190
12191   /* Copy the saved-up fields into the field vector.  Start from the head of
12192      the list, adding to the tail of the field array, so that they end up in
12193      the same order in the array in which they were added to the list.  */
12194   while (nfields-- > 0)
12195     {
12196       struct nextfield *fieldp;
12197
12198       if (fip->fields)
12199         {
12200           fieldp = fip->fields;
12201           fip->fields = fieldp->next;
12202         }
12203       else
12204         {
12205           fieldp = fip->baseclasses;
12206           fip->baseclasses = fieldp->next;
12207         }
12208
12209       TYPE_FIELD (type, nfields) = fieldp->field;
12210       switch (fieldp->accessibility)
12211         {
12212         case DW_ACCESS_private:
12213           if (cu->language != language_ada)
12214             SET_TYPE_FIELD_PRIVATE (type, nfields);
12215           break;
12216
12217         case DW_ACCESS_protected:
12218           if (cu->language != language_ada)
12219             SET_TYPE_FIELD_PROTECTED (type, nfields);
12220           break;
12221
12222         case DW_ACCESS_public:
12223           break;
12224
12225         default:
12226           /* Unknown accessibility.  Complain and treat it as public.  */
12227           {
12228             complaint (&symfile_complaints, _("unsupported accessibility %d"),
12229                        fieldp->accessibility);
12230           }
12231           break;
12232         }
12233       if (nfields < fip->nbaseclasses)
12234         {
12235           switch (fieldp->virtuality)
12236             {
12237             case DW_VIRTUALITY_virtual:
12238             case DW_VIRTUALITY_pure_virtual:
12239               if (cu->language == language_ada)
12240                 error (_("unexpected virtuality in component of Ada type"));
12241               SET_TYPE_FIELD_VIRTUAL (type, nfields);
12242               break;
12243             }
12244         }
12245     }
12246 }
12247
12248 /* Return true if this member function is a constructor, false
12249    otherwise.  */
12250
12251 static int
12252 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
12253 {
12254   const char *fieldname;
12255   const char *typename;
12256   int len;
12257
12258   if (die->parent == NULL)
12259     return 0;
12260
12261   if (die->parent->tag != DW_TAG_structure_type
12262       && die->parent->tag != DW_TAG_union_type
12263       && die->parent->tag != DW_TAG_class_type)
12264     return 0;
12265
12266   fieldname = dwarf2_name (die, cu);
12267   typename = dwarf2_name (die->parent, cu);
12268   if (fieldname == NULL || typename == NULL)
12269     return 0;
12270
12271   len = strlen (fieldname);
12272   return (strncmp (fieldname, typename, len) == 0
12273           && (typename[len] == '\0' || typename[len] == '<'));
12274 }
12275
12276 /* Add a member function to the proper fieldlist.  */
12277
12278 static void
12279 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
12280                       struct type *type, struct dwarf2_cu *cu)
12281 {
12282   struct objfile *objfile = cu->objfile;
12283   struct attribute *attr;
12284   struct fnfieldlist *flp;
12285   int i;
12286   struct fn_field *fnp;
12287   const char *fieldname;
12288   struct nextfnfield *new_fnfield;
12289   struct type *this_type;
12290   enum dwarf_access_attribute accessibility;
12291
12292   if (cu->language == language_ada)
12293     error (_("unexpected member function in Ada type"));
12294
12295   /* Get name of member function.  */
12296   fieldname = dwarf2_name (die, cu);
12297   if (fieldname == NULL)
12298     return;
12299
12300   /* Look up member function name in fieldlist.  */
12301   for (i = 0; i < fip->nfnfields; i++)
12302     {
12303       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
12304         break;
12305     }
12306
12307   /* Create new list element if necessary.  */
12308   if (i < fip->nfnfields)
12309     flp = &fip->fnfieldlists[i];
12310   else
12311     {
12312       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
12313         {
12314           fip->fnfieldlists = (struct fnfieldlist *)
12315             xrealloc (fip->fnfieldlists,
12316                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
12317                       * sizeof (struct fnfieldlist));
12318           if (fip->nfnfields == 0)
12319             make_cleanup (free_current_contents, &fip->fnfieldlists);
12320         }
12321       flp = &fip->fnfieldlists[fip->nfnfields];
12322       flp->name = fieldname;
12323       flp->length = 0;
12324       flp->head = NULL;
12325       i = fip->nfnfields++;
12326     }
12327
12328   /* Create a new member function field and chain it to the field list
12329      entry.  */
12330   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
12331   make_cleanup (xfree, new_fnfield);
12332   memset (new_fnfield, 0, sizeof (struct nextfnfield));
12333   new_fnfield->next = flp->head;
12334   flp->head = new_fnfield;
12335   flp->length++;
12336
12337   /* Fill in the member function field info.  */
12338   fnp = &new_fnfield->fnfield;
12339
12340   /* Delay processing of the physname until later.  */
12341   if (cu->language == language_cplus || cu->language == language_java)
12342     {
12343       add_to_method_list (type, i, flp->length - 1, fieldname,
12344                           die, cu);
12345     }
12346   else
12347     {
12348       const char *physname = dwarf2_physname (fieldname, die, cu);
12349       fnp->physname = physname ? physname : "";
12350     }
12351
12352   fnp->type = alloc_type (objfile);
12353   this_type = read_type_die (die, cu);
12354   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
12355     {
12356       int nparams = TYPE_NFIELDS (this_type);
12357
12358       /* TYPE is the domain of this method, and THIS_TYPE is the type
12359            of the method itself (TYPE_CODE_METHOD).  */
12360       smash_to_method_type (fnp->type, type,
12361                             TYPE_TARGET_TYPE (this_type),
12362                             TYPE_FIELDS (this_type),
12363                             TYPE_NFIELDS (this_type),
12364                             TYPE_VARARGS (this_type));
12365
12366       /* Handle static member functions.
12367          Dwarf2 has no clean way to discern C++ static and non-static
12368          member functions.  G++ helps GDB by marking the first
12369          parameter for non-static member functions (which is the this
12370          pointer) as artificial.  We obtain this information from
12371          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
12372       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
12373         fnp->voffset = VOFFSET_STATIC;
12374     }
12375   else
12376     complaint (&symfile_complaints, _("member function type missing for '%s'"),
12377                dwarf2_full_name (fieldname, die, cu));
12378
12379   /* Get fcontext from DW_AT_containing_type if present.  */
12380   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12381     fnp->fcontext = die_containing_type (die, cu);
12382
12383   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
12384      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
12385
12386   /* Get accessibility.  */
12387   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12388   if (attr)
12389     accessibility = DW_UNSND (attr);
12390   else
12391     accessibility = dwarf2_default_access_attribute (die, cu);
12392   switch (accessibility)
12393     {
12394     case DW_ACCESS_private:
12395       fnp->is_private = 1;
12396       break;
12397     case DW_ACCESS_protected:
12398       fnp->is_protected = 1;
12399       break;
12400     }
12401
12402   /* Check for artificial methods.  */
12403   attr = dwarf2_attr (die, DW_AT_artificial, cu);
12404   if (attr && DW_UNSND (attr) != 0)
12405     fnp->is_artificial = 1;
12406
12407   fnp->is_constructor = dwarf2_is_constructor (die, cu);
12408
12409   /* Get index in virtual function table if it is a virtual member
12410      function.  For older versions of GCC, this is an offset in the
12411      appropriate virtual table, as specified by DW_AT_containing_type.
12412      For everyone else, it is an expression to be evaluated relative
12413      to the object address.  */
12414
12415   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
12416   if (attr)
12417     {
12418       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
12419         {
12420           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
12421             {
12422               /* Old-style GCC.  */
12423               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
12424             }
12425           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
12426                    || (DW_BLOCK (attr)->size > 1
12427                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
12428                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
12429             {
12430               struct dwarf_block blk;
12431               int offset;
12432
12433               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
12434                         ? 1 : 2);
12435               blk.size = DW_BLOCK (attr)->size - offset;
12436               blk.data = DW_BLOCK (attr)->data + offset;
12437               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
12438               if ((fnp->voffset % cu->header.addr_size) != 0)
12439                 dwarf2_complex_location_expr_complaint ();
12440               else
12441                 fnp->voffset /= cu->header.addr_size;
12442               fnp->voffset += 2;
12443             }
12444           else
12445             dwarf2_complex_location_expr_complaint ();
12446
12447           if (!fnp->fcontext)
12448             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
12449         }
12450       else if (attr_form_is_section_offset (attr))
12451         {
12452           dwarf2_complex_location_expr_complaint ();
12453         }
12454       else
12455         {
12456           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
12457                                                  fieldname);
12458         }
12459     }
12460   else
12461     {
12462       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12463       if (attr && DW_UNSND (attr))
12464         {
12465           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
12466           complaint (&symfile_complaints,
12467                      _("Member function \"%s\" (offset %d) is virtual "
12468                        "but the vtable offset is not specified"),
12469                      fieldname, die->offset.sect_off);
12470           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12471           TYPE_CPLUS_DYNAMIC (type) = 1;
12472         }
12473     }
12474 }
12475
12476 /* Create the vector of member function fields, and attach it to the type.  */
12477
12478 static void
12479 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
12480                                  struct dwarf2_cu *cu)
12481 {
12482   struct fnfieldlist *flp;
12483   int i;
12484
12485   if (cu->language == language_ada)
12486     error (_("unexpected member functions in Ada type"));
12487
12488   ALLOCATE_CPLUS_STRUCT_TYPE (type);
12489   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
12490     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
12491
12492   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
12493     {
12494       struct nextfnfield *nfp = flp->head;
12495       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
12496       int k;
12497
12498       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
12499       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
12500       fn_flp->fn_fields = (struct fn_field *)
12501         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
12502       for (k = flp->length; (k--, nfp); nfp = nfp->next)
12503         fn_flp->fn_fields[k] = nfp->fnfield;
12504     }
12505
12506   TYPE_NFN_FIELDS (type) = fip->nfnfields;
12507 }
12508
12509 /* Returns non-zero if NAME is the name of a vtable member in CU's
12510    language, zero otherwise.  */
12511 static int
12512 is_vtable_name (const char *name, struct dwarf2_cu *cu)
12513 {
12514   static const char vptr[] = "_vptr";
12515   static const char vtable[] = "vtable";
12516
12517   /* Look for the C++ and Java forms of the vtable.  */
12518   if ((cu->language == language_java
12519        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
12520        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
12521        && is_cplus_marker (name[sizeof (vptr) - 1])))
12522     return 1;
12523
12524   return 0;
12525 }
12526
12527 /* GCC outputs unnamed structures that are really pointers to member
12528    functions, with the ABI-specified layout.  If TYPE describes
12529    such a structure, smash it into a member function type.
12530
12531    GCC shouldn't do this; it should just output pointer to member DIEs.
12532    This is GCC PR debug/28767.  */
12533
12534 static void
12535 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
12536 {
12537   struct type *pfn_type, *domain_type, *new_type;
12538
12539   /* Check for a structure with no name and two children.  */
12540   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
12541     return;
12542
12543   /* Check for __pfn and __delta members.  */
12544   if (TYPE_FIELD_NAME (type, 0) == NULL
12545       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
12546       || TYPE_FIELD_NAME (type, 1) == NULL
12547       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
12548     return;
12549
12550   /* Find the type of the method.  */
12551   pfn_type = TYPE_FIELD_TYPE (type, 0);
12552   if (pfn_type == NULL
12553       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
12554       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
12555     return;
12556
12557   /* Look for the "this" argument.  */
12558   pfn_type = TYPE_TARGET_TYPE (pfn_type);
12559   if (TYPE_NFIELDS (pfn_type) == 0
12560       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
12561       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
12562     return;
12563
12564   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
12565   new_type = alloc_type (objfile);
12566   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
12567                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
12568                         TYPE_VARARGS (pfn_type));
12569   smash_to_methodptr_type (type, new_type);
12570 }
12571
12572 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
12573    (icc).  */
12574
12575 static int
12576 producer_is_icc (struct dwarf2_cu *cu)
12577 {
12578   if (!cu->checked_producer)
12579     check_producer (cu);
12580
12581   return cu->producer_is_icc;
12582 }
12583
12584 /* Called when we find the DIE that starts a structure or union scope
12585    (definition) to create a type for the structure or union.  Fill in
12586    the type's name and general properties; the members will not be
12587    processed until process_structure_scope.
12588
12589    NOTE: we need to call these functions regardless of whether or not the
12590    DIE has a DW_AT_name attribute, since it might be an anonymous
12591    structure or union.  This gets the type entered into our set of
12592    user defined types.
12593
12594    However, if the structure is incomplete (an opaque struct/union)
12595    then suppress creating a symbol table entry for it since gdb only
12596    wants to find the one with the complete definition.  Note that if
12597    it is complete, we just call new_symbol, which does it's own
12598    checking about whether the struct/union is anonymous or not (and
12599    suppresses creating a symbol table entry itself).  */
12600
12601 static struct type *
12602 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
12603 {
12604   struct objfile *objfile = cu->objfile;
12605   struct type *type;
12606   struct attribute *attr;
12607   const char *name;
12608
12609   /* If the definition of this type lives in .debug_types, read that type.
12610      Don't follow DW_AT_specification though, that will take us back up
12611      the chain and we want to go down.  */
12612   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12613   if (attr)
12614     {
12615       type = get_DW_AT_signature_type (die, attr, cu);
12616
12617       /* The type's CU may not be the same as CU.
12618          Ensure TYPE is recorded with CU in die_type_hash.  */
12619       return set_die_type (die, type, cu);
12620     }
12621
12622   type = alloc_type (objfile);
12623   INIT_CPLUS_SPECIFIC (type);
12624
12625   name = dwarf2_name (die, cu);
12626   if (name != NULL)
12627     {
12628       if (cu->language == language_cplus
12629           || cu->language == language_java)
12630         {
12631           const char *full_name = dwarf2_full_name (name, die, cu);
12632
12633           /* dwarf2_full_name might have already finished building the DIE's
12634              type.  If so, there is no need to continue.  */
12635           if (get_die_type (die, cu) != NULL)
12636             return get_die_type (die, cu);
12637
12638           TYPE_TAG_NAME (type) = full_name;
12639           if (die->tag == DW_TAG_structure_type
12640               || die->tag == DW_TAG_class_type)
12641             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12642         }
12643       else
12644         {
12645           /* The name is already allocated along with this objfile, so
12646              we don't need to duplicate it for the type.  */
12647           TYPE_TAG_NAME (type) = name;
12648           if (die->tag == DW_TAG_class_type)
12649             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12650         }
12651     }
12652
12653   if (die->tag == DW_TAG_structure_type)
12654     {
12655       TYPE_CODE (type) = TYPE_CODE_STRUCT;
12656     }
12657   else if (die->tag == DW_TAG_union_type)
12658     {
12659       TYPE_CODE (type) = TYPE_CODE_UNION;
12660     }
12661   else
12662     {
12663       TYPE_CODE (type) = TYPE_CODE_CLASS;
12664     }
12665
12666   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
12667     TYPE_DECLARED_CLASS (type) = 1;
12668
12669   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12670   if (attr)
12671     {
12672       TYPE_LENGTH (type) = DW_UNSND (attr);
12673     }
12674   else
12675     {
12676       TYPE_LENGTH (type) = 0;
12677     }
12678
12679   if (producer_is_icc (cu))
12680     {
12681       /* ICC does not output the required DW_AT_declaration
12682          on incomplete types, but gives them a size of zero.  */
12683     }
12684   else
12685     TYPE_STUB_SUPPORTED (type) = 1;
12686
12687   if (die_is_declaration (die, cu))
12688     TYPE_STUB (type) = 1;
12689   else if (attr == NULL && die->child == NULL
12690            && producer_is_realview (cu->producer))
12691     /* RealView does not output the required DW_AT_declaration
12692        on incomplete types.  */
12693     TYPE_STUB (type) = 1;
12694
12695   /* We need to add the type field to the die immediately so we don't
12696      infinitely recurse when dealing with pointers to the structure
12697      type within the structure itself.  */
12698   set_die_type (die, type, cu);
12699
12700   /* set_die_type should be already done.  */
12701   set_descriptive_type (type, die, cu);
12702
12703   return type;
12704 }
12705
12706 /* Finish creating a structure or union type, including filling in
12707    its members and creating a symbol for it.  */
12708
12709 static void
12710 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
12711 {
12712   struct objfile *objfile = cu->objfile;
12713   struct die_info *child_die = die->child;
12714   struct type *type;
12715
12716   type = get_die_type (die, cu);
12717   if (type == NULL)
12718     type = read_structure_type (die, cu);
12719
12720   if (die->child != NULL && ! die_is_declaration (die, cu))
12721     {
12722       struct field_info fi;
12723       struct die_info *child_die;
12724       VEC (symbolp) *template_args = NULL;
12725       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
12726
12727       memset (&fi, 0, sizeof (struct field_info));
12728
12729       child_die = die->child;
12730
12731       while (child_die && child_die->tag)
12732         {
12733           if (child_die->tag == DW_TAG_member
12734               || child_die->tag == DW_TAG_variable)
12735             {
12736               /* NOTE: carlton/2002-11-05: A C++ static data member
12737                  should be a DW_TAG_member that is a declaration, but
12738                  all versions of G++ as of this writing (so through at
12739                  least 3.2.1) incorrectly generate DW_TAG_variable
12740                  tags for them instead.  */
12741               dwarf2_add_field (&fi, child_die, cu);
12742             }
12743           else if (child_die->tag == DW_TAG_subprogram)
12744             {
12745               /* C++ member function.  */
12746               dwarf2_add_member_fn (&fi, child_die, type, cu);
12747             }
12748           else if (child_die->tag == DW_TAG_inheritance)
12749             {
12750               /* C++ base class field.  */
12751               dwarf2_add_field (&fi, child_die, cu);
12752             }
12753           else if (child_die->tag == DW_TAG_typedef)
12754             dwarf2_add_typedef (&fi, child_die, cu);
12755           else if (child_die->tag == DW_TAG_template_type_param
12756                    || child_die->tag == DW_TAG_template_value_param)
12757             {
12758               struct symbol *arg = new_symbol (child_die, NULL, cu);
12759
12760               if (arg != NULL)
12761                 VEC_safe_push (symbolp, template_args, arg);
12762             }
12763
12764           child_die = sibling_die (child_die);
12765         }
12766
12767       /* Attach template arguments to type.  */
12768       if (! VEC_empty (symbolp, template_args))
12769         {
12770           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12771           TYPE_N_TEMPLATE_ARGUMENTS (type)
12772             = VEC_length (symbolp, template_args);
12773           TYPE_TEMPLATE_ARGUMENTS (type)
12774             = obstack_alloc (&objfile->objfile_obstack,
12775                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12776                               * sizeof (struct symbol *)));
12777           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12778                   VEC_address (symbolp, template_args),
12779                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12780                    * sizeof (struct symbol *)));
12781           VEC_free (symbolp, template_args);
12782         }
12783
12784       /* Attach fields and member functions to the type.  */
12785       if (fi.nfields)
12786         dwarf2_attach_fields_to_type (&fi, type, cu);
12787       if (fi.nfnfields)
12788         {
12789           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12790
12791           /* Get the type which refers to the base class (possibly this
12792              class itself) which contains the vtable pointer for the current
12793              class from the DW_AT_containing_type attribute.  This use of
12794              DW_AT_containing_type is a GNU extension.  */
12795
12796           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12797             {
12798               struct type *t = die_containing_type (die, cu);
12799
12800               TYPE_VPTR_BASETYPE (type) = t;
12801               if (type == t)
12802                 {
12803                   int i;
12804
12805                   /* Our own class provides vtbl ptr.  */
12806                   for (i = TYPE_NFIELDS (t) - 1;
12807                        i >= TYPE_N_BASECLASSES (t);
12808                        --i)
12809                     {
12810                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12811
12812                       if (is_vtable_name (fieldname, cu))
12813                         {
12814                           TYPE_VPTR_FIELDNO (type) = i;
12815                           break;
12816                         }
12817                     }
12818
12819                   /* Complain if virtual function table field not found.  */
12820                   if (i < TYPE_N_BASECLASSES (t))
12821                     complaint (&symfile_complaints,
12822                                _("virtual function table pointer "
12823                                  "not found when defining class '%s'"),
12824                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12825                                "");
12826                 }
12827               else
12828                 {
12829                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12830                 }
12831             }
12832           else if (cu->producer
12833                    && strncmp (cu->producer,
12834                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12835             {
12836               /* The IBM XLC compiler does not provide direct indication
12837                  of the containing type, but the vtable pointer is
12838                  always named __vfp.  */
12839
12840               int i;
12841
12842               for (i = TYPE_NFIELDS (type) - 1;
12843                    i >= TYPE_N_BASECLASSES (type);
12844                    --i)
12845                 {
12846                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12847                     {
12848                       TYPE_VPTR_FIELDNO (type) = i;
12849                       TYPE_VPTR_BASETYPE (type) = type;
12850                       break;
12851                     }
12852                 }
12853             }
12854         }
12855
12856       /* Copy fi.typedef_field_list linked list elements content into the
12857          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12858       if (fi.typedef_field_list)
12859         {
12860           int i = fi.typedef_field_list_count;
12861
12862           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12863           TYPE_TYPEDEF_FIELD_ARRAY (type)
12864             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12865           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12866
12867           /* Reverse the list order to keep the debug info elements order.  */
12868           while (--i >= 0)
12869             {
12870               struct typedef_field *dest, *src;
12871
12872               dest = &TYPE_TYPEDEF_FIELD (type, i);
12873               src = &fi.typedef_field_list->field;
12874               fi.typedef_field_list = fi.typedef_field_list->next;
12875               *dest = *src;
12876             }
12877         }
12878
12879       do_cleanups (back_to);
12880
12881       if (HAVE_CPLUS_STRUCT (type))
12882         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12883     }
12884
12885   quirk_gcc_member_function_pointer (type, objfile);
12886
12887   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12888      snapshots) has been known to create a die giving a declaration
12889      for a class that has, as a child, a die giving a definition for a
12890      nested class.  So we have to process our children even if the
12891      current die is a declaration.  Normally, of course, a declaration
12892      won't have any children at all.  */
12893
12894   while (child_die != NULL && child_die->tag)
12895     {
12896       if (child_die->tag == DW_TAG_member
12897           || child_die->tag == DW_TAG_variable
12898           || child_die->tag == DW_TAG_inheritance
12899           || child_die->tag == DW_TAG_template_value_param
12900           || child_die->tag == DW_TAG_template_type_param)
12901         {
12902           /* Do nothing.  */
12903         }
12904       else
12905         process_die (child_die, cu);
12906
12907       child_die = sibling_die (child_die);
12908     }
12909
12910   /* Do not consider external references.  According to the DWARF standard,
12911      these DIEs are identified by the fact that they have no byte_size
12912      attribute, and a declaration attribute.  */
12913   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12914       || !die_is_declaration (die, cu))
12915     new_symbol (die, type, cu);
12916 }
12917
12918 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12919    complete the type's fields yet, or create any symbols.  */
12920
12921 static struct type *
12922 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12923 {
12924   struct objfile *objfile = cu->objfile;
12925   struct type *type;
12926   struct attribute *attr;
12927   const char *name;
12928
12929   /* If the definition of this type lives in .debug_types, read that type.
12930      Don't follow DW_AT_specification though, that will take us back up
12931      the chain and we want to go down.  */
12932   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12933   if (attr)
12934     {
12935       type = get_DW_AT_signature_type (die, attr, cu);
12936
12937       /* The type's CU may not be the same as CU.
12938          Ensure TYPE is recorded with CU in die_type_hash.  */
12939       return set_die_type (die, type, cu);
12940     }
12941
12942   type = alloc_type (objfile);
12943
12944   TYPE_CODE (type) = TYPE_CODE_ENUM;
12945   name = dwarf2_full_name (NULL, die, cu);
12946   if (name != NULL)
12947     TYPE_TAG_NAME (type) = name;
12948
12949   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12950   if (attr)
12951     {
12952       TYPE_LENGTH (type) = DW_UNSND (attr);
12953     }
12954   else
12955     {
12956       TYPE_LENGTH (type) = 0;
12957     }
12958
12959   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12960      declared as private in the package spec, and then defined only
12961      inside the package body.  Such types are known as Taft Amendment
12962      Types.  When another package uses such a type, an incomplete DIE
12963      may be generated by the compiler.  */
12964   if (die_is_declaration (die, cu))
12965     TYPE_STUB (type) = 1;
12966
12967   return set_die_type (die, type, cu);
12968 }
12969
12970 /* Given a pointer to a die which begins an enumeration, process all
12971    the dies that define the members of the enumeration, and create the
12972    symbol for the enumeration type.
12973
12974    NOTE: We reverse the order of the element list.  */
12975
12976 static void
12977 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12978 {
12979   struct type *this_type;
12980
12981   this_type = get_die_type (die, cu);
12982   if (this_type == NULL)
12983     this_type = read_enumeration_type (die, cu);
12984
12985   if (die->child != NULL)
12986     {
12987       struct die_info *child_die;
12988       struct symbol *sym;
12989       struct field *fields = NULL;
12990       int num_fields = 0;
12991       int unsigned_enum = 1;
12992       const char *name;
12993       int flag_enum = 1;
12994       ULONGEST mask = 0;
12995
12996       child_die = die->child;
12997       while (child_die && child_die->tag)
12998         {
12999           if (child_die->tag != DW_TAG_enumerator)
13000             {
13001               process_die (child_die, cu);
13002             }
13003           else
13004             {
13005               name = dwarf2_name (child_die, cu);
13006               if (name)
13007                 {
13008                   sym = new_symbol (child_die, this_type, cu);
13009                   if (SYMBOL_VALUE (sym) < 0)
13010                     {
13011                       unsigned_enum = 0;
13012                       flag_enum = 0;
13013                     }
13014                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
13015                     flag_enum = 0;
13016                   else
13017                     mask |= SYMBOL_VALUE (sym);
13018
13019                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
13020                     {
13021                       fields = (struct field *)
13022                         xrealloc (fields,
13023                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
13024                                   * sizeof (struct field));
13025                     }
13026
13027                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
13028                   FIELD_TYPE (fields[num_fields]) = NULL;
13029                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
13030                   FIELD_BITSIZE (fields[num_fields]) = 0;
13031
13032                   num_fields++;
13033                 }
13034             }
13035
13036           child_die = sibling_die (child_die);
13037         }
13038
13039       if (num_fields)
13040         {
13041           TYPE_NFIELDS (this_type) = num_fields;
13042           TYPE_FIELDS (this_type) = (struct field *)
13043             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
13044           memcpy (TYPE_FIELDS (this_type), fields,
13045                   sizeof (struct field) * num_fields);
13046           xfree (fields);
13047         }
13048       if (unsigned_enum)
13049         TYPE_UNSIGNED (this_type) = 1;
13050       if (flag_enum)
13051         TYPE_FLAG_ENUM (this_type) = 1;
13052     }
13053
13054   /* If we are reading an enum from a .debug_types unit, and the enum
13055      is a declaration, and the enum is not the signatured type in the
13056      unit, then we do not want to add a symbol for it.  Adding a
13057      symbol would in some cases obscure the true definition of the
13058      enum, giving users an incomplete type when the definition is
13059      actually available.  Note that we do not want to do this for all
13060      enums which are just declarations, because C++0x allows forward
13061      enum declarations.  */
13062   if (cu->per_cu->is_debug_types
13063       && die_is_declaration (die, cu))
13064     {
13065       struct signatured_type *sig_type;
13066
13067       sig_type = (struct signatured_type *) cu->per_cu;
13068       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
13069       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
13070         return;
13071     }
13072
13073   new_symbol (die, this_type, cu);
13074 }
13075
13076 /* Extract all information from a DW_TAG_array_type DIE and put it in
13077    the DIE's type field.  For now, this only handles one dimensional
13078    arrays.  */
13079
13080 static struct type *
13081 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
13082 {
13083   struct objfile *objfile = cu->objfile;
13084   struct die_info *child_die;
13085   struct type *type;
13086   struct type *element_type, *range_type, *index_type;
13087   struct type **range_types = NULL;
13088   struct attribute *attr;
13089   int ndim = 0;
13090   struct cleanup *back_to;
13091   const char *name;
13092
13093   element_type = die_type (die, cu);
13094
13095   /* The die_type call above may have already set the type for this DIE.  */
13096   type = get_die_type (die, cu);
13097   if (type)
13098     return type;
13099
13100   /* Irix 6.2 native cc creates array types without children for
13101      arrays with unspecified length.  */
13102   if (die->child == NULL)
13103     {
13104       index_type = objfile_type (objfile)->builtin_int;
13105       range_type = create_range_type (NULL, index_type, 0, -1);
13106       type = create_array_type (NULL, element_type, range_type);
13107       return set_die_type (die, type, cu);
13108     }
13109
13110   back_to = make_cleanup (null_cleanup, NULL);
13111   child_die = die->child;
13112   while (child_die && child_die->tag)
13113     {
13114       if (child_die->tag == DW_TAG_subrange_type)
13115         {
13116           struct type *child_type = read_type_die (child_die, cu);
13117
13118           if (child_type != NULL)
13119             {
13120               /* The range type was succesfully read.  Save it for the
13121                  array type creation.  */
13122               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
13123                 {
13124                   range_types = (struct type **)
13125                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
13126                               * sizeof (struct type *));
13127                   if (ndim == 0)
13128                     make_cleanup (free_current_contents, &range_types);
13129                 }
13130               range_types[ndim++] = child_type;
13131             }
13132         }
13133       child_die = sibling_die (child_die);
13134     }
13135
13136   /* Dwarf2 dimensions are output from left to right, create the
13137      necessary array types in backwards order.  */
13138
13139   type = element_type;
13140
13141   if (read_array_order (die, cu) == DW_ORD_col_major)
13142     {
13143       int i = 0;
13144
13145       while (i < ndim)
13146         type = create_array_type (NULL, type, range_types[i++]);
13147     }
13148   else
13149     {
13150       while (ndim-- > 0)
13151         type = create_array_type (NULL, type, range_types[ndim]);
13152     }
13153
13154   /* Understand Dwarf2 support for vector types (like they occur on
13155      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
13156      array type.  This is not part of the Dwarf2/3 standard yet, but a
13157      custom vendor extension.  The main difference between a regular
13158      array and the vector variant is that vectors are passed by value
13159      to functions.  */
13160   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
13161   if (attr)
13162     make_vector_type (type);
13163
13164   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
13165      implementation may choose to implement triple vectors using this
13166      attribute.  */
13167   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13168   if (attr)
13169     {
13170       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
13171         TYPE_LENGTH (type) = DW_UNSND (attr);
13172       else
13173         complaint (&symfile_complaints,
13174                    _("DW_AT_byte_size for array type smaller "
13175                      "than the total size of elements"));
13176     }
13177
13178   name = dwarf2_name (die, cu);
13179   if (name)
13180     TYPE_NAME (type) = name;
13181
13182   /* Install the type in the die.  */
13183   set_die_type (die, type, cu);
13184
13185   /* set_die_type should be already done.  */
13186   set_descriptive_type (type, die, cu);
13187
13188   do_cleanups (back_to);
13189
13190   return type;
13191 }
13192
13193 static enum dwarf_array_dim_ordering
13194 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
13195 {
13196   struct attribute *attr;
13197
13198   attr = dwarf2_attr (die, DW_AT_ordering, cu);
13199
13200   if (attr) return DW_SND (attr);
13201
13202   /* GNU F77 is a special case, as at 08/2004 array type info is the
13203      opposite order to the dwarf2 specification, but data is still
13204      laid out as per normal fortran.
13205
13206      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
13207      version checking.  */
13208
13209   if (cu->language == language_fortran
13210       && cu->producer && strstr (cu->producer, "GNU F77"))
13211     {
13212       return DW_ORD_row_major;
13213     }
13214
13215   switch (cu->language_defn->la_array_ordering)
13216     {
13217     case array_column_major:
13218       return DW_ORD_col_major;
13219     case array_row_major:
13220     default:
13221       return DW_ORD_row_major;
13222     };
13223 }
13224
13225 /* Extract all information from a DW_TAG_set_type DIE and put it in
13226    the DIE's type field.  */
13227
13228 static struct type *
13229 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
13230 {
13231   struct type *domain_type, *set_type;
13232   struct attribute *attr;
13233
13234   domain_type = die_type (die, cu);
13235
13236   /* The die_type call above may have already set the type for this DIE.  */
13237   set_type = get_die_type (die, cu);
13238   if (set_type)
13239     return set_type;
13240
13241   set_type = create_set_type (NULL, domain_type);
13242
13243   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13244   if (attr)
13245     TYPE_LENGTH (set_type) = DW_UNSND (attr);
13246
13247   return set_die_type (die, set_type, cu);
13248 }
13249
13250 /* A helper for read_common_block that creates a locexpr baton.
13251    SYM is the symbol which we are marking as computed.
13252    COMMON_DIE is the DIE for the common block.
13253    COMMON_LOC is the location expression attribute for the common
13254    block itself.
13255    MEMBER_LOC is the location expression attribute for the particular
13256    member of the common block that we are processing.
13257    CU is the CU from which the above come.  */
13258
13259 static void
13260 mark_common_block_symbol_computed (struct symbol *sym,
13261                                    struct die_info *common_die,
13262                                    struct attribute *common_loc,
13263                                    struct attribute *member_loc,
13264                                    struct dwarf2_cu *cu)
13265 {
13266   struct objfile *objfile = dwarf2_per_objfile->objfile;
13267   struct dwarf2_locexpr_baton *baton;
13268   gdb_byte *ptr;
13269   unsigned int cu_off;
13270   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
13271   LONGEST offset = 0;
13272
13273   gdb_assert (common_loc && member_loc);
13274   gdb_assert (attr_form_is_block (common_loc));
13275   gdb_assert (attr_form_is_block (member_loc)
13276               || attr_form_is_constant (member_loc));
13277
13278   baton = obstack_alloc (&objfile->objfile_obstack,
13279                          sizeof (struct dwarf2_locexpr_baton));
13280   baton->per_cu = cu->per_cu;
13281   gdb_assert (baton->per_cu);
13282
13283   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
13284
13285   if (attr_form_is_constant (member_loc))
13286     {
13287       offset = dwarf2_get_attr_constant_value (member_loc, 0);
13288       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
13289     }
13290   else
13291     baton->size += DW_BLOCK (member_loc)->size;
13292
13293   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
13294   baton->data = ptr;
13295
13296   *ptr++ = DW_OP_call4;
13297   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
13298   store_unsigned_integer (ptr, 4, byte_order, cu_off);
13299   ptr += 4;
13300
13301   if (attr_form_is_constant (member_loc))
13302     {
13303       *ptr++ = DW_OP_addr;
13304       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
13305       ptr += cu->header.addr_size;
13306     }
13307   else
13308     {
13309       /* We have to copy the data here, because DW_OP_call4 will only
13310          use a DW_AT_location attribute.  */
13311       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
13312       ptr += DW_BLOCK (member_loc)->size;
13313     }
13314
13315   *ptr++ = DW_OP_plus;
13316   gdb_assert (ptr - baton->data == baton->size);
13317
13318   SYMBOL_LOCATION_BATON (sym) = baton;
13319   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
13320 }
13321
13322 /* Create appropriate locally-scoped variables for all the
13323    DW_TAG_common_block entries.  Also create a struct common_block
13324    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
13325    is used to sepate the common blocks name namespace from regular
13326    variable names.  */
13327
13328 static void
13329 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
13330 {
13331   struct attribute *attr;
13332
13333   attr = dwarf2_attr (die, DW_AT_location, cu);
13334   if (attr)
13335     {
13336       /* Support the .debug_loc offsets.  */
13337       if (attr_form_is_block (attr))
13338         {
13339           /* Ok.  */
13340         }
13341       else if (attr_form_is_section_offset (attr))
13342         {
13343           dwarf2_complex_location_expr_complaint ();
13344           attr = NULL;
13345         }
13346       else
13347         {
13348           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13349                                                  "common block member");
13350           attr = NULL;
13351         }
13352     }
13353
13354   if (die->child != NULL)
13355     {
13356       struct objfile *objfile = cu->objfile;
13357       struct die_info *child_die;
13358       size_t n_entries = 0, size;
13359       struct common_block *common_block;
13360       struct symbol *sym;
13361
13362       for (child_die = die->child;
13363            child_die && child_die->tag;
13364            child_die = sibling_die (child_die))
13365         ++n_entries;
13366
13367       size = (sizeof (struct common_block)
13368               + (n_entries - 1) * sizeof (struct symbol *));
13369       common_block = obstack_alloc (&objfile->objfile_obstack, size);
13370       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
13371       common_block->n_entries = 0;
13372
13373       for (child_die = die->child;
13374            child_die && child_die->tag;
13375            child_die = sibling_die (child_die))
13376         {
13377           /* Create the symbol in the DW_TAG_common_block block in the current
13378              symbol scope.  */
13379           sym = new_symbol (child_die, NULL, cu);
13380           if (sym != NULL)
13381             {
13382               struct attribute *member_loc;
13383
13384               common_block->contents[common_block->n_entries++] = sym;
13385
13386               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
13387                                         cu);
13388               if (member_loc)
13389                 {
13390                   /* GDB has handled this for a long time, but it is
13391                      not specified by DWARF.  It seems to have been
13392                      emitted by gfortran at least as recently as:
13393                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
13394                   complaint (&symfile_complaints,
13395                              _("Variable in common block has "
13396                                "DW_AT_data_member_location "
13397                                "- DIE at 0x%x [in module %s]"),
13398                              child_die->offset.sect_off,
13399                              objfile_name (cu->objfile));
13400
13401                   if (attr_form_is_section_offset (member_loc))
13402                     dwarf2_complex_location_expr_complaint ();
13403                   else if (attr_form_is_constant (member_loc)
13404                            || attr_form_is_block (member_loc))
13405                     {
13406                       if (attr)
13407                         mark_common_block_symbol_computed (sym, die, attr,
13408                                                            member_loc, cu);
13409                     }
13410                   else
13411                     dwarf2_complex_location_expr_complaint ();
13412                 }
13413             }
13414         }
13415
13416       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
13417       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
13418     }
13419 }
13420
13421 /* Create a type for a C++ namespace.  */
13422
13423 static struct type *
13424 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
13425 {
13426   struct objfile *objfile = cu->objfile;
13427   const char *previous_prefix, *name;
13428   int is_anonymous;
13429   struct type *type;
13430
13431   /* For extensions, reuse the type of the original namespace.  */
13432   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
13433     {
13434       struct die_info *ext_die;
13435       struct dwarf2_cu *ext_cu = cu;
13436
13437       ext_die = dwarf2_extension (die, &ext_cu);
13438       type = read_type_die (ext_die, ext_cu);
13439
13440       /* EXT_CU may not be the same as CU.
13441          Ensure TYPE is recorded with CU in die_type_hash.  */
13442       return set_die_type (die, type, cu);
13443     }
13444
13445   name = namespace_name (die, &is_anonymous, cu);
13446
13447   /* Now build the name of the current namespace.  */
13448
13449   previous_prefix = determine_prefix (die, cu);
13450   if (previous_prefix[0] != '\0')
13451     name = typename_concat (&objfile->objfile_obstack,
13452                             previous_prefix, name, 0, cu);
13453
13454   /* Create the type.  */
13455   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
13456                     objfile);
13457   TYPE_NAME (type) = name;
13458   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13459
13460   return set_die_type (die, type, cu);
13461 }
13462
13463 /* Read a C++ namespace.  */
13464
13465 static void
13466 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
13467 {
13468   struct objfile *objfile = cu->objfile;
13469   int is_anonymous;
13470
13471   /* Add a symbol associated to this if we haven't seen the namespace
13472      before.  Also, add a using directive if it's an anonymous
13473      namespace.  */
13474
13475   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
13476     {
13477       struct type *type;
13478
13479       type = read_type_die (die, cu);
13480       new_symbol (die, type, cu);
13481
13482       namespace_name (die, &is_anonymous, cu);
13483       if (is_anonymous)
13484         {
13485           const char *previous_prefix = determine_prefix (die, cu);
13486
13487           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
13488                                   NULL, NULL, 0, &objfile->objfile_obstack);
13489         }
13490     }
13491
13492   if (die->child != NULL)
13493     {
13494       struct die_info *child_die = die->child;
13495
13496       while (child_die && child_die->tag)
13497         {
13498           process_die (child_die, cu);
13499           child_die = sibling_die (child_die);
13500         }
13501     }
13502 }
13503
13504 /* Read a Fortran module as type.  This DIE can be only a declaration used for
13505    imported module.  Still we need that type as local Fortran "use ... only"
13506    declaration imports depend on the created type in determine_prefix.  */
13507
13508 static struct type *
13509 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
13510 {
13511   struct objfile *objfile = cu->objfile;
13512   const char *module_name;
13513   struct type *type;
13514
13515   module_name = dwarf2_name (die, cu);
13516   if (!module_name)
13517     complaint (&symfile_complaints,
13518                _("DW_TAG_module has no name, offset 0x%x"),
13519                die->offset.sect_off);
13520   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
13521
13522   /* determine_prefix uses TYPE_TAG_NAME.  */
13523   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13524
13525   return set_die_type (die, type, cu);
13526 }
13527
13528 /* Read a Fortran module.  */
13529
13530 static void
13531 read_module (struct die_info *die, struct dwarf2_cu *cu)
13532 {
13533   struct die_info *child_die = die->child;
13534
13535   while (child_die && child_die->tag)
13536     {
13537       process_die (child_die, cu);
13538       child_die = sibling_die (child_die);
13539     }
13540 }
13541
13542 /* Return the name of the namespace represented by DIE.  Set
13543    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
13544    namespace.  */
13545
13546 static const char *
13547 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
13548 {
13549   struct die_info *current_die;
13550   const char *name = NULL;
13551
13552   /* Loop through the extensions until we find a name.  */
13553
13554   for (current_die = die;
13555        current_die != NULL;
13556        current_die = dwarf2_extension (die, &cu))
13557     {
13558       name = dwarf2_name (current_die, cu);
13559       if (name != NULL)
13560         break;
13561     }
13562
13563   /* Is it an anonymous namespace?  */
13564
13565   *is_anonymous = (name == NULL);
13566   if (*is_anonymous)
13567     name = CP_ANONYMOUS_NAMESPACE_STR;
13568
13569   return name;
13570 }
13571
13572 /* Extract all information from a DW_TAG_pointer_type DIE and add to
13573    the user defined type vector.  */
13574
13575 static struct type *
13576 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
13577 {
13578   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
13579   struct comp_unit_head *cu_header = &cu->header;
13580   struct type *type;
13581   struct attribute *attr_byte_size;
13582   struct attribute *attr_address_class;
13583   int byte_size, addr_class;
13584   struct type *target_type;
13585
13586   target_type = die_type (die, cu);
13587
13588   /* The die_type call above may have already set the type for this DIE.  */
13589   type = get_die_type (die, cu);
13590   if (type)
13591     return type;
13592
13593   type = lookup_pointer_type (target_type);
13594
13595   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
13596   if (attr_byte_size)
13597     byte_size = DW_UNSND (attr_byte_size);
13598   else
13599     byte_size = cu_header->addr_size;
13600
13601   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
13602   if (attr_address_class)
13603     addr_class = DW_UNSND (attr_address_class);
13604   else
13605     addr_class = DW_ADDR_none;
13606
13607   /* If the pointer size or address class is different than the
13608      default, create a type variant marked as such and set the
13609      length accordingly.  */
13610   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
13611     {
13612       if (gdbarch_address_class_type_flags_p (gdbarch))
13613         {
13614           int type_flags;
13615
13616           type_flags = gdbarch_address_class_type_flags
13617                          (gdbarch, byte_size, addr_class);
13618           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
13619                       == 0);
13620           type = make_type_with_address_space (type, type_flags);
13621         }
13622       else if (TYPE_LENGTH (type) != byte_size)
13623         {
13624           complaint (&symfile_complaints,
13625                      _("invalid pointer size %d"), byte_size);
13626         }
13627       else
13628         {
13629           /* Should we also complain about unhandled address classes?  */
13630         }
13631     }
13632
13633   TYPE_LENGTH (type) = byte_size;
13634   return set_die_type (die, type, cu);
13635 }
13636
13637 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
13638    the user defined type vector.  */
13639
13640 static struct type *
13641 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
13642 {
13643   struct type *type;
13644   struct type *to_type;
13645   struct type *domain;
13646
13647   to_type = die_type (die, cu);
13648   domain = die_containing_type (die, cu);
13649
13650   /* The calls above may have already set the type for this DIE.  */
13651   type = get_die_type (die, cu);
13652   if (type)
13653     return type;
13654
13655   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
13656     type = lookup_methodptr_type (to_type);
13657   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
13658     {
13659       struct type *new_type = alloc_type (cu->objfile);
13660
13661       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
13662                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
13663                             TYPE_VARARGS (to_type));
13664       type = lookup_methodptr_type (new_type);
13665     }
13666   else
13667     type = lookup_memberptr_type (to_type, domain);
13668
13669   return set_die_type (die, type, cu);
13670 }
13671
13672 /* Extract all information from a DW_TAG_reference_type DIE and add to
13673    the user defined type vector.  */
13674
13675 static struct type *
13676 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
13677 {
13678   struct comp_unit_head *cu_header = &cu->header;
13679   struct type *type, *target_type;
13680   struct attribute *attr;
13681
13682   target_type = die_type (die, cu);
13683
13684   /* The die_type call above may have already set the type for this DIE.  */
13685   type = get_die_type (die, cu);
13686   if (type)
13687     return type;
13688
13689   type = lookup_reference_type (target_type);
13690   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13691   if (attr)
13692     {
13693       TYPE_LENGTH (type) = DW_UNSND (attr);
13694     }
13695   else
13696     {
13697       TYPE_LENGTH (type) = cu_header->addr_size;
13698     }
13699   return set_die_type (die, type, cu);
13700 }
13701
13702 static struct type *
13703 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
13704 {
13705   struct type *base_type, *cv_type;
13706
13707   base_type = die_type (die, cu);
13708
13709   /* The die_type call above may have already set the type for this DIE.  */
13710   cv_type = get_die_type (die, cu);
13711   if (cv_type)
13712     return cv_type;
13713
13714   /* In case the const qualifier is applied to an array type, the element type
13715      is so qualified, not the array type (section 6.7.3 of C99).  */
13716   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
13717     {
13718       struct type *el_type, *inner_array;
13719
13720       base_type = copy_type (base_type);
13721       inner_array = base_type;
13722
13723       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
13724         {
13725           TYPE_TARGET_TYPE (inner_array) =
13726             copy_type (TYPE_TARGET_TYPE (inner_array));
13727           inner_array = TYPE_TARGET_TYPE (inner_array);
13728         }
13729
13730       el_type = TYPE_TARGET_TYPE (inner_array);
13731       TYPE_TARGET_TYPE (inner_array) =
13732         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
13733
13734       return set_die_type (die, base_type, cu);
13735     }
13736
13737   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
13738   return set_die_type (die, cv_type, cu);
13739 }
13740
13741 static struct type *
13742 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
13743 {
13744   struct type *base_type, *cv_type;
13745
13746   base_type = die_type (die, cu);
13747
13748   /* The die_type call above may have already set the type for this DIE.  */
13749   cv_type = get_die_type (die, cu);
13750   if (cv_type)
13751     return cv_type;
13752
13753   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
13754   return set_die_type (die, cv_type, cu);
13755 }
13756
13757 /* Handle DW_TAG_restrict_type.  */
13758
13759 static struct type *
13760 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13761 {
13762   struct type *base_type, *cv_type;
13763
13764   base_type = die_type (die, cu);
13765
13766   /* The die_type call above may have already set the type for this DIE.  */
13767   cv_type = get_die_type (die, cu);
13768   if (cv_type)
13769     return cv_type;
13770
13771   cv_type = make_restrict_type (base_type);
13772   return set_die_type (die, cv_type, cu);
13773 }
13774
13775 /* Extract all information from a DW_TAG_string_type DIE and add to
13776    the user defined type vector.  It isn't really a user defined type,
13777    but it behaves like one, with other DIE's using an AT_user_def_type
13778    attribute to reference it.  */
13779
13780 static struct type *
13781 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13782 {
13783   struct objfile *objfile = cu->objfile;
13784   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13785   struct type *type, *range_type, *index_type, *char_type;
13786   struct attribute *attr;
13787   unsigned int length;
13788
13789   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13790   if (attr)
13791     {
13792       length = DW_UNSND (attr);
13793     }
13794   else
13795     {
13796       /* Check for the DW_AT_byte_size attribute.  */
13797       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13798       if (attr)
13799         {
13800           length = DW_UNSND (attr);
13801         }
13802       else
13803         {
13804           length = 1;
13805         }
13806     }
13807
13808   index_type = objfile_type (objfile)->builtin_int;
13809   range_type = create_range_type (NULL, index_type, 1, length);
13810   char_type = language_string_char_type (cu->language_defn, gdbarch);
13811   type = create_string_type (NULL, char_type, range_type);
13812
13813   return set_die_type (die, type, cu);
13814 }
13815
13816 /* Assuming that DIE corresponds to a function, returns nonzero
13817    if the function is prototyped.  */
13818
13819 static int
13820 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13821 {
13822   struct attribute *attr;
13823
13824   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13825   if (attr && (DW_UNSND (attr) != 0))
13826     return 1;
13827
13828   /* The DWARF standard implies that the DW_AT_prototyped attribute
13829      is only meaninful for C, but the concept also extends to other
13830      languages that allow unprototyped functions (Eg: Objective C).
13831      For all other languages, assume that functions are always
13832      prototyped.  */
13833   if (cu->language != language_c
13834       && cu->language != language_objc
13835       && cu->language != language_opencl)
13836     return 1;
13837
13838   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13839      prototyped and unprototyped functions; default to prototyped,
13840      since that is more common in modern code (and RealView warns
13841      about unprototyped functions).  */
13842   if (producer_is_realview (cu->producer))
13843     return 1;
13844
13845   return 0;
13846 }
13847
13848 /* Handle DIES due to C code like:
13849
13850    struct foo
13851    {
13852    int (*funcp)(int a, long l);
13853    int b;
13854    };
13855
13856    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13857
13858 static struct type *
13859 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13860 {
13861   struct objfile *objfile = cu->objfile;
13862   struct type *type;            /* Type that this function returns.  */
13863   struct type *ftype;           /* Function that returns above type.  */
13864   struct attribute *attr;
13865
13866   type = die_type (die, cu);
13867
13868   /* The die_type call above may have already set the type for this DIE.  */
13869   ftype = get_die_type (die, cu);
13870   if (ftype)
13871     return ftype;
13872
13873   ftype = lookup_function_type (type);
13874
13875   if (prototyped_function_p (die, cu))
13876     TYPE_PROTOTYPED (ftype) = 1;
13877
13878   /* Store the calling convention in the type if it's available in
13879      the subroutine die.  Otherwise set the calling convention to
13880      the default value DW_CC_normal.  */
13881   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13882   if (attr)
13883     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13884   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13885     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13886   else
13887     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13888
13889   /* We need to add the subroutine type to the die immediately so
13890      we don't infinitely recurse when dealing with parameters
13891      declared as the same subroutine type.  */
13892   set_die_type (die, ftype, cu);
13893
13894   if (die->child != NULL)
13895     {
13896       struct type *void_type = objfile_type (objfile)->builtin_void;
13897       struct die_info *child_die;
13898       int nparams, iparams;
13899
13900       /* Count the number of parameters.
13901          FIXME: GDB currently ignores vararg functions, but knows about
13902          vararg member functions.  */
13903       nparams = 0;
13904       child_die = die->child;
13905       while (child_die && child_die->tag)
13906         {
13907           if (child_die->tag == DW_TAG_formal_parameter)
13908             nparams++;
13909           else if (child_die->tag == DW_TAG_unspecified_parameters)
13910             TYPE_VARARGS (ftype) = 1;
13911           child_die = sibling_die (child_die);
13912         }
13913
13914       /* Allocate storage for parameters and fill them in.  */
13915       TYPE_NFIELDS (ftype) = nparams;
13916       TYPE_FIELDS (ftype) = (struct field *)
13917         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13918
13919       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13920          even if we error out during the parameters reading below.  */
13921       for (iparams = 0; iparams < nparams; iparams++)
13922         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13923
13924       iparams = 0;
13925       child_die = die->child;
13926       while (child_die && child_die->tag)
13927         {
13928           if (child_die->tag == DW_TAG_formal_parameter)
13929             {
13930               struct type *arg_type;
13931
13932               /* DWARF version 2 has no clean way to discern C++
13933                  static and non-static member functions.  G++ helps
13934                  GDB by marking the first parameter for non-static
13935                  member functions (which is the this pointer) as
13936                  artificial.  We pass this information to
13937                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13938
13939                  DWARF version 3 added DW_AT_object_pointer, which GCC
13940                  4.5 does not yet generate.  */
13941               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13942               if (attr)
13943                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13944               else
13945                 {
13946                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13947
13948                   /* GCC/43521: In java, the formal parameter
13949                      "this" is sometimes not marked with DW_AT_artificial.  */
13950                   if (cu->language == language_java)
13951                     {
13952                       const char *name = dwarf2_name (child_die, cu);
13953
13954                       if (name && !strcmp (name, "this"))
13955                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13956                     }
13957                 }
13958               arg_type = die_type (child_die, cu);
13959
13960               /* RealView does not mark THIS as const, which the testsuite
13961                  expects.  GCC marks THIS as const in method definitions,
13962                  but not in the class specifications (GCC PR 43053).  */
13963               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13964                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13965                 {
13966                   int is_this = 0;
13967                   struct dwarf2_cu *arg_cu = cu;
13968                   const char *name = dwarf2_name (child_die, cu);
13969
13970                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13971                   if (attr)
13972                     {
13973                       /* If the compiler emits this, use it.  */
13974                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13975                         is_this = 1;
13976                     }
13977                   else if (name && strcmp (name, "this") == 0)
13978                     /* Function definitions will have the argument names.  */
13979                     is_this = 1;
13980                   else if (name == NULL && iparams == 0)
13981                     /* Declarations may not have the names, so like
13982                        elsewhere in GDB, assume an artificial first
13983                        argument is "this".  */
13984                     is_this = 1;
13985
13986                   if (is_this)
13987                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13988                                              arg_type, 0);
13989                 }
13990
13991               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13992               iparams++;
13993             }
13994           child_die = sibling_die (child_die);
13995         }
13996     }
13997
13998   return ftype;
13999 }
14000
14001 static struct type *
14002 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
14003 {
14004   struct objfile *objfile = cu->objfile;
14005   const char *name = NULL;
14006   struct type *this_type, *target_type;
14007
14008   name = dwarf2_full_name (NULL, die, cu);
14009   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
14010                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
14011   TYPE_NAME (this_type) = name;
14012   set_die_type (die, this_type, cu);
14013   target_type = die_type (die, cu);
14014   if (target_type != this_type)
14015     TYPE_TARGET_TYPE (this_type) = target_type;
14016   else
14017     {
14018       /* Self-referential typedefs are, it seems, not allowed by the DWARF
14019          spec and cause infinite loops in GDB.  */
14020       complaint (&symfile_complaints,
14021                  _("Self-referential DW_TAG_typedef "
14022                    "- DIE at 0x%x [in module %s]"),
14023                  die->offset.sect_off, objfile_name (objfile));
14024       TYPE_TARGET_TYPE (this_type) = NULL;
14025     }
14026   return this_type;
14027 }
14028
14029 /* Find a representation of a given base type and install
14030    it in the TYPE field of the die.  */
14031
14032 static struct type *
14033 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
14034 {
14035   struct objfile *objfile = cu->objfile;
14036   struct type *type;
14037   struct attribute *attr;
14038   int encoding = 0, size = 0;
14039   const char *name;
14040   enum type_code code = TYPE_CODE_INT;
14041   int type_flags = 0;
14042   struct type *target_type = NULL;
14043
14044   attr = dwarf2_attr (die, DW_AT_encoding, cu);
14045   if (attr)
14046     {
14047       encoding = DW_UNSND (attr);
14048     }
14049   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14050   if (attr)
14051     {
14052       size = DW_UNSND (attr);
14053     }
14054   name = dwarf2_name (die, cu);
14055   if (!name)
14056     {
14057       complaint (&symfile_complaints,
14058                  _("DW_AT_name missing from DW_TAG_base_type"));
14059     }
14060
14061   switch (encoding)
14062     {
14063       case DW_ATE_address:
14064         /* Turn DW_ATE_address into a void * pointer.  */
14065         code = TYPE_CODE_PTR;
14066         type_flags |= TYPE_FLAG_UNSIGNED;
14067         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
14068         break;
14069       case DW_ATE_boolean:
14070         code = TYPE_CODE_BOOL;
14071         type_flags |= TYPE_FLAG_UNSIGNED;
14072         break;
14073       case DW_ATE_complex_float:
14074         code = TYPE_CODE_COMPLEX;
14075         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
14076         break;
14077       case DW_ATE_decimal_float:
14078         code = TYPE_CODE_DECFLOAT;
14079         break;
14080       case DW_ATE_float:
14081         code = TYPE_CODE_FLT;
14082         break;
14083       case DW_ATE_signed:
14084         break;
14085       case DW_ATE_unsigned:
14086         type_flags |= TYPE_FLAG_UNSIGNED;
14087         if (cu->language == language_fortran
14088             && name
14089             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
14090           code = TYPE_CODE_CHAR;
14091         break;
14092       case DW_ATE_signed_char:
14093         if (cu->language == language_ada || cu->language == language_m2
14094             || cu->language == language_pascal
14095             || cu->language == language_fortran)
14096           code = TYPE_CODE_CHAR;
14097         break;
14098       case DW_ATE_unsigned_char:
14099         if (cu->language == language_ada || cu->language == language_m2
14100             || cu->language == language_pascal
14101             || cu->language == language_fortran)
14102           code = TYPE_CODE_CHAR;
14103         type_flags |= TYPE_FLAG_UNSIGNED;
14104         break;
14105       case DW_ATE_UTF:
14106         /* We just treat this as an integer and then recognize the
14107            type by name elsewhere.  */
14108         break;
14109
14110       default:
14111         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
14112                    dwarf_type_encoding_name (encoding));
14113         break;
14114     }
14115
14116   type = init_type (code, size, type_flags, NULL, objfile);
14117   TYPE_NAME (type) = name;
14118   TYPE_TARGET_TYPE (type) = target_type;
14119
14120   if (name && strcmp (name, "char") == 0)
14121     TYPE_NOSIGN (type) = 1;
14122
14123   return set_die_type (die, type, cu);
14124 }
14125
14126 /* Read the given DW_AT_subrange DIE.  */
14127
14128 static struct type *
14129 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
14130 {
14131   struct type *base_type, *orig_base_type;
14132   struct type *range_type;
14133   struct attribute *attr;
14134   LONGEST low, high;
14135   int low_default_is_valid;
14136   const char *name;
14137   LONGEST negative_mask;
14138
14139   orig_base_type = die_type (die, cu);
14140   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
14141      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
14142      creating the range type, but we use the result of check_typedef
14143      when examining properties of the type.  */
14144   base_type = check_typedef (orig_base_type);
14145
14146   /* The die_type call above may have already set the type for this DIE.  */
14147   range_type = get_die_type (die, cu);
14148   if (range_type)
14149     return range_type;
14150
14151   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
14152      omitting DW_AT_lower_bound.  */
14153   switch (cu->language)
14154     {
14155     case language_c:
14156     case language_cplus:
14157       low = 0;
14158       low_default_is_valid = 1;
14159       break;
14160     case language_fortran:
14161       low = 1;
14162       low_default_is_valid = 1;
14163       break;
14164     case language_d:
14165     case language_java:
14166     case language_objc:
14167       low = 0;
14168       low_default_is_valid = (cu->header.version >= 4);
14169       break;
14170     case language_ada:
14171     case language_m2:
14172     case language_pascal:
14173       low = 1;
14174       low_default_is_valid = (cu->header.version >= 4);
14175       break;
14176     default:
14177       low = 0;
14178       low_default_is_valid = 0;
14179       break;
14180     }
14181
14182   /* FIXME: For variable sized arrays either of these could be
14183      a variable rather than a constant value.  We'll allow it,
14184      but we don't know how to handle it.  */
14185   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
14186   if (attr)
14187     low = dwarf2_get_attr_constant_value (attr, low);
14188   else if (!low_default_is_valid)
14189     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
14190                                       "- DIE at 0x%x [in module %s]"),
14191                die->offset.sect_off, objfile_name (cu->objfile));
14192
14193   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
14194   if (attr)
14195     {
14196       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
14197         {
14198           /* GCC encodes arrays with unspecified or dynamic length
14199              with a DW_FORM_block1 attribute or a reference attribute.
14200              FIXME: GDB does not yet know how to handle dynamic
14201              arrays properly, treat them as arrays with unspecified
14202              length for now.
14203
14204              FIXME: jimb/2003-09-22: GDB does not really know
14205              how to handle arrays of unspecified length
14206              either; we just represent them as zero-length
14207              arrays.  Choose an appropriate upper bound given
14208              the lower bound we've computed above.  */
14209           high = low - 1;
14210         }
14211       else
14212         high = dwarf2_get_attr_constant_value (attr, 1);
14213     }
14214   else
14215     {
14216       attr = dwarf2_attr (die, DW_AT_count, cu);
14217       if (attr)
14218         {
14219           int count = dwarf2_get_attr_constant_value (attr, 1);
14220           high = low + count - 1;
14221         }
14222       else
14223         {
14224           /* Unspecified array length.  */
14225           high = low - 1;
14226         }
14227     }
14228
14229   /* Dwarf-2 specifications explicitly allows to create subrange types
14230      without specifying a base type.
14231      In that case, the base type must be set to the type of
14232      the lower bound, upper bound or count, in that order, if any of these
14233      three attributes references an object that has a type.
14234      If no base type is found, the Dwarf-2 specifications say that
14235      a signed integer type of size equal to the size of an address should
14236      be used.
14237      For the following C code: `extern char gdb_int [];'
14238      GCC produces an empty range DIE.
14239      FIXME: muller/2010-05-28: Possible references to object for low bound,
14240      high bound or count are not yet handled by this code.  */
14241   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
14242     {
14243       struct objfile *objfile = cu->objfile;
14244       struct gdbarch *gdbarch = get_objfile_arch (objfile);
14245       int addr_size = gdbarch_addr_bit (gdbarch) /8;
14246       struct type *int_type = objfile_type (objfile)->builtin_int;
14247
14248       /* Test "int", "long int", and "long long int" objfile types,
14249          and select the first one having a size above or equal to the
14250          architecture address size.  */
14251       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14252         base_type = int_type;
14253       else
14254         {
14255           int_type = objfile_type (objfile)->builtin_long;
14256           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14257             base_type = int_type;
14258           else
14259             {
14260               int_type = objfile_type (objfile)->builtin_long_long;
14261               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14262                 base_type = int_type;
14263             }
14264         }
14265     }
14266
14267   negative_mask =
14268     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
14269   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
14270     low |= negative_mask;
14271   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
14272     high |= negative_mask;
14273
14274   range_type = create_range_type (NULL, orig_base_type, low, high);
14275
14276   /* Mark arrays with dynamic length at least as an array of unspecified
14277      length.  GDB could check the boundary but before it gets implemented at
14278      least allow accessing the array elements.  */
14279   if (attr && attr_form_is_block (attr))
14280     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14281
14282   /* Ada expects an empty array on no boundary attributes.  */
14283   if (attr == NULL && cu->language != language_ada)
14284     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14285
14286   name = dwarf2_name (die, cu);
14287   if (name)
14288     TYPE_NAME (range_type) = name;
14289
14290   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14291   if (attr)
14292     TYPE_LENGTH (range_type) = DW_UNSND (attr);
14293
14294   set_die_type (die, range_type, cu);
14295
14296   /* set_die_type should be already done.  */
14297   set_descriptive_type (range_type, die, cu);
14298
14299   return range_type;
14300 }
14301
14302 static struct type *
14303 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
14304 {
14305   struct type *type;
14306
14307   /* For now, we only support the C meaning of an unspecified type: void.  */
14308
14309   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
14310   TYPE_NAME (type) = dwarf2_name (die, cu);
14311
14312   return set_die_type (die, type, cu);
14313 }
14314
14315 /* Read a single die and all its descendents.  Set the die's sibling
14316    field to NULL; set other fields in the die correctly, and set all
14317    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
14318    location of the info_ptr after reading all of those dies.  PARENT
14319    is the parent of the die in question.  */
14320
14321 static struct die_info *
14322 read_die_and_children (const struct die_reader_specs *reader,
14323                        const gdb_byte *info_ptr,
14324                        const gdb_byte **new_info_ptr,
14325                        struct die_info *parent)
14326 {
14327   struct die_info *die;
14328   const gdb_byte *cur_ptr;
14329   int has_children;
14330
14331   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
14332   if (die == NULL)
14333     {
14334       *new_info_ptr = cur_ptr;
14335       return NULL;
14336     }
14337   store_in_ref_table (die, reader->cu);
14338
14339   if (has_children)
14340     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
14341   else
14342     {
14343       die->child = NULL;
14344       *new_info_ptr = cur_ptr;
14345     }
14346
14347   die->sibling = NULL;
14348   die->parent = parent;
14349   return die;
14350 }
14351
14352 /* Read a die, all of its descendents, and all of its siblings; set
14353    all of the fields of all of the dies correctly.  Arguments are as
14354    in read_die_and_children.  */
14355
14356 static struct die_info *
14357 read_die_and_siblings_1 (const struct die_reader_specs *reader,
14358                          const gdb_byte *info_ptr,
14359                          const gdb_byte **new_info_ptr,
14360                          struct die_info *parent)
14361 {
14362   struct die_info *first_die, *last_sibling;
14363   const gdb_byte *cur_ptr;
14364
14365   cur_ptr = info_ptr;
14366   first_die = last_sibling = NULL;
14367
14368   while (1)
14369     {
14370       struct die_info *die
14371         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
14372
14373       if (die == NULL)
14374         {
14375           *new_info_ptr = cur_ptr;
14376           return first_die;
14377         }
14378
14379       if (!first_die)
14380         first_die = die;
14381       else
14382         last_sibling->sibling = die;
14383
14384       last_sibling = die;
14385     }
14386 }
14387
14388 /* Read a die, all of its descendents, and all of its siblings; set
14389    all of the fields of all of the dies correctly.  Arguments are as
14390    in read_die_and_children.
14391    This the main entry point for reading a DIE and all its children.  */
14392
14393 static struct die_info *
14394 read_die_and_siblings (const struct die_reader_specs *reader,
14395                        const gdb_byte *info_ptr,
14396                        const gdb_byte **new_info_ptr,
14397                        struct die_info *parent)
14398 {
14399   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
14400                                                   new_info_ptr, parent);
14401
14402   if (dwarf2_die_debug)
14403     {
14404       fprintf_unfiltered (gdb_stdlog,
14405                           "Read die from %s@0x%x of %s:\n",
14406                           get_section_name (reader->die_section),
14407                           (unsigned) (info_ptr - reader->die_section->buffer),
14408                           bfd_get_filename (reader->abfd));
14409       dump_die (die, dwarf2_die_debug);
14410     }
14411
14412   return die;
14413 }
14414
14415 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
14416    attributes.
14417    The caller is responsible for filling in the extra attributes
14418    and updating (*DIEP)->num_attrs.
14419    Set DIEP to point to a newly allocated die with its information,
14420    except for its child, sibling, and parent fields.
14421    Set HAS_CHILDREN to tell whether the die has children or not.  */
14422
14423 static const gdb_byte *
14424 read_full_die_1 (const struct die_reader_specs *reader,
14425                  struct die_info **diep, const gdb_byte *info_ptr,
14426                  int *has_children, int num_extra_attrs)
14427 {
14428   unsigned int abbrev_number, bytes_read, i;
14429   sect_offset offset;
14430   struct abbrev_info *abbrev;
14431   struct die_info *die;
14432   struct dwarf2_cu *cu = reader->cu;
14433   bfd *abfd = reader->abfd;
14434
14435   offset.sect_off = info_ptr - reader->buffer;
14436   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14437   info_ptr += bytes_read;
14438   if (!abbrev_number)
14439     {
14440       *diep = NULL;
14441       *has_children = 0;
14442       return info_ptr;
14443     }
14444
14445   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
14446   if (!abbrev)
14447     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
14448            abbrev_number,
14449            bfd_get_filename (abfd));
14450
14451   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
14452   die->offset = offset;
14453   die->tag = abbrev->tag;
14454   die->abbrev = abbrev_number;
14455
14456   /* Make the result usable.
14457      The caller needs to update num_attrs after adding the extra
14458      attributes.  */
14459   die->num_attrs = abbrev->num_attrs;
14460
14461   for (i = 0; i < abbrev->num_attrs; ++i)
14462     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
14463                                info_ptr);
14464
14465   *diep = die;
14466   *has_children = abbrev->has_children;
14467   return info_ptr;
14468 }
14469
14470 /* Read a die and all its attributes.
14471    Set DIEP to point to a newly allocated die with its information,
14472    except for its child, sibling, and parent fields.
14473    Set HAS_CHILDREN to tell whether the die has children or not.  */
14474
14475 static const gdb_byte *
14476 read_full_die (const struct die_reader_specs *reader,
14477                struct die_info **diep, const gdb_byte *info_ptr,
14478                int *has_children)
14479 {
14480   const gdb_byte *result;
14481
14482   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
14483
14484   if (dwarf2_die_debug)
14485     {
14486       fprintf_unfiltered (gdb_stdlog,
14487                           "Read die from %s@0x%x of %s:\n",
14488                           get_section_name (reader->die_section),
14489                           (unsigned) (info_ptr - reader->die_section->buffer),
14490                           bfd_get_filename (reader->abfd));
14491       dump_die (*diep, dwarf2_die_debug);
14492     }
14493
14494   return result;
14495 }
14496 \f
14497 /* Abbreviation tables.
14498
14499    In DWARF version 2, the description of the debugging information is
14500    stored in a separate .debug_abbrev section.  Before we read any
14501    dies from a section we read in all abbreviations and install them
14502    in a hash table.  */
14503
14504 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
14505
14506 static struct abbrev_info *
14507 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
14508 {
14509   struct abbrev_info *abbrev;
14510
14511   abbrev = (struct abbrev_info *)
14512     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
14513   memset (abbrev, 0, sizeof (struct abbrev_info));
14514   return abbrev;
14515 }
14516
14517 /* Add an abbreviation to the table.  */
14518
14519 static void
14520 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
14521                          unsigned int abbrev_number,
14522                          struct abbrev_info *abbrev)
14523 {
14524   unsigned int hash_number;
14525
14526   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14527   abbrev->next = abbrev_table->abbrevs[hash_number];
14528   abbrev_table->abbrevs[hash_number] = abbrev;
14529 }
14530
14531 /* Look up an abbrev in the table.
14532    Returns NULL if the abbrev is not found.  */
14533
14534 static struct abbrev_info *
14535 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
14536                             unsigned int abbrev_number)
14537 {
14538   unsigned int hash_number;
14539   struct abbrev_info *abbrev;
14540
14541   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14542   abbrev = abbrev_table->abbrevs[hash_number];
14543
14544   while (abbrev)
14545     {
14546       if (abbrev->number == abbrev_number)
14547         return abbrev;
14548       abbrev = abbrev->next;
14549     }
14550   return NULL;
14551 }
14552
14553 /* Read in an abbrev table.  */
14554
14555 static struct abbrev_table *
14556 abbrev_table_read_table (struct dwarf2_section_info *section,
14557                          sect_offset offset)
14558 {
14559   struct objfile *objfile = dwarf2_per_objfile->objfile;
14560   bfd *abfd = get_section_bfd_owner (section);
14561   struct abbrev_table *abbrev_table;
14562   const gdb_byte *abbrev_ptr;
14563   struct abbrev_info *cur_abbrev;
14564   unsigned int abbrev_number, bytes_read, abbrev_name;
14565   unsigned int abbrev_form;
14566   struct attr_abbrev *cur_attrs;
14567   unsigned int allocated_attrs;
14568
14569   abbrev_table = XMALLOC (struct abbrev_table);
14570   abbrev_table->offset = offset;
14571   obstack_init (&abbrev_table->abbrev_obstack);
14572   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
14573                                          (ABBREV_HASH_SIZE
14574                                           * sizeof (struct abbrev_info *)));
14575   memset (abbrev_table->abbrevs, 0,
14576           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
14577
14578   dwarf2_read_section (objfile, section);
14579   abbrev_ptr = section->buffer + offset.sect_off;
14580   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14581   abbrev_ptr += bytes_read;
14582
14583   allocated_attrs = ATTR_ALLOC_CHUNK;
14584   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
14585
14586   /* Loop until we reach an abbrev number of 0.  */
14587   while (abbrev_number)
14588     {
14589       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
14590
14591       /* read in abbrev header */
14592       cur_abbrev->number = abbrev_number;
14593       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14594       abbrev_ptr += bytes_read;
14595       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
14596       abbrev_ptr += 1;
14597
14598       /* now read in declarations */
14599       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14600       abbrev_ptr += bytes_read;
14601       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14602       abbrev_ptr += bytes_read;
14603       while (abbrev_name)
14604         {
14605           if (cur_abbrev->num_attrs == allocated_attrs)
14606             {
14607               allocated_attrs += ATTR_ALLOC_CHUNK;
14608               cur_attrs
14609                 = xrealloc (cur_attrs, (allocated_attrs
14610                                         * sizeof (struct attr_abbrev)));
14611             }
14612
14613           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
14614           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
14615           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14616           abbrev_ptr += bytes_read;
14617           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14618           abbrev_ptr += bytes_read;
14619         }
14620
14621       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
14622                                          (cur_abbrev->num_attrs
14623                                           * sizeof (struct attr_abbrev)));
14624       memcpy (cur_abbrev->attrs, cur_attrs,
14625               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
14626
14627       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
14628
14629       /* Get next abbreviation.
14630          Under Irix6 the abbreviations for a compilation unit are not
14631          always properly terminated with an abbrev number of 0.
14632          Exit loop if we encounter an abbreviation which we have
14633          already read (which means we are about to read the abbreviations
14634          for the next compile unit) or if the end of the abbreviation
14635          table is reached.  */
14636       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
14637         break;
14638       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14639       abbrev_ptr += bytes_read;
14640       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
14641         break;
14642     }
14643
14644   xfree (cur_attrs);
14645   return abbrev_table;
14646 }
14647
14648 /* Free the resources held by ABBREV_TABLE.  */
14649
14650 static void
14651 abbrev_table_free (struct abbrev_table *abbrev_table)
14652 {
14653   obstack_free (&abbrev_table->abbrev_obstack, NULL);
14654   xfree (abbrev_table);
14655 }
14656
14657 /* Same as abbrev_table_free but as a cleanup.
14658    We pass in a pointer to the pointer to the table so that we can
14659    set the pointer to NULL when we're done.  It also simplifies
14660    build_type_unit_groups.  */
14661
14662 static void
14663 abbrev_table_free_cleanup (void *table_ptr)
14664 {
14665   struct abbrev_table **abbrev_table_ptr = table_ptr;
14666
14667   if (*abbrev_table_ptr != NULL)
14668     abbrev_table_free (*abbrev_table_ptr);
14669   *abbrev_table_ptr = NULL;
14670 }
14671
14672 /* Read the abbrev table for CU from ABBREV_SECTION.  */
14673
14674 static void
14675 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
14676                      struct dwarf2_section_info *abbrev_section)
14677 {
14678   cu->abbrev_table =
14679     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
14680 }
14681
14682 /* Release the memory used by the abbrev table for a compilation unit.  */
14683
14684 static void
14685 dwarf2_free_abbrev_table (void *ptr_to_cu)
14686 {
14687   struct dwarf2_cu *cu = ptr_to_cu;
14688
14689   if (cu->abbrev_table != NULL)
14690     abbrev_table_free (cu->abbrev_table);
14691   /* Set this to NULL so that we SEGV if we try to read it later,
14692      and also because free_comp_unit verifies this is NULL.  */
14693   cu->abbrev_table = NULL;
14694 }
14695 \f
14696 /* Returns nonzero if TAG represents a type that we might generate a partial
14697    symbol for.  */
14698
14699 static int
14700 is_type_tag_for_partial (int tag)
14701 {
14702   switch (tag)
14703     {
14704 #if 0
14705     /* Some types that would be reasonable to generate partial symbols for,
14706        that we don't at present.  */
14707     case DW_TAG_array_type:
14708     case DW_TAG_file_type:
14709     case DW_TAG_ptr_to_member_type:
14710     case DW_TAG_set_type:
14711     case DW_TAG_string_type:
14712     case DW_TAG_subroutine_type:
14713 #endif
14714     case DW_TAG_base_type:
14715     case DW_TAG_class_type:
14716     case DW_TAG_interface_type:
14717     case DW_TAG_enumeration_type:
14718     case DW_TAG_structure_type:
14719     case DW_TAG_subrange_type:
14720     case DW_TAG_typedef:
14721     case DW_TAG_union_type:
14722       return 1;
14723     default:
14724       return 0;
14725     }
14726 }
14727
14728 /* Load all DIEs that are interesting for partial symbols into memory.  */
14729
14730 static struct partial_die_info *
14731 load_partial_dies (const struct die_reader_specs *reader,
14732                    const gdb_byte *info_ptr, int building_psymtab)
14733 {
14734   struct dwarf2_cu *cu = reader->cu;
14735   struct objfile *objfile = cu->objfile;
14736   struct partial_die_info *part_die;
14737   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
14738   struct abbrev_info *abbrev;
14739   unsigned int bytes_read;
14740   unsigned int load_all = 0;
14741   int nesting_level = 1;
14742
14743   parent_die = NULL;
14744   last_die = NULL;
14745
14746   gdb_assert (cu->per_cu != NULL);
14747   if (cu->per_cu->load_all_dies)
14748     load_all = 1;
14749
14750   cu->partial_dies
14751     = htab_create_alloc_ex (cu->header.length / 12,
14752                             partial_die_hash,
14753                             partial_die_eq,
14754                             NULL,
14755                             &cu->comp_unit_obstack,
14756                             hashtab_obstack_allocate,
14757                             dummy_obstack_deallocate);
14758
14759   part_die = obstack_alloc (&cu->comp_unit_obstack,
14760                             sizeof (struct partial_die_info));
14761
14762   while (1)
14763     {
14764       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14765
14766       /* A NULL abbrev means the end of a series of children.  */
14767       if (abbrev == NULL)
14768         {
14769           if (--nesting_level == 0)
14770             {
14771               /* PART_DIE was probably the last thing allocated on the
14772                  comp_unit_obstack, so we could call obstack_free
14773                  here.  We don't do that because the waste is small,
14774                  and will be cleaned up when we're done with this
14775                  compilation unit.  This way, we're also more robust
14776                  against other users of the comp_unit_obstack.  */
14777               return first_die;
14778             }
14779           info_ptr += bytes_read;
14780           last_die = parent_die;
14781           parent_die = parent_die->die_parent;
14782           continue;
14783         }
14784
14785       /* Check for template arguments.  We never save these; if
14786          they're seen, we just mark the parent, and go on our way.  */
14787       if (parent_die != NULL
14788           && cu->language == language_cplus
14789           && (abbrev->tag == DW_TAG_template_type_param
14790               || abbrev->tag == DW_TAG_template_value_param))
14791         {
14792           parent_die->has_template_arguments = 1;
14793
14794           if (!load_all)
14795             {
14796               /* We don't need a partial DIE for the template argument.  */
14797               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14798               continue;
14799             }
14800         }
14801
14802       /* We only recurse into c++ subprograms looking for template arguments.
14803          Skip their other children.  */
14804       if (!load_all
14805           && cu->language == language_cplus
14806           && parent_die != NULL
14807           && parent_die->tag == DW_TAG_subprogram)
14808         {
14809           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14810           continue;
14811         }
14812
14813       /* Check whether this DIE is interesting enough to save.  Normally
14814          we would not be interested in members here, but there may be
14815          later variables referencing them via DW_AT_specification (for
14816          static members).  */
14817       if (!load_all
14818           && !is_type_tag_for_partial (abbrev->tag)
14819           && abbrev->tag != DW_TAG_constant
14820           && abbrev->tag != DW_TAG_enumerator
14821           && abbrev->tag != DW_TAG_subprogram
14822           && abbrev->tag != DW_TAG_lexical_block
14823           && abbrev->tag != DW_TAG_variable
14824           && abbrev->tag != DW_TAG_namespace
14825           && abbrev->tag != DW_TAG_module
14826           && abbrev->tag != DW_TAG_member
14827           && abbrev->tag != DW_TAG_imported_unit)
14828         {
14829           /* Otherwise we skip to the next sibling, if any.  */
14830           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14831           continue;
14832         }
14833
14834       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14835                                    info_ptr);
14836
14837       /* This two-pass algorithm for processing partial symbols has a
14838          high cost in cache pressure.  Thus, handle some simple cases
14839          here which cover the majority of C partial symbols.  DIEs
14840          which neither have specification tags in them, nor could have
14841          specification tags elsewhere pointing at them, can simply be
14842          processed and discarded.
14843
14844          This segment is also optional; scan_partial_symbols and
14845          add_partial_symbol will handle these DIEs if we chain
14846          them in normally.  When compilers which do not emit large
14847          quantities of duplicate debug information are more common,
14848          this code can probably be removed.  */
14849
14850       /* Any complete simple types at the top level (pretty much all
14851          of them, for a language without namespaces), can be processed
14852          directly.  */
14853       if (parent_die == NULL
14854           && part_die->has_specification == 0
14855           && part_die->is_declaration == 0
14856           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14857               || part_die->tag == DW_TAG_base_type
14858               || part_die->tag == DW_TAG_subrange_type))
14859         {
14860           if (building_psymtab && part_die->name != NULL)
14861             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14862                                  VAR_DOMAIN, LOC_TYPEDEF,
14863                                  &objfile->static_psymbols,
14864                                  0, (CORE_ADDR) 0, cu->language, objfile);
14865           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14866           continue;
14867         }
14868
14869       /* The exception for DW_TAG_typedef with has_children above is
14870          a workaround of GCC PR debug/47510.  In the case of this complaint
14871          type_name_no_tag_or_error will error on such types later.
14872
14873          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14874          it could not find the child DIEs referenced later, this is checked
14875          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14876
14877       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14878         complaint (&symfile_complaints,
14879                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14880                      "- DIE at 0x%x [in module %s]"),
14881                    part_die->offset.sect_off, objfile_name (objfile));
14882
14883       /* If we're at the second level, and we're an enumerator, and
14884          our parent has no specification (meaning possibly lives in a
14885          namespace elsewhere), then we can add the partial symbol now
14886          instead of queueing it.  */
14887       if (part_die->tag == DW_TAG_enumerator
14888           && parent_die != NULL
14889           && parent_die->die_parent == NULL
14890           && parent_die->tag == DW_TAG_enumeration_type
14891           && parent_die->has_specification == 0)
14892         {
14893           if (part_die->name == NULL)
14894             complaint (&symfile_complaints,
14895                        _("malformed enumerator DIE ignored"));
14896           else if (building_psymtab)
14897             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14898                                  VAR_DOMAIN, LOC_CONST,
14899                                  (cu->language == language_cplus
14900                                   || cu->language == language_java)
14901                                  ? &objfile->global_psymbols
14902                                  : &objfile->static_psymbols,
14903                                  0, (CORE_ADDR) 0, cu->language, objfile);
14904
14905           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14906           continue;
14907         }
14908
14909       /* We'll save this DIE so link it in.  */
14910       part_die->die_parent = parent_die;
14911       part_die->die_sibling = NULL;
14912       part_die->die_child = NULL;
14913
14914       if (last_die && last_die == parent_die)
14915         last_die->die_child = part_die;
14916       else if (last_die)
14917         last_die->die_sibling = part_die;
14918
14919       last_die = part_die;
14920
14921       if (first_die == NULL)
14922         first_die = part_die;
14923
14924       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14925          find interesting need to be in the hash table, because we
14926          also have the parent/sibling/child chains; only those that we
14927          might refer to by offset later during partial symbol reading.
14928
14929          For now this means things that might have be the target of a
14930          DW_AT_specification, DW_AT_abstract_origin, or
14931          DW_AT_extension.  DW_AT_extension will refer only to
14932          namespaces; DW_AT_abstract_origin refers to functions (and
14933          many things under the function DIE, but we do not recurse
14934          into function DIEs during partial symbol reading) and
14935          possibly variables as well; DW_AT_specification refers to
14936          declarations.  Declarations ought to have the DW_AT_declaration
14937          flag.  It happens that GCC forgets to put it in sometimes, but
14938          only for functions, not for types.
14939
14940          Adding more things than necessary to the hash table is harmless
14941          except for the performance cost.  Adding too few will result in
14942          wasted time in find_partial_die, when we reread the compilation
14943          unit with load_all_dies set.  */
14944
14945       if (load_all
14946           || abbrev->tag == DW_TAG_constant
14947           || abbrev->tag == DW_TAG_subprogram
14948           || abbrev->tag == DW_TAG_variable
14949           || abbrev->tag == DW_TAG_namespace
14950           || part_die->is_declaration)
14951         {
14952           void **slot;
14953
14954           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14955                                            part_die->offset.sect_off, INSERT);
14956           *slot = part_die;
14957         }
14958
14959       part_die = obstack_alloc (&cu->comp_unit_obstack,
14960                                 sizeof (struct partial_die_info));
14961
14962       /* For some DIEs we want to follow their children (if any).  For C
14963          we have no reason to follow the children of structures; for other
14964          languages we have to, so that we can get at method physnames
14965          to infer fully qualified class names, for DW_AT_specification,
14966          and for C++ template arguments.  For C++, we also look one level
14967          inside functions to find template arguments (if the name of the
14968          function does not already contain the template arguments).
14969
14970          For Ada, we need to scan the children of subprograms and lexical
14971          blocks as well because Ada allows the definition of nested
14972          entities that could be interesting for the debugger, such as
14973          nested subprograms for instance.  */
14974       if (last_die->has_children
14975           && (load_all
14976               || last_die->tag == DW_TAG_namespace
14977               || last_die->tag == DW_TAG_module
14978               || last_die->tag == DW_TAG_enumeration_type
14979               || (cu->language == language_cplus
14980                   && last_die->tag == DW_TAG_subprogram
14981                   && (last_die->name == NULL
14982                       || strchr (last_die->name, '<') == NULL))
14983               || (cu->language != language_c
14984                   && (last_die->tag == DW_TAG_class_type
14985                       || last_die->tag == DW_TAG_interface_type
14986                       || last_die->tag == DW_TAG_structure_type
14987                       || last_die->tag == DW_TAG_union_type))
14988               || (cu->language == language_ada
14989                   && (last_die->tag == DW_TAG_subprogram
14990                       || last_die->tag == DW_TAG_lexical_block))))
14991         {
14992           nesting_level++;
14993           parent_die = last_die;
14994           continue;
14995         }
14996
14997       /* Otherwise we skip to the next sibling, if any.  */
14998       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14999
15000       /* Back to the top, do it again.  */
15001     }
15002 }
15003
15004 /* Read a minimal amount of information into the minimal die structure.  */
15005
15006 static const gdb_byte *
15007 read_partial_die (const struct die_reader_specs *reader,
15008                   struct partial_die_info *part_die,
15009                   struct abbrev_info *abbrev, unsigned int abbrev_len,
15010                   const gdb_byte *info_ptr)
15011 {
15012   struct dwarf2_cu *cu = reader->cu;
15013   struct objfile *objfile = cu->objfile;
15014   const gdb_byte *buffer = reader->buffer;
15015   unsigned int i;
15016   struct attribute attr;
15017   int has_low_pc_attr = 0;
15018   int has_high_pc_attr = 0;
15019   int high_pc_relative = 0;
15020
15021   memset (part_die, 0, sizeof (struct partial_die_info));
15022
15023   part_die->offset.sect_off = info_ptr - buffer;
15024
15025   info_ptr += abbrev_len;
15026
15027   if (abbrev == NULL)
15028     return info_ptr;
15029
15030   part_die->tag = abbrev->tag;
15031   part_die->has_children = abbrev->has_children;
15032
15033   for (i = 0; i < abbrev->num_attrs; ++i)
15034     {
15035       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
15036
15037       /* Store the data if it is of an attribute we want to keep in a
15038          partial symbol table.  */
15039       switch (attr.name)
15040         {
15041         case DW_AT_name:
15042           switch (part_die->tag)
15043             {
15044             case DW_TAG_compile_unit:
15045             case DW_TAG_partial_unit:
15046             case DW_TAG_type_unit:
15047               /* Compilation units have a DW_AT_name that is a filename, not
15048                  a source language identifier.  */
15049             case DW_TAG_enumeration_type:
15050             case DW_TAG_enumerator:
15051               /* These tags always have simple identifiers already; no need
15052                  to canonicalize them.  */
15053               part_die->name = DW_STRING (&attr);
15054               break;
15055             default:
15056               part_die->name
15057                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
15058                                             &objfile->objfile_obstack);
15059               break;
15060             }
15061           break;
15062         case DW_AT_linkage_name:
15063         case DW_AT_MIPS_linkage_name:
15064           /* Note that both forms of linkage name might appear.  We
15065              assume they will be the same, and we only store the last
15066              one we see.  */
15067           if (cu->language == language_ada)
15068             part_die->name = DW_STRING (&attr);
15069           part_die->linkage_name = DW_STRING (&attr);
15070           break;
15071         case DW_AT_low_pc:
15072           has_low_pc_attr = 1;
15073           part_die->lowpc = DW_ADDR (&attr);
15074           break;
15075         case DW_AT_high_pc:
15076           has_high_pc_attr = 1;
15077           if (attr.form == DW_FORM_addr
15078               || attr.form == DW_FORM_GNU_addr_index)
15079             part_die->highpc = DW_ADDR (&attr);
15080           else
15081             {
15082               high_pc_relative = 1;
15083               part_die->highpc = DW_UNSND (&attr);
15084             }
15085           break;
15086         case DW_AT_location:
15087           /* Support the .debug_loc offsets.  */
15088           if (attr_form_is_block (&attr))
15089             {
15090                part_die->d.locdesc = DW_BLOCK (&attr);
15091             }
15092           else if (attr_form_is_section_offset (&attr))
15093             {
15094               dwarf2_complex_location_expr_complaint ();
15095             }
15096           else
15097             {
15098               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15099                                                      "partial symbol information");
15100             }
15101           break;
15102         case DW_AT_external:
15103           part_die->is_external = DW_UNSND (&attr);
15104           break;
15105         case DW_AT_declaration:
15106           part_die->is_declaration = DW_UNSND (&attr);
15107           break;
15108         case DW_AT_type:
15109           part_die->has_type = 1;
15110           break;
15111         case DW_AT_abstract_origin:
15112         case DW_AT_specification:
15113         case DW_AT_extension:
15114           part_die->has_specification = 1;
15115           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
15116           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15117                                    || cu->per_cu->is_dwz);
15118           break;
15119         case DW_AT_sibling:
15120           /* Ignore absolute siblings, they might point outside of
15121              the current compile unit.  */
15122           if (attr.form == DW_FORM_ref_addr)
15123             complaint (&symfile_complaints,
15124                        _("ignoring absolute DW_AT_sibling"));
15125           else
15126             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
15127           break;
15128         case DW_AT_byte_size:
15129           part_die->has_byte_size = 1;
15130           break;
15131         case DW_AT_calling_convention:
15132           /* DWARF doesn't provide a way to identify a program's source-level
15133              entry point.  DW_AT_calling_convention attributes are only meant
15134              to describe functions' calling conventions.
15135
15136              However, because it's a necessary piece of information in
15137              Fortran, and because DW_CC_program is the only piece of debugging
15138              information whose definition refers to a 'main program' at all,
15139              several compilers have begun marking Fortran main programs with
15140              DW_CC_program --- even when those functions use the standard
15141              calling conventions.
15142
15143              So until DWARF specifies a way to provide this information and
15144              compilers pick up the new representation, we'll support this
15145              practice.  */
15146           if (DW_UNSND (&attr) == DW_CC_program
15147               && cu->language == language_fortran)
15148             {
15149               set_main_name (part_die->name);
15150
15151               /* As this DIE has a static linkage the name would be difficult
15152                  to look up later.  */
15153               language_of_main = language_fortran;
15154             }
15155           break;
15156         case DW_AT_inline:
15157           if (DW_UNSND (&attr) == DW_INL_inlined
15158               || DW_UNSND (&attr) == DW_INL_declared_inlined)
15159             part_die->may_be_inlined = 1;
15160           break;
15161
15162         case DW_AT_import:
15163           if (part_die->tag == DW_TAG_imported_unit)
15164             {
15165               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
15166               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15167                                   || cu->per_cu->is_dwz);
15168             }
15169           break;
15170
15171         default:
15172           break;
15173         }
15174     }
15175
15176   if (high_pc_relative)
15177     part_die->highpc += part_die->lowpc;
15178
15179   if (has_low_pc_attr && has_high_pc_attr)
15180     {
15181       /* When using the GNU linker, .gnu.linkonce. sections are used to
15182          eliminate duplicate copies of functions and vtables and such.
15183          The linker will arbitrarily choose one and discard the others.
15184          The AT_*_pc values for such functions refer to local labels in
15185          these sections.  If the section from that file was discarded, the
15186          labels are not in the output, so the relocs get a value of 0.
15187          If this is a discarded function, mark the pc bounds as invalid,
15188          so that GDB will ignore it.  */
15189       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
15190         {
15191           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15192
15193           complaint (&symfile_complaints,
15194                      _("DW_AT_low_pc %s is zero "
15195                        "for DIE at 0x%x [in module %s]"),
15196                      paddress (gdbarch, part_die->lowpc),
15197                      part_die->offset.sect_off, objfile_name (objfile));
15198         }
15199       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
15200       else if (part_die->lowpc >= part_die->highpc)
15201         {
15202           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15203
15204           complaint (&symfile_complaints,
15205                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
15206                        "for DIE at 0x%x [in module %s]"),
15207                      paddress (gdbarch, part_die->lowpc),
15208                      paddress (gdbarch, part_die->highpc),
15209                      part_die->offset.sect_off, objfile_name (objfile));
15210         }
15211       else
15212         part_die->has_pc_info = 1;
15213     }
15214
15215   return info_ptr;
15216 }
15217
15218 /* Find a cached partial DIE at OFFSET in CU.  */
15219
15220 static struct partial_die_info *
15221 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
15222 {
15223   struct partial_die_info *lookup_die = NULL;
15224   struct partial_die_info part_die;
15225
15226   part_die.offset = offset;
15227   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
15228                                     offset.sect_off);
15229
15230   return lookup_die;
15231 }
15232
15233 /* Find a partial DIE at OFFSET, which may or may not be in CU,
15234    except in the case of .debug_types DIEs which do not reference
15235    outside their CU (they do however referencing other types via
15236    DW_FORM_ref_sig8).  */
15237
15238 static struct partial_die_info *
15239 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
15240 {
15241   struct objfile *objfile = cu->objfile;
15242   struct dwarf2_per_cu_data *per_cu = NULL;
15243   struct partial_die_info *pd = NULL;
15244
15245   if (offset_in_dwz == cu->per_cu->is_dwz
15246       && offset_in_cu_p (&cu->header, offset))
15247     {
15248       pd = find_partial_die_in_comp_unit (offset, cu);
15249       if (pd != NULL)
15250         return pd;
15251       /* We missed recording what we needed.
15252          Load all dies and try again.  */
15253       per_cu = cu->per_cu;
15254     }
15255   else
15256     {
15257       /* TUs don't reference other CUs/TUs (except via type signatures).  */
15258       if (cu->per_cu->is_debug_types)
15259         {
15260           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
15261                    " external reference to offset 0x%lx [in module %s].\n"),
15262                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
15263                  bfd_get_filename (objfile->obfd));
15264         }
15265       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
15266                                                  objfile);
15267
15268       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
15269         load_partial_comp_unit (per_cu);
15270
15271       per_cu->cu->last_used = 0;
15272       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15273     }
15274
15275   /* If we didn't find it, and not all dies have been loaded,
15276      load them all and try again.  */
15277
15278   if (pd == NULL && per_cu->load_all_dies == 0)
15279     {
15280       per_cu->load_all_dies = 1;
15281
15282       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
15283          THIS_CU->cu may already be in use.  So we can't just free it and
15284          replace its DIEs with the ones we read in.  Instead, we leave those
15285          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
15286          and clobber THIS_CU->cu->partial_dies with the hash table for the new
15287          set.  */
15288       load_partial_comp_unit (per_cu);
15289
15290       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15291     }
15292
15293   if (pd == NULL)
15294     internal_error (__FILE__, __LINE__,
15295                     _("could not find partial DIE 0x%x "
15296                       "in cache [from module %s]\n"),
15297                     offset.sect_off, bfd_get_filename (objfile->obfd));
15298   return pd;
15299 }
15300
15301 /* See if we can figure out if the class lives in a namespace.  We do
15302    this by looking for a member function; its demangled name will
15303    contain namespace info, if there is any.  */
15304
15305 static void
15306 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
15307                                   struct dwarf2_cu *cu)
15308 {
15309   /* NOTE: carlton/2003-10-07: Getting the info this way changes
15310      what template types look like, because the demangler
15311      frequently doesn't give the same name as the debug info.  We
15312      could fix this by only using the demangled name to get the
15313      prefix (but see comment in read_structure_type).  */
15314
15315   struct partial_die_info *real_pdi;
15316   struct partial_die_info *child_pdi;
15317
15318   /* If this DIE (this DIE's specification, if any) has a parent, then
15319      we should not do this.  We'll prepend the parent's fully qualified
15320      name when we create the partial symbol.  */
15321
15322   real_pdi = struct_pdi;
15323   while (real_pdi->has_specification)
15324     real_pdi = find_partial_die (real_pdi->spec_offset,
15325                                  real_pdi->spec_is_dwz, cu);
15326
15327   if (real_pdi->die_parent != NULL)
15328     return;
15329
15330   for (child_pdi = struct_pdi->die_child;
15331        child_pdi != NULL;
15332        child_pdi = child_pdi->die_sibling)
15333     {
15334       if (child_pdi->tag == DW_TAG_subprogram
15335           && child_pdi->linkage_name != NULL)
15336         {
15337           char *actual_class_name
15338             = language_class_name_from_physname (cu->language_defn,
15339                                                  child_pdi->linkage_name);
15340           if (actual_class_name != NULL)
15341             {
15342               struct_pdi->name
15343                 = obstack_copy0 (&cu->objfile->objfile_obstack,
15344                                  actual_class_name,
15345                                  strlen (actual_class_name));
15346               xfree (actual_class_name);
15347             }
15348           break;
15349         }
15350     }
15351 }
15352
15353 /* Adjust PART_DIE before generating a symbol for it.  This function
15354    may set the is_external flag or change the DIE's name.  */
15355
15356 static void
15357 fixup_partial_die (struct partial_die_info *part_die,
15358                    struct dwarf2_cu *cu)
15359 {
15360   /* Once we've fixed up a die, there's no point in doing so again.
15361      This also avoids a memory leak if we were to call
15362      guess_partial_die_structure_name multiple times.  */
15363   if (part_die->fixup_called)
15364     return;
15365
15366   /* If we found a reference attribute and the DIE has no name, try
15367      to find a name in the referred to DIE.  */
15368
15369   if (part_die->name == NULL && part_die->has_specification)
15370     {
15371       struct partial_die_info *spec_die;
15372
15373       spec_die = find_partial_die (part_die->spec_offset,
15374                                    part_die->spec_is_dwz, cu);
15375
15376       fixup_partial_die (spec_die, cu);
15377
15378       if (spec_die->name)
15379         {
15380           part_die->name = spec_die->name;
15381
15382           /* Copy DW_AT_external attribute if it is set.  */
15383           if (spec_die->is_external)
15384             part_die->is_external = spec_die->is_external;
15385         }
15386     }
15387
15388   /* Set default names for some unnamed DIEs.  */
15389
15390   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
15391     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
15392
15393   /* If there is no parent die to provide a namespace, and there are
15394      children, see if we can determine the namespace from their linkage
15395      name.  */
15396   if (cu->language == language_cplus
15397       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
15398       && part_die->die_parent == NULL
15399       && part_die->has_children
15400       && (part_die->tag == DW_TAG_class_type
15401           || part_die->tag == DW_TAG_structure_type
15402           || part_die->tag == DW_TAG_union_type))
15403     guess_partial_die_structure_name (part_die, cu);
15404
15405   /* GCC might emit a nameless struct or union that has a linkage
15406      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15407   if (part_die->name == NULL
15408       && (part_die->tag == DW_TAG_class_type
15409           || part_die->tag == DW_TAG_interface_type
15410           || part_die->tag == DW_TAG_structure_type
15411           || part_die->tag == DW_TAG_union_type)
15412       && part_die->linkage_name != NULL)
15413     {
15414       char *demangled;
15415
15416       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
15417       if (demangled)
15418         {
15419           const char *base;
15420
15421           /* Strip any leading namespaces/classes, keep only the base name.
15422              DW_AT_name for named DIEs does not contain the prefixes.  */
15423           base = strrchr (demangled, ':');
15424           if (base && base > demangled && base[-1] == ':')
15425             base++;
15426           else
15427             base = demangled;
15428
15429           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
15430                                           base, strlen (base));
15431           xfree (demangled);
15432         }
15433     }
15434
15435   part_die->fixup_called = 1;
15436 }
15437
15438 /* Read an attribute value described by an attribute form.  */
15439
15440 static const gdb_byte *
15441 read_attribute_value (const struct die_reader_specs *reader,
15442                       struct attribute *attr, unsigned form,
15443                       const gdb_byte *info_ptr)
15444 {
15445   struct dwarf2_cu *cu = reader->cu;
15446   bfd *abfd = reader->abfd;
15447   struct comp_unit_head *cu_header = &cu->header;
15448   unsigned int bytes_read;
15449   struct dwarf_block *blk;
15450
15451   attr->form = form;
15452   switch (form)
15453     {
15454     case DW_FORM_ref_addr:
15455       if (cu->header.version == 2)
15456         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15457       else
15458         DW_UNSND (attr) = read_offset (abfd, info_ptr,
15459                                        &cu->header, &bytes_read);
15460       info_ptr += bytes_read;
15461       break;
15462     case DW_FORM_GNU_ref_alt:
15463       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15464       info_ptr += bytes_read;
15465       break;
15466     case DW_FORM_addr:
15467       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15468       info_ptr += bytes_read;
15469       break;
15470     case DW_FORM_block2:
15471       blk = dwarf_alloc_block (cu);
15472       blk->size = read_2_bytes (abfd, info_ptr);
15473       info_ptr += 2;
15474       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15475       info_ptr += blk->size;
15476       DW_BLOCK (attr) = blk;
15477       break;
15478     case DW_FORM_block4:
15479       blk = dwarf_alloc_block (cu);
15480       blk->size = read_4_bytes (abfd, info_ptr);
15481       info_ptr += 4;
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_data2:
15487       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
15488       info_ptr += 2;
15489       break;
15490     case DW_FORM_data4:
15491       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
15492       info_ptr += 4;
15493       break;
15494     case DW_FORM_data8:
15495       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
15496       info_ptr += 8;
15497       break;
15498     case DW_FORM_sec_offset:
15499       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15500       info_ptr += bytes_read;
15501       break;
15502     case DW_FORM_string:
15503       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
15504       DW_STRING_IS_CANONICAL (attr) = 0;
15505       info_ptr += bytes_read;
15506       break;
15507     case DW_FORM_strp:
15508       if (!cu->per_cu->is_dwz)
15509         {
15510           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
15511                                                    &bytes_read);
15512           DW_STRING_IS_CANONICAL (attr) = 0;
15513           info_ptr += bytes_read;
15514           break;
15515         }
15516       /* FALLTHROUGH */
15517     case DW_FORM_GNU_strp_alt:
15518       {
15519         struct dwz_file *dwz = dwarf2_get_dwz_file ();
15520         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
15521                                           &bytes_read);
15522
15523         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
15524         DW_STRING_IS_CANONICAL (attr) = 0;
15525         info_ptr += bytes_read;
15526       }
15527       break;
15528     case DW_FORM_exprloc:
15529     case DW_FORM_block:
15530       blk = dwarf_alloc_block (cu);
15531       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15532       info_ptr += bytes_read;
15533       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15534       info_ptr += blk->size;
15535       DW_BLOCK (attr) = blk;
15536       break;
15537     case DW_FORM_block1:
15538       blk = dwarf_alloc_block (cu);
15539       blk->size = read_1_byte (abfd, info_ptr);
15540       info_ptr += 1;
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_data1:
15546       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15547       info_ptr += 1;
15548       break;
15549     case DW_FORM_flag:
15550       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15551       info_ptr += 1;
15552       break;
15553     case DW_FORM_flag_present:
15554       DW_UNSND (attr) = 1;
15555       break;
15556     case DW_FORM_sdata:
15557       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
15558       info_ptr += bytes_read;
15559       break;
15560     case DW_FORM_udata:
15561       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15562       info_ptr += bytes_read;
15563       break;
15564     case DW_FORM_ref1:
15565       DW_UNSND (attr) = (cu->header.offset.sect_off
15566                          + read_1_byte (abfd, info_ptr));
15567       info_ptr += 1;
15568       break;
15569     case DW_FORM_ref2:
15570       DW_UNSND (attr) = (cu->header.offset.sect_off
15571                          + read_2_bytes (abfd, info_ptr));
15572       info_ptr += 2;
15573       break;
15574     case DW_FORM_ref4:
15575       DW_UNSND (attr) = (cu->header.offset.sect_off
15576                          + read_4_bytes (abfd, info_ptr));
15577       info_ptr += 4;
15578       break;
15579     case DW_FORM_ref8:
15580       DW_UNSND (attr) = (cu->header.offset.sect_off
15581                          + read_8_bytes (abfd, info_ptr));
15582       info_ptr += 8;
15583       break;
15584     case DW_FORM_ref_sig8:
15585       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
15586       info_ptr += 8;
15587       break;
15588     case DW_FORM_ref_udata:
15589       DW_UNSND (attr) = (cu->header.offset.sect_off
15590                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
15591       info_ptr += bytes_read;
15592       break;
15593     case DW_FORM_indirect:
15594       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15595       info_ptr += bytes_read;
15596       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
15597       break;
15598     case DW_FORM_GNU_addr_index:
15599       if (reader->dwo_file == NULL)
15600         {
15601           /* For now flag a hard error.
15602              Later we can turn this into a complaint.  */
15603           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15604                  dwarf_form_name (form),
15605                  bfd_get_filename (abfd));
15606         }
15607       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
15608       info_ptr += bytes_read;
15609       break;
15610     case DW_FORM_GNU_str_index:
15611       if (reader->dwo_file == NULL)
15612         {
15613           /* For now flag a hard error.
15614              Later we can turn this into a complaint if warranted.  */
15615           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15616                  dwarf_form_name (form),
15617                  bfd_get_filename (abfd));
15618         }
15619       {
15620         ULONGEST str_index =
15621           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15622
15623         DW_STRING (attr) = read_str_index (reader, cu, str_index);
15624         DW_STRING_IS_CANONICAL (attr) = 0;
15625         info_ptr += bytes_read;
15626       }
15627       break;
15628     default:
15629       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
15630              dwarf_form_name (form),
15631              bfd_get_filename (abfd));
15632     }
15633
15634   /* Super hack.  */
15635   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
15636     attr->form = DW_FORM_GNU_ref_alt;
15637
15638   /* We have seen instances where the compiler tried to emit a byte
15639      size attribute of -1 which ended up being encoded as an unsigned
15640      0xffffffff.  Although 0xffffffff is technically a valid size value,
15641      an object of this size seems pretty unlikely so we can relatively
15642      safely treat these cases as if the size attribute was invalid and
15643      treat them as zero by default.  */
15644   if (attr->name == DW_AT_byte_size
15645       && form == DW_FORM_data4
15646       && DW_UNSND (attr) >= 0xffffffff)
15647     {
15648       complaint
15649         (&symfile_complaints,
15650          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
15651          hex_string (DW_UNSND (attr)));
15652       DW_UNSND (attr) = 0;
15653     }
15654
15655   return info_ptr;
15656 }
15657
15658 /* Read an attribute described by an abbreviated attribute.  */
15659
15660 static const gdb_byte *
15661 read_attribute (const struct die_reader_specs *reader,
15662                 struct attribute *attr, struct attr_abbrev *abbrev,
15663                 const gdb_byte *info_ptr)
15664 {
15665   attr->name = abbrev->name;
15666   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
15667 }
15668
15669 /* Read dwarf information from a buffer.  */
15670
15671 static unsigned int
15672 read_1_byte (bfd *abfd, const gdb_byte *buf)
15673 {
15674   return bfd_get_8 (abfd, buf);
15675 }
15676
15677 static int
15678 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
15679 {
15680   return bfd_get_signed_8 (abfd, buf);
15681 }
15682
15683 static unsigned int
15684 read_2_bytes (bfd *abfd, const gdb_byte *buf)
15685 {
15686   return bfd_get_16 (abfd, buf);
15687 }
15688
15689 static int
15690 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
15691 {
15692   return bfd_get_signed_16 (abfd, buf);
15693 }
15694
15695 static unsigned int
15696 read_4_bytes (bfd *abfd, const gdb_byte *buf)
15697 {
15698   return bfd_get_32 (abfd, buf);
15699 }
15700
15701 static int
15702 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
15703 {
15704   return bfd_get_signed_32 (abfd, buf);
15705 }
15706
15707 static ULONGEST
15708 read_8_bytes (bfd *abfd, const gdb_byte *buf)
15709 {
15710   return bfd_get_64 (abfd, buf);
15711 }
15712
15713 static CORE_ADDR
15714 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
15715               unsigned int *bytes_read)
15716 {
15717   struct comp_unit_head *cu_header = &cu->header;
15718   CORE_ADDR retval = 0;
15719
15720   if (cu_header->signed_addr_p)
15721     {
15722       switch (cu_header->addr_size)
15723         {
15724         case 2:
15725           retval = bfd_get_signed_16 (abfd, buf);
15726           break;
15727         case 4:
15728           retval = bfd_get_signed_32 (abfd, buf);
15729           break;
15730         case 8:
15731           retval = bfd_get_signed_64 (abfd, buf);
15732           break;
15733         default:
15734           internal_error (__FILE__, __LINE__,
15735                           _("read_address: bad switch, signed [in module %s]"),
15736                           bfd_get_filename (abfd));
15737         }
15738     }
15739   else
15740     {
15741       switch (cu_header->addr_size)
15742         {
15743         case 2:
15744           retval = bfd_get_16 (abfd, buf);
15745           break;
15746         case 4:
15747           retval = bfd_get_32 (abfd, buf);
15748           break;
15749         case 8:
15750           retval = bfd_get_64 (abfd, buf);
15751           break;
15752         default:
15753           internal_error (__FILE__, __LINE__,
15754                           _("read_address: bad switch, "
15755                             "unsigned [in module %s]"),
15756                           bfd_get_filename (abfd));
15757         }
15758     }
15759
15760   *bytes_read = cu_header->addr_size;
15761   return retval;
15762 }
15763
15764 /* Read the initial length from a section.  The (draft) DWARF 3
15765    specification allows the initial length to take up either 4 bytes
15766    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15767    bytes describe the length and all offsets will be 8 bytes in length
15768    instead of 4.
15769
15770    An older, non-standard 64-bit format is also handled by this
15771    function.  The older format in question stores the initial length
15772    as an 8-byte quantity without an escape value.  Lengths greater
15773    than 2^32 aren't very common which means that the initial 4 bytes
15774    is almost always zero.  Since a length value of zero doesn't make
15775    sense for the 32-bit format, this initial zero can be considered to
15776    be an escape value which indicates the presence of the older 64-bit
15777    format.  As written, the code can't detect (old format) lengths
15778    greater than 4GB.  If it becomes necessary to handle lengths
15779    somewhat larger than 4GB, we could allow other small values (such
15780    as the non-sensical values of 1, 2, and 3) to also be used as
15781    escape values indicating the presence of the old format.
15782
15783    The value returned via bytes_read should be used to increment the
15784    relevant pointer after calling read_initial_length().
15785
15786    [ Note:  read_initial_length() and read_offset() are based on the
15787      document entitled "DWARF Debugging Information Format", revision
15788      3, draft 8, dated November 19, 2001.  This document was obtained
15789      from:
15790
15791         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15792
15793      This document is only a draft and is subject to change.  (So beware.)
15794
15795      Details regarding the older, non-standard 64-bit format were
15796      determined empirically by examining 64-bit ELF files produced by
15797      the SGI toolchain on an IRIX 6.5 machine.
15798
15799      - Kevin, July 16, 2002
15800    ] */
15801
15802 static LONGEST
15803 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15804 {
15805   LONGEST length = bfd_get_32 (abfd, buf);
15806
15807   if (length == 0xffffffff)
15808     {
15809       length = bfd_get_64 (abfd, buf + 4);
15810       *bytes_read = 12;
15811     }
15812   else if (length == 0)
15813     {
15814       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15815       length = bfd_get_64 (abfd, buf);
15816       *bytes_read = 8;
15817     }
15818   else
15819     {
15820       *bytes_read = 4;
15821     }
15822
15823   return length;
15824 }
15825
15826 /* Cover function for read_initial_length.
15827    Returns the length of the object at BUF, and stores the size of the
15828    initial length in *BYTES_READ and stores the size that offsets will be in
15829    *OFFSET_SIZE.
15830    If the initial length size is not equivalent to that specified in
15831    CU_HEADER then issue a complaint.
15832    This is useful when reading non-comp-unit headers.  */
15833
15834 static LONGEST
15835 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15836                                         const struct comp_unit_head *cu_header,
15837                                         unsigned int *bytes_read,
15838                                         unsigned int *offset_size)
15839 {
15840   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15841
15842   gdb_assert (cu_header->initial_length_size == 4
15843               || cu_header->initial_length_size == 8
15844               || cu_header->initial_length_size == 12);
15845
15846   if (cu_header->initial_length_size != *bytes_read)
15847     complaint (&symfile_complaints,
15848                _("intermixed 32-bit and 64-bit DWARF sections"));
15849
15850   *offset_size = (*bytes_read == 4) ? 4 : 8;
15851   return length;
15852 }
15853
15854 /* Read an offset from the data stream.  The size of the offset is
15855    given by cu_header->offset_size.  */
15856
15857 static LONGEST
15858 read_offset (bfd *abfd, const gdb_byte *buf,
15859              const struct comp_unit_head *cu_header,
15860              unsigned int *bytes_read)
15861 {
15862   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15863
15864   *bytes_read = cu_header->offset_size;
15865   return offset;
15866 }
15867
15868 /* Read an offset from the data stream.  */
15869
15870 static LONGEST
15871 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15872 {
15873   LONGEST retval = 0;
15874
15875   switch (offset_size)
15876     {
15877     case 4:
15878       retval = bfd_get_32 (abfd, buf);
15879       break;
15880     case 8:
15881       retval = bfd_get_64 (abfd, buf);
15882       break;
15883     default:
15884       internal_error (__FILE__, __LINE__,
15885                       _("read_offset_1: bad switch [in module %s]"),
15886                       bfd_get_filename (abfd));
15887     }
15888
15889   return retval;
15890 }
15891
15892 static const gdb_byte *
15893 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15894 {
15895   /* If the size of a host char is 8 bits, we can return a pointer
15896      to the buffer, otherwise we have to copy the data to a buffer
15897      allocated on the temporary obstack.  */
15898   gdb_assert (HOST_CHAR_BIT == 8);
15899   return buf;
15900 }
15901
15902 static const char *
15903 read_direct_string (bfd *abfd, const gdb_byte *buf,
15904                     unsigned int *bytes_read_ptr)
15905 {
15906   /* If the size of a host char is 8 bits, we can return a pointer
15907      to the string, otherwise we have to copy the string to a buffer
15908      allocated on the temporary obstack.  */
15909   gdb_assert (HOST_CHAR_BIT == 8);
15910   if (*buf == '\0')
15911     {
15912       *bytes_read_ptr = 1;
15913       return NULL;
15914     }
15915   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15916   return (const char *) buf;
15917 }
15918
15919 static const char *
15920 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15921 {
15922   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15923   if (dwarf2_per_objfile->str.buffer == NULL)
15924     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15925            bfd_get_filename (abfd));
15926   if (str_offset >= dwarf2_per_objfile->str.size)
15927     error (_("DW_FORM_strp pointing outside of "
15928              ".debug_str section [in module %s]"),
15929            bfd_get_filename (abfd));
15930   gdb_assert (HOST_CHAR_BIT == 8);
15931   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15932     return NULL;
15933   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15934 }
15935
15936 /* Read a string at offset STR_OFFSET in the .debug_str section from
15937    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15938    the string consists of a single NUL byte, return NULL; otherwise
15939    return a pointer to the string.  */
15940
15941 static const char *
15942 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15943 {
15944   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15945
15946   if (dwz->str.buffer == NULL)
15947     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15948              "section [in module %s]"),
15949            bfd_get_filename (dwz->dwz_bfd));
15950   if (str_offset >= dwz->str.size)
15951     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15952              ".debug_str section [in module %s]"),
15953            bfd_get_filename (dwz->dwz_bfd));
15954   gdb_assert (HOST_CHAR_BIT == 8);
15955   if (dwz->str.buffer[str_offset] == '\0')
15956     return NULL;
15957   return (const char *) (dwz->str.buffer + str_offset);
15958 }
15959
15960 static const char *
15961 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15962                       const struct comp_unit_head *cu_header,
15963                       unsigned int *bytes_read_ptr)
15964 {
15965   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15966
15967   return read_indirect_string_at_offset (abfd, str_offset);
15968 }
15969
15970 static ULONGEST
15971 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15972                       unsigned int *bytes_read_ptr)
15973 {
15974   ULONGEST result;
15975   unsigned int num_read;
15976   int i, shift;
15977   unsigned char byte;
15978
15979   result = 0;
15980   shift = 0;
15981   num_read = 0;
15982   i = 0;
15983   while (1)
15984     {
15985       byte = bfd_get_8 (abfd, buf);
15986       buf++;
15987       num_read++;
15988       result |= ((ULONGEST) (byte & 127) << shift);
15989       if ((byte & 128) == 0)
15990         {
15991           break;
15992         }
15993       shift += 7;
15994     }
15995   *bytes_read_ptr = num_read;
15996   return result;
15997 }
15998
15999 static LONGEST
16000 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
16001                     unsigned int *bytes_read_ptr)
16002 {
16003   LONGEST result;
16004   int i, shift, num_read;
16005   unsigned char byte;
16006
16007   result = 0;
16008   shift = 0;
16009   num_read = 0;
16010   i = 0;
16011   while (1)
16012     {
16013       byte = bfd_get_8 (abfd, buf);
16014       buf++;
16015       num_read++;
16016       result |= ((LONGEST) (byte & 127) << shift);
16017       shift += 7;
16018       if ((byte & 128) == 0)
16019         {
16020           break;
16021         }
16022     }
16023   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
16024     result |= -(((LONGEST) 1) << shift);
16025   *bytes_read_ptr = num_read;
16026   return result;
16027 }
16028
16029 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
16030    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
16031    ADDR_SIZE is the size of addresses from the CU header.  */
16032
16033 static CORE_ADDR
16034 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
16035 {
16036   struct objfile *objfile = dwarf2_per_objfile->objfile;
16037   bfd *abfd = objfile->obfd;
16038   const gdb_byte *info_ptr;
16039
16040   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
16041   if (dwarf2_per_objfile->addr.buffer == NULL)
16042     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
16043            objfile_name (objfile));
16044   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
16045     error (_("DW_FORM_addr_index pointing outside of "
16046              ".debug_addr section [in module %s]"),
16047            objfile_name (objfile));
16048   info_ptr = (dwarf2_per_objfile->addr.buffer
16049               + addr_base + addr_index * addr_size);
16050   if (addr_size == 4)
16051     return bfd_get_32 (abfd, info_ptr);
16052   else
16053     return bfd_get_64 (abfd, info_ptr);
16054 }
16055
16056 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
16057
16058 static CORE_ADDR
16059 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
16060 {
16061   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
16062 }
16063
16064 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
16065
16066 static CORE_ADDR
16067 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
16068                              unsigned int *bytes_read)
16069 {
16070   bfd *abfd = cu->objfile->obfd;
16071   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
16072
16073   return read_addr_index (cu, addr_index);
16074 }
16075
16076 /* Data structure to pass results from dwarf2_read_addr_index_reader
16077    back to dwarf2_read_addr_index.  */
16078
16079 struct dwarf2_read_addr_index_data
16080 {
16081   ULONGEST addr_base;
16082   int addr_size;
16083 };
16084
16085 /* die_reader_func for dwarf2_read_addr_index.  */
16086
16087 static void
16088 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
16089                                const gdb_byte *info_ptr,
16090                                struct die_info *comp_unit_die,
16091                                int has_children,
16092                                void *data)
16093 {
16094   struct dwarf2_cu *cu = reader->cu;
16095   struct dwarf2_read_addr_index_data *aidata =
16096     (struct dwarf2_read_addr_index_data *) data;
16097
16098   aidata->addr_base = cu->addr_base;
16099   aidata->addr_size = cu->header.addr_size;
16100 }
16101
16102 /* Given an index in .debug_addr, fetch the value.
16103    NOTE: This can be called during dwarf expression evaluation,
16104    long after the debug information has been read, and thus per_cu->cu
16105    may no longer exist.  */
16106
16107 CORE_ADDR
16108 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
16109                         unsigned int addr_index)
16110 {
16111   struct objfile *objfile = per_cu->objfile;
16112   struct dwarf2_cu *cu = per_cu->cu;
16113   ULONGEST addr_base;
16114   int addr_size;
16115
16116   /* This is intended to be called from outside this file.  */
16117   dw2_setup (objfile);
16118
16119   /* We need addr_base and addr_size.
16120      If we don't have PER_CU->cu, we have to get it.
16121      Nasty, but the alternative is storing the needed info in PER_CU,
16122      which at this point doesn't seem justified: it's not clear how frequently
16123      it would get used and it would increase the size of every PER_CU.
16124      Entry points like dwarf2_per_cu_addr_size do a similar thing
16125      so we're not in uncharted territory here.
16126      Alas we need to be a bit more complicated as addr_base is contained
16127      in the DIE.
16128
16129      We don't need to read the entire CU(/TU).
16130      We just need the header and top level die.
16131
16132      IWBN to use the aging mechanism to let us lazily later discard the CU.
16133      For now we skip this optimization.  */
16134
16135   if (cu != NULL)
16136     {
16137       addr_base = cu->addr_base;
16138       addr_size = cu->header.addr_size;
16139     }
16140   else
16141     {
16142       struct dwarf2_read_addr_index_data aidata;
16143
16144       /* Note: We can't use init_cutu_and_read_dies_simple here,
16145          we need addr_base.  */
16146       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
16147                                dwarf2_read_addr_index_reader, &aidata);
16148       addr_base = aidata.addr_base;
16149       addr_size = aidata.addr_size;
16150     }
16151
16152   return read_addr_index_1 (addr_index, addr_base, addr_size);
16153 }
16154
16155 /* Given a DW_FORM_GNU_str_index, fetch the string.
16156    This is only used by the Fission support.  */
16157
16158 static const char *
16159 read_str_index (const struct die_reader_specs *reader,
16160                 struct dwarf2_cu *cu, ULONGEST str_index)
16161 {
16162   struct objfile *objfile = dwarf2_per_objfile->objfile;
16163   const char *dwo_name = objfile_name (objfile);
16164   bfd *abfd = objfile->obfd;
16165   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
16166   struct dwarf2_section_info *str_offsets_section =
16167     &reader->dwo_file->sections.str_offsets;
16168   const gdb_byte *info_ptr;
16169   ULONGEST str_offset;
16170   static const char form_name[] = "DW_FORM_GNU_str_index";
16171
16172   dwarf2_read_section (objfile, str_section);
16173   dwarf2_read_section (objfile, str_offsets_section);
16174   if (str_section->buffer == NULL)
16175     error (_("%s used without .debug_str.dwo section"
16176              " in CU at offset 0x%lx [in module %s]"),
16177            form_name, (long) cu->header.offset.sect_off, dwo_name);
16178   if (str_offsets_section->buffer == NULL)
16179     error (_("%s used without .debug_str_offsets.dwo section"
16180              " in CU at offset 0x%lx [in module %s]"),
16181            form_name, (long) cu->header.offset.sect_off, dwo_name);
16182   if (str_index * cu->header.offset_size >= str_offsets_section->size)
16183     error (_("%s pointing outside of .debug_str_offsets.dwo"
16184              " section in CU at offset 0x%lx [in module %s]"),
16185            form_name, (long) cu->header.offset.sect_off, dwo_name);
16186   info_ptr = (str_offsets_section->buffer
16187               + str_index * cu->header.offset_size);
16188   if (cu->header.offset_size == 4)
16189     str_offset = bfd_get_32 (abfd, info_ptr);
16190   else
16191     str_offset = bfd_get_64 (abfd, info_ptr);
16192   if (str_offset >= str_section->size)
16193     error (_("Offset from %s pointing outside of"
16194              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
16195            form_name, (long) cu->header.offset.sect_off, dwo_name);
16196   return (const char *) (str_section->buffer + str_offset);
16197 }
16198
16199 /* Return the length of an LEB128 number in BUF.  */
16200
16201 static int
16202 leb128_size (const gdb_byte *buf)
16203 {
16204   const gdb_byte *begin = buf;
16205   gdb_byte byte;
16206
16207   while (1)
16208     {
16209       byte = *buf++;
16210       if ((byte & 128) == 0)
16211         return buf - begin;
16212     }
16213 }
16214
16215 static void
16216 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
16217 {
16218   switch (lang)
16219     {
16220     case DW_LANG_C89:
16221     case DW_LANG_C99:
16222     case DW_LANG_C:
16223     case DW_LANG_UPC:
16224       cu->language = language_c;
16225       break;
16226     case DW_LANG_C_plus_plus:
16227       cu->language = language_cplus;
16228       break;
16229     case DW_LANG_D:
16230       cu->language = language_d;
16231       break;
16232     case DW_LANG_Fortran77:
16233     case DW_LANG_Fortran90:
16234     case DW_LANG_Fortran95:
16235       cu->language = language_fortran;
16236       break;
16237     case DW_LANG_Go:
16238       cu->language = language_go;
16239       break;
16240     case DW_LANG_Mips_Assembler:
16241       cu->language = language_asm;
16242       break;
16243     case DW_LANG_Java:
16244       cu->language = language_java;
16245       break;
16246     case DW_LANG_Ada83:
16247     case DW_LANG_Ada95:
16248       cu->language = language_ada;
16249       break;
16250     case DW_LANG_Modula2:
16251       cu->language = language_m2;
16252       break;
16253     case DW_LANG_Pascal83:
16254       cu->language = language_pascal;
16255       break;
16256     case DW_LANG_ObjC:
16257       cu->language = language_objc;
16258       break;
16259     case DW_LANG_Cobol74:
16260     case DW_LANG_Cobol85:
16261     default:
16262       cu->language = language_minimal;
16263       break;
16264     }
16265   cu->language_defn = language_def (cu->language);
16266 }
16267
16268 /* Return the named attribute or NULL if not there.  */
16269
16270 static struct attribute *
16271 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
16272 {
16273   for (;;)
16274     {
16275       unsigned int i;
16276       struct attribute *spec = NULL;
16277
16278       for (i = 0; i < die->num_attrs; ++i)
16279         {
16280           if (die->attrs[i].name == name)
16281             return &die->attrs[i];
16282           if (die->attrs[i].name == DW_AT_specification
16283               || die->attrs[i].name == DW_AT_abstract_origin)
16284             spec = &die->attrs[i];
16285         }
16286
16287       if (!spec)
16288         break;
16289
16290       die = follow_die_ref (die, spec, &cu);
16291     }
16292
16293   return NULL;
16294 }
16295
16296 /* Return the named attribute or NULL if not there,
16297    but do not follow DW_AT_specification, etc.
16298    This is for use in contexts where we're reading .debug_types dies.
16299    Following DW_AT_specification, DW_AT_abstract_origin will take us
16300    back up the chain, and we want to go down.  */
16301
16302 static struct attribute *
16303 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
16304 {
16305   unsigned int i;
16306
16307   for (i = 0; i < die->num_attrs; ++i)
16308     if (die->attrs[i].name == name)
16309       return &die->attrs[i];
16310
16311   return NULL;
16312 }
16313
16314 /* Return non-zero iff the attribute NAME is defined for the given DIE,
16315    and holds a non-zero value.  This function should only be used for
16316    DW_FORM_flag or DW_FORM_flag_present attributes.  */
16317
16318 static int
16319 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
16320 {
16321   struct attribute *attr = dwarf2_attr (die, name, cu);
16322
16323   return (attr && DW_UNSND (attr));
16324 }
16325
16326 static int
16327 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
16328 {
16329   /* A DIE is a declaration if it has a DW_AT_declaration attribute
16330      which value is non-zero.  However, we have to be careful with
16331      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
16332      (via dwarf2_flag_true_p) follows this attribute.  So we may
16333      end up accidently finding a declaration attribute that belongs
16334      to a different DIE referenced by the specification attribute,
16335      even though the given DIE does not have a declaration attribute.  */
16336   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
16337           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
16338 }
16339
16340 /* Return the die giving the specification for DIE, if there is
16341    one.  *SPEC_CU is the CU containing DIE on input, and the CU
16342    containing the return value on output.  If there is no
16343    specification, but there is an abstract origin, that is
16344    returned.  */
16345
16346 static struct die_info *
16347 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
16348 {
16349   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
16350                                              *spec_cu);
16351
16352   if (spec_attr == NULL)
16353     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
16354
16355   if (spec_attr == NULL)
16356     return NULL;
16357   else
16358     return follow_die_ref (die, spec_attr, spec_cu);
16359 }
16360
16361 /* Free the line_header structure *LH, and any arrays and strings it
16362    refers to.
16363    NOTE: This is also used as a "cleanup" function.  */
16364
16365 static void
16366 free_line_header (struct line_header *lh)
16367 {
16368   if (lh->standard_opcode_lengths)
16369     xfree (lh->standard_opcode_lengths);
16370
16371   /* Remember that all the lh->file_names[i].name pointers are
16372      pointers into debug_line_buffer, and don't need to be freed.  */
16373   if (lh->file_names)
16374     xfree (lh->file_names);
16375
16376   /* Similarly for the include directory names.  */
16377   if (lh->include_dirs)
16378     xfree (lh->include_dirs);
16379
16380   xfree (lh);
16381 }
16382
16383 /* Add an entry to LH's include directory table.  */
16384
16385 static void
16386 add_include_dir (struct line_header *lh, const char *include_dir)
16387 {
16388   /* Grow the array if necessary.  */
16389   if (lh->include_dirs_size == 0)
16390     {
16391       lh->include_dirs_size = 1; /* for testing */
16392       lh->include_dirs = xmalloc (lh->include_dirs_size
16393                                   * sizeof (*lh->include_dirs));
16394     }
16395   else if (lh->num_include_dirs >= lh->include_dirs_size)
16396     {
16397       lh->include_dirs_size *= 2;
16398       lh->include_dirs = xrealloc (lh->include_dirs,
16399                                    (lh->include_dirs_size
16400                                     * sizeof (*lh->include_dirs)));
16401     }
16402
16403   lh->include_dirs[lh->num_include_dirs++] = include_dir;
16404 }
16405
16406 /* Add an entry to LH's file name table.  */
16407
16408 static void
16409 add_file_name (struct line_header *lh,
16410                const char *name,
16411                unsigned int dir_index,
16412                unsigned int mod_time,
16413                unsigned int length)
16414 {
16415   struct file_entry *fe;
16416
16417   /* Grow the array if necessary.  */
16418   if (lh->file_names_size == 0)
16419     {
16420       lh->file_names_size = 1; /* for testing */
16421       lh->file_names = xmalloc (lh->file_names_size
16422                                 * sizeof (*lh->file_names));
16423     }
16424   else if (lh->num_file_names >= lh->file_names_size)
16425     {
16426       lh->file_names_size *= 2;
16427       lh->file_names = xrealloc (lh->file_names,
16428                                  (lh->file_names_size
16429                                   * sizeof (*lh->file_names)));
16430     }
16431
16432   fe = &lh->file_names[lh->num_file_names++];
16433   fe->name = name;
16434   fe->dir_index = dir_index;
16435   fe->mod_time = mod_time;
16436   fe->length = length;
16437   fe->included_p = 0;
16438   fe->symtab = NULL;
16439 }
16440
16441 /* A convenience function to find the proper .debug_line section for a
16442    CU.  */
16443
16444 static struct dwarf2_section_info *
16445 get_debug_line_section (struct dwarf2_cu *cu)
16446 {
16447   struct dwarf2_section_info *section;
16448
16449   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
16450      DWO file.  */
16451   if (cu->dwo_unit && cu->per_cu->is_debug_types)
16452     section = &cu->dwo_unit->dwo_file->sections.line;
16453   else if (cu->per_cu->is_dwz)
16454     {
16455       struct dwz_file *dwz = dwarf2_get_dwz_file ();
16456
16457       section = &dwz->line;
16458     }
16459   else
16460     section = &dwarf2_per_objfile->line;
16461
16462   return section;
16463 }
16464
16465 /* Read the statement program header starting at OFFSET in
16466    .debug_line, or .debug_line.dwo.  Return a pointer
16467    to a struct line_header, allocated using xmalloc.
16468
16469    NOTE: the strings in the include directory and file name tables of
16470    the returned object point into the dwarf line section buffer,
16471    and must not be freed.  */
16472
16473 static struct line_header *
16474 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
16475 {
16476   struct cleanup *back_to;
16477   struct line_header *lh;
16478   const gdb_byte *line_ptr;
16479   unsigned int bytes_read, offset_size;
16480   int i;
16481   const char *cur_dir, *cur_file;
16482   struct dwarf2_section_info *section;
16483   bfd *abfd;
16484
16485   section = get_debug_line_section (cu);
16486   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
16487   if (section->buffer == NULL)
16488     {
16489       if (cu->dwo_unit && cu->per_cu->is_debug_types)
16490         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
16491       else
16492         complaint (&symfile_complaints, _("missing .debug_line section"));
16493       return 0;
16494     }
16495
16496   /* We can't do this until we know the section is non-empty.
16497      Only then do we know we have such a section.  */
16498   abfd = get_section_bfd_owner (section);
16499
16500   /* Make sure that at least there's room for the total_length field.
16501      That could be 12 bytes long, but we're just going to fudge that.  */
16502   if (offset + 4 >= section->size)
16503     {
16504       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16505       return 0;
16506     }
16507
16508   lh = xmalloc (sizeof (*lh));
16509   memset (lh, 0, sizeof (*lh));
16510   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
16511                           (void *) lh);
16512
16513   line_ptr = section->buffer + offset;
16514
16515   /* Read in the header.  */
16516   lh->total_length =
16517     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
16518                                             &bytes_read, &offset_size);
16519   line_ptr += bytes_read;
16520   if (line_ptr + lh->total_length > (section->buffer + section->size))
16521     {
16522       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16523       do_cleanups (back_to);
16524       return 0;
16525     }
16526   lh->statement_program_end = line_ptr + lh->total_length;
16527   lh->version = read_2_bytes (abfd, line_ptr);
16528   line_ptr += 2;
16529   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
16530   line_ptr += offset_size;
16531   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
16532   line_ptr += 1;
16533   if (lh->version >= 4)
16534     {
16535       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
16536       line_ptr += 1;
16537     }
16538   else
16539     lh->maximum_ops_per_instruction = 1;
16540
16541   if (lh->maximum_ops_per_instruction == 0)
16542     {
16543       lh->maximum_ops_per_instruction = 1;
16544       complaint (&symfile_complaints,
16545                  _("invalid maximum_ops_per_instruction "
16546                    "in `.debug_line' section"));
16547     }
16548
16549   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
16550   line_ptr += 1;
16551   lh->line_base = read_1_signed_byte (abfd, line_ptr);
16552   line_ptr += 1;
16553   lh->line_range = read_1_byte (abfd, line_ptr);
16554   line_ptr += 1;
16555   lh->opcode_base = read_1_byte (abfd, line_ptr);
16556   line_ptr += 1;
16557   lh->standard_opcode_lengths
16558     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
16559
16560   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
16561   for (i = 1; i < lh->opcode_base; ++i)
16562     {
16563       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
16564       line_ptr += 1;
16565     }
16566
16567   /* Read directory table.  */
16568   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16569     {
16570       line_ptr += bytes_read;
16571       add_include_dir (lh, cur_dir);
16572     }
16573   line_ptr += bytes_read;
16574
16575   /* Read file name table.  */
16576   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16577     {
16578       unsigned int dir_index, mod_time, length;
16579
16580       line_ptr += bytes_read;
16581       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16582       line_ptr += bytes_read;
16583       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16584       line_ptr += bytes_read;
16585       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16586       line_ptr += bytes_read;
16587
16588       add_file_name (lh, cur_file, dir_index, mod_time, length);
16589     }
16590   line_ptr += bytes_read;
16591   lh->statement_program_start = line_ptr;
16592
16593   if (line_ptr > (section->buffer + section->size))
16594     complaint (&symfile_complaints,
16595                _("line number info header doesn't "
16596                  "fit in `.debug_line' section"));
16597
16598   discard_cleanups (back_to);
16599   return lh;
16600 }
16601
16602 /* Subroutine of dwarf_decode_lines to simplify it.
16603    Return the file name of the psymtab for included file FILE_INDEX
16604    in line header LH of PST.
16605    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16606    If space for the result is malloc'd, it will be freed by a cleanup.
16607    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
16608
16609    The function creates dangling cleanup registration.  */
16610
16611 static const char *
16612 psymtab_include_file_name (const struct line_header *lh, int file_index,
16613                            const struct partial_symtab *pst,
16614                            const char *comp_dir)
16615 {
16616   const struct file_entry fe = lh->file_names [file_index];
16617   const char *include_name = fe.name;
16618   const char *include_name_to_compare = include_name;
16619   const char *dir_name = NULL;
16620   const char *pst_filename;
16621   char *copied_name = NULL;
16622   int file_is_pst;
16623
16624   if (fe.dir_index)
16625     dir_name = lh->include_dirs[fe.dir_index - 1];
16626
16627   if (!IS_ABSOLUTE_PATH (include_name)
16628       && (dir_name != NULL || comp_dir != NULL))
16629     {
16630       /* Avoid creating a duplicate psymtab for PST.
16631          We do this by comparing INCLUDE_NAME and PST_FILENAME.
16632          Before we do the comparison, however, we need to account
16633          for DIR_NAME and COMP_DIR.
16634          First prepend dir_name (if non-NULL).  If we still don't
16635          have an absolute path prepend comp_dir (if non-NULL).
16636          However, the directory we record in the include-file's
16637          psymtab does not contain COMP_DIR (to match the
16638          corresponding symtab(s)).
16639
16640          Example:
16641
16642          bash$ cd /tmp
16643          bash$ gcc -g ./hello.c
16644          include_name = "hello.c"
16645          dir_name = "."
16646          DW_AT_comp_dir = comp_dir = "/tmp"
16647          DW_AT_name = "./hello.c"  */
16648
16649       if (dir_name != NULL)
16650         {
16651           char *tem = concat (dir_name, SLASH_STRING,
16652                               include_name, (char *)NULL);
16653
16654           make_cleanup (xfree, tem);
16655           include_name = tem;
16656           include_name_to_compare = include_name;
16657         }
16658       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
16659         {
16660           char *tem = concat (comp_dir, SLASH_STRING,
16661                               include_name, (char *)NULL);
16662
16663           make_cleanup (xfree, tem);
16664           include_name_to_compare = tem;
16665         }
16666     }
16667
16668   pst_filename = pst->filename;
16669   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
16670     {
16671       copied_name = concat (pst->dirname, SLASH_STRING,
16672                             pst_filename, (char *)NULL);
16673       pst_filename = copied_name;
16674     }
16675
16676   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
16677
16678   if (copied_name != NULL)
16679     xfree (copied_name);
16680
16681   if (file_is_pst)
16682     return NULL;
16683   return include_name;
16684 }
16685
16686 /* Ignore this record_line request.  */
16687
16688 static void
16689 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
16690 {
16691   return;
16692 }
16693
16694 /* Subroutine of dwarf_decode_lines to simplify it.
16695    Process the line number information in LH.  */
16696
16697 static void
16698 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
16699                       struct dwarf2_cu *cu, struct partial_symtab *pst)
16700 {
16701   const gdb_byte *line_ptr, *extended_end;
16702   const gdb_byte *line_end;
16703   unsigned int bytes_read, extended_len;
16704   unsigned char op_code, extended_op, adj_opcode;
16705   CORE_ADDR baseaddr;
16706   struct objfile *objfile = cu->objfile;
16707   bfd *abfd = objfile->obfd;
16708   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16709   const int decode_for_pst_p = (pst != NULL);
16710   struct subfile *last_subfile = NULL;
16711   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
16712     = record_line;
16713
16714   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16715
16716   line_ptr = lh->statement_program_start;
16717   line_end = lh->statement_program_end;
16718
16719   /* Read the statement sequences until there's nothing left.  */
16720   while (line_ptr < line_end)
16721     {
16722       /* state machine registers  */
16723       CORE_ADDR address = 0;
16724       unsigned int file = 1;
16725       unsigned int line = 1;
16726       unsigned int column = 0;
16727       int is_stmt = lh->default_is_stmt;
16728       int basic_block = 0;
16729       int end_sequence = 0;
16730       CORE_ADDR addr;
16731       unsigned char op_index = 0;
16732
16733       if (!decode_for_pst_p && lh->num_file_names >= file)
16734         {
16735           /* Start a subfile for the current file of the state machine.  */
16736           /* lh->include_dirs and lh->file_names are 0-based, but the
16737              directory and file name numbers in the statement program
16738              are 1-based.  */
16739           struct file_entry *fe = &lh->file_names[file - 1];
16740           const char *dir = NULL;
16741
16742           if (fe->dir_index)
16743             dir = lh->include_dirs[fe->dir_index - 1];
16744
16745           dwarf2_start_subfile (fe->name, dir, comp_dir);
16746         }
16747
16748       /* Decode the table.  */
16749       while (!end_sequence)
16750         {
16751           op_code = read_1_byte (abfd, line_ptr);
16752           line_ptr += 1;
16753           if (line_ptr > line_end)
16754             {
16755               dwarf2_debug_line_missing_end_sequence_complaint ();
16756               break;
16757             }
16758
16759           if (op_code >= lh->opcode_base)
16760             {
16761               /* Special operand.  */
16762               adj_opcode = op_code - lh->opcode_base;
16763               address += (((op_index + (adj_opcode / lh->line_range))
16764                            / lh->maximum_ops_per_instruction)
16765                           * lh->minimum_instruction_length);
16766               op_index = ((op_index + (adj_opcode / lh->line_range))
16767                           % lh->maximum_ops_per_instruction);
16768               line += lh->line_base + (adj_opcode % lh->line_range);
16769               if (lh->num_file_names < file || file == 0)
16770                 dwarf2_debug_line_missing_file_complaint ();
16771               /* For now we ignore lines not starting on an
16772                  instruction boundary.  */
16773               else if (op_index == 0)
16774                 {
16775                   lh->file_names[file - 1].included_p = 1;
16776                   if (!decode_for_pst_p && is_stmt)
16777                     {
16778                       if (last_subfile != current_subfile)
16779                         {
16780                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16781                           if (last_subfile)
16782                             (*p_record_line) (last_subfile, 0, addr);
16783                           last_subfile = current_subfile;
16784                         }
16785                       /* Append row to matrix using current values.  */
16786                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16787                       (*p_record_line) (current_subfile, line, addr);
16788                     }
16789                 }
16790               basic_block = 0;
16791             }
16792           else switch (op_code)
16793             {
16794             case DW_LNS_extended_op:
16795               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16796                                                    &bytes_read);
16797               line_ptr += bytes_read;
16798               extended_end = line_ptr + extended_len;
16799               extended_op = read_1_byte (abfd, line_ptr);
16800               line_ptr += 1;
16801               switch (extended_op)
16802                 {
16803                 case DW_LNE_end_sequence:
16804                   p_record_line = record_line;
16805                   end_sequence = 1;
16806                   break;
16807                 case DW_LNE_set_address:
16808                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16809
16810                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16811                     {
16812                       /* This line table is for a function which has been
16813                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16814
16815                       long line_offset
16816                         = line_ptr - get_debug_line_section (cu)->buffer;
16817
16818                       complaint (&symfile_complaints,
16819                                  _(".debug_line address at offset 0x%lx is 0 "
16820                                    "[in module %s]"),
16821                                  line_offset, objfile_name (objfile));
16822                       p_record_line = noop_record_line;
16823                     }
16824
16825                   op_index = 0;
16826                   line_ptr += bytes_read;
16827                   address += baseaddr;
16828                   break;
16829                 case DW_LNE_define_file:
16830                   {
16831                     const char *cur_file;
16832                     unsigned int dir_index, mod_time, length;
16833
16834                     cur_file = read_direct_string (abfd, line_ptr,
16835                                                    &bytes_read);
16836                     line_ptr += bytes_read;
16837                     dir_index =
16838                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16839                     line_ptr += bytes_read;
16840                     mod_time =
16841                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16842                     line_ptr += bytes_read;
16843                     length =
16844                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16845                     line_ptr += bytes_read;
16846                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16847                   }
16848                   break;
16849                 case DW_LNE_set_discriminator:
16850                   /* The discriminator is not interesting to the debugger;
16851                      just ignore it.  */
16852                   line_ptr = extended_end;
16853                   break;
16854                 default:
16855                   complaint (&symfile_complaints,
16856                              _("mangled .debug_line section"));
16857                   return;
16858                 }
16859               /* Make sure that we parsed the extended op correctly.  If e.g.
16860                  we expected a different address size than the producer used,
16861                  we may have read the wrong number of bytes.  */
16862               if (line_ptr != extended_end)
16863                 {
16864                   complaint (&symfile_complaints,
16865                              _("mangled .debug_line section"));
16866                   return;
16867                 }
16868               break;
16869             case DW_LNS_copy:
16870               if (lh->num_file_names < file || file == 0)
16871                 dwarf2_debug_line_missing_file_complaint ();
16872               else
16873                 {
16874                   lh->file_names[file - 1].included_p = 1;
16875                   if (!decode_for_pst_p && is_stmt)
16876                     {
16877                       if (last_subfile != current_subfile)
16878                         {
16879                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16880                           if (last_subfile)
16881                             (*p_record_line) (last_subfile, 0, addr);
16882                           last_subfile = current_subfile;
16883                         }
16884                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16885                       (*p_record_line) (current_subfile, line, addr);
16886                     }
16887                 }
16888               basic_block = 0;
16889               break;
16890             case DW_LNS_advance_pc:
16891               {
16892                 CORE_ADDR adjust
16893                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16894
16895                 address += (((op_index + adjust)
16896                              / lh->maximum_ops_per_instruction)
16897                             * lh->minimum_instruction_length);
16898                 op_index = ((op_index + adjust)
16899                             % lh->maximum_ops_per_instruction);
16900                 line_ptr += bytes_read;
16901               }
16902               break;
16903             case DW_LNS_advance_line:
16904               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16905               line_ptr += bytes_read;
16906               break;
16907             case DW_LNS_set_file:
16908               {
16909                 /* The arrays lh->include_dirs and lh->file_names are
16910                    0-based, but the directory and file name numbers in
16911                    the statement program are 1-based.  */
16912                 struct file_entry *fe;
16913                 const char *dir = NULL;
16914
16915                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16916                 line_ptr += bytes_read;
16917                 if (lh->num_file_names < file || file == 0)
16918                   dwarf2_debug_line_missing_file_complaint ();
16919                 else
16920                   {
16921                     fe = &lh->file_names[file - 1];
16922                     if (fe->dir_index)
16923                       dir = lh->include_dirs[fe->dir_index - 1];
16924                     if (!decode_for_pst_p)
16925                       {
16926                         last_subfile = current_subfile;
16927                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16928                       }
16929                   }
16930               }
16931               break;
16932             case DW_LNS_set_column:
16933               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16934               line_ptr += bytes_read;
16935               break;
16936             case DW_LNS_negate_stmt:
16937               is_stmt = (!is_stmt);
16938               break;
16939             case DW_LNS_set_basic_block:
16940               basic_block = 1;
16941               break;
16942             /* Add to the address register of the state machine the
16943                address increment value corresponding to special opcode
16944                255.  I.e., this value is scaled by the minimum
16945                instruction length since special opcode 255 would have
16946                scaled the increment.  */
16947             case DW_LNS_const_add_pc:
16948               {
16949                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16950
16951                 address += (((op_index + adjust)
16952                              / lh->maximum_ops_per_instruction)
16953                             * lh->minimum_instruction_length);
16954                 op_index = ((op_index + adjust)
16955                             % lh->maximum_ops_per_instruction);
16956               }
16957               break;
16958             case DW_LNS_fixed_advance_pc:
16959               address += read_2_bytes (abfd, line_ptr);
16960               op_index = 0;
16961               line_ptr += 2;
16962               break;
16963             default:
16964               {
16965                 /* Unknown standard opcode, ignore it.  */
16966                 int i;
16967
16968                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16969                   {
16970                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16971                     line_ptr += bytes_read;
16972                   }
16973               }
16974             }
16975         }
16976       if (lh->num_file_names < file || file == 0)
16977         dwarf2_debug_line_missing_file_complaint ();
16978       else
16979         {
16980           lh->file_names[file - 1].included_p = 1;
16981           if (!decode_for_pst_p)
16982             {
16983               addr = gdbarch_addr_bits_remove (gdbarch, address);
16984               (*p_record_line) (current_subfile, 0, addr);
16985             }
16986         }
16987     }
16988 }
16989
16990 /* Decode the Line Number Program (LNP) for the given line_header
16991    structure and CU.  The actual information extracted and the type
16992    of structures created from the LNP depends on the value of PST.
16993
16994    1. If PST is NULL, then this procedure uses the data from the program
16995       to create all necessary symbol tables, and their linetables.
16996
16997    2. If PST is not NULL, this procedure reads the program to determine
16998       the list of files included by the unit represented by PST, and
16999       builds all the associated partial symbol tables.
17000
17001    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
17002    It is used for relative paths in the line table.
17003    NOTE: When processing partial symtabs (pst != NULL),
17004    comp_dir == pst->dirname.
17005
17006    NOTE: It is important that psymtabs have the same file name (via strcmp)
17007    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
17008    symtab we don't use it in the name of the psymtabs we create.
17009    E.g. expand_line_sal requires this when finding psymtabs to expand.
17010    A good testcase for this is mb-inline.exp.  */
17011
17012 static void
17013 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
17014                     struct dwarf2_cu *cu, struct partial_symtab *pst,
17015                     int want_line_info)
17016 {
17017   struct objfile *objfile = cu->objfile;
17018   const int decode_for_pst_p = (pst != NULL);
17019   struct subfile *first_subfile = current_subfile;
17020
17021   if (want_line_info)
17022     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
17023
17024   if (decode_for_pst_p)
17025     {
17026       int file_index;
17027
17028       /* Now that we're done scanning the Line Header Program, we can
17029          create the psymtab of each included file.  */
17030       for (file_index = 0; file_index < lh->num_file_names; file_index++)
17031         if (lh->file_names[file_index].included_p == 1)
17032           {
17033             const char *include_name =
17034               psymtab_include_file_name (lh, file_index, pst, comp_dir);
17035             if (include_name != NULL)
17036               dwarf2_create_include_psymtab (include_name, pst, objfile);
17037           }
17038     }
17039   else
17040     {
17041       /* Make sure a symtab is created for every file, even files
17042          which contain only variables (i.e. no code with associated
17043          line numbers).  */
17044       int i;
17045
17046       for (i = 0; i < lh->num_file_names; i++)
17047         {
17048           const char *dir = NULL;
17049           struct file_entry *fe;
17050
17051           fe = &lh->file_names[i];
17052           if (fe->dir_index)
17053             dir = lh->include_dirs[fe->dir_index - 1];
17054           dwarf2_start_subfile (fe->name, dir, comp_dir);
17055
17056           /* Skip the main file; we don't need it, and it must be
17057              allocated last, so that it will show up before the
17058              non-primary symtabs in the objfile's symtab list.  */
17059           if (current_subfile == first_subfile)
17060             continue;
17061
17062           if (current_subfile->symtab == NULL)
17063             current_subfile->symtab = allocate_symtab (current_subfile->name,
17064                                                        objfile);
17065           fe->symtab = current_subfile->symtab;
17066         }
17067     }
17068 }
17069
17070 /* Start a subfile for DWARF.  FILENAME is the name of the file and
17071    DIRNAME the name of the source directory which contains FILENAME
17072    or NULL if not known.  COMP_DIR is the compilation directory for the
17073    linetable's compilation unit or NULL if not known.
17074    This routine tries to keep line numbers from identical absolute and
17075    relative file names in a common subfile.
17076
17077    Using the `list' example from the GDB testsuite, which resides in
17078    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
17079    of /srcdir/list0.c yields the following debugging information for list0.c:
17080
17081    DW_AT_name:          /srcdir/list0.c
17082    DW_AT_comp_dir:              /compdir
17083    files.files[0].name: list0.h
17084    files.files[0].dir:  /srcdir
17085    files.files[1].name: list0.c
17086    files.files[1].dir:  /srcdir
17087
17088    The line number information for list0.c has to end up in a single
17089    subfile, so that `break /srcdir/list0.c:1' works as expected.
17090    start_subfile will ensure that this happens provided that we pass the
17091    concatenation of files.files[1].dir and files.files[1].name as the
17092    subfile's name.  */
17093
17094 static void
17095 dwarf2_start_subfile (const char *filename, const char *dirname,
17096                       const char *comp_dir)
17097 {
17098   char *copy = NULL;
17099
17100   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
17101      `start_symtab' will always pass the contents of DW_AT_comp_dir as
17102      second argument to start_subfile.  To be consistent, we do the
17103      same here.  In order not to lose the line information directory,
17104      we concatenate it to the filename when it makes sense.
17105      Note that the Dwarf3 standard says (speaking of filenames in line
17106      information): ``The directory index is ignored for file names
17107      that represent full path names''.  Thus ignoring dirname in the
17108      `else' branch below isn't an issue.  */
17109
17110   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
17111     {
17112       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
17113       filename = copy;
17114     }
17115
17116   start_subfile (filename, comp_dir);
17117
17118   if (copy != NULL)
17119     xfree (copy);
17120 }
17121
17122 /* Start a symtab for DWARF.
17123    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
17124
17125 static void
17126 dwarf2_start_symtab (struct dwarf2_cu *cu,
17127                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
17128 {
17129   start_symtab (name, comp_dir, low_pc);
17130   record_debugformat ("DWARF 2");
17131   record_producer (cu->producer);
17132
17133   /* We assume that we're processing GCC output.  */
17134   processing_gcc_compilation = 2;
17135
17136   cu->processing_has_namespace_info = 0;
17137 }
17138
17139 static void
17140 var_decode_location (struct attribute *attr, struct symbol *sym,
17141                      struct dwarf2_cu *cu)
17142 {
17143   struct objfile *objfile = cu->objfile;
17144   struct comp_unit_head *cu_header = &cu->header;
17145
17146   /* NOTE drow/2003-01-30: There used to be a comment and some special
17147      code here to turn a symbol with DW_AT_external and a
17148      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
17149      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
17150      with some versions of binutils) where shared libraries could have
17151      relocations against symbols in their debug information - the
17152      minimal symbol would have the right address, but the debug info
17153      would not.  It's no longer necessary, because we will explicitly
17154      apply relocations when we read in the debug information now.  */
17155
17156   /* A DW_AT_location attribute with no contents indicates that a
17157      variable has been optimized away.  */
17158   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
17159     {
17160       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17161       return;
17162     }
17163
17164   /* Handle one degenerate form of location expression specially, to
17165      preserve GDB's previous behavior when section offsets are
17166      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
17167      then mark this symbol as LOC_STATIC.  */
17168
17169   if (attr_form_is_block (attr)
17170       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
17171            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
17172           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
17173               && (DW_BLOCK (attr)->size
17174                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
17175     {
17176       unsigned int dummy;
17177
17178       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
17179         SYMBOL_VALUE_ADDRESS (sym) =
17180           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
17181       else
17182         SYMBOL_VALUE_ADDRESS (sym) =
17183           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
17184       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
17185       fixup_symbol_section (sym, objfile);
17186       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
17187                                               SYMBOL_SECTION (sym));
17188       return;
17189     }
17190
17191   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
17192      expression evaluator, and use LOC_COMPUTED only when necessary
17193      (i.e. when the value of a register or memory location is
17194      referenced, or a thread-local block, etc.).  Then again, it might
17195      not be worthwhile.  I'm assuming that it isn't unless performance
17196      or memory numbers show me otherwise.  */
17197
17198   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
17199
17200   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
17201     cu->has_loclist = 1;
17202 }
17203
17204 /* Given a pointer to a DWARF information entry, figure out if we need
17205    to make a symbol table entry for it, and if so, create a new entry
17206    and return a pointer to it.
17207    If TYPE is NULL, determine symbol type from the die, otherwise
17208    used the passed type.
17209    If SPACE is not NULL, use it to hold the new symbol.  If it is
17210    NULL, allocate a new symbol on the objfile's obstack.  */
17211
17212 static struct symbol *
17213 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
17214                  struct symbol *space)
17215 {
17216   struct objfile *objfile = cu->objfile;
17217   struct symbol *sym = NULL;
17218   const char *name;
17219   struct attribute *attr = NULL;
17220   struct attribute *attr2 = NULL;
17221   CORE_ADDR baseaddr;
17222   struct pending **list_to_add = NULL;
17223
17224   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
17225
17226   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17227
17228   name = dwarf2_name (die, cu);
17229   if (name)
17230     {
17231       const char *linkagename;
17232       int suppress_add = 0;
17233
17234       if (space)
17235         sym = space;
17236       else
17237         sym = allocate_symbol (objfile);
17238       OBJSTAT (objfile, n_syms++);
17239
17240       /* Cache this symbol's name and the name's demangled form (if any).  */
17241       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
17242       linkagename = dwarf2_physname (name, die, cu);
17243       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
17244
17245       /* Fortran does not have mangling standard and the mangling does differ
17246          between gfortran, iFort etc.  */
17247       if (cu->language == language_fortran
17248           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
17249         symbol_set_demangled_name (&(sym->ginfo),
17250                                    dwarf2_full_name (name, die, cu),
17251                                    NULL);
17252
17253       /* Default assumptions.
17254          Use the passed type or decode it from the die.  */
17255       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17256       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17257       if (type != NULL)
17258         SYMBOL_TYPE (sym) = type;
17259       else
17260         SYMBOL_TYPE (sym) = die_type (die, cu);
17261       attr = dwarf2_attr (die,
17262                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
17263                           cu);
17264       if (attr)
17265         {
17266           SYMBOL_LINE (sym) = DW_UNSND (attr);
17267         }
17268
17269       attr = dwarf2_attr (die,
17270                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
17271                           cu);
17272       if (attr)
17273         {
17274           int file_index = DW_UNSND (attr);
17275
17276           if (cu->line_header == NULL
17277               || file_index > cu->line_header->num_file_names)
17278             complaint (&symfile_complaints,
17279                        _("file index out of range"));
17280           else if (file_index > 0)
17281             {
17282               struct file_entry *fe;
17283
17284               fe = &cu->line_header->file_names[file_index - 1];
17285               SYMBOL_SYMTAB (sym) = fe->symtab;
17286             }
17287         }
17288
17289       switch (die->tag)
17290         {
17291         case DW_TAG_label:
17292           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
17293           if (attr)
17294             {
17295               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
17296             }
17297           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
17298           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
17299           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
17300           add_symbol_to_list (sym, cu->list_in_scope);
17301           break;
17302         case DW_TAG_subprogram:
17303           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17304              finish_block.  */
17305           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17306           attr2 = dwarf2_attr (die, DW_AT_external, cu);
17307           if ((attr2 && (DW_UNSND (attr2) != 0))
17308               || cu->language == language_ada)
17309             {
17310               /* Subprograms marked external are stored as a global symbol.
17311                  Ada subprograms, whether marked external or not, are always
17312                  stored as a global symbol, because we want to be able to
17313                  access them globally.  For instance, we want to be able
17314                  to break on a nested subprogram without having to
17315                  specify the context.  */
17316               list_to_add = &global_symbols;
17317             }
17318           else
17319             {
17320               list_to_add = cu->list_in_scope;
17321             }
17322           break;
17323         case DW_TAG_inlined_subroutine:
17324           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17325              finish_block.  */
17326           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17327           SYMBOL_INLINED (sym) = 1;
17328           list_to_add = cu->list_in_scope;
17329           break;
17330         case DW_TAG_template_value_param:
17331           suppress_add = 1;
17332           /* Fall through.  */
17333         case DW_TAG_constant:
17334         case DW_TAG_variable:
17335         case DW_TAG_member:
17336           /* Compilation with minimal debug info may result in
17337              variables with missing type entries.  Change the
17338              misleading `void' type to something sensible.  */
17339           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
17340             SYMBOL_TYPE (sym)
17341               = objfile_type (objfile)->nodebug_data_symbol;
17342
17343           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17344           /* In the case of DW_TAG_member, we should only be called for
17345              static const members.  */
17346           if (die->tag == DW_TAG_member)
17347             {
17348               /* dwarf2_add_field uses die_is_declaration,
17349                  so we do the same.  */
17350               gdb_assert (die_is_declaration (die, cu));
17351               gdb_assert (attr);
17352             }
17353           if (attr)
17354             {
17355               dwarf2_const_value (attr, sym, cu);
17356               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17357               if (!suppress_add)
17358                 {
17359                   if (attr2 && (DW_UNSND (attr2) != 0))
17360                     list_to_add = &global_symbols;
17361                   else
17362                     list_to_add = cu->list_in_scope;
17363                 }
17364               break;
17365             }
17366           attr = dwarf2_attr (die, DW_AT_location, cu);
17367           if (attr)
17368             {
17369               var_decode_location (attr, sym, cu);
17370               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17371
17372               /* Fortran explicitly imports any global symbols to the local
17373                  scope by DW_TAG_common_block.  */
17374               if (cu->language == language_fortran && die->parent
17375                   && die->parent->tag == DW_TAG_common_block)
17376                 attr2 = NULL;
17377
17378               if (SYMBOL_CLASS (sym) == LOC_STATIC
17379                   && SYMBOL_VALUE_ADDRESS (sym) == 0
17380                   && !dwarf2_per_objfile->has_section_at_zero)
17381                 {
17382                   /* When a static variable is eliminated by the linker,
17383                      the corresponding debug information is not stripped
17384                      out, but the variable address is set to null;
17385                      do not add such variables into symbol table.  */
17386                 }
17387               else if (attr2 && (DW_UNSND (attr2) != 0))
17388                 {
17389                   /* Workaround gfortran PR debug/40040 - it uses
17390                      DW_AT_location for variables in -fPIC libraries which may
17391                      get overriden by other libraries/executable and get
17392                      a different address.  Resolve it by the minimal symbol
17393                      which may come from inferior's executable using copy
17394                      relocation.  Make this workaround only for gfortran as for
17395                      other compilers GDB cannot guess the minimal symbol
17396                      Fortran mangling kind.  */
17397                   if (cu->language == language_fortran && die->parent
17398                       && die->parent->tag == DW_TAG_module
17399                       && cu->producer
17400                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
17401                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17402
17403                   /* A variable with DW_AT_external is never static,
17404                      but it may be block-scoped.  */
17405                   list_to_add = (cu->list_in_scope == &file_symbols
17406                                  ? &global_symbols : cu->list_in_scope);
17407                 }
17408               else
17409                 list_to_add = cu->list_in_scope;
17410             }
17411           else
17412             {
17413               /* We do not know the address of this symbol.
17414                  If it is an external symbol and we have type information
17415                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
17416                  The address of the variable will then be determined from
17417                  the minimal symbol table whenever the variable is
17418                  referenced.  */
17419               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17420
17421               /* Fortran explicitly imports any global symbols to the local
17422                  scope by DW_TAG_common_block.  */
17423               if (cu->language == language_fortran && die->parent
17424                   && die->parent->tag == DW_TAG_common_block)
17425                 {
17426                   /* SYMBOL_CLASS doesn't matter here because
17427                      read_common_block is going to reset it.  */
17428                   if (!suppress_add)
17429                     list_to_add = cu->list_in_scope;
17430                 }
17431               else if (attr2 && (DW_UNSND (attr2) != 0)
17432                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
17433                 {
17434                   /* A variable with DW_AT_external is never static, but it
17435                      may be block-scoped.  */
17436                   list_to_add = (cu->list_in_scope == &file_symbols
17437                                  ? &global_symbols : cu->list_in_scope);
17438
17439                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17440                 }
17441               else if (!die_is_declaration (die, cu))
17442                 {
17443                   /* Use the default LOC_OPTIMIZED_OUT class.  */
17444                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
17445                   if (!suppress_add)
17446                     list_to_add = cu->list_in_scope;
17447                 }
17448             }
17449           break;
17450         case DW_TAG_formal_parameter:
17451           /* If we are inside a function, mark this as an argument.  If
17452              not, we might be looking at an argument to an inlined function
17453              when we do not have enough information to show inlined frames;
17454              pretend it's a local variable in that case so that the user can
17455              still see it.  */
17456           if (context_stack_depth > 0
17457               && context_stack[context_stack_depth - 1].name != NULL)
17458             SYMBOL_IS_ARGUMENT (sym) = 1;
17459           attr = dwarf2_attr (die, DW_AT_location, cu);
17460           if (attr)
17461             {
17462               var_decode_location (attr, sym, cu);
17463             }
17464           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17465           if (attr)
17466             {
17467               dwarf2_const_value (attr, sym, cu);
17468             }
17469
17470           list_to_add = cu->list_in_scope;
17471           break;
17472         case DW_TAG_unspecified_parameters:
17473           /* From varargs functions; gdb doesn't seem to have any
17474              interest in this information, so just ignore it for now.
17475              (FIXME?) */
17476           break;
17477         case DW_TAG_template_type_param:
17478           suppress_add = 1;
17479           /* Fall through.  */
17480         case DW_TAG_class_type:
17481         case DW_TAG_interface_type:
17482         case DW_TAG_structure_type:
17483         case DW_TAG_union_type:
17484         case DW_TAG_set_type:
17485         case DW_TAG_enumeration_type:
17486           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17487           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
17488
17489           {
17490             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
17491                really ever be static objects: otherwise, if you try
17492                to, say, break of a class's method and you're in a file
17493                which doesn't mention that class, it won't work unless
17494                the check for all static symbols in lookup_symbol_aux
17495                saves you.  See the OtherFileClass tests in
17496                gdb.c++/namespace.exp.  */
17497
17498             if (!suppress_add)
17499               {
17500                 list_to_add = (cu->list_in_scope == &file_symbols
17501                                && (cu->language == language_cplus
17502                                    || cu->language == language_java)
17503                                ? &global_symbols : cu->list_in_scope);
17504
17505                 /* The semantics of C++ state that "struct foo {
17506                    ... }" also defines a typedef for "foo".  A Java
17507                    class declaration also defines a typedef for the
17508                    class.  */
17509                 if (cu->language == language_cplus
17510                     || cu->language == language_java
17511                     || cu->language == language_ada)
17512                   {
17513                     /* The symbol's name is already allocated along
17514                        with this objfile, so we don't need to
17515                        duplicate it for the type.  */
17516                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
17517                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
17518                   }
17519               }
17520           }
17521           break;
17522         case DW_TAG_typedef:
17523           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17524           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17525           list_to_add = cu->list_in_scope;
17526           break;
17527         case DW_TAG_base_type:
17528         case DW_TAG_subrange_type:
17529           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17530           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17531           list_to_add = cu->list_in_scope;
17532           break;
17533         case DW_TAG_enumerator:
17534           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17535           if (attr)
17536             {
17537               dwarf2_const_value (attr, sym, cu);
17538             }
17539           {
17540             /* NOTE: carlton/2003-11-10: See comment above in the
17541                DW_TAG_class_type, etc. block.  */
17542
17543             list_to_add = (cu->list_in_scope == &file_symbols
17544                            && (cu->language == language_cplus
17545                                || cu->language == language_java)
17546                            ? &global_symbols : cu->list_in_scope);
17547           }
17548           break;
17549         case DW_TAG_namespace:
17550           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17551           list_to_add = &global_symbols;
17552           break;
17553         case DW_TAG_common_block:
17554           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
17555           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
17556           add_symbol_to_list (sym, cu->list_in_scope);
17557           break;
17558         default:
17559           /* Not a tag we recognize.  Hopefully we aren't processing
17560              trash data, but since we must specifically ignore things
17561              we don't recognize, there is nothing else we should do at
17562              this point.  */
17563           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
17564                      dwarf_tag_name (die->tag));
17565           break;
17566         }
17567
17568       if (suppress_add)
17569         {
17570           sym->hash_next = objfile->template_symbols;
17571           objfile->template_symbols = sym;
17572           list_to_add = NULL;
17573         }
17574
17575       if (list_to_add != NULL)
17576         add_symbol_to_list (sym, list_to_add);
17577
17578       /* For the benefit of old versions of GCC, check for anonymous
17579          namespaces based on the demangled name.  */
17580       if (!cu->processing_has_namespace_info
17581           && cu->language == language_cplus)
17582         cp_scan_for_anonymous_namespaces (sym, objfile);
17583     }
17584   return (sym);
17585 }
17586
17587 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
17588
17589 static struct symbol *
17590 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
17591 {
17592   return new_symbol_full (die, type, cu, NULL);
17593 }
17594
17595 /* Given an attr with a DW_FORM_dataN value in host byte order,
17596    zero-extend it as appropriate for the symbol's type.  The DWARF
17597    standard (v4) is not entirely clear about the meaning of using
17598    DW_FORM_dataN for a constant with a signed type, where the type is
17599    wider than the data.  The conclusion of a discussion on the DWARF
17600    list was that this is unspecified.  We choose to always zero-extend
17601    because that is the interpretation long in use by GCC.  */
17602
17603 static gdb_byte *
17604 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
17605                          struct dwarf2_cu *cu, LONGEST *value, int bits)
17606 {
17607   struct objfile *objfile = cu->objfile;
17608   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
17609                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
17610   LONGEST l = DW_UNSND (attr);
17611
17612   if (bits < sizeof (*value) * 8)
17613     {
17614       l &= ((LONGEST) 1 << bits) - 1;
17615       *value = l;
17616     }
17617   else if (bits == sizeof (*value) * 8)
17618     *value = l;
17619   else
17620     {
17621       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
17622       store_unsigned_integer (bytes, bits / 8, byte_order, l);
17623       return bytes;
17624     }
17625
17626   return NULL;
17627 }
17628
17629 /* Read a constant value from an attribute.  Either set *VALUE, or if
17630    the value does not fit in *VALUE, set *BYTES - either already
17631    allocated on the objfile obstack, or newly allocated on OBSTACK,
17632    or, set *BATON, if we translated the constant to a location
17633    expression.  */
17634
17635 static void
17636 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
17637                          const char *name, struct obstack *obstack,
17638                          struct dwarf2_cu *cu,
17639                          LONGEST *value, const gdb_byte **bytes,
17640                          struct dwarf2_locexpr_baton **baton)
17641 {
17642   struct objfile *objfile = cu->objfile;
17643   struct comp_unit_head *cu_header = &cu->header;
17644   struct dwarf_block *blk;
17645   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
17646                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
17647
17648   *value = 0;
17649   *bytes = NULL;
17650   *baton = NULL;
17651
17652   switch (attr->form)
17653     {
17654     case DW_FORM_addr:
17655     case DW_FORM_GNU_addr_index:
17656       {
17657         gdb_byte *data;
17658
17659         if (TYPE_LENGTH (type) != cu_header->addr_size)
17660           dwarf2_const_value_length_mismatch_complaint (name,
17661                                                         cu_header->addr_size,
17662                                                         TYPE_LENGTH (type));
17663         /* Symbols of this form are reasonably rare, so we just
17664            piggyback on the existing location code rather than writing
17665            a new implementation of symbol_computed_ops.  */
17666         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
17667         (*baton)->per_cu = cu->per_cu;
17668         gdb_assert ((*baton)->per_cu);
17669
17670         (*baton)->size = 2 + cu_header->addr_size;
17671         data = obstack_alloc (obstack, (*baton)->size);
17672         (*baton)->data = data;
17673
17674         data[0] = DW_OP_addr;
17675         store_unsigned_integer (&data[1], cu_header->addr_size,
17676                                 byte_order, DW_ADDR (attr));
17677         data[cu_header->addr_size + 1] = DW_OP_stack_value;
17678       }
17679       break;
17680     case DW_FORM_string:
17681     case DW_FORM_strp:
17682     case DW_FORM_GNU_str_index:
17683     case DW_FORM_GNU_strp_alt:
17684       /* DW_STRING is already allocated on the objfile obstack, point
17685          directly to it.  */
17686       *bytes = (const gdb_byte *) DW_STRING (attr);
17687       break;
17688     case DW_FORM_block1:
17689     case DW_FORM_block2:
17690     case DW_FORM_block4:
17691     case DW_FORM_block:
17692     case DW_FORM_exprloc:
17693       blk = DW_BLOCK (attr);
17694       if (TYPE_LENGTH (type) != blk->size)
17695         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
17696                                                       TYPE_LENGTH (type));
17697       *bytes = blk->data;
17698       break;
17699
17700       /* The DW_AT_const_value attributes are supposed to carry the
17701          symbol's value "represented as it would be on the target
17702          architecture."  By the time we get here, it's already been
17703          converted to host endianness, so we just need to sign- or
17704          zero-extend it as appropriate.  */
17705     case DW_FORM_data1:
17706       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
17707       break;
17708     case DW_FORM_data2:
17709       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
17710       break;
17711     case DW_FORM_data4:
17712       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
17713       break;
17714     case DW_FORM_data8:
17715       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
17716       break;
17717
17718     case DW_FORM_sdata:
17719       *value = DW_SND (attr);
17720       break;
17721
17722     case DW_FORM_udata:
17723       *value = DW_UNSND (attr);
17724       break;
17725
17726     default:
17727       complaint (&symfile_complaints,
17728                  _("unsupported const value attribute form: '%s'"),
17729                  dwarf_form_name (attr->form));
17730       *value = 0;
17731       break;
17732     }
17733 }
17734
17735
17736 /* Copy constant value from an attribute to a symbol.  */
17737
17738 static void
17739 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
17740                     struct dwarf2_cu *cu)
17741 {
17742   struct objfile *objfile = cu->objfile;
17743   struct comp_unit_head *cu_header = &cu->header;
17744   LONGEST value;
17745   const gdb_byte *bytes;
17746   struct dwarf2_locexpr_baton *baton;
17747
17748   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
17749                            SYMBOL_PRINT_NAME (sym),
17750                            &objfile->objfile_obstack, cu,
17751                            &value, &bytes, &baton);
17752
17753   if (baton != NULL)
17754     {
17755       SYMBOL_LOCATION_BATON (sym) = baton;
17756       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17757     }
17758   else if (bytes != NULL)
17759      {
17760       SYMBOL_VALUE_BYTES (sym) = bytes;
17761       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
17762     }
17763   else
17764     {
17765       SYMBOL_VALUE (sym) = value;
17766       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17767     }
17768 }
17769
17770 /* Return the type of the die in question using its DW_AT_type attribute.  */
17771
17772 static struct type *
17773 die_type (struct die_info *die, struct dwarf2_cu *cu)
17774 {
17775   struct attribute *type_attr;
17776
17777   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17778   if (!type_attr)
17779     {
17780       /* A missing DW_AT_type represents a void type.  */
17781       return objfile_type (cu->objfile)->builtin_void;
17782     }
17783
17784   return lookup_die_type (die, type_attr, cu);
17785 }
17786
17787 /* True iff CU's producer generates GNAT Ada auxiliary information
17788    that allows to find parallel types through that information instead
17789    of having to do expensive parallel lookups by type name.  */
17790
17791 static int
17792 need_gnat_info (struct dwarf2_cu *cu)
17793 {
17794   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17795      of GNAT produces this auxiliary information, without any indication
17796      that it is produced.  Part of enhancing the FSF version of GNAT
17797      to produce that information will be to put in place an indicator
17798      that we can use in order to determine whether the descriptive type
17799      info is available or not.  One suggestion that has been made is
17800      to use a new attribute, attached to the CU die.  For now, assume
17801      that the descriptive type info is not available.  */
17802   return 0;
17803 }
17804
17805 /* Return the auxiliary type of the die in question using its
17806    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17807    attribute is not present.  */
17808
17809 static struct type *
17810 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17811 {
17812   struct attribute *type_attr;
17813
17814   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17815   if (!type_attr)
17816     return NULL;
17817
17818   return lookup_die_type (die, type_attr, cu);
17819 }
17820
17821 /* If DIE has a descriptive_type attribute, then set the TYPE's
17822    descriptive type accordingly.  */
17823
17824 static void
17825 set_descriptive_type (struct type *type, struct die_info *die,
17826                       struct dwarf2_cu *cu)
17827 {
17828   struct type *descriptive_type = die_descriptive_type (die, cu);
17829
17830   if (descriptive_type)
17831     {
17832       ALLOCATE_GNAT_AUX_TYPE (type);
17833       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17834     }
17835 }
17836
17837 /* Return the containing type of the die in question using its
17838    DW_AT_containing_type attribute.  */
17839
17840 static struct type *
17841 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17842 {
17843   struct attribute *type_attr;
17844
17845   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17846   if (!type_attr)
17847     error (_("Dwarf Error: Problem turning containing type into gdb type "
17848              "[in module %s]"), objfile_name (cu->objfile));
17849
17850   return lookup_die_type (die, type_attr, cu);
17851 }
17852
17853 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17854
17855 static struct type *
17856 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17857 {
17858   struct objfile *objfile = dwarf2_per_objfile->objfile;
17859   char *message, *saved;
17860
17861   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17862                         objfile_name (objfile),
17863                         cu->header.offset.sect_off,
17864                         die->offset.sect_off);
17865   saved = obstack_copy0 (&objfile->objfile_obstack,
17866                          message, strlen (message));
17867   xfree (message);
17868
17869   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17870 }
17871
17872 /* Look up the type of DIE in CU using its type attribute ATTR.
17873    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17874    DW_AT_containing_type.
17875    If there is no type substitute an error marker.  */
17876
17877 static struct type *
17878 lookup_die_type (struct die_info *die, const struct attribute *attr,
17879                  struct dwarf2_cu *cu)
17880 {
17881   struct objfile *objfile = cu->objfile;
17882   struct type *this_type;
17883
17884   gdb_assert (attr->name == DW_AT_type
17885               || attr->name == DW_AT_GNAT_descriptive_type
17886               || attr->name == DW_AT_containing_type);
17887
17888   /* First see if we have it cached.  */
17889
17890   if (attr->form == DW_FORM_GNU_ref_alt)
17891     {
17892       struct dwarf2_per_cu_data *per_cu;
17893       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17894
17895       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17896       this_type = get_die_type_at_offset (offset, per_cu);
17897     }
17898   else if (attr_form_is_ref (attr))
17899     {
17900       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17901
17902       this_type = get_die_type_at_offset (offset, cu->per_cu);
17903     }
17904   else if (attr->form == DW_FORM_ref_sig8)
17905     {
17906       ULONGEST signature = DW_SIGNATURE (attr);
17907
17908       return get_signatured_type (die, signature, cu);
17909     }
17910   else
17911     {
17912       complaint (&symfile_complaints,
17913                  _("Dwarf Error: Bad type attribute %s in DIE"
17914                    " at 0x%x [in module %s]"),
17915                  dwarf_attr_name (attr->name), die->offset.sect_off,
17916                  objfile_name (objfile));
17917       return build_error_marker_type (cu, die);
17918     }
17919
17920   /* If not cached we need to read it in.  */
17921
17922   if (this_type == NULL)
17923     {
17924       struct die_info *type_die = NULL;
17925       struct dwarf2_cu *type_cu = cu;
17926
17927       if (attr_form_is_ref (attr))
17928         type_die = follow_die_ref (die, attr, &type_cu);
17929       if (type_die == NULL)
17930         return build_error_marker_type (cu, die);
17931       /* If we find the type now, it's probably because the type came
17932          from an inter-CU reference and the type's CU got expanded before
17933          ours.  */
17934       this_type = read_type_die (type_die, type_cu);
17935     }
17936
17937   /* If we still don't have a type use an error marker.  */
17938
17939   if (this_type == NULL)
17940     return build_error_marker_type (cu, die);
17941
17942   return this_type;
17943 }
17944
17945 /* Return the type in DIE, CU.
17946    Returns NULL for invalid types.
17947
17948    This first does a lookup in die_type_hash,
17949    and only reads the die in if necessary.
17950
17951    NOTE: This can be called when reading in partial or full symbols.  */
17952
17953 static struct type *
17954 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17955 {
17956   struct type *this_type;
17957
17958   this_type = get_die_type (die, cu);
17959   if (this_type)
17960     return this_type;
17961
17962   return read_type_die_1 (die, cu);
17963 }
17964
17965 /* Read the type in DIE, CU.
17966    Returns NULL for invalid types.  */
17967
17968 static struct type *
17969 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17970 {
17971   struct type *this_type = NULL;
17972
17973   switch (die->tag)
17974     {
17975     case DW_TAG_class_type:
17976     case DW_TAG_interface_type:
17977     case DW_TAG_structure_type:
17978     case DW_TAG_union_type:
17979       this_type = read_structure_type (die, cu);
17980       break;
17981     case DW_TAG_enumeration_type:
17982       this_type = read_enumeration_type (die, cu);
17983       break;
17984     case DW_TAG_subprogram:
17985     case DW_TAG_subroutine_type:
17986     case DW_TAG_inlined_subroutine:
17987       this_type = read_subroutine_type (die, cu);
17988       break;
17989     case DW_TAG_array_type:
17990       this_type = read_array_type (die, cu);
17991       break;
17992     case DW_TAG_set_type:
17993       this_type = read_set_type (die, cu);
17994       break;
17995     case DW_TAG_pointer_type:
17996       this_type = read_tag_pointer_type (die, cu);
17997       break;
17998     case DW_TAG_ptr_to_member_type:
17999       this_type = read_tag_ptr_to_member_type (die, cu);
18000       break;
18001     case DW_TAG_reference_type:
18002       this_type = read_tag_reference_type (die, cu);
18003       break;
18004     case DW_TAG_const_type:
18005       this_type = read_tag_const_type (die, cu);
18006       break;
18007     case DW_TAG_volatile_type:
18008       this_type = read_tag_volatile_type (die, cu);
18009       break;
18010     case DW_TAG_restrict_type:
18011       this_type = read_tag_restrict_type (die, cu);
18012       break;
18013     case DW_TAG_string_type:
18014       this_type = read_tag_string_type (die, cu);
18015       break;
18016     case DW_TAG_typedef:
18017       this_type = read_typedef (die, cu);
18018       break;
18019     case DW_TAG_subrange_type:
18020       this_type = read_subrange_type (die, cu);
18021       break;
18022     case DW_TAG_base_type:
18023       this_type = read_base_type (die, cu);
18024       break;
18025     case DW_TAG_unspecified_type:
18026       this_type = read_unspecified_type (die, cu);
18027       break;
18028     case DW_TAG_namespace:
18029       this_type = read_namespace_type (die, cu);
18030       break;
18031     case DW_TAG_module:
18032       this_type = read_module_type (die, cu);
18033       break;
18034     default:
18035       complaint (&symfile_complaints,
18036                  _("unexpected tag in read_type_die: '%s'"),
18037                  dwarf_tag_name (die->tag));
18038       break;
18039     }
18040
18041   return this_type;
18042 }
18043
18044 /* See if we can figure out if the class lives in a namespace.  We do
18045    this by looking for a member function; its demangled name will
18046    contain namespace info, if there is any.
18047    Return the computed name or NULL.
18048    Space for the result is allocated on the objfile's obstack.
18049    This is the full-die version of guess_partial_die_structure_name.
18050    In this case we know DIE has no useful parent.  */
18051
18052 static char *
18053 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
18054 {
18055   struct die_info *spec_die;
18056   struct dwarf2_cu *spec_cu;
18057   struct die_info *child;
18058
18059   spec_cu = cu;
18060   spec_die = die_specification (die, &spec_cu);
18061   if (spec_die != NULL)
18062     {
18063       die = spec_die;
18064       cu = spec_cu;
18065     }
18066
18067   for (child = die->child;
18068        child != NULL;
18069        child = child->sibling)
18070     {
18071       if (child->tag == DW_TAG_subprogram)
18072         {
18073           struct attribute *attr;
18074
18075           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
18076           if (attr == NULL)
18077             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
18078           if (attr != NULL)
18079             {
18080               char *actual_name
18081                 = language_class_name_from_physname (cu->language_defn,
18082                                                      DW_STRING (attr));
18083               char *name = NULL;
18084
18085               if (actual_name != NULL)
18086                 {
18087                   const char *die_name = dwarf2_name (die, cu);
18088
18089                   if (die_name != NULL
18090                       && strcmp (die_name, actual_name) != 0)
18091                     {
18092                       /* Strip off the class name from the full name.
18093                          We want the prefix.  */
18094                       int die_name_len = strlen (die_name);
18095                       int actual_name_len = strlen (actual_name);
18096
18097                       /* Test for '::' as a sanity check.  */
18098                       if (actual_name_len > die_name_len + 2
18099                           && actual_name[actual_name_len
18100                                          - die_name_len - 1] == ':')
18101                         name =
18102                           obstack_copy0 (&cu->objfile->objfile_obstack,
18103                                          actual_name,
18104                                          actual_name_len - die_name_len - 2);
18105                     }
18106                 }
18107               xfree (actual_name);
18108               return name;
18109             }
18110         }
18111     }
18112
18113   return NULL;
18114 }
18115
18116 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
18117    prefix part in such case.  See
18118    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18119
18120 static char *
18121 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
18122 {
18123   struct attribute *attr;
18124   char *base;
18125
18126   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
18127       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
18128     return NULL;
18129
18130   attr = dwarf2_attr (die, DW_AT_name, cu);
18131   if (attr != NULL && DW_STRING (attr) != NULL)
18132     return NULL;
18133
18134   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18135   if (attr == NULL)
18136     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18137   if (attr == NULL || DW_STRING (attr) == NULL)
18138     return NULL;
18139
18140   /* dwarf2_name had to be already called.  */
18141   gdb_assert (DW_STRING_IS_CANONICAL (attr));
18142
18143   /* Strip the base name, keep any leading namespaces/classes.  */
18144   base = strrchr (DW_STRING (attr), ':');
18145   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
18146     return "";
18147
18148   return obstack_copy0 (&cu->objfile->objfile_obstack,
18149                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
18150 }
18151
18152 /* Return the name of the namespace/class that DIE is defined within,
18153    or "" if we can't tell.  The caller should not xfree the result.
18154
18155    For example, if we're within the method foo() in the following
18156    code:
18157
18158    namespace N {
18159      class C {
18160        void foo () {
18161        }
18162      };
18163    }
18164
18165    then determine_prefix on foo's die will return "N::C".  */
18166
18167 static const char *
18168 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
18169 {
18170   struct die_info *parent, *spec_die;
18171   struct dwarf2_cu *spec_cu;
18172   struct type *parent_type;
18173   char *retval;
18174
18175   if (cu->language != language_cplus && cu->language != language_java
18176       && cu->language != language_fortran)
18177     return "";
18178
18179   retval = anonymous_struct_prefix (die, cu);
18180   if (retval)
18181     return retval;
18182
18183   /* We have to be careful in the presence of DW_AT_specification.
18184      For example, with GCC 3.4, given the code
18185
18186      namespace N {
18187        void foo() {
18188          // Definition of N::foo.
18189        }
18190      }
18191
18192      then we'll have a tree of DIEs like this:
18193
18194      1: DW_TAG_compile_unit
18195        2: DW_TAG_namespace        // N
18196          3: DW_TAG_subprogram     // declaration of N::foo
18197        4: DW_TAG_subprogram       // definition of N::foo
18198             DW_AT_specification   // refers to die #3
18199
18200      Thus, when processing die #4, we have to pretend that we're in
18201      the context of its DW_AT_specification, namely the contex of die
18202      #3.  */
18203   spec_cu = cu;
18204   spec_die = die_specification (die, &spec_cu);
18205   if (spec_die == NULL)
18206     parent = die->parent;
18207   else
18208     {
18209       parent = spec_die->parent;
18210       cu = spec_cu;
18211     }
18212
18213   if (parent == NULL)
18214     return "";
18215   else if (parent->building_fullname)
18216     {
18217       const char *name;
18218       const char *parent_name;
18219
18220       /* It has been seen on RealView 2.2 built binaries,
18221          DW_TAG_template_type_param types actually _defined_ as
18222          children of the parent class:
18223
18224          enum E {};
18225          template class <class Enum> Class{};
18226          Class<enum E> class_e;
18227
18228          1: DW_TAG_class_type (Class)
18229            2: DW_TAG_enumeration_type (E)
18230              3: DW_TAG_enumerator (enum1:0)
18231              3: DW_TAG_enumerator (enum2:1)
18232              ...
18233            2: DW_TAG_template_type_param
18234               DW_AT_type  DW_FORM_ref_udata (E)
18235
18236          Besides being broken debug info, it can put GDB into an
18237          infinite loop.  Consider:
18238
18239          When we're building the full name for Class<E>, we'll start
18240          at Class, and go look over its template type parameters,
18241          finding E.  We'll then try to build the full name of E, and
18242          reach here.  We're now trying to build the full name of E,
18243          and look over the parent DIE for containing scope.  In the
18244          broken case, if we followed the parent DIE of E, we'd again
18245          find Class, and once again go look at its template type
18246          arguments, etc., etc.  Simply don't consider such parent die
18247          as source-level parent of this die (it can't be, the language
18248          doesn't allow it), and break the loop here.  */
18249       name = dwarf2_name (die, cu);
18250       parent_name = dwarf2_name (parent, cu);
18251       complaint (&symfile_complaints,
18252                  _("template param type '%s' defined within parent '%s'"),
18253                  name ? name : "<unknown>",
18254                  parent_name ? parent_name : "<unknown>");
18255       return "";
18256     }
18257   else
18258     switch (parent->tag)
18259       {
18260       case DW_TAG_namespace:
18261         parent_type = read_type_die (parent, cu);
18262         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
18263            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
18264            Work around this problem here.  */
18265         if (cu->language == language_cplus
18266             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
18267           return "";
18268         /* We give a name to even anonymous namespaces.  */
18269         return TYPE_TAG_NAME (parent_type);
18270       case DW_TAG_class_type:
18271       case DW_TAG_interface_type:
18272       case DW_TAG_structure_type:
18273       case DW_TAG_union_type:
18274       case DW_TAG_module:
18275         parent_type = read_type_die (parent, cu);
18276         if (TYPE_TAG_NAME (parent_type) != NULL)
18277           return TYPE_TAG_NAME (parent_type);
18278         else
18279           /* An anonymous structure is only allowed non-static data
18280              members; no typedefs, no member functions, et cetera.
18281              So it does not need a prefix.  */
18282           return "";
18283       case DW_TAG_compile_unit:
18284       case DW_TAG_partial_unit:
18285         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
18286         if (cu->language == language_cplus
18287             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18288             && die->child != NULL
18289             && (die->tag == DW_TAG_class_type
18290                 || die->tag == DW_TAG_structure_type
18291                 || die->tag == DW_TAG_union_type))
18292           {
18293             char *name = guess_full_die_structure_name (die, cu);
18294             if (name != NULL)
18295               return name;
18296           }
18297         return "";
18298       default:
18299         return determine_prefix (parent, cu);
18300       }
18301 }
18302
18303 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
18304    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
18305    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
18306    an obconcat, otherwise allocate storage for the result.  The CU argument is
18307    used to determine the language and hence, the appropriate separator.  */
18308
18309 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
18310
18311 static char *
18312 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
18313                  int physname, struct dwarf2_cu *cu)
18314 {
18315   const char *lead = "";
18316   const char *sep;
18317
18318   if (suffix == NULL || suffix[0] == '\0'
18319       || prefix == NULL || prefix[0] == '\0')
18320     sep = "";
18321   else if (cu->language == language_java)
18322     sep = ".";
18323   else if (cu->language == language_fortran && physname)
18324     {
18325       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
18326          DW_AT_MIPS_linkage_name is preferred and used instead.  */
18327
18328       lead = "__";
18329       sep = "_MOD_";
18330     }
18331   else
18332     sep = "::";
18333
18334   if (prefix == NULL)
18335     prefix = "";
18336   if (suffix == NULL)
18337     suffix = "";
18338
18339   if (obs == NULL)
18340     {
18341       char *retval
18342         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
18343
18344       strcpy (retval, lead);
18345       strcat (retval, prefix);
18346       strcat (retval, sep);
18347       strcat (retval, suffix);
18348       return retval;
18349     }
18350   else
18351     {
18352       /* We have an obstack.  */
18353       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
18354     }
18355 }
18356
18357 /* Return sibling of die, NULL if no sibling.  */
18358
18359 static struct die_info *
18360 sibling_die (struct die_info *die)
18361 {
18362   return die->sibling;
18363 }
18364
18365 /* Get name of a die, return NULL if not found.  */
18366
18367 static const char *
18368 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
18369                           struct obstack *obstack)
18370 {
18371   if (name && cu->language == language_cplus)
18372     {
18373       char *canon_name = cp_canonicalize_string (name);
18374
18375       if (canon_name != NULL)
18376         {
18377           if (strcmp (canon_name, name) != 0)
18378             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
18379           xfree (canon_name);
18380         }
18381     }
18382
18383   return name;
18384 }
18385
18386 /* Get name of a die, return NULL if not found.  */
18387
18388 static const char *
18389 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
18390 {
18391   struct attribute *attr;
18392
18393   attr = dwarf2_attr (die, DW_AT_name, cu);
18394   if ((!attr || !DW_STRING (attr))
18395       && die->tag != DW_TAG_class_type
18396       && die->tag != DW_TAG_interface_type
18397       && die->tag != DW_TAG_structure_type
18398       && die->tag != DW_TAG_union_type)
18399     return NULL;
18400
18401   switch (die->tag)
18402     {
18403     case DW_TAG_compile_unit:
18404     case DW_TAG_partial_unit:
18405       /* Compilation units have a DW_AT_name that is a filename, not
18406          a source language identifier.  */
18407     case DW_TAG_enumeration_type:
18408     case DW_TAG_enumerator:
18409       /* These tags always have simple identifiers already; no need
18410          to canonicalize them.  */
18411       return DW_STRING (attr);
18412
18413     case DW_TAG_subprogram:
18414       /* Java constructors will all be named "<init>", so return
18415          the class name when we see this special case.  */
18416       if (cu->language == language_java
18417           && DW_STRING (attr) != NULL
18418           && strcmp (DW_STRING (attr), "<init>") == 0)
18419         {
18420           struct dwarf2_cu *spec_cu = cu;
18421           struct die_info *spec_die;
18422
18423           /* GCJ will output '<init>' for Java constructor names.
18424              For this special case, return the name of the parent class.  */
18425
18426           /* GCJ may output suprogram DIEs with AT_specification set.
18427              If so, use the name of the specified DIE.  */
18428           spec_die = die_specification (die, &spec_cu);
18429           if (spec_die != NULL)
18430             return dwarf2_name (spec_die, spec_cu);
18431
18432           do
18433             {
18434               die = die->parent;
18435               if (die->tag == DW_TAG_class_type)
18436                 return dwarf2_name (die, cu);
18437             }
18438           while (die->tag != DW_TAG_compile_unit
18439                  && die->tag != DW_TAG_partial_unit);
18440         }
18441       break;
18442
18443     case DW_TAG_class_type:
18444     case DW_TAG_interface_type:
18445     case DW_TAG_structure_type:
18446     case DW_TAG_union_type:
18447       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
18448          structures or unions.  These were of the form "._%d" in GCC 4.1,
18449          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
18450          and GCC 4.4.  We work around this problem by ignoring these.  */
18451       if (attr && DW_STRING (attr)
18452           && (strncmp (DW_STRING (attr), "._", 2) == 0
18453               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
18454         return NULL;
18455
18456       /* GCC might emit a nameless typedef that has a linkage name.  See
18457          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18458       if (!attr || DW_STRING (attr) == NULL)
18459         {
18460           char *demangled = NULL;
18461
18462           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18463           if (attr == NULL)
18464             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18465
18466           if (attr == NULL || DW_STRING (attr) == NULL)
18467             return NULL;
18468
18469           /* Avoid demangling DW_STRING (attr) the second time on a second
18470              call for the same DIE.  */
18471           if (!DW_STRING_IS_CANONICAL (attr))
18472             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
18473
18474           if (demangled)
18475             {
18476               char *base;
18477
18478               /* FIXME: we already did this for the partial symbol... */
18479               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
18480                                                 demangled, strlen (demangled));
18481               DW_STRING_IS_CANONICAL (attr) = 1;
18482               xfree (demangled);
18483
18484               /* Strip any leading namespaces/classes, keep only the base name.
18485                  DW_AT_name for named DIEs does not contain the prefixes.  */
18486               base = strrchr (DW_STRING (attr), ':');
18487               if (base && base > DW_STRING (attr) && base[-1] == ':')
18488                 return &base[1];
18489               else
18490                 return DW_STRING (attr);
18491             }
18492         }
18493       break;
18494
18495     default:
18496       break;
18497     }
18498
18499   if (!DW_STRING_IS_CANONICAL (attr))
18500     {
18501       DW_STRING (attr)
18502         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
18503                                     &cu->objfile->objfile_obstack);
18504       DW_STRING_IS_CANONICAL (attr) = 1;
18505     }
18506   return DW_STRING (attr);
18507 }
18508
18509 /* Return the die that this die in an extension of, or NULL if there
18510    is none.  *EXT_CU is the CU containing DIE on input, and the CU
18511    containing the return value on output.  */
18512
18513 static struct die_info *
18514 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
18515 {
18516   struct attribute *attr;
18517
18518   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
18519   if (attr == NULL)
18520     return NULL;
18521
18522   return follow_die_ref (die, attr, ext_cu);
18523 }
18524
18525 /* Convert a DIE tag into its string name.  */
18526
18527 static const char *
18528 dwarf_tag_name (unsigned tag)
18529 {
18530   const char *name = get_DW_TAG_name (tag);
18531
18532   if (name == NULL)
18533     return "DW_TAG_<unknown>";
18534
18535   return name;
18536 }
18537
18538 /* Convert a DWARF attribute code into its string name.  */
18539
18540 static const char *
18541 dwarf_attr_name (unsigned attr)
18542 {
18543   const char *name;
18544
18545 #ifdef MIPS /* collides with DW_AT_HP_block_index */
18546   if (attr == DW_AT_MIPS_fde)
18547     return "DW_AT_MIPS_fde";
18548 #else
18549   if (attr == DW_AT_HP_block_index)
18550     return "DW_AT_HP_block_index";
18551 #endif
18552
18553   name = get_DW_AT_name (attr);
18554
18555   if (name == NULL)
18556     return "DW_AT_<unknown>";
18557
18558   return name;
18559 }
18560
18561 /* Convert a DWARF value form code into its string name.  */
18562
18563 static const char *
18564 dwarf_form_name (unsigned form)
18565 {
18566   const char *name = get_DW_FORM_name (form);
18567
18568   if (name == NULL)
18569     return "DW_FORM_<unknown>";
18570
18571   return name;
18572 }
18573
18574 static char *
18575 dwarf_bool_name (unsigned mybool)
18576 {
18577   if (mybool)
18578     return "TRUE";
18579   else
18580     return "FALSE";
18581 }
18582
18583 /* Convert a DWARF type code into its string name.  */
18584
18585 static const char *
18586 dwarf_type_encoding_name (unsigned enc)
18587 {
18588   const char *name = get_DW_ATE_name (enc);
18589
18590   if (name == NULL)
18591     return "DW_ATE_<unknown>";
18592
18593   return name;
18594 }
18595
18596 static void
18597 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
18598 {
18599   unsigned int i;
18600
18601   print_spaces (indent, f);
18602   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
18603            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
18604
18605   if (die->parent != NULL)
18606     {
18607       print_spaces (indent, f);
18608       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
18609                           die->parent->offset.sect_off);
18610     }
18611
18612   print_spaces (indent, f);
18613   fprintf_unfiltered (f, "  has children: %s\n",
18614            dwarf_bool_name (die->child != NULL));
18615
18616   print_spaces (indent, f);
18617   fprintf_unfiltered (f, "  attributes:\n");
18618
18619   for (i = 0; i < die->num_attrs; ++i)
18620     {
18621       print_spaces (indent, f);
18622       fprintf_unfiltered (f, "    %s (%s) ",
18623                dwarf_attr_name (die->attrs[i].name),
18624                dwarf_form_name (die->attrs[i].form));
18625
18626       switch (die->attrs[i].form)
18627         {
18628         case DW_FORM_addr:
18629         case DW_FORM_GNU_addr_index:
18630           fprintf_unfiltered (f, "address: ");
18631           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
18632           break;
18633         case DW_FORM_block2:
18634         case DW_FORM_block4:
18635         case DW_FORM_block:
18636         case DW_FORM_block1:
18637           fprintf_unfiltered (f, "block: size %s",
18638                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18639           break;
18640         case DW_FORM_exprloc:
18641           fprintf_unfiltered (f, "expression: size %s",
18642                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18643           break;
18644         case DW_FORM_ref_addr:
18645           fprintf_unfiltered (f, "ref address: ");
18646           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18647           break;
18648         case DW_FORM_GNU_ref_alt:
18649           fprintf_unfiltered (f, "alt ref address: ");
18650           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18651           break;
18652         case DW_FORM_ref1:
18653         case DW_FORM_ref2:
18654         case DW_FORM_ref4:
18655         case DW_FORM_ref8:
18656         case DW_FORM_ref_udata:
18657           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
18658                               (long) (DW_UNSND (&die->attrs[i])));
18659           break;
18660         case DW_FORM_data1:
18661         case DW_FORM_data2:
18662         case DW_FORM_data4:
18663         case DW_FORM_data8:
18664         case DW_FORM_udata:
18665         case DW_FORM_sdata:
18666           fprintf_unfiltered (f, "constant: %s",
18667                               pulongest (DW_UNSND (&die->attrs[i])));
18668           break;
18669         case DW_FORM_sec_offset:
18670           fprintf_unfiltered (f, "section offset: %s",
18671                               pulongest (DW_UNSND (&die->attrs[i])));
18672           break;
18673         case DW_FORM_ref_sig8:
18674           fprintf_unfiltered (f, "signature: %s",
18675                               hex_string (DW_SIGNATURE (&die->attrs[i])));
18676           break;
18677         case DW_FORM_string:
18678         case DW_FORM_strp:
18679         case DW_FORM_GNU_str_index:
18680         case DW_FORM_GNU_strp_alt:
18681           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
18682                    DW_STRING (&die->attrs[i])
18683                    ? DW_STRING (&die->attrs[i]) : "",
18684                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
18685           break;
18686         case DW_FORM_flag:
18687           if (DW_UNSND (&die->attrs[i]))
18688             fprintf_unfiltered (f, "flag: TRUE");
18689           else
18690             fprintf_unfiltered (f, "flag: FALSE");
18691           break;
18692         case DW_FORM_flag_present:
18693           fprintf_unfiltered (f, "flag: TRUE");
18694           break;
18695         case DW_FORM_indirect:
18696           /* The reader will have reduced the indirect form to
18697              the "base form" so this form should not occur.  */
18698           fprintf_unfiltered (f, 
18699                               "unexpected attribute form: DW_FORM_indirect");
18700           break;
18701         default:
18702           fprintf_unfiltered (f, "unsupported attribute form: %d.",
18703                    die->attrs[i].form);
18704           break;
18705         }
18706       fprintf_unfiltered (f, "\n");
18707     }
18708 }
18709
18710 static void
18711 dump_die_for_error (struct die_info *die)
18712 {
18713   dump_die_shallow (gdb_stderr, 0, die);
18714 }
18715
18716 static void
18717 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
18718 {
18719   int indent = level * 4;
18720
18721   gdb_assert (die != NULL);
18722
18723   if (level >= max_level)
18724     return;
18725
18726   dump_die_shallow (f, indent, die);
18727
18728   if (die->child != NULL)
18729     {
18730       print_spaces (indent, f);
18731       fprintf_unfiltered (f, "  Children:");
18732       if (level + 1 < max_level)
18733         {
18734           fprintf_unfiltered (f, "\n");
18735           dump_die_1 (f, level + 1, max_level, die->child);
18736         }
18737       else
18738         {
18739           fprintf_unfiltered (f,
18740                               " [not printed, max nesting level reached]\n");
18741         }
18742     }
18743
18744   if (die->sibling != NULL && level > 0)
18745     {
18746       dump_die_1 (f, level, max_level, die->sibling);
18747     }
18748 }
18749
18750 /* This is called from the pdie macro in gdbinit.in.
18751    It's not static so gcc will keep a copy callable from gdb.  */
18752
18753 void
18754 dump_die (struct die_info *die, int max_level)
18755 {
18756   dump_die_1 (gdb_stdlog, 0, max_level, die);
18757 }
18758
18759 static void
18760 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
18761 {
18762   void **slot;
18763
18764   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18765                                    INSERT);
18766
18767   *slot = die;
18768 }
18769
18770 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18771    required kind.  */
18772
18773 static sect_offset
18774 dwarf2_get_ref_die_offset (const struct attribute *attr)
18775 {
18776   sect_offset retval = { DW_UNSND (attr) };
18777
18778   if (attr_form_is_ref (attr))
18779     return retval;
18780
18781   retval.sect_off = 0;
18782   complaint (&symfile_complaints,
18783              _("unsupported die ref attribute form: '%s'"),
18784              dwarf_form_name (attr->form));
18785   return retval;
18786 }
18787
18788 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18789  * the value held by the attribute is not constant.  */
18790
18791 static LONGEST
18792 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18793 {
18794   if (attr->form == DW_FORM_sdata)
18795     return DW_SND (attr);
18796   else if (attr->form == DW_FORM_udata
18797            || attr->form == DW_FORM_data1
18798            || attr->form == DW_FORM_data2
18799            || attr->form == DW_FORM_data4
18800            || attr->form == DW_FORM_data8)
18801     return DW_UNSND (attr);
18802   else
18803     {
18804       complaint (&symfile_complaints,
18805                  _("Attribute value is not a constant (%s)"),
18806                  dwarf_form_name (attr->form));
18807       return default_value;
18808     }
18809 }
18810
18811 /* Follow reference or signature attribute ATTR of SRC_DIE.
18812    On entry *REF_CU is the CU of SRC_DIE.
18813    On exit *REF_CU is the CU of the result.  */
18814
18815 static struct die_info *
18816 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18817                        struct dwarf2_cu **ref_cu)
18818 {
18819   struct die_info *die;
18820
18821   if (attr_form_is_ref (attr))
18822     die = follow_die_ref (src_die, attr, ref_cu);
18823   else if (attr->form == DW_FORM_ref_sig8)
18824     die = follow_die_sig (src_die, attr, ref_cu);
18825   else
18826     {
18827       dump_die_for_error (src_die);
18828       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18829              objfile_name ((*ref_cu)->objfile));
18830     }
18831
18832   return die;
18833 }
18834
18835 /* Follow reference OFFSET.
18836    On entry *REF_CU is the CU of the source die referencing OFFSET.
18837    On exit *REF_CU is the CU of the result.
18838    Returns NULL if OFFSET is invalid.  */
18839
18840 static struct die_info *
18841 follow_die_offset (sect_offset offset, int offset_in_dwz,
18842                    struct dwarf2_cu **ref_cu)
18843 {
18844   struct die_info temp_die;
18845   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18846
18847   gdb_assert (cu->per_cu != NULL);
18848
18849   target_cu = cu;
18850
18851   if (cu->per_cu->is_debug_types)
18852     {
18853       /* .debug_types CUs cannot reference anything outside their CU.
18854          If they need to, they have to reference a signatured type via
18855          DW_FORM_ref_sig8.  */
18856       if (! offset_in_cu_p (&cu->header, offset))
18857         return NULL;
18858     }
18859   else if (offset_in_dwz != cu->per_cu->is_dwz
18860            || ! offset_in_cu_p (&cu->header, offset))
18861     {
18862       struct dwarf2_per_cu_data *per_cu;
18863
18864       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18865                                                  cu->objfile);
18866
18867       /* If necessary, add it to the queue and load its DIEs.  */
18868       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18869         load_full_comp_unit (per_cu, cu->language);
18870
18871       target_cu = per_cu->cu;
18872     }
18873   else if (cu->dies == NULL)
18874     {
18875       /* We're loading full DIEs during partial symbol reading.  */
18876       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18877       load_full_comp_unit (cu->per_cu, language_minimal);
18878     }
18879
18880   *ref_cu = target_cu;
18881   temp_die.offset = offset;
18882   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18883 }
18884
18885 /* Follow reference attribute ATTR of SRC_DIE.
18886    On entry *REF_CU is the CU of SRC_DIE.
18887    On exit *REF_CU is the CU of the result.  */
18888
18889 static struct die_info *
18890 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18891                 struct dwarf2_cu **ref_cu)
18892 {
18893   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18894   struct dwarf2_cu *cu = *ref_cu;
18895   struct die_info *die;
18896
18897   die = follow_die_offset (offset,
18898                            (attr->form == DW_FORM_GNU_ref_alt
18899                             || cu->per_cu->is_dwz),
18900                            ref_cu);
18901   if (!die)
18902     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18903            "at 0x%x [in module %s]"),
18904            offset.sect_off, src_die->offset.sect_off,
18905            objfile_name (cu->objfile));
18906
18907   return die;
18908 }
18909
18910 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18911    Returned value is intended for DW_OP_call*.  Returned
18912    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18913
18914 struct dwarf2_locexpr_baton
18915 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18916                                struct dwarf2_per_cu_data *per_cu,
18917                                CORE_ADDR (*get_frame_pc) (void *baton),
18918                                void *baton)
18919 {
18920   struct dwarf2_cu *cu;
18921   struct die_info *die;
18922   struct attribute *attr;
18923   struct dwarf2_locexpr_baton retval;
18924
18925   dw2_setup (per_cu->objfile);
18926
18927   if (per_cu->cu == NULL)
18928     load_cu (per_cu);
18929   cu = per_cu->cu;
18930
18931   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18932   if (!die)
18933     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18934            offset.sect_off, objfile_name (per_cu->objfile));
18935
18936   attr = dwarf2_attr (die, DW_AT_location, cu);
18937   if (!attr)
18938     {
18939       /* DWARF: "If there is no such attribute, then there is no effect.".
18940          DATA is ignored if SIZE is 0.  */
18941
18942       retval.data = NULL;
18943       retval.size = 0;
18944     }
18945   else if (attr_form_is_section_offset (attr))
18946     {
18947       struct dwarf2_loclist_baton loclist_baton;
18948       CORE_ADDR pc = (*get_frame_pc) (baton);
18949       size_t size;
18950
18951       fill_in_loclist_baton (cu, &loclist_baton, attr);
18952
18953       retval.data = dwarf2_find_location_expression (&loclist_baton,
18954                                                      &size, pc);
18955       retval.size = size;
18956     }
18957   else
18958     {
18959       if (!attr_form_is_block (attr))
18960         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18961                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18962                offset.sect_off, objfile_name (per_cu->objfile));
18963
18964       retval.data = DW_BLOCK (attr)->data;
18965       retval.size = DW_BLOCK (attr)->size;
18966     }
18967   retval.per_cu = cu->per_cu;
18968
18969   age_cached_comp_units ();
18970
18971   return retval;
18972 }
18973
18974 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18975    offset.  */
18976
18977 struct dwarf2_locexpr_baton
18978 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18979                              struct dwarf2_per_cu_data *per_cu,
18980                              CORE_ADDR (*get_frame_pc) (void *baton),
18981                              void *baton)
18982 {
18983   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18984
18985   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18986 }
18987
18988 /* Write a constant of a given type as target-ordered bytes into
18989    OBSTACK.  */
18990
18991 static const gdb_byte *
18992 write_constant_as_bytes (struct obstack *obstack,
18993                          enum bfd_endian byte_order,
18994                          struct type *type,
18995                          ULONGEST value,
18996                          LONGEST *len)
18997 {
18998   gdb_byte *result;
18999
19000   *len = TYPE_LENGTH (type);
19001   result = obstack_alloc (obstack, *len);
19002   store_unsigned_integer (result, *len, byte_order, value);
19003
19004   return result;
19005 }
19006
19007 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
19008    pointer to the constant bytes and set LEN to the length of the
19009    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
19010    does not have a DW_AT_const_value, return NULL.  */
19011
19012 const gdb_byte *
19013 dwarf2_fetch_constant_bytes (sect_offset offset,
19014                              struct dwarf2_per_cu_data *per_cu,
19015                              struct obstack *obstack,
19016                              LONGEST *len)
19017 {
19018   struct dwarf2_cu *cu;
19019   struct die_info *die;
19020   struct attribute *attr;
19021   const gdb_byte *result = NULL;
19022   struct type *type;
19023   LONGEST value;
19024   enum bfd_endian byte_order;
19025
19026   dw2_setup (per_cu->objfile);
19027
19028   if (per_cu->cu == NULL)
19029     load_cu (per_cu);
19030   cu = per_cu->cu;
19031
19032   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
19033   if (!die)
19034     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
19035            offset.sect_off, objfile_name (per_cu->objfile));
19036
19037
19038   attr = dwarf2_attr (die, DW_AT_const_value, cu);
19039   if (attr == NULL)
19040     return NULL;
19041
19042   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
19043                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19044
19045   switch (attr->form)
19046     {
19047     case DW_FORM_addr:
19048     case DW_FORM_GNU_addr_index:
19049       {
19050         gdb_byte *tem;
19051
19052         *len = cu->header.addr_size;
19053         tem = obstack_alloc (obstack, *len);
19054         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
19055         result = tem;
19056       }
19057       break;
19058     case DW_FORM_string:
19059     case DW_FORM_strp:
19060     case DW_FORM_GNU_str_index:
19061     case DW_FORM_GNU_strp_alt:
19062       /* DW_STRING is already allocated on the objfile obstack, point
19063          directly to it.  */
19064       result = (const gdb_byte *) DW_STRING (attr);
19065       *len = strlen (DW_STRING (attr));
19066       break;
19067     case DW_FORM_block1:
19068     case DW_FORM_block2:
19069     case DW_FORM_block4:
19070     case DW_FORM_block:
19071     case DW_FORM_exprloc:
19072       result = DW_BLOCK (attr)->data;
19073       *len = DW_BLOCK (attr)->size;
19074       break;
19075
19076       /* The DW_AT_const_value attributes are supposed to carry the
19077          symbol's value "represented as it would be on the target
19078          architecture."  By the time we get here, it's already been
19079          converted to host endianness, so we just need to sign- or
19080          zero-extend it as appropriate.  */
19081     case DW_FORM_data1:
19082       type = die_type (die, cu);
19083       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
19084       if (result == NULL)
19085         result = write_constant_as_bytes (obstack, byte_order,
19086                                           type, value, len);
19087       break;
19088     case DW_FORM_data2:
19089       type = die_type (die, cu);
19090       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
19091       if (result == NULL)
19092         result = write_constant_as_bytes (obstack, byte_order,
19093                                           type, value, len);
19094       break;
19095     case DW_FORM_data4:
19096       type = die_type (die, cu);
19097       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
19098       if (result == NULL)
19099         result = write_constant_as_bytes (obstack, byte_order,
19100                                           type, value, len);
19101       break;
19102     case DW_FORM_data8:
19103       type = die_type (die, cu);
19104       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
19105       if (result == NULL)
19106         result = write_constant_as_bytes (obstack, byte_order,
19107                                           type, value, len);
19108       break;
19109
19110     case DW_FORM_sdata:
19111       type = die_type (die, cu);
19112       result = write_constant_as_bytes (obstack, byte_order,
19113                                         type, DW_SND (attr), len);
19114       break;
19115
19116     case DW_FORM_udata:
19117       type = die_type (die, cu);
19118       result = write_constant_as_bytes (obstack, byte_order,
19119                                         type, DW_UNSND (attr), len);
19120       break;
19121
19122     default:
19123       complaint (&symfile_complaints,
19124                  _("unsupported const value attribute form: '%s'"),
19125                  dwarf_form_name (attr->form));
19126       break;
19127     }
19128
19129   return result;
19130 }
19131
19132 /* Return the type of the DIE at DIE_OFFSET in the CU named by
19133    PER_CU.  */
19134
19135 struct type *
19136 dwarf2_get_die_type (cu_offset die_offset,
19137                      struct dwarf2_per_cu_data *per_cu)
19138 {
19139   sect_offset die_offset_sect;
19140
19141   dw2_setup (per_cu->objfile);
19142
19143   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
19144   return get_die_type_at_offset (die_offset_sect, per_cu);
19145 }
19146
19147 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
19148    On entry *REF_CU is the CU of SRC_DIE.
19149    On exit *REF_CU is the CU of the result.
19150    Returns NULL if the referenced DIE isn't found.  */
19151
19152 static struct die_info *
19153 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
19154                   struct dwarf2_cu **ref_cu)
19155 {
19156   struct objfile *objfile = (*ref_cu)->objfile;
19157   struct die_info temp_die;
19158   struct dwarf2_cu *sig_cu;
19159   struct die_info *die;
19160
19161   /* While it might be nice to assert sig_type->type == NULL here,
19162      we can get here for DW_AT_imported_declaration where we need
19163      the DIE not the type.  */
19164
19165   /* If necessary, add it to the queue and load its DIEs.  */
19166
19167   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
19168     read_signatured_type (sig_type);
19169
19170   sig_cu = sig_type->per_cu.cu;
19171   gdb_assert (sig_cu != NULL);
19172   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
19173   temp_die.offset = sig_type->type_offset_in_section;
19174   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
19175                              temp_die.offset.sect_off);
19176   if (die)
19177     {
19178       /* For .gdb_index version 7 keep track of included TUs.
19179          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
19180       if (dwarf2_per_objfile->index_table != NULL
19181           && dwarf2_per_objfile->index_table->version <= 7)
19182         {
19183           VEC_safe_push (dwarf2_per_cu_ptr,
19184                          (*ref_cu)->per_cu->imported_symtabs,
19185                          sig_cu->per_cu);
19186         }
19187
19188       *ref_cu = sig_cu;
19189       return die;
19190     }
19191
19192   return NULL;
19193 }
19194
19195 /* Follow signatured type referenced by ATTR in SRC_DIE.
19196    On entry *REF_CU is the CU of SRC_DIE.
19197    On exit *REF_CU is the CU of the result.
19198    The result is the DIE of the type.
19199    If the referenced type cannot be found an error is thrown.  */
19200
19201 static struct die_info *
19202 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
19203                 struct dwarf2_cu **ref_cu)
19204 {
19205   ULONGEST signature = DW_SIGNATURE (attr);
19206   struct signatured_type *sig_type;
19207   struct die_info *die;
19208
19209   gdb_assert (attr->form == DW_FORM_ref_sig8);
19210
19211   sig_type = lookup_signatured_type (*ref_cu, signature);
19212   /* sig_type will be NULL if the signatured type is missing from
19213      the debug info.  */
19214   if (sig_type == NULL)
19215     {
19216       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
19217                " from DIE at 0x%x [in module %s]"),
19218              hex_string (signature), src_die->offset.sect_off,
19219              objfile_name ((*ref_cu)->objfile));
19220     }
19221
19222   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
19223   if (die == NULL)
19224     {
19225       dump_die_for_error (src_die);
19226       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
19227                " from DIE at 0x%x [in module %s]"),
19228              hex_string (signature), src_die->offset.sect_off,
19229              objfile_name ((*ref_cu)->objfile));
19230     }
19231
19232   return die;
19233 }
19234
19235 /* Get the type specified by SIGNATURE referenced in DIE/CU,
19236    reading in and processing the type unit if necessary.  */
19237
19238 static struct type *
19239 get_signatured_type (struct die_info *die, ULONGEST signature,
19240                      struct dwarf2_cu *cu)
19241 {
19242   struct signatured_type *sig_type;
19243   struct dwarf2_cu *type_cu;
19244   struct die_info *type_die;
19245   struct type *type;
19246
19247   sig_type = lookup_signatured_type (cu, signature);
19248   /* sig_type will be NULL if the signatured type is missing from
19249      the debug info.  */
19250   if (sig_type == NULL)
19251     {
19252       complaint (&symfile_complaints,
19253                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
19254                    " from DIE at 0x%x [in module %s]"),
19255                  hex_string (signature), die->offset.sect_off,
19256                  objfile_name (dwarf2_per_objfile->objfile));
19257       return build_error_marker_type (cu, die);
19258     }
19259
19260   /* If we already know the type we're done.  */
19261   if (sig_type->type != NULL)
19262     return sig_type->type;
19263
19264   type_cu = cu;
19265   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
19266   if (type_die != NULL)
19267     {
19268       /* N.B. We need to call get_die_type to ensure only one type for this DIE
19269          is created.  This is important, for example, because for c++ classes
19270          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
19271       type = read_type_die (type_die, type_cu);
19272       if (type == NULL)
19273         {
19274           complaint (&symfile_complaints,
19275                      _("Dwarf Error: Cannot build signatured type %s"
19276                        " referenced from DIE at 0x%x [in module %s]"),
19277                      hex_string (signature), die->offset.sect_off,
19278                      objfile_name (dwarf2_per_objfile->objfile));
19279           type = build_error_marker_type (cu, die);
19280         }
19281     }
19282   else
19283     {
19284       complaint (&symfile_complaints,
19285                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
19286                    " from DIE at 0x%x [in module %s]"),
19287                  hex_string (signature), die->offset.sect_off,
19288                  objfile_name (dwarf2_per_objfile->objfile));
19289       type = build_error_marker_type (cu, die);
19290     }
19291   sig_type->type = type;
19292
19293   return type;
19294 }
19295
19296 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
19297    reading in and processing the type unit if necessary.  */
19298
19299 static struct type *
19300 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
19301                           struct dwarf2_cu *cu) /* ARI: editCase function */
19302 {
19303   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
19304   if (attr_form_is_ref (attr))
19305     {
19306       struct dwarf2_cu *type_cu = cu;
19307       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
19308
19309       return read_type_die (type_die, type_cu);
19310     }
19311   else if (attr->form == DW_FORM_ref_sig8)
19312     {
19313       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
19314     }
19315   else
19316     {
19317       complaint (&symfile_complaints,
19318                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
19319                    " at 0x%x [in module %s]"),
19320                  dwarf_form_name (attr->form), die->offset.sect_off,
19321                  objfile_name (dwarf2_per_objfile->objfile));
19322       return build_error_marker_type (cu, die);
19323     }
19324 }
19325
19326 /* Load the DIEs associated with type unit PER_CU into memory.  */
19327
19328 static void
19329 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
19330 {
19331   struct signatured_type *sig_type;
19332
19333   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
19334   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
19335
19336   /* We have the per_cu, but we need the signatured_type.
19337      Fortunately this is an easy translation.  */
19338   gdb_assert (per_cu->is_debug_types);
19339   sig_type = (struct signatured_type *) per_cu;
19340
19341   gdb_assert (per_cu->cu == NULL);
19342
19343   read_signatured_type (sig_type);
19344
19345   gdb_assert (per_cu->cu != NULL);
19346 }
19347
19348 /* die_reader_func for read_signatured_type.
19349    This is identical to load_full_comp_unit_reader,
19350    but is kept separate for now.  */
19351
19352 static void
19353 read_signatured_type_reader (const struct die_reader_specs *reader,
19354                              const gdb_byte *info_ptr,
19355                              struct die_info *comp_unit_die,
19356                              int has_children,
19357                              void *data)
19358 {
19359   struct dwarf2_cu *cu = reader->cu;
19360
19361   gdb_assert (cu->die_hash == NULL);
19362   cu->die_hash =
19363     htab_create_alloc_ex (cu->header.length / 12,
19364                           die_hash,
19365                           die_eq,
19366                           NULL,
19367                           &cu->comp_unit_obstack,
19368                           hashtab_obstack_allocate,
19369                           dummy_obstack_deallocate);
19370
19371   if (has_children)
19372     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
19373                                                   &info_ptr, comp_unit_die);
19374   cu->dies = comp_unit_die;
19375   /* comp_unit_die is not stored in die_hash, no need.  */
19376
19377   /* We try not to read any attributes in this function, because not
19378      all CUs needed for references have been loaded yet, and symbol
19379      table processing isn't initialized.  But we have to set the CU language,
19380      or we won't be able to build types correctly.
19381      Similarly, if we do not read the producer, we can not apply
19382      producer-specific interpretation.  */
19383   prepare_one_comp_unit (cu, cu->dies, language_minimal);
19384 }
19385
19386 /* Read in a signatured type and build its CU and DIEs.
19387    If the type is a stub for the real type in a DWO file,
19388    read in the real type from the DWO file as well.  */
19389
19390 static void
19391 read_signatured_type (struct signatured_type *sig_type)
19392 {
19393   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
19394
19395   gdb_assert (per_cu->is_debug_types);
19396   gdb_assert (per_cu->cu == NULL);
19397
19398   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
19399                            read_signatured_type_reader, NULL);
19400   sig_type->per_cu.tu_read = 1;
19401 }
19402
19403 /* Decode simple location descriptions.
19404    Given a pointer to a dwarf block that defines a location, compute
19405    the location and return the value.
19406
19407    NOTE drow/2003-11-18: This function is called in two situations
19408    now: for the address of static or global variables (partial symbols
19409    only) and for offsets into structures which are expected to be
19410    (more or less) constant.  The partial symbol case should go away,
19411    and only the constant case should remain.  That will let this
19412    function complain more accurately.  A few special modes are allowed
19413    without complaint for global variables (for instance, global
19414    register values and thread-local values).
19415
19416    A location description containing no operations indicates that the
19417    object is optimized out.  The return value is 0 for that case.
19418    FIXME drow/2003-11-16: No callers check for this case any more; soon all
19419    callers will only want a very basic result and this can become a
19420    complaint.
19421
19422    Note that stack[0] is unused except as a default error return.  */
19423
19424 static CORE_ADDR
19425 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
19426 {
19427   struct objfile *objfile = cu->objfile;
19428   size_t i;
19429   size_t size = blk->size;
19430   const gdb_byte *data = blk->data;
19431   CORE_ADDR stack[64];
19432   int stacki;
19433   unsigned int bytes_read, unsnd;
19434   gdb_byte op;
19435
19436   i = 0;
19437   stacki = 0;
19438   stack[stacki] = 0;
19439   stack[++stacki] = 0;
19440
19441   while (i < size)
19442     {
19443       op = data[i++];
19444       switch (op)
19445         {
19446         case DW_OP_lit0:
19447         case DW_OP_lit1:
19448         case DW_OP_lit2:
19449         case DW_OP_lit3:
19450         case DW_OP_lit4:
19451         case DW_OP_lit5:
19452         case DW_OP_lit6:
19453         case DW_OP_lit7:
19454         case DW_OP_lit8:
19455         case DW_OP_lit9:
19456         case DW_OP_lit10:
19457         case DW_OP_lit11:
19458         case DW_OP_lit12:
19459         case DW_OP_lit13:
19460         case DW_OP_lit14:
19461         case DW_OP_lit15:
19462         case DW_OP_lit16:
19463         case DW_OP_lit17:
19464         case DW_OP_lit18:
19465         case DW_OP_lit19:
19466         case DW_OP_lit20:
19467         case DW_OP_lit21:
19468         case DW_OP_lit22:
19469         case DW_OP_lit23:
19470         case DW_OP_lit24:
19471         case DW_OP_lit25:
19472         case DW_OP_lit26:
19473         case DW_OP_lit27:
19474         case DW_OP_lit28:
19475         case DW_OP_lit29:
19476         case DW_OP_lit30:
19477         case DW_OP_lit31:
19478           stack[++stacki] = op - DW_OP_lit0;
19479           break;
19480
19481         case DW_OP_reg0:
19482         case DW_OP_reg1:
19483         case DW_OP_reg2:
19484         case DW_OP_reg3:
19485         case DW_OP_reg4:
19486         case DW_OP_reg5:
19487         case DW_OP_reg6:
19488         case DW_OP_reg7:
19489         case DW_OP_reg8:
19490         case DW_OP_reg9:
19491         case DW_OP_reg10:
19492         case DW_OP_reg11:
19493         case DW_OP_reg12:
19494         case DW_OP_reg13:
19495         case DW_OP_reg14:
19496         case DW_OP_reg15:
19497         case DW_OP_reg16:
19498         case DW_OP_reg17:
19499         case DW_OP_reg18:
19500         case DW_OP_reg19:
19501         case DW_OP_reg20:
19502         case DW_OP_reg21:
19503         case DW_OP_reg22:
19504         case DW_OP_reg23:
19505         case DW_OP_reg24:
19506         case DW_OP_reg25:
19507         case DW_OP_reg26:
19508         case DW_OP_reg27:
19509         case DW_OP_reg28:
19510         case DW_OP_reg29:
19511         case DW_OP_reg30:
19512         case DW_OP_reg31:
19513           stack[++stacki] = op - DW_OP_reg0;
19514           if (i < size)
19515             dwarf2_complex_location_expr_complaint ();
19516           break;
19517
19518         case DW_OP_regx:
19519           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
19520           i += bytes_read;
19521           stack[++stacki] = unsnd;
19522           if (i < size)
19523             dwarf2_complex_location_expr_complaint ();
19524           break;
19525
19526         case DW_OP_addr:
19527           stack[++stacki] = read_address (objfile->obfd, &data[i],
19528                                           cu, &bytes_read);
19529           i += bytes_read;
19530           break;
19531
19532         case DW_OP_const1u:
19533           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
19534           i += 1;
19535           break;
19536
19537         case DW_OP_const1s:
19538           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
19539           i += 1;
19540           break;
19541
19542         case DW_OP_const2u:
19543           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
19544           i += 2;
19545           break;
19546
19547         case DW_OP_const2s:
19548           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
19549           i += 2;
19550           break;
19551
19552         case DW_OP_const4u:
19553           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
19554           i += 4;
19555           break;
19556
19557         case DW_OP_const4s:
19558           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
19559           i += 4;
19560           break;
19561
19562         case DW_OP_const8u:
19563           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
19564           i += 8;
19565           break;
19566
19567         case DW_OP_constu:
19568           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
19569                                                   &bytes_read);
19570           i += bytes_read;
19571           break;
19572
19573         case DW_OP_consts:
19574           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
19575           i += bytes_read;
19576           break;
19577
19578         case DW_OP_dup:
19579           stack[stacki + 1] = stack[stacki];
19580           stacki++;
19581           break;
19582
19583         case DW_OP_plus:
19584           stack[stacki - 1] += stack[stacki];
19585           stacki--;
19586           break;
19587
19588         case DW_OP_plus_uconst:
19589           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
19590                                                  &bytes_read);
19591           i += bytes_read;
19592           break;
19593
19594         case DW_OP_minus:
19595           stack[stacki - 1] -= stack[stacki];
19596           stacki--;
19597           break;
19598
19599         case DW_OP_deref:
19600           /* If we're not the last op, then we definitely can't encode
19601              this using GDB's address_class enum.  This is valid for partial
19602              global symbols, although the variable's address will be bogus
19603              in the psymtab.  */
19604           if (i < size)
19605             dwarf2_complex_location_expr_complaint ();
19606           break;
19607
19608         case DW_OP_GNU_push_tls_address:
19609           /* The top of the stack has the offset from the beginning
19610              of the thread control block at which the variable is located.  */
19611           /* Nothing should follow this operator, so the top of stack would
19612              be returned.  */
19613           /* This is valid for partial global symbols, but the variable's
19614              address will be bogus in the psymtab.  Make it always at least
19615              non-zero to not look as a variable garbage collected by linker
19616              which have DW_OP_addr 0.  */
19617           if (i < size)
19618             dwarf2_complex_location_expr_complaint ();
19619           stack[stacki]++;
19620           break;
19621
19622         case DW_OP_GNU_uninit:
19623           break;
19624
19625         case DW_OP_GNU_addr_index:
19626         case DW_OP_GNU_const_index:
19627           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
19628                                                          &bytes_read);
19629           i += bytes_read;
19630           break;
19631
19632         default:
19633           {
19634             const char *name = get_DW_OP_name (op);
19635
19636             if (name)
19637               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
19638                          name);
19639             else
19640               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
19641                          op);
19642           }
19643
19644           return (stack[stacki]);
19645         }
19646
19647       /* Enforce maximum stack depth of SIZE-1 to avoid writing
19648          outside of the allocated space.  Also enforce minimum>0.  */
19649       if (stacki >= ARRAY_SIZE (stack) - 1)
19650         {
19651           complaint (&symfile_complaints,
19652                      _("location description stack overflow"));
19653           return 0;
19654         }
19655
19656       if (stacki <= 0)
19657         {
19658           complaint (&symfile_complaints,
19659                      _("location description stack underflow"));
19660           return 0;
19661         }
19662     }
19663   return (stack[stacki]);
19664 }
19665
19666 /* memory allocation interface */
19667
19668 static struct dwarf_block *
19669 dwarf_alloc_block (struct dwarf2_cu *cu)
19670 {
19671   struct dwarf_block *blk;
19672
19673   blk = (struct dwarf_block *)
19674     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
19675   return (blk);
19676 }
19677
19678 static struct die_info *
19679 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
19680 {
19681   struct die_info *die;
19682   size_t size = sizeof (struct die_info);
19683
19684   if (num_attrs > 1)
19685     size += (num_attrs - 1) * sizeof (struct attribute);
19686
19687   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
19688   memset (die, 0, sizeof (struct die_info));
19689   return (die);
19690 }
19691
19692 \f
19693 /* Macro support.  */
19694
19695 /* Return file name relative to the compilation directory of file number I in
19696    *LH's file name table.  The result is allocated using xmalloc; the caller is
19697    responsible for freeing it.  */
19698
19699 static char *
19700 file_file_name (int file, struct line_header *lh)
19701 {
19702   /* Is the file number a valid index into the line header's file name
19703      table?  Remember that file numbers start with one, not zero.  */
19704   if (1 <= file && file <= lh->num_file_names)
19705     {
19706       struct file_entry *fe = &lh->file_names[file - 1];
19707
19708       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
19709         return xstrdup (fe->name);
19710       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
19711                      fe->name, NULL);
19712     }
19713   else
19714     {
19715       /* The compiler produced a bogus file number.  We can at least
19716          record the macro definitions made in the file, even if we
19717          won't be able to find the file by name.  */
19718       char fake_name[80];
19719
19720       xsnprintf (fake_name, sizeof (fake_name),
19721                  "<bad macro file number %d>", file);
19722
19723       complaint (&symfile_complaints,
19724                  _("bad file number in macro information (%d)"),
19725                  file);
19726
19727       return xstrdup (fake_name);
19728     }
19729 }
19730
19731 /* Return the full name of file number I in *LH's file name table.
19732    Use COMP_DIR as the name of the current directory of the
19733    compilation.  The result is allocated using xmalloc; the caller is
19734    responsible for freeing it.  */
19735 static char *
19736 file_full_name (int file, struct line_header *lh, const char *comp_dir)
19737 {
19738   /* Is the file number a valid index into the line header's file name
19739      table?  Remember that file numbers start with one, not zero.  */
19740   if (1 <= file && file <= lh->num_file_names)
19741     {
19742       char *relative = file_file_name (file, lh);
19743
19744       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
19745         return relative;
19746       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
19747     }
19748   else
19749     return file_file_name (file, lh);
19750 }
19751
19752
19753 static struct macro_source_file *
19754 macro_start_file (int file, int line,
19755                   struct macro_source_file *current_file,
19756                   const char *comp_dir,
19757                   struct line_header *lh, struct objfile *objfile)
19758 {
19759   /* File name relative to the compilation directory of this source file.  */
19760   char *file_name = file_file_name (file, lh);
19761
19762   if (! current_file)
19763     {
19764       /* Note: We don't create a macro table for this compilation unit
19765          at all until we actually get a filename.  */
19766       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
19767
19768       /* If we have no current file, then this must be the start_file
19769          directive for the compilation unit's main source file.  */
19770       current_file = macro_set_main (macro_table, file_name);
19771       macro_define_special (macro_table);
19772     }
19773   else
19774     current_file = macro_include (current_file, line, file_name);
19775
19776   xfree (file_name);
19777
19778   return current_file;
19779 }
19780
19781
19782 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19783    followed by a null byte.  */
19784 static char *
19785 copy_string (const char *buf, int len)
19786 {
19787   char *s = xmalloc (len + 1);
19788
19789   memcpy (s, buf, len);
19790   s[len] = '\0';
19791   return s;
19792 }
19793
19794
19795 static const char *
19796 consume_improper_spaces (const char *p, const char *body)
19797 {
19798   if (*p == ' ')
19799     {
19800       complaint (&symfile_complaints,
19801                  _("macro definition contains spaces "
19802                    "in formal argument list:\n`%s'"),
19803                  body);
19804
19805       while (*p == ' ')
19806         p++;
19807     }
19808
19809   return p;
19810 }
19811
19812
19813 static void
19814 parse_macro_definition (struct macro_source_file *file, int line,
19815                         const char *body)
19816 {
19817   const char *p;
19818
19819   /* The body string takes one of two forms.  For object-like macro
19820      definitions, it should be:
19821
19822         <macro name> " " <definition>
19823
19824      For function-like macro definitions, it should be:
19825
19826         <macro name> "() " <definition>
19827      or
19828         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19829
19830      Spaces may appear only where explicitly indicated, and in the
19831      <definition>.
19832
19833      The Dwarf 2 spec says that an object-like macro's name is always
19834      followed by a space, but versions of GCC around March 2002 omit
19835      the space when the macro's definition is the empty string.
19836
19837      The Dwarf 2 spec says that there should be no spaces between the
19838      formal arguments in a function-like macro's formal argument list,
19839      but versions of GCC around March 2002 include spaces after the
19840      commas.  */
19841
19842
19843   /* Find the extent of the macro name.  The macro name is terminated
19844      by either a space or null character (for an object-like macro) or
19845      an opening paren (for a function-like macro).  */
19846   for (p = body; *p; p++)
19847     if (*p == ' ' || *p == '(')
19848       break;
19849
19850   if (*p == ' ' || *p == '\0')
19851     {
19852       /* It's an object-like macro.  */
19853       int name_len = p - body;
19854       char *name = copy_string (body, name_len);
19855       const char *replacement;
19856
19857       if (*p == ' ')
19858         replacement = body + name_len + 1;
19859       else
19860         {
19861           dwarf2_macro_malformed_definition_complaint (body);
19862           replacement = body + name_len;
19863         }
19864
19865       macro_define_object (file, line, name, replacement);
19866
19867       xfree (name);
19868     }
19869   else if (*p == '(')
19870     {
19871       /* It's a function-like macro.  */
19872       char *name = copy_string (body, p - body);
19873       int argc = 0;
19874       int argv_size = 1;
19875       char **argv = xmalloc (argv_size * sizeof (*argv));
19876
19877       p++;
19878
19879       p = consume_improper_spaces (p, body);
19880
19881       /* Parse the formal argument list.  */
19882       while (*p && *p != ')')
19883         {
19884           /* Find the extent of the current argument name.  */
19885           const char *arg_start = p;
19886
19887           while (*p && *p != ',' && *p != ')' && *p != ' ')
19888             p++;
19889
19890           if (! *p || p == arg_start)
19891             dwarf2_macro_malformed_definition_complaint (body);
19892           else
19893             {
19894               /* Make sure argv has room for the new argument.  */
19895               if (argc >= argv_size)
19896                 {
19897                   argv_size *= 2;
19898                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19899                 }
19900
19901               argv[argc++] = copy_string (arg_start, p - arg_start);
19902             }
19903
19904           p = consume_improper_spaces (p, body);
19905
19906           /* Consume the comma, if present.  */
19907           if (*p == ',')
19908             {
19909               p++;
19910
19911               p = consume_improper_spaces (p, body);
19912             }
19913         }
19914
19915       if (*p == ')')
19916         {
19917           p++;
19918
19919           if (*p == ' ')
19920             /* Perfectly formed definition, no complaints.  */
19921             macro_define_function (file, line, name,
19922                                    argc, (const char **) argv,
19923                                    p + 1);
19924           else if (*p == '\0')
19925             {
19926               /* Complain, but do define it.  */
19927               dwarf2_macro_malformed_definition_complaint (body);
19928               macro_define_function (file, line, name,
19929                                      argc, (const char **) argv,
19930                                      p);
19931             }
19932           else
19933             /* Just complain.  */
19934             dwarf2_macro_malformed_definition_complaint (body);
19935         }
19936       else
19937         /* Just complain.  */
19938         dwarf2_macro_malformed_definition_complaint (body);
19939
19940       xfree (name);
19941       {
19942         int i;
19943
19944         for (i = 0; i < argc; i++)
19945           xfree (argv[i]);
19946       }
19947       xfree (argv);
19948     }
19949   else
19950     dwarf2_macro_malformed_definition_complaint (body);
19951 }
19952
19953 /* Skip some bytes from BYTES according to the form given in FORM.
19954    Returns the new pointer.  */
19955
19956 static const gdb_byte *
19957 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19958                  enum dwarf_form form,
19959                  unsigned int offset_size,
19960                  struct dwarf2_section_info *section)
19961 {
19962   unsigned int bytes_read;
19963
19964   switch (form)
19965     {
19966     case DW_FORM_data1:
19967     case DW_FORM_flag:
19968       ++bytes;
19969       break;
19970
19971     case DW_FORM_data2:
19972       bytes += 2;
19973       break;
19974
19975     case DW_FORM_data4:
19976       bytes += 4;
19977       break;
19978
19979     case DW_FORM_data8:
19980       bytes += 8;
19981       break;
19982
19983     case DW_FORM_string:
19984       read_direct_string (abfd, bytes, &bytes_read);
19985       bytes += bytes_read;
19986       break;
19987
19988     case DW_FORM_sec_offset:
19989     case DW_FORM_strp:
19990     case DW_FORM_GNU_strp_alt:
19991       bytes += offset_size;
19992       break;
19993
19994     case DW_FORM_block:
19995       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19996       bytes += bytes_read;
19997       break;
19998
19999     case DW_FORM_block1:
20000       bytes += 1 + read_1_byte (abfd, bytes);
20001       break;
20002     case DW_FORM_block2:
20003       bytes += 2 + read_2_bytes (abfd, bytes);
20004       break;
20005     case DW_FORM_block4:
20006       bytes += 4 + read_4_bytes (abfd, bytes);
20007       break;
20008
20009     case DW_FORM_sdata:
20010     case DW_FORM_udata:
20011     case DW_FORM_GNU_addr_index:
20012     case DW_FORM_GNU_str_index:
20013       bytes = gdb_skip_leb128 (bytes, buffer_end);
20014       if (bytes == NULL)
20015         {
20016           dwarf2_section_buffer_overflow_complaint (section);
20017           return NULL;
20018         }
20019       break;
20020
20021     default:
20022       {
20023       complain:
20024         complaint (&symfile_complaints,
20025                    _("invalid form 0x%x in `%s'"),
20026                    form, get_section_name (section));
20027         return NULL;
20028       }
20029     }
20030
20031   return bytes;
20032 }
20033
20034 /* A helper for dwarf_decode_macros that handles skipping an unknown
20035    opcode.  Returns an updated pointer to the macro data buffer; or,
20036    on error, issues a complaint and returns NULL.  */
20037
20038 static const gdb_byte *
20039 skip_unknown_opcode (unsigned int opcode,
20040                      const gdb_byte **opcode_definitions,
20041                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20042                      bfd *abfd,
20043                      unsigned int offset_size,
20044                      struct dwarf2_section_info *section)
20045 {
20046   unsigned int bytes_read, i;
20047   unsigned long arg;
20048   const gdb_byte *defn;
20049
20050   if (opcode_definitions[opcode] == NULL)
20051     {
20052       complaint (&symfile_complaints,
20053                  _("unrecognized DW_MACFINO opcode 0x%x"),
20054                  opcode);
20055       return NULL;
20056     }
20057
20058   defn = opcode_definitions[opcode];
20059   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
20060   defn += bytes_read;
20061
20062   for (i = 0; i < arg; ++i)
20063     {
20064       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
20065                                  section);
20066       if (mac_ptr == NULL)
20067         {
20068           /* skip_form_bytes already issued the complaint.  */
20069           return NULL;
20070         }
20071     }
20072
20073   return mac_ptr;
20074 }
20075
20076 /* A helper function which parses the header of a macro section.
20077    If the macro section is the extended (for now called "GNU") type,
20078    then this updates *OFFSET_SIZE.  Returns a pointer to just after
20079    the header, or issues a complaint and returns NULL on error.  */
20080
20081 static const gdb_byte *
20082 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
20083                           bfd *abfd,
20084                           const gdb_byte *mac_ptr,
20085                           unsigned int *offset_size,
20086                           int section_is_gnu)
20087 {
20088   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
20089
20090   if (section_is_gnu)
20091     {
20092       unsigned int version, flags;
20093
20094       version = read_2_bytes (abfd, mac_ptr);
20095       if (version != 4)
20096         {
20097           complaint (&symfile_complaints,
20098                      _("unrecognized version `%d' in .debug_macro section"),
20099                      version);
20100           return NULL;
20101         }
20102       mac_ptr += 2;
20103
20104       flags = read_1_byte (abfd, mac_ptr);
20105       ++mac_ptr;
20106       *offset_size = (flags & 1) ? 8 : 4;
20107
20108       if ((flags & 2) != 0)
20109         /* We don't need the line table offset.  */
20110         mac_ptr += *offset_size;
20111
20112       /* Vendor opcode descriptions.  */
20113       if ((flags & 4) != 0)
20114         {
20115           unsigned int i, count;
20116
20117           count = read_1_byte (abfd, mac_ptr);
20118           ++mac_ptr;
20119           for (i = 0; i < count; ++i)
20120             {
20121               unsigned int opcode, bytes_read;
20122               unsigned long arg;
20123
20124               opcode = read_1_byte (abfd, mac_ptr);
20125               ++mac_ptr;
20126               opcode_definitions[opcode] = mac_ptr;
20127               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20128               mac_ptr += bytes_read;
20129               mac_ptr += arg;
20130             }
20131         }
20132     }
20133
20134   return mac_ptr;
20135 }
20136
20137 /* A helper for dwarf_decode_macros that handles the GNU extensions,
20138    including DW_MACRO_GNU_transparent_include.  */
20139
20140 static void
20141 dwarf_decode_macro_bytes (bfd *abfd,
20142                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20143                           struct macro_source_file *current_file,
20144                           struct line_header *lh, const char *comp_dir,
20145                           struct dwarf2_section_info *section,
20146                           int section_is_gnu, int section_is_dwz,
20147                           unsigned int offset_size,
20148                           struct objfile *objfile,
20149                           htab_t include_hash)
20150 {
20151   enum dwarf_macro_record_type macinfo_type;
20152   int at_commandline;
20153   const gdb_byte *opcode_definitions[256];
20154
20155   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20156                                       &offset_size, section_is_gnu);
20157   if (mac_ptr == NULL)
20158     {
20159       /* We already issued a complaint.  */
20160       return;
20161     }
20162
20163   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
20164      GDB is still reading the definitions from command line.  First
20165      DW_MACINFO_start_file will need to be ignored as it was already executed
20166      to create CURRENT_FILE for the main source holding also the command line
20167      definitions.  On first met DW_MACINFO_start_file this flag is reset to
20168      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
20169
20170   at_commandline = 1;
20171
20172   do
20173     {
20174       /* Do we at least have room for a macinfo type byte?  */
20175       if (mac_ptr >= mac_end)
20176         {
20177           dwarf2_section_buffer_overflow_complaint (section);
20178           break;
20179         }
20180
20181       macinfo_type = read_1_byte (abfd, mac_ptr);
20182       mac_ptr++;
20183
20184       /* Note that we rely on the fact that the corresponding GNU and
20185          DWARF constants are the same.  */
20186       switch (macinfo_type)
20187         {
20188           /* A zero macinfo type indicates the end of the macro
20189              information.  */
20190         case 0:
20191           break;
20192
20193         case DW_MACRO_GNU_define:
20194         case DW_MACRO_GNU_undef:
20195         case DW_MACRO_GNU_define_indirect:
20196         case DW_MACRO_GNU_undef_indirect:
20197         case DW_MACRO_GNU_define_indirect_alt:
20198         case DW_MACRO_GNU_undef_indirect_alt:
20199           {
20200             unsigned int bytes_read;
20201             int line;
20202             const char *body;
20203             int is_define;
20204
20205             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20206             mac_ptr += bytes_read;
20207
20208             if (macinfo_type == DW_MACRO_GNU_define
20209                 || macinfo_type == DW_MACRO_GNU_undef)
20210               {
20211                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
20212                 mac_ptr += bytes_read;
20213               }
20214             else
20215               {
20216                 LONGEST str_offset;
20217
20218                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
20219                 mac_ptr += offset_size;
20220
20221                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
20222                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
20223                     || section_is_dwz)
20224                   {
20225                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
20226
20227                     body = read_indirect_string_from_dwz (dwz, str_offset);
20228                   }
20229                 else
20230                   body = read_indirect_string_at_offset (abfd, str_offset);
20231               }
20232
20233             is_define = (macinfo_type == DW_MACRO_GNU_define
20234                          || macinfo_type == DW_MACRO_GNU_define_indirect
20235                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
20236             if (! current_file)
20237               {
20238                 /* DWARF violation as no main source is present.  */
20239                 complaint (&symfile_complaints,
20240                            _("debug info with no main source gives macro %s "
20241                              "on line %d: %s"),
20242                            is_define ? _("definition") : _("undefinition"),
20243                            line, body);
20244                 break;
20245               }
20246             if ((line == 0 && !at_commandline)
20247                 || (line != 0 && at_commandline))
20248               complaint (&symfile_complaints,
20249                          _("debug info gives %s macro %s with %s line %d: %s"),
20250                          at_commandline ? _("command-line") : _("in-file"),
20251                          is_define ? _("definition") : _("undefinition"),
20252                          line == 0 ? _("zero") : _("non-zero"), line, body);
20253
20254             if (is_define)
20255               parse_macro_definition (current_file, line, body);
20256             else
20257               {
20258                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
20259                             || macinfo_type == DW_MACRO_GNU_undef_indirect
20260                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
20261                 macro_undef (current_file, line, body);
20262               }
20263           }
20264           break;
20265
20266         case DW_MACRO_GNU_start_file:
20267           {
20268             unsigned int bytes_read;
20269             int line, file;
20270
20271             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20272             mac_ptr += bytes_read;
20273             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20274             mac_ptr += bytes_read;
20275
20276             if ((line == 0 && !at_commandline)
20277                 || (line != 0 && at_commandline))
20278               complaint (&symfile_complaints,
20279                          _("debug info gives source %d included "
20280                            "from %s at %s line %d"),
20281                          file, at_commandline ? _("command-line") : _("file"),
20282                          line == 0 ? _("zero") : _("non-zero"), line);
20283
20284             if (at_commandline)
20285               {
20286                 /* This DW_MACRO_GNU_start_file was executed in the
20287                    pass one.  */
20288                 at_commandline = 0;
20289               }
20290             else
20291               current_file = macro_start_file (file, line,
20292                                                current_file, comp_dir,
20293                                                lh, objfile);
20294           }
20295           break;
20296
20297         case DW_MACRO_GNU_end_file:
20298           if (! current_file)
20299             complaint (&symfile_complaints,
20300                        _("macro debug info has an unmatched "
20301                          "`close_file' directive"));
20302           else
20303             {
20304               current_file = current_file->included_by;
20305               if (! current_file)
20306                 {
20307                   enum dwarf_macro_record_type next_type;
20308
20309                   /* GCC circa March 2002 doesn't produce the zero
20310                      type byte marking the end of the compilation
20311                      unit.  Complain if it's not there, but exit no
20312                      matter what.  */
20313
20314                   /* Do we at least have room for a macinfo type byte?  */
20315                   if (mac_ptr >= mac_end)
20316                     {
20317                       dwarf2_section_buffer_overflow_complaint (section);
20318                       return;
20319                     }
20320
20321                   /* We don't increment mac_ptr here, so this is just
20322                      a look-ahead.  */
20323                   next_type = read_1_byte (abfd, mac_ptr);
20324                   if (next_type != 0)
20325                     complaint (&symfile_complaints,
20326                                _("no terminating 0-type entry for "
20327                                  "macros in `.debug_macinfo' section"));
20328
20329                   return;
20330                 }
20331             }
20332           break;
20333
20334         case DW_MACRO_GNU_transparent_include:
20335         case DW_MACRO_GNU_transparent_include_alt:
20336           {
20337             LONGEST offset;
20338             void **slot;
20339             bfd *include_bfd = abfd;
20340             struct dwarf2_section_info *include_section = section;
20341             struct dwarf2_section_info alt_section;
20342             const gdb_byte *include_mac_end = mac_end;
20343             int is_dwz = section_is_dwz;
20344             const gdb_byte *new_mac_ptr;
20345
20346             offset = read_offset_1 (abfd, mac_ptr, offset_size);
20347             mac_ptr += offset_size;
20348
20349             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
20350               {
20351                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
20352
20353                 dwarf2_read_section (dwarf2_per_objfile->objfile,
20354                                      &dwz->macro);
20355
20356                 include_section = &dwz->macro;
20357                 include_bfd = get_section_bfd_owner (include_section);
20358                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
20359                 is_dwz = 1;
20360               }
20361
20362             new_mac_ptr = include_section->buffer + offset;
20363             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
20364
20365             if (*slot != NULL)
20366               {
20367                 /* This has actually happened; see
20368                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
20369                 complaint (&symfile_complaints,
20370                            _("recursive DW_MACRO_GNU_transparent_include in "
20371                              ".debug_macro section"));
20372               }
20373             else
20374               {
20375                 *slot = (void *) new_mac_ptr;
20376
20377                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
20378                                           include_mac_end, current_file,
20379                                           lh, comp_dir,
20380                                           section, section_is_gnu, is_dwz,
20381                                           offset_size, objfile, include_hash);
20382
20383                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
20384               }
20385           }
20386           break;
20387
20388         case DW_MACINFO_vendor_ext:
20389           if (!section_is_gnu)
20390             {
20391               unsigned int bytes_read;
20392               int constant;
20393
20394               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20395               mac_ptr += bytes_read;
20396               read_direct_string (abfd, mac_ptr, &bytes_read);
20397               mac_ptr += bytes_read;
20398
20399               /* We don't recognize any vendor extensions.  */
20400               break;
20401             }
20402           /* FALLTHROUGH */
20403
20404         default:
20405           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20406                                          mac_ptr, mac_end, abfd, offset_size,
20407                                          section);
20408           if (mac_ptr == NULL)
20409             return;
20410           break;
20411         }
20412     } while (macinfo_type != 0);
20413 }
20414
20415 static void
20416 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
20417                      const char *comp_dir, int section_is_gnu)
20418 {
20419   struct objfile *objfile = dwarf2_per_objfile->objfile;
20420   struct line_header *lh = cu->line_header;
20421   bfd *abfd;
20422   const gdb_byte *mac_ptr, *mac_end;
20423   struct macro_source_file *current_file = 0;
20424   enum dwarf_macro_record_type macinfo_type;
20425   unsigned int offset_size = cu->header.offset_size;
20426   const gdb_byte *opcode_definitions[256];
20427   struct cleanup *cleanup;
20428   htab_t include_hash;
20429   void **slot;
20430   struct dwarf2_section_info *section;
20431   const char *section_name;
20432
20433   if (cu->dwo_unit != NULL)
20434     {
20435       if (section_is_gnu)
20436         {
20437           section = &cu->dwo_unit->dwo_file->sections.macro;
20438           section_name = ".debug_macro.dwo";
20439         }
20440       else
20441         {
20442           section = &cu->dwo_unit->dwo_file->sections.macinfo;
20443           section_name = ".debug_macinfo.dwo";
20444         }
20445     }
20446   else
20447     {
20448       if (section_is_gnu)
20449         {
20450           section = &dwarf2_per_objfile->macro;
20451           section_name = ".debug_macro";
20452         }
20453       else
20454         {
20455           section = &dwarf2_per_objfile->macinfo;
20456           section_name = ".debug_macinfo";
20457         }
20458     }
20459
20460   dwarf2_read_section (objfile, section);
20461   if (section->buffer == NULL)
20462     {
20463       complaint (&symfile_complaints, _("missing %s section"), section_name);
20464       return;
20465     }
20466   abfd = get_section_bfd_owner (section);
20467
20468   /* First pass: Find the name of the base filename.
20469      This filename is needed in order to process all macros whose definition
20470      (or undefinition) comes from the command line.  These macros are defined
20471      before the first DW_MACINFO_start_file entry, and yet still need to be
20472      associated to the base file.
20473
20474      To determine the base file name, we scan the macro definitions until we
20475      reach the first DW_MACINFO_start_file entry.  We then initialize
20476      CURRENT_FILE accordingly so that any macro definition found before the
20477      first DW_MACINFO_start_file can still be associated to the base file.  */
20478
20479   mac_ptr = section->buffer + offset;
20480   mac_end = section->buffer + section->size;
20481
20482   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20483                                       &offset_size, section_is_gnu);
20484   if (mac_ptr == NULL)
20485     {
20486       /* We already issued a complaint.  */
20487       return;
20488     }
20489
20490   do
20491     {
20492       /* Do we at least have room for a macinfo type byte?  */
20493       if (mac_ptr >= mac_end)
20494         {
20495           /* Complaint is printed during the second pass as GDB will probably
20496              stop the first pass earlier upon finding
20497              DW_MACINFO_start_file.  */
20498           break;
20499         }
20500
20501       macinfo_type = read_1_byte (abfd, mac_ptr);
20502       mac_ptr++;
20503
20504       /* Note that we rely on the fact that the corresponding GNU and
20505          DWARF constants are the same.  */
20506       switch (macinfo_type)
20507         {
20508           /* A zero macinfo type indicates the end of the macro
20509              information.  */
20510         case 0:
20511           break;
20512
20513         case DW_MACRO_GNU_define:
20514         case DW_MACRO_GNU_undef:
20515           /* Only skip the data by MAC_PTR.  */
20516           {
20517             unsigned int bytes_read;
20518
20519             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20520             mac_ptr += bytes_read;
20521             read_direct_string (abfd, mac_ptr, &bytes_read);
20522             mac_ptr += bytes_read;
20523           }
20524           break;
20525
20526         case DW_MACRO_GNU_start_file:
20527           {
20528             unsigned int bytes_read;
20529             int line, file;
20530
20531             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20532             mac_ptr += bytes_read;
20533             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20534             mac_ptr += bytes_read;
20535
20536             current_file = macro_start_file (file, line, current_file,
20537                                              comp_dir, lh, objfile);
20538           }
20539           break;
20540
20541         case DW_MACRO_GNU_end_file:
20542           /* No data to skip by MAC_PTR.  */
20543           break;
20544
20545         case DW_MACRO_GNU_define_indirect:
20546         case DW_MACRO_GNU_undef_indirect:
20547         case DW_MACRO_GNU_define_indirect_alt:
20548         case DW_MACRO_GNU_undef_indirect_alt:
20549           {
20550             unsigned int bytes_read;
20551
20552             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20553             mac_ptr += bytes_read;
20554             mac_ptr += offset_size;
20555           }
20556           break;
20557
20558         case DW_MACRO_GNU_transparent_include:
20559         case DW_MACRO_GNU_transparent_include_alt:
20560           /* Note that, according to the spec, a transparent include
20561              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
20562              skip this opcode.  */
20563           mac_ptr += offset_size;
20564           break;
20565
20566         case DW_MACINFO_vendor_ext:
20567           /* Only skip the data by MAC_PTR.  */
20568           if (!section_is_gnu)
20569             {
20570               unsigned int bytes_read;
20571
20572               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20573               mac_ptr += bytes_read;
20574               read_direct_string (abfd, mac_ptr, &bytes_read);
20575               mac_ptr += bytes_read;
20576             }
20577           /* FALLTHROUGH */
20578
20579         default:
20580           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20581                                          mac_ptr, mac_end, abfd, offset_size,
20582                                          section);
20583           if (mac_ptr == NULL)
20584             return;
20585           break;
20586         }
20587     } while (macinfo_type != 0 && current_file == NULL);
20588
20589   /* Second pass: Process all entries.
20590
20591      Use the AT_COMMAND_LINE flag to determine whether we are still processing
20592      command-line macro definitions/undefinitions.  This flag is unset when we
20593      reach the first DW_MACINFO_start_file entry.  */
20594
20595   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
20596                                     NULL, xcalloc, xfree);
20597   cleanup = make_cleanup_htab_delete (include_hash);
20598   mac_ptr = section->buffer + offset;
20599   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
20600   *slot = (void *) mac_ptr;
20601   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
20602                             current_file, lh, comp_dir, section,
20603                             section_is_gnu, 0,
20604                             offset_size, objfile, include_hash);
20605   do_cleanups (cleanup);
20606 }
20607
20608 /* Check if the attribute's form is a DW_FORM_block*
20609    if so return true else false.  */
20610
20611 static int
20612 attr_form_is_block (const struct attribute *attr)
20613 {
20614   return (attr == NULL ? 0 :
20615       attr->form == DW_FORM_block1
20616       || attr->form == DW_FORM_block2
20617       || attr->form == DW_FORM_block4
20618       || attr->form == DW_FORM_block
20619       || attr->form == DW_FORM_exprloc);
20620 }
20621
20622 /* Return non-zero if ATTR's value is a section offset --- classes
20623    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
20624    You may use DW_UNSND (attr) to retrieve such offsets.
20625
20626    Section 7.5.4, "Attribute Encodings", explains that no attribute
20627    may have a value that belongs to more than one of these classes; it
20628    would be ambiguous if we did, because we use the same forms for all
20629    of them.  */
20630
20631 static int
20632 attr_form_is_section_offset (const struct attribute *attr)
20633 {
20634   return (attr->form == DW_FORM_data4
20635           || attr->form == DW_FORM_data8
20636           || attr->form == DW_FORM_sec_offset);
20637 }
20638
20639 /* Return non-zero if ATTR's value falls in the 'constant' class, or
20640    zero otherwise.  When this function returns true, you can apply
20641    dwarf2_get_attr_constant_value to it.
20642
20643    However, note that for some attributes you must check
20644    attr_form_is_section_offset before using this test.  DW_FORM_data4
20645    and DW_FORM_data8 are members of both the constant class, and of
20646    the classes that contain offsets into other debug sections
20647    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
20648    that, if an attribute's can be either a constant or one of the
20649    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
20650    taken as section offsets, not constants.  */
20651
20652 static int
20653 attr_form_is_constant (const struct attribute *attr)
20654 {
20655   switch (attr->form)
20656     {
20657     case DW_FORM_sdata:
20658     case DW_FORM_udata:
20659     case DW_FORM_data1:
20660     case DW_FORM_data2:
20661     case DW_FORM_data4:
20662     case DW_FORM_data8:
20663       return 1;
20664     default:
20665       return 0;
20666     }
20667 }
20668
20669
20670 /* DW_ADDR is always stored already as sect_offset; despite for the forms
20671    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
20672
20673 static int
20674 attr_form_is_ref (const struct attribute *attr)
20675 {
20676   switch (attr->form)
20677     {
20678     case DW_FORM_ref_addr:
20679     case DW_FORM_ref1:
20680     case DW_FORM_ref2:
20681     case DW_FORM_ref4:
20682     case DW_FORM_ref8:
20683     case DW_FORM_ref_udata:
20684     case DW_FORM_GNU_ref_alt:
20685       return 1;
20686     default:
20687       return 0;
20688     }
20689 }
20690
20691 /* Return the .debug_loc section to use for CU.
20692    For DWO files use .debug_loc.dwo.  */
20693
20694 static struct dwarf2_section_info *
20695 cu_debug_loc_section (struct dwarf2_cu *cu)
20696 {
20697   if (cu->dwo_unit)
20698     return &cu->dwo_unit->dwo_file->sections.loc;
20699   return &dwarf2_per_objfile->loc;
20700 }
20701
20702 /* A helper function that fills in a dwarf2_loclist_baton.  */
20703
20704 static void
20705 fill_in_loclist_baton (struct dwarf2_cu *cu,
20706                        struct dwarf2_loclist_baton *baton,
20707                        const struct attribute *attr)
20708 {
20709   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20710
20711   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20712
20713   baton->per_cu = cu->per_cu;
20714   gdb_assert (baton->per_cu);
20715   /* We don't know how long the location list is, but make sure we
20716      don't run off the edge of the section.  */
20717   baton->size = section->size - DW_UNSND (attr);
20718   baton->data = section->buffer + DW_UNSND (attr);
20719   baton->base_address = cu->base_address;
20720   baton->from_dwo = cu->dwo_unit != NULL;
20721 }
20722
20723 static void
20724 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
20725                              struct dwarf2_cu *cu, int is_block)
20726 {
20727   struct objfile *objfile = dwarf2_per_objfile->objfile;
20728   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20729
20730   if (attr_form_is_section_offset (attr)
20731       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
20732          the section.  If so, fall through to the complaint in the
20733          other branch.  */
20734       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
20735     {
20736       struct dwarf2_loclist_baton *baton;
20737
20738       baton = obstack_alloc (&objfile->objfile_obstack,
20739                              sizeof (struct dwarf2_loclist_baton));
20740
20741       fill_in_loclist_baton (cu, baton, attr);
20742
20743       if (cu->base_known == 0)
20744         complaint (&symfile_complaints,
20745                    _("Location list used without "
20746                      "specifying the CU base address."));
20747
20748       SYMBOL_ACLASS_INDEX (sym) = (is_block
20749                                    ? dwarf2_loclist_block_index
20750                                    : dwarf2_loclist_index);
20751       SYMBOL_LOCATION_BATON (sym) = baton;
20752     }
20753   else
20754     {
20755       struct dwarf2_locexpr_baton *baton;
20756
20757       baton = obstack_alloc (&objfile->objfile_obstack,
20758                              sizeof (struct dwarf2_locexpr_baton));
20759       baton->per_cu = cu->per_cu;
20760       gdb_assert (baton->per_cu);
20761
20762       if (attr_form_is_block (attr))
20763         {
20764           /* Note that we're just copying the block's data pointer
20765              here, not the actual data.  We're still pointing into the
20766              info_buffer for SYM's objfile; right now we never release
20767              that buffer, but when we do clean up properly this may
20768              need to change.  */
20769           baton->size = DW_BLOCK (attr)->size;
20770           baton->data = DW_BLOCK (attr)->data;
20771         }
20772       else
20773         {
20774           dwarf2_invalid_attrib_class_complaint ("location description",
20775                                                  SYMBOL_NATURAL_NAME (sym));
20776           baton->size = 0;
20777         }
20778
20779       SYMBOL_ACLASS_INDEX (sym) = (is_block
20780                                    ? dwarf2_locexpr_block_index
20781                                    : dwarf2_locexpr_index);
20782       SYMBOL_LOCATION_BATON (sym) = baton;
20783     }
20784 }
20785
20786 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20787    came from a separate debuginfo file, then the master objfile is
20788    returned.  */
20789
20790 struct objfile *
20791 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20792 {
20793   struct objfile *objfile = per_cu->objfile;
20794
20795   /* Return the master objfile, so that we can report and look up the
20796      correct file containing this variable.  */
20797   if (objfile->separate_debug_objfile_backlink)
20798     objfile = objfile->separate_debug_objfile_backlink;
20799
20800   return objfile;
20801 }
20802
20803 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20804    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20805    CU_HEADERP first.  */
20806
20807 static const struct comp_unit_head *
20808 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20809                        struct dwarf2_per_cu_data *per_cu)
20810 {
20811   const gdb_byte *info_ptr;
20812
20813   if (per_cu->cu)
20814     return &per_cu->cu->header;
20815
20816   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20817
20818   memset (cu_headerp, 0, sizeof (*cu_headerp));
20819   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20820
20821   return cu_headerp;
20822 }
20823
20824 /* Return the address size given in the compilation unit header for CU.  */
20825
20826 int
20827 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20828 {
20829   struct comp_unit_head cu_header_local;
20830   const struct comp_unit_head *cu_headerp;
20831
20832   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20833
20834   return cu_headerp->addr_size;
20835 }
20836
20837 /* Return the offset size given in the compilation unit header for CU.  */
20838
20839 int
20840 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20841 {
20842   struct comp_unit_head cu_header_local;
20843   const struct comp_unit_head *cu_headerp;
20844
20845   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20846
20847   return cu_headerp->offset_size;
20848 }
20849
20850 /* See its dwarf2loc.h declaration.  */
20851
20852 int
20853 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20854 {
20855   struct comp_unit_head cu_header_local;
20856   const struct comp_unit_head *cu_headerp;
20857
20858   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20859
20860   if (cu_headerp->version == 2)
20861     return cu_headerp->addr_size;
20862   else
20863     return cu_headerp->offset_size;
20864 }
20865
20866 /* Return the text offset of the CU.  The returned offset comes from
20867    this CU's objfile.  If this objfile came from a separate debuginfo
20868    file, then the offset may be different from the corresponding
20869    offset in the parent objfile.  */
20870
20871 CORE_ADDR
20872 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20873 {
20874   struct objfile *objfile = per_cu->objfile;
20875
20876   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20877 }
20878
20879 /* Locate the .debug_info compilation unit from CU's objfile which contains
20880    the DIE at OFFSET.  Raises an error on failure.  */
20881
20882 static struct dwarf2_per_cu_data *
20883 dwarf2_find_containing_comp_unit (sect_offset offset,
20884                                   unsigned int offset_in_dwz,
20885                                   struct objfile *objfile)
20886 {
20887   struct dwarf2_per_cu_data *this_cu;
20888   int low, high;
20889   const sect_offset *cu_off;
20890
20891   low = 0;
20892   high = dwarf2_per_objfile->n_comp_units - 1;
20893   while (high > low)
20894     {
20895       struct dwarf2_per_cu_data *mid_cu;
20896       int mid = low + (high - low) / 2;
20897
20898       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20899       cu_off = &mid_cu->offset;
20900       if (mid_cu->is_dwz > offset_in_dwz
20901           || (mid_cu->is_dwz == offset_in_dwz
20902               && cu_off->sect_off >= offset.sect_off))
20903         high = mid;
20904       else
20905         low = mid + 1;
20906     }
20907   gdb_assert (low == high);
20908   this_cu = dwarf2_per_objfile->all_comp_units[low];
20909   cu_off = &this_cu->offset;
20910   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20911     {
20912       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20913         error (_("Dwarf Error: could not find partial DIE containing "
20914                "offset 0x%lx [in module %s]"),
20915                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20916
20917       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20918                   <= offset.sect_off);
20919       return dwarf2_per_objfile->all_comp_units[low-1];
20920     }
20921   else
20922     {
20923       this_cu = dwarf2_per_objfile->all_comp_units[low];
20924       if (low == dwarf2_per_objfile->n_comp_units - 1
20925           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20926         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20927       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20928       return this_cu;
20929     }
20930 }
20931
20932 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20933
20934 static void
20935 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20936 {
20937   memset (cu, 0, sizeof (*cu));
20938   per_cu->cu = cu;
20939   cu->per_cu = per_cu;
20940   cu->objfile = per_cu->objfile;
20941   obstack_init (&cu->comp_unit_obstack);
20942 }
20943
20944 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20945
20946 static void
20947 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20948                        enum language pretend_language)
20949 {
20950   struct attribute *attr;
20951
20952   /* Set the language we're debugging.  */
20953   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20954   if (attr)
20955     set_cu_language (DW_UNSND (attr), cu);
20956   else
20957     {
20958       cu->language = pretend_language;
20959       cu->language_defn = language_def (cu->language);
20960     }
20961
20962   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20963   if (attr)
20964     cu->producer = DW_STRING (attr);
20965 }
20966
20967 /* Release one cached compilation unit, CU.  We unlink it from the tree
20968    of compilation units, but we don't remove it from the read_in_chain;
20969    the caller is responsible for that.
20970    NOTE: DATA is a void * because this function is also used as a
20971    cleanup routine.  */
20972
20973 static void
20974 free_heap_comp_unit (void *data)
20975 {
20976   struct dwarf2_cu *cu = data;
20977
20978   gdb_assert (cu->per_cu != NULL);
20979   cu->per_cu->cu = NULL;
20980   cu->per_cu = NULL;
20981
20982   obstack_free (&cu->comp_unit_obstack, NULL);
20983
20984   xfree (cu);
20985 }
20986
20987 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20988    when we're finished with it.  We can't free the pointer itself, but be
20989    sure to unlink it from the cache.  Also release any associated storage.  */
20990
20991 static void
20992 free_stack_comp_unit (void *data)
20993 {
20994   struct dwarf2_cu *cu = data;
20995
20996   gdb_assert (cu->per_cu != NULL);
20997   cu->per_cu->cu = NULL;
20998   cu->per_cu = NULL;
20999
21000   obstack_free (&cu->comp_unit_obstack, NULL);
21001   cu->partial_dies = NULL;
21002 }
21003
21004 /* Free all cached compilation units.  */
21005
21006 static void
21007 free_cached_comp_units (void *data)
21008 {
21009   struct dwarf2_per_cu_data *per_cu, **last_chain;
21010
21011   per_cu = dwarf2_per_objfile->read_in_chain;
21012   last_chain = &dwarf2_per_objfile->read_in_chain;
21013   while (per_cu != NULL)
21014     {
21015       struct dwarf2_per_cu_data *next_cu;
21016
21017       next_cu = per_cu->cu->read_in_chain;
21018
21019       free_heap_comp_unit (per_cu->cu);
21020       *last_chain = next_cu;
21021
21022       per_cu = next_cu;
21023     }
21024 }
21025
21026 /* Increase the age counter on each cached compilation unit, and free
21027    any that are too old.  */
21028
21029 static void
21030 age_cached_comp_units (void)
21031 {
21032   struct dwarf2_per_cu_data *per_cu, **last_chain;
21033
21034   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
21035   per_cu = dwarf2_per_objfile->read_in_chain;
21036   while (per_cu != NULL)
21037     {
21038       per_cu->cu->last_used ++;
21039       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
21040         dwarf2_mark (per_cu->cu);
21041       per_cu = per_cu->cu->read_in_chain;
21042     }
21043
21044   per_cu = dwarf2_per_objfile->read_in_chain;
21045   last_chain = &dwarf2_per_objfile->read_in_chain;
21046   while (per_cu != NULL)
21047     {
21048       struct dwarf2_per_cu_data *next_cu;
21049
21050       next_cu = per_cu->cu->read_in_chain;
21051
21052       if (!per_cu->cu->mark)
21053         {
21054           free_heap_comp_unit (per_cu->cu);
21055           *last_chain = next_cu;
21056         }
21057       else
21058         last_chain = &per_cu->cu->read_in_chain;
21059
21060       per_cu = next_cu;
21061     }
21062 }
21063
21064 /* Remove a single compilation unit from the cache.  */
21065
21066 static void
21067 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
21068 {
21069   struct dwarf2_per_cu_data *per_cu, **last_chain;
21070
21071   per_cu = dwarf2_per_objfile->read_in_chain;
21072   last_chain = &dwarf2_per_objfile->read_in_chain;
21073   while (per_cu != NULL)
21074     {
21075       struct dwarf2_per_cu_data *next_cu;
21076
21077       next_cu = per_cu->cu->read_in_chain;
21078
21079       if (per_cu == target_per_cu)
21080         {
21081           free_heap_comp_unit (per_cu->cu);
21082           per_cu->cu = NULL;
21083           *last_chain = next_cu;
21084           break;
21085         }
21086       else
21087         last_chain = &per_cu->cu->read_in_chain;
21088
21089       per_cu = next_cu;
21090     }
21091 }
21092
21093 /* Release all extra memory associated with OBJFILE.  */
21094
21095 void
21096 dwarf2_free_objfile (struct objfile *objfile)
21097 {
21098   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21099
21100   if (dwarf2_per_objfile == NULL)
21101     return;
21102
21103   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
21104   free_cached_comp_units (NULL);
21105
21106   if (dwarf2_per_objfile->quick_file_names_table)
21107     htab_delete (dwarf2_per_objfile->quick_file_names_table);
21108
21109   /* Everything else should be on the objfile obstack.  */
21110 }
21111
21112 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
21113    We store these in a hash table separate from the DIEs, and preserve them
21114    when the DIEs are flushed out of cache.
21115
21116    The CU "per_cu" pointer is needed because offset alone is not enough to
21117    uniquely identify the type.  A file may have multiple .debug_types sections,
21118    or the type may come from a DWO file.  Furthermore, while it's more logical
21119    to use per_cu->section+offset, with Fission the section with the data is in
21120    the DWO file but we don't know that section at the point we need it.
21121    We have to use something in dwarf2_per_cu_data (or the pointer to it)
21122    because we can enter the lookup routine, get_die_type_at_offset, from
21123    outside this file, and thus won't necessarily have PER_CU->cu.
21124    Fortunately, PER_CU is stable for the life of the objfile.  */
21125
21126 struct dwarf2_per_cu_offset_and_type
21127 {
21128   const struct dwarf2_per_cu_data *per_cu;
21129   sect_offset offset;
21130   struct type *type;
21131 };
21132
21133 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
21134
21135 static hashval_t
21136 per_cu_offset_and_type_hash (const void *item)
21137 {
21138   const struct dwarf2_per_cu_offset_and_type *ofs = item;
21139
21140   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
21141 }
21142
21143 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
21144
21145 static int
21146 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
21147 {
21148   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
21149   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
21150
21151   return (ofs_lhs->per_cu == ofs_rhs->per_cu
21152           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
21153 }
21154
21155 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
21156    table if necessary.  For convenience, return TYPE.
21157
21158    The DIEs reading must have careful ordering to:
21159     * Not cause infite loops trying to read in DIEs as a prerequisite for
21160       reading current DIE.
21161     * Not trying to dereference contents of still incompletely read in types
21162       while reading in other DIEs.
21163     * Enable referencing still incompletely read in types just by a pointer to
21164       the type without accessing its fields.
21165
21166    Therefore caller should follow these rules:
21167      * Try to fetch any prerequisite types we may need to build this DIE type
21168        before building the type and calling set_die_type.
21169      * After building type call set_die_type for current DIE as soon as
21170        possible before fetching more types to complete the current type.
21171      * Make the type as complete as possible before fetching more types.  */
21172
21173 static struct type *
21174 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21175 {
21176   struct dwarf2_per_cu_offset_and_type **slot, ofs;
21177   struct objfile *objfile = cu->objfile;
21178
21179   /* For Ada types, make sure that the gnat-specific data is always
21180      initialized (if not already set).  There are a few types where
21181      we should not be doing so, because the type-specific area is
21182      already used to hold some other piece of info (eg: TYPE_CODE_FLT
21183      where the type-specific area is used to store the floatformat).
21184      But this is not a problem, because the gnat-specific information
21185      is actually not needed for these types.  */
21186   if (need_gnat_info (cu)
21187       && TYPE_CODE (type) != TYPE_CODE_FUNC
21188       && TYPE_CODE (type) != TYPE_CODE_FLT
21189       && !HAVE_GNAT_AUX_INFO (type))
21190     INIT_GNAT_SPECIFIC (type);
21191
21192   if (dwarf2_per_objfile->die_type_hash == NULL)
21193     {
21194       dwarf2_per_objfile->die_type_hash =
21195         htab_create_alloc_ex (127,
21196                               per_cu_offset_and_type_hash,
21197                               per_cu_offset_and_type_eq,
21198                               NULL,
21199                               &objfile->objfile_obstack,
21200                               hashtab_obstack_allocate,
21201                               dummy_obstack_deallocate);
21202     }
21203
21204   ofs.per_cu = cu->per_cu;
21205   ofs.offset = die->offset;
21206   ofs.type = type;
21207   slot = (struct dwarf2_per_cu_offset_and_type **)
21208     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
21209   if (*slot)
21210     complaint (&symfile_complaints,
21211                _("A problem internal to GDB: DIE 0x%x has type already set"),
21212                die->offset.sect_off);
21213   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
21214   **slot = ofs;
21215   return type;
21216 }
21217
21218 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
21219    or return NULL if the die does not have a saved type.  */
21220
21221 static struct type *
21222 get_die_type_at_offset (sect_offset offset,
21223                         struct dwarf2_per_cu_data *per_cu)
21224 {
21225   struct dwarf2_per_cu_offset_and_type *slot, ofs;
21226
21227   if (dwarf2_per_objfile->die_type_hash == NULL)
21228     return NULL;
21229
21230   ofs.per_cu = per_cu;
21231   ofs.offset = offset;
21232   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
21233   if (slot)
21234     return slot->type;
21235   else
21236     return NULL;
21237 }
21238
21239 /* Look up the type for DIE in CU in die_type_hash,
21240    or return NULL if DIE does not have a saved type.  */
21241
21242 static struct type *
21243 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
21244 {
21245   return get_die_type_at_offset (die->offset, cu->per_cu);
21246 }
21247
21248 /* Add a dependence relationship from CU to REF_PER_CU.  */
21249
21250 static void
21251 dwarf2_add_dependence (struct dwarf2_cu *cu,
21252                        struct dwarf2_per_cu_data *ref_per_cu)
21253 {
21254   void **slot;
21255
21256   if (cu->dependencies == NULL)
21257     cu->dependencies
21258       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
21259                               NULL, &cu->comp_unit_obstack,
21260                               hashtab_obstack_allocate,
21261                               dummy_obstack_deallocate);
21262
21263   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
21264   if (*slot == NULL)
21265     *slot = ref_per_cu;
21266 }
21267
21268 /* Subroutine of dwarf2_mark to pass to htab_traverse.
21269    Set the mark field in every compilation unit in the
21270    cache that we must keep because we are keeping CU.  */
21271
21272 static int
21273 dwarf2_mark_helper (void **slot, void *data)
21274 {
21275   struct dwarf2_per_cu_data *per_cu;
21276
21277   per_cu = (struct dwarf2_per_cu_data *) *slot;
21278
21279   /* cu->dependencies references may not yet have been ever read if QUIT aborts
21280      reading of the chain.  As such dependencies remain valid it is not much
21281      useful to track and undo them during QUIT cleanups.  */
21282   if (per_cu->cu == NULL)
21283     return 1;
21284
21285   if (per_cu->cu->mark)
21286     return 1;
21287   per_cu->cu->mark = 1;
21288
21289   if (per_cu->cu->dependencies != NULL)
21290     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
21291
21292   return 1;
21293 }
21294
21295 /* Set the mark field in CU and in every other compilation unit in the
21296    cache that we must keep because we are keeping CU.  */
21297
21298 static void
21299 dwarf2_mark (struct dwarf2_cu *cu)
21300 {
21301   if (cu->mark)
21302     return;
21303   cu->mark = 1;
21304   if (cu->dependencies != NULL)
21305     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
21306 }
21307
21308 static void
21309 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
21310 {
21311   while (per_cu)
21312     {
21313       per_cu->cu->mark = 0;
21314       per_cu = per_cu->cu->read_in_chain;
21315     }
21316 }
21317
21318 /* Trivial hash function for partial_die_info: the hash value of a DIE
21319    is its offset in .debug_info for this objfile.  */
21320
21321 static hashval_t
21322 partial_die_hash (const void *item)
21323 {
21324   const struct partial_die_info *part_die = item;
21325
21326   return part_die->offset.sect_off;
21327 }
21328
21329 /* Trivial comparison function for partial_die_info structures: two DIEs
21330    are equal if they have the same offset.  */
21331
21332 static int
21333 partial_die_eq (const void *item_lhs, const void *item_rhs)
21334 {
21335   const struct partial_die_info *part_die_lhs = item_lhs;
21336   const struct partial_die_info *part_die_rhs = item_rhs;
21337
21338   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
21339 }
21340
21341 static struct cmd_list_element *set_dwarf2_cmdlist;
21342 static struct cmd_list_element *show_dwarf2_cmdlist;
21343
21344 static void
21345 set_dwarf2_cmd (char *args, int from_tty)
21346 {
21347   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
21348 }
21349
21350 static void
21351 show_dwarf2_cmd (char *args, int from_tty)
21352 {
21353   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
21354 }
21355
21356 /* Free data associated with OBJFILE, if necessary.  */
21357
21358 static void
21359 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
21360 {
21361   struct dwarf2_per_objfile *data = d;
21362   int ix;
21363
21364   /* Make sure we don't accidentally use dwarf2_per_objfile while
21365      cleaning up.  */
21366   dwarf2_per_objfile = NULL;
21367
21368   for (ix = 0; ix < data->n_comp_units; ++ix)
21369    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
21370
21371   for (ix = 0; ix < data->n_type_units; ++ix)
21372     VEC_free (dwarf2_per_cu_ptr,
21373               data->all_type_units[ix]->per_cu.imported_symtabs);
21374   xfree (data->all_type_units);
21375
21376   VEC_free (dwarf2_section_info_def, data->types);
21377
21378   if (data->dwo_files)
21379     free_dwo_files (data->dwo_files, objfile);
21380   if (data->dwp_file)
21381     gdb_bfd_unref (data->dwp_file->dbfd);
21382
21383   if (data->dwz_file && data->dwz_file->dwz_bfd)
21384     gdb_bfd_unref (data->dwz_file->dwz_bfd);
21385 }
21386
21387 \f
21388 /* The "save gdb-index" command.  */
21389
21390 /* The contents of the hash table we create when building the string
21391    table.  */
21392 struct strtab_entry
21393 {
21394   offset_type offset;
21395   const char *str;
21396 };
21397
21398 /* Hash function for a strtab_entry.
21399
21400    Function is used only during write_hash_table so no index format backward
21401    compatibility is needed.  */
21402
21403 static hashval_t
21404 hash_strtab_entry (const void *e)
21405 {
21406   const struct strtab_entry *entry = e;
21407   return mapped_index_string_hash (INT_MAX, entry->str);
21408 }
21409
21410 /* Equality function for a strtab_entry.  */
21411
21412 static int
21413 eq_strtab_entry (const void *a, const void *b)
21414 {
21415   const struct strtab_entry *ea = a;
21416   const struct strtab_entry *eb = b;
21417   return !strcmp (ea->str, eb->str);
21418 }
21419
21420 /* Create a strtab_entry hash table.  */
21421
21422 static htab_t
21423 create_strtab (void)
21424 {
21425   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
21426                             xfree, xcalloc, xfree);
21427 }
21428
21429 /* Add a string to the constant pool.  Return the string's offset in
21430    host order.  */
21431
21432 static offset_type
21433 add_string (htab_t table, struct obstack *cpool, const char *str)
21434 {
21435   void **slot;
21436   struct strtab_entry entry;
21437   struct strtab_entry *result;
21438
21439   entry.str = str;
21440   slot = htab_find_slot (table, &entry, INSERT);
21441   if (*slot)
21442     result = *slot;
21443   else
21444     {
21445       result = XNEW (struct strtab_entry);
21446       result->offset = obstack_object_size (cpool);
21447       result->str = str;
21448       obstack_grow_str0 (cpool, str);
21449       *slot = result;
21450     }
21451   return result->offset;
21452 }
21453
21454 /* An entry in the symbol table.  */
21455 struct symtab_index_entry
21456 {
21457   /* The name of the symbol.  */
21458   const char *name;
21459   /* The offset of the name in the constant pool.  */
21460   offset_type index_offset;
21461   /* A sorted vector of the indices of all the CUs that hold an object
21462      of this name.  */
21463   VEC (offset_type) *cu_indices;
21464 };
21465
21466 /* The symbol table.  This is a power-of-2-sized hash table.  */
21467 struct mapped_symtab
21468 {
21469   offset_type n_elements;
21470   offset_type size;
21471   struct symtab_index_entry **data;
21472 };
21473
21474 /* Hash function for a symtab_index_entry.  */
21475
21476 static hashval_t
21477 hash_symtab_entry (const void *e)
21478 {
21479   const struct symtab_index_entry *entry = e;
21480   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
21481                          sizeof (offset_type) * VEC_length (offset_type,
21482                                                             entry->cu_indices),
21483                          0);
21484 }
21485
21486 /* Equality function for a symtab_index_entry.  */
21487
21488 static int
21489 eq_symtab_entry (const void *a, const void *b)
21490 {
21491   const struct symtab_index_entry *ea = a;
21492   const struct symtab_index_entry *eb = b;
21493   int len = VEC_length (offset_type, ea->cu_indices);
21494   if (len != VEC_length (offset_type, eb->cu_indices))
21495     return 0;
21496   return !memcmp (VEC_address (offset_type, ea->cu_indices),
21497                   VEC_address (offset_type, eb->cu_indices),
21498                   sizeof (offset_type) * len);
21499 }
21500
21501 /* Destroy a symtab_index_entry.  */
21502
21503 static void
21504 delete_symtab_entry (void *p)
21505 {
21506   struct symtab_index_entry *entry = p;
21507   VEC_free (offset_type, entry->cu_indices);
21508   xfree (entry);
21509 }
21510
21511 /* Create a hash table holding symtab_index_entry objects.  */
21512
21513 static htab_t
21514 create_symbol_hash_table (void)
21515 {
21516   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
21517                             delete_symtab_entry, xcalloc, xfree);
21518 }
21519
21520 /* Create a new mapped symtab object.  */
21521
21522 static struct mapped_symtab *
21523 create_mapped_symtab (void)
21524 {
21525   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
21526   symtab->n_elements = 0;
21527   symtab->size = 1024;
21528   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21529   return symtab;
21530 }
21531
21532 /* Destroy a mapped_symtab.  */
21533
21534 static void
21535 cleanup_mapped_symtab (void *p)
21536 {
21537   struct mapped_symtab *symtab = p;
21538   /* The contents of the array are freed when the other hash table is
21539      destroyed.  */
21540   xfree (symtab->data);
21541   xfree (symtab);
21542 }
21543
21544 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
21545    the slot.
21546    
21547    Function is used only during write_hash_table so no index format backward
21548    compatibility is needed.  */
21549
21550 static struct symtab_index_entry **
21551 find_slot (struct mapped_symtab *symtab, const char *name)
21552 {
21553   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
21554
21555   index = hash & (symtab->size - 1);
21556   step = ((hash * 17) & (symtab->size - 1)) | 1;
21557
21558   for (;;)
21559     {
21560       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
21561         return &symtab->data[index];
21562       index = (index + step) & (symtab->size - 1);
21563     }
21564 }
21565
21566 /* Expand SYMTAB's hash table.  */
21567
21568 static void
21569 hash_expand (struct mapped_symtab *symtab)
21570 {
21571   offset_type old_size = symtab->size;
21572   offset_type i;
21573   struct symtab_index_entry **old_entries = symtab->data;
21574
21575   symtab->size *= 2;
21576   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21577
21578   for (i = 0; i < old_size; ++i)
21579     {
21580       if (old_entries[i])
21581         {
21582           struct symtab_index_entry **slot = find_slot (symtab,
21583                                                         old_entries[i]->name);
21584           *slot = old_entries[i];
21585         }
21586     }
21587
21588   xfree (old_entries);
21589 }
21590
21591 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
21592    CU_INDEX is the index of the CU in which the symbol appears.
21593    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
21594
21595 static void
21596 add_index_entry (struct mapped_symtab *symtab, const char *name,
21597                  int is_static, gdb_index_symbol_kind kind,
21598                  offset_type cu_index)
21599 {
21600   struct symtab_index_entry **slot;
21601   offset_type cu_index_and_attrs;
21602
21603   ++symtab->n_elements;
21604   if (4 * symtab->n_elements / 3 >= symtab->size)
21605     hash_expand (symtab);
21606
21607   slot = find_slot (symtab, name);
21608   if (!*slot)
21609     {
21610       *slot = XNEW (struct symtab_index_entry);
21611       (*slot)->name = name;
21612       /* index_offset is set later.  */
21613       (*slot)->cu_indices = NULL;
21614     }
21615
21616   cu_index_and_attrs = 0;
21617   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
21618   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
21619   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
21620
21621   /* We don't want to record an index value twice as we want to avoid the
21622      duplication.
21623      We process all global symbols and then all static symbols
21624      (which would allow us to avoid the duplication by only having to check
21625      the last entry pushed), but a symbol could have multiple kinds in one CU.
21626      To keep things simple we don't worry about the duplication here and
21627      sort and uniqufy the list after we've processed all symbols.  */
21628   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
21629 }
21630
21631 /* qsort helper routine for uniquify_cu_indices.  */
21632
21633 static int
21634 offset_type_compare (const void *ap, const void *bp)
21635 {
21636   offset_type a = *(offset_type *) ap;
21637   offset_type b = *(offset_type *) bp;
21638
21639   return (a > b) - (b > a);
21640 }
21641
21642 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
21643
21644 static void
21645 uniquify_cu_indices (struct mapped_symtab *symtab)
21646 {
21647   int i;
21648
21649   for (i = 0; i < symtab->size; ++i)
21650     {
21651       struct symtab_index_entry *entry = symtab->data[i];
21652
21653       if (entry
21654           && entry->cu_indices != NULL)
21655         {
21656           unsigned int next_to_insert, next_to_check;
21657           offset_type last_value;
21658
21659           qsort (VEC_address (offset_type, entry->cu_indices),
21660                  VEC_length (offset_type, entry->cu_indices),
21661                  sizeof (offset_type), offset_type_compare);
21662
21663           last_value = VEC_index (offset_type, entry->cu_indices, 0);
21664           next_to_insert = 1;
21665           for (next_to_check = 1;
21666                next_to_check < VEC_length (offset_type, entry->cu_indices);
21667                ++next_to_check)
21668             {
21669               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
21670                   != last_value)
21671                 {
21672                   last_value = VEC_index (offset_type, entry->cu_indices,
21673                                           next_to_check);
21674                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
21675                                last_value);
21676                   ++next_to_insert;
21677                 }
21678             }
21679           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
21680         }
21681     }
21682 }
21683
21684 /* Add a vector of indices to the constant pool.  */
21685
21686 static offset_type
21687 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
21688                       struct symtab_index_entry *entry)
21689 {
21690   void **slot;
21691
21692   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
21693   if (!*slot)
21694     {
21695       offset_type len = VEC_length (offset_type, entry->cu_indices);
21696       offset_type val = MAYBE_SWAP (len);
21697       offset_type iter;
21698       int i;
21699
21700       *slot = entry;
21701       entry->index_offset = obstack_object_size (cpool);
21702
21703       obstack_grow (cpool, &val, sizeof (val));
21704       for (i = 0;
21705            VEC_iterate (offset_type, entry->cu_indices, i, iter);
21706            ++i)
21707         {
21708           val = MAYBE_SWAP (iter);
21709           obstack_grow (cpool, &val, sizeof (val));
21710         }
21711     }
21712   else
21713     {
21714       struct symtab_index_entry *old_entry = *slot;
21715       entry->index_offset = old_entry->index_offset;
21716       entry = old_entry;
21717     }
21718   return entry->index_offset;
21719 }
21720
21721 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
21722    constant pool entries going into the obstack CPOOL.  */
21723
21724 static void
21725 write_hash_table (struct mapped_symtab *symtab,
21726                   struct obstack *output, struct obstack *cpool)
21727 {
21728   offset_type i;
21729   htab_t symbol_hash_table;
21730   htab_t str_table;
21731
21732   symbol_hash_table = create_symbol_hash_table ();
21733   str_table = create_strtab ();
21734
21735   /* We add all the index vectors to the constant pool first, to
21736      ensure alignment is ok.  */
21737   for (i = 0; i < symtab->size; ++i)
21738     {
21739       if (symtab->data[i])
21740         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
21741     }
21742
21743   /* Now write out the hash table.  */
21744   for (i = 0; i < symtab->size; ++i)
21745     {
21746       offset_type str_off, vec_off;
21747
21748       if (symtab->data[i])
21749         {
21750           str_off = add_string (str_table, cpool, symtab->data[i]->name);
21751           vec_off = symtab->data[i]->index_offset;
21752         }
21753       else
21754         {
21755           /* While 0 is a valid constant pool index, it is not valid
21756              to have 0 for both offsets.  */
21757           str_off = 0;
21758           vec_off = 0;
21759         }
21760
21761       str_off = MAYBE_SWAP (str_off);
21762       vec_off = MAYBE_SWAP (vec_off);
21763
21764       obstack_grow (output, &str_off, sizeof (str_off));
21765       obstack_grow (output, &vec_off, sizeof (vec_off));
21766     }
21767
21768   htab_delete (str_table);
21769   htab_delete (symbol_hash_table);
21770 }
21771
21772 /* Struct to map psymtab to CU index in the index file.  */
21773 struct psymtab_cu_index_map
21774 {
21775   struct partial_symtab *psymtab;
21776   unsigned int cu_index;
21777 };
21778
21779 static hashval_t
21780 hash_psymtab_cu_index (const void *item)
21781 {
21782   const struct psymtab_cu_index_map *map = item;
21783
21784   return htab_hash_pointer (map->psymtab);
21785 }
21786
21787 static int
21788 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21789 {
21790   const struct psymtab_cu_index_map *lhs = item_lhs;
21791   const struct psymtab_cu_index_map *rhs = item_rhs;
21792
21793   return lhs->psymtab == rhs->psymtab;
21794 }
21795
21796 /* Helper struct for building the address table.  */
21797 struct addrmap_index_data
21798 {
21799   struct objfile *objfile;
21800   struct obstack *addr_obstack;
21801   htab_t cu_index_htab;
21802
21803   /* Non-zero if the previous_* fields are valid.
21804      We can't write an entry until we see the next entry (since it is only then
21805      that we know the end of the entry).  */
21806   int previous_valid;
21807   /* Index of the CU in the table of all CUs in the index file.  */
21808   unsigned int previous_cu_index;
21809   /* Start address of the CU.  */
21810   CORE_ADDR previous_cu_start;
21811 };
21812
21813 /* Write an address entry to OBSTACK.  */
21814
21815 static void
21816 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21817                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21818 {
21819   offset_type cu_index_to_write;
21820   gdb_byte addr[8];
21821   CORE_ADDR baseaddr;
21822
21823   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21824
21825   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21826   obstack_grow (obstack, addr, 8);
21827   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21828   obstack_grow (obstack, addr, 8);
21829   cu_index_to_write = MAYBE_SWAP (cu_index);
21830   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21831 }
21832
21833 /* Worker function for traversing an addrmap to build the address table.  */
21834
21835 static int
21836 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21837 {
21838   struct addrmap_index_data *data = datap;
21839   struct partial_symtab *pst = obj;
21840
21841   if (data->previous_valid)
21842     add_address_entry (data->objfile, data->addr_obstack,
21843                        data->previous_cu_start, start_addr,
21844                        data->previous_cu_index);
21845
21846   data->previous_cu_start = start_addr;
21847   if (pst != NULL)
21848     {
21849       struct psymtab_cu_index_map find_map, *map;
21850       find_map.psymtab = pst;
21851       map = htab_find (data->cu_index_htab, &find_map);
21852       gdb_assert (map != NULL);
21853       data->previous_cu_index = map->cu_index;
21854       data->previous_valid = 1;
21855     }
21856   else
21857       data->previous_valid = 0;
21858
21859   return 0;
21860 }
21861
21862 /* Write OBJFILE's address map to OBSTACK.
21863    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21864    in the index file.  */
21865
21866 static void
21867 write_address_map (struct objfile *objfile, struct obstack *obstack,
21868                    htab_t cu_index_htab)
21869 {
21870   struct addrmap_index_data addrmap_index_data;
21871
21872   /* When writing the address table, we have to cope with the fact that
21873      the addrmap iterator only provides the start of a region; we have to
21874      wait until the next invocation to get the start of the next region.  */
21875
21876   addrmap_index_data.objfile = objfile;
21877   addrmap_index_data.addr_obstack = obstack;
21878   addrmap_index_data.cu_index_htab = cu_index_htab;
21879   addrmap_index_data.previous_valid = 0;
21880
21881   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21882                    &addrmap_index_data);
21883
21884   /* It's highly unlikely the last entry (end address = 0xff...ff)
21885      is valid, but we should still handle it.
21886      The end address is recorded as the start of the next region, but that
21887      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21888      anyway.  */
21889   if (addrmap_index_data.previous_valid)
21890     add_address_entry (objfile, obstack,
21891                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21892                        addrmap_index_data.previous_cu_index);
21893 }
21894
21895 /* Return the symbol kind of PSYM.  */
21896
21897 static gdb_index_symbol_kind
21898 symbol_kind (struct partial_symbol *psym)
21899 {
21900   domain_enum domain = PSYMBOL_DOMAIN (psym);
21901   enum address_class aclass = PSYMBOL_CLASS (psym);
21902
21903   switch (domain)
21904     {
21905     case VAR_DOMAIN:
21906       switch (aclass)
21907         {
21908         case LOC_BLOCK:
21909           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21910         case LOC_TYPEDEF:
21911           return GDB_INDEX_SYMBOL_KIND_TYPE;
21912         case LOC_COMPUTED:
21913         case LOC_CONST_BYTES:
21914         case LOC_OPTIMIZED_OUT:
21915         case LOC_STATIC:
21916           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21917         case LOC_CONST:
21918           /* Note: It's currently impossible to recognize psyms as enum values
21919              short of reading the type info.  For now punt.  */
21920           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21921         default:
21922           /* There are other LOC_FOO values that one might want to classify
21923              as variables, but dwarf2read.c doesn't currently use them.  */
21924           return GDB_INDEX_SYMBOL_KIND_OTHER;
21925         }
21926     case STRUCT_DOMAIN:
21927       return GDB_INDEX_SYMBOL_KIND_TYPE;
21928     default:
21929       return GDB_INDEX_SYMBOL_KIND_OTHER;
21930     }
21931 }
21932
21933 /* Add a list of partial symbols to SYMTAB.  */
21934
21935 static void
21936 write_psymbols (struct mapped_symtab *symtab,
21937                 htab_t psyms_seen,
21938                 struct partial_symbol **psymp,
21939                 int count,
21940                 offset_type cu_index,
21941                 int is_static)
21942 {
21943   for (; count-- > 0; ++psymp)
21944     {
21945       struct partial_symbol *psym = *psymp;
21946       void **slot;
21947
21948       if (SYMBOL_LANGUAGE (psym) == language_ada)
21949         error (_("Ada is not currently supported by the index"));
21950
21951       /* Only add a given psymbol once.  */
21952       slot = htab_find_slot (psyms_seen, psym, INSERT);
21953       if (!*slot)
21954         {
21955           gdb_index_symbol_kind kind = symbol_kind (psym);
21956
21957           *slot = psym;
21958           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21959                            is_static, kind, cu_index);
21960         }
21961     }
21962 }
21963
21964 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21965    exception if there is an error.  */
21966
21967 static void
21968 write_obstack (FILE *file, struct obstack *obstack)
21969 {
21970   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21971               file)
21972       != obstack_object_size (obstack))
21973     error (_("couldn't data write to file"));
21974 }
21975
21976 /* Unlink a file if the argument is not NULL.  */
21977
21978 static void
21979 unlink_if_set (void *p)
21980 {
21981   char **filename = p;
21982   if (*filename)
21983     unlink (*filename);
21984 }
21985
21986 /* A helper struct used when iterating over debug_types.  */
21987 struct signatured_type_index_data
21988 {
21989   struct objfile *objfile;
21990   struct mapped_symtab *symtab;
21991   struct obstack *types_list;
21992   htab_t psyms_seen;
21993   int cu_index;
21994 };
21995
21996 /* A helper function that writes a single signatured_type to an
21997    obstack.  */
21998
21999 static int
22000 write_one_signatured_type (void **slot, void *d)
22001 {
22002   struct signatured_type_index_data *info = d;
22003   struct signatured_type *entry = (struct signatured_type *) *slot;
22004   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
22005   gdb_byte val[8];
22006
22007   write_psymbols (info->symtab,
22008                   info->psyms_seen,
22009                   info->objfile->global_psymbols.list
22010                   + psymtab->globals_offset,
22011                   psymtab->n_global_syms, info->cu_index,
22012                   0);
22013   write_psymbols (info->symtab,
22014                   info->psyms_seen,
22015                   info->objfile->static_psymbols.list
22016                   + psymtab->statics_offset,
22017                   psymtab->n_static_syms, info->cu_index,
22018                   1);
22019
22020   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22021                           entry->per_cu.offset.sect_off);
22022   obstack_grow (info->types_list, val, 8);
22023   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22024                           entry->type_offset_in_tu.cu_off);
22025   obstack_grow (info->types_list, val, 8);
22026   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
22027   obstack_grow (info->types_list, val, 8);
22028
22029   ++info->cu_index;
22030
22031   return 1;
22032 }
22033
22034 /* Recurse into all "included" dependencies and write their symbols as
22035    if they appeared in this psymtab.  */
22036
22037 static void
22038 recursively_write_psymbols (struct objfile *objfile,
22039                             struct partial_symtab *psymtab,
22040                             struct mapped_symtab *symtab,
22041                             htab_t psyms_seen,
22042                             offset_type cu_index)
22043 {
22044   int i;
22045
22046   for (i = 0; i < psymtab->number_of_dependencies; ++i)
22047     if (psymtab->dependencies[i]->user != NULL)
22048       recursively_write_psymbols (objfile, psymtab->dependencies[i],
22049                                   symtab, psyms_seen, cu_index);
22050
22051   write_psymbols (symtab,
22052                   psyms_seen,
22053                   objfile->global_psymbols.list + psymtab->globals_offset,
22054                   psymtab->n_global_syms, cu_index,
22055                   0);
22056   write_psymbols (symtab,
22057                   psyms_seen,
22058                   objfile->static_psymbols.list + psymtab->statics_offset,
22059                   psymtab->n_static_syms, cu_index,
22060                   1);
22061 }
22062
22063 /* Create an index file for OBJFILE in the directory DIR.  */
22064
22065 static void
22066 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
22067 {
22068   struct cleanup *cleanup;
22069   char *filename, *cleanup_filename;
22070   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
22071   struct obstack cu_list, types_cu_list;
22072   int i;
22073   FILE *out_file;
22074   struct mapped_symtab *symtab;
22075   offset_type val, size_of_contents, total_len;
22076   struct stat st;
22077   htab_t psyms_seen;
22078   htab_t cu_index_htab;
22079   struct psymtab_cu_index_map *psymtab_cu_index_map;
22080
22081   if (dwarf2_per_objfile->using_index)
22082     error (_("Cannot use an index to create the index"));
22083
22084   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
22085     error (_("Cannot make an index when the file has multiple .debug_types sections"));
22086
22087   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
22088     return;
22089
22090   if (stat (objfile_name (objfile), &st) < 0)
22091     perror_with_name (objfile_name (objfile));
22092
22093   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
22094                      INDEX_SUFFIX, (char *) NULL);
22095   cleanup = make_cleanup (xfree, filename);
22096
22097   out_file = gdb_fopen_cloexec (filename, "wb");
22098   if (!out_file)
22099     error (_("Can't open `%s' for writing"), filename);
22100
22101   cleanup_filename = filename;
22102   make_cleanup (unlink_if_set, &cleanup_filename);
22103
22104   symtab = create_mapped_symtab ();
22105   make_cleanup (cleanup_mapped_symtab, symtab);
22106
22107   obstack_init (&addr_obstack);
22108   make_cleanup_obstack_free (&addr_obstack);
22109
22110   obstack_init (&cu_list);
22111   make_cleanup_obstack_free (&cu_list);
22112
22113   obstack_init (&types_cu_list);
22114   make_cleanup_obstack_free (&types_cu_list);
22115
22116   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
22117                                   NULL, xcalloc, xfree);
22118   make_cleanup_htab_delete (psyms_seen);
22119
22120   /* While we're scanning CU's create a table that maps a psymtab pointer
22121      (which is what addrmap records) to its index (which is what is recorded
22122      in the index file).  This will later be needed to write the address
22123      table.  */
22124   cu_index_htab = htab_create_alloc (100,
22125                                      hash_psymtab_cu_index,
22126                                      eq_psymtab_cu_index,
22127                                      NULL, xcalloc, xfree);
22128   make_cleanup_htab_delete (cu_index_htab);
22129   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
22130     xmalloc (sizeof (struct psymtab_cu_index_map)
22131              * dwarf2_per_objfile->n_comp_units);
22132   make_cleanup (xfree, psymtab_cu_index_map);
22133
22134   /* The CU list is already sorted, so we don't need to do additional
22135      work here.  Also, the debug_types entries do not appear in
22136      all_comp_units, but only in their own hash table.  */
22137   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
22138     {
22139       struct dwarf2_per_cu_data *per_cu
22140         = dwarf2_per_objfile->all_comp_units[i];
22141       struct partial_symtab *psymtab = per_cu->v.psymtab;
22142       gdb_byte val[8];
22143       struct psymtab_cu_index_map *map;
22144       void **slot;
22145
22146       /* CU of a shared file from 'dwz -m' may be unused by this main file.
22147          It may be referenced from a local scope but in such case it does not
22148          need to be present in .gdb_index.  */
22149       if (psymtab == NULL)
22150         continue;
22151
22152       if (psymtab->user == NULL)
22153         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
22154
22155       map = &psymtab_cu_index_map[i];
22156       map->psymtab = psymtab;
22157       map->cu_index = i;
22158       slot = htab_find_slot (cu_index_htab, map, INSERT);
22159       gdb_assert (slot != NULL);
22160       gdb_assert (*slot == NULL);
22161       *slot = map;
22162
22163       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22164                               per_cu->offset.sect_off);
22165       obstack_grow (&cu_list, val, 8);
22166       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
22167       obstack_grow (&cu_list, val, 8);
22168     }
22169
22170   /* Dump the address map.  */
22171   write_address_map (objfile, &addr_obstack, cu_index_htab);
22172
22173   /* Write out the .debug_type entries, if any.  */
22174   if (dwarf2_per_objfile->signatured_types)
22175     {
22176       struct signatured_type_index_data sig_data;
22177
22178       sig_data.objfile = objfile;
22179       sig_data.symtab = symtab;
22180       sig_data.types_list = &types_cu_list;
22181       sig_data.psyms_seen = psyms_seen;
22182       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
22183       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
22184                               write_one_signatured_type, &sig_data);
22185     }
22186
22187   /* Now that we've processed all symbols we can shrink their cu_indices
22188      lists.  */
22189   uniquify_cu_indices (symtab);
22190
22191   obstack_init (&constant_pool);
22192   make_cleanup_obstack_free (&constant_pool);
22193   obstack_init (&symtab_obstack);
22194   make_cleanup_obstack_free (&symtab_obstack);
22195   write_hash_table (symtab, &symtab_obstack, &constant_pool);
22196
22197   obstack_init (&contents);
22198   make_cleanup_obstack_free (&contents);
22199   size_of_contents = 6 * sizeof (offset_type);
22200   total_len = size_of_contents;
22201
22202   /* The version number.  */
22203   val = MAYBE_SWAP (8);
22204   obstack_grow (&contents, &val, sizeof (val));
22205
22206   /* The offset of the CU list from the start of the file.  */
22207   val = MAYBE_SWAP (total_len);
22208   obstack_grow (&contents, &val, sizeof (val));
22209   total_len += obstack_object_size (&cu_list);
22210
22211   /* The offset of the types CU list from the start of the file.  */
22212   val = MAYBE_SWAP (total_len);
22213   obstack_grow (&contents, &val, sizeof (val));
22214   total_len += obstack_object_size (&types_cu_list);
22215
22216   /* The offset of the address table from the start of the file.  */
22217   val = MAYBE_SWAP (total_len);
22218   obstack_grow (&contents, &val, sizeof (val));
22219   total_len += obstack_object_size (&addr_obstack);
22220
22221   /* The offset of the symbol table from the start of the file.  */
22222   val = MAYBE_SWAP (total_len);
22223   obstack_grow (&contents, &val, sizeof (val));
22224   total_len += obstack_object_size (&symtab_obstack);
22225
22226   /* The offset of the constant pool from the start of the file.  */
22227   val = MAYBE_SWAP (total_len);
22228   obstack_grow (&contents, &val, sizeof (val));
22229   total_len += obstack_object_size (&constant_pool);
22230
22231   gdb_assert (obstack_object_size (&contents) == size_of_contents);
22232
22233   write_obstack (out_file, &contents);
22234   write_obstack (out_file, &cu_list);
22235   write_obstack (out_file, &types_cu_list);
22236   write_obstack (out_file, &addr_obstack);
22237   write_obstack (out_file, &symtab_obstack);
22238   write_obstack (out_file, &constant_pool);
22239
22240   fclose (out_file);
22241
22242   /* We want to keep the file, so we set cleanup_filename to NULL
22243      here.  See unlink_if_set.  */
22244   cleanup_filename = NULL;
22245
22246   do_cleanups (cleanup);
22247 }
22248
22249 /* Implementation of the `save gdb-index' command.
22250    
22251    Note that the file format used by this command is documented in the
22252    GDB manual.  Any changes here must be documented there.  */
22253
22254 static void
22255 save_gdb_index_command (char *arg, int from_tty)
22256 {
22257   struct objfile *objfile;
22258
22259   if (!arg || !*arg)
22260     error (_("usage: save gdb-index DIRECTORY"));
22261
22262   ALL_OBJFILES (objfile)
22263   {
22264     struct stat st;
22265
22266     /* If the objfile does not correspond to an actual file, skip it.  */
22267     if (stat (objfile_name (objfile), &st) < 0)
22268       continue;
22269
22270     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
22271     if (dwarf2_per_objfile)
22272       {
22273         volatile struct gdb_exception except;
22274
22275         TRY_CATCH (except, RETURN_MASK_ERROR)
22276           {
22277             write_psymtabs_to_index (objfile, arg);
22278           }
22279         if (except.reason < 0)
22280           exception_fprintf (gdb_stderr, except,
22281                              _("Error while writing index for `%s': "),
22282                              objfile_name (objfile));
22283       }
22284   }
22285 }
22286
22287 \f
22288
22289 int dwarf2_always_disassemble;
22290
22291 static void
22292 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
22293                                 struct cmd_list_element *c, const char *value)
22294 {
22295   fprintf_filtered (file,
22296                     _("Whether to always disassemble "
22297                       "DWARF expressions is %s.\n"),
22298                     value);
22299 }
22300
22301 static void
22302 show_check_physname (struct ui_file *file, int from_tty,
22303                      struct cmd_list_element *c, const char *value)
22304 {
22305   fprintf_filtered (file,
22306                     _("Whether to check \"physname\" is %s.\n"),
22307                     value);
22308 }
22309
22310 void _initialize_dwarf2_read (void);
22311
22312 void
22313 _initialize_dwarf2_read (void)
22314 {
22315   struct cmd_list_element *c;
22316
22317   dwarf2_objfile_data_key
22318     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
22319
22320   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
22321 Set DWARF 2 specific variables.\n\
22322 Configure DWARF 2 variables such as the cache size"),
22323                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
22324                   0/*allow-unknown*/, &maintenance_set_cmdlist);
22325
22326   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
22327 Show DWARF 2 specific variables\n\
22328 Show DWARF 2 variables such as the cache size"),
22329                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
22330                   0/*allow-unknown*/, &maintenance_show_cmdlist);
22331
22332   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
22333                             &dwarf2_max_cache_age, _("\
22334 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
22335 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
22336 A higher limit means that cached compilation units will be stored\n\
22337 in memory longer, and more total memory will be used.  Zero disables\n\
22338 caching, which can slow down startup."),
22339                             NULL,
22340                             show_dwarf2_max_cache_age,
22341                             &set_dwarf2_cmdlist,
22342                             &show_dwarf2_cmdlist);
22343
22344   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
22345                            &dwarf2_always_disassemble, _("\
22346 Set whether `info address' always disassembles DWARF expressions."), _("\
22347 Show whether `info address' always disassembles DWARF expressions."), _("\
22348 When enabled, DWARF expressions are always printed in an assembly-like\n\
22349 syntax.  When disabled, expressions will be printed in a more\n\
22350 conversational style, when possible."),
22351                            NULL,
22352                            show_dwarf2_always_disassemble,
22353                            &set_dwarf2_cmdlist,
22354                            &show_dwarf2_cmdlist);
22355
22356   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
22357 Set debugging of the dwarf2 reader."), _("\
22358 Show debugging of the dwarf2 reader."), _("\
22359 When enabled, debugging messages are printed during dwarf2 reading\n\
22360 and symtab expansion."),
22361                             NULL,
22362                             NULL,
22363                             &setdebuglist, &showdebuglist);
22364
22365   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
22366 Set debugging of the dwarf2 DIE reader."), _("\
22367 Show debugging of the dwarf2 DIE reader."), _("\
22368 When enabled (non-zero), DIEs are dumped after they are read in.\n\
22369 The value is the maximum depth to print."),
22370                              NULL,
22371                              NULL,
22372                              &setdebuglist, &showdebuglist);
22373
22374   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
22375 Set cross-checking of \"physname\" code against demangler."), _("\
22376 Show cross-checking of \"physname\" code against demangler."), _("\
22377 When enabled, GDB's internal \"physname\" code is checked against\n\
22378 the demangler."),
22379                            NULL, show_check_physname,
22380                            &setdebuglist, &showdebuglist);
22381
22382   add_setshow_boolean_cmd ("use-deprecated-index-sections",
22383                            no_class, &use_deprecated_index_sections, _("\
22384 Set whether to use deprecated gdb_index sections."), _("\
22385 Show whether to use deprecated gdb_index sections."), _("\
22386 When enabled, deprecated .gdb_index sections are used anyway.\n\
22387 Normally they are ignored either because of a missing feature or\n\
22388 performance issue.\n\
22389 Warning: This option must be enabled before gdb reads the file."),
22390                            NULL,
22391                            NULL,
22392                            &setlist, &showlist);
22393
22394   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
22395                _("\
22396 Save a gdb-index file.\n\
22397 Usage: save gdb-index DIRECTORY"),
22398                &save_cmdlist);
22399   set_cmd_completer (c, filename_completer);
22400
22401   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
22402                                                         &dwarf2_locexpr_funcs);
22403   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
22404                                                         &dwarf2_loclist_funcs);
22405
22406   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
22407                                         &dwarf2_block_frame_base_locexpr_funcs);
22408   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
22409                                         &dwarf2_block_frame_base_loclist_funcs);
22410 }