Work around gold/15646.
[platform/upstream/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72 #include "build-id.h"
73
74 #include <fcntl.h>
75 #include "gdb_string.h"
76 #include "gdb_assert.h"
77 #include <sys/types.h>
78
79 typedef struct symbol *symbolp;
80 DEF_VEC_P (symbolp);
81
82 /* When == 1, print basic high level tracing messages.
83    When > 1, be more verbose.
84    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
85 static unsigned int dwarf2_read_debug = 0;
86
87 /* When non-zero, dump DIEs after they are read in.  */
88 static unsigned int dwarf2_die_debug = 0;
89
90 /* When non-zero, cross-check physname against demangler.  */
91 static int check_physname = 0;
92
93 /* When non-zero, do not reject deprecated .gdb_index sections.  */
94 static int use_deprecated_index_sections = 0;
95
96 static const struct objfile_data *dwarf2_objfile_data_key;
97
98 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
99
100 static int dwarf2_locexpr_index;
101 static int dwarf2_loclist_index;
102 static int dwarf2_locexpr_block_index;
103 static int dwarf2_loclist_block_index;
104
105 /* A descriptor for dwarf sections.
106
107    S.ASECTION, SIZE are typically initialized when the objfile is first
108    scanned.  BUFFER, READIN are filled in later when the section is read.
109    If the section contained compressed data then SIZE is updated to record
110    the uncompressed size of the section.
111
112    DWP file format V2 introduces a wrinkle that is easiest to handle by
113    creating the concept of virtual sections contained within a real section.
114    In DWP V2 the sections of the input DWO files are concatenated together
115    into one section, but section offsets are kept relative to the original
116    input section.
117    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
118    the real section this "virtual" section is contained in, and BUFFER,SIZE
119    describe the virtual section.  */
120
121 struct dwarf2_section_info
122 {
123   union
124   {
125     /* If this is a real section, the bfd section.  */
126     asection *asection;
127     /* If this is a virtual section, pointer to the containing ("real")
128        section.  */
129     struct dwarf2_section_info *containing_section;
130   } s;
131   /* Pointer to section data, only valid if readin.  */
132   const gdb_byte *buffer;
133   /* The size of the section, real or virtual.  */
134   bfd_size_type size;
135   /* If this is a virtual section, the offset in the real section.
136      Only valid if is_virtual.  */
137   bfd_size_type virtual_offset;
138   /* True if we have tried to read this section.  */
139   char readin;
140   /* True if this is a virtual section, False otherwise.
141      This specifies which of s.asection and s.containing_section to use.  */
142   char is_virtual;
143 };
144
145 typedef struct dwarf2_section_info dwarf2_section_info_def;
146 DEF_VEC_O (dwarf2_section_info_def);
147
148 /* All offsets in the index are of this type.  It must be
149    architecture-independent.  */
150 typedef uint32_t offset_type;
151
152 DEF_VEC_I (offset_type);
153
154 /* Ensure only legit values are used.  */
155 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
156   do { \
157     gdb_assert ((unsigned int) (value) <= 1); \
158     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
159   } while (0)
160
161 /* Ensure only legit values are used.  */
162 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
163   do { \
164     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
165                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
166     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
167   } while (0)
168
169 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
170 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
171   do { \
172     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
173     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
174   } while (0)
175
176 /* A description of the mapped index.  The file format is described in
177    a comment by the code that writes the index.  */
178 struct mapped_index
179 {
180   /* Index data format version.  */
181   int version;
182
183   /* The total length of the buffer.  */
184   off_t total_size;
185
186   /* A pointer to the address table data.  */
187   const gdb_byte *address_table;
188
189   /* Size of the address table data in bytes.  */
190   offset_type address_table_size;
191
192   /* The symbol table, implemented as a hash table.  */
193   const offset_type *symbol_table;
194
195   /* Size in slots, each slot is 2 offset_types.  */
196   offset_type symbol_table_slots;
197
198   /* A pointer to the constant pool.  */
199   const char *constant_pool;
200 };
201
202 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
203 DEF_VEC_P (dwarf2_per_cu_ptr);
204
205 /* Collection of data recorded per objfile.
206    This hangs off of dwarf2_objfile_data_key.  */
207
208 struct dwarf2_per_objfile
209 {
210   struct dwarf2_section_info info;
211   struct dwarf2_section_info abbrev;
212   struct dwarf2_section_info line;
213   struct dwarf2_section_info loc;
214   struct dwarf2_section_info macinfo;
215   struct dwarf2_section_info macro;
216   struct dwarf2_section_info str;
217   struct dwarf2_section_info ranges;
218   struct dwarf2_section_info addr;
219   struct dwarf2_section_info frame;
220   struct dwarf2_section_info eh_frame;
221   struct dwarf2_section_info gdb_index;
222
223   VEC (dwarf2_section_info_def) *types;
224
225   /* Back link.  */
226   struct objfile *objfile;
227
228   /* Table of all the compilation units.  This is used to locate
229      the target compilation unit of a particular reference.  */
230   struct dwarf2_per_cu_data **all_comp_units;
231
232   /* The number of compilation units in ALL_COMP_UNITS.  */
233   int n_comp_units;
234
235   /* The number of .debug_types-related CUs.  */
236   int n_type_units;
237
238   /* The .debug_types-related CUs (TUs).
239      This is stored in malloc space because we may realloc it.  */
240   struct signatured_type **all_type_units;
241
242   /* The number of entries in all_type_unit_groups.  */
243   int n_type_unit_groups;
244
245   /* Table of type unit groups.
246      This exists to make it easy to iterate over all CUs and TU groups.  */
247   struct type_unit_group **all_type_unit_groups;
248
249   /* Table of struct type_unit_group objects.
250      The hash key is the DW_AT_stmt_list value.  */
251   htab_t type_unit_groups;
252
253   /* A table mapping .debug_types signatures to its signatured_type entry.
254      This is NULL if the .debug_types section hasn't been read in yet.  */
255   htab_t signatured_types;
256
257   /* Type unit statistics, to see how well the scaling improvements
258      are doing.  */
259   struct tu_stats
260   {
261     int nr_uniq_abbrev_tables;
262     int nr_symtabs;
263     int nr_symtab_sharers;
264     int nr_stmt_less_type_units;
265   } tu_stats;
266
267   /* A chain of compilation units that are currently read in, so that
268      they can be freed later.  */
269   struct dwarf2_per_cu_data *read_in_chain;
270
271   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
272      This is NULL if the table hasn't been allocated yet.  */
273   htab_t dwo_files;
274
275   /* Non-zero if we've check for whether there is a DWP file.  */
276   int dwp_checked;
277
278   /* The DWP file if there is one, or NULL.  */
279   struct dwp_file *dwp_file;
280
281   /* The shared '.dwz' file, if one exists.  This is used when the
282      original data was compressed using 'dwz -m'.  */
283   struct dwz_file *dwz_file;
284
285   /* A flag indicating wether this objfile has a section loaded at a
286      VMA of 0.  */
287   int has_section_at_zero;
288
289   /* True if we are using the mapped index,
290      or we are faking it for OBJF_READNOW's sake.  */
291   unsigned char using_index;
292
293   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
294   struct mapped_index *index_table;
295
296   /* When using index_table, this keeps track of all quick_file_names entries.
297      TUs typically share line table entries with a CU, so we maintain a
298      separate table of all line table entries to support the sharing.
299      Note that while there can be way more TUs than CUs, we've already
300      sorted all the TUs into "type unit groups", grouped by their
301      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
302      CU and its associated TU group if there is one.  */
303   htab_t quick_file_names_table;
304
305   /* Set during partial symbol reading, to prevent queueing of full
306      symbols.  */
307   int reading_partial_symbols;
308
309   /* Table mapping type DIEs to their struct type *.
310      This is NULL if not allocated yet.
311      The mapping is done via (CU/TU + DIE offset) -> type.  */
312   htab_t die_type_hash;
313
314   /* The CUs we recently read.  */
315   VEC (dwarf2_per_cu_ptr) *just_read_cus;
316 };
317
318 static struct dwarf2_per_objfile *dwarf2_per_objfile;
319
320 /* Default names of the debugging sections.  */
321
322 /* Note that if the debugging section has been compressed, it might
323    have a name like .zdebug_info.  */
324
325 static const struct dwarf2_debug_sections dwarf2_elf_names =
326 {
327   { ".debug_info", ".zdebug_info" },
328   { ".debug_abbrev", ".zdebug_abbrev" },
329   { ".debug_line", ".zdebug_line" },
330   { ".debug_loc", ".zdebug_loc" },
331   { ".debug_macinfo", ".zdebug_macinfo" },
332   { ".debug_macro", ".zdebug_macro" },
333   { ".debug_str", ".zdebug_str" },
334   { ".debug_ranges", ".zdebug_ranges" },
335   { ".debug_types", ".zdebug_types" },
336   { ".debug_addr", ".zdebug_addr" },
337   { ".debug_frame", ".zdebug_frame" },
338   { ".eh_frame", NULL },
339   { ".gdb_index", ".zgdb_index" },
340   23
341 };
342
343 /* List of DWO/DWP sections.  */
344
345 static const struct dwop_section_names
346 {
347   struct dwarf2_section_names abbrev_dwo;
348   struct dwarf2_section_names info_dwo;
349   struct dwarf2_section_names line_dwo;
350   struct dwarf2_section_names loc_dwo;
351   struct dwarf2_section_names macinfo_dwo;
352   struct dwarf2_section_names macro_dwo;
353   struct dwarf2_section_names str_dwo;
354   struct dwarf2_section_names str_offsets_dwo;
355   struct dwarf2_section_names types_dwo;
356   struct dwarf2_section_names cu_index;
357   struct dwarf2_section_names tu_index;
358 }
359 dwop_section_names =
360 {
361   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
362   { ".debug_info.dwo", ".zdebug_info.dwo" },
363   { ".debug_line.dwo", ".zdebug_line.dwo" },
364   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
365   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
366   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
367   { ".debug_str.dwo", ".zdebug_str.dwo" },
368   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
369   { ".debug_types.dwo", ".zdebug_types.dwo" },
370   { ".debug_cu_index", ".zdebug_cu_index" },
371   { ".debug_tu_index", ".zdebug_tu_index" },
372 };
373
374 /* local data types */
375
376 /* The data in a compilation unit header, after target2host
377    translation, looks like this.  */
378 struct comp_unit_head
379 {
380   unsigned int length;
381   short version;
382   unsigned char addr_size;
383   unsigned char signed_addr_p;
384   sect_offset abbrev_offset;
385
386   /* Size of file offsets; either 4 or 8.  */
387   unsigned int offset_size;
388
389   /* Size of the length field; either 4 or 12.  */
390   unsigned int initial_length_size;
391
392   /* Offset to the first byte of this compilation unit header in the
393      .debug_info section, for resolving relative reference dies.  */
394   sect_offset offset;
395
396   /* Offset to first die in this cu from the start of the cu.
397      This will be the first byte following the compilation unit header.  */
398   cu_offset first_die_offset;
399 };
400
401 /* Type used for delaying computation of method physnames.
402    See comments for compute_delayed_physnames.  */
403 struct delayed_method_info
404 {
405   /* The type to which the method is attached, i.e., its parent class.  */
406   struct type *type;
407
408   /* The index of the method in the type's function fieldlists.  */
409   int fnfield_index;
410
411   /* The index of the method in the fieldlist.  */
412   int index;
413
414   /* The name of the DIE.  */
415   const char *name;
416
417   /*  The DIE associated with this method.  */
418   struct die_info *die;
419 };
420
421 typedef struct delayed_method_info delayed_method_info;
422 DEF_VEC_O (delayed_method_info);
423
424 /* Internal state when decoding a particular compilation unit.  */
425 struct dwarf2_cu
426 {
427   /* The objfile containing this compilation unit.  */
428   struct objfile *objfile;
429
430   /* The header of the compilation unit.  */
431   struct comp_unit_head header;
432
433   /* Base address of this compilation unit.  */
434   CORE_ADDR base_address;
435
436   /* Non-zero if base_address has been set.  */
437   int base_known;
438
439   /* The language we are debugging.  */
440   enum language language;
441   const struct language_defn *language_defn;
442
443   const char *producer;
444
445   /* The generic symbol table building routines have separate lists for
446      file scope symbols and all all other scopes (local scopes).  So
447      we need to select the right one to pass to add_symbol_to_list().
448      We do it by keeping a pointer to the correct list in list_in_scope.
449
450      FIXME: The original dwarf code just treated the file scope as the
451      first local scope, and all other local scopes as nested local
452      scopes, and worked fine.  Check to see if we really need to
453      distinguish these in buildsym.c.  */
454   struct pending **list_in_scope;
455
456   /* The abbrev table for this CU.
457      Normally this points to the abbrev table in the objfile.
458      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
459   struct abbrev_table *abbrev_table;
460
461   /* Hash table holding all the loaded partial DIEs
462      with partial_die->offset.SECT_OFF as hash.  */
463   htab_t partial_dies;
464
465   /* Storage for things with the same lifetime as this read-in compilation
466      unit, including partial DIEs.  */
467   struct obstack comp_unit_obstack;
468
469   /* When multiple dwarf2_cu structures are living in memory, this field
470      chains them all together, so that they can be released efficiently.
471      We will probably also want a generation counter so that most-recently-used
472      compilation units are cached...  */
473   struct dwarf2_per_cu_data *read_in_chain;
474
475   /* Backlink to our per_cu entry.  */
476   struct dwarf2_per_cu_data *per_cu;
477
478   /* How many compilation units ago was this CU last referenced?  */
479   int last_used;
480
481   /* A hash table of DIE cu_offset for following references with
482      die_info->offset.sect_off as hash.  */
483   htab_t die_hash;
484
485   /* Full DIEs if read in.  */
486   struct die_info *dies;
487
488   /* A set of pointers to dwarf2_per_cu_data objects for compilation
489      units referenced by this one.  Only set during full symbol processing;
490      partial symbol tables do not have dependencies.  */
491   htab_t dependencies;
492
493   /* Header data from the line table, during full symbol processing.  */
494   struct line_header *line_header;
495
496   /* A list of methods which need to have physnames computed
497      after all type information has been read.  */
498   VEC (delayed_method_info) *method_list;
499
500   /* To be copied to symtab->call_site_htab.  */
501   htab_t call_site_htab;
502
503   /* Non-NULL if this CU came from a DWO file.
504      There is an invariant here that is important to remember:
505      Except for attributes copied from the top level DIE in the "main"
506      (or "stub") file in preparation for reading the DWO file
507      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
508      Either there isn't a DWO file (in which case this is NULL and the point
509      is moot), or there is and either we're not going to read it (in which
510      case this is NULL) or there is and we are reading it (in which case this
511      is non-NULL).  */
512   struct dwo_unit *dwo_unit;
513
514   /* The DW_AT_addr_base attribute if present, zero otherwise
515      (zero is a valid value though).
516      Note this value comes from the stub CU/TU's DIE.  */
517   ULONGEST addr_base;
518
519   /* The DW_AT_ranges_base attribute if present, zero otherwise
520      (zero is a valid value though).
521      Note this value comes from the stub CU/TU's DIE.
522      Also note that the value is zero in the non-DWO case so this value can
523      be used without needing to know whether DWO files are in use or not.
524      N.B. This does not apply to DW_AT_ranges appearing in
525      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
526      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
527      DW_AT_ranges_base *would* have to be applied, and we'd have to care
528      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
529   ULONGEST ranges_base;
530
531   /* Mark used when releasing cached dies.  */
532   unsigned int mark : 1;
533
534   /* This CU references .debug_loc.  See the symtab->locations_valid field.
535      This test is imperfect as there may exist optimized debug code not using
536      any location list and still facing inlining issues if handled as
537      unoptimized code.  For a future better test see GCC PR other/32998.  */
538   unsigned int has_loclist : 1;
539
540   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
541      if all the producer_is_* fields are valid.  This information is cached
542      because profiling CU expansion showed excessive time spent in
543      producer_is_gxx_lt_4_6.  */
544   unsigned int checked_producer : 1;
545   unsigned int producer_is_gxx_lt_4_6 : 1;
546   unsigned int producer_is_gcc_lt_4_3 : 1;
547   unsigned int producer_is_icc : 1;
548
549   /* When set, the file that we're processing is known to have
550      debugging info for C++ namespaces.  GCC 3.3.x did not produce
551      this information, but later versions do.  */
552
553   unsigned int processing_has_namespace_info : 1;
554 };
555
556 /* Persistent data held for a compilation unit, even when not
557    processing it.  We put a pointer to this structure in the
558    read_symtab_private field of the psymtab.  */
559
560 struct dwarf2_per_cu_data
561 {
562   /* The start offset and length of this compilation unit.
563      NOTE: Unlike comp_unit_head.length, this length includes
564      initial_length_size.
565      If the DIE refers to a DWO file, this is always of the original die,
566      not the DWO file.  */
567   sect_offset offset;
568   unsigned int length;
569
570   /* Flag indicating this compilation unit will be read in before
571      any of the current compilation units are processed.  */
572   unsigned int queued : 1;
573
574   /* This flag will be set when reading partial DIEs if we need to load
575      absolutely all DIEs for this compilation unit, instead of just the ones
576      we think are interesting.  It gets set if we look for a DIE in the
577      hash table and don't find it.  */
578   unsigned int load_all_dies : 1;
579
580   /* Non-zero if this CU is from .debug_types.
581      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
582      this is non-zero.  */
583   unsigned int is_debug_types : 1;
584
585   /* Non-zero if this CU is from the .dwz file.  */
586   unsigned int is_dwz : 1;
587
588   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
589      This flag is only valid if is_debug_types is true.
590      We can't read a CU directly from a DWO file: There are required
591      attributes in the stub.  */
592   unsigned int reading_dwo_directly : 1;
593
594   /* Non-zero if the TU has been read.
595      This is used to assist the "Stay in DWO Optimization" for Fission:
596      When reading a DWO, it's faster to read TUs from the DWO instead of
597      fetching them from random other DWOs (due to comdat folding).
598      If the TU has already been read, the optimization is unnecessary
599      (and unwise - we don't want to change where gdb thinks the TU lives
600      "midflight").
601      This flag is only valid if is_debug_types is true.  */
602   unsigned int tu_read : 1;
603
604   /* The section this CU/TU lives in.
605      If the DIE refers to a DWO file, this is always the original die,
606      not the DWO file.  */
607   struct dwarf2_section_info *section;
608
609   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
610      of the CU cache it gets reset to NULL again.  */
611   struct dwarf2_cu *cu;
612
613   /* The corresponding objfile.
614      Normally we can get the objfile from dwarf2_per_objfile.
615      However we can enter this file with just a "per_cu" handle.  */
616   struct objfile *objfile;
617
618   /* When using partial symbol tables, the 'psymtab' field is active.
619      Otherwise the 'quick' field is active.  */
620   union
621   {
622     /* The partial symbol table associated with this compilation unit,
623        or NULL for unread partial units.  */
624     struct partial_symtab *psymtab;
625
626     /* Data needed by the "quick" functions.  */
627     struct dwarf2_per_cu_quick_data *quick;
628   } v;
629
630   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
631      while reading psymtabs, used to compute the psymtab dependencies,
632      and then cleared.  Then it is filled in again while reading full
633      symbols, and only deleted when the objfile is destroyed.
634
635      This is also used to work around a difference between the way gold
636      generates .gdb_index version <=7 and the way gdb does.  Arguably this
637      is a gold bug.  For symbols coming from TUs, gold records in the index
638      the CU that includes the TU instead of the TU itself.  This breaks
639      dw2_lookup_symbol: It assumes that if the index says symbol X lives
640      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
641      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
642      we need to look in TU Z to find X.  Fortunately, this is akin to
643      DW_TAG_imported_unit, so we just use the same mechanism: For
644      .gdb_index version <=7 this also records the TUs that the CU referred
645      to.  Concurrently with this change gdb was modified to emit version 8
646      indices so we only pay a price for gold generated indices.
647      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
648   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
649 };
650
651 /* Entry in the signatured_types hash table.  */
652
653 struct signatured_type
654 {
655   /* The "per_cu" object of this type.
656      This struct is used iff per_cu.is_debug_types.
657      N.B.: This is the first member so that it's easy to convert pointers
658      between them.  */
659   struct dwarf2_per_cu_data per_cu;
660
661   /* The type's signature.  */
662   ULONGEST signature;
663
664   /* Offset in the TU of the type's DIE, as read from the TU header.
665      If this TU is a DWO stub and the definition lives in a DWO file
666      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
667   cu_offset type_offset_in_tu;
668
669   /* Offset in the section of the type's DIE.
670      If the definition lives in a DWO file, this is the offset in the
671      .debug_types.dwo section.
672      The value is zero until the actual value is known.
673      Zero is otherwise not a valid section offset.  */
674   sect_offset type_offset_in_section;
675
676   /* Type units are grouped by their DW_AT_stmt_list entry so that they
677      can share them.  This points to the containing symtab.  */
678   struct type_unit_group *type_unit_group;
679
680   /* The type.
681      The first time we encounter this type we fully read it in and install it
682      in the symbol tables.  Subsequent times we only need the type.  */
683   struct type *type;
684
685   /* Containing DWO unit.
686      This field is valid iff per_cu.reading_dwo_directly.  */
687   struct dwo_unit *dwo_unit;
688 };
689
690 typedef struct signatured_type *sig_type_ptr;
691 DEF_VEC_P (sig_type_ptr);
692
693 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
694    This includes type_unit_group and quick_file_names.  */
695
696 struct stmt_list_hash
697 {
698   /* The DWO unit this table is from or NULL if there is none.  */
699   struct dwo_unit *dwo_unit;
700
701   /* Offset in .debug_line or .debug_line.dwo.  */
702   sect_offset line_offset;
703 };
704
705 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
706    an object of this type.  */
707
708 struct type_unit_group
709 {
710   /* dwarf2read.c's main "handle" on a TU symtab.
711      To simplify things we create an artificial CU that "includes" all the
712      type units using this stmt_list so that the rest of the code still has
713      a "per_cu" handle on the symtab.
714      This PER_CU is recognized by having no section.  */
715 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
716   struct dwarf2_per_cu_data per_cu;
717
718   /* The TUs that share this DW_AT_stmt_list entry.
719      This is added to while parsing type units to build partial symtabs,
720      and is deleted afterwards and not used again.  */
721   VEC (sig_type_ptr) *tus;
722
723   /* The primary symtab.
724      Type units in a group needn't all be defined in the same source file,
725      so we create an essentially anonymous symtab as the primary symtab.  */
726   struct symtab *primary_symtab;
727
728   /* The data used to construct the hash key.  */
729   struct stmt_list_hash hash;
730
731   /* The number of symtabs from the line header.
732      The value here must match line_header.num_file_names.  */
733   unsigned int num_symtabs;
734
735   /* The symbol tables for this TU (obtained from the files listed in
736      DW_AT_stmt_list).
737      WARNING: The order of entries here must match the order of entries
738      in the line header.  After the first TU using this type_unit_group, the
739      line header for the subsequent TUs is recreated from this.  This is done
740      because we need to use the same symtabs for each TU using the same
741      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
742      there's no guarantee the line header doesn't have duplicate entries.  */
743   struct symtab **symtabs;
744 };
745
746 /* These sections are what may appear in a (real or virtual) DWO file.  */
747
748 struct dwo_sections
749 {
750   struct dwarf2_section_info abbrev;
751   struct dwarf2_section_info line;
752   struct dwarf2_section_info loc;
753   struct dwarf2_section_info macinfo;
754   struct dwarf2_section_info macro;
755   struct dwarf2_section_info str;
756   struct dwarf2_section_info str_offsets;
757   /* In the case of a virtual DWO file, these two are unused.  */
758   struct dwarf2_section_info info;
759   VEC (dwarf2_section_info_def) *types;
760 };
761
762 /* CUs/TUs in DWP/DWO files.  */
763
764 struct dwo_unit
765 {
766   /* Backlink to the containing struct dwo_file.  */
767   struct dwo_file *dwo_file;
768
769   /* The "id" that distinguishes this CU/TU.
770      .debug_info calls this "dwo_id", .debug_types calls this "signature".
771      Since signatures came first, we stick with it for consistency.  */
772   ULONGEST signature;
773
774   /* The section this CU/TU lives in, in the DWO file.  */
775   struct dwarf2_section_info *section;
776
777   /* Same as dwarf2_per_cu_data:{offset,length} but in the DWO section.  */
778   sect_offset offset;
779   unsigned int length;
780
781   /* For types, offset in the type's DIE of the type defined by this TU.  */
782   cu_offset type_offset_in_tu;
783 };
784
785 /* include/dwarf2.h defines the DWP section codes.
786    It defines a max value but it doesn't define a min value, which we
787    use for error checking, so provide one.  */
788
789 enum dwp_v2_section_ids
790 {
791   DW_SECT_MIN = 1
792 };
793
794 /* Data for one DWO file.
795
796    This includes virtual DWO files (a virtual DWO file is a DWO file as it
797    appears in a DWP file).  DWP files don't really have DWO files per se -
798    comdat folding of types "loses" the DWO file they came from, and from
799    a high level view DWP files appear to contain a mass of random types.
800    However, to maintain consistency with the non-DWP case we pretend DWP
801    files contain virtual DWO files, and we assign each TU with one virtual
802    DWO file (generally based on the line and abbrev section offsets -
803    a heuristic that seems to work in practice).  */
804
805 struct dwo_file
806 {
807   /* The DW_AT_GNU_dwo_name attribute.
808      For virtual DWO files the name is constructed from the section offsets
809      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
810      from related CU+TUs.  */
811   const char *dwo_name;
812
813   /* The DW_AT_comp_dir attribute.  */
814   const char *comp_dir;
815
816   /* The bfd, when the file is open.  Otherwise this is NULL.
817      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
818   bfd *dbfd;
819
820   /* The sections that make up this DWO file.
821      Remember that for virtual DWO files in DWP V2, these are virtual
822      sections (for lack of a better name).  */
823   struct dwo_sections sections;
824
825   /* The CU in the file.
826      We only support one because having more than one requires hacking the
827      dwo_name of each to match, which is highly unlikely to happen.
828      Doing this means all TUs can share comp_dir: We also assume that
829      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
830   struct dwo_unit *cu;
831
832   /* Table of TUs in the file.
833      Each element is a struct dwo_unit.  */
834   htab_t tus;
835 };
836
837 /* These sections are what may appear in a DWP file.  */
838
839 struct dwp_sections
840 {
841   /* These are used by both DWP version 1 and 2.  */
842   struct dwarf2_section_info str;
843   struct dwarf2_section_info cu_index;
844   struct dwarf2_section_info tu_index;
845
846   /* These are only used by DWP version 2 files.
847      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
848      sections are referenced by section number, and are not recorded here.
849      In DWP version 2 there is at most one copy of all these sections, each
850      section being (effectively) comprised of the concatenation of all of the
851      individual sections that exist in the version 1 format.
852      To keep the code simple we treat each of these concatenated pieces as a
853      section itself (a virtual section?).  */
854   struct dwarf2_section_info abbrev;
855   struct dwarf2_section_info info;
856   struct dwarf2_section_info line;
857   struct dwarf2_section_info loc;
858   struct dwarf2_section_info macinfo;
859   struct dwarf2_section_info macro;
860   struct dwarf2_section_info str_offsets;
861   struct dwarf2_section_info types;
862 };
863
864 /* These sections are what may appear in a virtual DWO file in DWP version 1.
865    A virtual DWO file is a DWO file as it appears in a DWP file.  */
866
867 struct virtual_v1_dwo_sections
868 {
869   struct dwarf2_section_info abbrev;
870   struct dwarf2_section_info line;
871   struct dwarf2_section_info loc;
872   struct dwarf2_section_info macinfo;
873   struct dwarf2_section_info macro;
874   struct dwarf2_section_info str_offsets;
875   /* Each DWP hash table entry records one CU or one TU.
876      That is recorded here, and copied to dwo_unit.section.  */
877   struct dwarf2_section_info info_or_types;
878 };
879
880 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
881    In version 2, the sections of the DWO files are concatenated together
882    and stored in one section of that name.  Thus each ELF section contains
883    several "virtual" sections.  */
884
885 struct virtual_v2_dwo_sections
886 {
887   bfd_size_type abbrev_offset;
888   bfd_size_type abbrev_size;
889
890   bfd_size_type line_offset;
891   bfd_size_type line_size;
892
893   bfd_size_type loc_offset;
894   bfd_size_type loc_size;
895
896   bfd_size_type macinfo_offset;
897   bfd_size_type macinfo_size;
898
899   bfd_size_type macro_offset;
900   bfd_size_type macro_size;
901
902   bfd_size_type str_offsets_offset;
903   bfd_size_type str_offsets_size;
904
905   /* Each DWP hash table entry records one CU or one TU.
906      That is recorded here, and copied to dwo_unit.section.  */
907   bfd_size_type info_or_types_offset;
908   bfd_size_type info_or_types_size;
909 };
910
911 /* Contents of DWP hash tables.  */
912
913 struct dwp_hash_table
914 {
915   uint32_t version, nr_columns;
916   uint32_t nr_units, nr_slots;
917   const gdb_byte *hash_table, *unit_table;
918   union
919   {
920     struct
921     {
922       const gdb_byte *indices;
923     } v1;
924     struct
925     {
926       /* This is indexed by column number and gives the id of the section
927          in that column.  */
928 #define MAX_NR_V2_DWO_SECTIONS \
929   (1 /* .debug_info or .debug_types */ \
930    + 1 /* .debug_abbrev */ \
931    + 1 /* .debug_line */ \
932    + 1 /* .debug_loc */ \
933    + 1 /* .debug_str_offsets */ \
934    + 1 /* .debug_macro or .debug_macinfo */)
935       int section_ids[MAX_NR_V2_DWO_SECTIONS];
936       const gdb_byte *offsets;
937       const gdb_byte *sizes;
938     } v2;
939   } section_pool;
940 };
941
942 /* Data for one DWP file.  */
943
944 struct dwp_file
945 {
946   /* Name of the file.  */
947   const char *name;
948
949   /* File format version.  */
950   int version;
951
952   /* The bfd.  */
953   bfd *dbfd;
954
955   /* Section info for this file.  */
956   struct dwp_sections sections;
957
958   /* Table of CUs in the file.  */
959   const struct dwp_hash_table *cus;
960
961   /* Table of TUs in the file.  */
962   const struct dwp_hash_table *tus;
963
964   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
965   htab_t loaded_cus;
966   htab_t loaded_tus;
967
968   /* Table to map ELF section numbers to their sections.
969      This is only needed for the DWP V1 file format.  */
970   unsigned int num_sections;
971   asection **elf_sections;
972 };
973
974 /* This represents a '.dwz' file.  */
975
976 struct dwz_file
977 {
978   /* A dwz file can only contain a few sections.  */
979   struct dwarf2_section_info abbrev;
980   struct dwarf2_section_info info;
981   struct dwarf2_section_info str;
982   struct dwarf2_section_info line;
983   struct dwarf2_section_info macro;
984   struct dwarf2_section_info gdb_index;
985
986   /* The dwz's BFD.  */
987   bfd *dwz_bfd;
988 };
989
990 /* Struct used to pass misc. parameters to read_die_and_children, et
991    al.  which are used for both .debug_info and .debug_types dies.
992    All parameters here are unchanging for the life of the call.  This
993    struct exists to abstract away the constant parameters of die reading.  */
994
995 struct die_reader_specs
996 {
997   /* The bfd of die_section.  */
998   bfd* abfd;
999
1000   /* The CU of the DIE we are parsing.  */
1001   struct dwarf2_cu *cu;
1002
1003   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1004   struct dwo_file *dwo_file;
1005
1006   /* The section the die comes from.
1007      This is either .debug_info or .debug_types, or the .dwo variants.  */
1008   struct dwarf2_section_info *die_section;
1009
1010   /* die_section->buffer.  */
1011   const gdb_byte *buffer;
1012
1013   /* The end of the buffer.  */
1014   const gdb_byte *buffer_end;
1015
1016   /* The value of the DW_AT_comp_dir attribute.  */
1017   const char *comp_dir;
1018 };
1019
1020 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1021 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1022                                       const gdb_byte *info_ptr,
1023                                       struct die_info *comp_unit_die,
1024                                       int has_children,
1025                                       void *data);
1026
1027 /* The line number information for a compilation unit (found in the
1028    .debug_line section) begins with a "statement program header",
1029    which contains the following information.  */
1030 struct line_header
1031 {
1032   unsigned int total_length;
1033   unsigned short version;
1034   unsigned int header_length;
1035   unsigned char minimum_instruction_length;
1036   unsigned char maximum_ops_per_instruction;
1037   unsigned char default_is_stmt;
1038   int line_base;
1039   unsigned char line_range;
1040   unsigned char opcode_base;
1041
1042   /* standard_opcode_lengths[i] is the number of operands for the
1043      standard opcode whose value is i.  This means that
1044      standard_opcode_lengths[0] is unused, and the last meaningful
1045      element is standard_opcode_lengths[opcode_base - 1].  */
1046   unsigned char *standard_opcode_lengths;
1047
1048   /* The include_directories table.  NOTE!  These strings are not
1049      allocated with xmalloc; instead, they are pointers into
1050      debug_line_buffer.  If you try to free them, `free' will get
1051      indigestion.  */
1052   unsigned int num_include_dirs, include_dirs_size;
1053   const char **include_dirs;
1054
1055   /* The file_names table.  NOTE!  These strings are not allocated
1056      with xmalloc; instead, they are pointers into debug_line_buffer.
1057      Don't try to free them directly.  */
1058   unsigned int num_file_names, file_names_size;
1059   struct file_entry
1060   {
1061     const char *name;
1062     unsigned int dir_index;
1063     unsigned int mod_time;
1064     unsigned int length;
1065     int included_p; /* Non-zero if referenced by the Line Number Program.  */
1066     struct symtab *symtab; /* The associated symbol table, if any.  */
1067   } *file_names;
1068
1069   /* The start and end of the statement program following this
1070      header.  These point into dwarf2_per_objfile->line_buffer.  */
1071   const gdb_byte *statement_program_start, *statement_program_end;
1072 };
1073
1074 /* When we construct a partial symbol table entry we only
1075    need this much information.  */
1076 struct partial_die_info
1077   {
1078     /* Offset of this DIE.  */
1079     sect_offset offset;
1080
1081     /* DWARF-2 tag for this DIE.  */
1082     ENUM_BITFIELD(dwarf_tag) tag : 16;
1083
1084     /* Assorted flags describing the data found in this DIE.  */
1085     unsigned int has_children : 1;
1086     unsigned int is_external : 1;
1087     unsigned int is_declaration : 1;
1088     unsigned int has_type : 1;
1089     unsigned int has_specification : 1;
1090     unsigned int has_pc_info : 1;
1091     unsigned int may_be_inlined : 1;
1092
1093     /* Flag set if the SCOPE field of this structure has been
1094        computed.  */
1095     unsigned int scope_set : 1;
1096
1097     /* Flag set if the DIE has a byte_size attribute.  */
1098     unsigned int has_byte_size : 1;
1099
1100     /* Flag set if any of the DIE's children are template arguments.  */
1101     unsigned int has_template_arguments : 1;
1102
1103     /* Flag set if fixup_partial_die has been called on this die.  */
1104     unsigned int fixup_called : 1;
1105
1106     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1107     unsigned int is_dwz : 1;
1108
1109     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1110     unsigned int spec_is_dwz : 1;
1111
1112     /* The name of this DIE.  Normally the value of DW_AT_name, but
1113        sometimes a default name for unnamed DIEs.  */
1114     const char *name;
1115
1116     /* The linkage name, if present.  */
1117     const char *linkage_name;
1118
1119     /* The scope to prepend to our children.  This is generally
1120        allocated on the comp_unit_obstack, so will disappear
1121        when this compilation unit leaves the cache.  */
1122     const char *scope;
1123
1124     /* Some data associated with the partial DIE.  The tag determines
1125        which field is live.  */
1126     union
1127     {
1128       /* The location description associated with this DIE, if any.  */
1129       struct dwarf_block *locdesc;
1130       /* The offset of an import, for DW_TAG_imported_unit.  */
1131       sect_offset offset;
1132     } d;
1133
1134     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1135     CORE_ADDR lowpc;
1136     CORE_ADDR highpc;
1137
1138     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1139        DW_AT_sibling, if any.  */
1140     /* NOTE: This member isn't strictly necessary, read_partial_die could
1141        return DW_AT_sibling values to its caller load_partial_dies.  */
1142     const gdb_byte *sibling;
1143
1144     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1145        DW_AT_specification (or DW_AT_abstract_origin or
1146        DW_AT_extension).  */
1147     sect_offset spec_offset;
1148
1149     /* Pointers to this DIE's parent, first child, and next sibling,
1150        if any.  */
1151     struct partial_die_info *die_parent, *die_child, *die_sibling;
1152   };
1153
1154 /* This data structure holds the information of an abbrev.  */
1155 struct abbrev_info
1156   {
1157     unsigned int number;        /* number identifying abbrev */
1158     enum dwarf_tag tag;         /* dwarf tag */
1159     unsigned short has_children;                /* boolean */
1160     unsigned short num_attrs;   /* number of attributes */
1161     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1162     struct abbrev_info *next;   /* next in chain */
1163   };
1164
1165 struct attr_abbrev
1166   {
1167     ENUM_BITFIELD(dwarf_attribute) name : 16;
1168     ENUM_BITFIELD(dwarf_form) form : 16;
1169   };
1170
1171 /* Size of abbrev_table.abbrev_hash_table.  */
1172 #define ABBREV_HASH_SIZE 121
1173
1174 /* Top level data structure to contain an abbreviation table.  */
1175
1176 struct abbrev_table
1177 {
1178   /* Where the abbrev table came from.
1179      This is used as a sanity check when the table is used.  */
1180   sect_offset offset;
1181
1182   /* Storage for the abbrev table.  */
1183   struct obstack abbrev_obstack;
1184
1185   /* Hash table of abbrevs.
1186      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1187      It could be statically allocated, but the previous code didn't so we
1188      don't either.  */
1189   struct abbrev_info **abbrevs;
1190 };
1191
1192 /* Attributes have a name and a value.  */
1193 struct attribute
1194   {
1195     ENUM_BITFIELD(dwarf_attribute) name : 16;
1196     ENUM_BITFIELD(dwarf_form) form : 15;
1197
1198     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1199        field should be in u.str (existing only for DW_STRING) but it is kept
1200        here for better struct attribute alignment.  */
1201     unsigned int string_is_canonical : 1;
1202
1203     union
1204       {
1205         const char *str;
1206         struct dwarf_block *blk;
1207         ULONGEST unsnd;
1208         LONGEST snd;
1209         CORE_ADDR addr;
1210         ULONGEST signature;
1211       }
1212     u;
1213   };
1214
1215 /* This data structure holds a complete die structure.  */
1216 struct die_info
1217   {
1218     /* DWARF-2 tag for this DIE.  */
1219     ENUM_BITFIELD(dwarf_tag) tag : 16;
1220
1221     /* Number of attributes */
1222     unsigned char num_attrs;
1223
1224     /* True if we're presently building the full type name for the
1225        type derived from this DIE.  */
1226     unsigned char building_fullname : 1;
1227
1228     /* Abbrev number */
1229     unsigned int abbrev;
1230
1231     /* Offset in .debug_info or .debug_types section.  */
1232     sect_offset offset;
1233
1234     /* The dies in a compilation unit form an n-ary tree.  PARENT
1235        points to this die's parent; CHILD points to the first child of
1236        this node; and all the children of a given node are chained
1237        together via their SIBLING fields.  */
1238     struct die_info *child;     /* Its first child, if any.  */
1239     struct die_info *sibling;   /* Its next sibling, if any.  */
1240     struct die_info *parent;    /* Its parent, if any.  */
1241
1242     /* An array of attributes, with NUM_ATTRS elements.  There may be
1243        zero, but it's not common and zero-sized arrays are not
1244        sufficiently portable C.  */
1245     struct attribute attrs[1];
1246   };
1247
1248 /* Get at parts of an attribute structure.  */
1249
1250 #define DW_STRING(attr)    ((attr)->u.str)
1251 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1252 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1253 #define DW_BLOCK(attr)     ((attr)->u.blk)
1254 #define DW_SND(attr)       ((attr)->u.snd)
1255 #define DW_ADDR(attr)      ((attr)->u.addr)
1256 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1257
1258 /* Blocks are a bunch of untyped bytes.  */
1259 struct dwarf_block
1260   {
1261     size_t size;
1262
1263     /* Valid only if SIZE is not zero.  */
1264     const gdb_byte *data;
1265   };
1266
1267 #ifndef ATTR_ALLOC_CHUNK
1268 #define ATTR_ALLOC_CHUNK 4
1269 #endif
1270
1271 /* Allocate fields for structs, unions and enums in this size.  */
1272 #ifndef DW_FIELD_ALLOC_CHUNK
1273 #define DW_FIELD_ALLOC_CHUNK 4
1274 #endif
1275
1276 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1277    but this would require a corresponding change in unpack_field_as_long
1278    and friends.  */
1279 static int bits_per_byte = 8;
1280
1281 /* The routines that read and process dies for a C struct or C++ class
1282    pass lists of data member fields and lists of member function fields
1283    in an instance of a field_info structure, as defined below.  */
1284 struct field_info
1285   {
1286     /* List of data member and baseclasses fields.  */
1287     struct nextfield
1288       {
1289         struct nextfield *next;
1290         int accessibility;
1291         int virtuality;
1292         struct field field;
1293       }
1294      *fields, *baseclasses;
1295
1296     /* Number of fields (including baseclasses).  */
1297     int nfields;
1298
1299     /* Number of baseclasses.  */
1300     int nbaseclasses;
1301
1302     /* Set if the accesibility of one of the fields is not public.  */
1303     int non_public_fields;
1304
1305     /* Member function fields array, entries are allocated in the order they
1306        are encountered in the object file.  */
1307     struct nextfnfield
1308       {
1309         struct nextfnfield *next;
1310         struct fn_field fnfield;
1311       }
1312      *fnfields;
1313
1314     /* Member function fieldlist array, contains name of possibly overloaded
1315        member function, number of overloaded member functions and a pointer
1316        to the head of the member function field chain.  */
1317     struct fnfieldlist
1318       {
1319         const char *name;
1320         int length;
1321         struct nextfnfield *head;
1322       }
1323      *fnfieldlists;
1324
1325     /* Number of entries in the fnfieldlists array.  */
1326     int nfnfields;
1327
1328     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1329        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1330     struct typedef_field_list
1331       {
1332         struct typedef_field field;
1333         struct typedef_field_list *next;
1334       }
1335     *typedef_field_list;
1336     unsigned typedef_field_list_count;
1337   };
1338
1339 /* One item on the queue of compilation units to read in full symbols
1340    for.  */
1341 struct dwarf2_queue_item
1342 {
1343   struct dwarf2_per_cu_data *per_cu;
1344   enum language pretend_language;
1345   struct dwarf2_queue_item *next;
1346 };
1347
1348 /* The current queue.  */
1349 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1350
1351 /* Loaded secondary compilation units are kept in memory until they
1352    have not been referenced for the processing of this many
1353    compilation units.  Set this to zero to disable caching.  Cache
1354    sizes of up to at least twenty will improve startup time for
1355    typical inter-CU-reference binaries, at an obvious memory cost.  */
1356 static int dwarf2_max_cache_age = 5;
1357 static void
1358 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1359                            struct cmd_list_element *c, const char *value)
1360 {
1361   fprintf_filtered (file, _("The upper bound on the age of cached "
1362                             "dwarf2 compilation units is %s.\n"),
1363                     value);
1364 }
1365 \f
1366 /* local function prototypes */
1367
1368 static const char *get_section_name (const struct dwarf2_section_info *);
1369
1370 static const char *get_section_file_name (const struct dwarf2_section_info *);
1371
1372 static void dwarf2_locate_sections (bfd *, asection *, void *);
1373
1374 static void dwarf2_find_base_address (struct die_info *die,
1375                                       struct dwarf2_cu *cu);
1376
1377 static struct partial_symtab *create_partial_symtab
1378   (struct dwarf2_per_cu_data *per_cu, const char *name);
1379
1380 static void dwarf2_build_psymtabs_hard (struct objfile *);
1381
1382 static void scan_partial_symbols (struct partial_die_info *,
1383                                   CORE_ADDR *, CORE_ADDR *,
1384                                   int, struct dwarf2_cu *);
1385
1386 static void add_partial_symbol (struct partial_die_info *,
1387                                 struct dwarf2_cu *);
1388
1389 static void add_partial_namespace (struct partial_die_info *pdi,
1390                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1391                                    int need_pc, struct dwarf2_cu *cu);
1392
1393 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1394                                 CORE_ADDR *highpc, int need_pc,
1395                                 struct dwarf2_cu *cu);
1396
1397 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1398                                      struct dwarf2_cu *cu);
1399
1400 static void add_partial_subprogram (struct partial_die_info *pdi,
1401                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1402                                     int need_pc, struct dwarf2_cu *cu);
1403
1404 static void dwarf2_read_symtab (struct partial_symtab *,
1405                                 struct objfile *);
1406
1407 static void psymtab_to_symtab_1 (struct partial_symtab *);
1408
1409 static struct abbrev_info *abbrev_table_lookup_abbrev
1410   (const struct abbrev_table *, unsigned int);
1411
1412 static struct abbrev_table *abbrev_table_read_table
1413   (struct dwarf2_section_info *, sect_offset);
1414
1415 static void abbrev_table_free (struct abbrev_table *);
1416
1417 static void abbrev_table_free_cleanup (void *);
1418
1419 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1420                                  struct dwarf2_section_info *);
1421
1422 static void dwarf2_free_abbrev_table (void *);
1423
1424 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1425
1426 static struct partial_die_info *load_partial_dies
1427   (const struct die_reader_specs *, const gdb_byte *, int);
1428
1429 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1430                                          struct partial_die_info *,
1431                                          struct abbrev_info *,
1432                                          unsigned int,
1433                                          const gdb_byte *);
1434
1435 static struct partial_die_info *find_partial_die (sect_offset, int,
1436                                                   struct dwarf2_cu *);
1437
1438 static void fixup_partial_die (struct partial_die_info *,
1439                                struct dwarf2_cu *);
1440
1441 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1442                                        struct attribute *, struct attr_abbrev *,
1443                                        const gdb_byte *);
1444
1445 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1446
1447 static int read_1_signed_byte (bfd *, const gdb_byte *);
1448
1449 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1450
1451 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1452
1453 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1454
1455 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1456                                unsigned int *);
1457
1458 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1459
1460 static LONGEST read_checked_initial_length_and_offset
1461   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1462    unsigned int *, unsigned int *);
1463
1464 static LONGEST read_offset (bfd *, const gdb_byte *,
1465                             const struct comp_unit_head *,
1466                             unsigned int *);
1467
1468 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1469
1470 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1471                                        sect_offset);
1472
1473 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1474
1475 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1476
1477 static const char *read_indirect_string (bfd *, const gdb_byte *,
1478                                          const struct comp_unit_head *,
1479                                          unsigned int *);
1480
1481 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1482
1483 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1484
1485 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1486
1487 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1488                                               const gdb_byte *,
1489                                               unsigned int *);
1490
1491 static const char *read_str_index (const struct die_reader_specs *reader,
1492                                    struct dwarf2_cu *cu, ULONGEST str_index);
1493
1494 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1495
1496 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1497                                       struct dwarf2_cu *);
1498
1499 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1500                                                 unsigned int);
1501
1502 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1503                                struct dwarf2_cu *cu);
1504
1505 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1506
1507 static struct die_info *die_specification (struct die_info *die,
1508                                            struct dwarf2_cu **);
1509
1510 static void free_line_header (struct line_header *lh);
1511
1512 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1513                                                      struct dwarf2_cu *cu);
1514
1515 static void dwarf_decode_lines (struct line_header *, const char *,
1516                                 struct dwarf2_cu *, struct partial_symtab *,
1517                                 int);
1518
1519 static void dwarf2_start_subfile (const char *, const char *, const char *);
1520
1521 static void dwarf2_start_symtab (struct dwarf2_cu *,
1522                                  const char *, const char *, CORE_ADDR);
1523
1524 static struct symbol *new_symbol (struct die_info *, struct type *,
1525                                   struct dwarf2_cu *);
1526
1527 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1528                                        struct dwarf2_cu *, struct symbol *);
1529
1530 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1531                                 struct dwarf2_cu *);
1532
1533 static void dwarf2_const_value_attr (const struct attribute *attr,
1534                                      struct type *type,
1535                                      const char *name,
1536                                      struct obstack *obstack,
1537                                      struct dwarf2_cu *cu, LONGEST *value,
1538                                      const gdb_byte **bytes,
1539                                      struct dwarf2_locexpr_baton **baton);
1540
1541 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1542
1543 static int need_gnat_info (struct dwarf2_cu *);
1544
1545 static struct type *die_descriptive_type (struct die_info *,
1546                                           struct dwarf2_cu *);
1547
1548 static void set_descriptive_type (struct type *, struct die_info *,
1549                                   struct dwarf2_cu *);
1550
1551 static struct type *die_containing_type (struct die_info *,
1552                                          struct dwarf2_cu *);
1553
1554 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1555                                      struct dwarf2_cu *);
1556
1557 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1558
1559 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1560
1561 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1562
1563 static char *typename_concat (struct obstack *obs, const char *prefix,
1564                               const char *suffix, int physname,
1565                               struct dwarf2_cu *cu);
1566
1567 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1568
1569 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1570
1571 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1572
1573 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1574
1575 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1576
1577 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1578                                struct dwarf2_cu *, struct partial_symtab *);
1579
1580 static int dwarf2_get_pc_bounds (struct die_info *,
1581                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1582                                  struct partial_symtab *);
1583
1584 static void get_scope_pc_bounds (struct die_info *,
1585                                  CORE_ADDR *, CORE_ADDR *,
1586                                  struct dwarf2_cu *);
1587
1588 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1589                                         CORE_ADDR, struct dwarf2_cu *);
1590
1591 static void dwarf2_add_field (struct field_info *, struct die_info *,
1592                               struct dwarf2_cu *);
1593
1594 static void dwarf2_attach_fields_to_type (struct field_info *,
1595                                           struct type *, struct dwarf2_cu *);
1596
1597 static void dwarf2_add_member_fn (struct field_info *,
1598                                   struct die_info *, struct type *,
1599                                   struct dwarf2_cu *);
1600
1601 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1602                                              struct type *,
1603                                              struct dwarf2_cu *);
1604
1605 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1606
1607 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1608
1609 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1610
1611 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1612
1613 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1614
1615 static struct type *read_module_type (struct die_info *die,
1616                                       struct dwarf2_cu *cu);
1617
1618 static const char *namespace_name (struct die_info *die,
1619                                    int *is_anonymous, struct dwarf2_cu *);
1620
1621 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1622
1623 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1624
1625 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1626                                                        struct dwarf2_cu *);
1627
1628 static struct die_info *read_die_and_siblings_1
1629   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1630    struct die_info *);
1631
1632 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1633                                                const gdb_byte *info_ptr,
1634                                                const gdb_byte **new_info_ptr,
1635                                                struct die_info *parent);
1636
1637 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1638                                         struct die_info **, const gdb_byte *,
1639                                         int *, int);
1640
1641 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1642                                       struct die_info **, const gdb_byte *,
1643                                       int *);
1644
1645 static void process_die (struct die_info *, struct dwarf2_cu *);
1646
1647 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1648                                              struct obstack *);
1649
1650 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1651
1652 static const char *dwarf2_full_name (const char *name,
1653                                      struct die_info *die,
1654                                      struct dwarf2_cu *cu);
1655
1656 static const char *dwarf2_physname (const char *name, struct die_info *die,
1657                                     struct dwarf2_cu *cu);
1658
1659 static struct die_info *dwarf2_extension (struct die_info *die,
1660                                           struct dwarf2_cu **);
1661
1662 static const char *dwarf_tag_name (unsigned int);
1663
1664 static const char *dwarf_attr_name (unsigned int);
1665
1666 static const char *dwarf_form_name (unsigned int);
1667
1668 static char *dwarf_bool_name (unsigned int);
1669
1670 static const char *dwarf_type_encoding_name (unsigned int);
1671
1672 static struct die_info *sibling_die (struct die_info *);
1673
1674 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1675
1676 static void dump_die_for_error (struct die_info *);
1677
1678 static void dump_die_1 (struct ui_file *, int level, int max_level,
1679                         struct die_info *);
1680
1681 /*static*/ void dump_die (struct die_info *, int max_level);
1682
1683 static void store_in_ref_table (struct die_info *,
1684                                 struct dwarf2_cu *);
1685
1686 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1687
1688 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1689
1690 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1691                                                const struct attribute *,
1692                                                struct dwarf2_cu **);
1693
1694 static struct die_info *follow_die_ref (struct die_info *,
1695                                         const struct attribute *,
1696                                         struct dwarf2_cu **);
1697
1698 static struct die_info *follow_die_sig (struct die_info *,
1699                                         const struct attribute *,
1700                                         struct dwarf2_cu **);
1701
1702 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1703                                          struct dwarf2_cu *);
1704
1705 static struct type *get_DW_AT_signature_type (struct die_info *,
1706                                               const struct attribute *,
1707                                               struct dwarf2_cu *);
1708
1709 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1710
1711 static void read_signatured_type (struct signatured_type *);
1712
1713 static struct type_unit_group *get_type_unit_group
1714     (struct dwarf2_cu *, const struct attribute *);
1715
1716 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1717
1718 /* memory allocation interface */
1719
1720 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1721
1722 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1723
1724 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1725                                  const char *, int);
1726
1727 static int attr_form_is_block (const struct attribute *);
1728
1729 static int attr_form_is_section_offset (const struct attribute *);
1730
1731 static int attr_form_is_constant (const struct attribute *);
1732
1733 static int attr_form_is_ref (const struct attribute *);
1734
1735 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1736                                    struct dwarf2_loclist_baton *baton,
1737                                    const struct attribute *attr);
1738
1739 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1740                                          struct symbol *sym,
1741                                          struct dwarf2_cu *cu,
1742                                          int is_block);
1743
1744 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1745                                      const gdb_byte *info_ptr,
1746                                      struct abbrev_info *abbrev);
1747
1748 static void free_stack_comp_unit (void *);
1749
1750 static hashval_t partial_die_hash (const void *item);
1751
1752 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1753
1754 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1755   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1756
1757 static void init_one_comp_unit (struct dwarf2_cu *cu,
1758                                 struct dwarf2_per_cu_data *per_cu);
1759
1760 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1761                                    struct die_info *comp_unit_die,
1762                                    enum language pretend_language);
1763
1764 static void free_heap_comp_unit (void *);
1765
1766 static void free_cached_comp_units (void *);
1767
1768 static void age_cached_comp_units (void);
1769
1770 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1771
1772 static struct type *set_die_type (struct die_info *, struct type *,
1773                                   struct dwarf2_cu *);
1774
1775 static void create_all_comp_units (struct objfile *);
1776
1777 static int create_all_type_units (struct objfile *);
1778
1779 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1780                                  enum language);
1781
1782 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1783                                     enum language);
1784
1785 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1786                                     enum language);
1787
1788 static void dwarf2_add_dependence (struct dwarf2_cu *,
1789                                    struct dwarf2_per_cu_data *);
1790
1791 static void dwarf2_mark (struct dwarf2_cu *);
1792
1793 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1794
1795 static struct type *get_die_type_at_offset (sect_offset,
1796                                             struct dwarf2_per_cu_data *);
1797
1798 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1799
1800 static void dwarf2_release_queue (void *dummy);
1801
1802 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1803                              enum language pretend_language);
1804
1805 static void process_queue (void);
1806
1807 static void find_file_and_directory (struct die_info *die,
1808                                      struct dwarf2_cu *cu,
1809                                      const char **name, const char **comp_dir);
1810
1811 static char *file_full_name (int file, struct line_header *lh,
1812                              const char *comp_dir);
1813
1814 static const gdb_byte *read_and_check_comp_unit_head
1815   (struct comp_unit_head *header,
1816    struct dwarf2_section_info *section,
1817    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1818    int is_debug_types_section);
1819
1820 static void init_cutu_and_read_dies
1821   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1822    int use_existing_cu, int keep,
1823    die_reader_func_ftype *die_reader_func, void *data);
1824
1825 static void init_cutu_and_read_dies_simple
1826   (struct dwarf2_per_cu_data *this_cu,
1827    die_reader_func_ftype *die_reader_func, void *data);
1828
1829 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1830
1831 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1832
1833 static struct dwo_unit *lookup_dwo_unit_in_dwp
1834   (struct dwp_file *dwp_file, const char *comp_dir,
1835    ULONGEST signature, int is_debug_types);
1836
1837 static struct dwp_file *get_dwp_file (void);
1838
1839 static struct dwo_unit *lookup_dwo_comp_unit
1840   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1841
1842 static struct dwo_unit *lookup_dwo_type_unit
1843   (struct signatured_type *, const char *, const char *);
1844
1845 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1846
1847 static void free_dwo_file_cleanup (void *);
1848
1849 static void process_cu_includes (void);
1850
1851 static void check_producer (struct dwarf2_cu *cu);
1852 \f
1853 /* Various complaints about symbol reading that don't abort the process.  */
1854
1855 static void
1856 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1857 {
1858   complaint (&symfile_complaints,
1859              _("statement list doesn't fit in .debug_line section"));
1860 }
1861
1862 static void
1863 dwarf2_debug_line_missing_file_complaint (void)
1864 {
1865   complaint (&symfile_complaints,
1866              _(".debug_line section has line data without a file"));
1867 }
1868
1869 static void
1870 dwarf2_debug_line_missing_end_sequence_complaint (void)
1871 {
1872   complaint (&symfile_complaints,
1873              _(".debug_line section has line "
1874                "program sequence without an end"));
1875 }
1876
1877 static void
1878 dwarf2_complex_location_expr_complaint (void)
1879 {
1880   complaint (&symfile_complaints, _("location expression too complex"));
1881 }
1882
1883 static void
1884 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1885                                               int arg3)
1886 {
1887   complaint (&symfile_complaints,
1888              _("const value length mismatch for '%s', got %d, expected %d"),
1889              arg1, arg2, arg3);
1890 }
1891
1892 static void
1893 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1894 {
1895   complaint (&symfile_complaints,
1896              _("debug info runs off end of %s section"
1897                " [in module %s]"),
1898              get_section_name (section),
1899              get_section_file_name (section));
1900 }
1901
1902 static void
1903 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1904 {
1905   complaint (&symfile_complaints,
1906              _("macro debug info contains a "
1907                "malformed macro definition:\n`%s'"),
1908              arg1);
1909 }
1910
1911 static void
1912 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1913 {
1914   complaint (&symfile_complaints,
1915              _("invalid attribute class or form for '%s' in '%s'"),
1916              arg1, arg2);
1917 }
1918 \f
1919 #if WORDS_BIGENDIAN
1920
1921 /* Convert VALUE between big- and little-endian.  */
1922 static offset_type
1923 byte_swap (offset_type value)
1924 {
1925   offset_type result;
1926
1927   result = (value & 0xff) << 24;
1928   result |= (value & 0xff00) << 8;
1929   result |= (value & 0xff0000) >> 8;
1930   result |= (value & 0xff000000) >> 24;
1931   return result;
1932 }
1933
1934 #define MAYBE_SWAP(V)  byte_swap (V)
1935
1936 #else
1937 #define MAYBE_SWAP(V) (V)
1938 #endif /* WORDS_BIGENDIAN */
1939
1940 /* The suffix for an index file.  */
1941 #define INDEX_SUFFIX ".gdb-index"
1942
1943 /* Try to locate the sections we need for DWARF 2 debugging
1944    information and return true if we have enough to do something.
1945    NAMES points to the dwarf2 section names, or is NULL if the standard
1946    ELF names are used.  */
1947
1948 int
1949 dwarf2_has_info (struct objfile *objfile,
1950                  const struct dwarf2_debug_sections *names)
1951 {
1952   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1953   if (!dwarf2_per_objfile)
1954     {
1955       /* Initialize per-objfile state.  */
1956       struct dwarf2_per_objfile *data
1957         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1958
1959       memset (data, 0, sizeof (*data));
1960       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1961       dwarf2_per_objfile = data;
1962
1963       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1964                              (void *) names);
1965       dwarf2_per_objfile->objfile = objfile;
1966     }
1967   return (!dwarf2_per_objfile->info.is_virtual
1968           && dwarf2_per_objfile->info.s.asection != NULL
1969           && !dwarf2_per_objfile->abbrev.is_virtual
1970           && dwarf2_per_objfile->abbrev.s.asection != NULL);
1971 }
1972
1973 /* Return the containing section of virtual section SECTION.  */
1974
1975 static struct dwarf2_section_info *
1976 get_containing_section (const struct dwarf2_section_info *section)
1977 {
1978   gdb_assert (section->is_virtual);
1979   return section->s.containing_section;
1980 }
1981
1982 /* Return the bfd owner of SECTION.  */
1983
1984 static struct bfd *
1985 get_section_bfd_owner (const struct dwarf2_section_info *section)
1986 {
1987   if (section->is_virtual)
1988     {
1989       section = get_containing_section (section);
1990       gdb_assert (!section->is_virtual);
1991     }
1992   return section->s.asection->owner;
1993 }
1994
1995 /* Return the bfd section of SECTION.
1996    Returns NULL if the section is not present.  */
1997
1998 static asection *
1999 get_section_bfd_section (const struct dwarf2_section_info *section)
2000 {
2001   if (section->is_virtual)
2002     {
2003       section = get_containing_section (section);
2004       gdb_assert (!section->is_virtual);
2005     }
2006   return section->s.asection;
2007 }
2008
2009 /* Return the name of SECTION.  */
2010
2011 static const char *
2012 get_section_name (const struct dwarf2_section_info *section)
2013 {
2014   asection *sectp = get_section_bfd_section (section);
2015
2016   gdb_assert (sectp != NULL);
2017   return bfd_section_name (get_section_bfd_owner (section), sectp);
2018 }
2019
2020 /* Return the name of the file SECTION is in.  */
2021
2022 static const char *
2023 get_section_file_name (const struct dwarf2_section_info *section)
2024 {
2025   bfd *abfd = get_section_bfd_owner (section);
2026
2027   return bfd_get_filename (abfd);
2028 }
2029
2030 /* Return the id of SECTION.
2031    Returns 0 if SECTION doesn't exist.  */
2032
2033 static int
2034 get_section_id (const struct dwarf2_section_info *section)
2035 {
2036   asection *sectp = get_section_bfd_section (section);
2037
2038   if (sectp == NULL)
2039     return 0;
2040   return sectp->id;
2041 }
2042
2043 /* Return the flags of SECTION.
2044    SECTION (or containing section if this is a virtual section) must exist.  */
2045
2046 static int
2047 get_section_flags (const struct dwarf2_section_info *section)
2048 {
2049   asection *sectp = get_section_bfd_section (section);
2050
2051   gdb_assert (sectp != NULL);
2052   return bfd_get_section_flags (sectp->owner, sectp);
2053 }
2054
2055 /* When loading sections, we look either for uncompressed section or for
2056    compressed section names.  */
2057
2058 static int
2059 section_is_p (const char *section_name,
2060               const struct dwarf2_section_names *names)
2061 {
2062   if (names->normal != NULL
2063       && strcmp (section_name, names->normal) == 0)
2064     return 1;
2065   if (names->compressed != NULL
2066       && strcmp (section_name, names->compressed) == 0)
2067     return 1;
2068   return 0;
2069 }
2070
2071 /* This function is mapped across the sections and remembers the
2072    offset and size of each of the debugging sections we are interested
2073    in.  */
2074
2075 static void
2076 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
2077 {
2078   const struct dwarf2_debug_sections *names;
2079   flagword aflag = bfd_get_section_flags (abfd, sectp);
2080
2081   if (vnames == NULL)
2082     names = &dwarf2_elf_names;
2083   else
2084     names = (const struct dwarf2_debug_sections *) vnames;
2085
2086   if ((aflag & SEC_HAS_CONTENTS) == 0)
2087     {
2088     }
2089   else if (section_is_p (sectp->name, &names->info))
2090     {
2091       dwarf2_per_objfile->info.s.asection = sectp;
2092       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
2093     }
2094   else if (section_is_p (sectp->name, &names->abbrev))
2095     {
2096       dwarf2_per_objfile->abbrev.s.asection = sectp;
2097       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
2098     }
2099   else if (section_is_p (sectp->name, &names->line))
2100     {
2101       dwarf2_per_objfile->line.s.asection = sectp;
2102       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
2103     }
2104   else if (section_is_p (sectp->name, &names->loc))
2105     {
2106       dwarf2_per_objfile->loc.s.asection = sectp;
2107       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
2108     }
2109   else if (section_is_p (sectp->name, &names->macinfo))
2110     {
2111       dwarf2_per_objfile->macinfo.s.asection = sectp;
2112       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
2113     }
2114   else if (section_is_p (sectp->name, &names->macro))
2115     {
2116       dwarf2_per_objfile->macro.s.asection = sectp;
2117       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
2118     }
2119   else if (section_is_p (sectp->name, &names->str))
2120     {
2121       dwarf2_per_objfile->str.s.asection = sectp;
2122       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
2123     }
2124   else if (section_is_p (sectp->name, &names->addr))
2125     {
2126       dwarf2_per_objfile->addr.s.asection = sectp;
2127       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
2128     }
2129   else if (section_is_p (sectp->name, &names->frame))
2130     {
2131       dwarf2_per_objfile->frame.s.asection = sectp;
2132       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
2133     }
2134   else if (section_is_p (sectp->name, &names->eh_frame))
2135     {
2136       dwarf2_per_objfile->eh_frame.s.asection = sectp;
2137       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
2138     }
2139   else if (section_is_p (sectp->name, &names->ranges))
2140     {
2141       dwarf2_per_objfile->ranges.s.asection = sectp;
2142       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
2143     }
2144   else if (section_is_p (sectp->name, &names->types))
2145     {
2146       struct dwarf2_section_info type_section;
2147
2148       memset (&type_section, 0, sizeof (type_section));
2149       type_section.s.asection = sectp;
2150       type_section.size = bfd_get_section_size (sectp);
2151
2152       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
2153                      &type_section);
2154     }
2155   else if (section_is_p (sectp->name, &names->gdb_index))
2156     {
2157       dwarf2_per_objfile->gdb_index.s.asection = sectp;
2158       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
2159     }
2160
2161   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
2162       && bfd_section_vma (abfd, sectp) == 0)
2163     dwarf2_per_objfile->has_section_at_zero = 1;
2164 }
2165
2166 /* A helper function that decides whether a section is empty,
2167    or not present.  */
2168
2169 static int
2170 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2171 {
2172   if (section->is_virtual)
2173     return section->size == 0;
2174   return section->s.asection == NULL || section->size == 0;
2175 }
2176
2177 /* Read the contents of the section INFO.
2178    OBJFILE is the main object file, but not necessarily the file where
2179    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2180    of the DWO file.
2181    If the section is compressed, uncompress it before returning.  */
2182
2183 static void
2184 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2185 {
2186   asection *sectp;
2187   bfd *abfd;
2188   gdb_byte *buf, *retbuf;
2189
2190   if (info->readin)
2191     return;
2192   info->buffer = NULL;
2193   info->readin = 1;
2194
2195   if (dwarf2_section_empty_p (info))
2196     return;
2197
2198   sectp = get_section_bfd_section (info);
2199
2200   /* If this is a virtual section we need to read in the real one first.  */
2201   if (info->is_virtual)
2202     {
2203       struct dwarf2_section_info *containing_section =
2204         get_containing_section (info);
2205
2206       gdb_assert (sectp != NULL);
2207       if ((sectp->flags & SEC_RELOC) != 0)
2208         {
2209           error (_("Dwarf Error: DWP format V2 with relocations is not"
2210                    " supported in section %s [in module %s]"),
2211                  get_section_name (info), get_section_file_name (info));
2212         }
2213       dwarf2_read_section (objfile, containing_section);
2214       /* Other code should have already caught virtual sections that don't
2215          fit.  */
2216       gdb_assert (info->virtual_offset + info->size
2217                   <= containing_section->size);
2218       /* If the real section is empty or there was a problem reading the
2219          section we shouldn't get here.  */
2220       gdb_assert (containing_section->buffer != NULL);
2221       info->buffer = containing_section->buffer + info->virtual_offset;
2222       return;
2223     }
2224
2225   /* If the section has relocations, we must read it ourselves.
2226      Otherwise we attach it to the BFD.  */
2227   if ((sectp->flags & SEC_RELOC) == 0)
2228     {
2229       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2230       return;
2231     }
2232
2233   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
2234   info->buffer = buf;
2235
2236   /* When debugging .o files, we may need to apply relocations; see
2237      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2238      We never compress sections in .o files, so we only need to
2239      try this when the section is not compressed.  */
2240   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2241   if (retbuf != NULL)
2242     {
2243       info->buffer = retbuf;
2244       return;
2245     }
2246
2247   abfd = get_section_bfd_owner (info);
2248   gdb_assert (abfd != NULL);
2249
2250   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2251       || bfd_bread (buf, info->size, abfd) != info->size)
2252     {
2253       error (_("Dwarf Error: Can't read DWARF data"
2254                " in section %s [in module %s]"),
2255              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2256     }
2257 }
2258
2259 /* A helper function that returns the size of a section in a safe way.
2260    If you are positive that the section has been read before using the
2261    size, then it is safe to refer to the dwarf2_section_info object's
2262    "size" field directly.  In other cases, you must call this
2263    function, because for compressed sections the size field is not set
2264    correctly until the section has been read.  */
2265
2266 static bfd_size_type
2267 dwarf2_section_size (struct objfile *objfile,
2268                      struct dwarf2_section_info *info)
2269 {
2270   if (!info->readin)
2271     dwarf2_read_section (objfile, info);
2272   return info->size;
2273 }
2274
2275 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2276    SECTION_NAME.  */
2277
2278 void
2279 dwarf2_get_section_info (struct objfile *objfile,
2280                          enum dwarf2_section_enum sect,
2281                          asection **sectp, const gdb_byte **bufp,
2282                          bfd_size_type *sizep)
2283 {
2284   struct dwarf2_per_objfile *data
2285     = objfile_data (objfile, dwarf2_objfile_data_key);
2286   struct dwarf2_section_info *info;
2287
2288   /* We may see an objfile without any DWARF, in which case we just
2289      return nothing.  */
2290   if (data == NULL)
2291     {
2292       *sectp = NULL;
2293       *bufp = NULL;
2294       *sizep = 0;
2295       return;
2296     }
2297   switch (sect)
2298     {
2299     case DWARF2_DEBUG_FRAME:
2300       info = &data->frame;
2301       break;
2302     case DWARF2_EH_FRAME:
2303       info = &data->eh_frame;
2304       break;
2305     default:
2306       gdb_assert_not_reached ("unexpected section");
2307     }
2308
2309   dwarf2_read_section (objfile, info);
2310
2311   *sectp = get_section_bfd_section (info);
2312   *bufp = info->buffer;
2313   *sizep = info->size;
2314 }
2315
2316 /* A helper function to find the sections for a .dwz file.  */
2317
2318 static void
2319 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2320 {
2321   struct dwz_file *dwz_file = arg;
2322
2323   /* Note that we only support the standard ELF names, because .dwz
2324      is ELF-only (at the time of writing).  */
2325   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2326     {
2327       dwz_file->abbrev.s.asection = sectp;
2328       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2329     }
2330   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2331     {
2332       dwz_file->info.s.asection = sectp;
2333       dwz_file->info.size = bfd_get_section_size (sectp);
2334     }
2335   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2336     {
2337       dwz_file->str.s.asection = sectp;
2338       dwz_file->str.size = bfd_get_section_size (sectp);
2339     }
2340   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2341     {
2342       dwz_file->line.s.asection = sectp;
2343       dwz_file->line.size = bfd_get_section_size (sectp);
2344     }
2345   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2346     {
2347       dwz_file->macro.s.asection = sectp;
2348       dwz_file->macro.size = bfd_get_section_size (sectp);
2349     }
2350   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2351     {
2352       dwz_file->gdb_index.s.asection = sectp;
2353       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2354     }
2355 }
2356
2357 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2358    there is no .gnu_debugaltlink section in the file.  Error if there
2359    is such a section but the file cannot be found.  */
2360
2361 static struct dwz_file *
2362 dwarf2_get_dwz_file (void)
2363 {
2364   bfd *dwz_bfd;
2365   char *data;
2366   struct cleanup *cleanup;
2367   const char *filename;
2368   struct dwz_file *result;
2369   bfd_size_type buildid_len_arg;
2370   size_t buildid_len;
2371   bfd_byte *buildid;
2372
2373   if (dwarf2_per_objfile->dwz_file != NULL)
2374     return dwarf2_per_objfile->dwz_file;
2375
2376   bfd_set_error (bfd_error_no_error);
2377   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2378                                       &buildid_len_arg, &buildid);
2379   if (data == NULL)
2380     {
2381       if (bfd_get_error () == bfd_error_no_error)
2382         return NULL;
2383       error (_("could not read '.gnu_debugaltlink' section: %s"),
2384              bfd_errmsg (bfd_get_error ()));
2385     }
2386   cleanup = make_cleanup (xfree, data);
2387   make_cleanup (xfree, buildid);
2388
2389   buildid_len = (size_t) buildid_len_arg;
2390
2391   filename = (const char *) data;
2392   if (!IS_ABSOLUTE_PATH (filename))
2393     {
2394       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2395       char *rel;
2396
2397       make_cleanup (xfree, abs);
2398       abs = ldirname (abs);
2399       make_cleanup (xfree, abs);
2400
2401       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2402       make_cleanup (xfree, rel);
2403       filename = rel;
2404     }
2405
2406   /* First try the file name given in the section.  If that doesn't
2407      work, try to use the build-id instead.  */
2408   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2409   if (dwz_bfd != NULL)
2410     {
2411       if (!build_id_verify (dwz_bfd, buildid_len, buildid))
2412         {
2413           gdb_bfd_unref (dwz_bfd);
2414           dwz_bfd = NULL;
2415         }
2416     }
2417
2418   if (dwz_bfd == NULL)
2419     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2420
2421   if (dwz_bfd == NULL)
2422     error (_("could not find '.gnu_debugaltlink' file for %s"),
2423            objfile_name (dwarf2_per_objfile->objfile));
2424
2425   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2426                            struct dwz_file);
2427   result->dwz_bfd = dwz_bfd;
2428
2429   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2430
2431   do_cleanups (cleanup);
2432
2433   dwarf2_per_objfile->dwz_file = result;
2434   return result;
2435 }
2436 \f
2437 /* DWARF quick_symbols_functions support.  */
2438
2439 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2440    unique line tables, so we maintain a separate table of all .debug_line
2441    derived entries to support the sharing.
2442    All the quick functions need is the list of file names.  We discard the
2443    line_header when we're done and don't need to record it here.  */
2444 struct quick_file_names
2445 {
2446   /* The data used to construct the hash key.  */
2447   struct stmt_list_hash hash;
2448
2449   /* The number of entries in file_names, real_names.  */
2450   unsigned int num_file_names;
2451
2452   /* The file names from the line table, after being run through
2453      file_full_name.  */
2454   const char **file_names;
2455
2456   /* The file names from the line table after being run through
2457      gdb_realpath.  These are computed lazily.  */
2458   const char **real_names;
2459 };
2460
2461 /* When using the index (and thus not using psymtabs), each CU has an
2462    object of this type.  This is used to hold information needed by
2463    the various "quick" methods.  */
2464 struct dwarf2_per_cu_quick_data
2465 {
2466   /* The file table.  This can be NULL if there was no file table
2467      or it's currently not read in.
2468      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2469   struct quick_file_names *file_names;
2470
2471   /* The corresponding symbol table.  This is NULL if symbols for this
2472      CU have not yet been read.  */
2473   struct symtab *symtab;
2474
2475   /* A temporary mark bit used when iterating over all CUs in
2476      expand_symtabs_matching.  */
2477   unsigned int mark : 1;
2478
2479   /* True if we've tried to read the file table and found there isn't one.
2480      There will be no point in trying to read it again next time.  */
2481   unsigned int no_file_data : 1;
2482 };
2483
2484 /* Utility hash function for a stmt_list_hash.  */
2485
2486 static hashval_t
2487 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2488 {
2489   hashval_t v = 0;
2490
2491   if (stmt_list_hash->dwo_unit != NULL)
2492     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2493   v += stmt_list_hash->line_offset.sect_off;
2494   return v;
2495 }
2496
2497 /* Utility equality function for a stmt_list_hash.  */
2498
2499 static int
2500 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2501                     const struct stmt_list_hash *rhs)
2502 {
2503   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2504     return 0;
2505   if (lhs->dwo_unit != NULL
2506       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2507     return 0;
2508
2509   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2510 }
2511
2512 /* Hash function for a quick_file_names.  */
2513
2514 static hashval_t
2515 hash_file_name_entry (const void *e)
2516 {
2517   const struct quick_file_names *file_data = e;
2518
2519   return hash_stmt_list_entry (&file_data->hash);
2520 }
2521
2522 /* Equality function for a quick_file_names.  */
2523
2524 static int
2525 eq_file_name_entry (const void *a, const void *b)
2526 {
2527   const struct quick_file_names *ea = a;
2528   const struct quick_file_names *eb = b;
2529
2530   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2531 }
2532
2533 /* Delete function for a quick_file_names.  */
2534
2535 static void
2536 delete_file_name_entry (void *e)
2537 {
2538   struct quick_file_names *file_data = e;
2539   int i;
2540
2541   for (i = 0; i < file_data->num_file_names; ++i)
2542     {
2543       xfree ((void*) file_data->file_names[i]);
2544       if (file_data->real_names)
2545         xfree ((void*) file_data->real_names[i]);
2546     }
2547
2548   /* The space for the struct itself lives on objfile_obstack,
2549      so we don't free it here.  */
2550 }
2551
2552 /* Create a quick_file_names hash table.  */
2553
2554 static htab_t
2555 create_quick_file_names_table (unsigned int nr_initial_entries)
2556 {
2557   return htab_create_alloc (nr_initial_entries,
2558                             hash_file_name_entry, eq_file_name_entry,
2559                             delete_file_name_entry, xcalloc, xfree);
2560 }
2561
2562 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2563    have to be created afterwards.  You should call age_cached_comp_units after
2564    processing PER_CU->CU.  dw2_setup must have been already called.  */
2565
2566 static void
2567 load_cu (struct dwarf2_per_cu_data *per_cu)
2568 {
2569   if (per_cu->is_debug_types)
2570     load_full_type_unit (per_cu);
2571   else
2572     load_full_comp_unit (per_cu, language_minimal);
2573
2574   gdb_assert (per_cu->cu != NULL);
2575
2576   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2577 }
2578
2579 /* Read in the symbols for PER_CU.  */
2580
2581 static void
2582 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2583 {
2584   struct cleanup *back_to;
2585
2586   /* Skip type_unit_groups, reading the type units they contain
2587      is handled elsewhere.  */
2588   if (IS_TYPE_UNIT_GROUP (per_cu))
2589     return;
2590
2591   back_to = make_cleanup (dwarf2_release_queue, NULL);
2592
2593   if (dwarf2_per_objfile->using_index
2594       ? per_cu->v.quick->symtab == NULL
2595       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2596     {
2597       queue_comp_unit (per_cu, language_minimal);
2598       load_cu (per_cu);
2599
2600       /* If we just loaded a CU from a DWO, and we're working with an index
2601          that may badly handle TUs, load all the TUs in that DWO as well.
2602          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2603       if (!per_cu->is_debug_types
2604           && per_cu->cu->dwo_unit != NULL
2605           && dwarf2_per_objfile->index_table != NULL
2606           && dwarf2_per_objfile->index_table->version <= 7
2607           /* DWP files aren't supported yet.  */
2608           && get_dwp_file () == NULL)
2609         queue_and_load_all_dwo_tus (per_cu);
2610     }
2611
2612   process_queue ();
2613
2614   /* Age the cache, releasing compilation units that have not
2615      been used recently.  */
2616   age_cached_comp_units ();
2617
2618   do_cleanups (back_to);
2619 }
2620
2621 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2622    the objfile from which this CU came.  Returns the resulting symbol
2623    table.  */
2624
2625 static struct symtab *
2626 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2627 {
2628   gdb_assert (dwarf2_per_objfile->using_index);
2629   if (!per_cu->v.quick->symtab)
2630     {
2631       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2632       increment_reading_symtab ();
2633       dw2_do_instantiate_symtab (per_cu);
2634       process_cu_includes ();
2635       do_cleanups (back_to);
2636     }
2637   return per_cu->v.quick->symtab;
2638 }
2639
2640 /* Return the CU given its index.
2641
2642    This is intended for loops like:
2643
2644    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2645                     + dwarf2_per_objfile->n_type_units); ++i)
2646      {
2647        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2648
2649        ...;
2650      }
2651 */
2652
2653 static struct dwarf2_per_cu_data *
2654 dw2_get_cu (int index)
2655 {
2656   if (index >= dwarf2_per_objfile->n_comp_units)
2657     {
2658       index -= dwarf2_per_objfile->n_comp_units;
2659       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2660       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2661     }
2662
2663   return dwarf2_per_objfile->all_comp_units[index];
2664 }
2665
2666 /* Return the primary CU given its index.
2667    The difference between this function and dw2_get_cu is in the handling
2668    of type units (TUs).  Here we return the type_unit_group object.
2669
2670    This is intended for loops like:
2671
2672    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2673                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2674      {
2675        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2676
2677        ...;
2678      }
2679 */
2680
2681 static struct dwarf2_per_cu_data *
2682 dw2_get_primary_cu (int index)
2683 {
2684   if (index >= dwarf2_per_objfile->n_comp_units)
2685     {
2686       index -= dwarf2_per_objfile->n_comp_units;
2687       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2688       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2689     }
2690
2691   return dwarf2_per_objfile->all_comp_units[index];
2692 }
2693
2694 /* A helper for create_cus_from_index that handles a given list of
2695    CUs.  */
2696
2697 static void
2698 create_cus_from_index_list (struct objfile *objfile,
2699                             const gdb_byte *cu_list, offset_type n_elements,
2700                             struct dwarf2_section_info *section,
2701                             int is_dwz,
2702                             int base_offset)
2703 {
2704   offset_type i;
2705
2706   for (i = 0; i < n_elements; i += 2)
2707     {
2708       struct dwarf2_per_cu_data *the_cu;
2709       ULONGEST offset, length;
2710
2711       gdb_static_assert (sizeof (ULONGEST) >= 8);
2712       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2713       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2714       cu_list += 2 * 8;
2715
2716       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2717                                struct dwarf2_per_cu_data);
2718       the_cu->offset.sect_off = offset;
2719       the_cu->length = length;
2720       the_cu->objfile = objfile;
2721       the_cu->section = section;
2722       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2723                                         struct dwarf2_per_cu_quick_data);
2724       the_cu->is_dwz = is_dwz;
2725       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2726     }
2727 }
2728
2729 /* Read the CU list from the mapped index, and use it to create all
2730    the CU objects for this objfile.  */
2731
2732 static void
2733 create_cus_from_index (struct objfile *objfile,
2734                        const gdb_byte *cu_list, offset_type cu_list_elements,
2735                        const gdb_byte *dwz_list, offset_type dwz_elements)
2736 {
2737   struct dwz_file *dwz;
2738
2739   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2740   dwarf2_per_objfile->all_comp_units
2741     = obstack_alloc (&objfile->objfile_obstack,
2742                      dwarf2_per_objfile->n_comp_units
2743                      * sizeof (struct dwarf2_per_cu_data *));
2744
2745   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2746                               &dwarf2_per_objfile->info, 0, 0);
2747
2748   if (dwz_elements == 0)
2749     return;
2750
2751   dwz = dwarf2_get_dwz_file ();
2752   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2753                               cu_list_elements / 2);
2754 }
2755
2756 /* Create the signatured type hash table from the index.  */
2757
2758 static void
2759 create_signatured_type_table_from_index (struct objfile *objfile,
2760                                          struct dwarf2_section_info *section,
2761                                          const gdb_byte *bytes,
2762                                          offset_type elements)
2763 {
2764   offset_type i;
2765   htab_t sig_types_hash;
2766
2767   dwarf2_per_objfile->n_type_units = elements / 3;
2768   dwarf2_per_objfile->all_type_units
2769     = xmalloc (dwarf2_per_objfile->n_type_units
2770                * sizeof (struct signatured_type *));
2771
2772   sig_types_hash = allocate_signatured_type_table (objfile);
2773
2774   for (i = 0; i < elements; i += 3)
2775     {
2776       struct signatured_type *sig_type;
2777       ULONGEST offset, type_offset_in_tu, signature;
2778       void **slot;
2779
2780       gdb_static_assert (sizeof (ULONGEST) >= 8);
2781       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2782       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2783                                                     BFD_ENDIAN_LITTLE);
2784       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2785       bytes += 3 * 8;
2786
2787       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2788                                  struct signatured_type);
2789       sig_type->signature = signature;
2790       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2791       sig_type->per_cu.is_debug_types = 1;
2792       sig_type->per_cu.section = section;
2793       sig_type->per_cu.offset.sect_off = offset;
2794       sig_type->per_cu.objfile = objfile;
2795       sig_type->per_cu.v.quick
2796         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2797                           struct dwarf2_per_cu_quick_data);
2798
2799       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2800       *slot = sig_type;
2801
2802       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2803     }
2804
2805   dwarf2_per_objfile->signatured_types = sig_types_hash;
2806 }
2807
2808 /* Read the address map data from the mapped index, and use it to
2809    populate the objfile's psymtabs_addrmap.  */
2810
2811 static void
2812 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2813 {
2814   const gdb_byte *iter, *end;
2815   struct obstack temp_obstack;
2816   struct addrmap *mutable_map;
2817   struct cleanup *cleanup;
2818   CORE_ADDR baseaddr;
2819
2820   obstack_init (&temp_obstack);
2821   cleanup = make_cleanup_obstack_free (&temp_obstack);
2822   mutable_map = addrmap_create_mutable (&temp_obstack);
2823
2824   iter = index->address_table;
2825   end = iter + index->address_table_size;
2826
2827   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2828
2829   while (iter < end)
2830     {
2831       ULONGEST hi, lo, cu_index;
2832       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2833       iter += 8;
2834       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2835       iter += 8;
2836       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2837       iter += 4;
2838
2839       if (lo > hi)
2840         {
2841           complaint (&symfile_complaints,
2842                      _(".gdb_index address table has invalid range (%s - %s)"),
2843                      hex_string (lo), hex_string (hi));
2844           continue;
2845         }
2846
2847       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2848         {
2849           complaint (&symfile_complaints,
2850                      _(".gdb_index address table has invalid CU number %u"),
2851                      (unsigned) cu_index);
2852           continue;
2853         }
2854
2855       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2856                          dw2_get_cu (cu_index));
2857     }
2858
2859   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2860                                                     &objfile->objfile_obstack);
2861   do_cleanups (cleanup);
2862 }
2863
2864 /* The hash function for strings in the mapped index.  This is the same as
2865    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2866    implementation.  This is necessary because the hash function is tied to the
2867    format of the mapped index file.  The hash values do not have to match with
2868    SYMBOL_HASH_NEXT.
2869    
2870    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2871
2872 static hashval_t
2873 mapped_index_string_hash (int index_version, const void *p)
2874 {
2875   const unsigned char *str = (const unsigned char *) p;
2876   hashval_t r = 0;
2877   unsigned char c;
2878
2879   while ((c = *str++) != 0)
2880     {
2881       if (index_version >= 5)
2882         c = tolower (c);
2883       r = r * 67 + c - 113;
2884     }
2885
2886   return r;
2887 }
2888
2889 /* Find a slot in the mapped index INDEX for the object named NAME.
2890    If NAME is found, set *VEC_OUT to point to the CU vector in the
2891    constant pool and return 1.  If NAME cannot be found, return 0.  */
2892
2893 static int
2894 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2895                           offset_type **vec_out)
2896 {
2897   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2898   offset_type hash;
2899   offset_type slot, step;
2900   int (*cmp) (const char *, const char *);
2901
2902   if (current_language->la_language == language_cplus
2903       || current_language->la_language == language_java
2904       || current_language->la_language == language_fortran)
2905     {
2906       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2907          not contain any.  */
2908       const char *paren = strchr (name, '(');
2909
2910       if (paren)
2911         {
2912           char *dup;
2913
2914           dup = xmalloc (paren - name + 1);
2915           memcpy (dup, name, paren - name);
2916           dup[paren - name] = 0;
2917
2918           make_cleanup (xfree, dup);
2919           name = dup;
2920         }
2921     }
2922
2923   /* Index version 4 did not support case insensitive searches.  But the
2924      indices for case insensitive languages are built in lowercase, therefore
2925      simulate our NAME being searched is also lowercased.  */
2926   hash = mapped_index_string_hash ((index->version == 4
2927                                     && case_sensitivity == case_sensitive_off
2928                                     ? 5 : index->version),
2929                                    name);
2930
2931   slot = hash & (index->symbol_table_slots - 1);
2932   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2933   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2934
2935   for (;;)
2936     {
2937       /* Convert a slot number to an offset into the table.  */
2938       offset_type i = 2 * slot;
2939       const char *str;
2940       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2941         {
2942           do_cleanups (back_to);
2943           return 0;
2944         }
2945
2946       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2947       if (!cmp (name, str))
2948         {
2949           *vec_out = (offset_type *) (index->constant_pool
2950                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2951           do_cleanups (back_to);
2952           return 1;
2953         }
2954
2955       slot = (slot + step) & (index->symbol_table_slots - 1);
2956     }
2957 }
2958
2959 /* A helper function that reads the .gdb_index from SECTION and fills
2960    in MAP.  FILENAME is the name of the file containing the section;
2961    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2962    ok to use deprecated sections.
2963
2964    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2965    out parameters that are filled in with information about the CU and
2966    TU lists in the section.
2967
2968    Returns 1 if all went well, 0 otherwise.  */
2969
2970 static int
2971 read_index_from_section (struct objfile *objfile,
2972                          const char *filename,
2973                          int deprecated_ok,
2974                          struct dwarf2_section_info *section,
2975                          struct mapped_index *map,
2976                          const gdb_byte **cu_list,
2977                          offset_type *cu_list_elements,
2978                          const gdb_byte **types_list,
2979                          offset_type *types_list_elements)
2980 {
2981   const gdb_byte *addr;
2982   offset_type version;
2983   offset_type *metadata;
2984   int i;
2985
2986   if (dwarf2_section_empty_p (section))
2987     return 0;
2988
2989   /* Older elfutils strip versions could keep the section in the main
2990      executable while splitting it for the separate debug info file.  */
2991   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
2992     return 0;
2993
2994   dwarf2_read_section (objfile, section);
2995
2996   addr = section->buffer;
2997   /* Version check.  */
2998   version = MAYBE_SWAP (*(offset_type *) addr);
2999   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3000      causes the index to behave very poorly for certain requests.  Version 3
3001      contained incomplete addrmap.  So, it seems better to just ignore such
3002      indices.  */
3003   if (version < 4)
3004     {
3005       static int warning_printed = 0;
3006       if (!warning_printed)
3007         {
3008           warning (_("Skipping obsolete .gdb_index section in %s."),
3009                    filename);
3010           warning_printed = 1;
3011         }
3012       return 0;
3013     }
3014   /* Index version 4 uses a different hash function than index version
3015      5 and later.
3016
3017      Versions earlier than 6 did not emit psymbols for inlined
3018      functions.  Using these files will cause GDB not to be able to
3019      set breakpoints on inlined functions by name, so we ignore these
3020      indices unless the user has done
3021      "set use-deprecated-index-sections on".  */
3022   if (version < 6 && !deprecated_ok)
3023     {
3024       static int warning_printed = 0;
3025       if (!warning_printed)
3026         {
3027           warning (_("\
3028 Skipping deprecated .gdb_index section in %s.\n\
3029 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3030 to use the section anyway."),
3031                    filename);
3032           warning_printed = 1;
3033         }
3034       return 0;
3035     }
3036   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3037      of the TU (for symbols coming from TUs),
3038      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3039      Plus gold-generated indices can have duplicate entries for global symbols,
3040      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3041      These are just performance bugs, and we can't distinguish gdb-generated
3042      indices from gold-generated ones, so issue no warning here.  */
3043
3044   /* Indexes with higher version than the one supported by GDB may be no
3045      longer backward compatible.  */
3046   if (version > 8)
3047     return 0;
3048
3049   map->version = version;
3050   map->total_size = section->size;
3051
3052   metadata = (offset_type *) (addr + sizeof (offset_type));
3053
3054   i = 0;
3055   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3056   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3057                        / 8);
3058   ++i;
3059
3060   *types_list = addr + MAYBE_SWAP (metadata[i]);
3061   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3062                            - MAYBE_SWAP (metadata[i]))
3063                           / 8);
3064   ++i;
3065
3066   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3067   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3068                              - MAYBE_SWAP (metadata[i]));
3069   ++i;
3070
3071   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3072   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3073                               - MAYBE_SWAP (metadata[i]))
3074                              / (2 * sizeof (offset_type)));
3075   ++i;
3076
3077   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3078
3079   return 1;
3080 }
3081
3082
3083 /* Read the index file.  If everything went ok, initialize the "quick"
3084    elements of all the CUs and return 1.  Otherwise, return 0.  */
3085
3086 static int
3087 dwarf2_read_index (struct objfile *objfile)
3088 {
3089   struct mapped_index local_map, *map;
3090   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3091   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3092   struct dwz_file *dwz;
3093
3094   if (!read_index_from_section (objfile, objfile_name (objfile),
3095                                 use_deprecated_index_sections,
3096                                 &dwarf2_per_objfile->gdb_index, &local_map,
3097                                 &cu_list, &cu_list_elements,
3098                                 &types_list, &types_list_elements))
3099     return 0;
3100
3101   /* Don't use the index if it's empty.  */
3102   if (local_map.symbol_table_slots == 0)
3103     return 0;
3104
3105   /* If there is a .dwz file, read it so we can get its CU list as
3106      well.  */
3107   dwz = dwarf2_get_dwz_file ();
3108   if (dwz != NULL)
3109     {
3110       struct mapped_index dwz_map;
3111       const gdb_byte *dwz_types_ignore;
3112       offset_type dwz_types_elements_ignore;
3113
3114       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3115                                     1,
3116                                     &dwz->gdb_index, &dwz_map,
3117                                     &dwz_list, &dwz_list_elements,
3118                                     &dwz_types_ignore,
3119                                     &dwz_types_elements_ignore))
3120         {
3121           warning (_("could not read '.gdb_index' section from %s; skipping"),
3122                    bfd_get_filename (dwz->dwz_bfd));
3123           return 0;
3124         }
3125     }
3126
3127   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3128                          dwz_list_elements);
3129
3130   if (types_list_elements)
3131     {
3132       struct dwarf2_section_info *section;
3133
3134       /* We can only handle a single .debug_types when we have an
3135          index.  */
3136       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3137         return 0;
3138
3139       section = VEC_index (dwarf2_section_info_def,
3140                            dwarf2_per_objfile->types, 0);
3141
3142       create_signatured_type_table_from_index (objfile, section, types_list,
3143                                                types_list_elements);
3144     }
3145
3146   create_addrmap_from_index (objfile, &local_map);
3147
3148   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
3149   *map = local_map;
3150
3151   dwarf2_per_objfile->index_table = map;
3152   dwarf2_per_objfile->using_index = 1;
3153   dwarf2_per_objfile->quick_file_names_table =
3154     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3155
3156   return 1;
3157 }
3158
3159 /* A helper for the "quick" functions which sets the global
3160    dwarf2_per_objfile according to OBJFILE.  */
3161
3162 static void
3163 dw2_setup (struct objfile *objfile)
3164 {
3165   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
3166   gdb_assert (dwarf2_per_objfile);
3167 }
3168
3169 /* die_reader_func for dw2_get_file_names.  */
3170
3171 static void
3172 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3173                            const gdb_byte *info_ptr,
3174                            struct die_info *comp_unit_die,
3175                            int has_children,
3176                            void *data)
3177 {
3178   struct dwarf2_cu *cu = reader->cu;
3179   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3180   struct objfile *objfile = dwarf2_per_objfile->objfile;
3181   struct dwarf2_per_cu_data *lh_cu;
3182   struct line_header *lh;
3183   struct attribute *attr;
3184   int i;
3185   const char *name, *comp_dir;
3186   void **slot;
3187   struct quick_file_names *qfn;
3188   unsigned int line_offset;
3189
3190   gdb_assert (! this_cu->is_debug_types);
3191
3192   /* Our callers never want to match partial units -- instead they
3193      will match the enclosing full CU.  */
3194   if (comp_unit_die->tag == DW_TAG_partial_unit)
3195     {
3196       this_cu->v.quick->no_file_data = 1;
3197       return;
3198     }
3199
3200   lh_cu = this_cu;
3201   lh = NULL;
3202   slot = NULL;
3203   line_offset = 0;
3204
3205   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3206   if (attr)
3207     {
3208       struct quick_file_names find_entry;
3209
3210       line_offset = DW_UNSND (attr);
3211
3212       /* We may have already read in this line header (TU line header sharing).
3213          If we have we're done.  */
3214       find_entry.hash.dwo_unit = cu->dwo_unit;
3215       find_entry.hash.line_offset.sect_off = line_offset;
3216       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3217                              &find_entry, INSERT);
3218       if (*slot != NULL)
3219         {
3220           lh_cu->v.quick->file_names = *slot;
3221           return;
3222         }
3223
3224       lh = dwarf_decode_line_header (line_offset, cu);
3225     }
3226   if (lh == NULL)
3227     {
3228       lh_cu->v.quick->no_file_data = 1;
3229       return;
3230     }
3231
3232   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
3233   qfn->hash.dwo_unit = cu->dwo_unit;
3234   qfn->hash.line_offset.sect_off = line_offset;
3235   gdb_assert (slot != NULL);
3236   *slot = qfn;
3237
3238   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
3239
3240   qfn->num_file_names = lh->num_file_names;
3241   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
3242                                    lh->num_file_names * sizeof (char *));
3243   for (i = 0; i < lh->num_file_names; ++i)
3244     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
3245   qfn->real_names = NULL;
3246
3247   free_line_header (lh);
3248
3249   lh_cu->v.quick->file_names = qfn;
3250 }
3251
3252 /* A helper for the "quick" functions which attempts to read the line
3253    table for THIS_CU.  */
3254
3255 static struct quick_file_names *
3256 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3257 {
3258   /* This should never be called for TUs.  */
3259   gdb_assert (! this_cu->is_debug_types);
3260   /* Nor type unit groups.  */
3261   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3262
3263   if (this_cu->v.quick->file_names != NULL)
3264     return this_cu->v.quick->file_names;
3265   /* If we know there is no line data, no point in looking again.  */
3266   if (this_cu->v.quick->no_file_data)
3267     return NULL;
3268
3269   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3270
3271   if (this_cu->v.quick->no_file_data)
3272     return NULL;
3273   return this_cu->v.quick->file_names;
3274 }
3275
3276 /* A helper for the "quick" functions which computes and caches the
3277    real path for a given file name from the line table.  */
3278
3279 static const char *
3280 dw2_get_real_path (struct objfile *objfile,
3281                    struct quick_file_names *qfn, int index)
3282 {
3283   if (qfn->real_names == NULL)
3284     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3285                                       qfn->num_file_names, char *);
3286
3287   if (qfn->real_names[index] == NULL)
3288     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3289
3290   return qfn->real_names[index];
3291 }
3292
3293 static struct symtab *
3294 dw2_find_last_source_symtab (struct objfile *objfile)
3295 {
3296   int index;
3297
3298   dw2_setup (objfile);
3299   index = dwarf2_per_objfile->n_comp_units - 1;
3300   return dw2_instantiate_symtab (dw2_get_cu (index));
3301 }
3302
3303 /* Traversal function for dw2_forget_cached_source_info.  */
3304
3305 static int
3306 dw2_free_cached_file_names (void **slot, void *info)
3307 {
3308   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3309
3310   if (file_data->real_names)
3311     {
3312       int i;
3313
3314       for (i = 0; i < file_data->num_file_names; ++i)
3315         {
3316           xfree ((void*) file_data->real_names[i]);
3317           file_data->real_names[i] = NULL;
3318         }
3319     }
3320
3321   return 1;
3322 }
3323
3324 static void
3325 dw2_forget_cached_source_info (struct objfile *objfile)
3326 {
3327   dw2_setup (objfile);
3328
3329   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3330                           dw2_free_cached_file_names, NULL);
3331 }
3332
3333 /* Helper function for dw2_map_symtabs_matching_filename that expands
3334    the symtabs and calls the iterator.  */
3335
3336 static int
3337 dw2_map_expand_apply (struct objfile *objfile,
3338                       struct dwarf2_per_cu_data *per_cu,
3339                       const char *name, const char *real_path,
3340                       int (*callback) (struct symtab *, void *),
3341                       void *data)
3342 {
3343   struct symtab *last_made = objfile->symtabs;
3344
3345   /* Don't visit already-expanded CUs.  */
3346   if (per_cu->v.quick->symtab)
3347     return 0;
3348
3349   /* This may expand more than one symtab, and we want to iterate over
3350      all of them.  */
3351   dw2_instantiate_symtab (per_cu);
3352
3353   return iterate_over_some_symtabs (name, real_path, callback, data,
3354                                     objfile->symtabs, last_made);
3355 }
3356
3357 /* Implementation of the map_symtabs_matching_filename method.  */
3358
3359 static int
3360 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3361                                    const char *real_path,
3362                                    int (*callback) (struct symtab *, void *),
3363                                    void *data)
3364 {
3365   int i;
3366   const char *name_basename = lbasename (name);
3367
3368   dw2_setup (objfile);
3369
3370   /* The rule is CUs specify all the files, including those used by
3371      any TU, so there's no need to scan TUs here.  */
3372
3373   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3374     {
3375       int j;
3376       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3377       struct quick_file_names *file_data;
3378
3379       /* We only need to look at symtabs not already expanded.  */
3380       if (per_cu->v.quick->symtab)
3381         continue;
3382
3383       file_data = dw2_get_file_names (per_cu);
3384       if (file_data == NULL)
3385         continue;
3386
3387       for (j = 0; j < file_data->num_file_names; ++j)
3388         {
3389           const char *this_name = file_data->file_names[j];
3390           const char *this_real_name;
3391
3392           if (compare_filenames_for_search (this_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           /* Before we invoke realpath, which can get expensive when many
3401              files are involved, do a quick comparison of the basenames.  */
3402           if (! basenames_may_differ
3403               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3404             continue;
3405
3406           this_real_name = dw2_get_real_path (objfile, file_data, j);
3407           if (compare_filenames_for_search (this_real_name, name))
3408             {
3409               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3410                                         callback, data))
3411                 return 1;
3412               continue;
3413             }
3414
3415           if (real_path != NULL)
3416             {
3417               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3418               gdb_assert (IS_ABSOLUTE_PATH (name));
3419               if (this_real_name != NULL
3420                   && FILENAME_CMP (real_path, this_real_name) == 0)
3421                 {
3422                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3423                                             callback, data))
3424                     return 1;
3425                   continue;
3426                 }
3427             }
3428         }
3429     }
3430
3431   return 0;
3432 }
3433
3434 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3435
3436 struct dw2_symtab_iterator
3437 {
3438   /* The internalized form of .gdb_index.  */
3439   struct mapped_index *index;
3440   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3441   int want_specific_block;
3442   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3443      Unused if !WANT_SPECIFIC_BLOCK.  */
3444   int block_index;
3445   /* The kind of symbol we're looking for.  */
3446   domain_enum domain;
3447   /* The list of CUs from the index entry of the symbol,
3448      or NULL if not found.  */
3449   offset_type *vec;
3450   /* The next element in VEC to look at.  */
3451   int next;
3452   /* The number of elements in VEC, or zero if there is no match.  */
3453   int length;
3454   /* Have we seen a global version of the symbol?
3455      If so we can ignore all further global instances.
3456      This is to work around gold/15646, inefficient gold-generated
3457      indices.  */
3458   int global_seen;
3459 };
3460
3461 /* Initialize the index symtab iterator ITER.
3462    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3463    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3464
3465 static void
3466 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3467                       struct mapped_index *index,
3468                       int want_specific_block,
3469                       int block_index,
3470                       domain_enum domain,
3471                       const char *name)
3472 {
3473   iter->index = index;
3474   iter->want_specific_block = want_specific_block;
3475   iter->block_index = block_index;
3476   iter->domain = domain;
3477   iter->next = 0;
3478   iter->global_seen = 0;
3479
3480   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3481     iter->length = MAYBE_SWAP (*iter->vec);
3482   else
3483     {
3484       iter->vec = NULL;
3485       iter->length = 0;
3486     }
3487 }
3488
3489 /* Return the next matching CU or NULL if there are no more.  */
3490
3491 static struct dwarf2_per_cu_data *
3492 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3493 {
3494   for ( ; iter->next < iter->length; ++iter->next)
3495     {
3496       offset_type cu_index_and_attrs =
3497         MAYBE_SWAP (iter->vec[iter->next + 1]);
3498       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3499       struct dwarf2_per_cu_data *per_cu;
3500       int want_static = iter->block_index != GLOBAL_BLOCK;
3501       /* This value is only valid for index versions >= 7.  */
3502       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3503       gdb_index_symbol_kind symbol_kind =
3504         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3505       /* Only check the symbol attributes if they're present.
3506          Indices prior to version 7 don't record them,
3507          and indices >= 7 may elide them for certain symbols
3508          (gold does this).  */
3509       int attrs_valid =
3510         (iter->index->version >= 7
3511          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3512
3513       /* Don't crash on bad data.  */
3514       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3515                        + dwarf2_per_objfile->n_type_units))
3516         {
3517           complaint (&symfile_complaints,
3518                      _(".gdb_index entry has bad CU index"
3519                        " [in module %s]"),
3520                      objfile_name (dwarf2_per_objfile->objfile));
3521           continue;
3522         }
3523
3524       per_cu = dw2_get_cu (cu_index);
3525
3526       /* Skip if already read in.  */
3527       if (per_cu->v.quick->symtab)
3528         continue;
3529
3530       /* Check static vs global.  */
3531       if (attrs_valid)
3532         {
3533           if (iter->want_specific_block
3534               && want_static != is_static)
3535             continue;
3536           /* Work around gold/15646.  */
3537           if (!is_static && iter->global_seen)
3538             continue;
3539           if (!is_static)
3540             iter->global_seen = 1;
3541         }
3542
3543       /* Only check the symbol's kind if it has one.  */
3544       if (attrs_valid)
3545         {
3546           switch (iter->domain)
3547             {
3548             case VAR_DOMAIN:
3549               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3550                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3551                   /* Some types are also in VAR_DOMAIN.  */
3552                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3553                 continue;
3554               break;
3555             case STRUCT_DOMAIN:
3556               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3557                 continue;
3558               break;
3559             case LABEL_DOMAIN:
3560               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3561                 continue;
3562               break;
3563             default:
3564               break;
3565             }
3566         }
3567
3568       ++iter->next;
3569       return per_cu;
3570     }
3571
3572   return NULL;
3573 }
3574
3575 static struct symtab *
3576 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3577                    const char *name, domain_enum domain)
3578 {
3579   struct symtab *stab_best = NULL;
3580   struct mapped_index *index;
3581
3582   dw2_setup (objfile);
3583
3584   index = dwarf2_per_objfile->index_table;
3585
3586   /* index is NULL if OBJF_READNOW.  */
3587   if (index)
3588     {
3589       struct dw2_symtab_iterator iter;
3590       struct dwarf2_per_cu_data *per_cu;
3591
3592       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3593
3594       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3595         {
3596           struct symbol *sym = NULL;
3597           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3598
3599           /* Some caution must be observed with overloaded functions
3600              and methods, since the index will not contain any overload
3601              information (but NAME might contain it).  */
3602           if (stab->primary)
3603             {
3604               struct blockvector *bv = BLOCKVECTOR (stab);
3605               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3606
3607               sym = lookup_block_symbol (block, name, domain);
3608             }
3609
3610           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3611             {
3612               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3613                 return stab;
3614
3615               stab_best = stab;
3616             }
3617
3618           /* Keep looking through other CUs.  */
3619         }
3620     }
3621
3622   return stab_best;
3623 }
3624
3625 static void
3626 dw2_print_stats (struct objfile *objfile)
3627 {
3628   int i, total, count;
3629
3630   dw2_setup (objfile);
3631   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3632   count = 0;
3633   for (i = 0; i < total; ++i)
3634     {
3635       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3636
3637       if (!per_cu->v.quick->symtab)
3638         ++count;
3639     }
3640   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3641   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3642 }
3643
3644 /* This dumps minimal information about the index.
3645    It is called via "mt print objfiles".
3646    One use is to verify .gdb_index has been loaded by the
3647    gdb.dwarf2/gdb-index.exp testcase.  */
3648
3649 static void
3650 dw2_dump (struct objfile *objfile)
3651 {
3652   dw2_setup (objfile);
3653   gdb_assert (dwarf2_per_objfile->using_index);
3654   printf_filtered (".gdb_index:");
3655   if (dwarf2_per_objfile->index_table != NULL)
3656     {
3657       printf_filtered (" version %d\n",
3658                        dwarf2_per_objfile->index_table->version);
3659     }
3660   else
3661     printf_filtered (" faked for \"readnow\"\n");
3662   printf_filtered ("\n");
3663 }
3664
3665 static void
3666 dw2_relocate (struct objfile *objfile,
3667               const struct section_offsets *new_offsets,
3668               const struct section_offsets *delta)
3669 {
3670   /* There's nothing to relocate here.  */
3671 }
3672
3673 static void
3674 dw2_expand_symtabs_for_function (struct objfile *objfile,
3675                                  const char *func_name)
3676 {
3677   struct mapped_index *index;
3678
3679   dw2_setup (objfile);
3680
3681   index = dwarf2_per_objfile->index_table;
3682
3683   /* index is NULL if OBJF_READNOW.  */
3684   if (index)
3685     {
3686       struct dw2_symtab_iterator iter;
3687       struct dwarf2_per_cu_data *per_cu;
3688
3689       /* Note: It doesn't matter what we pass for block_index here.  */
3690       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3691                             func_name);
3692
3693       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3694         dw2_instantiate_symtab (per_cu);
3695     }
3696 }
3697
3698 static void
3699 dw2_expand_all_symtabs (struct objfile *objfile)
3700 {
3701   int i;
3702
3703   dw2_setup (objfile);
3704
3705   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3706                    + dwarf2_per_objfile->n_type_units); ++i)
3707     {
3708       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3709
3710       dw2_instantiate_symtab (per_cu);
3711     }
3712 }
3713
3714 static void
3715 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3716                                   const char *fullname)
3717 {
3718   int i;
3719
3720   dw2_setup (objfile);
3721
3722   /* We don't need to consider type units here.
3723      This is only called for examining code, e.g. expand_line_sal.
3724      There can be an order of magnitude (or more) more type units
3725      than comp units, and we avoid them if we can.  */
3726
3727   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3728     {
3729       int j;
3730       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3731       struct quick_file_names *file_data;
3732
3733       /* We only need to look at symtabs not already expanded.  */
3734       if (per_cu->v.quick->symtab)
3735         continue;
3736
3737       file_data = dw2_get_file_names (per_cu);
3738       if (file_data == NULL)
3739         continue;
3740
3741       for (j = 0; j < file_data->num_file_names; ++j)
3742         {
3743           const char *this_fullname = file_data->file_names[j];
3744
3745           if (filename_cmp (this_fullname, fullname) == 0)
3746             {
3747               dw2_instantiate_symtab (per_cu);
3748               break;
3749             }
3750         }
3751     }
3752 }
3753
3754 static void
3755 dw2_map_matching_symbols (struct objfile *objfile,
3756                           const char * name, domain_enum namespace,
3757                           int global,
3758                           int (*callback) (struct block *,
3759                                            struct symbol *, void *),
3760                           void *data, symbol_compare_ftype *match,
3761                           symbol_compare_ftype *ordered_compare)
3762 {
3763   /* Currently unimplemented; used for Ada.  The function can be called if the
3764      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3765      does not look for non-Ada symbols this function should just return.  */
3766 }
3767
3768 static void
3769 dw2_expand_symtabs_matching
3770   (struct objfile *objfile,
3771    int (*file_matcher) (const char *, void *, int basenames),
3772    int (*name_matcher) (const char *, void *),
3773    enum search_domain kind,
3774    void *data)
3775 {
3776   int i;
3777   offset_type iter;
3778   struct mapped_index *index;
3779
3780   dw2_setup (objfile);
3781
3782   /* index_table is NULL if OBJF_READNOW.  */
3783   if (!dwarf2_per_objfile->index_table)
3784     return;
3785   index = dwarf2_per_objfile->index_table;
3786
3787   if (file_matcher != NULL)
3788     {
3789       struct cleanup *cleanup;
3790       htab_t visited_found, visited_not_found;
3791
3792       visited_found = htab_create_alloc (10,
3793                                          htab_hash_pointer, htab_eq_pointer,
3794                                          NULL, xcalloc, xfree);
3795       cleanup = make_cleanup_htab_delete (visited_found);
3796       visited_not_found = htab_create_alloc (10,
3797                                              htab_hash_pointer, htab_eq_pointer,
3798                                              NULL, xcalloc, xfree);
3799       make_cleanup_htab_delete (visited_not_found);
3800
3801       /* The rule is CUs specify all the files, including those used by
3802          any TU, so there's no need to scan TUs here.  */
3803
3804       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3805         {
3806           int j;
3807           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3808           struct quick_file_names *file_data;
3809           void **slot;
3810
3811           per_cu->v.quick->mark = 0;
3812
3813           /* We only need to look at symtabs not already expanded.  */
3814           if (per_cu->v.quick->symtab)
3815             continue;
3816
3817           file_data = dw2_get_file_names (per_cu);
3818           if (file_data == NULL)
3819             continue;
3820
3821           if (htab_find (visited_not_found, file_data) != NULL)
3822             continue;
3823           else if (htab_find (visited_found, file_data) != NULL)
3824             {
3825               per_cu->v.quick->mark = 1;
3826               continue;
3827             }
3828
3829           for (j = 0; j < file_data->num_file_names; ++j)
3830             {
3831               const char *this_real_name;
3832
3833               if (file_matcher (file_data->file_names[j], data, 0))
3834                 {
3835                   per_cu->v.quick->mark = 1;
3836                   break;
3837                 }
3838
3839               /* Before we invoke realpath, which can get expensive when many
3840                  files are involved, do a quick comparison of the basenames.  */
3841               if (!basenames_may_differ
3842                   && !file_matcher (lbasename (file_data->file_names[j]),
3843                                     data, 1))
3844                 continue;
3845
3846               this_real_name = dw2_get_real_path (objfile, file_data, j);
3847               if (file_matcher (this_real_name, data, 0))
3848                 {
3849                   per_cu->v.quick->mark = 1;
3850                   break;
3851                 }
3852             }
3853
3854           slot = htab_find_slot (per_cu->v.quick->mark
3855                                  ? visited_found
3856                                  : visited_not_found,
3857                                  file_data, INSERT);
3858           *slot = file_data;
3859         }
3860
3861       do_cleanups (cleanup);
3862     }
3863
3864   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3865     {
3866       offset_type idx = 2 * iter;
3867       const char *name;
3868       offset_type *vec, vec_len, vec_idx;
3869       int global_seen = 0;
3870
3871       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3872         continue;
3873
3874       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3875
3876       if (! (*name_matcher) (name, data))
3877         continue;
3878
3879       /* The name was matched, now expand corresponding CUs that were
3880          marked.  */
3881       vec = (offset_type *) (index->constant_pool
3882                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3883       vec_len = MAYBE_SWAP (vec[0]);
3884       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3885         {
3886           struct dwarf2_per_cu_data *per_cu;
3887           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3888           /* This value is only valid for index versions >= 7.  */
3889           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3890           gdb_index_symbol_kind symbol_kind =
3891             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3892           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3893           /* Only check the symbol attributes if they're present.
3894              Indices prior to version 7 don't record them,
3895              and indices >= 7 may elide them for certain symbols
3896              (gold does this).  */
3897           int attrs_valid =
3898             (index->version >= 7
3899              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3900
3901           /* Work around gold/15646.  */
3902           if (attrs_valid)
3903             {
3904               if (!is_static && global_seen)
3905                 continue;
3906               if (!is_static)
3907                 global_seen = 1;
3908             }
3909
3910           /* Only check the symbol's kind if it has one.  */
3911           if (attrs_valid)
3912             {
3913               switch (kind)
3914                 {
3915                 case VARIABLES_DOMAIN:
3916                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3917                     continue;
3918                   break;
3919                 case FUNCTIONS_DOMAIN:
3920                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3921                     continue;
3922                   break;
3923                 case TYPES_DOMAIN:
3924                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3925                     continue;
3926                   break;
3927                 default:
3928                   break;
3929                 }
3930             }
3931
3932           /* Don't crash on bad data.  */
3933           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3934                            + dwarf2_per_objfile->n_type_units))
3935             {
3936               complaint (&symfile_complaints,
3937                          _(".gdb_index entry has bad CU index"
3938                            " [in module %s]"), objfile_name (objfile));
3939               continue;
3940             }
3941
3942           per_cu = dw2_get_cu (cu_index);
3943           if (file_matcher == NULL || per_cu->v.quick->mark)
3944             dw2_instantiate_symtab (per_cu);
3945         }
3946     }
3947 }
3948
3949 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3950    symtab.  */
3951
3952 static struct symtab *
3953 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3954 {
3955   int i;
3956
3957   if (BLOCKVECTOR (symtab) != NULL
3958       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3959     return symtab;
3960
3961   if (symtab->includes == NULL)
3962     return NULL;
3963
3964   for (i = 0; symtab->includes[i]; ++i)
3965     {
3966       struct symtab *s = symtab->includes[i];
3967
3968       s = recursively_find_pc_sect_symtab (s, pc);
3969       if (s != NULL)
3970         return s;
3971     }
3972
3973   return NULL;
3974 }
3975
3976 static struct symtab *
3977 dw2_find_pc_sect_symtab (struct objfile *objfile,
3978                          struct minimal_symbol *msymbol,
3979                          CORE_ADDR pc,
3980                          struct obj_section *section,
3981                          int warn_if_readin)
3982 {
3983   struct dwarf2_per_cu_data *data;
3984   struct symtab *result;
3985
3986   dw2_setup (objfile);
3987
3988   if (!objfile->psymtabs_addrmap)
3989     return NULL;
3990
3991   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3992   if (!data)
3993     return NULL;
3994
3995   if (warn_if_readin && data->v.quick->symtab)
3996     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3997              paddress (get_objfile_arch (objfile), pc));
3998
3999   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
4000   gdb_assert (result != NULL);
4001   return result;
4002 }
4003
4004 static void
4005 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4006                           void *data, int need_fullname)
4007 {
4008   int i;
4009   struct cleanup *cleanup;
4010   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
4011                                       NULL, xcalloc, xfree);
4012
4013   cleanup = make_cleanup_htab_delete (visited);
4014   dw2_setup (objfile);
4015
4016   /* The rule is CUs specify all the files, including those used by
4017      any TU, so there's no need to scan TUs here.
4018      We can ignore file names coming from already-expanded CUs.  */
4019
4020   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4021     {
4022       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4023
4024       if (per_cu->v.quick->symtab)
4025         {
4026           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
4027                                         INSERT);
4028
4029           *slot = per_cu->v.quick->file_names;
4030         }
4031     }
4032
4033   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4034     {
4035       int j;
4036       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
4037       struct quick_file_names *file_data;
4038       void **slot;
4039
4040       /* We only need to look at symtabs not already expanded.  */
4041       if (per_cu->v.quick->symtab)
4042         continue;
4043
4044       file_data = dw2_get_file_names (per_cu);
4045       if (file_data == NULL)
4046         continue;
4047
4048       slot = htab_find_slot (visited, file_data, INSERT);
4049       if (*slot)
4050         {
4051           /* Already visited.  */
4052           continue;
4053         }
4054       *slot = file_data;
4055
4056       for (j = 0; j < file_data->num_file_names; ++j)
4057         {
4058           const char *this_real_name;
4059
4060           if (need_fullname)
4061             this_real_name = dw2_get_real_path (objfile, file_data, j);
4062           else
4063             this_real_name = NULL;
4064           (*fun) (file_data->file_names[j], this_real_name, data);
4065         }
4066     }
4067
4068   do_cleanups (cleanup);
4069 }
4070
4071 static int
4072 dw2_has_symbols (struct objfile *objfile)
4073 {
4074   return 1;
4075 }
4076
4077 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4078 {
4079   dw2_has_symbols,
4080   dw2_find_last_source_symtab,
4081   dw2_forget_cached_source_info,
4082   dw2_map_symtabs_matching_filename,
4083   dw2_lookup_symbol,
4084   dw2_print_stats,
4085   dw2_dump,
4086   dw2_relocate,
4087   dw2_expand_symtabs_for_function,
4088   dw2_expand_all_symtabs,
4089   dw2_expand_symtabs_with_fullname,
4090   dw2_map_matching_symbols,
4091   dw2_expand_symtabs_matching,
4092   dw2_find_pc_sect_symtab,
4093   dw2_map_symbol_filenames
4094 };
4095
4096 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4097    file will use psymtabs, or 1 if using the GNU index.  */
4098
4099 int
4100 dwarf2_initialize_objfile (struct objfile *objfile)
4101 {
4102   /* If we're about to read full symbols, don't bother with the
4103      indices.  In this case we also don't care if some other debug
4104      format is making psymtabs, because they are all about to be
4105      expanded anyway.  */
4106   if ((objfile->flags & OBJF_READNOW))
4107     {
4108       int i;
4109
4110       dwarf2_per_objfile->using_index = 1;
4111       create_all_comp_units (objfile);
4112       create_all_type_units (objfile);
4113       dwarf2_per_objfile->quick_file_names_table =
4114         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4115
4116       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4117                        + dwarf2_per_objfile->n_type_units); ++i)
4118         {
4119           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4120
4121           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4122                                             struct dwarf2_per_cu_quick_data);
4123         }
4124
4125       /* Return 1 so that gdb sees the "quick" functions.  However,
4126          these functions will be no-ops because we will have expanded
4127          all symtabs.  */
4128       return 1;
4129     }
4130
4131   if (dwarf2_read_index (objfile))
4132     return 1;
4133
4134   return 0;
4135 }
4136
4137 \f
4138
4139 /* Build a partial symbol table.  */
4140
4141 void
4142 dwarf2_build_psymtabs (struct objfile *objfile)
4143 {
4144   volatile struct gdb_exception except;
4145
4146   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4147     {
4148       init_psymbol_list (objfile, 1024);
4149     }
4150
4151   TRY_CATCH (except, RETURN_MASK_ERROR)
4152     {
4153       /* This isn't really ideal: all the data we allocate on the
4154          objfile's obstack is still uselessly kept around.  However,
4155          freeing it seems unsafe.  */
4156       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
4157
4158       dwarf2_build_psymtabs_hard (objfile);
4159       discard_cleanups (cleanups);
4160     }
4161   if (except.reason < 0)
4162     exception_print (gdb_stderr, except);
4163 }
4164
4165 /* Return the total length of the CU described by HEADER.  */
4166
4167 static unsigned int
4168 get_cu_length (const struct comp_unit_head *header)
4169 {
4170   return header->initial_length_size + header->length;
4171 }
4172
4173 /* Return TRUE if OFFSET is within CU_HEADER.  */
4174
4175 static inline int
4176 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
4177 {
4178   sect_offset bottom = { cu_header->offset.sect_off };
4179   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
4180
4181   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
4182 }
4183
4184 /* Find the base address of the compilation unit for range lists and
4185    location lists.  It will normally be specified by DW_AT_low_pc.
4186    In DWARF-3 draft 4, the base address could be overridden by
4187    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4188    compilation units with discontinuous ranges.  */
4189
4190 static void
4191 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4192 {
4193   struct attribute *attr;
4194
4195   cu->base_known = 0;
4196   cu->base_address = 0;
4197
4198   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4199   if (attr)
4200     {
4201       cu->base_address = DW_ADDR (attr);
4202       cu->base_known = 1;
4203     }
4204   else
4205     {
4206       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4207       if (attr)
4208         {
4209           cu->base_address = DW_ADDR (attr);
4210           cu->base_known = 1;
4211         }
4212     }
4213 }
4214
4215 /* Read in the comp unit header information from the debug_info at info_ptr.
4216    NOTE: This leaves members offset, first_die_offset to be filled in
4217    by the caller.  */
4218
4219 static const gdb_byte *
4220 read_comp_unit_head (struct comp_unit_head *cu_header,
4221                      const gdb_byte *info_ptr, bfd *abfd)
4222 {
4223   int signed_addr;
4224   unsigned int bytes_read;
4225
4226   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4227   cu_header->initial_length_size = bytes_read;
4228   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4229   info_ptr += bytes_read;
4230   cu_header->version = read_2_bytes (abfd, info_ptr);
4231   info_ptr += 2;
4232   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
4233                                              &bytes_read);
4234   info_ptr += bytes_read;
4235   cu_header->addr_size = read_1_byte (abfd, info_ptr);
4236   info_ptr += 1;
4237   signed_addr = bfd_get_sign_extend_vma (abfd);
4238   if (signed_addr < 0)
4239     internal_error (__FILE__, __LINE__,
4240                     _("read_comp_unit_head: dwarf from non elf file"));
4241   cu_header->signed_addr_p = signed_addr;
4242
4243   return info_ptr;
4244 }
4245
4246 /* Helper function that returns the proper abbrev section for
4247    THIS_CU.  */
4248
4249 static struct dwarf2_section_info *
4250 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4251 {
4252   struct dwarf2_section_info *abbrev;
4253
4254   if (this_cu->is_dwz)
4255     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4256   else
4257     abbrev = &dwarf2_per_objfile->abbrev;
4258
4259   return abbrev;
4260 }
4261
4262 /* Subroutine of read_and_check_comp_unit_head and
4263    read_and_check_type_unit_head to simplify them.
4264    Perform various error checking on the header.  */
4265
4266 static void
4267 error_check_comp_unit_head (struct comp_unit_head *header,
4268                             struct dwarf2_section_info *section,
4269                             struct dwarf2_section_info *abbrev_section)
4270 {
4271   bfd *abfd = get_section_bfd_owner (section);
4272   const char *filename = get_section_file_name (section);
4273
4274   if (header->version != 2 && header->version != 3 && header->version != 4)
4275     error (_("Dwarf Error: wrong version in compilation unit header "
4276            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4277            filename);
4278
4279   if (header->abbrev_offset.sect_off
4280       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4281     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4282            "(offset 0x%lx + 6) [in module %s]"),
4283            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4284            filename);
4285
4286   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4287      avoid potential 32-bit overflow.  */
4288   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4289       > section->size)
4290     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4291            "(offset 0x%lx + 0) [in module %s]"),
4292            (long) header->length, (long) header->offset.sect_off,
4293            filename);
4294 }
4295
4296 /* Read in a CU/TU header and perform some basic error checking.
4297    The contents of the header are stored in HEADER.
4298    The result is a pointer to the start of the first DIE.  */
4299
4300 static const gdb_byte *
4301 read_and_check_comp_unit_head (struct comp_unit_head *header,
4302                                struct dwarf2_section_info *section,
4303                                struct dwarf2_section_info *abbrev_section,
4304                                const gdb_byte *info_ptr,
4305                                int is_debug_types_section)
4306 {
4307   const gdb_byte *beg_of_comp_unit = info_ptr;
4308   bfd *abfd = get_section_bfd_owner (section);
4309
4310   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4311
4312   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4313
4314   /* If we're reading a type unit, skip over the signature and
4315      type_offset fields.  */
4316   if (is_debug_types_section)
4317     info_ptr += 8 /*signature*/ + header->offset_size;
4318
4319   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4320
4321   error_check_comp_unit_head (header, section, abbrev_section);
4322
4323   return info_ptr;
4324 }
4325
4326 /* Read in the types comp unit header information from .debug_types entry at
4327    types_ptr.  The result is a pointer to one past the end of the header.  */
4328
4329 static const gdb_byte *
4330 read_and_check_type_unit_head (struct comp_unit_head *header,
4331                                struct dwarf2_section_info *section,
4332                                struct dwarf2_section_info *abbrev_section,
4333                                const gdb_byte *info_ptr,
4334                                ULONGEST *signature,
4335                                cu_offset *type_offset_in_tu)
4336 {
4337   const gdb_byte *beg_of_comp_unit = info_ptr;
4338   bfd *abfd = get_section_bfd_owner (section);
4339
4340   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4341
4342   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4343
4344   /* If we're reading a type unit, skip over the signature and
4345      type_offset fields.  */
4346   if (signature != NULL)
4347     *signature = read_8_bytes (abfd, info_ptr);
4348   info_ptr += 8;
4349   if (type_offset_in_tu != NULL)
4350     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4351                                                header->offset_size);
4352   info_ptr += header->offset_size;
4353
4354   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4355
4356   error_check_comp_unit_head (header, section, abbrev_section);
4357
4358   return info_ptr;
4359 }
4360
4361 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4362
4363 static sect_offset
4364 read_abbrev_offset (struct dwarf2_section_info *section,
4365                     sect_offset offset)
4366 {
4367   bfd *abfd = get_section_bfd_owner (section);
4368   const gdb_byte *info_ptr;
4369   unsigned int length, initial_length_size, offset_size;
4370   sect_offset abbrev_offset;
4371
4372   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4373   info_ptr = section->buffer + offset.sect_off;
4374   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4375   offset_size = initial_length_size == 4 ? 4 : 8;
4376   info_ptr += initial_length_size + 2 /*version*/;
4377   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4378   return abbrev_offset;
4379 }
4380
4381 /* Allocate a new partial symtab for file named NAME and mark this new
4382    partial symtab as being an include of PST.  */
4383
4384 static void
4385 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4386                                struct objfile *objfile)
4387 {
4388   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4389
4390   if (!IS_ABSOLUTE_PATH (subpst->filename))
4391     {
4392       /* It shares objfile->objfile_obstack.  */
4393       subpst->dirname = pst->dirname;
4394     }
4395
4396   subpst->section_offsets = pst->section_offsets;
4397   subpst->textlow = 0;
4398   subpst->texthigh = 0;
4399
4400   subpst->dependencies = (struct partial_symtab **)
4401     obstack_alloc (&objfile->objfile_obstack,
4402                    sizeof (struct partial_symtab *));
4403   subpst->dependencies[0] = pst;
4404   subpst->number_of_dependencies = 1;
4405
4406   subpst->globals_offset = 0;
4407   subpst->n_global_syms = 0;
4408   subpst->statics_offset = 0;
4409   subpst->n_static_syms = 0;
4410   subpst->symtab = NULL;
4411   subpst->read_symtab = pst->read_symtab;
4412   subpst->readin = 0;
4413
4414   /* No private part is necessary for include psymtabs.  This property
4415      can be used to differentiate between such include psymtabs and
4416      the regular ones.  */
4417   subpst->read_symtab_private = NULL;
4418 }
4419
4420 /* Read the Line Number Program data and extract the list of files
4421    included by the source file represented by PST.  Build an include
4422    partial symtab for each of these included files.  */
4423
4424 static void
4425 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4426                                struct die_info *die,
4427                                struct partial_symtab *pst)
4428 {
4429   struct line_header *lh = NULL;
4430   struct attribute *attr;
4431
4432   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4433   if (attr)
4434     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4435   if (lh == NULL)
4436     return;  /* No linetable, so no includes.  */
4437
4438   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4439   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4440
4441   free_line_header (lh);
4442 }
4443
4444 static hashval_t
4445 hash_signatured_type (const void *item)
4446 {
4447   const struct signatured_type *sig_type = item;
4448
4449   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4450   return sig_type->signature;
4451 }
4452
4453 static int
4454 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4455 {
4456   const struct signatured_type *lhs = item_lhs;
4457   const struct signatured_type *rhs = item_rhs;
4458
4459   return lhs->signature == rhs->signature;
4460 }
4461
4462 /* Allocate a hash table for signatured types.  */
4463
4464 static htab_t
4465 allocate_signatured_type_table (struct objfile *objfile)
4466 {
4467   return htab_create_alloc_ex (41,
4468                                hash_signatured_type,
4469                                eq_signatured_type,
4470                                NULL,
4471                                &objfile->objfile_obstack,
4472                                hashtab_obstack_allocate,
4473                                dummy_obstack_deallocate);
4474 }
4475
4476 /* A helper function to add a signatured type CU to a table.  */
4477
4478 static int
4479 add_signatured_type_cu_to_table (void **slot, void *datum)
4480 {
4481   struct signatured_type *sigt = *slot;
4482   struct signatured_type ***datap = datum;
4483
4484   **datap = sigt;
4485   ++*datap;
4486
4487   return 1;
4488 }
4489
4490 /* Create the hash table of all entries in the .debug_types
4491    (or .debug_types.dwo) section(s).
4492    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4493    otherwise it is NULL.
4494
4495    The result is a pointer to the hash table or NULL if there are no types.
4496
4497    Note: This function processes DWO files only, not DWP files.  */
4498
4499 static htab_t
4500 create_debug_types_hash_table (struct dwo_file *dwo_file,
4501                                VEC (dwarf2_section_info_def) *types)
4502 {
4503   struct objfile *objfile = dwarf2_per_objfile->objfile;
4504   htab_t types_htab = NULL;
4505   int ix;
4506   struct dwarf2_section_info *section;
4507   struct dwarf2_section_info *abbrev_section;
4508
4509   if (VEC_empty (dwarf2_section_info_def, types))
4510     return NULL;
4511
4512   abbrev_section = (dwo_file != NULL
4513                     ? &dwo_file->sections.abbrev
4514                     : &dwarf2_per_objfile->abbrev);
4515
4516   if (dwarf2_read_debug)
4517     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4518                         dwo_file ? ".dwo" : "",
4519                         get_section_file_name (abbrev_section));
4520
4521   for (ix = 0;
4522        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4523        ++ix)
4524     {
4525       bfd *abfd;
4526       const gdb_byte *info_ptr, *end_ptr;
4527
4528       dwarf2_read_section (objfile, section);
4529       info_ptr = section->buffer;
4530
4531       if (info_ptr == NULL)
4532         continue;
4533
4534       /* We can't set abfd until now because the section may be empty or
4535          not present, in which case the bfd is unknown.  */
4536       abfd = get_section_bfd_owner (section);
4537
4538       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4539          because we don't need to read any dies: the signature is in the
4540          header.  */
4541
4542       end_ptr = info_ptr + section->size;
4543       while (info_ptr < end_ptr)
4544         {
4545           sect_offset offset;
4546           cu_offset type_offset_in_tu;
4547           ULONGEST signature;
4548           struct signatured_type *sig_type;
4549           struct dwo_unit *dwo_tu;
4550           void **slot;
4551           const gdb_byte *ptr = info_ptr;
4552           struct comp_unit_head header;
4553           unsigned int length;
4554
4555           offset.sect_off = ptr - section->buffer;
4556
4557           /* We need to read the type's signature in order to build the hash
4558              table, but we don't need anything else just yet.  */
4559
4560           ptr = read_and_check_type_unit_head (&header, section,
4561                                                abbrev_section, ptr,
4562                                                &signature, &type_offset_in_tu);
4563
4564           length = get_cu_length (&header);
4565
4566           /* Skip dummy type units.  */
4567           if (ptr >= info_ptr + length
4568               || peek_abbrev_code (abfd, ptr) == 0)
4569             {
4570               info_ptr += length;
4571               continue;
4572             }
4573
4574           if (types_htab == NULL)
4575             {
4576               if (dwo_file)
4577                 types_htab = allocate_dwo_unit_table (objfile);
4578               else
4579                 types_htab = allocate_signatured_type_table (objfile);
4580             }
4581
4582           if (dwo_file)
4583             {
4584               sig_type = NULL;
4585               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4586                                        struct dwo_unit);
4587               dwo_tu->dwo_file = dwo_file;
4588               dwo_tu->signature = signature;
4589               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4590               dwo_tu->section = section;
4591               dwo_tu->offset = offset;
4592               dwo_tu->length = length;
4593             }
4594           else
4595             {
4596               /* N.B.: type_offset is not usable if this type uses a DWO file.
4597                  The real type_offset is in the DWO file.  */
4598               dwo_tu = NULL;
4599               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4600                                          struct signatured_type);
4601               sig_type->signature = signature;
4602               sig_type->type_offset_in_tu = type_offset_in_tu;
4603               sig_type->per_cu.objfile = objfile;
4604               sig_type->per_cu.is_debug_types = 1;
4605               sig_type->per_cu.section = section;
4606               sig_type->per_cu.offset = offset;
4607               sig_type->per_cu.length = length;
4608             }
4609
4610           slot = htab_find_slot (types_htab,
4611                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4612                                  INSERT);
4613           gdb_assert (slot != NULL);
4614           if (*slot != NULL)
4615             {
4616               sect_offset dup_offset;
4617
4618               if (dwo_file)
4619                 {
4620                   const struct dwo_unit *dup_tu = *slot;
4621
4622                   dup_offset = dup_tu->offset;
4623                 }
4624               else
4625                 {
4626                   const struct signatured_type *dup_tu = *slot;
4627
4628                   dup_offset = dup_tu->per_cu.offset;
4629                 }
4630
4631               complaint (&symfile_complaints,
4632                          _("debug type entry at offset 0x%x is duplicate to"
4633                            " the entry at offset 0x%x, signature %s"),
4634                          offset.sect_off, dup_offset.sect_off,
4635                          hex_string (signature));
4636             }
4637           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4638
4639           if (dwarf2_read_debug > 1)
4640             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4641                                 offset.sect_off,
4642                                 hex_string (signature));
4643
4644           info_ptr += length;
4645         }
4646     }
4647
4648   return types_htab;
4649 }
4650
4651 /* Create the hash table of all entries in the .debug_types section,
4652    and initialize all_type_units.
4653    The result is zero if there is an error (e.g. missing .debug_types section),
4654    otherwise non-zero.  */
4655
4656 static int
4657 create_all_type_units (struct objfile *objfile)
4658 {
4659   htab_t types_htab;
4660   struct signatured_type **iter;
4661
4662   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4663   if (types_htab == NULL)
4664     {
4665       dwarf2_per_objfile->signatured_types = NULL;
4666       return 0;
4667     }
4668
4669   dwarf2_per_objfile->signatured_types = types_htab;
4670
4671   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4672   dwarf2_per_objfile->all_type_units
4673     = xmalloc (dwarf2_per_objfile->n_type_units
4674                * sizeof (struct signatured_type *));
4675   iter = &dwarf2_per_objfile->all_type_units[0];
4676   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4677   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4678               == dwarf2_per_objfile->n_type_units);
4679
4680   return 1;
4681 }
4682
4683 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4684    Fill in SIG_ENTRY with DWO_ENTRY.  */
4685
4686 static void
4687 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4688                                   struct signatured_type *sig_entry,
4689                                   struct dwo_unit *dwo_entry)
4690 {
4691   /* Make sure we're not clobbering something we don't expect to.  */
4692   gdb_assert (! sig_entry->per_cu.queued);
4693   gdb_assert (sig_entry->per_cu.cu == NULL);
4694   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4695   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4696   gdb_assert (sig_entry->signature == dwo_entry->signature);
4697   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4698   gdb_assert (sig_entry->type_unit_group == NULL);
4699   gdb_assert (sig_entry->dwo_unit == NULL);
4700
4701   sig_entry->per_cu.section = dwo_entry->section;
4702   sig_entry->per_cu.offset = dwo_entry->offset;
4703   sig_entry->per_cu.length = dwo_entry->length;
4704   sig_entry->per_cu.reading_dwo_directly = 1;
4705   sig_entry->per_cu.objfile = objfile;
4706   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4707   sig_entry->dwo_unit = dwo_entry;
4708 }
4709
4710 /* Subroutine of lookup_signatured_type.
4711    If we haven't read the TU yet, create the signatured_type data structure
4712    for a TU to be read in directly from a DWO file, bypassing the stub.
4713    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4714    using .gdb_index, then when reading a CU we want to stay in the DWO file
4715    containing that CU.  Otherwise we could end up reading several other DWO
4716    files (due to comdat folding) to process the transitive closure of all the
4717    mentioned TUs, and that can be slow.  The current DWO file will have every
4718    type signature that it needs.
4719    We only do this for .gdb_index because in the psymtab case we already have
4720    to read all the DWOs to build the type unit groups.  */
4721
4722 static struct signatured_type *
4723 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4724 {
4725   struct objfile *objfile = dwarf2_per_objfile->objfile;
4726   struct dwo_file *dwo_file;
4727   struct dwo_unit find_dwo_entry, *dwo_entry;
4728   struct signatured_type find_sig_entry, *sig_entry;
4729
4730   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4731
4732   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4733      dwo_unit of the TU itself.  */
4734   dwo_file = cu->dwo_unit->dwo_file;
4735
4736   /* We only ever need to read in one copy of a signatured type.
4737      Just use the global signatured_types array.  If this is the first time
4738      we're reading this type, replace the recorded data from .gdb_index with
4739      this TU.  */
4740
4741   if (dwarf2_per_objfile->signatured_types == NULL)
4742     return NULL;
4743   find_sig_entry.signature = sig;
4744   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4745   if (sig_entry == NULL)
4746     return NULL;
4747
4748   /* We can get here with the TU already read, *or* in the process of being
4749      read.  Don't reassign it if that's the case.  Also note that if the TU is
4750      already being read, it may not have come from a DWO, the program may be
4751      a mix of Fission-compiled code and non-Fission-compiled code.  */
4752   /* Have we already tried to read this TU?  */
4753   if (sig_entry->per_cu.tu_read)
4754     return sig_entry;
4755
4756   /* Ok, this is the first time we're reading this TU.  */
4757   if (dwo_file->tus == NULL)
4758     return NULL;
4759   find_dwo_entry.signature = sig;
4760   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4761   if (dwo_entry == NULL)
4762     return NULL;
4763
4764   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4765   sig_entry->per_cu.tu_read = 1;
4766   return sig_entry;
4767 }
4768
4769 /* Subroutine of lookup_dwp_signatured_type.
4770    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4771
4772 static struct signatured_type *
4773 add_type_unit (ULONGEST sig)
4774 {
4775   struct objfile *objfile = dwarf2_per_objfile->objfile;
4776   int n_type_units = dwarf2_per_objfile->n_type_units;
4777   struct signatured_type *sig_type;
4778   void **slot;
4779
4780   ++n_type_units;
4781   dwarf2_per_objfile->all_type_units =
4782     xrealloc (dwarf2_per_objfile->all_type_units,
4783               n_type_units * sizeof (struct signatured_type *));
4784   dwarf2_per_objfile->n_type_units = n_type_units;
4785   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4786                              struct signatured_type);
4787   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4788   sig_type->signature = sig;
4789   sig_type->per_cu.is_debug_types = 1;
4790   sig_type->per_cu.v.quick =
4791     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4792                     struct dwarf2_per_cu_quick_data);
4793   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4794                          sig_type, INSERT);
4795   gdb_assert (*slot == NULL);
4796   *slot = sig_type;
4797   /* The rest of sig_type must be filled in by the caller.  */
4798   return sig_type;
4799 }
4800
4801 /* Subroutine of lookup_signatured_type.
4802    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4803    then try the DWP file.
4804    Normally this "can't happen", but if there's a bug in signature
4805    generation and/or the DWP file is built incorrectly, it can happen.
4806    Using the type directly from the DWP file means we don't have the stub
4807    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4808    not critical.  [Eventually the stub may go away for type units anyway.]  */
4809
4810 static struct signatured_type *
4811 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4812 {
4813   struct objfile *objfile = dwarf2_per_objfile->objfile;
4814   struct dwp_file *dwp_file = get_dwp_file ();
4815   struct dwo_unit *dwo_entry;
4816   struct signatured_type find_sig_entry, *sig_entry;
4817
4818   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4819   gdb_assert (dwp_file != NULL);
4820
4821   if (dwarf2_per_objfile->signatured_types != NULL)
4822     {
4823       find_sig_entry.signature = sig;
4824       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4825                              &find_sig_entry);
4826       if (sig_entry != NULL)
4827         return sig_entry;
4828     }
4829
4830   /* This is the "shouldn't happen" case.
4831      Try the DWP file and hope for the best.  */
4832   if (dwp_file->tus == NULL)
4833     return NULL;
4834   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
4835                                       sig, 1 /* is_debug_types */);
4836   if (dwo_entry == NULL)
4837     return NULL;
4838
4839   sig_entry = add_type_unit (sig);
4840   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4841
4842   /* The caller will signal a complaint if we return NULL.
4843      Here we don't return NULL but we still want to complain.  */
4844   complaint (&symfile_complaints,
4845              _("Bad type signature %s referenced by %s at 0x%x,"
4846                " coping by using copy in DWP [in module %s]"),
4847              hex_string (sig),
4848              cu->per_cu->is_debug_types ? "TU" : "CU",
4849              cu->per_cu->offset.sect_off,
4850              objfile_name (objfile));
4851
4852   return sig_entry;
4853 }
4854
4855 /* Lookup a signature based type for DW_FORM_ref_sig8.
4856    Returns NULL if signature SIG is not present in the table.
4857    It is up to the caller to complain about this.  */
4858
4859 static struct signatured_type *
4860 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4861 {
4862   if (cu->dwo_unit
4863       && dwarf2_per_objfile->using_index)
4864     {
4865       /* We're in a DWO/DWP file, and we're using .gdb_index.
4866          These cases require special processing.  */
4867       if (get_dwp_file () == NULL)
4868         return lookup_dwo_signatured_type (cu, sig);
4869       else
4870         return lookup_dwp_signatured_type (cu, sig);
4871     }
4872   else
4873     {
4874       struct signatured_type find_entry, *entry;
4875
4876       if (dwarf2_per_objfile->signatured_types == NULL)
4877         return NULL;
4878       find_entry.signature = sig;
4879       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4880       return entry;
4881     }
4882 }
4883 \f
4884 /* Low level DIE reading support.  */
4885
4886 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4887
4888 static void
4889 init_cu_die_reader (struct die_reader_specs *reader,
4890                     struct dwarf2_cu *cu,
4891                     struct dwarf2_section_info *section,
4892                     struct dwo_file *dwo_file)
4893 {
4894   gdb_assert (section->readin && section->buffer != NULL);
4895   reader->abfd = get_section_bfd_owner (section);
4896   reader->cu = cu;
4897   reader->dwo_file = dwo_file;
4898   reader->die_section = section;
4899   reader->buffer = section->buffer;
4900   reader->buffer_end = section->buffer + section->size;
4901   reader->comp_dir = NULL;
4902 }
4903
4904 /* Subroutine of init_cutu_and_read_dies to simplify it.
4905    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4906    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4907    already.
4908
4909    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4910    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4911    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4912    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4913    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4914    COMP_DIR must be non-NULL.
4915    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4916    are filled in with the info of the DIE from the DWO file.
4917    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4918    provided an abbrev table to use.
4919    The result is non-zero if a valid (non-dummy) DIE was found.  */
4920
4921 static int
4922 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4923                         struct dwo_unit *dwo_unit,
4924                         int abbrev_table_provided,
4925                         struct die_info *stub_comp_unit_die,
4926                         const char *stub_comp_dir,
4927                         struct die_reader_specs *result_reader,
4928                         const gdb_byte **result_info_ptr,
4929                         struct die_info **result_comp_unit_die,
4930                         int *result_has_children)
4931 {
4932   struct objfile *objfile = dwarf2_per_objfile->objfile;
4933   struct dwarf2_cu *cu = this_cu->cu;
4934   struct dwarf2_section_info *section;
4935   bfd *abfd;
4936   const gdb_byte *begin_info_ptr, *info_ptr;
4937   const char *comp_dir_string;
4938   ULONGEST signature; /* Or dwo_id.  */
4939   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4940   int i,num_extra_attrs;
4941   struct dwarf2_section_info *dwo_abbrev_section;
4942   struct attribute *attr;
4943   struct attribute comp_dir_attr;
4944   struct die_info *comp_unit_die;
4945
4946   /* Both can't be provided.  */
4947   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4948
4949   /* These attributes aren't processed until later:
4950      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4951      However, the attribute is found in the stub which we won't have later.
4952      In order to not impose this complication on the rest of the code,
4953      we read them here and copy them to the DWO CU/TU die.  */
4954
4955   stmt_list = NULL;
4956   low_pc = NULL;
4957   high_pc = NULL;
4958   ranges = NULL;
4959   comp_dir = NULL;
4960
4961   if (stub_comp_unit_die != NULL)
4962     {
4963       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4964          DWO file.  */
4965       if (! this_cu->is_debug_types)
4966         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4967       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4968       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4969       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4970       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4971
4972       /* There should be a DW_AT_addr_base attribute here (if needed).
4973          We need the value before we can process DW_FORM_GNU_addr_index.  */
4974       cu->addr_base = 0;
4975       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4976       if (attr)
4977         cu->addr_base = DW_UNSND (attr);
4978
4979       /* There should be a DW_AT_ranges_base attribute here (if needed).
4980          We need the value before we can process DW_AT_ranges.  */
4981       cu->ranges_base = 0;
4982       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4983       if (attr)
4984         cu->ranges_base = DW_UNSND (attr);
4985     }
4986   else if (stub_comp_dir != NULL)
4987     {
4988       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4989       comp_dir = (struct attribute *)
4990         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4991       comp_dir->name = DW_AT_comp_dir;
4992       comp_dir->form = DW_FORM_string;
4993       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4994       DW_STRING (comp_dir) = stub_comp_dir;
4995     }
4996
4997   /* Set up for reading the DWO CU/TU.  */
4998   cu->dwo_unit = dwo_unit;
4999   section = dwo_unit->section;
5000   dwarf2_read_section (objfile, section);
5001   abfd = get_section_bfd_owner (section);
5002   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
5003   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5004   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5005
5006   if (this_cu->is_debug_types)
5007     {
5008       ULONGEST header_signature;
5009       cu_offset type_offset_in_tu;
5010       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5011
5012       info_ptr = read_and_check_type_unit_head (&cu->header, section,
5013                                                 dwo_abbrev_section,
5014                                                 info_ptr,
5015                                                 &header_signature,
5016                                                 &type_offset_in_tu);
5017       /* This is not an assert because it can be caused by bad debug info.  */
5018       if (sig_type->signature != header_signature)
5019         {
5020           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5021                    " TU at offset 0x%x [in module %s]"),
5022                  hex_string (sig_type->signature),
5023                  hex_string (header_signature),
5024                  dwo_unit->offset.sect_off,
5025                  bfd_get_filename (abfd));
5026         }
5027       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5028       /* For DWOs coming from DWP files, we don't know the CU length
5029          nor the type's offset in the TU until now.  */
5030       dwo_unit->length = get_cu_length (&cu->header);
5031       dwo_unit->type_offset_in_tu = type_offset_in_tu;
5032
5033       /* Establish the type offset that can be used to lookup the type.
5034          For DWO files, we don't know it until now.  */
5035       sig_type->type_offset_in_section.sect_off =
5036         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
5037     }
5038   else
5039     {
5040       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5041                                                 dwo_abbrev_section,
5042                                                 info_ptr, 0);
5043       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5044       /* For DWOs coming from DWP files, we don't know the CU length
5045          until now.  */
5046       dwo_unit->length = get_cu_length (&cu->header);
5047     }
5048
5049   /* Replace the CU's original abbrev table with the DWO's.
5050      Reminder: We can't read the abbrev table until we've read the header.  */
5051   if (abbrev_table_provided)
5052     {
5053       /* Don't free the provided abbrev table, the caller of
5054          init_cutu_and_read_dies owns it.  */
5055       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5056       /* Ensure the DWO abbrev table gets freed.  */
5057       make_cleanup (dwarf2_free_abbrev_table, cu);
5058     }
5059   else
5060     {
5061       dwarf2_free_abbrev_table (cu);
5062       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5063       /* Leave any existing abbrev table cleanup as is.  */
5064     }
5065
5066   /* Read in the die, but leave space to copy over the attributes
5067      from the stub.  This has the benefit of simplifying the rest of
5068      the code - all the work to maintain the illusion of a single
5069      DW_TAG_{compile,type}_unit DIE is done here.  */
5070   num_extra_attrs = ((stmt_list != NULL)
5071                      + (low_pc != NULL)
5072                      + (high_pc != NULL)
5073                      + (ranges != NULL)
5074                      + (comp_dir != NULL));
5075   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5076                               result_has_children, num_extra_attrs);
5077
5078   /* Copy over the attributes from the stub to the DIE we just read in.  */
5079   comp_unit_die = *result_comp_unit_die;
5080   i = comp_unit_die->num_attrs;
5081   if (stmt_list != NULL)
5082     comp_unit_die->attrs[i++] = *stmt_list;
5083   if (low_pc != NULL)
5084     comp_unit_die->attrs[i++] = *low_pc;
5085   if (high_pc != NULL)
5086     comp_unit_die->attrs[i++] = *high_pc;
5087   if (ranges != NULL)
5088     comp_unit_die->attrs[i++] = *ranges;
5089   if (comp_dir != NULL)
5090     comp_unit_die->attrs[i++] = *comp_dir;
5091   comp_unit_die->num_attrs += num_extra_attrs;
5092
5093   if (dwarf2_die_debug)
5094     {
5095       fprintf_unfiltered (gdb_stdlog,
5096                           "Read die from %s@0x%x of %s:\n",
5097                           get_section_name (section),
5098                           (unsigned) (begin_info_ptr - section->buffer),
5099                           bfd_get_filename (abfd));
5100       dump_die (comp_unit_die, dwarf2_die_debug);
5101     }
5102
5103   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5104      TUs by skipping the stub and going directly to the entry in the DWO file.
5105      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5106      to get it via circuitous means.  Blech.  */
5107   if (comp_dir != NULL)
5108     result_reader->comp_dir = DW_STRING (comp_dir);
5109
5110   /* Skip dummy compilation units.  */
5111   if (info_ptr >= begin_info_ptr + dwo_unit->length
5112       || peek_abbrev_code (abfd, info_ptr) == 0)
5113     return 0;
5114
5115   *result_info_ptr = info_ptr;
5116   return 1;
5117 }
5118
5119 /* Subroutine of init_cutu_and_read_dies to simplify it.
5120    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5121    Returns NULL if the specified DWO unit cannot be found.  */
5122
5123 static struct dwo_unit *
5124 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5125                  struct die_info *comp_unit_die)
5126 {
5127   struct dwarf2_cu *cu = this_cu->cu;
5128   struct attribute *attr;
5129   ULONGEST signature;
5130   struct dwo_unit *dwo_unit;
5131   const char *comp_dir, *dwo_name;
5132
5133   gdb_assert (cu != NULL);
5134
5135   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5136   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5137   gdb_assert (attr != NULL);
5138   dwo_name = DW_STRING (attr);
5139   comp_dir = NULL;
5140   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5141   if (attr)
5142     comp_dir = DW_STRING (attr);
5143
5144   if (this_cu->is_debug_types)
5145     {
5146       struct signatured_type *sig_type;
5147
5148       /* Since this_cu is the first member of struct signatured_type,
5149          we can go from a pointer to one to a pointer to the other.  */
5150       sig_type = (struct signatured_type *) this_cu;
5151       signature = sig_type->signature;
5152       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5153     }
5154   else
5155     {
5156       struct attribute *attr;
5157
5158       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5159       if (! attr)
5160         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5161                  " [in module %s]"),
5162                dwo_name, objfile_name (this_cu->objfile));
5163       signature = DW_UNSND (attr);
5164       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5165                                        signature);
5166     }
5167
5168   return dwo_unit;
5169 }
5170
5171 /* Subroutine of init_cutu_and_read_dies to simplify it.
5172    Read a TU directly from a DWO file, bypassing the stub.  */
5173
5174 static void
5175 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
5176                            die_reader_func_ftype *die_reader_func,
5177                            void *data)
5178 {
5179   struct dwarf2_cu *cu;
5180   struct signatured_type *sig_type;
5181   struct cleanup *cleanups, *free_cu_cleanup;
5182   struct die_reader_specs reader;
5183   const gdb_byte *info_ptr;
5184   struct die_info *comp_unit_die;
5185   int has_children;
5186
5187   /* Verify we can do the following downcast, and that we have the
5188      data we need.  */
5189   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5190   sig_type = (struct signatured_type *) this_cu;
5191   gdb_assert (sig_type->dwo_unit != NULL);
5192
5193   cleanups = make_cleanup (null_cleanup, NULL);
5194
5195   gdb_assert (this_cu->cu == NULL);
5196   cu = xmalloc (sizeof (*cu));
5197   init_one_comp_unit (cu, this_cu);
5198   /* If an error occurs while loading, release our storage.  */
5199   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5200
5201   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5202                               0 /* abbrev_table_provided */,
5203                               NULL /* stub_comp_unit_die */,
5204                               sig_type->dwo_unit->dwo_file->comp_dir,
5205                               &reader, &info_ptr,
5206                               &comp_unit_die, &has_children) == 0)
5207     {
5208       /* Dummy die.  */
5209       do_cleanups (cleanups);
5210       return;
5211     }
5212
5213   /* All the "real" work is done here.  */
5214   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5215
5216   /* This duplicates some code in init_cutu_and_read_dies,
5217      but the alternative is making the latter more complex.
5218      This function is only for the special case of using DWO files directly:
5219      no point in overly complicating the general case just to handle this.  */
5220   if (keep)
5221     {
5222       /* We've successfully allocated this compilation unit.  Let our
5223          caller clean it up when finished with it.  */
5224       discard_cleanups (free_cu_cleanup);
5225
5226       /* We can only discard free_cu_cleanup and all subsequent cleanups.
5227          So we have to manually free the abbrev table.  */
5228       dwarf2_free_abbrev_table (cu);
5229
5230       /* Link this CU into read_in_chain.  */
5231       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5232       dwarf2_per_objfile->read_in_chain = this_cu;
5233     }
5234   else
5235     do_cleanups (free_cu_cleanup);
5236
5237   do_cleanups (cleanups);
5238 }
5239
5240 /* Initialize a CU (or TU) and read its DIEs.
5241    If the CU defers to a DWO file, read the DWO file as well.
5242
5243    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5244    Otherwise the table specified in the comp unit header is read in and used.
5245    This is an optimization for when we already have the abbrev table.
5246
5247    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5248    Otherwise, a new CU is allocated with xmalloc.
5249
5250    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5251    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5252
5253    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5254    linker) then DIE_READER_FUNC will not get called.  */
5255
5256 static void
5257 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5258                          struct abbrev_table *abbrev_table,
5259                          int use_existing_cu, int keep,
5260                          die_reader_func_ftype *die_reader_func,
5261                          void *data)
5262 {
5263   struct objfile *objfile = dwarf2_per_objfile->objfile;
5264   struct dwarf2_section_info *section = this_cu->section;
5265   bfd *abfd = get_section_bfd_owner (section);
5266   struct dwarf2_cu *cu;
5267   const gdb_byte *begin_info_ptr, *info_ptr;
5268   struct die_reader_specs reader;
5269   struct die_info *comp_unit_die;
5270   int has_children;
5271   struct attribute *attr;
5272   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5273   struct signatured_type *sig_type = NULL;
5274   struct dwarf2_section_info *abbrev_section;
5275   /* Non-zero if CU currently points to a DWO file and we need to
5276      reread it.  When this happens we need to reread the skeleton die
5277      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5278   int rereading_dwo_cu = 0;
5279
5280   if (dwarf2_die_debug)
5281     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5282                         this_cu->is_debug_types ? "type" : "comp",
5283                         this_cu->offset.sect_off);
5284
5285   if (use_existing_cu)
5286     gdb_assert (keep);
5287
5288   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5289      file (instead of going through the stub), short-circuit all of this.  */
5290   if (this_cu->reading_dwo_directly)
5291     {
5292       /* Narrow down the scope of possibilities to have to understand.  */
5293       gdb_assert (this_cu->is_debug_types);
5294       gdb_assert (abbrev_table == NULL);
5295       gdb_assert (!use_existing_cu);
5296       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5297       return;
5298     }
5299
5300   cleanups = make_cleanup (null_cleanup, NULL);
5301
5302   /* This is cheap if the section is already read in.  */
5303   dwarf2_read_section (objfile, section);
5304
5305   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5306
5307   abbrev_section = get_abbrev_section_for_cu (this_cu);
5308
5309   if (use_existing_cu && this_cu->cu != NULL)
5310     {
5311       cu = this_cu->cu;
5312
5313       /* If this CU is from a DWO file we need to start over, we need to
5314          refetch the attributes from the skeleton CU.
5315          This could be optimized by retrieving those attributes from when we
5316          were here the first time: the previous comp_unit_die was stored in
5317          comp_unit_obstack.  But there's no data yet that we need this
5318          optimization.  */
5319       if (cu->dwo_unit != NULL)
5320         rereading_dwo_cu = 1;
5321     }
5322   else
5323     {
5324       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5325       gdb_assert (this_cu->cu == NULL);
5326
5327       cu = xmalloc (sizeof (*cu));
5328       init_one_comp_unit (cu, this_cu);
5329
5330       /* If an error occurs while loading, release our storage.  */
5331       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5332     }
5333
5334   /* Get the header.  */
5335   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5336     {
5337       /* We already have the header, there's no need to read it in again.  */
5338       info_ptr += cu->header.first_die_offset.cu_off;
5339     }
5340   else
5341     {
5342       if (this_cu->is_debug_types)
5343         {
5344           ULONGEST signature;
5345           cu_offset type_offset_in_tu;
5346
5347           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5348                                                     abbrev_section, info_ptr,
5349                                                     &signature,
5350                                                     &type_offset_in_tu);
5351
5352           /* Since per_cu is the first member of struct signatured_type,
5353              we can go from a pointer to one to a pointer to the other.  */
5354           sig_type = (struct signatured_type *) this_cu;
5355           gdb_assert (sig_type->signature == signature);
5356           gdb_assert (sig_type->type_offset_in_tu.cu_off
5357                       == type_offset_in_tu.cu_off);
5358           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5359
5360           /* LENGTH has not been set yet for type units if we're
5361              using .gdb_index.  */
5362           this_cu->length = get_cu_length (&cu->header);
5363
5364           /* Establish the type offset that can be used to lookup the type.  */
5365           sig_type->type_offset_in_section.sect_off =
5366             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5367         }
5368       else
5369         {
5370           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5371                                                     abbrev_section,
5372                                                     info_ptr, 0);
5373
5374           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5375           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5376         }
5377     }
5378
5379   /* Skip dummy compilation units.  */
5380   if (info_ptr >= begin_info_ptr + this_cu->length
5381       || peek_abbrev_code (abfd, info_ptr) == 0)
5382     {
5383       do_cleanups (cleanups);
5384       return;
5385     }
5386
5387   /* If we don't have them yet, read the abbrevs for this compilation unit.
5388      And if we need to read them now, make sure they're freed when we're
5389      done.  Note that it's important that if the CU had an abbrev table
5390      on entry we don't free it when we're done: Somewhere up the call stack
5391      it may be in use.  */
5392   if (abbrev_table != NULL)
5393     {
5394       gdb_assert (cu->abbrev_table == NULL);
5395       gdb_assert (cu->header.abbrev_offset.sect_off
5396                   == abbrev_table->offset.sect_off);
5397       cu->abbrev_table = abbrev_table;
5398     }
5399   else if (cu->abbrev_table == NULL)
5400     {
5401       dwarf2_read_abbrevs (cu, abbrev_section);
5402       make_cleanup (dwarf2_free_abbrev_table, cu);
5403     }
5404   else if (rereading_dwo_cu)
5405     {
5406       dwarf2_free_abbrev_table (cu);
5407       dwarf2_read_abbrevs (cu, abbrev_section);
5408     }
5409
5410   /* Read the top level CU/TU die.  */
5411   init_cu_die_reader (&reader, cu, section, NULL);
5412   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5413
5414   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5415      from the DWO file.
5416      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5417      DWO CU, that this test will fail (the attribute will not be present).  */
5418   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5419   if (attr)
5420     {
5421       struct dwo_unit *dwo_unit;
5422       struct die_info *dwo_comp_unit_die;
5423
5424       if (has_children)
5425         {
5426           complaint (&symfile_complaints,
5427                      _("compilation unit with DW_AT_GNU_dwo_name"
5428                        " has children (offset 0x%x) [in module %s]"),
5429                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5430         }
5431       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5432       if (dwo_unit != NULL)
5433         {
5434           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5435                                       abbrev_table != NULL,
5436                                       comp_unit_die, NULL,
5437                                       &reader, &info_ptr,
5438                                       &dwo_comp_unit_die, &has_children) == 0)
5439             {
5440               /* Dummy die.  */
5441               do_cleanups (cleanups);
5442               return;
5443             }
5444           comp_unit_die = dwo_comp_unit_die;
5445         }
5446       else
5447         {
5448           /* Yikes, we couldn't find the rest of the DIE, we only have
5449              the stub.  A complaint has already been logged.  There's
5450              not much more we can do except pass on the stub DIE to
5451              die_reader_func.  We don't want to throw an error on bad
5452              debug info.  */
5453         }
5454     }
5455
5456   /* All of the above is setup for this call.  Yikes.  */
5457   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5458
5459   /* Done, clean up.  */
5460   if (free_cu_cleanup != NULL)
5461     {
5462       if (keep)
5463         {
5464           /* We've successfully allocated this compilation unit.  Let our
5465              caller clean it up when finished with it.  */
5466           discard_cleanups (free_cu_cleanup);
5467
5468           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5469              So we have to manually free the abbrev table.  */
5470           dwarf2_free_abbrev_table (cu);
5471
5472           /* Link this CU into read_in_chain.  */
5473           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5474           dwarf2_per_objfile->read_in_chain = this_cu;
5475         }
5476       else
5477         do_cleanups (free_cu_cleanup);
5478     }
5479
5480   do_cleanups (cleanups);
5481 }
5482
5483 /* Read CU/TU THIS_CU in section SECTION,
5484    but do not follow DW_AT_GNU_dwo_name if present.
5485    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5486    to have already done the lookup to find the DWO/DWP file).
5487
5488    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5489    THIS_CU->is_debug_types, but nothing else.
5490
5491    We fill in THIS_CU->length.
5492
5493    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5494    linker) then DIE_READER_FUNC will not get called.
5495
5496    THIS_CU->cu is always freed when done.
5497    This is done in order to not leave THIS_CU->cu in a state where we have
5498    to care whether it refers to the "main" CU or the DWO CU.  */
5499
5500 static void
5501 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5502                                    struct dwarf2_section_info *abbrev_section,
5503                                    struct dwo_file *dwo_file,
5504                                    die_reader_func_ftype *die_reader_func,
5505                                    void *data)
5506 {
5507   struct objfile *objfile = dwarf2_per_objfile->objfile;
5508   struct dwarf2_section_info *section = this_cu->section;
5509   bfd *abfd = get_section_bfd_owner (section);
5510   struct dwarf2_cu cu;
5511   const gdb_byte *begin_info_ptr, *info_ptr;
5512   struct die_reader_specs reader;
5513   struct cleanup *cleanups;
5514   struct die_info *comp_unit_die;
5515   int has_children;
5516
5517   if (dwarf2_die_debug)
5518     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5519                         this_cu->is_debug_types ? "type" : "comp",
5520                         this_cu->offset.sect_off);
5521
5522   gdb_assert (this_cu->cu == NULL);
5523
5524   /* This is cheap if the section is already read in.  */
5525   dwarf2_read_section (objfile, section);
5526
5527   init_one_comp_unit (&cu, this_cu);
5528
5529   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5530
5531   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5532   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5533                                             abbrev_section, info_ptr,
5534                                             this_cu->is_debug_types);
5535
5536   this_cu->length = get_cu_length (&cu.header);
5537
5538   /* Skip dummy compilation units.  */
5539   if (info_ptr >= begin_info_ptr + this_cu->length
5540       || peek_abbrev_code (abfd, info_ptr) == 0)
5541     {
5542       do_cleanups (cleanups);
5543       return;
5544     }
5545
5546   dwarf2_read_abbrevs (&cu, abbrev_section);
5547   make_cleanup (dwarf2_free_abbrev_table, &cu);
5548
5549   init_cu_die_reader (&reader, &cu, section, dwo_file);
5550   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5551
5552   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5553
5554   do_cleanups (cleanups);
5555 }
5556
5557 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5558    does not lookup the specified DWO file.
5559    This cannot be used to read DWO files.
5560
5561    THIS_CU->cu is always freed when done.
5562    This is done in order to not leave THIS_CU->cu in a state where we have
5563    to care whether it refers to the "main" CU or the DWO CU.
5564    We can revisit this if the data shows there's a performance issue.  */
5565
5566 static void
5567 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5568                                 die_reader_func_ftype *die_reader_func,
5569                                 void *data)
5570 {
5571   init_cutu_and_read_dies_no_follow (this_cu,
5572                                      get_abbrev_section_for_cu (this_cu),
5573                                      NULL,
5574                                      die_reader_func, data);
5575 }
5576 \f
5577 /* Type Unit Groups.
5578
5579    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5580    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5581    so that all types coming from the same compilation (.o file) are grouped
5582    together.  A future step could be to put the types in the same symtab as
5583    the CU the types ultimately came from.  */
5584
5585 static hashval_t
5586 hash_type_unit_group (const void *item)
5587 {
5588   const struct type_unit_group *tu_group = item;
5589
5590   return hash_stmt_list_entry (&tu_group->hash);
5591 }
5592
5593 static int
5594 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5595 {
5596   const struct type_unit_group *lhs = item_lhs;
5597   const struct type_unit_group *rhs = item_rhs;
5598
5599   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5600 }
5601
5602 /* Allocate a hash table for type unit groups.  */
5603
5604 static htab_t
5605 allocate_type_unit_groups_table (void)
5606 {
5607   return htab_create_alloc_ex (3,
5608                                hash_type_unit_group,
5609                                eq_type_unit_group,
5610                                NULL,
5611                                &dwarf2_per_objfile->objfile->objfile_obstack,
5612                                hashtab_obstack_allocate,
5613                                dummy_obstack_deallocate);
5614 }
5615
5616 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5617    partial symtabs.  We combine several TUs per psymtab to not let the size
5618    of any one psymtab grow too big.  */
5619 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5620 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5621
5622 /* Helper routine for get_type_unit_group.
5623    Create the type_unit_group object used to hold one or more TUs.  */
5624
5625 static struct type_unit_group *
5626 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5627 {
5628   struct objfile *objfile = dwarf2_per_objfile->objfile;
5629   struct dwarf2_per_cu_data *per_cu;
5630   struct type_unit_group *tu_group;
5631
5632   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5633                              struct type_unit_group);
5634   per_cu = &tu_group->per_cu;
5635   per_cu->objfile = objfile;
5636
5637   if (dwarf2_per_objfile->using_index)
5638     {
5639       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5640                                         struct dwarf2_per_cu_quick_data);
5641     }
5642   else
5643     {
5644       unsigned int line_offset = line_offset_struct.sect_off;
5645       struct partial_symtab *pst;
5646       char *name;
5647
5648       /* Give the symtab a useful name for debug purposes.  */
5649       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5650         name = xstrprintf ("<type_units_%d>",
5651                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5652       else
5653         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5654
5655       pst = create_partial_symtab (per_cu, name);
5656       pst->anonymous = 1;
5657
5658       xfree (name);
5659     }
5660
5661   tu_group->hash.dwo_unit = cu->dwo_unit;
5662   tu_group->hash.line_offset = line_offset_struct;
5663
5664   return tu_group;
5665 }
5666
5667 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5668    STMT_LIST is a DW_AT_stmt_list attribute.  */
5669
5670 static struct type_unit_group *
5671 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5672 {
5673   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5674   struct type_unit_group *tu_group;
5675   void **slot;
5676   unsigned int line_offset;
5677   struct type_unit_group type_unit_group_for_lookup;
5678
5679   if (dwarf2_per_objfile->type_unit_groups == NULL)
5680     {
5681       dwarf2_per_objfile->type_unit_groups =
5682         allocate_type_unit_groups_table ();
5683     }
5684
5685   /* Do we need to create a new group, or can we use an existing one?  */
5686
5687   if (stmt_list)
5688     {
5689       line_offset = DW_UNSND (stmt_list);
5690       ++tu_stats->nr_symtab_sharers;
5691     }
5692   else
5693     {
5694       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5695          We can do various things here like create one group per TU or
5696          spread them over multiple groups to split up the expansion work.
5697          To avoid worst case scenarios (too many groups or too large groups)
5698          we, umm, group them in bunches.  */
5699       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5700                      | (tu_stats->nr_stmt_less_type_units
5701                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5702       ++tu_stats->nr_stmt_less_type_units;
5703     }
5704
5705   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5706   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5707   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5708                          &type_unit_group_for_lookup, INSERT);
5709   if (*slot != NULL)
5710     {
5711       tu_group = *slot;
5712       gdb_assert (tu_group != NULL);
5713     }
5714   else
5715     {
5716       sect_offset line_offset_struct;
5717
5718       line_offset_struct.sect_off = line_offset;
5719       tu_group = create_type_unit_group (cu, line_offset_struct);
5720       *slot = tu_group;
5721       ++tu_stats->nr_symtabs;
5722     }
5723
5724   return tu_group;
5725 }
5726
5727 /* Struct used to sort TUs by their abbreviation table offset.  */
5728
5729 struct tu_abbrev_offset
5730 {
5731   struct signatured_type *sig_type;
5732   sect_offset abbrev_offset;
5733 };
5734
5735 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5736
5737 static int
5738 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5739 {
5740   const struct tu_abbrev_offset * const *a = ap;
5741   const struct tu_abbrev_offset * const *b = bp;
5742   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5743   unsigned int boff = (*b)->abbrev_offset.sect_off;
5744
5745   return (aoff > boff) - (aoff < boff);
5746 }
5747
5748 /* A helper function to add a type_unit_group to a table.  */
5749
5750 static int
5751 add_type_unit_group_to_table (void **slot, void *datum)
5752 {
5753   struct type_unit_group *tu_group = *slot;
5754   struct type_unit_group ***datap = datum;
5755
5756   **datap = tu_group;
5757   ++*datap;
5758
5759   return 1;
5760 }
5761
5762 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5763    each one passing FUNC,DATA.
5764
5765    The efficiency is because we sort TUs by the abbrev table they use and
5766    only read each abbrev table once.  In one program there are 200K TUs
5767    sharing 8K abbrev tables.
5768
5769    The main purpose of this function is to support building the
5770    dwarf2_per_objfile->type_unit_groups table.
5771    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5772    can collapse the search space by grouping them by stmt_list.
5773    The savings can be significant, in the same program from above the 200K TUs
5774    share 8K stmt_list tables.
5775
5776    FUNC is expected to call get_type_unit_group, which will create the
5777    struct type_unit_group if necessary and add it to
5778    dwarf2_per_objfile->type_unit_groups.  */
5779
5780 static void
5781 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5782 {
5783   struct objfile *objfile = dwarf2_per_objfile->objfile;
5784   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5785   struct cleanup *cleanups;
5786   struct abbrev_table *abbrev_table;
5787   sect_offset abbrev_offset;
5788   struct tu_abbrev_offset *sorted_by_abbrev;
5789   struct type_unit_group **iter;
5790   int i;
5791
5792   /* It's up to the caller to not call us multiple times.  */
5793   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5794
5795   if (dwarf2_per_objfile->n_type_units == 0)
5796     return;
5797
5798   /* TUs typically share abbrev tables, and there can be way more TUs than
5799      abbrev tables.  Sort by abbrev table to reduce the number of times we
5800      read each abbrev table in.
5801      Alternatives are to punt or to maintain a cache of abbrev tables.
5802      This is simpler and efficient enough for now.
5803
5804      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5805      symtab to use).  Typically TUs with the same abbrev offset have the same
5806      stmt_list value too so in practice this should work well.
5807
5808      The basic algorithm here is:
5809
5810       sort TUs by abbrev table
5811       for each TU with same abbrev table:
5812         read abbrev table if first user
5813         read TU top level DIE
5814           [IWBN if DWO skeletons had DW_AT_stmt_list]
5815         call FUNC  */
5816
5817   if (dwarf2_read_debug)
5818     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5819
5820   /* Sort in a separate table to maintain the order of all_type_units
5821      for .gdb_index: TU indices directly index all_type_units.  */
5822   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5823                               dwarf2_per_objfile->n_type_units);
5824   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5825     {
5826       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5827
5828       sorted_by_abbrev[i].sig_type = sig_type;
5829       sorted_by_abbrev[i].abbrev_offset =
5830         read_abbrev_offset (sig_type->per_cu.section,
5831                             sig_type->per_cu.offset);
5832     }
5833   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5834   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5835          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5836
5837   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5838      called any number of times, so we don't reset tu_stats here.  */
5839
5840   abbrev_offset.sect_off = ~(unsigned) 0;
5841   abbrev_table = NULL;
5842   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5843
5844   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5845     {
5846       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5847
5848       /* Switch to the next abbrev table if necessary.  */
5849       if (abbrev_table == NULL
5850           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5851         {
5852           if (abbrev_table != NULL)
5853             {
5854               abbrev_table_free (abbrev_table);
5855               /* Reset to NULL in case abbrev_table_read_table throws
5856                  an error: abbrev_table_free_cleanup will get called.  */
5857               abbrev_table = NULL;
5858             }
5859           abbrev_offset = tu->abbrev_offset;
5860           abbrev_table =
5861             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5862                                      abbrev_offset);
5863           ++tu_stats->nr_uniq_abbrev_tables;
5864         }
5865
5866       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5867                                func, data);
5868     }
5869
5870   /* type_unit_groups can be NULL if there is an error in the debug info.
5871      Just create an empty table so the rest of gdb doesn't have to watch
5872      for this error case.  */
5873   if (dwarf2_per_objfile->type_unit_groups == NULL)
5874     {
5875       dwarf2_per_objfile->type_unit_groups =
5876         allocate_type_unit_groups_table ();
5877       dwarf2_per_objfile->n_type_unit_groups = 0;
5878     }
5879
5880   /* Create a vector of pointers to primary type units to make it easy to
5881      iterate over them and CUs.  See dw2_get_primary_cu.  */
5882   dwarf2_per_objfile->n_type_unit_groups =
5883     htab_elements (dwarf2_per_objfile->type_unit_groups);
5884   dwarf2_per_objfile->all_type_unit_groups =
5885     obstack_alloc (&objfile->objfile_obstack,
5886                    dwarf2_per_objfile->n_type_unit_groups
5887                    * sizeof (struct type_unit_group *));
5888   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5889   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5890                           add_type_unit_group_to_table, &iter);
5891   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5892               == dwarf2_per_objfile->n_type_unit_groups);
5893
5894   do_cleanups (cleanups);
5895
5896   if (dwarf2_read_debug)
5897     {
5898       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5899       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5900                           dwarf2_per_objfile->n_type_units);
5901       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5902                           tu_stats->nr_uniq_abbrev_tables);
5903       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5904                           tu_stats->nr_symtabs);
5905       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5906                           tu_stats->nr_symtab_sharers);
5907       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5908                           tu_stats->nr_stmt_less_type_units);
5909     }
5910 }
5911 \f
5912 /* Partial symbol tables.  */
5913
5914 /* Create a psymtab named NAME and assign it to PER_CU.
5915
5916    The caller must fill in the following details:
5917    dirname, textlow, texthigh.  */
5918
5919 static struct partial_symtab *
5920 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5921 {
5922   struct objfile *objfile = per_cu->objfile;
5923   struct partial_symtab *pst;
5924
5925   pst = start_psymtab_common (objfile, objfile->section_offsets,
5926                               name, 0,
5927                               objfile->global_psymbols.next,
5928                               objfile->static_psymbols.next);
5929
5930   pst->psymtabs_addrmap_supported = 1;
5931
5932   /* This is the glue that links PST into GDB's symbol API.  */
5933   pst->read_symtab_private = per_cu;
5934   pst->read_symtab = dwarf2_read_symtab;
5935   per_cu->v.psymtab = pst;
5936
5937   return pst;
5938 }
5939
5940 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5941    type.  */
5942
5943 struct process_psymtab_comp_unit_data
5944 {
5945   /* True if we are reading a DW_TAG_partial_unit.  */
5946
5947   int want_partial_unit;
5948
5949   /* The "pretend" language that is used if the CU doesn't declare a
5950      language.  */
5951
5952   enum language pretend_language;
5953 };
5954
5955 /* die_reader_func for process_psymtab_comp_unit.  */
5956
5957 static void
5958 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5959                                   const gdb_byte *info_ptr,
5960                                   struct die_info *comp_unit_die,
5961                                   int has_children,
5962                                   void *data)
5963 {
5964   struct dwarf2_cu *cu = reader->cu;
5965   struct objfile *objfile = cu->objfile;
5966   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5967   struct attribute *attr;
5968   CORE_ADDR baseaddr;
5969   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5970   struct partial_symtab *pst;
5971   int has_pc_info;
5972   const char *filename;
5973   struct process_psymtab_comp_unit_data *info = data;
5974
5975   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5976     return;
5977
5978   gdb_assert (! per_cu->is_debug_types);
5979
5980   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5981
5982   cu->list_in_scope = &file_symbols;
5983
5984   /* Allocate a new partial symbol table structure.  */
5985   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5986   if (attr == NULL || !DW_STRING (attr))
5987     filename = "";
5988   else
5989     filename = DW_STRING (attr);
5990
5991   pst = create_partial_symtab (per_cu, filename);
5992
5993   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5994   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5995   if (attr != NULL)
5996     pst->dirname = DW_STRING (attr);
5997
5998   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5999
6000   dwarf2_find_base_address (comp_unit_die, cu);
6001
6002   /* Possibly set the default values of LOWPC and HIGHPC from
6003      `DW_AT_ranges'.  */
6004   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6005                                       &best_highpc, cu, pst);
6006   if (has_pc_info == 1 && best_lowpc < best_highpc)
6007     /* Store the contiguous range if it is not empty; it can be empty for
6008        CUs with no code.  */
6009     addrmap_set_empty (objfile->psymtabs_addrmap,
6010                        best_lowpc + baseaddr,
6011                        best_highpc + baseaddr - 1, pst);
6012
6013   /* Check if comp unit has_children.
6014      If so, read the rest of the partial symbols from this comp unit.
6015      If not, there's no more debug_info for this comp unit.  */
6016   if (has_children)
6017     {
6018       struct partial_die_info *first_die;
6019       CORE_ADDR lowpc, highpc;
6020
6021       lowpc = ((CORE_ADDR) -1);
6022       highpc = ((CORE_ADDR) 0);
6023
6024       first_die = load_partial_dies (reader, info_ptr, 1);
6025
6026       scan_partial_symbols (first_die, &lowpc, &highpc,
6027                             ! has_pc_info, cu);
6028
6029       /* If we didn't find a lowpc, set it to highpc to avoid
6030          complaints from `maint check'.  */
6031       if (lowpc == ((CORE_ADDR) -1))
6032         lowpc = highpc;
6033
6034       /* If the compilation unit didn't have an explicit address range,
6035          then use the information extracted from its child dies.  */
6036       if (! has_pc_info)
6037         {
6038           best_lowpc = lowpc;
6039           best_highpc = highpc;
6040         }
6041     }
6042   pst->textlow = best_lowpc + baseaddr;
6043   pst->texthigh = best_highpc + baseaddr;
6044
6045   pst->n_global_syms = objfile->global_psymbols.next -
6046     (objfile->global_psymbols.list + pst->globals_offset);
6047   pst->n_static_syms = objfile->static_psymbols.next -
6048     (objfile->static_psymbols.list + pst->statics_offset);
6049   sort_pst_symbols (objfile, pst);
6050
6051   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6052     {
6053       int i;
6054       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6055       struct dwarf2_per_cu_data *iter;
6056
6057       /* Fill in 'dependencies' here; we fill in 'users' in a
6058          post-pass.  */
6059       pst->number_of_dependencies = len;
6060       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6061                                          len * sizeof (struct symtab *));
6062       for (i = 0;
6063            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6064                         i, iter);
6065            ++i)
6066         pst->dependencies[i] = iter->v.psymtab;
6067
6068       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6069     }
6070
6071   /* Get the list of files included in the current compilation unit,
6072      and build a psymtab for each of them.  */
6073   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6074
6075   if (dwarf2_read_debug)
6076     {
6077       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6078
6079       fprintf_unfiltered (gdb_stdlog,
6080                           "Psymtab for %s unit @0x%x: %s - %s"
6081                           ", %d global, %d static syms\n",
6082                           per_cu->is_debug_types ? "type" : "comp",
6083                           per_cu->offset.sect_off,
6084                           paddress (gdbarch, pst->textlow),
6085                           paddress (gdbarch, pst->texthigh),
6086                           pst->n_global_syms, pst->n_static_syms);
6087     }
6088 }
6089
6090 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6091    Process compilation unit THIS_CU for a psymtab.  */
6092
6093 static void
6094 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6095                            int want_partial_unit,
6096                            enum language pretend_language)
6097 {
6098   struct process_psymtab_comp_unit_data info;
6099
6100   /* If this compilation unit was already read in, free the
6101      cached copy in order to read it in again.  This is
6102      necessary because we skipped some symbols when we first
6103      read in the compilation unit (see load_partial_dies).
6104      This problem could be avoided, but the benefit is unclear.  */
6105   if (this_cu->cu != NULL)
6106     free_one_cached_comp_unit (this_cu);
6107
6108   gdb_assert (! this_cu->is_debug_types);
6109   info.want_partial_unit = want_partial_unit;
6110   info.pretend_language = pretend_language;
6111   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6112                            process_psymtab_comp_unit_reader,
6113                            &info);
6114
6115   /* Age out any secondary CUs.  */
6116   age_cached_comp_units ();
6117 }
6118
6119 /* Reader function for build_type_psymtabs.  */
6120
6121 static void
6122 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6123                             const gdb_byte *info_ptr,
6124                             struct die_info *type_unit_die,
6125                             int has_children,
6126                             void *data)
6127 {
6128   struct objfile *objfile = dwarf2_per_objfile->objfile;
6129   struct dwarf2_cu *cu = reader->cu;
6130   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6131   struct signatured_type *sig_type;
6132   struct type_unit_group *tu_group;
6133   struct attribute *attr;
6134   struct partial_die_info *first_die;
6135   CORE_ADDR lowpc, highpc;
6136   struct partial_symtab *pst;
6137
6138   gdb_assert (data == NULL);
6139   gdb_assert (per_cu->is_debug_types);
6140   sig_type = (struct signatured_type *) per_cu;
6141
6142   if (! has_children)
6143     return;
6144
6145   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6146   tu_group = get_type_unit_group (cu, attr);
6147
6148   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6149
6150   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6151   cu->list_in_scope = &file_symbols;
6152   pst = create_partial_symtab (per_cu, "");
6153   pst->anonymous = 1;
6154
6155   first_die = load_partial_dies (reader, info_ptr, 1);
6156
6157   lowpc = (CORE_ADDR) -1;
6158   highpc = (CORE_ADDR) 0;
6159   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6160
6161   pst->n_global_syms = objfile->global_psymbols.next -
6162     (objfile->global_psymbols.list + pst->globals_offset);
6163   pst->n_static_syms = objfile->static_psymbols.next -
6164     (objfile->static_psymbols.list + pst->statics_offset);
6165   sort_pst_symbols (objfile, pst);
6166 }
6167
6168 /* Traversal function for build_type_psymtabs.  */
6169
6170 static int
6171 build_type_psymtab_dependencies (void **slot, void *info)
6172 {
6173   struct objfile *objfile = dwarf2_per_objfile->objfile;
6174   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6175   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6176   struct partial_symtab *pst = per_cu->v.psymtab;
6177   int len = VEC_length (sig_type_ptr, tu_group->tus);
6178   struct signatured_type *iter;
6179   int i;
6180
6181   gdb_assert (len > 0);
6182   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6183
6184   pst->number_of_dependencies = len;
6185   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6186                                      len * sizeof (struct psymtab *));
6187   for (i = 0;
6188        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6189        ++i)
6190     {
6191       gdb_assert (iter->per_cu.is_debug_types);
6192       pst->dependencies[i] = iter->per_cu.v.psymtab;
6193       iter->type_unit_group = tu_group;
6194     }
6195
6196   VEC_free (sig_type_ptr, tu_group->tus);
6197
6198   return 1;
6199 }
6200
6201 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6202    Build partial symbol tables for the .debug_types comp-units.  */
6203
6204 static void
6205 build_type_psymtabs (struct objfile *objfile)
6206 {
6207   if (! create_all_type_units (objfile))
6208     return;
6209
6210   build_type_unit_groups (build_type_psymtabs_reader, NULL);
6211
6212   /* Now that all TUs have been processed we can fill in the dependencies.  */
6213   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6214                           build_type_psymtab_dependencies, NULL);
6215 }
6216
6217 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6218
6219 static void
6220 psymtabs_addrmap_cleanup (void *o)
6221 {
6222   struct objfile *objfile = o;
6223
6224   objfile->psymtabs_addrmap = NULL;
6225 }
6226
6227 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6228
6229 static void
6230 set_partial_user (struct objfile *objfile)
6231 {
6232   int i;
6233
6234   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6235     {
6236       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6237       struct partial_symtab *pst = per_cu->v.psymtab;
6238       int j;
6239
6240       if (pst == NULL)
6241         continue;
6242
6243       for (j = 0; j < pst->number_of_dependencies; ++j)
6244         {
6245           /* Set the 'user' field only if it is not already set.  */
6246           if (pst->dependencies[j]->user == NULL)
6247             pst->dependencies[j]->user = pst;
6248         }
6249     }
6250 }
6251
6252 /* Build the partial symbol table by doing a quick pass through the
6253    .debug_info and .debug_abbrev sections.  */
6254
6255 static void
6256 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6257 {
6258   struct cleanup *back_to, *addrmap_cleanup;
6259   struct obstack temp_obstack;
6260   int i;
6261
6262   if (dwarf2_read_debug)
6263     {
6264       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6265                           objfile_name (objfile));
6266     }
6267
6268   dwarf2_per_objfile->reading_partial_symbols = 1;
6269
6270   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6271
6272   /* Any cached compilation units will be linked by the per-objfile
6273      read_in_chain.  Make sure to free them when we're done.  */
6274   back_to = make_cleanup (free_cached_comp_units, NULL);
6275
6276   build_type_psymtabs (objfile);
6277
6278   create_all_comp_units (objfile);
6279
6280   /* Create a temporary address map on a temporary obstack.  We later
6281      copy this to the final obstack.  */
6282   obstack_init (&temp_obstack);
6283   make_cleanup_obstack_free (&temp_obstack);
6284   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6285   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6286
6287   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6288     {
6289       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6290
6291       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6292     }
6293
6294   set_partial_user (objfile);
6295
6296   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6297                                                     &objfile->objfile_obstack);
6298   discard_cleanups (addrmap_cleanup);
6299
6300   do_cleanups (back_to);
6301
6302   if (dwarf2_read_debug)
6303     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6304                         objfile_name (objfile));
6305 }
6306
6307 /* die_reader_func for load_partial_comp_unit.  */
6308
6309 static void
6310 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6311                                const gdb_byte *info_ptr,
6312                                struct die_info *comp_unit_die,
6313                                int has_children,
6314                                void *data)
6315 {
6316   struct dwarf2_cu *cu = reader->cu;
6317
6318   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6319
6320   /* Check if comp unit has_children.
6321      If so, read the rest of the partial symbols from this comp unit.
6322      If not, there's no more debug_info for this comp unit.  */
6323   if (has_children)
6324     load_partial_dies (reader, info_ptr, 0);
6325 }
6326
6327 /* Load the partial DIEs for a secondary CU into memory.
6328    This is also used when rereading a primary CU with load_all_dies.  */
6329
6330 static void
6331 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6332 {
6333   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6334                            load_partial_comp_unit_reader, NULL);
6335 }
6336
6337 static void
6338 read_comp_units_from_section (struct objfile *objfile,
6339                               struct dwarf2_section_info *section,
6340                               unsigned int is_dwz,
6341                               int *n_allocated,
6342                               int *n_comp_units,
6343                               struct dwarf2_per_cu_data ***all_comp_units)
6344 {
6345   const gdb_byte *info_ptr;
6346   bfd *abfd = get_section_bfd_owner (section);
6347
6348   if (dwarf2_read_debug)
6349     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6350                         get_section_name (section),
6351                         get_section_file_name (section));
6352
6353   dwarf2_read_section (objfile, section);
6354
6355   info_ptr = section->buffer;
6356
6357   while (info_ptr < section->buffer + section->size)
6358     {
6359       unsigned int length, initial_length_size;
6360       struct dwarf2_per_cu_data *this_cu;
6361       sect_offset offset;
6362
6363       offset.sect_off = info_ptr - section->buffer;
6364
6365       /* Read just enough information to find out where the next
6366          compilation unit is.  */
6367       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6368
6369       /* Save the compilation unit for later lookup.  */
6370       this_cu = obstack_alloc (&objfile->objfile_obstack,
6371                                sizeof (struct dwarf2_per_cu_data));
6372       memset (this_cu, 0, sizeof (*this_cu));
6373       this_cu->offset = offset;
6374       this_cu->length = length + initial_length_size;
6375       this_cu->is_dwz = is_dwz;
6376       this_cu->objfile = objfile;
6377       this_cu->section = section;
6378
6379       if (*n_comp_units == *n_allocated)
6380         {
6381           *n_allocated *= 2;
6382           *all_comp_units = xrealloc (*all_comp_units,
6383                                       *n_allocated
6384                                       * sizeof (struct dwarf2_per_cu_data *));
6385         }
6386       (*all_comp_units)[*n_comp_units] = this_cu;
6387       ++*n_comp_units;
6388
6389       info_ptr = info_ptr + this_cu->length;
6390     }
6391 }
6392
6393 /* Create a list of all compilation units in OBJFILE.
6394    This is only done for -readnow and building partial symtabs.  */
6395
6396 static void
6397 create_all_comp_units (struct objfile *objfile)
6398 {
6399   int n_allocated;
6400   int n_comp_units;
6401   struct dwarf2_per_cu_data **all_comp_units;
6402   struct dwz_file *dwz;
6403
6404   n_comp_units = 0;
6405   n_allocated = 10;
6406   all_comp_units = xmalloc (n_allocated
6407                             * sizeof (struct dwarf2_per_cu_data *));
6408
6409   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6410                                 &n_allocated, &n_comp_units, &all_comp_units);
6411
6412   dwz = dwarf2_get_dwz_file ();
6413   if (dwz != NULL)
6414     read_comp_units_from_section (objfile, &dwz->info, 1,
6415                                   &n_allocated, &n_comp_units,
6416                                   &all_comp_units);
6417
6418   dwarf2_per_objfile->all_comp_units
6419     = obstack_alloc (&objfile->objfile_obstack,
6420                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6421   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6422           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6423   xfree (all_comp_units);
6424   dwarf2_per_objfile->n_comp_units = n_comp_units;
6425 }
6426
6427 /* Process all loaded DIEs for compilation unit CU, starting at
6428    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6429    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6430    DW_AT_ranges).  If NEED_PC is set, then this function will set
6431    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6432    and record the covered ranges in the addrmap.  */
6433
6434 static void
6435 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6436                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6437 {
6438   struct partial_die_info *pdi;
6439
6440   /* Now, march along the PDI's, descending into ones which have
6441      interesting children but skipping the children of the other ones,
6442      until we reach the end of the compilation unit.  */
6443
6444   pdi = first_die;
6445
6446   while (pdi != NULL)
6447     {
6448       fixup_partial_die (pdi, cu);
6449
6450       /* Anonymous namespaces or modules have no name but have interesting
6451          children, so we need to look at them.  Ditto for anonymous
6452          enums.  */
6453
6454       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6455           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6456           || pdi->tag == DW_TAG_imported_unit)
6457         {
6458           switch (pdi->tag)
6459             {
6460             case DW_TAG_subprogram:
6461               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6462               break;
6463             case DW_TAG_constant:
6464             case DW_TAG_variable:
6465             case DW_TAG_typedef:
6466             case DW_TAG_union_type:
6467               if (!pdi->is_declaration)
6468                 {
6469                   add_partial_symbol (pdi, cu);
6470                 }
6471               break;
6472             case DW_TAG_class_type:
6473             case DW_TAG_interface_type:
6474             case DW_TAG_structure_type:
6475               if (!pdi->is_declaration)
6476                 {
6477                   add_partial_symbol (pdi, cu);
6478                 }
6479               break;
6480             case DW_TAG_enumeration_type:
6481               if (!pdi->is_declaration)
6482                 add_partial_enumeration (pdi, cu);
6483               break;
6484             case DW_TAG_base_type:
6485             case DW_TAG_subrange_type:
6486               /* File scope base type definitions are added to the partial
6487                  symbol table.  */
6488               add_partial_symbol (pdi, cu);
6489               break;
6490             case DW_TAG_namespace:
6491               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6492               break;
6493             case DW_TAG_module:
6494               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6495               break;
6496             case DW_TAG_imported_unit:
6497               {
6498                 struct dwarf2_per_cu_data *per_cu;
6499
6500                 /* For now we don't handle imported units in type units.  */
6501                 if (cu->per_cu->is_debug_types)
6502                   {
6503                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6504                              " supported in type units [in module %s]"),
6505                            objfile_name (cu->objfile));
6506                   }
6507
6508                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6509                                                            pdi->is_dwz,
6510                                                            cu->objfile);
6511
6512                 /* Go read the partial unit, if needed.  */
6513                 if (per_cu->v.psymtab == NULL)
6514                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6515
6516                 VEC_safe_push (dwarf2_per_cu_ptr,
6517                                cu->per_cu->imported_symtabs, per_cu);
6518               }
6519               break;
6520             default:
6521               break;
6522             }
6523         }
6524
6525       /* If the die has a sibling, skip to the sibling.  */
6526
6527       pdi = pdi->die_sibling;
6528     }
6529 }
6530
6531 /* Functions used to compute the fully scoped name of a partial DIE.
6532
6533    Normally, this is simple.  For C++, the parent DIE's fully scoped
6534    name is concatenated with "::" and the partial DIE's name.  For
6535    Java, the same thing occurs except that "." is used instead of "::".
6536    Enumerators are an exception; they use the scope of their parent
6537    enumeration type, i.e. the name of the enumeration type is not
6538    prepended to the enumerator.
6539
6540    There are two complexities.  One is DW_AT_specification; in this
6541    case "parent" means the parent of the target of the specification,
6542    instead of the direct parent of the DIE.  The other is compilers
6543    which do not emit DW_TAG_namespace; in this case we try to guess
6544    the fully qualified name of structure types from their members'
6545    linkage names.  This must be done using the DIE's children rather
6546    than the children of any DW_AT_specification target.  We only need
6547    to do this for structures at the top level, i.e. if the target of
6548    any DW_AT_specification (if any; otherwise the DIE itself) does not
6549    have a parent.  */
6550
6551 /* Compute the scope prefix associated with PDI's parent, in
6552    compilation unit CU.  The result will be allocated on CU's
6553    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6554    field.  NULL is returned if no prefix is necessary.  */
6555 static const char *
6556 partial_die_parent_scope (struct partial_die_info *pdi,
6557                           struct dwarf2_cu *cu)
6558 {
6559   const char *grandparent_scope;
6560   struct partial_die_info *parent, *real_pdi;
6561
6562   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6563      then this means the parent of the specification DIE.  */
6564
6565   real_pdi = pdi;
6566   while (real_pdi->has_specification)
6567     real_pdi = find_partial_die (real_pdi->spec_offset,
6568                                  real_pdi->spec_is_dwz, cu);
6569
6570   parent = real_pdi->die_parent;
6571   if (parent == NULL)
6572     return NULL;
6573
6574   if (parent->scope_set)
6575     return parent->scope;
6576
6577   fixup_partial_die (parent, cu);
6578
6579   grandparent_scope = partial_die_parent_scope (parent, cu);
6580
6581   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6582      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6583      Work around this problem here.  */
6584   if (cu->language == language_cplus
6585       && parent->tag == DW_TAG_namespace
6586       && strcmp (parent->name, "::") == 0
6587       && grandparent_scope == NULL)
6588     {
6589       parent->scope = NULL;
6590       parent->scope_set = 1;
6591       return NULL;
6592     }
6593
6594   if (pdi->tag == DW_TAG_enumerator)
6595     /* Enumerators should not get the name of the enumeration as a prefix.  */
6596     parent->scope = grandparent_scope;
6597   else if (parent->tag == DW_TAG_namespace
6598       || parent->tag == DW_TAG_module
6599       || parent->tag == DW_TAG_structure_type
6600       || parent->tag == DW_TAG_class_type
6601       || parent->tag == DW_TAG_interface_type
6602       || parent->tag == DW_TAG_union_type
6603       || parent->tag == DW_TAG_enumeration_type)
6604     {
6605       if (grandparent_scope == NULL)
6606         parent->scope = parent->name;
6607       else
6608         parent->scope = typename_concat (&cu->comp_unit_obstack,
6609                                          grandparent_scope,
6610                                          parent->name, 0, cu);
6611     }
6612   else
6613     {
6614       /* FIXME drow/2004-04-01: What should we be doing with
6615          function-local names?  For partial symbols, we should probably be
6616          ignoring them.  */
6617       complaint (&symfile_complaints,
6618                  _("unhandled containing DIE tag %d for DIE at %d"),
6619                  parent->tag, pdi->offset.sect_off);
6620       parent->scope = grandparent_scope;
6621     }
6622
6623   parent->scope_set = 1;
6624   return parent->scope;
6625 }
6626
6627 /* Return the fully scoped name associated with PDI, from compilation unit
6628    CU.  The result will be allocated with malloc.  */
6629
6630 static char *
6631 partial_die_full_name (struct partial_die_info *pdi,
6632                        struct dwarf2_cu *cu)
6633 {
6634   const char *parent_scope;
6635
6636   /* If this is a template instantiation, we can not work out the
6637      template arguments from partial DIEs.  So, unfortunately, we have
6638      to go through the full DIEs.  At least any work we do building
6639      types here will be reused if full symbols are loaded later.  */
6640   if (pdi->has_template_arguments)
6641     {
6642       fixup_partial_die (pdi, cu);
6643
6644       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6645         {
6646           struct die_info *die;
6647           struct attribute attr;
6648           struct dwarf2_cu *ref_cu = cu;
6649
6650           /* DW_FORM_ref_addr is using section offset.  */
6651           attr.name = 0;
6652           attr.form = DW_FORM_ref_addr;
6653           attr.u.unsnd = pdi->offset.sect_off;
6654           die = follow_die_ref (NULL, &attr, &ref_cu);
6655
6656           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6657         }
6658     }
6659
6660   parent_scope = partial_die_parent_scope (pdi, cu);
6661   if (parent_scope == NULL)
6662     return NULL;
6663   else
6664     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6665 }
6666
6667 static void
6668 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6669 {
6670   struct objfile *objfile = cu->objfile;
6671   CORE_ADDR addr = 0;
6672   const char *actual_name = NULL;
6673   CORE_ADDR baseaddr;
6674   char *built_actual_name;
6675
6676   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6677
6678   built_actual_name = partial_die_full_name (pdi, cu);
6679   if (built_actual_name != NULL)
6680     actual_name = built_actual_name;
6681
6682   if (actual_name == NULL)
6683     actual_name = pdi->name;
6684
6685   switch (pdi->tag)
6686     {
6687     case DW_TAG_subprogram:
6688       if (pdi->is_external || cu->language == language_ada)
6689         {
6690           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6691              of the global scope.  But in Ada, we want to be able to access
6692              nested procedures globally.  So all Ada subprograms are stored
6693              in the global scope.  */
6694           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6695              mst_text, objfile); */
6696           add_psymbol_to_list (actual_name, strlen (actual_name),
6697                                built_actual_name != NULL,
6698                                VAR_DOMAIN, LOC_BLOCK,
6699                                &objfile->global_psymbols,
6700                                0, pdi->lowpc + baseaddr,
6701                                cu->language, objfile);
6702         }
6703       else
6704         {
6705           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6706              mst_file_text, objfile); */
6707           add_psymbol_to_list (actual_name, strlen (actual_name),
6708                                built_actual_name != NULL,
6709                                VAR_DOMAIN, LOC_BLOCK,
6710                                &objfile->static_psymbols,
6711                                0, pdi->lowpc + baseaddr,
6712                                cu->language, objfile);
6713         }
6714       break;
6715     case DW_TAG_constant:
6716       {
6717         struct psymbol_allocation_list *list;
6718
6719         if (pdi->is_external)
6720           list = &objfile->global_psymbols;
6721         else
6722           list = &objfile->static_psymbols;
6723         add_psymbol_to_list (actual_name, strlen (actual_name),
6724                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6725                              list, 0, 0, cu->language, objfile);
6726       }
6727       break;
6728     case DW_TAG_variable:
6729       if (pdi->d.locdesc)
6730         addr = decode_locdesc (pdi->d.locdesc, cu);
6731
6732       if (pdi->d.locdesc
6733           && addr == 0
6734           && !dwarf2_per_objfile->has_section_at_zero)
6735         {
6736           /* A global or static variable may also have been stripped
6737              out by the linker if unused, in which case its address
6738              will be nullified; do not add such variables into partial
6739              symbol table then.  */
6740         }
6741       else if (pdi->is_external)
6742         {
6743           /* Global Variable.
6744              Don't enter into the minimal symbol tables as there is
6745              a minimal symbol table entry from the ELF symbols already.
6746              Enter into partial symbol table if it has a location
6747              descriptor or a type.
6748              If the location descriptor is missing, new_symbol will create
6749              a LOC_UNRESOLVED symbol, the address of the variable will then
6750              be determined from the minimal symbol table whenever the variable
6751              is referenced.
6752              The address for the partial symbol table entry is not
6753              used by GDB, but it comes in handy for debugging partial symbol
6754              table building.  */
6755
6756           if (pdi->d.locdesc || pdi->has_type)
6757             add_psymbol_to_list (actual_name, strlen (actual_name),
6758                                  built_actual_name != NULL,
6759                                  VAR_DOMAIN, LOC_STATIC,
6760                                  &objfile->global_psymbols,
6761                                  0, addr + baseaddr,
6762                                  cu->language, objfile);
6763         }
6764       else
6765         {
6766           /* Static Variable.  Skip symbols without location descriptors.  */
6767           if (pdi->d.locdesc == NULL)
6768             {
6769               xfree (built_actual_name);
6770               return;
6771             }
6772           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6773              mst_file_data, objfile); */
6774           add_psymbol_to_list (actual_name, strlen (actual_name),
6775                                built_actual_name != NULL,
6776                                VAR_DOMAIN, LOC_STATIC,
6777                                &objfile->static_psymbols,
6778                                0, addr + baseaddr,
6779                                cu->language, objfile);
6780         }
6781       break;
6782     case DW_TAG_typedef:
6783     case DW_TAG_base_type:
6784     case DW_TAG_subrange_type:
6785       add_psymbol_to_list (actual_name, strlen (actual_name),
6786                            built_actual_name != NULL,
6787                            VAR_DOMAIN, LOC_TYPEDEF,
6788                            &objfile->static_psymbols,
6789                            0, (CORE_ADDR) 0, cu->language, objfile);
6790       break;
6791     case DW_TAG_namespace:
6792       add_psymbol_to_list (actual_name, strlen (actual_name),
6793                            built_actual_name != NULL,
6794                            VAR_DOMAIN, LOC_TYPEDEF,
6795                            &objfile->global_psymbols,
6796                            0, (CORE_ADDR) 0, cu->language, objfile);
6797       break;
6798     case DW_TAG_class_type:
6799     case DW_TAG_interface_type:
6800     case DW_TAG_structure_type:
6801     case DW_TAG_union_type:
6802     case DW_TAG_enumeration_type:
6803       /* Skip external references.  The DWARF standard says in the section
6804          about "Structure, Union, and Class Type Entries": "An incomplete
6805          structure, union or class type is represented by a structure,
6806          union or class entry that does not have a byte size attribute
6807          and that has a DW_AT_declaration attribute."  */
6808       if (!pdi->has_byte_size && pdi->is_declaration)
6809         {
6810           xfree (built_actual_name);
6811           return;
6812         }
6813
6814       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6815          static vs. global.  */
6816       add_psymbol_to_list (actual_name, strlen (actual_name),
6817                            built_actual_name != NULL,
6818                            STRUCT_DOMAIN, LOC_TYPEDEF,
6819                            (cu->language == language_cplus
6820                             || cu->language == language_java)
6821                            ? &objfile->global_psymbols
6822                            : &objfile->static_psymbols,
6823                            0, (CORE_ADDR) 0, cu->language, objfile);
6824
6825       break;
6826     case DW_TAG_enumerator:
6827       add_psymbol_to_list (actual_name, strlen (actual_name),
6828                            built_actual_name != NULL,
6829                            VAR_DOMAIN, LOC_CONST,
6830                            (cu->language == language_cplus
6831                             || cu->language == language_java)
6832                            ? &objfile->global_psymbols
6833                            : &objfile->static_psymbols,
6834                            0, (CORE_ADDR) 0, cu->language, objfile);
6835       break;
6836     default:
6837       break;
6838     }
6839
6840   xfree (built_actual_name);
6841 }
6842
6843 /* Read a partial die corresponding to a namespace; also, add a symbol
6844    corresponding to that namespace to the symbol table.  NAMESPACE is
6845    the name of the enclosing namespace.  */
6846
6847 static void
6848 add_partial_namespace (struct partial_die_info *pdi,
6849                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6850                        int need_pc, struct dwarf2_cu *cu)
6851 {
6852   /* Add a symbol for the namespace.  */
6853
6854   add_partial_symbol (pdi, cu);
6855
6856   /* Now scan partial symbols in that namespace.  */
6857
6858   if (pdi->has_children)
6859     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6860 }
6861
6862 /* Read a partial die corresponding to a Fortran module.  */
6863
6864 static void
6865 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6866                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6867 {
6868   /* Now scan partial symbols in that module.  */
6869
6870   if (pdi->has_children)
6871     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6872 }
6873
6874 /* Read a partial die corresponding to a subprogram and create a partial
6875    symbol for that subprogram.  When the CU language allows it, this
6876    routine also defines a partial symbol for each nested subprogram
6877    that this subprogram contains.
6878
6879    DIE my also be a lexical block, in which case we simply search
6880    recursively for suprograms defined inside that lexical block.
6881    Again, this is only performed when the CU language allows this
6882    type of definitions.  */
6883
6884 static void
6885 add_partial_subprogram (struct partial_die_info *pdi,
6886                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6887                         int need_pc, struct dwarf2_cu *cu)
6888 {
6889   if (pdi->tag == DW_TAG_subprogram)
6890     {
6891       if (pdi->has_pc_info)
6892         {
6893           if (pdi->lowpc < *lowpc)
6894             *lowpc = pdi->lowpc;
6895           if (pdi->highpc > *highpc)
6896             *highpc = pdi->highpc;
6897           if (need_pc)
6898             {
6899               CORE_ADDR baseaddr;
6900               struct objfile *objfile = cu->objfile;
6901
6902               baseaddr = ANOFFSET (objfile->section_offsets,
6903                                    SECT_OFF_TEXT (objfile));
6904               addrmap_set_empty (objfile->psymtabs_addrmap,
6905                                  pdi->lowpc + baseaddr,
6906                                  pdi->highpc - 1 + baseaddr,
6907                                  cu->per_cu->v.psymtab);
6908             }
6909         }
6910
6911       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6912         {
6913           if (!pdi->is_declaration)
6914             /* Ignore subprogram DIEs that do not have a name, they are
6915                illegal.  Do not emit a complaint at this point, we will
6916                do so when we convert this psymtab into a symtab.  */
6917             if (pdi->name)
6918               add_partial_symbol (pdi, cu);
6919         }
6920     }
6921
6922   if (! pdi->has_children)
6923     return;
6924
6925   if (cu->language == language_ada)
6926     {
6927       pdi = pdi->die_child;
6928       while (pdi != NULL)
6929         {
6930           fixup_partial_die (pdi, cu);
6931           if (pdi->tag == DW_TAG_subprogram
6932               || pdi->tag == DW_TAG_lexical_block)
6933             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6934           pdi = pdi->die_sibling;
6935         }
6936     }
6937 }
6938
6939 /* Read a partial die corresponding to an enumeration type.  */
6940
6941 static void
6942 add_partial_enumeration (struct partial_die_info *enum_pdi,
6943                          struct dwarf2_cu *cu)
6944 {
6945   struct partial_die_info *pdi;
6946
6947   if (enum_pdi->name != NULL)
6948     add_partial_symbol (enum_pdi, cu);
6949
6950   pdi = enum_pdi->die_child;
6951   while (pdi)
6952     {
6953       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6954         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6955       else
6956         add_partial_symbol (pdi, cu);
6957       pdi = pdi->die_sibling;
6958     }
6959 }
6960
6961 /* Return the initial uleb128 in the die at INFO_PTR.  */
6962
6963 static unsigned int
6964 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6965 {
6966   unsigned int bytes_read;
6967
6968   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6969 }
6970
6971 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6972    Return the corresponding abbrev, or NULL if the number is zero (indicating
6973    an empty DIE).  In either case *BYTES_READ will be set to the length of
6974    the initial number.  */
6975
6976 static struct abbrev_info *
6977 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6978                  struct dwarf2_cu *cu)
6979 {
6980   bfd *abfd = cu->objfile->obfd;
6981   unsigned int abbrev_number;
6982   struct abbrev_info *abbrev;
6983
6984   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6985
6986   if (abbrev_number == 0)
6987     return NULL;
6988
6989   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6990   if (!abbrev)
6991     {
6992       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6993              abbrev_number, bfd_get_filename (abfd));
6994     }
6995
6996   return abbrev;
6997 }
6998
6999 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7000    Returns a pointer to the end of a series of DIEs, terminated by an empty
7001    DIE.  Any children of the skipped DIEs will also be skipped.  */
7002
7003 static const gdb_byte *
7004 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7005 {
7006   struct dwarf2_cu *cu = reader->cu;
7007   struct abbrev_info *abbrev;
7008   unsigned int bytes_read;
7009
7010   while (1)
7011     {
7012       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7013       if (abbrev == NULL)
7014         return info_ptr + bytes_read;
7015       else
7016         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7017     }
7018 }
7019
7020 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7021    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7022    abbrev corresponding to that skipped uleb128 should be passed in
7023    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7024    children.  */
7025
7026 static const gdb_byte *
7027 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7028               struct abbrev_info *abbrev)
7029 {
7030   unsigned int bytes_read;
7031   struct attribute attr;
7032   bfd *abfd = reader->abfd;
7033   struct dwarf2_cu *cu = reader->cu;
7034   const gdb_byte *buffer = reader->buffer;
7035   const gdb_byte *buffer_end = reader->buffer_end;
7036   const gdb_byte *start_info_ptr = info_ptr;
7037   unsigned int form, i;
7038
7039   for (i = 0; i < abbrev->num_attrs; i++)
7040     {
7041       /* The only abbrev we care about is DW_AT_sibling.  */
7042       if (abbrev->attrs[i].name == DW_AT_sibling)
7043         {
7044           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7045           if (attr.form == DW_FORM_ref_addr)
7046             complaint (&symfile_complaints,
7047                        _("ignoring absolute DW_AT_sibling"));
7048           else
7049             {
7050               unsigned int off = dwarf2_get_ref_die_offset (&attr).sect_off;
7051               const gdb_byte *sibling_ptr = buffer + off;
7052
7053               if (sibling_ptr < info_ptr)
7054                 complaint (&symfile_complaints,
7055                            _("DW_AT_sibling points backwards"));
7056               else
7057                 return sibling_ptr;
7058             }
7059         }
7060
7061       /* If it isn't DW_AT_sibling, skip this attribute.  */
7062       form = abbrev->attrs[i].form;
7063     skip_attribute:
7064       switch (form)
7065         {
7066         case DW_FORM_ref_addr:
7067           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7068              and later it is offset sized.  */
7069           if (cu->header.version == 2)
7070             info_ptr += cu->header.addr_size;
7071           else
7072             info_ptr += cu->header.offset_size;
7073           break;
7074         case DW_FORM_GNU_ref_alt:
7075           info_ptr += cu->header.offset_size;
7076           break;
7077         case DW_FORM_addr:
7078           info_ptr += cu->header.addr_size;
7079           break;
7080         case DW_FORM_data1:
7081         case DW_FORM_ref1:
7082         case DW_FORM_flag:
7083           info_ptr += 1;
7084           break;
7085         case DW_FORM_flag_present:
7086           break;
7087         case DW_FORM_data2:
7088         case DW_FORM_ref2:
7089           info_ptr += 2;
7090           break;
7091         case DW_FORM_data4:
7092         case DW_FORM_ref4:
7093           info_ptr += 4;
7094           break;
7095         case DW_FORM_data8:
7096         case DW_FORM_ref8:
7097         case DW_FORM_ref_sig8:
7098           info_ptr += 8;
7099           break;
7100         case DW_FORM_string:
7101           read_direct_string (abfd, info_ptr, &bytes_read);
7102           info_ptr += bytes_read;
7103           break;
7104         case DW_FORM_sec_offset:
7105         case DW_FORM_strp:
7106         case DW_FORM_GNU_strp_alt:
7107           info_ptr += cu->header.offset_size;
7108           break;
7109         case DW_FORM_exprloc:
7110         case DW_FORM_block:
7111           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7112           info_ptr += bytes_read;
7113           break;
7114         case DW_FORM_block1:
7115           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7116           break;
7117         case DW_FORM_block2:
7118           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7119           break;
7120         case DW_FORM_block4:
7121           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7122           break;
7123         case DW_FORM_sdata:
7124         case DW_FORM_udata:
7125         case DW_FORM_ref_udata:
7126         case DW_FORM_GNU_addr_index:
7127         case DW_FORM_GNU_str_index:
7128           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7129           break;
7130         case DW_FORM_indirect:
7131           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7132           info_ptr += bytes_read;
7133           /* We need to continue parsing from here, so just go back to
7134              the top.  */
7135           goto skip_attribute;
7136
7137         default:
7138           error (_("Dwarf Error: Cannot handle %s "
7139                    "in DWARF reader [in module %s]"),
7140                  dwarf_form_name (form),
7141                  bfd_get_filename (abfd));
7142         }
7143     }
7144
7145   if (abbrev->has_children)
7146     return skip_children (reader, info_ptr);
7147   else
7148     return info_ptr;
7149 }
7150
7151 /* Locate ORIG_PDI's sibling.
7152    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7153
7154 static const gdb_byte *
7155 locate_pdi_sibling (const struct die_reader_specs *reader,
7156                     struct partial_die_info *orig_pdi,
7157                     const gdb_byte *info_ptr)
7158 {
7159   /* Do we know the sibling already?  */
7160
7161   if (orig_pdi->sibling)
7162     return orig_pdi->sibling;
7163
7164   /* Are there any children to deal with?  */
7165
7166   if (!orig_pdi->has_children)
7167     return info_ptr;
7168
7169   /* Skip the children the long way.  */
7170
7171   return skip_children (reader, info_ptr);
7172 }
7173
7174 /* Expand this partial symbol table into a full symbol table.  SELF is
7175    not NULL.  */
7176
7177 static void
7178 dwarf2_read_symtab (struct partial_symtab *self,
7179                     struct objfile *objfile)
7180 {
7181   if (self->readin)
7182     {
7183       warning (_("bug: psymtab for %s is already read in."),
7184                self->filename);
7185     }
7186   else
7187     {
7188       if (info_verbose)
7189         {
7190           printf_filtered (_("Reading in symbols for %s..."),
7191                            self->filename);
7192           gdb_flush (gdb_stdout);
7193         }
7194
7195       /* Restore our global data.  */
7196       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
7197
7198       /* If this psymtab is constructed from a debug-only objfile, the
7199          has_section_at_zero flag will not necessarily be correct.  We
7200          can get the correct value for this flag by looking at the data
7201          associated with the (presumably stripped) associated objfile.  */
7202       if (objfile->separate_debug_objfile_backlink)
7203         {
7204           struct dwarf2_per_objfile *dpo_backlink
7205             = objfile_data (objfile->separate_debug_objfile_backlink,
7206                             dwarf2_objfile_data_key);
7207
7208           dwarf2_per_objfile->has_section_at_zero
7209             = dpo_backlink->has_section_at_zero;
7210         }
7211
7212       dwarf2_per_objfile->reading_partial_symbols = 0;
7213
7214       psymtab_to_symtab_1 (self);
7215
7216       /* Finish up the debug error message.  */
7217       if (info_verbose)
7218         printf_filtered (_("done.\n"));
7219     }
7220
7221   process_cu_includes ();
7222 }
7223 \f
7224 /* Reading in full CUs.  */
7225
7226 /* Add PER_CU to the queue.  */
7227
7228 static void
7229 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7230                  enum language pretend_language)
7231 {
7232   struct dwarf2_queue_item *item;
7233
7234   per_cu->queued = 1;
7235   item = xmalloc (sizeof (*item));
7236   item->per_cu = per_cu;
7237   item->pretend_language = pretend_language;
7238   item->next = NULL;
7239
7240   if (dwarf2_queue == NULL)
7241     dwarf2_queue = item;
7242   else
7243     dwarf2_queue_tail->next = item;
7244
7245   dwarf2_queue_tail = item;
7246 }
7247
7248 /* If PER_CU is not yet queued, add it to the queue.
7249    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7250    dependency.
7251    The result is non-zero if PER_CU was queued, otherwise the result is zero
7252    meaning either PER_CU is already queued or it is already loaded.
7253
7254    N.B. There is an invariant here that if a CU is queued then it is loaded.
7255    The caller is required to load PER_CU if we return non-zero.  */
7256
7257 static int
7258 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7259                        struct dwarf2_per_cu_data *per_cu,
7260                        enum language pretend_language)
7261 {
7262   /* We may arrive here during partial symbol reading, if we need full
7263      DIEs to process an unusual case (e.g. template arguments).  Do
7264      not queue PER_CU, just tell our caller to load its DIEs.  */
7265   if (dwarf2_per_objfile->reading_partial_symbols)
7266     {
7267       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7268         return 1;
7269       return 0;
7270     }
7271
7272   /* Mark the dependence relation so that we don't flush PER_CU
7273      too early.  */
7274   if (dependent_cu != NULL)
7275     dwarf2_add_dependence (dependent_cu, per_cu);
7276
7277   /* If it's already on the queue, we have nothing to do.  */
7278   if (per_cu->queued)
7279     return 0;
7280
7281   /* If the compilation unit is already loaded, just mark it as
7282      used.  */
7283   if (per_cu->cu != NULL)
7284     {
7285       per_cu->cu->last_used = 0;
7286       return 0;
7287     }
7288
7289   /* Add it to the queue.  */
7290   queue_comp_unit (per_cu, pretend_language);
7291
7292   return 1;
7293 }
7294
7295 /* Process the queue.  */
7296
7297 static void
7298 process_queue (void)
7299 {
7300   struct dwarf2_queue_item *item, *next_item;
7301
7302   if (dwarf2_read_debug)
7303     {
7304       fprintf_unfiltered (gdb_stdlog,
7305                           "Expanding one or more symtabs of objfile %s ...\n",
7306                           objfile_name (dwarf2_per_objfile->objfile));
7307     }
7308
7309   /* The queue starts out with one item, but following a DIE reference
7310      may load a new CU, adding it to the end of the queue.  */
7311   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7312     {
7313       if (dwarf2_per_objfile->using_index
7314           ? !item->per_cu->v.quick->symtab
7315           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7316         {
7317           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7318           unsigned int debug_print_threshold;
7319           char buf[100];
7320
7321           if (per_cu->is_debug_types)
7322             {
7323               struct signatured_type *sig_type =
7324                 (struct signatured_type *) per_cu;
7325
7326               sprintf (buf, "TU %s at offset 0x%x",
7327                        hex_string (sig_type->signature),
7328                        per_cu->offset.sect_off);
7329               /* There can be 100s of TUs.
7330                  Only print them in verbose mode.  */
7331               debug_print_threshold = 2;
7332             }
7333           else
7334             {
7335               sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7336               debug_print_threshold = 1;
7337             }
7338
7339           if (dwarf2_read_debug >= debug_print_threshold)
7340             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7341
7342           if (per_cu->is_debug_types)
7343             process_full_type_unit (per_cu, item->pretend_language);
7344           else
7345             process_full_comp_unit (per_cu, item->pretend_language);
7346
7347           if (dwarf2_read_debug >= debug_print_threshold)
7348             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7349         }
7350
7351       item->per_cu->queued = 0;
7352       next_item = item->next;
7353       xfree (item);
7354     }
7355
7356   dwarf2_queue_tail = NULL;
7357
7358   if (dwarf2_read_debug)
7359     {
7360       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7361                           objfile_name (dwarf2_per_objfile->objfile));
7362     }
7363 }
7364
7365 /* Free all allocated queue entries.  This function only releases anything if
7366    an error was thrown; if the queue was processed then it would have been
7367    freed as we went along.  */
7368
7369 static void
7370 dwarf2_release_queue (void *dummy)
7371 {
7372   struct dwarf2_queue_item *item, *last;
7373
7374   item = dwarf2_queue;
7375   while (item)
7376     {
7377       /* Anything still marked queued is likely to be in an
7378          inconsistent state, so discard it.  */
7379       if (item->per_cu->queued)
7380         {
7381           if (item->per_cu->cu != NULL)
7382             free_one_cached_comp_unit (item->per_cu);
7383           item->per_cu->queued = 0;
7384         }
7385
7386       last = item;
7387       item = item->next;
7388       xfree (last);
7389     }
7390
7391   dwarf2_queue = dwarf2_queue_tail = NULL;
7392 }
7393
7394 /* Read in full symbols for PST, and anything it depends on.  */
7395
7396 static void
7397 psymtab_to_symtab_1 (struct partial_symtab *pst)
7398 {
7399   struct dwarf2_per_cu_data *per_cu;
7400   int i;
7401
7402   if (pst->readin)
7403     return;
7404
7405   for (i = 0; i < pst->number_of_dependencies; i++)
7406     if (!pst->dependencies[i]->readin
7407         && pst->dependencies[i]->user == NULL)
7408       {
7409         /* Inform about additional files that need to be read in.  */
7410         if (info_verbose)
7411           {
7412             /* FIXME: i18n: Need to make this a single string.  */
7413             fputs_filtered (" ", gdb_stdout);
7414             wrap_here ("");
7415             fputs_filtered ("and ", gdb_stdout);
7416             wrap_here ("");
7417             printf_filtered ("%s...", pst->dependencies[i]->filename);
7418             wrap_here ("");     /* Flush output.  */
7419             gdb_flush (gdb_stdout);
7420           }
7421         psymtab_to_symtab_1 (pst->dependencies[i]);
7422       }
7423
7424   per_cu = pst->read_symtab_private;
7425
7426   if (per_cu == NULL)
7427     {
7428       /* It's an include file, no symbols to read for it.
7429          Everything is in the parent symtab.  */
7430       pst->readin = 1;
7431       return;
7432     }
7433
7434   dw2_do_instantiate_symtab (per_cu);
7435 }
7436
7437 /* Trivial hash function for die_info: the hash value of a DIE
7438    is its offset in .debug_info for this objfile.  */
7439
7440 static hashval_t
7441 die_hash (const void *item)
7442 {
7443   const struct die_info *die = item;
7444
7445   return die->offset.sect_off;
7446 }
7447
7448 /* Trivial comparison function for die_info structures: two DIEs
7449    are equal if they have the same offset.  */
7450
7451 static int
7452 die_eq (const void *item_lhs, const void *item_rhs)
7453 {
7454   const struct die_info *die_lhs = item_lhs;
7455   const struct die_info *die_rhs = item_rhs;
7456
7457   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7458 }
7459
7460 /* die_reader_func for load_full_comp_unit.
7461    This is identical to read_signatured_type_reader,
7462    but is kept separate for now.  */
7463
7464 static void
7465 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7466                             const gdb_byte *info_ptr,
7467                             struct die_info *comp_unit_die,
7468                             int has_children,
7469                             void *data)
7470 {
7471   struct dwarf2_cu *cu = reader->cu;
7472   enum language *language_ptr = data;
7473
7474   gdb_assert (cu->die_hash == NULL);
7475   cu->die_hash =
7476     htab_create_alloc_ex (cu->header.length / 12,
7477                           die_hash,
7478                           die_eq,
7479                           NULL,
7480                           &cu->comp_unit_obstack,
7481                           hashtab_obstack_allocate,
7482                           dummy_obstack_deallocate);
7483
7484   if (has_children)
7485     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7486                                                   &info_ptr, comp_unit_die);
7487   cu->dies = comp_unit_die;
7488   /* comp_unit_die is not stored in die_hash, no need.  */
7489
7490   /* We try not to read any attributes in this function, because not
7491      all CUs needed for references have been loaded yet, and symbol
7492      table processing isn't initialized.  But we have to set the CU language,
7493      or we won't be able to build types correctly.
7494      Similarly, if we do not read the producer, we can not apply
7495      producer-specific interpretation.  */
7496   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7497 }
7498
7499 /* Load the DIEs associated with PER_CU into memory.  */
7500
7501 static void
7502 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7503                      enum language pretend_language)
7504 {
7505   gdb_assert (! this_cu->is_debug_types);
7506
7507   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7508                            load_full_comp_unit_reader, &pretend_language);
7509 }
7510
7511 /* Add a DIE to the delayed physname list.  */
7512
7513 static void
7514 add_to_method_list (struct type *type, int fnfield_index, int index,
7515                     const char *name, struct die_info *die,
7516                     struct dwarf2_cu *cu)
7517 {
7518   struct delayed_method_info mi;
7519   mi.type = type;
7520   mi.fnfield_index = fnfield_index;
7521   mi.index = index;
7522   mi.name = name;
7523   mi.die = die;
7524   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7525 }
7526
7527 /* A cleanup for freeing the delayed method list.  */
7528
7529 static void
7530 free_delayed_list (void *ptr)
7531 {
7532   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7533   if (cu->method_list != NULL)
7534     {
7535       VEC_free (delayed_method_info, cu->method_list);
7536       cu->method_list = NULL;
7537     }
7538 }
7539
7540 /* Compute the physnames of any methods on the CU's method list.
7541
7542    The computation of method physnames is delayed in order to avoid the
7543    (bad) condition that one of the method's formal parameters is of an as yet
7544    incomplete type.  */
7545
7546 static void
7547 compute_delayed_physnames (struct dwarf2_cu *cu)
7548 {
7549   int i;
7550   struct delayed_method_info *mi;
7551   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7552     {
7553       const char *physname;
7554       struct fn_fieldlist *fn_flp
7555         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7556       physname = dwarf2_physname (mi->name, mi->die, cu);
7557       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7558     }
7559 }
7560
7561 /* Go objects should be embedded in a DW_TAG_module DIE,
7562    and it's not clear if/how imported objects will appear.
7563    To keep Go support simple until that's worked out,
7564    go back through what we've read and create something usable.
7565    We could do this while processing each DIE, and feels kinda cleaner,
7566    but that way is more invasive.
7567    This is to, for example, allow the user to type "p var" or "b main"
7568    without having to specify the package name, and allow lookups
7569    of module.object to work in contexts that use the expression
7570    parser.  */
7571
7572 static void
7573 fixup_go_packaging (struct dwarf2_cu *cu)
7574 {
7575   char *package_name = NULL;
7576   struct pending *list;
7577   int i;
7578
7579   for (list = global_symbols; list != NULL; list = list->next)
7580     {
7581       for (i = 0; i < list->nsyms; ++i)
7582         {
7583           struct symbol *sym = list->symbol[i];
7584
7585           if (SYMBOL_LANGUAGE (sym) == language_go
7586               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7587             {
7588               char *this_package_name = go_symbol_package_name (sym);
7589
7590               if (this_package_name == NULL)
7591                 continue;
7592               if (package_name == NULL)
7593                 package_name = this_package_name;
7594               else
7595                 {
7596                   if (strcmp (package_name, this_package_name) != 0)
7597                     complaint (&symfile_complaints,
7598                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7599                                (SYMBOL_SYMTAB (sym)
7600                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7601                                 : objfile_name (cu->objfile)),
7602                                this_package_name, package_name);
7603                   xfree (this_package_name);
7604                 }
7605             }
7606         }
7607     }
7608
7609   if (package_name != NULL)
7610     {
7611       struct objfile *objfile = cu->objfile;
7612       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7613                                                       package_name,
7614                                                       strlen (package_name));
7615       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7616                                      saved_package_name, objfile);
7617       struct symbol *sym;
7618
7619       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7620
7621       sym = allocate_symbol (objfile);
7622       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7623       SYMBOL_SET_NAMES (sym, saved_package_name,
7624                         strlen (saved_package_name), 0, objfile);
7625       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7626          e.g., "main" finds the "main" module and not C's main().  */
7627       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7628       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7629       SYMBOL_TYPE (sym) = type;
7630
7631       add_symbol_to_list (sym, &global_symbols);
7632
7633       xfree (package_name);
7634     }
7635 }
7636
7637 /* Return the symtab for PER_CU.  This works properly regardless of
7638    whether we're using the index or psymtabs.  */
7639
7640 static struct symtab *
7641 get_symtab (struct dwarf2_per_cu_data *per_cu)
7642 {
7643   return (dwarf2_per_objfile->using_index
7644           ? per_cu->v.quick->symtab
7645           : per_cu->v.psymtab->symtab);
7646 }
7647
7648 /* A helper function for computing the list of all symbol tables
7649    included by PER_CU.  */
7650
7651 static void
7652 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7653                                 htab_t all_children, htab_t all_type_symtabs,
7654                                 struct dwarf2_per_cu_data *per_cu,
7655                                 struct symtab *immediate_parent)
7656 {
7657   void **slot;
7658   int ix;
7659   struct symtab *symtab;
7660   struct dwarf2_per_cu_data *iter;
7661
7662   slot = htab_find_slot (all_children, per_cu, INSERT);
7663   if (*slot != NULL)
7664     {
7665       /* This inclusion and its children have been processed.  */
7666       return;
7667     }
7668
7669   *slot = per_cu;
7670   /* Only add a CU if it has a symbol table.  */
7671   symtab = get_symtab (per_cu);
7672   if (symtab != NULL)
7673     {
7674       /* If this is a type unit only add its symbol table if we haven't
7675          seen it yet (type unit per_cu's can share symtabs).  */
7676       if (per_cu->is_debug_types)
7677         {
7678           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7679           if (*slot == NULL)
7680             {
7681               *slot = symtab;
7682               VEC_safe_push (symtab_ptr, *result, symtab);
7683               if (symtab->user == NULL)
7684                 symtab->user = immediate_parent;
7685             }
7686         }
7687       else
7688         {
7689           VEC_safe_push (symtab_ptr, *result, symtab);
7690           if (symtab->user == NULL)
7691             symtab->user = immediate_parent;
7692         }
7693     }
7694
7695   for (ix = 0;
7696        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7697        ++ix)
7698     {
7699       recursively_compute_inclusions (result, all_children,
7700                                       all_type_symtabs, iter, symtab);
7701     }
7702 }
7703
7704 /* Compute the symtab 'includes' fields for the symtab related to
7705    PER_CU.  */
7706
7707 static void
7708 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7709 {
7710   gdb_assert (! per_cu->is_debug_types);
7711
7712   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7713     {
7714       int ix, len;
7715       struct dwarf2_per_cu_data *per_cu_iter;
7716       struct symtab *symtab_iter;
7717       VEC (symtab_ptr) *result_symtabs = NULL;
7718       htab_t all_children, all_type_symtabs;
7719       struct symtab *symtab = get_symtab (per_cu);
7720
7721       /* If we don't have a symtab, we can just skip this case.  */
7722       if (symtab == NULL)
7723         return;
7724
7725       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7726                                         NULL, xcalloc, xfree);
7727       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7728                                             NULL, xcalloc, xfree);
7729
7730       for (ix = 0;
7731            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7732                         ix, per_cu_iter);
7733            ++ix)
7734         {
7735           recursively_compute_inclusions (&result_symtabs, all_children,
7736                                           all_type_symtabs, per_cu_iter,
7737                                           symtab);
7738         }
7739
7740       /* Now we have a transitive closure of all the included symtabs.  */
7741       len = VEC_length (symtab_ptr, result_symtabs);
7742       symtab->includes
7743         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7744                          (len + 1) * sizeof (struct symtab *));
7745       for (ix = 0;
7746            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7747            ++ix)
7748         symtab->includes[ix] = symtab_iter;
7749       symtab->includes[len] = NULL;
7750
7751       VEC_free (symtab_ptr, result_symtabs);
7752       htab_delete (all_children);
7753       htab_delete (all_type_symtabs);
7754     }
7755 }
7756
7757 /* Compute the 'includes' field for the symtabs of all the CUs we just
7758    read.  */
7759
7760 static void
7761 process_cu_includes (void)
7762 {
7763   int ix;
7764   struct dwarf2_per_cu_data *iter;
7765
7766   for (ix = 0;
7767        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7768                     ix, iter);
7769        ++ix)
7770     {
7771       if (! iter->is_debug_types)
7772         compute_symtab_includes (iter);
7773     }
7774
7775   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7776 }
7777
7778 /* Generate full symbol information for PER_CU, whose DIEs have
7779    already been loaded into memory.  */
7780
7781 static void
7782 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7783                         enum language pretend_language)
7784 {
7785   struct dwarf2_cu *cu = per_cu->cu;
7786   struct objfile *objfile = per_cu->objfile;
7787   CORE_ADDR lowpc, highpc;
7788   struct symtab *symtab;
7789   struct cleanup *back_to, *delayed_list_cleanup;
7790   CORE_ADDR baseaddr;
7791   struct block *static_block;
7792
7793   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7794
7795   buildsym_init ();
7796   back_to = make_cleanup (really_free_pendings, NULL);
7797   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7798
7799   cu->list_in_scope = &file_symbols;
7800
7801   cu->language = pretend_language;
7802   cu->language_defn = language_def (cu->language);
7803
7804   /* Do line number decoding in read_file_scope () */
7805   process_die (cu->dies, cu);
7806
7807   /* For now fudge the Go package.  */
7808   if (cu->language == language_go)
7809     fixup_go_packaging (cu);
7810
7811   /* Now that we have processed all the DIEs in the CU, all the types 
7812      should be complete, and it should now be safe to compute all of the
7813      physnames.  */
7814   compute_delayed_physnames (cu);
7815   do_cleanups (delayed_list_cleanup);
7816
7817   /* Some compilers don't define a DW_AT_high_pc attribute for the
7818      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7819      it, by scanning the DIE's below the compilation unit.  */
7820   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7821
7822   static_block
7823     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7824
7825   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7826      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7827      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7828      addrmap to help ensure it has an accurate map of pc values belonging to
7829      this comp unit.  */
7830   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7831
7832   symtab = end_symtab_from_static_block (static_block, objfile,
7833                                          SECT_OFF_TEXT (objfile), 0);
7834
7835   if (symtab != NULL)
7836     {
7837       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7838
7839       /* Set symtab language to language from DW_AT_language.  If the
7840          compilation is from a C file generated by language preprocessors, do
7841          not set the language if it was already deduced by start_subfile.  */
7842       if (!(cu->language == language_c && symtab->language != language_c))
7843         symtab->language = cu->language;
7844
7845       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7846          produce DW_AT_location with location lists but it can be possibly
7847          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7848          there were bugs in prologue debug info, fixed later in GCC-4.5
7849          by "unwind info for epilogues" patch (which is not directly related).
7850
7851          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7852          needed, it would be wrong due to missing DW_AT_producer there.
7853
7854          Still one can confuse GDB by using non-standard GCC compilation
7855          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7856          */ 
7857       if (cu->has_loclist && gcc_4_minor >= 5)
7858         symtab->locations_valid = 1;
7859
7860       if (gcc_4_minor >= 5)
7861         symtab->epilogue_unwind_valid = 1;
7862
7863       symtab->call_site_htab = cu->call_site_htab;
7864     }
7865
7866   if (dwarf2_per_objfile->using_index)
7867     per_cu->v.quick->symtab = symtab;
7868   else
7869     {
7870       struct partial_symtab *pst = per_cu->v.psymtab;
7871       pst->symtab = symtab;
7872       pst->readin = 1;
7873     }
7874
7875   /* Push it for inclusion processing later.  */
7876   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7877
7878   do_cleanups (back_to);
7879 }
7880
7881 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7882    already been loaded into memory.  */
7883
7884 static void
7885 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7886                         enum language pretend_language)
7887 {
7888   struct dwarf2_cu *cu = per_cu->cu;
7889   struct objfile *objfile = per_cu->objfile;
7890   struct symtab *symtab;
7891   struct cleanup *back_to, *delayed_list_cleanup;
7892   struct signatured_type *sig_type;
7893
7894   gdb_assert (per_cu->is_debug_types);
7895   sig_type = (struct signatured_type *) per_cu;
7896
7897   buildsym_init ();
7898   back_to = make_cleanup (really_free_pendings, NULL);
7899   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7900
7901   cu->list_in_scope = &file_symbols;
7902
7903   cu->language = pretend_language;
7904   cu->language_defn = language_def (cu->language);
7905
7906   /* The symbol tables are set up in read_type_unit_scope.  */
7907   process_die (cu->dies, cu);
7908
7909   /* For now fudge the Go package.  */
7910   if (cu->language == language_go)
7911     fixup_go_packaging (cu);
7912
7913   /* Now that we have processed all the DIEs in the CU, all the types 
7914      should be complete, and it should now be safe to compute all of the
7915      physnames.  */
7916   compute_delayed_physnames (cu);
7917   do_cleanups (delayed_list_cleanup);
7918
7919   /* TUs share symbol tables.
7920      If this is the first TU to use this symtab, complete the construction
7921      of it with end_expandable_symtab.  Otherwise, complete the addition of
7922      this TU's symbols to the existing symtab.  */
7923   if (sig_type->type_unit_group->primary_symtab == NULL)
7924     {
7925       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7926       sig_type->type_unit_group->primary_symtab = symtab;
7927
7928       if (symtab != NULL)
7929         {
7930           /* Set symtab language to language from DW_AT_language.  If the
7931              compilation is from a C file generated by language preprocessors,
7932              do not set the language if it was already deduced by
7933              start_subfile.  */
7934           if (!(cu->language == language_c && symtab->language != language_c))
7935             symtab->language = cu->language;
7936         }
7937     }
7938   else
7939     {
7940       augment_type_symtab (objfile,
7941                            sig_type->type_unit_group->primary_symtab);
7942       symtab = sig_type->type_unit_group->primary_symtab;
7943     }
7944
7945   if (dwarf2_per_objfile->using_index)
7946     per_cu->v.quick->symtab = symtab;
7947   else
7948     {
7949       struct partial_symtab *pst = per_cu->v.psymtab;
7950       pst->symtab = symtab;
7951       pst->readin = 1;
7952     }
7953
7954   do_cleanups (back_to);
7955 }
7956
7957 /* Process an imported unit DIE.  */
7958
7959 static void
7960 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7961 {
7962   struct attribute *attr;
7963
7964   /* For now we don't handle imported units in type units.  */
7965   if (cu->per_cu->is_debug_types)
7966     {
7967       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7968                " supported in type units [in module %s]"),
7969              objfile_name (cu->objfile));
7970     }
7971
7972   attr = dwarf2_attr (die, DW_AT_import, cu);
7973   if (attr != NULL)
7974     {
7975       struct dwarf2_per_cu_data *per_cu;
7976       struct symtab *imported_symtab;
7977       sect_offset offset;
7978       int is_dwz;
7979
7980       offset = dwarf2_get_ref_die_offset (attr);
7981       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7982       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7983
7984       /* If necessary, add it to the queue and load its DIEs.  */
7985       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7986         load_full_comp_unit (per_cu, cu->language);
7987
7988       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7989                      per_cu);
7990     }
7991 }
7992
7993 /* Process a die and its children.  */
7994
7995 static void
7996 process_die (struct die_info *die, struct dwarf2_cu *cu)
7997 {
7998   switch (die->tag)
7999     {
8000     case DW_TAG_padding:
8001       break;
8002     case DW_TAG_compile_unit:
8003     case DW_TAG_partial_unit:
8004       read_file_scope (die, cu);
8005       break;
8006     case DW_TAG_type_unit:
8007       read_type_unit_scope (die, cu);
8008       break;
8009     case DW_TAG_subprogram:
8010     case DW_TAG_inlined_subroutine:
8011       read_func_scope (die, cu);
8012       break;
8013     case DW_TAG_lexical_block:
8014     case DW_TAG_try_block:
8015     case DW_TAG_catch_block:
8016       read_lexical_block_scope (die, cu);
8017       break;
8018     case DW_TAG_GNU_call_site:
8019       read_call_site_scope (die, cu);
8020       break;
8021     case DW_TAG_class_type:
8022     case DW_TAG_interface_type:
8023     case DW_TAG_structure_type:
8024     case DW_TAG_union_type:
8025       process_structure_scope (die, cu);
8026       break;
8027     case DW_TAG_enumeration_type:
8028       process_enumeration_scope (die, cu);
8029       break;
8030
8031     /* These dies have a type, but processing them does not create
8032        a symbol or recurse to process the children.  Therefore we can
8033        read them on-demand through read_type_die.  */
8034     case DW_TAG_subroutine_type:
8035     case DW_TAG_set_type:
8036     case DW_TAG_array_type:
8037     case DW_TAG_pointer_type:
8038     case DW_TAG_ptr_to_member_type:
8039     case DW_TAG_reference_type:
8040     case DW_TAG_string_type:
8041       break;
8042
8043     case DW_TAG_base_type:
8044     case DW_TAG_subrange_type:
8045     case DW_TAG_typedef:
8046       /* Add a typedef symbol for the type definition, if it has a
8047          DW_AT_name.  */
8048       new_symbol (die, read_type_die (die, cu), cu);
8049       break;
8050     case DW_TAG_common_block:
8051       read_common_block (die, cu);
8052       break;
8053     case DW_TAG_common_inclusion:
8054       break;
8055     case DW_TAG_namespace:
8056       cu->processing_has_namespace_info = 1;
8057       read_namespace (die, cu);
8058       break;
8059     case DW_TAG_module:
8060       cu->processing_has_namespace_info = 1;
8061       read_module (die, cu);
8062       break;
8063     case DW_TAG_imported_declaration:
8064     case DW_TAG_imported_module:
8065       cu->processing_has_namespace_info = 1;
8066       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8067                                  || cu->language != language_fortran))
8068         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8069                    dwarf_tag_name (die->tag));
8070       read_import_statement (die, cu);
8071       break;
8072
8073     case DW_TAG_imported_unit:
8074       process_imported_unit_die (die, cu);
8075       break;
8076
8077     default:
8078       new_symbol (die, NULL, cu);
8079       break;
8080     }
8081 }
8082 \f
8083 /* DWARF name computation.  */
8084
8085 /* A helper function for dwarf2_compute_name which determines whether DIE
8086    needs to have the name of the scope prepended to the name listed in the
8087    die.  */
8088
8089 static int
8090 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8091 {
8092   struct attribute *attr;
8093
8094   switch (die->tag)
8095     {
8096     case DW_TAG_namespace:
8097     case DW_TAG_typedef:
8098     case DW_TAG_class_type:
8099     case DW_TAG_interface_type:
8100     case DW_TAG_structure_type:
8101     case DW_TAG_union_type:
8102     case DW_TAG_enumeration_type:
8103     case DW_TAG_enumerator:
8104     case DW_TAG_subprogram:
8105     case DW_TAG_member:
8106       return 1;
8107
8108     case DW_TAG_variable:
8109     case DW_TAG_constant:
8110       /* We only need to prefix "globally" visible variables.  These include
8111          any variable marked with DW_AT_external or any variable that
8112          lives in a namespace.  [Variables in anonymous namespaces
8113          require prefixing, but they are not DW_AT_external.]  */
8114
8115       if (dwarf2_attr (die, DW_AT_specification, cu))
8116         {
8117           struct dwarf2_cu *spec_cu = cu;
8118
8119           return die_needs_namespace (die_specification (die, &spec_cu),
8120                                       spec_cu);
8121         }
8122
8123       attr = dwarf2_attr (die, DW_AT_external, cu);
8124       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8125           && die->parent->tag != DW_TAG_module)
8126         return 0;
8127       /* A variable in a lexical block of some kind does not need a
8128          namespace, even though in C++ such variables may be external
8129          and have a mangled name.  */
8130       if (die->parent->tag ==  DW_TAG_lexical_block
8131           || die->parent->tag ==  DW_TAG_try_block
8132           || die->parent->tag ==  DW_TAG_catch_block
8133           || die->parent->tag == DW_TAG_subprogram)
8134         return 0;
8135       return 1;
8136
8137     default:
8138       return 0;
8139     }
8140 }
8141
8142 /* Retrieve the last character from a mem_file.  */
8143
8144 static void
8145 do_ui_file_peek_last (void *object, const char *buffer, long length)
8146 {
8147   char *last_char_p = (char *) object;
8148
8149   if (length > 0)
8150     *last_char_p = buffer[length - 1];
8151 }
8152
8153 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8154    compute the physname for the object, which include a method's:
8155    - formal parameters (C++/Java),
8156    - receiver type (Go),
8157    - return type (Java).
8158
8159    The term "physname" is a bit confusing.
8160    For C++, for example, it is the demangled name.
8161    For Go, for example, it's the mangled name.
8162
8163    For Ada, return the DIE's linkage name rather than the fully qualified
8164    name.  PHYSNAME is ignored..
8165
8166    The result is allocated on the objfile_obstack and canonicalized.  */
8167
8168 static const char *
8169 dwarf2_compute_name (const char *name,
8170                      struct die_info *die, struct dwarf2_cu *cu,
8171                      int physname)
8172 {
8173   struct objfile *objfile = cu->objfile;
8174
8175   if (name == NULL)
8176     name = dwarf2_name (die, cu);
8177
8178   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
8179      compute it by typename_concat inside GDB.  */
8180   if (cu->language == language_ada
8181       || (cu->language == language_fortran && physname))
8182     {
8183       /* For Ada unit, we prefer the linkage name over the name, as
8184          the former contains the exported name, which the user expects
8185          to be able to reference.  Ideally, we want the user to be able
8186          to reference this entity using either natural or linkage name,
8187          but we haven't started looking at this enhancement yet.  */
8188       struct attribute *attr;
8189
8190       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8191       if (attr == NULL)
8192         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8193       if (attr && DW_STRING (attr))
8194         return DW_STRING (attr);
8195     }
8196
8197   /* These are the only languages we know how to qualify names in.  */
8198   if (name != NULL
8199       && (cu->language == language_cplus || cu->language == language_java
8200           || cu->language == language_fortran))
8201     {
8202       if (die_needs_namespace (die, cu))
8203         {
8204           long length;
8205           const char *prefix;
8206           struct ui_file *buf;
8207
8208           prefix = determine_prefix (die, cu);
8209           buf = mem_fileopen ();
8210           if (*prefix != '\0')
8211             {
8212               char *prefixed_name = typename_concat (NULL, prefix, name,
8213                                                      physname, cu);
8214
8215               fputs_unfiltered (prefixed_name, buf);
8216               xfree (prefixed_name);
8217             }
8218           else
8219             fputs_unfiltered (name, buf);
8220
8221           /* Template parameters may be specified in the DIE's DW_AT_name, or
8222              as children with DW_TAG_template_type_param or
8223              DW_TAG_value_type_param.  If the latter, add them to the name
8224              here.  If the name already has template parameters, then
8225              skip this step; some versions of GCC emit both, and
8226              it is more efficient to use the pre-computed name.
8227
8228              Something to keep in mind about this process: it is very
8229              unlikely, or in some cases downright impossible, to produce
8230              something that will match the mangled name of a function.
8231              If the definition of the function has the same debug info,
8232              we should be able to match up with it anyway.  But fallbacks
8233              using the minimal symbol, for instance to find a method
8234              implemented in a stripped copy of libstdc++, will not work.
8235              If we do not have debug info for the definition, we will have to
8236              match them up some other way.
8237
8238              When we do name matching there is a related problem with function
8239              templates; two instantiated function templates are allowed to
8240              differ only by their return types, which we do not add here.  */
8241
8242           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8243             {
8244               struct attribute *attr;
8245               struct die_info *child;
8246               int first = 1;
8247
8248               die->building_fullname = 1;
8249
8250               for (child = die->child; child != NULL; child = child->sibling)
8251                 {
8252                   struct type *type;
8253                   LONGEST value;
8254                   const gdb_byte *bytes;
8255                   struct dwarf2_locexpr_baton *baton;
8256                   struct value *v;
8257
8258                   if (child->tag != DW_TAG_template_type_param
8259                       && child->tag != DW_TAG_template_value_param)
8260                     continue;
8261
8262                   if (first)
8263                     {
8264                       fputs_unfiltered ("<", buf);
8265                       first = 0;
8266                     }
8267                   else
8268                     fputs_unfiltered (", ", buf);
8269
8270                   attr = dwarf2_attr (child, DW_AT_type, cu);
8271                   if (attr == NULL)
8272                     {
8273                       complaint (&symfile_complaints,
8274                                  _("template parameter missing DW_AT_type"));
8275                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
8276                       continue;
8277                     }
8278                   type = die_type (child, cu);
8279
8280                   if (child->tag == DW_TAG_template_type_param)
8281                     {
8282                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
8283                       continue;
8284                     }
8285
8286                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8287                   if (attr == NULL)
8288                     {
8289                       complaint (&symfile_complaints,
8290                                  _("template parameter missing "
8291                                    "DW_AT_const_value"));
8292                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8293                       continue;
8294                     }
8295
8296                   dwarf2_const_value_attr (attr, type, name,
8297                                            &cu->comp_unit_obstack, cu,
8298                                            &value, &bytes, &baton);
8299
8300                   if (TYPE_NOSIGN (type))
8301                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8302                        changed, this can use value_print instead.  */
8303                     c_printchar (value, type, buf);
8304                   else
8305                     {
8306                       struct value_print_options opts;
8307
8308                       if (baton != NULL)
8309                         v = dwarf2_evaluate_loc_desc (type, NULL,
8310                                                       baton->data,
8311                                                       baton->size,
8312                                                       baton->per_cu);
8313                       else if (bytes != NULL)
8314                         {
8315                           v = allocate_value (type);
8316                           memcpy (value_contents_writeable (v), bytes,
8317                                   TYPE_LENGTH (type));
8318                         }
8319                       else
8320                         v = value_from_longest (type, value);
8321
8322                       /* Specify decimal so that we do not depend on
8323                          the radix.  */
8324                       get_formatted_print_options (&opts, 'd');
8325                       opts.raw = 1;
8326                       value_print (v, buf, &opts);
8327                       release_value (v);
8328                       value_free (v);
8329                     }
8330                 }
8331
8332               die->building_fullname = 0;
8333
8334               if (!first)
8335                 {
8336                   /* Close the argument list, with a space if necessary
8337                      (nested templates).  */
8338                   char last_char = '\0';
8339                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8340                   if (last_char == '>')
8341                     fputs_unfiltered (" >", buf);
8342                   else
8343                     fputs_unfiltered (">", buf);
8344                 }
8345             }
8346
8347           /* For Java and C++ methods, append formal parameter type
8348              information, if PHYSNAME.  */
8349
8350           if (physname && die->tag == DW_TAG_subprogram
8351               && (cu->language == language_cplus
8352                   || cu->language == language_java))
8353             {
8354               struct type *type = read_type_die (die, cu);
8355
8356               c_type_print_args (type, buf, 1, cu->language,
8357                                  &type_print_raw_options);
8358
8359               if (cu->language == language_java)
8360                 {
8361                   /* For java, we must append the return type to method
8362                      names.  */
8363                   if (die->tag == DW_TAG_subprogram)
8364                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8365                                      0, 0, &type_print_raw_options);
8366                 }
8367               else if (cu->language == language_cplus)
8368                 {
8369                   /* Assume that an artificial first parameter is
8370                      "this", but do not crash if it is not.  RealView
8371                      marks unnamed (and thus unused) parameters as
8372                      artificial; there is no way to differentiate
8373                      the two cases.  */
8374                   if (TYPE_NFIELDS (type) > 0
8375                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8376                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8377                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8378                                                                         0))))
8379                     fputs_unfiltered (" const", buf);
8380                 }
8381             }
8382
8383           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8384                                        &length);
8385           ui_file_delete (buf);
8386
8387           if (cu->language == language_cplus)
8388             {
8389               const char *cname
8390                 = dwarf2_canonicalize_name (name, cu,
8391                                             &objfile->objfile_obstack);
8392
8393               if (cname != NULL)
8394                 name = cname;
8395             }
8396         }
8397     }
8398
8399   return name;
8400 }
8401
8402 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8403    If scope qualifiers are appropriate they will be added.  The result
8404    will be allocated on the objfile_obstack, or NULL if the DIE does
8405    not have a name.  NAME may either be from a previous call to
8406    dwarf2_name or NULL.
8407
8408    The output string will be canonicalized (if C++/Java).  */
8409
8410 static const char *
8411 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8412 {
8413   return dwarf2_compute_name (name, die, cu, 0);
8414 }
8415
8416 /* Construct a physname for the given DIE in CU.  NAME may either be
8417    from a previous call to dwarf2_name or NULL.  The result will be
8418    allocated on the objfile_objstack or NULL if the DIE does not have a
8419    name.
8420
8421    The output string will be canonicalized (if C++/Java).  */
8422
8423 static const char *
8424 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8425 {
8426   struct objfile *objfile = cu->objfile;
8427   struct attribute *attr;
8428   const char *retval, *mangled = NULL, *canon = NULL;
8429   struct cleanup *back_to;
8430   int need_copy = 1;
8431
8432   /* In this case dwarf2_compute_name is just a shortcut not building anything
8433      on its own.  */
8434   if (!die_needs_namespace (die, cu))
8435     return dwarf2_compute_name (name, die, cu, 1);
8436
8437   back_to = make_cleanup (null_cleanup, NULL);
8438
8439   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8440   if (!attr)
8441     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8442
8443   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8444      has computed.  */
8445   if (attr && DW_STRING (attr))
8446     {
8447       char *demangled;
8448
8449       mangled = DW_STRING (attr);
8450
8451       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8452          type.  It is easier for GDB users to search for such functions as
8453          `name(params)' than `long name(params)'.  In such case the minimal
8454          symbol names do not match the full symbol names but for template
8455          functions there is never a need to look up their definition from their
8456          declaration so the only disadvantage remains the minimal symbol
8457          variant `long name(params)' does not have the proper inferior type.
8458          */
8459
8460       if (cu->language == language_go)
8461         {
8462           /* This is a lie, but we already lie to the caller new_symbol_full.
8463              new_symbol_full assumes we return the mangled name.
8464              This just undoes that lie until things are cleaned up.  */
8465           demangled = NULL;
8466         }
8467       else
8468         {
8469           demangled = gdb_demangle (mangled,
8470                                     (DMGL_PARAMS | DMGL_ANSI
8471                                      | (cu->language == language_java
8472                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8473                                         : DMGL_RET_DROP)));
8474         }
8475       if (demangled)
8476         {
8477           make_cleanup (xfree, demangled);
8478           canon = demangled;
8479         }
8480       else
8481         {
8482           canon = mangled;
8483           need_copy = 0;
8484         }
8485     }
8486
8487   if (canon == NULL || check_physname)
8488     {
8489       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8490
8491       if (canon != NULL && strcmp (physname, canon) != 0)
8492         {
8493           /* It may not mean a bug in GDB.  The compiler could also
8494              compute DW_AT_linkage_name incorrectly.  But in such case
8495              GDB would need to be bug-to-bug compatible.  */
8496
8497           complaint (&symfile_complaints,
8498                      _("Computed physname <%s> does not match demangled <%s> "
8499                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8500                      physname, canon, mangled, die->offset.sect_off,
8501                      objfile_name (objfile));
8502
8503           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8504              is available here - over computed PHYSNAME.  It is safer
8505              against both buggy GDB and buggy compilers.  */
8506
8507           retval = canon;
8508         }
8509       else
8510         {
8511           retval = physname;
8512           need_copy = 0;
8513         }
8514     }
8515   else
8516     retval = canon;
8517
8518   if (need_copy)
8519     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8520
8521   do_cleanups (back_to);
8522   return retval;
8523 }
8524
8525 /* Read the import statement specified by the given die and record it.  */
8526
8527 static void
8528 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8529 {
8530   struct objfile *objfile = cu->objfile;
8531   struct attribute *import_attr;
8532   struct die_info *imported_die, *child_die;
8533   struct dwarf2_cu *imported_cu;
8534   const char *imported_name;
8535   const char *imported_name_prefix;
8536   const char *canonical_name;
8537   const char *import_alias;
8538   const char *imported_declaration = NULL;
8539   const char *import_prefix;
8540   VEC (const_char_ptr) *excludes = NULL;
8541   struct cleanup *cleanups;
8542
8543   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8544   if (import_attr == NULL)
8545     {
8546       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8547                  dwarf_tag_name (die->tag));
8548       return;
8549     }
8550
8551   imported_cu = cu;
8552   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8553   imported_name = dwarf2_name (imported_die, imported_cu);
8554   if (imported_name == NULL)
8555     {
8556       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8557
8558         The import in the following code:
8559         namespace A
8560           {
8561             typedef int B;
8562           }
8563
8564         int main ()
8565           {
8566             using A::B;
8567             B b;
8568             return b;
8569           }
8570
8571         ...
8572          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8573             <52>   DW_AT_decl_file   : 1
8574             <53>   DW_AT_decl_line   : 6
8575             <54>   DW_AT_import      : <0x75>
8576          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8577             <59>   DW_AT_name        : B
8578             <5b>   DW_AT_decl_file   : 1
8579             <5c>   DW_AT_decl_line   : 2
8580             <5d>   DW_AT_type        : <0x6e>
8581         ...
8582          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8583             <76>   DW_AT_byte_size   : 4
8584             <77>   DW_AT_encoding    : 5        (signed)
8585
8586         imports the wrong die ( 0x75 instead of 0x58 ).
8587         This case will be ignored until the gcc bug is fixed.  */
8588       return;
8589     }
8590
8591   /* Figure out the local name after import.  */
8592   import_alias = dwarf2_name (die, cu);
8593
8594   /* Figure out where the statement is being imported to.  */
8595   import_prefix = determine_prefix (die, cu);
8596
8597   /* Figure out what the scope of the imported die is and prepend it
8598      to the name of the imported die.  */
8599   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8600
8601   if (imported_die->tag != DW_TAG_namespace
8602       && imported_die->tag != DW_TAG_module)
8603     {
8604       imported_declaration = imported_name;
8605       canonical_name = imported_name_prefix;
8606     }
8607   else if (strlen (imported_name_prefix) > 0)
8608     canonical_name = obconcat (&objfile->objfile_obstack,
8609                                imported_name_prefix, "::", imported_name,
8610                                (char *) NULL);
8611   else
8612     canonical_name = imported_name;
8613
8614   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8615
8616   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8617     for (child_die = die->child; child_die && child_die->tag;
8618          child_die = sibling_die (child_die))
8619       {
8620         /* DWARF-4: A Fortran use statement with a “rename list” may be
8621            represented by an imported module entry with an import attribute
8622            referring to the module and owned entries corresponding to those
8623            entities that are renamed as part of being imported.  */
8624
8625         if (child_die->tag != DW_TAG_imported_declaration)
8626           {
8627             complaint (&symfile_complaints,
8628                        _("child DW_TAG_imported_declaration expected "
8629                          "- DIE at 0x%x [in module %s]"),
8630                        child_die->offset.sect_off, objfile_name (objfile));
8631             continue;
8632           }
8633
8634         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8635         if (import_attr == NULL)
8636           {
8637             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8638                        dwarf_tag_name (child_die->tag));
8639             continue;
8640           }
8641
8642         imported_cu = cu;
8643         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8644                                               &imported_cu);
8645         imported_name = dwarf2_name (imported_die, imported_cu);
8646         if (imported_name == NULL)
8647           {
8648             complaint (&symfile_complaints,
8649                        _("child DW_TAG_imported_declaration has unknown "
8650                          "imported name - DIE at 0x%x [in module %s]"),
8651                        child_die->offset.sect_off, objfile_name (objfile));
8652             continue;
8653           }
8654
8655         VEC_safe_push (const_char_ptr, excludes, imported_name);
8656
8657         process_die (child_die, cu);
8658       }
8659
8660   cp_add_using_directive (import_prefix,
8661                           canonical_name,
8662                           import_alias,
8663                           imported_declaration,
8664                           excludes,
8665                           0,
8666                           &objfile->objfile_obstack);
8667
8668   do_cleanups (cleanups);
8669 }
8670
8671 /* Cleanup function for handle_DW_AT_stmt_list.  */
8672
8673 static void
8674 free_cu_line_header (void *arg)
8675 {
8676   struct dwarf2_cu *cu = arg;
8677
8678   free_line_header (cu->line_header);
8679   cu->line_header = NULL;
8680 }
8681
8682 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8683    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8684    this, it was first present in GCC release 4.3.0.  */
8685
8686 static int
8687 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8688 {
8689   if (!cu->checked_producer)
8690     check_producer (cu);
8691
8692   return cu->producer_is_gcc_lt_4_3;
8693 }
8694
8695 static void
8696 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8697                          const char **name, const char **comp_dir)
8698 {
8699   struct attribute *attr;
8700
8701   *name = NULL;
8702   *comp_dir = NULL;
8703
8704   /* Find the filename.  Do not use dwarf2_name here, since the filename
8705      is not a source language identifier.  */
8706   attr = dwarf2_attr (die, DW_AT_name, cu);
8707   if (attr)
8708     {
8709       *name = DW_STRING (attr);
8710     }
8711
8712   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8713   if (attr)
8714     *comp_dir = DW_STRING (attr);
8715   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8716            && IS_ABSOLUTE_PATH (*name))
8717     {
8718       char *d = ldirname (*name);
8719
8720       *comp_dir = d;
8721       if (d != NULL)
8722         make_cleanup (xfree, d);
8723     }
8724   if (*comp_dir != NULL)
8725     {
8726       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8727          directory, get rid of it.  */
8728       char *cp = strchr (*comp_dir, ':');
8729
8730       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8731         *comp_dir = cp + 1;
8732     }
8733
8734   if (*name == NULL)
8735     *name = "<unknown>";
8736 }
8737
8738 /* Handle DW_AT_stmt_list for a compilation unit.
8739    DIE is the DW_TAG_compile_unit die for CU.
8740    COMP_DIR is the compilation directory.
8741    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8742
8743 static void
8744 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8745                         const char *comp_dir) /* ARI: editCase function */
8746 {
8747   struct attribute *attr;
8748
8749   gdb_assert (! cu->per_cu->is_debug_types);
8750
8751   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8752   if (attr)
8753     {
8754       unsigned int line_offset = DW_UNSND (attr);
8755       struct line_header *line_header
8756         = dwarf_decode_line_header (line_offset, cu);
8757
8758       if (line_header)
8759         {
8760           cu->line_header = line_header;
8761           make_cleanup (free_cu_line_header, cu);
8762           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8763         }
8764     }
8765 }
8766
8767 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8768
8769 static void
8770 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8771 {
8772   struct objfile *objfile = dwarf2_per_objfile->objfile;
8773   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8774   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8775   CORE_ADDR highpc = ((CORE_ADDR) 0);
8776   struct attribute *attr;
8777   const char *name = NULL;
8778   const char *comp_dir = NULL;
8779   struct die_info *child_die;
8780   bfd *abfd = objfile->obfd;
8781   CORE_ADDR baseaddr;
8782
8783   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8784
8785   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8786
8787   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8788      from finish_block.  */
8789   if (lowpc == ((CORE_ADDR) -1))
8790     lowpc = highpc;
8791   lowpc += baseaddr;
8792   highpc += baseaddr;
8793
8794   find_file_and_directory (die, cu, &name, &comp_dir);
8795
8796   prepare_one_comp_unit (cu, die, cu->language);
8797
8798   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8799      standardised yet.  As a workaround for the language detection we fall
8800      back to the DW_AT_producer string.  */
8801   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8802     cu->language = language_opencl;
8803
8804   /* Similar hack for Go.  */
8805   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8806     set_cu_language (DW_LANG_Go, cu);
8807
8808   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8809
8810   /* Decode line number information if present.  We do this before
8811      processing child DIEs, so that the line header table is available
8812      for DW_AT_decl_file.  */
8813   handle_DW_AT_stmt_list (die, cu, comp_dir);
8814
8815   /* Process all dies in compilation unit.  */
8816   if (die->child != NULL)
8817     {
8818       child_die = die->child;
8819       while (child_die && child_die->tag)
8820         {
8821           process_die (child_die, cu);
8822           child_die = sibling_die (child_die);
8823         }
8824     }
8825
8826   /* Decode macro information, if present.  Dwarf 2 macro information
8827      refers to information in the line number info statement program
8828      header, so we can only read it if we've read the header
8829      successfully.  */
8830   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8831   if (attr && cu->line_header)
8832     {
8833       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8834         complaint (&symfile_complaints,
8835                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8836
8837       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8838     }
8839   else
8840     {
8841       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8842       if (attr && cu->line_header)
8843         {
8844           unsigned int macro_offset = DW_UNSND (attr);
8845
8846           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8847         }
8848     }
8849
8850   do_cleanups (back_to);
8851 }
8852
8853 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8854    Create the set of symtabs used by this TU, or if this TU is sharing
8855    symtabs with another TU and the symtabs have already been created
8856    then restore those symtabs in the line header.
8857    We don't need the pc/line-number mapping for type units.  */
8858
8859 static void
8860 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8861 {
8862   struct objfile *objfile = dwarf2_per_objfile->objfile;
8863   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8864   struct type_unit_group *tu_group;
8865   int first_time;
8866   struct line_header *lh;
8867   struct attribute *attr;
8868   unsigned int i, line_offset;
8869   struct signatured_type *sig_type;
8870
8871   gdb_assert (per_cu->is_debug_types);
8872   sig_type = (struct signatured_type *) per_cu;
8873
8874   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8875
8876   /* If we're using .gdb_index (includes -readnow) then
8877      per_cu->type_unit_group may not have been set up yet.  */
8878   if (sig_type->type_unit_group == NULL)
8879     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8880   tu_group = sig_type->type_unit_group;
8881
8882   /* If we've already processed this stmt_list there's no real need to
8883      do it again, we could fake it and just recreate the part we need
8884      (file name,index -> symtab mapping).  If data shows this optimization
8885      is useful we can do it then.  */
8886   first_time = tu_group->primary_symtab == NULL;
8887
8888   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8889      debug info.  */
8890   lh = NULL;
8891   if (attr != NULL)
8892     {
8893       line_offset = DW_UNSND (attr);
8894       lh = dwarf_decode_line_header (line_offset, cu);
8895     }
8896   if (lh == NULL)
8897     {
8898       if (first_time)
8899         dwarf2_start_symtab (cu, "", NULL, 0);
8900       else
8901         {
8902           gdb_assert (tu_group->symtabs == NULL);
8903           restart_symtab (0);
8904         }
8905       /* Note: The primary symtab will get allocated at the end.  */
8906       return;
8907     }
8908
8909   cu->line_header = lh;
8910   make_cleanup (free_cu_line_header, cu);
8911
8912   if (first_time)
8913     {
8914       dwarf2_start_symtab (cu, "", NULL, 0);
8915
8916       tu_group->num_symtabs = lh->num_file_names;
8917       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8918
8919       for (i = 0; i < lh->num_file_names; ++i)
8920         {
8921           const char *dir = NULL;
8922           struct file_entry *fe = &lh->file_names[i];
8923
8924           if (fe->dir_index)
8925             dir = lh->include_dirs[fe->dir_index - 1];
8926           dwarf2_start_subfile (fe->name, dir, NULL);
8927
8928           /* Note: We don't have to watch for the main subfile here, type units
8929              don't have DW_AT_name.  */
8930
8931           if (current_subfile->symtab == NULL)
8932             {
8933               /* NOTE: start_subfile will recognize when it's been passed
8934                  a file it has already seen.  So we can't assume there's a
8935                  simple mapping from lh->file_names to subfiles,
8936                  lh->file_names may contain dups.  */
8937               current_subfile->symtab = allocate_symtab (current_subfile->name,
8938                                                          objfile);
8939             }
8940
8941           fe->symtab = current_subfile->symtab;
8942           tu_group->symtabs[i] = fe->symtab;
8943         }
8944     }
8945   else
8946     {
8947       restart_symtab (0);
8948
8949       for (i = 0; i < lh->num_file_names; ++i)
8950         {
8951           struct file_entry *fe = &lh->file_names[i];
8952
8953           fe->symtab = tu_group->symtabs[i];
8954         }
8955     }
8956
8957   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8958      so they don't have a "real" (so to speak) symtab anyway.
8959      There is later code that will assign the main symtab to all symbols
8960      that don't have one.  We need to handle the case of a symbol with a
8961      missing symtab (DW_AT_decl_file) anyway.  */
8962 }
8963
8964 /* Process DW_TAG_type_unit.
8965    For TUs we want to skip the first top level sibling if it's not the
8966    actual type being defined by this TU.  In this case the first top
8967    level sibling is there to provide context only.  */
8968
8969 static void
8970 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8971 {
8972   struct die_info *child_die;
8973
8974   prepare_one_comp_unit (cu, die, language_minimal);
8975
8976   /* Initialize (or reinitialize) the machinery for building symtabs.
8977      We do this before processing child DIEs, so that the line header table
8978      is available for DW_AT_decl_file.  */
8979   setup_type_unit_groups (die, cu);
8980
8981   if (die->child != NULL)
8982     {
8983       child_die = die->child;
8984       while (child_die && child_die->tag)
8985         {
8986           process_die (child_die, cu);
8987           child_die = sibling_die (child_die);
8988         }
8989     }
8990 }
8991 \f
8992 /* DWO/DWP files.
8993
8994    http://gcc.gnu.org/wiki/DebugFission
8995    http://gcc.gnu.org/wiki/DebugFissionDWP
8996
8997    To simplify handling of both DWO files ("object" files with the DWARF info)
8998    and DWP files (a file with the DWOs packaged up into one file), we treat
8999    DWP files as having a collection of virtual DWO files.  */
9000
9001 static hashval_t
9002 hash_dwo_file (const void *item)
9003 {
9004   const struct dwo_file *dwo_file = item;
9005   hashval_t hash;
9006
9007   hash = htab_hash_string (dwo_file->dwo_name);
9008   if (dwo_file->comp_dir != NULL)
9009     hash += htab_hash_string (dwo_file->comp_dir);
9010   return hash;
9011 }
9012
9013 static int
9014 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9015 {
9016   const struct dwo_file *lhs = item_lhs;
9017   const struct dwo_file *rhs = item_rhs;
9018
9019   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9020     return 0;
9021   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9022     return lhs->comp_dir == rhs->comp_dir;
9023   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9024 }
9025
9026 /* Allocate a hash table for DWO files.  */
9027
9028 static htab_t
9029 allocate_dwo_file_hash_table (void)
9030 {
9031   struct objfile *objfile = dwarf2_per_objfile->objfile;
9032
9033   return htab_create_alloc_ex (41,
9034                                hash_dwo_file,
9035                                eq_dwo_file,
9036                                NULL,
9037                                &objfile->objfile_obstack,
9038                                hashtab_obstack_allocate,
9039                                dummy_obstack_deallocate);
9040 }
9041
9042 /* Lookup DWO file DWO_NAME.  */
9043
9044 static void **
9045 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9046 {
9047   struct dwo_file find_entry;
9048   void **slot;
9049
9050   if (dwarf2_per_objfile->dwo_files == NULL)
9051     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9052
9053   memset (&find_entry, 0, sizeof (find_entry));
9054   find_entry.dwo_name = dwo_name;
9055   find_entry.comp_dir = comp_dir;
9056   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9057
9058   return slot;
9059 }
9060
9061 static hashval_t
9062 hash_dwo_unit (const void *item)
9063 {
9064   const struct dwo_unit *dwo_unit = item;
9065
9066   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9067   return dwo_unit->signature;
9068 }
9069
9070 static int
9071 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9072 {
9073   const struct dwo_unit *lhs = item_lhs;
9074   const struct dwo_unit *rhs = item_rhs;
9075
9076   /* The signature is assumed to be unique within the DWO file.
9077      So while object file CU dwo_id's always have the value zero,
9078      that's OK, assuming each object file DWO file has only one CU,
9079      and that's the rule for now.  */
9080   return lhs->signature == rhs->signature;
9081 }
9082
9083 /* Allocate a hash table for DWO CUs,TUs.
9084    There is one of these tables for each of CUs,TUs for each DWO file.  */
9085
9086 static htab_t
9087 allocate_dwo_unit_table (struct objfile *objfile)
9088 {
9089   /* Start out with a pretty small number.
9090      Generally DWO files contain only one CU and maybe some TUs.  */
9091   return htab_create_alloc_ex (3,
9092                                hash_dwo_unit,
9093                                eq_dwo_unit,
9094                                NULL,
9095                                &objfile->objfile_obstack,
9096                                hashtab_obstack_allocate,
9097                                dummy_obstack_deallocate);
9098 }
9099
9100 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9101
9102 struct create_dwo_cu_data
9103 {
9104   struct dwo_file *dwo_file;
9105   struct dwo_unit dwo_unit;
9106 };
9107
9108 /* die_reader_func for create_dwo_cu.  */
9109
9110 static void
9111 create_dwo_cu_reader (const struct die_reader_specs *reader,
9112                       const gdb_byte *info_ptr,
9113                       struct die_info *comp_unit_die,
9114                       int has_children,
9115                       void *datap)
9116 {
9117   struct dwarf2_cu *cu = reader->cu;
9118   struct objfile *objfile = dwarf2_per_objfile->objfile;
9119   sect_offset offset = cu->per_cu->offset;
9120   struct dwarf2_section_info *section = cu->per_cu->section;
9121   struct create_dwo_cu_data *data = datap;
9122   struct dwo_file *dwo_file = data->dwo_file;
9123   struct dwo_unit *dwo_unit = &data->dwo_unit;
9124   struct attribute *attr;
9125
9126   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9127   if (attr == NULL)
9128     {
9129       complaint (&symfile_complaints,
9130                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9131                    " its dwo_id [in module %s]"),
9132                  offset.sect_off, dwo_file->dwo_name);
9133       return;
9134     }
9135
9136   dwo_unit->dwo_file = dwo_file;
9137   dwo_unit->signature = DW_UNSND (attr);
9138   dwo_unit->section = section;
9139   dwo_unit->offset = offset;
9140   dwo_unit->length = cu->per_cu->length;
9141
9142   if (dwarf2_read_debug)
9143     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9144                         offset.sect_off, hex_string (dwo_unit->signature));
9145 }
9146
9147 /* Create the dwo_unit for the lone CU in DWO_FILE.
9148    Note: This function processes DWO files only, not DWP files.  */
9149
9150 static struct dwo_unit *
9151 create_dwo_cu (struct dwo_file *dwo_file)
9152 {
9153   struct objfile *objfile = dwarf2_per_objfile->objfile;
9154   struct dwarf2_section_info *section = &dwo_file->sections.info;
9155   bfd *abfd;
9156   htab_t cu_htab;
9157   const gdb_byte *info_ptr, *end_ptr;
9158   struct create_dwo_cu_data create_dwo_cu_data;
9159   struct dwo_unit *dwo_unit;
9160
9161   dwarf2_read_section (objfile, section);
9162   info_ptr = section->buffer;
9163
9164   if (info_ptr == NULL)
9165     return NULL;
9166
9167   /* We can't set abfd until now because the section may be empty or
9168      not present, in which case section->asection will be NULL.  */
9169   abfd = get_section_bfd_owner (section);
9170
9171   if (dwarf2_read_debug)
9172     {
9173       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9174                           get_section_name (section),
9175                           get_section_file_name (section));
9176     }
9177
9178   create_dwo_cu_data.dwo_file = dwo_file;
9179   dwo_unit = NULL;
9180
9181   end_ptr = info_ptr + section->size;
9182   while (info_ptr < end_ptr)
9183     {
9184       struct dwarf2_per_cu_data per_cu;
9185
9186       memset (&create_dwo_cu_data.dwo_unit, 0,
9187               sizeof (create_dwo_cu_data.dwo_unit));
9188       memset (&per_cu, 0, sizeof (per_cu));
9189       per_cu.objfile = objfile;
9190       per_cu.is_debug_types = 0;
9191       per_cu.offset.sect_off = info_ptr - section->buffer;
9192       per_cu.section = section;
9193
9194       init_cutu_and_read_dies_no_follow (&per_cu,
9195                                          &dwo_file->sections.abbrev,
9196                                          dwo_file,
9197                                          create_dwo_cu_reader,
9198                                          &create_dwo_cu_data);
9199
9200       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
9201         {
9202           /* If we've already found one, complain.  We only support one
9203              because having more than one requires hacking the dwo_name of
9204              each to match, which is highly unlikely to happen.  */
9205           if (dwo_unit != NULL)
9206             {
9207               complaint (&symfile_complaints,
9208                          _("Multiple CUs in DWO file %s [in module %s]"),
9209                          dwo_file->dwo_name, objfile_name (objfile));
9210               break;
9211             }
9212
9213           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9214           *dwo_unit = create_dwo_cu_data.dwo_unit;
9215         }
9216
9217       info_ptr += per_cu.length;
9218     }
9219
9220   return dwo_unit;
9221 }
9222
9223 /* DWP file .debug_{cu,tu}_index section format:
9224    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9225
9226    DWP Version 1:
9227
9228    Both index sections have the same format, and serve to map a 64-bit
9229    signature to a set of section numbers.  Each section begins with a header,
9230    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9231    indexes, and a pool of 32-bit section numbers.  The index sections will be
9232    aligned at 8-byte boundaries in the file.
9233
9234    The index section header consists of:
9235
9236     V, 32 bit version number
9237     -, 32 bits unused
9238     N, 32 bit number of compilation units or type units in the index
9239     M, 32 bit number of slots in the hash table
9240
9241    Numbers are recorded using the byte order of the application binary.
9242
9243    The hash table begins at offset 16 in the section, and consists of an array
9244    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9245    order of the application binary).  Unused slots in the hash table are 0.
9246    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9247
9248    The parallel table begins immediately after the hash table
9249    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9250    array of 32-bit indexes (using the byte order of the application binary),
9251    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9252    table contains a 32-bit index into the pool of section numbers.  For unused
9253    hash table slots, the corresponding entry in the parallel table will be 0.
9254
9255    The pool of section numbers begins immediately following the hash table
9256    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9257    section numbers consists of an array of 32-bit words (using the byte order
9258    of the application binary).  Each item in the array is indexed starting
9259    from 0.  The hash table entry provides the index of the first section
9260    number in the set.  Additional section numbers in the set follow, and the
9261    set is terminated by a 0 entry (section number 0 is not used in ELF).
9262
9263    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9264    section must be the first entry in the set, and the .debug_abbrev.dwo must
9265    be the second entry. Other members of the set may follow in any order.
9266
9267    ---
9268
9269    DWP Version 2:
9270
9271    DWP Version 2 combines all the .debug_info, etc. sections into one,
9272    and the entries in the index tables are now offsets into these sections.
9273    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9274    section.
9275
9276    Index Section Contents:
9277     Header
9278     Hash Table of Signatures   dwp_hash_table.hash_table
9279     Parallel Table of Indices  dwp_hash_table.unit_table
9280     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9281     Table of Section Sizes     dwp_hash_table.v2.sizes
9282
9283    The index section header consists of:
9284
9285     V, 32 bit version number
9286     L, 32 bit number of columns in the table of section offsets
9287     N, 32 bit number of compilation units or type units in the index
9288     M, 32 bit number of slots in the hash table
9289
9290    Numbers are recorded using the byte order of the application binary.
9291
9292    The hash table has the same format as version 1.
9293    The parallel table of indices has the same format as version 1,
9294    except that the entries are origin-1 indices into the table of sections
9295    offsets and the table of section sizes.
9296
9297    The table of offsets begins immediately following the parallel table
9298    (at offset 16 + 12 * M from the beginning of the section).  The table is
9299    a two-dimensional array of 32-bit words (using the byte order of the
9300    application binary), with L columns and N+1 rows, in row-major order.
9301    Each row in the array is indexed starting from 0.  The first row provides
9302    a key to the remaining rows: each column in this row provides an identifier
9303    for a debug section, and the offsets in the same column of subsequent rows
9304    refer to that section.  The section identifiers are:
9305
9306     DW_SECT_INFO         1  .debug_info.dwo
9307     DW_SECT_TYPES        2  .debug_types.dwo
9308     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9309     DW_SECT_LINE         4  .debug_line.dwo
9310     DW_SECT_LOC          5  .debug_loc.dwo
9311     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9312     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9313     DW_SECT_MACRO        8  .debug_macro.dwo
9314
9315    The offsets provided by the CU and TU index sections are the base offsets
9316    for the contributions made by each CU or TU to the corresponding section
9317    in the package file.  Each CU and TU header contains an abbrev_offset
9318    field, used to find the abbreviations table for that CU or TU within the
9319    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9320    be interpreted as relative to the base offset given in the index section.
9321    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9322    should be interpreted as relative to the base offset for .debug_line.dwo,
9323    and offsets into other debug sections obtained from DWARF attributes should
9324    also be interpreted as relative to the corresponding base offset.
9325
9326    The table of sizes begins immediately following the table of offsets.
9327    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9328    with L columns and N rows, in row-major order.  Each row in the array is
9329    indexed starting from 1 (row 0 is shared by the two tables).
9330
9331    ---
9332
9333    Hash table lookup is handled the same in version 1 and 2:
9334
9335    We assume that N and M will not exceed 2^32 - 1.
9336    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9337
9338    Given a 64-bit compilation unit signature or a type signature S, an entry
9339    in the hash table is located as follows:
9340
9341    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9342       the low-order k bits all set to 1.
9343
9344    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9345
9346    3) If the hash table entry at index H matches the signature, use that
9347       entry.  If the hash table entry at index H is unused (all zeroes),
9348       terminate the search: the signature is not present in the table.
9349
9350    4) Let H = (H + H') modulo M. Repeat at Step 3.
9351
9352    Because M > N and H' and M are relatively prime, the search is guaranteed
9353    to stop at an unused slot or find the match.  */
9354
9355 /* Create a hash table to map DWO IDs to their CU/TU entry in
9356    .debug_{info,types}.dwo in DWP_FILE.
9357    Returns NULL if there isn't one.
9358    Note: This function processes DWP files only, not DWO files.  */
9359
9360 static struct dwp_hash_table *
9361 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9362 {
9363   struct objfile *objfile = dwarf2_per_objfile->objfile;
9364   bfd *dbfd = dwp_file->dbfd;
9365   const gdb_byte *index_ptr, *index_end;
9366   struct dwarf2_section_info *index;
9367   uint32_t version, nr_columns, nr_units, nr_slots;
9368   struct dwp_hash_table *htab;
9369
9370   if (is_debug_types)
9371     index = &dwp_file->sections.tu_index;
9372   else
9373     index = &dwp_file->sections.cu_index;
9374
9375   if (dwarf2_section_empty_p (index))
9376     return NULL;
9377   dwarf2_read_section (objfile, index);
9378
9379   index_ptr = index->buffer;
9380   index_end = index_ptr + index->size;
9381
9382   version = read_4_bytes (dbfd, index_ptr);
9383   index_ptr += 4;
9384   if (version == 2)
9385     nr_columns = read_4_bytes (dbfd, index_ptr);
9386   else
9387     nr_columns = 0;
9388   index_ptr += 4;
9389   nr_units = read_4_bytes (dbfd, index_ptr);
9390   index_ptr += 4;
9391   nr_slots = read_4_bytes (dbfd, index_ptr);
9392   index_ptr += 4;
9393
9394   if (version != 1 && version != 2)
9395     {
9396       error (_("Dwarf Error: unsupported DWP file version (%s)"
9397                " [in module %s]"),
9398              pulongest (version), dwp_file->name);
9399     }
9400   if (nr_slots != (nr_slots & -nr_slots))
9401     {
9402       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9403                " is not power of 2 [in module %s]"),
9404              pulongest (nr_slots), dwp_file->name);
9405     }
9406
9407   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9408   htab->version = version;
9409   htab->nr_columns = nr_columns;
9410   htab->nr_units = nr_units;
9411   htab->nr_slots = nr_slots;
9412   htab->hash_table = index_ptr;
9413   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9414
9415   /* Exit early if the table is empty.  */
9416   if (nr_slots == 0 || nr_units == 0
9417       || (version == 2 && nr_columns == 0))
9418     {
9419       /* All must be zero.  */
9420       if (nr_slots != 0 || nr_units != 0
9421           || (version == 2 && nr_columns != 0))
9422         {
9423           complaint (&symfile_complaints,
9424                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
9425                        " all zero [in modules %s]"),
9426                      dwp_file->name);
9427         }
9428       return htab;
9429     }
9430
9431   if (version == 1)
9432     {
9433       htab->section_pool.v1.indices =
9434         htab->unit_table + sizeof (uint32_t) * nr_slots;
9435       /* It's harder to decide whether the section is too small in v1.
9436          V1 is deprecated anyway so we punt.  */
9437     }
9438   else
9439     {
9440       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
9441       int *ids = htab->section_pool.v2.section_ids;
9442       /* Reverse map for error checking.  */
9443       int ids_seen[DW_SECT_MAX + 1];
9444       int i;
9445
9446       if (nr_columns < 2)
9447         {
9448           error (_("Dwarf Error: bad DWP hash table, too few columns"
9449                    " in section table [in module %s]"),
9450                  dwp_file->name);
9451         }
9452       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
9453         {
9454           error (_("Dwarf Error: bad DWP hash table, too many columns"
9455                    " in section table [in module %s]"),
9456                  dwp_file->name);
9457         }
9458       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9459       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9460       for (i = 0; i < nr_columns; ++i)
9461         {
9462           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
9463
9464           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
9465             {
9466               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
9467                        " in section table [in module %s]"),
9468                      id, dwp_file->name);
9469             }
9470           if (ids_seen[id] != -1)
9471             {
9472               error (_("Dwarf Error: bad DWP hash table, duplicate section"
9473                        " id %d in section table [in module %s]"),
9474                      id, dwp_file->name);
9475             }
9476           ids_seen[id] = i;
9477           ids[i] = id;
9478         }
9479       /* Must have exactly one info or types section.  */
9480       if (((ids_seen[DW_SECT_INFO] != -1)
9481            + (ids_seen[DW_SECT_TYPES] != -1))
9482           != 1)
9483         {
9484           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
9485                    " DWO info/types section [in module %s]"),
9486                  dwp_file->name);
9487         }
9488       /* Must have an abbrev section.  */
9489       if (ids_seen[DW_SECT_ABBREV] == -1)
9490         {
9491           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
9492                    " section [in module %s]"),
9493                  dwp_file->name);
9494         }
9495       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
9496       htab->section_pool.v2.sizes =
9497         htab->section_pool.v2.offsets + (sizeof (uint32_t)
9498                                          * nr_units * nr_columns);
9499       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
9500                                           * nr_units * nr_columns))
9501           > index_end)
9502         {
9503           error (_("Dwarf Error: DWP index section is corrupt (too small)"
9504                    " [in module %s]"),
9505                  dwp_file->name);
9506         }
9507     }
9508
9509   return htab;
9510 }
9511
9512 /* Update SECTIONS with the data from SECTP.
9513
9514    This function is like the other "locate" section routines that are
9515    passed to bfd_map_over_sections, but in this context the sections to
9516    read comes from the DWP V1 hash table, not the full ELF section table.
9517
9518    The result is non-zero for success, or zero if an error was found.  */
9519
9520 static int
9521 locate_v1_virtual_dwo_sections (asection *sectp,
9522                                 struct virtual_v1_dwo_sections *sections)
9523 {
9524   const struct dwop_section_names *names = &dwop_section_names;
9525
9526   if (section_is_p (sectp->name, &names->abbrev_dwo))
9527     {
9528       /* There can be only one.  */
9529       if (sections->abbrev.s.asection != NULL)
9530         return 0;
9531       sections->abbrev.s.asection = sectp;
9532       sections->abbrev.size = bfd_get_section_size (sectp);
9533     }
9534   else if (section_is_p (sectp->name, &names->info_dwo)
9535            || section_is_p (sectp->name, &names->types_dwo))
9536     {
9537       /* There can be only one.  */
9538       if (sections->info_or_types.s.asection != NULL)
9539         return 0;
9540       sections->info_or_types.s.asection = sectp;
9541       sections->info_or_types.size = bfd_get_section_size (sectp);
9542     }
9543   else if (section_is_p (sectp->name, &names->line_dwo))
9544     {
9545       /* There can be only one.  */
9546       if (sections->line.s.asection != NULL)
9547         return 0;
9548       sections->line.s.asection = sectp;
9549       sections->line.size = bfd_get_section_size (sectp);
9550     }
9551   else if (section_is_p (sectp->name, &names->loc_dwo))
9552     {
9553       /* There can be only one.  */
9554       if (sections->loc.s.asection != NULL)
9555         return 0;
9556       sections->loc.s.asection = sectp;
9557       sections->loc.size = bfd_get_section_size (sectp);
9558     }
9559   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9560     {
9561       /* There can be only one.  */
9562       if (sections->macinfo.s.asection != NULL)
9563         return 0;
9564       sections->macinfo.s.asection = sectp;
9565       sections->macinfo.size = bfd_get_section_size (sectp);
9566     }
9567   else if (section_is_p (sectp->name, &names->macro_dwo))
9568     {
9569       /* There can be only one.  */
9570       if (sections->macro.s.asection != NULL)
9571         return 0;
9572       sections->macro.s.asection = sectp;
9573       sections->macro.size = bfd_get_section_size (sectp);
9574     }
9575   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9576     {
9577       /* There can be only one.  */
9578       if (sections->str_offsets.s.asection != NULL)
9579         return 0;
9580       sections->str_offsets.s.asection = sectp;
9581       sections->str_offsets.size = bfd_get_section_size (sectp);
9582     }
9583   else
9584     {
9585       /* No other kind of section is valid.  */
9586       return 0;
9587     }
9588
9589   return 1;
9590 }
9591
9592 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9593    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9594    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9595    This is for DWP version 1 files.  */
9596
9597 static struct dwo_unit *
9598 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
9599                            uint32_t unit_index,
9600                            const char *comp_dir,
9601                            ULONGEST signature, int is_debug_types)
9602 {
9603   struct objfile *objfile = dwarf2_per_objfile->objfile;
9604   const struct dwp_hash_table *dwp_htab =
9605     is_debug_types ? dwp_file->tus : dwp_file->cus;
9606   bfd *dbfd = dwp_file->dbfd;
9607   const char *kind = is_debug_types ? "TU" : "CU";
9608   struct dwo_file *dwo_file;
9609   struct dwo_unit *dwo_unit;
9610   struct virtual_v1_dwo_sections sections;
9611   void **dwo_file_slot;
9612   char *virtual_dwo_name;
9613   struct dwarf2_section_info *cutu;
9614   struct cleanup *cleanups;
9615   int i;
9616
9617   gdb_assert (dwp_file->version == 1);
9618
9619   if (dwarf2_read_debug)
9620     {
9621       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
9622                           kind,
9623                           pulongest (unit_index), hex_string (signature),
9624                           dwp_file->name);
9625     }
9626
9627   /* Fetch the sections of this DWO unit.
9628      Put a limit on the number of sections we look for so that bad data
9629      doesn't cause us to loop forever.  */
9630
9631 #define MAX_NR_V1_DWO_SECTIONS \
9632   (1 /* .debug_info or .debug_types */ \
9633    + 1 /* .debug_abbrev */ \
9634    + 1 /* .debug_line */ \
9635    + 1 /* .debug_loc */ \
9636    + 1 /* .debug_str_offsets */ \
9637    + 1 /* .debug_macro or .debug_macinfo */ \
9638    + 1 /* trailing zero */)
9639
9640   memset (&sections, 0, sizeof (sections));
9641   cleanups = make_cleanup (null_cleanup, 0);
9642
9643   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
9644     {
9645       asection *sectp;
9646       uint32_t section_nr =
9647         read_4_bytes (dbfd,
9648                       dwp_htab->section_pool.v1.indices
9649                       + (unit_index + i) * sizeof (uint32_t));
9650
9651       if (section_nr == 0)
9652         break;
9653       if (section_nr >= dwp_file->num_sections)
9654         {
9655           error (_("Dwarf Error: bad DWP hash table, section number too large"
9656                    " [in module %s]"),
9657                  dwp_file->name);
9658         }
9659
9660       sectp = dwp_file->elf_sections[section_nr];
9661       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
9662         {
9663           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9664                    " [in module %s]"),
9665                  dwp_file->name);
9666         }
9667     }
9668
9669   if (i < 2
9670       || dwarf2_section_empty_p (&sections.info_or_types)
9671       || dwarf2_section_empty_p (&sections.abbrev))
9672     {
9673       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9674                " [in module %s]"),
9675              dwp_file->name);
9676     }
9677   if (i == MAX_NR_V1_DWO_SECTIONS)
9678     {
9679       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9680                " [in module %s]"),
9681              dwp_file->name);
9682     }
9683
9684   /* It's easier for the rest of the code if we fake a struct dwo_file and
9685      have dwo_unit "live" in that.  At least for now.
9686
9687      The DWP file can be made up of a random collection of CUs and TUs.
9688      However, for each CU + set of TUs that came from the same original DWO
9689      file, we can combine them back into a virtual DWO file to save space
9690      (fewer struct dwo_file objects to allocate).  Remember that for really
9691      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9692
9693   virtual_dwo_name =
9694     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9695                 get_section_id (&sections.abbrev),
9696                 get_section_id (&sections.line),
9697                 get_section_id (&sections.loc),
9698                 get_section_id (&sections.str_offsets));
9699   make_cleanup (xfree, virtual_dwo_name);
9700   /* Can we use an existing virtual DWO file?  */
9701   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9702   /* Create one if necessary.  */
9703   if (*dwo_file_slot == NULL)
9704     {
9705       if (dwarf2_read_debug)
9706         {
9707           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9708                               virtual_dwo_name);
9709         }
9710       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9711       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9712                                           virtual_dwo_name,
9713                                           strlen (virtual_dwo_name));
9714       dwo_file->comp_dir = comp_dir;
9715       dwo_file->sections.abbrev = sections.abbrev;
9716       dwo_file->sections.line = sections.line;
9717       dwo_file->sections.loc = sections.loc;
9718       dwo_file->sections.macinfo = sections.macinfo;
9719       dwo_file->sections.macro = sections.macro;
9720       dwo_file->sections.str_offsets = sections.str_offsets;
9721       /* The "str" section is global to the entire DWP file.  */
9722       dwo_file->sections.str = dwp_file->sections.str;
9723       /* The info or types section is assigned below to dwo_unit,
9724          there's no need to record it in dwo_file.
9725          Also, we can't simply record type sections in dwo_file because
9726          we record a pointer into the vector in dwo_unit.  As we collect more
9727          types we'll grow the vector and eventually have to reallocate space
9728          for it, invalidating all copies of pointers into the previous
9729          contents.  */
9730       *dwo_file_slot = dwo_file;
9731     }
9732   else
9733     {
9734       if (dwarf2_read_debug)
9735         {
9736           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9737                               virtual_dwo_name);
9738         }
9739       dwo_file = *dwo_file_slot;
9740     }
9741   do_cleanups (cleanups);
9742
9743   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9744   dwo_unit->dwo_file = dwo_file;
9745   dwo_unit->signature = signature;
9746   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9747                                      sizeof (struct dwarf2_section_info));
9748   *dwo_unit->section = sections.info_or_types;
9749   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9750
9751   return dwo_unit;
9752 }
9753
9754 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
9755    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
9756    piece within that section used by a TU/CU, return a virtual section
9757    of just that piece.  */
9758
9759 static struct dwarf2_section_info
9760 create_dwp_v2_section (struct dwarf2_section_info *section,
9761                        bfd_size_type offset, bfd_size_type size)
9762 {
9763   struct dwarf2_section_info result;
9764   asection *sectp;
9765
9766   gdb_assert (section != NULL);
9767   gdb_assert (!section->is_virtual);
9768
9769   memset (&result, 0, sizeof (result));
9770   result.s.containing_section = section;
9771   result.is_virtual = 1;
9772
9773   if (size == 0)
9774     return result;
9775
9776   sectp = get_section_bfd_section (section);
9777
9778   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
9779      bounds of the real section.  This is a pretty-rare event, so just
9780      flag an error (easier) instead of a warning and trying to cope.  */
9781   if (sectp == NULL
9782       || offset + size > bfd_get_section_size (sectp))
9783     {
9784       bfd *abfd = sectp->owner;
9785
9786       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
9787                " in section %s [in module %s]"),
9788              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
9789              objfile_name (dwarf2_per_objfile->objfile));
9790     }
9791
9792   result.virtual_offset = offset;
9793   result.size = size;
9794   return result;
9795 }
9796
9797 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9798    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9799    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9800    This is for DWP version 2 files.  */
9801
9802 static struct dwo_unit *
9803 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
9804                            uint32_t unit_index,
9805                            const char *comp_dir,
9806                            ULONGEST signature, int is_debug_types)
9807 {
9808   struct objfile *objfile = dwarf2_per_objfile->objfile;
9809   const struct dwp_hash_table *dwp_htab =
9810     is_debug_types ? dwp_file->tus : dwp_file->cus;
9811   bfd *dbfd = dwp_file->dbfd;
9812   const char *kind = is_debug_types ? "TU" : "CU";
9813   struct dwo_file *dwo_file;
9814   struct dwo_unit *dwo_unit;
9815   struct virtual_v2_dwo_sections sections;
9816   void **dwo_file_slot;
9817   char *virtual_dwo_name;
9818   struct dwarf2_section_info *cutu;
9819   struct cleanup *cleanups;
9820   int i;
9821
9822   gdb_assert (dwp_file->version == 2);
9823
9824   if (dwarf2_read_debug)
9825     {
9826       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
9827                           kind,
9828                           pulongest (unit_index), hex_string (signature),
9829                           dwp_file->name);
9830     }
9831
9832   /* Fetch the section offsets of this DWO unit.  */
9833
9834   memset (&sections, 0, sizeof (sections));
9835   cleanups = make_cleanup (null_cleanup, 0);
9836
9837   for (i = 0; i < dwp_htab->nr_columns; ++i)
9838     {
9839       uint32_t offset = read_4_bytes (dbfd,
9840                                       dwp_htab->section_pool.v2.offsets
9841                                       + (((unit_index - 1) * dwp_htab->nr_columns
9842                                           + i)
9843                                          * sizeof (uint32_t)));
9844       uint32_t size = read_4_bytes (dbfd,
9845                                     dwp_htab->section_pool.v2.sizes
9846                                     + (((unit_index - 1) * dwp_htab->nr_columns
9847                                         + i)
9848                                        * sizeof (uint32_t)));
9849
9850       switch (dwp_htab->section_pool.v2.section_ids[i])
9851         {
9852         case DW_SECT_INFO:
9853         case DW_SECT_TYPES:
9854           sections.info_or_types_offset = offset;
9855           sections.info_or_types_size = size;
9856           break;
9857         case DW_SECT_ABBREV:
9858           sections.abbrev_offset = offset;
9859           sections.abbrev_size = size;
9860           break;
9861         case DW_SECT_LINE:
9862           sections.line_offset = offset;
9863           sections.line_size = size;
9864           break;
9865         case DW_SECT_LOC:
9866           sections.loc_offset = offset;
9867           sections.loc_size = size;
9868           break;
9869         case DW_SECT_STR_OFFSETS:
9870           sections.str_offsets_offset = offset;
9871           sections.str_offsets_size = size;
9872           break;
9873         case DW_SECT_MACINFO:
9874           sections.macinfo_offset = offset;
9875           sections.macinfo_size = size;
9876           break;
9877         case DW_SECT_MACRO:
9878           sections.macro_offset = offset;
9879           sections.macro_size = size;
9880           break;
9881         }
9882     }
9883
9884   /* It's easier for the rest of the code if we fake a struct dwo_file and
9885      have dwo_unit "live" in that.  At least for now.
9886
9887      The DWP file can be made up of a random collection of CUs and TUs.
9888      However, for each CU + set of TUs that came from the same original DWO
9889      file, we can combine them back into a virtual DWO file to save space
9890      (fewer struct dwo_file objects to allocate).  Remember that for really
9891      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9892
9893   virtual_dwo_name =
9894     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
9895                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
9896                 (long) (sections.line_size ? sections.line_offset : 0),
9897                 (long) (sections.loc_size ? sections.loc_offset : 0),
9898                 (long) (sections.str_offsets_size
9899                         ? sections.str_offsets_offset : 0));
9900   make_cleanup (xfree, virtual_dwo_name);
9901   /* Can we use an existing virtual DWO file?  */
9902   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9903   /* Create one if necessary.  */
9904   if (*dwo_file_slot == NULL)
9905     {
9906       if (dwarf2_read_debug)
9907         {
9908           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9909                               virtual_dwo_name);
9910         }
9911       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9912       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9913                                           virtual_dwo_name,
9914                                           strlen (virtual_dwo_name));
9915       dwo_file->comp_dir = comp_dir;
9916       dwo_file->sections.abbrev =
9917         create_dwp_v2_section (&dwp_file->sections.abbrev,
9918                                sections.abbrev_offset, sections.abbrev_size);
9919       dwo_file->sections.line =
9920         create_dwp_v2_section (&dwp_file->sections.line,
9921                                sections.line_offset, sections.line_size);
9922       dwo_file->sections.loc =
9923         create_dwp_v2_section (&dwp_file->sections.loc,
9924                                sections.loc_offset, sections.loc_size);
9925       dwo_file->sections.macinfo =
9926         create_dwp_v2_section (&dwp_file->sections.macinfo,
9927                                sections.macinfo_offset, sections.macinfo_size);
9928       dwo_file->sections.macro =
9929         create_dwp_v2_section (&dwp_file->sections.macro,
9930                                sections.macro_offset, sections.macro_size);
9931       dwo_file->sections.str_offsets =
9932         create_dwp_v2_section (&dwp_file->sections.str_offsets,
9933                                sections.str_offsets_offset,
9934                                sections.str_offsets_size);
9935       /* The "str" section is global to the entire DWP file.  */
9936       dwo_file->sections.str = dwp_file->sections.str;
9937       /* The info or types section is assigned below to dwo_unit,
9938          there's no need to record it in dwo_file.
9939          Also, we can't simply record type sections in dwo_file because
9940          we record a pointer into the vector in dwo_unit.  As we collect more
9941          types we'll grow the vector and eventually have to reallocate space
9942          for it, invalidating all copies of pointers into the previous
9943          contents.  */
9944       *dwo_file_slot = dwo_file;
9945     }
9946   else
9947     {
9948       if (dwarf2_read_debug)
9949         {
9950           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9951                               virtual_dwo_name);
9952         }
9953       dwo_file = *dwo_file_slot;
9954     }
9955   do_cleanups (cleanups);
9956
9957   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9958   dwo_unit->dwo_file = dwo_file;
9959   dwo_unit->signature = signature;
9960   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9961                                      sizeof (struct dwarf2_section_info));
9962   *dwo_unit->section = create_dwp_v2_section (is_debug_types
9963                                               ? &dwp_file->sections.types
9964                                               : &dwp_file->sections.info,
9965                                               sections.info_or_types_offset,
9966                                               sections.info_or_types_size);
9967   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9968
9969   return dwo_unit;
9970 }
9971
9972 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
9973    Returns NULL if the signature isn't found.  */
9974
9975 static struct dwo_unit *
9976 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
9977                         ULONGEST signature, int is_debug_types)
9978 {
9979   const struct dwp_hash_table *dwp_htab =
9980     is_debug_types ? dwp_file->tus : dwp_file->cus;
9981   bfd *dbfd = dwp_file->dbfd;
9982   uint32_t mask = dwp_htab->nr_slots - 1;
9983   uint32_t hash = signature & mask;
9984   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9985   unsigned int i;
9986   void **slot;
9987   struct dwo_unit find_dwo_cu, *dwo_cu;
9988
9989   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9990   find_dwo_cu.signature = signature;
9991   slot = htab_find_slot (is_debug_types
9992                          ? dwp_file->loaded_tus
9993                          : dwp_file->loaded_cus,
9994                          &find_dwo_cu, INSERT);
9995
9996   if (*slot != NULL)
9997     return *slot;
9998
9999   /* Use a for loop so that we don't loop forever on bad debug info.  */
10000   for (i = 0; i < dwp_htab->nr_slots; ++i)
10001     {
10002       ULONGEST signature_in_table;
10003
10004       signature_in_table =
10005         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10006       if (signature_in_table == signature)
10007         {
10008           uint32_t unit_index =
10009             read_4_bytes (dbfd,
10010                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10011
10012           if (dwp_file->version == 1)
10013             {
10014               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10015                                                  comp_dir, signature,
10016                                                  is_debug_types);
10017             }
10018           else
10019             {
10020               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10021                                                  comp_dir, signature,
10022                                                  is_debug_types);
10023             }
10024           return *slot;
10025         }
10026       if (signature_in_table == 0)
10027         return NULL;
10028       hash = (hash + hash2) & mask;
10029     }
10030
10031   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10032            " [in module %s]"),
10033          dwp_file->name);
10034 }
10035
10036 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10037    Open the file specified by FILE_NAME and hand it off to BFD for
10038    preliminary analysis.  Return a newly initialized bfd *, which
10039    includes a canonicalized copy of FILE_NAME.
10040    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10041    SEARCH_CWD is true if the current directory is to be searched.
10042    It will be searched before debug-file-directory.
10043    If unable to find/open the file, return NULL.
10044    NOTE: This function is derived from symfile_bfd_open.  */
10045
10046 static bfd *
10047 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10048 {
10049   bfd *sym_bfd;
10050   int desc, flags;
10051   char *absolute_name;
10052   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10053      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10054      to debug_file_directory.  */
10055   char *search_path;
10056   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10057
10058   if (search_cwd)
10059     {
10060       if (*debug_file_directory != '\0')
10061         search_path = concat (".", dirname_separator_string,
10062                               debug_file_directory, NULL);
10063       else
10064         search_path = xstrdup (".");
10065     }
10066   else
10067     search_path = xstrdup (debug_file_directory);
10068
10069   flags = OPF_RETURN_REALPATH;
10070   if (is_dwp)
10071     flags |= OPF_SEARCH_IN_PATH;
10072   desc = openp (search_path, flags, file_name,
10073                 O_RDONLY | O_BINARY, &absolute_name);
10074   xfree (search_path);
10075   if (desc < 0)
10076     return NULL;
10077
10078   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
10079   xfree (absolute_name);
10080   if (sym_bfd == NULL)
10081     return NULL;
10082   bfd_set_cacheable (sym_bfd, 1);
10083
10084   if (!bfd_check_format (sym_bfd, bfd_object))
10085     {
10086       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
10087       return NULL;
10088     }
10089
10090   return sym_bfd;
10091 }
10092
10093 /* Try to open DWO file FILE_NAME.
10094    COMP_DIR is the DW_AT_comp_dir attribute.
10095    The result is the bfd handle of the file.
10096    If there is a problem finding or opening the file, return NULL.
10097    Upon success, the canonicalized path of the file is stored in the bfd,
10098    same as symfile_bfd_open.  */
10099
10100 static bfd *
10101 open_dwo_file (const char *file_name, const char *comp_dir)
10102 {
10103   bfd *abfd;
10104
10105   if (IS_ABSOLUTE_PATH (file_name))
10106     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10107
10108   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10109
10110   if (comp_dir != NULL)
10111     {
10112       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
10113
10114       /* NOTE: If comp_dir is a relative path, this will also try the
10115          search path, which seems useful.  */
10116       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
10117       xfree (path_to_try);
10118       if (abfd != NULL)
10119         return abfd;
10120     }
10121
10122   /* That didn't work, try debug-file-directory, which, despite its name,
10123      is a list of paths.  */
10124
10125   if (*debug_file_directory == '\0')
10126     return NULL;
10127
10128   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10129 }
10130
10131 /* This function is mapped across the sections and remembers the offset and
10132    size of each of the DWO debugging sections we are interested in.  */
10133
10134 static void
10135 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10136 {
10137   struct dwo_sections *dwo_sections = dwo_sections_ptr;
10138   const struct dwop_section_names *names = &dwop_section_names;
10139
10140   if (section_is_p (sectp->name, &names->abbrev_dwo))
10141     {
10142       dwo_sections->abbrev.s.asection = sectp;
10143       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10144     }
10145   else if (section_is_p (sectp->name, &names->info_dwo))
10146     {
10147       dwo_sections->info.s.asection = sectp;
10148       dwo_sections->info.size = bfd_get_section_size (sectp);
10149     }
10150   else if (section_is_p (sectp->name, &names->line_dwo))
10151     {
10152       dwo_sections->line.s.asection = sectp;
10153       dwo_sections->line.size = bfd_get_section_size (sectp);
10154     }
10155   else if (section_is_p (sectp->name, &names->loc_dwo))
10156     {
10157       dwo_sections->loc.s.asection = sectp;
10158       dwo_sections->loc.size = bfd_get_section_size (sectp);
10159     }
10160   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10161     {
10162       dwo_sections->macinfo.s.asection = sectp;
10163       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10164     }
10165   else if (section_is_p (sectp->name, &names->macro_dwo))
10166     {
10167       dwo_sections->macro.s.asection = sectp;
10168       dwo_sections->macro.size = bfd_get_section_size (sectp);
10169     }
10170   else if (section_is_p (sectp->name, &names->str_dwo))
10171     {
10172       dwo_sections->str.s.asection = sectp;
10173       dwo_sections->str.size = bfd_get_section_size (sectp);
10174     }
10175   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10176     {
10177       dwo_sections->str_offsets.s.asection = sectp;
10178       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10179     }
10180   else if (section_is_p (sectp->name, &names->types_dwo))
10181     {
10182       struct dwarf2_section_info type_section;
10183
10184       memset (&type_section, 0, sizeof (type_section));
10185       type_section.s.asection = sectp;
10186       type_section.size = bfd_get_section_size (sectp);
10187       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10188                      &type_section);
10189     }
10190 }
10191
10192 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10193    by PER_CU.  This is for the non-DWP case.
10194    The result is NULL if DWO_NAME can't be found.  */
10195
10196 static struct dwo_file *
10197 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10198                         const char *dwo_name, const char *comp_dir)
10199 {
10200   struct objfile *objfile = dwarf2_per_objfile->objfile;
10201   struct dwo_file *dwo_file;
10202   bfd *dbfd;
10203   struct cleanup *cleanups;
10204
10205   dbfd = open_dwo_file (dwo_name, comp_dir);
10206   if (dbfd == NULL)
10207     {
10208       if (dwarf2_read_debug)
10209         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10210       return NULL;
10211     }
10212   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10213   dwo_file->dwo_name = dwo_name;
10214   dwo_file->comp_dir = comp_dir;
10215   dwo_file->dbfd = dbfd;
10216
10217   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10218
10219   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
10220
10221   dwo_file->cu = create_dwo_cu (dwo_file);
10222
10223   dwo_file->tus = create_debug_types_hash_table (dwo_file,
10224                                                  dwo_file->sections.types);
10225
10226   discard_cleanups (cleanups);
10227
10228   if (dwarf2_read_debug)
10229     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10230
10231   return dwo_file;
10232 }
10233
10234 /* This function is mapped across the sections and remembers the offset and
10235    size of each of the DWP debugging sections common to version 1 and 2 that
10236    we are interested in.  */
10237
10238 static void
10239 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10240                                    void *dwp_file_ptr)
10241 {
10242   struct dwp_file *dwp_file = dwp_file_ptr;
10243   const struct dwop_section_names *names = &dwop_section_names;
10244   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10245
10246   /* Record the ELF section number for later lookup: this is what the
10247      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10248   gdb_assert (elf_section_nr < dwp_file->num_sections);
10249   dwp_file->elf_sections[elf_section_nr] = sectp;
10250
10251   /* Look for specific sections that we need.  */
10252   if (section_is_p (sectp->name, &names->str_dwo))
10253     {
10254       dwp_file->sections.str.s.asection = sectp;
10255       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10256     }
10257   else if (section_is_p (sectp->name, &names->cu_index))
10258     {
10259       dwp_file->sections.cu_index.s.asection = sectp;
10260       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10261     }
10262   else if (section_is_p (sectp->name, &names->tu_index))
10263     {
10264       dwp_file->sections.tu_index.s.asection = sectp;
10265       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10266     }
10267 }
10268
10269 /* This function is mapped across the sections and remembers the offset and
10270    size of each of the DWP version 2 debugging sections that we are interested
10271    in.  This is split into a separate function because we don't know if we
10272    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10273
10274 static void
10275 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10276 {
10277   struct dwp_file *dwp_file = dwp_file_ptr;
10278   const struct dwop_section_names *names = &dwop_section_names;
10279   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10280
10281   /* Record the ELF section number for later lookup: this is what the
10282      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10283   gdb_assert (elf_section_nr < dwp_file->num_sections);
10284   dwp_file->elf_sections[elf_section_nr] = sectp;
10285
10286   /* Look for specific sections that we need.  */
10287   if (section_is_p (sectp->name, &names->abbrev_dwo))
10288     {
10289       dwp_file->sections.abbrev.s.asection = sectp;
10290       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10291     }
10292   else if (section_is_p (sectp->name, &names->info_dwo))
10293     {
10294       dwp_file->sections.info.s.asection = sectp;
10295       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10296     }
10297   else if (section_is_p (sectp->name, &names->line_dwo))
10298     {
10299       dwp_file->sections.line.s.asection = sectp;
10300       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10301     }
10302   else if (section_is_p (sectp->name, &names->loc_dwo))
10303     {
10304       dwp_file->sections.loc.s.asection = sectp;
10305       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10306     }
10307   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10308     {
10309       dwp_file->sections.macinfo.s.asection = sectp;
10310       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10311     }
10312   else if (section_is_p (sectp->name, &names->macro_dwo))
10313     {
10314       dwp_file->sections.macro.s.asection = sectp;
10315       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10316     }
10317   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10318     {
10319       dwp_file->sections.str_offsets.s.asection = sectp;
10320       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10321     }
10322   else if (section_is_p (sectp->name, &names->types_dwo))
10323     {
10324       dwp_file->sections.types.s.asection = sectp;
10325       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10326     }
10327 }
10328
10329 /* Hash function for dwp_file loaded CUs/TUs.  */
10330
10331 static hashval_t
10332 hash_dwp_loaded_cutus (const void *item)
10333 {
10334   const struct dwo_unit *dwo_unit = item;
10335
10336   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10337   return dwo_unit->signature;
10338 }
10339
10340 /* Equality function for dwp_file loaded CUs/TUs.  */
10341
10342 static int
10343 eq_dwp_loaded_cutus (const void *a, const void *b)
10344 {
10345   const struct dwo_unit *dua = a;
10346   const struct dwo_unit *dub = b;
10347
10348   return dua->signature == dub->signature;
10349 }
10350
10351 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10352
10353 static htab_t
10354 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10355 {
10356   return htab_create_alloc_ex (3,
10357                                hash_dwp_loaded_cutus,
10358                                eq_dwp_loaded_cutus,
10359                                NULL,
10360                                &objfile->objfile_obstack,
10361                                hashtab_obstack_allocate,
10362                                dummy_obstack_deallocate);
10363 }
10364
10365 /* Try to open DWP file FILE_NAME.
10366    The result is the bfd handle of the file.
10367    If there is a problem finding or opening the file, return NULL.
10368    Upon success, the canonicalized path of the file is stored in the bfd,
10369    same as symfile_bfd_open.  */
10370
10371 static bfd *
10372 open_dwp_file (const char *file_name)
10373 {
10374   bfd *abfd;
10375
10376   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
10377   if (abfd != NULL)
10378     return abfd;
10379
10380   /* Work around upstream bug 15652.
10381      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10382      [Whether that's a "bug" is debatable, but it is getting in our way.]
10383      We have no real idea where the dwp file is, because gdb's realpath-ing
10384      of the executable's path may have discarded the needed info.
10385      [IWBN if the dwp file name was recorded in the executable, akin to
10386      .gnu_debuglink, but that doesn't exist yet.]
10387      Strip the directory from FILE_NAME and search again.  */
10388   if (*debug_file_directory != '\0')
10389     {
10390       /* Don't implicitly search the current directory here.
10391          If the user wants to search "." to handle this case,
10392          it must be added to debug-file-directory.  */
10393       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
10394                                  0 /*search_cwd*/);
10395     }
10396
10397   return NULL;
10398 }
10399
10400 /* Initialize the use of the DWP file for the current objfile.
10401    By convention the name of the DWP file is ${objfile}.dwp.
10402    The result is NULL if it can't be found.  */
10403
10404 static struct dwp_file *
10405 open_and_init_dwp_file (void)
10406 {
10407   struct objfile *objfile = dwarf2_per_objfile->objfile;
10408   struct dwp_file *dwp_file;
10409   char *dwp_name;
10410   bfd *dbfd;
10411   struct cleanup *cleanups;
10412
10413   /* Try to find first .dwp for the binary file before any symbolic links
10414      resolving.  */
10415   dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
10416   cleanups = make_cleanup (xfree, dwp_name);
10417
10418   dbfd = open_dwp_file (dwp_name);
10419   if (dbfd == NULL
10420       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
10421     {
10422       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
10423       dwp_name = xstrprintf ("%s.dwp", objfile_name (objfile));
10424       make_cleanup (xfree, dwp_name);
10425       dbfd = open_dwp_file (dwp_name);
10426     }
10427
10428   if (dbfd == NULL)
10429     {
10430       if (dwarf2_read_debug)
10431         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
10432       do_cleanups (cleanups);
10433       return NULL;
10434     }
10435   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
10436   dwp_file->name = bfd_get_filename (dbfd);
10437   dwp_file->dbfd = dbfd;
10438   do_cleanups (cleanups);
10439
10440   /* +1: section 0 is unused */
10441   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
10442   dwp_file->elf_sections =
10443     OBSTACK_CALLOC (&objfile->objfile_obstack,
10444                     dwp_file->num_sections, asection *);
10445
10446   bfd_map_over_sections (dbfd, dwarf2_locate_common_dwp_sections, dwp_file);
10447
10448   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
10449
10450   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
10451
10452   /* The DWP file version is stored in the hash table.  Oh well.  */
10453   if (dwp_file->cus->version != dwp_file->tus->version)
10454     {
10455       /* Technically speaking, we should try to limp along, but this is
10456          pretty bizarre.  */
10457       error (_("Dwarf Error: DWP file CU version %d doesn't match"
10458                " TU version %d [in DWP file %s]"),
10459              dwp_file->cus->version, dwp_file->tus->version, dwp_name);
10460     }
10461   dwp_file->version = dwp_file->cus->version;
10462
10463   if (dwp_file->version == 2)
10464     bfd_map_over_sections (dbfd, dwarf2_locate_v2_dwp_sections, dwp_file);
10465
10466   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
10467   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
10468
10469   if (dwarf2_read_debug)
10470     {
10471       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
10472       fprintf_unfiltered (gdb_stdlog,
10473                           "    %s CUs, %s TUs\n",
10474                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
10475                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
10476     }
10477
10478   return dwp_file;
10479 }
10480
10481 /* Wrapper around open_and_init_dwp_file, only open it once.  */
10482
10483 static struct dwp_file *
10484 get_dwp_file (void)
10485 {
10486   if (! dwarf2_per_objfile->dwp_checked)
10487     {
10488       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
10489       dwarf2_per_objfile->dwp_checked = 1;
10490     }
10491   return dwarf2_per_objfile->dwp_file;
10492 }
10493
10494 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
10495    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
10496    or in the DWP file for the objfile, referenced by THIS_UNIT.
10497    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
10498    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
10499
10500    This is called, for example, when wanting to read a variable with a
10501    complex location.  Therefore we don't want to do file i/o for every call.
10502    Therefore we don't want to look for a DWO file on every call.
10503    Therefore we first see if we've already seen SIGNATURE in a DWP file,
10504    then we check if we've already seen DWO_NAME, and only THEN do we check
10505    for a DWO file.
10506
10507    The result is a pointer to the dwo_unit object or NULL if we didn't find it
10508    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
10509
10510 static struct dwo_unit *
10511 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
10512                  const char *dwo_name, const char *comp_dir,
10513                  ULONGEST signature, int is_debug_types)
10514 {
10515   struct objfile *objfile = dwarf2_per_objfile->objfile;
10516   const char *kind = is_debug_types ? "TU" : "CU";
10517   void **dwo_file_slot;
10518   struct dwo_file *dwo_file;
10519   struct dwp_file *dwp_file;
10520
10521   /* First see if there's a DWP file.
10522      If we have a DWP file but didn't find the DWO inside it, don't
10523      look for the original DWO file.  It makes gdb behave differently
10524      depending on whether one is debugging in the build tree.  */
10525
10526   dwp_file = get_dwp_file ();
10527   if (dwp_file != NULL)
10528     {
10529       const struct dwp_hash_table *dwp_htab =
10530         is_debug_types ? dwp_file->tus : dwp_file->cus;
10531
10532       if (dwp_htab != NULL)
10533         {
10534           struct dwo_unit *dwo_cutu =
10535             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
10536                                     signature, is_debug_types);
10537
10538           if (dwo_cutu != NULL)
10539             {
10540               if (dwarf2_read_debug)
10541                 {
10542                   fprintf_unfiltered (gdb_stdlog,
10543                                       "Virtual DWO %s %s found: @%s\n",
10544                                       kind, hex_string (signature),
10545                                       host_address_to_string (dwo_cutu));
10546                 }
10547               return dwo_cutu;
10548             }
10549         }
10550     }
10551   else
10552     {
10553       /* No DWP file, look for the DWO file.  */
10554
10555       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
10556       if (*dwo_file_slot == NULL)
10557         {
10558           /* Read in the file and build a table of the CUs/TUs it contains.  */
10559           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
10560         }
10561       /* NOTE: This will be NULL if unable to open the file.  */
10562       dwo_file = *dwo_file_slot;
10563
10564       if (dwo_file != NULL)
10565         {
10566           struct dwo_unit *dwo_cutu = NULL;
10567
10568           if (is_debug_types && dwo_file->tus)
10569             {
10570               struct dwo_unit find_dwo_cutu;
10571
10572               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
10573               find_dwo_cutu.signature = signature;
10574               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
10575             }
10576           else if (!is_debug_types && dwo_file->cu)
10577             {
10578               if (signature == dwo_file->cu->signature)
10579                 dwo_cutu = dwo_file->cu;
10580             }
10581
10582           if (dwo_cutu != NULL)
10583             {
10584               if (dwarf2_read_debug)
10585                 {
10586                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
10587                                       kind, dwo_name, hex_string (signature),
10588                                       host_address_to_string (dwo_cutu));
10589                 }
10590               return dwo_cutu;
10591             }
10592         }
10593     }
10594
10595   /* We didn't find it.  This could mean a dwo_id mismatch, or
10596      someone deleted the DWO/DWP file, or the search path isn't set up
10597      correctly to find the file.  */
10598
10599   if (dwarf2_read_debug)
10600     {
10601       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
10602                           kind, dwo_name, hex_string (signature));
10603     }
10604
10605   /* This is a warning and not a complaint because it can be caused by
10606      pilot error (e.g., user accidentally deleting the DWO).  */
10607   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
10608              " [in module %s]"),
10609            kind, dwo_name, hex_string (signature),
10610            this_unit->is_debug_types ? "TU" : "CU",
10611            this_unit->offset.sect_off, objfile_name (objfile));
10612   return NULL;
10613 }
10614
10615 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
10616    See lookup_dwo_cutu_unit for details.  */
10617
10618 static struct dwo_unit *
10619 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
10620                       const char *dwo_name, const char *comp_dir,
10621                       ULONGEST signature)
10622 {
10623   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
10624 }
10625
10626 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
10627    See lookup_dwo_cutu_unit for details.  */
10628
10629 static struct dwo_unit *
10630 lookup_dwo_type_unit (struct signatured_type *this_tu,
10631                       const char *dwo_name, const char *comp_dir)
10632 {
10633   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
10634 }
10635
10636 /* Traversal function for queue_and_load_all_dwo_tus.  */
10637
10638 static int
10639 queue_and_load_dwo_tu (void **slot, void *info)
10640 {
10641   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
10642   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
10643   ULONGEST signature = dwo_unit->signature;
10644   struct signatured_type *sig_type =
10645     lookup_dwo_signatured_type (per_cu->cu, signature);
10646
10647   if (sig_type != NULL)
10648     {
10649       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
10650
10651       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
10652          a real dependency of PER_CU on SIG_TYPE.  That is detected later
10653          while processing PER_CU.  */
10654       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
10655         load_full_type_unit (sig_cu);
10656       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
10657     }
10658
10659   return 1;
10660 }
10661
10662 /* Queue all TUs contained in the DWO of PER_CU to be read in.
10663    The DWO may have the only definition of the type, though it may not be
10664    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
10665    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
10666
10667 static void
10668 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
10669 {
10670   struct dwo_unit *dwo_unit;
10671   struct dwo_file *dwo_file;
10672
10673   gdb_assert (!per_cu->is_debug_types);
10674   gdb_assert (get_dwp_file () == NULL);
10675   gdb_assert (per_cu->cu != NULL);
10676
10677   dwo_unit = per_cu->cu->dwo_unit;
10678   gdb_assert (dwo_unit != NULL);
10679
10680   dwo_file = dwo_unit->dwo_file;
10681   if (dwo_file->tus != NULL)
10682     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
10683 }
10684
10685 /* Free all resources associated with DWO_FILE.
10686    Close the DWO file and munmap the sections.
10687    All memory should be on the objfile obstack.  */
10688
10689 static void
10690 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
10691 {
10692   int ix;
10693   struct dwarf2_section_info *section;
10694
10695   /* Note: dbfd is NULL for virtual DWO files.  */
10696   gdb_bfd_unref (dwo_file->dbfd);
10697
10698   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
10699 }
10700
10701 /* Wrapper for free_dwo_file for use in cleanups.  */
10702
10703 static void
10704 free_dwo_file_cleanup (void *arg)
10705 {
10706   struct dwo_file *dwo_file = (struct dwo_file *) arg;
10707   struct objfile *objfile = dwarf2_per_objfile->objfile;
10708
10709   free_dwo_file (dwo_file, objfile);
10710 }
10711
10712 /* Traversal function for free_dwo_files.  */
10713
10714 static int
10715 free_dwo_file_from_slot (void **slot, void *info)
10716 {
10717   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
10718   struct objfile *objfile = (struct objfile *) info;
10719
10720   free_dwo_file (dwo_file, objfile);
10721
10722   return 1;
10723 }
10724
10725 /* Free all resources associated with DWO_FILES.  */
10726
10727 static void
10728 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
10729 {
10730   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
10731 }
10732 \f
10733 /* Read in various DIEs.  */
10734
10735 /* qsort helper for inherit_abstract_dies.  */
10736
10737 static int
10738 unsigned_int_compar (const void *ap, const void *bp)
10739 {
10740   unsigned int a = *(unsigned int *) ap;
10741   unsigned int b = *(unsigned int *) bp;
10742
10743   return (a > b) - (b > a);
10744 }
10745
10746 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
10747    Inherit only the children of the DW_AT_abstract_origin DIE not being
10748    already referenced by DW_AT_abstract_origin from the children of the
10749    current DIE.  */
10750
10751 static void
10752 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
10753 {
10754   struct die_info *child_die;
10755   unsigned die_children_count;
10756   /* CU offsets which were referenced by children of the current DIE.  */
10757   sect_offset *offsets;
10758   sect_offset *offsets_end, *offsetp;
10759   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
10760   struct die_info *origin_die;
10761   /* Iterator of the ORIGIN_DIE children.  */
10762   struct die_info *origin_child_die;
10763   struct cleanup *cleanups;
10764   struct attribute *attr;
10765   struct dwarf2_cu *origin_cu;
10766   struct pending **origin_previous_list_in_scope;
10767
10768   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10769   if (!attr)
10770     return;
10771
10772   /* Note that following die references may follow to a die in a
10773      different cu.  */
10774
10775   origin_cu = cu;
10776   origin_die = follow_die_ref (die, attr, &origin_cu);
10777
10778   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
10779      symbols in.  */
10780   origin_previous_list_in_scope = origin_cu->list_in_scope;
10781   origin_cu->list_in_scope = cu->list_in_scope;
10782
10783   if (die->tag != origin_die->tag
10784       && !(die->tag == DW_TAG_inlined_subroutine
10785            && origin_die->tag == DW_TAG_subprogram))
10786     complaint (&symfile_complaints,
10787                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
10788                die->offset.sect_off, origin_die->offset.sect_off);
10789
10790   child_die = die->child;
10791   die_children_count = 0;
10792   while (child_die && child_die->tag)
10793     {
10794       child_die = sibling_die (child_die);
10795       die_children_count++;
10796     }
10797   offsets = xmalloc (sizeof (*offsets) * die_children_count);
10798   cleanups = make_cleanup (xfree, offsets);
10799
10800   offsets_end = offsets;
10801   child_die = die->child;
10802   while (child_die && child_die->tag)
10803     {
10804       /* For each CHILD_DIE, find the corresponding child of
10805          ORIGIN_DIE.  If there is more than one layer of
10806          DW_AT_abstract_origin, follow them all; there shouldn't be,
10807          but GCC versions at least through 4.4 generate this (GCC PR
10808          40573).  */
10809       struct die_info *child_origin_die = child_die;
10810       struct dwarf2_cu *child_origin_cu = cu;
10811
10812       while (1)
10813         {
10814           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
10815                               child_origin_cu);
10816           if (attr == NULL)
10817             break;
10818           child_origin_die = follow_die_ref (child_origin_die, attr,
10819                                              &child_origin_cu);
10820         }
10821
10822       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10823          counterpart may exist.  */
10824       if (child_origin_die != child_die)
10825         {
10826           if (child_die->tag != child_origin_die->tag
10827               && !(child_die->tag == DW_TAG_inlined_subroutine
10828                    && child_origin_die->tag == DW_TAG_subprogram))
10829             complaint (&symfile_complaints,
10830                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10831                          "different tags"), child_die->offset.sect_off,
10832                        child_origin_die->offset.sect_off);
10833           if (child_origin_die->parent != origin_die)
10834             complaint (&symfile_complaints,
10835                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10836                          "different parents"), child_die->offset.sect_off,
10837                        child_origin_die->offset.sect_off);
10838           else
10839             *offsets_end++ = child_origin_die->offset;
10840         }
10841       child_die = sibling_die (child_die);
10842     }
10843   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10844          unsigned_int_compar);
10845   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10846     if (offsetp[-1].sect_off == offsetp->sect_off)
10847       complaint (&symfile_complaints,
10848                  _("Multiple children of DIE 0x%x refer "
10849                    "to DIE 0x%x as their abstract origin"),
10850                  die->offset.sect_off, offsetp->sect_off);
10851
10852   offsetp = offsets;
10853   origin_child_die = origin_die->child;
10854   while (origin_child_die && origin_child_die->tag)
10855     {
10856       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10857       while (offsetp < offsets_end
10858              && offsetp->sect_off < origin_child_die->offset.sect_off)
10859         offsetp++;
10860       if (offsetp >= offsets_end
10861           || offsetp->sect_off > origin_child_die->offset.sect_off)
10862         {
10863           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10864           process_die (origin_child_die, origin_cu);
10865         }
10866       origin_child_die = sibling_die (origin_child_die);
10867     }
10868   origin_cu->list_in_scope = origin_previous_list_in_scope;
10869
10870   do_cleanups (cleanups);
10871 }
10872
10873 static void
10874 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10875 {
10876   struct objfile *objfile = cu->objfile;
10877   struct context_stack *new;
10878   CORE_ADDR lowpc;
10879   CORE_ADDR highpc;
10880   struct die_info *child_die;
10881   struct attribute *attr, *call_line, *call_file;
10882   const char *name;
10883   CORE_ADDR baseaddr;
10884   struct block *block;
10885   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10886   VEC (symbolp) *template_args = NULL;
10887   struct template_symbol *templ_func = NULL;
10888
10889   if (inlined_func)
10890     {
10891       /* If we do not have call site information, we can't show the
10892          caller of this inlined function.  That's too confusing, so
10893          only use the scope for local variables.  */
10894       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10895       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10896       if (call_line == NULL || call_file == NULL)
10897         {
10898           read_lexical_block_scope (die, cu);
10899           return;
10900         }
10901     }
10902
10903   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10904
10905   name = dwarf2_name (die, cu);
10906
10907   /* Ignore functions with missing or empty names.  These are actually
10908      illegal according to the DWARF standard.  */
10909   if (name == NULL)
10910     {
10911       complaint (&symfile_complaints,
10912                  _("missing name for subprogram DIE at %d"),
10913                  die->offset.sect_off);
10914       return;
10915     }
10916
10917   /* Ignore functions with missing or invalid low and high pc attributes.  */
10918   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10919     {
10920       attr = dwarf2_attr (die, DW_AT_external, cu);
10921       if (!attr || !DW_UNSND (attr))
10922         complaint (&symfile_complaints,
10923                    _("cannot get low and high bounds "
10924                      "for subprogram DIE at %d"),
10925                    die->offset.sect_off);
10926       return;
10927     }
10928
10929   lowpc += baseaddr;
10930   highpc += baseaddr;
10931
10932   /* If we have any template arguments, then we must allocate a
10933      different sort of symbol.  */
10934   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10935     {
10936       if (child_die->tag == DW_TAG_template_type_param
10937           || child_die->tag == DW_TAG_template_value_param)
10938         {
10939           templ_func = allocate_template_symbol (objfile);
10940           templ_func->base.is_cplus_template_function = 1;
10941           break;
10942         }
10943     }
10944
10945   new = push_context (0, lowpc);
10946   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10947                                (struct symbol *) templ_func);
10948
10949   /* If there is a location expression for DW_AT_frame_base, record
10950      it.  */
10951   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10952   if (attr)
10953     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10954
10955   cu->list_in_scope = &local_symbols;
10956
10957   if (die->child != NULL)
10958     {
10959       child_die = die->child;
10960       while (child_die && child_die->tag)
10961         {
10962           if (child_die->tag == DW_TAG_template_type_param
10963               || child_die->tag == DW_TAG_template_value_param)
10964             {
10965               struct symbol *arg = new_symbol (child_die, NULL, cu);
10966
10967               if (arg != NULL)
10968                 VEC_safe_push (symbolp, template_args, arg);
10969             }
10970           else
10971             process_die (child_die, cu);
10972           child_die = sibling_die (child_die);
10973         }
10974     }
10975
10976   inherit_abstract_dies (die, cu);
10977
10978   /* If we have a DW_AT_specification, we might need to import using
10979      directives from the context of the specification DIE.  See the
10980      comment in determine_prefix.  */
10981   if (cu->language == language_cplus
10982       && dwarf2_attr (die, DW_AT_specification, cu))
10983     {
10984       struct dwarf2_cu *spec_cu = cu;
10985       struct die_info *spec_die = die_specification (die, &spec_cu);
10986
10987       while (spec_die)
10988         {
10989           child_die = spec_die->child;
10990           while (child_die && child_die->tag)
10991             {
10992               if (child_die->tag == DW_TAG_imported_module)
10993                 process_die (child_die, spec_cu);
10994               child_die = sibling_die (child_die);
10995             }
10996
10997           /* In some cases, GCC generates specification DIEs that
10998              themselves contain DW_AT_specification attributes.  */
10999           spec_die = die_specification (spec_die, &spec_cu);
11000         }
11001     }
11002
11003   new = pop_context ();
11004   /* Make a block for the local symbols within.  */
11005   block = finish_block (new->name, &local_symbols, new->old_blocks,
11006                         lowpc, highpc, objfile);
11007
11008   /* For C++, set the block's scope.  */
11009   if ((cu->language == language_cplus || cu->language == language_fortran)
11010       && cu->processing_has_namespace_info)
11011     block_set_scope (block, determine_prefix (die, cu),
11012                      &objfile->objfile_obstack);
11013
11014   /* If we have address ranges, record them.  */
11015   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11016
11017   /* Attach template arguments to function.  */
11018   if (! VEC_empty (symbolp, template_args))
11019     {
11020       gdb_assert (templ_func != NULL);
11021
11022       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11023       templ_func->template_arguments
11024         = obstack_alloc (&objfile->objfile_obstack,
11025                          (templ_func->n_template_arguments
11026                           * sizeof (struct symbol *)));
11027       memcpy (templ_func->template_arguments,
11028               VEC_address (symbolp, template_args),
11029               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11030       VEC_free (symbolp, template_args);
11031     }
11032
11033   /* In C++, we can have functions nested inside functions (e.g., when
11034      a function declares a class that has methods).  This means that
11035      when we finish processing a function scope, we may need to go
11036      back to building a containing block's symbol lists.  */
11037   local_symbols = new->locals;
11038   using_directives = new->using_directives;
11039
11040   /* If we've finished processing a top-level function, subsequent
11041      symbols go in the file symbol list.  */
11042   if (outermost_context_p ())
11043     cu->list_in_scope = &file_symbols;
11044 }
11045
11046 /* Process all the DIES contained within a lexical block scope.  Start
11047    a new scope, process the dies, and then close the scope.  */
11048
11049 static void
11050 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11051 {
11052   struct objfile *objfile = cu->objfile;
11053   struct context_stack *new;
11054   CORE_ADDR lowpc, highpc;
11055   struct die_info *child_die;
11056   CORE_ADDR baseaddr;
11057
11058   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11059
11060   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11061   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11062      as multiple lexical blocks?  Handling children in a sane way would
11063      be nasty.  Might be easier to properly extend generic blocks to
11064      describe ranges.  */
11065   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11066     return;
11067   lowpc += baseaddr;
11068   highpc += baseaddr;
11069
11070   push_context (0, lowpc);
11071   if (die->child != NULL)
11072     {
11073       child_die = die->child;
11074       while (child_die && child_die->tag)
11075         {
11076           process_die (child_die, cu);
11077           child_die = sibling_die (child_die);
11078         }
11079     }
11080   new = pop_context ();
11081
11082   if (local_symbols != NULL || using_directives != NULL)
11083     {
11084       struct block *block
11085         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
11086                         highpc, objfile);
11087
11088       /* Note that recording ranges after traversing children, as we
11089          do here, means that recording a parent's ranges entails
11090          walking across all its children's ranges as they appear in
11091          the address map, which is quadratic behavior.
11092
11093          It would be nicer to record the parent's ranges before
11094          traversing its children, simply overriding whatever you find
11095          there.  But since we don't even decide whether to create a
11096          block until after we've traversed its children, that's hard
11097          to do.  */
11098       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11099     }
11100   local_symbols = new->locals;
11101   using_directives = new->using_directives;
11102 }
11103
11104 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
11105
11106 static void
11107 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11108 {
11109   struct objfile *objfile = cu->objfile;
11110   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11111   CORE_ADDR pc, baseaddr;
11112   struct attribute *attr;
11113   struct call_site *call_site, call_site_local;
11114   void **slot;
11115   int nparams;
11116   struct die_info *child_die;
11117
11118   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11119
11120   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11121   if (!attr)
11122     {
11123       complaint (&symfile_complaints,
11124                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
11125                    "DIE 0x%x [in module %s]"),
11126                  die->offset.sect_off, objfile_name (objfile));
11127       return;
11128     }
11129   pc = DW_ADDR (attr) + baseaddr;
11130
11131   if (cu->call_site_htab == NULL)
11132     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11133                                                NULL, &objfile->objfile_obstack,
11134                                                hashtab_obstack_allocate, NULL);
11135   call_site_local.pc = pc;
11136   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11137   if (*slot != NULL)
11138     {
11139       complaint (&symfile_complaints,
11140                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
11141                    "DIE 0x%x [in module %s]"),
11142                  paddress (gdbarch, pc), die->offset.sect_off,
11143                  objfile_name (objfile));
11144       return;
11145     }
11146
11147   /* Count parameters at the caller.  */
11148
11149   nparams = 0;
11150   for (child_die = die->child; child_die && child_die->tag;
11151        child_die = sibling_die (child_die))
11152     {
11153       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11154         {
11155           complaint (&symfile_complaints,
11156                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
11157                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11158                      child_die->tag, child_die->offset.sect_off,
11159                      objfile_name (objfile));
11160           continue;
11161         }
11162
11163       nparams++;
11164     }
11165
11166   call_site = obstack_alloc (&objfile->objfile_obstack,
11167                              (sizeof (*call_site)
11168                               + (sizeof (*call_site->parameter)
11169                                  * (nparams - 1))));
11170   *slot = call_site;
11171   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11172   call_site->pc = pc;
11173
11174   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11175     {
11176       struct die_info *func_die;
11177
11178       /* Skip also over DW_TAG_inlined_subroutine.  */
11179       for (func_die = die->parent;
11180            func_die && func_die->tag != DW_TAG_subprogram
11181            && func_die->tag != DW_TAG_subroutine_type;
11182            func_die = func_die->parent);
11183
11184       /* DW_AT_GNU_all_call_sites is a superset
11185          of DW_AT_GNU_all_tail_call_sites.  */
11186       if (func_die
11187           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11188           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11189         {
11190           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11191              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11192              both the initial caller containing the real return address PC and
11193              the final callee containing the current PC of a chain of tail
11194              calls do not need to have the tail call list complete.  But any
11195              function candidate for a virtual tail call frame searched via
11196              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11197              determined unambiguously.  */
11198         }
11199       else
11200         {
11201           struct type *func_type = NULL;
11202
11203           if (func_die)
11204             func_type = get_die_type (func_die, cu);
11205           if (func_type != NULL)
11206             {
11207               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11208
11209               /* Enlist this call site to the function.  */
11210               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11211               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11212             }
11213           else
11214             complaint (&symfile_complaints,
11215                        _("Cannot find function owning DW_TAG_GNU_call_site "
11216                          "DIE 0x%x [in module %s]"),
11217                        die->offset.sect_off, objfile_name (objfile));
11218         }
11219     }
11220
11221   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11222   if (attr == NULL)
11223     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11224   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11225   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11226     /* Keep NULL DWARF_BLOCK.  */;
11227   else if (attr_form_is_block (attr))
11228     {
11229       struct dwarf2_locexpr_baton *dlbaton;
11230
11231       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
11232       dlbaton->data = DW_BLOCK (attr)->data;
11233       dlbaton->size = DW_BLOCK (attr)->size;
11234       dlbaton->per_cu = cu->per_cu;
11235
11236       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11237     }
11238   else if (attr_form_is_ref (attr))
11239     {
11240       struct dwarf2_cu *target_cu = cu;
11241       struct die_info *target_die;
11242
11243       target_die = follow_die_ref (die, attr, &target_cu);
11244       gdb_assert (target_cu->objfile == objfile);
11245       if (die_is_declaration (target_die, target_cu))
11246         {
11247           const char *target_physname = NULL;
11248           struct attribute *target_attr;
11249
11250           /* Prefer the mangled name; otherwise compute the demangled one.  */
11251           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
11252           if (target_attr == NULL)
11253             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
11254                                        target_cu);
11255           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
11256             target_physname = DW_STRING (target_attr);
11257           else
11258             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11259           if (target_physname == NULL)
11260             complaint (&symfile_complaints,
11261                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11262                          "physname, for referencing DIE 0x%x [in module %s]"),
11263                        die->offset.sect_off, objfile_name (objfile));
11264           else
11265             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11266         }
11267       else
11268         {
11269           CORE_ADDR lowpc;
11270
11271           /* DW_AT_entry_pc should be preferred.  */
11272           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
11273             complaint (&symfile_complaints,
11274                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11275                          "low pc, for referencing DIE 0x%x [in module %s]"),
11276                        die->offset.sect_off, objfile_name (objfile));
11277           else
11278             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
11279         }
11280     }
11281   else
11282     complaint (&symfile_complaints,
11283                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
11284                  "block nor reference, for DIE 0x%x [in module %s]"),
11285                die->offset.sect_off, objfile_name (objfile));
11286
11287   call_site->per_cu = cu->per_cu;
11288
11289   for (child_die = die->child;
11290        child_die && child_die->tag;
11291        child_die = sibling_die (child_die))
11292     {
11293       struct call_site_parameter *parameter;
11294       struct attribute *loc, *origin;
11295
11296       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11297         {
11298           /* Already printed the complaint above.  */
11299           continue;
11300         }
11301
11302       gdb_assert (call_site->parameter_count < nparams);
11303       parameter = &call_site->parameter[call_site->parameter_count];
11304
11305       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
11306          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
11307          register is contained in DW_AT_GNU_call_site_value.  */
11308
11309       loc = dwarf2_attr (child_die, DW_AT_location, cu);
11310       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
11311       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
11312         {
11313           sect_offset offset;
11314
11315           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
11316           offset = dwarf2_get_ref_die_offset (origin);
11317           if (!offset_in_cu_p (&cu->header, offset))
11318             {
11319               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
11320                  binding can be done only inside one CU.  Such referenced DIE
11321                  therefore cannot be even moved to DW_TAG_partial_unit.  */
11322               complaint (&symfile_complaints,
11323                          _("DW_AT_abstract_origin offset is not in CU for "
11324                            "DW_TAG_GNU_call_site child DIE 0x%x "
11325                            "[in module %s]"),
11326                          child_die->offset.sect_off, objfile_name (objfile));
11327               continue;
11328             }
11329           parameter->u.param_offset.cu_off = (offset.sect_off
11330                                               - cu->header.offset.sect_off);
11331         }
11332       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
11333         {
11334           complaint (&symfile_complaints,
11335                      _("No DW_FORM_block* DW_AT_location for "
11336                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11337                      child_die->offset.sect_off, objfile_name (objfile));
11338           continue;
11339         }
11340       else
11341         {
11342           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
11343             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
11344           if (parameter->u.dwarf_reg != -1)
11345             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
11346           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
11347                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
11348                                              &parameter->u.fb_offset))
11349             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
11350           else
11351             {
11352               complaint (&symfile_complaints,
11353                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
11354                            "for DW_FORM_block* DW_AT_location is supported for "
11355                            "DW_TAG_GNU_call_site child DIE 0x%x "
11356                            "[in module %s]"),
11357                          child_die->offset.sect_off, objfile_name (objfile));
11358               continue;
11359             }
11360         }
11361
11362       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
11363       if (!attr_form_is_block (attr))
11364         {
11365           complaint (&symfile_complaints,
11366                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
11367                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11368                      child_die->offset.sect_off, objfile_name (objfile));
11369           continue;
11370         }
11371       parameter->value = DW_BLOCK (attr)->data;
11372       parameter->value_size = DW_BLOCK (attr)->size;
11373
11374       /* Parameters are not pre-cleared by memset above.  */
11375       parameter->data_value = NULL;
11376       parameter->data_value_size = 0;
11377       call_site->parameter_count++;
11378
11379       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
11380       if (attr)
11381         {
11382           if (!attr_form_is_block (attr))
11383             complaint (&symfile_complaints,
11384                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
11385                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11386                        child_die->offset.sect_off, objfile_name (objfile));
11387           else
11388             {
11389               parameter->data_value = DW_BLOCK (attr)->data;
11390               parameter->data_value_size = DW_BLOCK (attr)->size;
11391             }
11392         }
11393     }
11394 }
11395
11396 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
11397    Return 1 if the attributes are present and valid, otherwise, return 0.
11398    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
11399
11400 static int
11401 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
11402                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
11403                     struct partial_symtab *ranges_pst)
11404 {
11405   struct objfile *objfile = cu->objfile;
11406   struct comp_unit_head *cu_header = &cu->header;
11407   bfd *obfd = objfile->obfd;
11408   unsigned int addr_size = cu_header->addr_size;
11409   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11410   /* Base address selection entry.  */
11411   CORE_ADDR base;
11412   int found_base;
11413   unsigned int dummy;
11414   const gdb_byte *buffer;
11415   CORE_ADDR marker;
11416   int low_set;
11417   CORE_ADDR low = 0;
11418   CORE_ADDR high = 0;
11419   CORE_ADDR baseaddr;
11420
11421   found_base = cu->base_known;
11422   base = cu->base_address;
11423
11424   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11425   if (offset >= dwarf2_per_objfile->ranges.size)
11426     {
11427       complaint (&symfile_complaints,
11428                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
11429                  offset);
11430       return 0;
11431     }
11432   buffer = dwarf2_per_objfile->ranges.buffer + offset;
11433
11434   /* Read in the largest possible address.  */
11435   marker = read_address (obfd, buffer, cu, &dummy);
11436   if ((marker & mask) == mask)
11437     {
11438       /* If we found the largest possible address, then
11439          read the base address.  */
11440       base = read_address (obfd, buffer + addr_size, cu, &dummy);
11441       buffer += 2 * addr_size;
11442       offset += 2 * addr_size;
11443       found_base = 1;
11444     }
11445
11446   low_set = 0;
11447
11448   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11449
11450   while (1)
11451     {
11452       CORE_ADDR range_beginning, range_end;
11453
11454       range_beginning = read_address (obfd, buffer, cu, &dummy);
11455       buffer += addr_size;
11456       range_end = read_address (obfd, buffer, cu, &dummy);
11457       buffer += addr_size;
11458       offset += 2 * addr_size;
11459
11460       /* An end of list marker is a pair of zero addresses.  */
11461       if (range_beginning == 0 && range_end == 0)
11462         /* Found the end of list entry.  */
11463         break;
11464
11465       /* Each base address selection entry is a pair of 2 values.
11466          The first is the largest possible address, the second is
11467          the base address.  Check for a base address here.  */
11468       if ((range_beginning & mask) == mask)
11469         {
11470           /* If we found the largest possible address, then
11471              read the base address.  */
11472           base = read_address (obfd, buffer + addr_size, cu, &dummy);
11473           found_base = 1;
11474           continue;
11475         }
11476
11477       if (!found_base)
11478         {
11479           /* We have no valid base address for the ranges
11480              data.  */
11481           complaint (&symfile_complaints,
11482                      _("Invalid .debug_ranges data (no base address)"));
11483           return 0;
11484         }
11485
11486       if (range_beginning > range_end)
11487         {
11488           /* Inverted range entries are invalid.  */
11489           complaint (&symfile_complaints,
11490                      _("Invalid .debug_ranges data (inverted range)"));
11491           return 0;
11492         }
11493
11494       /* Empty range entries have no effect.  */
11495       if (range_beginning == range_end)
11496         continue;
11497
11498       range_beginning += base;
11499       range_end += base;
11500
11501       /* A not-uncommon case of bad debug info.
11502          Don't pollute the addrmap with bad data.  */
11503       if (range_beginning + baseaddr == 0
11504           && !dwarf2_per_objfile->has_section_at_zero)
11505         {
11506           complaint (&symfile_complaints,
11507                      _(".debug_ranges entry has start address of zero"
11508                        " [in module %s]"), objfile_name (objfile));
11509           continue;
11510         }
11511
11512       if (ranges_pst != NULL)
11513         addrmap_set_empty (objfile->psymtabs_addrmap,
11514                            range_beginning + baseaddr,
11515                            range_end - 1 + baseaddr,
11516                            ranges_pst);
11517
11518       /* FIXME: This is recording everything as a low-high
11519          segment of consecutive addresses.  We should have a
11520          data structure for discontiguous block ranges
11521          instead.  */
11522       if (! low_set)
11523         {
11524           low = range_beginning;
11525           high = range_end;
11526           low_set = 1;
11527         }
11528       else
11529         {
11530           if (range_beginning < low)
11531             low = range_beginning;
11532           if (range_end > high)
11533             high = range_end;
11534         }
11535     }
11536
11537   if (! low_set)
11538     /* If the first entry is an end-of-list marker, the range
11539        describes an empty scope, i.e. no instructions.  */
11540     return 0;
11541
11542   if (low_return)
11543     *low_return = low;
11544   if (high_return)
11545     *high_return = high;
11546   return 1;
11547 }
11548
11549 /* Get low and high pc attributes from a die.  Return 1 if the attributes
11550    are present and valid, otherwise, return 0.  Return -1 if the range is
11551    discontinuous, i.e. derived from DW_AT_ranges information.  */
11552
11553 static int
11554 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
11555                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
11556                       struct partial_symtab *pst)
11557 {
11558   struct attribute *attr;
11559   struct attribute *attr_high;
11560   CORE_ADDR low = 0;
11561   CORE_ADDR high = 0;
11562   int ret = 0;
11563
11564   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11565   if (attr_high)
11566     {
11567       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11568       if (attr)
11569         {
11570           low = DW_ADDR (attr);
11571           if (attr_high->form == DW_FORM_addr
11572               || attr_high->form == DW_FORM_GNU_addr_index)
11573             high = DW_ADDR (attr_high);
11574           else
11575             high = low + DW_UNSND (attr_high);
11576         }
11577       else
11578         /* Found high w/o low attribute.  */
11579         return 0;
11580
11581       /* Found consecutive range of addresses.  */
11582       ret = 1;
11583     }
11584   else
11585     {
11586       attr = dwarf2_attr (die, DW_AT_ranges, cu);
11587       if (attr != NULL)
11588         {
11589           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11590              We take advantage of the fact that DW_AT_ranges does not appear
11591              in DW_TAG_compile_unit of DWO files.  */
11592           int need_ranges_base = die->tag != DW_TAG_compile_unit;
11593           unsigned int ranges_offset = (DW_UNSND (attr)
11594                                         + (need_ranges_base
11595                                            ? cu->ranges_base
11596                                            : 0));
11597
11598           /* Value of the DW_AT_ranges attribute is the offset in the
11599              .debug_ranges section.  */
11600           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
11601             return 0;
11602           /* Found discontinuous range of addresses.  */
11603           ret = -1;
11604         }
11605     }
11606
11607   /* read_partial_die has also the strict LOW < HIGH requirement.  */
11608   if (high <= low)
11609     return 0;
11610
11611   /* When using the GNU linker, .gnu.linkonce. sections are used to
11612      eliminate duplicate copies of functions and vtables and such.
11613      The linker will arbitrarily choose one and discard the others.
11614      The AT_*_pc values for such functions refer to local labels in
11615      these sections.  If the section from that file was discarded, the
11616      labels are not in the output, so the relocs get a value of 0.
11617      If this is a discarded function, mark the pc bounds as invalid,
11618      so that GDB will ignore it.  */
11619   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
11620     return 0;
11621
11622   *lowpc = low;
11623   if (highpc)
11624     *highpc = high;
11625   return ret;
11626 }
11627
11628 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
11629    its low and high PC addresses.  Do nothing if these addresses could not
11630    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
11631    and HIGHPC to the high address if greater than HIGHPC.  */
11632
11633 static void
11634 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
11635                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
11636                                  struct dwarf2_cu *cu)
11637 {
11638   CORE_ADDR low, high;
11639   struct die_info *child = die->child;
11640
11641   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
11642     {
11643       *lowpc = min (*lowpc, low);
11644       *highpc = max (*highpc, high);
11645     }
11646
11647   /* If the language does not allow nested subprograms (either inside
11648      subprograms or lexical blocks), we're done.  */
11649   if (cu->language != language_ada)
11650     return;
11651
11652   /* Check all the children of the given DIE.  If it contains nested
11653      subprograms, then check their pc bounds.  Likewise, we need to
11654      check lexical blocks as well, as they may also contain subprogram
11655      definitions.  */
11656   while (child && child->tag)
11657     {
11658       if (child->tag == DW_TAG_subprogram
11659           || child->tag == DW_TAG_lexical_block)
11660         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
11661       child = sibling_die (child);
11662     }
11663 }
11664
11665 /* Get the low and high pc's represented by the scope DIE, and store
11666    them in *LOWPC and *HIGHPC.  If the correct values can't be
11667    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
11668
11669 static void
11670 get_scope_pc_bounds (struct die_info *die,
11671                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
11672                      struct dwarf2_cu *cu)
11673 {
11674   CORE_ADDR best_low = (CORE_ADDR) -1;
11675   CORE_ADDR best_high = (CORE_ADDR) 0;
11676   CORE_ADDR current_low, current_high;
11677
11678   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
11679     {
11680       best_low = current_low;
11681       best_high = current_high;
11682     }
11683   else
11684     {
11685       struct die_info *child = die->child;
11686
11687       while (child && child->tag)
11688         {
11689           switch (child->tag) {
11690           case DW_TAG_subprogram:
11691             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
11692             break;
11693           case DW_TAG_namespace:
11694           case DW_TAG_module:
11695             /* FIXME: carlton/2004-01-16: Should we do this for
11696                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
11697                that current GCC's always emit the DIEs corresponding
11698                to definitions of methods of classes as children of a
11699                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
11700                the DIEs giving the declarations, which could be
11701                anywhere).  But I don't see any reason why the
11702                standards says that they have to be there.  */
11703             get_scope_pc_bounds (child, &current_low, &current_high, cu);
11704
11705             if (current_low != ((CORE_ADDR) -1))
11706               {
11707                 best_low = min (best_low, current_low);
11708                 best_high = max (best_high, current_high);
11709               }
11710             break;
11711           default:
11712             /* Ignore.  */
11713             break;
11714           }
11715
11716           child = sibling_die (child);
11717         }
11718     }
11719
11720   *lowpc = best_low;
11721   *highpc = best_high;
11722 }
11723
11724 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
11725    in DIE.  */
11726
11727 static void
11728 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
11729                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
11730 {
11731   struct objfile *objfile = cu->objfile;
11732   struct attribute *attr;
11733   struct attribute *attr_high;
11734
11735   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11736   if (attr_high)
11737     {
11738       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11739       if (attr)
11740         {
11741           CORE_ADDR low = DW_ADDR (attr);
11742           CORE_ADDR high;
11743           if (attr_high->form == DW_FORM_addr
11744               || attr_high->form == DW_FORM_GNU_addr_index)
11745             high = DW_ADDR (attr_high);
11746           else
11747             high = low + DW_UNSND (attr_high);
11748
11749           record_block_range (block, baseaddr + low, baseaddr + high - 1);
11750         }
11751     }
11752
11753   attr = dwarf2_attr (die, DW_AT_ranges, cu);
11754   if (attr)
11755     {
11756       bfd *obfd = objfile->obfd;
11757       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11758          We take advantage of the fact that DW_AT_ranges does not appear
11759          in DW_TAG_compile_unit of DWO files.  */
11760       int need_ranges_base = die->tag != DW_TAG_compile_unit;
11761
11762       /* The value of the DW_AT_ranges attribute is the offset of the
11763          address range list in the .debug_ranges section.  */
11764       unsigned long offset = (DW_UNSND (attr)
11765                               + (need_ranges_base ? cu->ranges_base : 0));
11766       const gdb_byte *buffer;
11767
11768       /* For some target architectures, but not others, the
11769          read_address function sign-extends the addresses it returns.
11770          To recognize base address selection entries, we need a
11771          mask.  */
11772       unsigned int addr_size = cu->header.addr_size;
11773       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11774
11775       /* The base address, to which the next pair is relative.  Note
11776          that this 'base' is a DWARF concept: most entries in a range
11777          list are relative, to reduce the number of relocs against the
11778          debugging information.  This is separate from this function's
11779          'baseaddr' argument, which GDB uses to relocate debugging
11780          information from a shared library based on the address at
11781          which the library was loaded.  */
11782       CORE_ADDR base = cu->base_address;
11783       int base_known = cu->base_known;
11784
11785       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11786       if (offset >= dwarf2_per_objfile->ranges.size)
11787         {
11788           complaint (&symfile_complaints,
11789                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
11790                      offset);
11791           return;
11792         }
11793       buffer = dwarf2_per_objfile->ranges.buffer + offset;
11794
11795       for (;;)
11796         {
11797           unsigned int bytes_read;
11798           CORE_ADDR start, end;
11799
11800           start = read_address (obfd, buffer, cu, &bytes_read);
11801           buffer += bytes_read;
11802           end = read_address (obfd, buffer, cu, &bytes_read);
11803           buffer += bytes_read;
11804
11805           /* Did we find the end of the range list?  */
11806           if (start == 0 && end == 0)
11807             break;
11808
11809           /* Did we find a base address selection entry?  */
11810           else if ((start & base_select_mask) == base_select_mask)
11811             {
11812               base = end;
11813               base_known = 1;
11814             }
11815
11816           /* We found an ordinary address range.  */
11817           else
11818             {
11819               if (!base_known)
11820                 {
11821                   complaint (&symfile_complaints,
11822                              _("Invalid .debug_ranges data "
11823                                "(no base address)"));
11824                   return;
11825                 }
11826
11827               if (start > end)
11828                 {
11829                   /* Inverted range entries are invalid.  */
11830                   complaint (&symfile_complaints,
11831                              _("Invalid .debug_ranges data "
11832                                "(inverted range)"));
11833                   return;
11834                 }
11835
11836               /* Empty range entries have no effect.  */
11837               if (start == end)
11838                 continue;
11839
11840               start += base + baseaddr;
11841               end += base + baseaddr;
11842
11843               /* A not-uncommon case of bad debug info.
11844                  Don't pollute the addrmap with bad data.  */
11845               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11846                 {
11847                   complaint (&symfile_complaints,
11848                              _(".debug_ranges entry has start address of zero"
11849                                " [in module %s]"), objfile_name (objfile));
11850                   continue;
11851                 }
11852
11853               record_block_range (block, start, end - 1);
11854             }
11855         }
11856     }
11857 }
11858
11859 /* Check whether the producer field indicates either of GCC < 4.6, or the
11860    Intel C/C++ compiler, and cache the result in CU.  */
11861
11862 static void
11863 check_producer (struct dwarf2_cu *cu)
11864 {
11865   const char *cs;
11866   int major, minor, release;
11867
11868   if (cu->producer == NULL)
11869     {
11870       /* For unknown compilers expect their behavior is DWARF version
11871          compliant.
11872
11873          GCC started to support .debug_types sections by -gdwarf-4 since
11874          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11875          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11876          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11877          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11878     }
11879   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11880     {
11881       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11882
11883       cs = &cu->producer[strlen ("GNU ")];
11884       while (*cs && !isdigit (*cs))
11885         cs++;
11886       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11887         {
11888           /* Not recognized as GCC.  */
11889         }
11890       else
11891         {
11892           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11893           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11894         }
11895     }
11896   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11897     cu->producer_is_icc = 1;
11898   else
11899     {
11900       /* For other non-GCC compilers, expect their behavior is DWARF version
11901          compliant.  */
11902     }
11903
11904   cu->checked_producer = 1;
11905 }
11906
11907 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11908    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11909    during 4.6.0 experimental.  */
11910
11911 static int
11912 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11913 {
11914   if (!cu->checked_producer)
11915     check_producer (cu);
11916
11917   return cu->producer_is_gxx_lt_4_6;
11918 }
11919
11920 /* Return the default accessibility type if it is not overriden by
11921    DW_AT_accessibility.  */
11922
11923 static enum dwarf_access_attribute
11924 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11925 {
11926   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11927     {
11928       /* The default DWARF 2 accessibility for members is public, the default
11929          accessibility for inheritance is private.  */
11930
11931       if (die->tag != DW_TAG_inheritance)
11932         return DW_ACCESS_public;
11933       else
11934         return DW_ACCESS_private;
11935     }
11936   else
11937     {
11938       /* DWARF 3+ defines the default accessibility a different way.  The same
11939          rules apply now for DW_TAG_inheritance as for the members and it only
11940          depends on the container kind.  */
11941
11942       if (die->parent->tag == DW_TAG_class_type)
11943         return DW_ACCESS_private;
11944       else
11945         return DW_ACCESS_public;
11946     }
11947 }
11948
11949 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11950    offset.  If the attribute was not found return 0, otherwise return
11951    1.  If it was found but could not properly be handled, set *OFFSET
11952    to 0.  */
11953
11954 static int
11955 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11956                              LONGEST *offset)
11957 {
11958   struct attribute *attr;
11959
11960   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11961   if (attr != NULL)
11962     {
11963       *offset = 0;
11964
11965       /* Note that we do not check for a section offset first here.
11966          This is because DW_AT_data_member_location is new in DWARF 4,
11967          so if we see it, we can assume that a constant form is really
11968          a constant and not a section offset.  */
11969       if (attr_form_is_constant (attr))
11970         *offset = dwarf2_get_attr_constant_value (attr, 0);
11971       else if (attr_form_is_section_offset (attr))
11972         dwarf2_complex_location_expr_complaint ();
11973       else if (attr_form_is_block (attr))
11974         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11975       else
11976         dwarf2_complex_location_expr_complaint ();
11977
11978       return 1;
11979     }
11980
11981   return 0;
11982 }
11983
11984 /* Add an aggregate field to the field list.  */
11985
11986 static void
11987 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11988                   struct dwarf2_cu *cu)
11989 {
11990   struct objfile *objfile = cu->objfile;
11991   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11992   struct nextfield *new_field;
11993   struct attribute *attr;
11994   struct field *fp;
11995   const char *fieldname = "";
11996
11997   /* Allocate a new field list entry and link it in.  */
11998   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11999   make_cleanup (xfree, new_field);
12000   memset (new_field, 0, sizeof (struct nextfield));
12001
12002   if (die->tag == DW_TAG_inheritance)
12003     {
12004       new_field->next = fip->baseclasses;
12005       fip->baseclasses = new_field;
12006     }
12007   else
12008     {
12009       new_field->next = fip->fields;
12010       fip->fields = new_field;
12011     }
12012   fip->nfields++;
12013
12014   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12015   if (attr)
12016     new_field->accessibility = DW_UNSND (attr);
12017   else
12018     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12019   if (new_field->accessibility != DW_ACCESS_public)
12020     fip->non_public_fields = 1;
12021
12022   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12023   if (attr)
12024     new_field->virtuality = DW_UNSND (attr);
12025   else
12026     new_field->virtuality = DW_VIRTUALITY_none;
12027
12028   fp = &new_field->field;
12029
12030   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12031     {
12032       LONGEST offset;
12033
12034       /* Data member other than a C++ static data member.  */
12035
12036       /* Get type of field.  */
12037       fp->type = die_type (die, cu);
12038
12039       SET_FIELD_BITPOS (*fp, 0);
12040
12041       /* Get bit size of field (zero if none).  */
12042       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12043       if (attr)
12044         {
12045           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12046         }
12047       else
12048         {
12049           FIELD_BITSIZE (*fp) = 0;
12050         }
12051
12052       /* Get bit offset of field.  */
12053       if (handle_data_member_location (die, cu, &offset))
12054         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12055       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12056       if (attr)
12057         {
12058           if (gdbarch_bits_big_endian (gdbarch))
12059             {
12060               /* For big endian bits, the DW_AT_bit_offset gives the
12061                  additional bit offset from the MSB of the containing
12062                  anonymous object to the MSB of the field.  We don't
12063                  have to do anything special since we don't need to
12064                  know the size of the anonymous object.  */
12065               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12066             }
12067           else
12068             {
12069               /* For little endian bits, compute the bit offset to the
12070                  MSB of the anonymous object, subtract off the number of
12071                  bits from the MSB of the field to the MSB of the
12072                  object, and then subtract off the number of bits of
12073                  the field itself.  The result is the bit offset of
12074                  the LSB of the field.  */
12075               int anonymous_size;
12076               int bit_offset = DW_UNSND (attr);
12077
12078               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12079               if (attr)
12080                 {
12081                   /* The size of the anonymous object containing
12082                      the bit field is explicit, so use the
12083                      indicated size (in bytes).  */
12084                   anonymous_size = DW_UNSND (attr);
12085                 }
12086               else
12087                 {
12088                   /* The size of the anonymous object containing
12089                      the bit field must be inferred from the type
12090                      attribute of the data member containing the
12091                      bit field.  */
12092                   anonymous_size = TYPE_LENGTH (fp->type);
12093                 }
12094               SET_FIELD_BITPOS (*fp,
12095                                 (FIELD_BITPOS (*fp)
12096                                  + anonymous_size * bits_per_byte
12097                                  - bit_offset - FIELD_BITSIZE (*fp)));
12098             }
12099         }
12100
12101       /* Get name of field.  */
12102       fieldname = dwarf2_name (die, cu);
12103       if (fieldname == NULL)
12104         fieldname = "";
12105
12106       /* The name is already allocated along with this objfile, so we don't
12107          need to duplicate it for the type.  */
12108       fp->name = fieldname;
12109
12110       /* Change accessibility for artificial fields (e.g. virtual table
12111          pointer or virtual base class pointer) to private.  */
12112       if (dwarf2_attr (die, DW_AT_artificial, cu))
12113         {
12114           FIELD_ARTIFICIAL (*fp) = 1;
12115           new_field->accessibility = DW_ACCESS_private;
12116           fip->non_public_fields = 1;
12117         }
12118     }
12119   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12120     {
12121       /* C++ static member.  */
12122
12123       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12124          is a declaration, but all versions of G++ as of this writing
12125          (so through at least 3.2.1) incorrectly generate
12126          DW_TAG_variable tags.  */
12127
12128       const char *physname;
12129
12130       /* Get name of field.  */
12131       fieldname = dwarf2_name (die, cu);
12132       if (fieldname == NULL)
12133         return;
12134
12135       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12136       if (attr
12137           /* Only create a symbol if this is an external value.
12138              new_symbol checks this and puts the value in the global symbol
12139              table, which we want.  If it is not external, new_symbol
12140              will try to put the value in cu->list_in_scope which is wrong.  */
12141           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12142         {
12143           /* A static const member, not much different than an enum as far as
12144              we're concerned, except that we can support more types.  */
12145           new_symbol (die, NULL, cu);
12146         }
12147
12148       /* Get physical name.  */
12149       physname = dwarf2_physname (fieldname, die, cu);
12150
12151       /* The name is already allocated along with this objfile, so we don't
12152          need to duplicate it for the type.  */
12153       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
12154       FIELD_TYPE (*fp) = die_type (die, cu);
12155       FIELD_NAME (*fp) = fieldname;
12156     }
12157   else if (die->tag == DW_TAG_inheritance)
12158     {
12159       LONGEST offset;
12160
12161       /* C++ base class field.  */
12162       if (handle_data_member_location (die, cu, &offset))
12163         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12164       FIELD_BITSIZE (*fp) = 0;
12165       FIELD_TYPE (*fp) = die_type (die, cu);
12166       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
12167       fip->nbaseclasses++;
12168     }
12169 }
12170
12171 /* Add a typedef defined in the scope of the FIP's class.  */
12172
12173 static void
12174 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
12175                     struct dwarf2_cu *cu)
12176 {
12177   struct objfile *objfile = cu->objfile;
12178   struct typedef_field_list *new_field;
12179   struct attribute *attr;
12180   struct typedef_field *fp;
12181   char *fieldname = "";
12182
12183   /* Allocate a new field list entry and link it in.  */
12184   new_field = xzalloc (sizeof (*new_field));
12185   make_cleanup (xfree, new_field);
12186
12187   gdb_assert (die->tag == DW_TAG_typedef);
12188
12189   fp = &new_field->field;
12190
12191   /* Get name of field.  */
12192   fp->name = dwarf2_name (die, cu);
12193   if (fp->name == NULL)
12194     return;
12195
12196   fp->type = read_type_die (die, cu);
12197
12198   new_field->next = fip->typedef_field_list;
12199   fip->typedef_field_list = new_field;
12200   fip->typedef_field_list_count++;
12201 }
12202
12203 /* Create the vector of fields, and attach it to the type.  */
12204
12205 static void
12206 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
12207                               struct dwarf2_cu *cu)
12208 {
12209   int nfields = fip->nfields;
12210
12211   /* Record the field count, allocate space for the array of fields,
12212      and create blank accessibility bitfields if necessary.  */
12213   TYPE_NFIELDS (type) = nfields;
12214   TYPE_FIELDS (type) = (struct field *)
12215     TYPE_ALLOC (type, sizeof (struct field) * nfields);
12216   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
12217
12218   if (fip->non_public_fields && cu->language != language_ada)
12219     {
12220       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12221
12222       TYPE_FIELD_PRIVATE_BITS (type) =
12223         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12224       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
12225
12226       TYPE_FIELD_PROTECTED_BITS (type) =
12227         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12228       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
12229
12230       TYPE_FIELD_IGNORE_BITS (type) =
12231         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12232       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
12233     }
12234
12235   /* If the type has baseclasses, allocate and clear a bit vector for
12236      TYPE_FIELD_VIRTUAL_BITS.  */
12237   if (fip->nbaseclasses && cu->language != language_ada)
12238     {
12239       int num_bytes = B_BYTES (fip->nbaseclasses);
12240       unsigned char *pointer;
12241
12242       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12243       pointer = TYPE_ALLOC (type, num_bytes);
12244       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
12245       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
12246       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
12247     }
12248
12249   /* Copy the saved-up fields into the field vector.  Start from the head of
12250      the list, adding to the tail of the field array, so that they end up in
12251      the same order in the array in which they were added to the list.  */
12252   while (nfields-- > 0)
12253     {
12254       struct nextfield *fieldp;
12255
12256       if (fip->fields)
12257         {
12258           fieldp = fip->fields;
12259           fip->fields = fieldp->next;
12260         }
12261       else
12262         {
12263           fieldp = fip->baseclasses;
12264           fip->baseclasses = fieldp->next;
12265         }
12266
12267       TYPE_FIELD (type, nfields) = fieldp->field;
12268       switch (fieldp->accessibility)
12269         {
12270         case DW_ACCESS_private:
12271           if (cu->language != language_ada)
12272             SET_TYPE_FIELD_PRIVATE (type, nfields);
12273           break;
12274
12275         case DW_ACCESS_protected:
12276           if (cu->language != language_ada)
12277             SET_TYPE_FIELD_PROTECTED (type, nfields);
12278           break;
12279
12280         case DW_ACCESS_public:
12281           break;
12282
12283         default:
12284           /* Unknown accessibility.  Complain and treat it as public.  */
12285           {
12286             complaint (&symfile_complaints, _("unsupported accessibility %d"),
12287                        fieldp->accessibility);
12288           }
12289           break;
12290         }
12291       if (nfields < fip->nbaseclasses)
12292         {
12293           switch (fieldp->virtuality)
12294             {
12295             case DW_VIRTUALITY_virtual:
12296             case DW_VIRTUALITY_pure_virtual:
12297               if (cu->language == language_ada)
12298                 error (_("unexpected virtuality in component of Ada type"));
12299               SET_TYPE_FIELD_VIRTUAL (type, nfields);
12300               break;
12301             }
12302         }
12303     }
12304 }
12305
12306 /* Return true if this member function is a constructor, false
12307    otherwise.  */
12308
12309 static int
12310 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
12311 {
12312   const char *fieldname;
12313   const char *typename;
12314   int len;
12315
12316   if (die->parent == NULL)
12317     return 0;
12318
12319   if (die->parent->tag != DW_TAG_structure_type
12320       && die->parent->tag != DW_TAG_union_type
12321       && die->parent->tag != DW_TAG_class_type)
12322     return 0;
12323
12324   fieldname = dwarf2_name (die, cu);
12325   typename = dwarf2_name (die->parent, cu);
12326   if (fieldname == NULL || typename == NULL)
12327     return 0;
12328
12329   len = strlen (fieldname);
12330   return (strncmp (fieldname, typename, len) == 0
12331           && (typename[len] == '\0' || typename[len] == '<'));
12332 }
12333
12334 /* Add a member function to the proper fieldlist.  */
12335
12336 static void
12337 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
12338                       struct type *type, struct dwarf2_cu *cu)
12339 {
12340   struct objfile *objfile = cu->objfile;
12341   struct attribute *attr;
12342   struct fnfieldlist *flp;
12343   int i;
12344   struct fn_field *fnp;
12345   const char *fieldname;
12346   struct nextfnfield *new_fnfield;
12347   struct type *this_type;
12348   enum dwarf_access_attribute accessibility;
12349
12350   if (cu->language == language_ada)
12351     error (_("unexpected member function in Ada type"));
12352
12353   /* Get name of member function.  */
12354   fieldname = dwarf2_name (die, cu);
12355   if (fieldname == NULL)
12356     return;
12357
12358   /* Look up member function name in fieldlist.  */
12359   for (i = 0; i < fip->nfnfields; i++)
12360     {
12361       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
12362         break;
12363     }
12364
12365   /* Create new list element if necessary.  */
12366   if (i < fip->nfnfields)
12367     flp = &fip->fnfieldlists[i];
12368   else
12369     {
12370       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
12371         {
12372           fip->fnfieldlists = (struct fnfieldlist *)
12373             xrealloc (fip->fnfieldlists,
12374                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
12375                       * sizeof (struct fnfieldlist));
12376           if (fip->nfnfields == 0)
12377             make_cleanup (free_current_contents, &fip->fnfieldlists);
12378         }
12379       flp = &fip->fnfieldlists[fip->nfnfields];
12380       flp->name = fieldname;
12381       flp->length = 0;
12382       flp->head = NULL;
12383       i = fip->nfnfields++;
12384     }
12385
12386   /* Create a new member function field and chain it to the field list
12387      entry.  */
12388   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
12389   make_cleanup (xfree, new_fnfield);
12390   memset (new_fnfield, 0, sizeof (struct nextfnfield));
12391   new_fnfield->next = flp->head;
12392   flp->head = new_fnfield;
12393   flp->length++;
12394
12395   /* Fill in the member function field info.  */
12396   fnp = &new_fnfield->fnfield;
12397
12398   /* Delay processing of the physname until later.  */
12399   if (cu->language == language_cplus || cu->language == language_java)
12400     {
12401       add_to_method_list (type, i, flp->length - 1, fieldname,
12402                           die, cu);
12403     }
12404   else
12405     {
12406       const char *physname = dwarf2_physname (fieldname, die, cu);
12407       fnp->physname = physname ? physname : "";
12408     }
12409
12410   fnp->type = alloc_type (objfile);
12411   this_type = read_type_die (die, cu);
12412   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
12413     {
12414       int nparams = TYPE_NFIELDS (this_type);
12415
12416       /* TYPE is the domain of this method, and THIS_TYPE is the type
12417            of the method itself (TYPE_CODE_METHOD).  */
12418       smash_to_method_type (fnp->type, type,
12419                             TYPE_TARGET_TYPE (this_type),
12420                             TYPE_FIELDS (this_type),
12421                             TYPE_NFIELDS (this_type),
12422                             TYPE_VARARGS (this_type));
12423
12424       /* Handle static member functions.
12425          Dwarf2 has no clean way to discern C++ static and non-static
12426          member functions.  G++ helps GDB by marking the first
12427          parameter for non-static member functions (which is the this
12428          pointer) as artificial.  We obtain this information from
12429          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
12430       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
12431         fnp->voffset = VOFFSET_STATIC;
12432     }
12433   else
12434     complaint (&symfile_complaints, _("member function type missing for '%s'"),
12435                dwarf2_full_name (fieldname, die, cu));
12436
12437   /* Get fcontext from DW_AT_containing_type if present.  */
12438   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12439     fnp->fcontext = die_containing_type (die, cu);
12440
12441   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
12442      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
12443
12444   /* Get accessibility.  */
12445   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12446   if (attr)
12447     accessibility = DW_UNSND (attr);
12448   else
12449     accessibility = dwarf2_default_access_attribute (die, cu);
12450   switch (accessibility)
12451     {
12452     case DW_ACCESS_private:
12453       fnp->is_private = 1;
12454       break;
12455     case DW_ACCESS_protected:
12456       fnp->is_protected = 1;
12457       break;
12458     }
12459
12460   /* Check for artificial methods.  */
12461   attr = dwarf2_attr (die, DW_AT_artificial, cu);
12462   if (attr && DW_UNSND (attr) != 0)
12463     fnp->is_artificial = 1;
12464
12465   fnp->is_constructor = dwarf2_is_constructor (die, cu);
12466
12467   /* Get index in virtual function table if it is a virtual member
12468      function.  For older versions of GCC, this is an offset in the
12469      appropriate virtual table, as specified by DW_AT_containing_type.
12470      For everyone else, it is an expression to be evaluated relative
12471      to the object address.  */
12472
12473   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
12474   if (attr)
12475     {
12476       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
12477         {
12478           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
12479             {
12480               /* Old-style GCC.  */
12481               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
12482             }
12483           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
12484                    || (DW_BLOCK (attr)->size > 1
12485                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
12486                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
12487             {
12488               struct dwarf_block blk;
12489               int offset;
12490
12491               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
12492                         ? 1 : 2);
12493               blk.size = DW_BLOCK (attr)->size - offset;
12494               blk.data = DW_BLOCK (attr)->data + offset;
12495               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
12496               if ((fnp->voffset % cu->header.addr_size) != 0)
12497                 dwarf2_complex_location_expr_complaint ();
12498               else
12499                 fnp->voffset /= cu->header.addr_size;
12500               fnp->voffset += 2;
12501             }
12502           else
12503             dwarf2_complex_location_expr_complaint ();
12504
12505           if (!fnp->fcontext)
12506             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
12507         }
12508       else if (attr_form_is_section_offset (attr))
12509         {
12510           dwarf2_complex_location_expr_complaint ();
12511         }
12512       else
12513         {
12514           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
12515                                                  fieldname);
12516         }
12517     }
12518   else
12519     {
12520       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12521       if (attr && DW_UNSND (attr))
12522         {
12523           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
12524           complaint (&symfile_complaints,
12525                      _("Member function \"%s\" (offset %d) is virtual "
12526                        "but the vtable offset is not specified"),
12527                      fieldname, die->offset.sect_off);
12528           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12529           TYPE_CPLUS_DYNAMIC (type) = 1;
12530         }
12531     }
12532 }
12533
12534 /* Create the vector of member function fields, and attach it to the type.  */
12535
12536 static void
12537 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
12538                                  struct dwarf2_cu *cu)
12539 {
12540   struct fnfieldlist *flp;
12541   int i;
12542
12543   if (cu->language == language_ada)
12544     error (_("unexpected member functions in Ada type"));
12545
12546   ALLOCATE_CPLUS_STRUCT_TYPE (type);
12547   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
12548     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
12549
12550   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
12551     {
12552       struct nextfnfield *nfp = flp->head;
12553       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
12554       int k;
12555
12556       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
12557       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
12558       fn_flp->fn_fields = (struct fn_field *)
12559         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
12560       for (k = flp->length; (k--, nfp); nfp = nfp->next)
12561         fn_flp->fn_fields[k] = nfp->fnfield;
12562     }
12563
12564   TYPE_NFN_FIELDS (type) = fip->nfnfields;
12565 }
12566
12567 /* Returns non-zero if NAME is the name of a vtable member in CU's
12568    language, zero otherwise.  */
12569 static int
12570 is_vtable_name (const char *name, struct dwarf2_cu *cu)
12571 {
12572   static const char vptr[] = "_vptr";
12573   static const char vtable[] = "vtable";
12574
12575   /* Look for the C++ and Java forms of the vtable.  */
12576   if ((cu->language == language_java
12577        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
12578        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
12579        && is_cplus_marker (name[sizeof (vptr) - 1])))
12580     return 1;
12581
12582   return 0;
12583 }
12584
12585 /* GCC outputs unnamed structures that are really pointers to member
12586    functions, with the ABI-specified layout.  If TYPE describes
12587    such a structure, smash it into a member function type.
12588
12589    GCC shouldn't do this; it should just output pointer to member DIEs.
12590    This is GCC PR debug/28767.  */
12591
12592 static void
12593 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
12594 {
12595   struct type *pfn_type, *domain_type, *new_type;
12596
12597   /* Check for a structure with no name and two children.  */
12598   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
12599     return;
12600
12601   /* Check for __pfn and __delta members.  */
12602   if (TYPE_FIELD_NAME (type, 0) == NULL
12603       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
12604       || TYPE_FIELD_NAME (type, 1) == NULL
12605       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
12606     return;
12607
12608   /* Find the type of the method.  */
12609   pfn_type = TYPE_FIELD_TYPE (type, 0);
12610   if (pfn_type == NULL
12611       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
12612       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
12613     return;
12614
12615   /* Look for the "this" argument.  */
12616   pfn_type = TYPE_TARGET_TYPE (pfn_type);
12617   if (TYPE_NFIELDS (pfn_type) == 0
12618       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
12619       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
12620     return;
12621
12622   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
12623   new_type = alloc_type (objfile);
12624   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
12625                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
12626                         TYPE_VARARGS (pfn_type));
12627   smash_to_methodptr_type (type, new_type);
12628 }
12629
12630 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
12631    (icc).  */
12632
12633 static int
12634 producer_is_icc (struct dwarf2_cu *cu)
12635 {
12636   if (!cu->checked_producer)
12637     check_producer (cu);
12638
12639   return cu->producer_is_icc;
12640 }
12641
12642 /* Called when we find the DIE that starts a structure or union scope
12643    (definition) to create a type for the structure or union.  Fill in
12644    the type's name and general properties; the members will not be
12645    processed until process_structure_scope.
12646
12647    NOTE: we need to call these functions regardless of whether or not the
12648    DIE has a DW_AT_name attribute, since it might be an anonymous
12649    structure or union.  This gets the type entered into our set of
12650    user defined types.
12651
12652    However, if the structure is incomplete (an opaque struct/union)
12653    then suppress creating a symbol table entry for it since gdb only
12654    wants to find the one with the complete definition.  Note that if
12655    it is complete, we just call new_symbol, which does it's own
12656    checking about whether the struct/union is anonymous or not (and
12657    suppresses creating a symbol table entry itself).  */
12658
12659 static struct type *
12660 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
12661 {
12662   struct objfile *objfile = cu->objfile;
12663   struct type *type;
12664   struct attribute *attr;
12665   const char *name;
12666
12667   /* If the definition of this type lives in .debug_types, read that type.
12668      Don't follow DW_AT_specification though, that will take us back up
12669      the chain and we want to go down.  */
12670   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12671   if (attr)
12672     {
12673       type = get_DW_AT_signature_type (die, attr, cu);
12674
12675       /* The type's CU may not be the same as CU.
12676          Ensure TYPE is recorded with CU in die_type_hash.  */
12677       return set_die_type (die, type, cu);
12678     }
12679
12680   type = alloc_type (objfile);
12681   INIT_CPLUS_SPECIFIC (type);
12682
12683   name = dwarf2_name (die, cu);
12684   if (name != NULL)
12685     {
12686       if (cu->language == language_cplus
12687           || cu->language == language_java)
12688         {
12689           const char *full_name = dwarf2_full_name (name, die, cu);
12690
12691           /* dwarf2_full_name might have already finished building the DIE's
12692              type.  If so, there is no need to continue.  */
12693           if (get_die_type (die, cu) != NULL)
12694             return get_die_type (die, cu);
12695
12696           TYPE_TAG_NAME (type) = full_name;
12697           if (die->tag == DW_TAG_structure_type
12698               || die->tag == DW_TAG_class_type)
12699             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12700         }
12701       else
12702         {
12703           /* The name is already allocated along with this objfile, so
12704              we don't need to duplicate it for the type.  */
12705           TYPE_TAG_NAME (type) = name;
12706           if (die->tag == DW_TAG_class_type)
12707             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12708         }
12709     }
12710
12711   if (die->tag == DW_TAG_structure_type)
12712     {
12713       TYPE_CODE (type) = TYPE_CODE_STRUCT;
12714     }
12715   else if (die->tag == DW_TAG_union_type)
12716     {
12717       TYPE_CODE (type) = TYPE_CODE_UNION;
12718     }
12719   else
12720     {
12721       TYPE_CODE (type) = TYPE_CODE_CLASS;
12722     }
12723
12724   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
12725     TYPE_DECLARED_CLASS (type) = 1;
12726
12727   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12728   if (attr)
12729     {
12730       TYPE_LENGTH (type) = DW_UNSND (attr);
12731     }
12732   else
12733     {
12734       TYPE_LENGTH (type) = 0;
12735     }
12736
12737   if (producer_is_icc (cu))
12738     {
12739       /* ICC does not output the required DW_AT_declaration
12740          on incomplete types, but gives them a size of zero.  */
12741     }
12742   else
12743     TYPE_STUB_SUPPORTED (type) = 1;
12744
12745   if (die_is_declaration (die, cu))
12746     TYPE_STUB (type) = 1;
12747   else if (attr == NULL && die->child == NULL
12748            && producer_is_realview (cu->producer))
12749     /* RealView does not output the required DW_AT_declaration
12750        on incomplete types.  */
12751     TYPE_STUB (type) = 1;
12752
12753   /* We need to add the type field to the die immediately so we don't
12754      infinitely recurse when dealing with pointers to the structure
12755      type within the structure itself.  */
12756   set_die_type (die, type, cu);
12757
12758   /* set_die_type should be already done.  */
12759   set_descriptive_type (type, die, cu);
12760
12761   return type;
12762 }
12763
12764 /* Finish creating a structure or union type, including filling in
12765    its members and creating a symbol for it.  */
12766
12767 static void
12768 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
12769 {
12770   struct objfile *objfile = cu->objfile;
12771   struct die_info *child_die = die->child;
12772   struct type *type;
12773
12774   type = get_die_type (die, cu);
12775   if (type == NULL)
12776     type = read_structure_type (die, cu);
12777
12778   if (die->child != NULL && ! die_is_declaration (die, cu))
12779     {
12780       struct field_info fi;
12781       struct die_info *child_die;
12782       VEC (symbolp) *template_args = NULL;
12783       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
12784
12785       memset (&fi, 0, sizeof (struct field_info));
12786
12787       child_die = die->child;
12788
12789       while (child_die && child_die->tag)
12790         {
12791           if (child_die->tag == DW_TAG_member
12792               || child_die->tag == DW_TAG_variable)
12793             {
12794               /* NOTE: carlton/2002-11-05: A C++ static data member
12795                  should be a DW_TAG_member that is a declaration, but
12796                  all versions of G++ as of this writing (so through at
12797                  least 3.2.1) incorrectly generate DW_TAG_variable
12798                  tags for them instead.  */
12799               dwarf2_add_field (&fi, child_die, cu);
12800             }
12801           else if (child_die->tag == DW_TAG_subprogram)
12802             {
12803               /* C++ member function.  */
12804               dwarf2_add_member_fn (&fi, child_die, type, cu);
12805             }
12806           else if (child_die->tag == DW_TAG_inheritance)
12807             {
12808               /* C++ base class field.  */
12809               dwarf2_add_field (&fi, child_die, cu);
12810             }
12811           else if (child_die->tag == DW_TAG_typedef)
12812             dwarf2_add_typedef (&fi, child_die, cu);
12813           else if (child_die->tag == DW_TAG_template_type_param
12814                    || child_die->tag == DW_TAG_template_value_param)
12815             {
12816               struct symbol *arg = new_symbol (child_die, NULL, cu);
12817
12818               if (arg != NULL)
12819                 VEC_safe_push (symbolp, template_args, arg);
12820             }
12821
12822           child_die = sibling_die (child_die);
12823         }
12824
12825       /* Attach template arguments to type.  */
12826       if (! VEC_empty (symbolp, template_args))
12827         {
12828           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12829           TYPE_N_TEMPLATE_ARGUMENTS (type)
12830             = VEC_length (symbolp, template_args);
12831           TYPE_TEMPLATE_ARGUMENTS (type)
12832             = obstack_alloc (&objfile->objfile_obstack,
12833                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12834                               * sizeof (struct symbol *)));
12835           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12836                   VEC_address (symbolp, template_args),
12837                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12838                    * sizeof (struct symbol *)));
12839           VEC_free (symbolp, template_args);
12840         }
12841
12842       /* Attach fields and member functions to the type.  */
12843       if (fi.nfields)
12844         dwarf2_attach_fields_to_type (&fi, type, cu);
12845       if (fi.nfnfields)
12846         {
12847           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12848
12849           /* Get the type which refers to the base class (possibly this
12850              class itself) which contains the vtable pointer for the current
12851              class from the DW_AT_containing_type attribute.  This use of
12852              DW_AT_containing_type is a GNU extension.  */
12853
12854           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12855             {
12856               struct type *t = die_containing_type (die, cu);
12857
12858               TYPE_VPTR_BASETYPE (type) = t;
12859               if (type == t)
12860                 {
12861                   int i;
12862
12863                   /* Our own class provides vtbl ptr.  */
12864                   for (i = TYPE_NFIELDS (t) - 1;
12865                        i >= TYPE_N_BASECLASSES (t);
12866                        --i)
12867                     {
12868                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12869
12870                       if (is_vtable_name (fieldname, cu))
12871                         {
12872                           TYPE_VPTR_FIELDNO (type) = i;
12873                           break;
12874                         }
12875                     }
12876
12877                   /* Complain if virtual function table field not found.  */
12878                   if (i < TYPE_N_BASECLASSES (t))
12879                     complaint (&symfile_complaints,
12880                                _("virtual function table pointer "
12881                                  "not found when defining class '%s'"),
12882                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12883                                "");
12884                 }
12885               else
12886                 {
12887                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12888                 }
12889             }
12890           else if (cu->producer
12891                    && strncmp (cu->producer,
12892                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12893             {
12894               /* The IBM XLC compiler does not provide direct indication
12895                  of the containing type, but the vtable pointer is
12896                  always named __vfp.  */
12897
12898               int i;
12899
12900               for (i = TYPE_NFIELDS (type) - 1;
12901                    i >= TYPE_N_BASECLASSES (type);
12902                    --i)
12903                 {
12904                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12905                     {
12906                       TYPE_VPTR_FIELDNO (type) = i;
12907                       TYPE_VPTR_BASETYPE (type) = type;
12908                       break;
12909                     }
12910                 }
12911             }
12912         }
12913
12914       /* Copy fi.typedef_field_list linked list elements content into the
12915          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12916       if (fi.typedef_field_list)
12917         {
12918           int i = fi.typedef_field_list_count;
12919
12920           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12921           TYPE_TYPEDEF_FIELD_ARRAY (type)
12922             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12923           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12924
12925           /* Reverse the list order to keep the debug info elements order.  */
12926           while (--i >= 0)
12927             {
12928               struct typedef_field *dest, *src;
12929
12930               dest = &TYPE_TYPEDEF_FIELD (type, i);
12931               src = &fi.typedef_field_list->field;
12932               fi.typedef_field_list = fi.typedef_field_list->next;
12933               *dest = *src;
12934             }
12935         }
12936
12937       do_cleanups (back_to);
12938
12939       if (HAVE_CPLUS_STRUCT (type))
12940         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12941     }
12942
12943   quirk_gcc_member_function_pointer (type, objfile);
12944
12945   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12946      snapshots) has been known to create a die giving a declaration
12947      for a class that has, as a child, a die giving a definition for a
12948      nested class.  So we have to process our children even if the
12949      current die is a declaration.  Normally, of course, a declaration
12950      won't have any children at all.  */
12951
12952   while (child_die != NULL && child_die->tag)
12953     {
12954       if (child_die->tag == DW_TAG_member
12955           || child_die->tag == DW_TAG_variable
12956           || child_die->tag == DW_TAG_inheritance
12957           || child_die->tag == DW_TAG_template_value_param
12958           || child_die->tag == DW_TAG_template_type_param)
12959         {
12960           /* Do nothing.  */
12961         }
12962       else
12963         process_die (child_die, cu);
12964
12965       child_die = sibling_die (child_die);
12966     }
12967
12968   /* Do not consider external references.  According to the DWARF standard,
12969      these DIEs are identified by the fact that they have no byte_size
12970      attribute, and a declaration attribute.  */
12971   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12972       || !die_is_declaration (die, cu))
12973     new_symbol (die, type, cu);
12974 }
12975
12976 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12977    complete the type's fields yet, or create any symbols.  */
12978
12979 static struct type *
12980 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12981 {
12982   struct objfile *objfile = cu->objfile;
12983   struct type *type;
12984   struct attribute *attr;
12985   const char *name;
12986
12987   /* If the definition of this type lives in .debug_types, read that type.
12988      Don't follow DW_AT_specification though, that will take us back up
12989      the chain and we want to go down.  */
12990   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12991   if (attr)
12992     {
12993       type = get_DW_AT_signature_type (die, attr, cu);
12994
12995       /* The type's CU may not be the same as CU.
12996          Ensure TYPE is recorded with CU in die_type_hash.  */
12997       return set_die_type (die, type, cu);
12998     }
12999
13000   type = alloc_type (objfile);
13001
13002   TYPE_CODE (type) = TYPE_CODE_ENUM;
13003   name = dwarf2_full_name (NULL, die, cu);
13004   if (name != NULL)
13005     TYPE_TAG_NAME (type) = name;
13006
13007   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13008   if (attr)
13009     {
13010       TYPE_LENGTH (type) = DW_UNSND (attr);
13011     }
13012   else
13013     {
13014       TYPE_LENGTH (type) = 0;
13015     }
13016
13017   /* The enumeration DIE can be incomplete.  In Ada, any type can be
13018      declared as private in the package spec, and then defined only
13019      inside the package body.  Such types are known as Taft Amendment
13020      Types.  When another package uses such a type, an incomplete DIE
13021      may be generated by the compiler.  */
13022   if (die_is_declaration (die, cu))
13023     TYPE_STUB (type) = 1;
13024
13025   return set_die_type (die, type, cu);
13026 }
13027
13028 /* Given a pointer to a die which begins an enumeration, process all
13029    the dies that define the members of the enumeration, and create the
13030    symbol for the enumeration type.
13031
13032    NOTE: We reverse the order of the element list.  */
13033
13034 static void
13035 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
13036 {
13037   struct type *this_type;
13038
13039   this_type = get_die_type (die, cu);
13040   if (this_type == NULL)
13041     this_type = read_enumeration_type (die, cu);
13042
13043   if (die->child != NULL)
13044     {
13045       struct die_info *child_die;
13046       struct symbol *sym;
13047       struct field *fields = NULL;
13048       int num_fields = 0;
13049       int unsigned_enum = 1;
13050       const char *name;
13051       int flag_enum = 1;
13052       ULONGEST mask = 0;
13053
13054       child_die = die->child;
13055       while (child_die && child_die->tag)
13056         {
13057           if (child_die->tag != DW_TAG_enumerator)
13058             {
13059               process_die (child_die, cu);
13060             }
13061           else
13062             {
13063               name = dwarf2_name (child_die, cu);
13064               if (name)
13065                 {
13066                   sym = new_symbol (child_die, this_type, cu);
13067                   if (SYMBOL_VALUE (sym) < 0)
13068                     {
13069                       unsigned_enum = 0;
13070                       flag_enum = 0;
13071                     }
13072                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
13073                     flag_enum = 0;
13074                   else
13075                     mask |= SYMBOL_VALUE (sym);
13076
13077                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
13078                     {
13079                       fields = (struct field *)
13080                         xrealloc (fields,
13081                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
13082                                   * sizeof (struct field));
13083                     }
13084
13085                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
13086                   FIELD_TYPE (fields[num_fields]) = NULL;
13087                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
13088                   FIELD_BITSIZE (fields[num_fields]) = 0;
13089
13090                   num_fields++;
13091                 }
13092             }
13093
13094           child_die = sibling_die (child_die);
13095         }
13096
13097       if (num_fields)
13098         {
13099           TYPE_NFIELDS (this_type) = num_fields;
13100           TYPE_FIELDS (this_type) = (struct field *)
13101             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
13102           memcpy (TYPE_FIELDS (this_type), fields,
13103                   sizeof (struct field) * num_fields);
13104           xfree (fields);
13105         }
13106       if (unsigned_enum)
13107         TYPE_UNSIGNED (this_type) = 1;
13108       if (flag_enum)
13109         TYPE_FLAG_ENUM (this_type) = 1;
13110     }
13111
13112   /* If we are reading an enum from a .debug_types unit, and the enum
13113      is a declaration, and the enum is not the signatured type in the
13114      unit, then we do not want to add a symbol for it.  Adding a
13115      symbol would in some cases obscure the true definition of the
13116      enum, giving users an incomplete type when the definition is
13117      actually available.  Note that we do not want to do this for all
13118      enums which are just declarations, because C++0x allows forward
13119      enum declarations.  */
13120   if (cu->per_cu->is_debug_types
13121       && die_is_declaration (die, cu))
13122     {
13123       struct signatured_type *sig_type;
13124
13125       sig_type = (struct signatured_type *) cu->per_cu;
13126       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
13127       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
13128         return;
13129     }
13130
13131   new_symbol (die, this_type, cu);
13132 }
13133
13134 /* Extract all information from a DW_TAG_array_type DIE and put it in
13135    the DIE's type field.  For now, this only handles one dimensional
13136    arrays.  */
13137
13138 static struct type *
13139 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
13140 {
13141   struct objfile *objfile = cu->objfile;
13142   struct die_info *child_die;
13143   struct type *type;
13144   struct type *element_type, *range_type, *index_type;
13145   struct type **range_types = NULL;
13146   struct attribute *attr;
13147   int ndim = 0;
13148   struct cleanup *back_to;
13149   const char *name;
13150
13151   element_type = die_type (die, cu);
13152
13153   /* The die_type call above may have already set the type for this DIE.  */
13154   type = get_die_type (die, cu);
13155   if (type)
13156     return type;
13157
13158   /* Irix 6.2 native cc creates array types without children for
13159      arrays with unspecified length.  */
13160   if (die->child == NULL)
13161     {
13162       index_type = objfile_type (objfile)->builtin_int;
13163       range_type = create_range_type (NULL, index_type, 0, -1);
13164       type = create_array_type (NULL, element_type, range_type);
13165       return set_die_type (die, type, cu);
13166     }
13167
13168   back_to = make_cleanup (null_cleanup, NULL);
13169   child_die = die->child;
13170   while (child_die && child_die->tag)
13171     {
13172       if (child_die->tag == DW_TAG_subrange_type)
13173         {
13174           struct type *child_type = read_type_die (child_die, cu);
13175
13176           if (child_type != NULL)
13177             {
13178               /* The range type was succesfully read.  Save it for the
13179                  array type creation.  */
13180               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
13181                 {
13182                   range_types = (struct type **)
13183                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
13184                               * sizeof (struct type *));
13185                   if (ndim == 0)
13186                     make_cleanup (free_current_contents, &range_types);
13187                 }
13188               range_types[ndim++] = child_type;
13189             }
13190         }
13191       child_die = sibling_die (child_die);
13192     }
13193
13194   /* Dwarf2 dimensions are output from left to right, create the
13195      necessary array types in backwards order.  */
13196
13197   type = element_type;
13198
13199   if (read_array_order (die, cu) == DW_ORD_col_major)
13200     {
13201       int i = 0;
13202
13203       while (i < ndim)
13204         type = create_array_type (NULL, type, range_types[i++]);
13205     }
13206   else
13207     {
13208       while (ndim-- > 0)
13209         type = create_array_type (NULL, type, range_types[ndim]);
13210     }
13211
13212   /* Understand Dwarf2 support for vector types (like they occur on
13213      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
13214      array type.  This is not part of the Dwarf2/3 standard yet, but a
13215      custom vendor extension.  The main difference between a regular
13216      array and the vector variant is that vectors are passed by value
13217      to functions.  */
13218   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
13219   if (attr)
13220     make_vector_type (type);
13221
13222   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
13223      implementation may choose to implement triple vectors using this
13224      attribute.  */
13225   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13226   if (attr)
13227     {
13228       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
13229         TYPE_LENGTH (type) = DW_UNSND (attr);
13230       else
13231         complaint (&symfile_complaints,
13232                    _("DW_AT_byte_size for array type smaller "
13233                      "than the total size of elements"));
13234     }
13235
13236   name = dwarf2_name (die, cu);
13237   if (name)
13238     TYPE_NAME (type) = name;
13239
13240   /* Install the type in the die.  */
13241   set_die_type (die, type, cu);
13242
13243   /* set_die_type should be already done.  */
13244   set_descriptive_type (type, die, cu);
13245
13246   do_cleanups (back_to);
13247
13248   return type;
13249 }
13250
13251 static enum dwarf_array_dim_ordering
13252 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
13253 {
13254   struct attribute *attr;
13255
13256   attr = dwarf2_attr (die, DW_AT_ordering, cu);
13257
13258   if (attr) return DW_SND (attr);
13259
13260   /* GNU F77 is a special case, as at 08/2004 array type info is the
13261      opposite order to the dwarf2 specification, but data is still
13262      laid out as per normal fortran.
13263
13264      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
13265      version checking.  */
13266
13267   if (cu->language == language_fortran
13268       && cu->producer && strstr (cu->producer, "GNU F77"))
13269     {
13270       return DW_ORD_row_major;
13271     }
13272
13273   switch (cu->language_defn->la_array_ordering)
13274     {
13275     case array_column_major:
13276       return DW_ORD_col_major;
13277     case array_row_major:
13278     default:
13279       return DW_ORD_row_major;
13280     };
13281 }
13282
13283 /* Extract all information from a DW_TAG_set_type DIE and put it in
13284    the DIE's type field.  */
13285
13286 static struct type *
13287 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
13288 {
13289   struct type *domain_type, *set_type;
13290   struct attribute *attr;
13291
13292   domain_type = die_type (die, cu);
13293
13294   /* The die_type call above may have already set the type for this DIE.  */
13295   set_type = get_die_type (die, cu);
13296   if (set_type)
13297     return set_type;
13298
13299   set_type = create_set_type (NULL, domain_type);
13300
13301   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13302   if (attr)
13303     TYPE_LENGTH (set_type) = DW_UNSND (attr);
13304
13305   return set_die_type (die, set_type, cu);
13306 }
13307
13308 /* A helper for read_common_block that creates a locexpr baton.
13309    SYM is the symbol which we are marking as computed.
13310    COMMON_DIE is the DIE for the common block.
13311    COMMON_LOC is the location expression attribute for the common
13312    block itself.
13313    MEMBER_LOC is the location expression attribute for the particular
13314    member of the common block that we are processing.
13315    CU is the CU from which the above come.  */
13316
13317 static void
13318 mark_common_block_symbol_computed (struct symbol *sym,
13319                                    struct die_info *common_die,
13320                                    struct attribute *common_loc,
13321                                    struct attribute *member_loc,
13322                                    struct dwarf2_cu *cu)
13323 {
13324   struct objfile *objfile = dwarf2_per_objfile->objfile;
13325   struct dwarf2_locexpr_baton *baton;
13326   gdb_byte *ptr;
13327   unsigned int cu_off;
13328   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
13329   LONGEST offset = 0;
13330
13331   gdb_assert (common_loc && member_loc);
13332   gdb_assert (attr_form_is_block (common_loc));
13333   gdb_assert (attr_form_is_block (member_loc)
13334               || attr_form_is_constant (member_loc));
13335
13336   baton = obstack_alloc (&objfile->objfile_obstack,
13337                          sizeof (struct dwarf2_locexpr_baton));
13338   baton->per_cu = cu->per_cu;
13339   gdb_assert (baton->per_cu);
13340
13341   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
13342
13343   if (attr_form_is_constant (member_loc))
13344     {
13345       offset = dwarf2_get_attr_constant_value (member_loc, 0);
13346       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
13347     }
13348   else
13349     baton->size += DW_BLOCK (member_loc)->size;
13350
13351   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
13352   baton->data = ptr;
13353
13354   *ptr++ = DW_OP_call4;
13355   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
13356   store_unsigned_integer (ptr, 4, byte_order, cu_off);
13357   ptr += 4;
13358
13359   if (attr_form_is_constant (member_loc))
13360     {
13361       *ptr++ = DW_OP_addr;
13362       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
13363       ptr += cu->header.addr_size;
13364     }
13365   else
13366     {
13367       /* We have to copy the data here, because DW_OP_call4 will only
13368          use a DW_AT_location attribute.  */
13369       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
13370       ptr += DW_BLOCK (member_loc)->size;
13371     }
13372
13373   *ptr++ = DW_OP_plus;
13374   gdb_assert (ptr - baton->data == baton->size);
13375
13376   SYMBOL_LOCATION_BATON (sym) = baton;
13377   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
13378 }
13379
13380 /* Create appropriate locally-scoped variables for all the
13381    DW_TAG_common_block entries.  Also create a struct common_block
13382    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
13383    is used to sepate the common blocks name namespace from regular
13384    variable names.  */
13385
13386 static void
13387 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
13388 {
13389   struct attribute *attr;
13390
13391   attr = dwarf2_attr (die, DW_AT_location, cu);
13392   if (attr)
13393     {
13394       /* Support the .debug_loc offsets.  */
13395       if (attr_form_is_block (attr))
13396         {
13397           /* Ok.  */
13398         }
13399       else if (attr_form_is_section_offset (attr))
13400         {
13401           dwarf2_complex_location_expr_complaint ();
13402           attr = NULL;
13403         }
13404       else
13405         {
13406           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13407                                                  "common block member");
13408           attr = NULL;
13409         }
13410     }
13411
13412   if (die->child != NULL)
13413     {
13414       struct objfile *objfile = cu->objfile;
13415       struct die_info *child_die;
13416       size_t n_entries = 0, size;
13417       struct common_block *common_block;
13418       struct symbol *sym;
13419
13420       for (child_die = die->child;
13421            child_die && child_die->tag;
13422            child_die = sibling_die (child_die))
13423         ++n_entries;
13424
13425       size = (sizeof (struct common_block)
13426               + (n_entries - 1) * sizeof (struct symbol *));
13427       common_block = obstack_alloc (&objfile->objfile_obstack, size);
13428       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
13429       common_block->n_entries = 0;
13430
13431       for (child_die = die->child;
13432            child_die && child_die->tag;
13433            child_die = sibling_die (child_die))
13434         {
13435           /* Create the symbol in the DW_TAG_common_block block in the current
13436              symbol scope.  */
13437           sym = new_symbol (child_die, NULL, cu);
13438           if (sym != NULL)
13439             {
13440               struct attribute *member_loc;
13441
13442               common_block->contents[common_block->n_entries++] = sym;
13443
13444               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
13445                                         cu);
13446               if (member_loc)
13447                 {
13448                   /* GDB has handled this for a long time, but it is
13449                      not specified by DWARF.  It seems to have been
13450                      emitted by gfortran at least as recently as:
13451                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
13452                   complaint (&symfile_complaints,
13453                              _("Variable in common block has "
13454                                "DW_AT_data_member_location "
13455                                "- DIE at 0x%x [in module %s]"),
13456                              child_die->offset.sect_off,
13457                              objfile_name (cu->objfile));
13458
13459                   if (attr_form_is_section_offset (member_loc))
13460                     dwarf2_complex_location_expr_complaint ();
13461                   else if (attr_form_is_constant (member_loc)
13462                            || attr_form_is_block (member_loc))
13463                     {
13464                       if (attr)
13465                         mark_common_block_symbol_computed (sym, die, attr,
13466                                                            member_loc, cu);
13467                     }
13468                   else
13469                     dwarf2_complex_location_expr_complaint ();
13470                 }
13471             }
13472         }
13473
13474       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
13475       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
13476     }
13477 }
13478
13479 /* Create a type for a C++ namespace.  */
13480
13481 static struct type *
13482 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
13483 {
13484   struct objfile *objfile = cu->objfile;
13485   const char *previous_prefix, *name;
13486   int is_anonymous;
13487   struct type *type;
13488
13489   /* For extensions, reuse the type of the original namespace.  */
13490   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
13491     {
13492       struct die_info *ext_die;
13493       struct dwarf2_cu *ext_cu = cu;
13494
13495       ext_die = dwarf2_extension (die, &ext_cu);
13496       type = read_type_die (ext_die, ext_cu);
13497
13498       /* EXT_CU may not be the same as CU.
13499          Ensure TYPE is recorded with CU in die_type_hash.  */
13500       return set_die_type (die, type, cu);
13501     }
13502
13503   name = namespace_name (die, &is_anonymous, cu);
13504
13505   /* Now build the name of the current namespace.  */
13506
13507   previous_prefix = determine_prefix (die, cu);
13508   if (previous_prefix[0] != '\0')
13509     name = typename_concat (&objfile->objfile_obstack,
13510                             previous_prefix, name, 0, cu);
13511
13512   /* Create the type.  */
13513   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
13514                     objfile);
13515   TYPE_NAME (type) = name;
13516   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13517
13518   return set_die_type (die, type, cu);
13519 }
13520
13521 /* Read a C++ namespace.  */
13522
13523 static void
13524 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
13525 {
13526   struct objfile *objfile = cu->objfile;
13527   int is_anonymous;
13528
13529   /* Add a symbol associated to this if we haven't seen the namespace
13530      before.  Also, add a using directive if it's an anonymous
13531      namespace.  */
13532
13533   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
13534     {
13535       struct type *type;
13536
13537       type = read_type_die (die, cu);
13538       new_symbol (die, type, cu);
13539
13540       namespace_name (die, &is_anonymous, cu);
13541       if (is_anonymous)
13542         {
13543           const char *previous_prefix = determine_prefix (die, cu);
13544
13545           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
13546                                   NULL, NULL, 0, &objfile->objfile_obstack);
13547         }
13548     }
13549
13550   if (die->child != NULL)
13551     {
13552       struct die_info *child_die = die->child;
13553
13554       while (child_die && child_die->tag)
13555         {
13556           process_die (child_die, cu);
13557           child_die = sibling_die (child_die);
13558         }
13559     }
13560 }
13561
13562 /* Read a Fortran module as type.  This DIE can be only a declaration used for
13563    imported module.  Still we need that type as local Fortran "use ... only"
13564    declaration imports depend on the created type in determine_prefix.  */
13565
13566 static struct type *
13567 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
13568 {
13569   struct objfile *objfile = cu->objfile;
13570   const char *module_name;
13571   struct type *type;
13572
13573   module_name = dwarf2_name (die, cu);
13574   if (!module_name)
13575     complaint (&symfile_complaints,
13576                _("DW_TAG_module has no name, offset 0x%x"),
13577                die->offset.sect_off);
13578   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
13579
13580   /* determine_prefix uses TYPE_TAG_NAME.  */
13581   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13582
13583   return set_die_type (die, type, cu);
13584 }
13585
13586 /* Read a Fortran module.  */
13587
13588 static void
13589 read_module (struct die_info *die, struct dwarf2_cu *cu)
13590 {
13591   struct die_info *child_die = die->child;
13592
13593   while (child_die && child_die->tag)
13594     {
13595       process_die (child_die, cu);
13596       child_die = sibling_die (child_die);
13597     }
13598 }
13599
13600 /* Return the name of the namespace represented by DIE.  Set
13601    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
13602    namespace.  */
13603
13604 static const char *
13605 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
13606 {
13607   struct die_info *current_die;
13608   const char *name = NULL;
13609
13610   /* Loop through the extensions until we find a name.  */
13611
13612   for (current_die = die;
13613        current_die != NULL;
13614        current_die = dwarf2_extension (die, &cu))
13615     {
13616       name = dwarf2_name (current_die, cu);
13617       if (name != NULL)
13618         break;
13619     }
13620
13621   /* Is it an anonymous namespace?  */
13622
13623   *is_anonymous = (name == NULL);
13624   if (*is_anonymous)
13625     name = CP_ANONYMOUS_NAMESPACE_STR;
13626
13627   return name;
13628 }
13629
13630 /* Extract all information from a DW_TAG_pointer_type DIE and add to
13631    the user defined type vector.  */
13632
13633 static struct type *
13634 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
13635 {
13636   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
13637   struct comp_unit_head *cu_header = &cu->header;
13638   struct type *type;
13639   struct attribute *attr_byte_size;
13640   struct attribute *attr_address_class;
13641   int byte_size, addr_class;
13642   struct type *target_type;
13643
13644   target_type = die_type (die, cu);
13645
13646   /* The die_type call above may have already set the type for this DIE.  */
13647   type = get_die_type (die, cu);
13648   if (type)
13649     return type;
13650
13651   type = lookup_pointer_type (target_type);
13652
13653   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
13654   if (attr_byte_size)
13655     byte_size = DW_UNSND (attr_byte_size);
13656   else
13657     byte_size = cu_header->addr_size;
13658
13659   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
13660   if (attr_address_class)
13661     addr_class = DW_UNSND (attr_address_class);
13662   else
13663     addr_class = DW_ADDR_none;
13664
13665   /* If the pointer size or address class is different than the
13666      default, create a type variant marked as such and set the
13667      length accordingly.  */
13668   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
13669     {
13670       if (gdbarch_address_class_type_flags_p (gdbarch))
13671         {
13672           int type_flags;
13673
13674           type_flags = gdbarch_address_class_type_flags
13675                          (gdbarch, byte_size, addr_class);
13676           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
13677                       == 0);
13678           type = make_type_with_address_space (type, type_flags);
13679         }
13680       else if (TYPE_LENGTH (type) != byte_size)
13681         {
13682           complaint (&symfile_complaints,
13683                      _("invalid pointer size %d"), byte_size);
13684         }
13685       else
13686         {
13687           /* Should we also complain about unhandled address classes?  */
13688         }
13689     }
13690
13691   TYPE_LENGTH (type) = byte_size;
13692   return set_die_type (die, type, cu);
13693 }
13694
13695 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
13696    the user defined type vector.  */
13697
13698 static struct type *
13699 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
13700 {
13701   struct type *type;
13702   struct type *to_type;
13703   struct type *domain;
13704
13705   to_type = die_type (die, cu);
13706   domain = die_containing_type (die, cu);
13707
13708   /* The calls above may have already set the type for this DIE.  */
13709   type = get_die_type (die, cu);
13710   if (type)
13711     return type;
13712
13713   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
13714     type = lookup_methodptr_type (to_type);
13715   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
13716     {
13717       struct type *new_type = alloc_type (cu->objfile);
13718
13719       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
13720                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
13721                             TYPE_VARARGS (to_type));
13722       type = lookup_methodptr_type (new_type);
13723     }
13724   else
13725     type = lookup_memberptr_type (to_type, domain);
13726
13727   return set_die_type (die, type, cu);
13728 }
13729
13730 /* Extract all information from a DW_TAG_reference_type DIE and add to
13731    the user defined type vector.  */
13732
13733 static struct type *
13734 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
13735 {
13736   struct comp_unit_head *cu_header = &cu->header;
13737   struct type *type, *target_type;
13738   struct attribute *attr;
13739
13740   target_type = die_type (die, cu);
13741
13742   /* The die_type call above may have already set the type for this DIE.  */
13743   type = get_die_type (die, cu);
13744   if (type)
13745     return type;
13746
13747   type = lookup_reference_type (target_type);
13748   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13749   if (attr)
13750     {
13751       TYPE_LENGTH (type) = DW_UNSND (attr);
13752     }
13753   else
13754     {
13755       TYPE_LENGTH (type) = cu_header->addr_size;
13756     }
13757   return set_die_type (die, type, cu);
13758 }
13759
13760 static struct type *
13761 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
13762 {
13763   struct type *base_type, *cv_type;
13764
13765   base_type = die_type (die, cu);
13766
13767   /* The die_type call above may have already set the type for this DIE.  */
13768   cv_type = get_die_type (die, cu);
13769   if (cv_type)
13770     return cv_type;
13771
13772   /* In case the const qualifier is applied to an array type, the element type
13773      is so qualified, not the array type (section 6.7.3 of C99).  */
13774   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
13775     {
13776       struct type *el_type, *inner_array;
13777
13778       base_type = copy_type (base_type);
13779       inner_array = base_type;
13780
13781       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
13782         {
13783           TYPE_TARGET_TYPE (inner_array) =
13784             copy_type (TYPE_TARGET_TYPE (inner_array));
13785           inner_array = TYPE_TARGET_TYPE (inner_array);
13786         }
13787
13788       el_type = TYPE_TARGET_TYPE (inner_array);
13789       TYPE_TARGET_TYPE (inner_array) =
13790         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
13791
13792       return set_die_type (die, base_type, cu);
13793     }
13794
13795   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
13796   return set_die_type (die, cv_type, cu);
13797 }
13798
13799 static struct type *
13800 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
13801 {
13802   struct type *base_type, *cv_type;
13803
13804   base_type = die_type (die, cu);
13805
13806   /* The die_type call above may have already set the type for this DIE.  */
13807   cv_type = get_die_type (die, cu);
13808   if (cv_type)
13809     return cv_type;
13810
13811   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
13812   return set_die_type (die, cv_type, cu);
13813 }
13814
13815 /* Handle DW_TAG_restrict_type.  */
13816
13817 static struct type *
13818 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13819 {
13820   struct type *base_type, *cv_type;
13821
13822   base_type = die_type (die, cu);
13823
13824   /* The die_type call above may have already set the type for this DIE.  */
13825   cv_type = get_die_type (die, cu);
13826   if (cv_type)
13827     return cv_type;
13828
13829   cv_type = make_restrict_type (base_type);
13830   return set_die_type (die, cv_type, cu);
13831 }
13832
13833 /* Extract all information from a DW_TAG_string_type DIE and add to
13834    the user defined type vector.  It isn't really a user defined type,
13835    but it behaves like one, with other DIE's using an AT_user_def_type
13836    attribute to reference it.  */
13837
13838 static struct type *
13839 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13840 {
13841   struct objfile *objfile = cu->objfile;
13842   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13843   struct type *type, *range_type, *index_type, *char_type;
13844   struct attribute *attr;
13845   unsigned int length;
13846
13847   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13848   if (attr)
13849     {
13850       length = DW_UNSND (attr);
13851     }
13852   else
13853     {
13854       /* Check for the DW_AT_byte_size attribute.  */
13855       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13856       if (attr)
13857         {
13858           length = DW_UNSND (attr);
13859         }
13860       else
13861         {
13862           length = 1;
13863         }
13864     }
13865
13866   index_type = objfile_type (objfile)->builtin_int;
13867   range_type = create_range_type (NULL, index_type, 1, length);
13868   char_type = language_string_char_type (cu->language_defn, gdbarch);
13869   type = create_string_type (NULL, char_type, range_type);
13870
13871   return set_die_type (die, type, cu);
13872 }
13873
13874 /* Assuming that DIE corresponds to a function, returns nonzero
13875    if the function is prototyped.  */
13876
13877 static int
13878 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13879 {
13880   struct attribute *attr;
13881
13882   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13883   if (attr && (DW_UNSND (attr) != 0))
13884     return 1;
13885
13886   /* The DWARF standard implies that the DW_AT_prototyped attribute
13887      is only meaninful for C, but the concept also extends to other
13888      languages that allow unprototyped functions (Eg: Objective C).
13889      For all other languages, assume that functions are always
13890      prototyped.  */
13891   if (cu->language != language_c
13892       && cu->language != language_objc
13893       && cu->language != language_opencl)
13894     return 1;
13895
13896   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13897      prototyped and unprototyped functions; default to prototyped,
13898      since that is more common in modern code (and RealView warns
13899      about unprototyped functions).  */
13900   if (producer_is_realview (cu->producer))
13901     return 1;
13902
13903   return 0;
13904 }
13905
13906 /* Handle DIES due to C code like:
13907
13908    struct foo
13909    {
13910    int (*funcp)(int a, long l);
13911    int b;
13912    };
13913
13914    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13915
13916 static struct type *
13917 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13918 {
13919   struct objfile *objfile = cu->objfile;
13920   struct type *type;            /* Type that this function returns.  */
13921   struct type *ftype;           /* Function that returns above type.  */
13922   struct attribute *attr;
13923
13924   type = die_type (die, cu);
13925
13926   /* The die_type call above may have already set the type for this DIE.  */
13927   ftype = get_die_type (die, cu);
13928   if (ftype)
13929     return ftype;
13930
13931   ftype = lookup_function_type (type);
13932
13933   if (prototyped_function_p (die, cu))
13934     TYPE_PROTOTYPED (ftype) = 1;
13935
13936   /* Store the calling convention in the type if it's available in
13937      the subroutine die.  Otherwise set the calling convention to
13938      the default value DW_CC_normal.  */
13939   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13940   if (attr)
13941     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13942   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13943     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13944   else
13945     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13946
13947   /* We need to add the subroutine type to the die immediately so
13948      we don't infinitely recurse when dealing with parameters
13949      declared as the same subroutine type.  */
13950   set_die_type (die, ftype, cu);
13951
13952   if (die->child != NULL)
13953     {
13954       struct type *void_type = objfile_type (objfile)->builtin_void;
13955       struct die_info *child_die;
13956       int nparams, iparams;
13957
13958       /* Count the number of parameters.
13959          FIXME: GDB currently ignores vararg functions, but knows about
13960          vararg member functions.  */
13961       nparams = 0;
13962       child_die = die->child;
13963       while (child_die && child_die->tag)
13964         {
13965           if (child_die->tag == DW_TAG_formal_parameter)
13966             nparams++;
13967           else if (child_die->tag == DW_TAG_unspecified_parameters)
13968             TYPE_VARARGS (ftype) = 1;
13969           child_die = sibling_die (child_die);
13970         }
13971
13972       /* Allocate storage for parameters and fill them in.  */
13973       TYPE_NFIELDS (ftype) = nparams;
13974       TYPE_FIELDS (ftype) = (struct field *)
13975         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13976
13977       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13978          even if we error out during the parameters reading below.  */
13979       for (iparams = 0; iparams < nparams; iparams++)
13980         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13981
13982       iparams = 0;
13983       child_die = die->child;
13984       while (child_die && child_die->tag)
13985         {
13986           if (child_die->tag == DW_TAG_formal_parameter)
13987             {
13988               struct type *arg_type;
13989
13990               /* DWARF version 2 has no clean way to discern C++
13991                  static and non-static member functions.  G++ helps
13992                  GDB by marking the first parameter for non-static
13993                  member functions (which is the this pointer) as
13994                  artificial.  We pass this information to
13995                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13996
13997                  DWARF version 3 added DW_AT_object_pointer, which GCC
13998                  4.5 does not yet generate.  */
13999               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
14000               if (attr)
14001                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
14002               else
14003                 {
14004                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
14005
14006                   /* GCC/43521: In java, the formal parameter
14007                      "this" is sometimes not marked with DW_AT_artificial.  */
14008                   if (cu->language == language_java)
14009                     {
14010                       const char *name = dwarf2_name (child_die, cu);
14011
14012                       if (name && !strcmp (name, "this"))
14013                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
14014                     }
14015                 }
14016               arg_type = die_type (child_die, cu);
14017
14018               /* RealView does not mark THIS as const, which the testsuite
14019                  expects.  GCC marks THIS as const in method definitions,
14020                  but not in the class specifications (GCC PR 43053).  */
14021               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
14022                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
14023                 {
14024                   int is_this = 0;
14025                   struct dwarf2_cu *arg_cu = cu;
14026                   const char *name = dwarf2_name (child_die, cu);
14027
14028                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
14029                   if (attr)
14030                     {
14031                       /* If the compiler emits this, use it.  */
14032                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
14033                         is_this = 1;
14034                     }
14035                   else if (name && strcmp (name, "this") == 0)
14036                     /* Function definitions will have the argument names.  */
14037                     is_this = 1;
14038                   else if (name == NULL && iparams == 0)
14039                     /* Declarations may not have the names, so like
14040                        elsewhere in GDB, assume an artificial first
14041                        argument is "this".  */
14042                     is_this = 1;
14043
14044                   if (is_this)
14045                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
14046                                              arg_type, 0);
14047                 }
14048
14049               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
14050               iparams++;
14051             }
14052           child_die = sibling_die (child_die);
14053         }
14054     }
14055
14056   return ftype;
14057 }
14058
14059 static struct type *
14060 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
14061 {
14062   struct objfile *objfile = cu->objfile;
14063   const char *name = NULL;
14064   struct type *this_type, *target_type;
14065
14066   name = dwarf2_full_name (NULL, die, cu);
14067   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
14068                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
14069   TYPE_NAME (this_type) = name;
14070   set_die_type (die, this_type, cu);
14071   target_type = die_type (die, cu);
14072   if (target_type != this_type)
14073     TYPE_TARGET_TYPE (this_type) = target_type;
14074   else
14075     {
14076       /* Self-referential typedefs are, it seems, not allowed by the DWARF
14077          spec and cause infinite loops in GDB.  */
14078       complaint (&symfile_complaints,
14079                  _("Self-referential DW_TAG_typedef "
14080                    "- DIE at 0x%x [in module %s]"),
14081                  die->offset.sect_off, objfile_name (objfile));
14082       TYPE_TARGET_TYPE (this_type) = NULL;
14083     }
14084   return this_type;
14085 }
14086
14087 /* Find a representation of a given base type and install
14088    it in the TYPE field of the die.  */
14089
14090 static struct type *
14091 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
14092 {
14093   struct objfile *objfile = cu->objfile;
14094   struct type *type;
14095   struct attribute *attr;
14096   int encoding = 0, size = 0;
14097   const char *name;
14098   enum type_code code = TYPE_CODE_INT;
14099   int type_flags = 0;
14100   struct type *target_type = NULL;
14101
14102   attr = dwarf2_attr (die, DW_AT_encoding, cu);
14103   if (attr)
14104     {
14105       encoding = DW_UNSND (attr);
14106     }
14107   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14108   if (attr)
14109     {
14110       size = DW_UNSND (attr);
14111     }
14112   name = dwarf2_name (die, cu);
14113   if (!name)
14114     {
14115       complaint (&symfile_complaints,
14116                  _("DW_AT_name missing from DW_TAG_base_type"));
14117     }
14118
14119   switch (encoding)
14120     {
14121       case DW_ATE_address:
14122         /* Turn DW_ATE_address into a void * pointer.  */
14123         code = TYPE_CODE_PTR;
14124         type_flags |= TYPE_FLAG_UNSIGNED;
14125         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
14126         break;
14127       case DW_ATE_boolean:
14128         code = TYPE_CODE_BOOL;
14129         type_flags |= TYPE_FLAG_UNSIGNED;
14130         break;
14131       case DW_ATE_complex_float:
14132         code = TYPE_CODE_COMPLEX;
14133         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
14134         break;
14135       case DW_ATE_decimal_float:
14136         code = TYPE_CODE_DECFLOAT;
14137         break;
14138       case DW_ATE_float:
14139         code = TYPE_CODE_FLT;
14140         break;
14141       case DW_ATE_signed:
14142         break;
14143       case DW_ATE_unsigned:
14144         type_flags |= TYPE_FLAG_UNSIGNED;
14145         if (cu->language == language_fortran
14146             && name
14147             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
14148           code = TYPE_CODE_CHAR;
14149         break;
14150       case DW_ATE_signed_char:
14151         if (cu->language == language_ada || cu->language == language_m2
14152             || cu->language == language_pascal
14153             || cu->language == language_fortran)
14154           code = TYPE_CODE_CHAR;
14155         break;
14156       case DW_ATE_unsigned_char:
14157         if (cu->language == language_ada || cu->language == language_m2
14158             || cu->language == language_pascal
14159             || cu->language == language_fortran)
14160           code = TYPE_CODE_CHAR;
14161         type_flags |= TYPE_FLAG_UNSIGNED;
14162         break;
14163       case DW_ATE_UTF:
14164         /* We just treat this as an integer and then recognize the
14165            type by name elsewhere.  */
14166         break;
14167
14168       default:
14169         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
14170                    dwarf_type_encoding_name (encoding));
14171         break;
14172     }
14173
14174   type = init_type (code, size, type_flags, NULL, objfile);
14175   TYPE_NAME (type) = name;
14176   TYPE_TARGET_TYPE (type) = target_type;
14177
14178   if (name && strcmp (name, "char") == 0)
14179     TYPE_NOSIGN (type) = 1;
14180
14181   return set_die_type (die, type, cu);
14182 }
14183
14184 /* Read the given DW_AT_subrange DIE.  */
14185
14186 static struct type *
14187 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
14188 {
14189   struct type *base_type, *orig_base_type;
14190   struct type *range_type;
14191   struct attribute *attr;
14192   LONGEST low, high;
14193   int low_default_is_valid;
14194   const char *name;
14195   LONGEST negative_mask;
14196
14197   orig_base_type = die_type (die, cu);
14198   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
14199      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
14200      creating the range type, but we use the result of check_typedef
14201      when examining properties of the type.  */
14202   base_type = check_typedef (orig_base_type);
14203
14204   /* The die_type call above may have already set the type for this DIE.  */
14205   range_type = get_die_type (die, cu);
14206   if (range_type)
14207     return range_type;
14208
14209   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
14210      omitting DW_AT_lower_bound.  */
14211   switch (cu->language)
14212     {
14213     case language_c:
14214     case language_cplus:
14215       low = 0;
14216       low_default_is_valid = 1;
14217       break;
14218     case language_fortran:
14219       low = 1;
14220       low_default_is_valid = 1;
14221       break;
14222     case language_d:
14223     case language_java:
14224     case language_objc:
14225       low = 0;
14226       low_default_is_valid = (cu->header.version >= 4);
14227       break;
14228     case language_ada:
14229     case language_m2:
14230     case language_pascal:
14231       low = 1;
14232       low_default_is_valid = (cu->header.version >= 4);
14233       break;
14234     default:
14235       low = 0;
14236       low_default_is_valid = 0;
14237       break;
14238     }
14239
14240   /* FIXME: For variable sized arrays either of these could be
14241      a variable rather than a constant value.  We'll allow it,
14242      but we don't know how to handle it.  */
14243   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
14244   if (attr)
14245     low = dwarf2_get_attr_constant_value (attr, low);
14246   else if (!low_default_is_valid)
14247     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
14248                                       "- DIE at 0x%x [in module %s]"),
14249                die->offset.sect_off, objfile_name (cu->objfile));
14250
14251   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
14252   if (attr)
14253     {
14254       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
14255         {
14256           /* GCC encodes arrays with unspecified or dynamic length
14257              with a DW_FORM_block1 attribute or a reference attribute.
14258              FIXME: GDB does not yet know how to handle dynamic
14259              arrays properly, treat them as arrays with unspecified
14260              length for now.
14261
14262              FIXME: jimb/2003-09-22: GDB does not really know
14263              how to handle arrays of unspecified length
14264              either; we just represent them as zero-length
14265              arrays.  Choose an appropriate upper bound given
14266              the lower bound we've computed above.  */
14267           high = low - 1;
14268         }
14269       else
14270         high = dwarf2_get_attr_constant_value (attr, 1);
14271     }
14272   else
14273     {
14274       attr = dwarf2_attr (die, DW_AT_count, cu);
14275       if (attr)
14276         {
14277           int count = dwarf2_get_attr_constant_value (attr, 1);
14278           high = low + count - 1;
14279         }
14280       else
14281         {
14282           /* Unspecified array length.  */
14283           high = low - 1;
14284         }
14285     }
14286
14287   /* Dwarf-2 specifications explicitly allows to create subrange types
14288      without specifying a base type.
14289      In that case, the base type must be set to the type of
14290      the lower bound, upper bound or count, in that order, if any of these
14291      three attributes references an object that has a type.
14292      If no base type is found, the Dwarf-2 specifications say that
14293      a signed integer type of size equal to the size of an address should
14294      be used.
14295      For the following C code: `extern char gdb_int [];'
14296      GCC produces an empty range DIE.
14297      FIXME: muller/2010-05-28: Possible references to object for low bound,
14298      high bound or count are not yet handled by this code.  */
14299   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
14300     {
14301       struct objfile *objfile = cu->objfile;
14302       struct gdbarch *gdbarch = get_objfile_arch (objfile);
14303       int addr_size = gdbarch_addr_bit (gdbarch) /8;
14304       struct type *int_type = objfile_type (objfile)->builtin_int;
14305
14306       /* Test "int", "long int", and "long long int" objfile types,
14307          and select the first one having a size above or equal to the
14308          architecture address size.  */
14309       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14310         base_type = int_type;
14311       else
14312         {
14313           int_type = objfile_type (objfile)->builtin_long;
14314           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14315             base_type = int_type;
14316           else
14317             {
14318               int_type = objfile_type (objfile)->builtin_long_long;
14319               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14320                 base_type = int_type;
14321             }
14322         }
14323     }
14324
14325   negative_mask =
14326     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
14327   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
14328     low |= negative_mask;
14329   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
14330     high |= negative_mask;
14331
14332   range_type = create_range_type (NULL, orig_base_type, low, high);
14333
14334   /* Mark arrays with dynamic length at least as an array of unspecified
14335      length.  GDB could check the boundary but before it gets implemented at
14336      least allow accessing the array elements.  */
14337   if (attr && attr_form_is_block (attr))
14338     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14339
14340   /* Ada expects an empty array on no boundary attributes.  */
14341   if (attr == NULL && cu->language != language_ada)
14342     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14343
14344   name = dwarf2_name (die, cu);
14345   if (name)
14346     TYPE_NAME (range_type) = name;
14347
14348   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14349   if (attr)
14350     TYPE_LENGTH (range_type) = DW_UNSND (attr);
14351
14352   set_die_type (die, range_type, cu);
14353
14354   /* set_die_type should be already done.  */
14355   set_descriptive_type (range_type, die, cu);
14356
14357   return range_type;
14358 }
14359
14360 static struct type *
14361 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
14362 {
14363   struct type *type;
14364
14365   /* For now, we only support the C meaning of an unspecified type: void.  */
14366
14367   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
14368   TYPE_NAME (type) = dwarf2_name (die, cu);
14369
14370   return set_die_type (die, type, cu);
14371 }
14372
14373 /* Read a single die and all its descendents.  Set the die's sibling
14374    field to NULL; set other fields in the die correctly, and set all
14375    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
14376    location of the info_ptr after reading all of those dies.  PARENT
14377    is the parent of the die in question.  */
14378
14379 static struct die_info *
14380 read_die_and_children (const struct die_reader_specs *reader,
14381                        const gdb_byte *info_ptr,
14382                        const gdb_byte **new_info_ptr,
14383                        struct die_info *parent)
14384 {
14385   struct die_info *die;
14386   const gdb_byte *cur_ptr;
14387   int has_children;
14388
14389   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
14390   if (die == NULL)
14391     {
14392       *new_info_ptr = cur_ptr;
14393       return NULL;
14394     }
14395   store_in_ref_table (die, reader->cu);
14396
14397   if (has_children)
14398     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
14399   else
14400     {
14401       die->child = NULL;
14402       *new_info_ptr = cur_ptr;
14403     }
14404
14405   die->sibling = NULL;
14406   die->parent = parent;
14407   return die;
14408 }
14409
14410 /* Read a die, all of its descendents, and all of its siblings; set
14411    all of the fields of all of the dies correctly.  Arguments are as
14412    in read_die_and_children.  */
14413
14414 static struct die_info *
14415 read_die_and_siblings_1 (const struct die_reader_specs *reader,
14416                          const gdb_byte *info_ptr,
14417                          const gdb_byte **new_info_ptr,
14418                          struct die_info *parent)
14419 {
14420   struct die_info *first_die, *last_sibling;
14421   const gdb_byte *cur_ptr;
14422
14423   cur_ptr = info_ptr;
14424   first_die = last_sibling = NULL;
14425
14426   while (1)
14427     {
14428       struct die_info *die
14429         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
14430
14431       if (die == NULL)
14432         {
14433           *new_info_ptr = cur_ptr;
14434           return first_die;
14435         }
14436
14437       if (!first_die)
14438         first_die = die;
14439       else
14440         last_sibling->sibling = die;
14441
14442       last_sibling = die;
14443     }
14444 }
14445
14446 /* Read a die, all of its descendents, and all of its siblings; set
14447    all of the fields of all of the dies correctly.  Arguments are as
14448    in read_die_and_children.
14449    This the main entry point for reading a DIE and all its children.  */
14450
14451 static struct die_info *
14452 read_die_and_siblings (const struct die_reader_specs *reader,
14453                        const gdb_byte *info_ptr,
14454                        const gdb_byte **new_info_ptr,
14455                        struct die_info *parent)
14456 {
14457   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
14458                                                   new_info_ptr, parent);
14459
14460   if (dwarf2_die_debug)
14461     {
14462       fprintf_unfiltered (gdb_stdlog,
14463                           "Read die from %s@0x%x of %s:\n",
14464                           get_section_name (reader->die_section),
14465                           (unsigned) (info_ptr - reader->die_section->buffer),
14466                           bfd_get_filename (reader->abfd));
14467       dump_die (die, dwarf2_die_debug);
14468     }
14469
14470   return die;
14471 }
14472
14473 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
14474    attributes.
14475    The caller is responsible for filling in the extra attributes
14476    and updating (*DIEP)->num_attrs.
14477    Set DIEP to point to a newly allocated die with its information,
14478    except for its child, sibling, and parent fields.
14479    Set HAS_CHILDREN to tell whether the die has children or not.  */
14480
14481 static const gdb_byte *
14482 read_full_die_1 (const struct die_reader_specs *reader,
14483                  struct die_info **diep, const gdb_byte *info_ptr,
14484                  int *has_children, int num_extra_attrs)
14485 {
14486   unsigned int abbrev_number, bytes_read, i;
14487   sect_offset offset;
14488   struct abbrev_info *abbrev;
14489   struct die_info *die;
14490   struct dwarf2_cu *cu = reader->cu;
14491   bfd *abfd = reader->abfd;
14492
14493   offset.sect_off = info_ptr - reader->buffer;
14494   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14495   info_ptr += bytes_read;
14496   if (!abbrev_number)
14497     {
14498       *diep = NULL;
14499       *has_children = 0;
14500       return info_ptr;
14501     }
14502
14503   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
14504   if (!abbrev)
14505     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
14506            abbrev_number,
14507            bfd_get_filename (abfd));
14508
14509   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
14510   die->offset = offset;
14511   die->tag = abbrev->tag;
14512   die->abbrev = abbrev_number;
14513
14514   /* Make the result usable.
14515      The caller needs to update num_attrs after adding the extra
14516      attributes.  */
14517   die->num_attrs = abbrev->num_attrs;
14518
14519   for (i = 0; i < abbrev->num_attrs; ++i)
14520     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
14521                                info_ptr);
14522
14523   *diep = die;
14524   *has_children = abbrev->has_children;
14525   return info_ptr;
14526 }
14527
14528 /* Read a die and all its attributes.
14529    Set DIEP to point to a newly allocated die with its information,
14530    except for its child, sibling, and parent fields.
14531    Set HAS_CHILDREN to tell whether the die has children or not.  */
14532
14533 static const gdb_byte *
14534 read_full_die (const struct die_reader_specs *reader,
14535                struct die_info **diep, const gdb_byte *info_ptr,
14536                int *has_children)
14537 {
14538   const gdb_byte *result;
14539
14540   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
14541
14542   if (dwarf2_die_debug)
14543     {
14544       fprintf_unfiltered (gdb_stdlog,
14545                           "Read die from %s@0x%x of %s:\n",
14546                           get_section_name (reader->die_section),
14547                           (unsigned) (info_ptr - reader->die_section->buffer),
14548                           bfd_get_filename (reader->abfd));
14549       dump_die (*diep, dwarf2_die_debug);
14550     }
14551
14552   return result;
14553 }
14554 \f
14555 /* Abbreviation tables.
14556
14557    In DWARF version 2, the description of the debugging information is
14558    stored in a separate .debug_abbrev section.  Before we read any
14559    dies from a section we read in all abbreviations and install them
14560    in a hash table.  */
14561
14562 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
14563
14564 static struct abbrev_info *
14565 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
14566 {
14567   struct abbrev_info *abbrev;
14568
14569   abbrev = (struct abbrev_info *)
14570     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
14571   memset (abbrev, 0, sizeof (struct abbrev_info));
14572   return abbrev;
14573 }
14574
14575 /* Add an abbreviation to the table.  */
14576
14577 static void
14578 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
14579                          unsigned int abbrev_number,
14580                          struct abbrev_info *abbrev)
14581 {
14582   unsigned int hash_number;
14583
14584   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14585   abbrev->next = abbrev_table->abbrevs[hash_number];
14586   abbrev_table->abbrevs[hash_number] = abbrev;
14587 }
14588
14589 /* Look up an abbrev in the table.
14590    Returns NULL if the abbrev is not found.  */
14591
14592 static struct abbrev_info *
14593 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
14594                             unsigned int abbrev_number)
14595 {
14596   unsigned int hash_number;
14597   struct abbrev_info *abbrev;
14598
14599   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14600   abbrev = abbrev_table->abbrevs[hash_number];
14601
14602   while (abbrev)
14603     {
14604       if (abbrev->number == abbrev_number)
14605         return abbrev;
14606       abbrev = abbrev->next;
14607     }
14608   return NULL;
14609 }
14610
14611 /* Read in an abbrev table.  */
14612
14613 static struct abbrev_table *
14614 abbrev_table_read_table (struct dwarf2_section_info *section,
14615                          sect_offset offset)
14616 {
14617   struct objfile *objfile = dwarf2_per_objfile->objfile;
14618   bfd *abfd = get_section_bfd_owner (section);
14619   struct abbrev_table *abbrev_table;
14620   const gdb_byte *abbrev_ptr;
14621   struct abbrev_info *cur_abbrev;
14622   unsigned int abbrev_number, bytes_read, abbrev_name;
14623   unsigned int abbrev_form;
14624   struct attr_abbrev *cur_attrs;
14625   unsigned int allocated_attrs;
14626
14627   abbrev_table = XMALLOC (struct abbrev_table);
14628   abbrev_table->offset = offset;
14629   obstack_init (&abbrev_table->abbrev_obstack);
14630   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
14631                                          (ABBREV_HASH_SIZE
14632                                           * sizeof (struct abbrev_info *)));
14633   memset (abbrev_table->abbrevs, 0,
14634           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
14635
14636   dwarf2_read_section (objfile, section);
14637   abbrev_ptr = section->buffer + offset.sect_off;
14638   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14639   abbrev_ptr += bytes_read;
14640
14641   allocated_attrs = ATTR_ALLOC_CHUNK;
14642   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
14643
14644   /* Loop until we reach an abbrev number of 0.  */
14645   while (abbrev_number)
14646     {
14647       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
14648
14649       /* read in abbrev header */
14650       cur_abbrev->number = abbrev_number;
14651       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14652       abbrev_ptr += bytes_read;
14653       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
14654       abbrev_ptr += 1;
14655
14656       /* now read in declarations */
14657       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14658       abbrev_ptr += bytes_read;
14659       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14660       abbrev_ptr += bytes_read;
14661       while (abbrev_name)
14662         {
14663           if (cur_abbrev->num_attrs == allocated_attrs)
14664             {
14665               allocated_attrs += ATTR_ALLOC_CHUNK;
14666               cur_attrs
14667                 = xrealloc (cur_attrs, (allocated_attrs
14668                                         * sizeof (struct attr_abbrev)));
14669             }
14670
14671           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
14672           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
14673           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14674           abbrev_ptr += bytes_read;
14675           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14676           abbrev_ptr += bytes_read;
14677         }
14678
14679       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
14680                                          (cur_abbrev->num_attrs
14681                                           * sizeof (struct attr_abbrev)));
14682       memcpy (cur_abbrev->attrs, cur_attrs,
14683               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
14684
14685       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
14686
14687       /* Get next abbreviation.
14688          Under Irix6 the abbreviations for a compilation unit are not
14689          always properly terminated with an abbrev number of 0.
14690          Exit loop if we encounter an abbreviation which we have
14691          already read (which means we are about to read the abbreviations
14692          for the next compile unit) or if the end of the abbreviation
14693          table is reached.  */
14694       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
14695         break;
14696       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14697       abbrev_ptr += bytes_read;
14698       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
14699         break;
14700     }
14701
14702   xfree (cur_attrs);
14703   return abbrev_table;
14704 }
14705
14706 /* Free the resources held by ABBREV_TABLE.  */
14707
14708 static void
14709 abbrev_table_free (struct abbrev_table *abbrev_table)
14710 {
14711   obstack_free (&abbrev_table->abbrev_obstack, NULL);
14712   xfree (abbrev_table);
14713 }
14714
14715 /* Same as abbrev_table_free but as a cleanup.
14716    We pass in a pointer to the pointer to the table so that we can
14717    set the pointer to NULL when we're done.  It also simplifies
14718    build_type_unit_groups.  */
14719
14720 static void
14721 abbrev_table_free_cleanup (void *table_ptr)
14722 {
14723   struct abbrev_table **abbrev_table_ptr = table_ptr;
14724
14725   if (*abbrev_table_ptr != NULL)
14726     abbrev_table_free (*abbrev_table_ptr);
14727   *abbrev_table_ptr = NULL;
14728 }
14729
14730 /* Read the abbrev table for CU from ABBREV_SECTION.  */
14731
14732 static void
14733 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
14734                      struct dwarf2_section_info *abbrev_section)
14735 {
14736   cu->abbrev_table =
14737     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
14738 }
14739
14740 /* Release the memory used by the abbrev table for a compilation unit.  */
14741
14742 static void
14743 dwarf2_free_abbrev_table (void *ptr_to_cu)
14744 {
14745   struct dwarf2_cu *cu = ptr_to_cu;
14746
14747   if (cu->abbrev_table != NULL)
14748     abbrev_table_free (cu->abbrev_table);
14749   /* Set this to NULL so that we SEGV if we try to read it later,
14750      and also because free_comp_unit verifies this is NULL.  */
14751   cu->abbrev_table = NULL;
14752 }
14753 \f
14754 /* Returns nonzero if TAG represents a type that we might generate a partial
14755    symbol for.  */
14756
14757 static int
14758 is_type_tag_for_partial (int tag)
14759 {
14760   switch (tag)
14761     {
14762 #if 0
14763     /* Some types that would be reasonable to generate partial symbols for,
14764        that we don't at present.  */
14765     case DW_TAG_array_type:
14766     case DW_TAG_file_type:
14767     case DW_TAG_ptr_to_member_type:
14768     case DW_TAG_set_type:
14769     case DW_TAG_string_type:
14770     case DW_TAG_subroutine_type:
14771 #endif
14772     case DW_TAG_base_type:
14773     case DW_TAG_class_type:
14774     case DW_TAG_interface_type:
14775     case DW_TAG_enumeration_type:
14776     case DW_TAG_structure_type:
14777     case DW_TAG_subrange_type:
14778     case DW_TAG_typedef:
14779     case DW_TAG_union_type:
14780       return 1;
14781     default:
14782       return 0;
14783     }
14784 }
14785
14786 /* Load all DIEs that are interesting for partial symbols into memory.  */
14787
14788 static struct partial_die_info *
14789 load_partial_dies (const struct die_reader_specs *reader,
14790                    const gdb_byte *info_ptr, int building_psymtab)
14791 {
14792   struct dwarf2_cu *cu = reader->cu;
14793   struct objfile *objfile = cu->objfile;
14794   struct partial_die_info *part_die;
14795   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
14796   struct abbrev_info *abbrev;
14797   unsigned int bytes_read;
14798   unsigned int load_all = 0;
14799   int nesting_level = 1;
14800
14801   parent_die = NULL;
14802   last_die = NULL;
14803
14804   gdb_assert (cu->per_cu != NULL);
14805   if (cu->per_cu->load_all_dies)
14806     load_all = 1;
14807
14808   cu->partial_dies
14809     = htab_create_alloc_ex (cu->header.length / 12,
14810                             partial_die_hash,
14811                             partial_die_eq,
14812                             NULL,
14813                             &cu->comp_unit_obstack,
14814                             hashtab_obstack_allocate,
14815                             dummy_obstack_deallocate);
14816
14817   part_die = obstack_alloc (&cu->comp_unit_obstack,
14818                             sizeof (struct partial_die_info));
14819
14820   while (1)
14821     {
14822       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14823
14824       /* A NULL abbrev means the end of a series of children.  */
14825       if (abbrev == NULL)
14826         {
14827           if (--nesting_level == 0)
14828             {
14829               /* PART_DIE was probably the last thing allocated on the
14830                  comp_unit_obstack, so we could call obstack_free
14831                  here.  We don't do that because the waste is small,
14832                  and will be cleaned up when we're done with this
14833                  compilation unit.  This way, we're also more robust
14834                  against other users of the comp_unit_obstack.  */
14835               return first_die;
14836             }
14837           info_ptr += bytes_read;
14838           last_die = parent_die;
14839           parent_die = parent_die->die_parent;
14840           continue;
14841         }
14842
14843       /* Check for template arguments.  We never save these; if
14844          they're seen, we just mark the parent, and go on our way.  */
14845       if (parent_die != NULL
14846           && cu->language == language_cplus
14847           && (abbrev->tag == DW_TAG_template_type_param
14848               || abbrev->tag == DW_TAG_template_value_param))
14849         {
14850           parent_die->has_template_arguments = 1;
14851
14852           if (!load_all)
14853             {
14854               /* We don't need a partial DIE for the template argument.  */
14855               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14856               continue;
14857             }
14858         }
14859
14860       /* We only recurse into c++ subprograms looking for template arguments.
14861          Skip their other children.  */
14862       if (!load_all
14863           && cu->language == language_cplus
14864           && parent_die != NULL
14865           && parent_die->tag == DW_TAG_subprogram)
14866         {
14867           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14868           continue;
14869         }
14870
14871       /* Check whether this DIE is interesting enough to save.  Normally
14872          we would not be interested in members here, but there may be
14873          later variables referencing them via DW_AT_specification (for
14874          static members).  */
14875       if (!load_all
14876           && !is_type_tag_for_partial (abbrev->tag)
14877           && abbrev->tag != DW_TAG_constant
14878           && abbrev->tag != DW_TAG_enumerator
14879           && abbrev->tag != DW_TAG_subprogram
14880           && abbrev->tag != DW_TAG_lexical_block
14881           && abbrev->tag != DW_TAG_variable
14882           && abbrev->tag != DW_TAG_namespace
14883           && abbrev->tag != DW_TAG_module
14884           && abbrev->tag != DW_TAG_member
14885           && abbrev->tag != DW_TAG_imported_unit)
14886         {
14887           /* Otherwise we skip to the next sibling, if any.  */
14888           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14889           continue;
14890         }
14891
14892       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14893                                    info_ptr);
14894
14895       /* This two-pass algorithm for processing partial symbols has a
14896          high cost in cache pressure.  Thus, handle some simple cases
14897          here which cover the majority of C partial symbols.  DIEs
14898          which neither have specification tags in them, nor could have
14899          specification tags elsewhere pointing at them, can simply be
14900          processed and discarded.
14901
14902          This segment is also optional; scan_partial_symbols and
14903          add_partial_symbol will handle these DIEs if we chain
14904          them in normally.  When compilers which do not emit large
14905          quantities of duplicate debug information are more common,
14906          this code can probably be removed.  */
14907
14908       /* Any complete simple types at the top level (pretty much all
14909          of them, for a language without namespaces), can be processed
14910          directly.  */
14911       if (parent_die == NULL
14912           && part_die->has_specification == 0
14913           && part_die->is_declaration == 0
14914           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14915               || part_die->tag == DW_TAG_base_type
14916               || part_die->tag == DW_TAG_subrange_type))
14917         {
14918           if (building_psymtab && part_die->name != NULL)
14919             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14920                                  VAR_DOMAIN, LOC_TYPEDEF,
14921                                  &objfile->static_psymbols,
14922                                  0, (CORE_ADDR) 0, cu->language, objfile);
14923           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14924           continue;
14925         }
14926
14927       /* The exception for DW_TAG_typedef with has_children above is
14928          a workaround of GCC PR debug/47510.  In the case of this complaint
14929          type_name_no_tag_or_error will error on such types later.
14930
14931          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14932          it could not find the child DIEs referenced later, this is checked
14933          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14934
14935       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14936         complaint (&symfile_complaints,
14937                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14938                      "- DIE at 0x%x [in module %s]"),
14939                    part_die->offset.sect_off, objfile_name (objfile));
14940
14941       /* If we're at the second level, and we're an enumerator, and
14942          our parent has no specification (meaning possibly lives in a
14943          namespace elsewhere), then we can add the partial symbol now
14944          instead of queueing it.  */
14945       if (part_die->tag == DW_TAG_enumerator
14946           && parent_die != NULL
14947           && parent_die->die_parent == NULL
14948           && parent_die->tag == DW_TAG_enumeration_type
14949           && parent_die->has_specification == 0)
14950         {
14951           if (part_die->name == NULL)
14952             complaint (&symfile_complaints,
14953                        _("malformed enumerator DIE ignored"));
14954           else if (building_psymtab)
14955             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14956                                  VAR_DOMAIN, LOC_CONST,
14957                                  (cu->language == language_cplus
14958                                   || cu->language == language_java)
14959                                  ? &objfile->global_psymbols
14960                                  : &objfile->static_psymbols,
14961                                  0, (CORE_ADDR) 0, cu->language, objfile);
14962
14963           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14964           continue;
14965         }
14966
14967       /* We'll save this DIE so link it in.  */
14968       part_die->die_parent = parent_die;
14969       part_die->die_sibling = NULL;
14970       part_die->die_child = NULL;
14971
14972       if (last_die && last_die == parent_die)
14973         last_die->die_child = part_die;
14974       else if (last_die)
14975         last_die->die_sibling = part_die;
14976
14977       last_die = part_die;
14978
14979       if (first_die == NULL)
14980         first_die = part_die;
14981
14982       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14983          find interesting need to be in the hash table, because we
14984          also have the parent/sibling/child chains; only those that we
14985          might refer to by offset later during partial symbol reading.
14986
14987          For now this means things that might have be the target of a
14988          DW_AT_specification, DW_AT_abstract_origin, or
14989          DW_AT_extension.  DW_AT_extension will refer only to
14990          namespaces; DW_AT_abstract_origin refers to functions (and
14991          many things under the function DIE, but we do not recurse
14992          into function DIEs during partial symbol reading) and
14993          possibly variables as well; DW_AT_specification refers to
14994          declarations.  Declarations ought to have the DW_AT_declaration
14995          flag.  It happens that GCC forgets to put it in sometimes, but
14996          only for functions, not for types.
14997
14998          Adding more things than necessary to the hash table is harmless
14999          except for the performance cost.  Adding too few will result in
15000          wasted time in find_partial_die, when we reread the compilation
15001          unit with load_all_dies set.  */
15002
15003       if (load_all
15004           || abbrev->tag == DW_TAG_constant
15005           || abbrev->tag == DW_TAG_subprogram
15006           || abbrev->tag == DW_TAG_variable
15007           || abbrev->tag == DW_TAG_namespace
15008           || part_die->is_declaration)
15009         {
15010           void **slot;
15011
15012           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
15013                                            part_die->offset.sect_off, INSERT);
15014           *slot = part_die;
15015         }
15016
15017       part_die = obstack_alloc (&cu->comp_unit_obstack,
15018                                 sizeof (struct partial_die_info));
15019
15020       /* For some DIEs we want to follow their children (if any).  For C
15021          we have no reason to follow the children of structures; for other
15022          languages we have to, so that we can get at method physnames
15023          to infer fully qualified class names, for DW_AT_specification,
15024          and for C++ template arguments.  For C++, we also look one level
15025          inside functions to find template arguments (if the name of the
15026          function does not already contain the template arguments).
15027
15028          For Ada, we need to scan the children of subprograms and lexical
15029          blocks as well because Ada allows the definition of nested
15030          entities that could be interesting for the debugger, such as
15031          nested subprograms for instance.  */
15032       if (last_die->has_children
15033           && (load_all
15034               || last_die->tag == DW_TAG_namespace
15035               || last_die->tag == DW_TAG_module
15036               || last_die->tag == DW_TAG_enumeration_type
15037               || (cu->language == language_cplus
15038                   && last_die->tag == DW_TAG_subprogram
15039                   && (last_die->name == NULL
15040                       || strchr (last_die->name, '<') == NULL))
15041               || (cu->language != language_c
15042                   && (last_die->tag == DW_TAG_class_type
15043                       || last_die->tag == DW_TAG_interface_type
15044                       || last_die->tag == DW_TAG_structure_type
15045                       || last_die->tag == DW_TAG_union_type))
15046               || (cu->language == language_ada
15047                   && (last_die->tag == DW_TAG_subprogram
15048                       || last_die->tag == DW_TAG_lexical_block))))
15049         {
15050           nesting_level++;
15051           parent_die = last_die;
15052           continue;
15053         }
15054
15055       /* Otherwise we skip to the next sibling, if any.  */
15056       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
15057
15058       /* Back to the top, do it again.  */
15059     }
15060 }
15061
15062 /* Read a minimal amount of information into the minimal die structure.  */
15063
15064 static const gdb_byte *
15065 read_partial_die (const struct die_reader_specs *reader,
15066                   struct partial_die_info *part_die,
15067                   struct abbrev_info *abbrev, unsigned int abbrev_len,
15068                   const gdb_byte *info_ptr)
15069 {
15070   struct dwarf2_cu *cu = reader->cu;
15071   struct objfile *objfile = cu->objfile;
15072   const gdb_byte *buffer = reader->buffer;
15073   unsigned int i;
15074   struct attribute attr;
15075   int has_low_pc_attr = 0;
15076   int has_high_pc_attr = 0;
15077   int high_pc_relative = 0;
15078
15079   memset (part_die, 0, sizeof (struct partial_die_info));
15080
15081   part_die->offset.sect_off = info_ptr - buffer;
15082
15083   info_ptr += abbrev_len;
15084
15085   if (abbrev == NULL)
15086     return info_ptr;
15087
15088   part_die->tag = abbrev->tag;
15089   part_die->has_children = abbrev->has_children;
15090
15091   for (i = 0; i < abbrev->num_attrs; ++i)
15092     {
15093       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
15094
15095       /* Store the data if it is of an attribute we want to keep in a
15096          partial symbol table.  */
15097       switch (attr.name)
15098         {
15099         case DW_AT_name:
15100           switch (part_die->tag)
15101             {
15102             case DW_TAG_compile_unit:
15103             case DW_TAG_partial_unit:
15104             case DW_TAG_type_unit:
15105               /* Compilation units have a DW_AT_name that is a filename, not
15106                  a source language identifier.  */
15107             case DW_TAG_enumeration_type:
15108             case DW_TAG_enumerator:
15109               /* These tags always have simple identifiers already; no need
15110                  to canonicalize them.  */
15111               part_die->name = DW_STRING (&attr);
15112               break;
15113             default:
15114               part_die->name
15115                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
15116                                             &objfile->objfile_obstack);
15117               break;
15118             }
15119           break;
15120         case DW_AT_linkage_name:
15121         case DW_AT_MIPS_linkage_name:
15122           /* Note that both forms of linkage name might appear.  We
15123              assume they will be the same, and we only store the last
15124              one we see.  */
15125           if (cu->language == language_ada)
15126             part_die->name = DW_STRING (&attr);
15127           part_die->linkage_name = DW_STRING (&attr);
15128           break;
15129         case DW_AT_low_pc:
15130           has_low_pc_attr = 1;
15131           part_die->lowpc = DW_ADDR (&attr);
15132           break;
15133         case DW_AT_high_pc:
15134           has_high_pc_attr = 1;
15135           if (attr.form == DW_FORM_addr
15136               || attr.form == DW_FORM_GNU_addr_index)
15137             part_die->highpc = DW_ADDR (&attr);
15138           else
15139             {
15140               high_pc_relative = 1;
15141               part_die->highpc = DW_UNSND (&attr);
15142             }
15143           break;
15144         case DW_AT_location:
15145           /* Support the .debug_loc offsets.  */
15146           if (attr_form_is_block (&attr))
15147             {
15148                part_die->d.locdesc = DW_BLOCK (&attr);
15149             }
15150           else if (attr_form_is_section_offset (&attr))
15151             {
15152               dwarf2_complex_location_expr_complaint ();
15153             }
15154           else
15155             {
15156               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15157                                                      "partial symbol information");
15158             }
15159           break;
15160         case DW_AT_external:
15161           part_die->is_external = DW_UNSND (&attr);
15162           break;
15163         case DW_AT_declaration:
15164           part_die->is_declaration = DW_UNSND (&attr);
15165           break;
15166         case DW_AT_type:
15167           part_die->has_type = 1;
15168           break;
15169         case DW_AT_abstract_origin:
15170         case DW_AT_specification:
15171         case DW_AT_extension:
15172           part_die->has_specification = 1;
15173           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
15174           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15175                                    || cu->per_cu->is_dwz);
15176           break;
15177         case DW_AT_sibling:
15178           /* Ignore absolute siblings, they might point outside of
15179              the current compile unit.  */
15180           if (attr.form == DW_FORM_ref_addr)
15181             complaint (&symfile_complaints,
15182                        _("ignoring absolute DW_AT_sibling"));
15183           else
15184             {
15185               unsigned int off = dwarf2_get_ref_die_offset (&attr).sect_off;
15186               const gdb_byte *sibling_ptr = buffer + off;
15187
15188               if (sibling_ptr < info_ptr)
15189                 complaint (&symfile_complaints,
15190                            _("DW_AT_sibling points backwards"));
15191               else
15192                 part_die->sibling = sibling_ptr;
15193             }
15194           break;
15195         case DW_AT_byte_size:
15196           part_die->has_byte_size = 1;
15197           break;
15198         case DW_AT_calling_convention:
15199           /* DWARF doesn't provide a way to identify a program's source-level
15200              entry point.  DW_AT_calling_convention attributes are only meant
15201              to describe functions' calling conventions.
15202
15203              However, because it's a necessary piece of information in
15204              Fortran, and because DW_CC_program is the only piece of debugging
15205              information whose definition refers to a 'main program' at all,
15206              several compilers have begun marking Fortran main programs with
15207              DW_CC_program --- even when those functions use the standard
15208              calling conventions.
15209
15210              So until DWARF specifies a way to provide this information and
15211              compilers pick up the new representation, we'll support this
15212              practice.  */
15213           if (DW_UNSND (&attr) == DW_CC_program
15214               && cu->language == language_fortran)
15215             {
15216               set_main_name (part_die->name);
15217
15218               /* As this DIE has a static linkage the name would be difficult
15219                  to look up later.  */
15220               language_of_main = language_fortran;
15221             }
15222           break;
15223         case DW_AT_inline:
15224           if (DW_UNSND (&attr) == DW_INL_inlined
15225               || DW_UNSND (&attr) == DW_INL_declared_inlined)
15226             part_die->may_be_inlined = 1;
15227           break;
15228
15229         case DW_AT_import:
15230           if (part_die->tag == DW_TAG_imported_unit)
15231             {
15232               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
15233               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15234                                   || cu->per_cu->is_dwz);
15235             }
15236           break;
15237
15238         default:
15239           break;
15240         }
15241     }
15242
15243   if (high_pc_relative)
15244     part_die->highpc += part_die->lowpc;
15245
15246   if (has_low_pc_attr && has_high_pc_attr)
15247     {
15248       /* When using the GNU linker, .gnu.linkonce. sections are used to
15249          eliminate duplicate copies of functions and vtables and such.
15250          The linker will arbitrarily choose one and discard the others.
15251          The AT_*_pc values for such functions refer to local labels in
15252          these sections.  If the section from that file was discarded, the
15253          labels are not in the output, so the relocs get a value of 0.
15254          If this is a discarded function, mark the pc bounds as invalid,
15255          so that GDB will ignore it.  */
15256       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
15257         {
15258           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15259
15260           complaint (&symfile_complaints,
15261                      _("DW_AT_low_pc %s is zero "
15262                        "for DIE at 0x%x [in module %s]"),
15263                      paddress (gdbarch, part_die->lowpc),
15264                      part_die->offset.sect_off, objfile_name (objfile));
15265         }
15266       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
15267       else if (part_die->lowpc >= part_die->highpc)
15268         {
15269           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15270
15271           complaint (&symfile_complaints,
15272                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
15273                        "for DIE at 0x%x [in module %s]"),
15274                      paddress (gdbarch, part_die->lowpc),
15275                      paddress (gdbarch, part_die->highpc),
15276                      part_die->offset.sect_off, objfile_name (objfile));
15277         }
15278       else
15279         part_die->has_pc_info = 1;
15280     }
15281
15282   return info_ptr;
15283 }
15284
15285 /* Find a cached partial DIE at OFFSET in CU.  */
15286
15287 static struct partial_die_info *
15288 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
15289 {
15290   struct partial_die_info *lookup_die = NULL;
15291   struct partial_die_info part_die;
15292
15293   part_die.offset = offset;
15294   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
15295                                     offset.sect_off);
15296
15297   return lookup_die;
15298 }
15299
15300 /* Find a partial DIE at OFFSET, which may or may not be in CU,
15301    except in the case of .debug_types DIEs which do not reference
15302    outside their CU (they do however referencing other types via
15303    DW_FORM_ref_sig8).  */
15304
15305 static struct partial_die_info *
15306 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
15307 {
15308   struct objfile *objfile = cu->objfile;
15309   struct dwarf2_per_cu_data *per_cu = NULL;
15310   struct partial_die_info *pd = NULL;
15311
15312   if (offset_in_dwz == cu->per_cu->is_dwz
15313       && offset_in_cu_p (&cu->header, offset))
15314     {
15315       pd = find_partial_die_in_comp_unit (offset, cu);
15316       if (pd != NULL)
15317         return pd;
15318       /* We missed recording what we needed.
15319          Load all dies and try again.  */
15320       per_cu = cu->per_cu;
15321     }
15322   else
15323     {
15324       /* TUs don't reference other CUs/TUs (except via type signatures).  */
15325       if (cu->per_cu->is_debug_types)
15326         {
15327           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
15328                    " external reference to offset 0x%lx [in module %s].\n"),
15329                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
15330                  bfd_get_filename (objfile->obfd));
15331         }
15332       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
15333                                                  objfile);
15334
15335       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
15336         load_partial_comp_unit (per_cu);
15337
15338       per_cu->cu->last_used = 0;
15339       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15340     }
15341
15342   /* If we didn't find it, and not all dies have been loaded,
15343      load them all and try again.  */
15344
15345   if (pd == NULL && per_cu->load_all_dies == 0)
15346     {
15347       per_cu->load_all_dies = 1;
15348
15349       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
15350          THIS_CU->cu may already be in use.  So we can't just free it and
15351          replace its DIEs with the ones we read in.  Instead, we leave those
15352          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
15353          and clobber THIS_CU->cu->partial_dies with the hash table for the new
15354          set.  */
15355       load_partial_comp_unit (per_cu);
15356
15357       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15358     }
15359
15360   if (pd == NULL)
15361     internal_error (__FILE__, __LINE__,
15362                     _("could not find partial DIE 0x%x "
15363                       "in cache [from module %s]\n"),
15364                     offset.sect_off, bfd_get_filename (objfile->obfd));
15365   return pd;
15366 }
15367
15368 /* See if we can figure out if the class lives in a namespace.  We do
15369    this by looking for a member function; its demangled name will
15370    contain namespace info, if there is any.  */
15371
15372 static void
15373 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
15374                                   struct dwarf2_cu *cu)
15375 {
15376   /* NOTE: carlton/2003-10-07: Getting the info this way changes
15377      what template types look like, because the demangler
15378      frequently doesn't give the same name as the debug info.  We
15379      could fix this by only using the demangled name to get the
15380      prefix (but see comment in read_structure_type).  */
15381
15382   struct partial_die_info *real_pdi;
15383   struct partial_die_info *child_pdi;
15384
15385   /* If this DIE (this DIE's specification, if any) has a parent, then
15386      we should not do this.  We'll prepend the parent's fully qualified
15387      name when we create the partial symbol.  */
15388
15389   real_pdi = struct_pdi;
15390   while (real_pdi->has_specification)
15391     real_pdi = find_partial_die (real_pdi->spec_offset,
15392                                  real_pdi->spec_is_dwz, cu);
15393
15394   if (real_pdi->die_parent != NULL)
15395     return;
15396
15397   for (child_pdi = struct_pdi->die_child;
15398        child_pdi != NULL;
15399        child_pdi = child_pdi->die_sibling)
15400     {
15401       if (child_pdi->tag == DW_TAG_subprogram
15402           && child_pdi->linkage_name != NULL)
15403         {
15404           char *actual_class_name
15405             = language_class_name_from_physname (cu->language_defn,
15406                                                  child_pdi->linkage_name);
15407           if (actual_class_name != NULL)
15408             {
15409               struct_pdi->name
15410                 = obstack_copy0 (&cu->objfile->objfile_obstack,
15411                                  actual_class_name,
15412                                  strlen (actual_class_name));
15413               xfree (actual_class_name);
15414             }
15415           break;
15416         }
15417     }
15418 }
15419
15420 /* Adjust PART_DIE before generating a symbol for it.  This function
15421    may set the is_external flag or change the DIE's name.  */
15422
15423 static void
15424 fixup_partial_die (struct partial_die_info *part_die,
15425                    struct dwarf2_cu *cu)
15426 {
15427   /* Once we've fixed up a die, there's no point in doing so again.
15428      This also avoids a memory leak if we were to call
15429      guess_partial_die_structure_name multiple times.  */
15430   if (part_die->fixup_called)
15431     return;
15432
15433   /* If we found a reference attribute and the DIE has no name, try
15434      to find a name in the referred to DIE.  */
15435
15436   if (part_die->name == NULL && part_die->has_specification)
15437     {
15438       struct partial_die_info *spec_die;
15439
15440       spec_die = find_partial_die (part_die->spec_offset,
15441                                    part_die->spec_is_dwz, cu);
15442
15443       fixup_partial_die (spec_die, cu);
15444
15445       if (spec_die->name)
15446         {
15447           part_die->name = spec_die->name;
15448
15449           /* Copy DW_AT_external attribute if it is set.  */
15450           if (spec_die->is_external)
15451             part_die->is_external = spec_die->is_external;
15452         }
15453     }
15454
15455   /* Set default names for some unnamed DIEs.  */
15456
15457   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
15458     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
15459
15460   /* If there is no parent die to provide a namespace, and there are
15461      children, see if we can determine the namespace from their linkage
15462      name.  */
15463   if (cu->language == language_cplus
15464       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
15465       && part_die->die_parent == NULL
15466       && part_die->has_children
15467       && (part_die->tag == DW_TAG_class_type
15468           || part_die->tag == DW_TAG_structure_type
15469           || part_die->tag == DW_TAG_union_type))
15470     guess_partial_die_structure_name (part_die, cu);
15471
15472   /* GCC might emit a nameless struct or union that has a linkage
15473      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15474   if (part_die->name == NULL
15475       && (part_die->tag == DW_TAG_class_type
15476           || part_die->tag == DW_TAG_interface_type
15477           || part_die->tag == DW_TAG_structure_type
15478           || part_die->tag == DW_TAG_union_type)
15479       && part_die->linkage_name != NULL)
15480     {
15481       char *demangled;
15482
15483       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
15484       if (demangled)
15485         {
15486           const char *base;
15487
15488           /* Strip any leading namespaces/classes, keep only the base name.
15489              DW_AT_name for named DIEs does not contain the prefixes.  */
15490           base = strrchr (demangled, ':');
15491           if (base && base > demangled && base[-1] == ':')
15492             base++;
15493           else
15494             base = demangled;
15495
15496           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
15497                                           base, strlen (base));
15498           xfree (demangled);
15499         }
15500     }
15501
15502   part_die->fixup_called = 1;
15503 }
15504
15505 /* Read an attribute value described by an attribute form.  */
15506
15507 static const gdb_byte *
15508 read_attribute_value (const struct die_reader_specs *reader,
15509                       struct attribute *attr, unsigned form,
15510                       const gdb_byte *info_ptr)
15511 {
15512   struct dwarf2_cu *cu = reader->cu;
15513   bfd *abfd = reader->abfd;
15514   struct comp_unit_head *cu_header = &cu->header;
15515   unsigned int bytes_read;
15516   struct dwarf_block *blk;
15517
15518   attr->form = form;
15519   switch (form)
15520     {
15521     case DW_FORM_ref_addr:
15522       if (cu->header.version == 2)
15523         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15524       else
15525         DW_UNSND (attr) = read_offset (abfd, info_ptr,
15526                                        &cu->header, &bytes_read);
15527       info_ptr += bytes_read;
15528       break;
15529     case DW_FORM_GNU_ref_alt:
15530       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15531       info_ptr += bytes_read;
15532       break;
15533     case DW_FORM_addr:
15534       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15535       info_ptr += bytes_read;
15536       break;
15537     case DW_FORM_block2:
15538       blk = dwarf_alloc_block (cu);
15539       blk->size = read_2_bytes (abfd, info_ptr);
15540       info_ptr += 2;
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_block4:
15546       blk = dwarf_alloc_block (cu);
15547       blk->size = read_4_bytes (abfd, info_ptr);
15548       info_ptr += 4;
15549       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15550       info_ptr += blk->size;
15551       DW_BLOCK (attr) = blk;
15552       break;
15553     case DW_FORM_data2:
15554       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
15555       info_ptr += 2;
15556       break;
15557     case DW_FORM_data4:
15558       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
15559       info_ptr += 4;
15560       break;
15561     case DW_FORM_data8:
15562       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
15563       info_ptr += 8;
15564       break;
15565     case DW_FORM_sec_offset:
15566       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15567       info_ptr += bytes_read;
15568       break;
15569     case DW_FORM_string:
15570       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
15571       DW_STRING_IS_CANONICAL (attr) = 0;
15572       info_ptr += bytes_read;
15573       break;
15574     case DW_FORM_strp:
15575       if (!cu->per_cu->is_dwz)
15576         {
15577           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
15578                                                    &bytes_read);
15579           DW_STRING_IS_CANONICAL (attr) = 0;
15580           info_ptr += bytes_read;
15581           break;
15582         }
15583       /* FALLTHROUGH */
15584     case DW_FORM_GNU_strp_alt:
15585       {
15586         struct dwz_file *dwz = dwarf2_get_dwz_file ();
15587         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
15588                                           &bytes_read);
15589
15590         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
15591         DW_STRING_IS_CANONICAL (attr) = 0;
15592         info_ptr += bytes_read;
15593       }
15594       break;
15595     case DW_FORM_exprloc:
15596     case DW_FORM_block:
15597       blk = dwarf_alloc_block (cu);
15598       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15599       info_ptr += bytes_read;
15600       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15601       info_ptr += blk->size;
15602       DW_BLOCK (attr) = blk;
15603       break;
15604     case DW_FORM_block1:
15605       blk = dwarf_alloc_block (cu);
15606       blk->size = read_1_byte (abfd, info_ptr);
15607       info_ptr += 1;
15608       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15609       info_ptr += blk->size;
15610       DW_BLOCK (attr) = blk;
15611       break;
15612     case DW_FORM_data1:
15613       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15614       info_ptr += 1;
15615       break;
15616     case DW_FORM_flag:
15617       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15618       info_ptr += 1;
15619       break;
15620     case DW_FORM_flag_present:
15621       DW_UNSND (attr) = 1;
15622       break;
15623     case DW_FORM_sdata:
15624       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
15625       info_ptr += bytes_read;
15626       break;
15627     case DW_FORM_udata:
15628       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15629       info_ptr += bytes_read;
15630       break;
15631     case DW_FORM_ref1:
15632       DW_UNSND (attr) = (cu->header.offset.sect_off
15633                          + read_1_byte (abfd, info_ptr));
15634       info_ptr += 1;
15635       break;
15636     case DW_FORM_ref2:
15637       DW_UNSND (attr) = (cu->header.offset.sect_off
15638                          + read_2_bytes (abfd, info_ptr));
15639       info_ptr += 2;
15640       break;
15641     case DW_FORM_ref4:
15642       DW_UNSND (attr) = (cu->header.offset.sect_off
15643                          + read_4_bytes (abfd, info_ptr));
15644       info_ptr += 4;
15645       break;
15646     case DW_FORM_ref8:
15647       DW_UNSND (attr) = (cu->header.offset.sect_off
15648                          + read_8_bytes (abfd, info_ptr));
15649       info_ptr += 8;
15650       break;
15651     case DW_FORM_ref_sig8:
15652       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
15653       info_ptr += 8;
15654       break;
15655     case DW_FORM_ref_udata:
15656       DW_UNSND (attr) = (cu->header.offset.sect_off
15657                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
15658       info_ptr += bytes_read;
15659       break;
15660     case DW_FORM_indirect:
15661       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15662       info_ptr += bytes_read;
15663       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
15664       break;
15665     case DW_FORM_GNU_addr_index:
15666       if (reader->dwo_file == NULL)
15667         {
15668           /* For now flag a hard error.
15669              Later we can turn this into a complaint.  */
15670           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15671                  dwarf_form_name (form),
15672                  bfd_get_filename (abfd));
15673         }
15674       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
15675       info_ptr += bytes_read;
15676       break;
15677     case DW_FORM_GNU_str_index:
15678       if (reader->dwo_file == NULL)
15679         {
15680           /* For now flag a hard error.
15681              Later we can turn this into a complaint if warranted.  */
15682           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15683                  dwarf_form_name (form),
15684                  bfd_get_filename (abfd));
15685         }
15686       {
15687         ULONGEST str_index =
15688           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15689
15690         DW_STRING (attr) = read_str_index (reader, cu, str_index);
15691         DW_STRING_IS_CANONICAL (attr) = 0;
15692         info_ptr += bytes_read;
15693       }
15694       break;
15695     default:
15696       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
15697              dwarf_form_name (form),
15698              bfd_get_filename (abfd));
15699     }
15700
15701   /* Super hack.  */
15702   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
15703     attr->form = DW_FORM_GNU_ref_alt;
15704
15705   /* We have seen instances where the compiler tried to emit a byte
15706      size attribute of -1 which ended up being encoded as an unsigned
15707      0xffffffff.  Although 0xffffffff is technically a valid size value,
15708      an object of this size seems pretty unlikely so we can relatively
15709      safely treat these cases as if the size attribute was invalid and
15710      treat them as zero by default.  */
15711   if (attr->name == DW_AT_byte_size
15712       && form == DW_FORM_data4
15713       && DW_UNSND (attr) >= 0xffffffff)
15714     {
15715       complaint
15716         (&symfile_complaints,
15717          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
15718          hex_string (DW_UNSND (attr)));
15719       DW_UNSND (attr) = 0;
15720     }
15721
15722   return info_ptr;
15723 }
15724
15725 /* Read an attribute described by an abbreviated attribute.  */
15726
15727 static const gdb_byte *
15728 read_attribute (const struct die_reader_specs *reader,
15729                 struct attribute *attr, struct attr_abbrev *abbrev,
15730                 const gdb_byte *info_ptr)
15731 {
15732   attr->name = abbrev->name;
15733   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
15734 }
15735
15736 /* Read dwarf information from a buffer.  */
15737
15738 static unsigned int
15739 read_1_byte (bfd *abfd, const gdb_byte *buf)
15740 {
15741   return bfd_get_8 (abfd, buf);
15742 }
15743
15744 static int
15745 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
15746 {
15747   return bfd_get_signed_8 (abfd, buf);
15748 }
15749
15750 static unsigned int
15751 read_2_bytes (bfd *abfd, const gdb_byte *buf)
15752 {
15753   return bfd_get_16 (abfd, buf);
15754 }
15755
15756 static int
15757 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
15758 {
15759   return bfd_get_signed_16 (abfd, buf);
15760 }
15761
15762 static unsigned int
15763 read_4_bytes (bfd *abfd, const gdb_byte *buf)
15764 {
15765   return bfd_get_32 (abfd, buf);
15766 }
15767
15768 static int
15769 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
15770 {
15771   return bfd_get_signed_32 (abfd, buf);
15772 }
15773
15774 static ULONGEST
15775 read_8_bytes (bfd *abfd, const gdb_byte *buf)
15776 {
15777   return bfd_get_64 (abfd, buf);
15778 }
15779
15780 static CORE_ADDR
15781 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
15782               unsigned int *bytes_read)
15783 {
15784   struct comp_unit_head *cu_header = &cu->header;
15785   CORE_ADDR retval = 0;
15786
15787   if (cu_header->signed_addr_p)
15788     {
15789       switch (cu_header->addr_size)
15790         {
15791         case 2:
15792           retval = bfd_get_signed_16 (abfd, buf);
15793           break;
15794         case 4:
15795           retval = bfd_get_signed_32 (abfd, buf);
15796           break;
15797         case 8:
15798           retval = bfd_get_signed_64 (abfd, buf);
15799           break;
15800         default:
15801           internal_error (__FILE__, __LINE__,
15802                           _("read_address: bad switch, signed [in module %s]"),
15803                           bfd_get_filename (abfd));
15804         }
15805     }
15806   else
15807     {
15808       switch (cu_header->addr_size)
15809         {
15810         case 2:
15811           retval = bfd_get_16 (abfd, buf);
15812           break;
15813         case 4:
15814           retval = bfd_get_32 (abfd, buf);
15815           break;
15816         case 8:
15817           retval = bfd_get_64 (abfd, buf);
15818           break;
15819         default:
15820           internal_error (__FILE__, __LINE__,
15821                           _("read_address: bad switch, "
15822                             "unsigned [in module %s]"),
15823                           bfd_get_filename (abfd));
15824         }
15825     }
15826
15827   *bytes_read = cu_header->addr_size;
15828   return retval;
15829 }
15830
15831 /* Read the initial length from a section.  The (draft) DWARF 3
15832    specification allows the initial length to take up either 4 bytes
15833    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15834    bytes describe the length and all offsets will be 8 bytes in length
15835    instead of 4.
15836
15837    An older, non-standard 64-bit format is also handled by this
15838    function.  The older format in question stores the initial length
15839    as an 8-byte quantity without an escape value.  Lengths greater
15840    than 2^32 aren't very common which means that the initial 4 bytes
15841    is almost always zero.  Since a length value of zero doesn't make
15842    sense for the 32-bit format, this initial zero can be considered to
15843    be an escape value which indicates the presence of the older 64-bit
15844    format.  As written, the code can't detect (old format) lengths
15845    greater than 4GB.  If it becomes necessary to handle lengths
15846    somewhat larger than 4GB, we could allow other small values (such
15847    as the non-sensical values of 1, 2, and 3) to also be used as
15848    escape values indicating the presence of the old format.
15849
15850    The value returned via bytes_read should be used to increment the
15851    relevant pointer after calling read_initial_length().
15852
15853    [ Note:  read_initial_length() and read_offset() are based on the
15854      document entitled "DWARF Debugging Information Format", revision
15855      3, draft 8, dated November 19, 2001.  This document was obtained
15856      from:
15857
15858         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15859
15860      This document is only a draft and is subject to change.  (So beware.)
15861
15862      Details regarding the older, non-standard 64-bit format were
15863      determined empirically by examining 64-bit ELF files produced by
15864      the SGI toolchain on an IRIX 6.5 machine.
15865
15866      - Kevin, July 16, 2002
15867    ] */
15868
15869 static LONGEST
15870 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15871 {
15872   LONGEST length = bfd_get_32 (abfd, buf);
15873
15874   if (length == 0xffffffff)
15875     {
15876       length = bfd_get_64 (abfd, buf + 4);
15877       *bytes_read = 12;
15878     }
15879   else if (length == 0)
15880     {
15881       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15882       length = bfd_get_64 (abfd, buf);
15883       *bytes_read = 8;
15884     }
15885   else
15886     {
15887       *bytes_read = 4;
15888     }
15889
15890   return length;
15891 }
15892
15893 /* Cover function for read_initial_length.
15894    Returns the length of the object at BUF, and stores the size of the
15895    initial length in *BYTES_READ and stores the size that offsets will be in
15896    *OFFSET_SIZE.
15897    If the initial length size is not equivalent to that specified in
15898    CU_HEADER then issue a complaint.
15899    This is useful when reading non-comp-unit headers.  */
15900
15901 static LONGEST
15902 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15903                                         const struct comp_unit_head *cu_header,
15904                                         unsigned int *bytes_read,
15905                                         unsigned int *offset_size)
15906 {
15907   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15908
15909   gdb_assert (cu_header->initial_length_size == 4
15910               || cu_header->initial_length_size == 8
15911               || cu_header->initial_length_size == 12);
15912
15913   if (cu_header->initial_length_size != *bytes_read)
15914     complaint (&symfile_complaints,
15915                _("intermixed 32-bit and 64-bit DWARF sections"));
15916
15917   *offset_size = (*bytes_read == 4) ? 4 : 8;
15918   return length;
15919 }
15920
15921 /* Read an offset from the data stream.  The size of the offset is
15922    given by cu_header->offset_size.  */
15923
15924 static LONGEST
15925 read_offset (bfd *abfd, const gdb_byte *buf,
15926              const struct comp_unit_head *cu_header,
15927              unsigned int *bytes_read)
15928 {
15929   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15930
15931   *bytes_read = cu_header->offset_size;
15932   return offset;
15933 }
15934
15935 /* Read an offset from the data stream.  */
15936
15937 static LONGEST
15938 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15939 {
15940   LONGEST retval = 0;
15941
15942   switch (offset_size)
15943     {
15944     case 4:
15945       retval = bfd_get_32 (abfd, buf);
15946       break;
15947     case 8:
15948       retval = bfd_get_64 (abfd, buf);
15949       break;
15950     default:
15951       internal_error (__FILE__, __LINE__,
15952                       _("read_offset_1: bad switch [in module %s]"),
15953                       bfd_get_filename (abfd));
15954     }
15955
15956   return retval;
15957 }
15958
15959 static const gdb_byte *
15960 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15961 {
15962   /* If the size of a host char is 8 bits, we can return a pointer
15963      to the buffer, otherwise we have to copy the data to a buffer
15964      allocated on the temporary obstack.  */
15965   gdb_assert (HOST_CHAR_BIT == 8);
15966   return buf;
15967 }
15968
15969 static const char *
15970 read_direct_string (bfd *abfd, const gdb_byte *buf,
15971                     unsigned int *bytes_read_ptr)
15972 {
15973   /* If the size of a host char is 8 bits, we can return a pointer
15974      to the string, otherwise we have to copy the string to a buffer
15975      allocated on the temporary obstack.  */
15976   gdb_assert (HOST_CHAR_BIT == 8);
15977   if (*buf == '\0')
15978     {
15979       *bytes_read_ptr = 1;
15980       return NULL;
15981     }
15982   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15983   return (const char *) buf;
15984 }
15985
15986 static const char *
15987 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15988 {
15989   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15990   if (dwarf2_per_objfile->str.buffer == NULL)
15991     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15992            bfd_get_filename (abfd));
15993   if (str_offset >= dwarf2_per_objfile->str.size)
15994     error (_("DW_FORM_strp pointing outside of "
15995              ".debug_str section [in module %s]"),
15996            bfd_get_filename (abfd));
15997   gdb_assert (HOST_CHAR_BIT == 8);
15998   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15999     return NULL;
16000   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
16001 }
16002
16003 /* Read a string at offset STR_OFFSET in the .debug_str section from
16004    the .dwz file DWZ.  Throw an error if the offset is too large.  If
16005    the string consists of a single NUL byte, return NULL; otherwise
16006    return a pointer to the string.  */
16007
16008 static const char *
16009 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
16010 {
16011   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
16012
16013   if (dwz->str.buffer == NULL)
16014     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
16015              "section [in module %s]"),
16016            bfd_get_filename (dwz->dwz_bfd));
16017   if (str_offset >= dwz->str.size)
16018     error (_("DW_FORM_GNU_strp_alt pointing outside of "
16019              ".debug_str section [in module %s]"),
16020            bfd_get_filename (dwz->dwz_bfd));
16021   gdb_assert (HOST_CHAR_BIT == 8);
16022   if (dwz->str.buffer[str_offset] == '\0')
16023     return NULL;
16024   return (const char *) (dwz->str.buffer + str_offset);
16025 }
16026
16027 static const char *
16028 read_indirect_string (bfd *abfd, const gdb_byte *buf,
16029                       const struct comp_unit_head *cu_header,
16030                       unsigned int *bytes_read_ptr)
16031 {
16032   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
16033
16034   return read_indirect_string_at_offset (abfd, str_offset);
16035 }
16036
16037 static ULONGEST
16038 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
16039                       unsigned int *bytes_read_ptr)
16040 {
16041   ULONGEST result;
16042   unsigned int num_read;
16043   int i, shift;
16044   unsigned char byte;
16045
16046   result = 0;
16047   shift = 0;
16048   num_read = 0;
16049   i = 0;
16050   while (1)
16051     {
16052       byte = bfd_get_8 (abfd, buf);
16053       buf++;
16054       num_read++;
16055       result |= ((ULONGEST) (byte & 127) << shift);
16056       if ((byte & 128) == 0)
16057         {
16058           break;
16059         }
16060       shift += 7;
16061     }
16062   *bytes_read_ptr = num_read;
16063   return result;
16064 }
16065
16066 static LONGEST
16067 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
16068                     unsigned int *bytes_read_ptr)
16069 {
16070   LONGEST result;
16071   int i, shift, num_read;
16072   unsigned char byte;
16073
16074   result = 0;
16075   shift = 0;
16076   num_read = 0;
16077   i = 0;
16078   while (1)
16079     {
16080       byte = bfd_get_8 (abfd, buf);
16081       buf++;
16082       num_read++;
16083       result |= ((LONGEST) (byte & 127) << shift);
16084       shift += 7;
16085       if ((byte & 128) == 0)
16086         {
16087           break;
16088         }
16089     }
16090   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
16091     result |= -(((LONGEST) 1) << shift);
16092   *bytes_read_ptr = num_read;
16093   return result;
16094 }
16095
16096 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
16097    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
16098    ADDR_SIZE is the size of addresses from the CU header.  */
16099
16100 static CORE_ADDR
16101 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
16102 {
16103   struct objfile *objfile = dwarf2_per_objfile->objfile;
16104   bfd *abfd = objfile->obfd;
16105   const gdb_byte *info_ptr;
16106
16107   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
16108   if (dwarf2_per_objfile->addr.buffer == NULL)
16109     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
16110            objfile_name (objfile));
16111   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
16112     error (_("DW_FORM_addr_index pointing outside of "
16113              ".debug_addr section [in module %s]"),
16114            objfile_name (objfile));
16115   info_ptr = (dwarf2_per_objfile->addr.buffer
16116               + addr_base + addr_index * addr_size);
16117   if (addr_size == 4)
16118     return bfd_get_32 (abfd, info_ptr);
16119   else
16120     return bfd_get_64 (abfd, info_ptr);
16121 }
16122
16123 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
16124
16125 static CORE_ADDR
16126 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
16127 {
16128   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
16129 }
16130
16131 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
16132
16133 static CORE_ADDR
16134 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
16135                              unsigned int *bytes_read)
16136 {
16137   bfd *abfd = cu->objfile->obfd;
16138   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
16139
16140   return read_addr_index (cu, addr_index);
16141 }
16142
16143 /* Data structure to pass results from dwarf2_read_addr_index_reader
16144    back to dwarf2_read_addr_index.  */
16145
16146 struct dwarf2_read_addr_index_data
16147 {
16148   ULONGEST addr_base;
16149   int addr_size;
16150 };
16151
16152 /* die_reader_func for dwarf2_read_addr_index.  */
16153
16154 static void
16155 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
16156                                const gdb_byte *info_ptr,
16157                                struct die_info *comp_unit_die,
16158                                int has_children,
16159                                void *data)
16160 {
16161   struct dwarf2_cu *cu = reader->cu;
16162   struct dwarf2_read_addr_index_data *aidata =
16163     (struct dwarf2_read_addr_index_data *) data;
16164
16165   aidata->addr_base = cu->addr_base;
16166   aidata->addr_size = cu->header.addr_size;
16167 }
16168
16169 /* Given an index in .debug_addr, fetch the value.
16170    NOTE: This can be called during dwarf expression evaluation,
16171    long after the debug information has been read, and thus per_cu->cu
16172    may no longer exist.  */
16173
16174 CORE_ADDR
16175 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
16176                         unsigned int addr_index)
16177 {
16178   struct objfile *objfile = per_cu->objfile;
16179   struct dwarf2_cu *cu = per_cu->cu;
16180   ULONGEST addr_base;
16181   int addr_size;
16182
16183   /* This is intended to be called from outside this file.  */
16184   dw2_setup (objfile);
16185
16186   /* We need addr_base and addr_size.
16187      If we don't have PER_CU->cu, we have to get it.
16188      Nasty, but the alternative is storing the needed info in PER_CU,
16189      which at this point doesn't seem justified: it's not clear how frequently
16190      it would get used and it would increase the size of every PER_CU.
16191      Entry points like dwarf2_per_cu_addr_size do a similar thing
16192      so we're not in uncharted territory here.
16193      Alas we need to be a bit more complicated as addr_base is contained
16194      in the DIE.
16195
16196      We don't need to read the entire CU(/TU).
16197      We just need the header and top level die.
16198
16199      IWBN to use the aging mechanism to let us lazily later discard the CU.
16200      For now we skip this optimization.  */
16201
16202   if (cu != NULL)
16203     {
16204       addr_base = cu->addr_base;
16205       addr_size = cu->header.addr_size;
16206     }
16207   else
16208     {
16209       struct dwarf2_read_addr_index_data aidata;
16210
16211       /* Note: We can't use init_cutu_and_read_dies_simple here,
16212          we need addr_base.  */
16213       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
16214                                dwarf2_read_addr_index_reader, &aidata);
16215       addr_base = aidata.addr_base;
16216       addr_size = aidata.addr_size;
16217     }
16218
16219   return read_addr_index_1 (addr_index, addr_base, addr_size);
16220 }
16221
16222 /* Given a DW_FORM_GNU_str_index, fetch the string.
16223    This is only used by the Fission support.  */
16224
16225 static const char *
16226 read_str_index (const struct die_reader_specs *reader,
16227                 struct dwarf2_cu *cu, ULONGEST str_index)
16228 {
16229   struct objfile *objfile = dwarf2_per_objfile->objfile;
16230   const char *dwo_name = objfile_name (objfile);
16231   bfd *abfd = objfile->obfd;
16232   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
16233   struct dwarf2_section_info *str_offsets_section =
16234     &reader->dwo_file->sections.str_offsets;
16235   const gdb_byte *info_ptr;
16236   ULONGEST str_offset;
16237   static const char form_name[] = "DW_FORM_GNU_str_index";
16238
16239   dwarf2_read_section (objfile, str_section);
16240   dwarf2_read_section (objfile, str_offsets_section);
16241   if (str_section->buffer == NULL)
16242     error (_("%s used without .debug_str.dwo section"
16243              " in CU at offset 0x%lx [in module %s]"),
16244            form_name, (long) cu->header.offset.sect_off, dwo_name);
16245   if (str_offsets_section->buffer == NULL)
16246     error (_("%s used without .debug_str_offsets.dwo section"
16247              " in CU at offset 0x%lx [in module %s]"),
16248            form_name, (long) cu->header.offset.sect_off, dwo_name);
16249   if (str_index * cu->header.offset_size >= str_offsets_section->size)
16250     error (_("%s pointing outside of .debug_str_offsets.dwo"
16251              " section in CU at offset 0x%lx [in module %s]"),
16252            form_name, (long) cu->header.offset.sect_off, dwo_name);
16253   info_ptr = (str_offsets_section->buffer
16254               + str_index * cu->header.offset_size);
16255   if (cu->header.offset_size == 4)
16256     str_offset = bfd_get_32 (abfd, info_ptr);
16257   else
16258     str_offset = bfd_get_64 (abfd, info_ptr);
16259   if (str_offset >= str_section->size)
16260     error (_("Offset from %s pointing outside of"
16261              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
16262            form_name, (long) cu->header.offset.sect_off, dwo_name);
16263   return (const char *) (str_section->buffer + str_offset);
16264 }
16265
16266 /* Return the length of an LEB128 number in BUF.  */
16267
16268 static int
16269 leb128_size (const gdb_byte *buf)
16270 {
16271   const gdb_byte *begin = buf;
16272   gdb_byte byte;
16273
16274   while (1)
16275     {
16276       byte = *buf++;
16277       if ((byte & 128) == 0)
16278         return buf - begin;
16279     }
16280 }
16281
16282 static void
16283 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
16284 {
16285   switch (lang)
16286     {
16287     case DW_LANG_C89:
16288     case DW_LANG_C99:
16289     case DW_LANG_C:
16290     case DW_LANG_UPC:
16291       cu->language = language_c;
16292       break;
16293     case DW_LANG_C_plus_plus:
16294       cu->language = language_cplus;
16295       break;
16296     case DW_LANG_D:
16297       cu->language = language_d;
16298       break;
16299     case DW_LANG_Fortran77:
16300     case DW_LANG_Fortran90:
16301     case DW_LANG_Fortran95:
16302       cu->language = language_fortran;
16303       break;
16304     case DW_LANG_Go:
16305       cu->language = language_go;
16306       break;
16307     case DW_LANG_Mips_Assembler:
16308       cu->language = language_asm;
16309       break;
16310     case DW_LANG_Java:
16311       cu->language = language_java;
16312       break;
16313     case DW_LANG_Ada83:
16314     case DW_LANG_Ada95:
16315       cu->language = language_ada;
16316       break;
16317     case DW_LANG_Modula2:
16318       cu->language = language_m2;
16319       break;
16320     case DW_LANG_Pascal83:
16321       cu->language = language_pascal;
16322       break;
16323     case DW_LANG_ObjC:
16324       cu->language = language_objc;
16325       break;
16326     case DW_LANG_Cobol74:
16327     case DW_LANG_Cobol85:
16328     default:
16329       cu->language = language_minimal;
16330       break;
16331     }
16332   cu->language_defn = language_def (cu->language);
16333 }
16334
16335 /* Return the named attribute or NULL if not there.  */
16336
16337 static struct attribute *
16338 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
16339 {
16340   for (;;)
16341     {
16342       unsigned int i;
16343       struct attribute *spec = NULL;
16344
16345       for (i = 0; i < die->num_attrs; ++i)
16346         {
16347           if (die->attrs[i].name == name)
16348             return &die->attrs[i];
16349           if (die->attrs[i].name == DW_AT_specification
16350               || die->attrs[i].name == DW_AT_abstract_origin)
16351             spec = &die->attrs[i];
16352         }
16353
16354       if (!spec)
16355         break;
16356
16357       die = follow_die_ref (die, spec, &cu);
16358     }
16359
16360   return NULL;
16361 }
16362
16363 /* Return the named attribute or NULL if not there,
16364    but do not follow DW_AT_specification, etc.
16365    This is for use in contexts where we're reading .debug_types dies.
16366    Following DW_AT_specification, DW_AT_abstract_origin will take us
16367    back up the chain, and we want to go down.  */
16368
16369 static struct attribute *
16370 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
16371 {
16372   unsigned int i;
16373
16374   for (i = 0; i < die->num_attrs; ++i)
16375     if (die->attrs[i].name == name)
16376       return &die->attrs[i];
16377
16378   return NULL;
16379 }
16380
16381 /* Return non-zero iff the attribute NAME is defined for the given DIE,
16382    and holds a non-zero value.  This function should only be used for
16383    DW_FORM_flag or DW_FORM_flag_present attributes.  */
16384
16385 static int
16386 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
16387 {
16388   struct attribute *attr = dwarf2_attr (die, name, cu);
16389
16390   return (attr && DW_UNSND (attr));
16391 }
16392
16393 static int
16394 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
16395 {
16396   /* A DIE is a declaration if it has a DW_AT_declaration attribute
16397      which value is non-zero.  However, we have to be careful with
16398      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
16399      (via dwarf2_flag_true_p) follows this attribute.  So we may
16400      end up accidently finding a declaration attribute that belongs
16401      to a different DIE referenced by the specification attribute,
16402      even though the given DIE does not have a declaration attribute.  */
16403   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
16404           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
16405 }
16406
16407 /* Return the die giving the specification for DIE, if there is
16408    one.  *SPEC_CU is the CU containing DIE on input, and the CU
16409    containing the return value on output.  If there is no
16410    specification, but there is an abstract origin, that is
16411    returned.  */
16412
16413 static struct die_info *
16414 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
16415 {
16416   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
16417                                              *spec_cu);
16418
16419   if (spec_attr == NULL)
16420     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
16421
16422   if (spec_attr == NULL)
16423     return NULL;
16424   else
16425     return follow_die_ref (die, spec_attr, spec_cu);
16426 }
16427
16428 /* Free the line_header structure *LH, and any arrays and strings it
16429    refers to.
16430    NOTE: This is also used as a "cleanup" function.  */
16431
16432 static void
16433 free_line_header (struct line_header *lh)
16434 {
16435   if (lh->standard_opcode_lengths)
16436     xfree (lh->standard_opcode_lengths);
16437
16438   /* Remember that all the lh->file_names[i].name pointers are
16439      pointers into debug_line_buffer, and don't need to be freed.  */
16440   if (lh->file_names)
16441     xfree (lh->file_names);
16442
16443   /* Similarly for the include directory names.  */
16444   if (lh->include_dirs)
16445     xfree (lh->include_dirs);
16446
16447   xfree (lh);
16448 }
16449
16450 /* Add an entry to LH's include directory table.  */
16451
16452 static void
16453 add_include_dir (struct line_header *lh, const char *include_dir)
16454 {
16455   /* Grow the array if necessary.  */
16456   if (lh->include_dirs_size == 0)
16457     {
16458       lh->include_dirs_size = 1; /* for testing */
16459       lh->include_dirs = xmalloc (lh->include_dirs_size
16460                                   * sizeof (*lh->include_dirs));
16461     }
16462   else if (lh->num_include_dirs >= lh->include_dirs_size)
16463     {
16464       lh->include_dirs_size *= 2;
16465       lh->include_dirs = xrealloc (lh->include_dirs,
16466                                    (lh->include_dirs_size
16467                                     * sizeof (*lh->include_dirs)));
16468     }
16469
16470   lh->include_dirs[lh->num_include_dirs++] = include_dir;
16471 }
16472
16473 /* Add an entry to LH's file name table.  */
16474
16475 static void
16476 add_file_name (struct line_header *lh,
16477                const char *name,
16478                unsigned int dir_index,
16479                unsigned int mod_time,
16480                unsigned int length)
16481 {
16482   struct file_entry *fe;
16483
16484   /* Grow the array if necessary.  */
16485   if (lh->file_names_size == 0)
16486     {
16487       lh->file_names_size = 1; /* for testing */
16488       lh->file_names = xmalloc (lh->file_names_size
16489                                 * sizeof (*lh->file_names));
16490     }
16491   else if (lh->num_file_names >= lh->file_names_size)
16492     {
16493       lh->file_names_size *= 2;
16494       lh->file_names = xrealloc (lh->file_names,
16495                                  (lh->file_names_size
16496                                   * sizeof (*lh->file_names)));
16497     }
16498
16499   fe = &lh->file_names[lh->num_file_names++];
16500   fe->name = name;
16501   fe->dir_index = dir_index;
16502   fe->mod_time = mod_time;
16503   fe->length = length;
16504   fe->included_p = 0;
16505   fe->symtab = NULL;
16506 }
16507
16508 /* A convenience function to find the proper .debug_line section for a
16509    CU.  */
16510
16511 static struct dwarf2_section_info *
16512 get_debug_line_section (struct dwarf2_cu *cu)
16513 {
16514   struct dwarf2_section_info *section;
16515
16516   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
16517      DWO file.  */
16518   if (cu->dwo_unit && cu->per_cu->is_debug_types)
16519     section = &cu->dwo_unit->dwo_file->sections.line;
16520   else if (cu->per_cu->is_dwz)
16521     {
16522       struct dwz_file *dwz = dwarf2_get_dwz_file ();
16523
16524       section = &dwz->line;
16525     }
16526   else
16527     section = &dwarf2_per_objfile->line;
16528
16529   return section;
16530 }
16531
16532 /* Read the statement program header starting at OFFSET in
16533    .debug_line, or .debug_line.dwo.  Return a pointer
16534    to a struct line_header, allocated using xmalloc.
16535
16536    NOTE: the strings in the include directory and file name tables of
16537    the returned object point into the dwarf line section buffer,
16538    and must not be freed.  */
16539
16540 static struct line_header *
16541 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
16542 {
16543   struct cleanup *back_to;
16544   struct line_header *lh;
16545   const gdb_byte *line_ptr;
16546   unsigned int bytes_read, offset_size;
16547   int i;
16548   const char *cur_dir, *cur_file;
16549   struct dwarf2_section_info *section;
16550   bfd *abfd;
16551
16552   section = get_debug_line_section (cu);
16553   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
16554   if (section->buffer == NULL)
16555     {
16556       if (cu->dwo_unit && cu->per_cu->is_debug_types)
16557         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
16558       else
16559         complaint (&symfile_complaints, _("missing .debug_line section"));
16560       return 0;
16561     }
16562
16563   /* We can't do this until we know the section is non-empty.
16564      Only then do we know we have such a section.  */
16565   abfd = get_section_bfd_owner (section);
16566
16567   /* Make sure that at least there's room for the total_length field.
16568      That could be 12 bytes long, but we're just going to fudge that.  */
16569   if (offset + 4 >= section->size)
16570     {
16571       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16572       return 0;
16573     }
16574
16575   lh = xmalloc (sizeof (*lh));
16576   memset (lh, 0, sizeof (*lh));
16577   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
16578                           (void *) lh);
16579
16580   line_ptr = section->buffer + offset;
16581
16582   /* Read in the header.  */
16583   lh->total_length =
16584     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
16585                                             &bytes_read, &offset_size);
16586   line_ptr += bytes_read;
16587   if (line_ptr + lh->total_length > (section->buffer + section->size))
16588     {
16589       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16590       do_cleanups (back_to);
16591       return 0;
16592     }
16593   lh->statement_program_end = line_ptr + lh->total_length;
16594   lh->version = read_2_bytes (abfd, line_ptr);
16595   line_ptr += 2;
16596   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
16597   line_ptr += offset_size;
16598   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
16599   line_ptr += 1;
16600   if (lh->version >= 4)
16601     {
16602       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
16603       line_ptr += 1;
16604     }
16605   else
16606     lh->maximum_ops_per_instruction = 1;
16607
16608   if (lh->maximum_ops_per_instruction == 0)
16609     {
16610       lh->maximum_ops_per_instruction = 1;
16611       complaint (&symfile_complaints,
16612                  _("invalid maximum_ops_per_instruction "
16613                    "in `.debug_line' section"));
16614     }
16615
16616   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
16617   line_ptr += 1;
16618   lh->line_base = read_1_signed_byte (abfd, line_ptr);
16619   line_ptr += 1;
16620   lh->line_range = read_1_byte (abfd, line_ptr);
16621   line_ptr += 1;
16622   lh->opcode_base = read_1_byte (abfd, line_ptr);
16623   line_ptr += 1;
16624   lh->standard_opcode_lengths
16625     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
16626
16627   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
16628   for (i = 1; i < lh->opcode_base; ++i)
16629     {
16630       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
16631       line_ptr += 1;
16632     }
16633
16634   /* Read directory table.  */
16635   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16636     {
16637       line_ptr += bytes_read;
16638       add_include_dir (lh, cur_dir);
16639     }
16640   line_ptr += bytes_read;
16641
16642   /* Read file name table.  */
16643   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16644     {
16645       unsigned int dir_index, mod_time, length;
16646
16647       line_ptr += bytes_read;
16648       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16649       line_ptr += bytes_read;
16650       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16651       line_ptr += bytes_read;
16652       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16653       line_ptr += bytes_read;
16654
16655       add_file_name (lh, cur_file, dir_index, mod_time, length);
16656     }
16657   line_ptr += bytes_read;
16658   lh->statement_program_start = line_ptr;
16659
16660   if (line_ptr > (section->buffer + section->size))
16661     complaint (&symfile_complaints,
16662                _("line number info header doesn't "
16663                  "fit in `.debug_line' section"));
16664
16665   discard_cleanups (back_to);
16666   return lh;
16667 }
16668
16669 /* Subroutine of dwarf_decode_lines to simplify it.
16670    Return the file name of the psymtab for included file FILE_INDEX
16671    in line header LH of PST.
16672    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16673    If space for the result is malloc'd, it will be freed by a cleanup.
16674    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
16675
16676    The function creates dangling cleanup registration.  */
16677
16678 static const char *
16679 psymtab_include_file_name (const struct line_header *lh, int file_index,
16680                            const struct partial_symtab *pst,
16681                            const char *comp_dir)
16682 {
16683   const struct file_entry fe = lh->file_names [file_index];
16684   const char *include_name = fe.name;
16685   const char *include_name_to_compare = include_name;
16686   const char *dir_name = NULL;
16687   const char *pst_filename;
16688   char *copied_name = NULL;
16689   int file_is_pst;
16690
16691   if (fe.dir_index)
16692     dir_name = lh->include_dirs[fe.dir_index - 1];
16693
16694   if (!IS_ABSOLUTE_PATH (include_name)
16695       && (dir_name != NULL || comp_dir != NULL))
16696     {
16697       /* Avoid creating a duplicate psymtab for PST.
16698          We do this by comparing INCLUDE_NAME and PST_FILENAME.
16699          Before we do the comparison, however, we need to account
16700          for DIR_NAME and COMP_DIR.
16701          First prepend dir_name (if non-NULL).  If we still don't
16702          have an absolute path prepend comp_dir (if non-NULL).
16703          However, the directory we record in the include-file's
16704          psymtab does not contain COMP_DIR (to match the
16705          corresponding symtab(s)).
16706
16707          Example:
16708
16709          bash$ cd /tmp
16710          bash$ gcc -g ./hello.c
16711          include_name = "hello.c"
16712          dir_name = "."
16713          DW_AT_comp_dir = comp_dir = "/tmp"
16714          DW_AT_name = "./hello.c"  */
16715
16716       if (dir_name != NULL)
16717         {
16718           char *tem = concat (dir_name, SLASH_STRING,
16719                               include_name, (char *)NULL);
16720
16721           make_cleanup (xfree, tem);
16722           include_name = tem;
16723           include_name_to_compare = include_name;
16724         }
16725       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
16726         {
16727           char *tem = concat (comp_dir, SLASH_STRING,
16728                               include_name, (char *)NULL);
16729
16730           make_cleanup (xfree, tem);
16731           include_name_to_compare = tem;
16732         }
16733     }
16734
16735   pst_filename = pst->filename;
16736   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
16737     {
16738       copied_name = concat (pst->dirname, SLASH_STRING,
16739                             pst_filename, (char *)NULL);
16740       pst_filename = copied_name;
16741     }
16742
16743   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
16744
16745   if (copied_name != NULL)
16746     xfree (copied_name);
16747
16748   if (file_is_pst)
16749     return NULL;
16750   return include_name;
16751 }
16752
16753 /* Ignore this record_line request.  */
16754
16755 static void
16756 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
16757 {
16758   return;
16759 }
16760
16761 /* Subroutine of dwarf_decode_lines to simplify it.
16762    Process the line number information in LH.  */
16763
16764 static void
16765 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
16766                       struct dwarf2_cu *cu, struct partial_symtab *pst)
16767 {
16768   const gdb_byte *line_ptr, *extended_end;
16769   const gdb_byte *line_end;
16770   unsigned int bytes_read, extended_len;
16771   unsigned char op_code, extended_op, adj_opcode;
16772   CORE_ADDR baseaddr;
16773   struct objfile *objfile = cu->objfile;
16774   bfd *abfd = objfile->obfd;
16775   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16776   const int decode_for_pst_p = (pst != NULL);
16777   struct subfile *last_subfile = NULL;
16778   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
16779     = record_line;
16780
16781   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16782
16783   line_ptr = lh->statement_program_start;
16784   line_end = lh->statement_program_end;
16785
16786   /* Read the statement sequences until there's nothing left.  */
16787   while (line_ptr < line_end)
16788     {
16789       /* state machine registers  */
16790       CORE_ADDR address = 0;
16791       unsigned int file = 1;
16792       unsigned int line = 1;
16793       unsigned int column = 0;
16794       int is_stmt = lh->default_is_stmt;
16795       int basic_block = 0;
16796       int end_sequence = 0;
16797       CORE_ADDR addr;
16798       unsigned char op_index = 0;
16799
16800       if (!decode_for_pst_p && lh->num_file_names >= file)
16801         {
16802           /* Start a subfile for the current file of the state machine.  */
16803           /* lh->include_dirs and lh->file_names are 0-based, but the
16804              directory and file name numbers in the statement program
16805              are 1-based.  */
16806           struct file_entry *fe = &lh->file_names[file - 1];
16807           const char *dir = NULL;
16808
16809           if (fe->dir_index)
16810             dir = lh->include_dirs[fe->dir_index - 1];
16811
16812           dwarf2_start_subfile (fe->name, dir, comp_dir);
16813         }
16814
16815       /* Decode the table.  */
16816       while (!end_sequence)
16817         {
16818           op_code = read_1_byte (abfd, line_ptr);
16819           line_ptr += 1;
16820           if (line_ptr > line_end)
16821             {
16822               dwarf2_debug_line_missing_end_sequence_complaint ();
16823               break;
16824             }
16825
16826           if (op_code >= lh->opcode_base)
16827             {
16828               /* Special operand.  */
16829               adj_opcode = op_code - lh->opcode_base;
16830               address += (((op_index + (adj_opcode / lh->line_range))
16831                            / lh->maximum_ops_per_instruction)
16832                           * lh->minimum_instruction_length);
16833               op_index = ((op_index + (adj_opcode / lh->line_range))
16834                           % lh->maximum_ops_per_instruction);
16835               line += lh->line_base + (adj_opcode % lh->line_range);
16836               if (lh->num_file_names < file || file == 0)
16837                 dwarf2_debug_line_missing_file_complaint ();
16838               /* For now we ignore lines not starting on an
16839                  instruction boundary.  */
16840               else if (op_index == 0)
16841                 {
16842                   lh->file_names[file - 1].included_p = 1;
16843                   if (!decode_for_pst_p && is_stmt)
16844                     {
16845                       if (last_subfile != current_subfile)
16846                         {
16847                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16848                           if (last_subfile)
16849                             (*p_record_line) (last_subfile, 0, addr);
16850                           last_subfile = current_subfile;
16851                         }
16852                       /* Append row to matrix using current values.  */
16853                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16854                       (*p_record_line) (current_subfile, line, addr);
16855                     }
16856                 }
16857               basic_block = 0;
16858             }
16859           else switch (op_code)
16860             {
16861             case DW_LNS_extended_op:
16862               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16863                                                    &bytes_read);
16864               line_ptr += bytes_read;
16865               extended_end = line_ptr + extended_len;
16866               extended_op = read_1_byte (abfd, line_ptr);
16867               line_ptr += 1;
16868               switch (extended_op)
16869                 {
16870                 case DW_LNE_end_sequence:
16871                   p_record_line = record_line;
16872                   end_sequence = 1;
16873                   break;
16874                 case DW_LNE_set_address:
16875                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16876
16877                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16878                     {
16879                       /* This line table is for a function which has been
16880                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16881
16882                       long line_offset
16883                         = line_ptr - get_debug_line_section (cu)->buffer;
16884
16885                       complaint (&symfile_complaints,
16886                                  _(".debug_line address at offset 0x%lx is 0 "
16887                                    "[in module %s]"),
16888                                  line_offset, objfile_name (objfile));
16889                       p_record_line = noop_record_line;
16890                     }
16891
16892                   op_index = 0;
16893                   line_ptr += bytes_read;
16894                   address += baseaddr;
16895                   break;
16896                 case DW_LNE_define_file:
16897                   {
16898                     const char *cur_file;
16899                     unsigned int dir_index, mod_time, length;
16900
16901                     cur_file = read_direct_string (abfd, line_ptr,
16902                                                    &bytes_read);
16903                     line_ptr += bytes_read;
16904                     dir_index =
16905                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16906                     line_ptr += bytes_read;
16907                     mod_time =
16908                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16909                     line_ptr += bytes_read;
16910                     length =
16911                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16912                     line_ptr += bytes_read;
16913                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16914                   }
16915                   break;
16916                 case DW_LNE_set_discriminator:
16917                   /* The discriminator is not interesting to the debugger;
16918                      just ignore it.  */
16919                   line_ptr = extended_end;
16920                   break;
16921                 default:
16922                   complaint (&symfile_complaints,
16923                              _("mangled .debug_line section"));
16924                   return;
16925                 }
16926               /* Make sure that we parsed the extended op correctly.  If e.g.
16927                  we expected a different address size than the producer used,
16928                  we may have read the wrong number of bytes.  */
16929               if (line_ptr != extended_end)
16930                 {
16931                   complaint (&symfile_complaints,
16932                              _("mangled .debug_line section"));
16933                   return;
16934                 }
16935               break;
16936             case DW_LNS_copy:
16937               if (lh->num_file_names < file || file == 0)
16938                 dwarf2_debug_line_missing_file_complaint ();
16939               else
16940                 {
16941                   lh->file_names[file - 1].included_p = 1;
16942                   if (!decode_for_pst_p && is_stmt)
16943                     {
16944                       if (last_subfile != current_subfile)
16945                         {
16946                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16947                           if (last_subfile)
16948                             (*p_record_line) (last_subfile, 0, addr);
16949                           last_subfile = current_subfile;
16950                         }
16951                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16952                       (*p_record_line) (current_subfile, line, addr);
16953                     }
16954                 }
16955               basic_block = 0;
16956               break;
16957             case DW_LNS_advance_pc:
16958               {
16959                 CORE_ADDR adjust
16960                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16961
16962                 address += (((op_index + adjust)
16963                              / lh->maximum_ops_per_instruction)
16964                             * lh->minimum_instruction_length);
16965                 op_index = ((op_index + adjust)
16966                             % lh->maximum_ops_per_instruction);
16967                 line_ptr += bytes_read;
16968               }
16969               break;
16970             case DW_LNS_advance_line:
16971               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16972               line_ptr += bytes_read;
16973               break;
16974             case DW_LNS_set_file:
16975               {
16976                 /* The arrays lh->include_dirs and lh->file_names are
16977                    0-based, but the directory and file name numbers in
16978                    the statement program are 1-based.  */
16979                 struct file_entry *fe;
16980                 const char *dir = NULL;
16981
16982                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16983                 line_ptr += bytes_read;
16984                 if (lh->num_file_names < file || file == 0)
16985                   dwarf2_debug_line_missing_file_complaint ();
16986                 else
16987                   {
16988                     fe = &lh->file_names[file - 1];
16989                     if (fe->dir_index)
16990                       dir = lh->include_dirs[fe->dir_index - 1];
16991                     if (!decode_for_pst_p)
16992                       {
16993                         last_subfile = current_subfile;
16994                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16995                       }
16996                   }
16997               }
16998               break;
16999             case DW_LNS_set_column:
17000               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17001               line_ptr += bytes_read;
17002               break;
17003             case DW_LNS_negate_stmt:
17004               is_stmt = (!is_stmt);
17005               break;
17006             case DW_LNS_set_basic_block:
17007               basic_block = 1;
17008               break;
17009             /* Add to the address register of the state machine the
17010                address increment value corresponding to special opcode
17011                255.  I.e., this value is scaled by the minimum
17012                instruction length since special opcode 255 would have
17013                scaled the increment.  */
17014             case DW_LNS_const_add_pc:
17015               {
17016                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
17017
17018                 address += (((op_index + adjust)
17019                              / lh->maximum_ops_per_instruction)
17020                             * lh->minimum_instruction_length);
17021                 op_index = ((op_index + adjust)
17022                             % lh->maximum_ops_per_instruction);
17023               }
17024               break;
17025             case DW_LNS_fixed_advance_pc:
17026               address += read_2_bytes (abfd, line_ptr);
17027               op_index = 0;
17028               line_ptr += 2;
17029               break;
17030             default:
17031               {
17032                 /* Unknown standard opcode, ignore it.  */
17033                 int i;
17034
17035                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
17036                   {
17037                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17038                     line_ptr += bytes_read;
17039                   }
17040               }
17041             }
17042         }
17043       if (lh->num_file_names < file || file == 0)
17044         dwarf2_debug_line_missing_file_complaint ();
17045       else
17046         {
17047           lh->file_names[file - 1].included_p = 1;
17048           if (!decode_for_pst_p)
17049             {
17050               addr = gdbarch_addr_bits_remove (gdbarch, address);
17051               (*p_record_line) (current_subfile, 0, addr);
17052             }
17053         }
17054     }
17055 }
17056
17057 /* Decode the Line Number Program (LNP) for the given line_header
17058    structure and CU.  The actual information extracted and the type
17059    of structures created from the LNP depends on the value of PST.
17060
17061    1. If PST is NULL, then this procedure uses the data from the program
17062       to create all necessary symbol tables, and their linetables.
17063
17064    2. If PST is not NULL, this procedure reads the program to determine
17065       the list of files included by the unit represented by PST, and
17066       builds all the associated partial symbol tables.
17067
17068    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
17069    It is used for relative paths in the line table.
17070    NOTE: When processing partial symtabs (pst != NULL),
17071    comp_dir == pst->dirname.
17072
17073    NOTE: It is important that psymtabs have the same file name (via strcmp)
17074    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
17075    symtab we don't use it in the name of the psymtabs we create.
17076    E.g. expand_line_sal requires this when finding psymtabs to expand.
17077    A good testcase for this is mb-inline.exp.  */
17078
17079 static void
17080 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
17081                     struct dwarf2_cu *cu, struct partial_symtab *pst,
17082                     int want_line_info)
17083 {
17084   struct objfile *objfile = cu->objfile;
17085   const int decode_for_pst_p = (pst != NULL);
17086   struct subfile *first_subfile = current_subfile;
17087
17088   if (want_line_info)
17089     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
17090
17091   if (decode_for_pst_p)
17092     {
17093       int file_index;
17094
17095       /* Now that we're done scanning the Line Header Program, we can
17096          create the psymtab of each included file.  */
17097       for (file_index = 0; file_index < lh->num_file_names; file_index++)
17098         if (lh->file_names[file_index].included_p == 1)
17099           {
17100             const char *include_name =
17101               psymtab_include_file_name (lh, file_index, pst, comp_dir);
17102             if (include_name != NULL)
17103               dwarf2_create_include_psymtab (include_name, pst, objfile);
17104           }
17105     }
17106   else
17107     {
17108       /* Make sure a symtab is created for every file, even files
17109          which contain only variables (i.e. no code with associated
17110          line numbers).  */
17111       int i;
17112
17113       for (i = 0; i < lh->num_file_names; i++)
17114         {
17115           const char *dir = NULL;
17116           struct file_entry *fe;
17117
17118           fe = &lh->file_names[i];
17119           if (fe->dir_index)
17120             dir = lh->include_dirs[fe->dir_index - 1];
17121           dwarf2_start_subfile (fe->name, dir, comp_dir);
17122
17123           /* Skip the main file; we don't need it, and it must be
17124              allocated last, so that it will show up before the
17125              non-primary symtabs in the objfile's symtab list.  */
17126           if (current_subfile == first_subfile)
17127             continue;
17128
17129           if (current_subfile->symtab == NULL)
17130             current_subfile->symtab = allocate_symtab (current_subfile->name,
17131                                                        objfile);
17132           fe->symtab = current_subfile->symtab;
17133         }
17134     }
17135 }
17136
17137 /* Start a subfile for DWARF.  FILENAME is the name of the file and
17138    DIRNAME the name of the source directory which contains FILENAME
17139    or NULL if not known.  COMP_DIR is the compilation directory for the
17140    linetable's compilation unit or NULL if not known.
17141    This routine tries to keep line numbers from identical absolute and
17142    relative file names in a common subfile.
17143
17144    Using the `list' example from the GDB testsuite, which resides in
17145    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
17146    of /srcdir/list0.c yields the following debugging information for list0.c:
17147
17148    DW_AT_name:          /srcdir/list0.c
17149    DW_AT_comp_dir:              /compdir
17150    files.files[0].name: list0.h
17151    files.files[0].dir:  /srcdir
17152    files.files[1].name: list0.c
17153    files.files[1].dir:  /srcdir
17154
17155    The line number information for list0.c has to end up in a single
17156    subfile, so that `break /srcdir/list0.c:1' works as expected.
17157    start_subfile will ensure that this happens provided that we pass the
17158    concatenation of files.files[1].dir and files.files[1].name as the
17159    subfile's name.  */
17160
17161 static void
17162 dwarf2_start_subfile (const char *filename, const char *dirname,
17163                       const char *comp_dir)
17164 {
17165   char *copy = NULL;
17166
17167   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
17168      `start_symtab' will always pass the contents of DW_AT_comp_dir as
17169      second argument to start_subfile.  To be consistent, we do the
17170      same here.  In order not to lose the line information directory,
17171      we concatenate it to the filename when it makes sense.
17172      Note that the Dwarf3 standard says (speaking of filenames in line
17173      information): ``The directory index is ignored for file names
17174      that represent full path names''.  Thus ignoring dirname in the
17175      `else' branch below isn't an issue.  */
17176
17177   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
17178     {
17179       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
17180       filename = copy;
17181     }
17182
17183   start_subfile (filename, comp_dir);
17184
17185   if (copy != NULL)
17186     xfree (copy);
17187 }
17188
17189 /* Start a symtab for DWARF.
17190    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
17191
17192 static void
17193 dwarf2_start_symtab (struct dwarf2_cu *cu,
17194                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
17195 {
17196   start_symtab (name, comp_dir, low_pc);
17197   record_debugformat ("DWARF 2");
17198   record_producer (cu->producer);
17199
17200   /* We assume that we're processing GCC output.  */
17201   processing_gcc_compilation = 2;
17202
17203   cu->processing_has_namespace_info = 0;
17204 }
17205
17206 static void
17207 var_decode_location (struct attribute *attr, struct symbol *sym,
17208                      struct dwarf2_cu *cu)
17209 {
17210   struct objfile *objfile = cu->objfile;
17211   struct comp_unit_head *cu_header = &cu->header;
17212
17213   /* NOTE drow/2003-01-30: There used to be a comment and some special
17214      code here to turn a symbol with DW_AT_external and a
17215      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
17216      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
17217      with some versions of binutils) where shared libraries could have
17218      relocations against symbols in their debug information - the
17219      minimal symbol would have the right address, but the debug info
17220      would not.  It's no longer necessary, because we will explicitly
17221      apply relocations when we read in the debug information now.  */
17222
17223   /* A DW_AT_location attribute with no contents indicates that a
17224      variable has been optimized away.  */
17225   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
17226     {
17227       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17228       return;
17229     }
17230
17231   /* Handle one degenerate form of location expression specially, to
17232      preserve GDB's previous behavior when section offsets are
17233      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
17234      then mark this symbol as LOC_STATIC.  */
17235
17236   if (attr_form_is_block (attr)
17237       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
17238            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
17239           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
17240               && (DW_BLOCK (attr)->size
17241                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
17242     {
17243       unsigned int dummy;
17244
17245       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
17246         SYMBOL_VALUE_ADDRESS (sym) =
17247           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
17248       else
17249         SYMBOL_VALUE_ADDRESS (sym) =
17250           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
17251       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
17252       fixup_symbol_section (sym, objfile);
17253       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
17254                                               SYMBOL_SECTION (sym));
17255       return;
17256     }
17257
17258   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
17259      expression evaluator, and use LOC_COMPUTED only when necessary
17260      (i.e. when the value of a register or memory location is
17261      referenced, or a thread-local block, etc.).  Then again, it might
17262      not be worthwhile.  I'm assuming that it isn't unless performance
17263      or memory numbers show me otherwise.  */
17264
17265   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
17266
17267   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
17268     cu->has_loclist = 1;
17269 }
17270
17271 /* Given a pointer to a DWARF information entry, figure out if we need
17272    to make a symbol table entry for it, and if so, create a new entry
17273    and return a pointer to it.
17274    If TYPE is NULL, determine symbol type from the die, otherwise
17275    used the passed type.
17276    If SPACE is not NULL, use it to hold the new symbol.  If it is
17277    NULL, allocate a new symbol on the objfile's obstack.  */
17278
17279 static struct symbol *
17280 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
17281                  struct symbol *space)
17282 {
17283   struct objfile *objfile = cu->objfile;
17284   struct symbol *sym = NULL;
17285   const char *name;
17286   struct attribute *attr = NULL;
17287   struct attribute *attr2 = NULL;
17288   CORE_ADDR baseaddr;
17289   struct pending **list_to_add = NULL;
17290
17291   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
17292
17293   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17294
17295   name = dwarf2_name (die, cu);
17296   if (name)
17297     {
17298       const char *linkagename;
17299       int suppress_add = 0;
17300
17301       if (space)
17302         sym = space;
17303       else
17304         sym = allocate_symbol (objfile);
17305       OBJSTAT (objfile, n_syms++);
17306
17307       /* Cache this symbol's name and the name's demangled form (if any).  */
17308       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
17309       linkagename = dwarf2_physname (name, die, cu);
17310       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
17311
17312       /* Fortran does not have mangling standard and the mangling does differ
17313          between gfortran, iFort etc.  */
17314       if (cu->language == language_fortran
17315           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
17316         symbol_set_demangled_name (&(sym->ginfo),
17317                                    dwarf2_full_name (name, die, cu),
17318                                    NULL);
17319
17320       /* Default assumptions.
17321          Use the passed type or decode it from the die.  */
17322       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17323       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17324       if (type != NULL)
17325         SYMBOL_TYPE (sym) = type;
17326       else
17327         SYMBOL_TYPE (sym) = die_type (die, cu);
17328       attr = dwarf2_attr (die,
17329                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
17330                           cu);
17331       if (attr)
17332         {
17333           SYMBOL_LINE (sym) = DW_UNSND (attr);
17334         }
17335
17336       attr = dwarf2_attr (die,
17337                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
17338                           cu);
17339       if (attr)
17340         {
17341           int file_index = DW_UNSND (attr);
17342
17343           if (cu->line_header == NULL
17344               || file_index > cu->line_header->num_file_names)
17345             complaint (&symfile_complaints,
17346                        _("file index out of range"));
17347           else if (file_index > 0)
17348             {
17349               struct file_entry *fe;
17350
17351               fe = &cu->line_header->file_names[file_index - 1];
17352               SYMBOL_SYMTAB (sym) = fe->symtab;
17353             }
17354         }
17355
17356       switch (die->tag)
17357         {
17358         case DW_TAG_label:
17359           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
17360           if (attr)
17361             {
17362               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
17363             }
17364           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
17365           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
17366           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
17367           add_symbol_to_list (sym, cu->list_in_scope);
17368           break;
17369         case DW_TAG_subprogram:
17370           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17371              finish_block.  */
17372           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17373           attr2 = dwarf2_attr (die, DW_AT_external, cu);
17374           if ((attr2 && (DW_UNSND (attr2) != 0))
17375               || cu->language == language_ada)
17376             {
17377               /* Subprograms marked external are stored as a global symbol.
17378                  Ada subprograms, whether marked external or not, are always
17379                  stored as a global symbol, because we want to be able to
17380                  access them globally.  For instance, we want to be able
17381                  to break on a nested subprogram without having to
17382                  specify the context.  */
17383               list_to_add = &global_symbols;
17384             }
17385           else
17386             {
17387               list_to_add = cu->list_in_scope;
17388             }
17389           break;
17390         case DW_TAG_inlined_subroutine:
17391           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17392              finish_block.  */
17393           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17394           SYMBOL_INLINED (sym) = 1;
17395           list_to_add = cu->list_in_scope;
17396           break;
17397         case DW_TAG_template_value_param:
17398           suppress_add = 1;
17399           /* Fall through.  */
17400         case DW_TAG_constant:
17401         case DW_TAG_variable:
17402         case DW_TAG_member:
17403           /* Compilation with minimal debug info may result in
17404              variables with missing type entries.  Change the
17405              misleading `void' type to something sensible.  */
17406           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
17407             SYMBOL_TYPE (sym)
17408               = objfile_type (objfile)->nodebug_data_symbol;
17409
17410           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17411           /* In the case of DW_TAG_member, we should only be called for
17412              static const members.  */
17413           if (die->tag == DW_TAG_member)
17414             {
17415               /* dwarf2_add_field uses die_is_declaration,
17416                  so we do the same.  */
17417               gdb_assert (die_is_declaration (die, cu));
17418               gdb_assert (attr);
17419             }
17420           if (attr)
17421             {
17422               dwarf2_const_value (attr, sym, cu);
17423               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17424               if (!suppress_add)
17425                 {
17426                   if (attr2 && (DW_UNSND (attr2) != 0))
17427                     list_to_add = &global_symbols;
17428                   else
17429                     list_to_add = cu->list_in_scope;
17430                 }
17431               break;
17432             }
17433           attr = dwarf2_attr (die, DW_AT_location, cu);
17434           if (attr)
17435             {
17436               var_decode_location (attr, sym, cu);
17437               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17438
17439               /* Fortran explicitly imports any global symbols to the local
17440                  scope by DW_TAG_common_block.  */
17441               if (cu->language == language_fortran && die->parent
17442                   && die->parent->tag == DW_TAG_common_block)
17443                 attr2 = NULL;
17444
17445               if (SYMBOL_CLASS (sym) == LOC_STATIC
17446                   && SYMBOL_VALUE_ADDRESS (sym) == 0
17447                   && !dwarf2_per_objfile->has_section_at_zero)
17448                 {
17449                   /* When a static variable is eliminated by the linker,
17450                      the corresponding debug information is not stripped
17451                      out, but the variable address is set to null;
17452                      do not add such variables into symbol table.  */
17453                 }
17454               else if (attr2 && (DW_UNSND (attr2) != 0))
17455                 {
17456                   /* Workaround gfortran PR debug/40040 - it uses
17457                      DW_AT_location for variables in -fPIC libraries which may
17458                      get overriden by other libraries/executable and get
17459                      a different address.  Resolve it by the minimal symbol
17460                      which may come from inferior's executable using copy
17461                      relocation.  Make this workaround only for gfortran as for
17462                      other compilers GDB cannot guess the minimal symbol
17463                      Fortran mangling kind.  */
17464                   if (cu->language == language_fortran && die->parent
17465                       && die->parent->tag == DW_TAG_module
17466                       && cu->producer
17467                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
17468                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17469
17470                   /* A variable with DW_AT_external is never static,
17471                      but it may be block-scoped.  */
17472                   list_to_add = (cu->list_in_scope == &file_symbols
17473                                  ? &global_symbols : cu->list_in_scope);
17474                 }
17475               else
17476                 list_to_add = cu->list_in_scope;
17477             }
17478           else
17479             {
17480               /* We do not know the address of this symbol.
17481                  If it is an external symbol and we have type information
17482                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
17483                  The address of the variable will then be determined from
17484                  the minimal symbol table whenever the variable is
17485                  referenced.  */
17486               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17487
17488               /* Fortran explicitly imports any global symbols to the local
17489                  scope by DW_TAG_common_block.  */
17490               if (cu->language == language_fortran && die->parent
17491                   && die->parent->tag == DW_TAG_common_block)
17492                 {
17493                   /* SYMBOL_CLASS doesn't matter here because
17494                      read_common_block is going to reset it.  */
17495                   if (!suppress_add)
17496                     list_to_add = cu->list_in_scope;
17497                 }
17498               else if (attr2 && (DW_UNSND (attr2) != 0)
17499                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
17500                 {
17501                   /* A variable with DW_AT_external is never static, but it
17502                      may be block-scoped.  */
17503                   list_to_add = (cu->list_in_scope == &file_symbols
17504                                  ? &global_symbols : cu->list_in_scope);
17505
17506                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17507                 }
17508               else if (!die_is_declaration (die, cu))
17509                 {
17510                   /* Use the default LOC_OPTIMIZED_OUT class.  */
17511                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
17512                   if (!suppress_add)
17513                     list_to_add = cu->list_in_scope;
17514                 }
17515             }
17516           break;
17517         case DW_TAG_formal_parameter:
17518           /* If we are inside a function, mark this as an argument.  If
17519              not, we might be looking at an argument to an inlined function
17520              when we do not have enough information to show inlined frames;
17521              pretend it's a local variable in that case so that the user can
17522              still see it.  */
17523           if (context_stack_depth > 0
17524               && context_stack[context_stack_depth - 1].name != NULL)
17525             SYMBOL_IS_ARGUMENT (sym) = 1;
17526           attr = dwarf2_attr (die, DW_AT_location, cu);
17527           if (attr)
17528             {
17529               var_decode_location (attr, sym, cu);
17530             }
17531           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17532           if (attr)
17533             {
17534               dwarf2_const_value (attr, sym, cu);
17535             }
17536
17537           list_to_add = cu->list_in_scope;
17538           break;
17539         case DW_TAG_unspecified_parameters:
17540           /* From varargs functions; gdb doesn't seem to have any
17541              interest in this information, so just ignore it for now.
17542              (FIXME?) */
17543           break;
17544         case DW_TAG_template_type_param:
17545           suppress_add = 1;
17546           /* Fall through.  */
17547         case DW_TAG_class_type:
17548         case DW_TAG_interface_type:
17549         case DW_TAG_structure_type:
17550         case DW_TAG_union_type:
17551         case DW_TAG_set_type:
17552         case DW_TAG_enumeration_type:
17553           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17554           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
17555
17556           {
17557             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
17558                really ever be static objects: otherwise, if you try
17559                to, say, break of a class's method and you're in a file
17560                which doesn't mention that class, it won't work unless
17561                the check for all static symbols in lookup_symbol_aux
17562                saves you.  See the OtherFileClass tests in
17563                gdb.c++/namespace.exp.  */
17564
17565             if (!suppress_add)
17566               {
17567                 list_to_add = (cu->list_in_scope == &file_symbols
17568                                && (cu->language == language_cplus
17569                                    || cu->language == language_java)
17570                                ? &global_symbols : cu->list_in_scope);
17571
17572                 /* The semantics of C++ state that "struct foo {
17573                    ... }" also defines a typedef for "foo".  A Java
17574                    class declaration also defines a typedef for the
17575                    class.  */
17576                 if (cu->language == language_cplus
17577                     || cu->language == language_java
17578                     || cu->language == language_ada)
17579                   {
17580                     /* The symbol's name is already allocated along
17581                        with this objfile, so we don't need to
17582                        duplicate it for the type.  */
17583                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
17584                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
17585                   }
17586               }
17587           }
17588           break;
17589         case DW_TAG_typedef:
17590           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17591           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17592           list_to_add = cu->list_in_scope;
17593           break;
17594         case DW_TAG_base_type:
17595         case DW_TAG_subrange_type:
17596           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17597           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17598           list_to_add = cu->list_in_scope;
17599           break;
17600         case DW_TAG_enumerator:
17601           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17602           if (attr)
17603             {
17604               dwarf2_const_value (attr, sym, cu);
17605             }
17606           {
17607             /* NOTE: carlton/2003-11-10: See comment above in the
17608                DW_TAG_class_type, etc. block.  */
17609
17610             list_to_add = (cu->list_in_scope == &file_symbols
17611                            && (cu->language == language_cplus
17612                                || cu->language == language_java)
17613                            ? &global_symbols : cu->list_in_scope);
17614           }
17615           break;
17616         case DW_TAG_namespace:
17617           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17618           list_to_add = &global_symbols;
17619           break;
17620         case DW_TAG_common_block:
17621           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
17622           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
17623           add_symbol_to_list (sym, cu->list_in_scope);
17624           break;
17625         default:
17626           /* Not a tag we recognize.  Hopefully we aren't processing
17627              trash data, but since we must specifically ignore things
17628              we don't recognize, there is nothing else we should do at
17629              this point.  */
17630           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
17631                      dwarf_tag_name (die->tag));
17632           break;
17633         }
17634
17635       if (suppress_add)
17636         {
17637           sym->hash_next = objfile->template_symbols;
17638           objfile->template_symbols = sym;
17639           list_to_add = NULL;
17640         }
17641
17642       if (list_to_add != NULL)
17643         add_symbol_to_list (sym, list_to_add);
17644
17645       /* For the benefit of old versions of GCC, check for anonymous
17646          namespaces based on the demangled name.  */
17647       if (!cu->processing_has_namespace_info
17648           && cu->language == language_cplus)
17649         cp_scan_for_anonymous_namespaces (sym, objfile);
17650     }
17651   return (sym);
17652 }
17653
17654 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
17655
17656 static struct symbol *
17657 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
17658 {
17659   return new_symbol_full (die, type, cu, NULL);
17660 }
17661
17662 /* Given an attr with a DW_FORM_dataN value in host byte order,
17663    zero-extend it as appropriate for the symbol's type.  The DWARF
17664    standard (v4) is not entirely clear about the meaning of using
17665    DW_FORM_dataN for a constant with a signed type, where the type is
17666    wider than the data.  The conclusion of a discussion on the DWARF
17667    list was that this is unspecified.  We choose to always zero-extend
17668    because that is the interpretation long in use by GCC.  */
17669
17670 static gdb_byte *
17671 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
17672                          struct dwarf2_cu *cu, LONGEST *value, int bits)
17673 {
17674   struct objfile *objfile = cu->objfile;
17675   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
17676                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
17677   LONGEST l = DW_UNSND (attr);
17678
17679   if (bits < sizeof (*value) * 8)
17680     {
17681       l &= ((LONGEST) 1 << bits) - 1;
17682       *value = l;
17683     }
17684   else if (bits == sizeof (*value) * 8)
17685     *value = l;
17686   else
17687     {
17688       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
17689       store_unsigned_integer (bytes, bits / 8, byte_order, l);
17690       return bytes;
17691     }
17692
17693   return NULL;
17694 }
17695
17696 /* Read a constant value from an attribute.  Either set *VALUE, or if
17697    the value does not fit in *VALUE, set *BYTES - either already
17698    allocated on the objfile obstack, or newly allocated on OBSTACK,
17699    or, set *BATON, if we translated the constant to a location
17700    expression.  */
17701
17702 static void
17703 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
17704                          const char *name, struct obstack *obstack,
17705                          struct dwarf2_cu *cu,
17706                          LONGEST *value, const gdb_byte **bytes,
17707                          struct dwarf2_locexpr_baton **baton)
17708 {
17709   struct objfile *objfile = cu->objfile;
17710   struct comp_unit_head *cu_header = &cu->header;
17711   struct dwarf_block *blk;
17712   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
17713                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
17714
17715   *value = 0;
17716   *bytes = NULL;
17717   *baton = NULL;
17718
17719   switch (attr->form)
17720     {
17721     case DW_FORM_addr:
17722     case DW_FORM_GNU_addr_index:
17723       {
17724         gdb_byte *data;
17725
17726         if (TYPE_LENGTH (type) != cu_header->addr_size)
17727           dwarf2_const_value_length_mismatch_complaint (name,
17728                                                         cu_header->addr_size,
17729                                                         TYPE_LENGTH (type));
17730         /* Symbols of this form are reasonably rare, so we just
17731            piggyback on the existing location code rather than writing
17732            a new implementation of symbol_computed_ops.  */
17733         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
17734         (*baton)->per_cu = cu->per_cu;
17735         gdb_assert ((*baton)->per_cu);
17736
17737         (*baton)->size = 2 + cu_header->addr_size;
17738         data = obstack_alloc (obstack, (*baton)->size);
17739         (*baton)->data = data;
17740
17741         data[0] = DW_OP_addr;
17742         store_unsigned_integer (&data[1], cu_header->addr_size,
17743                                 byte_order, DW_ADDR (attr));
17744         data[cu_header->addr_size + 1] = DW_OP_stack_value;
17745       }
17746       break;
17747     case DW_FORM_string:
17748     case DW_FORM_strp:
17749     case DW_FORM_GNU_str_index:
17750     case DW_FORM_GNU_strp_alt:
17751       /* DW_STRING is already allocated on the objfile obstack, point
17752          directly to it.  */
17753       *bytes = (const gdb_byte *) DW_STRING (attr);
17754       break;
17755     case DW_FORM_block1:
17756     case DW_FORM_block2:
17757     case DW_FORM_block4:
17758     case DW_FORM_block:
17759     case DW_FORM_exprloc:
17760       blk = DW_BLOCK (attr);
17761       if (TYPE_LENGTH (type) != blk->size)
17762         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
17763                                                       TYPE_LENGTH (type));
17764       *bytes = blk->data;
17765       break;
17766
17767       /* The DW_AT_const_value attributes are supposed to carry the
17768          symbol's value "represented as it would be on the target
17769          architecture."  By the time we get here, it's already been
17770          converted to host endianness, so we just need to sign- or
17771          zero-extend it as appropriate.  */
17772     case DW_FORM_data1:
17773       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
17774       break;
17775     case DW_FORM_data2:
17776       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
17777       break;
17778     case DW_FORM_data4:
17779       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
17780       break;
17781     case DW_FORM_data8:
17782       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
17783       break;
17784
17785     case DW_FORM_sdata:
17786       *value = DW_SND (attr);
17787       break;
17788
17789     case DW_FORM_udata:
17790       *value = DW_UNSND (attr);
17791       break;
17792
17793     default:
17794       complaint (&symfile_complaints,
17795                  _("unsupported const value attribute form: '%s'"),
17796                  dwarf_form_name (attr->form));
17797       *value = 0;
17798       break;
17799     }
17800 }
17801
17802
17803 /* Copy constant value from an attribute to a symbol.  */
17804
17805 static void
17806 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
17807                     struct dwarf2_cu *cu)
17808 {
17809   struct objfile *objfile = cu->objfile;
17810   struct comp_unit_head *cu_header = &cu->header;
17811   LONGEST value;
17812   const gdb_byte *bytes;
17813   struct dwarf2_locexpr_baton *baton;
17814
17815   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
17816                            SYMBOL_PRINT_NAME (sym),
17817                            &objfile->objfile_obstack, cu,
17818                            &value, &bytes, &baton);
17819
17820   if (baton != NULL)
17821     {
17822       SYMBOL_LOCATION_BATON (sym) = baton;
17823       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17824     }
17825   else if (bytes != NULL)
17826      {
17827       SYMBOL_VALUE_BYTES (sym) = bytes;
17828       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
17829     }
17830   else
17831     {
17832       SYMBOL_VALUE (sym) = value;
17833       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17834     }
17835 }
17836
17837 /* Return the type of the die in question using its DW_AT_type attribute.  */
17838
17839 static struct type *
17840 die_type (struct die_info *die, struct dwarf2_cu *cu)
17841 {
17842   struct attribute *type_attr;
17843
17844   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17845   if (!type_attr)
17846     {
17847       /* A missing DW_AT_type represents a void type.  */
17848       return objfile_type (cu->objfile)->builtin_void;
17849     }
17850
17851   return lookup_die_type (die, type_attr, cu);
17852 }
17853
17854 /* True iff CU's producer generates GNAT Ada auxiliary information
17855    that allows to find parallel types through that information instead
17856    of having to do expensive parallel lookups by type name.  */
17857
17858 static int
17859 need_gnat_info (struct dwarf2_cu *cu)
17860 {
17861   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17862      of GNAT produces this auxiliary information, without any indication
17863      that it is produced.  Part of enhancing the FSF version of GNAT
17864      to produce that information will be to put in place an indicator
17865      that we can use in order to determine whether the descriptive type
17866      info is available or not.  One suggestion that has been made is
17867      to use a new attribute, attached to the CU die.  For now, assume
17868      that the descriptive type info is not available.  */
17869   return 0;
17870 }
17871
17872 /* Return the auxiliary type of the die in question using its
17873    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17874    attribute is not present.  */
17875
17876 static struct type *
17877 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17878 {
17879   struct attribute *type_attr;
17880
17881   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17882   if (!type_attr)
17883     return NULL;
17884
17885   return lookup_die_type (die, type_attr, cu);
17886 }
17887
17888 /* If DIE has a descriptive_type attribute, then set the TYPE's
17889    descriptive type accordingly.  */
17890
17891 static void
17892 set_descriptive_type (struct type *type, struct die_info *die,
17893                       struct dwarf2_cu *cu)
17894 {
17895   struct type *descriptive_type = die_descriptive_type (die, cu);
17896
17897   if (descriptive_type)
17898     {
17899       ALLOCATE_GNAT_AUX_TYPE (type);
17900       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17901     }
17902 }
17903
17904 /* Return the containing type of the die in question using its
17905    DW_AT_containing_type attribute.  */
17906
17907 static struct type *
17908 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17909 {
17910   struct attribute *type_attr;
17911
17912   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17913   if (!type_attr)
17914     error (_("Dwarf Error: Problem turning containing type into gdb type "
17915              "[in module %s]"), objfile_name (cu->objfile));
17916
17917   return lookup_die_type (die, type_attr, cu);
17918 }
17919
17920 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17921
17922 static struct type *
17923 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17924 {
17925   struct objfile *objfile = dwarf2_per_objfile->objfile;
17926   char *message, *saved;
17927
17928   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17929                         objfile_name (objfile),
17930                         cu->header.offset.sect_off,
17931                         die->offset.sect_off);
17932   saved = obstack_copy0 (&objfile->objfile_obstack,
17933                          message, strlen (message));
17934   xfree (message);
17935
17936   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17937 }
17938
17939 /* Look up the type of DIE in CU using its type attribute ATTR.
17940    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17941    DW_AT_containing_type.
17942    If there is no type substitute an error marker.  */
17943
17944 static struct type *
17945 lookup_die_type (struct die_info *die, const struct attribute *attr,
17946                  struct dwarf2_cu *cu)
17947 {
17948   struct objfile *objfile = cu->objfile;
17949   struct type *this_type;
17950
17951   gdb_assert (attr->name == DW_AT_type
17952               || attr->name == DW_AT_GNAT_descriptive_type
17953               || attr->name == DW_AT_containing_type);
17954
17955   /* First see if we have it cached.  */
17956
17957   if (attr->form == DW_FORM_GNU_ref_alt)
17958     {
17959       struct dwarf2_per_cu_data *per_cu;
17960       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17961
17962       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17963       this_type = get_die_type_at_offset (offset, per_cu);
17964     }
17965   else if (attr_form_is_ref (attr))
17966     {
17967       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17968
17969       this_type = get_die_type_at_offset (offset, cu->per_cu);
17970     }
17971   else if (attr->form == DW_FORM_ref_sig8)
17972     {
17973       ULONGEST signature = DW_SIGNATURE (attr);
17974
17975       return get_signatured_type (die, signature, cu);
17976     }
17977   else
17978     {
17979       complaint (&symfile_complaints,
17980                  _("Dwarf Error: Bad type attribute %s in DIE"
17981                    " at 0x%x [in module %s]"),
17982                  dwarf_attr_name (attr->name), die->offset.sect_off,
17983                  objfile_name (objfile));
17984       return build_error_marker_type (cu, die);
17985     }
17986
17987   /* If not cached we need to read it in.  */
17988
17989   if (this_type == NULL)
17990     {
17991       struct die_info *type_die = NULL;
17992       struct dwarf2_cu *type_cu = cu;
17993
17994       if (attr_form_is_ref (attr))
17995         type_die = follow_die_ref (die, attr, &type_cu);
17996       if (type_die == NULL)
17997         return build_error_marker_type (cu, die);
17998       /* If we find the type now, it's probably because the type came
17999          from an inter-CU reference and the type's CU got expanded before
18000          ours.  */
18001       this_type = read_type_die (type_die, type_cu);
18002     }
18003
18004   /* If we still don't have a type use an error marker.  */
18005
18006   if (this_type == NULL)
18007     return build_error_marker_type (cu, die);
18008
18009   return this_type;
18010 }
18011
18012 /* Return the type in DIE, CU.
18013    Returns NULL for invalid types.
18014
18015    This first does a lookup in die_type_hash,
18016    and only reads the die in if necessary.
18017
18018    NOTE: This can be called when reading in partial or full symbols.  */
18019
18020 static struct type *
18021 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
18022 {
18023   struct type *this_type;
18024
18025   this_type = get_die_type (die, cu);
18026   if (this_type)
18027     return this_type;
18028
18029   return read_type_die_1 (die, cu);
18030 }
18031
18032 /* Read the type in DIE, CU.
18033    Returns NULL for invalid types.  */
18034
18035 static struct type *
18036 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
18037 {
18038   struct type *this_type = NULL;
18039
18040   switch (die->tag)
18041     {
18042     case DW_TAG_class_type:
18043     case DW_TAG_interface_type:
18044     case DW_TAG_structure_type:
18045     case DW_TAG_union_type:
18046       this_type = read_structure_type (die, cu);
18047       break;
18048     case DW_TAG_enumeration_type:
18049       this_type = read_enumeration_type (die, cu);
18050       break;
18051     case DW_TAG_subprogram:
18052     case DW_TAG_subroutine_type:
18053     case DW_TAG_inlined_subroutine:
18054       this_type = read_subroutine_type (die, cu);
18055       break;
18056     case DW_TAG_array_type:
18057       this_type = read_array_type (die, cu);
18058       break;
18059     case DW_TAG_set_type:
18060       this_type = read_set_type (die, cu);
18061       break;
18062     case DW_TAG_pointer_type:
18063       this_type = read_tag_pointer_type (die, cu);
18064       break;
18065     case DW_TAG_ptr_to_member_type:
18066       this_type = read_tag_ptr_to_member_type (die, cu);
18067       break;
18068     case DW_TAG_reference_type:
18069       this_type = read_tag_reference_type (die, cu);
18070       break;
18071     case DW_TAG_const_type:
18072       this_type = read_tag_const_type (die, cu);
18073       break;
18074     case DW_TAG_volatile_type:
18075       this_type = read_tag_volatile_type (die, cu);
18076       break;
18077     case DW_TAG_restrict_type:
18078       this_type = read_tag_restrict_type (die, cu);
18079       break;
18080     case DW_TAG_string_type:
18081       this_type = read_tag_string_type (die, cu);
18082       break;
18083     case DW_TAG_typedef:
18084       this_type = read_typedef (die, cu);
18085       break;
18086     case DW_TAG_subrange_type:
18087       this_type = read_subrange_type (die, cu);
18088       break;
18089     case DW_TAG_base_type:
18090       this_type = read_base_type (die, cu);
18091       break;
18092     case DW_TAG_unspecified_type:
18093       this_type = read_unspecified_type (die, cu);
18094       break;
18095     case DW_TAG_namespace:
18096       this_type = read_namespace_type (die, cu);
18097       break;
18098     case DW_TAG_module:
18099       this_type = read_module_type (die, cu);
18100       break;
18101     default:
18102       complaint (&symfile_complaints,
18103                  _("unexpected tag in read_type_die: '%s'"),
18104                  dwarf_tag_name (die->tag));
18105       break;
18106     }
18107
18108   return this_type;
18109 }
18110
18111 /* See if we can figure out if the class lives in a namespace.  We do
18112    this by looking for a member function; its demangled name will
18113    contain namespace info, if there is any.
18114    Return the computed name or NULL.
18115    Space for the result is allocated on the objfile's obstack.
18116    This is the full-die version of guess_partial_die_structure_name.
18117    In this case we know DIE has no useful parent.  */
18118
18119 static char *
18120 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
18121 {
18122   struct die_info *spec_die;
18123   struct dwarf2_cu *spec_cu;
18124   struct die_info *child;
18125
18126   spec_cu = cu;
18127   spec_die = die_specification (die, &spec_cu);
18128   if (spec_die != NULL)
18129     {
18130       die = spec_die;
18131       cu = spec_cu;
18132     }
18133
18134   for (child = die->child;
18135        child != NULL;
18136        child = child->sibling)
18137     {
18138       if (child->tag == DW_TAG_subprogram)
18139         {
18140           struct attribute *attr;
18141
18142           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
18143           if (attr == NULL)
18144             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
18145           if (attr != NULL)
18146             {
18147               char *actual_name
18148                 = language_class_name_from_physname (cu->language_defn,
18149                                                      DW_STRING (attr));
18150               char *name = NULL;
18151
18152               if (actual_name != NULL)
18153                 {
18154                   const char *die_name = dwarf2_name (die, cu);
18155
18156                   if (die_name != NULL
18157                       && strcmp (die_name, actual_name) != 0)
18158                     {
18159                       /* Strip off the class name from the full name.
18160                          We want the prefix.  */
18161                       int die_name_len = strlen (die_name);
18162                       int actual_name_len = strlen (actual_name);
18163
18164                       /* Test for '::' as a sanity check.  */
18165                       if (actual_name_len > die_name_len + 2
18166                           && actual_name[actual_name_len
18167                                          - die_name_len - 1] == ':')
18168                         name =
18169                           obstack_copy0 (&cu->objfile->objfile_obstack,
18170                                          actual_name,
18171                                          actual_name_len - die_name_len - 2);
18172                     }
18173                 }
18174               xfree (actual_name);
18175               return name;
18176             }
18177         }
18178     }
18179
18180   return NULL;
18181 }
18182
18183 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
18184    prefix part in such case.  See
18185    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18186
18187 static char *
18188 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
18189 {
18190   struct attribute *attr;
18191   char *base;
18192
18193   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
18194       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
18195     return NULL;
18196
18197   attr = dwarf2_attr (die, DW_AT_name, cu);
18198   if (attr != NULL && DW_STRING (attr) != NULL)
18199     return NULL;
18200
18201   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18202   if (attr == NULL)
18203     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18204   if (attr == NULL || DW_STRING (attr) == NULL)
18205     return NULL;
18206
18207   /* dwarf2_name had to be already called.  */
18208   gdb_assert (DW_STRING_IS_CANONICAL (attr));
18209
18210   /* Strip the base name, keep any leading namespaces/classes.  */
18211   base = strrchr (DW_STRING (attr), ':');
18212   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
18213     return "";
18214
18215   return obstack_copy0 (&cu->objfile->objfile_obstack,
18216                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
18217 }
18218
18219 /* Return the name of the namespace/class that DIE is defined within,
18220    or "" if we can't tell.  The caller should not xfree the result.
18221
18222    For example, if we're within the method foo() in the following
18223    code:
18224
18225    namespace N {
18226      class C {
18227        void foo () {
18228        }
18229      };
18230    }
18231
18232    then determine_prefix on foo's die will return "N::C".  */
18233
18234 static const char *
18235 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
18236 {
18237   struct die_info *parent, *spec_die;
18238   struct dwarf2_cu *spec_cu;
18239   struct type *parent_type;
18240   char *retval;
18241
18242   if (cu->language != language_cplus && cu->language != language_java
18243       && cu->language != language_fortran)
18244     return "";
18245
18246   retval = anonymous_struct_prefix (die, cu);
18247   if (retval)
18248     return retval;
18249
18250   /* We have to be careful in the presence of DW_AT_specification.
18251      For example, with GCC 3.4, given the code
18252
18253      namespace N {
18254        void foo() {
18255          // Definition of N::foo.
18256        }
18257      }
18258
18259      then we'll have a tree of DIEs like this:
18260
18261      1: DW_TAG_compile_unit
18262        2: DW_TAG_namespace        // N
18263          3: DW_TAG_subprogram     // declaration of N::foo
18264        4: DW_TAG_subprogram       // definition of N::foo
18265             DW_AT_specification   // refers to die #3
18266
18267      Thus, when processing die #4, we have to pretend that we're in
18268      the context of its DW_AT_specification, namely the contex of die
18269      #3.  */
18270   spec_cu = cu;
18271   spec_die = die_specification (die, &spec_cu);
18272   if (spec_die == NULL)
18273     parent = die->parent;
18274   else
18275     {
18276       parent = spec_die->parent;
18277       cu = spec_cu;
18278     }
18279
18280   if (parent == NULL)
18281     return "";
18282   else if (parent->building_fullname)
18283     {
18284       const char *name;
18285       const char *parent_name;
18286
18287       /* It has been seen on RealView 2.2 built binaries,
18288          DW_TAG_template_type_param types actually _defined_ as
18289          children of the parent class:
18290
18291          enum E {};
18292          template class <class Enum> Class{};
18293          Class<enum E> class_e;
18294
18295          1: DW_TAG_class_type (Class)
18296            2: DW_TAG_enumeration_type (E)
18297              3: DW_TAG_enumerator (enum1:0)
18298              3: DW_TAG_enumerator (enum2:1)
18299              ...
18300            2: DW_TAG_template_type_param
18301               DW_AT_type  DW_FORM_ref_udata (E)
18302
18303          Besides being broken debug info, it can put GDB into an
18304          infinite loop.  Consider:
18305
18306          When we're building the full name for Class<E>, we'll start
18307          at Class, and go look over its template type parameters,
18308          finding E.  We'll then try to build the full name of E, and
18309          reach here.  We're now trying to build the full name of E,
18310          and look over the parent DIE for containing scope.  In the
18311          broken case, if we followed the parent DIE of E, we'd again
18312          find Class, and once again go look at its template type
18313          arguments, etc., etc.  Simply don't consider such parent die
18314          as source-level parent of this die (it can't be, the language
18315          doesn't allow it), and break the loop here.  */
18316       name = dwarf2_name (die, cu);
18317       parent_name = dwarf2_name (parent, cu);
18318       complaint (&symfile_complaints,
18319                  _("template param type '%s' defined within parent '%s'"),
18320                  name ? name : "<unknown>",
18321                  parent_name ? parent_name : "<unknown>");
18322       return "";
18323     }
18324   else
18325     switch (parent->tag)
18326       {
18327       case DW_TAG_namespace:
18328         parent_type = read_type_die (parent, cu);
18329         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
18330            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
18331            Work around this problem here.  */
18332         if (cu->language == language_cplus
18333             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
18334           return "";
18335         /* We give a name to even anonymous namespaces.  */
18336         return TYPE_TAG_NAME (parent_type);
18337       case DW_TAG_class_type:
18338       case DW_TAG_interface_type:
18339       case DW_TAG_structure_type:
18340       case DW_TAG_union_type:
18341       case DW_TAG_module:
18342         parent_type = read_type_die (parent, cu);
18343         if (TYPE_TAG_NAME (parent_type) != NULL)
18344           return TYPE_TAG_NAME (parent_type);
18345         else
18346           /* An anonymous structure is only allowed non-static data
18347              members; no typedefs, no member functions, et cetera.
18348              So it does not need a prefix.  */
18349           return "";
18350       case DW_TAG_compile_unit:
18351       case DW_TAG_partial_unit:
18352         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
18353         if (cu->language == language_cplus
18354             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18355             && die->child != NULL
18356             && (die->tag == DW_TAG_class_type
18357                 || die->tag == DW_TAG_structure_type
18358                 || die->tag == DW_TAG_union_type))
18359           {
18360             char *name = guess_full_die_structure_name (die, cu);
18361             if (name != NULL)
18362               return name;
18363           }
18364         return "";
18365       default:
18366         return determine_prefix (parent, cu);
18367       }
18368 }
18369
18370 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
18371    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
18372    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
18373    an obconcat, otherwise allocate storage for the result.  The CU argument is
18374    used to determine the language and hence, the appropriate separator.  */
18375
18376 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
18377
18378 static char *
18379 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
18380                  int physname, struct dwarf2_cu *cu)
18381 {
18382   const char *lead = "";
18383   const char *sep;
18384
18385   if (suffix == NULL || suffix[0] == '\0'
18386       || prefix == NULL || prefix[0] == '\0')
18387     sep = "";
18388   else if (cu->language == language_java)
18389     sep = ".";
18390   else if (cu->language == language_fortran && physname)
18391     {
18392       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
18393          DW_AT_MIPS_linkage_name is preferred and used instead.  */
18394
18395       lead = "__";
18396       sep = "_MOD_";
18397     }
18398   else
18399     sep = "::";
18400
18401   if (prefix == NULL)
18402     prefix = "";
18403   if (suffix == NULL)
18404     suffix = "";
18405
18406   if (obs == NULL)
18407     {
18408       char *retval
18409         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
18410
18411       strcpy (retval, lead);
18412       strcat (retval, prefix);
18413       strcat (retval, sep);
18414       strcat (retval, suffix);
18415       return retval;
18416     }
18417   else
18418     {
18419       /* We have an obstack.  */
18420       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
18421     }
18422 }
18423
18424 /* Return sibling of die, NULL if no sibling.  */
18425
18426 static struct die_info *
18427 sibling_die (struct die_info *die)
18428 {
18429   return die->sibling;
18430 }
18431
18432 /* Get name of a die, return NULL if not found.  */
18433
18434 static const char *
18435 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
18436                           struct obstack *obstack)
18437 {
18438   if (name && cu->language == language_cplus)
18439     {
18440       char *canon_name = cp_canonicalize_string (name);
18441
18442       if (canon_name != NULL)
18443         {
18444           if (strcmp (canon_name, name) != 0)
18445             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
18446           xfree (canon_name);
18447         }
18448     }
18449
18450   return name;
18451 }
18452
18453 /* Get name of a die, return NULL if not found.  */
18454
18455 static const char *
18456 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
18457 {
18458   struct attribute *attr;
18459
18460   attr = dwarf2_attr (die, DW_AT_name, cu);
18461   if ((!attr || !DW_STRING (attr))
18462       && die->tag != DW_TAG_class_type
18463       && die->tag != DW_TAG_interface_type
18464       && die->tag != DW_TAG_structure_type
18465       && die->tag != DW_TAG_union_type)
18466     return NULL;
18467
18468   switch (die->tag)
18469     {
18470     case DW_TAG_compile_unit:
18471     case DW_TAG_partial_unit:
18472       /* Compilation units have a DW_AT_name that is a filename, not
18473          a source language identifier.  */
18474     case DW_TAG_enumeration_type:
18475     case DW_TAG_enumerator:
18476       /* These tags always have simple identifiers already; no need
18477          to canonicalize them.  */
18478       return DW_STRING (attr);
18479
18480     case DW_TAG_subprogram:
18481       /* Java constructors will all be named "<init>", so return
18482          the class name when we see this special case.  */
18483       if (cu->language == language_java
18484           && DW_STRING (attr) != NULL
18485           && strcmp (DW_STRING (attr), "<init>") == 0)
18486         {
18487           struct dwarf2_cu *spec_cu = cu;
18488           struct die_info *spec_die;
18489
18490           /* GCJ will output '<init>' for Java constructor names.
18491              For this special case, return the name of the parent class.  */
18492
18493           /* GCJ may output suprogram DIEs with AT_specification set.
18494              If so, use the name of the specified DIE.  */
18495           spec_die = die_specification (die, &spec_cu);
18496           if (spec_die != NULL)
18497             return dwarf2_name (spec_die, spec_cu);
18498
18499           do
18500             {
18501               die = die->parent;
18502               if (die->tag == DW_TAG_class_type)
18503                 return dwarf2_name (die, cu);
18504             }
18505           while (die->tag != DW_TAG_compile_unit
18506                  && die->tag != DW_TAG_partial_unit);
18507         }
18508       break;
18509
18510     case DW_TAG_class_type:
18511     case DW_TAG_interface_type:
18512     case DW_TAG_structure_type:
18513     case DW_TAG_union_type:
18514       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
18515          structures or unions.  These were of the form "._%d" in GCC 4.1,
18516          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
18517          and GCC 4.4.  We work around this problem by ignoring these.  */
18518       if (attr && DW_STRING (attr)
18519           && (strncmp (DW_STRING (attr), "._", 2) == 0
18520               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
18521         return NULL;
18522
18523       /* GCC might emit a nameless typedef that has a linkage name.  See
18524          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18525       if (!attr || DW_STRING (attr) == NULL)
18526         {
18527           char *demangled = NULL;
18528
18529           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18530           if (attr == NULL)
18531             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18532
18533           if (attr == NULL || DW_STRING (attr) == NULL)
18534             return NULL;
18535
18536           /* Avoid demangling DW_STRING (attr) the second time on a second
18537              call for the same DIE.  */
18538           if (!DW_STRING_IS_CANONICAL (attr))
18539             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
18540
18541           if (demangled)
18542             {
18543               char *base;
18544
18545               /* FIXME: we already did this for the partial symbol... */
18546               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
18547                                                 demangled, strlen (demangled));
18548               DW_STRING_IS_CANONICAL (attr) = 1;
18549               xfree (demangled);
18550
18551               /* Strip any leading namespaces/classes, keep only the base name.
18552                  DW_AT_name for named DIEs does not contain the prefixes.  */
18553               base = strrchr (DW_STRING (attr), ':');
18554               if (base && base > DW_STRING (attr) && base[-1] == ':')
18555                 return &base[1];
18556               else
18557                 return DW_STRING (attr);
18558             }
18559         }
18560       break;
18561
18562     default:
18563       break;
18564     }
18565
18566   if (!DW_STRING_IS_CANONICAL (attr))
18567     {
18568       DW_STRING (attr)
18569         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
18570                                     &cu->objfile->objfile_obstack);
18571       DW_STRING_IS_CANONICAL (attr) = 1;
18572     }
18573   return DW_STRING (attr);
18574 }
18575
18576 /* Return the die that this die in an extension of, or NULL if there
18577    is none.  *EXT_CU is the CU containing DIE on input, and the CU
18578    containing the return value on output.  */
18579
18580 static struct die_info *
18581 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
18582 {
18583   struct attribute *attr;
18584
18585   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
18586   if (attr == NULL)
18587     return NULL;
18588
18589   return follow_die_ref (die, attr, ext_cu);
18590 }
18591
18592 /* Convert a DIE tag into its string name.  */
18593
18594 static const char *
18595 dwarf_tag_name (unsigned tag)
18596 {
18597   const char *name = get_DW_TAG_name (tag);
18598
18599   if (name == NULL)
18600     return "DW_TAG_<unknown>";
18601
18602   return name;
18603 }
18604
18605 /* Convert a DWARF attribute code into its string name.  */
18606
18607 static const char *
18608 dwarf_attr_name (unsigned attr)
18609 {
18610   const char *name;
18611
18612 #ifdef MIPS /* collides with DW_AT_HP_block_index */
18613   if (attr == DW_AT_MIPS_fde)
18614     return "DW_AT_MIPS_fde";
18615 #else
18616   if (attr == DW_AT_HP_block_index)
18617     return "DW_AT_HP_block_index";
18618 #endif
18619
18620   name = get_DW_AT_name (attr);
18621
18622   if (name == NULL)
18623     return "DW_AT_<unknown>";
18624
18625   return name;
18626 }
18627
18628 /* Convert a DWARF value form code into its string name.  */
18629
18630 static const char *
18631 dwarf_form_name (unsigned form)
18632 {
18633   const char *name = get_DW_FORM_name (form);
18634
18635   if (name == NULL)
18636     return "DW_FORM_<unknown>";
18637
18638   return name;
18639 }
18640
18641 static char *
18642 dwarf_bool_name (unsigned mybool)
18643 {
18644   if (mybool)
18645     return "TRUE";
18646   else
18647     return "FALSE";
18648 }
18649
18650 /* Convert a DWARF type code into its string name.  */
18651
18652 static const char *
18653 dwarf_type_encoding_name (unsigned enc)
18654 {
18655   const char *name = get_DW_ATE_name (enc);
18656
18657   if (name == NULL)
18658     return "DW_ATE_<unknown>";
18659
18660   return name;
18661 }
18662
18663 static void
18664 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
18665 {
18666   unsigned int i;
18667
18668   print_spaces (indent, f);
18669   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
18670            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
18671
18672   if (die->parent != NULL)
18673     {
18674       print_spaces (indent, f);
18675       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
18676                           die->parent->offset.sect_off);
18677     }
18678
18679   print_spaces (indent, f);
18680   fprintf_unfiltered (f, "  has children: %s\n",
18681            dwarf_bool_name (die->child != NULL));
18682
18683   print_spaces (indent, f);
18684   fprintf_unfiltered (f, "  attributes:\n");
18685
18686   for (i = 0; i < die->num_attrs; ++i)
18687     {
18688       print_spaces (indent, f);
18689       fprintf_unfiltered (f, "    %s (%s) ",
18690                dwarf_attr_name (die->attrs[i].name),
18691                dwarf_form_name (die->attrs[i].form));
18692
18693       switch (die->attrs[i].form)
18694         {
18695         case DW_FORM_addr:
18696         case DW_FORM_GNU_addr_index:
18697           fprintf_unfiltered (f, "address: ");
18698           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
18699           break;
18700         case DW_FORM_block2:
18701         case DW_FORM_block4:
18702         case DW_FORM_block:
18703         case DW_FORM_block1:
18704           fprintf_unfiltered (f, "block: size %s",
18705                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18706           break;
18707         case DW_FORM_exprloc:
18708           fprintf_unfiltered (f, "expression: size %s",
18709                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18710           break;
18711         case DW_FORM_ref_addr:
18712           fprintf_unfiltered (f, "ref address: ");
18713           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18714           break;
18715         case DW_FORM_GNU_ref_alt:
18716           fprintf_unfiltered (f, "alt ref address: ");
18717           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18718           break;
18719         case DW_FORM_ref1:
18720         case DW_FORM_ref2:
18721         case DW_FORM_ref4:
18722         case DW_FORM_ref8:
18723         case DW_FORM_ref_udata:
18724           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
18725                               (long) (DW_UNSND (&die->attrs[i])));
18726           break;
18727         case DW_FORM_data1:
18728         case DW_FORM_data2:
18729         case DW_FORM_data4:
18730         case DW_FORM_data8:
18731         case DW_FORM_udata:
18732         case DW_FORM_sdata:
18733           fprintf_unfiltered (f, "constant: %s",
18734                               pulongest (DW_UNSND (&die->attrs[i])));
18735           break;
18736         case DW_FORM_sec_offset:
18737           fprintf_unfiltered (f, "section offset: %s",
18738                               pulongest (DW_UNSND (&die->attrs[i])));
18739           break;
18740         case DW_FORM_ref_sig8:
18741           fprintf_unfiltered (f, "signature: %s",
18742                               hex_string (DW_SIGNATURE (&die->attrs[i])));
18743           break;
18744         case DW_FORM_string:
18745         case DW_FORM_strp:
18746         case DW_FORM_GNU_str_index:
18747         case DW_FORM_GNU_strp_alt:
18748           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
18749                    DW_STRING (&die->attrs[i])
18750                    ? DW_STRING (&die->attrs[i]) : "",
18751                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
18752           break;
18753         case DW_FORM_flag:
18754           if (DW_UNSND (&die->attrs[i]))
18755             fprintf_unfiltered (f, "flag: TRUE");
18756           else
18757             fprintf_unfiltered (f, "flag: FALSE");
18758           break;
18759         case DW_FORM_flag_present:
18760           fprintf_unfiltered (f, "flag: TRUE");
18761           break;
18762         case DW_FORM_indirect:
18763           /* The reader will have reduced the indirect form to
18764              the "base form" so this form should not occur.  */
18765           fprintf_unfiltered (f, 
18766                               "unexpected attribute form: DW_FORM_indirect");
18767           break;
18768         default:
18769           fprintf_unfiltered (f, "unsupported attribute form: %d.",
18770                    die->attrs[i].form);
18771           break;
18772         }
18773       fprintf_unfiltered (f, "\n");
18774     }
18775 }
18776
18777 static void
18778 dump_die_for_error (struct die_info *die)
18779 {
18780   dump_die_shallow (gdb_stderr, 0, die);
18781 }
18782
18783 static void
18784 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
18785 {
18786   int indent = level * 4;
18787
18788   gdb_assert (die != NULL);
18789
18790   if (level >= max_level)
18791     return;
18792
18793   dump_die_shallow (f, indent, die);
18794
18795   if (die->child != NULL)
18796     {
18797       print_spaces (indent, f);
18798       fprintf_unfiltered (f, "  Children:");
18799       if (level + 1 < max_level)
18800         {
18801           fprintf_unfiltered (f, "\n");
18802           dump_die_1 (f, level + 1, max_level, die->child);
18803         }
18804       else
18805         {
18806           fprintf_unfiltered (f,
18807                               " [not printed, max nesting level reached]\n");
18808         }
18809     }
18810
18811   if (die->sibling != NULL && level > 0)
18812     {
18813       dump_die_1 (f, level, max_level, die->sibling);
18814     }
18815 }
18816
18817 /* This is called from the pdie macro in gdbinit.in.
18818    It's not static so gcc will keep a copy callable from gdb.  */
18819
18820 void
18821 dump_die (struct die_info *die, int max_level)
18822 {
18823   dump_die_1 (gdb_stdlog, 0, max_level, die);
18824 }
18825
18826 static void
18827 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
18828 {
18829   void **slot;
18830
18831   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18832                                    INSERT);
18833
18834   *slot = die;
18835 }
18836
18837 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18838    required kind.  */
18839
18840 static sect_offset
18841 dwarf2_get_ref_die_offset (const struct attribute *attr)
18842 {
18843   sect_offset retval = { DW_UNSND (attr) };
18844
18845   if (attr_form_is_ref (attr))
18846     return retval;
18847
18848   retval.sect_off = 0;
18849   complaint (&symfile_complaints,
18850              _("unsupported die ref attribute form: '%s'"),
18851              dwarf_form_name (attr->form));
18852   return retval;
18853 }
18854
18855 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18856  * the value held by the attribute is not constant.  */
18857
18858 static LONGEST
18859 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18860 {
18861   if (attr->form == DW_FORM_sdata)
18862     return DW_SND (attr);
18863   else if (attr->form == DW_FORM_udata
18864            || attr->form == DW_FORM_data1
18865            || attr->form == DW_FORM_data2
18866            || attr->form == DW_FORM_data4
18867            || attr->form == DW_FORM_data8)
18868     return DW_UNSND (attr);
18869   else
18870     {
18871       complaint (&symfile_complaints,
18872                  _("Attribute value is not a constant (%s)"),
18873                  dwarf_form_name (attr->form));
18874       return default_value;
18875     }
18876 }
18877
18878 /* Follow reference or signature attribute ATTR of SRC_DIE.
18879    On entry *REF_CU is the CU of SRC_DIE.
18880    On exit *REF_CU is the CU of the result.  */
18881
18882 static struct die_info *
18883 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18884                        struct dwarf2_cu **ref_cu)
18885 {
18886   struct die_info *die;
18887
18888   if (attr_form_is_ref (attr))
18889     die = follow_die_ref (src_die, attr, ref_cu);
18890   else if (attr->form == DW_FORM_ref_sig8)
18891     die = follow_die_sig (src_die, attr, ref_cu);
18892   else
18893     {
18894       dump_die_for_error (src_die);
18895       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18896              objfile_name ((*ref_cu)->objfile));
18897     }
18898
18899   return die;
18900 }
18901
18902 /* Follow reference OFFSET.
18903    On entry *REF_CU is the CU of the source die referencing OFFSET.
18904    On exit *REF_CU is the CU of the result.
18905    Returns NULL if OFFSET is invalid.  */
18906
18907 static struct die_info *
18908 follow_die_offset (sect_offset offset, int offset_in_dwz,
18909                    struct dwarf2_cu **ref_cu)
18910 {
18911   struct die_info temp_die;
18912   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18913
18914   gdb_assert (cu->per_cu != NULL);
18915
18916   target_cu = cu;
18917
18918   if (cu->per_cu->is_debug_types)
18919     {
18920       /* .debug_types CUs cannot reference anything outside their CU.
18921          If they need to, they have to reference a signatured type via
18922          DW_FORM_ref_sig8.  */
18923       if (! offset_in_cu_p (&cu->header, offset))
18924         return NULL;
18925     }
18926   else if (offset_in_dwz != cu->per_cu->is_dwz
18927            || ! offset_in_cu_p (&cu->header, offset))
18928     {
18929       struct dwarf2_per_cu_data *per_cu;
18930
18931       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18932                                                  cu->objfile);
18933
18934       /* If necessary, add it to the queue and load its DIEs.  */
18935       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18936         load_full_comp_unit (per_cu, cu->language);
18937
18938       target_cu = per_cu->cu;
18939     }
18940   else if (cu->dies == NULL)
18941     {
18942       /* We're loading full DIEs during partial symbol reading.  */
18943       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18944       load_full_comp_unit (cu->per_cu, language_minimal);
18945     }
18946
18947   *ref_cu = target_cu;
18948   temp_die.offset = offset;
18949   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18950 }
18951
18952 /* Follow reference attribute ATTR of SRC_DIE.
18953    On entry *REF_CU is the CU of SRC_DIE.
18954    On exit *REF_CU is the CU of the result.  */
18955
18956 static struct die_info *
18957 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18958                 struct dwarf2_cu **ref_cu)
18959 {
18960   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18961   struct dwarf2_cu *cu = *ref_cu;
18962   struct die_info *die;
18963
18964   die = follow_die_offset (offset,
18965                            (attr->form == DW_FORM_GNU_ref_alt
18966                             || cu->per_cu->is_dwz),
18967                            ref_cu);
18968   if (!die)
18969     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18970            "at 0x%x [in module %s]"),
18971            offset.sect_off, src_die->offset.sect_off,
18972            objfile_name (cu->objfile));
18973
18974   return die;
18975 }
18976
18977 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18978    Returned value is intended for DW_OP_call*.  Returned
18979    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18980
18981 struct dwarf2_locexpr_baton
18982 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18983                                struct dwarf2_per_cu_data *per_cu,
18984                                CORE_ADDR (*get_frame_pc) (void *baton),
18985                                void *baton)
18986 {
18987   struct dwarf2_cu *cu;
18988   struct die_info *die;
18989   struct attribute *attr;
18990   struct dwarf2_locexpr_baton retval;
18991
18992   dw2_setup (per_cu->objfile);
18993
18994   if (per_cu->cu == NULL)
18995     load_cu (per_cu);
18996   cu = per_cu->cu;
18997
18998   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18999   if (!die)
19000     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
19001            offset.sect_off, objfile_name (per_cu->objfile));
19002
19003   attr = dwarf2_attr (die, DW_AT_location, cu);
19004   if (!attr)
19005     {
19006       /* DWARF: "If there is no such attribute, then there is no effect.".
19007          DATA is ignored if SIZE is 0.  */
19008
19009       retval.data = NULL;
19010       retval.size = 0;
19011     }
19012   else if (attr_form_is_section_offset (attr))
19013     {
19014       struct dwarf2_loclist_baton loclist_baton;
19015       CORE_ADDR pc = (*get_frame_pc) (baton);
19016       size_t size;
19017
19018       fill_in_loclist_baton (cu, &loclist_baton, attr);
19019
19020       retval.data = dwarf2_find_location_expression (&loclist_baton,
19021                                                      &size, pc);
19022       retval.size = size;
19023     }
19024   else
19025     {
19026       if (!attr_form_is_block (attr))
19027         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
19028                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
19029                offset.sect_off, objfile_name (per_cu->objfile));
19030
19031       retval.data = DW_BLOCK (attr)->data;
19032       retval.size = DW_BLOCK (attr)->size;
19033     }
19034   retval.per_cu = cu->per_cu;
19035
19036   age_cached_comp_units ();
19037
19038   return retval;
19039 }
19040
19041 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
19042    offset.  */
19043
19044 struct dwarf2_locexpr_baton
19045 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
19046                              struct dwarf2_per_cu_data *per_cu,
19047                              CORE_ADDR (*get_frame_pc) (void *baton),
19048                              void *baton)
19049 {
19050   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
19051
19052   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
19053 }
19054
19055 /* Write a constant of a given type as target-ordered bytes into
19056    OBSTACK.  */
19057
19058 static const gdb_byte *
19059 write_constant_as_bytes (struct obstack *obstack,
19060                          enum bfd_endian byte_order,
19061                          struct type *type,
19062                          ULONGEST value,
19063                          LONGEST *len)
19064 {
19065   gdb_byte *result;
19066
19067   *len = TYPE_LENGTH (type);
19068   result = obstack_alloc (obstack, *len);
19069   store_unsigned_integer (result, *len, byte_order, value);
19070
19071   return result;
19072 }
19073
19074 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
19075    pointer to the constant bytes and set LEN to the length of the
19076    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
19077    does not have a DW_AT_const_value, return NULL.  */
19078
19079 const gdb_byte *
19080 dwarf2_fetch_constant_bytes (sect_offset offset,
19081                              struct dwarf2_per_cu_data *per_cu,
19082                              struct obstack *obstack,
19083                              LONGEST *len)
19084 {
19085   struct dwarf2_cu *cu;
19086   struct die_info *die;
19087   struct attribute *attr;
19088   const gdb_byte *result = NULL;
19089   struct type *type;
19090   LONGEST value;
19091   enum bfd_endian byte_order;
19092
19093   dw2_setup (per_cu->objfile);
19094
19095   if (per_cu->cu == NULL)
19096     load_cu (per_cu);
19097   cu = per_cu->cu;
19098
19099   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
19100   if (!die)
19101     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
19102            offset.sect_off, objfile_name (per_cu->objfile));
19103
19104
19105   attr = dwarf2_attr (die, DW_AT_const_value, cu);
19106   if (attr == NULL)
19107     return NULL;
19108
19109   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
19110                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19111
19112   switch (attr->form)
19113     {
19114     case DW_FORM_addr:
19115     case DW_FORM_GNU_addr_index:
19116       {
19117         gdb_byte *tem;
19118
19119         *len = cu->header.addr_size;
19120         tem = obstack_alloc (obstack, *len);
19121         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
19122         result = tem;
19123       }
19124       break;
19125     case DW_FORM_string:
19126     case DW_FORM_strp:
19127     case DW_FORM_GNU_str_index:
19128     case DW_FORM_GNU_strp_alt:
19129       /* DW_STRING is already allocated on the objfile obstack, point
19130          directly to it.  */
19131       result = (const gdb_byte *) DW_STRING (attr);
19132       *len = strlen (DW_STRING (attr));
19133       break;
19134     case DW_FORM_block1:
19135     case DW_FORM_block2:
19136     case DW_FORM_block4:
19137     case DW_FORM_block:
19138     case DW_FORM_exprloc:
19139       result = DW_BLOCK (attr)->data;
19140       *len = DW_BLOCK (attr)->size;
19141       break;
19142
19143       /* The DW_AT_const_value attributes are supposed to carry the
19144          symbol's value "represented as it would be on the target
19145          architecture."  By the time we get here, it's already been
19146          converted to host endianness, so we just need to sign- or
19147          zero-extend it as appropriate.  */
19148     case DW_FORM_data1:
19149       type = die_type (die, cu);
19150       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
19151       if (result == NULL)
19152         result = write_constant_as_bytes (obstack, byte_order,
19153                                           type, value, len);
19154       break;
19155     case DW_FORM_data2:
19156       type = die_type (die, cu);
19157       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
19158       if (result == NULL)
19159         result = write_constant_as_bytes (obstack, byte_order,
19160                                           type, value, len);
19161       break;
19162     case DW_FORM_data4:
19163       type = die_type (die, cu);
19164       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
19165       if (result == NULL)
19166         result = write_constant_as_bytes (obstack, byte_order,
19167                                           type, value, len);
19168       break;
19169     case DW_FORM_data8:
19170       type = die_type (die, cu);
19171       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
19172       if (result == NULL)
19173         result = write_constant_as_bytes (obstack, byte_order,
19174                                           type, value, len);
19175       break;
19176
19177     case DW_FORM_sdata:
19178       type = die_type (die, cu);
19179       result = write_constant_as_bytes (obstack, byte_order,
19180                                         type, DW_SND (attr), len);
19181       break;
19182
19183     case DW_FORM_udata:
19184       type = die_type (die, cu);
19185       result = write_constant_as_bytes (obstack, byte_order,
19186                                         type, DW_UNSND (attr), len);
19187       break;
19188
19189     default:
19190       complaint (&symfile_complaints,
19191                  _("unsupported const value attribute form: '%s'"),
19192                  dwarf_form_name (attr->form));
19193       break;
19194     }
19195
19196   return result;
19197 }
19198
19199 /* Return the type of the DIE at DIE_OFFSET in the CU named by
19200    PER_CU.  */
19201
19202 struct type *
19203 dwarf2_get_die_type (cu_offset die_offset,
19204                      struct dwarf2_per_cu_data *per_cu)
19205 {
19206   sect_offset die_offset_sect;
19207
19208   dw2_setup (per_cu->objfile);
19209
19210   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
19211   return get_die_type_at_offset (die_offset_sect, per_cu);
19212 }
19213
19214 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
19215    On entry *REF_CU is the CU of SRC_DIE.
19216    On exit *REF_CU is the CU of the result.
19217    Returns NULL if the referenced DIE isn't found.  */
19218
19219 static struct die_info *
19220 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
19221                   struct dwarf2_cu **ref_cu)
19222 {
19223   struct objfile *objfile = (*ref_cu)->objfile;
19224   struct die_info temp_die;
19225   struct dwarf2_cu *sig_cu;
19226   struct die_info *die;
19227
19228   /* While it might be nice to assert sig_type->type == NULL here,
19229      we can get here for DW_AT_imported_declaration where we need
19230      the DIE not the type.  */
19231
19232   /* If necessary, add it to the queue and load its DIEs.  */
19233
19234   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
19235     read_signatured_type (sig_type);
19236
19237   sig_cu = sig_type->per_cu.cu;
19238   gdb_assert (sig_cu != NULL);
19239   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
19240   temp_die.offset = sig_type->type_offset_in_section;
19241   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
19242                              temp_die.offset.sect_off);
19243   if (die)
19244     {
19245       /* For .gdb_index version 7 keep track of included TUs.
19246          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
19247       if (dwarf2_per_objfile->index_table != NULL
19248           && dwarf2_per_objfile->index_table->version <= 7)
19249         {
19250           VEC_safe_push (dwarf2_per_cu_ptr,
19251                          (*ref_cu)->per_cu->imported_symtabs,
19252                          sig_cu->per_cu);
19253         }
19254
19255       *ref_cu = sig_cu;
19256       return die;
19257     }
19258
19259   return NULL;
19260 }
19261
19262 /* Follow signatured type referenced by ATTR in SRC_DIE.
19263    On entry *REF_CU is the CU of SRC_DIE.
19264    On exit *REF_CU is the CU of the result.
19265    The result is the DIE of the type.
19266    If the referenced type cannot be found an error is thrown.  */
19267
19268 static struct die_info *
19269 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
19270                 struct dwarf2_cu **ref_cu)
19271 {
19272   ULONGEST signature = DW_SIGNATURE (attr);
19273   struct signatured_type *sig_type;
19274   struct die_info *die;
19275
19276   gdb_assert (attr->form == DW_FORM_ref_sig8);
19277
19278   sig_type = lookup_signatured_type (*ref_cu, signature);
19279   /* sig_type will be NULL if the signatured type is missing from
19280      the debug info.  */
19281   if (sig_type == NULL)
19282     {
19283       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
19284                " from DIE at 0x%x [in module %s]"),
19285              hex_string (signature), src_die->offset.sect_off,
19286              objfile_name ((*ref_cu)->objfile));
19287     }
19288
19289   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
19290   if (die == NULL)
19291     {
19292       dump_die_for_error (src_die);
19293       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
19294                " from DIE at 0x%x [in module %s]"),
19295              hex_string (signature), src_die->offset.sect_off,
19296              objfile_name ((*ref_cu)->objfile));
19297     }
19298
19299   return die;
19300 }
19301
19302 /* Get the type specified by SIGNATURE referenced in DIE/CU,
19303    reading in and processing the type unit if necessary.  */
19304
19305 static struct type *
19306 get_signatured_type (struct die_info *die, ULONGEST signature,
19307                      struct dwarf2_cu *cu)
19308 {
19309   struct signatured_type *sig_type;
19310   struct dwarf2_cu *type_cu;
19311   struct die_info *type_die;
19312   struct type *type;
19313
19314   sig_type = lookup_signatured_type (cu, signature);
19315   /* sig_type will be NULL if the signatured type is missing from
19316      the debug info.  */
19317   if (sig_type == NULL)
19318     {
19319       complaint (&symfile_complaints,
19320                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
19321                    " from DIE at 0x%x [in module %s]"),
19322                  hex_string (signature), die->offset.sect_off,
19323                  objfile_name (dwarf2_per_objfile->objfile));
19324       return build_error_marker_type (cu, die);
19325     }
19326
19327   /* If we already know the type we're done.  */
19328   if (sig_type->type != NULL)
19329     return sig_type->type;
19330
19331   type_cu = cu;
19332   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
19333   if (type_die != NULL)
19334     {
19335       /* N.B. We need to call get_die_type to ensure only one type for this DIE
19336          is created.  This is important, for example, because for c++ classes
19337          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
19338       type = read_type_die (type_die, type_cu);
19339       if (type == NULL)
19340         {
19341           complaint (&symfile_complaints,
19342                      _("Dwarf Error: Cannot build signatured type %s"
19343                        " referenced from DIE at 0x%x [in module %s]"),
19344                      hex_string (signature), die->offset.sect_off,
19345                      objfile_name (dwarf2_per_objfile->objfile));
19346           type = build_error_marker_type (cu, die);
19347         }
19348     }
19349   else
19350     {
19351       complaint (&symfile_complaints,
19352                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
19353                    " from DIE at 0x%x [in module %s]"),
19354                  hex_string (signature), die->offset.sect_off,
19355                  objfile_name (dwarf2_per_objfile->objfile));
19356       type = build_error_marker_type (cu, die);
19357     }
19358   sig_type->type = type;
19359
19360   return type;
19361 }
19362
19363 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
19364    reading in and processing the type unit if necessary.  */
19365
19366 static struct type *
19367 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
19368                           struct dwarf2_cu *cu) /* ARI: editCase function */
19369 {
19370   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
19371   if (attr_form_is_ref (attr))
19372     {
19373       struct dwarf2_cu *type_cu = cu;
19374       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
19375
19376       return read_type_die (type_die, type_cu);
19377     }
19378   else if (attr->form == DW_FORM_ref_sig8)
19379     {
19380       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
19381     }
19382   else
19383     {
19384       complaint (&symfile_complaints,
19385                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
19386                    " at 0x%x [in module %s]"),
19387                  dwarf_form_name (attr->form), die->offset.sect_off,
19388                  objfile_name (dwarf2_per_objfile->objfile));
19389       return build_error_marker_type (cu, die);
19390     }
19391 }
19392
19393 /* Load the DIEs associated with type unit PER_CU into memory.  */
19394
19395 static void
19396 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
19397 {
19398   struct signatured_type *sig_type;
19399
19400   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
19401   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
19402
19403   /* We have the per_cu, but we need the signatured_type.
19404      Fortunately this is an easy translation.  */
19405   gdb_assert (per_cu->is_debug_types);
19406   sig_type = (struct signatured_type *) per_cu;
19407
19408   gdb_assert (per_cu->cu == NULL);
19409
19410   read_signatured_type (sig_type);
19411
19412   gdb_assert (per_cu->cu != NULL);
19413 }
19414
19415 /* die_reader_func for read_signatured_type.
19416    This is identical to load_full_comp_unit_reader,
19417    but is kept separate for now.  */
19418
19419 static void
19420 read_signatured_type_reader (const struct die_reader_specs *reader,
19421                              const gdb_byte *info_ptr,
19422                              struct die_info *comp_unit_die,
19423                              int has_children,
19424                              void *data)
19425 {
19426   struct dwarf2_cu *cu = reader->cu;
19427
19428   gdb_assert (cu->die_hash == NULL);
19429   cu->die_hash =
19430     htab_create_alloc_ex (cu->header.length / 12,
19431                           die_hash,
19432                           die_eq,
19433                           NULL,
19434                           &cu->comp_unit_obstack,
19435                           hashtab_obstack_allocate,
19436                           dummy_obstack_deallocate);
19437
19438   if (has_children)
19439     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
19440                                                   &info_ptr, comp_unit_die);
19441   cu->dies = comp_unit_die;
19442   /* comp_unit_die is not stored in die_hash, no need.  */
19443
19444   /* We try not to read any attributes in this function, because not
19445      all CUs needed for references have been loaded yet, and symbol
19446      table processing isn't initialized.  But we have to set the CU language,
19447      or we won't be able to build types correctly.
19448      Similarly, if we do not read the producer, we can not apply
19449      producer-specific interpretation.  */
19450   prepare_one_comp_unit (cu, cu->dies, language_minimal);
19451 }
19452
19453 /* Read in a signatured type and build its CU and DIEs.
19454    If the type is a stub for the real type in a DWO file,
19455    read in the real type from the DWO file as well.  */
19456
19457 static void
19458 read_signatured_type (struct signatured_type *sig_type)
19459 {
19460   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
19461
19462   gdb_assert (per_cu->is_debug_types);
19463   gdb_assert (per_cu->cu == NULL);
19464
19465   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
19466                            read_signatured_type_reader, NULL);
19467   sig_type->per_cu.tu_read = 1;
19468 }
19469
19470 /* Decode simple location descriptions.
19471    Given a pointer to a dwarf block that defines a location, compute
19472    the location and return the value.
19473
19474    NOTE drow/2003-11-18: This function is called in two situations
19475    now: for the address of static or global variables (partial symbols
19476    only) and for offsets into structures which are expected to be
19477    (more or less) constant.  The partial symbol case should go away,
19478    and only the constant case should remain.  That will let this
19479    function complain more accurately.  A few special modes are allowed
19480    without complaint for global variables (for instance, global
19481    register values and thread-local values).
19482
19483    A location description containing no operations indicates that the
19484    object is optimized out.  The return value is 0 for that case.
19485    FIXME drow/2003-11-16: No callers check for this case any more; soon all
19486    callers will only want a very basic result and this can become a
19487    complaint.
19488
19489    Note that stack[0] is unused except as a default error return.  */
19490
19491 static CORE_ADDR
19492 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
19493 {
19494   struct objfile *objfile = cu->objfile;
19495   size_t i;
19496   size_t size = blk->size;
19497   const gdb_byte *data = blk->data;
19498   CORE_ADDR stack[64];
19499   int stacki;
19500   unsigned int bytes_read, unsnd;
19501   gdb_byte op;
19502
19503   i = 0;
19504   stacki = 0;
19505   stack[stacki] = 0;
19506   stack[++stacki] = 0;
19507
19508   while (i < size)
19509     {
19510       op = data[i++];
19511       switch (op)
19512         {
19513         case DW_OP_lit0:
19514         case DW_OP_lit1:
19515         case DW_OP_lit2:
19516         case DW_OP_lit3:
19517         case DW_OP_lit4:
19518         case DW_OP_lit5:
19519         case DW_OP_lit6:
19520         case DW_OP_lit7:
19521         case DW_OP_lit8:
19522         case DW_OP_lit9:
19523         case DW_OP_lit10:
19524         case DW_OP_lit11:
19525         case DW_OP_lit12:
19526         case DW_OP_lit13:
19527         case DW_OP_lit14:
19528         case DW_OP_lit15:
19529         case DW_OP_lit16:
19530         case DW_OP_lit17:
19531         case DW_OP_lit18:
19532         case DW_OP_lit19:
19533         case DW_OP_lit20:
19534         case DW_OP_lit21:
19535         case DW_OP_lit22:
19536         case DW_OP_lit23:
19537         case DW_OP_lit24:
19538         case DW_OP_lit25:
19539         case DW_OP_lit26:
19540         case DW_OP_lit27:
19541         case DW_OP_lit28:
19542         case DW_OP_lit29:
19543         case DW_OP_lit30:
19544         case DW_OP_lit31:
19545           stack[++stacki] = op - DW_OP_lit0;
19546           break;
19547
19548         case DW_OP_reg0:
19549         case DW_OP_reg1:
19550         case DW_OP_reg2:
19551         case DW_OP_reg3:
19552         case DW_OP_reg4:
19553         case DW_OP_reg5:
19554         case DW_OP_reg6:
19555         case DW_OP_reg7:
19556         case DW_OP_reg8:
19557         case DW_OP_reg9:
19558         case DW_OP_reg10:
19559         case DW_OP_reg11:
19560         case DW_OP_reg12:
19561         case DW_OP_reg13:
19562         case DW_OP_reg14:
19563         case DW_OP_reg15:
19564         case DW_OP_reg16:
19565         case DW_OP_reg17:
19566         case DW_OP_reg18:
19567         case DW_OP_reg19:
19568         case DW_OP_reg20:
19569         case DW_OP_reg21:
19570         case DW_OP_reg22:
19571         case DW_OP_reg23:
19572         case DW_OP_reg24:
19573         case DW_OP_reg25:
19574         case DW_OP_reg26:
19575         case DW_OP_reg27:
19576         case DW_OP_reg28:
19577         case DW_OP_reg29:
19578         case DW_OP_reg30:
19579         case DW_OP_reg31:
19580           stack[++stacki] = op - DW_OP_reg0;
19581           if (i < size)
19582             dwarf2_complex_location_expr_complaint ();
19583           break;
19584
19585         case DW_OP_regx:
19586           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
19587           i += bytes_read;
19588           stack[++stacki] = unsnd;
19589           if (i < size)
19590             dwarf2_complex_location_expr_complaint ();
19591           break;
19592
19593         case DW_OP_addr:
19594           stack[++stacki] = read_address (objfile->obfd, &data[i],
19595                                           cu, &bytes_read);
19596           i += bytes_read;
19597           break;
19598
19599         case DW_OP_const1u:
19600           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
19601           i += 1;
19602           break;
19603
19604         case DW_OP_const1s:
19605           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
19606           i += 1;
19607           break;
19608
19609         case DW_OP_const2u:
19610           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
19611           i += 2;
19612           break;
19613
19614         case DW_OP_const2s:
19615           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
19616           i += 2;
19617           break;
19618
19619         case DW_OP_const4u:
19620           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
19621           i += 4;
19622           break;
19623
19624         case DW_OP_const4s:
19625           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
19626           i += 4;
19627           break;
19628
19629         case DW_OP_const8u:
19630           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
19631           i += 8;
19632           break;
19633
19634         case DW_OP_constu:
19635           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
19636                                                   &bytes_read);
19637           i += bytes_read;
19638           break;
19639
19640         case DW_OP_consts:
19641           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
19642           i += bytes_read;
19643           break;
19644
19645         case DW_OP_dup:
19646           stack[stacki + 1] = stack[stacki];
19647           stacki++;
19648           break;
19649
19650         case DW_OP_plus:
19651           stack[stacki - 1] += stack[stacki];
19652           stacki--;
19653           break;
19654
19655         case DW_OP_plus_uconst:
19656           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
19657                                                  &bytes_read);
19658           i += bytes_read;
19659           break;
19660
19661         case DW_OP_minus:
19662           stack[stacki - 1] -= stack[stacki];
19663           stacki--;
19664           break;
19665
19666         case DW_OP_deref:
19667           /* If we're not the last op, then we definitely can't encode
19668              this using GDB's address_class enum.  This is valid for partial
19669              global symbols, although the variable's address will be bogus
19670              in the psymtab.  */
19671           if (i < size)
19672             dwarf2_complex_location_expr_complaint ();
19673           break;
19674
19675         case DW_OP_GNU_push_tls_address:
19676           /* The top of the stack has the offset from the beginning
19677              of the thread control block at which the variable is located.  */
19678           /* Nothing should follow this operator, so the top of stack would
19679              be returned.  */
19680           /* This is valid for partial global symbols, but the variable's
19681              address will be bogus in the psymtab.  Make it always at least
19682              non-zero to not look as a variable garbage collected by linker
19683              which have DW_OP_addr 0.  */
19684           if (i < size)
19685             dwarf2_complex_location_expr_complaint ();
19686           stack[stacki]++;
19687           break;
19688
19689         case DW_OP_GNU_uninit:
19690           break;
19691
19692         case DW_OP_GNU_addr_index:
19693         case DW_OP_GNU_const_index:
19694           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
19695                                                          &bytes_read);
19696           i += bytes_read;
19697           break;
19698
19699         default:
19700           {
19701             const char *name = get_DW_OP_name (op);
19702
19703             if (name)
19704               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
19705                          name);
19706             else
19707               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
19708                          op);
19709           }
19710
19711           return (stack[stacki]);
19712         }
19713
19714       /* Enforce maximum stack depth of SIZE-1 to avoid writing
19715          outside of the allocated space.  Also enforce minimum>0.  */
19716       if (stacki >= ARRAY_SIZE (stack) - 1)
19717         {
19718           complaint (&symfile_complaints,
19719                      _("location description stack overflow"));
19720           return 0;
19721         }
19722
19723       if (stacki <= 0)
19724         {
19725           complaint (&symfile_complaints,
19726                      _("location description stack underflow"));
19727           return 0;
19728         }
19729     }
19730   return (stack[stacki]);
19731 }
19732
19733 /* memory allocation interface */
19734
19735 static struct dwarf_block *
19736 dwarf_alloc_block (struct dwarf2_cu *cu)
19737 {
19738   struct dwarf_block *blk;
19739
19740   blk = (struct dwarf_block *)
19741     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
19742   return (blk);
19743 }
19744
19745 static struct die_info *
19746 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
19747 {
19748   struct die_info *die;
19749   size_t size = sizeof (struct die_info);
19750
19751   if (num_attrs > 1)
19752     size += (num_attrs - 1) * sizeof (struct attribute);
19753
19754   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
19755   memset (die, 0, sizeof (struct die_info));
19756   return (die);
19757 }
19758
19759 \f
19760 /* Macro support.  */
19761
19762 /* Return file name relative to the compilation directory of file number I in
19763    *LH's file name table.  The result is allocated using xmalloc; the caller is
19764    responsible for freeing it.  */
19765
19766 static char *
19767 file_file_name (int file, struct line_header *lh)
19768 {
19769   /* Is the file number a valid index into the line header's file name
19770      table?  Remember that file numbers start with one, not zero.  */
19771   if (1 <= file && file <= lh->num_file_names)
19772     {
19773       struct file_entry *fe = &lh->file_names[file - 1];
19774
19775       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
19776         return xstrdup (fe->name);
19777       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
19778                      fe->name, NULL);
19779     }
19780   else
19781     {
19782       /* The compiler produced a bogus file number.  We can at least
19783          record the macro definitions made in the file, even if we
19784          won't be able to find the file by name.  */
19785       char fake_name[80];
19786
19787       xsnprintf (fake_name, sizeof (fake_name),
19788                  "<bad macro file number %d>", file);
19789
19790       complaint (&symfile_complaints,
19791                  _("bad file number in macro information (%d)"),
19792                  file);
19793
19794       return xstrdup (fake_name);
19795     }
19796 }
19797
19798 /* Return the full name of file number I in *LH's file name table.
19799    Use COMP_DIR as the name of the current directory of the
19800    compilation.  The result is allocated using xmalloc; the caller is
19801    responsible for freeing it.  */
19802 static char *
19803 file_full_name (int file, struct line_header *lh, const char *comp_dir)
19804 {
19805   /* Is the file number a valid index into the line header's file name
19806      table?  Remember that file numbers start with one, not zero.  */
19807   if (1 <= file && file <= lh->num_file_names)
19808     {
19809       char *relative = file_file_name (file, lh);
19810
19811       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
19812         return relative;
19813       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
19814     }
19815   else
19816     return file_file_name (file, lh);
19817 }
19818
19819
19820 static struct macro_source_file *
19821 macro_start_file (int file, int line,
19822                   struct macro_source_file *current_file,
19823                   const char *comp_dir,
19824                   struct line_header *lh, struct objfile *objfile)
19825 {
19826   /* File name relative to the compilation directory of this source file.  */
19827   char *file_name = file_file_name (file, lh);
19828
19829   if (! current_file)
19830     {
19831       /* Note: We don't create a macro table for this compilation unit
19832          at all until we actually get a filename.  */
19833       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
19834
19835       /* If we have no current file, then this must be the start_file
19836          directive for the compilation unit's main source file.  */
19837       current_file = macro_set_main (macro_table, file_name);
19838       macro_define_special (macro_table);
19839     }
19840   else
19841     current_file = macro_include (current_file, line, file_name);
19842
19843   xfree (file_name);
19844
19845   return current_file;
19846 }
19847
19848
19849 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19850    followed by a null byte.  */
19851 static char *
19852 copy_string (const char *buf, int len)
19853 {
19854   char *s = xmalloc (len + 1);
19855
19856   memcpy (s, buf, len);
19857   s[len] = '\0';
19858   return s;
19859 }
19860
19861
19862 static const char *
19863 consume_improper_spaces (const char *p, const char *body)
19864 {
19865   if (*p == ' ')
19866     {
19867       complaint (&symfile_complaints,
19868                  _("macro definition contains spaces "
19869                    "in formal argument list:\n`%s'"),
19870                  body);
19871
19872       while (*p == ' ')
19873         p++;
19874     }
19875
19876   return p;
19877 }
19878
19879
19880 static void
19881 parse_macro_definition (struct macro_source_file *file, int line,
19882                         const char *body)
19883 {
19884   const char *p;
19885
19886   /* The body string takes one of two forms.  For object-like macro
19887      definitions, it should be:
19888
19889         <macro name> " " <definition>
19890
19891      For function-like macro definitions, it should be:
19892
19893         <macro name> "() " <definition>
19894      or
19895         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19896
19897      Spaces may appear only where explicitly indicated, and in the
19898      <definition>.
19899
19900      The Dwarf 2 spec says that an object-like macro's name is always
19901      followed by a space, but versions of GCC around March 2002 omit
19902      the space when the macro's definition is the empty string.
19903
19904      The Dwarf 2 spec says that there should be no spaces between the
19905      formal arguments in a function-like macro's formal argument list,
19906      but versions of GCC around March 2002 include spaces after the
19907      commas.  */
19908
19909
19910   /* Find the extent of the macro name.  The macro name is terminated
19911      by either a space or null character (for an object-like macro) or
19912      an opening paren (for a function-like macro).  */
19913   for (p = body; *p; p++)
19914     if (*p == ' ' || *p == '(')
19915       break;
19916
19917   if (*p == ' ' || *p == '\0')
19918     {
19919       /* It's an object-like macro.  */
19920       int name_len = p - body;
19921       char *name = copy_string (body, name_len);
19922       const char *replacement;
19923
19924       if (*p == ' ')
19925         replacement = body + name_len + 1;
19926       else
19927         {
19928           dwarf2_macro_malformed_definition_complaint (body);
19929           replacement = body + name_len;
19930         }
19931
19932       macro_define_object (file, line, name, replacement);
19933
19934       xfree (name);
19935     }
19936   else if (*p == '(')
19937     {
19938       /* It's a function-like macro.  */
19939       char *name = copy_string (body, p - body);
19940       int argc = 0;
19941       int argv_size = 1;
19942       char **argv = xmalloc (argv_size * sizeof (*argv));
19943
19944       p++;
19945
19946       p = consume_improper_spaces (p, body);
19947
19948       /* Parse the formal argument list.  */
19949       while (*p && *p != ')')
19950         {
19951           /* Find the extent of the current argument name.  */
19952           const char *arg_start = p;
19953
19954           while (*p && *p != ',' && *p != ')' && *p != ' ')
19955             p++;
19956
19957           if (! *p || p == arg_start)
19958             dwarf2_macro_malformed_definition_complaint (body);
19959           else
19960             {
19961               /* Make sure argv has room for the new argument.  */
19962               if (argc >= argv_size)
19963                 {
19964                   argv_size *= 2;
19965                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19966                 }
19967
19968               argv[argc++] = copy_string (arg_start, p - arg_start);
19969             }
19970
19971           p = consume_improper_spaces (p, body);
19972
19973           /* Consume the comma, if present.  */
19974           if (*p == ',')
19975             {
19976               p++;
19977
19978               p = consume_improper_spaces (p, body);
19979             }
19980         }
19981
19982       if (*p == ')')
19983         {
19984           p++;
19985
19986           if (*p == ' ')
19987             /* Perfectly formed definition, no complaints.  */
19988             macro_define_function (file, line, name,
19989                                    argc, (const char **) argv,
19990                                    p + 1);
19991           else if (*p == '\0')
19992             {
19993               /* Complain, but do define it.  */
19994               dwarf2_macro_malformed_definition_complaint (body);
19995               macro_define_function (file, line, name,
19996                                      argc, (const char **) argv,
19997                                      p);
19998             }
19999           else
20000             /* Just complain.  */
20001             dwarf2_macro_malformed_definition_complaint (body);
20002         }
20003       else
20004         /* Just complain.  */
20005         dwarf2_macro_malformed_definition_complaint (body);
20006
20007       xfree (name);
20008       {
20009         int i;
20010
20011         for (i = 0; i < argc; i++)
20012           xfree (argv[i]);
20013       }
20014       xfree (argv);
20015     }
20016   else
20017     dwarf2_macro_malformed_definition_complaint (body);
20018 }
20019
20020 /* Skip some bytes from BYTES according to the form given in FORM.
20021    Returns the new pointer.  */
20022
20023 static const gdb_byte *
20024 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
20025                  enum dwarf_form form,
20026                  unsigned int offset_size,
20027                  struct dwarf2_section_info *section)
20028 {
20029   unsigned int bytes_read;
20030
20031   switch (form)
20032     {
20033     case DW_FORM_data1:
20034     case DW_FORM_flag:
20035       ++bytes;
20036       break;
20037
20038     case DW_FORM_data2:
20039       bytes += 2;
20040       break;
20041
20042     case DW_FORM_data4:
20043       bytes += 4;
20044       break;
20045
20046     case DW_FORM_data8:
20047       bytes += 8;
20048       break;
20049
20050     case DW_FORM_string:
20051       read_direct_string (abfd, bytes, &bytes_read);
20052       bytes += bytes_read;
20053       break;
20054
20055     case DW_FORM_sec_offset:
20056     case DW_FORM_strp:
20057     case DW_FORM_GNU_strp_alt:
20058       bytes += offset_size;
20059       break;
20060
20061     case DW_FORM_block:
20062       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
20063       bytes += bytes_read;
20064       break;
20065
20066     case DW_FORM_block1:
20067       bytes += 1 + read_1_byte (abfd, bytes);
20068       break;
20069     case DW_FORM_block2:
20070       bytes += 2 + read_2_bytes (abfd, bytes);
20071       break;
20072     case DW_FORM_block4:
20073       bytes += 4 + read_4_bytes (abfd, bytes);
20074       break;
20075
20076     case DW_FORM_sdata:
20077     case DW_FORM_udata:
20078     case DW_FORM_GNU_addr_index:
20079     case DW_FORM_GNU_str_index:
20080       bytes = gdb_skip_leb128 (bytes, buffer_end);
20081       if (bytes == NULL)
20082         {
20083           dwarf2_section_buffer_overflow_complaint (section);
20084           return NULL;
20085         }
20086       break;
20087
20088     default:
20089       {
20090       complain:
20091         complaint (&symfile_complaints,
20092                    _("invalid form 0x%x in `%s'"),
20093                    form, get_section_name (section));
20094         return NULL;
20095       }
20096     }
20097
20098   return bytes;
20099 }
20100
20101 /* A helper for dwarf_decode_macros that handles skipping an unknown
20102    opcode.  Returns an updated pointer to the macro data buffer; or,
20103    on error, issues a complaint and returns NULL.  */
20104
20105 static const gdb_byte *
20106 skip_unknown_opcode (unsigned int opcode,
20107                      const gdb_byte **opcode_definitions,
20108                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20109                      bfd *abfd,
20110                      unsigned int offset_size,
20111                      struct dwarf2_section_info *section)
20112 {
20113   unsigned int bytes_read, i;
20114   unsigned long arg;
20115   const gdb_byte *defn;
20116
20117   if (opcode_definitions[opcode] == NULL)
20118     {
20119       complaint (&symfile_complaints,
20120                  _("unrecognized DW_MACFINO opcode 0x%x"),
20121                  opcode);
20122       return NULL;
20123     }
20124
20125   defn = opcode_definitions[opcode];
20126   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
20127   defn += bytes_read;
20128
20129   for (i = 0; i < arg; ++i)
20130     {
20131       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
20132                                  section);
20133       if (mac_ptr == NULL)
20134         {
20135           /* skip_form_bytes already issued the complaint.  */
20136           return NULL;
20137         }
20138     }
20139
20140   return mac_ptr;
20141 }
20142
20143 /* A helper function which parses the header of a macro section.
20144    If the macro section is the extended (for now called "GNU") type,
20145    then this updates *OFFSET_SIZE.  Returns a pointer to just after
20146    the header, or issues a complaint and returns NULL on error.  */
20147
20148 static const gdb_byte *
20149 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
20150                           bfd *abfd,
20151                           const gdb_byte *mac_ptr,
20152                           unsigned int *offset_size,
20153                           int section_is_gnu)
20154 {
20155   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
20156
20157   if (section_is_gnu)
20158     {
20159       unsigned int version, flags;
20160
20161       version = read_2_bytes (abfd, mac_ptr);
20162       if (version != 4)
20163         {
20164           complaint (&symfile_complaints,
20165                      _("unrecognized version `%d' in .debug_macro section"),
20166                      version);
20167           return NULL;
20168         }
20169       mac_ptr += 2;
20170
20171       flags = read_1_byte (abfd, mac_ptr);
20172       ++mac_ptr;
20173       *offset_size = (flags & 1) ? 8 : 4;
20174
20175       if ((flags & 2) != 0)
20176         /* We don't need the line table offset.  */
20177         mac_ptr += *offset_size;
20178
20179       /* Vendor opcode descriptions.  */
20180       if ((flags & 4) != 0)
20181         {
20182           unsigned int i, count;
20183
20184           count = read_1_byte (abfd, mac_ptr);
20185           ++mac_ptr;
20186           for (i = 0; i < count; ++i)
20187             {
20188               unsigned int opcode, bytes_read;
20189               unsigned long arg;
20190
20191               opcode = read_1_byte (abfd, mac_ptr);
20192               ++mac_ptr;
20193               opcode_definitions[opcode] = mac_ptr;
20194               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20195               mac_ptr += bytes_read;
20196               mac_ptr += arg;
20197             }
20198         }
20199     }
20200
20201   return mac_ptr;
20202 }
20203
20204 /* A helper for dwarf_decode_macros that handles the GNU extensions,
20205    including DW_MACRO_GNU_transparent_include.  */
20206
20207 static void
20208 dwarf_decode_macro_bytes (bfd *abfd,
20209                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20210                           struct macro_source_file *current_file,
20211                           struct line_header *lh, const char *comp_dir,
20212                           struct dwarf2_section_info *section,
20213                           int section_is_gnu, int section_is_dwz,
20214                           unsigned int offset_size,
20215                           struct objfile *objfile,
20216                           htab_t include_hash)
20217 {
20218   enum dwarf_macro_record_type macinfo_type;
20219   int at_commandline;
20220   const gdb_byte *opcode_definitions[256];
20221
20222   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20223                                       &offset_size, section_is_gnu);
20224   if (mac_ptr == NULL)
20225     {
20226       /* We already issued a complaint.  */
20227       return;
20228     }
20229
20230   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
20231      GDB is still reading the definitions from command line.  First
20232      DW_MACINFO_start_file will need to be ignored as it was already executed
20233      to create CURRENT_FILE for the main source holding also the command line
20234      definitions.  On first met DW_MACINFO_start_file this flag is reset to
20235      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
20236
20237   at_commandline = 1;
20238
20239   do
20240     {
20241       /* Do we at least have room for a macinfo type byte?  */
20242       if (mac_ptr >= mac_end)
20243         {
20244           dwarf2_section_buffer_overflow_complaint (section);
20245           break;
20246         }
20247
20248       macinfo_type = read_1_byte (abfd, mac_ptr);
20249       mac_ptr++;
20250
20251       /* Note that we rely on the fact that the corresponding GNU and
20252          DWARF constants are the same.  */
20253       switch (macinfo_type)
20254         {
20255           /* A zero macinfo type indicates the end of the macro
20256              information.  */
20257         case 0:
20258           break;
20259
20260         case DW_MACRO_GNU_define:
20261         case DW_MACRO_GNU_undef:
20262         case DW_MACRO_GNU_define_indirect:
20263         case DW_MACRO_GNU_undef_indirect:
20264         case DW_MACRO_GNU_define_indirect_alt:
20265         case DW_MACRO_GNU_undef_indirect_alt:
20266           {
20267             unsigned int bytes_read;
20268             int line;
20269             const char *body;
20270             int is_define;
20271
20272             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20273             mac_ptr += bytes_read;
20274
20275             if (macinfo_type == DW_MACRO_GNU_define
20276                 || macinfo_type == DW_MACRO_GNU_undef)
20277               {
20278                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
20279                 mac_ptr += bytes_read;
20280               }
20281             else
20282               {
20283                 LONGEST str_offset;
20284
20285                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
20286                 mac_ptr += offset_size;
20287
20288                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
20289                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
20290                     || section_is_dwz)
20291                   {
20292                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
20293
20294                     body = read_indirect_string_from_dwz (dwz, str_offset);
20295                   }
20296                 else
20297                   body = read_indirect_string_at_offset (abfd, str_offset);
20298               }
20299
20300             is_define = (macinfo_type == DW_MACRO_GNU_define
20301                          || macinfo_type == DW_MACRO_GNU_define_indirect
20302                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
20303             if (! current_file)
20304               {
20305                 /* DWARF violation as no main source is present.  */
20306                 complaint (&symfile_complaints,
20307                            _("debug info with no main source gives macro %s "
20308                              "on line %d: %s"),
20309                            is_define ? _("definition") : _("undefinition"),
20310                            line, body);
20311                 break;
20312               }
20313             if ((line == 0 && !at_commandline)
20314                 || (line != 0 && at_commandline))
20315               complaint (&symfile_complaints,
20316                          _("debug info gives %s macro %s with %s line %d: %s"),
20317                          at_commandline ? _("command-line") : _("in-file"),
20318                          is_define ? _("definition") : _("undefinition"),
20319                          line == 0 ? _("zero") : _("non-zero"), line, body);
20320
20321             if (is_define)
20322               parse_macro_definition (current_file, line, body);
20323             else
20324               {
20325                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
20326                             || macinfo_type == DW_MACRO_GNU_undef_indirect
20327                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
20328                 macro_undef (current_file, line, body);
20329               }
20330           }
20331           break;
20332
20333         case DW_MACRO_GNU_start_file:
20334           {
20335             unsigned int bytes_read;
20336             int line, file;
20337
20338             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20339             mac_ptr += bytes_read;
20340             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20341             mac_ptr += bytes_read;
20342
20343             if ((line == 0 && !at_commandline)
20344                 || (line != 0 && at_commandline))
20345               complaint (&symfile_complaints,
20346                          _("debug info gives source %d included "
20347                            "from %s at %s line %d"),
20348                          file, at_commandline ? _("command-line") : _("file"),
20349                          line == 0 ? _("zero") : _("non-zero"), line);
20350
20351             if (at_commandline)
20352               {
20353                 /* This DW_MACRO_GNU_start_file was executed in the
20354                    pass one.  */
20355                 at_commandline = 0;
20356               }
20357             else
20358               current_file = macro_start_file (file, line,
20359                                                current_file, comp_dir,
20360                                                lh, objfile);
20361           }
20362           break;
20363
20364         case DW_MACRO_GNU_end_file:
20365           if (! current_file)
20366             complaint (&symfile_complaints,
20367                        _("macro debug info has an unmatched "
20368                          "`close_file' directive"));
20369           else
20370             {
20371               current_file = current_file->included_by;
20372               if (! current_file)
20373                 {
20374                   enum dwarf_macro_record_type next_type;
20375
20376                   /* GCC circa March 2002 doesn't produce the zero
20377                      type byte marking the end of the compilation
20378                      unit.  Complain if it's not there, but exit no
20379                      matter what.  */
20380
20381                   /* Do we at least have room for a macinfo type byte?  */
20382                   if (mac_ptr >= mac_end)
20383                     {
20384                       dwarf2_section_buffer_overflow_complaint (section);
20385                       return;
20386                     }
20387
20388                   /* We don't increment mac_ptr here, so this is just
20389                      a look-ahead.  */
20390                   next_type = read_1_byte (abfd, mac_ptr);
20391                   if (next_type != 0)
20392                     complaint (&symfile_complaints,
20393                                _("no terminating 0-type entry for "
20394                                  "macros in `.debug_macinfo' section"));
20395
20396                   return;
20397                 }
20398             }
20399           break;
20400
20401         case DW_MACRO_GNU_transparent_include:
20402         case DW_MACRO_GNU_transparent_include_alt:
20403           {
20404             LONGEST offset;
20405             void **slot;
20406             bfd *include_bfd = abfd;
20407             struct dwarf2_section_info *include_section = section;
20408             struct dwarf2_section_info alt_section;
20409             const gdb_byte *include_mac_end = mac_end;
20410             int is_dwz = section_is_dwz;
20411             const gdb_byte *new_mac_ptr;
20412
20413             offset = read_offset_1 (abfd, mac_ptr, offset_size);
20414             mac_ptr += offset_size;
20415
20416             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
20417               {
20418                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
20419
20420                 dwarf2_read_section (dwarf2_per_objfile->objfile,
20421                                      &dwz->macro);
20422
20423                 include_section = &dwz->macro;
20424                 include_bfd = get_section_bfd_owner (include_section);
20425                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
20426                 is_dwz = 1;
20427               }
20428
20429             new_mac_ptr = include_section->buffer + offset;
20430             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
20431
20432             if (*slot != NULL)
20433               {
20434                 /* This has actually happened; see
20435                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
20436                 complaint (&symfile_complaints,
20437                            _("recursive DW_MACRO_GNU_transparent_include in "
20438                              ".debug_macro section"));
20439               }
20440             else
20441               {
20442                 *slot = (void *) new_mac_ptr;
20443
20444                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
20445                                           include_mac_end, current_file,
20446                                           lh, comp_dir,
20447                                           section, section_is_gnu, is_dwz,
20448                                           offset_size, objfile, include_hash);
20449
20450                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
20451               }
20452           }
20453           break;
20454
20455         case DW_MACINFO_vendor_ext:
20456           if (!section_is_gnu)
20457             {
20458               unsigned int bytes_read;
20459               int constant;
20460
20461               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20462               mac_ptr += bytes_read;
20463               read_direct_string (abfd, mac_ptr, &bytes_read);
20464               mac_ptr += bytes_read;
20465
20466               /* We don't recognize any vendor extensions.  */
20467               break;
20468             }
20469           /* FALLTHROUGH */
20470
20471         default:
20472           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20473                                          mac_ptr, mac_end, abfd, offset_size,
20474                                          section);
20475           if (mac_ptr == NULL)
20476             return;
20477           break;
20478         }
20479     } while (macinfo_type != 0);
20480 }
20481
20482 static void
20483 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
20484                      const char *comp_dir, int section_is_gnu)
20485 {
20486   struct objfile *objfile = dwarf2_per_objfile->objfile;
20487   struct line_header *lh = cu->line_header;
20488   bfd *abfd;
20489   const gdb_byte *mac_ptr, *mac_end;
20490   struct macro_source_file *current_file = 0;
20491   enum dwarf_macro_record_type macinfo_type;
20492   unsigned int offset_size = cu->header.offset_size;
20493   const gdb_byte *opcode_definitions[256];
20494   struct cleanup *cleanup;
20495   htab_t include_hash;
20496   void **slot;
20497   struct dwarf2_section_info *section;
20498   const char *section_name;
20499
20500   if (cu->dwo_unit != NULL)
20501     {
20502       if (section_is_gnu)
20503         {
20504           section = &cu->dwo_unit->dwo_file->sections.macro;
20505           section_name = ".debug_macro.dwo";
20506         }
20507       else
20508         {
20509           section = &cu->dwo_unit->dwo_file->sections.macinfo;
20510           section_name = ".debug_macinfo.dwo";
20511         }
20512     }
20513   else
20514     {
20515       if (section_is_gnu)
20516         {
20517           section = &dwarf2_per_objfile->macro;
20518           section_name = ".debug_macro";
20519         }
20520       else
20521         {
20522           section = &dwarf2_per_objfile->macinfo;
20523           section_name = ".debug_macinfo";
20524         }
20525     }
20526
20527   dwarf2_read_section (objfile, section);
20528   if (section->buffer == NULL)
20529     {
20530       complaint (&symfile_complaints, _("missing %s section"), section_name);
20531       return;
20532     }
20533   abfd = get_section_bfd_owner (section);
20534
20535   /* First pass: Find the name of the base filename.
20536      This filename is needed in order to process all macros whose definition
20537      (or undefinition) comes from the command line.  These macros are defined
20538      before the first DW_MACINFO_start_file entry, and yet still need to be
20539      associated to the base file.
20540
20541      To determine the base file name, we scan the macro definitions until we
20542      reach the first DW_MACINFO_start_file entry.  We then initialize
20543      CURRENT_FILE accordingly so that any macro definition found before the
20544      first DW_MACINFO_start_file can still be associated to the base file.  */
20545
20546   mac_ptr = section->buffer + offset;
20547   mac_end = section->buffer + section->size;
20548
20549   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20550                                       &offset_size, section_is_gnu);
20551   if (mac_ptr == NULL)
20552     {
20553       /* We already issued a complaint.  */
20554       return;
20555     }
20556
20557   do
20558     {
20559       /* Do we at least have room for a macinfo type byte?  */
20560       if (mac_ptr >= mac_end)
20561         {
20562           /* Complaint is printed during the second pass as GDB will probably
20563              stop the first pass earlier upon finding
20564              DW_MACINFO_start_file.  */
20565           break;
20566         }
20567
20568       macinfo_type = read_1_byte (abfd, mac_ptr);
20569       mac_ptr++;
20570
20571       /* Note that we rely on the fact that the corresponding GNU and
20572          DWARF constants are the same.  */
20573       switch (macinfo_type)
20574         {
20575           /* A zero macinfo type indicates the end of the macro
20576              information.  */
20577         case 0:
20578           break;
20579
20580         case DW_MACRO_GNU_define:
20581         case DW_MACRO_GNU_undef:
20582           /* Only skip the data by MAC_PTR.  */
20583           {
20584             unsigned int bytes_read;
20585
20586             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20587             mac_ptr += bytes_read;
20588             read_direct_string (abfd, mac_ptr, &bytes_read);
20589             mac_ptr += bytes_read;
20590           }
20591           break;
20592
20593         case DW_MACRO_GNU_start_file:
20594           {
20595             unsigned int bytes_read;
20596             int line, file;
20597
20598             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20599             mac_ptr += bytes_read;
20600             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20601             mac_ptr += bytes_read;
20602
20603             current_file = macro_start_file (file, line, current_file,
20604                                              comp_dir, lh, objfile);
20605           }
20606           break;
20607
20608         case DW_MACRO_GNU_end_file:
20609           /* No data to skip by MAC_PTR.  */
20610           break;
20611
20612         case DW_MACRO_GNU_define_indirect:
20613         case DW_MACRO_GNU_undef_indirect:
20614         case DW_MACRO_GNU_define_indirect_alt:
20615         case DW_MACRO_GNU_undef_indirect_alt:
20616           {
20617             unsigned int bytes_read;
20618
20619             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20620             mac_ptr += bytes_read;
20621             mac_ptr += offset_size;
20622           }
20623           break;
20624
20625         case DW_MACRO_GNU_transparent_include:
20626         case DW_MACRO_GNU_transparent_include_alt:
20627           /* Note that, according to the spec, a transparent include
20628              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
20629              skip this opcode.  */
20630           mac_ptr += offset_size;
20631           break;
20632
20633         case DW_MACINFO_vendor_ext:
20634           /* Only skip the data by MAC_PTR.  */
20635           if (!section_is_gnu)
20636             {
20637               unsigned int bytes_read;
20638
20639               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20640               mac_ptr += bytes_read;
20641               read_direct_string (abfd, mac_ptr, &bytes_read);
20642               mac_ptr += bytes_read;
20643             }
20644           /* FALLTHROUGH */
20645
20646         default:
20647           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20648                                          mac_ptr, mac_end, abfd, offset_size,
20649                                          section);
20650           if (mac_ptr == NULL)
20651             return;
20652           break;
20653         }
20654     } while (macinfo_type != 0 && current_file == NULL);
20655
20656   /* Second pass: Process all entries.
20657
20658      Use the AT_COMMAND_LINE flag to determine whether we are still processing
20659      command-line macro definitions/undefinitions.  This flag is unset when we
20660      reach the first DW_MACINFO_start_file entry.  */
20661
20662   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
20663                                     NULL, xcalloc, xfree);
20664   cleanup = make_cleanup_htab_delete (include_hash);
20665   mac_ptr = section->buffer + offset;
20666   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
20667   *slot = (void *) mac_ptr;
20668   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
20669                             current_file, lh, comp_dir, section,
20670                             section_is_gnu, 0,
20671                             offset_size, objfile, include_hash);
20672   do_cleanups (cleanup);
20673 }
20674
20675 /* Check if the attribute's form is a DW_FORM_block*
20676    if so return true else false.  */
20677
20678 static int
20679 attr_form_is_block (const struct attribute *attr)
20680 {
20681   return (attr == NULL ? 0 :
20682       attr->form == DW_FORM_block1
20683       || attr->form == DW_FORM_block2
20684       || attr->form == DW_FORM_block4
20685       || attr->form == DW_FORM_block
20686       || attr->form == DW_FORM_exprloc);
20687 }
20688
20689 /* Return non-zero if ATTR's value is a section offset --- classes
20690    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
20691    You may use DW_UNSND (attr) to retrieve such offsets.
20692
20693    Section 7.5.4, "Attribute Encodings", explains that no attribute
20694    may have a value that belongs to more than one of these classes; it
20695    would be ambiguous if we did, because we use the same forms for all
20696    of them.  */
20697
20698 static int
20699 attr_form_is_section_offset (const struct attribute *attr)
20700 {
20701   return (attr->form == DW_FORM_data4
20702           || attr->form == DW_FORM_data8
20703           || attr->form == DW_FORM_sec_offset);
20704 }
20705
20706 /* Return non-zero if ATTR's value falls in the 'constant' class, or
20707    zero otherwise.  When this function returns true, you can apply
20708    dwarf2_get_attr_constant_value to it.
20709
20710    However, note that for some attributes you must check
20711    attr_form_is_section_offset before using this test.  DW_FORM_data4
20712    and DW_FORM_data8 are members of both the constant class, and of
20713    the classes that contain offsets into other debug sections
20714    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
20715    that, if an attribute's can be either a constant or one of the
20716    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
20717    taken as section offsets, not constants.  */
20718
20719 static int
20720 attr_form_is_constant (const struct attribute *attr)
20721 {
20722   switch (attr->form)
20723     {
20724     case DW_FORM_sdata:
20725     case DW_FORM_udata:
20726     case DW_FORM_data1:
20727     case DW_FORM_data2:
20728     case DW_FORM_data4:
20729     case DW_FORM_data8:
20730       return 1;
20731     default:
20732       return 0;
20733     }
20734 }
20735
20736
20737 /* DW_ADDR is always stored already as sect_offset; despite for the forms
20738    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
20739
20740 static int
20741 attr_form_is_ref (const struct attribute *attr)
20742 {
20743   switch (attr->form)
20744     {
20745     case DW_FORM_ref_addr:
20746     case DW_FORM_ref1:
20747     case DW_FORM_ref2:
20748     case DW_FORM_ref4:
20749     case DW_FORM_ref8:
20750     case DW_FORM_ref_udata:
20751     case DW_FORM_GNU_ref_alt:
20752       return 1;
20753     default:
20754       return 0;
20755     }
20756 }
20757
20758 /* Return the .debug_loc section to use for CU.
20759    For DWO files use .debug_loc.dwo.  */
20760
20761 static struct dwarf2_section_info *
20762 cu_debug_loc_section (struct dwarf2_cu *cu)
20763 {
20764   if (cu->dwo_unit)
20765     return &cu->dwo_unit->dwo_file->sections.loc;
20766   return &dwarf2_per_objfile->loc;
20767 }
20768
20769 /* A helper function that fills in a dwarf2_loclist_baton.  */
20770
20771 static void
20772 fill_in_loclist_baton (struct dwarf2_cu *cu,
20773                        struct dwarf2_loclist_baton *baton,
20774                        const struct attribute *attr)
20775 {
20776   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20777
20778   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20779
20780   baton->per_cu = cu->per_cu;
20781   gdb_assert (baton->per_cu);
20782   /* We don't know how long the location list is, but make sure we
20783      don't run off the edge of the section.  */
20784   baton->size = section->size - DW_UNSND (attr);
20785   baton->data = section->buffer + DW_UNSND (attr);
20786   baton->base_address = cu->base_address;
20787   baton->from_dwo = cu->dwo_unit != NULL;
20788 }
20789
20790 static void
20791 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
20792                              struct dwarf2_cu *cu, int is_block)
20793 {
20794   struct objfile *objfile = dwarf2_per_objfile->objfile;
20795   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20796
20797   if (attr_form_is_section_offset (attr)
20798       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
20799          the section.  If so, fall through to the complaint in the
20800          other branch.  */
20801       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
20802     {
20803       struct dwarf2_loclist_baton *baton;
20804
20805       baton = obstack_alloc (&objfile->objfile_obstack,
20806                              sizeof (struct dwarf2_loclist_baton));
20807
20808       fill_in_loclist_baton (cu, baton, attr);
20809
20810       if (cu->base_known == 0)
20811         complaint (&symfile_complaints,
20812                    _("Location list used without "
20813                      "specifying the CU base address."));
20814
20815       SYMBOL_ACLASS_INDEX (sym) = (is_block
20816                                    ? dwarf2_loclist_block_index
20817                                    : dwarf2_loclist_index);
20818       SYMBOL_LOCATION_BATON (sym) = baton;
20819     }
20820   else
20821     {
20822       struct dwarf2_locexpr_baton *baton;
20823
20824       baton = obstack_alloc (&objfile->objfile_obstack,
20825                              sizeof (struct dwarf2_locexpr_baton));
20826       baton->per_cu = cu->per_cu;
20827       gdb_assert (baton->per_cu);
20828
20829       if (attr_form_is_block (attr))
20830         {
20831           /* Note that we're just copying the block's data pointer
20832              here, not the actual data.  We're still pointing into the
20833              info_buffer for SYM's objfile; right now we never release
20834              that buffer, but when we do clean up properly this may
20835              need to change.  */
20836           baton->size = DW_BLOCK (attr)->size;
20837           baton->data = DW_BLOCK (attr)->data;
20838         }
20839       else
20840         {
20841           dwarf2_invalid_attrib_class_complaint ("location description",
20842                                                  SYMBOL_NATURAL_NAME (sym));
20843           baton->size = 0;
20844         }
20845
20846       SYMBOL_ACLASS_INDEX (sym) = (is_block
20847                                    ? dwarf2_locexpr_block_index
20848                                    : dwarf2_locexpr_index);
20849       SYMBOL_LOCATION_BATON (sym) = baton;
20850     }
20851 }
20852
20853 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20854    came from a separate debuginfo file, then the master objfile is
20855    returned.  */
20856
20857 struct objfile *
20858 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20859 {
20860   struct objfile *objfile = per_cu->objfile;
20861
20862   /* Return the master objfile, so that we can report and look up the
20863      correct file containing this variable.  */
20864   if (objfile->separate_debug_objfile_backlink)
20865     objfile = objfile->separate_debug_objfile_backlink;
20866
20867   return objfile;
20868 }
20869
20870 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20871    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20872    CU_HEADERP first.  */
20873
20874 static const struct comp_unit_head *
20875 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20876                        struct dwarf2_per_cu_data *per_cu)
20877 {
20878   const gdb_byte *info_ptr;
20879
20880   if (per_cu->cu)
20881     return &per_cu->cu->header;
20882
20883   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20884
20885   memset (cu_headerp, 0, sizeof (*cu_headerp));
20886   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20887
20888   return cu_headerp;
20889 }
20890
20891 /* Return the address size given in the compilation unit header for CU.  */
20892
20893 int
20894 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20895 {
20896   struct comp_unit_head cu_header_local;
20897   const struct comp_unit_head *cu_headerp;
20898
20899   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20900
20901   return cu_headerp->addr_size;
20902 }
20903
20904 /* Return the offset size given in the compilation unit header for CU.  */
20905
20906 int
20907 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20908 {
20909   struct comp_unit_head cu_header_local;
20910   const struct comp_unit_head *cu_headerp;
20911
20912   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20913
20914   return cu_headerp->offset_size;
20915 }
20916
20917 /* See its dwarf2loc.h declaration.  */
20918
20919 int
20920 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20921 {
20922   struct comp_unit_head cu_header_local;
20923   const struct comp_unit_head *cu_headerp;
20924
20925   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20926
20927   if (cu_headerp->version == 2)
20928     return cu_headerp->addr_size;
20929   else
20930     return cu_headerp->offset_size;
20931 }
20932
20933 /* Return the text offset of the CU.  The returned offset comes from
20934    this CU's objfile.  If this objfile came from a separate debuginfo
20935    file, then the offset may be different from the corresponding
20936    offset in the parent objfile.  */
20937
20938 CORE_ADDR
20939 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20940 {
20941   struct objfile *objfile = per_cu->objfile;
20942
20943   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20944 }
20945
20946 /* Locate the .debug_info compilation unit from CU's objfile which contains
20947    the DIE at OFFSET.  Raises an error on failure.  */
20948
20949 static struct dwarf2_per_cu_data *
20950 dwarf2_find_containing_comp_unit (sect_offset offset,
20951                                   unsigned int offset_in_dwz,
20952                                   struct objfile *objfile)
20953 {
20954   struct dwarf2_per_cu_data *this_cu;
20955   int low, high;
20956   const sect_offset *cu_off;
20957
20958   low = 0;
20959   high = dwarf2_per_objfile->n_comp_units - 1;
20960   while (high > low)
20961     {
20962       struct dwarf2_per_cu_data *mid_cu;
20963       int mid = low + (high - low) / 2;
20964
20965       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20966       cu_off = &mid_cu->offset;
20967       if (mid_cu->is_dwz > offset_in_dwz
20968           || (mid_cu->is_dwz == offset_in_dwz
20969               && cu_off->sect_off >= offset.sect_off))
20970         high = mid;
20971       else
20972         low = mid + 1;
20973     }
20974   gdb_assert (low == high);
20975   this_cu = dwarf2_per_objfile->all_comp_units[low];
20976   cu_off = &this_cu->offset;
20977   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20978     {
20979       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20980         error (_("Dwarf Error: could not find partial DIE containing "
20981                "offset 0x%lx [in module %s]"),
20982                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20983
20984       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20985                   <= offset.sect_off);
20986       return dwarf2_per_objfile->all_comp_units[low-1];
20987     }
20988   else
20989     {
20990       this_cu = dwarf2_per_objfile->all_comp_units[low];
20991       if (low == dwarf2_per_objfile->n_comp_units - 1
20992           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20993         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20994       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20995       return this_cu;
20996     }
20997 }
20998
20999 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
21000
21001 static void
21002 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
21003 {
21004   memset (cu, 0, sizeof (*cu));
21005   per_cu->cu = cu;
21006   cu->per_cu = per_cu;
21007   cu->objfile = per_cu->objfile;
21008   obstack_init (&cu->comp_unit_obstack);
21009 }
21010
21011 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
21012
21013 static void
21014 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
21015                        enum language pretend_language)
21016 {
21017   struct attribute *attr;
21018
21019   /* Set the language we're debugging.  */
21020   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
21021   if (attr)
21022     set_cu_language (DW_UNSND (attr), cu);
21023   else
21024     {
21025       cu->language = pretend_language;
21026       cu->language_defn = language_def (cu->language);
21027     }
21028
21029   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
21030   if (attr)
21031     cu->producer = DW_STRING (attr);
21032 }
21033
21034 /* Release one cached compilation unit, CU.  We unlink it from the tree
21035    of compilation units, but we don't remove it from the read_in_chain;
21036    the caller is responsible for that.
21037    NOTE: DATA is a void * because this function is also used as a
21038    cleanup routine.  */
21039
21040 static void
21041 free_heap_comp_unit (void *data)
21042 {
21043   struct dwarf2_cu *cu = data;
21044
21045   gdb_assert (cu->per_cu != NULL);
21046   cu->per_cu->cu = NULL;
21047   cu->per_cu = NULL;
21048
21049   obstack_free (&cu->comp_unit_obstack, NULL);
21050
21051   xfree (cu);
21052 }
21053
21054 /* This cleanup function is passed the address of a dwarf2_cu on the stack
21055    when we're finished with it.  We can't free the pointer itself, but be
21056    sure to unlink it from the cache.  Also release any associated storage.  */
21057
21058 static void
21059 free_stack_comp_unit (void *data)
21060 {
21061   struct dwarf2_cu *cu = data;
21062
21063   gdb_assert (cu->per_cu != NULL);
21064   cu->per_cu->cu = NULL;
21065   cu->per_cu = NULL;
21066
21067   obstack_free (&cu->comp_unit_obstack, NULL);
21068   cu->partial_dies = NULL;
21069 }
21070
21071 /* Free all cached compilation units.  */
21072
21073 static void
21074 free_cached_comp_units (void *data)
21075 {
21076   struct dwarf2_per_cu_data *per_cu, **last_chain;
21077
21078   per_cu = dwarf2_per_objfile->read_in_chain;
21079   last_chain = &dwarf2_per_objfile->read_in_chain;
21080   while (per_cu != NULL)
21081     {
21082       struct dwarf2_per_cu_data *next_cu;
21083
21084       next_cu = per_cu->cu->read_in_chain;
21085
21086       free_heap_comp_unit (per_cu->cu);
21087       *last_chain = next_cu;
21088
21089       per_cu = next_cu;
21090     }
21091 }
21092
21093 /* Increase the age counter on each cached compilation unit, and free
21094    any that are too old.  */
21095
21096 static void
21097 age_cached_comp_units (void)
21098 {
21099   struct dwarf2_per_cu_data *per_cu, **last_chain;
21100
21101   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
21102   per_cu = dwarf2_per_objfile->read_in_chain;
21103   while (per_cu != NULL)
21104     {
21105       per_cu->cu->last_used ++;
21106       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
21107         dwarf2_mark (per_cu->cu);
21108       per_cu = per_cu->cu->read_in_chain;
21109     }
21110
21111   per_cu = dwarf2_per_objfile->read_in_chain;
21112   last_chain = &dwarf2_per_objfile->read_in_chain;
21113   while (per_cu != NULL)
21114     {
21115       struct dwarf2_per_cu_data *next_cu;
21116
21117       next_cu = per_cu->cu->read_in_chain;
21118
21119       if (!per_cu->cu->mark)
21120         {
21121           free_heap_comp_unit (per_cu->cu);
21122           *last_chain = next_cu;
21123         }
21124       else
21125         last_chain = &per_cu->cu->read_in_chain;
21126
21127       per_cu = next_cu;
21128     }
21129 }
21130
21131 /* Remove a single compilation unit from the cache.  */
21132
21133 static void
21134 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
21135 {
21136   struct dwarf2_per_cu_data *per_cu, **last_chain;
21137
21138   per_cu = dwarf2_per_objfile->read_in_chain;
21139   last_chain = &dwarf2_per_objfile->read_in_chain;
21140   while (per_cu != NULL)
21141     {
21142       struct dwarf2_per_cu_data *next_cu;
21143
21144       next_cu = per_cu->cu->read_in_chain;
21145
21146       if (per_cu == target_per_cu)
21147         {
21148           free_heap_comp_unit (per_cu->cu);
21149           per_cu->cu = NULL;
21150           *last_chain = next_cu;
21151           break;
21152         }
21153       else
21154         last_chain = &per_cu->cu->read_in_chain;
21155
21156       per_cu = next_cu;
21157     }
21158 }
21159
21160 /* Release all extra memory associated with OBJFILE.  */
21161
21162 void
21163 dwarf2_free_objfile (struct objfile *objfile)
21164 {
21165   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21166
21167   if (dwarf2_per_objfile == NULL)
21168     return;
21169
21170   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
21171   free_cached_comp_units (NULL);
21172
21173   if (dwarf2_per_objfile->quick_file_names_table)
21174     htab_delete (dwarf2_per_objfile->quick_file_names_table);
21175
21176   /* Everything else should be on the objfile obstack.  */
21177 }
21178
21179 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
21180    We store these in a hash table separate from the DIEs, and preserve them
21181    when the DIEs are flushed out of cache.
21182
21183    The CU "per_cu" pointer is needed because offset alone is not enough to
21184    uniquely identify the type.  A file may have multiple .debug_types sections,
21185    or the type may come from a DWO file.  Furthermore, while it's more logical
21186    to use per_cu->section+offset, with Fission the section with the data is in
21187    the DWO file but we don't know that section at the point we need it.
21188    We have to use something in dwarf2_per_cu_data (or the pointer to it)
21189    because we can enter the lookup routine, get_die_type_at_offset, from
21190    outside this file, and thus won't necessarily have PER_CU->cu.
21191    Fortunately, PER_CU is stable for the life of the objfile.  */
21192
21193 struct dwarf2_per_cu_offset_and_type
21194 {
21195   const struct dwarf2_per_cu_data *per_cu;
21196   sect_offset offset;
21197   struct type *type;
21198 };
21199
21200 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
21201
21202 static hashval_t
21203 per_cu_offset_and_type_hash (const void *item)
21204 {
21205   const struct dwarf2_per_cu_offset_and_type *ofs = item;
21206
21207   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
21208 }
21209
21210 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
21211
21212 static int
21213 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
21214 {
21215   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
21216   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
21217
21218   return (ofs_lhs->per_cu == ofs_rhs->per_cu
21219           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
21220 }
21221
21222 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
21223    table if necessary.  For convenience, return TYPE.
21224
21225    The DIEs reading must have careful ordering to:
21226     * Not cause infite loops trying to read in DIEs as a prerequisite for
21227       reading current DIE.
21228     * Not trying to dereference contents of still incompletely read in types
21229       while reading in other DIEs.
21230     * Enable referencing still incompletely read in types just by a pointer to
21231       the type without accessing its fields.
21232
21233    Therefore caller should follow these rules:
21234      * Try to fetch any prerequisite types we may need to build this DIE type
21235        before building the type and calling set_die_type.
21236      * After building type call set_die_type for current DIE as soon as
21237        possible before fetching more types to complete the current type.
21238      * Make the type as complete as possible before fetching more types.  */
21239
21240 static struct type *
21241 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21242 {
21243   struct dwarf2_per_cu_offset_and_type **slot, ofs;
21244   struct objfile *objfile = cu->objfile;
21245
21246   /* For Ada types, make sure that the gnat-specific data is always
21247      initialized (if not already set).  There are a few types where
21248      we should not be doing so, because the type-specific area is
21249      already used to hold some other piece of info (eg: TYPE_CODE_FLT
21250      where the type-specific area is used to store the floatformat).
21251      But this is not a problem, because the gnat-specific information
21252      is actually not needed for these types.  */
21253   if (need_gnat_info (cu)
21254       && TYPE_CODE (type) != TYPE_CODE_FUNC
21255       && TYPE_CODE (type) != TYPE_CODE_FLT
21256       && !HAVE_GNAT_AUX_INFO (type))
21257     INIT_GNAT_SPECIFIC (type);
21258
21259   if (dwarf2_per_objfile->die_type_hash == NULL)
21260     {
21261       dwarf2_per_objfile->die_type_hash =
21262         htab_create_alloc_ex (127,
21263                               per_cu_offset_and_type_hash,
21264                               per_cu_offset_and_type_eq,
21265                               NULL,
21266                               &objfile->objfile_obstack,
21267                               hashtab_obstack_allocate,
21268                               dummy_obstack_deallocate);
21269     }
21270
21271   ofs.per_cu = cu->per_cu;
21272   ofs.offset = die->offset;
21273   ofs.type = type;
21274   slot = (struct dwarf2_per_cu_offset_and_type **)
21275     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
21276   if (*slot)
21277     complaint (&symfile_complaints,
21278                _("A problem internal to GDB: DIE 0x%x has type already set"),
21279                die->offset.sect_off);
21280   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
21281   **slot = ofs;
21282   return type;
21283 }
21284
21285 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
21286    or return NULL if the die does not have a saved type.  */
21287
21288 static struct type *
21289 get_die_type_at_offset (sect_offset offset,
21290                         struct dwarf2_per_cu_data *per_cu)
21291 {
21292   struct dwarf2_per_cu_offset_and_type *slot, ofs;
21293
21294   if (dwarf2_per_objfile->die_type_hash == NULL)
21295     return NULL;
21296
21297   ofs.per_cu = per_cu;
21298   ofs.offset = offset;
21299   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
21300   if (slot)
21301     return slot->type;
21302   else
21303     return NULL;
21304 }
21305
21306 /* Look up the type for DIE in CU in die_type_hash,
21307    or return NULL if DIE does not have a saved type.  */
21308
21309 static struct type *
21310 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
21311 {
21312   return get_die_type_at_offset (die->offset, cu->per_cu);
21313 }
21314
21315 /* Add a dependence relationship from CU to REF_PER_CU.  */
21316
21317 static void
21318 dwarf2_add_dependence (struct dwarf2_cu *cu,
21319                        struct dwarf2_per_cu_data *ref_per_cu)
21320 {
21321   void **slot;
21322
21323   if (cu->dependencies == NULL)
21324     cu->dependencies
21325       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
21326                               NULL, &cu->comp_unit_obstack,
21327                               hashtab_obstack_allocate,
21328                               dummy_obstack_deallocate);
21329
21330   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
21331   if (*slot == NULL)
21332     *slot = ref_per_cu;
21333 }
21334
21335 /* Subroutine of dwarf2_mark to pass to htab_traverse.
21336    Set the mark field in every compilation unit in the
21337    cache that we must keep because we are keeping CU.  */
21338
21339 static int
21340 dwarf2_mark_helper (void **slot, void *data)
21341 {
21342   struct dwarf2_per_cu_data *per_cu;
21343
21344   per_cu = (struct dwarf2_per_cu_data *) *slot;
21345
21346   /* cu->dependencies references may not yet have been ever read if QUIT aborts
21347      reading of the chain.  As such dependencies remain valid it is not much
21348      useful to track and undo them during QUIT cleanups.  */
21349   if (per_cu->cu == NULL)
21350     return 1;
21351
21352   if (per_cu->cu->mark)
21353     return 1;
21354   per_cu->cu->mark = 1;
21355
21356   if (per_cu->cu->dependencies != NULL)
21357     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
21358
21359   return 1;
21360 }
21361
21362 /* Set the mark field in CU and in every other compilation unit in the
21363    cache that we must keep because we are keeping CU.  */
21364
21365 static void
21366 dwarf2_mark (struct dwarf2_cu *cu)
21367 {
21368   if (cu->mark)
21369     return;
21370   cu->mark = 1;
21371   if (cu->dependencies != NULL)
21372     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
21373 }
21374
21375 static void
21376 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
21377 {
21378   while (per_cu)
21379     {
21380       per_cu->cu->mark = 0;
21381       per_cu = per_cu->cu->read_in_chain;
21382     }
21383 }
21384
21385 /* Trivial hash function for partial_die_info: the hash value of a DIE
21386    is its offset in .debug_info for this objfile.  */
21387
21388 static hashval_t
21389 partial_die_hash (const void *item)
21390 {
21391   const struct partial_die_info *part_die = item;
21392
21393   return part_die->offset.sect_off;
21394 }
21395
21396 /* Trivial comparison function for partial_die_info structures: two DIEs
21397    are equal if they have the same offset.  */
21398
21399 static int
21400 partial_die_eq (const void *item_lhs, const void *item_rhs)
21401 {
21402   const struct partial_die_info *part_die_lhs = item_lhs;
21403   const struct partial_die_info *part_die_rhs = item_rhs;
21404
21405   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
21406 }
21407
21408 static struct cmd_list_element *set_dwarf2_cmdlist;
21409 static struct cmd_list_element *show_dwarf2_cmdlist;
21410
21411 static void
21412 set_dwarf2_cmd (char *args, int from_tty)
21413 {
21414   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
21415 }
21416
21417 static void
21418 show_dwarf2_cmd (char *args, int from_tty)
21419 {
21420   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
21421 }
21422
21423 /* Free data associated with OBJFILE, if necessary.  */
21424
21425 static void
21426 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
21427 {
21428   struct dwarf2_per_objfile *data = d;
21429   int ix;
21430
21431   /* Make sure we don't accidentally use dwarf2_per_objfile while
21432      cleaning up.  */
21433   dwarf2_per_objfile = NULL;
21434
21435   for (ix = 0; ix < data->n_comp_units; ++ix)
21436    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
21437
21438   for (ix = 0; ix < data->n_type_units; ++ix)
21439     VEC_free (dwarf2_per_cu_ptr,
21440               data->all_type_units[ix]->per_cu.imported_symtabs);
21441   xfree (data->all_type_units);
21442
21443   VEC_free (dwarf2_section_info_def, data->types);
21444
21445   if (data->dwo_files)
21446     free_dwo_files (data->dwo_files, objfile);
21447   if (data->dwp_file)
21448     gdb_bfd_unref (data->dwp_file->dbfd);
21449
21450   if (data->dwz_file && data->dwz_file->dwz_bfd)
21451     gdb_bfd_unref (data->dwz_file->dwz_bfd);
21452 }
21453
21454 \f
21455 /* The "save gdb-index" command.  */
21456
21457 /* The contents of the hash table we create when building the string
21458    table.  */
21459 struct strtab_entry
21460 {
21461   offset_type offset;
21462   const char *str;
21463 };
21464
21465 /* Hash function for a strtab_entry.
21466
21467    Function is used only during write_hash_table so no index format backward
21468    compatibility is needed.  */
21469
21470 static hashval_t
21471 hash_strtab_entry (const void *e)
21472 {
21473   const struct strtab_entry *entry = e;
21474   return mapped_index_string_hash (INT_MAX, entry->str);
21475 }
21476
21477 /* Equality function for a strtab_entry.  */
21478
21479 static int
21480 eq_strtab_entry (const void *a, const void *b)
21481 {
21482   const struct strtab_entry *ea = a;
21483   const struct strtab_entry *eb = b;
21484   return !strcmp (ea->str, eb->str);
21485 }
21486
21487 /* Create a strtab_entry hash table.  */
21488
21489 static htab_t
21490 create_strtab (void)
21491 {
21492   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
21493                             xfree, xcalloc, xfree);
21494 }
21495
21496 /* Add a string to the constant pool.  Return the string's offset in
21497    host order.  */
21498
21499 static offset_type
21500 add_string (htab_t table, struct obstack *cpool, const char *str)
21501 {
21502   void **slot;
21503   struct strtab_entry entry;
21504   struct strtab_entry *result;
21505
21506   entry.str = str;
21507   slot = htab_find_slot (table, &entry, INSERT);
21508   if (*slot)
21509     result = *slot;
21510   else
21511     {
21512       result = XNEW (struct strtab_entry);
21513       result->offset = obstack_object_size (cpool);
21514       result->str = str;
21515       obstack_grow_str0 (cpool, str);
21516       *slot = result;
21517     }
21518   return result->offset;
21519 }
21520
21521 /* An entry in the symbol table.  */
21522 struct symtab_index_entry
21523 {
21524   /* The name of the symbol.  */
21525   const char *name;
21526   /* The offset of the name in the constant pool.  */
21527   offset_type index_offset;
21528   /* A sorted vector of the indices of all the CUs that hold an object
21529      of this name.  */
21530   VEC (offset_type) *cu_indices;
21531 };
21532
21533 /* The symbol table.  This is a power-of-2-sized hash table.  */
21534 struct mapped_symtab
21535 {
21536   offset_type n_elements;
21537   offset_type size;
21538   struct symtab_index_entry **data;
21539 };
21540
21541 /* Hash function for a symtab_index_entry.  */
21542
21543 static hashval_t
21544 hash_symtab_entry (const void *e)
21545 {
21546   const struct symtab_index_entry *entry = e;
21547   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
21548                          sizeof (offset_type) * VEC_length (offset_type,
21549                                                             entry->cu_indices),
21550                          0);
21551 }
21552
21553 /* Equality function for a symtab_index_entry.  */
21554
21555 static int
21556 eq_symtab_entry (const void *a, const void *b)
21557 {
21558   const struct symtab_index_entry *ea = a;
21559   const struct symtab_index_entry *eb = b;
21560   int len = VEC_length (offset_type, ea->cu_indices);
21561   if (len != VEC_length (offset_type, eb->cu_indices))
21562     return 0;
21563   return !memcmp (VEC_address (offset_type, ea->cu_indices),
21564                   VEC_address (offset_type, eb->cu_indices),
21565                   sizeof (offset_type) * len);
21566 }
21567
21568 /* Destroy a symtab_index_entry.  */
21569
21570 static void
21571 delete_symtab_entry (void *p)
21572 {
21573   struct symtab_index_entry *entry = p;
21574   VEC_free (offset_type, entry->cu_indices);
21575   xfree (entry);
21576 }
21577
21578 /* Create a hash table holding symtab_index_entry objects.  */
21579
21580 static htab_t
21581 create_symbol_hash_table (void)
21582 {
21583   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
21584                             delete_symtab_entry, xcalloc, xfree);
21585 }
21586
21587 /* Create a new mapped symtab object.  */
21588
21589 static struct mapped_symtab *
21590 create_mapped_symtab (void)
21591 {
21592   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
21593   symtab->n_elements = 0;
21594   symtab->size = 1024;
21595   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21596   return symtab;
21597 }
21598
21599 /* Destroy a mapped_symtab.  */
21600
21601 static void
21602 cleanup_mapped_symtab (void *p)
21603 {
21604   struct mapped_symtab *symtab = p;
21605   /* The contents of the array are freed when the other hash table is
21606      destroyed.  */
21607   xfree (symtab->data);
21608   xfree (symtab);
21609 }
21610
21611 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
21612    the slot.
21613    
21614    Function is used only during write_hash_table so no index format backward
21615    compatibility is needed.  */
21616
21617 static struct symtab_index_entry **
21618 find_slot (struct mapped_symtab *symtab, const char *name)
21619 {
21620   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
21621
21622   index = hash & (symtab->size - 1);
21623   step = ((hash * 17) & (symtab->size - 1)) | 1;
21624
21625   for (;;)
21626     {
21627       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
21628         return &symtab->data[index];
21629       index = (index + step) & (symtab->size - 1);
21630     }
21631 }
21632
21633 /* Expand SYMTAB's hash table.  */
21634
21635 static void
21636 hash_expand (struct mapped_symtab *symtab)
21637 {
21638   offset_type old_size = symtab->size;
21639   offset_type i;
21640   struct symtab_index_entry **old_entries = symtab->data;
21641
21642   symtab->size *= 2;
21643   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21644
21645   for (i = 0; i < old_size; ++i)
21646     {
21647       if (old_entries[i])
21648         {
21649           struct symtab_index_entry **slot = find_slot (symtab,
21650                                                         old_entries[i]->name);
21651           *slot = old_entries[i];
21652         }
21653     }
21654
21655   xfree (old_entries);
21656 }
21657
21658 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
21659    CU_INDEX is the index of the CU in which the symbol appears.
21660    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
21661
21662 static void
21663 add_index_entry (struct mapped_symtab *symtab, const char *name,
21664                  int is_static, gdb_index_symbol_kind kind,
21665                  offset_type cu_index)
21666 {
21667   struct symtab_index_entry **slot;
21668   offset_type cu_index_and_attrs;
21669
21670   ++symtab->n_elements;
21671   if (4 * symtab->n_elements / 3 >= symtab->size)
21672     hash_expand (symtab);
21673
21674   slot = find_slot (symtab, name);
21675   if (!*slot)
21676     {
21677       *slot = XNEW (struct symtab_index_entry);
21678       (*slot)->name = name;
21679       /* index_offset is set later.  */
21680       (*slot)->cu_indices = NULL;
21681     }
21682
21683   cu_index_and_attrs = 0;
21684   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
21685   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
21686   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
21687
21688   /* We don't want to record an index value twice as we want to avoid the
21689      duplication.
21690      We process all global symbols and then all static symbols
21691      (which would allow us to avoid the duplication by only having to check
21692      the last entry pushed), but a symbol could have multiple kinds in one CU.
21693      To keep things simple we don't worry about the duplication here and
21694      sort and uniqufy the list after we've processed all symbols.  */
21695   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
21696 }
21697
21698 /* qsort helper routine for uniquify_cu_indices.  */
21699
21700 static int
21701 offset_type_compare (const void *ap, const void *bp)
21702 {
21703   offset_type a = *(offset_type *) ap;
21704   offset_type b = *(offset_type *) bp;
21705
21706   return (a > b) - (b > a);
21707 }
21708
21709 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
21710
21711 static void
21712 uniquify_cu_indices (struct mapped_symtab *symtab)
21713 {
21714   int i;
21715
21716   for (i = 0; i < symtab->size; ++i)
21717     {
21718       struct symtab_index_entry *entry = symtab->data[i];
21719
21720       if (entry
21721           && entry->cu_indices != NULL)
21722         {
21723           unsigned int next_to_insert, next_to_check;
21724           offset_type last_value;
21725
21726           qsort (VEC_address (offset_type, entry->cu_indices),
21727                  VEC_length (offset_type, entry->cu_indices),
21728                  sizeof (offset_type), offset_type_compare);
21729
21730           last_value = VEC_index (offset_type, entry->cu_indices, 0);
21731           next_to_insert = 1;
21732           for (next_to_check = 1;
21733                next_to_check < VEC_length (offset_type, entry->cu_indices);
21734                ++next_to_check)
21735             {
21736               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
21737                   != last_value)
21738                 {
21739                   last_value = VEC_index (offset_type, entry->cu_indices,
21740                                           next_to_check);
21741                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
21742                                last_value);
21743                   ++next_to_insert;
21744                 }
21745             }
21746           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
21747         }
21748     }
21749 }
21750
21751 /* Add a vector of indices to the constant pool.  */
21752
21753 static offset_type
21754 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
21755                       struct symtab_index_entry *entry)
21756 {
21757   void **slot;
21758
21759   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
21760   if (!*slot)
21761     {
21762       offset_type len = VEC_length (offset_type, entry->cu_indices);
21763       offset_type val = MAYBE_SWAP (len);
21764       offset_type iter;
21765       int i;
21766
21767       *slot = entry;
21768       entry->index_offset = obstack_object_size (cpool);
21769
21770       obstack_grow (cpool, &val, sizeof (val));
21771       for (i = 0;
21772            VEC_iterate (offset_type, entry->cu_indices, i, iter);
21773            ++i)
21774         {
21775           val = MAYBE_SWAP (iter);
21776           obstack_grow (cpool, &val, sizeof (val));
21777         }
21778     }
21779   else
21780     {
21781       struct symtab_index_entry *old_entry = *slot;
21782       entry->index_offset = old_entry->index_offset;
21783       entry = old_entry;
21784     }
21785   return entry->index_offset;
21786 }
21787
21788 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
21789    constant pool entries going into the obstack CPOOL.  */
21790
21791 static void
21792 write_hash_table (struct mapped_symtab *symtab,
21793                   struct obstack *output, struct obstack *cpool)
21794 {
21795   offset_type i;
21796   htab_t symbol_hash_table;
21797   htab_t str_table;
21798
21799   symbol_hash_table = create_symbol_hash_table ();
21800   str_table = create_strtab ();
21801
21802   /* We add all the index vectors to the constant pool first, to
21803      ensure alignment is ok.  */
21804   for (i = 0; i < symtab->size; ++i)
21805     {
21806       if (symtab->data[i])
21807         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
21808     }
21809
21810   /* Now write out the hash table.  */
21811   for (i = 0; i < symtab->size; ++i)
21812     {
21813       offset_type str_off, vec_off;
21814
21815       if (symtab->data[i])
21816         {
21817           str_off = add_string (str_table, cpool, symtab->data[i]->name);
21818           vec_off = symtab->data[i]->index_offset;
21819         }
21820       else
21821         {
21822           /* While 0 is a valid constant pool index, it is not valid
21823              to have 0 for both offsets.  */
21824           str_off = 0;
21825           vec_off = 0;
21826         }
21827
21828       str_off = MAYBE_SWAP (str_off);
21829       vec_off = MAYBE_SWAP (vec_off);
21830
21831       obstack_grow (output, &str_off, sizeof (str_off));
21832       obstack_grow (output, &vec_off, sizeof (vec_off));
21833     }
21834
21835   htab_delete (str_table);
21836   htab_delete (symbol_hash_table);
21837 }
21838
21839 /* Struct to map psymtab to CU index in the index file.  */
21840 struct psymtab_cu_index_map
21841 {
21842   struct partial_symtab *psymtab;
21843   unsigned int cu_index;
21844 };
21845
21846 static hashval_t
21847 hash_psymtab_cu_index (const void *item)
21848 {
21849   const struct psymtab_cu_index_map *map = item;
21850
21851   return htab_hash_pointer (map->psymtab);
21852 }
21853
21854 static int
21855 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21856 {
21857   const struct psymtab_cu_index_map *lhs = item_lhs;
21858   const struct psymtab_cu_index_map *rhs = item_rhs;
21859
21860   return lhs->psymtab == rhs->psymtab;
21861 }
21862
21863 /* Helper struct for building the address table.  */
21864 struct addrmap_index_data
21865 {
21866   struct objfile *objfile;
21867   struct obstack *addr_obstack;
21868   htab_t cu_index_htab;
21869
21870   /* Non-zero if the previous_* fields are valid.
21871      We can't write an entry until we see the next entry (since it is only then
21872      that we know the end of the entry).  */
21873   int previous_valid;
21874   /* Index of the CU in the table of all CUs in the index file.  */
21875   unsigned int previous_cu_index;
21876   /* Start address of the CU.  */
21877   CORE_ADDR previous_cu_start;
21878 };
21879
21880 /* Write an address entry to OBSTACK.  */
21881
21882 static void
21883 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21884                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21885 {
21886   offset_type cu_index_to_write;
21887   gdb_byte addr[8];
21888   CORE_ADDR baseaddr;
21889
21890   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21891
21892   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21893   obstack_grow (obstack, addr, 8);
21894   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21895   obstack_grow (obstack, addr, 8);
21896   cu_index_to_write = MAYBE_SWAP (cu_index);
21897   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21898 }
21899
21900 /* Worker function for traversing an addrmap to build the address table.  */
21901
21902 static int
21903 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21904 {
21905   struct addrmap_index_data *data = datap;
21906   struct partial_symtab *pst = obj;
21907
21908   if (data->previous_valid)
21909     add_address_entry (data->objfile, data->addr_obstack,
21910                        data->previous_cu_start, start_addr,
21911                        data->previous_cu_index);
21912
21913   data->previous_cu_start = start_addr;
21914   if (pst != NULL)
21915     {
21916       struct psymtab_cu_index_map find_map, *map;
21917       find_map.psymtab = pst;
21918       map = htab_find (data->cu_index_htab, &find_map);
21919       gdb_assert (map != NULL);
21920       data->previous_cu_index = map->cu_index;
21921       data->previous_valid = 1;
21922     }
21923   else
21924       data->previous_valid = 0;
21925
21926   return 0;
21927 }
21928
21929 /* Write OBJFILE's address map to OBSTACK.
21930    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21931    in the index file.  */
21932
21933 static void
21934 write_address_map (struct objfile *objfile, struct obstack *obstack,
21935                    htab_t cu_index_htab)
21936 {
21937   struct addrmap_index_data addrmap_index_data;
21938
21939   /* When writing the address table, we have to cope with the fact that
21940      the addrmap iterator only provides the start of a region; we have to
21941      wait until the next invocation to get the start of the next region.  */
21942
21943   addrmap_index_data.objfile = objfile;
21944   addrmap_index_data.addr_obstack = obstack;
21945   addrmap_index_data.cu_index_htab = cu_index_htab;
21946   addrmap_index_data.previous_valid = 0;
21947
21948   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21949                    &addrmap_index_data);
21950
21951   /* It's highly unlikely the last entry (end address = 0xff...ff)
21952      is valid, but we should still handle it.
21953      The end address is recorded as the start of the next region, but that
21954      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21955      anyway.  */
21956   if (addrmap_index_data.previous_valid)
21957     add_address_entry (objfile, obstack,
21958                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21959                        addrmap_index_data.previous_cu_index);
21960 }
21961
21962 /* Return the symbol kind of PSYM.  */
21963
21964 static gdb_index_symbol_kind
21965 symbol_kind (struct partial_symbol *psym)
21966 {
21967   domain_enum domain = PSYMBOL_DOMAIN (psym);
21968   enum address_class aclass = PSYMBOL_CLASS (psym);
21969
21970   switch (domain)
21971     {
21972     case VAR_DOMAIN:
21973       switch (aclass)
21974         {
21975         case LOC_BLOCK:
21976           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21977         case LOC_TYPEDEF:
21978           return GDB_INDEX_SYMBOL_KIND_TYPE;
21979         case LOC_COMPUTED:
21980         case LOC_CONST_BYTES:
21981         case LOC_OPTIMIZED_OUT:
21982         case LOC_STATIC:
21983           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21984         case LOC_CONST:
21985           /* Note: It's currently impossible to recognize psyms as enum values
21986              short of reading the type info.  For now punt.  */
21987           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21988         default:
21989           /* There are other LOC_FOO values that one might want to classify
21990              as variables, but dwarf2read.c doesn't currently use them.  */
21991           return GDB_INDEX_SYMBOL_KIND_OTHER;
21992         }
21993     case STRUCT_DOMAIN:
21994       return GDB_INDEX_SYMBOL_KIND_TYPE;
21995     default:
21996       return GDB_INDEX_SYMBOL_KIND_OTHER;
21997     }
21998 }
21999
22000 /* Add a list of partial symbols to SYMTAB.  */
22001
22002 static void
22003 write_psymbols (struct mapped_symtab *symtab,
22004                 htab_t psyms_seen,
22005                 struct partial_symbol **psymp,
22006                 int count,
22007                 offset_type cu_index,
22008                 int is_static)
22009 {
22010   for (; count-- > 0; ++psymp)
22011     {
22012       struct partial_symbol *psym = *psymp;
22013       void **slot;
22014
22015       if (SYMBOL_LANGUAGE (psym) == language_ada)
22016         error (_("Ada is not currently supported by the index"));
22017
22018       /* Only add a given psymbol once.  */
22019       slot = htab_find_slot (psyms_seen, psym, INSERT);
22020       if (!*slot)
22021         {
22022           gdb_index_symbol_kind kind = symbol_kind (psym);
22023
22024           *slot = psym;
22025           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
22026                            is_static, kind, cu_index);
22027         }
22028     }
22029 }
22030
22031 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
22032    exception if there is an error.  */
22033
22034 static void
22035 write_obstack (FILE *file, struct obstack *obstack)
22036 {
22037   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
22038               file)
22039       != obstack_object_size (obstack))
22040     error (_("couldn't data write to file"));
22041 }
22042
22043 /* Unlink a file if the argument is not NULL.  */
22044
22045 static void
22046 unlink_if_set (void *p)
22047 {
22048   char **filename = p;
22049   if (*filename)
22050     unlink (*filename);
22051 }
22052
22053 /* A helper struct used when iterating over debug_types.  */
22054 struct signatured_type_index_data
22055 {
22056   struct objfile *objfile;
22057   struct mapped_symtab *symtab;
22058   struct obstack *types_list;
22059   htab_t psyms_seen;
22060   int cu_index;
22061 };
22062
22063 /* A helper function that writes a single signatured_type to an
22064    obstack.  */
22065
22066 static int
22067 write_one_signatured_type (void **slot, void *d)
22068 {
22069   struct signatured_type_index_data *info = d;
22070   struct signatured_type *entry = (struct signatured_type *) *slot;
22071   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
22072   gdb_byte val[8];
22073
22074   write_psymbols (info->symtab,
22075                   info->psyms_seen,
22076                   info->objfile->global_psymbols.list
22077                   + psymtab->globals_offset,
22078                   psymtab->n_global_syms, info->cu_index,
22079                   0);
22080   write_psymbols (info->symtab,
22081                   info->psyms_seen,
22082                   info->objfile->static_psymbols.list
22083                   + psymtab->statics_offset,
22084                   psymtab->n_static_syms, info->cu_index,
22085                   1);
22086
22087   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22088                           entry->per_cu.offset.sect_off);
22089   obstack_grow (info->types_list, val, 8);
22090   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22091                           entry->type_offset_in_tu.cu_off);
22092   obstack_grow (info->types_list, val, 8);
22093   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
22094   obstack_grow (info->types_list, val, 8);
22095
22096   ++info->cu_index;
22097
22098   return 1;
22099 }
22100
22101 /* Recurse into all "included" dependencies and write their symbols as
22102    if they appeared in this psymtab.  */
22103
22104 static void
22105 recursively_write_psymbols (struct objfile *objfile,
22106                             struct partial_symtab *psymtab,
22107                             struct mapped_symtab *symtab,
22108                             htab_t psyms_seen,
22109                             offset_type cu_index)
22110 {
22111   int i;
22112
22113   for (i = 0; i < psymtab->number_of_dependencies; ++i)
22114     if (psymtab->dependencies[i]->user != NULL)
22115       recursively_write_psymbols (objfile, psymtab->dependencies[i],
22116                                   symtab, psyms_seen, cu_index);
22117
22118   write_psymbols (symtab,
22119                   psyms_seen,
22120                   objfile->global_psymbols.list + psymtab->globals_offset,
22121                   psymtab->n_global_syms, cu_index,
22122                   0);
22123   write_psymbols (symtab,
22124                   psyms_seen,
22125                   objfile->static_psymbols.list + psymtab->statics_offset,
22126                   psymtab->n_static_syms, cu_index,
22127                   1);
22128 }
22129
22130 /* Create an index file for OBJFILE in the directory DIR.  */
22131
22132 static void
22133 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
22134 {
22135   struct cleanup *cleanup;
22136   char *filename, *cleanup_filename;
22137   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
22138   struct obstack cu_list, types_cu_list;
22139   int i;
22140   FILE *out_file;
22141   struct mapped_symtab *symtab;
22142   offset_type val, size_of_contents, total_len;
22143   struct stat st;
22144   htab_t psyms_seen;
22145   htab_t cu_index_htab;
22146   struct psymtab_cu_index_map *psymtab_cu_index_map;
22147
22148   if (dwarf2_per_objfile->using_index)
22149     error (_("Cannot use an index to create the index"));
22150
22151   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
22152     error (_("Cannot make an index when the file has multiple .debug_types sections"));
22153
22154   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
22155     return;
22156
22157   if (stat (objfile_name (objfile), &st) < 0)
22158     perror_with_name (objfile_name (objfile));
22159
22160   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
22161                      INDEX_SUFFIX, (char *) NULL);
22162   cleanup = make_cleanup (xfree, filename);
22163
22164   out_file = gdb_fopen_cloexec (filename, "wb");
22165   if (!out_file)
22166     error (_("Can't open `%s' for writing"), filename);
22167
22168   cleanup_filename = filename;
22169   make_cleanup (unlink_if_set, &cleanup_filename);
22170
22171   symtab = create_mapped_symtab ();
22172   make_cleanup (cleanup_mapped_symtab, symtab);
22173
22174   obstack_init (&addr_obstack);
22175   make_cleanup_obstack_free (&addr_obstack);
22176
22177   obstack_init (&cu_list);
22178   make_cleanup_obstack_free (&cu_list);
22179
22180   obstack_init (&types_cu_list);
22181   make_cleanup_obstack_free (&types_cu_list);
22182
22183   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
22184                                   NULL, xcalloc, xfree);
22185   make_cleanup_htab_delete (psyms_seen);
22186
22187   /* While we're scanning CU's create a table that maps a psymtab pointer
22188      (which is what addrmap records) to its index (which is what is recorded
22189      in the index file).  This will later be needed to write the address
22190      table.  */
22191   cu_index_htab = htab_create_alloc (100,
22192                                      hash_psymtab_cu_index,
22193                                      eq_psymtab_cu_index,
22194                                      NULL, xcalloc, xfree);
22195   make_cleanup_htab_delete (cu_index_htab);
22196   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
22197     xmalloc (sizeof (struct psymtab_cu_index_map)
22198              * dwarf2_per_objfile->n_comp_units);
22199   make_cleanup (xfree, psymtab_cu_index_map);
22200
22201   /* The CU list is already sorted, so we don't need to do additional
22202      work here.  Also, the debug_types entries do not appear in
22203      all_comp_units, but only in their own hash table.  */
22204   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
22205     {
22206       struct dwarf2_per_cu_data *per_cu
22207         = dwarf2_per_objfile->all_comp_units[i];
22208       struct partial_symtab *psymtab = per_cu->v.psymtab;
22209       gdb_byte val[8];
22210       struct psymtab_cu_index_map *map;
22211       void **slot;
22212
22213       /* CU of a shared file from 'dwz -m' may be unused by this main file.
22214          It may be referenced from a local scope but in such case it does not
22215          need to be present in .gdb_index.  */
22216       if (psymtab == NULL)
22217         continue;
22218
22219       if (psymtab->user == NULL)
22220         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
22221
22222       map = &psymtab_cu_index_map[i];
22223       map->psymtab = psymtab;
22224       map->cu_index = i;
22225       slot = htab_find_slot (cu_index_htab, map, INSERT);
22226       gdb_assert (slot != NULL);
22227       gdb_assert (*slot == NULL);
22228       *slot = map;
22229
22230       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22231                               per_cu->offset.sect_off);
22232       obstack_grow (&cu_list, val, 8);
22233       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
22234       obstack_grow (&cu_list, val, 8);
22235     }
22236
22237   /* Dump the address map.  */
22238   write_address_map (objfile, &addr_obstack, cu_index_htab);
22239
22240   /* Write out the .debug_type entries, if any.  */
22241   if (dwarf2_per_objfile->signatured_types)
22242     {
22243       struct signatured_type_index_data sig_data;
22244
22245       sig_data.objfile = objfile;
22246       sig_data.symtab = symtab;
22247       sig_data.types_list = &types_cu_list;
22248       sig_data.psyms_seen = psyms_seen;
22249       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
22250       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
22251                               write_one_signatured_type, &sig_data);
22252     }
22253
22254   /* Now that we've processed all symbols we can shrink their cu_indices
22255      lists.  */
22256   uniquify_cu_indices (symtab);
22257
22258   obstack_init (&constant_pool);
22259   make_cleanup_obstack_free (&constant_pool);
22260   obstack_init (&symtab_obstack);
22261   make_cleanup_obstack_free (&symtab_obstack);
22262   write_hash_table (symtab, &symtab_obstack, &constant_pool);
22263
22264   obstack_init (&contents);
22265   make_cleanup_obstack_free (&contents);
22266   size_of_contents = 6 * sizeof (offset_type);
22267   total_len = size_of_contents;
22268
22269   /* The version number.  */
22270   val = MAYBE_SWAP (8);
22271   obstack_grow (&contents, &val, sizeof (val));
22272
22273   /* The offset of the CU list from the start of the file.  */
22274   val = MAYBE_SWAP (total_len);
22275   obstack_grow (&contents, &val, sizeof (val));
22276   total_len += obstack_object_size (&cu_list);
22277
22278   /* The offset of the types CU list from the start of the file.  */
22279   val = MAYBE_SWAP (total_len);
22280   obstack_grow (&contents, &val, sizeof (val));
22281   total_len += obstack_object_size (&types_cu_list);
22282
22283   /* The offset of the address table from the start of the file.  */
22284   val = MAYBE_SWAP (total_len);
22285   obstack_grow (&contents, &val, sizeof (val));
22286   total_len += obstack_object_size (&addr_obstack);
22287
22288   /* The offset of the symbol table from the start of the file.  */
22289   val = MAYBE_SWAP (total_len);
22290   obstack_grow (&contents, &val, sizeof (val));
22291   total_len += obstack_object_size (&symtab_obstack);
22292
22293   /* The offset of the constant pool from the start of the file.  */
22294   val = MAYBE_SWAP (total_len);
22295   obstack_grow (&contents, &val, sizeof (val));
22296   total_len += obstack_object_size (&constant_pool);
22297
22298   gdb_assert (obstack_object_size (&contents) == size_of_contents);
22299
22300   write_obstack (out_file, &contents);
22301   write_obstack (out_file, &cu_list);
22302   write_obstack (out_file, &types_cu_list);
22303   write_obstack (out_file, &addr_obstack);
22304   write_obstack (out_file, &symtab_obstack);
22305   write_obstack (out_file, &constant_pool);
22306
22307   fclose (out_file);
22308
22309   /* We want to keep the file, so we set cleanup_filename to NULL
22310      here.  See unlink_if_set.  */
22311   cleanup_filename = NULL;
22312
22313   do_cleanups (cleanup);
22314 }
22315
22316 /* Implementation of the `save gdb-index' command.
22317    
22318    Note that the file format used by this command is documented in the
22319    GDB manual.  Any changes here must be documented there.  */
22320
22321 static void
22322 save_gdb_index_command (char *arg, int from_tty)
22323 {
22324   struct objfile *objfile;
22325
22326   if (!arg || !*arg)
22327     error (_("usage: save gdb-index DIRECTORY"));
22328
22329   ALL_OBJFILES (objfile)
22330   {
22331     struct stat st;
22332
22333     /* If the objfile does not correspond to an actual file, skip it.  */
22334     if (stat (objfile_name (objfile), &st) < 0)
22335       continue;
22336
22337     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
22338     if (dwarf2_per_objfile)
22339       {
22340         volatile struct gdb_exception except;
22341
22342         TRY_CATCH (except, RETURN_MASK_ERROR)
22343           {
22344             write_psymtabs_to_index (objfile, arg);
22345           }
22346         if (except.reason < 0)
22347           exception_fprintf (gdb_stderr, except,
22348                              _("Error while writing index for `%s': "),
22349                              objfile_name (objfile));
22350       }
22351   }
22352 }
22353
22354 \f
22355
22356 int dwarf2_always_disassemble;
22357
22358 static void
22359 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
22360                                 struct cmd_list_element *c, const char *value)
22361 {
22362   fprintf_filtered (file,
22363                     _("Whether to always disassemble "
22364                       "DWARF expressions is %s.\n"),
22365                     value);
22366 }
22367
22368 static void
22369 show_check_physname (struct ui_file *file, int from_tty,
22370                      struct cmd_list_element *c, const char *value)
22371 {
22372   fprintf_filtered (file,
22373                     _("Whether to check \"physname\" is %s.\n"),
22374                     value);
22375 }
22376
22377 void _initialize_dwarf2_read (void);
22378
22379 void
22380 _initialize_dwarf2_read (void)
22381 {
22382   struct cmd_list_element *c;
22383
22384   dwarf2_objfile_data_key
22385     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
22386
22387   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
22388 Set DWARF 2 specific variables.\n\
22389 Configure DWARF 2 variables such as the cache size"),
22390                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
22391                   0/*allow-unknown*/, &maintenance_set_cmdlist);
22392
22393   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
22394 Show DWARF 2 specific variables\n\
22395 Show DWARF 2 variables such as the cache size"),
22396                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
22397                   0/*allow-unknown*/, &maintenance_show_cmdlist);
22398
22399   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
22400                             &dwarf2_max_cache_age, _("\
22401 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
22402 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
22403 A higher limit means that cached compilation units will be stored\n\
22404 in memory longer, and more total memory will be used.  Zero disables\n\
22405 caching, which can slow down startup."),
22406                             NULL,
22407                             show_dwarf2_max_cache_age,
22408                             &set_dwarf2_cmdlist,
22409                             &show_dwarf2_cmdlist);
22410
22411   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
22412                            &dwarf2_always_disassemble, _("\
22413 Set whether `info address' always disassembles DWARF expressions."), _("\
22414 Show whether `info address' always disassembles DWARF expressions."), _("\
22415 When enabled, DWARF expressions are always printed in an assembly-like\n\
22416 syntax.  When disabled, expressions will be printed in a more\n\
22417 conversational style, when possible."),
22418                            NULL,
22419                            show_dwarf2_always_disassemble,
22420                            &set_dwarf2_cmdlist,
22421                            &show_dwarf2_cmdlist);
22422
22423   add_setshow_zuinteger_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
22424 Set debugging of the dwarf2 reader."), _("\
22425 Show debugging of the dwarf2 reader."), _("\
22426 When enabled (non-zero), debugging messages are printed during dwarf2\n\
22427 reading and symtab expansion.  A value of 1 (one) provides basic\n\
22428 information.  A value greater than 1 provides more verbose information."),
22429                             NULL,
22430                             NULL,
22431                             &setdebuglist, &showdebuglist);
22432
22433   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
22434 Set debugging of the dwarf2 DIE reader."), _("\
22435 Show debugging of the dwarf2 DIE reader."), _("\
22436 When enabled (non-zero), DIEs are dumped after they are read in.\n\
22437 The value is the maximum depth to print."),
22438                              NULL,
22439                              NULL,
22440                              &setdebuglist, &showdebuglist);
22441
22442   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
22443 Set cross-checking of \"physname\" code against demangler."), _("\
22444 Show cross-checking of \"physname\" code against demangler."), _("\
22445 When enabled, GDB's internal \"physname\" code is checked against\n\
22446 the demangler."),
22447                            NULL, show_check_physname,
22448                            &setdebuglist, &showdebuglist);
22449
22450   add_setshow_boolean_cmd ("use-deprecated-index-sections",
22451                            no_class, &use_deprecated_index_sections, _("\
22452 Set whether to use deprecated gdb_index sections."), _("\
22453 Show whether to use deprecated gdb_index sections."), _("\
22454 When enabled, deprecated .gdb_index sections are used anyway.\n\
22455 Normally they are ignored either because of a missing feature or\n\
22456 performance issue.\n\
22457 Warning: This option must be enabled before gdb reads the file."),
22458                            NULL,
22459                            NULL,
22460                            &setlist, &showlist);
22461
22462   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
22463                _("\
22464 Save a gdb-index file.\n\
22465 Usage: save gdb-index DIRECTORY"),
22466                &save_cmdlist);
22467   set_cmd_completer (c, filename_completer);
22468
22469   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
22470                                                         &dwarf2_locexpr_funcs);
22471   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
22472                                                         &dwarf2_loclist_funcs);
22473
22474   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
22475                                         &dwarf2_block_frame_base_locexpr_funcs);
22476   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
22477                                         &dwarf2_block_frame_base_loclist_funcs);
22478 }