Add NaCl (NativeClient) specific classes Target_mips_nacl and
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2014 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 <sys/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 <sys/types.h>
76
77 typedef struct symbol *symbolp;
78 DEF_VEC_P (symbolp);
79
80 /* When == 1, print basic high level tracing messages.
81    When > 1, be more verbose.
82    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
83 static unsigned int dwarf2_read_debug = 0;
84
85 /* When non-zero, dump DIEs after they are read in.  */
86 static unsigned int dwarf2_die_debug = 0;
87
88 /* When non-zero, cross-check physname against demangler.  */
89 static int check_physname = 0;
90
91 /* When non-zero, do not reject deprecated .gdb_index sections.  */
92 static int use_deprecated_index_sections = 0;
93
94 static const struct objfile_data *dwarf2_objfile_data_key;
95
96 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
97
98 static int dwarf2_locexpr_index;
99 static int dwarf2_loclist_index;
100 static int dwarf2_locexpr_block_index;
101 static int dwarf2_loclist_block_index;
102
103 /* A descriptor for dwarf sections.
104
105    S.ASECTION, SIZE are typically initialized when the objfile is first
106    scanned.  BUFFER, READIN are filled in later when the section is read.
107    If the section contained compressed data then SIZE is updated to record
108    the uncompressed size of the section.
109
110    DWP file format V2 introduces a wrinkle that is easiest to handle by
111    creating the concept of virtual sections contained within a real section.
112    In DWP V2 the sections of the input DWO files are concatenated together
113    into one section, but section offsets are kept relative to the original
114    input section.
115    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
116    the real section this "virtual" section is contained in, and BUFFER,SIZE
117    describe the virtual section.  */
118
119 struct dwarf2_section_info
120 {
121   union
122   {
123     /* If this is a real section, the bfd section.  */
124     asection *asection;
125     /* If this is a virtual section, pointer to the containing ("real")
126        section.  */
127     struct dwarf2_section_info *containing_section;
128   } s;
129   /* Pointer to section data, only valid if readin.  */
130   const gdb_byte *buffer;
131   /* The size of the section, real or virtual.  */
132   bfd_size_type size;
133   /* If this is a virtual section, the offset in the real section.
134      Only valid if is_virtual.  */
135   bfd_size_type virtual_offset;
136   /* True if we have tried to read this section.  */
137   char readin;
138   /* True if this is a virtual section, False otherwise.
139      This specifies which of s.asection and s.containing_section to use.  */
140   char is_virtual;
141 };
142
143 typedef struct dwarf2_section_info dwarf2_section_info_def;
144 DEF_VEC_O (dwarf2_section_info_def);
145
146 /* All offsets in the index are of this type.  It must be
147    architecture-independent.  */
148 typedef uint32_t offset_type;
149
150 DEF_VEC_I (offset_type);
151
152 /* Ensure only legit values are used.  */
153 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
154   do { \
155     gdb_assert ((unsigned int) (value) <= 1); \
156     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
157   } while (0)
158
159 /* Ensure only legit values are used.  */
160 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
161   do { \
162     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
163                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
164     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
165   } while (0)
166
167 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
168 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
169   do { \
170     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
171     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
172   } while (0)
173
174 /* A description of the mapped index.  The file format is described in
175    a comment by the code that writes the index.  */
176 struct mapped_index
177 {
178   /* Index data format version.  */
179   int version;
180
181   /* The total length of the buffer.  */
182   off_t total_size;
183
184   /* A pointer to the address table data.  */
185   const gdb_byte *address_table;
186
187   /* Size of the address table data in bytes.  */
188   offset_type address_table_size;
189
190   /* The symbol table, implemented as a hash table.  */
191   const offset_type *symbol_table;
192
193   /* Size in slots, each slot is 2 offset_types.  */
194   offset_type symbol_table_slots;
195
196   /* A pointer to the constant pool.  */
197   const char *constant_pool;
198 };
199
200 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
201 DEF_VEC_P (dwarf2_per_cu_ptr);
202
203 /* Collection of data recorded per objfile.
204    This hangs off of dwarf2_objfile_data_key.  */
205
206 struct dwarf2_per_objfile
207 {
208   struct dwarf2_section_info info;
209   struct dwarf2_section_info abbrev;
210   struct dwarf2_section_info line;
211   struct dwarf2_section_info loc;
212   struct dwarf2_section_info macinfo;
213   struct dwarf2_section_info macro;
214   struct dwarf2_section_info str;
215   struct dwarf2_section_info ranges;
216   struct dwarf2_section_info addr;
217   struct dwarf2_section_info frame;
218   struct dwarf2_section_info eh_frame;
219   struct dwarf2_section_info gdb_index;
220
221   VEC (dwarf2_section_info_def) *types;
222
223   /* Back link.  */
224   struct objfile *objfile;
225
226   /* Table of all the compilation units.  This is used to locate
227      the target compilation unit of a particular reference.  */
228   struct dwarf2_per_cu_data **all_comp_units;
229
230   /* The number of compilation units in ALL_COMP_UNITS.  */
231   int n_comp_units;
232
233   /* The number of .debug_types-related CUs.  */
234   int n_type_units;
235
236   /* The number of elements allocated in all_type_units.
237      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
238   int n_allocated_type_units;
239
240   /* The .debug_types-related CUs (TUs).
241      This is stored in malloc space because we may realloc it.  */
242   struct signatured_type **all_type_units;
243
244   /* Table of struct type_unit_group objects.
245      The hash key is the DW_AT_stmt_list value.  */
246   htab_t type_unit_groups;
247
248   /* A table mapping .debug_types signatures to its signatured_type entry.
249      This is NULL if the .debug_types section hasn't been read in yet.  */
250   htab_t signatured_types;
251
252   /* Type unit statistics, to see how well the scaling improvements
253      are doing.  */
254   struct tu_stats
255   {
256     int nr_uniq_abbrev_tables;
257     int nr_symtabs;
258     int nr_symtab_sharers;
259     int nr_stmt_less_type_units;
260     int nr_all_type_units_reallocs;
261   } tu_stats;
262
263   /* A chain of compilation units that are currently read in, so that
264      they can be freed later.  */
265   struct dwarf2_per_cu_data *read_in_chain;
266
267   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
268      This is NULL if the table hasn't been allocated yet.  */
269   htab_t dwo_files;
270
271   /* Non-zero if we've check for whether there is a DWP file.  */
272   int dwp_checked;
273
274   /* The DWP file if there is one, or NULL.  */
275   struct dwp_file *dwp_file;
276
277   /* The shared '.dwz' file, if one exists.  This is used when the
278      original data was compressed using 'dwz -m'.  */
279   struct dwz_file *dwz_file;
280
281   /* A flag indicating wether this objfile has a section loaded at a
282      VMA of 0.  */
283   int has_section_at_zero;
284
285   /* True if we are using the mapped index,
286      or we are faking it for OBJF_READNOW's sake.  */
287   unsigned char using_index;
288
289   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
290   struct mapped_index *index_table;
291
292   /* When using index_table, this keeps track of all quick_file_names entries.
293      TUs typically share line table entries with a CU, so we maintain a
294      separate table of all line table entries to support the sharing.
295      Note that while there can be way more TUs than CUs, we've already
296      sorted all the TUs into "type unit groups", grouped by their
297      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
298      CU and its associated TU group if there is one.  */
299   htab_t quick_file_names_table;
300
301   /* Set during partial symbol reading, to prevent queueing of full
302      symbols.  */
303   int reading_partial_symbols;
304
305   /* Table mapping type DIEs to their struct type *.
306      This is NULL if not allocated yet.
307      The mapping is done via (CU/TU + DIE offset) -> type.  */
308   htab_t die_type_hash;
309
310   /* The CUs we recently read.  */
311   VEC (dwarf2_per_cu_ptr) *just_read_cus;
312 };
313
314 static struct dwarf2_per_objfile *dwarf2_per_objfile;
315
316 /* Default names of the debugging sections.  */
317
318 /* Note that if the debugging section has been compressed, it might
319    have a name like .zdebug_info.  */
320
321 static const struct dwarf2_debug_sections dwarf2_elf_names =
322 {
323   { ".debug_info", ".zdebug_info" },
324   { ".debug_abbrev", ".zdebug_abbrev" },
325   { ".debug_line", ".zdebug_line" },
326   { ".debug_loc", ".zdebug_loc" },
327   { ".debug_macinfo", ".zdebug_macinfo" },
328   { ".debug_macro", ".zdebug_macro" },
329   { ".debug_str", ".zdebug_str" },
330   { ".debug_ranges", ".zdebug_ranges" },
331   { ".debug_types", ".zdebug_types" },
332   { ".debug_addr", ".zdebug_addr" },
333   { ".debug_frame", ".zdebug_frame" },
334   { ".eh_frame", NULL },
335   { ".gdb_index", ".zgdb_index" },
336   23
337 };
338
339 /* List of DWO/DWP sections.  */
340
341 static const struct dwop_section_names
342 {
343   struct dwarf2_section_names abbrev_dwo;
344   struct dwarf2_section_names info_dwo;
345   struct dwarf2_section_names line_dwo;
346   struct dwarf2_section_names loc_dwo;
347   struct dwarf2_section_names macinfo_dwo;
348   struct dwarf2_section_names macro_dwo;
349   struct dwarf2_section_names str_dwo;
350   struct dwarf2_section_names str_offsets_dwo;
351   struct dwarf2_section_names types_dwo;
352   struct dwarf2_section_names cu_index;
353   struct dwarf2_section_names tu_index;
354 }
355 dwop_section_names =
356 {
357   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
358   { ".debug_info.dwo", ".zdebug_info.dwo" },
359   { ".debug_line.dwo", ".zdebug_line.dwo" },
360   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
361   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
362   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
363   { ".debug_str.dwo", ".zdebug_str.dwo" },
364   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
365   { ".debug_types.dwo", ".zdebug_types.dwo" },
366   { ".debug_cu_index", ".zdebug_cu_index" },
367   { ".debug_tu_index", ".zdebug_tu_index" },
368 };
369
370 /* local data types */
371
372 /* The data in a compilation unit header, after target2host
373    translation, looks like this.  */
374 struct comp_unit_head
375 {
376   unsigned int length;
377   short version;
378   unsigned char addr_size;
379   unsigned char signed_addr_p;
380   sect_offset abbrev_offset;
381
382   /* Size of file offsets; either 4 or 8.  */
383   unsigned int offset_size;
384
385   /* Size of the length field; either 4 or 12.  */
386   unsigned int initial_length_size;
387
388   /* Offset to the first byte of this compilation unit header in the
389      .debug_info section, for resolving relative reference dies.  */
390   sect_offset offset;
391
392   /* Offset to first die in this cu from the start of the cu.
393      This will be the first byte following the compilation unit header.  */
394   cu_offset first_die_offset;
395 };
396
397 /* Type used for delaying computation of method physnames.
398    See comments for compute_delayed_physnames.  */
399 struct delayed_method_info
400 {
401   /* The type to which the method is attached, i.e., its parent class.  */
402   struct type *type;
403
404   /* The index of the method in the type's function fieldlists.  */
405   int fnfield_index;
406
407   /* The index of the method in the fieldlist.  */
408   int index;
409
410   /* The name of the DIE.  */
411   const char *name;
412
413   /*  The DIE associated with this method.  */
414   struct die_info *die;
415 };
416
417 typedef struct delayed_method_info delayed_method_info;
418 DEF_VEC_O (delayed_method_info);
419
420 /* Internal state when decoding a particular compilation unit.  */
421 struct dwarf2_cu
422 {
423   /* The objfile containing this compilation unit.  */
424   struct objfile *objfile;
425
426   /* The header of the compilation unit.  */
427   struct comp_unit_head header;
428
429   /* Base address of this compilation unit.  */
430   CORE_ADDR base_address;
431
432   /* Non-zero if base_address has been set.  */
433   int base_known;
434
435   /* The language we are debugging.  */
436   enum language language;
437   const struct language_defn *language_defn;
438
439   const char *producer;
440
441   /* The generic symbol table building routines have separate lists for
442      file scope symbols and all all other scopes (local scopes).  So
443      we need to select the right one to pass to add_symbol_to_list().
444      We do it by keeping a pointer to the correct list in list_in_scope.
445
446      FIXME: The original dwarf code just treated the file scope as the
447      first local scope, and all other local scopes as nested local
448      scopes, and worked fine.  Check to see if we really need to
449      distinguish these in buildsym.c.  */
450   struct pending **list_in_scope;
451
452   /* The abbrev table for this CU.
453      Normally this points to the abbrev table in the objfile.
454      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
455   struct abbrev_table *abbrev_table;
456
457   /* Hash table holding all the loaded partial DIEs
458      with partial_die->offset.SECT_OFF as hash.  */
459   htab_t partial_dies;
460
461   /* Storage for things with the same lifetime as this read-in compilation
462      unit, including partial DIEs.  */
463   struct obstack comp_unit_obstack;
464
465   /* When multiple dwarf2_cu structures are living in memory, this field
466      chains them all together, so that they can be released efficiently.
467      We will probably also want a generation counter so that most-recently-used
468      compilation units are cached...  */
469   struct dwarf2_per_cu_data *read_in_chain;
470
471   /* Backlink to our per_cu entry.  */
472   struct dwarf2_per_cu_data *per_cu;
473
474   /* How many compilation units ago was this CU last referenced?  */
475   int last_used;
476
477   /* A hash table of DIE cu_offset for following references with
478      die_info->offset.sect_off as hash.  */
479   htab_t die_hash;
480
481   /* Full DIEs if read in.  */
482   struct die_info *dies;
483
484   /* A set of pointers to dwarf2_per_cu_data objects for compilation
485      units referenced by this one.  Only set during full symbol processing;
486      partial symbol tables do not have dependencies.  */
487   htab_t dependencies;
488
489   /* Header data from the line table, during full symbol processing.  */
490   struct line_header *line_header;
491
492   /* A list of methods which need to have physnames computed
493      after all type information has been read.  */
494   VEC (delayed_method_info) *method_list;
495
496   /* To be copied to symtab->call_site_htab.  */
497   htab_t call_site_htab;
498
499   /* Non-NULL if this CU came from a DWO file.
500      There is an invariant here that is important to remember:
501      Except for attributes copied from the top level DIE in the "main"
502      (or "stub") file in preparation for reading the DWO file
503      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
504      Either there isn't a DWO file (in which case this is NULL and the point
505      is moot), or there is and either we're not going to read it (in which
506      case this is NULL) or there is and we are reading it (in which case this
507      is non-NULL).  */
508   struct dwo_unit *dwo_unit;
509
510   /* The DW_AT_addr_base attribute if present, zero otherwise
511      (zero is a valid value though).
512      Note this value comes from the Fission stub CU/TU's DIE.  */
513   ULONGEST addr_base;
514
515   /* The DW_AT_ranges_base attribute if present, zero otherwise
516      (zero is a valid value though).
517      Note this value comes from the Fission stub CU/TU's DIE.
518      Also note that the value is zero in the non-DWO case so this value can
519      be used without needing to know whether DWO files are in use or not.
520      N.B. This does not apply to DW_AT_ranges appearing in
521      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
522      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
523      DW_AT_ranges_base *would* have to be applied, and we'd have to care
524      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
525   ULONGEST ranges_base;
526
527   /* Mark used when releasing cached dies.  */
528   unsigned int mark : 1;
529
530   /* This CU references .debug_loc.  See the symtab->locations_valid field.
531      This test is imperfect as there may exist optimized debug code not using
532      any location list and still facing inlining issues if handled as
533      unoptimized code.  For a future better test see GCC PR other/32998.  */
534   unsigned int has_loclist : 1;
535
536   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
537      if all the producer_is_* fields are valid.  This information is cached
538      because profiling CU expansion showed excessive time spent in
539      producer_is_gxx_lt_4_6.  */
540   unsigned int checked_producer : 1;
541   unsigned int producer_is_gxx_lt_4_6 : 1;
542   unsigned int producer_is_gcc_lt_4_3 : 1;
543   unsigned int producer_is_icc : 1;
544
545   /* When set, the file that we're processing is known to have
546      debugging info for C++ namespaces.  GCC 3.3.x did not produce
547      this information, but later versions do.  */
548
549   unsigned int processing_has_namespace_info : 1;
550 };
551
552 /* Persistent data held for a compilation unit, even when not
553    processing it.  We put a pointer to this structure in the
554    read_symtab_private field of the psymtab.  */
555
556 struct dwarf2_per_cu_data
557 {
558   /* The start offset and length of this compilation unit.
559      NOTE: Unlike comp_unit_head.length, this length includes
560      initial_length_size.
561      If the DIE refers to a DWO file, this is always of the original die,
562      not the DWO file.  */
563   sect_offset offset;
564   unsigned int length;
565
566   /* Flag indicating this compilation unit will be read in before
567      any of the current compilation units are processed.  */
568   unsigned int queued : 1;
569
570   /* This flag will be set when reading partial DIEs if we need to load
571      absolutely all DIEs for this compilation unit, instead of just the ones
572      we think are interesting.  It gets set if we look for a DIE in the
573      hash table and don't find it.  */
574   unsigned int load_all_dies : 1;
575
576   /* Non-zero if this CU is from .debug_types.
577      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
578      this is non-zero.  */
579   unsigned int is_debug_types : 1;
580
581   /* Non-zero if this CU is from the .dwz file.  */
582   unsigned int is_dwz : 1;
583
584   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
585      This flag is only valid if is_debug_types is true.
586      We can't read a CU directly from a DWO file: There are required
587      attributes in the stub.  */
588   unsigned int reading_dwo_directly : 1;
589
590   /* Non-zero if the TU has been read.
591      This is used to assist the "Stay in DWO Optimization" for Fission:
592      When reading a DWO, it's faster to read TUs from the DWO instead of
593      fetching them from random other DWOs (due to comdat folding).
594      If the TU has already been read, the optimization is unnecessary
595      (and unwise - we don't want to change where gdb thinks the TU lives
596      "midflight").
597      This flag is only valid if is_debug_types is true.  */
598   unsigned int tu_read : 1;
599
600   /* The section this CU/TU lives in.
601      If the DIE refers to a DWO file, this is always the original die,
602      not the DWO file.  */
603   struct dwarf2_section_info *section;
604
605   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
606      of the CU cache it gets reset to NULL again.  */
607   struct dwarf2_cu *cu;
608
609   /* The corresponding objfile.
610      Normally we can get the objfile from dwarf2_per_objfile.
611      However we can enter this file with just a "per_cu" handle.  */
612   struct objfile *objfile;
613
614   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
615      is active.  Otherwise, the 'psymtab' field is active.  */
616   union
617   {
618     /* The partial symbol table associated with this compilation unit,
619        or NULL for unread partial units.  */
620     struct partial_symtab *psymtab;
621
622     /* Data needed by the "quick" functions.  */
623     struct dwarf2_per_cu_quick_data *quick;
624   } v;
625
626   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
627      while reading psymtabs, used to compute the psymtab dependencies,
628      and then cleared.  Then it is filled in again while reading full
629      symbols, and only deleted when the objfile is destroyed.
630
631      This is also used to work around a difference between the way gold
632      generates .gdb_index version <=7 and the way gdb does.  Arguably this
633      is a gold bug.  For symbols coming from TUs, gold records in the index
634      the CU that includes the TU instead of the TU itself.  This breaks
635      dw2_lookup_symbol: It assumes that if the index says symbol X lives
636      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
637      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
638      we need to look in TU Z to find X.  Fortunately, this is akin to
639      DW_TAG_imported_unit, so we just use the same mechanism: For
640      .gdb_index version <=7 this also records the TUs that the CU referred
641      to.  Concurrently with this change gdb was modified to emit version 8
642      indices so we only pay a price for gold generated indices.
643      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
644   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
645 };
646
647 /* Entry in the signatured_types hash table.  */
648
649 struct signatured_type
650 {
651   /* The "per_cu" object of this type.
652      This struct is used iff per_cu.is_debug_types.
653      N.B.: This is the first member so that it's easy to convert pointers
654      between them.  */
655   struct dwarf2_per_cu_data per_cu;
656
657   /* The type's signature.  */
658   ULONGEST signature;
659
660   /* Offset in the TU of the type's DIE, as read from the TU header.
661      If this TU is a DWO stub and the definition lives in a DWO file
662      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
663   cu_offset type_offset_in_tu;
664
665   /* Offset in the section of the type's DIE.
666      If the definition lives in a DWO file, this is the offset in the
667      .debug_types.dwo section.
668      The value is zero until the actual value is known.
669      Zero is otherwise not a valid section offset.  */
670   sect_offset type_offset_in_section;
671
672   /* Type units are grouped by their DW_AT_stmt_list entry so that they
673      can share them.  This points to the containing symtab.  */
674   struct type_unit_group *type_unit_group;
675
676   /* The type.
677      The first time we encounter this type we fully read it in and install it
678      in the symbol tables.  Subsequent times we only need the type.  */
679   struct type *type;
680
681   /* Containing DWO unit.
682      This field is valid iff per_cu.reading_dwo_directly.  */
683   struct dwo_unit *dwo_unit;
684 };
685
686 typedef struct signatured_type *sig_type_ptr;
687 DEF_VEC_P (sig_type_ptr);
688
689 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
690    This includes type_unit_group and quick_file_names.  */
691
692 struct stmt_list_hash
693 {
694   /* The DWO unit this table is from or NULL if there is none.  */
695   struct dwo_unit *dwo_unit;
696
697   /* Offset in .debug_line or .debug_line.dwo.  */
698   sect_offset line_offset;
699 };
700
701 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
702    an object of this type.  */
703
704 struct type_unit_group
705 {
706   /* dwarf2read.c's main "handle" on a TU symtab.
707      To simplify things we create an artificial CU that "includes" all the
708      type units using this stmt_list so that the rest of the code still has
709      a "per_cu" handle on the symtab.
710      This PER_CU is recognized by having no section.  */
711 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
712   struct dwarf2_per_cu_data per_cu;
713
714   /* The TUs that share this DW_AT_stmt_list entry.
715      This is added to while parsing type units to build partial symtabs,
716      and is deleted afterwards and not used again.  */
717   VEC (sig_type_ptr) *tus;
718
719   /* The primary symtab.
720      Type units in a group needn't all be defined in the same source file,
721      so we create an essentially anonymous symtab as the primary symtab.  */
722   struct symtab *primary_symtab;
723
724   /* The data used to construct the hash key.  */
725   struct stmt_list_hash hash;
726
727   /* The number of symtabs from the line header.
728      The value here must match line_header.num_file_names.  */
729   unsigned int num_symtabs;
730
731   /* The symbol tables for this TU (obtained from the files listed in
732      DW_AT_stmt_list).
733      WARNING: The order of entries here must match the order of entries
734      in the line header.  After the first TU using this type_unit_group, the
735      line header for the subsequent TUs is recreated from this.  This is done
736      because we need to use the same symtabs for each TU using the same
737      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
738      there's no guarantee the line header doesn't have duplicate entries.  */
739   struct symtab **symtabs;
740 };
741
742 /* These sections are what may appear in a (real or virtual) DWO file.  */
743
744 struct dwo_sections
745 {
746   struct dwarf2_section_info abbrev;
747   struct dwarf2_section_info line;
748   struct dwarf2_section_info loc;
749   struct dwarf2_section_info macinfo;
750   struct dwarf2_section_info macro;
751   struct dwarf2_section_info str;
752   struct dwarf2_section_info str_offsets;
753   /* In the case of a virtual DWO file, these two are unused.  */
754   struct dwarf2_section_info info;
755   VEC (dwarf2_section_info_def) *types;
756 };
757
758 /* CUs/TUs in DWP/DWO files.  */
759
760 struct dwo_unit
761 {
762   /* Backlink to the containing struct dwo_file.  */
763   struct dwo_file *dwo_file;
764
765   /* The "id" that distinguishes this CU/TU.
766      .debug_info calls this "dwo_id", .debug_types calls this "signature".
767      Since signatures came first, we stick with it for consistency.  */
768   ULONGEST signature;
769
770   /* The section this CU/TU lives in, in the DWO file.  */
771   struct dwarf2_section_info *section;
772
773   /* Same as dwarf2_per_cu_data:{offset,length} but in the DWO section.  */
774   sect_offset offset;
775   unsigned int length;
776
777   /* For types, offset in the type's DIE of the type defined by this TU.  */
778   cu_offset type_offset_in_tu;
779 };
780
781 /* include/dwarf2.h defines the DWP section codes.
782    It defines a max value but it doesn't define a min value, which we
783    use for error checking, so provide one.  */
784
785 enum dwp_v2_section_ids
786 {
787   DW_SECT_MIN = 1
788 };
789
790 /* Data for one DWO file.
791
792    This includes virtual DWO files (a virtual DWO file is a DWO file as it
793    appears in a DWP file).  DWP files don't really have DWO files per se -
794    comdat folding of types "loses" the DWO file they came from, and from
795    a high level view DWP files appear to contain a mass of random types.
796    However, to maintain consistency with the non-DWP case we pretend DWP
797    files contain virtual DWO files, and we assign each TU with one virtual
798    DWO file (generally based on the line and abbrev section offsets -
799    a heuristic that seems to work in practice).  */
800
801 struct dwo_file
802 {
803   /* The DW_AT_GNU_dwo_name attribute.
804      For virtual DWO files the name is constructed from the section offsets
805      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
806      from related CU+TUs.  */
807   const char *dwo_name;
808
809   /* The DW_AT_comp_dir attribute.  */
810   const char *comp_dir;
811
812   /* The bfd, when the file is open.  Otherwise this is NULL.
813      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
814   bfd *dbfd;
815
816   /* The sections that make up this DWO file.
817      Remember that for virtual DWO files in DWP V2, these are virtual
818      sections (for lack of a better name).  */
819   struct dwo_sections sections;
820
821   /* The CU in the file.
822      We only support one because having more than one requires hacking the
823      dwo_name of each to match, which is highly unlikely to happen.
824      Doing this means all TUs can share comp_dir: We also assume that
825      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
826   struct dwo_unit *cu;
827
828   /* Table of TUs in the file.
829      Each element is a struct dwo_unit.  */
830   htab_t tus;
831 };
832
833 /* These sections are what may appear in a DWP file.  */
834
835 struct dwp_sections
836 {
837   /* These are used by both DWP version 1 and 2.  */
838   struct dwarf2_section_info str;
839   struct dwarf2_section_info cu_index;
840   struct dwarf2_section_info tu_index;
841
842   /* These are only used by DWP version 2 files.
843      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
844      sections are referenced by section number, and are not recorded here.
845      In DWP version 2 there is at most one copy of all these sections, each
846      section being (effectively) comprised of the concatenation of all of the
847      individual sections that exist in the version 1 format.
848      To keep the code simple we treat each of these concatenated pieces as a
849      section itself (a virtual section?).  */
850   struct dwarf2_section_info abbrev;
851   struct dwarf2_section_info info;
852   struct dwarf2_section_info line;
853   struct dwarf2_section_info loc;
854   struct dwarf2_section_info macinfo;
855   struct dwarf2_section_info macro;
856   struct dwarf2_section_info str_offsets;
857   struct dwarf2_section_info types;
858 };
859
860 /* These sections are what may appear in a virtual DWO file in DWP version 1.
861    A virtual DWO file is a DWO file as it appears in a DWP file.  */
862
863 struct virtual_v1_dwo_sections
864 {
865   struct dwarf2_section_info abbrev;
866   struct dwarf2_section_info line;
867   struct dwarf2_section_info loc;
868   struct dwarf2_section_info macinfo;
869   struct dwarf2_section_info macro;
870   struct dwarf2_section_info str_offsets;
871   /* Each DWP hash table entry records one CU or one TU.
872      That is recorded here, and copied to dwo_unit.section.  */
873   struct dwarf2_section_info info_or_types;
874 };
875
876 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
877    In version 2, the sections of the DWO files are concatenated together
878    and stored in one section of that name.  Thus each ELF section contains
879    several "virtual" sections.  */
880
881 struct virtual_v2_dwo_sections
882 {
883   bfd_size_type abbrev_offset;
884   bfd_size_type abbrev_size;
885
886   bfd_size_type line_offset;
887   bfd_size_type line_size;
888
889   bfd_size_type loc_offset;
890   bfd_size_type loc_size;
891
892   bfd_size_type macinfo_offset;
893   bfd_size_type macinfo_size;
894
895   bfd_size_type macro_offset;
896   bfd_size_type macro_size;
897
898   bfd_size_type str_offsets_offset;
899   bfd_size_type str_offsets_size;
900
901   /* Each DWP hash table entry records one CU or one TU.
902      That is recorded here, and copied to dwo_unit.section.  */
903   bfd_size_type info_or_types_offset;
904   bfd_size_type info_or_types_size;
905 };
906
907 /* Contents of DWP hash tables.  */
908
909 struct dwp_hash_table
910 {
911   uint32_t version, nr_columns;
912   uint32_t nr_units, nr_slots;
913   const gdb_byte *hash_table, *unit_table;
914   union
915   {
916     struct
917     {
918       const gdb_byte *indices;
919     } v1;
920     struct
921     {
922       /* This is indexed by column number and gives the id of the section
923          in that column.  */
924 #define MAX_NR_V2_DWO_SECTIONS \
925   (1 /* .debug_info or .debug_types */ \
926    + 1 /* .debug_abbrev */ \
927    + 1 /* .debug_line */ \
928    + 1 /* .debug_loc */ \
929    + 1 /* .debug_str_offsets */ \
930    + 1 /* .debug_macro or .debug_macinfo */)
931       int section_ids[MAX_NR_V2_DWO_SECTIONS];
932       const gdb_byte *offsets;
933       const gdb_byte *sizes;
934     } v2;
935   } section_pool;
936 };
937
938 /* Data for one DWP file.  */
939
940 struct dwp_file
941 {
942   /* Name of the file.  */
943   const char *name;
944
945   /* File format version.  */
946   int version;
947
948   /* The bfd.  */
949   bfd *dbfd;
950
951   /* Section info for this file.  */
952   struct dwp_sections sections;
953
954   /* Table of CUs in the file.  */
955   const struct dwp_hash_table *cus;
956
957   /* Table of TUs in the file.  */
958   const struct dwp_hash_table *tus;
959
960   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
961   htab_t loaded_cus;
962   htab_t loaded_tus;
963
964   /* Table to map ELF section numbers to their sections.
965      This is only needed for the DWP V1 file format.  */
966   unsigned int num_sections;
967   asection **elf_sections;
968 };
969
970 /* This represents a '.dwz' file.  */
971
972 struct dwz_file
973 {
974   /* A dwz file can only contain a few sections.  */
975   struct dwarf2_section_info abbrev;
976   struct dwarf2_section_info info;
977   struct dwarf2_section_info str;
978   struct dwarf2_section_info line;
979   struct dwarf2_section_info macro;
980   struct dwarf2_section_info gdb_index;
981
982   /* The dwz's BFD.  */
983   bfd *dwz_bfd;
984 };
985
986 /* Struct used to pass misc. parameters to read_die_and_children, et
987    al.  which are used for both .debug_info and .debug_types dies.
988    All parameters here are unchanging for the life of the call.  This
989    struct exists to abstract away the constant parameters of die reading.  */
990
991 struct die_reader_specs
992 {
993   /* The bfd of die_section.  */
994   bfd* abfd;
995
996   /* The CU of the DIE we are parsing.  */
997   struct dwarf2_cu *cu;
998
999   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1000   struct dwo_file *dwo_file;
1001
1002   /* The section the die comes from.
1003      This is either .debug_info or .debug_types, or the .dwo variants.  */
1004   struct dwarf2_section_info *die_section;
1005
1006   /* die_section->buffer.  */
1007   const gdb_byte *buffer;
1008
1009   /* The end of the buffer.  */
1010   const gdb_byte *buffer_end;
1011
1012   /* The value of the DW_AT_comp_dir attribute.  */
1013   const char *comp_dir;
1014 };
1015
1016 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1017 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1018                                       const gdb_byte *info_ptr,
1019                                       struct die_info *comp_unit_die,
1020                                       int has_children,
1021                                       void *data);
1022
1023 /* The line number information for a compilation unit (found in the
1024    .debug_line section) begins with a "statement program header",
1025    which contains the following information.  */
1026 struct line_header
1027 {
1028   unsigned int total_length;
1029   unsigned short version;
1030   unsigned int header_length;
1031   unsigned char minimum_instruction_length;
1032   unsigned char maximum_ops_per_instruction;
1033   unsigned char default_is_stmt;
1034   int line_base;
1035   unsigned char line_range;
1036   unsigned char opcode_base;
1037
1038   /* standard_opcode_lengths[i] is the number of operands for the
1039      standard opcode whose value is i.  This means that
1040      standard_opcode_lengths[0] is unused, and the last meaningful
1041      element is standard_opcode_lengths[opcode_base - 1].  */
1042   unsigned char *standard_opcode_lengths;
1043
1044   /* The include_directories table.  NOTE!  These strings are not
1045      allocated with xmalloc; instead, they are pointers into
1046      debug_line_buffer.  If you try to free them, `free' will get
1047      indigestion.  */
1048   unsigned int num_include_dirs, include_dirs_size;
1049   const char **include_dirs;
1050
1051   /* The file_names table.  NOTE!  These strings are not allocated
1052      with xmalloc; instead, they are pointers into debug_line_buffer.
1053      Don't try to free them directly.  */
1054   unsigned int num_file_names, file_names_size;
1055   struct file_entry
1056   {
1057     const char *name;
1058     unsigned int dir_index;
1059     unsigned int mod_time;
1060     unsigned int length;
1061     int included_p; /* Non-zero if referenced by the Line Number Program.  */
1062     struct symtab *symtab; /* The associated symbol table, if any.  */
1063   } *file_names;
1064
1065   /* The start and end of the statement program following this
1066      header.  These point into dwarf2_per_objfile->line_buffer.  */
1067   const gdb_byte *statement_program_start, *statement_program_end;
1068 };
1069
1070 /* When we construct a partial symbol table entry we only
1071    need this much information.  */
1072 struct partial_die_info
1073   {
1074     /* Offset of this DIE.  */
1075     sect_offset offset;
1076
1077     /* DWARF-2 tag for this DIE.  */
1078     ENUM_BITFIELD(dwarf_tag) tag : 16;
1079
1080     /* Assorted flags describing the data found in this DIE.  */
1081     unsigned int has_children : 1;
1082     unsigned int is_external : 1;
1083     unsigned int is_declaration : 1;
1084     unsigned int has_type : 1;
1085     unsigned int has_specification : 1;
1086     unsigned int has_pc_info : 1;
1087     unsigned int may_be_inlined : 1;
1088
1089     /* Flag set if the SCOPE field of this structure has been
1090        computed.  */
1091     unsigned int scope_set : 1;
1092
1093     /* Flag set if the DIE has a byte_size attribute.  */
1094     unsigned int has_byte_size : 1;
1095
1096     /* Flag set if any of the DIE's children are template arguments.  */
1097     unsigned int has_template_arguments : 1;
1098
1099     /* Flag set if fixup_partial_die has been called on this die.  */
1100     unsigned int fixup_called : 1;
1101
1102     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1103     unsigned int is_dwz : 1;
1104
1105     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1106     unsigned int spec_is_dwz : 1;
1107
1108     /* The name of this DIE.  Normally the value of DW_AT_name, but
1109        sometimes a default name for unnamed DIEs.  */
1110     const char *name;
1111
1112     /* The linkage name, if present.  */
1113     const char *linkage_name;
1114
1115     /* The scope to prepend to our children.  This is generally
1116        allocated on the comp_unit_obstack, so will disappear
1117        when this compilation unit leaves the cache.  */
1118     const char *scope;
1119
1120     /* Some data associated with the partial DIE.  The tag determines
1121        which field is live.  */
1122     union
1123     {
1124       /* The location description associated with this DIE, if any.  */
1125       struct dwarf_block *locdesc;
1126       /* The offset of an import, for DW_TAG_imported_unit.  */
1127       sect_offset offset;
1128     } d;
1129
1130     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1131     CORE_ADDR lowpc;
1132     CORE_ADDR highpc;
1133
1134     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1135        DW_AT_sibling, if any.  */
1136     /* NOTE: This member isn't strictly necessary, read_partial_die could
1137        return DW_AT_sibling values to its caller load_partial_dies.  */
1138     const gdb_byte *sibling;
1139
1140     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1141        DW_AT_specification (or DW_AT_abstract_origin or
1142        DW_AT_extension).  */
1143     sect_offset spec_offset;
1144
1145     /* Pointers to this DIE's parent, first child, and next sibling,
1146        if any.  */
1147     struct partial_die_info *die_parent, *die_child, *die_sibling;
1148   };
1149
1150 /* This data structure holds the information of an abbrev.  */
1151 struct abbrev_info
1152   {
1153     unsigned int number;        /* number identifying abbrev */
1154     enum dwarf_tag tag;         /* dwarf tag */
1155     unsigned short has_children;                /* boolean */
1156     unsigned short num_attrs;   /* number of attributes */
1157     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1158     struct abbrev_info *next;   /* next in chain */
1159   };
1160
1161 struct attr_abbrev
1162   {
1163     ENUM_BITFIELD(dwarf_attribute) name : 16;
1164     ENUM_BITFIELD(dwarf_form) form : 16;
1165   };
1166
1167 /* Size of abbrev_table.abbrev_hash_table.  */
1168 #define ABBREV_HASH_SIZE 121
1169
1170 /* Top level data structure to contain an abbreviation table.  */
1171
1172 struct abbrev_table
1173 {
1174   /* Where the abbrev table came from.
1175      This is used as a sanity check when the table is used.  */
1176   sect_offset offset;
1177
1178   /* Storage for the abbrev table.  */
1179   struct obstack abbrev_obstack;
1180
1181   /* Hash table of abbrevs.
1182      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1183      It could be statically allocated, but the previous code didn't so we
1184      don't either.  */
1185   struct abbrev_info **abbrevs;
1186 };
1187
1188 /* Attributes have a name and a value.  */
1189 struct attribute
1190   {
1191     ENUM_BITFIELD(dwarf_attribute) name : 16;
1192     ENUM_BITFIELD(dwarf_form) form : 15;
1193
1194     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1195        field should be in u.str (existing only for DW_STRING) but it is kept
1196        here for better struct attribute alignment.  */
1197     unsigned int string_is_canonical : 1;
1198
1199     union
1200       {
1201         const char *str;
1202         struct dwarf_block *blk;
1203         ULONGEST unsnd;
1204         LONGEST snd;
1205         CORE_ADDR addr;
1206         ULONGEST signature;
1207       }
1208     u;
1209   };
1210
1211 /* This data structure holds a complete die structure.  */
1212 struct die_info
1213   {
1214     /* DWARF-2 tag for this DIE.  */
1215     ENUM_BITFIELD(dwarf_tag) tag : 16;
1216
1217     /* Number of attributes */
1218     unsigned char num_attrs;
1219
1220     /* True if we're presently building the full type name for the
1221        type derived from this DIE.  */
1222     unsigned char building_fullname : 1;
1223
1224     /* True if this die is in process.  PR 16581.  */
1225     unsigned char in_process : 1;
1226
1227     /* Abbrev number */
1228     unsigned int abbrev;
1229
1230     /* Offset in .debug_info or .debug_types section.  */
1231     sect_offset offset;
1232
1233     /* The dies in a compilation unit form an n-ary tree.  PARENT
1234        points to this die's parent; CHILD points to the first child of
1235        this node; and all the children of a given node are chained
1236        together via their SIBLING fields.  */
1237     struct die_info *child;     /* Its first child, if any.  */
1238     struct die_info *sibling;   /* Its next sibling, if any.  */
1239     struct die_info *parent;    /* Its parent, if any.  */
1240
1241     /* An array of attributes, with NUM_ATTRS elements.  There may be
1242        zero, but it's not common and zero-sized arrays are not
1243        sufficiently portable C.  */
1244     struct attribute attrs[1];
1245   };
1246
1247 /* Get at parts of an attribute structure.  */
1248
1249 #define DW_STRING(attr)    ((attr)->u.str)
1250 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1251 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1252 #define DW_BLOCK(attr)     ((attr)->u.blk)
1253 #define DW_SND(attr)       ((attr)->u.snd)
1254 #define DW_ADDR(attr)      ((attr)->u.addr)
1255 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1256
1257 /* Blocks are a bunch of untyped bytes.  */
1258 struct dwarf_block
1259   {
1260     size_t size;
1261
1262     /* Valid only if SIZE is not zero.  */
1263     const gdb_byte *data;
1264   };
1265
1266 #ifndef ATTR_ALLOC_CHUNK
1267 #define ATTR_ALLOC_CHUNK 4
1268 #endif
1269
1270 /* Allocate fields for structs, unions and enums in this size.  */
1271 #ifndef DW_FIELD_ALLOC_CHUNK
1272 #define DW_FIELD_ALLOC_CHUNK 4
1273 #endif
1274
1275 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1276    but this would require a corresponding change in unpack_field_as_long
1277    and friends.  */
1278 static int bits_per_byte = 8;
1279
1280 /* The routines that read and process dies for a C struct or C++ class
1281    pass lists of data member fields and lists of member function fields
1282    in an instance of a field_info structure, as defined below.  */
1283 struct field_info
1284   {
1285     /* List of data member and baseclasses fields.  */
1286     struct nextfield
1287       {
1288         struct nextfield *next;
1289         int accessibility;
1290         int virtuality;
1291         struct field field;
1292       }
1293      *fields, *baseclasses;
1294
1295     /* Number of fields (including baseclasses).  */
1296     int nfields;
1297
1298     /* Number of baseclasses.  */
1299     int nbaseclasses;
1300
1301     /* Set if the accesibility of one of the fields is not public.  */
1302     int non_public_fields;
1303
1304     /* Member function fields array, entries are allocated in the order they
1305        are encountered in the object file.  */
1306     struct nextfnfield
1307       {
1308         struct nextfnfield *next;
1309         struct fn_field fnfield;
1310       }
1311      *fnfields;
1312
1313     /* Member function fieldlist array, contains name of possibly overloaded
1314        member function, number of overloaded member functions and a pointer
1315        to the head of the member function field chain.  */
1316     struct fnfieldlist
1317       {
1318         const char *name;
1319         int length;
1320         struct nextfnfield *head;
1321       }
1322      *fnfieldlists;
1323
1324     /* Number of entries in the fnfieldlists array.  */
1325     int nfnfields;
1326
1327     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1328        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1329     struct typedef_field_list
1330       {
1331         struct typedef_field field;
1332         struct typedef_field_list *next;
1333       }
1334     *typedef_field_list;
1335     unsigned typedef_field_list_count;
1336   };
1337
1338 /* One item on the queue of compilation units to read in full symbols
1339    for.  */
1340 struct dwarf2_queue_item
1341 {
1342   struct dwarf2_per_cu_data *per_cu;
1343   enum language pretend_language;
1344   struct dwarf2_queue_item *next;
1345 };
1346
1347 /* The current queue.  */
1348 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1349
1350 /* Loaded secondary compilation units are kept in memory until they
1351    have not been referenced for the processing of this many
1352    compilation units.  Set this to zero to disable caching.  Cache
1353    sizes of up to at least twenty will improve startup time for
1354    typical inter-CU-reference binaries, at an obvious memory cost.  */
1355 static int dwarf2_max_cache_age = 5;
1356 static void
1357 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1358                            struct cmd_list_element *c, const char *value)
1359 {
1360   fprintf_filtered (file, _("The upper bound on the age of cached "
1361                             "dwarf2 compilation units is %s.\n"),
1362                     value);
1363 }
1364 \f
1365 /* local function prototypes */
1366
1367 static const char *get_section_name (const struct dwarf2_section_info *);
1368
1369 static const char *get_section_file_name (const struct dwarf2_section_info *);
1370
1371 static void dwarf2_locate_sections (bfd *, asection *, void *);
1372
1373 static void dwarf2_find_base_address (struct die_info *die,
1374                                       struct dwarf2_cu *cu);
1375
1376 static struct partial_symtab *create_partial_symtab
1377   (struct dwarf2_per_cu_data *per_cu, const char *name);
1378
1379 static void dwarf2_build_psymtabs_hard (struct objfile *);
1380
1381 static void scan_partial_symbols (struct partial_die_info *,
1382                                   CORE_ADDR *, CORE_ADDR *,
1383                                   int, struct dwarf2_cu *);
1384
1385 static void add_partial_symbol (struct partial_die_info *,
1386                                 struct dwarf2_cu *);
1387
1388 static void add_partial_namespace (struct partial_die_info *pdi,
1389                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1390                                    int set_addrmap, struct dwarf2_cu *cu);
1391
1392 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1393                                 CORE_ADDR *highpc, int set_addrmap,
1394                                 struct dwarf2_cu *cu);
1395
1396 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1397                                      struct dwarf2_cu *cu);
1398
1399 static void add_partial_subprogram (struct partial_die_info *pdi,
1400                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1401                                     int need_pc, struct dwarf2_cu *cu);
1402
1403 static void dwarf2_read_symtab (struct partial_symtab *,
1404                                 struct objfile *);
1405
1406 static void psymtab_to_symtab_1 (struct partial_symtab *);
1407
1408 static struct abbrev_info *abbrev_table_lookup_abbrev
1409   (const struct abbrev_table *, unsigned int);
1410
1411 static struct abbrev_table *abbrev_table_read_table
1412   (struct dwarf2_section_info *, sect_offset);
1413
1414 static void abbrev_table_free (struct abbrev_table *);
1415
1416 static void abbrev_table_free_cleanup (void *);
1417
1418 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1419                                  struct dwarf2_section_info *);
1420
1421 static void dwarf2_free_abbrev_table (void *);
1422
1423 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1424
1425 static struct partial_die_info *load_partial_dies
1426   (const struct die_reader_specs *, const gdb_byte *, int);
1427
1428 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1429                                          struct partial_die_info *,
1430                                          struct abbrev_info *,
1431                                          unsigned int,
1432                                          const gdb_byte *);
1433
1434 static struct partial_die_info *find_partial_die (sect_offset, int,
1435                                                   struct dwarf2_cu *);
1436
1437 static void fixup_partial_die (struct partial_die_info *,
1438                                struct dwarf2_cu *);
1439
1440 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1441                                        struct attribute *, struct attr_abbrev *,
1442                                        const gdb_byte *);
1443
1444 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1445
1446 static int read_1_signed_byte (bfd *, const gdb_byte *);
1447
1448 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1449
1450 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1451
1452 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1453
1454 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1455                                unsigned int *);
1456
1457 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1458
1459 static LONGEST read_checked_initial_length_and_offset
1460   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1461    unsigned int *, unsigned int *);
1462
1463 static LONGEST read_offset (bfd *, const gdb_byte *,
1464                             const struct comp_unit_head *,
1465                             unsigned int *);
1466
1467 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1468
1469 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1470                                        sect_offset);
1471
1472 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1473
1474 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1475
1476 static const char *read_indirect_string (bfd *, const gdb_byte *,
1477                                          const struct comp_unit_head *,
1478                                          unsigned int *);
1479
1480 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1481
1482 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1483
1484 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1485
1486 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1487                                               const gdb_byte *,
1488                                               unsigned int *);
1489
1490 static const char *read_str_index (const struct die_reader_specs *reader,
1491                                    ULONGEST str_index);
1492
1493 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1494
1495 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1496                                       struct dwarf2_cu *);
1497
1498 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1499                                                 unsigned int);
1500
1501 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1502                                struct dwarf2_cu *cu);
1503
1504 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1505
1506 static struct die_info *die_specification (struct die_info *die,
1507                                            struct dwarf2_cu **);
1508
1509 static void free_line_header (struct line_header *lh);
1510
1511 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1512                                                      struct dwarf2_cu *cu);
1513
1514 static void dwarf_decode_lines (struct line_header *, const char *,
1515                                 struct dwarf2_cu *, struct partial_symtab *);
1516
1517 static void dwarf2_start_subfile (const char *, const char *, const char *);
1518
1519 static void dwarf2_start_symtab (struct dwarf2_cu *,
1520                                  const char *, const char *, CORE_ADDR);
1521
1522 static struct symbol *new_symbol (struct die_info *, struct type *,
1523                                   struct dwarf2_cu *);
1524
1525 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1526                                        struct dwarf2_cu *, struct symbol *);
1527
1528 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1529                                 struct dwarf2_cu *);
1530
1531 static void dwarf2_const_value_attr (const struct attribute *attr,
1532                                      struct type *type,
1533                                      const char *name,
1534                                      struct obstack *obstack,
1535                                      struct dwarf2_cu *cu, LONGEST *value,
1536                                      const gdb_byte **bytes,
1537                                      struct dwarf2_locexpr_baton **baton);
1538
1539 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1540
1541 static int need_gnat_info (struct dwarf2_cu *);
1542
1543 static struct type *die_descriptive_type (struct die_info *,
1544                                           struct dwarf2_cu *);
1545
1546 static void set_descriptive_type (struct type *, struct die_info *,
1547                                   struct dwarf2_cu *);
1548
1549 static struct type *die_containing_type (struct die_info *,
1550                                          struct dwarf2_cu *);
1551
1552 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1553                                      struct dwarf2_cu *);
1554
1555 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1556
1557 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1558
1559 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1560
1561 static char *typename_concat (struct obstack *obs, const char *prefix,
1562                               const char *suffix, int physname,
1563                               struct dwarf2_cu *cu);
1564
1565 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1566
1567 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1568
1569 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1570
1571 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1572
1573 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1574
1575 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1576                                struct dwarf2_cu *, struct partial_symtab *);
1577
1578 static int dwarf2_get_pc_bounds (struct die_info *,
1579                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1580                                  struct partial_symtab *);
1581
1582 static void get_scope_pc_bounds (struct die_info *,
1583                                  CORE_ADDR *, CORE_ADDR *,
1584                                  struct dwarf2_cu *);
1585
1586 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1587                                         CORE_ADDR, struct dwarf2_cu *);
1588
1589 static void dwarf2_add_field (struct field_info *, struct die_info *,
1590                               struct dwarf2_cu *);
1591
1592 static void dwarf2_attach_fields_to_type (struct field_info *,
1593                                           struct type *, struct dwarf2_cu *);
1594
1595 static void dwarf2_add_member_fn (struct field_info *,
1596                                   struct die_info *, struct type *,
1597                                   struct dwarf2_cu *);
1598
1599 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1600                                              struct type *,
1601                                              struct dwarf2_cu *);
1602
1603 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1604
1605 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1606
1607 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1608
1609 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1610
1611 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1612
1613 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *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 /* memory allocation interface */
1714
1715 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1716
1717 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1718
1719 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1720                                  const char *, int);
1721
1722 static int attr_form_is_block (const struct attribute *);
1723
1724 static int attr_form_is_section_offset (const struct attribute *);
1725
1726 static int attr_form_is_constant (const struct attribute *);
1727
1728 static int attr_form_is_ref (const struct attribute *);
1729
1730 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1731                                    struct dwarf2_loclist_baton *baton,
1732                                    const struct attribute *attr);
1733
1734 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1735                                          struct symbol *sym,
1736                                          struct dwarf2_cu *cu,
1737                                          int is_block);
1738
1739 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1740                                      const gdb_byte *info_ptr,
1741                                      struct abbrev_info *abbrev);
1742
1743 static void free_stack_comp_unit (void *);
1744
1745 static hashval_t partial_die_hash (const void *item);
1746
1747 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1748
1749 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1750   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1751
1752 static void init_one_comp_unit (struct dwarf2_cu *cu,
1753                                 struct dwarf2_per_cu_data *per_cu);
1754
1755 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1756                                    struct die_info *comp_unit_die,
1757                                    enum language pretend_language);
1758
1759 static void free_heap_comp_unit (void *);
1760
1761 static void free_cached_comp_units (void *);
1762
1763 static void age_cached_comp_units (void);
1764
1765 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1766
1767 static struct type *set_die_type (struct die_info *, struct type *,
1768                                   struct dwarf2_cu *);
1769
1770 static void create_all_comp_units (struct objfile *);
1771
1772 static int create_all_type_units (struct objfile *);
1773
1774 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1775                                  enum language);
1776
1777 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1778                                     enum language);
1779
1780 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1781                                     enum language);
1782
1783 static void dwarf2_add_dependence (struct dwarf2_cu *,
1784                                    struct dwarf2_per_cu_data *);
1785
1786 static void dwarf2_mark (struct dwarf2_cu *);
1787
1788 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1789
1790 static struct type *get_die_type_at_offset (sect_offset,
1791                                             struct dwarf2_per_cu_data *);
1792
1793 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1794
1795 static void dwarf2_release_queue (void *dummy);
1796
1797 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1798                              enum language pretend_language);
1799
1800 static void process_queue (void);
1801
1802 static void find_file_and_directory (struct die_info *die,
1803                                      struct dwarf2_cu *cu,
1804                                      const char **name, const char **comp_dir);
1805
1806 static char *file_full_name (int file, struct line_header *lh,
1807                              const char *comp_dir);
1808
1809 static const gdb_byte *read_and_check_comp_unit_head
1810   (struct comp_unit_head *header,
1811    struct dwarf2_section_info *section,
1812    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1813    int is_debug_types_section);
1814
1815 static void init_cutu_and_read_dies
1816   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1817    int use_existing_cu, int keep,
1818    die_reader_func_ftype *die_reader_func, void *data);
1819
1820 static void init_cutu_and_read_dies_simple
1821   (struct dwarf2_per_cu_data *this_cu,
1822    die_reader_func_ftype *die_reader_func, void *data);
1823
1824 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1825
1826 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1827
1828 static struct dwo_unit *lookup_dwo_unit_in_dwp
1829   (struct dwp_file *dwp_file, const char *comp_dir,
1830    ULONGEST signature, int is_debug_types);
1831
1832 static struct dwp_file *get_dwp_file (void);
1833
1834 static struct dwo_unit *lookup_dwo_comp_unit
1835   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1836
1837 static struct dwo_unit *lookup_dwo_type_unit
1838   (struct signatured_type *, const char *, const char *);
1839
1840 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1841
1842 static void free_dwo_file_cleanup (void *);
1843
1844 static void process_cu_includes (void);
1845
1846 static void check_producer (struct dwarf2_cu *cu);
1847 \f
1848 /* Various complaints about symbol reading that don't abort the process.  */
1849
1850 static void
1851 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1852 {
1853   complaint (&symfile_complaints,
1854              _("statement list doesn't fit in .debug_line section"));
1855 }
1856
1857 static void
1858 dwarf2_debug_line_missing_file_complaint (void)
1859 {
1860   complaint (&symfile_complaints,
1861              _(".debug_line section has line data without a file"));
1862 }
1863
1864 static void
1865 dwarf2_debug_line_missing_end_sequence_complaint (void)
1866 {
1867   complaint (&symfile_complaints,
1868              _(".debug_line section has line "
1869                "program sequence without an end"));
1870 }
1871
1872 static void
1873 dwarf2_complex_location_expr_complaint (void)
1874 {
1875   complaint (&symfile_complaints, _("location expression too complex"));
1876 }
1877
1878 static void
1879 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1880                                               int arg3)
1881 {
1882   complaint (&symfile_complaints,
1883              _("const value length mismatch for '%s', got %d, expected %d"),
1884              arg1, arg2, arg3);
1885 }
1886
1887 static void
1888 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1889 {
1890   complaint (&symfile_complaints,
1891              _("debug info runs off end of %s section"
1892                " [in module %s]"),
1893              get_section_name (section),
1894              get_section_file_name (section));
1895 }
1896
1897 static void
1898 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1899 {
1900   complaint (&symfile_complaints,
1901              _("macro debug info contains a "
1902                "malformed macro definition:\n`%s'"),
1903              arg1);
1904 }
1905
1906 static void
1907 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1908 {
1909   complaint (&symfile_complaints,
1910              _("invalid attribute class or form for '%s' in '%s'"),
1911              arg1, arg2);
1912 }
1913 \f
1914 #if WORDS_BIGENDIAN
1915
1916 /* Convert VALUE between big- and little-endian.  */
1917 static offset_type
1918 byte_swap (offset_type value)
1919 {
1920   offset_type result;
1921
1922   result = (value & 0xff) << 24;
1923   result |= (value & 0xff00) << 8;
1924   result |= (value & 0xff0000) >> 8;
1925   result |= (value & 0xff000000) >> 24;
1926   return result;
1927 }
1928
1929 #define MAYBE_SWAP(V)  byte_swap (V)
1930
1931 #else
1932 #define MAYBE_SWAP(V) (V)
1933 #endif /* WORDS_BIGENDIAN */
1934
1935 /* Read the given attribute value as an address, taking the attribute's
1936    form into account.  */
1937
1938 static CORE_ADDR
1939 attr_value_as_address (struct attribute *attr)
1940 {
1941   CORE_ADDR addr;
1942
1943   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
1944     {
1945       /* Aside from a few clearly defined exceptions, attributes that
1946          contain an address must always be in DW_FORM_addr form.
1947          Unfortunately, some compilers happen to be violating this
1948          requirement by encoding addresses using other forms, such
1949          as DW_FORM_data4 for example.  For those broken compilers,
1950          we try to do our best, without any guarantee of success,
1951          to interpret the address correctly.  It would also be nice
1952          to generate a complaint, but that would require us to maintain
1953          a list of legitimate cases where a non-address form is allowed,
1954          as well as update callers to pass in at least the CU's DWARF
1955          version.  This is more overhead than what we're willing to
1956          expand for a pretty rare case.  */
1957       addr = DW_UNSND (attr);
1958     }
1959   else
1960     addr = DW_ADDR (attr);
1961
1962   return addr;
1963 }
1964
1965 /* The suffix for an index file.  */
1966 #define INDEX_SUFFIX ".gdb-index"
1967
1968 /* Try to locate the sections we need for DWARF 2 debugging
1969    information and return true if we have enough to do something.
1970    NAMES points to the dwarf2 section names, or is NULL if the standard
1971    ELF names are used.  */
1972
1973 int
1974 dwarf2_has_info (struct objfile *objfile,
1975                  const struct dwarf2_debug_sections *names)
1976 {
1977   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1978   if (!dwarf2_per_objfile)
1979     {
1980       /* Initialize per-objfile state.  */
1981       struct dwarf2_per_objfile *data
1982         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1983
1984       memset (data, 0, sizeof (*data));
1985       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1986       dwarf2_per_objfile = data;
1987
1988       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1989                              (void *) names);
1990       dwarf2_per_objfile->objfile = objfile;
1991     }
1992   return (!dwarf2_per_objfile->info.is_virtual
1993           && dwarf2_per_objfile->info.s.asection != NULL
1994           && !dwarf2_per_objfile->abbrev.is_virtual
1995           && dwarf2_per_objfile->abbrev.s.asection != NULL);
1996 }
1997
1998 /* Return the containing section of virtual section SECTION.  */
1999
2000 static struct dwarf2_section_info *
2001 get_containing_section (const struct dwarf2_section_info *section)
2002 {
2003   gdb_assert (section->is_virtual);
2004   return section->s.containing_section;
2005 }
2006
2007 /* Return the bfd owner of SECTION.  */
2008
2009 static struct bfd *
2010 get_section_bfd_owner (const struct dwarf2_section_info *section)
2011 {
2012   if (section->is_virtual)
2013     {
2014       section = get_containing_section (section);
2015       gdb_assert (!section->is_virtual);
2016     }
2017   return section->s.asection->owner;
2018 }
2019
2020 /* Return the bfd section of SECTION.
2021    Returns NULL if the section is not present.  */
2022
2023 static asection *
2024 get_section_bfd_section (const struct dwarf2_section_info *section)
2025 {
2026   if (section->is_virtual)
2027     {
2028       section = get_containing_section (section);
2029       gdb_assert (!section->is_virtual);
2030     }
2031   return section->s.asection;
2032 }
2033
2034 /* Return the name of SECTION.  */
2035
2036 static const char *
2037 get_section_name (const struct dwarf2_section_info *section)
2038 {
2039   asection *sectp = get_section_bfd_section (section);
2040
2041   gdb_assert (sectp != NULL);
2042   return bfd_section_name (get_section_bfd_owner (section), sectp);
2043 }
2044
2045 /* Return the name of the file SECTION is in.  */
2046
2047 static const char *
2048 get_section_file_name (const struct dwarf2_section_info *section)
2049 {
2050   bfd *abfd = get_section_bfd_owner (section);
2051
2052   return bfd_get_filename (abfd);
2053 }
2054
2055 /* Return the id of SECTION.
2056    Returns 0 if SECTION doesn't exist.  */
2057
2058 static int
2059 get_section_id (const struct dwarf2_section_info *section)
2060 {
2061   asection *sectp = get_section_bfd_section (section);
2062
2063   if (sectp == NULL)
2064     return 0;
2065   return sectp->id;
2066 }
2067
2068 /* Return the flags of SECTION.
2069    SECTION (or containing section if this is a virtual section) must exist.  */
2070
2071 static int
2072 get_section_flags (const struct dwarf2_section_info *section)
2073 {
2074   asection *sectp = get_section_bfd_section (section);
2075
2076   gdb_assert (sectp != NULL);
2077   return bfd_get_section_flags (sectp->owner, sectp);
2078 }
2079
2080 /* When loading sections, we look either for uncompressed section or for
2081    compressed section names.  */
2082
2083 static int
2084 section_is_p (const char *section_name,
2085               const struct dwarf2_section_names *names)
2086 {
2087   if (names->normal != NULL
2088       && strcmp (section_name, names->normal) == 0)
2089     return 1;
2090   if (names->compressed != NULL
2091       && strcmp (section_name, names->compressed) == 0)
2092     return 1;
2093   return 0;
2094 }
2095
2096 /* This function is mapped across the sections and remembers the
2097    offset and size of each of the debugging sections we are interested
2098    in.  */
2099
2100 static void
2101 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
2102 {
2103   const struct dwarf2_debug_sections *names;
2104   flagword aflag = bfd_get_section_flags (abfd, sectp);
2105
2106   if (vnames == NULL)
2107     names = &dwarf2_elf_names;
2108   else
2109     names = (const struct dwarf2_debug_sections *) vnames;
2110
2111   if ((aflag & SEC_HAS_CONTENTS) == 0)
2112     {
2113     }
2114   else if (section_is_p (sectp->name, &names->info))
2115     {
2116       dwarf2_per_objfile->info.s.asection = sectp;
2117       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
2118     }
2119   else if (section_is_p (sectp->name, &names->abbrev))
2120     {
2121       dwarf2_per_objfile->abbrev.s.asection = sectp;
2122       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
2123     }
2124   else if (section_is_p (sectp->name, &names->line))
2125     {
2126       dwarf2_per_objfile->line.s.asection = sectp;
2127       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
2128     }
2129   else if (section_is_p (sectp->name, &names->loc))
2130     {
2131       dwarf2_per_objfile->loc.s.asection = sectp;
2132       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
2133     }
2134   else if (section_is_p (sectp->name, &names->macinfo))
2135     {
2136       dwarf2_per_objfile->macinfo.s.asection = sectp;
2137       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
2138     }
2139   else if (section_is_p (sectp->name, &names->macro))
2140     {
2141       dwarf2_per_objfile->macro.s.asection = sectp;
2142       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
2143     }
2144   else if (section_is_p (sectp->name, &names->str))
2145     {
2146       dwarf2_per_objfile->str.s.asection = sectp;
2147       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
2148     }
2149   else if (section_is_p (sectp->name, &names->addr))
2150     {
2151       dwarf2_per_objfile->addr.s.asection = sectp;
2152       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
2153     }
2154   else if (section_is_p (sectp->name, &names->frame))
2155     {
2156       dwarf2_per_objfile->frame.s.asection = sectp;
2157       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
2158     }
2159   else if (section_is_p (sectp->name, &names->eh_frame))
2160     {
2161       dwarf2_per_objfile->eh_frame.s.asection = sectp;
2162       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
2163     }
2164   else if (section_is_p (sectp->name, &names->ranges))
2165     {
2166       dwarf2_per_objfile->ranges.s.asection = sectp;
2167       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
2168     }
2169   else if (section_is_p (sectp->name, &names->types))
2170     {
2171       struct dwarf2_section_info type_section;
2172
2173       memset (&type_section, 0, sizeof (type_section));
2174       type_section.s.asection = sectp;
2175       type_section.size = bfd_get_section_size (sectp);
2176
2177       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
2178                      &type_section);
2179     }
2180   else if (section_is_p (sectp->name, &names->gdb_index))
2181     {
2182       dwarf2_per_objfile->gdb_index.s.asection = sectp;
2183       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
2184     }
2185
2186   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
2187       && bfd_section_vma (abfd, sectp) == 0)
2188     dwarf2_per_objfile->has_section_at_zero = 1;
2189 }
2190
2191 /* A helper function that decides whether a section is empty,
2192    or not present.  */
2193
2194 static int
2195 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2196 {
2197   if (section->is_virtual)
2198     return section->size == 0;
2199   return section->s.asection == NULL || section->size == 0;
2200 }
2201
2202 /* Read the contents of the section INFO.
2203    OBJFILE is the main object file, but not necessarily the file where
2204    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2205    of the DWO file.
2206    If the section is compressed, uncompress it before returning.  */
2207
2208 static void
2209 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2210 {
2211   asection *sectp;
2212   bfd *abfd;
2213   gdb_byte *buf, *retbuf;
2214
2215   if (info->readin)
2216     return;
2217   info->buffer = NULL;
2218   info->readin = 1;
2219
2220   if (dwarf2_section_empty_p (info))
2221     return;
2222
2223   sectp = get_section_bfd_section (info);
2224
2225   /* If this is a virtual section we need to read in the real one first.  */
2226   if (info->is_virtual)
2227     {
2228       struct dwarf2_section_info *containing_section =
2229         get_containing_section (info);
2230
2231       gdb_assert (sectp != NULL);
2232       if ((sectp->flags & SEC_RELOC) != 0)
2233         {
2234           error (_("Dwarf Error: DWP format V2 with relocations is not"
2235                    " supported in section %s [in module %s]"),
2236                  get_section_name (info), get_section_file_name (info));
2237         }
2238       dwarf2_read_section (objfile, containing_section);
2239       /* Other code should have already caught virtual sections that don't
2240          fit.  */
2241       gdb_assert (info->virtual_offset + info->size
2242                   <= containing_section->size);
2243       /* If the real section is empty or there was a problem reading the
2244          section we shouldn't get here.  */
2245       gdb_assert (containing_section->buffer != NULL);
2246       info->buffer = containing_section->buffer + info->virtual_offset;
2247       return;
2248     }
2249
2250   /* If the section has relocations, we must read it ourselves.
2251      Otherwise we attach it to the BFD.  */
2252   if ((sectp->flags & SEC_RELOC) == 0)
2253     {
2254       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2255       return;
2256     }
2257
2258   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
2259   info->buffer = buf;
2260
2261   /* When debugging .o files, we may need to apply relocations; see
2262      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2263      We never compress sections in .o files, so we only need to
2264      try this when the section is not compressed.  */
2265   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2266   if (retbuf != NULL)
2267     {
2268       info->buffer = retbuf;
2269       return;
2270     }
2271
2272   abfd = get_section_bfd_owner (info);
2273   gdb_assert (abfd != NULL);
2274
2275   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2276       || bfd_bread (buf, info->size, abfd) != info->size)
2277     {
2278       error (_("Dwarf Error: Can't read DWARF data"
2279                " in section %s [in module %s]"),
2280              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2281     }
2282 }
2283
2284 /* A helper function that returns the size of a section in a safe way.
2285    If you are positive that the section has been read before using the
2286    size, then it is safe to refer to the dwarf2_section_info object's
2287    "size" field directly.  In other cases, you must call this
2288    function, because for compressed sections the size field is not set
2289    correctly until the section has been read.  */
2290
2291 static bfd_size_type
2292 dwarf2_section_size (struct objfile *objfile,
2293                      struct dwarf2_section_info *info)
2294 {
2295   if (!info->readin)
2296     dwarf2_read_section (objfile, info);
2297   return info->size;
2298 }
2299
2300 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2301    SECTION_NAME.  */
2302
2303 void
2304 dwarf2_get_section_info (struct objfile *objfile,
2305                          enum dwarf2_section_enum sect,
2306                          asection **sectp, const gdb_byte **bufp,
2307                          bfd_size_type *sizep)
2308 {
2309   struct dwarf2_per_objfile *data
2310     = objfile_data (objfile, dwarf2_objfile_data_key);
2311   struct dwarf2_section_info *info;
2312
2313   /* We may see an objfile without any DWARF, in which case we just
2314      return nothing.  */
2315   if (data == NULL)
2316     {
2317       *sectp = NULL;
2318       *bufp = NULL;
2319       *sizep = 0;
2320       return;
2321     }
2322   switch (sect)
2323     {
2324     case DWARF2_DEBUG_FRAME:
2325       info = &data->frame;
2326       break;
2327     case DWARF2_EH_FRAME:
2328       info = &data->eh_frame;
2329       break;
2330     default:
2331       gdb_assert_not_reached ("unexpected section");
2332     }
2333
2334   dwarf2_read_section (objfile, info);
2335
2336   *sectp = get_section_bfd_section (info);
2337   *bufp = info->buffer;
2338   *sizep = info->size;
2339 }
2340
2341 /* A helper function to find the sections for a .dwz file.  */
2342
2343 static void
2344 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2345 {
2346   struct dwz_file *dwz_file = arg;
2347
2348   /* Note that we only support the standard ELF names, because .dwz
2349      is ELF-only (at the time of writing).  */
2350   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2351     {
2352       dwz_file->abbrev.s.asection = sectp;
2353       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2354     }
2355   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2356     {
2357       dwz_file->info.s.asection = sectp;
2358       dwz_file->info.size = bfd_get_section_size (sectp);
2359     }
2360   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2361     {
2362       dwz_file->str.s.asection = sectp;
2363       dwz_file->str.size = bfd_get_section_size (sectp);
2364     }
2365   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2366     {
2367       dwz_file->line.s.asection = sectp;
2368       dwz_file->line.size = bfd_get_section_size (sectp);
2369     }
2370   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2371     {
2372       dwz_file->macro.s.asection = sectp;
2373       dwz_file->macro.size = bfd_get_section_size (sectp);
2374     }
2375   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2376     {
2377       dwz_file->gdb_index.s.asection = sectp;
2378       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2379     }
2380 }
2381
2382 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2383    there is no .gnu_debugaltlink section in the file.  Error if there
2384    is such a section but the file cannot be found.  */
2385
2386 static struct dwz_file *
2387 dwarf2_get_dwz_file (void)
2388 {
2389   bfd *dwz_bfd;
2390   char *data;
2391   struct cleanup *cleanup;
2392   const char *filename;
2393   struct dwz_file *result;
2394   bfd_size_type buildid_len_arg;
2395   size_t buildid_len;
2396   bfd_byte *buildid;
2397
2398   if (dwarf2_per_objfile->dwz_file != NULL)
2399     return dwarf2_per_objfile->dwz_file;
2400
2401   bfd_set_error (bfd_error_no_error);
2402   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2403                                       &buildid_len_arg, &buildid);
2404   if (data == NULL)
2405     {
2406       if (bfd_get_error () == bfd_error_no_error)
2407         return NULL;
2408       error (_("could not read '.gnu_debugaltlink' section: %s"),
2409              bfd_errmsg (bfd_get_error ()));
2410     }
2411   cleanup = make_cleanup (xfree, data);
2412   make_cleanup (xfree, buildid);
2413
2414   buildid_len = (size_t) buildid_len_arg;
2415
2416   filename = (const char *) data;
2417   if (!IS_ABSOLUTE_PATH (filename))
2418     {
2419       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2420       char *rel;
2421
2422       make_cleanup (xfree, abs);
2423       abs = ldirname (abs);
2424       make_cleanup (xfree, abs);
2425
2426       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2427       make_cleanup (xfree, rel);
2428       filename = rel;
2429     }
2430
2431   /* First try the file name given in the section.  If that doesn't
2432      work, try to use the build-id instead.  */
2433   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2434   if (dwz_bfd != NULL)
2435     {
2436       if (!build_id_verify (dwz_bfd, buildid_len, buildid))
2437         {
2438           gdb_bfd_unref (dwz_bfd);
2439           dwz_bfd = NULL;
2440         }
2441     }
2442
2443   if (dwz_bfd == NULL)
2444     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2445
2446   if (dwz_bfd == NULL)
2447     error (_("could not find '.gnu_debugaltlink' file for %s"),
2448            objfile_name (dwarf2_per_objfile->objfile));
2449
2450   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2451                            struct dwz_file);
2452   result->dwz_bfd = dwz_bfd;
2453
2454   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2455
2456   do_cleanups (cleanup);
2457
2458   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, dwz_bfd);
2459   dwarf2_per_objfile->dwz_file = result;
2460   return result;
2461 }
2462 \f
2463 /* DWARF quick_symbols_functions support.  */
2464
2465 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2466    unique line tables, so we maintain a separate table of all .debug_line
2467    derived entries to support the sharing.
2468    All the quick functions need is the list of file names.  We discard the
2469    line_header when we're done and don't need to record it here.  */
2470 struct quick_file_names
2471 {
2472   /* The data used to construct the hash key.  */
2473   struct stmt_list_hash hash;
2474
2475   /* The number of entries in file_names, real_names.  */
2476   unsigned int num_file_names;
2477
2478   /* The file names from the line table, after being run through
2479      file_full_name.  */
2480   const char **file_names;
2481
2482   /* The file names from the line table after being run through
2483      gdb_realpath.  These are computed lazily.  */
2484   const char **real_names;
2485 };
2486
2487 /* When using the index (and thus not using psymtabs), each CU has an
2488    object of this type.  This is used to hold information needed by
2489    the various "quick" methods.  */
2490 struct dwarf2_per_cu_quick_data
2491 {
2492   /* The file table.  This can be NULL if there was no file table
2493      or it's currently not read in.
2494      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2495   struct quick_file_names *file_names;
2496
2497   /* The corresponding symbol table.  This is NULL if symbols for this
2498      CU have not yet been read.  */
2499   struct symtab *symtab;
2500
2501   /* A temporary mark bit used when iterating over all CUs in
2502      expand_symtabs_matching.  */
2503   unsigned int mark : 1;
2504
2505   /* True if we've tried to read the file table and found there isn't one.
2506      There will be no point in trying to read it again next time.  */
2507   unsigned int no_file_data : 1;
2508 };
2509
2510 /* Utility hash function for a stmt_list_hash.  */
2511
2512 static hashval_t
2513 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2514 {
2515   hashval_t v = 0;
2516
2517   if (stmt_list_hash->dwo_unit != NULL)
2518     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2519   v += stmt_list_hash->line_offset.sect_off;
2520   return v;
2521 }
2522
2523 /* Utility equality function for a stmt_list_hash.  */
2524
2525 static int
2526 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2527                     const struct stmt_list_hash *rhs)
2528 {
2529   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2530     return 0;
2531   if (lhs->dwo_unit != NULL
2532       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2533     return 0;
2534
2535   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2536 }
2537
2538 /* Hash function for a quick_file_names.  */
2539
2540 static hashval_t
2541 hash_file_name_entry (const void *e)
2542 {
2543   const struct quick_file_names *file_data = e;
2544
2545   return hash_stmt_list_entry (&file_data->hash);
2546 }
2547
2548 /* Equality function for a quick_file_names.  */
2549
2550 static int
2551 eq_file_name_entry (const void *a, const void *b)
2552 {
2553   const struct quick_file_names *ea = a;
2554   const struct quick_file_names *eb = b;
2555
2556   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2557 }
2558
2559 /* Delete function for a quick_file_names.  */
2560
2561 static void
2562 delete_file_name_entry (void *e)
2563 {
2564   struct quick_file_names *file_data = e;
2565   int i;
2566
2567   for (i = 0; i < file_data->num_file_names; ++i)
2568     {
2569       xfree ((void*) file_data->file_names[i]);
2570       if (file_data->real_names)
2571         xfree ((void*) file_data->real_names[i]);
2572     }
2573
2574   /* The space for the struct itself lives on objfile_obstack,
2575      so we don't free it here.  */
2576 }
2577
2578 /* Create a quick_file_names hash table.  */
2579
2580 static htab_t
2581 create_quick_file_names_table (unsigned int nr_initial_entries)
2582 {
2583   return htab_create_alloc (nr_initial_entries,
2584                             hash_file_name_entry, eq_file_name_entry,
2585                             delete_file_name_entry, xcalloc, xfree);
2586 }
2587
2588 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2589    have to be created afterwards.  You should call age_cached_comp_units after
2590    processing PER_CU->CU.  dw2_setup must have been already called.  */
2591
2592 static void
2593 load_cu (struct dwarf2_per_cu_data *per_cu)
2594 {
2595   if (per_cu->is_debug_types)
2596     load_full_type_unit (per_cu);
2597   else
2598     load_full_comp_unit (per_cu, language_minimal);
2599
2600   gdb_assert (per_cu->cu != NULL);
2601
2602   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2603 }
2604
2605 /* Read in the symbols for PER_CU.  */
2606
2607 static void
2608 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2609 {
2610   struct cleanup *back_to;
2611
2612   /* Skip type_unit_groups, reading the type units they contain
2613      is handled elsewhere.  */
2614   if (IS_TYPE_UNIT_GROUP (per_cu))
2615     return;
2616
2617   back_to = make_cleanup (dwarf2_release_queue, NULL);
2618
2619   if (dwarf2_per_objfile->using_index
2620       ? per_cu->v.quick->symtab == NULL
2621       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2622     {
2623       queue_comp_unit (per_cu, language_minimal);
2624       load_cu (per_cu);
2625
2626       /* If we just loaded a CU from a DWO, and we're working with an index
2627          that may badly handle TUs, load all the TUs in that DWO as well.
2628          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2629       if (!per_cu->is_debug_types
2630           && per_cu->cu->dwo_unit != NULL
2631           && dwarf2_per_objfile->index_table != NULL
2632           && dwarf2_per_objfile->index_table->version <= 7
2633           /* DWP files aren't supported yet.  */
2634           && get_dwp_file () == NULL)
2635         queue_and_load_all_dwo_tus (per_cu);
2636     }
2637
2638   process_queue ();
2639
2640   /* Age the cache, releasing compilation units that have not
2641      been used recently.  */
2642   age_cached_comp_units ();
2643
2644   do_cleanups (back_to);
2645 }
2646
2647 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2648    the objfile from which this CU came.  Returns the resulting symbol
2649    table.  */
2650
2651 static struct symtab *
2652 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2653 {
2654   gdb_assert (dwarf2_per_objfile->using_index);
2655   if (!per_cu->v.quick->symtab)
2656     {
2657       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2658       increment_reading_symtab ();
2659       dw2_do_instantiate_symtab (per_cu);
2660       process_cu_includes ();
2661       do_cleanups (back_to);
2662     }
2663   return per_cu->v.quick->symtab;
2664 }
2665
2666 /* Return the CU/TU given its index.
2667
2668    This is intended for loops like:
2669
2670    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2671                     + dwarf2_per_objfile->n_type_units); ++i)
2672      {
2673        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2674
2675        ...;
2676      }
2677 */
2678
2679 static struct dwarf2_per_cu_data *
2680 dw2_get_cutu (int index)
2681 {
2682   if (index >= dwarf2_per_objfile->n_comp_units)
2683     {
2684       index -= dwarf2_per_objfile->n_comp_units;
2685       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2686       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2687     }
2688
2689   return dwarf2_per_objfile->all_comp_units[index];
2690 }
2691
2692 /* Return the CU given its index.
2693    This differs from dw2_get_cutu in that it's for when you know INDEX
2694    refers to a CU.  */
2695
2696 static struct dwarf2_per_cu_data *
2697 dw2_get_cu (int index)
2698 {
2699   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2700
2701   return dwarf2_per_objfile->all_comp_units[index];
2702 }
2703
2704 /* A helper for create_cus_from_index that handles a given list of
2705    CUs.  */
2706
2707 static void
2708 create_cus_from_index_list (struct objfile *objfile,
2709                             const gdb_byte *cu_list, offset_type n_elements,
2710                             struct dwarf2_section_info *section,
2711                             int is_dwz,
2712                             int base_offset)
2713 {
2714   offset_type i;
2715
2716   for (i = 0; i < n_elements; i += 2)
2717     {
2718       struct dwarf2_per_cu_data *the_cu;
2719       ULONGEST offset, length;
2720
2721       gdb_static_assert (sizeof (ULONGEST) >= 8);
2722       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2723       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2724       cu_list += 2 * 8;
2725
2726       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2727                                struct dwarf2_per_cu_data);
2728       the_cu->offset.sect_off = offset;
2729       the_cu->length = length;
2730       the_cu->objfile = objfile;
2731       the_cu->section = section;
2732       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2733                                         struct dwarf2_per_cu_quick_data);
2734       the_cu->is_dwz = is_dwz;
2735       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2736     }
2737 }
2738
2739 /* Read the CU list from the mapped index, and use it to create all
2740    the CU objects for this objfile.  */
2741
2742 static void
2743 create_cus_from_index (struct objfile *objfile,
2744                        const gdb_byte *cu_list, offset_type cu_list_elements,
2745                        const gdb_byte *dwz_list, offset_type dwz_elements)
2746 {
2747   struct dwz_file *dwz;
2748
2749   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2750   dwarf2_per_objfile->all_comp_units
2751     = obstack_alloc (&objfile->objfile_obstack,
2752                      dwarf2_per_objfile->n_comp_units
2753                      * sizeof (struct dwarf2_per_cu_data *));
2754
2755   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2756                               &dwarf2_per_objfile->info, 0, 0);
2757
2758   if (dwz_elements == 0)
2759     return;
2760
2761   dwz = dwarf2_get_dwz_file ();
2762   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2763                               cu_list_elements / 2);
2764 }
2765
2766 /* Create the signatured type hash table from the index.  */
2767
2768 static void
2769 create_signatured_type_table_from_index (struct objfile *objfile,
2770                                          struct dwarf2_section_info *section,
2771                                          const gdb_byte *bytes,
2772                                          offset_type elements)
2773 {
2774   offset_type i;
2775   htab_t sig_types_hash;
2776
2777   dwarf2_per_objfile->n_type_units
2778     = dwarf2_per_objfile->n_allocated_type_units
2779     = elements / 3;
2780   dwarf2_per_objfile->all_type_units
2781     = xmalloc (dwarf2_per_objfile->n_type_units
2782                * sizeof (struct signatured_type *));
2783
2784   sig_types_hash = allocate_signatured_type_table (objfile);
2785
2786   for (i = 0; i < elements; i += 3)
2787     {
2788       struct signatured_type *sig_type;
2789       ULONGEST offset, type_offset_in_tu, signature;
2790       void **slot;
2791
2792       gdb_static_assert (sizeof (ULONGEST) >= 8);
2793       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2794       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2795                                                     BFD_ENDIAN_LITTLE);
2796       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2797       bytes += 3 * 8;
2798
2799       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2800                                  struct signatured_type);
2801       sig_type->signature = signature;
2802       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2803       sig_type->per_cu.is_debug_types = 1;
2804       sig_type->per_cu.section = section;
2805       sig_type->per_cu.offset.sect_off = offset;
2806       sig_type->per_cu.objfile = objfile;
2807       sig_type->per_cu.v.quick
2808         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2809                           struct dwarf2_per_cu_quick_data);
2810
2811       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2812       *slot = sig_type;
2813
2814       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2815     }
2816
2817   dwarf2_per_objfile->signatured_types = sig_types_hash;
2818 }
2819
2820 /* Read the address map data from the mapped index, and use it to
2821    populate the objfile's psymtabs_addrmap.  */
2822
2823 static void
2824 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2825 {
2826   const gdb_byte *iter, *end;
2827   struct obstack temp_obstack;
2828   struct addrmap *mutable_map;
2829   struct cleanup *cleanup;
2830   CORE_ADDR baseaddr;
2831
2832   obstack_init (&temp_obstack);
2833   cleanup = make_cleanup_obstack_free (&temp_obstack);
2834   mutable_map = addrmap_create_mutable (&temp_obstack);
2835
2836   iter = index->address_table;
2837   end = iter + index->address_table_size;
2838
2839   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2840
2841   while (iter < end)
2842     {
2843       ULONGEST hi, lo, cu_index;
2844       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2845       iter += 8;
2846       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2847       iter += 8;
2848       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2849       iter += 4;
2850
2851       if (lo > hi)
2852         {
2853           complaint (&symfile_complaints,
2854                      _(".gdb_index address table has invalid range (%s - %s)"),
2855                      hex_string (lo), hex_string (hi));
2856           continue;
2857         }
2858
2859       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2860         {
2861           complaint (&symfile_complaints,
2862                      _(".gdb_index address table has invalid CU number %u"),
2863                      (unsigned) cu_index);
2864           continue;
2865         }
2866
2867       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2868                          dw2_get_cutu (cu_index));
2869     }
2870
2871   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2872                                                     &objfile->objfile_obstack);
2873   do_cleanups (cleanup);
2874 }
2875
2876 /* The hash function for strings in the mapped index.  This is the same as
2877    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2878    implementation.  This is necessary because the hash function is tied to the
2879    format of the mapped index file.  The hash values do not have to match with
2880    SYMBOL_HASH_NEXT.
2881    
2882    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2883
2884 static hashval_t
2885 mapped_index_string_hash (int index_version, const void *p)
2886 {
2887   const unsigned char *str = (const unsigned char *) p;
2888   hashval_t r = 0;
2889   unsigned char c;
2890
2891   while ((c = *str++) != 0)
2892     {
2893       if (index_version >= 5)
2894         c = tolower (c);
2895       r = r * 67 + c - 113;
2896     }
2897
2898   return r;
2899 }
2900
2901 /* Find a slot in the mapped index INDEX for the object named NAME.
2902    If NAME is found, set *VEC_OUT to point to the CU vector in the
2903    constant pool and return 1.  If NAME cannot be found, return 0.  */
2904
2905 static int
2906 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2907                           offset_type **vec_out)
2908 {
2909   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2910   offset_type hash;
2911   offset_type slot, step;
2912   int (*cmp) (const char *, const char *);
2913
2914   if (current_language->la_language == language_cplus
2915       || current_language->la_language == language_java
2916       || current_language->la_language == language_fortran)
2917     {
2918       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2919          not contain any.  */
2920       const char *paren = strchr (name, '(');
2921
2922       if (paren)
2923         {
2924           char *dup;
2925
2926           dup = xmalloc (paren - name + 1);
2927           memcpy (dup, name, paren - name);
2928           dup[paren - name] = 0;
2929
2930           make_cleanup (xfree, dup);
2931           name = dup;
2932         }
2933     }
2934
2935   /* Index version 4 did not support case insensitive searches.  But the
2936      indices for case insensitive languages are built in lowercase, therefore
2937      simulate our NAME being searched is also lowercased.  */
2938   hash = mapped_index_string_hash ((index->version == 4
2939                                     && case_sensitivity == case_sensitive_off
2940                                     ? 5 : index->version),
2941                                    name);
2942
2943   slot = hash & (index->symbol_table_slots - 1);
2944   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2945   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2946
2947   for (;;)
2948     {
2949       /* Convert a slot number to an offset into the table.  */
2950       offset_type i = 2 * slot;
2951       const char *str;
2952       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2953         {
2954           do_cleanups (back_to);
2955           return 0;
2956         }
2957
2958       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2959       if (!cmp (name, str))
2960         {
2961           *vec_out = (offset_type *) (index->constant_pool
2962                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2963           do_cleanups (back_to);
2964           return 1;
2965         }
2966
2967       slot = (slot + step) & (index->symbol_table_slots - 1);
2968     }
2969 }
2970
2971 /* A helper function that reads the .gdb_index from SECTION and fills
2972    in MAP.  FILENAME is the name of the file containing the section;
2973    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2974    ok to use deprecated sections.
2975
2976    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2977    out parameters that are filled in with information about the CU and
2978    TU lists in the section.
2979
2980    Returns 1 if all went well, 0 otherwise.  */
2981
2982 static int
2983 read_index_from_section (struct objfile *objfile,
2984                          const char *filename,
2985                          int deprecated_ok,
2986                          struct dwarf2_section_info *section,
2987                          struct mapped_index *map,
2988                          const gdb_byte **cu_list,
2989                          offset_type *cu_list_elements,
2990                          const gdb_byte **types_list,
2991                          offset_type *types_list_elements)
2992 {
2993   const gdb_byte *addr;
2994   offset_type version;
2995   offset_type *metadata;
2996   int i;
2997
2998   if (dwarf2_section_empty_p (section))
2999     return 0;
3000
3001   /* Older elfutils strip versions could keep the section in the main
3002      executable while splitting it for the separate debug info file.  */
3003   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3004     return 0;
3005
3006   dwarf2_read_section (objfile, section);
3007
3008   addr = section->buffer;
3009   /* Version check.  */
3010   version = MAYBE_SWAP (*(offset_type *) addr);
3011   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3012      causes the index to behave very poorly for certain requests.  Version 3
3013      contained incomplete addrmap.  So, it seems better to just ignore such
3014      indices.  */
3015   if (version < 4)
3016     {
3017       static int warning_printed = 0;
3018       if (!warning_printed)
3019         {
3020           warning (_("Skipping obsolete .gdb_index section in %s."),
3021                    filename);
3022           warning_printed = 1;
3023         }
3024       return 0;
3025     }
3026   /* Index version 4 uses a different hash function than index version
3027      5 and later.
3028
3029      Versions earlier than 6 did not emit psymbols for inlined
3030      functions.  Using these files will cause GDB not to be able to
3031      set breakpoints on inlined functions by name, so we ignore these
3032      indices unless the user has done
3033      "set use-deprecated-index-sections on".  */
3034   if (version < 6 && !deprecated_ok)
3035     {
3036       static int warning_printed = 0;
3037       if (!warning_printed)
3038         {
3039           warning (_("\
3040 Skipping deprecated .gdb_index section in %s.\n\
3041 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3042 to use the section anyway."),
3043                    filename);
3044           warning_printed = 1;
3045         }
3046       return 0;
3047     }
3048   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3049      of the TU (for symbols coming from TUs),
3050      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3051      Plus gold-generated indices can have duplicate entries for global symbols,
3052      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3053      These are just performance bugs, and we can't distinguish gdb-generated
3054      indices from gold-generated ones, so issue no warning here.  */
3055
3056   /* Indexes with higher version than the one supported by GDB may be no
3057      longer backward compatible.  */
3058   if (version > 8)
3059     return 0;
3060
3061   map->version = version;
3062   map->total_size = section->size;
3063
3064   metadata = (offset_type *) (addr + sizeof (offset_type));
3065
3066   i = 0;
3067   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3068   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3069                        / 8);
3070   ++i;
3071
3072   *types_list = addr + MAYBE_SWAP (metadata[i]);
3073   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3074                            - MAYBE_SWAP (metadata[i]))
3075                           / 8);
3076   ++i;
3077
3078   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3079   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3080                              - MAYBE_SWAP (metadata[i]));
3081   ++i;
3082
3083   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3084   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3085                               - MAYBE_SWAP (metadata[i]))
3086                              / (2 * sizeof (offset_type)));
3087   ++i;
3088
3089   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3090
3091   return 1;
3092 }
3093
3094
3095 /* Read the index file.  If everything went ok, initialize the "quick"
3096    elements of all the CUs and return 1.  Otherwise, return 0.  */
3097
3098 static int
3099 dwarf2_read_index (struct objfile *objfile)
3100 {
3101   struct mapped_index local_map, *map;
3102   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3103   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3104   struct dwz_file *dwz;
3105
3106   if (!read_index_from_section (objfile, objfile_name (objfile),
3107                                 use_deprecated_index_sections,
3108                                 &dwarf2_per_objfile->gdb_index, &local_map,
3109                                 &cu_list, &cu_list_elements,
3110                                 &types_list, &types_list_elements))
3111     return 0;
3112
3113   /* Don't use the index if it's empty.  */
3114   if (local_map.symbol_table_slots == 0)
3115     return 0;
3116
3117   /* If there is a .dwz file, read it so we can get its CU list as
3118      well.  */
3119   dwz = dwarf2_get_dwz_file ();
3120   if (dwz != NULL)
3121     {
3122       struct mapped_index dwz_map;
3123       const gdb_byte *dwz_types_ignore;
3124       offset_type dwz_types_elements_ignore;
3125
3126       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3127                                     1,
3128                                     &dwz->gdb_index, &dwz_map,
3129                                     &dwz_list, &dwz_list_elements,
3130                                     &dwz_types_ignore,
3131                                     &dwz_types_elements_ignore))
3132         {
3133           warning (_("could not read '.gdb_index' section from %s; skipping"),
3134                    bfd_get_filename (dwz->dwz_bfd));
3135           return 0;
3136         }
3137     }
3138
3139   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3140                          dwz_list_elements);
3141
3142   if (types_list_elements)
3143     {
3144       struct dwarf2_section_info *section;
3145
3146       /* We can only handle a single .debug_types when we have an
3147          index.  */
3148       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3149         return 0;
3150
3151       section = VEC_index (dwarf2_section_info_def,
3152                            dwarf2_per_objfile->types, 0);
3153
3154       create_signatured_type_table_from_index (objfile, section, types_list,
3155                                                types_list_elements);
3156     }
3157
3158   create_addrmap_from_index (objfile, &local_map);
3159
3160   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
3161   *map = local_map;
3162
3163   dwarf2_per_objfile->index_table = map;
3164   dwarf2_per_objfile->using_index = 1;
3165   dwarf2_per_objfile->quick_file_names_table =
3166     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3167
3168   return 1;
3169 }
3170
3171 /* A helper for the "quick" functions which sets the global
3172    dwarf2_per_objfile according to OBJFILE.  */
3173
3174 static void
3175 dw2_setup (struct objfile *objfile)
3176 {
3177   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
3178   gdb_assert (dwarf2_per_objfile);
3179 }
3180
3181 /* die_reader_func for dw2_get_file_names.  */
3182
3183 static void
3184 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3185                            const gdb_byte *info_ptr,
3186                            struct die_info *comp_unit_die,
3187                            int has_children,
3188                            void *data)
3189 {
3190   struct dwarf2_cu *cu = reader->cu;
3191   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3192   struct objfile *objfile = dwarf2_per_objfile->objfile;
3193   struct dwarf2_per_cu_data *lh_cu;
3194   struct line_header *lh;
3195   struct attribute *attr;
3196   int i;
3197   const char *name, *comp_dir;
3198   void **slot;
3199   struct quick_file_names *qfn;
3200   unsigned int line_offset;
3201
3202   gdb_assert (! this_cu->is_debug_types);
3203
3204   /* Our callers never want to match partial units -- instead they
3205      will match the enclosing full CU.  */
3206   if (comp_unit_die->tag == DW_TAG_partial_unit)
3207     {
3208       this_cu->v.quick->no_file_data = 1;
3209       return;
3210     }
3211
3212   lh_cu = this_cu;
3213   lh = NULL;
3214   slot = NULL;
3215   line_offset = 0;
3216
3217   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3218   if (attr)
3219     {
3220       struct quick_file_names find_entry;
3221
3222       line_offset = DW_UNSND (attr);
3223
3224       /* We may have already read in this line header (TU line header sharing).
3225          If we have we're done.  */
3226       find_entry.hash.dwo_unit = cu->dwo_unit;
3227       find_entry.hash.line_offset.sect_off = line_offset;
3228       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3229                              &find_entry, INSERT);
3230       if (*slot != NULL)
3231         {
3232           lh_cu->v.quick->file_names = *slot;
3233           return;
3234         }
3235
3236       lh = dwarf_decode_line_header (line_offset, cu);
3237     }
3238   if (lh == NULL)
3239     {
3240       lh_cu->v.quick->no_file_data = 1;
3241       return;
3242     }
3243
3244   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
3245   qfn->hash.dwo_unit = cu->dwo_unit;
3246   qfn->hash.line_offset.sect_off = line_offset;
3247   gdb_assert (slot != NULL);
3248   *slot = qfn;
3249
3250   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
3251
3252   qfn->num_file_names = lh->num_file_names;
3253   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
3254                                    lh->num_file_names * sizeof (char *));
3255   for (i = 0; i < lh->num_file_names; ++i)
3256     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
3257   qfn->real_names = NULL;
3258
3259   free_line_header (lh);
3260
3261   lh_cu->v.quick->file_names = qfn;
3262 }
3263
3264 /* A helper for the "quick" functions which attempts to read the line
3265    table for THIS_CU.  */
3266
3267 static struct quick_file_names *
3268 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3269 {
3270   /* This should never be called for TUs.  */
3271   gdb_assert (! this_cu->is_debug_types);
3272   /* Nor type unit groups.  */
3273   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3274
3275   if (this_cu->v.quick->file_names != NULL)
3276     return this_cu->v.quick->file_names;
3277   /* If we know there is no line data, no point in looking again.  */
3278   if (this_cu->v.quick->no_file_data)
3279     return NULL;
3280
3281   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3282
3283   if (this_cu->v.quick->no_file_data)
3284     return NULL;
3285   return this_cu->v.quick->file_names;
3286 }
3287
3288 /* A helper for the "quick" functions which computes and caches the
3289    real path for a given file name from the line table.  */
3290
3291 static const char *
3292 dw2_get_real_path (struct objfile *objfile,
3293                    struct quick_file_names *qfn, int index)
3294 {
3295   if (qfn->real_names == NULL)
3296     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3297                                       qfn->num_file_names, const char *);
3298
3299   if (qfn->real_names[index] == NULL)
3300     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3301
3302   return qfn->real_names[index];
3303 }
3304
3305 static struct symtab *
3306 dw2_find_last_source_symtab (struct objfile *objfile)
3307 {
3308   int index;
3309
3310   dw2_setup (objfile);
3311   index = dwarf2_per_objfile->n_comp_units - 1;
3312   return dw2_instantiate_symtab (dw2_get_cutu (index));
3313 }
3314
3315 /* Traversal function for dw2_forget_cached_source_info.  */
3316
3317 static int
3318 dw2_free_cached_file_names (void **slot, void *info)
3319 {
3320   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3321
3322   if (file_data->real_names)
3323     {
3324       int i;
3325
3326       for (i = 0; i < file_data->num_file_names; ++i)
3327         {
3328           xfree ((void*) file_data->real_names[i]);
3329           file_data->real_names[i] = NULL;
3330         }
3331     }
3332
3333   return 1;
3334 }
3335
3336 static void
3337 dw2_forget_cached_source_info (struct objfile *objfile)
3338 {
3339   dw2_setup (objfile);
3340
3341   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3342                           dw2_free_cached_file_names, NULL);
3343 }
3344
3345 /* Helper function for dw2_map_symtabs_matching_filename that expands
3346    the symtabs and calls the iterator.  */
3347
3348 static int
3349 dw2_map_expand_apply (struct objfile *objfile,
3350                       struct dwarf2_per_cu_data *per_cu,
3351                       const char *name, const char *real_path,
3352                       int (*callback) (struct symtab *, void *),
3353                       void *data)
3354 {
3355   struct symtab *last_made = objfile->symtabs;
3356
3357   /* Don't visit already-expanded CUs.  */
3358   if (per_cu->v.quick->symtab)
3359     return 0;
3360
3361   /* This may expand more than one symtab, and we want to iterate over
3362      all of them.  */
3363   dw2_instantiate_symtab (per_cu);
3364
3365   return iterate_over_some_symtabs (name, real_path, callback, data,
3366                                     objfile->symtabs, last_made);
3367 }
3368
3369 /* Implementation of the map_symtabs_matching_filename method.  */
3370
3371 static int
3372 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3373                                    const char *real_path,
3374                                    int (*callback) (struct symtab *, void *),
3375                                    void *data)
3376 {
3377   int i;
3378   const char *name_basename = lbasename (name);
3379
3380   dw2_setup (objfile);
3381
3382   /* The rule is CUs specify all the files, including those used by
3383      any TU, so there's no need to scan TUs here.  */
3384
3385   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3386     {
3387       int j;
3388       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3389       struct quick_file_names *file_data;
3390
3391       /* We only need to look at symtabs not already expanded.  */
3392       if (per_cu->v.quick->symtab)
3393         continue;
3394
3395       file_data = dw2_get_file_names (per_cu);
3396       if (file_data == NULL)
3397         continue;
3398
3399       for (j = 0; j < file_data->num_file_names; ++j)
3400         {
3401           const char *this_name = file_data->file_names[j];
3402           const char *this_real_name;
3403
3404           if (compare_filenames_for_search (this_name, name))
3405             {
3406               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3407                                         callback, data))
3408                 return 1;
3409               continue;
3410             }
3411
3412           /* Before we invoke realpath, which can get expensive when many
3413              files are involved, do a quick comparison of the basenames.  */
3414           if (! basenames_may_differ
3415               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3416             continue;
3417
3418           this_real_name = dw2_get_real_path (objfile, file_data, j);
3419           if (compare_filenames_for_search (this_real_name, name))
3420             {
3421               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3422                                         callback, data))
3423                 return 1;
3424               continue;
3425             }
3426
3427           if (real_path != NULL)
3428             {
3429               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3430               gdb_assert (IS_ABSOLUTE_PATH (name));
3431               if (this_real_name != NULL
3432                   && FILENAME_CMP (real_path, this_real_name) == 0)
3433                 {
3434                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3435                                             callback, data))
3436                     return 1;
3437                   continue;
3438                 }
3439             }
3440         }
3441     }
3442
3443   return 0;
3444 }
3445
3446 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3447
3448 struct dw2_symtab_iterator
3449 {
3450   /* The internalized form of .gdb_index.  */
3451   struct mapped_index *index;
3452   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3453   int want_specific_block;
3454   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3455      Unused if !WANT_SPECIFIC_BLOCK.  */
3456   int block_index;
3457   /* The kind of symbol we're looking for.  */
3458   domain_enum domain;
3459   /* The list of CUs from the index entry of the symbol,
3460      or NULL if not found.  */
3461   offset_type *vec;
3462   /* The next element in VEC to look at.  */
3463   int next;
3464   /* The number of elements in VEC, or zero if there is no match.  */
3465   int length;
3466   /* Have we seen a global version of the symbol?
3467      If so we can ignore all further global instances.
3468      This is to work around gold/15646, inefficient gold-generated
3469      indices.  */
3470   int global_seen;
3471 };
3472
3473 /* Initialize the index symtab iterator ITER.
3474    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3475    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3476
3477 static void
3478 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3479                       struct mapped_index *index,
3480                       int want_specific_block,
3481                       int block_index,
3482                       domain_enum domain,
3483                       const char *name)
3484 {
3485   iter->index = index;
3486   iter->want_specific_block = want_specific_block;
3487   iter->block_index = block_index;
3488   iter->domain = domain;
3489   iter->next = 0;
3490   iter->global_seen = 0;
3491
3492   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3493     iter->length = MAYBE_SWAP (*iter->vec);
3494   else
3495     {
3496       iter->vec = NULL;
3497       iter->length = 0;
3498     }
3499 }
3500
3501 /* Return the next matching CU or NULL if there are no more.  */
3502
3503 static struct dwarf2_per_cu_data *
3504 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3505 {
3506   for ( ; iter->next < iter->length; ++iter->next)
3507     {
3508       offset_type cu_index_and_attrs =
3509         MAYBE_SWAP (iter->vec[iter->next + 1]);
3510       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3511       struct dwarf2_per_cu_data *per_cu;
3512       int want_static = iter->block_index != GLOBAL_BLOCK;
3513       /* This value is only valid for index versions >= 7.  */
3514       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3515       gdb_index_symbol_kind symbol_kind =
3516         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3517       /* Only check the symbol attributes if they're present.
3518          Indices prior to version 7 don't record them,
3519          and indices >= 7 may elide them for certain symbols
3520          (gold does this).  */
3521       int attrs_valid =
3522         (iter->index->version >= 7
3523          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3524
3525       /* Don't crash on bad data.  */
3526       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3527                        + dwarf2_per_objfile->n_type_units))
3528         {
3529           complaint (&symfile_complaints,
3530                      _(".gdb_index entry has bad CU index"
3531                        " [in module %s]"),
3532                      objfile_name (dwarf2_per_objfile->objfile));
3533           continue;
3534         }
3535
3536       per_cu = dw2_get_cutu (cu_index);
3537
3538       /* Skip if already read in.  */
3539       if (per_cu->v.quick->symtab)
3540         continue;
3541
3542       /* Check static vs global.  */
3543       if (attrs_valid)
3544         {
3545           if (iter->want_specific_block
3546               && want_static != is_static)
3547             continue;
3548           /* Work around gold/15646.  */
3549           if (!is_static && iter->global_seen)
3550             continue;
3551           if (!is_static)
3552             iter->global_seen = 1;
3553         }
3554
3555       /* Only check the symbol's kind if it has one.  */
3556       if (attrs_valid)
3557         {
3558           switch (iter->domain)
3559             {
3560             case VAR_DOMAIN:
3561               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3562                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3563                   /* Some types are also in VAR_DOMAIN.  */
3564                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3565                 continue;
3566               break;
3567             case STRUCT_DOMAIN:
3568               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3569                 continue;
3570               break;
3571             case LABEL_DOMAIN:
3572               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3573                 continue;
3574               break;
3575             default:
3576               break;
3577             }
3578         }
3579
3580       ++iter->next;
3581       return per_cu;
3582     }
3583
3584   return NULL;
3585 }
3586
3587 static struct symtab *
3588 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3589                    const char *name, domain_enum domain)
3590 {
3591   struct symtab *stab_best = NULL;
3592   struct mapped_index *index;
3593
3594   dw2_setup (objfile);
3595
3596   index = dwarf2_per_objfile->index_table;
3597
3598   /* index is NULL if OBJF_READNOW.  */
3599   if (index)
3600     {
3601       struct dw2_symtab_iterator iter;
3602       struct dwarf2_per_cu_data *per_cu;
3603
3604       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3605
3606       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3607         {
3608           struct symbol *sym = NULL;
3609           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3610
3611           /* Some caution must be observed with overloaded functions
3612              and methods, since the index will not contain any overload
3613              information (but NAME might contain it).  */
3614           if (stab->primary)
3615             {
3616               const struct blockvector *bv = BLOCKVECTOR (stab);
3617               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3618
3619               sym = lookup_block_symbol (block, name, domain);
3620             }
3621
3622           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3623             {
3624               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3625                 return stab;
3626
3627               stab_best = stab;
3628             }
3629
3630           /* Keep looking through other CUs.  */
3631         }
3632     }
3633
3634   return stab_best;
3635 }
3636
3637 static void
3638 dw2_print_stats (struct objfile *objfile)
3639 {
3640   int i, total, count;
3641
3642   dw2_setup (objfile);
3643   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3644   count = 0;
3645   for (i = 0; i < total; ++i)
3646     {
3647       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3648
3649       if (!per_cu->v.quick->symtab)
3650         ++count;
3651     }
3652   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3653   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3654 }
3655
3656 /* This dumps minimal information about the index.
3657    It is called via "mt print objfiles".
3658    One use is to verify .gdb_index has been loaded by the
3659    gdb.dwarf2/gdb-index.exp testcase.  */
3660
3661 static void
3662 dw2_dump (struct objfile *objfile)
3663 {
3664   dw2_setup (objfile);
3665   gdb_assert (dwarf2_per_objfile->using_index);
3666   printf_filtered (".gdb_index:");
3667   if (dwarf2_per_objfile->index_table != NULL)
3668     {
3669       printf_filtered (" version %d\n",
3670                        dwarf2_per_objfile->index_table->version);
3671     }
3672   else
3673     printf_filtered (" faked for \"readnow\"\n");
3674   printf_filtered ("\n");
3675 }
3676
3677 static void
3678 dw2_relocate (struct objfile *objfile,
3679               const struct section_offsets *new_offsets,
3680               const struct section_offsets *delta)
3681 {
3682   /* There's nothing to relocate here.  */
3683 }
3684
3685 static void
3686 dw2_expand_symtabs_for_function (struct objfile *objfile,
3687                                  const char *func_name)
3688 {
3689   struct mapped_index *index;
3690
3691   dw2_setup (objfile);
3692
3693   index = dwarf2_per_objfile->index_table;
3694
3695   /* index is NULL if OBJF_READNOW.  */
3696   if (index)
3697     {
3698       struct dw2_symtab_iterator iter;
3699       struct dwarf2_per_cu_data *per_cu;
3700
3701       /* Note: It doesn't matter what we pass for block_index here.  */
3702       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3703                             func_name);
3704
3705       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3706         dw2_instantiate_symtab (per_cu);
3707     }
3708 }
3709
3710 static void
3711 dw2_expand_all_symtabs (struct objfile *objfile)
3712 {
3713   int i;
3714
3715   dw2_setup (objfile);
3716
3717   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3718                    + dwarf2_per_objfile->n_type_units); ++i)
3719     {
3720       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3721
3722       dw2_instantiate_symtab (per_cu);
3723     }
3724 }
3725
3726 static void
3727 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3728                                   const char *fullname)
3729 {
3730   int i;
3731
3732   dw2_setup (objfile);
3733
3734   /* We don't need to consider type units here.
3735      This is only called for examining code, e.g. expand_line_sal.
3736      There can be an order of magnitude (or more) more type units
3737      than comp units, and we avoid them if we can.  */
3738
3739   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3740     {
3741       int j;
3742       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3743       struct quick_file_names *file_data;
3744
3745       /* We only need to look at symtabs not already expanded.  */
3746       if (per_cu->v.quick->symtab)
3747         continue;
3748
3749       file_data = dw2_get_file_names (per_cu);
3750       if (file_data == NULL)
3751         continue;
3752
3753       for (j = 0; j < file_data->num_file_names; ++j)
3754         {
3755           const char *this_fullname = file_data->file_names[j];
3756
3757           if (filename_cmp (this_fullname, fullname) == 0)
3758             {
3759               dw2_instantiate_symtab (per_cu);
3760               break;
3761             }
3762         }
3763     }
3764 }
3765
3766 static void
3767 dw2_map_matching_symbols (struct objfile *objfile,
3768                           const char * name, domain_enum namespace,
3769                           int global,
3770                           int (*callback) (struct block *,
3771                                            struct symbol *, void *),
3772                           void *data, symbol_compare_ftype *match,
3773                           symbol_compare_ftype *ordered_compare)
3774 {
3775   /* Currently unimplemented; used for Ada.  The function can be called if the
3776      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3777      does not look for non-Ada symbols this function should just return.  */
3778 }
3779
3780 static void
3781 dw2_expand_symtabs_matching
3782   (struct objfile *objfile,
3783    expand_symtabs_file_matcher_ftype *file_matcher,
3784    expand_symtabs_symbol_matcher_ftype *symbol_matcher,
3785    enum search_domain kind,
3786    void *data)
3787 {
3788   int i;
3789   offset_type iter;
3790   struct mapped_index *index;
3791
3792   dw2_setup (objfile);
3793
3794   /* index_table is NULL if OBJF_READNOW.  */
3795   if (!dwarf2_per_objfile->index_table)
3796     return;
3797   index = dwarf2_per_objfile->index_table;
3798
3799   if (file_matcher != NULL)
3800     {
3801       struct cleanup *cleanup;
3802       htab_t visited_found, visited_not_found;
3803
3804       visited_found = htab_create_alloc (10,
3805                                          htab_hash_pointer, htab_eq_pointer,
3806                                          NULL, xcalloc, xfree);
3807       cleanup = make_cleanup_htab_delete (visited_found);
3808       visited_not_found = htab_create_alloc (10,
3809                                              htab_hash_pointer, htab_eq_pointer,
3810                                              NULL, xcalloc, xfree);
3811       make_cleanup_htab_delete (visited_not_found);
3812
3813       /* The rule is CUs specify all the files, including those used by
3814          any TU, so there's no need to scan TUs here.  */
3815
3816       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3817         {
3818           int j;
3819           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3820           struct quick_file_names *file_data;
3821           void **slot;
3822
3823           per_cu->v.quick->mark = 0;
3824
3825           /* We only need to look at symtabs not already expanded.  */
3826           if (per_cu->v.quick->symtab)
3827             continue;
3828
3829           file_data = dw2_get_file_names (per_cu);
3830           if (file_data == NULL)
3831             continue;
3832
3833           if (htab_find (visited_not_found, file_data) != NULL)
3834             continue;
3835           else if (htab_find (visited_found, file_data) != NULL)
3836             {
3837               per_cu->v.quick->mark = 1;
3838               continue;
3839             }
3840
3841           for (j = 0; j < file_data->num_file_names; ++j)
3842             {
3843               const char *this_real_name;
3844
3845               if (file_matcher (file_data->file_names[j], data, 0))
3846                 {
3847                   per_cu->v.quick->mark = 1;
3848                   break;
3849                 }
3850
3851               /* Before we invoke realpath, which can get expensive when many
3852                  files are involved, do a quick comparison of the basenames.  */
3853               if (!basenames_may_differ
3854                   && !file_matcher (lbasename (file_data->file_names[j]),
3855                                     data, 1))
3856                 continue;
3857
3858               this_real_name = dw2_get_real_path (objfile, file_data, j);
3859               if (file_matcher (this_real_name, data, 0))
3860                 {
3861                   per_cu->v.quick->mark = 1;
3862                   break;
3863                 }
3864             }
3865
3866           slot = htab_find_slot (per_cu->v.quick->mark
3867                                  ? visited_found
3868                                  : visited_not_found,
3869                                  file_data, INSERT);
3870           *slot = file_data;
3871         }
3872
3873       do_cleanups (cleanup);
3874     }
3875
3876   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3877     {
3878       offset_type idx = 2 * iter;
3879       const char *name;
3880       offset_type *vec, vec_len, vec_idx;
3881       int global_seen = 0;
3882
3883       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3884         continue;
3885
3886       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3887
3888       if (! (*symbol_matcher) (name, data))
3889         continue;
3890
3891       /* The name was matched, now expand corresponding CUs that were
3892          marked.  */
3893       vec = (offset_type *) (index->constant_pool
3894                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3895       vec_len = MAYBE_SWAP (vec[0]);
3896       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3897         {
3898           struct dwarf2_per_cu_data *per_cu;
3899           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3900           /* This value is only valid for index versions >= 7.  */
3901           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3902           gdb_index_symbol_kind symbol_kind =
3903             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3904           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3905           /* Only check the symbol attributes if they're present.
3906              Indices prior to version 7 don't record them,
3907              and indices >= 7 may elide them for certain symbols
3908              (gold does this).  */
3909           int attrs_valid =
3910             (index->version >= 7
3911              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3912
3913           /* Work around gold/15646.  */
3914           if (attrs_valid)
3915             {
3916               if (!is_static && global_seen)
3917                 continue;
3918               if (!is_static)
3919                 global_seen = 1;
3920             }
3921
3922           /* Only check the symbol's kind if it has one.  */
3923           if (attrs_valid)
3924             {
3925               switch (kind)
3926                 {
3927                 case VARIABLES_DOMAIN:
3928                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3929                     continue;
3930                   break;
3931                 case FUNCTIONS_DOMAIN:
3932                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3933                     continue;
3934                   break;
3935                 case TYPES_DOMAIN:
3936                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3937                     continue;
3938                   break;
3939                 default:
3940                   break;
3941                 }
3942             }
3943
3944           /* Don't crash on bad data.  */
3945           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3946                            + dwarf2_per_objfile->n_type_units))
3947             {
3948               complaint (&symfile_complaints,
3949                          _(".gdb_index entry has bad CU index"
3950                            " [in module %s]"), objfile_name (objfile));
3951               continue;
3952             }
3953
3954           per_cu = dw2_get_cutu (cu_index);
3955           if (file_matcher == NULL || per_cu->v.quick->mark)
3956             dw2_instantiate_symtab (per_cu);
3957         }
3958     }
3959 }
3960
3961 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3962    symtab.  */
3963
3964 static struct symtab *
3965 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3966 {
3967   int i;
3968
3969   if (BLOCKVECTOR (symtab) != NULL
3970       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3971     return symtab;
3972
3973   if (symtab->includes == NULL)
3974     return NULL;
3975
3976   for (i = 0; symtab->includes[i]; ++i)
3977     {
3978       struct symtab *s = symtab->includes[i];
3979
3980       s = recursively_find_pc_sect_symtab (s, pc);
3981       if (s != NULL)
3982         return s;
3983     }
3984
3985   return NULL;
3986 }
3987
3988 static struct symtab *
3989 dw2_find_pc_sect_symtab (struct objfile *objfile,
3990                          struct bound_minimal_symbol msymbol,
3991                          CORE_ADDR pc,
3992                          struct obj_section *section,
3993                          int warn_if_readin)
3994 {
3995   struct dwarf2_per_cu_data *data;
3996   struct symtab *result;
3997
3998   dw2_setup (objfile);
3999
4000   if (!objfile->psymtabs_addrmap)
4001     return NULL;
4002
4003   data = addrmap_find (objfile->psymtabs_addrmap, pc);
4004   if (!data)
4005     return NULL;
4006
4007   if (warn_if_readin && data->v.quick->symtab)
4008     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4009              paddress (get_objfile_arch (objfile), pc));
4010
4011   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
4012   gdb_assert (result != NULL);
4013   return result;
4014 }
4015
4016 static void
4017 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4018                           void *data, int need_fullname)
4019 {
4020   int i;
4021   struct cleanup *cleanup;
4022   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
4023                                       NULL, xcalloc, xfree);
4024
4025   cleanup = make_cleanup_htab_delete (visited);
4026   dw2_setup (objfile);
4027
4028   /* The rule is CUs specify all the files, including those used by
4029      any TU, so there's no need to scan TUs here.
4030      We can ignore file names coming from already-expanded CUs.  */
4031
4032   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4033     {
4034       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4035
4036       if (per_cu->v.quick->symtab)
4037         {
4038           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
4039                                         INSERT);
4040
4041           *slot = per_cu->v.quick->file_names;
4042         }
4043     }
4044
4045   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4046     {
4047       int j;
4048       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4049       struct quick_file_names *file_data;
4050       void **slot;
4051
4052       /* We only need to look at symtabs not already expanded.  */
4053       if (per_cu->v.quick->symtab)
4054         continue;
4055
4056       file_data = dw2_get_file_names (per_cu);
4057       if (file_data == NULL)
4058         continue;
4059
4060       slot = htab_find_slot (visited, file_data, INSERT);
4061       if (*slot)
4062         {
4063           /* Already visited.  */
4064           continue;
4065         }
4066       *slot = file_data;
4067
4068       for (j = 0; j < file_data->num_file_names; ++j)
4069         {
4070           const char *this_real_name;
4071
4072           if (need_fullname)
4073             this_real_name = dw2_get_real_path (objfile, file_data, j);
4074           else
4075             this_real_name = NULL;
4076           (*fun) (file_data->file_names[j], this_real_name, data);
4077         }
4078     }
4079
4080   do_cleanups (cleanup);
4081 }
4082
4083 static int
4084 dw2_has_symbols (struct objfile *objfile)
4085 {
4086   return 1;
4087 }
4088
4089 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4090 {
4091   dw2_has_symbols,
4092   dw2_find_last_source_symtab,
4093   dw2_forget_cached_source_info,
4094   dw2_map_symtabs_matching_filename,
4095   dw2_lookup_symbol,
4096   dw2_print_stats,
4097   dw2_dump,
4098   dw2_relocate,
4099   dw2_expand_symtabs_for_function,
4100   dw2_expand_all_symtabs,
4101   dw2_expand_symtabs_with_fullname,
4102   dw2_map_matching_symbols,
4103   dw2_expand_symtabs_matching,
4104   dw2_find_pc_sect_symtab,
4105   dw2_map_symbol_filenames
4106 };
4107
4108 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4109    file will use psymtabs, or 1 if using the GNU index.  */
4110
4111 int
4112 dwarf2_initialize_objfile (struct objfile *objfile)
4113 {
4114   /* If we're about to read full symbols, don't bother with the
4115      indices.  In this case we also don't care if some other debug
4116      format is making psymtabs, because they are all about to be
4117      expanded anyway.  */
4118   if ((objfile->flags & OBJF_READNOW))
4119     {
4120       int i;
4121
4122       dwarf2_per_objfile->using_index = 1;
4123       create_all_comp_units (objfile);
4124       create_all_type_units (objfile);
4125       dwarf2_per_objfile->quick_file_names_table =
4126         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4127
4128       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4129                        + dwarf2_per_objfile->n_type_units); ++i)
4130         {
4131           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4132
4133           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4134                                             struct dwarf2_per_cu_quick_data);
4135         }
4136
4137       /* Return 1 so that gdb sees the "quick" functions.  However,
4138          these functions will be no-ops because we will have expanded
4139          all symtabs.  */
4140       return 1;
4141     }
4142
4143   if (dwarf2_read_index (objfile))
4144     return 1;
4145
4146   return 0;
4147 }
4148
4149 \f
4150
4151 /* Build a partial symbol table.  */
4152
4153 void
4154 dwarf2_build_psymtabs (struct objfile *objfile)
4155 {
4156   volatile struct gdb_exception except;
4157
4158   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4159     {
4160       init_psymbol_list (objfile, 1024);
4161     }
4162
4163   TRY_CATCH (except, RETURN_MASK_ERROR)
4164     {
4165       /* This isn't really ideal: all the data we allocate on the
4166          objfile's obstack is still uselessly kept around.  However,
4167          freeing it seems unsafe.  */
4168       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
4169
4170       dwarf2_build_psymtabs_hard (objfile);
4171       discard_cleanups (cleanups);
4172     }
4173   if (except.reason < 0)
4174     exception_print (gdb_stderr, except);
4175 }
4176
4177 /* Return the total length of the CU described by HEADER.  */
4178
4179 static unsigned int
4180 get_cu_length (const struct comp_unit_head *header)
4181 {
4182   return header->initial_length_size + header->length;
4183 }
4184
4185 /* Return TRUE if OFFSET is within CU_HEADER.  */
4186
4187 static inline int
4188 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
4189 {
4190   sect_offset bottom = { cu_header->offset.sect_off };
4191   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
4192
4193   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
4194 }
4195
4196 /* Find the base address of the compilation unit for range lists and
4197    location lists.  It will normally be specified by DW_AT_low_pc.
4198    In DWARF-3 draft 4, the base address could be overridden by
4199    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4200    compilation units with discontinuous ranges.  */
4201
4202 static void
4203 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4204 {
4205   struct attribute *attr;
4206
4207   cu->base_known = 0;
4208   cu->base_address = 0;
4209
4210   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4211   if (attr)
4212     {
4213       cu->base_address = attr_value_as_address (attr);
4214       cu->base_known = 1;
4215     }
4216   else
4217     {
4218       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4219       if (attr)
4220         {
4221           cu->base_address = attr_value_as_address (attr);
4222           cu->base_known = 1;
4223         }
4224     }
4225 }
4226
4227 /* Read in the comp unit header information from the debug_info at info_ptr.
4228    NOTE: This leaves members offset, first_die_offset to be filled in
4229    by the caller.  */
4230
4231 static const gdb_byte *
4232 read_comp_unit_head (struct comp_unit_head *cu_header,
4233                      const gdb_byte *info_ptr, bfd *abfd)
4234 {
4235   int signed_addr;
4236   unsigned int bytes_read;
4237
4238   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4239   cu_header->initial_length_size = bytes_read;
4240   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4241   info_ptr += bytes_read;
4242   cu_header->version = read_2_bytes (abfd, info_ptr);
4243   info_ptr += 2;
4244   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
4245                                              &bytes_read);
4246   info_ptr += bytes_read;
4247   cu_header->addr_size = read_1_byte (abfd, info_ptr);
4248   info_ptr += 1;
4249   signed_addr = bfd_get_sign_extend_vma (abfd);
4250   if (signed_addr < 0)
4251     internal_error (__FILE__, __LINE__,
4252                     _("read_comp_unit_head: dwarf from non elf file"));
4253   cu_header->signed_addr_p = signed_addr;
4254
4255   return info_ptr;
4256 }
4257
4258 /* Helper function that returns the proper abbrev section for
4259    THIS_CU.  */
4260
4261 static struct dwarf2_section_info *
4262 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4263 {
4264   struct dwarf2_section_info *abbrev;
4265
4266   if (this_cu->is_dwz)
4267     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4268   else
4269     abbrev = &dwarf2_per_objfile->abbrev;
4270
4271   return abbrev;
4272 }
4273
4274 /* Subroutine of read_and_check_comp_unit_head and
4275    read_and_check_type_unit_head to simplify them.
4276    Perform various error checking on the header.  */
4277
4278 static void
4279 error_check_comp_unit_head (struct comp_unit_head *header,
4280                             struct dwarf2_section_info *section,
4281                             struct dwarf2_section_info *abbrev_section)
4282 {
4283   bfd *abfd = get_section_bfd_owner (section);
4284   const char *filename = get_section_file_name (section);
4285
4286   if (header->version != 2 && header->version != 3 && header->version != 4)
4287     error (_("Dwarf Error: wrong version in compilation unit header "
4288            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4289            filename);
4290
4291   if (header->abbrev_offset.sect_off
4292       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4293     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4294            "(offset 0x%lx + 6) [in module %s]"),
4295            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4296            filename);
4297
4298   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4299      avoid potential 32-bit overflow.  */
4300   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4301       > section->size)
4302     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4303            "(offset 0x%lx + 0) [in module %s]"),
4304            (long) header->length, (long) header->offset.sect_off,
4305            filename);
4306 }
4307
4308 /* Read in a CU/TU header and perform some basic error checking.
4309    The contents of the header are stored in HEADER.
4310    The result is a pointer to the start of the first DIE.  */
4311
4312 static const gdb_byte *
4313 read_and_check_comp_unit_head (struct comp_unit_head *header,
4314                                struct dwarf2_section_info *section,
4315                                struct dwarf2_section_info *abbrev_section,
4316                                const gdb_byte *info_ptr,
4317                                int is_debug_types_section)
4318 {
4319   const gdb_byte *beg_of_comp_unit = info_ptr;
4320   bfd *abfd = get_section_bfd_owner (section);
4321
4322   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4323
4324   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4325
4326   /* If we're reading a type unit, skip over the signature and
4327      type_offset fields.  */
4328   if (is_debug_types_section)
4329     info_ptr += 8 /*signature*/ + header->offset_size;
4330
4331   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4332
4333   error_check_comp_unit_head (header, section, abbrev_section);
4334
4335   return info_ptr;
4336 }
4337
4338 /* Read in the types comp unit header information from .debug_types entry at
4339    types_ptr.  The result is a pointer to one past the end of the header.  */
4340
4341 static const gdb_byte *
4342 read_and_check_type_unit_head (struct comp_unit_head *header,
4343                                struct dwarf2_section_info *section,
4344                                struct dwarf2_section_info *abbrev_section,
4345                                const gdb_byte *info_ptr,
4346                                ULONGEST *signature,
4347                                cu_offset *type_offset_in_tu)
4348 {
4349   const gdb_byte *beg_of_comp_unit = info_ptr;
4350   bfd *abfd = get_section_bfd_owner (section);
4351
4352   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4353
4354   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4355
4356   /* If we're reading a type unit, skip over the signature and
4357      type_offset fields.  */
4358   if (signature != NULL)
4359     *signature = read_8_bytes (abfd, info_ptr);
4360   info_ptr += 8;
4361   if (type_offset_in_tu != NULL)
4362     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4363                                                header->offset_size);
4364   info_ptr += header->offset_size;
4365
4366   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4367
4368   error_check_comp_unit_head (header, section, abbrev_section);
4369
4370   return info_ptr;
4371 }
4372
4373 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4374
4375 static sect_offset
4376 read_abbrev_offset (struct dwarf2_section_info *section,
4377                     sect_offset offset)
4378 {
4379   bfd *abfd = get_section_bfd_owner (section);
4380   const gdb_byte *info_ptr;
4381   unsigned int length, initial_length_size, offset_size;
4382   sect_offset abbrev_offset;
4383
4384   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4385   info_ptr = section->buffer + offset.sect_off;
4386   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4387   offset_size = initial_length_size == 4 ? 4 : 8;
4388   info_ptr += initial_length_size + 2 /*version*/;
4389   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4390   return abbrev_offset;
4391 }
4392
4393 /* Allocate a new partial symtab for file named NAME and mark this new
4394    partial symtab as being an include of PST.  */
4395
4396 static void
4397 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4398                                struct objfile *objfile)
4399 {
4400   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4401
4402   if (!IS_ABSOLUTE_PATH (subpst->filename))
4403     {
4404       /* It shares objfile->objfile_obstack.  */
4405       subpst->dirname = pst->dirname;
4406     }
4407
4408   subpst->section_offsets = pst->section_offsets;
4409   subpst->textlow = 0;
4410   subpst->texthigh = 0;
4411
4412   subpst->dependencies = (struct partial_symtab **)
4413     obstack_alloc (&objfile->objfile_obstack,
4414                    sizeof (struct partial_symtab *));
4415   subpst->dependencies[0] = pst;
4416   subpst->number_of_dependencies = 1;
4417
4418   subpst->globals_offset = 0;
4419   subpst->n_global_syms = 0;
4420   subpst->statics_offset = 0;
4421   subpst->n_static_syms = 0;
4422   subpst->symtab = NULL;
4423   subpst->read_symtab = pst->read_symtab;
4424   subpst->readin = 0;
4425
4426   /* No private part is necessary for include psymtabs.  This property
4427      can be used to differentiate between such include psymtabs and
4428      the regular ones.  */
4429   subpst->read_symtab_private = NULL;
4430 }
4431
4432 /* Read the Line Number Program data and extract the list of files
4433    included by the source file represented by PST.  Build an include
4434    partial symtab for each of these included files.  */
4435
4436 static void
4437 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4438                                struct die_info *die,
4439                                struct partial_symtab *pst)
4440 {
4441   struct line_header *lh = NULL;
4442   struct attribute *attr;
4443
4444   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4445   if (attr)
4446     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4447   if (lh == NULL)
4448     return;  /* No linetable, so no includes.  */
4449
4450   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4451   dwarf_decode_lines (lh, pst->dirname, cu, pst);
4452
4453   free_line_header (lh);
4454 }
4455
4456 static hashval_t
4457 hash_signatured_type (const void *item)
4458 {
4459   const struct signatured_type *sig_type = item;
4460
4461   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4462   return sig_type->signature;
4463 }
4464
4465 static int
4466 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4467 {
4468   const struct signatured_type *lhs = item_lhs;
4469   const struct signatured_type *rhs = item_rhs;
4470
4471   return lhs->signature == rhs->signature;
4472 }
4473
4474 /* Allocate a hash table for signatured types.  */
4475
4476 static htab_t
4477 allocate_signatured_type_table (struct objfile *objfile)
4478 {
4479   return htab_create_alloc_ex (41,
4480                                hash_signatured_type,
4481                                eq_signatured_type,
4482                                NULL,
4483                                &objfile->objfile_obstack,
4484                                hashtab_obstack_allocate,
4485                                dummy_obstack_deallocate);
4486 }
4487
4488 /* A helper function to add a signatured type CU to a table.  */
4489
4490 static int
4491 add_signatured_type_cu_to_table (void **slot, void *datum)
4492 {
4493   struct signatured_type *sigt = *slot;
4494   struct signatured_type ***datap = datum;
4495
4496   **datap = sigt;
4497   ++*datap;
4498
4499   return 1;
4500 }
4501
4502 /* Create the hash table of all entries in the .debug_types
4503    (or .debug_types.dwo) section(s).
4504    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4505    otherwise it is NULL.
4506
4507    The result is a pointer to the hash table or NULL if there are no types.
4508
4509    Note: This function processes DWO files only, not DWP files.  */
4510
4511 static htab_t
4512 create_debug_types_hash_table (struct dwo_file *dwo_file,
4513                                VEC (dwarf2_section_info_def) *types)
4514 {
4515   struct objfile *objfile = dwarf2_per_objfile->objfile;
4516   htab_t types_htab = NULL;
4517   int ix;
4518   struct dwarf2_section_info *section;
4519   struct dwarf2_section_info *abbrev_section;
4520
4521   if (VEC_empty (dwarf2_section_info_def, types))
4522     return NULL;
4523
4524   abbrev_section = (dwo_file != NULL
4525                     ? &dwo_file->sections.abbrev
4526                     : &dwarf2_per_objfile->abbrev);
4527
4528   if (dwarf2_read_debug)
4529     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4530                         dwo_file ? ".dwo" : "",
4531                         get_section_file_name (abbrev_section));
4532
4533   for (ix = 0;
4534        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4535        ++ix)
4536     {
4537       bfd *abfd;
4538       const gdb_byte *info_ptr, *end_ptr;
4539
4540       dwarf2_read_section (objfile, section);
4541       info_ptr = section->buffer;
4542
4543       if (info_ptr == NULL)
4544         continue;
4545
4546       /* We can't set abfd until now because the section may be empty or
4547          not present, in which case the bfd is unknown.  */
4548       abfd = get_section_bfd_owner (section);
4549
4550       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4551          because we don't need to read any dies: the signature is in the
4552          header.  */
4553
4554       end_ptr = info_ptr + section->size;
4555       while (info_ptr < end_ptr)
4556         {
4557           sect_offset offset;
4558           cu_offset type_offset_in_tu;
4559           ULONGEST signature;
4560           struct signatured_type *sig_type;
4561           struct dwo_unit *dwo_tu;
4562           void **slot;
4563           const gdb_byte *ptr = info_ptr;
4564           struct comp_unit_head header;
4565           unsigned int length;
4566
4567           offset.sect_off = ptr - section->buffer;
4568
4569           /* We need to read the type's signature in order to build the hash
4570              table, but we don't need anything else just yet.  */
4571
4572           ptr = read_and_check_type_unit_head (&header, section,
4573                                                abbrev_section, ptr,
4574                                                &signature, &type_offset_in_tu);
4575
4576           length = get_cu_length (&header);
4577
4578           /* Skip dummy type units.  */
4579           if (ptr >= info_ptr + length
4580               || peek_abbrev_code (abfd, ptr) == 0)
4581             {
4582               info_ptr += length;
4583               continue;
4584             }
4585
4586           if (types_htab == NULL)
4587             {
4588               if (dwo_file)
4589                 types_htab = allocate_dwo_unit_table (objfile);
4590               else
4591                 types_htab = allocate_signatured_type_table (objfile);
4592             }
4593
4594           if (dwo_file)
4595             {
4596               sig_type = NULL;
4597               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4598                                        struct dwo_unit);
4599               dwo_tu->dwo_file = dwo_file;
4600               dwo_tu->signature = signature;
4601               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4602               dwo_tu->section = section;
4603               dwo_tu->offset = offset;
4604               dwo_tu->length = length;
4605             }
4606           else
4607             {
4608               /* N.B.: type_offset is not usable if this type uses a DWO file.
4609                  The real type_offset is in the DWO file.  */
4610               dwo_tu = NULL;
4611               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4612                                          struct signatured_type);
4613               sig_type->signature = signature;
4614               sig_type->type_offset_in_tu = type_offset_in_tu;
4615               sig_type->per_cu.objfile = objfile;
4616               sig_type->per_cu.is_debug_types = 1;
4617               sig_type->per_cu.section = section;
4618               sig_type->per_cu.offset = offset;
4619               sig_type->per_cu.length = length;
4620             }
4621
4622           slot = htab_find_slot (types_htab,
4623                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4624                                  INSERT);
4625           gdb_assert (slot != NULL);
4626           if (*slot != NULL)
4627             {
4628               sect_offset dup_offset;
4629
4630               if (dwo_file)
4631                 {
4632                   const struct dwo_unit *dup_tu = *slot;
4633
4634                   dup_offset = dup_tu->offset;
4635                 }
4636               else
4637                 {
4638                   const struct signatured_type *dup_tu = *slot;
4639
4640                   dup_offset = dup_tu->per_cu.offset;
4641                 }
4642
4643               complaint (&symfile_complaints,
4644                          _("debug type entry at offset 0x%x is duplicate to"
4645                            " the entry at offset 0x%x, signature %s"),
4646                          offset.sect_off, dup_offset.sect_off,
4647                          hex_string (signature));
4648             }
4649           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4650
4651           if (dwarf2_read_debug > 1)
4652             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4653                                 offset.sect_off,
4654                                 hex_string (signature));
4655
4656           info_ptr += length;
4657         }
4658     }
4659
4660   return types_htab;
4661 }
4662
4663 /* Create the hash table of all entries in the .debug_types section,
4664    and initialize all_type_units.
4665    The result is zero if there is an error (e.g. missing .debug_types section),
4666    otherwise non-zero.  */
4667
4668 static int
4669 create_all_type_units (struct objfile *objfile)
4670 {
4671   htab_t types_htab;
4672   struct signatured_type **iter;
4673
4674   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4675   if (types_htab == NULL)
4676     {
4677       dwarf2_per_objfile->signatured_types = NULL;
4678       return 0;
4679     }
4680
4681   dwarf2_per_objfile->signatured_types = types_htab;
4682
4683   dwarf2_per_objfile->n_type_units
4684     = dwarf2_per_objfile->n_allocated_type_units
4685     = htab_elements (types_htab);
4686   dwarf2_per_objfile->all_type_units
4687     = xmalloc (dwarf2_per_objfile->n_type_units
4688                * sizeof (struct signatured_type *));
4689   iter = &dwarf2_per_objfile->all_type_units[0];
4690   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4691   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4692               == dwarf2_per_objfile->n_type_units);
4693
4694   return 1;
4695 }
4696
4697 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
4698    If SLOT is non-NULL, it is the entry to use in the hash table.
4699    Otherwise we find one.  */
4700
4701 static struct signatured_type *
4702 add_type_unit (ULONGEST sig, void **slot)
4703 {
4704   struct objfile *objfile = dwarf2_per_objfile->objfile;
4705   int n_type_units = dwarf2_per_objfile->n_type_units;
4706   struct signatured_type *sig_type;
4707
4708   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
4709   ++n_type_units;
4710   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
4711     {
4712       if (dwarf2_per_objfile->n_allocated_type_units == 0)
4713         dwarf2_per_objfile->n_allocated_type_units = 1;
4714       dwarf2_per_objfile->n_allocated_type_units *= 2;
4715       dwarf2_per_objfile->all_type_units
4716         = xrealloc (dwarf2_per_objfile->all_type_units,
4717                     dwarf2_per_objfile->n_allocated_type_units
4718                     * sizeof (struct signatured_type *));
4719       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
4720     }
4721   dwarf2_per_objfile->n_type_units = n_type_units;
4722
4723   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4724                              struct signatured_type);
4725   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4726   sig_type->signature = sig;
4727   sig_type->per_cu.is_debug_types = 1;
4728   if (dwarf2_per_objfile->using_index)
4729     {
4730       sig_type->per_cu.v.quick =
4731         OBSTACK_ZALLOC (&objfile->objfile_obstack,
4732                         struct dwarf2_per_cu_quick_data);
4733     }
4734
4735   if (slot == NULL)
4736     {
4737       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4738                              sig_type, INSERT);
4739     }
4740   gdb_assert (*slot == NULL);
4741   *slot = sig_type;
4742   /* The rest of sig_type must be filled in by the caller.  */
4743   return sig_type;
4744 }
4745
4746 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4747    Fill in SIG_ENTRY with DWO_ENTRY.  */
4748
4749 static void
4750 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4751                                   struct signatured_type *sig_entry,
4752                                   struct dwo_unit *dwo_entry)
4753 {
4754   /* Make sure we're not clobbering something we don't expect to.  */
4755   gdb_assert (! sig_entry->per_cu.queued);
4756   gdb_assert (sig_entry->per_cu.cu == NULL);
4757   if (dwarf2_per_objfile->using_index)
4758     {
4759       gdb_assert (sig_entry->per_cu.v.quick != NULL);
4760       gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4761     }
4762   else
4763       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
4764   gdb_assert (sig_entry->signature == dwo_entry->signature);
4765   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4766   gdb_assert (sig_entry->type_unit_group == NULL);
4767   gdb_assert (sig_entry->dwo_unit == NULL);
4768
4769   sig_entry->per_cu.section = dwo_entry->section;
4770   sig_entry->per_cu.offset = dwo_entry->offset;
4771   sig_entry->per_cu.length = dwo_entry->length;
4772   sig_entry->per_cu.reading_dwo_directly = 1;
4773   sig_entry->per_cu.objfile = objfile;
4774   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4775   sig_entry->dwo_unit = dwo_entry;
4776 }
4777
4778 /* Subroutine of lookup_signatured_type.
4779    If we haven't read the TU yet, create the signatured_type data structure
4780    for a TU to be read in directly from a DWO file, bypassing the stub.
4781    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4782    using .gdb_index, then when reading a CU we want to stay in the DWO file
4783    containing that CU.  Otherwise we could end up reading several other DWO
4784    files (due to comdat folding) to process the transitive closure of all the
4785    mentioned TUs, and that can be slow.  The current DWO file will have every
4786    type signature that it needs.
4787    We only do this for .gdb_index because in the psymtab case we already have
4788    to read all the DWOs to build the type unit groups.  */
4789
4790 static struct signatured_type *
4791 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4792 {
4793   struct objfile *objfile = dwarf2_per_objfile->objfile;
4794   struct dwo_file *dwo_file;
4795   struct dwo_unit find_dwo_entry, *dwo_entry;
4796   struct signatured_type find_sig_entry, *sig_entry;
4797   void **slot;
4798
4799   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4800
4801   /* If TU skeletons have been removed then we may not have read in any
4802      TUs yet.  */
4803   if (dwarf2_per_objfile->signatured_types == NULL)
4804     {
4805       dwarf2_per_objfile->signatured_types
4806         = allocate_signatured_type_table (objfile);
4807     }
4808
4809   /* We only ever need to read in one copy of a signatured type.
4810      Use the global signatured_types array to do our own comdat-folding
4811      of types.  If this is the first time we're reading this TU, and
4812      the TU has an entry in .gdb_index, replace the recorded data from
4813      .gdb_index with this TU.  */
4814
4815   find_sig_entry.signature = sig;
4816   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4817                          &find_sig_entry, INSERT);
4818   sig_entry = *slot;
4819
4820   /* We can get here with the TU already read, *or* in the process of being
4821      read.  Don't reassign the global entry to point to this DWO if that's
4822      the case.  Also note that if the TU is already being read, it may not
4823      have come from a DWO, the program may be a mix of Fission-compiled
4824      code and non-Fission-compiled code.  */
4825
4826   /* Have we already tried to read this TU?
4827      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
4828      needn't exist in the global table yet).  */
4829   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
4830     return sig_entry;
4831
4832   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4833      dwo_unit of the TU itself.  */
4834   dwo_file = cu->dwo_unit->dwo_file;
4835
4836   /* Ok, this is the first time we're reading this TU.  */
4837   if (dwo_file->tus == NULL)
4838     return NULL;
4839   find_dwo_entry.signature = sig;
4840   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4841   if (dwo_entry == NULL)
4842     return NULL;
4843
4844   /* If the global table doesn't have an entry for this TU, add one.  */
4845   if (sig_entry == NULL)
4846     sig_entry = add_type_unit (sig, slot);
4847
4848   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4849   sig_entry->per_cu.tu_read = 1;
4850   return sig_entry;
4851 }
4852
4853 /* Subroutine of lookup_signatured_type.
4854    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4855    then try the DWP file.  If the TU stub (skeleton) has been removed then
4856    it won't be in .gdb_index.  */
4857
4858 static struct signatured_type *
4859 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4860 {
4861   struct objfile *objfile = dwarf2_per_objfile->objfile;
4862   struct dwp_file *dwp_file = get_dwp_file ();
4863   struct dwo_unit *dwo_entry;
4864   struct signatured_type find_sig_entry, *sig_entry;
4865   void **slot;
4866
4867   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4868   gdb_assert (dwp_file != NULL);
4869
4870   /* If TU skeletons have been removed then we may not have read in any
4871      TUs yet.  */
4872   if (dwarf2_per_objfile->signatured_types == NULL)
4873     {
4874       dwarf2_per_objfile->signatured_types
4875         = allocate_signatured_type_table (objfile);
4876     }
4877
4878   find_sig_entry.signature = sig;
4879   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4880                          &find_sig_entry, INSERT);
4881   sig_entry = *slot;
4882
4883   /* Have we already tried to read this TU?
4884      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
4885      needn't exist in the global table yet).  */
4886   if (sig_entry != NULL)
4887     return sig_entry;
4888
4889   if (dwp_file->tus == NULL)
4890     return NULL;
4891   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
4892                                       sig, 1 /* is_debug_types */);
4893   if (dwo_entry == NULL)
4894     return NULL;
4895
4896   sig_entry = add_type_unit (sig, slot);
4897   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4898
4899   return sig_entry;
4900 }
4901
4902 /* Lookup a signature based type for DW_FORM_ref_sig8.
4903    Returns NULL if signature SIG is not present in the table.
4904    It is up to the caller to complain about this.  */
4905
4906 static struct signatured_type *
4907 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4908 {
4909   if (cu->dwo_unit
4910       && dwarf2_per_objfile->using_index)
4911     {
4912       /* We're in a DWO/DWP file, and we're using .gdb_index.
4913          These cases require special processing.  */
4914       if (get_dwp_file () == NULL)
4915         return lookup_dwo_signatured_type (cu, sig);
4916       else
4917         return lookup_dwp_signatured_type (cu, sig);
4918     }
4919   else
4920     {
4921       struct signatured_type find_entry, *entry;
4922
4923       if (dwarf2_per_objfile->signatured_types == NULL)
4924         return NULL;
4925       find_entry.signature = sig;
4926       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4927       return entry;
4928     }
4929 }
4930 \f
4931 /* Low level DIE reading support.  */
4932
4933 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4934
4935 static void
4936 init_cu_die_reader (struct die_reader_specs *reader,
4937                     struct dwarf2_cu *cu,
4938                     struct dwarf2_section_info *section,
4939                     struct dwo_file *dwo_file)
4940 {
4941   gdb_assert (section->readin && section->buffer != NULL);
4942   reader->abfd = get_section_bfd_owner (section);
4943   reader->cu = cu;
4944   reader->dwo_file = dwo_file;
4945   reader->die_section = section;
4946   reader->buffer = section->buffer;
4947   reader->buffer_end = section->buffer + section->size;
4948   reader->comp_dir = NULL;
4949 }
4950
4951 /* Subroutine of init_cutu_and_read_dies to simplify it.
4952    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4953    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4954    already.
4955
4956    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4957    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4958    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4959    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4960    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
4961    STUB_COMP_DIR may be non-NULL.
4962    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4963    are filled in with the info of the DIE from the DWO file.
4964    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4965    provided an abbrev table to use.
4966    The result is non-zero if a valid (non-dummy) DIE was found.  */
4967
4968 static int
4969 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4970                         struct dwo_unit *dwo_unit,
4971                         int abbrev_table_provided,
4972                         struct die_info *stub_comp_unit_die,
4973                         const char *stub_comp_dir,
4974                         struct die_reader_specs *result_reader,
4975                         const gdb_byte **result_info_ptr,
4976                         struct die_info **result_comp_unit_die,
4977                         int *result_has_children)
4978 {
4979   struct objfile *objfile = dwarf2_per_objfile->objfile;
4980   struct dwarf2_cu *cu = this_cu->cu;
4981   struct dwarf2_section_info *section;
4982   bfd *abfd;
4983   const gdb_byte *begin_info_ptr, *info_ptr;
4984   ULONGEST signature; /* Or dwo_id.  */
4985   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4986   int i,num_extra_attrs;
4987   struct dwarf2_section_info *dwo_abbrev_section;
4988   struct attribute *attr;
4989   struct die_info *comp_unit_die;
4990
4991   /* At most one of these may be provided.  */
4992   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
4993
4994   /* These attributes aren't processed until later:
4995      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4996      DW_AT_comp_dir is used now, to find the DWO file, but it is also
4997      referenced later.  However, these attributes are found in the stub
4998      which we won't have later.  In order to not impose this complication
4999      on the rest of the code, we read them here and copy them to the
5000      DWO CU/TU die.  */
5001
5002   stmt_list = NULL;
5003   low_pc = NULL;
5004   high_pc = NULL;
5005   ranges = NULL;
5006   comp_dir = NULL;
5007
5008   if (stub_comp_unit_die != NULL)
5009     {
5010       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5011          DWO file.  */
5012       if (! this_cu->is_debug_types)
5013         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5014       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5015       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5016       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5017       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5018
5019       /* There should be a DW_AT_addr_base attribute here (if needed).
5020          We need the value before we can process DW_FORM_GNU_addr_index.  */
5021       cu->addr_base = 0;
5022       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5023       if (attr)
5024         cu->addr_base = DW_UNSND (attr);
5025
5026       /* There should be a DW_AT_ranges_base attribute here (if needed).
5027          We need the value before we can process DW_AT_ranges.  */
5028       cu->ranges_base = 0;
5029       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5030       if (attr)
5031         cu->ranges_base = DW_UNSND (attr);
5032     }
5033   else if (stub_comp_dir != NULL)
5034     {
5035       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5036       comp_dir = (struct attribute *)
5037         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
5038       comp_dir->name = DW_AT_comp_dir;
5039       comp_dir->form = DW_FORM_string;
5040       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5041       DW_STRING (comp_dir) = stub_comp_dir;
5042     }
5043
5044   /* Set up for reading the DWO CU/TU.  */
5045   cu->dwo_unit = dwo_unit;
5046   section = dwo_unit->section;
5047   dwarf2_read_section (objfile, section);
5048   abfd = get_section_bfd_owner (section);
5049   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
5050   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5051   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5052
5053   if (this_cu->is_debug_types)
5054     {
5055       ULONGEST header_signature;
5056       cu_offset type_offset_in_tu;
5057       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5058
5059       info_ptr = read_and_check_type_unit_head (&cu->header, section,
5060                                                 dwo_abbrev_section,
5061                                                 info_ptr,
5062                                                 &header_signature,
5063                                                 &type_offset_in_tu);
5064       /* This is not an assert because it can be caused by bad debug info.  */
5065       if (sig_type->signature != header_signature)
5066         {
5067           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5068                    " TU at offset 0x%x [in module %s]"),
5069                  hex_string (sig_type->signature),
5070                  hex_string (header_signature),
5071                  dwo_unit->offset.sect_off,
5072                  bfd_get_filename (abfd));
5073         }
5074       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5075       /* For DWOs coming from DWP files, we don't know the CU length
5076          nor the type's offset in the TU until now.  */
5077       dwo_unit->length = get_cu_length (&cu->header);
5078       dwo_unit->type_offset_in_tu = type_offset_in_tu;
5079
5080       /* Establish the type offset that can be used to lookup the type.
5081          For DWO files, we don't know it until now.  */
5082       sig_type->type_offset_in_section.sect_off =
5083         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
5084     }
5085   else
5086     {
5087       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5088                                                 dwo_abbrev_section,
5089                                                 info_ptr, 0);
5090       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5091       /* For DWOs coming from DWP files, we don't know the CU length
5092          until now.  */
5093       dwo_unit->length = get_cu_length (&cu->header);
5094     }
5095
5096   /* Replace the CU's original abbrev table with the DWO's.
5097      Reminder: We can't read the abbrev table until we've read the header.  */
5098   if (abbrev_table_provided)
5099     {
5100       /* Don't free the provided abbrev table, the caller of
5101          init_cutu_and_read_dies owns it.  */
5102       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5103       /* Ensure the DWO abbrev table gets freed.  */
5104       make_cleanup (dwarf2_free_abbrev_table, cu);
5105     }
5106   else
5107     {
5108       dwarf2_free_abbrev_table (cu);
5109       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5110       /* Leave any existing abbrev table cleanup as is.  */
5111     }
5112
5113   /* Read in the die, but leave space to copy over the attributes
5114      from the stub.  This has the benefit of simplifying the rest of
5115      the code - all the work to maintain the illusion of a single
5116      DW_TAG_{compile,type}_unit DIE is done here.  */
5117   num_extra_attrs = ((stmt_list != NULL)
5118                      + (low_pc != NULL)
5119                      + (high_pc != NULL)
5120                      + (ranges != NULL)
5121                      + (comp_dir != NULL));
5122   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5123                               result_has_children, num_extra_attrs);
5124
5125   /* Copy over the attributes from the stub to the DIE we just read in.  */
5126   comp_unit_die = *result_comp_unit_die;
5127   i = comp_unit_die->num_attrs;
5128   if (stmt_list != NULL)
5129     comp_unit_die->attrs[i++] = *stmt_list;
5130   if (low_pc != NULL)
5131     comp_unit_die->attrs[i++] = *low_pc;
5132   if (high_pc != NULL)
5133     comp_unit_die->attrs[i++] = *high_pc;
5134   if (ranges != NULL)
5135     comp_unit_die->attrs[i++] = *ranges;
5136   if (comp_dir != NULL)
5137     comp_unit_die->attrs[i++] = *comp_dir;
5138   comp_unit_die->num_attrs += num_extra_attrs;
5139
5140   if (dwarf2_die_debug)
5141     {
5142       fprintf_unfiltered (gdb_stdlog,
5143                           "Read die from %s@0x%x of %s:\n",
5144                           get_section_name (section),
5145                           (unsigned) (begin_info_ptr - section->buffer),
5146                           bfd_get_filename (abfd));
5147       dump_die (comp_unit_die, dwarf2_die_debug);
5148     }
5149
5150   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5151      TUs by skipping the stub and going directly to the entry in the DWO file.
5152      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5153      to get it via circuitous means.  Blech.  */
5154   if (comp_dir != NULL)
5155     result_reader->comp_dir = DW_STRING (comp_dir);
5156
5157   /* Skip dummy compilation units.  */
5158   if (info_ptr >= begin_info_ptr + dwo_unit->length
5159       || peek_abbrev_code (abfd, info_ptr) == 0)
5160     return 0;
5161
5162   *result_info_ptr = info_ptr;
5163   return 1;
5164 }
5165
5166 /* Subroutine of init_cutu_and_read_dies to simplify it.
5167    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5168    Returns NULL if the specified DWO unit cannot be found.  */
5169
5170 static struct dwo_unit *
5171 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5172                  struct die_info *comp_unit_die)
5173 {
5174   struct dwarf2_cu *cu = this_cu->cu;
5175   struct attribute *attr;
5176   ULONGEST signature;
5177   struct dwo_unit *dwo_unit;
5178   const char *comp_dir, *dwo_name;
5179
5180   gdb_assert (cu != NULL);
5181
5182   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5183   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5184   gdb_assert (attr != NULL);
5185   dwo_name = DW_STRING (attr);
5186   comp_dir = NULL;
5187   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5188   if (attr)
5189     comp_dir = DW_STRING (attr);
5190
5191   if (this_cu->is_debug_types)
5192     {
5193       struct signatured_type *sig_type;
5194
5195       /* Since this_cu is the first member of struct signatured_type,
5196          we can go from a pointer to one to a pointer to the other.  */
5197       sig_type = (struct signatured_type *) this_cu;
5198       signature = sig_type->signature;
5199       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5200     }
5201   else
5202     {
5203       struct attribute *attr;
5204
5205       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5206       if (! attr)
5207         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5208                  " [in module %s]"),
5209                dwo_name, objfile_name (this_cu->objfile));
5210       signature = DW_UNSND (attr);
5211       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5212                                        signature);
5213     }
5214
5215   return dwo_unit;
5216 }
5217
5218 /* Subroutine of init_cutu_and_read_dies to simplify it.
5219    See it for a description of the parameters.
5220    Read a TU directly from a DWO file, bypassing the stub.
5221
5222    Note: This function could be a little bit simpler if we shared cleanups
5223    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5224    to do, so we keep this function self-contained.  Or we could move this
5225    into our caller, but it's complex enough already.  */
5226
5227 static void
5228 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5229                            int use_existing_cu, int keep,
5230                            die_reader_func_ftype *die_reader_func,
5231                            void *data)
5232 {
5233   struct dwarf2_cu *cu;
5234   struct signatured_type *sig_type;
5235   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5236   struct die_reader_specs reader;
5237   const gdb_byte *info_ptr;
5238   struct die_info *comp_unit_die;
5239   int has_children;
5240
5241   /* Verify we can do the following downcast, and that we have the
5242      data we need.  */
5243   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5244   sig_type = (struct signatured_type *) this_cu;
5245   gdb_assert (sig_type->dwo_unit != NULL);
5246
5247   cleanups = make_cleanup (null_cleanup, NULL);
5248
5249   if (use_existing_cu && this_cu->cu != NULL)
5250     {
5251       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5252       cu = this_cu->cu;
5253       /* There's no need to do the rereading_dwo_cu handling that
5254          init_cutu_and_read_dies does since we don't read the stub.  */
5255     }
5256   else
5257     {
5258       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5259       gdb_assert (this_cu->cu == NULL);
5260       cu = xmalloc (sizeof (*cu));
5261       init_one_comp_unit (cu, this_cu);
5262       /* If an error occurs while loading, release our storage.  */
5263       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5264     }
5265
5266   /* A future optimization, if needed, would be to use an existing
5267      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5268      could share abbrev tables.  */
5269
5270   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5271                               0 /* abbrev_table_provided */,
5272                               NULL /* stub_comp_unit_die */,
5273                               sig_type->dwo_unit->dwo_file->comp_dir,
5274                               &reader, &info_ptr,
5275                               &comp_unit_die, &has_children) == 0)
5276     {
5277       /* Dummy die.  */
5278       do_cleanups (cleanups);
5279       return;
5280     }
5281
5282   /* All the "real" work is done here.  */
5283   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5284
5285   /* This duplicates the code in init_cutu_and_read_dies,
5286      but the alternative is making the latter more complex.
5287      This function is only for the special case of using DWO files directly:
5288      no point in overly complicating the general case just to handle this.  */
5289   if (free_cu_cleanup != NULL)
5290     {
5291       if (keep)
5292         {
5293           /* We've successfully allocated this compilation unit.  Let our
5294              caller clean it up when finished with it.  */
5295           discard_cleanups (free_cu_cleanup);
5296
5297           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5298              So we have to manually free the abbrev table.  */
5299           dwarf2_free_abbrev_table (cu);
5300
5301           /* Link this CU into read_in_chain.  */
5302           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5303           dwarf2_per_objfile->read_in_chain = this_cu;
5304         }
5305       else
5306         do_cleanups (free_cu_cleanup);
5307     }
5308
5309   do_cleanups (cleanups);
5310 }
5311
5312 /* Initialize a CU (or TU) and read its DIEs.
5313    If the CU defers to a DWO file, read the DWO file as well.
5314
5315    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5316    Otherwise the table specified in the comp unit header is read in and used.
5317    This is an optimization for when we already have the abbrev table.
5318
5319    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5320    Otherwise, a new CU is allocated with xmalloc.
5321
5322    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5323    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5324
5325    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5326    linker) then DIE_READER_FUNC will not get called.  */
5327
5328 static void
5329 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5330                          struct abbrev_table *abbrev_table,
5331                          int use_existing_cu, int keep,
5332                          die_reader_func_ftype *die_reader_func,
5333                          void *data)
5334 {
5335   struct objfile *objfile = dwarf2_per_objfile->objfile;
5336   struct dwarf2_section_info *section = this_cu->section;
5337   bfd *abfd = get_section_bfd_owner (section);
5338   struct dwarf2_cu *cu;
5339   const gdb_byte *begin_info_ptr, *info_ptr;
5340   struct die_reader_specs reader;
5341   struct die_info *comp_unit_die;
5342   int has_children;
5343   struct attribute *attr;
5344   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5345   struct signatured_type *sig_type = NULL;
5346   struct dwarf2_section_info *abbrev_section;
5347   /* Non-zero if CU currently points to a DWO file and we need to
5348      reread it.  When this happens we need to reread the skeleton die
5349      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5350   int rereading_dwo_cu = 0;
5351
5352   if (dwarf2_die_debug)
5353     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5354                         this_cu->is_debug_types ? "type" : "comp",
5355                         this_cu->offset.sect_off);
5356
5357   if (use_existing_cu)
5358     gdb_assert (keep);
5359
5360   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5361      file (instead of going through the stub), short-circuit all of this.  */
5362   if (this_cu->reading_dwo_directly)
5363     {
5364       /* Narrow down the scope of possibilities to have to understand.  */
5365       gdb_assert (this_cu->is_debug_types);
5366       gdb_assert (abbrev_table == NULL);
5367       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5368                                  die_reader_func, data);
5369       return;
5370     }
5371
5372   cleanups = make_cleanup (null_cleanup, NULL);
5373
5374   /* This is cheap if the section is already read in.  */
5375   dwarf2_read_section (objfile, section);
5376
5377   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5378
5379   abbrev_section = get_abbrev_section_for_cu (this_cu);
5380
5381   if (use_existing_cu && this_cu->cu != NULL)
5382     {
5383       cu = this_cu->cu;
5384       /* If this CU is from a DWO file we need to start over, we need to
5385          refetch the attributes from the skeleton CU.
5386          This could be optimized by retrieving those attributes from when we
5387          were here the first time: the previous comp_unit_die was stored in
5388          comp_unit_obstack.  But there's no data yet that we need this
5389          optimization.  */
5390       if (cu->dwo_unit != NULL)
5391         rereading_dwo_cu = 1;
5392     }
5393   else
5394     {
5395       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5396       gdb_assert (this_cu->cu == NULL);
5397       cu = xmalloc (sizeof (*cu));
5398       init_one_comp_unit (cu, this_cu);
5399       /* If an error occurs while loading, release our storage.  */
5400       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5401     }
5402
5403   /* Get the header.  */
5404   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5405     {
5406       /* We already have the header, there's no need to read it in again.  */
5407       info_ptr += cu->header.first_die_offset.cu_off;
5408     }
5409   else
5410     {
5411       if (this_cu->is_debug_types)
5412         {
5413           ULONGEST signature;
5414           cu_offset type_offset_in_tu;
5415
5416           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5417                                                     abbrev_section, info_ptr,
5418                                                     &signature,
5419                                                     &type_offset_in_tu);
5420
5421           /* Since per_cu is the first member of struct signatured_type,
5422              we can go from a pointer to one to a pointer to the other.  */
5423           sig_type = (struct signatured_type *) this_cu;
5424           gdb_assert (sig_type->signature == signature);
5425           gdb_assert (sig_type->type_offset_in_tu.cu_off
5426                       == type_offset_in_tu.cu_off);
5427           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5428
5429           /* LENGTH has not been set yet for type units if we're
5430              using .gdb_index.  */
5431           this_cu->length = get_cu_length (&cu->header);
5432
5433           /* Establish the type offset that can be used to lookup the type.  */
5434           sig_type->type_offset_in_section.sect_off =
5435             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5436         }
5437       else
5438         {
5439           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5440                                                     abbrev_section,
5441                                                     info_ptr, 0);
5442
5443           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5444           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5445         }
5446     }
5447
5448   /* Skip dummy compilation units.  */
5449   if (info_ptr >= begin_info_ptr + this_cu->length
5450       || peek_abbrev_code (abfd, info_ptr) == 0)
5451     {
5452       do_cleanups (cleanups);
5453       return;
5454     }
5455
5456   /* If we don't have them yet, read the abbrevs for this compilation unit.
5457      And if we need to read them now, make sure they're freed when we're
5458      done.  Note that it's important that if the CU had an abbrev table
5459      on entry we don't free it when we're done: Somewhere up the call stack
5460      it may be in use.  */
5461   if (abbrev_table != NULL)
5462     {
5463       gdb_assert (cu->abbrev_table == NULL);
5464       gdb_assert (cu->header.abbrev_offset.sect_off
5465                   == abbrev_table->offset.sect_off);
5466       cu->abbrev_table = abbrev_table;
5467     }
5468   else if (cu->abbrev_table == NULL)
5469     {
5470       dwarf2_read_abbrevs (cu, abbrev_section);
5471       make_cleanup (dwarf2_free_abbrev_table, cu);
5472     }
5473   else if (rereading_dwo_cu)
5474     {
5475       dwarf2_free_abbrev_table (cu);
5476       dwarf2_read_abbrevs (cu, abbrev_section);
5477     }
5478
5479   /* Read the top level CU/TU die.  */
5480   init_cu_die_reader (&reader, cu, section, NULL);
5481   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5482
5483   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5484      from the DWO file.
5485      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5486      DWO CU, that this test will fail (the attribute will not be present).  */
5487   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5488   if (attr)
5489     {
5490       struct dwo_unit *dwo_unit;
5491       struct die_info *dwo_comp_unit_die;
5492
5493       if (has_children)
5494         {
5495           complaint (&symfile_complaints,
5496                      _("compilation unit with DW_AT_GNU_dwo_name"
5497                        " has children (offset 0x%x) [in module %s]"),
5498                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5499         }
5500       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5501       if (dwo_unit != NULL)
5502         {
5503           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5504                                       abbrev_table != NULL,
5505                                       comp_unit_die, NULL,
5506                                       &reader, &info_ptr,
5507                                       &dwo_comp_unit_die, &has_children) == 0)
5508             {
5509               /* Dummy die.  */
5510               do_cleanups (cleanups);
5511               return;
5512             }
5513           comp_unit_die = dwo_comp_unit_die;
5514         }
5515       else
5516         {
5517           /* Yikes, we couldn't find the rest of the DIE, we only have
5518              the stub.  A complaint has already been logged.  There's
5519              not much more we can do except pass on the stub DIE to
5520              die_reader_func.  We don't want to throw an error on bad
5521              debug info.  */
5522         }
5523     }
5524
5525   /* All of the above is setup for this call.  Yikes.  */
5526   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5527
5528   /* Done, clean up.  */
5529   if (free_cu_cleanup != NULL)
5530     {
5531       if (keep)
5532         {
5533           /* We've successfully allocated this compilation unit.  Let our
5534              caller clean it up when finished with it.  */
5535           discard_cleanups (free_cu_cleanup);
5536
5537           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5538              So we have to manually free the abbrev table.  */
5539           dwarf2_free_abbrev_table (cu);
5540
5541           /* Link this CU into read_in_chain.  */
5542           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5543           dwarf2_per_objfile->read_in_chain = this_cu;
5544         }
5545       else
5546         do_cleanups (free_cu_cleanup);
5547     }
5548
5549   do_cleanups (cleanups);
5550 }
5551
5552 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5553    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5554    to have already done the lookup to find the DWO file).
5555
5556    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5557    THIS_CU->is_debug_types, but nothing else.
5558
5559    We fill in THIS_CU->length.
5560
5561    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5562    linker) then DIE_READER_FUNC will not get called.
5563
5564    THIS_CU->cu is always freed when done.
5565    This is done in order to not leave THIS_CU->cu in a state where we have
5566    to care whether it refers to the "main" CU or the DWO CU.  */
5567
5568 static void
5569 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5570                                    struct dwo_file *dwo_file,
5571                                    die_reader_func_ftype *die_reader_func,
5572                                    void *data)
5573 {
5574   struct objfile *objfile = dwarf2_per_objfile->objfile;
5575   struct dwarf2_section_info *section = this_cu->section;
5576   bfd *abfd = get_section_bfd_owner (section);
5577   struct dwarf2_section_info *abbrev_section;
5578   struct dwarf2_cu cu;
5579   const gdb_byte *begin_info_ptr, *info_ptr;
5580   struct die_reader_specs reader;
5581   struct cleanup *cleanups;
5582   struct die_info *comp_unit_die;
5583   int has_children;
5584
5585   if (dwarf2_die_debug)
5586     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5587                         this_cu->is_debug_types ? "type" : "comp",
5588                         this_cu->offset.sect_off);
5589
5590   gdb_assert (this_cu->cu == NULL);
5591
5592   abbrev_section = (dwo_file != NULL
5593                     ? &dwo_file->sections.abbrev
5594                     : get_abbrev_section_for_cu (this_cu));
5595
5596   /* This is cheap if the section is already read in.  */
5597   dwarf2_read_section (objfile, section);
5598
5599   init_one_comp_unit (&cu, this_cu);
5600
5601   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5602
5603   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5604   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5605                                             abbrev_section, info_ptr,
5606                                             this_cu->is_debug_types);
5607
5608   this_cu->length = get_cu_length (&cu.header);
5609
5610   /* Skip dummy compilation units.  */
5611   if (info_ptr >= begin_info_ptr + this_cu->length
5612       || peek_abbrev_code (abfd, info_ptr) == 0)
5613     {
5614       do_cleanups (cleanups);
5615       return;
5616     }
5617
5618   dwarf2_read_abbrevs (&cu, abbrev_section);
5619   make_cleanup (dwarf2_free_abbrev_table, &cu);
5620
5621   init_cu_die_reader (&reader, &cu, section, dwo_file);
5622   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5623
5624   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5625
5626   do_cleanups (cleanups);
5627 }
5628
5629 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5630    does not lookup the specified DWO file.
5631    This cannot be used to read DWO files.
5632
5633    THIS_CU->cu is always freed when done.
5634    This is done in order to not leave THIS_CU->cu in a state where we have
5635    to care whether it refers to the "main" CU or the DWO CU.
5636    We can revisit this if the data shows there's a performance issue.  */
5637
5638 static void
5639 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5640                                 die_reader_func_ftype *die_reader_func,
5641                                 void *data)
5642 {
5643   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5644 }
5645 \f
5646 /* Type Unit Groups.
5647
5648    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5649    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5650    so that all types coming from the same compilation (.o file) are grouped
5651    together.  A future step could be to put the types in the same symtab as
5652    the CU the types ultimately came from.  */
5653
5654 static hashval_t
5655 hash_type_unit_group (const void *item)
5656 {
5657   const struct type_unit_group *tu_group = item;
5658
5659   return hash_stmt_list_entry (&tu_group->hash);
5660 }
5661
5662 static int
5663 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5664 {
5665   const struct type_unit_group *lhs = item_lhs;
5666   const struct type_unit_group *rhs = item_rhs;
5667
5668   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5669 }
5670
5671 /* Allocate a hash table for type unit groups.  */
5672
5673 static htab_t
5674 allocate_type_unit_groups_table (void)
5675 {
5676   return htab_create_alloc_ex (3,
5677                                hash_type_unit_group,
5678                                eq_type_unit_group,
5679                                NULL,
5680                                &dwarf2_per_objfile->objfile->objfile_obstack,
5681                                hashtab_obstack_allocate,
5682                                dummy_obstack_deallocate);
5683 }
5684
5685 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5686    partial symtabs.  We combine several TUs per psymtab to not let the size
5687    of any one psymtab grow too big.  */
5688 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5689 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5690
5691 /* Helper routine for get_type_unit_group.
5692    Create the type_unit_group object used to hold one or more TUs.  */
5693
5694 static struct type_unit_group *
5695 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5696 {
5697   struct objfile *objfile = dwarf2_per_objfile->objfile;
5698   struct dwarf2_per_cu_data *per_cu;
5699   struct type_unit_group *tu_group;
5700
5701   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5702                              struct type_unit_group);
5703   per_cu = &tu_group->per_cu;
5704   per_cu->objfile = objfile;
5705
5706   if (dwarf2_per_objfile->using_index)
5707     {
5708       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5709                                         struct dwarf2_per_cu_quick_data);
5710     }
5711   else
5712     {
5713       unsigned int line_offset = line_offset_struct.sect_off;
5714       struct partial_symtab *pst;
5715       char *name;
5716
5717       /* Give the symtab a useful name for debug purposes.  */
5718       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5719         name = xstrprintf ("<type_units_%d>",
5720                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5721       else
5722         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5723
5724       pst = create_partial_symtab (per_cu, name);
5725       pst->anonymous = 1;
5726
5727       xfree (name);
5728     }
5729
5730   tu_group->hash.dwo_unit = cu->dwo_unit;
5731   tu_group->hash.line_offset = line_offset_struct;
5732
5733   return tu_group;
5734 }
5735
5736 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5737    STMT_LIST is a DW_AT_stmt_list attribute.  */
5738
5739 static struct type_unit_group *
5740 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5741 {
5742   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5743   struct type_unit_group *tu_group;
5744   void **slot;
5745   unsigned int line_offset;
5746   struct type_unit_group type_unit_group_for_lookup;
5747
5748   if (dwarf2_per_objfile->type_unit_groups == NULL)
5749     {
5750       dwarf2_per_objfile->type_unit_groups =
5751         allocate_type_unit_groups_table ();
5752     }
5753
5754   /* Do we need to create a new group, or can we use an existing one?  */
5755
5756   if (stmt_list)
5757     {
5758       line_offset = DW_UNSND (stmt_list);
5759       ++tu_stats->nr_symtab_sharers;
5760     }
5761   else
5762     {
5763       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5764          We can do various things here like create one group per TU or
5765          spread them over multiple groups to split up the expansion work.
5766          To avoid worst case scenarios (too many groups or too large groups)
5767          we, umm, group them in bunches.  */
5768       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5769                      | (tu_stats->nr_stmt_less_type_units
5770                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5771       ++tu_stats->nr_stmt_less_type_units;
5772     }
5773
5774   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5775   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5776   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5777                          &type_unit_group_for_lookup, INSERT);
5778   if (*slot != NULL)
5779     {
5780       tu_group = *slot;
5781       gdb_assert (tu_group != NULL);
5782     }
5783   else
5784     {
5785       sect_offset line_offset_struct;
5786
5787       line_offset_struct.sect_off = line_offset;
5788       tu_group = create_type_unit_group (cu, line_offset_struct);
5789       *slot = tu_group;
5790       ++tu_stats->nr_symtabs;
5791     }
5792
5793   return tu_group;
5794 }
5795 \f
5796 /* Partial symbol tables.  */
5797
5798 /* Create a psymtab named NAME and assign it to PER_CU.
5799
5800    The caller must fill in the following details:
5801    dirname, textlow, texthigh.  */
5802
5803 static struct partial_symtab *
5804 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5805 {
5806   struct objfile *objfile = per_cu->objfile;
5807   struct partial_symtab *pst;
5808
5809   pst = start_psymtab_common (objfile, objfile->section_offsets,
5810                               name, 0,
5811                               objfile->global_psymbols.next,
5812                               objfile->static_psymbols.next);
5813
5814   pst->psymtabs_addrmap_supported = 1;
5815
5816   /* This is the glue that links PST into GDB's symbol API.  */
5817   pst->read_symtab_private = per_cu;
5818   pst->read_symtab = dwarf2_read_symtab;
5819   per_cu->v.psymtab = pst;
5820
5821   return pst;
5822 }
5823
5824 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5825    type.  */
5826
5827 struct process_psymtab_comp_unit_data
5828 {
5829   /* True if we are reading a DW_TAG_partial_unit.  */
5830
5831   int want_partial_unit;
5832
5833   /* The "pretend" language that is used if the CU doesn't declare a
5834      language.  */
5835
5836   enum language pretend_language;
5837 };
5838
5839 /* die_reader_func for process_psymtab_comp_unit.  */
5840
5841 static void
5842 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5843                                   const gdb_byte *info_ptr,
5844                                   struct die_info *comp_unit_die,
5845                                   int has_children,
5846                                   void *data)
5847 {
5848   struct dwarf2_cu *cu = reader->cu;
5849   struct objfile *objfile = cu->objfile;
5850   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5851   struct attribute *attr;
5852   CORE_ADDR baseaddr;
5853   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5854   struct partial_symtab *pst;
5855   int has_pc_info;
5856   const char *filename;
5857   struct process_psymtab_comp_unit_data *info = data;
5858
5859   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5860     return;
5861
5862   gdb_assert (! per_cu->is_debug_types);
5863
5864   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5865
5866   cu->list_in_scope = &file_symbols;
5867
5868   /* Allocate a new partial symbol table structure.  */
5869   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5870   if (attr == NULL || !DW_STRING (attr))
5871     filename = "";
5872   else
5873     filename = DW_STRING (attr);
5874
5875   pst = create_partial_symtab (per_cu, filename);
5876
5877   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5878   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5879   if (attr != NULL)
5880     pst->dirname = DW_STRING (attr);
5881
5882   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5883
5884   dwarf2_find_base_address (comp_unit_die, cu);
5885
5886   /* Possibly set the default values of LOWPC and HIGHPC from
5887      `DW_AT_ranges'.  */
5888   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5889                                       &best_highpc, cu, pst);
5890   if (has_pc_info == 1 && best_lowpc < best_highpc)
5891     /* Store the contiguous range if it is not empty; it can be empty for
5892        CUs with no code.  */
5893     addrmap_set_empty (objfile->psymtabs_addrmap,
5894                        best_lowpc + baseaddr,
5895                        best_highpc + baseaddr - 1, pst);
5896
5897   /* Check if comp unit has_children.
5898      If so, read the rest of the partial symbols from this comp unit.
5899      If not, there's no more debug_info for this comp unit.  */
5900   if (has_children)
5901     {
5902       struct partial_die_info *first_die;
5903       CORE_ADDR lowpc, highpc;
5904
5905       lowpc = ((CORE_ADDR) -1);
5906       highpc = ((CORE_ADDR) 0);
5907
5908       first_die = load_partial_dies (reader, info_ptr, 1);
5909
5910       scan_partial_symbols (first_die, &lowpc, &highpc,
5911                             ! has_pc_info, cu);
5912
5913       /* If we didn't find a lowpc, set it to highpc to avoid
5914          complaints from `maint check'.  */
5915       if (lowpc == ((CORE_ADDR) -1))
5916         lowpc = highpc;
5917
5918       /* If the compilation unit didn't have an explicit address range,
5919          then use the information extracted from its child dies.  */
5920       if (! has_pc_info)
5921         {
5922           best_lowpc = lowpc;
5923           best_highpc = highpc;
5924         }
5925     }
5926   pst->textlow = best_lowpc + baseaddr;
5927   pst->texthigh = best_highpc + baseaddr;
5928
5929   pst->n_global_syms = objfile->global_psymbols.next -
5930     (objfile->global_psymbols.list + pst->globals_offset);
5931   pst->n_static_syms = objfile->static_psymbols.next -
5932     (objfile->static_psymbols.list + pst->statics_offset);
5933   sort_pst_symbols (objfile, pst);
5934
5935   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5936     {
5937       int i;
5938       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5939       struct dwarf2_per_cu_data *iter;
5940
5941       /* Fill in 'dependencies' here; we fill in 'users' in a
5942          post-pass.  */
5943       pst->number_of_dependencies = len;
5944       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5945                                          len * sizeof (struct symtab *));
5946       for (i = 0;
5947            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5948                         i, iter);
5949            ++i)
5950         pst->dependencies[i] = iter->v.psymtab;
5951
5952       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5953     }
5954
5955   /* Get the list of files included in the current compilation unit,
5956      and build a psymtab for each of them.  */
5957   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5958
5959   if (dwarf2_read_debug)
5960     {
5961       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5962
5963       fprintf_unfiltered (gdb_stdlog,
5964                           "Psymtab for %s unit @0x%x: %s - %s"
5965                           ", %d global, %d static syms\n",
5966                           per_cu->is_debug_types ? "type" : "comp",
5967                           per_cu->offset.sect_off,
5968                           paddress (gdbarch, pst->textlow),
5969                           paddress (gdbarch, pst->texthigh),
5970                           pst->n_global_syms, pst->n_static_syms);
5971     }
5972 }
5973
5974 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5975    Process compilation unit THIS_CU for a psymtab.  */
5976
5977 static void
5978 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5979                            int want_partial_unit,
5980                            enum language pretend_language)
5981 {
5982   struct process_psymtab_comp_unit_data info;
5983
5984   /* If this compilation unit was already read in, free the
5985      cached copy in order to read it in again.  This is
5986      necessary because we skipped some symbols when we first
5987      read in the compilation unit (see load_partial_dies).
5988      This problem could be avoided, but the benefit is unclear.  */
5989   if (this_cu->cu != NULL)
5990     free_one_cached_comp_unit (this_cu);
5991
5992   gdb_assert (! this_cu->is_debug_types);
5993   info.want_partial_unit = want_partial_unit;
5994   info.pretend_language = pretend_language;
5995   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5996                            process_psymtab_comp_unit_reader,
5997                            &info);
5998
5999   /* Age out any secondary CUs.  */
6000   age_cached_comp_units ();
6001 }
6002
6003 /* Reader function for build_type_psymtabs.  */
6004
6005 static void
6006 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6007                             const gdb_byte *info_ptr,
6008                             struct die_info *type_unit_die,
6009                             int has_children,
6010                             void *data)
6011 {
6012   struct objfile *objfile = dwarf2_per_objfile->objfile;
6013   struct dwarf2_cu *cu = reader->cu;
6014   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6015   struct signatured_type *sig_type;
6016   struct type_unit_group *tu_group;
6017   struct attribute *attr;
6018   struct partial_die_info *first_die;
6019   CORE_ADDR lowpc, highpc;
6020   struct partial_symtab *pst;
6021
6022   gdb_assert (data == NULL);
6023   gdb_assert (per_cu->is_debug_types);
6024   sig_type = (struct signatured_type *) per_cu;
6025
6026   if (! has_children)
6027     return;
6028
6029   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6030   tu_group = get_type_unit_group (cu, attr);
6031
6032   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6033
6034   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6035   cu->list_in_scope = &file_symbols;
6036   pst = create_partial_symtab (per_cu, "");
6037   pst->anonymous = 1;
6038
6039   first_die = load_partial_dies (reader, info_ptr, 1);
6040
6041   lowpc = (CORE_ADDR) -1;
6042   highpc = (CORE_ADDR) 0;
6043   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
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
6052 /* Struct used to sort TUs by their abbreviation table offset.  */
6053
6054 struct tu_abbrev_offset
6055 {
6056   struct signatured_type *sig_type;
6057   sect_offset abbrev_offset;
6058 };
6059
6060 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6061
6062 static int
6063 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6064 {
6065   const struct tu_abbrev_offset * const *a = ap;
6066   const struct tu_abbrev_offset * const *b = bp;
6067   unsigned int aoff = (*a)->abbrev_offset.sect_off;
6068   unsigned int boff = (*b)->abbrev_offset.sect_off;
6069
6070   return (aoff > boff) - (aoff < boff);
6071 }
6072
6073 /* Efficiently read all the type units.
6074    This does the bulk of the work for build_type_psymtabs.
6075
6076    The efficiency is because we sort TUs by the abbrev table they use and
6077    only read each abbrev table once.  In one program there are 200K TUs
6078    sharing 8K abbrev tables.
6079
6080    The main purpose of this function is to support building the
6081    dwarf2_per_objfile->type_unit_groups table.
6082    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6083    can collapse the search space by grouping them by stmt_list.
6084    The savings can be significant, in the same program from above the 200K TUs
6085    share 8K stmt_list tables.
6086
6087    FUNC is expected to call get_type_unit_group, which will create the
6088    struct type_unit_group if necessary and add it to
6089    dwarf2_per_objfile->type_unit_groups.  */
6090
6091 static void
6092 build_type_psymtabs_1 (void)
6093 {
6094   struct objfile *objfile = dwarf2_per_objfile->objfile;
6095   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6096   struct cleanup *cleanups;
6097   struct abbrev_table *abbrev_table;
6098   sect_offset abbrev_offset;
6099   struct tu_abbrev_offset *sorted_by_abbrev;
6100   struct type_unit_group **iter;
6101   int i;
6102
6103   /* It's up to the caller to not call us multiple times.  */
6104   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6105
6106   if (dwarf2_per_objfile->n_type_units == 0)
6107     return;
6108
6109   /* TUs typically share abbrev tables, and there can be way more TUs than
6110      abbrev tables.  Sort by abbrev table to reduce the number of times we
6111      read each abbrev table in.
6112      Alternatives are to punt or to maintain a cache of abbrev tables.
6113      This is simpler and efficient enough for now.
6114
6115      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6116      symtab to use).  Typically TUs with the same abbrev offset have the same
6117      stmt_list value too so in practice this should work well.
6118
6119      The basic algorithm here is:
6120
6121       sort TUs by abbrev table
6122       for each TU with same abbrev table:
6123         read abbrev table if first user
6124         read TU top level DIE
6125           [IWBN if DWO skeletons had DW_AT_stmt_list]
6126         call FUNC  */
6127
6128   if (dwarf2_read_debug)
6129     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6130
6131   /* Sort in a separate table to maintain the order of all_type_units
6132      for .gdb_index: TU indices directly index all_type_units.  */
6133   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6134                               dwarf2_per_objfile->n_type_units);
6135   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6136     {
6137       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6138
6139       sorted_by_abbrev[i].sig_type = sig_type;
6140       sorted_by_abbrev[i].abbrev_offset =
6141         read_abbrev_offset (sig_type->per_cu.section,
6142                             sig_type->per_cu.offset);
6143     }
6144   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6145   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6146          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6147
6148   abbrev_offset.sect_off = ~(unsigned) 0;
6149   abbrev_table = NULL;
6150   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6151
6152   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6153     {
6154       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6155
6156       /* Switch to the next abbrev table if necessary.  */
6157       if (abbrev_table == NULL
6158           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
6159         {
6160           if (abbrev_table != NULL)
6161             {
6162               abbrev_table_free (abbrev_table);
6163               /* Reset to NULL in case abbrev_table_read_table throws
6164                  an error: abbrev_table_free_cleanup will get called.  */
6165               abbrev_table = NULL;
6166             }
6167           abbrev_offset = tu->abbrev_offset;
6168           abbrev_table =
6169             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6170                                      abbrev_offset);
6171           ++tu_stats->nr_uniq_abbrev_tables;
6172         }
6173
6174       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6175                                build_type_psymtabs_reader, NULL);
6176     }
6177
6178   do_cleanups (cleanups);
6179 }
6180
6181 /* Print collected type unit statistics.  */
6182
6183 static void
6184 print_tu_stats (void)
6185 {
6186   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6187
6188   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6189   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6190                       dwarf2_per_objfile->n_type_units);
6191   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6192                       tu_stats->nr_uniq_abbrev_tables);
6193   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6194                       tu_stats->nr_symtabs);
6195   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6196                       tu_stats->nr_symtab_sharers);
6197   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6198                       tu_stats->nr_stmt_less_type_units);
6199   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6200                       tu_stats->nr_all_type_units_reallocs);
6201 }
6202
6203 /* Traversal function for build_type_psymtabs.  */
6204
6205 static int
6206 build_type_psymtab_dependencies (void **slot, void *info)
6207 {
6208   struct objfile *objfile = dwarf2_per_objfile->objfile;
6209   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6210   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6211   struct partial_symtab *pst = per_cu->v.psymtab;
6212   int len = VEC_length (sig_type_ptr, tu_group->tus);
6213   struct signatured_type *iter;
6214   int i;
6215
6216   gdb_assert (len > 0);
6217   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6218
6219   pst->number_of_dependencies = len;
6220   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6221                                      len * sizeof (struct psymtab *));
6222   for (i = 0;
6223        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6224        ++i)
6225     {
6226       gdb_assert (iter->per_cu.is_debug_types);
6227       pst->dependencies[i] = iter->per_cu.v.psymtab;
6228       iter->type_unit_group = tu_group;
6229     }
6230
6231   VEC_free (sig_type_ptr, tu_group->tus);
6232
6233   return 1;
6234 }
6235
6236 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6237    Build partial symbol tables for the .debug_types comp-units.  */
6238
6239 static void
6240 build_type_psymtabs (struct objfile *objfile)
6241 {
6242   if (! create_all_type_units (objfile))
6243     return;
6244
6245   build_type_psymtabs_1 ();
6246 }
6247
6248 /* Traversal function for process_skeletonless_type_unit.
6249    Read a TU in a DWO file and build partial symbols for it.  */
6250
6251 static int
6252 process_skeletonless_type_unit (void **slot, void *info)
6253 {
6254   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6255   struct objfile *objfile = info;
6256   struct signatured_type find_entry, *entry;
6257
6258   /* If this TU doesn't exist in the global table, add it and read it in.  */
6259
6260   if (dwarf2_per_objfile->signatured_types == NULL)
6261     {
6262       dwarf2_per_objfile->signatured_types
6263         = allocate_signatured_type_table (objfile);
6264     }
6265
6266   find_entry.signature = dwo_unit->signature;
6267   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6268                          INSERT);
6269   /* If we've already seen this type there's nothing to do.  What's happening
6270      is we're doing our own version of comdat-folding here.  */
6271   if (*slot != NULL)
6272     return 1;
6273
6274   /* This does the job that create_all_type_units would have done for
6275      this TU.  */
6276   entry = add_type_unit (dwo_unit->signature, slot);
6277   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6278   *slot = entry;
6279
6280   /* This does the job that build_type_psymtabs_1 would have done.  */
6281   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6282                            build_type_psymtabs_reader, NULL);
6283
6284   return 1;
6285 }
6286
6287 /* Traversal function for process_skeletonless_type_units.  */
6288
6289 static int
6290 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6291 {
6292   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6293
6294   if (dwo_file->tus != NULL)
6295     {
6296       htab_traverse_noresize (dwo_file->tus,
6297                               process_skeletonless_type_unit, info);
6298     }
6299
6300   return 1;
6301 }
6302
6303 /* Scan all TUs of DWO files, verifying we've processed them.
6304    This is needed in case a TU was emitted without its skeleton.
6305    Note: This can't be done until we know what all the DWO files are.  */
6306
6307 static void
6308 process_skeletonless_type_units (struct objfile *objfile)
6309 {
6310   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6311   if (get_dwp_file () == NULL
6312       && dwarf2_per_objfile->dwo_files != NULL)
6313     {
6314       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6315                               process_dwo_file_for_skeletonless_type_units,
6316                               objfile);
6317     }
6318 }
6319
6320 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6321
6322 static void
6323 psymtabs_addrmap_cleanup (void *o)
6324 {
6325   struct objfile *objfile = o;
6326
6327   objfile->psymtabs_addrmap = NULL;
6328 }
6329
6330 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6331
6332 static void
6333 set_partial_user (struct objfile *objfile)
6334 {
6335   int i;
6336
6337   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6338     {
6339       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6340       struct partial_symtab *pst = per_cu->v.psymtab;
6341       int j;
6342
6343       if (pst == NULL)
6344         continue;
6345
6346       for (j = 0; j < pst->number_of_dependencies; ++j)
6347         {
6348           /* Set the 'user' field only if it is not already set.  */
6349           if (pst->dependencies[j]->user == NULL)
6350             pst->dependencies[j]->user = pst;
6351         }
6352     }
6353 }
6354
6355 /* Build the partial symbol table by doing a quick pass through the
6356    .debug_info and .debug_abbrev sections.  */
6357
6358 static void
6359 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6360 {
6361   struct cleanup *back_to, *addrmap_cleanup;
6362   struct obstack temp_obstack;
6363   int i;
6364
6365   if (dwarf2_read_debug)
6366     {
6367       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6368                           objfile_name (objfile));
6369     }
6370
6371   dwarf2_per_objfile->reading_partial_symbols = 1;
6372
6373   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6374
6375   /* Any cached compilation units will be linked by the per-objfile
6376      read_in_chain.  Make sure to free them when we're done.  */
6377   back_to = make_cleanup (free_cached_comp_units, NULL);
6378
6379   build_type_psymtabs (objfile);
6380
6381   create_all_comp_units (objfile);
6382
6383   /* Create a temporary address map on a temporary obstack.  We later
6384      copy this to the final obstack.  */
6385   obstack_init (&temp_obstack);
6386   make_cleanup_obstack_free (&temp_obstack);
6387   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6388   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6389
6390   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6391     {
6392       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6393
6394       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6395     }
6396
6397   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6398   process_skeletonless_type_units (objfile);
6399
6400   /* Now that all TUs have been processed we can fill in the dependencies.  */
6401   if (dwarf2_per_objfile->type_unit_groups != NULL)
6402     {
6403       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6404                               build_type_psymtab_dependencies, NULL);
6405     }
6406
6407   if (dwarf2_read_debug)
6408     print_tu_stats ();
6409
6410   set_partial_user (objfile);
6411
6412   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6413                                                     &objfile->objfile_obstack);
6414   discard_cleanups (addrmap_cleanup);
6415
6416   do_cleanups (back_to);
6417
6418   if (dwarf2_read_debug)
6419     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6420                         objfile_name (objfile));
6421 }
6422
6423 /* die_reader_func for load_partial_comp_unit.  */
6424
6425 static void
6426 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6427                                const gdb_byte *info_ptr,
6428                                struct die_info *comp_unit_die,
6429                                int has_children,
6430                                void *data)
6431 {
6432   struct dwarf2_cu *cu = reader->cu;
6433
6434   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6435
6436   /* Check if comp unit has_children.
6437      If so, read the rest of the partial symbols from this comp unit.
6438      If not, there's no more debug_info for this comp unit.  */
6439   if (has_children)
6440     load_partial_dies (reader, info_ptr, 0);
6441 }
6442
6443 /* Load the partial DIEs for a secondary CU into memory.
6444    This is also used when rereading a primary CU with load_all_dies.  */
6445
6446 static void
6447 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6448 {
6449   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6450                            load_partial_comp_unit_reader, NULL);
6451 }
6452
6453 static void
6454 read_comp_units_from_section (struct objfile *objfile,
6455                               struct dwarf2_section_info *section,
6456                               unsigned int is_dwz,
6457                               int *n_allocated,
6458                               int *n_comp_units,
6459                               struct dwarf2_per_cu_data ***all_comp_units)
6460 {
6461   const gdb_byte *info_ptr;
6462   bfd *abfd = get_section_bfd_owner (section);
6463
6464   if (dwarf2_read_debug)
6465     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6466                         get_section_name (section),
6467                         get_section_file_name (section));
6468
6469   dwarf2_read_section (objfile, section);
6470
6471   info_ptr = section->buffer;
6472
6473   while (info_ptr < section->buffer + section->size)
6474     {
6475       unsigned int length, initial_length_size;
6476       struct dwarf2_per_cu_data *this_cu;
6477       sect_offset offset;
6478
6479       offset.sect_off = info_ptr - section->buffer;
6480
6481       /* Read just enough information to find out where the next
6482          compilation unit is.  */
6483       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6484
6485       /* Save the compilation unit for later lookup.  */
6486       this_cu = obstack_alloc (&objfile->objfile_obstack,
6487                                sizeof (struct dwarf2_per_cu_data));
6488       memset (this_cu, 0, sizeof (*this_cu));
6489       this_cu->offset = offset;
6490       this_cu->length = length + initial_length_size;
6491       this_cu->is_dwz = is_dwz;
6492       this_cu->objfile = objfile;
6493       this_cu->section = section;
6494
6495       if (*n_comp_units == *n_allocated)
6496         {
6497           *n_allocated *= 2;
6498           *all_comp_units = xrealloc (*all_comp_units,
6499                                       *n_allocated
6500                                       * sizeof (struct dwarf2_per_cu_data *));
6501         }
6502       (*all_comp_units)[*n_comp_units] = this_cu;
6503       ++*n_comp_units;
6504
6505       info_ptr = info_ptr + this_cu->length;
6506     }
6507 }
6508
6509 /* Create a list of all compilation units in OBJFILE.
6510    This is only done for -readnow and building partial symtabs.  */
6511
6512 static void
6513 create_all_comp_units (struct objfile *objfile)
6514 {
6515   int n_allocated;
6516   int n_comp_units;
6517   struct dwarf2_per_cu_data **all_comp_units;
6518   struct dwz_file *dwz;
6519
6520   n_comp_units = 0;
6521   n_allocated = 10;
6522   all_comp_units = xmalloc (n_allocated
6523                             * sizeof (struct dwarf2_per_cu_data *));
6524
6525   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6526                                 &n_allocated, &n_comp_units, &all_comp_units);
6527
6528   dwz = dwarf2_get_dwz_file ();
6529   if (dwz != NULL)
6530     read_comp_units_from_section (objfile, &dwz->info, 1,
6531                                   &n_allocated, &n_comp_units,
6532                                   &all_comp_units);
6533
6534   dwarf2_per_objfile->all_comp_units
6535     = obstack_alloc (&objfile->objfile_obstack,
6536                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6537   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6538           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6539   xfree (all_comp_units);
6540   dwarf2_per_objfile->n_comp_units = n_comp_units;
6541 }
6542
6543 /* Process all loaded DIEs for compilation unit CU, starting at
6544    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6545    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6546    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6547    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6548
6549 static void
6550 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6551                       CORE_ADDR *highpc, int set_addrmap,
6552                       struct dwarf2_cu *cu)
6553 {
6554   struct partial_die_info *pdi;
6555
6556   /* Now, march along the PDI's, descending into ones which have
6557      interesting children but skipping the children of the other ones,
6558      until we reach the end of the compilation unit.  */
6559
6560   pdi = first_die;
6561
6562   while (pdi != NULL)
6563     {
6564       fixup_partial_die (pdi, cu);
6565
6566       /* Anonymous namespaces or modules have no name but have interesting
6567          children, so we need to look at them.  Ditto for anonymous
6568          enums.  */
6569
6570       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6571           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6572           || pdi->tag == DW_TAG_imported_unit)
6573         {
6574           switch (pdi->tag)
6575             {
6576             case DW_TAG_subprogram:
6577               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6578               break;
6579             case DW_TAG_constant:
6580             case DW_TAG_variable:
6581             case DW_TAG_typedef:
6582             case DW_TAG_union_type:
6583               if (!pdi->is_declaration)
6584                 {
6585                   add_partial_symbol (pdi, cu);
6586                 }
6587               break;
6588             case DW_TAG_class_type:
6589             case DW_TAG_interface_type:
6590             case DW_TAG_structure_type:
6591               if (!pdi->is_declaration)
6592                 {
6593                   add_partial_symbol (pdi, cu);
6594                 }
6595               break;
6596             case DW_TAG_enumeration_type:
6597               if (!pdi->is_declaration)
6598                 add_partial_enumeration (pdi, cu);
6599               break;
6600             case DW_TAG_base_type:
6601             case DW_TAG_subrange_type:
6602               /* File scope base type definitions are added to the partial
6603                  symbol table.  */
6604               add_partial_symbol (pdi, cu);
6605               break;
6606             case DW_TAG_namespace:
6607               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6608               break;
6609             case DW_TAG_module:
6610               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6611               break;
6612             case DW_TAG_imported_unit:
6613               {
6614                 struct dwarf2_per_cu_data *per_cu;
6615
6616                 /* For now we don't handle imported units in type units.  */
6617                 if (cu->per_cu->is_debug_types)
6618                   {
6619                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6620                              " supported in type units [in module %s]"),
6621                            objfile_name (cu->objfile));
6622                   }
6623
6624                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6625                                                            pdi->is_dwz,
6626                                                            cu->objfile);
6627
6628                 /* Go read the partial unit, if needed.  */
6629                 if (per_cu->v.psymtab == NULL)
6630                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6631
6632                 VEC_safe_push (dwarf2_per_cu_ptr,
6633                                cu->per_cu->imported_symtabs, per_cu);
6634               }
6635               break;
6636             case DW_TAG_imported_declaration:
6637               add_partial_symbol (pdi, cu);
6638               break;
6639             default:
6640               break;
6641             }
6642         }
6643
6644       /* If the die has a sibling, skip to the sibling.  */
6645
6646       pdi = pdi->die_sibling;
6647     }
6648 }
6649
6650 /* Functions used to compute the fully scoped name of a partial DIE.
6651
6652    Normally, this is simple.  For C++, the parent DIE's fully scoped
6653    name is concatenated with "::" and the partial DIE's name.  For
6654    Java, the same thing occurs except that "." is used instead of "::".
6655    Enumerators are an exception; they use the scope of their parent
6656    enumeration type, i.e. the name of the enumeration type is not
6657    prepended to the enumerator.
6658
6659    There are two complexities.  One is DW_AT_specification; in this
6660    case "parent" means the parent of the target of the specification,
6661    instead of the direct parent of the DIE.  The other is compilers
6662    which do not emit DW_TAG_namespace; in this case we try to guess
6663    the fully qualified name of structure types from their members'
6664    linkage names.  This must be done using the DIE's children rather
6665    than the children of any DW_AT_specification target.  We only need
6666    to do this for structures at the top level, i.e. if the target of
6667    any DW_AT_specification (if any; otherwise the DIE itself) does not
6668    have a parent.  */
6669
6670 /* Compute the scope prefix associated with PDI's parent, in
6671    compilation unit CU.  The result will be allocated on CU's
6672    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6673    field.  NULL is returned if no prefix is necessary.  */
6674 static const char *
6675 partial_die_parent_scope (struct partial_die_info *pdi,
6676                           struct dwarf2_cu *cu)
6677 {
6678   const char *grandparent_scope;
6679   struct partial_die_info *parent, *real_pdi;
6680
6681   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6682      then this means the parent of the specification DIE.  */
6683
6684   real_pdi = pdi;
6685   while (real_pdi->has_specification)
6686     real_pdi = find_partial_die (real_pdi->spec_offset,
6687                                  real_pdi->spec_is_dwz, cu);
6688
6689   parent = real_pdi->die_parent;
6690   if (parent == NULL)
6691     return NULL;
6692
6693   if (parent->scope_set)
6694     return parent->scope;
6695
6696   fixup_partial_die (parent, cu);
6697
6698   grandparent_scope = partial_die_parent_scope (parent, cu);
6699
6700   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6701      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6702      Work around this problem here.  */
6703   if (cu->language == language_cplus
6704       && parent->tag == DW_TAG_namespace
6705       && strcmp (parent->name, "::") == 0
6706       && grandparent_scope == NULL)
6707     {
6708       parent->scope = NULL;
6709       parent->scope_set = 1;
6710       return NULL;
6711     }
6712
6713   if (pdi->tag == DW_TAG_enumerator)
6714     /* Enumerators should not get the name of the enumeration as a prefix.  */
6715     parent->scope = grandparent_scope;
6716   else if (parent->tag == DW_TAG_namespace
6717       || parent->tag == DW_TAG_module
6718       || parent->tag == DW_TAG_structure_type
6719       || parent->tag == DW_TAG_class_type
6720       || parent->tag == DW_TAG_interface_type
6721       || parent->tag == DW_TAG_union_type
6722       || parent->tag == DW_TAG_enumeration_type)
6723     {
6724       if (grandparent_scope == NULL)
6725         parent->scope = parent->name;
6726       else
6727         parent->scope = typename_concat (&cu->comp_unit_obstack,
6728                                          grandparent_scope,
6729                                          parent->name, 0, cu);
6730     }
6731   else
6732     {
6733       /* FIXME drow/2004-04-01: What should we be doing with
6734          function-local names?  For partial symbols, we should probably be
6735          ignoring them.  */
6736       complaint (&symfile_complaints,
6737                  _("unhandled containing DIE tag %d for DIE at %d"),
6738                  parent->tag, pdi->offset.sect_off);
6739       parent->scope = grandparent_scope;
6740     }
6741
6742   parent->scope_set = 1;
6743   return parent->scope;
6744 }
6745
6746 /* Return the fully scoped name associated with PDI, from compilation unit
6747    CU.  The result will be allocated with malloc.  */
6748
6749 static char *
6750 partial_die_full_name (struct partial_die_info *pdi,
6751                        struct dwarf2_cu *cu)
6752 {
6753   const char *parent_scope;
6754
6755   /* If this is a template instantiation, we can not work out the
6756      template arguments from partial DIEs.  So, unfortunately, we have
6757      to go through the full DIEs.  At least any work we do building
6758      types here will be reused if full symbols are loaded later.  */
6759   if (pdi->has_template_arguments)
6760     {
6761       fixup_partial_die (pdi, cu);
6762
6763       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6764         {
6765           struct die_info *die;
6766           struct attribute attr;
6767           struct dwarf2_cu *ref_cu = cu;
6768
6769           /* DW_FORM_ref_addr is using section offset.  */
6770           attr.name = 0;
6771           attr.form = DW_FORM_ref_addr;
6772           attr.u.unsnd = pdi->offset.sect_off;
6773           die = follow_die_ref (NULL, &attr, &ref_cu);
6774
6775           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6776         }
6777     }
6778
6779   parent_scope = partial_die_parent_scope (pdi, cu);
6780   if (parent_scope == NULL)
6781     return NULL;
6782   else
6783     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6784 }
6785
6786 static void
6787 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6788 {
6789   struct objfile *objfile = cu->objfile;
6790   CORE_ADDR addr = 0;
6791   const char *actual_name = NULL;
6792   CORE_ADDR baseaddr;
6793   char *built_actual_name;
6794
6795   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6796
6797   built_actual_name = partial_die_full_name (pdi, cu);
6798   if (built_actual_name != NULL)
6799     actual_name = built_actual_name;
6800
6801   if (actual_name == NULL)
6802     actual_name = pdi->name;
6803
6804   switch (pdi->tag)
6805     {
6806     case DW_TAG_subprogram:
6807       if (pdi->is_external || cu->language == language_ada)
6808         {
6809           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6810              of the global scope.  But in Ada, we want to be able to access
6811              nested procedures globally.  So all Ada subprograms are stored
6812              in the global scope.  */
6813           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6814              mst_text, objfile); */
6815           add_psymbol_to_list (actual_name, strlen (actual_name),
6816                                built_actual_name != NULL,
6817                                VAR_DOMAIN, LOC_BLOCK,
6818                                &objfile->global_psymbols,
6819                                0, pdi->lowpc + baseaddr,
6820                                cu->language, objfile);
6821         }
6822       else
6823         {
6824           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6825              mst_file_text, objfile); */
6826           add_psymbol_to_list (actual_name, strlen (actual_name),
6827                                built_actual_name != NULL,
6828                                VAR_DOMAIN, LOC_BLOCK,
6829                                &objfile->static_psymbols,
6830                                0, pdi->lowpc + baseaddr,
6831                                cu->language, objfile);
6832         }
6833       break;
6834     case DW_TAG_constant:
6835       {
6836         struct psymbol_allocation_list *list;
6837
6838         if (pdi->is_external)
6839           list = &objfile->global_psymbols;
6840         else
6841           list = &objfile->static_psymbols;
6842         add_psymbol_to_list (actual_name, strlen (actual_name),
6843                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6844                              list, 0, 0, cu->language, objfile);
6845       }
6846       break;
6847     case DW_TAG_variable:
6848       if (pdi->d.locdesc)
6849         addr = decode_locdesc (pdi->d.locdesc, cu);
6850
6851       if (pdi->d.locdesc
6852           && addr == 0
6853           && !dwarf2_per_objfile->has_section_at_zero)
6854         {
6855           /* A global or static variable may also have been stripped
6856              out by the linker if unused, in which case its address
6857              will be nullified; do not add such variables into partial
6858              symbol table then.  */
6859         }
6860       else if (pdi->is_external)
6861         {
6862           /* Global Variable.
6863              Don't enter into the minimal symbol tables as there is
6864              a minimal symbol table entry from the ELF symbols already.
6865              Enter into partial symbol table if it has a location
6866              descriptor or a type.
6867              If the location descriptor is missing, new_symbol will create
6868              a LOC_UNRESOLVED symbol, the address of the variable will then
6869              be determined from the minimal symbol table whenever the variable
6870              is referenced.
6871              The address for the partial symbol table entry is not
6872              used by GDB, but it comes in handy for debugging partial symbol
6873              table building.  */
6874
6875           if (pdi->d.locdesc || pdi->has_type)
6876             add_psymbol_to_list (actual_name, strlen (actual_name),
6877                                  built_actual_name != NULL,
6878                                  VAR_DOMAIN, LOC_STATIC,
6879                                  &objfile->global_psymbols,
6880                                  0, addr + baseaddr,
6881                                  cu->language, objfile);
6882         }
6883       else
6884         {
6885           /* Static Variable.  Skip symbols without location descriptors.  */
6886           if (pdi->d.locdesc == NULL)
6887             {
6888               xfree (built_actual_name);
6889               return;
6890             }
6891           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6892              mst_file_data, objfile); */
6893           add_psymbol_to_list (actual_name, strlen (actual_name),
6894                                built_actual_name != NULL,
6895                                VAR_DOMAIN, LOC_STATIC,
6896                                &objfile->static_psymbols,
6897                                0, addr + baseaddr,
6898                                cu->language, objfile);
6899         }
6900       break;
6901     case DW_TAG_typedef:
6902     case DW_TAG_base_type:
6903     case DW_TAG_subrange_type:
6904       add_psymbol_to_list (actual_name, strlen (actual_name),
6905                            built_actual_name != NULL,
6906                            VAR_DOMAIN, LOC_TYPEDEF,
6907                            &objfile->static_psymbols,
6908                            0, (CORE_ADDR) 0, cu->language, objfile);
6909       break;
6910     case DW_TAG_imported_declaration:
6911     case DW_TAG_namespace:
6912       add_psymbol_to_list (actual_name, strlen (actual_name),
6913                            built_actual_name != NULL,
6914                            VAR_DOMAIN, LOC_TYPEDEF,
6915                            &objfile->global_psymbols,
6916                            0, (CORE_ADDR) 0, cu->language, objfile);
6917       break;
6918     case DW_TAG_module:
6919       add_psymbol_to_list (actual_name, strlen (actual_name),
6920                            built_actual_name != NULL,
6921                            MODULE_DOMAIN, LOC_TYPEDEF,
6922                            &objfile->global_psymbols,
6923                            0, (CORE_ADDR) 0, cu->language, objfile);
6924       break;
6925     case DW_TAG_class_type:
6926     case DW_TAG_interface_type:
6927     case DW_TAG_structure_type:
6928     case DW_TAG_union_type:
6929     case DW_TAG_enumeration_type:
6930       /* Skip external references.  The DWARF standard says in the section
6931          about "Structure, Union, and Class Type Entries": "An incomplete
6932          structure, union or class type is represented by a structure,
6933          union or class entry that does not have a byte size attribute
6934          and that has a DW_AT_declaration attribute."  */
6935       if (!pdi->has_byte_size && pdi->is_declaration)
6936         {
6937           xfree (built_actual_name);
6938           return;
6939         }
6940
6941       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6942          static vs. global.  */
6943       add_psymbol_to_list (actual_name, strlen (actual_name),
6944                            built_actual_name != NULL,
6945                            STRUCT_DOMAIN, LOC_TYPEDEF,
6946                            (cu->language == language_cplus
6947                             || cu->language == language_java)
6948                            ? &objfile->global_psymbols
6949                            : &objfile->static_psymbols,
6950                            0, (CORE_ADDR) 0, cu->language, objfile);
6951
6952       break;
6953     case DW_TAG_enumerator:
6954       add_psymbol_to_list (actual_name, strlen (actual_name),
6955                            built_actual_name != NULL,
6956                            VAR_DOMAIN, LOC_CONST,
6957                            (cu->language == language_cplus
6958                             || cu->language == language_java)
6959                            ? &objfile->global_psymbols
6960                            : &objfile->static_psymbols,
6961                            0, (CORE_ADDR) 0, cu->language, objfile);
6962       break;
6963     default:
6964       break;
6965     }
6966
6967   xfree (built_actual_name);
6968 }
6969
6970 /* Read a partial die corresponding to a namespace; also, add a symbol
6971    corresponding to that namespace to the symbol table.  NAMESPACE is
6972    the name of the enclosing namespace.  */
6973
6974 static void
6975 add_partial_namespace (struct partial_die_info *pdi,
6976                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6977                        int set_addrmap, struct dwarf2_cu *cu)
6978 {
6979   /* Add a symbol for the namespace.  */
6980
6981   add_partial_symbol (pdi, cu);
6982
6983   /* Now scan partial symbols in that namespace.  */
6984
6985   if (pdi->has_children)
6986     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
6987 }
6988
6989 /* Read a partial die corresponding to a Fortran module.  */
6990
6991 static void
6992 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6993                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
6994 {
6995   /* Add a symbol for the namespace.  */
6996
6997   add_partial_symbol (pdi, cu);
6998
6999   /* Now scan partial symbols in that module.  */
7000
7001   if (pdi->has_children)
7002     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7003 }
7004
7005 /* Read a partial die corresponding to a subprogram and create a partial
7006    symbol for that subprogram.  When the CU language allows it, this
7007    routine also defines a partial symbol for each nested subprogram
7008    that this subprogram contains.  If SET_ADDRMAP is true, record the
7009    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7010    and highest PC values found in PDI.
7011
7012    PDI may also be a lexical block, in which case we simply search
7013    recursively for subprograms defined inside that lexical block.
7014    Again, this is only performed when the CU language allows this
7015    type of definitions.  */
7016
7017 static void
7018 add_partial_subprogram (struct partial_die_info *pdi,
7019                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7020                         int set_addrmap, struct dwarf2_cu *cu)
7021 {
7022   if (pdi->tag == DW_TAG_subprogram)
7023     {
7024       if (pdi->has_pc_info)
7025         {
7026           if (pdi->lowpc < *lowpc)
7027             *lowpc = pdi->lowpc;
7028           if (pdi->highpc > *highpc)
7029             *highpc = pdi->highpc;
7030           if (set_addrmap)
7031             {
7032               CORE_ADDR baseaddr;
7033               struct objfile *objfile = cu->objfile;
7034
7035               baseaddr = ANOFFSET (objfile->section_offsets,
7036                                    SECT_OFF_TEXT (objfile));
7037               addrmap_set_empty (objfile->psymtabs_addrmap,
7038                                  pdi->lowpc + baseaddr,
7039                                  pdi->highpc - 1 + baseaddr,
7040                                  cu->per_cu->v.psymtab);
7041             }
7042         }
7043
7044       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7045         {
7046           if (!pdi->is_declaration)
7047             /* Ignore subprogram DIEs that do not have a name, they are
7048                illegal.  Do not emit a complaint at this point, we will
7049                do so when we convert this psymtab into a symtab.  */
7050             if (pdi->name)
7051               add_partial_symbol (pdi, cu);
7052         }
7053     }
7054
7055   if (! pdi->has_children)
7056     return;
7057
7058   if (cu->language == language_ada)
7059     {
7060       pdi = pdi->die_child;
7061       while (pdi != NULL)
7062         {
7063           fixup_partial_die (pdi, cu);
7064           if (pdi->tag == DW_TAG_subprogram
7065               || pdi->tag == DW_TAG_lexical_block)
7066             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7067           pdi = pdi->die_sibling;
7068         }
7069     }
7070 }
7071
7072 /* Read a partial die corresponding to an enumeration type.  */
7073
7074 static void
7075 add_partial_enumeration (struct partial_die_info *enum_pdi,
7076                          struct dwarf2_cu *cu)
7077 {
7078   struct partial_die_info *pdi;
7079
7080   if (enum_pdi->name != NULL)
7081     add_partial_symbol (enum_pdi, cu);
7082
7083   pdi = enum_pdi->die_child;
7084   while (pdi)
7085     {
7086       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7087         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7088       else
7089         add_partial_symbol (pdi, cu);
7090       pdi = pdi->die_sibling;
7091     }
7092 }
7093
7094 /* Return the initial uleb128 in the die at INFO_PTR.  */
7095
7096 static unsigned int
7097 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7098 {
7099   unsigned int bytes_read;
7100
7101   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7102 }
7103
7104 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7105    Return the corresponding abbrev, or NULL if the number is zero (indicating
7106    an empty DIE).  In either case *BYTES_READ will be set to the length of
7107    the initial number.  */
7108
7109 static struct abbrev_info *
7110 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7111                  struct dwarf2_cu *cu)
7112 {
7113   bfd *abfd = cu->objfile->obfd;
7114   unsigned int abbrev_number;
7115   struct abbrev_info *abbrev;
7116
7117   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7118
7119   if (abbrev_number == 0)
7120     return NULL;
7121
7122   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7123   if (!abbrev)
7124     {
7125       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
7126              abbrev_number, bfd_get_filename (abfd));
7127     }
7128
7129   return abbrev;
7130 }
7131
7132 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7133    Returns a pointer to the end of a series of DIEs, terminated by an empty
7134    DIE.  Any children of the skipped DIEs will also be skipped.  */
7135
7136 static const gdb_byte *
7137 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7138 {
7139   struct dwarf2_cu *cu = reader->cu;
7140   struct abbrev_info *abbrev;
7141   unsigned int bytes_read;
7142
7143   while (1)
7144     {
7145       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7146       if (abbrev == NULL)
7147         return info_ptr + bytes_read;
7148       else
7149         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7150     }
7151 }
7152
7153 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7154    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7155    abbrev corresponding to that skipped uleb128 should be passed in
7156    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7157    children.  */
7158
7159 static const gdb_byte *
7160 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7161               struct abbrev_info *abbrev)
7162 {
7163   unsigned int bytes_read;
7164   struct attribute attr;
7165   bfd *abfd = reader->abfd;
7166   struct dwarf2_cu *cu = reader->cu;
7167   const gdb_byte *buffer = reader->buffer;
7168   const gdb_byte *buffer_end = reader->buffer_end;
7169   const gdb_byte *start_info_ptr = info_ptr;
7170   unsigned int form, i;
7171
7172   for (i = 0; i < abbrev->num_attrs; i++)
7173     {
7174       /* The only abbrev we care about is DW_AT_sibling.  */
7175       if (abbrev->attrs[i].name == DW_AT_sibling)
7176         {
7177           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7178           if (attr.form == DW_FORM_ref_addr)
7179             complaint (&symfile_complaints,
7180                        _("ignoring absolute DW_AT_sibling"));
7181           else
7182             {
7183               unsigned int off = dwarf2_get_ref_die_offset (&attr).sect_off;
7184               const gdb_byte *sibling_ptr = buffer + off;
7185
7186               if (sibling_ptr < info_ptr)
7187                 complaint (&symfile_complaints,
7188                            _("DW_AT_sibling points backwards"));
7189               else if (sibling_ptr > reader->buffer_end)
7190                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7191               else
7192                 return sibling_ptr;
7193             }
7194         }
7195
7196       /* If it isn't DW_AT_sibling, skip this attribute.  */
7197       form = abbrev->attrs[i].form;
7198     skip_attribute:
7199       switch (form)
7200         {
7201         case DW_FORM_ref_addr:
7202           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7203              and later it is offset sized.  */
7204           if (cu->header.version == 2)
7205             info_ptr += cu->header.addr_size;
7206           else
7207             info_ptr += cu->header.offset_size;
7208           break;
7209         case DW_FORM_GNU_ref_alt:
7210           info_ptr += cu->header.offset_size;
7211           break;
7212         case DW_FORM_addr:
7213           info_ptr += cu->header.addr_size;
7214           break;
7215         case DW_FORM_data1:
7216         case DW_FORM_ref1:
7217         case DW_FORM_flag:
7218           info_ptr += 1;
7219           break;
7220         case DW_FORM_flag_present:
7221           break;
7222         case DW_FORM_data2:
7223         case DW_FORM_ref2:
7224           info_ptr += 2;
7225           break;
7226         case DW_FORM_data4:
7227         case DW_FORM_ref4:
7228           info_ptr += 4;
7229           break;
7230         case DW_FORM_data8:
7231         case DW_FORM_ref8:
7232         case DW_FORM_ref_sig8:
7233           info_ptr += 8;
7234           break;
7235         case DW_FORM_string:
7236           read_direct_string (abfd, info_ptr, &bytes_read);
7237           info_ptr += bytes_read;
7238           break;
7239         case DW_FORM_sec_offset:
7240         case DW_FORM_strp:
7241         case DW_FORM_GNU_strp_alt:
7242           info_ptr += cu->header.offset_size;
7243           break;
7244         case DW_FORM_exprloc:
7245         case DW_FORM_block:
7246           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7247           info_ptr += bytes_read;
7248           break;
7249         case DW_FORM_block1:
7250           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7251           break;
7252         case DW_FORM_block2:
7253           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7254           break;
7255         case DW_FORM_block4:
7256           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7257           break;
7258         case DW_FORM_sdata:
7259         case DW_FORM_udata:
7260         case DW_FORM_ref_udata:
7261         case DW_FORM_GNU_addr_index:
7262         case DW_FORM_GNU_str_index:
7263           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7264           break;
7265         case DW_FORM_indirect:
7266           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7267           info_ptr += bytes_read;
7268           /* We need to continue parsing from here, so just go back to
7269              the top.  */
7270           goto skip_attribute;
7271
7272         default:
7273           error (_("Dwarf Error: Cannot handle %s "
7274                    "in DWARF reader [in module %s]"),
7275                  dwarf_form_name (form),
7276                  bfd_get_filename (abfd));
7277         }
7278     }
7279
7280   if (abbrev->has_children)
7281     return skip_children (reader, info_ptr);
7282   else
7283     return info_ptr;
7284 }
7285
7286 /* Locate ORIG_PDI's sibling.
7287    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7288
7289 static const gdb_byte *
7290 locate_pdi_sibling (const struct die_reader_specs *reader,
7291                     struct partial_die_info *orig_pdi,
7292                     const gdb_byte *info_ptr)
7293 {
7294   /* Do we know the sibling already?  */
7295
7296   if (orig_pdi->sibling)
7297     return orig_pdi->sibling;
7298
7299   /* Are there any children to deal with?  */
7300
7301   if (!orig_pdi->has_children)
7302     return info_ptr;
7303
7304   /* Skip the children the long way.  */
7305
7306   return skip_children (reader, info_ptr);
7307 }
7308
7309 /* Expand this partial symbol table into a full symbol table.  SELF is
7310    not NULL.  */
7311
7312 static void
7313 dwarf2_read_symtab (struct partial_symtab *self,
7314                     struct objfile *objfile)
7315 {
7316   if (self->readin)
7317     {
7318       warning (_("bug: psymtab for %s is already read in."),
7319                self->filename);
7320     }
7321   else
7322     {
7323       if (info_verbose)
7324         {
7325           printf_filtered (_("Reading in symbols for %s..."),
7326                            self->filename);
7327           gdb_flush (gdb_stdout);
7328         }
7329
7330       /* Restore our global data.  */
7331       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
7332
7333       /* If this psymtab is constructed from a debug-only objfile, the
7334          has_section_at_zero flag will not necessarily be correct.  We
7335          can get the correct value for this flag by looking at the data
7336          associated with the (presumably stripped) associated objfile.  */
7337       if (objfile->separate_debug_objfile_backlink)
7338         {
7339           struct dwarf2_per_objfile *dpo_backlink
7340             = objfile_data (objfile->separate_debug_objfile_backlink,
7341                             dwarf2_objfile_data_key);
7342
7343           dwarf2_per_objfile->has_section_at_zero
7344             = dpo_backlink->has_section_at_zero;
7345         }
7346
7347       dwarf2_per_objfile->reading_partial_symbols = 0;
7348
7349       psymtab_to_symtab_1 (self);
7350
7351       /* Finish up the debug error message.  */
7352       if (info_verbose)
7353         printf_filtered (_("done.\n"));
7354     }
7355
7356   process_cu_includes ();
7357 }
7358 \f
7359 /* Reading in full CUs.  */
7360
7361 /* Add PER_CU to the queue.  */
7362
7363 static void
7364 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7365                  enum language pretend_language)
7366 {
7367   struct dwarf2_queue_item *item;
7368
7369   per_cu->queued = 1;
7370   item = xmalloc (sizeof (*item));
7371   item->per_cu = per_cu;
7372   item->pretend_language = pretend_language;
7373   item->next = NULL;
7374
7375   if (dwarf2_queue == NULL)
7376     dwarf2_queue = item;
7377   else
7378     dwarf2_queue_tail->next = item;
7379
7380   dwarf2_queue_tail = item;
7381 }
7382
7383 /* If PER_CU is not yet queued, add it to the queue.
7384    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7385    dependency.
7386    The result is non-zero if PER_CU was queued, otherwise the result is zero
7387    meaning either PER_CU is already queued or it is already loaded.
7388
7389    N.B. There is an invariant here that if a CU is queued then it is loaded.
7390    The caller is required to load PER_CU if we return non-zero.  */
7391
7392 static int
7393 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7394                        struct dwarf2_per_cu_data *per_cu,
7395                        enum language pretend_language)
7396 {
7397   /* We may arrive here during partial symbol reading, if we need full
7398      DIEs to process an unusual case (e.g. template arguments).  Do
7399      not queue PER_CU, just tell our caller to load its DIEs.  */
7400   if (dwarf2_per_objfile->reading_partial_symbols)
7401     {
7402       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7403         return 1;
7404       return 0;
7405     }
7406
7407   /* Mark the dependence relation so that we don't flush PER_CU
7408      too early.  */
7409   if (dependent_cu != NULL)
7410     dwarf2_add_dependence (dependent_cu, per_cu);
7411
7412   /* If it's already on the queue, we have nothing to do.  */
7413   if (per_cu->queued)
7414     return 0;
7415
7416   /* If the compilation unit is already loaded, just mark it as
7417      used.  */
7418   if (per_cu->cu != NULL)
7419     {
7420       per_cu->cu->last_used = 0;
7421       return 0;
7422     }
7423
7424   /* Add it to the queue.  */
7425   queue_comp_unit (per_cu, pretend_language);
7426
7427   return 1;
7428 }
7429
7430 /* Process the queue.  */
7431
7432 static void
7433 process_queue (void)
7434 {
7435   struct dwarf2_queue_item *item, *next_item;
7436
7437   if (dwarf2_read_debug)
7438     {
7439       fprintf_unfiltered (gdb_stdlog,
7440                           "Expanding one or more symtabs of objfile %s ...\n",
7441                           objfile_name (dwarf2_per_objfile->objfile));
7442     }
7443
7444   /* The queue starts out with one item, but following a DIE reference
7445      may load a new CU, adding it to the end of the queue.  */
7446   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7447     {
7448       if (dwarf2_per_objfile->using_index
7449           ? !item->per_cu->v.quick->symtab
7450           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7451         {
7452           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7453           unsigned int debug_print_threshold;
7454           char buf[100];
7455
7456           if (per_cu->is_debug_types)
7457             {
7458               struct signatured_type *sig_type =
7459                 (struct signatured_type *) per_cu;
7460
7461               sprintf (buf, "TU %s at offset 0x%x",
7462                        hex_string (sig_type->signature),
7463                        per_cu->offset.sect_off);
7464               /* There can be 100s of TUs.
7465                  Only print them in verbose mode.  */
7466               debug_print_threshold = 2;
7467             }
7468           else
7469             {
7470               sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7471               debug_print_threshold = 1;
7472             }
7473
7474           if (dwarf2_read_debug >= debug_print_threshold)
7475             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7476
7477           if (per_cu->is_debug_types)
7478             process_full_type_unit (per_cu, item->pretend_language);
7479           else
7480             process_full_comp_unit (per_cu, item->pretend_language);
7481
7482           if (dwarf2_read_debug >= debug_print_threshold)
7483             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7484         }
7485
7486       item->per_cu->queued = 0;
7487       next_item = item->next;
7488       xfree (item);
7489     }
7490
7491   dwarf2_queue_tail = NULL;
7492
7493   if (dwarf2_read_debug)
7494     {
7495       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7496                           objfile_name (dwarf2_per_objfile->objfile));
7497     }
7498 }
7499
7500 /* Free all allocated queue entries.  This function only releases anything if
7501    an error was thrown; if the queue was processed then it would have been
7502    freed as we went along.  */
7503
7504 static void
7505 dwarf2_release_queue (void *dummy)
7506 {
7507   struct dwarf2_queue_item *item, *last;
7508
7509   item = dwarf2_queue;
7510   while (item)
7511     {
7512       /* Anything still marked queued is likely to be in an
7513          inconsistent state, so discard it.  */
7514       if (item->per_cu->queued)
7515         {
7516           if (item->per_cu->cu != NULL)
7517             free_one_cached_comp_unit (item->per_cu);
7518           item->per_cu->queued = 0;
7519         }
7520
7521       last = item;
7522       item = item->next;
7523       xfree (last);
7524     }
7525
7526   dwarf2_queue = dwarf2_queue_tail = NULL;
7527 }
7528
7529 /* Read in full symbols for PST, and anything it depends on.  */
7530
7531 static void
7532 psymtab_to_symtab_1 (struct partial_symtab *pst)
7533 {
7534   struct dwarf2_per_cu_data *per_cu;
7535   int i;
7536
7537   if (pst->readin)
7538     return;
7539
7540   for (i = 0; i < pst->number_of_dependencies; i++)
7541     if (!pst->dependencies[i]->readin
7542         && pst->dependencies[i]->user == NULL)
7543       {
7544         /* Inform about additional files that need to be read in.  */
7545         if (info_verbose)
7546           {
7547             /* FIXME: i18n: Need to make this a single string.  */
7548             fputs_filtered (" ", gdb_stdout);
7549             wrap_here ("");
7550             fputs_filtered ("and ", gdb_stdout);
7551             wrap_here ("");
7552             printf_filtered ("%s...", pst->dependencies[i]->filename);
7553             wrap_here ("");     /* Flush output.  */
7554             gdb_flush (gdb_stdout);
7555           }
7556         psymtab_to_symtab_1 (pst->dependencies[i]);
7557       }
7558
7559   per_cu = pst->read_symtab_private;
7560
7561   if (per_cu == NULL)
7562     {
7563       /* It's an include file, no symbols to read for it.
7564          Everything is in the parent symtab.  */
7565       pst->readin = 1;
7566       return;
7567     }
7568
7569   dw2_do_instantiate_symtab (per_cu);
7570 }
7571
7572 /* Trivial hash function for die_info: the hash value of a DIE
7573    is its offset in .debug_info for this objfile.  */
7574
7575 static hashval_t
7576 die_hash (const void *item)
7577 {
7578   const struct die_info *die = item;
7579
7580   return die->offset.sect_off;
7581 }
7582
7583 /* Trivial comparison function for die_info structures: two DIEs
7584    are equal if they have the same offset.  */
7585
7586 static int
7587 die_eq (const void *item_lhs, const void *item_rhs)
7588 {
7589   const struct die_info *die_lhs = item_lhs;
7590   const struct die_info *die_rhs = item_rhs;
7591
7592   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7593 }
7594
7595 /* die_reader_func for load_full_comp_unit.
7596    This is identical to read_signatured_type_reader,
7597    but is kept separate for now.  */
7598
7599 static void
7600 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7601                             const gdb_byte *info_ptr,
7602                             struct die_info *comp_unit_die,
7603                             int has_children,
7604                             void *data)
7605 {
7606   struct dwarf2_cu *cu = reader->cu;
7607   enum language *language_ptr = data;
7608
7609   gdb_assert (cu->die_hash == NULL);
7610   cu->die_hash =
7611     htab_create_alloc_ex (cu->header.length / 12,
7612                           die_hash,
7613                           die_eq,
7614                           NULL,
7615                           &cu->comp_unit_obstack,
7616                           hashtab_obstack_allocate,
7617                           dummy_obstack_deallocate);
7618
7619   if (has_children)
7620     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7621                                                   &info_ptr, comp_unit_die);
7622   cu->dies = comp_unit_die;
7623   /* comp_unit_die is not stored in die_hash, no need.  */
7624
7625   /* We try not to read any attributes in this function, because not
7626      all CUs needed for references have been loaded yet, and symbol
7627      table processing isn't initialized.  But we have to set the CU language,
7628      or we won't be able to build types correctly.
7629      Similarly, if we do not read the producer, we can not apply
7630      producer-specific interpretation.  */
7631   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7632 }
7633
7634 /* Load the DIEs associated with PER_CU into memory.  */
7635
7636 static void
7637 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7638                      enum language pretend_language)
7639 {
7640   gdb_assert (! this_cu->is_debug_types);
7641
7642   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7643                            load_full_comp_unit_reader, &pretend_language);
7644 }
7645
7646 /* Add a DIE to the delayed physname list.  */
7647
7648 static void
7649 add_to_method_list (struct type *type, int fnfield_index, int index,
7650                     const char *name, struct die_info *die,
7651                     struct dwarf2_cu *cu)
7652 {
7653   struct delayed_method_info mi;
7654   mi.type = type;
7655   mi.fnfield_index = fnfield_index;
7656   mi.index = index;
7657   mi.name = name;
7658   mi.die = die;
7659   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7660 }
7661
7662 /* A cleanup for freeing the delayed method list.  */
7663
7664 static void
7665 free_delayed_list (void *ptr)
7666 {
7667   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7668   if (cu->method_list != NULL)
7669     {
7670       VEC_free (delayed_method_info, cu->method_list);
7671       cu->method_list = NULL;
7672     }
7673 }
7674
7675 /* Compute the physnames of any methods on the CU's method list.
7676
7677    The computation of method physnames is delayed in order to avoid the
7678    (bad) condition that one of the method's formal parameters is of an as yet
7679    incomplete type.  */
7680
7681 static void
7682 compute_delayed_physnames (struct dwarf2_cu *cu)
7683 {
7684   int i;
7685   struct delayed_method_info *mi;
7686   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7687     {
7688       const char *physname;
7689       struct fn_fieldlist *fn_flp
7690         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7691       physname = dwarf2_physname (mi->name, mi->die, cu);
7692       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7693     }
7694 }
7695
7696 /* Go objects should be embedded in a DW_TAG_module DIE,
7697    and it's not clear if/how imported objects will appear.
7698    To keep Go support simple until that's worked out,
7699    go back through what we've read and create something usable.
7700    We could do this while processing each DIE, and feels kinda cleaner,
7701    but that way is more invasive.
7702    This is to, for example, allow the user to type "p var" or "b main"
7703    without having to specify the package name, and allow lookups
7704    of module.object to work in contexts that use the expression
7705    parser.  */
7706
7707 static void
7708 fixup_go_packaging (struct dwarf2_cu *cu)
7709 {
7710   char *package_name = NULL;
7711   struct pending *list;
7712   int i;
7713
7714   for (list = global_symbols; list != NULL; list = list->next)
7715     {
7716       for (i = 0; i < list->nsyms; ++i)
7717         {
7718           struct symbol *sym = list->symbol[i];
7719
7720           if (SYMBOL_LANGUAGE (sym) == language_go
7721               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7722             {
7723               char *this_package_name = go_symbol_package_name (sym);
7724
7725               if (this_package_name == NULL)
7726                 continue;
7727               if (package_name == NULL)
7728                 package_name = this_package_name;
7729               else
7730                 {
7731                   if (strcmp (package_name, this_package_name) != 0)
7732                     complaint (&symfile_complaints,
7733                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7734                                (SYMBOL_SYMTAB (sym)
7735                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7736                                 : objfile_name (cu->objfile)),
7737                                this_package_name, package_name);
7738                   xfree (this_package_name);
7739                 }
7740             }
7741         }
7742     }
7743
7744   if (package_name != NULL)
7745     {
7746       struct objfile *objfile = cu->objfile;
7747       const char *saved_package_name
7748         = obstack_copy0 (&objfile->per_bfd->storage_obstack,
7749                          package_name,
7750                          strlen (package_name));
7751       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7752                                      saved_package_name, objfile);
7753       struct symbol *sym;
7754
7755       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7756
7757       sym = allocate_symbol (objfile);
7758       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7759       SYMBOL_SET_NAMES (sym, saved_package_name,
7760                         strlen (saved_package_name), 0, objfile);
7761       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7762          e.g., "main" finds the "main" module and not C's main().  */
7763       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7764       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7765       SYMBOL_TYPE (sym) = type;
7766
7767       add_symbol_to_list (sym, &global_symbols);
7768
7769       xfree (package_name);
7770     }
7771 }
7772
7773 /* Return the symtab for PER_CU.  This works properly regardless of
7774    whether we're using the index or psymtabs.  */
7775
7776 static struct symtab *
7777 get_symtab (struct dwarf2_per_cu_data *per_cu)
7778 {
7779   return (dwarf2_per_objfile->using_index
7780           ? per_cu->v.quick->symtab
7781           : per_cu->v.psymtab->symtab);
7782 }
7783
7784 /* A helper function for computing the list of all symbol tables
7785    included by PER_CU.  */
7786
7787 static void
7788 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7789                                 htab_t all_children, htab_t all_type_symtabs,
7790                                 struct dwarf2_per_cu_data *per_cu,
7791                                 struct symtab *immediate_parent)
7792 {
7793   void **slot;
7794   int ix;
7795   struct symtab *symtab;
7796   struct dwarf2_per_cu_data *iter;
7797
7798   slot = htab_find_slot (all_children, per_cu, INSERT);
7799   if (*slot != NULL)
7800     {
7801       /* This inclusion and its children have been processed.  */
7802       return;
7803     }
7804
7805   *slot = per_cu;
7806   /* Only add a CU if it has a symbol table.  */
7807   symtab = get_symtab (per_cu);
7808   if (symtab != NULL)
7809     {
7810       /* If this is a type unit only add its symbol table if we haven't
7811          seen it yet (type unit per_cu's can share symtabs).  */
7812       if (per_cu->is_debug_types)
7813         {
7814           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7815           if (*slot == NULL)
7816             {
7817               *slot = symtab;
7818               VEC_safe_push (symtab_ptr, *result, symtab);
7819               if (symtab->user == NULL)
7820                 symtab->user = immediate_parent;
7821             }
7822         }
7823       else
7824         {
7825           VEC_safe_push (symtab_ptr, *result, symtab);
7826           if (symtab->user == NULL)
7827             symtab->user = immediate_parent;
7828         }
7829     }
7830
7831   for (ix = 0;
7832        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7833        ++ix)
7834     {
7835       recursively_compute_inclusions (result, all_children,
7836                                       all_type_symtabs, iter, symtab);
7837     }
7838 }
7839
7840 /* Compute the symtab 'includes' fields for the symtab related to
7841    PER_CU.  */
7842
7843 static void
7844 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7845 {
7846   gdb_assert (! per_cu->is_debug_types);
7847
7848   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7849     {
7850       int ix, len;
7851       struct dwarf2_per_cu_data *per_cu_iter;
7852       struct symtab *symtab_iter;
7853       VEC (symtab_ptr) *result_symtabs = NULL;
7854       htab_t all_children, all_type_symtabs;
7855       struct symtab *symtab = get_symtab (per_cu);
7856
7857       /* If we don't have a symtab, we can just skip this case.  */
7858       if (symtab == NULL)
7859         return;
7860
7861       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7862                                         NULL, xcalloc, xfree);
7863       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7864                                             NULL, xcalloc, xfree);
7865
7866       for (ix = 0;
7867            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7868                         ix, per_cu_iter);
7869            ++ix)
7870         {
7871           recursively_compute_inclusions (&result_symtabs, all_children,
7872                                           all_type_symtabs, per_cu_iter,
7873                                           symtab);
7874         }
7875
7876       /* Now we have a transitive closure of all the included symtabs.  */
7877       len = VEC_length (symtab_ptr, result_symtabs);
7878       symtab->includes
7879         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7880                          (len + 1) * sizeof (struct symtab *));
7881       for (ix = 0;
7882            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7883            ++ix)
7884         symtab->includes[ix] = symtab_iter;
7885       symtab->includes[len] = NULL;
7886
7887       VEC_free (symtab_ptr, result_symtabs);
7888       htab_delete (all_children);
7889       htab_delete (all_type_symtabs);
7890     }
7891 }
7892
7893 /* Compute the 'includes' field for the symtabs of all the CUs we just
7894    read.  */
7895
7896 static void
7897 process_cu_includes (void)
7898 {
7899   int ix;
7900   struct dwarf2_per_cu_data *iter;
7901
7902   for (ix = 0;
7903        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7904                     ix, iter);
7905        ++ix)
7906     {
7907       if (! iter->is_debug_types)
7908         compute_symtab_includes (iter);
7909     }
7910
7911   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7912 }
7913
7914 /* Generate full symbol information for PER_CU, whose DIEs have
7915    already been loaded into memory.  */
7916
7917 static void
7918 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7919                         enum language pretend_language)
7920 {
7921   struct dwarf2_cu *cu = per_cu->cu;
7922   struct objfile *objfile = per_cu->objfile;
7923   CORE_ADDR lowpc, highpc;
7924   struct symtab *symtab;
7925   struct cleanup *back_to, *delayed_list_cleanup;
7926   CORE_ADDR baseaddr;
7927   struct block *static_block;
7928
7929   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7930
7931   buildsym_init ();
7932   back_to = make_cleanup (really_free_pendings, NULL);
7933   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7934
7935   cu->list_in_scope = &file_symbols;
7936
7937   cu->language = pretend_language;
7938   cu->language_defn = language_def (cu->language);
7939
7940   /* Do line number decoding in read_file_scope () */
7941   process_die (cu->dies, cu);
7942
7943   /* For now fudge the Go package.  */
7944   if (cu->language == language_go)
7945     fixup_go_packaging (cu);
7946
7947   /* Now that we have processed all the DIEs in the CU, all the types 
7948      should be complete, and it should now be safe to compute all of the
7949      physnames.  */
7950   compute_delayed_physnames (cu);
7951   do_cleanups (delayed_list_cleanup);
7952
7953   /* Some compilers don't define a DW_AT_high_pc attribute for the
7954      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7955      it, by scanning the DIE's below the compilation unit.  */
7956   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7957
7958   static_block
7959     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7960
7961   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7962      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7963      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7964      addrmap to help ensure it has an accurate map of pc values belonging to
7965      this comp unit.  */
7966   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7967
7968   symtab = end_symtab_from_static_block (static_block, objfile,
7969                                          SECT_OFF_TEXT (objfile), 0);
7970
7971   if (symtab != NULL)
7972     {
7973       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7974
7975       /* Set symtab language to language from DW_AT_language.  If the
7976          compilation is from a C file generated by language preprocessors, do
7977          not set the language if it was already deduced by start_subfile.  */
7978       if (!(cu->language == language_c && symtab->language != language_c))
7979         symtab->language = cu->language;
7980
7981       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7982          produce DW_AT_location with location lists but it can be possibly
7983          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7984          there were bugs in prologue debug info, fixed later in GCC-4.5
7985          by "unwind info for epilogues" patch (which is not directly related).
7986
7987          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7988          needed, it would be wrong due to missing DW_AT_producer there.
7989
7990          Still one can confuse GDB by using non-standard GCC compilation
7991          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7992          */ 
7993       if (cu->has_loclist && gcc_4_minor >= 5)
7994         symtab->locations_valid = 1;
7995
7996       if (gcc_4_minor >= 5)
7997         symtab->epilogue_unwind_valid = 1;
7998
7999       symtab->call_site_htab = cu->call_site_htab;
8000     }
8001
8002   if (dwarf2_per_objfile->using_index)
8003     per_cu->v.quick->symtab = symtab;
8004   else
8005     {
8006       struct partial_symtab *pst = per_cu->v.psymtab;
8007       pst->symtab = symtab;
8008       pst->readin = 1;
8009     }
8010
8011   /* Push it for inclusion processing later.  */
8012   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8013
8014   do_cleanups (back_to);
8015 }
8016
8017 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8018    already been loaded into memory.  */
8019
8020 static void
8021 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8022                         enum language pretend_language)
8023 {
8024   struct dwarf2_cu *cu = per_cu->cu;
8025   struct objfile *objfile = per_cu->objfile;
8026   struct symtab *symtab;
8027   struct cleanup *back_to, *delayed_list_cleanup;
8028   struct signatured_type *sig_type;
8029
8030   gdb_assert (per_cu->is_debug_types);
8031   sig_type = (struct signatured_type *) per_cu;
8032
8033   buildsym_init ();
8034   back_to = make_cleanup (really_free_pendings, NULL);
8035   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8036
8037   cu->list_in_scope = &file_symbols;
8038
8039   cu->language = pretend_language;
8040   cu->language_defn = language_def (cu->language);
8041
8042   /* The symbol tables are set up in read_type_unit_scope.  */
8043   process_die (cu->dies, cu);
8044
8045   /* For now fudge the Go package.  */
8046   if (cu->language == language_go)
8047     fixup_go_packaging (cu);
8048
8049   /* Now that we have processed all the DIEs in the CU, all the types 
8050      should be complete, and it should now be safe to compute all of the
8051      physnames.  */
8052   compute_delayed_physnames (cu);
8053   do_cleanups (delayed_list_cleanup);
8054
8055   /* TUs share symbol tables.
8056      If this is the first TU to use this symtab, complete the construction
8057      of it with end_expandable_symtab.  Otherwise, complete the addition of
8058      this TU's symbols to the existing symtab.  */
8059   if (sig_type->type_unit_group->primary_symtab == NULL)
8060     {
8061       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
8062       sig_type->type_unit_group->primary_symtab = symtab;
8063
8064       if (symtab != NULL)
8065         {
8066           /* Set symtab language to language from DW_AT_language.  If the
8067              compilation is from a C file generated by language preprocessors,
8068              do not set the language if it was already deduced by
8069              start_subfile.  */
8070           if (!(cu->language == language_c && symtab->language != language_c))
8071             symtab->language = cu->language;
8072         }
8073     }
8074   else
8075     {
8076       augment_type_symtab (objfile,
8077                            sig_type->type_unit_group->primary_symtab);
8078       symtab = sig_type->type_unit_group->primary_symtab;
8079     }
8080
8081   if (dwarf2_per_objfile->using_index)
8082     per_cu->v.quick->symtab = symtab;
8083   else
8084     {
8085       struct partial_symtab *pst = per_cu->v.psymtab;
8086       pst->symtab = symtab;
8087       pst->readin = 1;
8088     }
8089
8090   do_cleanups (back_to);
8091 }
8092
8093 /* Process an imported unit DIE.  */
8094
8095 static void
8096 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8097 {
8098   struct attribute *attr;
8099
8100   /* For now we don't handle imported units in type units.  */
8101   if (cu->per_cu->is_debug_types)
8102     {
8103       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8104                " supported in type units [in module %s]"),
8105              objfile_name (cu->objfile));
8106     }
8107
8108   attr = dwarf2_attr (die, DW_AT_import, cu);
8109   if (attr != NULL)
8110     {
8111       struct dwarf2_per_cu_data *per_cu;
8112       struct symtab *imported_symtab;
8113       sect_offset offset;
8114       int is_dwz;
8115
8116       offset = dwarf2_get_ref_die_offset (attr);
8117       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8118       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
8119
8120       /* If necessary, add it to the queue and load its DIEs.  */
8121       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8122         load_full_comp_unit (per_cu, cu->language);
8123
8124       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8125                      per_cu);
8126     }
8127 }
8128
8129 /* Reset the in_process bit of a die.  */
8130
8131 static void
8132 reset_die_in_process (void *arg)
8133 {
8134   struct die_info *die = arg;
8135
8136   die->in_process = 0;
8137 }
8138
8139 /* Process a die and its children.  */
8140
8141 static void
8142 process_die (struct die_info *die, struct dwarf2_cu *cu)
8143 {
8144   struct cleanup *in_process;
8145
8146   /* We should only be processing those not already in process.  */
8147   gdb_assert (!die->in_process);
8148
8149   die->in_process = 1;
8150   in_process = make_cleanup (reset_die_in_process,die);
8151
8152   switch (die->tag)
8153     {
8154     case DW_TAG_padding:
8155       break;
8156     case DW_TAG_compile_unit:
8157     case DW_TAG_partial_unit:
8158       read_file_scope (die, cu);
8159       break;
8160     case DW_TAG_type_unit:
8161       read_type_unit_scope (die, cu);
8162       break;
8163     case DW_TAG_subprogram:
8164     case DW_TAG_inlined_subroutine:
8165       read_func_scope (die, cu);
8166       break;
8167     case DW_TAG_lexical_block:
8168     case DW_TAG_try_block:
8169     case DW_TAG_catch_block:
8170       read_lexical_block_scope (die, cu);
8171       break;
8172     case DW_TAG_GNU_call_site:
8173       read_call_site_scope (die, cu);
8174       break;
8175     case DW_TAG_class_type:
8176     case DW_TAG_interface_type:
8177     case DW_TAG_structure_type:
8178     case DW_TAG_union_type:
8179       process_structure_scope (die, cu);
8180       break;
8181     case DW_TAG_enumeration_type:
8182       process_enumeration_scope (die, cu);
8183       break;
8184
8185     /* These dies have a type, but processing them does not create
8186        a symbol or recurse to process the children.  Therefore we can
8187        read them on-demand through read_type_die.  */
8188     case DW_TAG_subroutine_type:
8189     case DW_TAG_set_type:
8190     case DW_TAG_array_type:
8191     case DW_TAG_pointer_type:
8192     case DW_TAG_ptr_to_member_type:
8193     case DW_TAG_reference_type:
8194     case DW_TAG_string_type:
8195       break;
8196
8197     case DW_TAG_base_type:
8198     case DW_TAG_subrange_type:
8199     case DW_TAG_typedef:
8200       /* Add a typedef symbol for the type definition, if it has a
8201          DW_AT_name.  */
8202       new_symbol (die, read_type_die (die, cu), cu);
8203       break;
8204     case DW_TAG_common_block:
8205       read_common_block (die, cu);
8206       break;
8207     case DW_TAG_common_inclusion:
8208       break;
8209     case DW_TAG_namespace:
8210       cu->processing_has_namespace_info = 1;
8211       read_namespace (die, cu);
8212       break;
8213     case DW_TAG_module:
8214       cu->processing_has_namespace_info = 1;
8215       read_module (die, cu);
8216       break;
8217     case DW_TAG_imported_declaration:
8218       cu->processing_has_namespace_info = 1;
8219       if (read_namespace_alias (die, cu))
8220         break;
8221       /* The declaration is not a global namespace alias: fall through.  */
8222     case DW_TAG_imported_module:
8223       cu->processing_has_namespace_info = 1;
8224       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8225                                  || cu->language != language_fortran))
8226         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8227                    dwarf_tag_name (die->tag));
8228       read_import_statement (die, cu);
8229       break;
8230
8231     case DW_TAG_imported_unit:
8232       process_imported_unit_die (die, cu);
8233       break;
8234
8235     default:
8236       new_symbol (die, NULL, cu);
8237       break;
8238     }
8239
8240   do_cleanups (in_process);
8241 }
8242 \f
8243 /* DWARF name computation.  */
8244
8245 /* A helper function for dwarf2_compute_name which determines whether DIE
8246    needs to have the name of the scope prepended to the name listed in the
8247    die.  */
8248
8249 static int
8250 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8251 {
8252   struct attribute *attr;
8253
8254   switch (die->tag)
8255     {
8256     case DW_TAG_namespace:
8257     case DW_TAG_typedef:
8258     case DW_TAG_class_type:
8259     case DW_TAG_interface_type:
8260     case DW_TAG_structure_type:
8261     case DW_TAG_union_type:
8262     case DW_TAG_enumeration_type:
8263     case DW_TAG_enumerator:
8264     case DW_TAG_subprogram:
8265     case DW_TAG_member:
8266     case DW_TAG_imported_declaration:
8267       return 1;
8268
8269     case DW_TAG_variable:
8270     case DW_TAG_constant:
8271       /* We only need to prefix "globally" visible variables.  These include
8272          any variable marked with DW_AT_external or any variable that
8273          lives in a namespace.  [Variables in anonymous namespaces
8274          require prefixing, but they are not DW_AT_external.]  */
8275
8276       if (dwarf2_attr (die, DW_AT_specification, cu))
8277         {
8278           struct dwarf2_cu *spec_cu = cu;
8279
8280           return die_needs_namespace (die_specification (die, &spec_cu),
8281                                       spec_cu);
8282         }
8283
8284       attr = dwarf2_attr (die, DW_AT_external, cu);
8285       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8286           && die->parent->tag != DW_TAG_module)
8287         return 0;
8288       /* A variable in a lexical block of some kind does not need a
8289          namespace, even though in C++ such variables may be external
8290          and have a mangled name.  */
8291       if (die->parent->tag ==  DW_TAG_lexical_block
8292           || die->parent->tag ==  DW_TAG_try_block
8293           || die->parent->tag ==  DW_TAG_catch_block
8294           || die->parent->tag == DW_TAG_subprogram)
8295         return 0;
8296       return 1;
8297
8298     default:
8299       return 0;
8300     }
8301 }
8302
8303 /* Retrieve the last character from a mem_file.  */
8304
8305 static void
8306 do_ui_file_peek_last (void *object, const char *buffer, long length)
8307 {
8308   char *last_char_p = (char *) object;
8309
8310   if (length > 0)
8311     *last_char_p = buffer[length - 1];
8312 }
8313
8314 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8315    compute the physname for the object, which include a method's:
8316    - formal parameters (C++/Java),
8317    - receiver type (Go),
8318    - return type (Java).
8319
8320    The term "physname" is a bit confusing.
8321    For C++, for example, it is the demangled name.
8322    For Go, for example, it's the mangled name.
8323
8324    For Ada, return the DIE's linkage name rather than the fully qualified
8325    name.  PHYSNAME is ignored..
8326
8327    The result is allocated on the objfile_obstack and canonicalized.  */
8328
8329 static const char *
8330 dwarf2_compute_name (const char *name,
8331                      struct die_info *die, struct dwarf2_cu *cu,
8332                      int physname)
8333 {
8334   struct objfile *objfile = cu->objfile;
8335
8336   if (name == NULL)
8337     name = dwarf2_name (die, cu);
8338
8339   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
8340      compute it by typename_concat inside GDB.  */
8341   if (cu->language == language_ada
8342       || (cu->language == language_fortran && physname))
8343     {
8344       /* For Ada unit, we prefer the linkage name over the name, as
8345          the former contains the exported name, which the user expects
8346          to be able to reference.  Ideally, we want the user to be able
8347          to reference this entity using either natural or linkage name,
8348          but we haven't started looking at this enhancement yet.  */
8349       struct attribute *attr;
8350
8351       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8352       if (attr == NULL)
8353         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8354       if (attr && DW_STRING (attr))
8355         return DW_STRING (attr);
8356     }
8357
8358   /* These are the only languages we know how to qualify names in.  */
8359   if (name != NULL
8360       && (cu->language == language_cplus || cu->language == language_java
8361           || cu->language == language_fortran))
8362     {
8363       if (die_needs_namespace (die, cu))
8364         {
8365           long length;
8366           const char *prefix;
8367           struct ui_file *buf;
8368           char *intermediate_name;
8369           const char *canonical_name = NULL;
8370
8371           prefix = determine_prefix (die, cu);
8372           buf = mem_fileopen ();
8373           if (*prefix != '\0')
8374             {
8375               char *prefixed_name = typename_concat (NULL, prefix, name,
8376                                                      physname, cu);
8377
8378               fputs_unfiltered (prefixed_name, buf);
8379               xfree (prefixed_name);
8380             }
8381           else
8382             fputs_unfiltered (name, buf);
8383
8384           /* Template parameters may be specified in the DIE's DW_AT_name, or
8385              as children with DW_TAG_template_type_param or
8386              DW_TAG_value_type_param.  If the latter, add them to the name
8387              here.  If the name already has template parameters, then
8388              skip this step; some versions of GCC emit both, and
8389              it is more efficient to use the pre-computed name.
8390
8391              Something to keep in mind about this process: it is very
8392              unlikely, or in some cases downright impossible, to produce
8393              something that will match the mangled name of a function.
8394              If the definition of the function has the same debug info,
8395              we should be able to match up with it anyway.  But fallbacks
8396              using the minimal symbol, for instance to find a method
8397              implemented in a stripped copy of libstdc++, will not work.
8398              If we do not have debug info for the definition, we will have to
8399              match them up some other way.
8400
8401              When we do name matching there is a related problem with function
8402              templates; two instantiated function templates are allowed to
8403              differ only by their return types, which we do not add here.  */
8404
8405           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8406             {
8407               struct attribute *attr;
8408               struct die_info *child;
8409               int first = 1;
8410
8411               die->building_fullname = 1;
8412
8413               for (child = die->child; child != NULL; child = child->sibling)
8414                 {
8415                   struct type *type;
8416                   LONGEST value;
8417                   const gdb_byte *bytes;
8418                   struct dwarf2_locexpr_baton *baton;
8419                   struct value *v;
8420
8421                   if (child->tag != DW_TAG_template_type_param
8422                       && child->tag != DW_TAG_template_value_param)
8423                     continue;
8424
8425                   if (first)
8426                     {
8427                       fputs_unfiltered ("<", buf);
8428                       first = 0;
8429                     }
8430                   else
8431                     fputs_unfiltered (", ", buf);
8432
8433                   attr = dwarf2_attr (child, DW_AT_type, cu);
8434                   if (attr == NULL)
8435                     {
8436                       complaint (&symfile_complaints,
8437                                  _("template parameter missing DW_AT_type"));
8438                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
8439                       continue;
8440                     }
8441                   type = die_type (child, cu);
8442
8443                   if (child->tag == DW_TAG_template_type_param)
8444                     {
8445                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
8446                       continue;
8447                     }
8448
8449                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8450                   if (attr == NULL)
8451                     {
8452                       complaint (&symfile_complaints,
8453                                  _("template parameter missing "
8454                                    "DW_AT_const_value"));
8455                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8456                       continue;
8457                     }
8458
8459                   dwarf2_const_value_attr (attr, type, name,
8460                                            &cu->comp_unit_obstack, cu,
8461                                            &value, &bytes, &baton);
8462
8463                   if (TYPE_NOSIGN (type))
8464                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8465                        changed, this can use value_print instead.  */
8466                     c_printchar (value, type, buf);
8467                   else
8468                     {
8469                       struct value_print_options opts;
8470
8471                       if (baton != NULL)
8472                         v = dwarf2_evaluate_loc_desc (type, NULL,
8473                                                       baton->data,
8474                                                       baton->size,
8475                                                       baton->per_cu);
8476                       else if (bytes != NULL)
8477                         {
8478                           v = allocate_value (type);
8479                           memcpy (value_contents_writeable (v), bytes,
8480                                   TYPE_LENGTH (type));
8481                         }
8482                       else
8483                         v = value_from_longest (type, value);
8484
8485                       /* Specify decimal so that we do not depend on
8486                          the radix.  */
8487                       get_formatted_print_options (&opts, 'd');
8488                       opts.raw = 1;
8489                       value_print (v, buf, &opts);
8490                       release_value (v);
8491                       value_free (v);
8492                     }
8493                 }
8494
8495               die->building_fullname = 0;
8496
8497               if (!first)
8498                 {
8499                   /* Close the argument list, with a space if necessary
8500                      (nested templates).  */
8501                   char last_char = '\0';
8502                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8503                   if (last_char == '>')
8504                     fputs_unfiltered (" >", buf);
8505                   else
8506                     fputs_unfiltered (">", buf);
8507                 }
8508             }
8509
8510           /* For Java and C++ methods, append formal parameter type
8511              information, if PHYSNAME.  */
8512
8513           if (physname && die->tag == DW_TAG_subprogram
8514               && (cu->language == language_cplus
8515                   || cu->language == language_java))
8516             {
8517               struct type *type = read_type_die (die, cu);
8518
8519               c_type_print_args (type, buf, 1, cu->language,
8520                                  &type_print_raw_options);
8521
8522               if (cu->language == language_java)
8523                 {
8524                   /* For java, we must append the return type to method
8525                      names.  */
8526                   if (die->tag == DW_TAG_subprogram)
8527                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8528                                      0, 0, &type_print_raw_options);
8529                 }
8530               else if (cu->language == language_cplus)
8531                 {
8532                   /* Assume that an artificial first parameter is
8533                      "this", but do not crash if it is not.  RealView
8534                      marks unnamed (and thus unused) parameters as
8535                      artificial; there is no way to differentiate
8536                      the two cases.  */
8537                   if (TYPE_NFIELDS (type) > 0
8538                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8539                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8540                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8541                                                                         0))))
8542                     fputs_unfiltered (" const", buf);
8543                 }
8544             }
8545
8546           intermediate_name = ui_file_xstrdup (buf, &length);
8547           ui_file_delete (buf);
8548
8549           if (cu->language == language_cplus)
8550             canonical_name
8551               = dwarf2_canonicalize_name (intermediate_name, cu,
8552                                           &objfile->per_bfd->storage_obstack);
8553
8554           /* If we only computed INTERMEDIATE_NAME, or if
8555              INTERMEDIATE_NAME is already canonical, then we need to
8556              copy it to the appropriate obstack.  */
8557           if (canonical_name == NULL || canonical_name == intermediate_name)
8558             name = obstack_copy0 (&objfile->per_bfd->storage_obstack,
8559                                   intermediate_name,
8560                                   strlen (intermediate_name));
8561           else
8562             name = canonical_name;
8563
8564           xfree (intermediate_name);
8565         }
8566     }
8567
8568   return name;
8569 }
8570
8571 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8572    If scope qualifiers are appropriate they will be added.  The result
8573    will be allocated on the storage_obstack, or NULL if the DIE does
8574    not have a name.  NAME may either be from a previous call to
8575    dwarf2_name or NULL.
8576
8577    The output string will be canonicalized (if C++/Java).  */
8578
8579 static const char *
8580 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8581 {
8582   return dwarf2_compute_name (name, die, cu, 0);
8583 }
8584
8585 /* Construct a physname for the given DIE in CU.  NAME may either be
8586    from a previous call to dwarf2_name or NULL.  The result will be
8587    allocated on the objfile_objstack or NULL if the DIE does not have a
8588    name.
8589
8590    The output string will be canonicalized (if C++/Java).  */
8591
8592 static const char *
8593 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8594 {
8595   struct objfile *objfile = cu->objfile;
8596   struct attribute *attr;
8597   const char *retval, *mangled = NULL, *canon = NULL;
8598   struct cleanup *back_to;
8599   int need_copy = 1;
8600
8601   /* In this case dwarf2_compute_name is just a shortcut not building anything
8602      on its own.  */
8603   if (!die_needs_namespace (die, cu))
8604     return dwarf2_compute_name (name, die, cu, 1);
8605
8606   back_to = make_cleanup (null_cleanup, NULL);
8607
8608   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8609   if (!attr)
8610     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8611
8612   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8613      has computed.  */
8614   if (attr && DW_STRING (attr))
8615     {
8616       char *demangled;
8617
8618       mangled = DW_STRING (attr);
8619
8620       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8621          type.  It is easier for GDB users to search for such functions as
8622          `name(params)' than `long name(params)'.  In such case the minimal
8623          symbol names do not match the full symbol names but for template
8624          functions there is never a need to look up their definition from their
8625          declaration so the only disadvantage remains the minimal symbol
8626          variant `long name(params)' does not have the proper inferior type.
8627          */
8628
8629       if (cu->language == language_go)
8630         {
8631           /* This is a lie, but we already lie to the caller new_symbol_full.
8632              new_symbol_full assumes we return the mangled name.
8633              This just undoes that lie until things are cleaned up.  */
8634           demangled = NULL;
8635         }
8636       else
8637         {
8638           demangled = gdb_demangle (mangled,
8639                                     (DMGL_PARAMS | DMGL_ANSI
8640                                      | (cu->language == language_java
8641                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8642                                         : DMGL_RET_DROP)));
8643         }
8644       if (demangled)
8645         {
8646           make_cleanup (xfree, demangled);
8647           canon = demangled;
8648         }
8649       else
8650         {
8651           canon = mangled;
8652           need_copy = 0;
8653         }
8654     }
8655
8656   if (canon == NULL || check_physname)
8657     {
8658       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8659
8660       if (canon != NULL && strcmp (physname, canon) != 0)
8661         {
8662           /* It may not mean a bug in GDB.  The compiler could also
8663              compute DW_AT_linkage_name incorrectly.  But in such case
8664              GDB would need to be bug-to-bug compatible.  */
8665
8666           complaint (&symfile_complaints,
8667                      _("Computed physname <%s> does not match demangled <%s> "
8668                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8669                      physname, canon, mangled, die->offset.sect_off,
8670                      objfile_name (objfile));
8671
8672           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8673              is available here - over computed PHYSNAME.  It is safer
8674              against both buggy GDB and buggy compilers.  */
8675
8676           retval = canon;
8677         }
8678       else
8679         {
8680           retval = physname;
8681           need_copy = 0;
8682         }
8683     }
8684   else
8685     retval = canon;
8686
8687   if (need_copy)
8688     retval = obstack_copy0 (&objfile->per_bfd->storage_obstack,
8689                             retval, strlen (retval));
8690
8691   do_cleanups (back_to);
8692   return retval;
8693 }
8694
8695 /* Inspect DIE in CU for a namespace alias.  If one exists, record
8696    a new symbol for it.
8697
8698    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
8699
8700 static int
8701 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
8702 {
8703   struct attribute *attr;
8704
8705   /* If the die does not have a name, this is not a namespace
8706      alias.  */
8707   attr = dwarf2_attr (die, DW_AT_name, cu);
8708   if (attr != NULL)
8709     {
8710       int num;
8711       struct die_info *d = die;
8712       struct dwarf2_cu *imported_cu = cu;
8713
8714       /* If the compiler has nested DW_AT_imported_declaration DIEs,
8715          keep inspecting DIEs until we hit the underlying import.  */
8716 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
8717       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
8718         {
8719           attr = dwarf2_attr (d, DW_AT_import, cu);
8720           if (attr == NULL)
8721             break;
8722
8723           d = follow_die_ref (d, attr, &imported_cu);
8724           if (d->tag != DW_TAG_imported_declaration)
8725             break;
8726         }
8727
8728       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
8729         {
8730           complaint (&symfile_complaints,
8731                      _("DIE at 0x%x has too many recursively imported "
8732                        "declarations"), d->offset.sect_off);
8733           return 0;
8734         }
8735
8736       if (attr != NULL)
8737         {
8738           struct type *type;
8739           sect_offset offset = dwarf2_get_ref_die_offset (attr);
8740
8741           type = get_die_type_at_offset (offset, cu->per_cu);
8742           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
8743             {
8744               /* This declaration is a global namespace alias.  Add
8745                  a symbol for it whose type is the aliased namespace.  */
8746               new_symbol (die, type, cu);
8747               return 1;
8748             }
8749         }
8750     }
8751
8752   return 0;
8753 }
8754
8755 /* Read the import statement specified by the given die and record it.  */
8756
8757 static void
8758 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8759 {
8760   struct objfile *objfile = cu->objfile;
8761   struct attribute *import_attr;
8762   struct die_info *imported_die, *child_die;
8763   struct dwarf2_cu *imported_cu;
8764   const char *imported_name;
8765   const char *imported_name_prefix;
8766   const char *canonical_name;
8767   const char *import_alias;
8768   const char *imported_declaration = NULL;
8769   const char *import_prefix;
8770   VEC (const_char_ptr) *excludes = NULL;
8771   struct cleanup *cleanups;
8772
8773   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8774   if (import_attr == NULL)
8775     {
8776       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8777                  dwarf_tag_name (die->tag));
8778       return;
8779     }
8780
8781   imported_cu = cu;
8782   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8783   imported_name = dwarf2_name (imported_die, imported_cu);
8784   if (imported_name == NULL)
8785     {
8786       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8787
8788         The import in the following code:
8789         namespace A
8790           {
8791             typedef int B;
8792           }
8793
8794         int main ()
8795           {
8796             using A::B;
8797             B b;
8798             return b;
8799           }
8800
8801         ...
8802          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8803             <52>   DW_AT_decl_file   : 1
8804             <53>   DW_AT_decl_line   : 6
8805             <54>   DW_AT_import      : <0x75>
8806          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8807             <59>   DW_AT_name        : B
8808             <5b>   DW_AT_decl_file   : 1
8809             <5c>   DW_AT_decl_line   : 2
8810             <5d>   DW_AT_type        : <0x6e>
8811         ...
8812          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8813             <76>   DW_AT_byte_size   : 4
8814             <77>   DW_AT_encoding    : 5        (signed)
8815
8816         imports the wrong die ( 0x75 instead of 0x58 ).
8817         This case will be ignored until the gcc bug is fixed.  */
8818       return;
8819     }
8820
8821   /* Figure out the local name after import.  */
8822   import_alias = dwarf2_name (die, cu);
8823
8824   /* Figure out where the statement is being imported to.  */
8825   import_prefix = determine_prefix (die, cu);
8826
8827   /* Figure out what the scope of the imported die is and prepend it
8828      to the name of the imported die.  */
8829   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8830
8831   if (imported_die->tag != DW_TAG_namespace
8832       && imported_die->tag != DW_TAG_module)
8833     {
8834       imported_declaration = imported_name;
8835       canonical_name = imported_name_prefix;
8836     }
8837   else if (strlen (imported_name_prefix) > 0)
8838     canonical_name = obconcat (&objfile->objfile_obstack,
8839                                imported_name_prefix, "::", imported_name,
8840                                (char *) NULL);
8841   else
8842     canonical_name = imported_name;
8843
8844   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8845
8846   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8847     for (child_die = die->child; child_die && child_die->tag;
8848          child_die = sibling_die (child_die))
8849       {
8850         /* DWARF-4: A Fortran use statement with a “rename list” may be
8851            represented by an imported module entry with an import attribute
8852            referring to the module and owned entries corresponding to those
8853            entities that are renamed as part of being imported.  */
8854
8855         if (child_die->tag != DW_TAG_imported_declaration)
8856           {
8857             complaint (&symfile_complaints,
8858                        _("child DW_TAG_imported_declaration expected "
8859                          "- DIE at 0x%x [in module %s]"),
8860                        child_die->offset.sect_off, objfile_name (objfile));
8861             continue;
8862           }
8863
8864         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8865         if (import_attr == NULL)
8866           {
8867             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8868                        dwarf_tag_name (child_die->tag));
8869             continue;
8870           }
8871
8872         imported_cu = cu;
8873         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8874                                               &imported_cu);
8875         imported_name = dwarf2_name (imported_die, imported_cu);
8876         if (imported_name == NULL)
8877           {
8878             complaint (&symfile_complaints,
8879                        _("child DW_TAG_imported_declaration has unknown "
8880                          "imported name - DIE at 0x%x [in module %s]"),
8881                        child_die->offset.sect_off, objfile_name (objfile));
8882             continue;
8883           }
8884
8885         VEC_safe_push (const_char_ptr, excludes, imported_name);
8886
8887         process_die (child_die, cu);
8888       }
8889
8890   cp_add_using_directive (import_prefix,
8891                           canonical_name,
8892                           import_alias,
8893                           imported_declaration,
8894                           excludes,
8895                           0,
8896                           &objfile->objfile_obstack);
8897
8898   do_cleanups (cleanups);
8899 }
8900
8901 /* Cleanup function for handle_DW_AT_stmt_list.  */
8902
8903 static void
8904 free_cu_line_header (void *arg)
8905 {
8906   struct dwarf2_cu *cu = arg;
8907
8908   free_line_header (cu->line_header);
8909   cu->line_header = NULL;
8910 }
8911
8912 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8913    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8914    this, it was first present in GCC release 4.3.0.  */
8915
8916 static int
8917 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8918 {
8919   if (!cu->checked_producer)
8920     check_producer (cu);
8921
8922   return cu->producer_is_gcc_lt_4_3;
8923 }
8924
8925 static void
8926 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8927                          const char **name, const char **comp_dir)
8928 {
8929   struct attribute *attr;
8930
8931   *name = NULL;
8932   *comp_dir = NULL;
8933
8934   /* Find the filename.  Do not use dwarf2_name here, since the filename
8935      is not a source language identifier.  */
8936   attr = dwarf2_attr (die, DW_AT_name, cu);
8937   if (attr)
8938     {
8939       *name = DW_STRING (attr);
8940     }
8941
8942   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8943   if (attr)
8944     *comp_dir = DW_STRING (attr);
8945   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8946            && IS_ABSOLUTE_PATH (*name))
8947     {
8948       char *d = ldirname (*name);
8949
8950       *comp_dir = d;
8951       if (d != NULL)
8952         make_cleanup (xfree, d);
8953     }
8954   if (*comp_dir != NULL)
8955     {
8956       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8957          directory, get rid of it.  */
8958       char *cp = strchr (*comp_dir, ':');
8959
8960       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8961         *comp_dir = cp + 1;
8962     }
8963
8964   if (*name == NULL)
8965     *name = "<unknown>";
8966 }
8967
8968 /* Handle DW_AT_stmt_list for a compilation unit.
8969    DIE is the DW_TAG_compile_unit die for CU.
8970    COMP_DIR is the compilation directory.  */
8971
8972 static void
8973 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8974                         const char *comp_dir) /* ARI: editCase function */
8975 {
8976   struct attribute *attr;
8977
8978   gdb_assert (! cu->per_cu->is_debug_types);
8979
8980   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8981   if (attr)
8982     {
8983       unsigned int line_offset = DW_UNSND (attr);
8984       struct line_header *line_header
8985         = dwarf_decode_line_header (line_offset, cu);
8986
8987       if (line_header)
8988         {
8989           cu->line_header = line_header;
8990           make_cleanup (free_cu_line_header, cu);
8991           dwarf_decode_lines (line_header, comp_dir, cu, NULL);
8992         }
8993     }
8994 }
8995
8996 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8997
8998 static void
8999 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9000 {
9001   struct objfile *objfile = dwarf2_per_objfile->objfile;
9002   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
9003   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9004   CORE_ADDR highpc = ((CORE_ADDR) 0);
9005   struct attribute *attr;
9006   const char *name = NULL;
9007   const char *comp_dir = NULL;
9008   struct die_info *child_die;
9009   bfd *abfd = objfile->obfd;
9010   CORE_ADDR baseaddr;
9011
9012   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9013
9014   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9015
9016   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9017      from finish_block.  */
9018   if (lowpc == ((CORE_ADDR) -1))
9019     lowpc = highpc;
9020   lowpc += baseaddr;
9021   highpc += baseaddr;
9022
9023   find_file_and_directory (die, cu, &name, &comp_dir);
9024
9025   prepare_one_comp_unit (cu, die, cu->language);
9026
9027   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9028      standardised yet.  As a workaround for the language detection we fall
9029      back to the DW_AT_producer string.  */
9030   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9031     cu->language = language_opencl;
9032
9033   /* Similar hack for Go.  */
9034   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9035     set_cu_language (DW_LANG_Go, cu);
9036
9037   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
9038
9039   /* Decode line number information if present.  We do this before
9040      processing child DIEs, so that the line header table is available
9041      for DW_AT_decl_file.  */
9042   handle_DW_AT_stmt_list (die, cu, comp_dir);
9043
9044   /* Process all dies in compilation unit.  */
9045   if (die->child != NULL)
9046     {
9047       child_die = die->child;
9048       while (child_die && child_die->tag)
9049         {
9050           process_die (child_die, cu);
9051           child_die = sibling_die (child_die);
9052         }
9053     }
9054
9055   /* Decode macro information, if present.  Dwarf 2 macro information
9056      refers to information in the line number info statement program
9057      header, so we can only read it if we've read the header
9058      successfully.  */
9059   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9060   if (attr && cu->line_header)
9061     {
9062       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9063         complaint (&symfile_complaints,
9064                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
9065
9066       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
9067     }
9068   else
9069     {
9070       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9071       if (attr && cu->line_header)
9072         {
9073           unsigned int macro_offset = DW_UNSND (attr);
9074
9075           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
9076         }
9077     }
9078
9079   do_cleanups (back_to);
9080 }
9081
9082 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9083    Create the set of symtabs used by this TU, or if this TU is sharing
9084    symtabs with another TU and the symtabs have already been created
9085    then restore those symtabs in the line header.
9086    We don't need the pc/line-number mapping for type units.  */
9087
9088 static void
9089 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9090 {
9091   struct objfile *objfile = dwarf2_per_objfile->objfile;
9092   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9093   struct type_unit_group *tu_group;
9094   int first_time;
9095   struct line_header *lh;
9096   struct attribute *attr;
9097   unsigned int i, line_offset;
9098   struct signatured_type *sig_type;
9099
9100   gdb_assert (per_cu->is_debug_types);
9101   sig_type = (struct signatured_type *) per_cu;
9102
9103   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9104
9105   /* If we're using .gdb_index (includes -readnow) then
9106      per_cu->type_unit_group may not have been set up yet.  */
9107   if (sig_type->type_unit_group == NULL)
9108     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9109   tu_group = sig_type->type_unit_group;
9110
9111   /* If we've already processed this stmt_list there's no real need to
9112      do it again, we could fake it and just recreate the part we need
9113      (file name,index -> symtab mapping).  If data shows this optimization
9114      is useful we can do it then.  */
9115   first_time = tu_group->primary_symtab == NULL;
9116
9117   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9118      debug info.  */
9119   lh = NULL;
9120   if (attr != NULL)
9121     {
9122       line_offset = DW_UNSND (attr);
9123       lh = dwarf_decode_line_header (line_offset, cu);
9124     }
9125   if (lh == NULL)
9126     {
9127       if (first_time)
9128         dwarf2_start_symtab (cu, "", NULL, 0);
9129       else
9130         {
9131           gdb_assert (tu_group->symtabs == NULL);
9132           restart_symtab (0);
9133         }
9134       /* Note: The primary symtab will get allocated at the end.  */
9135       return;
9136     }
9137
9138   cu->line_header = lh;
9139   make_cleanup (free_cu_line_header, cu);
9140
9141   if (first_time)
9142     {
9143       dwarf2_start_symtab (cu, "", NULL, 0);
9144
9145       tu_group->num_symtabs = lh->num_file_names;
9146       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
9147
9148       for (i = 0; i < lh->num_file_names; ++i)
9149         {
9150           const char *dir = NULL;
9151           struct file_entry *fe = &lh->file_names[i];
9152
9153           if (fe->dir_index)
9154             dir = lh->include_dirs[fe->dir_index - 1];
9155           dwarf2_start_subfile (fe->name, dir, NULL);
9156
9157           /* Note: We don't have to watch for the main subfile here, type units
9158              don't have DW_AT_name.  */
9159
9160           if (current_subfile->symtab == NULL)
9161             {
9162               /* NOTE: start_subfile will recognize when it's been passed
9163                  a file it has already seen.  So we can't assume there's a
9164                  simple mapping from lh->file_names to subfiles,
9165                  lh->file_names may contain dups.  */
9166               current_subfile->symtab = allocate_symtab (current_subfile->name,
9167                                                          objfile);
9168             }
9169
9170           fe->symtab = current_subfile->symtab;
9171           tu_group->symtabs[i] = fe->symtab;
9172         }
9173     }
9174   else
9175     {
9176       restart_symtab (0);
9177
9178       for (i = 0; i < lh->num_file_names; ++i)
9179         {
9180           struct file_entry *fe = &lh->file_names[i];
9181
9182           fe->symtab = tu_group->symtabs[i];
9183         }
9184     }
9185
9186   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9187      so they don't have a "real" (so to speak) symtab anyway.
9188      There is later code that will assign the main symtab to all symbols
9189      that don't have one.  We need to handle the case of a symbol with a
9190      missing symtab (DW_AT_decl_file) anyway.  */
9191 }
9192
9193 /* Process DW_TAG_type_unit.
9194    For TUs we want to skip the first top level sibling if it's not the
9195    actual type being defined by this TU.  In this case the first top
9196    level sibling is there to provide context only.  */
9197
9198 static void
9199 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9200 {
9201   struct die_info *child_die;
9202
9203   prepare_one_comp_unit (cu, die, language_minimal);
9204
9205   /* Initialize (or reinitialize) the machinery for building symtabs.
9206      We do this before processing child DIEs, so that the line header table
9207      is available for DW_AT_decl_file.  */
9208   setup_type_unit_groups (die, cu);
9209
9210   if (die->child != NULL)
9211     {
9212       child_die = die->child;
9213       while (child_die && child_die->tag)
9214         {
9215           process_die (child_die, cu);
9216           child_die = sibling_die (child_die);
9217         }
9218     }
9219 }
9220 \f
9221 /* DWO/DWP files.
9222
9223    http://gcc.gnu.org/wiki/DebugFission
9224    http://gcc.gnu.org/wiki/DebugFissionDWP
9225
9226    To simplify handling of both DWO files ("object" files with the DWARF info)
9227    and DWP files (a file with the DWOs packaged up into one file), we treat
9228    DWP files as having a collection of virtual DWO files.  */
9229
9230 static hashval_t
9231 hash_dwo_file (const void *item)
9232 {
9233   const struct dwo_file *dwo_file = item;
9234   hashval_t hash;
9235
9236   hash = htab_hash_string (dwo_file->dwo_name);
9237   if (dwo_file->comp_dir != NULL)
9238     hash += htab_hash_string (dwo_file->comp_dir);
9239   return hash;
9240 }
9241
9242 static int
9243 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9244 {
9245   const struct dwo_file *lhs = item_lhs;
9246   const struct dwo_file *rhs = item_rhs;
9247
9248   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9249     return 0;
9250   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9251     return lhs->comp_dir == rhs->comp_dir;
9252   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9253 }
9254
9255 /* Allocate a hash table for DWO files.  */
9256
9257 static htab_t
9258 allocate_dwo_file_hash_table (void)
9259 {
9260   struct objfile *objfile = dwarf2_per_objfile->objfile;
9261
9262   return htab_create_alloc_ex (41,
9263                                hash_dwo_file,
9264                                eq_dwo_file,
9265                                NULL,
9266                                &objfile->objfile_obstack,
9267                                hashtab_obstack_allocate,
9268                                dummy_obstack_deallocate);
9269 }
9270
9271 /* Lookup DWO file DWO_NAME.  */
9272
9273 static void **
9274 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9275 {
9276   struct dwo_file find_entry;
9277   void **slot;
9278
9279   if (dwarf2_per_objfile->dwo_files == NULL)
9280     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9281
9282   memset (&find_entry, 0, sizeof (find_entry));
9283   find_entry.dwo_name = dwo_name;
9284   find_entry.comp_dir = comp_dir;
9285   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9286
9287   return slot;
9288 }
9289
9290 static hashval_t
9291 hash_dwo_unit (const void *item)
9292 {
9293   const struct dwo_unit *dwo_unit = item;
9294
9295   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9296   return dwo_unit->signature;
9297 }
9298
9299 static int
9300 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9301 {
9302   const struct dwo_unit *lhs = item_lhs;
9303   const struct dwo_unit *rhs = item_rhs;
9304
9305   /* The signature is assumed to be unique within the DWO file.
9306      So while object file CU dwo_id's always have the value zero,
9307      that's OK, assuming each object file DWO file has only one CU,
9308      and that's the rule for now.  */
9309   return lhs->signature == rhs->signature;
9310 }
9311
9312 /* Allocate a hash table for DWO CUs,TUs.
9313    There is one of these tables for each of CUs,TUs for each DWO file.  */
9314
9315 static htab_t
9316 allocate_dwo_unit_table (struct objfile *objfile)
9317 {
9318   /* Start out with a pretty small number.
9319      Generally DWO files contain only one CU and maybe some TUs.  */
9320   return htab_create_alloc_ex (3,
9321                                hash_dwo_unit,
9322                                eq_dwo_unit,
9323                                NULL,
9324                                &objfile->objfile_obstack,
9325                                hashtab_obstack_allocate,
9326                                dummy_obstack_deallocate);
9327 }
9328
9329 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9330
9331 struct create_dwo_cu_data
9332 {
9333   struct dwo_file *dwo_file;
9334   struct dwo_unit dwo_unit;
9335 };
9336
9337 /* die_reader_func for create_dwo_cu.  */
9338
9339 static void
9340 create_dwo_cu_reader (const struct die_reader_specs *reader,
9341                       const gdb_byte *info_ptr,
9342                       struct die_info *comp_unit_die,
9343                       int has_children,
9344                       void *datap)
9345 {
9346   struct dwarf2_cu *cu = reader->cu;
9347   struct objfile *objfile = dwarf2_per_objfile->objfile;
9348   sect_offset offset = cu->per_cu->offset;
9349   struct dwarf2_section_info *section = cu->per_cu->section;
9350   struct create_dwo_cu_data *data = datap;
9351   struct dwo_file *dwo_file = data->dwo_file;
9352   struct dwo_unit *dwo_unit = &data->dwo_unit;
9353   struct attribute *attr;
9354
9355   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9356   if (attr == NULL)
9357     {
9358       complaint (&symfile_complaints,
9359                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9360                    " its dwo_id [in module %s]"),
9361                  offset.sect_off, dwo_file->dwo_name);
9362       return;
9363     }
9364
9365   dwo_unit->dwo_file = dwo_file;
9366   dwo_unit->signature = DW_UNSND (attr);
9367   dwo_unit->section = section;
9368   dwo_unit->offset = offset;
9369   dwo_unit->length = cu->per_cu->length;
9370
9371   if (dwarf2_read_debug)
9372     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9373                         offset.sect_off, hex_string (dwo_unit->signature));
9374 }
9375
9376 /* Create the dwo_unit for the lone CU in DWO_FILE.
9377    Note: This function processes DWO files only, not DWP files.  */
9378
9379 static struct dwo_unit *
9380 create_dwo_cu (struct dwo_file *dwo_file)
9381 {
9382   struct objfile *objfile = dwarf2_per_objfile->objfile;
9383   struct dwarf2_section_info *section = &dwo_file->sections.info;
9384   bfd *abfd;
9385   htab_t cu_htab;
9386   const gdb_byte *info_ptr, *end_ptr;
9387   struct create_dwo_cu_data create_dwo_cu_data;
9388   struct dwo_unit *dwo_unit;
9389
9390   dwarf2_read_section (objfile, section);
9391   info_ptr = section->buffer;
9392
9393   if (info_ptr == NULL)
9394     return NULL;
9395
9396   /* We can't set abfd until now because the section may be empty or
9397      not present, in which case section->asection will be NULL.  */
9398   abfd = get_section_bfd_owner (section);
9399
9400   if (dwarf2_read_debug)
9401     {
9402       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9403                           get_section_name (section),
9404                           get_section_file_name (section));
9405     }
9406
9407   create_dwo_cu_data.dwo_file = dwo_file;
9408   dwo_unit = NULL;
9409
9410   end_ptr = info_ptr + section->size;
9411   while (info_ptr < end_ptr)
9412     {
9413       struct dwarf2_per_cu_data per_cu;
9414
9415       memset (&create_dwo_cu_data.dwo_unit, 0,
9416               sizeof (create_dwo_cu_data.dwo_unit));
9417       memset (&per_cu, 0, sizeof (per_cu));
9418       per_cu.objfile = objfile;
9419       per_cu.is_debug_types = 0;
9420       per_cu.offset.sect_off = info_ptr - section->buffer;
9421       per_cu.section = section;
9422
9423       init_cutu_and_read_dies_no_follow (&per_cu, dwo_file,
9424                                          create_dwo_cu_reader,
9425                                          &create_dwo_cu_data);
9426
9427       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
9428         {
9429           /* If we've already found one, complain.  We only support one
9430              because having more than one requires hacking the dwo_name of
9431              each to match, which is highly unlikely to happen.  */
9432           if (dwo_unit != NULL)
9433             {
9434               complaint (&symfile_complaints,
9435                          _("Multiple CUs in DWO file %s [in module %s]"),
9436                          dwo_file->dwo_name, objfile_name (objfile));
9437               break;
9438             }
9439
9440           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9441           *dwo_unit = create_dwo_cu_data.dwo_unit;
9442         }
9443
9444       info_ptr += per_cu.length;
9445     }
9446
9447   return dwo_unit;
9448 }
9449
9450 /* DWP file .debug_{cu,tu}_index section format:
9451    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9452
9453    DWP Version 1:
9454
9455    Both index sections have the same format, and serve to map a 64-bit
9456    signature to a set of section numbers.  Each section begins with a header,
9457    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9458    indexes, and a pool of 32-bit section numbers.  The index sections will be
9459    aligned at 8-byte boundaries in the file.
9460
9461    The index section header consists of:
9462
9463     V, 32 bit version number
9464     -, 32 bits unused
9465     N, 32 bit number of compilation units or type units in the index
9466     M, 32 bit number of slots in the hash table
9467
9468    Numbers are recorded using the byte order of the application binary.
9469
9470    The hash table begins at offset 16 in the section, and consists of an array
9471    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9472    order of the application binary).  Unused slots in the hash table are 0.
9473    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9474
9475    The parallel table begins immediately after the hash table
9476    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9477    array of 32-bit indexes (using the byte order of the application binary),
9478    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9479    table contains a 32-bit index into the pool of section numbers.  For unused
9480    hash table slots, the corresponding entry in the parallel table will be 0.
9481
9482    The pool of section numbers begins immediately following the hash table
9483    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9484    section numbers consists of an array of 32-bit words (using the byte order
9485    of the application binary).  Each item in the array is indexed starting
9486    from 0.  The hash table entry provides the index of the first section
9487    number in the set.  Additional section numbers in the set follow, and the
9488    set is terminated by a 0 entry (section number 0 is not used in ELF).
9489
9490    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9491    section must be the first entry in the set, and the .debug_abbrev.dwo must
9492    be the second entry. Other members of the set may follow in any order.
9493
9494    ---
9495
9496    DWP Version 2:
9497
9498    DWP Version 2 combines all the .debug_info, etc. sections into one,
9499    and the entries in the index tables are now offsets into these sections.
9500    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9501    section.
9502
9503    Index Section Contents:
9504     Header
9505     Hash Table of Signatures   dwp_hash_table.hash_table
9506     Parallel Table of Indices  dwp_hash_table.unit_table
9507     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9508     Table of Section Sizes     dwp_hash_table.v2.sizes
9509
9510    The index section header consists of:
9511
9512     V, 32 bit version number
9513     L, 32 bit number of columns in the table of section offsets
9514     N, 32 bit number of compilation units or type units in the index
9515     M, 32 bit number of slots in the hash table
9516
9517    Numbers are recorded using the byte order of the application binary.
9518
9519    The hash table has the same format as version 1.
9520    The parallel table of indices has the same format as version 1,
9521    except that the entries are origin-1 indices into the table of sections
9522    offsets and the table of section sizes.
9523
9524    The table of offsets begins immediately following the parallel table
9525    (at offset 16 + 12 * M from the beginning of the section).  The table is
9526    a two-dimensional array of 32-bit words (using the byte order of the
9527    application binary), with L columns and N+1 rows, in row-major order.
9528    Each row in the array is indexed starting from 0.  The first row provides
9529    a key to the remaining rows: each column in this row provides an identifier
9530    for a debug section, and the offsets in the same column of subsequent rows
9531    refer to that section.  The section identifiers are:
9532
9533     DW_SECT_INFO         1  .debug_info.dwo
9534     DW_SECT_TYPES        2  .debug_types.dwo
9535     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9536     DW_SECT_LINE         4  .debug_line.dwo
9537     DW_SECT_LOC          5  .debug_loc.dwo
9538     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9539     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9540     DW_SECT_MACRO        8  .debug_macro.dwo
9541
9542    The offsets provided by the CU and TU index sections are the base offsets
9543    for the contributions made by each CU or TU to the corresponding section
9544    in the package file.  Each CU and TU header contains an abbrev_offset
9545    field, used to find the abbreviations table for that CU or TU within the
9546    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9547    be interpreted as relative to the base offset given in the index section.
9548    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9549    should be interpreted as relative to the base offset for .debug_line.dwo,
9550    and offsets into other debug sections obtained from DWARF attributes should
9551    also be interpreted as relative to the corresponding base offset.
9552
9553    The table of sizes begins immediately following the table of offsets.
9554    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9555    with L columns and N rows, in row-major order.  Each row in the array is
9556    indexed starting from 1 (row 0 is shared by the two tables).
9557
9558    ---
9559
9560    Hash table lookup is handled the same in version 1 and 2:
9561
9562    We assume that N and M will not exceed 2^32 - 1.
9563    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9564
9565    Given a 64-bit compilation unit signature or a type signature S, an entry
9566    in the hash table is located as follows:
9567
9568    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9569       the low-order k bits all set to 1.
9570
9571    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9572
9573    3) If the hash table entry at index H matches the signature, use that
9574       entry.  If the hash table entry at index H is unused (all zeroes),
9575       terminate the search: the signature is not present in the table.
9576
9577    4) Let H = (H + H') modulo M. Repeat at Step 3.
9578
9579    Because M > N and H' and M are relatively prime, the search is guaranteed
9580    to stop at an unused slot or find the match.  */
9581
9582 /* Create a hash table to map DWO IDs to their CU/TU entry in
9583    .debug_{info,types}.dwo in DWP_FILE.
9584    Returns NULL if there isn't one.
9585    Note: This function processes DWP files only, not DWO files.  */
9586
9587 static struct dwp_hash_table *
9588 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9589 {
9590   struct objfile *objfile = dwarf2_per_objfile->objfile;
9591   bfd *dbfd = dwp_file->dbfd;
9592   const gdb_byte *index_ptr, *index_end;
9593   struct dwarf2_section_info *index;
9594   uint32_t version, nr_columns, nr_units, nr_slots;
9595   struct dwp_hash_table *htab;
9596
9597   if (is_debug_types)
9598     index = &dwp_file->sections.tu_index;
9599   else
9600     index = &dwp_file->sections.cu_index;
9601
9602   if (dwarf2_section_empty_p (index))
9603     return NULL;
9604   dwarf2_read_section (objfile, index);
9605
9606   index_ptr = index->buffer;
9607   index_end = index_ptr + index->size;
9608
9609   version = read_4_bytes (dbfd, index_ptr);
9610   index_ptr += 4;
9611   if (version == 2)
9612     nr_columns = read_4_bytes (dbfd, index_ptr);
9613   else
9614     nr_columns = 0;
9615   index_ptr += 4;
9616   nr_units = read_4_bytes (dbfd, index_ptr);
9617   index_ptr += 4;
9618   nr_slots = read_4_bytes (dbfd, index_ptr);
9619   index_ptr += 4;
9620
9621   if (version != 1 && version != 2)
9622     {
9623       error (_("Dwarf Error: unsupported DWP file version (%s)"
9624                " [in module %s]"),
9625              pulongest (version), dwp_file->name);
9626     }
9627   if (nr_slots != (nr_slots & -nr_slots))
9628     {
9629       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9630                " is not power of 2 [in module %s]"),
9631              pulongest (nr_slots), dwp_file->name);
9632     }
9633
9634   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9635   htab->version = version;
9636   htab->nr_columns = nr_columns;
9637   htab->nr_units = nr_units;
9638   htab->nr_slots = nr_slots;
9639   htab->hash_table = index_ptr;
9640   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9641
9642   /* Exit early if the table is empty.  */
9643   if (nr_slots == 0 || nr_units == 0
9644       || (version == 2 && nr_columns == 0))
9645     {
9646       /* All must be zero.  */
9647       if (nr_slots != 0 || nr_units != 0
9648           || (version == 2 && nr_columns != 0))
9649         {
9650           complaint (&symfile_complaints,
9651                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
9652                        " all zero [in modules %s]"),
9653                      dwp_file->name);
9654         }
9655       return htab;
9656     }
9657
9658   if (version == 1)
9659     {
9660       htab->section_pool.v1.indices =
9661         htab->unit_table + sizeof (uint32_t) * nr_slots;
9662       /* It's harder to decide whether the section is too small in v1.
9663          V1 is deprecated anyway so we punt.  */
9664     }
9665   else
9666     {
9667       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
9668       int *ids = htab->section_pool.v2.section_ids;
9669       /* Reverse map for error checking.  */
9670       int ids_seen[DW_SECT_MAX + 1];
9671       int i;
9672
9673       if (nr_columns < 2)
9674         {
9675           error (_("Dwarf Error: bad DWP hash table, too few columns"
9676                    " in section table [in module %s]"),
9677                  dwp_file->name);
9678         }
9679       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
9680         {
9681           error (_("Dwarf Error: bad DWP hash table, too many columns"
9682                    " in section table [in module %s]"),
9683                  dwp_file->name);
9684         }
9685       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9686       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9687       for (i = 0; i < nr_columns; ++i)
9688         {
9689           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
9690
9691           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
9692             {
9693               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
9694                        " in section table [in module %s]"),
9695                      id, dwp_file->name);
9696             }
9697           if (ids_seen[id] != -1)
9698             {
9699               error (_("Dwarf Error: bad DWP hash table, duplicate section"
9700                        " id %d in section table [in module %s]"),
9701                      id, dwp_file->name);
9702             }
9703           ids_seen[id] = i;
9704           ids[i] = id;
9705         }
9706       /* Must have exactly one info or types section.  */
9707       if (((ids_seen[DW_SECT_INFO] != -1)
9708            + (ids_seen[DW_SECT_TYPES] != -1))
9709           != 1)
9710         {
9711           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
9712                    " DWO info/types section [in module %s]"),
9713                  dwp_file->name);
9714         }
9715       /* Must have an abbrev section.  */
9716       if (ids_seen[DW_SECT_ABBREV] == -1)
9717         {
9718           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
9719                    " section [in module %s]"),
9720                  dwp_file->name);
9721         }
9722       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
9723       htab->section_pool.v2.sizes =
9724         htab->section_pool.v2.offsets + (sizeof (uint32_t)
9725                                          * nr_units * nr_columns);
9726       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
9727                                           * nr_units * nr_columns))
9728           > index_end)
9729         {
9730           error (_("Dwarf Error: DWP index section is corrupt (too small)"
9731                    " [in module %s]"),
9732                  dwp_file->name);
9733         }
9734     }
9735
9736   return htab;
9737 }
9738
9739 /* Update SECTIONS with the data from SECTP.
9740
9741    This function is like the other "locate" section routines that are
9742    passed to bfd_map_over_sections, but in this context the sections to
9743    read comes from the DWP V1 hash table, not the full ELF section table.
9744
9745    The result is non-zero for success, or zero if an error was found.  */
9746
9747 static int
9748 locate_v1_virtual_dwo_sections (asection *sectp,
9749                                 struct virtual_v1_dwo_sections *sections)
9750 {
9751   const struct dwop_section_names *names = &dwop_section_names;
9752
9753   if (section_is_p (sectp->name, &names->abbrev_dwo))
9754     {
9755       /* There can be only one.  */
9756       if (sections->abbrev.s.asection != NULL)
9757         return 0;
9758       sections->abbrev.s.asection = sectp;
9759       sections->abbrev.size = bfd_get_section_size (sectp);
9760     }
9761   else if (section_is_p (sectp->name, &names->info_dwo)
9762            || section_is_p (sectp->name, &names->types_dwo))
9763     {
9764       /* There can be only one.  */
9765       if (sections->info_or_types.s.asection != NULL)
9766         return 0;
9767       sections->info_or_types.s.asection = sectp;
9768       sections->info_or_types.size = bfd_get_section_size (sectp);
9769     }
9770   else if (section_is_p (sectp->name, &names->line_dwo))
9771     {
9772       /* There can be only one.  */
9773       if (sections->line.s.asection != NULL)
9774         return 0;
9775       sections->line.s.asection = sectp;
9776       sections->line.size = bfd_get_section_size (sectp);
9777     }
9778   else if (section_is_p (sectp->name, &names->loc_dwo))
9779     {
9780       /* There can be only one.  */
9781       if (sections->loc.s.asection != NULL)
9782         return 0;
9783       sections->loc.s.asection = sectp;
9784       sections->loc.size = bfd_get_section_size (sectp);
9785     }
9786   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9787     {
9788       /* There can be only one.  */
9789       if (sections->macinfo.s.asection != NULL)
9790         return 0;
9791       sections->macinfo.s.asection = sectp;
9792       sections->macinfo.size = bfd_get_section_size (sectp);
9793     }
9794   else if (section_is_p (sectp->name, &names->macro_dwo))
9795     {
9796       /* There can be only one.  */
9797       if (sections->macro.s.asection != NULL)
9798         return 0;
9799       sections->macro.s.asection = sectp;
9800       sections->macro.size = bfd_get_section_size (sectp);
9801     }
9802   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9803     {
9804       /* There can be only one.  */
9805       if (sections->str_offsets.s.asection != NULL)
9806         return 0;
9807       sections->str_offsets.s.asection = sectp;
9808       sections->str_offsets.size = bfd_get_section_size (sectp);
9809     }
9810   else
9811     {
9812       /* No other kind of section is valid.  */
9813       return 0;
9814     }
9815
9816   return 1;
9817 }
9818
9819 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9820    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9821    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9822    This is for DWP version 1 files.  */
9823
9824 static struct dwo_unit *
9825 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
9826                            uint32_t unit_index,
9827                            const char *comp_dir,
9828                            ULONGEST signature, int is_debug_types)
9829 {
9830   struct objfile *objfile = dwarf2_per_objfile->objfile;
9831   const struct dwp_hash_table *dwp_htab =
9832     is_debug_types ? dwp_file->tus : dwp_file->cus;
9833   bfd *dbfd = dwp_file->dbfd;
9834   const char *kind = is_debug_types ? "TU" : "CU";
9835   struct dwo_file *dwo_file;
9836   struct dwo_unit *dwo_unit;
9837   struct virtual_v1_dwo_sections sections;
9838   void **dwo_file_slot;
9839   char *virtual_dwo_name;
9840   struct dwarf2_section_info *cutu;
9841   struct cleanup *cleanups;
9842   int i;
9843
9844   gdb_assert (dwp_file->version == 1);
9845
9846   if (dwarf2_read_debug)
9847     {
9848       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
9849                           kind,
9850                           pulongest (unit_index), hex_string (signature),
9851                           dwp_file->name);
9852     }
9853
9854   /* Fetch the sections of this DWO unit.
9855      Put a limit on the number of sections we look for so that bad data
9856      doesn't cause us to loop forever.  */
9857
9858 #define MAX_NR_V1_DWO_SECTIONS \
9859   (1 /* .debug_info or .debug_types */ \
9860    + 1 /* .debug_abbrev */ \
9861    + 1 /* .debug_line */ \
9862    + 1 /* .debug_loc */ \
9863    + 1 /* .debug_str_offsets */ \
9864    + 1 /* .debug_macro or .debug_macinfo */ \
9865    + 1 /* trailing zero */)
9866
9867   memset (&sections, 0, sizeof (sections));
9868   cleanups = make_cleanup (null_cleanup, 0);
9869
9870   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
9871     {
9872       asection *sectp;
9873       uint32_t section_nr =
9874         read_4_bytes (dbfd,
9875                       dwp_htab->section_pool.v1.indices
9876                       + (unit_index + i) * sizeof (uint32_t));
9877
9878       if (section_nr == 0)
9879         break;
9880       if (section_nr >= dwp_file->num_sections)
9881         {
9882           error (_("Dwarf Error: bad DWP hash table, section number too large"
9883                    " [in module %s]"),
9884                  dwp_file->name);
9885         }
9886
9887       sectp = dwp_file->elf_sections[section_nr];
9888       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
9889         {
9890           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9891                    " [in module %s]"),
9892                  dwp_file->name);
9893         }
9894     }
9895
9896   if (i < 2
9897       || dwarf2_section_empty_p (&sections.info_or_types)
9898       || dwarf2_section_empty_p (&sections.abbrev))
9899     {
9900       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9901                " [in module %s]"),
9902              dwp_file->name);
9903     }
9904   if (i == MAX_NR_V1_DWO_SECTIONS)
9905     {
9906       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9907                " [in module %s]"),
9908              dwp_file->name);
9909     }
9910
9911   /* It's easier for the rest of the code if we fake a struct dwo_file and
9912      have dwo_unit "live" in that.  At least for now.
9913
9914      The DWP file can be made up of a random collection of CUs and TUs.
9915      However, for each CU + set of TUs that came from the same original DWO
9916      file, we can combine them back into a virtual DWO file to save space
9917      (fewer struct dwo_file objects to allocate).  Remember that for really
9918      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9919
9920   virtual_dwo_name =
9921     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9922                 get_section_id (&sections.abbrev),
9923                 get_section_id (&sections.line),
9924                 get_section_id (&sections.loc),
9925                 get_section_id (&sections.str_offsets));
9926   make_cleanup (xfree, virtual_dwo_name);
9927   /* Can we use an existing virtual DWO file?  */
9928   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9929   /* Create one if necessary.  */
9930   if (*dwo_file_slot == NULL)
9931     {
9932       if (dwarf2_read_debug)
9933         {
9934           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9935                               virtual_dwo_name);
9936         }
9937       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9938       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9939                                           virtual_dwo_name,
9940                                           strlen (virtual_dwo_name));
9941       dwo_file->comp_dir = comp_dir;
9942       dwo_file->sections.abbrev = sections.abbrev;
9943       dwo_file->sections.line = sections.line;
9944       dwo_file->sections.loc = sections.loc;
9945       dwo_file->sections.macinfo = sections.macinfo;
9946       dwo_file->sections.macro = sections.macro;
9947       dwo_file->sections.str_offsets = sections.str_offsets;
9948       /* The "str" section is global to the entire DWP file.  */
9949       dwo_file->sections.str = dwp_file->sections.str;
9950       /* The info or types section is assigned below to dwo_unit,
9951          there's no need to record it in dwo_file.
9952          Also, we can't simply record type sections in dwo_file because
9953          we record a pointer into the vector in dwo_unit.  As we collect more
9954          types we'll grow the vector and eventually have to reallocate space
9955          for it, invalidating all copies of pointers into the previous
9956          contents.  */
9957       *dwo_file_slot = dwo_file;
9958     }
9959   else
9960     {
9961       if (dwarf2_read_debug)
9962         {
9963           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9964                               virtual_dwo_name);
9965         }
9966       dwo_file = *dwo_file_slot;
9967     }
9968   do_cleanups (cleanups);
9969
9970   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9971   dwo_unit->dwo_file = dwo_file;
9972   dwo_unit->signature = signature;
9973   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9974                                      sizeof (struct dwarf2_section_info));
9975   *dwo_unit->section = sections.info_or_types;
9976   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9977
9978   return dwo_unit;
9979 }
9980
9981 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
9982    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
9983    piece within that section used by a TU/CU, return a virtual section
9984    of just that piece.  */
9985
9986 static struct dwarf2_section_info
9987 create_dwp_v2_section (struct dwarf2_section_info *section,
9988                        bfd_size_type offset, bfd_size_type size)
9989 {
9990   struct dwarf2_section_info result;
9991   asection *sectp;
9992
9993   gdb_assert (section != NULL);
9994   gdb_assert (!section->is_virtual);
9995
9996   memset (&result, 0, sizeof (result));
9997   result.s.containing_section = section;
9998   result.is_virtual = 1;
9999
10000   if (size == 0)
10001     return result;
10002
10003   sectp = get_section_bfd_section (section);
10004
10005   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10006      bounds of the real section.  This is a pretty-rare event, so just
10007      flag an error (easier) instead of a warning and trying to cope.  */
10008   if (sectp == NULL
10009       || offset + size > bfd_get_section_size (sectp))
10010     {
10011       bfd *abfd = sectp->owner;
10012
10013       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10014                " in section %s [in module %s]"),
10015              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10016              objfile_name (dwarf2_per_objfile->objfile));
10017     }
10018
10019   result.virtual_offset = offset;
10020   result.size = size;
10021   return result;
10022 }
10023
10024 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10025    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10026    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10027    This is for DWP version 2 files.  */
10028
10029 static struct dwo_unit *
10030 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10031                            uint32_t unit_index,
10032                            const char *comp_dir,
10033                            ULONGEST signature, int is_debug_types)
10034 {
10035   struct objfile *objfile = dwarf2_per_objfile->objfile;
10036   const struct dwp_hash_table *dwp_htab =
10037     is_debug_types ? dwp_file->tus : dwp_file->cus;
10038   bfd *dbfd = dwp_file->dbfd;
10039   const char *kind = is_debug_types ? "TU" : "CU";
10040   struct dwo_file *dwo_file;
10041   struct dwo_unit *dwo_unit;
10042   struct virtual_v2_dwo_sections sections;
10043   void **dwo_file_slot;
10044   char *virtual_dwo_name;
10045   struct dwarf2_section_info *cutu;
10046   struct cleanup *cleanups;
10047   int i;
10048
10049   gdb_assert (dwp_file->version == 2);
10050
10051   if (dwarf2_read_debug)
10052     {
10053       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10054                           kind,
10055                           pulongest (unit_index), hex_string (signature),
10056                           dwp_file->name);
10057     }
10058
10059   /* Fetch the section offsets of this DWO unit.  */
10060
10061   memset (&sections, 0, sizeof (sections));
10062   cleanups = make_cleanup (null_cleanup, 0);
10063
10064   for (i = 0; i < dwp_htab->nr_columns; ++i)
10065     {
10066       uint32_t offset = read_4_bytes (dbfd,
10067                                       dwp_htab->section_pool.v2.offsets
10068                                       + (((unit_index - 1) * dwp_htab->nr_columns
10069                                           + i)
10070                                          * sizeof (uint32_t)));
10071       uint32_t size = read_4_bytes (dbfd,
10072                                     dwp_htab->section_pool.v2.sizes
10073                                     + (((unit_index - 1) * dwp_htab->nr_columns
10074                                         + i)
10075                                        * sizeof (uint32_t)));
10076
10077       switch (dwp_htab->section_pool.v2.section_ids[i])
10078         {
10079         case DW_SECT_INFO:
10080         case DW_SECT_TYPES:
10081           sections.info_or_types_offset = offset;
10082           sections.info_or_types_size = size;
10083           break;
10084         case DW_SECT_ABBREV:
10085           sections.abbrev_offset = offset;
10086           sections.abbrev_size = size;
10087           break;
10088         case DW_SECT_LINE:
10089           sections.line_offset = offset;
10090           sections.line_size = size;
10091           break;
10092         case DW_SECT_LOC:
10093           sections.loc_offset = offset;
10094           sections.loc_size = size;
10095           break;
10096         case DW_SECT_STR_OFFSETS:
10097           sections.str_offsets_offset = offset;
10098           sections.str_offsets_size = size;
10099           break;
10100         case DW_SECT_MACINFO:
10101           sections.macinfo_offset = offset;
10102           sections.macinfo_size = size;
10103           break;
10104         case DW_SECT_MACRO:
10105           sections.macro_offset = offset;
10106           sections.macro_size = size;
10107           break;
10108         }
10109     }
10110
10111   /* It's easier for the rest of the code if we fake a struct dwo_file and
10112      have dwo_unit "live" in that.  At least for now.
10113
10114      The DWP file can be made up of a random collection of CUs and TUs.
10115      However, for each CU + set of TUs that came from the same original DWO
10116      file, we can combine them back into a virtual DWO file to save space
10117      (fewer struct dwo_file objects to allocate).  Remember that for really
10118      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10119
10120   virtual_dwo_name =
10121     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10122                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10123                 (long) (sections.line_size ? sections.line_offset : 0),
10124                 (long) (sections.loc_size ? sections.loc_offset : 0),
10125                 (long) (sections.str_offsets_size
10126                         ? sections.str_offsets_offset : 0));
10127   make_cleanup (xfree, virtual_dwo_name);
10128   /* Can we use an existing virtual DWO file?  */
10129   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10130   /* Create one if necessary.  */
10131   if (*dwo_file_slot == NULL)
10132     {
10133       if (dwarf2_read_debug)
10134         {
10135           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10136                               virtual_dwo_name);
10137         }
10138       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10139       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
10140                                           virtual_dwo_name,
10141                                           strlen (virtual_dwo_name));
10142       dwo_file->comp_dir = comp_dir;
10143       dwo_file->sections.abbrev =
10144         create_dwp_v2_section (&dwp_file->sections.abbrev,
10145                                sections.abbrev_offset, sections.abbrev_size);
10146       dwo_file->sections.line =
10147         create_dwp_v2_section (&dwp_file->sections.line,
10148                                sections.line_offset, sections.line_size);
10149       dwo_file->sections.loc =
10150         create_dwp_v2_section (&dwp_file->sections.loc,
10151                                sections.loc_offset, sections.loc_size);
10152       dwo_file->sections.macinfo =
10153         create_dwp_v2_section (&dwp_file->sections.macinfo,
10154                                sections.macinfo_offset, sections.macinfo_size);
10155       dwo_file->sections.macro =
10156         create_dwp_v2_section (&dwp_file->sections.macro,
10157                                sections.macro_offset, sections.macro_size);
10158       dwo_file->sections.str_offsets =
10159         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10160                                sections.str_offsets_offset,
10161                                sections.str_offsets_size);
10162       /* The "str" section is global to the entire DWP file.  */
10163       dwo_file->sections.str = dwp_file->sections.str;
10164       /* The info or types section is assigned below to dwo_unit,
10165          there's no need to record it in dwo_file.
10166          Also, we can't simply record type sections in dwo_file because
10167          we record a pointer into the vector in dwo_unit.  As we collect more
10168          types we'll grow the vector and eventually have to reallocate space
10169          for it, invalidating all copies of pointers into the previous
10170          contents.  */
10171       *dwo_file_slot = dwo_file;
10172     }
10173   else
10174     {
10175       if (dwarf2_read_debug)
10176         {
10177           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10178                               virtual_dwo_name);
10179         }
10180       dwo_file = *dwo_file_slot;
10181     }
10182   do_cleanups (cleanups);
10183
10184   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10185   dwo_unit->dwo_file = dwo_file;
10186   dwo_unit->signature = signature;
10187   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
10188                                      sizeof (struct dwarf2_section_info));
10189   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10190                                               ? &dwp_file->sections.types
10191                                               : &dwp_file->sections.info,
10192                                               sections.info_or_types_offset,
10193                                               sections.info_or_types_size);
10194   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10195
10196   return dwo_unit;
10197 }
10198
10199 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10200    Returns NULL if the signature isn't found.  */
10201
10202 static struct dwo_unit *
10203 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10204                         ULONGEST signature, int is_debug_types)
10205 {
10206   const struct dwp_hash_table *dwp_htab =
10207     is_debug_types ? dwp_file->tus : dwp_file->cus;
10208   bfd *dbfd = dwp_file->dbfd;
10209   uint32_t mask = dwp_htab->nr_slots - 1;
10210   uint32_t hash = signature & mask;
10211   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10212   unsigned int i;
10213   void **slot;
10214   struct dwo_unit find_dwo_cu, *dwo_cu;
10215
10216   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10217   find_dwo_cu.signature = signature;
10218   slot = htab_find_slot (is_debug_types
10219                          ? dwp_file->loaded_tus
10220                          : dwp_file->loaded_cus,
10221                          &find_dwo_cu, INSERT);
10222
10223   if (*slot != NULL)
10224     return *slot;
10225
10226   /* Use a for loop so that we don't loop forever on bad debug info.  */
10227   for (i = 0; i < dwp_htab->nr_slots; ++i)
10228     {
10229       ULONGEST signature_in_table;
10230
10231       signature_in_table =
10232         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10233       if (signature_in_table == signature)
10234         {
10235           uint32_t unit_index =
10236             read_4_bytes (dbfd,
10237                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10238
10239           if (dwp_file->version == 1)
10240             {
10241               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10242                                                  comp_dir, signature,
10243                                                  is_debug_types);
10244             }
10245           else
10246             {
10247               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10248                                                  comp_dir, signature,
10249                                                  is_debug_types);
10250             }
10251           return *slot;
10252         }
10253       if (signature_in_table == 0)
10254         return NULL;
10255       hash = (hash + hash2) & mask;
10256     }
10257
10258   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10259            " [in module %s]"),
10260          dwp_file->name);
10261 }
10262
10263 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10264    Open the file specified by FILE_NAME and hand it off to BFD for
10265    preliminary analysis.  Return a newly initialized bfd *, which
10266    includes a canonicalized copy of FILE_NAME.
10267    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10268    SEARCH_CWD is true if the current directory is to be searched.
10269    It will be searched before debug-file-directory.
10270    If successful, the file is added to the bfd include table of the
10271    objfile's bfd (see gdb_bfd_record_inclusion).
10272    If unable to find/open the file, return NULL.
10273    NOTE: This function is derived from symfile_bfd_open.  */
10274
10275 static bfd *
10276 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10277 {
10278   bfd *sym_bfd;
10279   int desc, flags;
10280   char *absolute_name;
10281   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10282      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10283      to debug_file_directory.  */
10284   char *search_path;
10285   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10286
10287   if (search_cwd)
10288     {
10289       if (*debug_file_directory != '\0')
10290         search_path = concat (".", dirname_separator_string,
10291                               debug_file_directory, NULL);
10292       else
10293         search_path = xstrdup (".");
10294     }
10295   else
10296     search_path = xstrdup (debug_file_directory);
10297
10298   flags = OPF_RETURN_REALPATH;
10299   if (is_dwp)
10300     flags |= OPF_SEARCH_IN_PATH;
10301   desc = openp (search_path, flags, file_name,
10302                 O_RDONLY | O_BINARY, &absolute_name);
10303   xfree (search_path);
10304   if (desc < 0)
10305     return NULL;
10306
10307   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
10308   xfree (absolute_name);
10309   if (sym_bfd == NULL)
10310     return NULL;
10311   bfd_set_cacheable (sym_bfd, 1);
10312
10313   if (!bfd_check_format (sym_bfd, bfd_object))
10314     {
10315       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
10316       return NULL;
10317     }
10318
10319   /* Success.  Record the bfd as having been included by the objfile's bfd.
10320      This is important because things like demangled_names_hash lives in the
10321      objfile's per_bfd space and may have references to things like symbol
10322      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10323   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd);
10324
10325   return sym_bfd;
10326 }
10327
10328 /* Try to open DWO file FILE_NAME.
10329    COMP_DIR is the DW_AT_comp_dir attribute.
10330    The result is the bfd handle of the file.
10331    If there is a problem finding or opening the file, return NULL.
10332    Upon success, the canonicalized path of the file is stored in the bfd,
10333    same as symfile_bfd_open.  */
10334
10335 static bfd *
10336 open_dwo_file (const char *file_name, const char *comp_dir)
10337 {
10338   bfd *abfd;
10339
10340   if (IS_ABSOLUTE_PATH (file_name))
10341     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10342
10343   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10344
10345   if (comp_dir != NULL)
10346     {
10347       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
10348
10349       /* NOTE: If comp_dir is a relative path, this will also try the
10350          search path, which seems useful.  */
10351       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
10352       xfree (path_to_try);
10353       if (abfd != NULL)
10354         return abfd;
10355     }
10356
10357   /* That didn't work, try debug-file-directory, which, despite its name,
10358      is a list of paths.  */
10359
10360   if (*debug_file_directory == '\0')
10361     return NULL;
10362
10363   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10364 }
10365
10366 /* This function is mapped across the sections and remembers the offset and
10367    size of each of the DWO debugging sections we are interested in.  */
10368
10369 static void
10370 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10371 {
10372   struct dwo_sections *dwo_sections = dwo_sections_ptr;
10373   const struct dwop_section_names *names = &dwop_section_names;
10374
10375   if (section_is_p (sectp->name, &names->abbrev_dwo))
10376     {
10377       dwo_sections->abbrev.s.asection = sectp;
10378       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10379     }
10380   else if (section_is_p (sectp->name, &names->info_dwo))
10381     {
10382       dwo_sections->info.s.asection = sectp;
10383       dwo_sections->info.size = bfd_get_section_size (sectp);
10384     }
10385   else if (section_is_p (sectp->name, &names->line_dwo))
10386     {
10387       dwo_sections->line.s.asection = sectp;
10388       dwo_sections->line.size = bfd_get_section_size (sectp);
10389     }
10390   else if (section_is_p (sectp->name, &names->loc_dwo))
10391     {
10392       dwo_sections->loc.s.asection = sectp;
10393       dwo_sections->loc.size = bfd_get_section_size (sectp);
10394     }
10395   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10396     {
10397       dwo_sections->macinfo.s.asection = sectp;
10398       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10399     }
10400   else if (section_is_p (sectp->name, &names->macro_dwo))
10401     {
10402       dwo_sections->macro.s.asection = sectp;
10403       dwo_sections->macro.size = bfd_get_section_size (sectp);
10404     }
10405   else if (section_is_p (sectp->name, &names->str_dwo))
10406     {
10407       dwo_sections->str.s.asection = sectp;
10408       dwo_sections->str.size = bfd_get_section_size (sectp);
10409     }
10410   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10411     {
10412       dwo_sections->str_offsets.s.asection = sectp;
10413       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10414     }
10415   else if (section_is_p (sectp->name, &names->types_dwo))
10416     {
10417       struct dwarf2_section_info type_section;
10418
10419       memset (&type_section, 0, sizeof (type_section));
10420       type_section.s.asection = sectp;
10421       type_section.size = bfd_get_section_size (sectp);
10422       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10423                      &type_section);
10424     }
10425 }
10426
10427 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10428    by PER_CU.  This is for the non-DWP case.
10429    The result is NULL if DWO_NAME can't be found.  */
10430
10431 static struct dwo_file *
10432 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10433                         const char *dwo_name, const char *comp_dir)
10434 {
10435   struct objfile *objfile = dwarf2_per_objfile->objfile;
10436   struct dwo_file *dwo_file;
10437   bfd *dbfd;
10438   struct cleanup *cleanups;
10439
10440   dbfd = open_dwo_file (dwo_name, comp_dir);
10441   if (dbfd == NULL)
10442     {
10443       if (dwarf2_read_debug)
10444         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10445       return NULL;
10446     }
10447   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10448   dwo_file->dwo_name = dwo_name;
10449   dwo_file->comp_dir = comp_dir;
10450   dwo_file->dbfd = dbfd;
10451
10452   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10453
10454   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
10455
10456   dwo_file->cu = create_dwo_cu (dwo_file);
10457
10458   dwo_file->tus = create_debug_types_hash_table (dwo_file,
10459                                                  dwo_file->sections.types);
10460
10461   discard_cleanups (cleanups);
10462
10463   if (dwarf2_read_debug)
10464     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10465
10466   return dwo_file;
10467 }
10468
10469 /* This function is mapped across the sections and remembers the offset and
10470    size of each of the DWP debugging sections common to version 1 and 2 that
10471    we are interested in.  */
10472
10473 static void
10474 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10475                                    void *dwp_file_ptr)
10476 {
10477   struct dwp_file *dwp_file = dwp_file_ptr;
10478   const struct dwop_section_names *names = &dwop_section_names;
10479   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10480
10481   /* Record the ELF section number for later lookup: this is what the
10482      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10483   gdb_assert (elf_section_nr < dwp_file->num_sections);
10484   dwp_file->elf_sections[elf_section_nr] = sectp;
10485
10486   /* Look for specific sections that we need.  */
10487   if (section_is_p (sectp->name, &names->str_dwo))
10488     {
10489       dwp_file->sections.str.s.asection = sectp;
10490       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10491     }
10492   else if (section_is_p (sectp->name, &names->cu_index))
10493     {
10494       dwp_file->sections.cu_index.s.asection = sectp;
10495       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10496     }
10497   else if (section_is_p (sectp->name, &names->tu_index))
10498     {
10499       dwp_file->sections.tu_index.s.asection = sectp;
10500       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10501     }
10502 }
10503
10504 /* This function is mapped across the sections and remembers the offset and
10505    size of each of the DWP version 2 debugging sections that we are interested
10506    in.  This is split into a separate function because we don't know if we
10507    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10508
10509 static void
10510 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10511 {
10512   struct dwp_file *dwp_file = dwp_file_ptr;
10513   const struct dwop_section_names *names = &dwop_section_names;
10514   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10515
10516   /* Record the ELF section number for later lookup: this is what the
10517      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10518   gdb_assert (elf_section_nr < dwp_file->num_sections);
10519   dwp_file->elf_sections[elf_section_nr] = sectp;
10520
10521   /* Look for specific sections that we need.  */
10522   if (section_is_p (sectp->name, &names->abbrev_dwo))
10523     {
10524       dwp_file->sections.abbrev.s.asection = sectp;
10525       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10526     }
10527   else if (section_is_p (sectp->name, &names->info_dwo))
10528     {
10529       dwp_file->sections.info.s.asection = sectp;
10530       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10531     }
10532   else if (section_is_p (sectp->name, &names->line_dwo))
10533     {
10534       dwp_file->sections.line.s.asection = sectp;
10535       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10536     }
10537   else if (section_is_p (sectp->name, &names->loc_dwo))
10538     {
10539       dwp_file->sections.loc.s.asection = sectp;
10540       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10541     }
10542   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10543     {
10544       dwp_file->sections.macinfo.s.asection = sectp;
10545       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10546     }
10547   else if (section_is_p (sectp->name, &names->macro_dwo))
10548     {
10549       dwp_file->sections.macro.s.asection = sectp;
10550       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10551     }
10552   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10553     {
10554       dwp_file->sections.str_offsets.s.asection = sectp;
10555       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10556     }
10557   else if (section_is_p (sectp->name, &names->types_dwo))
10558     {
10559       dwp_file->sections.types.s.asection = sectp;
10560       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10561     }
10562 }
10563
10564 /* Hash function for dwp_file loaded CUs/TUs.  */
10565
10566 static hashval_t
10567 hash_dwp_loaded_cutus (const void *item)
10568 {
10569   const struct dwo_unit *dwo_unit = item;
10570
10571   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10572   return dwo_unit->signature;
10573 }
10574
10575 /* Equality function for dwp_file loaded CUs/TUs.  */
10576
10577 static int
10578 eq_dwp_loaded_cutus (const void *a, const void *b)
10579 {
10580   const struct dwo_unit *dua = a;
10581   const struct dwo_unit *dub = b;
10582
10583   return dua->signature == dub->signature;
10584 }
10585
10586 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10587
10588 static htab_t
10589 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10590 {
10591   return htab_create_alloc_ex (3,
10592                                hash_dwp_loaded_cutus,
10593                                eq_dwp_loaded_cutus,
10594                                NULL,
10595                                &objfile->objfile_obstack,
10596                                hashtab_obstack_allocate,
10597                                dummy_obstack_deallocate);
10598 }
10599
10600 /* Try to open DWP file FILE_NAME.
10601    The result is the bfd handle of the file.
10602    If there is a problem finding or opening the file, return NULL.
10603    Upon success, the canonicalized path of the file is stored in the bfd,
10604    same as symfile_bfd_open.  */
10605
10606 static bfd *
10607 open_dwp_file (const char *file_name)
10608 {
10609   bfd *abfd;
10610
10611   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
10612   if (abfd != NULL)
10613     return abfd;
10614
10615   /* Work around upstream bug 15652.
10616      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10617      [Whether that's a "bug" is debatable, but it is getting in our way.]
10618      We have no real idea where the dwp file is, because gdb's realpath-ing
10619      of the executable's path may have discarded the needed info.
10620      [IWBN if the dwp file name was recorded in the executable, akin to
10621      .gnu_debuglink, but that doesn't exist yet.]
10622      Strip the directory from FILE_NAME and search again.  */
10623   if (*debug_file_directory != '\0')
10624     {
10625       /* Don't implicitly search the current directory here.
10626          If the user wants to search "." to handle this case,
10627          it must be added to debug-file-directory.  */
10628       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
10629                                  0 /*search_cwd*/);
10630     }
10631
10632   return NULL;
10633 }
10634
10635 /* Initialize the use of the DWP file for the current objfile.
10636    By convention the name of the DWP file is ${objfile}.dwp.
10637    The result is NULL if it can't be found.  */
10638
10639 static struct dwp_file *
10640 open_and_init_dwp_file (void)
10641 {
10642   struct objfile *objfile = dwarf2_per_objfile->objfile;
10643   struct dwp_file *dwp_file;
10644   char *dwp_name;
10645   bfd *dbfd;
10646   struct cleanup *cleanups;
10647
10648   /* Try to find first .dwp for the binary file before any symbolic links
10649      resolving.  */
10650   dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
10651   cleanups = make_cleanup (xfree, dwp_name);
10652
10653   dbfd = open_dwp_file (dwp_name);
10654   if (dbfd == NULL
10655       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
10656     {
10657       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
10658       dwp_name = xstrprintf ("%s.dwp", objfile_name (objfile));
10659       make_cleanup (xfree, dwp_name);
10660       dbfd = open_dwp_file (dwp_name);
10661     }
10662
10663   if (dbfd == NULL)
10664     {
10665       if (dwarf2_read_debug)
10666         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
10667       do_cleanups (cleanups);
10668       return NULL;
10669     }
10670   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
10671   dwp_file->name = bfd_get_filename (dbfd);
10672   dwp_file->dbfd = dbfd;
10673   do_cleanups (cleanups);
10674
10675   /* +1: section 0 is unused */
10676   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
10677   dwp_file->elf_sections =
10678     OBSTACK_CALLOC (&objfile->objfile_obstack,
10679                     dwp_file->num_sections, asection *);
10680
10681   bfd_map_over_sections (dbfd, dwarf2_locate_common_dwp_sections, dwp_file);
10682
10683   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
10684
10685   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
10686
10687   /* The DWP file version is stored in the hash table.  Oh well.  */
10688   if (dwp_file->cus->version != dwp_file->tus->version)
10689     {
10690       /* Technically speaking, we should try to limp along, but this is
10691          pretty bizarre.  We use pulongest here because that's the established
10692          portability solution (e.g, we cannot use %u for uint32_t).  */
10693       error (_("Dwarf Error: DWP file CU version %s doesn't match"
10694                " TU version %s [in DWP file %s]"),
10695              pulongest (dwp_file->cus->version),
10696              pulongest (dwp_file->tus->version), dwp_name);
10697     }
10698   dwp_file->version = dwp_file->cus->version;
10699
10700   if (dwp_file->version == 2)
10701     bfd_map_over_sections (dbfd, dwarf2_locate_v2_dwp_sections, dwp_file);
10702
10703   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
10704   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
10705
10706   if (dwarf2_read_debug)
10707     {
10708       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
10709       fprintf_unfiltered (gdb_stdlog,
10710                           "    %s CUs, %s TUs\n",
10711                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
10712                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
10713     }
10714
10715   return dwp_file;
10716 }
10717
10718 /* Wrapper around open_and_init_dwp_file, only open it once.  */
10719
10720 static struct dwp_file *
10721 get_dwp_file (void)
10722 {
10723   if (! dwarf2_per_objfile->dwp_checked)
10724     {
10725       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
10726       dwarf2_per_objfile->dwp_checked = 1;
10727     }
10728   return dwarf2_per_objfile->dwp_file;
10729 }
10730
10731 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
10732    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
10733    or in the DWP file for the objfile, referenced by THIS_UNIT.
10734    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
10735    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
10736
10737    This is called, for example, when wanting to read a variable with a
10738    complex location.  Therefore we don't want to do file i/o for every call.
10739    Therefore we don't want to look for a DWO file on every call.
10740    Therefore we first see if we've already seen SIGNATURE in a DWP file,
10741    then we check if we've already seen DWO_NAME, and only THEN do we check
10742    for a DWO file.
10743
10744    The result is a pointer to the dwo_unit object or NULL if we didn't find it
10745    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
10746
10747 static struct dwo_unit *
10748 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
10749                  const char *dwo_name, const char *comp_dir,
10750                  ULONGEST signature, int is_debug_types)
10751 {
10752   struct objfile *objfile = dwarf2_per_objfile->objfile;
10753   const char *kind = is_debug_types ? "TU" : "CU";
10754   void **dwo_file_slot;
10755   struct dwo_file *dwo_file;
10756   struct dwp_file *dwp_file;
10757
10758   /* First see if there's a DWP file.
10759      If we have a DWP file but didn't find the DWO inside it, don't
10760      look for the original DWO file.  It makes gdb behave differently
10761      depending on whether one is debugging in the build tree.  */
10762
10763   dwp_file = get_dwp_file ();
10764   if (dwp_file != NULL)
10765     {
10766       const struct dwp_hash_table *dwp_htab =
10767         is_debug_types ? dwp_file->tus : dwp_file->cus;
10768
10769       if (dwp_htab != NULL)
10770         {
10771           struct dwo_unit *dwo_cutu =
10772             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
10773                                     signature, is_debug_types);
10774
10775           if (dwo_cutu != NULL)
10776             {
10777               if (dwarf2_read_debug)
10778                 {
10779                   fprintf_unfiltered (gdb_stdlog,
10780                                       "Virtual DWO %s %s found: @%s\n",
10781                                       kind, hex_string (signature),
10782                                       host_address_to_string (dwo_cutu));
10783                 }
10784               return dwo_cutu;
10785             }
10786         }
10787     }
10788   else
10789     {
10790       /* No DWP file, look for the DWO file.  */
10791
10792       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
10793       if (*dwo_file_slot == NULL)
10794         {
10795           /* Read in the file and build a table of the CUs/TUs it contains.  */
10796           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
10797         }
10798       /* NOTE: This will be NULL if unable to open the file.  */
10799       dwo_file = *dwo_file_slot;
10800
10801       if (dwo_file != NULL)
10802         {
10803           struct dwo_unit *dwo_cutu = NULL;
10804
10805           if (is_debug_types && dwo_file->tus)
10806             {
10807               struct dwo_unit find_dwo_cutu;
10808
10809               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
10810               find_dwo_cutu.signature = signature;
10811               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
10812             }
10813           else if (!is_debug_types && dwo_file->cu)
10814             {
10815               if (signature == dwo_file->cu->signature)
10816                 dwo_cutu = dwo_file->cu;
10817             }
10818
10819           if (dwo_cutu != NULL)
10820             {
10821               if (dwarf2_read_debug)
10822                 {
10823                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
10824                                       kind, dwo_name, hex_string (signature),
10825                                       host_address_to_string (dwo_cutu));
10826                 }
10827               return dwo_cutu;
10828             }
10829         }
10830     }
10831
10832   /* We didn't find it.  This could mean a dwo_id mismatch, or
10833      someone deleted the DWO/DWP file, or the search path isn't set up
10834      correctly to find the file.  */
10835
10836   if (dwarf2_read_debug)
10837     {
10838       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
10839                           kind, dwo_name, hex_string (signature));
10840     }
10841
10842   /* This is a warning and not a complaint because it can be caused by
10843      pilot error (e.g., user accidentally deleting the DWO).  */
10844   {
10845     /* Print the name of the DWP file if we looked there, helps the user
10846        better diagnose the problem.  */
10847     char *dwp_text = NULL;
10848     struct cleanup *cleanups;
10849
10850     if (dwp_file != NULL)
10851       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
10852     cleanups = make_cleanup (xfree, dwp_text);
10853
10854     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
10855                " [in module %s]"),
10856              kind, dwo_name, hex_string (signature),
10857              dwp_text != NULL ? dwp_text : "",
10858              this_unit->is_debug_types ? "TU" : "CU",
10859              this_unit->offset.sect_off, objfile_name (objfile));
10860
10861     do_cleanups (cleanups);
10862   }
10863   return NULL;
10864 }
10865
10866 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
10867    See lookup_dwo_cutu_unit for details.  */
10868
10869 static struct dwo_unit *
10870 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
10871                       const char *dwo_name, const char *comp_dir,
10872                       ULONGEST signature)
10873 {
10874   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
10875 }
10876
10877 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
10878    See lookup_dwo_cutu_unit for details.  */
10879
10880 static struct dwo_unit *
10881 lookup_dwo_type_unit (struct signatured_type *this_tu,
10882                       const char *dwo_name, const char *comp_dir)
10883 {
10884   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
10885 }
10886
10887 /* Traversal function for queue_and_load_all_dwo_tus.  */
10888
10889 static int
10890 queue_and_load_dwo_tu (void **slot, void *info)
10891 {
10892   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
10893   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
10894   ULONGEST signature = dwo_unit->signature;
10895   struct signatured_type *sig_type =
10896     lookup_dwo_signatured_type (per_cu->cu, signature);
10897
10898   if (sig_type != NULL)
10899     {
10900       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
10901
10902       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
10903          a real dependency of PER_CU on SIG_TYPE.  That is detected later
10904          while processing PER_CU.  */
10905       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
10906         load_full_type_unit (sig_cu);
10907       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
10908     }
10909
10910   return 1;
10911 }
10912
10913 /* Queue all TUs contained in the DWO of PER_CU to be read in.
10914    The DWO may have the only definition of the type, though it may not be
10915    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
10916    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
10917
10918 static void
10919 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
10920 {
10921   struct dwo_unit *dwo_unit;
10922   struct dwo_file *dwo_file;
10923
10924   gdb_assert (!per_cu->is_debug_types);
10925   gdb_assert (get_dwp_file () == NULL);
10926   gdb_assert (per_cu->cu != NULL);
10927
10928   dwo_unit = per_cu->cu->dwo_unit;
10929   gdb_assert (dwo_unit != NULL);
10930
10931   dwo_file = dwo_unit->dwo_file;
10932   if (dwo_file->tus != NULL)
10933     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
10934 }
10935
10936 /* Free all resources associated with DWO_FILE.
10937    Close the DWO file and munmap the sections.
10938    All memory should be on the objfile obstack.  */
10939
10940 static void
10941 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
10942 {
10943   int ix;
10944   struct dwarf2_section_info *section;
10945
10946   /* Note: dbfd is NULL for virtual DWO files.  */
10947   gdb_bfd_unref (dwo_file->dbfd);
10948
10949   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
10950 }
10951
10952 /* Wrapper for free_dwo_file for use in cleanups.  */
10953
10954 static void
10955 free_dwo_file_cleanup (void *arg)
10956 {
10957   struct dwo_file *dwo_file = (struct dwo_file *) arg;
10958   struct objfile *objfile = dwarf2_per_objfile->objfile;
10959
10960   free_dwo_file (dwo_file, objfile);
10961 }
10962
10963 /* Traversal function for free_dwo_files.  */
10964
10965 static int
10966 free_dwo_file_from_slot (void **slot, void *info)
10967 {
10968   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
10969   struct objfile *objfile = (struct objfile *) info;
10970
10971   free_dwo_file (dwo_file, objfile);
10972
10973   return 1;
10974 }
10975
10976 /* Free all resources associated with DWO_FILES.  */
10977
10978 static void
10979 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
10980 {
10981   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
10982 }
10983 \f
10984 /* Read in various DIEs.  */
10985
10986 /* qsort helper for inherit_abstract_dies.  */
10987
10988 static int
10989 unsigned_int_compar (const void *ap, const void *bp)
10990 {
10991   unsigned int a = *(unsigned int *) ap;
10992   unsigned int b = *(unsigned int *) bp;
10993
10994   return (a > b) - (b > a);
10995 }
10996
10997 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
10998    Inherit only the children of the DW_AT_abstract_origin DIE not being
10999    already referenced by DW_AT_abstract_origin from the children of the
11000    current DIE.  */
11001
11002 static void
11003 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11004 {
11005   struct die_info *child_die;
11006   unsigned die_children_count;
11007   /* CU offsets which were referenced by children of the current DIE.  */
11008   sect_offset *offsets;
11009   sect_offset *offsets_end, *offsetp;
11010   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11011   struct die_info *origin_die;
11012   /* Iterator of the ORIGIN_DIE children.  */
11013   struct die_info *origin_child_die;
11014   struct cleanup *cleanups;
11015   struct attribute *attr;
11016   struct dwarf2_cu *origin_cu;
11017   struct pending **origin_previous_list_in_scope;
11018
11019   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11020   if (!attr)
11021     return;
11022
11023   /* Note that following die references may follow to a die in a
11024      different cu.  */
11025
11026   origin_cu = cu;
11027   origin_die = follow_die_ref (die, attr, &origin_cu);
11028
11029   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11030      symbols in.  */
11031   origin_previous_list_in_scope = origin_cu->list_in_scope;
11032   origin_cu->list_in_scope = cu->list_in_scope;
11033
11034   if (die->tag != origin_die->tag
11035       && !(die->tag == DW_TAG_inlined_subroutine
11036            && origin_die->tag == DW_TAG_subprogram))
11037     complaint (&symfile_complaints,
11038                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11039                die->offset.sect_off, origin_die->offset.sect_off);
11040
11041   child_die = die->child;
11042   die_children_count = 0;
11043   while (child_die && child_die->tag)
11044     {
11045       child_die = sibling_die (child_die);
11046       die_children_count++;
11047     }
11048   offsets = xmalloc (sizeof (*offsets) * die_children_count);
11049   cleanups = make_cleanup (xfree, offsets);
11050
11051   offsets_end = offsets;
11052   child_die = die->child;
11053   while (child_die && child_die->tag)
11054     {
11055       /* For each CHILD_DIE, find the corresponding child of
11056          ORIGIN_DIE.  If there is more than one layer of
11057          DW_AT_abstract_origin, follow them all; there shouldn't be,
11058          but GCC versions at least through 4.4 generate this (GCC PR
11059          40573).  */
11060       struct die_info *child_origin_die = child_die;
11061       struct dwarf2_cu *child_origin_cu = cu;
11062
11063       while (1)
11064         {
11065           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11066                               child_origin_cu);
11067           if (attr == NULL)
11068             break;
11069           child_origin_die = follow_die_ref (child_origin_die, attr,
11070                                              &child_origin_cu);
11071         }
11072
11073       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11074          counterpart may exist.  */
11075       if (child_origin_die != child_die)
11076         {
11077           if (child_die->tag != child_origin_die->tag
11078               && !(child_die->tag == DW_TAG_inlined_subroutine
11079                    && child_origin_die->tag == DW_TAG_subprogram))
11080             complaint (&symfile_complaints,
11081                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11082                          "different tags"), child_die->offset.sect_off,
11083                        child_origin_die->offset.sect_off);
11084           if (child_origin_die->parent != origin_die)
11085             complaint (&symfile_complaints,
11086                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11087                          "different parents"), child_die->offset.sect_off,
11088                        child_origin_die->offset.sect_off);
11089           else
11090             *offsets_end++ = child_origin_die->offset;
11091         }
11092       child_die = sibling_die (child_die);
11093     }
11094   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11095          unsigned_int_compar);
11096   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11097     if (offsetp[-1].sect_off == offsetp->sect_off)
11098       complaint (&symfile_complaints,
11099                  _("Multiple children of DIE 0x%x refer "
11100                    "to DIE 0x%x as their abstract origin"),
11101                  die->offset.sect_off, offsetp->sect_off);
11102
11103   offsetp = offsets;
11104   origin_child_die = origin_die->child;
11105   while (origin_child_die && origin_child_die->tag)
11106     {
11107       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11108       while (offsetp < offsets_end
11109              && offsetp->sect_off < origin_child_die->offset.sect_off)
11110         offsetp++;
11111       if (offsetp >= offsets_end
11112           || offsetp->sect_off > origin_child_die->offset.sect_off)
11113         {
11114           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11115              Check whether we're already processing ORIGIN_CHILD_DIE.
11116              This can happen with mutually referenced abstract_origins.
11117              PR 16581.  */
11118           if (!origin_child_die->in_process)
11119             process_die (origin_child_die, origin_cu);
11120         }
11121       origin_child_die = sibling_die (origin_child_die);
11122     }
11123   origin_cu->list_in_scope = origin_previous_list_in_scope;
11124
11125   do_cleanups (cleanups);
11126 }
11127
11128 static void
11129 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11130 {
11131   struct objfile *objfile = cu->objfile;
11132   struct context_stack *new;
11133   CORE_ADDR lowpc;
11134   CORE_ADDR highpc;
11135   struct die_info *child_die;
11136   struct attribute *attr, *call_line, *call_file;
11137   const char *name;
11138   CORE_ADDR baseaddr;
11139   struct block *block;
11140   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11141   VEC (symbolp) *template_args = NULL;
11142   struct template_symbol *templ_func = NULL;
11143
11144   if (inlined_func)
11145     {
11146       /* If we do not have call site information, we can't show the
11147          caller of this inlined function.  That's too confusing, so
11148          only use the scope for local variables.  */
11149       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11150       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11151       if (call_line == NULL || call_file == NULL)
11152         {
11153           read_lexical_block_scope (die, cu);
11154           return;
11155         }
11156     }
11157
11158   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11159
11160   name = dwarf2_name (die, cu);
11161
11162   /* Ignore functions with missing or empty names.  These are actually
11163      illegal according to the DWARF standard.  */
11164   if (name == NULL)
11165     {
11166       complaint (&symfile_complaints,
11167                  _("missing name for subprogram DIE at %d"),
11168                  die->offset.sect_off);
11169       return;
11170     }
11171
11172   /* Ignore functions with missing or invalid low and high pc attributes.  */
11173   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11174     {
11175       attr = dwarf2_attr (die, DW_AT_external, cu);
11176       if (!attr || !DW_UNSND (attr))
11177         complaint (&symfile_complaints,
11178                    _("cannot get low and high bounds "
11179                      "for subprogram DIE at %d"),
11180                    die->offset.sect_off);
11181       return;
11182     }
11183
11184   lowpc += baseaddr;
11185   highpc += baseaddr;
11186
11187   /* If we have any template arguments, then we must allocate a
11188      different sort of symbol.  */
11189   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11190     {
11191       if (child_die->tag == DW_TAG_template_type_param
11192           || child_die->tag == DW_TAG_template_value_param)
11193         {
11194           templ_func = allocate_template_symbol (objfile);
11195           templ_func->base.is_cplus_template_function = 1;
11196           break;
11197         }
11198     }
11199
11200   new = push_context (0, lowpc);
11201   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
11202                                (struct symbol *) templ_func);
11203
11204   /* If there is a location expression for DW_AT_frame_base, record
11205      it.  */
11206   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11207   if (attr)
11208     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
11209
11210   cu->list_in_scope = &local_symbols;
11211
11212   if (die->child != NULL)
11213     {
11214       child_die = die->child;
11215       while (child_die && child_die->tag)
11216         {
11217           if (child_die->tag == DW_TAG_template_type_param
11218               || child_die->tag == DW_TAG_template_value_param)
11219             {
11220               struct symbol *arg = new_symbol (child_die, NULL, cu);
11221
11222               if (arg != NULL)
11223                 VEC_safe_push (symbolp, template_args, arg);
11224             }
11225           else
11226             process_die (child_die, cu);
11227           child_die = sibling_die (child_die);
11228         }
11229     }
11230
11231   inherit_abstract_dies (die, cu);
11232
11233   /* If we have a DW_AT_specification, we might need to import using
11234      directives from the context of the specification DIE.  See the
11235      comment in determine_prefix.  */
11236   if (cu->language == language_cplus
11237       && dwarf2_attr (die, DW_AT_specification, cu))
11238     {
11239       struct dwarf2_cu *spec_cu = cu;
11240       struct die_info *spec_die = die_specification (die, &spec_cu);
11241
11242       while (spec_die)
11243         {
11244           child_die = spec_die->child;
11245           while (child_die && child_die->tag)
11246             {
11247               if (child_die->tag == DW_TAG_imported_module)
11248                 process_die (child_die, spec_cu);
11249               child_die = sibling_die (child_die);
11250             }
11251
11252           /* In some cases, GCC generates specification DIEs that
11253              themselves contain DW_AT_specification attributes.  */
11254           spec_die = die_specification (spec_die, &spec_cu);
11255         }
11256     }
11257
11258   new = pop_context ();
11259   /* Make a block for the local symbols within.  */
11260   block = finish_block (new->name, &local_symbols, new->old_blocks,
11261                         lowpc, highpc, objfile);
11262
11263   /* For C++, set the block's scope.  */
11264   if ((cu->language == language_cplus || cu->language == language_fortran)
11265       && cu->processing_has_namespace_info)
11266     block_set_scope (block, determine_prefix (die, cu),
11267                      &objfile->objfile_obstack);
11268
11269   /* If we have address ranges, record them.  */
11270   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11271
11272   /* Attach template arguments to function.  */
11273   if (! VEC_empty (symbolp, template_args))
11274     {
11275       gdb_assert (templ_func != NULL);
11276
11277       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11278       templ_func->template_arguments
11279         = obstack_alloc (&objfile->objfile_obstack,
11280                          (templ_func->n_template_arguments
11281                           * sizeof (struct symbol *)));
11282       memcpy (templ_func->template_arguments,
11283               VEC_address (symbolp, template_args),
11284               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11285       VEC_free (symbolp, template_args);
11286     }
11287
11288   /* In C++, we can have functions nested inside functions (e.g., when
11289      a function declares a class that has methods).  This means that
11290      when we finish processing a function scope, we may need to go
11291      back to building a containing block's symbol lists.  */
11292   local_symbols = new->locals;
11293   using_directives = new->using_directives;
11294
11295   /* If we've finished processing a top-level function, subsequent
11296      symbols go in the file symbol list.  */
11297   if (outermost_context_p ())
11298     cu->list_in_scope = &file_symbols;
11299 }
11300
11301 /* Process all the DIES contained within a lexical block scope.  Start
11302    a new scope, process the dies, and then close the scope.  */
11303
11304 static void
11305 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11306 {
11307   struct objfile *objfile = cu->objfile;
11308   struct context_stack *new;
11309   CORE_ADDR lowpc, highpc;
11310   struct die_info *child_die;
11311   CORE_ADDR baseaddr;
11312
11313   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11314
11315   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11316   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11317      as multiple lexical blocks?  Handling children in a sane way would
11318      be nasty.  Might be easier to properly extend generic blocks to
11319      describe ranges.  */
11320   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11321     return;
11322   lowpc += baseaddr;
11323   highpc += baseaddr;
11324
11325   push_context (0, lowpc);
11326   if (die->child != NULL)
11327     {
11328       child_die = die->child;
11329       while (child_die && child_die->tag)
11330         {
11331           process_die (child_die, cu);
11332           child_die = sibling_die (child_die);
11333         }
11334     }
11335   new = pop_context ();
11336
11337   if (local_symbols != NULL || using_directives != NULL)
11338     {
11339       struct block *block
11340         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
11341                         highpc, objfile);
11342
11343       /* Note that recording ranges after traversing children, as we
11344          do here, means that recording a parent's ranges entails
11345          walking across all its children's ranges as they appear in
11346          the address map, which is quadratic behavior.
11347
11348          It would be nicer to record the parent's ranges before
11349          traversing its children, simply overriding whatever you find
11350          there.  But since we don't even decide whether to create a
11351          block until after we've traversed its children, that's hard
11352          to do.  */
11353       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11354     }
11355   local_symbols = new->locals;
11356   using_directives = new->using_directives;
11357 }
11358
11359 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
11360
11361 static void
11362 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11363 {
11364   struct objfile *objfile = cu->objfile;
11365   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11366   CORE_ADDR pc, baseaddr;
11367   struct attribute *attr;
11368   struct call_site *call_site, call_site_local;
11369   void **slot;
11370   int nparams;
11371   struct die_info *child_die;
11372
11373   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11374
11375   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11376   if (!attr)
11377     {
11378       complaint (&symfile_complaints,
11379                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
11380                    "DIE 0x%x [in module %s]"),
11381                  die->offset.sect_off, objfile_name (objfile));
11382       return;
11383     }
11384   pc = attr_value_as_address (attr) + baseaddr;
11385
11386   if (cu->call_site_htab == NULL)
11387     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11388                                                NULL, &objfile->objfile_obstack,
11389                                                hashtab_obstack_allocate, NULL);
11390   call_site_local.pc = pc;
11391   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11392   if (*slot != NULL)
11393     {
11394       complaint (&symfile_complaints,
11395                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
11396                    "DIE 0x%x [in module %s]"),
11397                  paddress (gdbarch, pc), die->offset.sect_off,
11398                  objfile_name (objfile));
11399       return;
11400     }
11401
11402   /* Count parameters at the caller.  */
11403
11404   nparams = 0;
11405   for (child_die = die->child; child_die && child_die->tag;
11406        child_die = sibling_die (child_die))
11407     {
11408       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11409         {
11410           complaint (&symfile_complaints,
11411                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
11412                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11413                      child_die->tag, child_die->offset.sect_off,
11414                      objfile_name (objfile));
11415           continue;
11416         }
11417
11418       nparams++;
11419     }
11420
11421   call_site = obstack_alloc (&objfile->objfile_obstack,
11422                              (sizeof (*call_site)
11423                               + (sizeof (*call_site->parameter)
11424                                  * (nparams - 1))));
11425   *slot = call_site;
11426   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11427   call_site->pc = pc;
11428
11429   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11430     {
11431       struct die_info *func_die;
11432
11433       /* Skip also over DW_TAG_inlined_subroutine.  */
11434       for (func_die = die->parent;
11435            func_die && func_die->tag != DW_TAG_subprogram
11436            && func_die->tag != DW_TAG_subroutine_type;
11437            func_die = func_die->parent);
11438
11439       /* DW_AT_GNU_all_call_sites is a superset
11440          of DW_AT_GNU_all_tail_call_sites.  */
11441       if (func_die
11442           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11443           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11444         {
11445           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11446              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11447              both the initial caller containing the real return address PC and
11448              the final callee containing the current PC of a chain of tail
11449              calls do not need to have the tail call list complete.  But any
11450              function candidate for a virtual tail call frame searched via
11451              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11452              determined unambiguously.  */
11453         }
11454       else
11455         {
11456           struct type *func_type = NULL;
11457
11458           if (func_die)
11459             func_type = get_die_type (func_die, cu);
11460           if (func_type != NULL)
11461             {
11462               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11463
11464               /* Enlist this call site to the function.  */
11465               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11466               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11467             }
11468           else
11469             complaint (&symfile_complaints,
11470                        _("Cannot find function owning DW_TAG_GNU_call_site "
11471                          "DIE 0x%x [in module %s]"),
11472                        die->offset.sect_off, objfile_name (objfile));
11473         }
11474     }
11475
11476   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11477   if (attr == NULL)
11478     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11479   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11480   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11481     /* Keep NULL DWARF_BLOCK.  */;
11482   else if (attr_form_is_block (attr))
11483     {
11484       struct dwarf2_locexpr_baton *dlbaton;
11485
11486       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
11487       dlbaton->data = DW_BLOCK (attr)->data;
11488       dlbaton->size = DW_BLOCK (attr)->size;
11489       dlbaton->per_cu = cu->per_cu;
11490
11491       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11492     }
11493   else if (attr_form_is_ref (attr))
11494     {
11495       struct dwarf2_cu *target_cu = cu;
11496       struct die_info *target_die;
11497
11498       target_die = follow_die_ref (die, attr, &target_cu);
11499       gdb_assert (target_cu->objfile == objfile);
11500       if (die_is_declaration (target_die, target_cu))
11501         {
11502           const char *target_physname = NULL;
11503           struct attribute *target_attr;
11504
11505           /* Prefer the mangled name; otherwise compute the demangled one.  */
11506           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
11507           if (target_attr == NULL)
11508             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
11509                                        target_cu);
11510           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
11511             target_physname = DW_STRING (target_attr);
11512           else
11513             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11514           if (target_physname == NULL)
11515             complaint (&symfile_complaints,
11516                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11517                          "physname, for referencing DIE 0x%x [in module %s]"),
11518                        die->offset.sect_off, objfile_name (objfile));
11519           else
11520             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11521         }
11522       else
11523         {
11524           CORE_ADDR lowpc;
11525
11526           /* DW_AT_entry_pc should be preferred.  */
11527           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
11528             complaint (&symfile_complaints,
11529                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11530                          "low pc, for referencing DIE 0x%x [in module %s]"),
11531                        die->offset.sect_off, objfile_name (objfile));
11532           else
11533             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
11534         }
11535     }
11536   else
11537     complaint (&symfile_complaints,
11538                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
11539                  "block nor reference, for DIE 0x%x [in module %s]"),
11540                die->offset.sect_off, objfile_name (objfile));
11541
11542   call_site->per_cu = cu->per_cu;
11543
11544   for (child_die = die->child;
11545        child_die && child_die->tag;
11546        child_die = sibling_die (child_die))
11547     {
11548       struct call_site_parameter *parameter;
11549       struct attribute *loc, *origin;
11550
11551       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11552         {
11553           /* Already printed the complaint above.  */
11554           continue;
11555         }
11556
11557       gdb_assert (call_site->parameter_count < nparams);
11558       parameter = &call_site->parameter[call_site->parameter_count];
11559
11560       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
11561          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
11562          register is contained in DW_AT_GNU_call_site_value.  */
11563
11564       loc = dwarf2_attr (child_die, DW_AT_location, cu);
11565       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
11566       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
11567         {
11568           sect_offset offset;
11569
11570           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
11571           offset = dwarf2_get_ref_die_offset (origin);
11572           if (!offset_in_cu_p (&cu->header, offset))
11573             {
11574               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
11575                  binding can be done only inside one CU.  Such referenced DIE
11576                  therefore cannot be even moved to DW_TAG_partial_unit.  */
11577               complaint (&symfile_complaints,
11578                          _("DW_AT_abstract_origin offset is not in CU for "
11579                            "DW_TAG_GNU_call_site child DIE 0x%x "
11580                            "[in module %s]"),
11581                          child_die->offset.sect_off, objfile_name (objfile));
11582               continue;
11583             }
11584           parameter->u.param_offset.cu_off = (offset.sect_off
11585                                               - cu->header.offset.sect_off);
11586         }
11587       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
11588         {
11589           complaint (&symfile_complaints,
11590                      _("No DW_FORM_block* DW_AT_location for "
11591                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11592                      child_die->offset.sect_off, objfile_name (objfile));
11593           continue;
11594         }
11595       else
11596         {
11597           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
11598             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
11599           if (parameter->u.dwarf_reg != -1)
11600             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
11601           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
11602                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
11603                                              &parameter->u.fb_offset))
11604             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
11605           else
11606             {
11607               complaint (&symfile_complaints,
11608                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
11609                            "for DW_FORM_block* DW_AT_location is supported for "
11610                            "DW_TAG_GNU_call_site child DIE 0x%x "
11611                            "[in module %s]"),
11612                          child_die->offset.sect_off, objfile_name (objfile));
11613               continue;
11614             }
11615         }
11616
11617       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
11618       if (!attr_form_is_block (attr))
11619         {
11620           complaint (&symfile_complaints,
11621                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
11622                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11623                      child_die->offset.sect_off, objfile_name (objfile));
11624           continue;
11625         }
11626       parameter->value = DW_BLOCK (attr)->data;
11627       parameter->value_size = DW_BLOCK (attr)->size;
11628
11629       /* Parameters are not pre-cleared by memset above.  */
11630       parameter->data_value = NULL;
11631       parameter->data_value_size = 0;
11632       call_site->parameter_count++;
11633
11634       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
11635       if (attr)
11636         {
11637           if (!attr_form_is_block (attr))
11638             complaint (&symfile_complaints,
11639                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
11640                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11641                        child_die->offset.sect_off, objfile_name (objfile));
11642           else
11643             {
11644               parameter->data_value = DW_BLOCK (attr)->data;
11645               parameter->data_value_size = DW_BLOCK (attr)->size;
11646             }
11647         }
11648     }
11649 }
11650
11651 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
11652    Return 1 if the attributes are present and valid, otherwise, return 0.
11653    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
11654
11655 static int
11656 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
11657                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
11658                     struct partial_symtab *ranges_pst)
11659 {
11660   struct objfile *objfile = cu->objfile;
11661   struct comp_unit_head *cu_header = &cu->header;
11662   bfd *obfd = objfile->obfd;
11663   unsigned int addr_size = cu_header->addr_size;
11664   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11665   /* Base address selection entry.  */
11666   CORE_ADDR base;
11667   int found_base;
11668   unsigned int dummy;
11669   const gdb_byte *buffer;
11670   CORE_ADDR marker;
11671   int low_set;
11672   CORE_ADDR low = 0;
11673   CORE_ADDR high = 0;
11674   CORE_ADDR baseaddr;
11675
11676   found_base = cu->base_known;
11677   base = cu->base_address;
11678
11679   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11680   if (offset >= dwarf2_per_objfile->ranges.size)
11681     {
11682       complaint (&symfile_complaints,
11683                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
11684                  offset);
11685       return 0;
11686     }
11687   buffer = dwarf2_per_objfile->ranges.buffer + offset;
11688
11689   /* Read in the largest possible address.  */
11690   marker = read_address (obfd, buffer, cu, &dummy);
11691   if ((marker & mask) == mask)
11692     {
11693       /* If we found the largest possible address, then
11694          read the base address.  */
11695       base = read_address (obfd, buffer + addr_size, cu, &dummy);
11696       buffer += 2 * addr_size;
11697       offset += 2 * addr_size;
11698       found_base = 1;
11699     }
11700
11701   low_set = 0;
11702
11703   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11704
11705   while (1)
11706     {
11707       CORE_ADDR range_beginning, range_end;
11708
11709       range_beginning = read_address (obfd, buffer, cu, &dummy);
11710       buffer += addr_size;
11711       range_end = read_address (obfd, buffer, cu, &dummy);
11712       buffer += addr_size;
11713       offset += 2 * addr_size;
11714
11715       /* An end of list marker is a pair of zero addresses.  */
11716       if (range_beginning == 0 && range_end == 0)
11717         /* Found the end of list entry.  */
11718         break;
11719
11720       /* Each base address selection entry is a pair of 2 values.
11721          The first is the largest possible address, the second is
11722          the base address.  Check for a base address here.  */
11723       if ((range_beginning & mask) == mask)
11724         {
11725           /* If we found the largest possible address, then
11726              read the base address.  */
11727           base = read_address (obfd, buffer + addr_size, cu, &dummy);
11728           found_base = 1;
11729           continue;
11730         }
11731
11732       if (!found_base)
11733         {
11734           /* We have no valid base address for the ranges
11735              data.  */
11736           complaint (&symfile_complaints,
11737                      _("Invalid .debug_ranges data (no base address)"));
11738           return 0;
11739         }
11740
11741       if (range_beginning > range_end)
11742         {
11743           /* Inverted range entries are invalid.  */
11744           complaint (&symfile_complaints,
11745                      _("Invalid .debug_ranges data (inverted range)"));
11746           return 0;
11747         }
11748
11749       /* Empty range entries have no effect.  */
11750       if (range_beginning == range_end)
11751         continue;
11752
11753       range_beginning += base;
11754       range_end += base;
11755
11756       /* A not-uncommon case of bad debug info.
11757          Don't pollute the addrmap with bad data.  */
11758       if (range_beginning + baseaddr == 0
11759           && !dwarf2_per_objfile->has_section_at_zero)
11760         {
11761           complaint (&symfile_complaints,
11762                      _(".debug_ranges entry has start address of zero"
11763                        " [in module %s]"), objfile_name (objfile));
11764           continue;
11765         }
11766
11767       if (ranges_pst != NULL)
11768         addrmap_set_empty (objfile->psymtabs_addrmap,
11769                            range_beginning + baseaddr,
11770                            range_end - 1 + baseaddr,
11771                            ranges_pst);
11772
11773       /* FIXME: This is recording everything as a low-high
11774          segment of consecutive addresses.  We should have a
11775          data structure for discontiguous block ranges
11776          instead.  */
11777       if (! low_set)
11778         {
11779           low = range_beginning;
11780           high = range_end;
11781           low_set = 1;
11782         }
11783       else
11784         {
11785           if (range_beginning < low)
11786             low = range_beginning;
11787           if (range_end > high)
11788             high = range_end;
11789         }
11790     }
11791
11792   if (! low_set)
11793     /* If the first entry is an end-of-list marker, the range
11794        describes an empty scope, i.e. no instructions.  */
11795     return 0;
11796
11797   if (low_return)
11798     *low_return = low;
11799   if (high_return)
11800     *high_return = high;
11801   return 1;
11802 }
11803
11804 /* Get low and high pc attributes from a die.  Return 1 if the attributes
11805    are present and valid, otherwise, return 0.  Return -1 if the range is
11806    discontinuous, i.e. derived from DW_AT_ranges information.  */
11807
11808 static int
11809 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
11810                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
11811                       struct partial_symtab *pst)
11812 {
11813   struct attribute *attr;
11814   struct attribute *attr_high;
11815   CORE_ADDR low = 0;
11816   CORE_ADDR high = 0;
11817   int ret = 0;
11818
11819   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11820   if (attr_high)
11821     {
11822       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11823       if (attr)
11824         {
11825           low = attr_value_as_address (attr);
11826           high = attr_value_as_address (attr_high);
11827           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
11828             high += low;
11829         }
11830       else
11831         /* Found high w/o low attribute.  */
11832         return 0;
11833
11834       /* Found consecutive range of addresses.  */
11835       ret = 1;
11836     }
11837   else
11838     {
11839       attr = dwarf2_attr (die, DW_AT_ranges, cu);
11840       if (attr != NULL)
11841         {
11842           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11843              We take advantage of the fact that DW_AT_ranges does not appear
11844              in DW_TAG_compile_unit of DWO files.  */
11845           int need_ranges_base = die->tag != DW_TAG_compile_unit;
11846           unsigned int ranges_offset = (DW_UNSND (attr)
11847                                         + (need_ranges_base
11848                                            ? cu->ranges_base
11849                                            : 0));
11850
11851           /* Value of the DW_AT_ranges attribute is the offset in the
11852              .debug_ranges section.  */
11853           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
11854             return 0;
11855           /* Found discontinuous range of addresses.  */
11856           ret = -1;
11857         }
11858     }
11859
11860   /* read_partial_die has also the strict LOW < HIGH requirement.  */
11861   if (high <= low)
11862     return 0;
11863
11864   /* When using the GNU linker, .gnu.linkonce. sections are used to
11865      eliminate duplicate copies of functions and vtables and such.
11866      The linker will arbitrarily choose one and discard the others.
11867      The AT_*_pc values for such functions refer to local labels in
11868      these sections.  If the section from that file was discarded, the
11869      labels are not in the output, so the relocs get a value of 0.
11870      If this is a discarded function, mark the pc bounds as invalid,
11871      so that GDB will ignore it.  */
11872   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
11873     return 0;
11874
11875   *lowpc = low;
11876   if (highpc)
11877     *highpc = high;
11878   return ret;
11879 }
11880
11881 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
11882    its low and high PC addresses.  Do nothing if these addresses could not
11883    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
11884    and HIGHPC to the high address if greater than HIGHPC.  */
11885
11886 static void
11887 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
11888                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
11889                                  struct dwarf2_cu *cu)
11890 {
11891   CORE_ADDR low, high;
11892   struct die_info *child = die->child;
11893
11894   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
11895     {
11896       *lowpc = min (*lowpc, low);
11897       *highpc = max (*highpc, high);
11898     }
11899
11900   /* If the language does not allow nested subprograms (either inside
11901      subprograms or lexical blocks), we're done.  */
11902   if (cu->language != language_ada)
11903     return;
11904
11905   /* Check all the children of the given DIE.  If it contains nested
11906      subprograms, then check their pc bounds.  Likewise, we need to
11907      check lexical blocks as well, as they may also contain subprogram
11908      definitions.  */
11909   while (child && child->tag)
11910     {
11911       if (child->tag == DW_TAG_subprogram
11912           || child->tag == DW_TAG_lexical_block)
11913         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
11914       child = sibling_die (child);
11915     }
11916 }
11917
11918 /* Get the low and high pc's represented by the scope DIE, and store
11919    them in *LOWPC and *HIGHPC.  If the correct values can't be
11920    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
11921
11922 static void
11923 get_scope_pc_bounds (struct die_info *die,
11924                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
11925                      struct dwarf2_cu *cu)
11926 {
11927   CORE_ADDR best_low = (CORE_ADDR) -1;
11928   CORE_ADDR best_high = (CORE_ADDR) 0;
11929   CORE_ADDR current_low, current_high;
11930
11931   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
11932     {
11933       best_low = current_low;
11934       best_high = current_high;
11935     }
11936   else
11937     {
11938       struct die_info *child = die->child;
11939
11940       while (child && child->tag)
11941         {
11942           switch (child->tag) {
11943           case DW_TAG_subprogram:
11944             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
11945             break;
11946           case DW_TAG_namespace:
11947           case DW_TAG_module:
11948             /* FIXME: carlton/2004-01-16: Should we do this for
11949                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
11950                that current GCC's always emit the DIEs corresponding
11951                to definitions of methods of classes as children of a
11952                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
11953                the DIEs giving the declarations, which could be
11954                anywhere).  But I don't see any reason why the
11955                standards says that they have to be there.  */
11956             get_scope_pc_bounds (child, &current_low, &current_high, cu);
11957
11958             if (current_low != ((CORE_ADDR) -1))
11959               {
11960                 best_low = min (best_low, current_low);
11961                 best_high = max (best_high, current_high);
11962               }
11963             break;
11964           default:
11965             /* Ignore.  */
11966             break;
11967           }
11968
11969           child = sibling_die (child);
11970         }
11971     }
11972
11973   *lowpc = best_low;
11974   *highpc = best_high;
11975 }
11976
11977 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
11978    in DIE.  */
11979
11980 static void
11981 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
11982                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
11983 {
11984   struct objfile *objfile = cu->objfile;
11985   struct attribute *attr;
11986   struct attribute *attr_high;
11987
11988   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11989   if (attr_high)
11990     {
11991       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11992       if (attr)
11993         {
11994           CORE_ADDR low = attr_value_as_address (attr);
11995           CORE_ADDR high = attr_value_as_address (attr_high);
11996
11997           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
11998             high += low;
11999
12000           record_block_range (block, baseaddr + low, baseaddr + high - 1);
12001         }
12002     }
12003
12004   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12005   if (attr)
12006     {
12007       bfd *obfd = objfile->obfd;
12008       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12009          We take advantage of the fact that DW_AT_ranges does not appear
12010          in DW_TAG_compile_unit of DWO files.  */
12011       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12012
12013       /* The value of the DW_AT_ranges attribute is the offset of the
12014          address range list in the .debug_ranges section.  */
12015       unsigned long offset = (DW_UNSND (attr)
12016                               + (need_ranges_base ? cu->ranges_base : 0));
12017       const gdb_byte *buffer;
12018
12019       /* For some target architectures, but not others, the
12020          read_address function sign-extends the addresses it returns.
12021          To recognize base address selection entries, we need a
12022          mask.  */
12023       unsigned int addr_size = cu->header.addr_size;
12024       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12025
12026       /* The base address, to which the next pair is relative.  Note
12027          that this 'base' is a DWARF concept: most entries in a range
12028          list are relative, to reduce the number of relocs against the
12029          debugging information.  This is separate from this function's
12030          'baseaddr' argument, which GDB uses to relocate debugging
12031          information from a shared library based on the address at
12032          which the library was loaded.  */
12033       CORE_ADDR base = cu->base_address;
12034       int base_known = cu->base_known;
12035
12036       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12037       if (offset >= dwarf2_per_objfile->ranges.size)
12038         {
12039           complaint (&symfile_complaints,
12040                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
12041                      offset);
12042           return;
12043         }
12044       buffer = dwarf2_per_objfile->ranges.buffer + offset;
12045
12046       for (;;)
12047         {
12048           unsigned int bytes_read;
12049           CORE_ADDR start, end;
12050
12051           start = read_address (obfd, buffer, cu, &bytes_read);
12052           buffer += bytes_read;
12053           end = read_address (obfd, buffer, cu, &bytes_read);
12054           buffer += bytes_read;
12055
12056           /* Did we find the end of the range list?  */
12057           if (start == 0 && end == 0)
12058             break;
12059
12060           /* Did we find a base address selection entry?  */
12061           else if ((start & base_select_mask) == base_select_mask)
12062             {
12063               base = end;
12064               base_known = 1;
12065             }
12066
12067           /* We found an ordinary address range.  */
12068           else
12069             {
12070               if (!base_known)
12071                 {
12072                   complaint (&symfile_complaints,
12073                              _("Invalid .debug_ranges data "
12074                                "(no base address)"));
12075                   return;
12076                 }
12077
12078               if (start > end)
12079                 {
12080                   /* Inverted range entries are invalid.  */
12081                   complaint (&symfile_complaints,
12082                              _("Invalid .debug_ranges data "
12083                                "(inverted range)"));
12084                   return;
12085                 }
12086
12087               /* Empty range entries have no effect.  */
12088               if (start == end)
12089                 continue;
12090
12091               start += base + baseaddr;
12092               end += base + baseaddr;
12093
12094               /* A not-uncommon case of bad debug info.
12095                  Don't pollute the addrmap with bad data.  */
12096               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
12097                 {
12098                   complaint (&symfile_complaints,
12099                              _(".debug_ranges entry has start address of zero"
12100                                " [in module %s]"), objfile_name (objfile));
12101                   continue;
12102                 }
12103
12104               record_block_range (block, start, end - 1);
12105             }
12106         }
12107     }
12108 }
12109
12110 /* Check whether the producer field indicates either of GCC < 4.6, or the
12111    Intel C/C++ compiler, and cache the result in CU.  */
12112
12113 static void
12114 check_producer (struct dwarf2_cu *cu)
12115 {
12116   const char *cs;
12117   int major, minor, release;
12118
12119   if (cu->producer == NULL)
12120     {
12121       /* For unknown compilers expect their behavior is DWARF version
12122          compliant.
12123
12124          GCC started to support .debug_types sections by -gdwarf-4 since
12125          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12126          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12127          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12128          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12129     }
12130   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
12131     {
12132       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
12133
12134       cs = &cu->producer[strlen ("GNU ")];
12135       while (*cs && !isdigit (*cs))
12136         cs++;
12137       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
12138         {
12139           /* Not recognized as GCC.  */
12140         }
12141       else
12142         {
12143           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12144           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12145         }
12146     }
12147   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
12148     cu->producer_is_icc = 1;
12149   else
12150     {
12151       /* For other non-GCC compilers, expect their behavior is DWARF version
12152          compliant.  */
12153     }
12154
12155   cu->checked_producer = 1;
12156 }
12157
12158 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12159    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12160    during 4.6.0 experimental.  */
12161
12162 static int
12163 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12164 {
12165   if (!cu->checked_producer)
12166     check_producer (cu);
12167
12168   return cu->producer_is_gxx_lt_4_6;
12169 }
12170
12171 /* Return the default accessibility type if it is not overriden by
12172    DW_AT_accessibility.  */
12173
12174 static enum dwarf_access_attribute
12175 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12176 {
12177   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12178     {
12179       /* The default DWARF 2 accessibility for members is public, the default
12180          accessibility for inheritance is private.  */
12181
12182       if (die->tag != DW_TAG_inheritance)
12183         return DW_ACCESS_public;
12184       else
12185         return DW_ACCESS_private;
12186     }
12187   else
12188     {
12189       /* DWARF 3+ defines the default accessibility a different way.  The same
12190          rules apply now for DW_TAG_inheritance as for the members and it only
12191          depends on the container kind.  */
12192
12193       if (die->parent->tag == DW_TAG_class_type)
12194         return DW_ACCESS_private;
12195       else
12196         return DW_ACCESS_public;
12197     }
12198 }
12199
12200 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12201    offset.  If the attribute was not found return 0, otherwise return
12202    1.  If it was found but could not properly be handled, set *OFFSET
12203    to 0.  */
12204
12205 static int
12206 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12207                              LONGEST *offset)
12208 {
12209   struct attribute *attr;
12210
12211   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12212   if (attr != NULL)
12213     {
12214       *offset = 0;
12215
12216       /* Note that we do not check for a section offset first here.
12217          This is because DW_AT_data_member_location is new in DWARF 4,
12218          so if we see it, we can assume that a constant form is really
12219          a constant and not a section offset.  */
12220       if (attr_form_is_constant (attr))
12221         *offset = dwarf2_get_attr_constant_value (attr, 0);
12222       else if (attr_form_is_section_offset (attr))
12223         dwarf2_complex_location_expr_complaint ();
12224       else if (attr_form_is_block (attr))
12225         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12226       else
12227         dwarf2_complex_location_expr_complaint ();
12228
12229       return 1;
12230     }
12231
12232   return 0;
12233 }
12234
12235 /* Add an aggregate field to the field list.  */
12236
12237 static void
12238 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12239                   struct dwarf2_cu *cu)
12240 {
12241   struct objfile *objfile = cu->objfile;
12242   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12243   struct nextfield *new_field;
12244   struct attribute *attr;
12245   struct field *fp;
12246   const char *fieldname = "";
12247
12248   /* Allocate a new field list entry and link it in.  */
12249   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
12250   make_cleanup (xfree, new_field);
12251   memset (new_field, 0, sizeof (struct nextfield));
12252
12253   if (die->tag == DW_TAG_inheritance)
12254     {
12255       new_field->next = fip->baseclasses;
12256       fip->baseclasses = new_field;
12257     }
12258   else
12259     {
12260       new_field->next = fip->fields;
12261       fip->fields = new_field;
12262     }
12263   fip->nfields++;
12264
12265   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12266   if (attr)
12267     new_field->accessibility = DW_UNSND (attr);
12268   else
12269     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12270   if (new_field->accessibility != DW_ACCESS_public)
12271     fip->non_public_fields = 1;
12272
12273   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12274   if (attr)
12275     new_field->virtuality = DW_UNSND (attr);
12276   else
12277     new_field->virtuality = DW_VIRTUALITY_none;
12278
12279   fp = &new_field->field;
12280
12281   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12282     {
12283       LONGEST offset;
12284
12285       /* Data member other than a C++ static data member.  */
12286
12287       /* Get type of field.  */
12288       fp->type = die_type (die, cu);
12289
12290       SET_FIELD_BITPOS (*fp, 0);
12291
12292       /* Get bit size of field (zero if none).  */
12293       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12294       if (attr)
12295         {
12296           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12297         }
12298       else
12299         {
12300           FIELD_BITSIZE (*fp) = 0;
12301         }
12302
12303       /* Get bit offset of field.  */
12304       if (handle_data_member_location (die, cu, &offset))
12305         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12306       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12307       if (attr)
12308         {
12309           if (gdbarch_bits_big_endian (gdbarch))
12310             {
12311               /* For big endian bits, the DW_AT_bit_offset gives the
12312                  additional bit offset from the MSB of the containing
12313                  anonymous object to the MSB of the field.  We don't
12314                  have to do anything special since we don't need to
12315                  know the size of the anonymous object.  */
12316               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12317             }
12318           else
12319             {
12320               /* For little endian bits, compute the bit offset to the
12321                  MSB of the anonymous object, subtract off the number of
12322                  bits from the MSB of the field to the MSB of the
12323                  object, and then subtract off the number of bits of
12324                  the field itself.  The result is the bit offset of
12325                  the LSB of the field.  */
12326               int anonymous_size;
12327               int bit_offset = DW_UNSND (attr);
12328
12329               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12330               if (attr)
12331                 {
12332                   /* The size of the anonymous object containing
12333                      the bit field is explicit, so use the
12334                      indicated size (in bytes).  */
12335                   anonymous_size = DW_UNSND (attr);
12336                 }
12337               else
12338                 {
12339                   /* The size of the anonymous object containing
12340                      the bit field must be inferred from the type
12341                      attribute of the data member containing the
12342                      bit field.  */
12343                   anonymous_size = TYPE_LENGTH (fp->type);
12344                 }
12345               SET_FIELD_BITPOS (*fp,
12346                                 (FIELD_BITPOS (*fp)
12347                                  + anonymous_size * bits_per_byte
12348                                  - bit_offset - FIELD_BITSIZE (*fp)));
12349             }
12350         }
12351
12352       /* Get name of field.  */
12353       fieldname = dwarf2_name (die, cu);
12354       if (fieldname == NULL)
12355         fieldname = "";
12356
12357       /* The name is already allocated along with this objfile, so we don't
12358          need to duplicate it for the type.  */
12359       fp->name = fieldname;
12360
12361       /* Change accessibility for artificial fields (e.g. virtual table
12362          pointer or virtual base class pointer) to private.  */
12363       if (dwarf2_attr (die, DW_AT_artificial, cu))
12364         {
12365           FIELD_ARTIFICIAL (*fp) = 1;
12366           new_field->accessibility = DW_ACCESS_private;
12367           fip->non_public_fields = 1;
12368         }
12369     }
12370   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12371     {
12372       /* C++ static member.  */
12373
12374       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12375          is a declaration, but all versions of G++ as of this writing
12376          (so through at least 3.2.1) incorrectly generate
12377          DW_TAG_variable tags.  */
12378
12379       const char *physname;
12380
12381       /* Get name of field.  */
12382       fieldname = dwarf2_name (die, cu);
12383       if (fieldname == NULL)
12384         return;
12385
12386       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12387       if (attr
12388           /* Only create a symbol if this is an external value.
12389              new_symbol checks this and puts the value in the global symbol
12390              table, which we want.  If it is not external, new_symbol
12391              will try to put the value in cu->list_in_scope which is wrong.  */
12392           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12393         {
12394           /* A static const member, not much different than an enum as far as
12395              we're concerned, except that we can support more types.  */
12396           new_symbol (die, NULL, cu);
12397         }
12398
12399       /* Get physical name.  */
12400       physname = dwarf2_physname (fieldname, die, cu);
12401
12402       /* The name is already allocated along with this objfile, so we don't
12403          need to duplicate it for the type.  */
12404       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
12405       FIELD_TYPE (*fp) = die_type (die, cu);
12406       FIELD_NAME (*fp) = fieldname;
12407     }
12408   else if (die->tag == DW_TAG_inheritance)
12409     {
12410       LONGEST offset;
12411
12412       /* C++ base class field.  */
12413       if (handle_data_member_location (die, cu, &offset))
12414         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12415       FIELD_BITSIZE (*fp) = 0;
12416       FIELD_TYPE (*fp) = die_type (die, cu);
12417       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
12418       fip->nbaseclasses++;
12419     }
12420 }
12421
12422 /* Add a typedef defined in the scope of the FIP's class.  */
12423
12424 static void
12425 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
12426                     struct dwarf2_cu *cu)
12427 {
12428   struct objfile *objfile = cu->objfile;
12429   struct typedef_field_list *new_field;
12430   struct attribute *attr;
12431   struct typedef_field *fp;
12432   char *fieldname = "";
12433
12434   /* Allocate a new field list entry and link it in.  */
12435   new_field = xzalloc (sizeof (*new_field));
12436   make_cleanup (xfree, new_field);
12437
12438   gdb_assert (die->tag == DW_TAG_typedef);
12439
12440   fp = &new_field->field;
12441
12442   /* Get name of field.  */
12443   fp->name = dwarf2_name (die, cu);
12444   if (fp->name == NULL)
12445     return;
12446
12447   fp->type = read_type_die (die, cu);
12448
12449   new_field->next = fip->typedef_field_list;
12450   fip->typedef_field_list = new_field;
12451   fip->typedef_field_list_count++;
12452 }
12453
12454 /* Create the vector of fields, and attach it to the type.  */
12455
12456 static void
12457 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
12458                               struct dwarf2_cu *cu)
12459 {
12460   int nfields = fip->nfields;
12461
12462   /* Record the field count, allocate space for the array of fields,
12463      and create blank accessibility bitfields if necessary.  */
12464   TYPE_NFIELDS (type) = nfields;
12465   TYPE_FIELDS (type) = (struct field *)
12466     TYPE_ALLOC (type, sizeof (struct field) * nfields);
12467   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
12468
12469   if (fip->non_public_fields && cu->language != language_ada)
12470     {
12471       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12472
12473       TYPE_FIELD_PRIVATE_BITS (type) =
12474         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12475       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
12476
12477       TYPE_FIELD_PROTECTED_BITS (type) =
12478         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12479       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
12480
12481       TYPE_FIELD_IGNORE_BITS (type) =
12482         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12483       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
12484     }
12485
12486   /* If the type has baseclasses, allocate and clear a bit vector for
12487      TYPE_FIELD_VIRTUAL_BITS.  */
12488   if (fip->nbaseclasses && cu->language != language_ada)
12489     {
12490       int num_bytes = B_BYTES (fip->nbaseclasses);
12491       unsigned char *pointer;
12492
12493       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12494       pointer = TYPE_ALLOC (type, num_bytes);
12495       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
12496       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
12497       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
12498     }
12499
12500   /* Copy the saved-up fields into the field vector.  Start from the head of
12501      the list, adding to the tail of the field array, so that they end up in
12502      the same order in the array in which they were added to the list.  */
12503   while (nfields-- > 0)
12504     {
12505       struct nextfield *fieldp;
12506
12507       if (fip->fields)
12508         {
12509           fieldp = fip->fields;
12510           fip->fields = fieldp->next;
12511         }
12512       else
12513         {
12514           fieldp = fip->baseclasses;
12515           fip->baseclasses = fieldp->next;
12516         }
12517
12518       TYPE_FIELD (type, nfields) = fieldp->field;
12519       switch (fieldp->accessibility)
12520         {
12521         case DW_ACCESS_private:
12522           if (cu->language != language_ada)
12523             SET_TYPE_FIELD_PRIVATE (type, nfields);
12524           break;
12525
12526         case DW_ACCESS_protected:
12527           if (cu->language != language_ada)
12528             SET_TYPE_FIELD_PROTECTED (type, nfields);
12529           break;
12530
12531         case DW_ACCESS_public:
12532           break;
12533
12534         default:
12535           /* Unknown accessibility.  Complain and treat it as public.  */
12536           {
12537             complaint (&symfile_complaints, _("unsupported accessibility %d"),
12538                        fieldp->accessibility);
12539           }
12540           break;
12541         }
12542       if (nfields < fip->nbaseclasses)
12543         {
12544           switch (fieldp->virtuality)
12545             {
12546             case DW_VIRTUALITY_virtual:
12547             case DW_VIRTUALITY_pure_virtual:
12548               if (cu->language == language_ada)
12549                 error (_("unexpected virtuality in component of Ada type"));
12550               SET_TYPE_FIELD_VIRTUAL (type, nfields);
12551               break;
12552             }
12553         }
12554     }
12555 }
12556
12557 /* Return true if this member function is a constructor, false
12558    otherwise.  */
12559
12560 static int
12561 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
12562 {
12563   const char *fieldname;
12564   const char *typename;
12565   int len;
12566
12567   if (die->parent == NULL)
12568     return 0;
12569
12570   if (die->parent->tag != DW_TAG_structure_type
12571       && die->parent->tag != DW_TAG_union_type
12572       && die->parent->tag != DW_TAG_class_type)
12573     return 0;
12574
12575   fieldname = dwarf2_name (die, cu);
12576   typename = dwarf2_name (die->parent, cu);
12577   if (fieldname == NULL || typename == NULL)
12578     return 0;
12579
12580   len = strlen (fieldname);
12581   return (strncmp (fieldname, typename, len) == 0
12582           && (typename[len] == '\0' || typename[len] == '<'));
12583 }
12584
12585 /* Add a member function to the proper fieldlist.  */
12586
12587 static void
12588 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
12589                       struct type *type, struct dwarf2_cu *cu)
12590 {
12591   struct objfile *objfile = cu->objfile;
12592   struct attribute *attr;
12593   struct fnfieldlist *flp;
12594   int i;
12595   struct fn_field *fnp;
12596   const char *fieldname;
12597   struct nextfnfield *new_fnfield;
12598   struct type *this_type;
12599   enum dwarf_access_attribute accessibility;
12600
12601   if (cu->language == language_ada)
12602     error (_("unexpected member function in Ada type"));
12603
12604   /* Get name of member function.  */
12605   fieldname = dwarf2_name (die, cu);
12606   if (fieldname == NULL)
12607     return;
12608
12609   /* Look up member function name in fieldlist.  */
12610   for (i = 0; i < fip->nfnfields; i++)
12611     {
12612       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
12613         break;
12614     }
12615
12616   /* Create new list element if necessary.  */
12617   if (i < fip->nfnfields)
12618     flp = &fip->fnfieldlists[i];
12619   else
12620     {
12621       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
12622         {
12623           fip->fnfieldlists = (struct fnfieldlist *)
12624             xrealloc (fip->fnfieldlists,
12625                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
12626                       * sizeof (struct fnfieldlist));
12627           if (fip->nfnfields == 0)
12628             make_cleanup (free_current_contents, &fip->fnfieldlists);
12629         }
12630       flp = &fip->fnfieldlists[fip->nfnfields];
12631       flp->name = fieldname;
12632       flp->length = 0;
12633       flp->head = NULL;
12634       i = fip->nfnfields++;
12635     }
12636
12637   /* Create a new member function field and chain it to the field list
12638      entry.  */
12639   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
12640   make_cleanup (xfree, new_fnfield);
12641   memset (new_fnfield, 0, sizeof (struct nextfnfield));
12642   new_fnfield->next = flp->head;
12643   flp->head = new_fnfield;
12644   flp->length++;
12645
12646   /* Fill in the member function field info.  */
12647   fnp = &new_fnfield->fnfield;
12648
12649   /* Delay processing of the physname until later.  */
12650   if (cu->language == language_cplus || cu->language == language_java)
12651     {
12652       add_to_method_list (type, i, flp->length - 1, fieldname,
12653                           die, cu);
12654     }
12655   else
12656     {
12657       const char *physname = dwarf2_physname (fieldname, die, cu);
12658       fnp->physname = physname ? physname : "";
12659     }
12660
12661   fnp->type = alloc_type (objfile);
12662   this_type = read_type_die (die, cu);
12663   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
12664     {
12665       int nparams = TYPE_NFIELDS (this_type);
12666
12667       /* TYPE is the domain of this method, and THIS_TYPE is the type
12668            of the method itself (TYPE_CODE_METHOD).  */
12669       smash_to_method_type (fnp->type, type,
12670                             TYPE_TARGET_TYPE (this_type),
12671                             TYPE_FIELDS (this_type),
12672                             TYPE_NFIELDS (this_type),
12673                             TYPE_VARARGS (this_type));
12674
12675       /* Handle static member functions.
12676          Dwarf2 has no clean way to discern C++ static and non-static
12677          member functions.  G++ helps GDB by marking the first
12678          parameter for non-static member functions (which is the this
12679          pointer) as artificial.  We obtain this information from
12680          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
12681       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
12682         fnp->voffset = VOFFSET_STATIC;
12683     }
12684   else
12685     complaint (&symfile_complaints, _("member function type missing for '%s'"),
12686                dwarf2_full_name (fieldname, die, cu));
12687
12688   /* Get fcontext from DW_AT_containing_type if present.  */
12689   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12690     fnp->fcontext = die_containing_type (die, cu);
12691
12692   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
12693      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
12694
12695   /* Get accessibility.  */
12696   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12697   if (attr)
12698     accessibility = DW_UNSND (attr);
12699   else
12700     accessibility = dwarf2_default_access_attribute (die, cu);
12701   switch (accessibility)
12702     {
12703     case DW_ACCESS_private:
12704       fnp->is_private = 1;
12705       break;
12706     case DW_ACCESS_protected:
12707       fnp->is_protected = 1;
12708       break;
12709     }
12710
12711   /* Check for artificial methods.  */
12712   attr = dwarf2_attr (die, DW_AT_artificial, cu);
12713   if (attr && DW_UNSND (attr) != 0)
12714     fnp->is_artificial = 1;
12715
12716   fnp->is_constructor = dwarf2_is_constructor (die, cu);
12717
12718   /* Get index in virtual function table if it is a virtual member
12719      function.  For older versions of GCC, this is an offset in the
12720      appropriate virtual table, as specified by DW_AT_containing_type.
12721      For everyone else, it is an expression to be evaluated relative
12722      to the object address.  */
12723
12724   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
12725   if (attr)
12726     {
12727       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
12728         {
12729           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
12730             {
12731               /* Old-style GCC.  */
12732               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
12733             }
12734           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
12735                    || (DW_BLOCK (attr)->size > 1
12736                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
12737                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
12738             {
12739               struct dwarf_block blk;
12740               int offset;
12741
12742               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
12743                         ? 1 : 2);
12744               blk.size = DW_BLOCK (attr)->size - offset;
12745               blk.data = DW_BLOCK (attr)->data + offset;
12746               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
12747               if ((fnp->voffset % cu->header.addr_size) != 0)
12748                 dwarf2_complex_location_expr_complaint ();
12749               else
12750                 fnp->voffset /= cu->header.addr_size;
12751               fnp->voffset += 2;
12752             }
12753           else
12754             dwarf2_complex_location_expr_complaint ();
12755
12756           if (!fnp->fcontext)
12757             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
12758         }
12759       else if (attr_form_is_section_offset (attr))
12760         {
12761           dwarf2_complex_location_expr_complaint ();
12762         }
12763       else
12764         {
12765           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
12766                                                  fieldname);
12767         }
12768     }
12769   else
12770     {
12771       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12772       if (attr && DW_UNSND (attr))
12773         {
12774           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
12775           complaint (&symfile_complaints,
12776                      _("Member function \"%s\" (offset %d) is virtual "
12777                        "but the vtable offset is not specified"),
12778                      fieldname, die->offset.sect_off);
12779           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12780           TYPE_CPLUS_DYNAMIC (type) = 1;
12781         }
12782     }
12783 }
12784
12785 /* Create the vector of member function fields, and attach it to the type.  */
12786
12787 static void
12788 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
12789                                  struct dwarf2_cu *cu)
12790 {
12791   struct fnfieldlist *flp;
12792   int i;
12793
12794   if (cu->language == language_ada)
12795     error (_("unexpected member functions in Ada type"));
12796
12797   ALLOCATE_CPLUS_STRUCT_TYPE (type);
12798   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
12799     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
12800
12801   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
12802     {
12803       struct nextfnfield *nfp = flp->head;
12804       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
12805       int k;
12806
12807       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
12808       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
12809       fn_flp->fn_fields = (struct fn_field *)
12810         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
12811       for (k = flp->length; (k--, nfp); nfp = nfp->next)
12812         fn_flp->fn_fields[k] = nfp->fnfield;
12813     }
12814
12815   TYPE_NFN_FIELDS (type) = fip->nfnfields;
12816 }
12817
12818 /* Returns non-zero if NAME is the name of a vtable member in CU's
12819    language, zero otherwise.  */
12820 static int
12821 is_vtable_name (const char *name, struct dwarf2_cu *cu)
12822 {
12823   static const char vptr[] = "_vptr";
12824   static const char vtable[] = "vtable";
12825
12826   /* Look for the C++ and Java forms of the vtable.  */
12827   if ((cu->language == language_java
12828        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
12829        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
12830        && is_cplus_marker (name[sizeof (vptr) - 1])))
12831     return 1;
12832
12833   return 0;
12834 }
12835
12836 /* GCC outputs unnamed structures that are really pointers to member
12837    functions, with the ABI-specified layout.  If TYPE describes
12838    such a structure, smash it into a member function type.
12839
12840    GCC shouldn't do this; it should just output pointer to member DIEs.
12841    This is GCC PR debug/28767.  */
12842
12843 static void
12844 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
12845 {
12846   struct type *pfn_type, *domain_type, *new_type;
12847
12848   /* Check for a structure with no name and two children.  */
12849   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
12850     return;
12851
12852   /* Check for __pfn and __delta members.  */
12853   if (TYPE_FIELD_NAME (type, 0) == NULL
12854       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
12855       || TYPE_FIELD_NAME (type, 1) == NULL
12856       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
12857     return;
12858
12859   /* Find the type of the method.  */
12860   pfn_type = TYPE_FIELD_TYPE (type, 0);
12861   if (pfn_type == NULL
12862       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
12863       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
12864     return;
12865
12866   /* Look for the "this" argument.  */
12867   pfn_type = TYPE_TARGET_TYPE (pfn_type);
12868   if (TYPE_NFIELDS (pfn_type) == 0
12869       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
12870       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
12871     return;
12872
12873   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
12874   new_type = alloc_type (objfile);
12875   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
12876                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
12877                         TYPE_VARARGS (pfn_type));
12878   smash_to_methodptr_type (type, new_type);
12879 }
12880
12881 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
12882    (icc).  */
12883
12884 static int
12885 producer_is_icc (struct dwarf2_cu *cu)
12886 {
12887   if (!cu->checked_producer)
12888     check_producer (cu);
12889
12890   return cu->producer_is_icc;
12891 }
12892
12893 /* Called when we find the DIE that starts a structure or union scope
12894    (definition) to create a type for the structure or union.  Fill in
12895    the type's name and general properties; the members will not be
12896    processed until process_structure_scope.  A symbol table entry for
12897    the type will also not be done until process_structure_scope (assuming
12898    the type has a name).
12899
12900    NOTE: we need to call these functions regardless of whether or not the
12901    DIE has a DW_AT_name attribute, since it might be an anonymous
12902    structure or union.  This gets the type entered into our set of
12903    user defined types.  */
12904
12905 static struct type *
12906 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
12907 {
12908   struct objfile *objfile = cu->objfile;
12909   struct type *type;
12910   struct attribute *attr;
12911   const char *name;
12912
12913   /* If the definition of this type lives in .debug_types, read that type.
12914      Don't follow DW_AT_specification though, that will take us back up
12915      the chain and we want to go down.  */
12916   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12917   if (attr)
12918     {
12919       type = get_DW_AT_signature_type (die, attr, cu);
12920
12921       /* The type's CU may not be the same as CU.
12922          Ensure TYPE is recorded with CU in die_type_hash.  */
12923       return set_die_type (die, type, cu);
12924     }
12925
12926   type = alloc_type (objfile);
12927   INIT_CPLUS_SPECIFIC (type);
12928
12929   name = dwarf2_name (die, cu);
12930   if (name != NULL)
12931     {
12932       if (cu->language == language_cplus
12933           || cu->language == language_java)
12934         {
12935           const char *full_name = dwarf2_full_name (name, die, cu);
12936
12937           /* dwarf2_full_name might have already finished building the DIE's
12938              type.  If so, there is no need to continue.  */
12939           if (get_die_type (die, cu) != NULL)
12940             return get_die_type (die, cu);
12941
12942           TYPE_TAG_NAME (type) = full_name;
12943           if (die->tag == DW_TAG_structure_type
12944               || die->tag == DW_TAG_class_type)
12945             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12946         }
12947       else
12948         {
12949           /* The name is already allocated along with this objfile, so
12950              we don't need to duplicate it for the type.  */
12951           TYPE_TAG_NAME (type) = name;
12952           if (die->tag == DW_TAG_class_type)
12953             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12954         }
12955     }
12956
12957   if (die->tag == DW_TAG_structure_type)
12958     {
12959       TYPE_CODE (type) = TYPE_CODE_STRUCT;
12960     }
12961   else if (die->tag == DW_TAG_union_type)
12962     {
12963       TYPE_CODE (type) = TYPE_CODE_UNION;
12964     }
12965   else
12966     {
12967       TYPE_CODE (type) = TYPE_CODE_CLASS;
12968     }
12969
12970   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
12971     TYPE_DECLARED_CLASS (type) = 1;
12972
12973   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12974   if (attr)
12975     {
12976       TYPE_LENGTH (type) = DW_UNSND (attr);
12977     }
12978   else
12979     {
12980       TYPE_LENGTH (type) = 0;
12981     }
12982
12983   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
12984     {
12985       /* ICC does not output the required DW_AT_declaration
12986          on incomplete types, but gives them a size of zero.  */
12987       TYPE_STUB (type) = 1;
12988     }
12989   else
12990     TYPE_STUB_SUPPORTED (type) = 1;
12991
12992   if (die_is_declaration (die, cu))
12993     TYPE_STUB (type) = 1;
12994   else if (attr == NULL && die->child == NULL
12995            && producer_is_realview (cu->producer))
12996     /* RealView does not output the required DW_AT_declaration
12997        on incomplete types.  */
12998     TYPE_STUB (type) = 1;
12999
13000   /* We need to add the type field to the die immediately so we don't
13001      infinitely recurse when dealing with pointers to the structure
13002      type within the structure itself.  */
13003   set_die_type (die, type, cu);
13004
13005   /* set_die_type should be already done.  */
13006   set_descriptive_type (type, die, cu);
13007
13008   return type;
13009 }
13010
13011 /* Finish creating a structure or union type, including filling in
13012    its members and creating a symbol for it.  */
13013
13014 static void
13015 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13016 {
13017   struct objfile *objfile = cu->objfile;
13018   struct die_info *child_die = die->child;
13019   struct type *type;
13020
13021   type = get_die_type (die, cu);
13022   if (type == NULL)
13023     type = read_structure_type (die, cu);
13024
13025   if (die->child != NULL && ! die_is_declaration (die, cu))
13026     {
13027       struct field_info fi;
13028       struct die_info *child_die;
13029       VEC (symbolp) *template_args = NULL;
13030       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13031
13032       memset (&fi, 0, sizeof (struct field_info));
13033
13034       child_die = die->child;
13035
13036       while (child_die && child_die->tag)
13037         {
13038           if (child_die->tag == DW_TAG_member
13039               || child_die->tag == DW_TAG_variable)
13040             {
13041               /* NOTE: carlton/2002-11-05: A C++ static data member
13042                  should be a DW_TAG_member that is a declaration, but
13043                  all versions of G++ as of this writing (so through at
13044                  least 3.2.1) incorrectly generate DW_TAG_variable
13045                  tags for them instead.  */
13046               dwarf2_add_field (&fi, child_die, cu);
13047             }
13048           else if (child_die->tag == DW_TAG_subprogram)
13049             {
13050               /* C++ member function.  */
13051               dwarf2_add_member_fn (&fi, child_die, type, cu);
13052             }
13053           else if (child_die->tag == DW_TAG_inheritance)
13054             {
13055               /* C++ base class field.  */
13056               dwarf2_add_field (&fi, child_die, cu);
13057             }
13058           else if (child_die->tag == DW_TAG_typedef)
13059             dwarf2_add_typedef (&fi, child_die, cu);
13060           else if (child_die->tag == DW_TAG_template_type_param
13061                    || child_die->tag == DW_TAG_template_value_param)
13062             {
13063               struct symbol *arg = new_symbol (child_die, NULL, cu);
13064
13065               if (arg != NULL)
13066                 VEC_safe_push (symbolp, template_args, arg);
13067             }
13068
13069           child_die = sibling_die (child_die);
13070         }
13071
13072       /* Attach template arguments to type.  */
13073       if (! VEC_empty (symbolp, template_args))
13074         {
13075           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13076           TYPE_N_TEMPLATE_ARGUMENTS (type)
13077             = VEC_length (symbolp, template_args);
13078           TYPE_TEMPLATE_ARGUMENTS (type)
13079             = obstack_alloc (&objfile->objfile_obstack,
13080                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
13081                               * sizeof (struct symbol *)));
13082           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13083                   VEC_address (symbolp, template_args),
13084                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13085                    * sizeof (struct symbol *)));
13086           VEC_free (symbolp, template_args);
13087         }
13088
13089       /* Attach fields and member functions to the type.  */
13090       if (fi.nfields)
13091         dwarf2_attach_fields_to_type (&fi, type, cu);
13092       if (fi.nfnfields)
13093         {
13094           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13095
13096           /* Get the type which refers to the base class (possibly this
13097              class itself) which contains the vtable pointer for the current
13098              class from the DW_AT_containing_type attribute.  This use of
13099              DW_AT_containing_type is a GNU extension.  */
13100
13101           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13102             {
13103               struct type *t = die_containing_type (die, cu);
13104
13105               TYPE_VPTR_BASETYPE (type) = t;
13106               if (type == t)
13107                 {
13108                   int i;
13109
13110                   /* Our own class provides vtbl ptr.  */
13111                   for (i = TYPE_NFIELDS (t) - 1;
13112                        i >= TYPE_N_BASECLASSES (t);
13113                        --i)
13114                     {
13115                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13116
13117                       if (is_vtable_name (fieldname, cu))
13118                         {
13119                           TYPE_VPTR_FIELDNO (type) = i;
13120                           break;
13121                         }
13122                     }
13123
13124                   /* Complain if virtual function table field not found.  */
13125                   if (i < TYPE_N_BASECLASSES (t))
13126                     complaint (&symfile_complaints,
13127                                _("virtual function table pointer "
13128                                  "not found when defining class '%s'"),
13129                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13130                                "");
13131                 }
13132               else
13133                 {
13134                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
13135                 }
13136             }
13137           else if (cu->producer
13138                    && strncmp (cu->producer,
13139                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
13140             {
13141               /* The IBM XLC compiler does not provide direct indication
13142                  of the containing type, but the vtable pointer is
13143                  always named __vfp.  */
13144
13145               int i;
13146
13147               for (i = TYPE_NFIELDS (type) - 1;
13148                    i >= TYPE_N_BASECLASSES (type);
13149                    --i)
13150                 {
13151                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13152                     {
13153                       TYPE_VPTR_FIELDNO (type) = i;
13154                       TYPE_VPTR_BASETYPE (type) = type;
13155                       break;
13156                     }
13157                 }
13158             }
13159         }
13160
13161       /* Copy fi.typedef_field_list linked list elements content into the
13162          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13163       if (fi.typedef_field_list)
13164         {
13165           int i = fi.typedef_field_list_count;
13166
13167           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13168           TYPE_TYPEDEF_FIELD_ARRAY (type)
13169             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
13170           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13171
13172           /* Reverse the list order to keep the debug info elements order.  */
13173           while (--i >= 0)
13174             {
13175               struct typedef_field *dest, *src;
13176
13177               dest = &TYPE_TYPEDEF_FIELD (type, i);
13178               src = &fi.typedef_field_list->field;
13179               fi.typedef_field_list = fi.typedef_field_list->next;
13180               *dest = *src;
13181             }
13182         }
13183
13184       do_cleanups (back_to);
13185
13186       if (HAVE_CPLUS_STRUCT (type))
13187         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
13188     }
13189
13190   quirk_gcc_member_function_pointer (type, objfile);
13191
13192   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13193      snapshots) has been known to create a die giving a declaration
13194      for a class that has, as a child, a die giving a definition for a
13195      nested class.  So we have to process our children even if the
13196      current die is a declaration.  Normally, of course, a declaration
13197      won't have any children at all.  */
13198
13199   while (child_die != NULL && child_die->tag)
13200     {
13201       if (child_die->tag == DW_TAG_member
13202           || child_die->tag == DW_TAG_variable
13203           || child_die->tag == DW_TAG_inheritance
13204           || child_die->tag == DW_TAG_template_value_param
13205           || child_die->tag == DW_TAG_template_type_param)
13206         {
13207           /* Do nothing.  */
13208         }
13209       else
13210         process_die (child_die, cu);
13211
13212       child_die = sibling_die (child_die);
13213     }
13214
13215   /* Do not consider external references.  According to the DWARF standard,
13216      these DIEs are identified by the fact that they have no byte_size
13217      attribute, and a declaration attribute.  */
13218   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13219       || !die_is_declaration (die, cu))
13220     new_symbol (die, type, cu);
13221 }
13222
13223 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13224    update TYPE using some information only available in DIE's children.  */
13225
13226 static void
13227 update_enumeration_type_from_children (struct die_info *die,
13228                                        struct type *type,
13229                                        struct dwarf2_cu *cu)
13230 {
13231   struct obstack obstack;
13232   struct die_info *child_die = die->child;
13233   int unsigned_enum = 1;
13234   int flag_enum = 1;
13235   ULONGEST mask = 0;
13236   struct cleanup *old_chain;
13237
13238   obstack_init (&obstack);
13239   old_chain = make_cleanup_obstack_free (&obstack);
13240
13241   while (child_die != NULL && child_die->tag)
13242     {
13243       struct attribute *attr;
13244       LONGEST value;
13245       const gdb_byte *bytes;
13246       struct dwarf2_locexpr_baton *baton;
13247       const char *name;
13248       if (child_die->tag != DW_TAG_enumerator)
13249         continue;
13250
13251       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13252       if (attr == NULL)
13253         continue;
13254
13255       name = dwarf2_name (child_die, cu);
13256       if (name == NULL)
13257         name = "<anonymous enumerator>";
13258
13259       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13260                                &value, &bytes, &baton);
13261       if (value < 0)
13262         {
13263           unsigned_enum = 0;
13264           flag_enum = 0;
13265         }
13266       else if ((mask & value) != 0)
13267         flag_enum = 0;
13268       else
13269         mask |= value;
13270
13271       /* If we already know that the enum type is neither unsigned, nor
13272          a flag type, no need to look at the rest of the enumerates.  */
13273       if (!unsigned_enum && !flag_enum)
13274         break;
13275       child_die = sibling_die (child_die);
13276     }
13277
13278   if (unsigned_enum)
13279     TYPE_UNSIGNED (type) = 1;
13280   if (flag_enum)
13281     TYPE_FLAG_ENUM (type) = 1;
13282
13283   do_cleanups (old_chain);
13284 }
13285
13286 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13287    complete the type's fields yet, or create any symbols.  */
13288
13289 static struct type *
13290 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13291 {
13292   struct objfile *objfile = cu->objfile;
13293   struct type *type;
13294   struct attribute *attr;
13295   const char *name;
13296
13297   /* If the definition of this type lives in .debug_types, read that type.
13298      Don't follow DW_AT_specification though, that will take us back up
13299      the chain and we want to go down.  */
13300   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13301   if (attr)
13302     {
13303       type = get_DW_AT_signature_type (die, attr, cu);
13304
13305       /* The type's CU may not be the same as CU.
13306          Ensure TYPE is recorded with CU in die_type_hash.  */
13307       return set_die_type (die, type, cu);
13308     }
13309
13310   type = alloc_type (objfile);
13311
13312   TYPE_CODE (type) = TYPE_CODE_ENUM;
13313   name = dwarf2_full_name (NULL, die, cu);
13314   if (name != NULL)
13315     TYPE_TAG_NAME (type) = name;
13316
13317   attr = dwarf2_attr (die, DW_AT_type, cu);
13318   if (attr != NULL)
13319     {
13320       struct type *underlying_type = die_type (die, cu);
13321
13322       TYPE_TARGET_TYPE (type) = underlying_type;
13323     }
13324
13325   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13326   if (attr)
13327     {
13328       TYPE_LENGTH (type) = DW_UNSND (attr);
13329     }
13330   else
13331     {
13332       TYPE_LENGTH (type) = 0;
13333     }
13334
13335   /* The enumeration DIE can be incomplete.  In Ada, any type can be
13336      declared as private in the package spec, and then defined only
13337      inside the package body.  Such types are known as Taft Amendment
13338      Types.  When another package uses such a type, an incomplete DIE
13339      may be generated by the compiler.  */
13340   if (die_is_declaration (die, cu))
13341     TYPE_STUB (type) = 1;
13342
13343   /* Finish the creation of this type by using the enum's children.
13344      We must call this even when the underlying type has been provided
13345      so that we can determine if we're looking at a "flag" enum.  */
13346   update_enumeration_type_from_children (die, type, cu);
13347
13348   /* If this type has an underlying type that is not a stub, then we
13349      may use its attributes.  We always use the "unsigned" attribute
13350      in this situation, because ordinarily we guess whether the type
13351      is unsigned -- but the guess can be wrong and the underlying type
13352      can tell us the reality.  However, we defer to a local size
13353      attribute if one exists, because this lets the compiler override
13354      the underlying type if needed.  */
13355   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
13356     {
13357       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
13358       if (TYPE_LENGTH (type) == 0)
13359         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
13360     }
13361
13362   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
13363
13364   return set_die_type (die, type, cu);
13365 }
13366
13367 /* Given a pointer to a die which begins an enumeration, process all
13368    the dies that define the members of the enumeration, and create the
13369    symbol for the enumeration type.
13370
13371    NOTE: We reverse the order of the element list.  */
13372
13373 static void
13374 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
13375 {
13376   struct type *this_type;
13377
13378   this_type = get_die_type (die, cu);
13379   if (this_type == NULL)
13380     this_type = read_enumeration_type (die, cu);
13381
13382   if (die->child != NULL)
13383     {
13384       struct die_info *child_die;
13385       struct symbol *sym;
13386       struct field *fields = NULL;
13387       int num_fields = 0;
13388       const char *name;
13389
13390       child_die = die->child;
13391       while (child_die && child_die->tag)
13392         {
13393           if (child_die->tag != DW_TAG_enumerator)
13394             {
13395               process_die (child_die, cu);
13396             }
13397           else
13398             {
13399               name = dwarf2_name (child_die, cu);
13400               if (name)
13401                 {
13402                   sym = new_symbol (child_die, this_type, cu);
13403
13404                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
13405                     {
13406                       fields = (struct field *)
13407                         xrealloc (fields,
13408                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
13409                                   * sizeof (struct field));
13410                     }
13411
13412                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
13413                   FIELD_TYPE (fields[num_fields]) = NULL;
13414                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
13415                   FIELD_BITSIZE (fields[num_fields]) = 0;
13416
13417                   num_fields++;
13418                 }
13419             }
13420
13421           child_die = sibling_die (child_die);
13422         }
13423
13424       if (num_fields)
13425         {
13426           TYPE_NFIELDS (this_type) = num_fields;
13427           TYPE_FIELDS (this_type) = (struct field *)
13428             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
13429           memcpy (TYPE_FIELDS (this_type), fields,
13430                   sizeof (struct field) * num_fields);
13431           xfree (fields);
13432         }
13433     }
13434
13435   /* If we are reading an enum from a .debug_types unit, and the enum
13436      is a declaration, and the enum is not the signatured type in the
13437      unit, then we do not want to add a symbol for it.  Adding a
13438      symbol would in some cases obscure the true definition of the
13439      enum, giving users an incomplete type when the definition is
13440      actually available.  Note that we do not want to do this for all
13441      enums which are just declarations, because C++0x allows forward
13442      enum declarations.  */
13443   if (cu->per_cu->is_debug_types
13444       && die_is_declaration (die, cu))
13445     {
13446       struct signatured_type *sig_type;
13447
13448       sig_type = (struct signatured_type *) cu->per_cu;
13449       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
13450       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
13451         return;
13452     }
13453
13454   new_symbol (die, this_type, cu);
13455 }
13456
13457 /* Extract all information from a DW_TAG_array_type DIE and put it in
13458    the DIE's type field.  For now, this only handles one dimensional
13459    arrays.  */
13460
13461 static struct type *
13462 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
13463 {
13464   struct objfile *objfile = cu->objfile;
13465   struct die_info *child_die;
13466   struct type *type;
13467   struct type *element_type, *range_type, *index_type;
13468   struct type **range_types = NULL;
13469   struct attribute *attr;
13470   int ndim = 0;
13471   struct cleanup *back_to;
13472   const char *name;
13473   unsigned int bit_stride = 0;
13474
13475   element_type = die_type (die, cu);
13476
13477   /* The die_type call above may have already set the type for this DIE.  */
13478   type = get_die_type (die, cu);
13479   if (type)
13480     return type;
13481
13482   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
13483   if (attr != NULL)
13484     bit_stride = DW_UNSND (attr) * 8;
13485
13486   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
13487   if (attr != NULL)
13488     bit_stride = DW_UNSND (attr);
13489
13490   /* Irix 6.2 native cc creates array types without children for
13491      arrays with unspecified length.  */
13492   if (die->child == NULL)
13493     {
13494       index_type = objfile_type (objfile)->builtin_int;
13495       range_type = create_static_range_type (NULL, index_type, 0, -1);
13496       type = create_array_type_with_stride (NULL, element_type, range_type,
13497                                             bit_stride);
13498       return set_die_type (die, type, cu);
13499     }
13500
13501   back_to = make_cleanup (null_cleanup, NULL);
13502   child_die = die->child;
13503   while (child_die && child_die->tag)
13504     {
13505       if (child_die->tag == DW_TAG_subrange_type)
13506         {
13507           struct type *child_type = read_type_die (child_die, cu);
13508
13509           if (child_type != NULL)
13510             {
13511               /* The range type was succesfully read.  Save it for the
13512                  array type creation.  */
13513               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
13514                 {
13515                   range_types = (struct type **)
13516                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
13517                               * sizeof (struct type *));
13518                   if (ndim == 0)
13519                     make_cleanup (free_current_contents, &range_types);
13520                 }
13521               range_types[ndim++] = child_type;
13522             }
13523         }
13524       child_die = sibling_die (child_die);
13525     }
13526
13527   /* Dwarf2 dimensions are output from left to right, create the
13528      necessary array types in backwards order.  */
13529
13530   type = element_type;
13531
13532   if (read_array_order (die, cu) == DW_ORD_col_major)
13533     {
13534       int i = 0;
13535
13536       while (i < ndim)
13537         type = create_array_type_with_stride (NULL, type, range_types[i++],
13538                                               bit_stride);
13539     }
13540   else
13541     {
13542       while (ndim-- > 0)
13543         type = create_array_type_with_stride (NULL, type, range_types[ndim],
13544                                               bit_stride);
13545     }
13546
13547   /* Understand Dwarf2 support for vector types (like they occur on
13548      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
13549      array type.  This is not part of the Dwarf2/3 standard yet, but a
13550      custom vendor extension.  The main difference between a regular
13551      array and the vector variant is that vectors are passed by value
13552      to functions.  */
13553   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
13554   if (attr)
13555     make_vector_type (type);
13556
13557   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
13558      implementation may choose to implement triple vectors using this
13559      attribute.  */
13560   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13561   if (attr)
13562     {
13563       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
13564         TYPE_LENGTH (type) = DW_UNSND (attr);
13565       else
13566         complaint (&symfile_complaints,
13567                    _("DW_AT_byte_size for array type smaller "
13568                      "than the total size of elements"));
13569     }
13570
13571   name = dwarf2_name (die, cu);
13572   if (name)
13573     TYPE_NAME (type) = name;
13574
13575   /* Install the type in the die.  */
13576   set_die_type (die, type, cu);
13577
13578   /* set_die_type should be already done.  */
13579   set_descriptive_type (type, die, cu);
13580
13581   do_cleanups (back_to);
13582
13583   return type;
13584 }
13585
13586 static enum dwarf_array_dim_ordering
13587 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
13588 {
13589   struct attribute *attr;
13590
13591   attr = dwarf2_attr (die, DW_AT_ordering, cu);
13592
13593   if (attr) return DW_SND (attr);
13594
13595   /* GNU F77 is a special case, as at 08/2004 array type info is the
13596      opposite order to the dwarf2 specification, but data is still
13597      laid out as per normal fortran.
13598
13599      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
13600      version checking.  */
13601
13602   if (cu->language == language_fortran
13603       && cu->producer && strstr (cu->producer, "GNU F77"))
13604     {
13605       return DW_ORD_row_major;
13606     }
13607
13608   switch (cu->language_defn->la_array_ordering)
13609     {
13610     case array_column_major:
13611       return DW_ORD_col_major;
13612     case array_row_major:
13613     default:
13614       return DW_ORD_row_major;
13615     };
13616 }
13617
13618 /* Extract all information from a DW_TAG_set_type DIE and put it in
13619    the DIE's type field.  */
13620
13621 static struct type *
13622 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
13623 {
13624   struct type *domain_type, *set_type;
13625   struct attribute *attr;
13626
13627   domain_type = die_type (die, cu);
13628
13629   /* The die_type call above may have already set the type for this DIE.  */
13630   set_type = get_die_type (die, cu);
13631   if (set_type)
13632     return set_type;
13633
13634   set_type = create_set_type (NULL, domain_type);
13635
13636   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13637   if (attr)
13638     TYPE_LENGTH (set_type) = DW_UNSND (attr);
13639
13640   return set_die_type (die, set_type, cu);
13641 }
13642
13643 /* A helper for read_common_block that creates a locexpr baton.
13644    SYM is the symbol which we are marking as computed.
13645    COMMON_DIE is the DIE for the common block.
13646    COMMON_LOC is the location expression attribute for the common
13647    block itself.
13648    MEMBER_LOC is the location expression attribute for the particular
13649    member of the common block that we are processing.
13650    CU is the CU from which the above come.  */
13651
13652 static void
13653 mark_common_block_symbol_computed (struct symbol *sym,
13654                                    struct die_info *common_die,
13655                                    struct attribute *common_loc,
13656                                    struct attribute *member_loc,
13657                                    struct dwarf2_cu *cu)
13658 {
13659   struct objfile *objfile = dwarf2_per_objfile->objfile;
13660   struct dwarf2_locexpr_baton *baton;
13661   gdb_byte *ptr;
13662   unsigned int cu_off;
13663   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
13664   LONGEST offset = 0;
13665
13666   gdb_assert (common_loc && member_loc);
13667   gdb_assert (attr_form_is_block (common_loc));
13668   gdb_assert (attr_form_is_block (member_loc)
13669               || attr_form_is_constant (member_loc));
13670
13671   baton = obstack_alloc (&objfile->objfile_obstack,
13672                          sizeof (struct dwarf2_locexpr_baton));
13673   baton->per_cu = cu->per_cu;
13674   gdb_assert (baton->per_cu);
13675
13676   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
13677
13678   if (attr_form_is_constant (member_loc))
13679     {
13680       offset = dwarf2_get_attr_constant_value (member_loc, 0);
13681       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
13682     }
13683   else
13684     baton->size += DW_BLOCK (member_loc)->size;
13685
13686   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
13687   baton->data = ptr;
13688
13689   *ptr++ = DW_OP_call4;
13690   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
13691   store_unsigned_integer (ptr, 4, byte_order, cu_off);
13692   ptr += 4;
13693
13694   if (attr_form_is_constant (member_loc))
13695     {
13696       *ptr++ = DW_OP_addr;
13697       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
13698       ptr += cu->header.addr_size;
13699     }
13700   else
13701     {
13702       /* We have to copy the data here, because DW_OP_call4 will only
13703          use a DW_AT_location attribute.  */
13704       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
13705       ptr += DW_BLOCK (member_loc)->size;
13706     }
13707
13708   *ptr++ = DW_OP_plus;
13709   gdb_assert (ptr - baton->data == baton->size);
13710
13711   SYMBOL_LOCATION_BATON (sym) = baton;
13712   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
13713 }
13714
13715 /* Create appropriate locally-scoped variables for all the
13716    DW_TAG_common_block entries.  Also create a struct common_block
13717    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
13718    is used to sepate the common blocks name namespace from regular
13719    variable names.  */
13720
13721 static void
13722 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
13723 {
13724   struct attribute *attr;
13725
13726   attr = dwarf2_attr (die, DW_AT_location, cu);
13727   if (attr)
13728     {
13729       /* Support the .debug_loc offsets.  */
13730       if (attr_form_is_block (attr))
13731         {
13732           /* Ok.  */
13733         }
13734       else if (attr_form_is_section_offset (attr))
13735         {
13736           dwarf2_complex_location_expr_complaint ();
13737           attr = NULL;
13738         }
13739       else
13740         {
13741           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13742                                                  "common block member");
13743           attr = NULL;
13744         }
13745     }
13746
13747   if (die->child != NULL)
13748     {
13749       struct objfile *objfile = cu->objfile;
13750       struct die_info *child_die;
13751       size_t n_entries = 0, size;
13752       struct common_block *common_block;
13753       struct symbol *sym;
13754
13755       for (child_die = die->child;
13756            child_die && child_die->tag;
13757            child_die = sibling_die (child_die))
13758         ++n_entries;
13759
13760       size = (sizeof (struct common_block)
13761               + (n_entries - 1) * sizeof (struct symbol *));
13762       common_block = obstack_alloc (&objfile->objfile_obstack, size);
13763       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
13764       common_block->n_entries = 0;
13765
13766       for (child_die = die->child;
13767            child_die && child_die->tag;
13768            child_die = sibling_die (child_die))
13769         {
13770           /* Create the symbol in the DW_TAG_common_block block in the current
13771              symbol scope.  */
13772           sym = new_symbol (child_die, NULL, cu);
13773           if (sym != NULL)
13774             {
13775               struct attribute *member_loc;
13776
13777               common_block->contents[common_block->n_entries++] = sym;
13778
13779               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
13780                                         cu);
13781               if (member_loc)
13782                 {
13783                   /* GDB has handled this for a long time, but it is
13784                      not specified by DWARF.  It seems to have been
13785                      emitted by gfortran at least as recently as:
13786                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
13787                   complaint (&symfile_complaints,
13788                              _("Variable in common block has "
13789                                "DW_AT_data_member_location "
13790                                "- DIE at 0x%x [in module %s]"),
13791                              child_die->offset.sect_off,
13792                              objfile_name (cu->objfile));
13793
13794                   if (attr_form_is_section_offset (member_loc))
13795                     dwarf2_complex_location_expr_complaint ();
13796                   else if (attr_form_is_constant (member_loc)
13797                            || attr_form_is_block (member_loc))
13798                     {
13799                       if (attr)
13800                         mark_common_block_symbol_computed (sym, die, attr,
13801                                                            member_loc, cu);
13802                     }
13803                   else
13804                     dwarf2_complex_location_expr_complaint ();
13805                 }
13806             }
13807         }
13808
13809       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
13810       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
13811     }
13812 }
13813
13814 /* Create a type for a C++ namespace.  */
13815
13816 static struct type *
13817 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
13818 {
13819   struct objfile *objfile = cu->objfile;
13820   const char *previous_prefix, *name;
13821   int is_anonymous;
13822   struct type *type;
13823
13824   /* For extensions, reuse the type of the original namespace.  */
13825   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
13826     {
13827       struct die_info *ext_die;
13828       struct dwarf2_cu *ext_cu = cu;
13829
13830       ext_die = dwarf2_extension (die, &ext_cu);
13831       type = read_type_die (ext_die, ext_cu);
13832
13833       /* EXT_CU may not be the same as CU.
13834          Ensure TYPE is recorded with CU in die_type_hash.  */
13835       return set_die_type (die, type, cu);
13836     }
13837
13838   name = namespace_name (die, &is_anonymous, cu);
13839
13840   /* Now build the name of the current namespace.  */
13841
13842   previous_prefix = determine_prefix (die, cu);
13843   if (previous_prefix[0] != '\0')
13844     name = typename_concat (&objfile->objfile_obstack,
13845                             previous_prefix, name, 0, cu);
13846
13847   /* Create the type.  */
13848   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
13849                     objfile);
13850   TYPE_NAME (type) = name;
13851   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13852
13853   return set_die_type (die, type, cu);
13854 }
13855
13856 /* Read a C++ namespace.  */
13857
13858 static void
13859 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
13860 {
13861   struct objfile *objfile = cu->objfile;
13862   int is_anonymous;
13863
13864   /* Add a symbol associated to this if we haven't seen the namespace
13865      before.  Also, add a using directive if it's an anonymous
13866      namespace.  */
13867
13868   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
13869     {
13870       struct type *type;
13871
13872       type = read_type_die (die, cu);
13873       new_symbol (die, type, cu);
13874
13875       namespace_name (die, &is_anonymous, cu);
13876       if (is_anonymous)
13877         {
13878           const char *previous_prefix = determine_prefix (die, cu);
13879
13880           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
13881                                   NULL, NULL, 0, &objfile->objfile_obstack);
13882         }
13883     }
13884
13885   if (die->child != NULL)
13886     {
13887       struct die_info *child_die = die->child;
13888
13889       while (child_die && child_die->tag)
13890         {
13891           process_die (child_die, cu);
13892           child_die = sibling_die (child_die);
13893         }
13894     }
13895 }
13896
13897 /* Read a Fortran module as type.  This DIE can be only a declaration used for
13898    imported module.  Still we need that type as local Fortran "use ... only"
13899    declaration imports depend on the created type in determine_prefix.  */
13900
13901 static struct type *
13902 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
13903 {
13904   struct objfile *objfile = cu->objfile;
13905   const char *module_name;
13906   struct type *type;
13907
13908   module_name = dwarf2_name (die, cu);
13909   if (!module_name)
13910     complaint (&symfile_complaints,
13911                _("DW_TAG_module has no name, offset 0x%x"),
13912                die->offset.sect_off);
13913   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
13914
13915   /* determine_prefix uses TYPE_TAG_NAME.  */
13916   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13917
13918   return set_die_type (die, type, cu);
13919 }
13920
13921 /* Read a Fortran module.  */
13922
13923 static void
13924 read_module (struct die_info *die, struct dwarf2_cu *cu)
13925 {
13926   struct die_info *child_die = die->child;
13927   struct type *type;
13928
13929   type = read_type_die (die, cu);
13930   new_symbol (die, type, cu);
13931
13932   while (child_die && child_die->tag)
13933     {
13934       process_die (child_die, cu);
13935       child_die = sibling_die (child_die);
13936     }
13937 }
13938
13939 /* Return the name of the namespace represented by DIE.  Set
13940    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
13941    namespace.  */
13942
13943 static const char *
13944 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
13945 {
13946   struct die_info *current_die;
13947   const char *name = NULL;
13948
13949   /* Loop through the extensions until we find a name.  */
13950
13951   for (current_die = die;
13952        current_die != NULL;
13953        current_die = dwarf2_extension (die, &cu))
13954     {
13955       name = dwarf2_name (current_die, cu);
13956       if (name != NULL)
13957         break;
13958     }
13959
13960   /* Is it an anonymous namespace?  */
13961
13962   *is_anonymous = (name == NULL);
13963   if (*is_anonymous)
13964     name = CP_ANONYMOUS_NAMESPACE_STR;
13965
13966   return name;
13967 }
13968
13969 /* Extract all information from a DW_TAG_pointer_type DIE and add to
13970    the user defined type vector.  */
13971
13972 static struct type *
13973 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
13974 {
13975   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
13976   struct comp_unit_head *cu_header = &cu->header;
13977   struct type *type;
13978   struct attribute *attr_byte_size;
13979   struct attribute *attr_address_class;
13980   int byte_size, addr_class;
13981   struct type *target_type;
13982
13983   target_type = die_type (die, cu);
13984
13985   /* The die_type call above may have already set the type for this DIE.  */
13986   type = get_die_type (die, cu);
13987   if (type)
13988     return type;
13989
13990   type = lookup_pointer_type (target_type);
13991
13992   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
13993   if (attr_byte_size)
13994     byte_size = DW_UNSND (attr_byte_size);
13995   else
13996     byte_size = cu_header->addr_size;
13997
13998   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
13999   if (attr_address_class)
14000     addr_class = DW_UNSND (attr_address_class);
14001   else
14002     addr_class = DW_ADDR_none;
14003
14004   /* If the pointer size or address class is different than the
14005      default, create a type variant marked as such and set the
14006      length accordingly.  */
14007   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14008     {
14009       if (gdbarch_address_class_type_flags_p (gdbarch))
14010         {
14011           int type_flags;
14012
14013           type_flags = gdbarch_address_class_type_flags
14014                          (gdbarch, byte_size, addr_class);
14015           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14016                       == 0);
14017           type = make_type_with_address_space (type, type_flags);
14018         }
14019       else if (TYPE_LENGTH (type) != byte_size)
14020         {
14021           complaint (&symfile_complaints,
14022                      _("invalid pointer size %d"), byte_size);
14023         }
14024       else
14025         {
14026           /* Should we also complain about unhandled address classes?  */
14027         }
14028     }
14029
14030   TYPE_LENGTH (type) = byte_size;
14031   return set_die_type (die, type, cu);
14032 }
14033
14034 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14035    the user defined type vector.  */
14036
14037 static struct type *
14038 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14039 {
14040   struct type *type;
14041   struct type *to_type;
14042   struct type *domain;
14043
14044   to_type = die_type (die, cu);
14045   domain = die_containing_type (die, cu);
14046
14047   /* The calls above may have already set the type for this DIE.  */
14048   type = get_die_type (die, cu);
14049   if (type)
14050     return type;
14051
14052   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14053     type = lookup_methodptr_type (to_type);
14054   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14055     {
14056       struct type *new_type = alloc_type (cu->objfile);
14057
14058       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14059                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14060                             TYPE_VARARGS (to_type));
14061       type = lookup_methodptr_type (new_type);
14062     }
14063   else
14064     type = lookup_memberptr_type (to_type, domain);
14065
14066   return set_die_type (die, type, cu);
14067 }
14068
14069 /* Extract all information from a DW_TAG_reference_type DIE and add to
14070    the user defined type vector.  */
14071
14072 static struct type *
14073 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
14074 {
14075   struct comp_unit_head *cu_header = &cu->header;
14076   struct type *type, *target_type;
14077   struct attribute *attr;
14078
14079   target_type = die_type (die, cu);
14080
14081   /* The die_type call above may have already set the type for this DIE.  */
14082   type = get_die_type (die, cu);
14083   if (type)
14084     return type;
14085
14086   type = lookup_reference_type (target_type);
14087   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14088   if (attr)
14089     {
14090       TYPE_LENGTH (type) = DW_UNSND (attr);
14091     }
14092   else
14093     {
14094       TYPE_LENGTH (type) = cu_header->addr_size;
14095     }
14096   return set_die_type (die, type, cu);
14097 }
14098
14099 /* Add the given cv-qualifiers to the element type of the array.  GCC
14100    outputs DWARF type qualifiers that apply to an array, not the
14101    element type.  But GDB relies on the array element type to carry
14102    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14103    specification.  */
14104
14105 static struct type *
14106 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14107                    struct type *base_type, int cnst, int voltl)
14108 {
14109   struct type *el_type, *inner_array;
14110
14111   base_type = copy_type (base_type);
14112   inner_array = base_type;
14113
14114   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14115     {
14116       TYPE_TARGET_TYPE (inner_array) =
14117         copy_type (TYPE_TARGET_TYPE (inner_array));
14118       inner_array = TYPE_TARGET_TYPE (inner_array);
14119     }
14120
14121   el_type = TYPE_TARGET_TYPE (inner_array);
14122   cnst |= TYPE_CONST (el_type);
14123   voltl |= TYPE_VOLATILE (el_type);
14124   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14125
14126   return set_die_type (die, base_type, cu);
14127 }
14128
14129 static struct type *
14130 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14131 {
14132   struct type *base_type, *cv_type;
14133
14134   base_type = die_type (die, cu);
14135
14136   /* The die_type call above may have already set the type for this DIE.  */
14137   cv_type = get_die_type (die, cu);
14138   if (cv_type)
14139     return cv_type;
14140
14141   /* In case the const qualifier is applied to an array type, the element type
14142      is so qualified, not the array type (section 6.7.3 of C99).  */
14143   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14144     return add_array_cv_type (die, cu, base_type, 1, 0);
14145
14146   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14147   return set_die_type (die, cv_type, cu);
14148 }
14149
14150 static struct type *
14151 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14152 {
14153   struct type *base_type, *cv_type;
14154
14155   base_type = die_type (die, cu);
14156
14157   /* The die_type call above may have already set the type for this DIE.  */
14158   cv_type = get_die_type (die, cu);
14159   if (cv_type)
14160     return cv_type;
14161
14162   /* In case the volatile qualifier is applied to an array type, the
14163      element type is so qualified, not the array type (section 6.7.3
14164      of C99).  */
14165   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14166     return add_array_cv_type (die, cu, base_type, 0, 1);
14167
14168   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14169   return set_die_type (die, cv_type, cu);
14170 }
14171
14172 /* Handle DW_TAG_restrict_type.  */
14173
14174 static struct type *
14175 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14176 {
14177   struct type *base_type, *cv_type;
14178
14179   base_type = die_type (die, cu);
14180
14181   /* The die_type call above may have already set the type for this DIE.  */
14182   cv_type = get_die_type (die, cu);
14183   if (cv_type)
14184     return cv_type;
14185
14186   cv_type = make_restrict_type (base_type);
14187   return set_die_type (die, cv_type, cu);
14188 }
14189
14190 /* Extract all information from a DW_TAG_string_type DIE and add to
14191    the user defined type vector.  It isn't really a user defined type,
14192    but it behaves like one, with other DIE's using an AT_user_def_type
14193    attribute to reference it.  */
14194
14195 static struct type *
14196 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14197 {
14198   struct objfile *objfile = cu->objfile;
14199   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14200   struct type *type, *range_type, *index_type, *char_type;
14201   struct attribute *attr;
14202   unsigned int length;
14203
14204   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14205   if (attr)
14206     {
14207       length = DW_UNSND (attr);
14208     }
14209   else
14210     {
14211       /* Check for the DW_AT_byte_size attribute.  */
14212       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14213       if (attr)
14214         {
14215           length = DW_UNSND (attr);
14216         }
14217       else
14218         {
14219           length = 1;
14220         }
14221     }
14222
14223   index_type = objfile_type (objfile)->builtin_int;
14224   range_type = create_static_range_type (NULL, index_type, 1, length);
14225   char_type = language_string_char_type (cu->language_defn, gdbarch);
14226   type = create_string_type (NULL, char_type, range_type);
14227
14228   return set_die_type (die, type, cu);
14229 }
14230
14231 /* Assuming that DIE corresponds to a function, returns nonzero
14232    if the function is prototyped.  */
14233
14234 static int
14235 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14236 {
14237   struct attribute *attr;
14238
14239   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14240   if (attr && (DW_UNSND (attr) != 0))
14241     return 1;
14242
14243   /* The DWARF standard implies that the DW_AT_prototyped attribute
14244      is only meaninful for C, but the concept also extends to other
14245      languages that allow unprototyped functions (Eg: Objective C).
14246      For all other languages, assume that functions are always
14247      prototyped.  */
14248   if (cu->language != language_c
14249       && cu->language != language_objc
14250       && cu->language != language_opencl)
14251     return 1;
14252
14253   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14254      prototyped and unprototyped functions; default to prototyped,
14255      since that is more common in modern code (and RealView warns
14256      about unprototyped functions).  */
14257   if (producer_is_realview (cu->producer))
14258     return 1;
14259
14260   return 0;
14261 }
14262
14263 /* Handle DIES due to C code like:
14264
14265    struct foo
14266    {
14267    int (*funcp)(int a, long l);
14268    int b;
14269    };
14270
14271    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14272
14273 static struct type *
14274 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14275 {
14276   struct objfile *objfile = cu->objfile;
14277   struct type *type;            /* Type that this function returns.  */
14278   struct type *ftype;           /* Function that returns above type.  */
14279   struct attribute *attr;
14280
14281   type = die_type (die, cu);
14282
14283   /* The die_type call above may have already set the type for this DIE.  */
14284   ftype = get_die_type (die, cu);
14285   if (ftype)
14286     return ftype;
14287
14288   ftype = lookup_function_type (type);
14289
14290   if (prototyped_function_p (die, cu))
14291     TYPE_PROTOTYPED (ftype) = 1;
14292
14293   /* Store the calling convention in the type if it's available in
14294      the subroutine die.  Otherwise set the calling convention to
14295      the default value DW_CC_normal.  */
14296   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
14297   if (attr)
14298     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
14299   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
14300     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
14301   else
14302     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
14303
14304   /* We need to add the subroutine type to the die immediately so
14305      we don't infinitely recurse when dealing with parameters
14306      declared as the same subroutine type.  */
14307   set_die_type (die, ftype, cu);
14308
14309   if (die->child != NULL)
14310     {
14311       struct type *void_type = objfile_type (objfile)->builtin_void;
14312       struct die_info *child_die;
14313       int nparams, iparams;
14314
14315       /* Count the number of parameters.
14316          FIXME: GDB currently ignores vararg functions, but knows about
14317          vararg member functions.  */
14318       nparams = 0;
14319       child_die = die->child;
14320       while (child_die && child_die->tag)
14321         {
14322           if (child_die->tag == DW_TAG_formal_parameter)
14323             nparams++;
14324           else if (child_die->tag == DW_TAG_unspecified_parameters)
14325             TYPE_VARARGS (ftype) = 1;
14326           child_die = sibling_die (child_die);
14327         }
14328
14329       /* Allocate storage for parameters and fill them in.  */
14330       TYPE_NFIELDS (ftype) = nparams;
14331       TYPE_FIELDS (ftype) = (struct field *)
14332         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
14333
14334       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
14335          even if we error out during the parameters reading below.  */
14336       for (iparams = 0; iparams < nparams; iparams++)
14337         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
14338
14339       iparams = 0;
14340       child_die = die->child;
14341       while (child_die && child_die->tag)
14342         {
14343           if (child_die->tag == DW_TAG_formal_parameter)
14344             {
14345               struct type *arg_type;
14346
14347               /* DWARF version 2 has no clean way to discern C++
14348                  static and non-static member functions.  G++ helps
14349                  GDB by marking the first parameter for non-static
14350                  member functions (which is the this pointer) as
14351                  artificial.  We pass this information to
14352                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
14353
14354                  DWARF version 3 added DW_AT_object_pointer, which GCC
14355                  4.5 does not yet generate.  */
14356               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
14357               if (attr)
14358                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
14359               else
14360                 {
14361                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
14362
14363                   /* GCC/43521: In java, the formal parameter
14364                      "this" is sometimes not marked with DW_AT_artificial.  */
14365                   if (cu->language == language_java)
14366                     {
14367                       const char *name = dwarf2_name (child_die, cu);
14368
14369                       if (name && !strcmp (name, "this"))
14370                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
14371                     }
14372                 }
14373               arg_type = die_type (child_die, cu);
14374
14375               /* RealView does not mark THIS as const, which the testsuite
14376                  expects.  GCC marks THIS as const in method definitions,
14377                  but not in the class specifications (GCC PR 43053).  */
14378               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
14379                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
14380                 {
14381                   int is_this = 0;
14382                   struct dwarf2_cu *arg_cu = cu;
14383                   const char *name = dwarf2_name (child_die, cu);
14384
14385                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
14386                   if (attr)
14387                     {
14388                       /* If the compiler emits this, use it.  */
14389                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
14390                         is_this = 1;
14391                     }
14392                   else if (name && strcmp (name, "this") == 0)
14393                     /* Function definitions will have the argument names.  */
14394                     is_this = 1;
14395                   else if (name == NULL && iparams == 0)
14396                     /* Declarations may not have the names, so like
14397                        elsewhere in GDB, assume an artificial first
14398                        argument is "this".  */
14399                     is_this = 1;
14400
14401                   if (is_this)
14402                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
14403                                              arg_type, 0);
14404                 }
14405
14406               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
14407               iparams++;
14408             }
14409           child_die = sibling_die (child_die);
14410         }
14411     }
14412
14413   return ftype;
14414 }
14415
14416 static struct type *
14417 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
14418 {
14419   struct objfile *objfile = cu->objfile;
14420   const char *name = NULL;
14421   struct type *this_type, *target_type;
14422
14423   name = dwarf2_full_name (NULL, die, cu);
14424   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
14425                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
14426   TYPE_NAME (this_type) = name;
14427   set_die_type (die, this_type, cu);
14428   target_type = die_type (die, cu);
14429   if (target_type != this_type)
14430     TYPE_TARGET_TYPE (this_type) = target_type;
14431   else
14432     {
14433       /* Self-referential typedefs are, it seems, not allowed by the DWARF
14434          spec and cause infinite loops in GDB.  */
14435       complaint (&symfile_complaints,
14436                  _("Self-referential DW_TAG_typedef "
14437                    "- DIE at 0x%x [in module %s]"),
14438                  die->offset.sect_off, objfile_name (objfile));
14439       TYPE_TARGET_TYPE (this_type) = NULL;
14440     }
14441   return this_type;
14442 }
14443
14444 /* Find a representation of a given base type and install
14445    it in the TYPE field of the die.  */
14446
14447 static struct type *
14448 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
14449 {
14450   struct objfile *objfile = cu->objfile;
14451   struct type *type;
14452   struct attribute *attr;
14453   int encoding = 0, size = 0;
14454   const char *name;
14455   enum type_code code = TYPE_CODE_INT;
14456   int type_flags = 0;
14457   struct type *target_type = NULL;
14458
14459   attr = dwarf2_attr (die, DW_AT_encoding, cu);
14460   if (attr)
14461     {
14462       encoding = DW_UNSND (attr);
14463     }
14464   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14465   if (attr)
14466     {
14467       size = DW_UNSND (attr);
14468     }
14469   name = dwarf2_name (die, cu);
14470   if (!name)
14471     {
14472       complaint (&symfile_complaints,
14473                  _("DW_AT_name missing from DW_TAG_base_type"));
14474     }
14475
14476   switch (encoding)
14477     {
14478       case DW_ATE_address:
14479         /* Turn DW_ATE_address into a void * pointer.  */
14480         code = TYPE_CODE_PTR;
14481         type_flags |= TYPE_FLAG_UNSIGNED;
14482         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
14483         break;
14484       case DW_ATE_boolean:
14485         code = TYPE_CODE_BOOL;
14486         type_flags |= TYPE_FLAG_UNSIGNED;
14487         break;
14488       case DW_ATE_complex_float:
14489         code = TYPE_CODE_COMPLEX;
14490         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
14491         break;
14492       case DW_ATE_decimal_float:
14493         code = TYPE_CODE_DECFLOAT;
14494         break;
14495       case DW_ATE_float:
14496         code = TYPE_CODE_FLT;
14497         break;
14498       case DW_ATE_signed:
14499         break;
14500       case DW_ATE_unsigned:
14501         type_flags |= TYPE_FLAG_UNSIGNED;
14502         if (cu->language == language_fortran
14503             && name
14504             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
14505           code = TYPE_CODE_CHAR;
14506         break;
14507       case DW_ATE_signed_char:
14508         if (cu->language == language_ada || cu->language == language_m2
14509             || cu->language == language_pascal
14510             || cu->language == language_fortran)
14511           code = TYPE_CODE_CHAR;
14512         break;
14513       case DW_ATE_unsigned_char:
14514         if (cu->language == language_ada || cu->language == language_m2
14515             || cu->language == language_pascal
14516             || cu->language == language_fortran)
14517           code = TYPE_CODE_CHAR;
14518         type_flags |= TYPE_FLAG_UNSIGNED;
14519         break;
14520       case DW_ATE_UTF:
14521         /* We just treat this as an integer and then recognize the
14522            type by name elsewhere.  */
14523         break;
14524
14525       default:
14526         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
14527                    dwarf_type_encoding_name (encoding));
14528         break;
14529     }
14530
14531   type = init_type (code, size, type_flags, NULL, objfile);
14532   TYPE_NAME (type) = name;
14533   TYPE_TARGET_TYPE (type) = target_type;
14534
14535   if (name && strcmp (name, "char") == 0)
14536     TYPE_NOSIGN (type) = 1;
14537
14538   return set_die_type (die, type, cu);
14539 }
14540
14541 /* Parse dwarf attribute if it's a block, reference or constant and put the
14542    resulting value of the attribute into struct bound_prop.
14543    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
14544
14545 static int
14546 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
14547                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
14548 {
14549   struct dwarf2_property_baton *baton;
14550   struct obstack *obstack = &cu->objfile->objfile_obstack;
14551
14552   if (attr == NULL || prop == NULL)
14553     return 0;
14554
14555   if (attr_form_is_block (attr))
14556     {
14557       baton = obstack_alloc (obstack, sizeof (*baton));
14558       baton->referenced_type = NULL;
14559       baton->locexpr.per_cu = cu->per_cu;
14560       baton->locexpr.size = DW_BLOCK (attr)->size;
14561       baton->locexpr.data = DW_BLOCK (attr)->data;
14562       prop->data.baton = baton;
14563       prop->kind = PROP_LOCEXPR;
14564       gdb_assert (prop->data.baton != NULL);
14565     }
14566   else if (attr_form_is_ref (attr))
14567     {
14568       struct dwarf2_cu *target_cu = cu;
14569       struct die_info *target_die;
14570       struct attribute *target_attr;
14571
14572       target_die = follow_die_ref (die, attr, &target_cu);
14573       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
14574       if (target_attr == NULL)
14575         return 0;
14576
14577       if (attr_form_is_section_offset (target_attr))
14578         {
14579           baton = obstack_alloc (obstack, sizeof (*baton));
14580           baton->referenced_type = die_type (target_die, target_cu);
14581           fill_in_loclist_baton (cu, &baton->loclist, target_attr);
14582           prop->data.baton = baton;
14583           prop->kind = PROP_LOCLIST;
14584           gdb_assert (prop->data.baton != NULL);
14585         }
14586       else if (attr_form_is_block (target_attr))
14587         {
14588           baton = obstack_alloc (obstack, sizeof (*baton));
14589           baton->referenced_type = die_type (target_die, target_cu);
14590           baton->locexpr.per_cu = cu->per_cu;
14591           baton->locexpr.size = DW_BLOCK (target_attr)->size;
14592           baton->locexpr.data = DW_BLOCK (target_attr)->data;
14593           prop->data.baton = baton;
14594           prop->kind = PROP_LOCEXPR;
14595           gdb_assert (prop->data.baton != NULL);
14596         }
14597       else
14598         {
14599           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14600                                                  "dynamic property");
14601           return 0;
14602         }
14603     }
14604   else if (attr_form_is_constant (attr))
14605     {
14606       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
14607       prop->kind = PROP_CONST;
14608     }
14609   else
14610     {
14611       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
14612                                              dwarf2_name (die, cu));
14613       return 0;
14614     }
14615
14616   return 1;
14617 }
14618
14619 /* Read the given DW_AT_subrange DIE.  */
14620
14621 static struct type *
14622 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
14623 {
14624   struct type *base_type, *orig_base_type;
14625   struct type *range_type;
14626   struct attribute *attr;
14627   struct dynamic_prop low, high;
14628   int low_default_is_valid;
14629   int high_bound_is_count = 0;
14630   const char *name;
14631   LONGEST negative_mask;
14632
14633   orig_base_type = die_type (die, cu);
14634   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
14635      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
14636      creating the range type, but we use the result of check_typedef
14637      when examining properties of the type.  */
14638   base_type = check_typedef (orig_base_type);
14639
14640   /* The die_type call above may have already set the type for this DIE.  */
14641   range_type = get_die_type (die, cu);
14642   if (range_type)
14643     return range_type;
14644
14645   low.kind = PROP_CONST;
14646   high.kind = PROP_CONST;
14647   high.data.const_val = 0;
14648
14649   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
14650      omitting DW_AT_lower_bound.  */
14651   switch (cu->language)
14652     {
14653     case language_c:
14654     case language_cplus:
14655       low.data.const_val = 0;
14656       low_default_is_valid = 1;
14657       break;
14658     case language_fortran:
14659       low.data.const_val = 1;
14660       low_default_is_valid = 1;
14661       break;
14662     case language_d:
14663     case language_java:
14664     case language_objc:
14665       low.data.const_val = 0;
14666       low_default_is_valid = (cu->header.version >= 4);
14667       break;
14668     case language_ada:
14669     case language_m2:
14670     case language_pascal:
14671       low.data.const_val = 1;
14672       low_default_is_valid = (cu->header.version >= 4);
14673       break;
14674     default:
14675       low.data.const_val = 0;
14676       low_default_is_valid = 0;
14677       break;
14678     }
14679
14680   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
14681   if (attr)
14682     attr_to_dynamic_prop (attr, die, cu, &low);
14683   else if (!low_default_is_valid)
14684     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
14685                                       "- DIE at 0x%x [in module %s]"),
14686                die->offset.sect_off, objfile_name (cu->objfile));
14687
14688   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
14689   if (!attr_to_dynamic_prop (attr, die, cu, &high))
14690     {
14691       attr = dwarf2_attr (die, DW_AT_count, cu);
14692       if (attr_to_dynamic_prop (attr, die, cu, &high))
14693         {
14694           /* If bounds are constant do the final calculation here.  */
14695           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
14696             high.data.const_val = low.data.const_val + high.data.const_val - 1;
14697           else
14698             high_bound_is_count = 1;
14699         }
14700     }
14701
14702   /* Dwarf-2 specifications explicitly allows to create subrange types
14703      without specifying a base type.
14704      In that case, the base type must be set to the type of
14705      the lower bound, upper bound or count, in that order, if any of these
14706      three attributes references an object that has a type.
14707      If no base type is found, the Dwarf-2 specifications say that
14708      a signed integer type of size equal to the size of an address should
14709      be used.
14710      For the following C code: `extern char gdb_int [];'
14711      GCC produces an empty range DIE.
14712      FIXME: muller/2010-05-28: Possible references to object for low bound,
14713      high bound or count are not yet handled by this code.  */
14714   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
14715     {
14716       struct objfile *objfile = cu->objfile;
14717       struct gdbarch *gdbarch = get_objfile_arch (objfile);
14718       int addr_size = gdbarch_addr_bit (gdbarch) /8;
14719       struct type *int_type = objfile_type (objfile)->builtin_int;
14720
14721       /* Test "int", "long int", and "long long int" objfile types,
14722          and select the first one having a size above or equal to the
14723          architecture address size.  */
14724       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14725         base_type = int_type;
14726       else
14727         {
14728           int_type = objfile_type (objfile)->builtin_long;
14729           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14730             base_type = int_type;
14731           else
14732             {
14733               int_type = objfile_type (objfile)->builtin_long_long;
14734               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14735                 base_type = int_type;
14736             }
14737         }
14738     }
14739
14740   /* Normally, the DWARF producers are expected to use a signed
14741      constant form (Eg. DW_FORM_sdata) to express negative bounds.
14742      But this is unfortunately not always the case, as witnessed
14743      with GCC, for instance, where the ambiguous DW_FORM_dataN form
14744      is used instead.  To work around that ambiguity, we treat
14745      the bounds as signed, and thus sign-extend their values, when
14746      the base type is signed.  */
14747   negative_mask =
14748     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
14749   if (low.kind == PROP_CONST
14750       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
14751     low.data.const_val |= negative_mask;
14752   if (high.kind == PROP_CONST
14753       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
14754     high.data.const_val |= negative_mask;
14755
14756   range_type = create_range_type (NULL, orig_base_type, &low, &high);
14757
14758   if (high_bound_is_count)
14759     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
14760
14761   /* Ada expects an empty array on no boundary attributes.  */
14762   if (attr == NULL && cu->language != language_ada)
14763     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
14764
14765   name = dwarf2_name (die, cu);
14766   if (name)
14767     TYPE_NAME (range_type) = name;
14768
14769   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14770   if (attr)
14771     TYPE_LENGTH (range_type) = DW_UNSND (attr);
14772
14773   set_die_type (die, range_type, cu);
14774
14775   /* set_die_type should be already done.  */
14776   set_descriptive_type (range_type, die, cu);
14777
14778   return range_type;
14779 }
14780
14781 static struct type *
14782 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
14783 {
14784   struct type *type;
14785
14786   /* For now, we only support the C meaning of an unspecified type: void.  */
14787
14788   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
14789   TYPE_NAME (type) = dwarf2_name (die, cu);
14790
14791   return set_die_type (die, type, cu);
14792 }
14793
14794 /* Read a single die and all its descendents.  Set the die's sibling
14795    field to NULL; set other fields in the die correctly, and set all
14796    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
14797    location of the info_ptr after reading all of those dies.  PARENT
14798    is the parent of the die in question.  */
14799
14800 static struct die_info *
14801 read_die_and_children (const struct die_reader_specs *reader,
14802                        const gdb_byte *info_ptr,
14803                        const gdb_byte **new_info_ptr,
14804                        struct die_info *parent)
14805 {
14806   struct die_info *die;
14807   const gdb_byte *cur_ptr;
14808   int has_children;
14809
14810   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
14811   if (die == NULL)
14812     {
14813       *new_info_ptr = cur_ptr;
14814       return NULL;
14815     }
14816   store_in_ref_table (die, reader->cu);
14817
14818   if (has_children)
14819     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
14820   else
14821     {
14822       die->child = NULL;
14823       *new_info_ptr = cur_ptr;
14824     }
14825
14826   die->sibling = NULL;
14827   die->parent = parent;
14828   return die;
14829 }
14830
14831 /* Read a die, all of its descendents, and all of its siblings; set
14832    all of the fields of all of the dies correctly.  Arguments are as
14833    in read_die_and_children.  */
14834
14835 static struct die_info *
14836 read_die_and_siblings_1 (const struct die_reader_specs *reader,
14837                          const gdb_byte *info_ptr,
14838                          const gdb_byte **new_info_ptr,
14839                          struct die_info *parent)
14840 {
14841   struct die_info *first_die, *last_sibling;
14842   const gdb_byte *cur_ptr;
14843
14844   cur_ptr = info_ptr;
14845   first_die = last_sibling = NULL;
14846
14847   while (1)
14848     {
14849       struct die_info *die
14850         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
14851
14852       if (die == NULL)
14853         {
14854           *new_info_ptr = cur_ptr;
14855           return first_die;
14856         }
14857
14858       if (!first_die)
14859         first_die = die;
14860       else
14861         last_sibling->sibling = die;
14862
14863       last_sibling = die;
14864     }
14865 }
14866
14867 /* Read a die, all of its descendents, and all of its siblings; set
14868    all of the fields of all of the dies correctly.  Arguments are as
14869    in read_die_and_children.
14870    This the main entry point for reading a DIE and all its children.  */
14871
14872 static struct die_info *
14873 read_die_and_siblings (const struct die_reader_specs *reader,
14874                        const gdb_byte *info_ptr,
14875                        const gdb_byte **new_info_ptr,
14876                        struct die_info *parent)
14877 {
14878   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
14879                                                   new_info_ptr, parent);
14880
14881   if (dwarf2_die_debug)
14882     {
14883       fprintf_unfiltered (gdb_stdlog,
14884                           "Read die from %s@0x%x of %s:\n",
14885                           get_section_name (reader->die_section),
14886                           (unsigned) (info_ptr - reader->die_section->buffer),
14887                           bfd_get_filename (reader->abfd));
14888       dump_die (die, dwarf2_die_debug);
14889     }
14890
14891   return die;
14892 }
14893
14894 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
14895    attributes.
14896    The caller is responsible for filling in the extra attributes
14897    and updating (*DIEP)->num_attrs.
14898    Set DIEP to point to a newly allocated die with its information,
14899    except for its child, sibling, and parent fields.
14900    Set HAS_CHILDREN to tell whether the die has children or not.  */
14901
14902 static const gdb_byte *
14903 read_full_die_1 (const struct die_reader_specs *reader,
14904                  struct die_info **diep, const gdb_byte *info_ptr,
14905                  int *has_children, int num_extra_attrs)
14906 {
14907   unsigned int abbrev_number, bytes_read, i;
14908   sect_offset offset;
14909   struct abbrev_info *abbrev;
14910   struct die_info *die;
14911   struct dwarf2_cu *cu = reader->cu;
14912   bfd *abfd = reader->abfd;
14913
14914   offset.sect_off = info_ptr - reader->buffer;
14915   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14916   info_ptr += bytes_read;
14917   if (!abbrev_number)
14918     {
14919       *diep = NULL;
14920       *has_children = 0;
14921       return info_ptr;
14922     }
14923
14924   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
14925   if (!abbrev)
14926     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
14927            abbrev_number,
14928            bfd_get_filename (abfd));
14929
14930   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
14931   die->offset = offset;
14932   die->tag = abbrev->tag;
14933   die->abbrev = abbrev_number;
14934
14935   /* Make the result usable.
14936      The caller needs to update num_attrs after adding the extra
14937      attributes.  */
14938   die->num_attrs = abbrev->num_attrs;
14939
14940   for (i = 0; i < abbrev->num_attrs; ++i)
14941     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
14942                                info_ptr);
14943
14944   *diep = die;
14945   *has_children = abbrev->has_children;
14946   return info_ptr;
14947 }
14948
14949 /* Read a die and all its attributes.
14950    Set DIEP to point to a newly allocated die with its information,
14951    except for its child, sibling, and parent fields.
14952    Set HAS_CHILDREN to tell whether the die has children or not.  */
14953
14954 static const gdb_byte *
14955 read_full_die (const struct die_reader_specs *reader,
14956                struct die_info **diep, const gdb_byte *info_ptr,
14957                int *has_children)
14958 {
14959   const gdb_byte *result;
14960
14961   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
14962
14963   if (dwarf2_die_debug)
14964     {
14965       fprintf_unfiltered (gdb_stdlog,
14966                           "Read die from %s@0x%x of %s:\n",
14967                           get_section_name (reader->die_section),
14968                           (unsigned) (info_ptr - reader->die_section->buffer),
14969                           bfd_get_filename (reader->abfd));
14970       dump_die (*diep, dwarf2_die_debug);
14971     }
14972
14973   return result;
14974 }
14975 \f
14976 /* Abbreviation tables.
14977
14978    In DWARF version 2, the description of the debugging information is
14979    stored in a separate .debug_abbrev section.  Before we read any
14980    dies from a section we read in all abbreviations and install them
14981    in a hash table.  */
14982
14983 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
14984
14985 static struct abbrev_info *
14986 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
14987 {
14988   struct abbrev_info *abbrev;
14989
14990   abbrev = (struct abbrev_info *)
14991     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
14992   memset (abbrev, 0, sizeof (struct abbrev_info));
14993   return abbrev;
14994 }
14995
14996 /* Add an abbreviation to the table.  */
14997
14998 static void
14999 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15000                          unsigned int abbrev_number,
15001                          struct abbrev_info *abbrev)
15002 {
15003   unsigned int hash_number;
15004
15005   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15006   abbrev->next = abbrev_table->abbrevs[hash_number];
15007   abbrev_table->abbrevs[hash_number] = abbrev;
15008 }
15009
15010 /* Look up an abbrev in the table.
15011    Returns NULL if the abbrev is not found.  */
15012
15013 static struct abbrev_info *
15014 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15015                             unsigned int abbrev_number)
15016 {
15017   unsigned int hash_number;
15018   struct abbrev_info *abbrev;
15019
15020   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15021   abbrev = abbrev_table->abbrevs[hash_number];
15022
15023   while (abbrev)
15024     {
15025       if (abbrev->number == abbrev_number)
15026         return abbrev;
15027       abbrev = abbrev->next;
15028     }
15029   return NULL;
15030 }
15031
15032 /* Read in an abbrev table.  */
15033
15034 static struct abbrev_table *
15035 abbrev_table_read_table (struct dwarf2_section_info *section,
15036                          sect_offset offset)
15037 {
15038   struct objfile *objfile = dwarf2_per_objfile->objfile;
15039   bfd *abfd = get_section_bfd_owner (section);
15040   struct abbrev_table *abbrev_table;
15041   const gdb_byte *abbrev_ptr;
15042   struct abbrev_info *cur_abbrev;
15043   unsigned int abbrev_number, bytes_read, abbrev_name;
15044   unsigned int abbrev_form;
15045   struct attr_abbrev *cur_attrs;
15046   unsigned int allocated_attrs;
15047
15048   abbrev_table = XNEW (struct abbrev_table);
15049   abbrev_table->offset = offset;
15050   obstack_init (&abbrev_table->abbrev_obstack);
15051   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
15052                                          (ABBREV_HASH_SIZE
15053                                           * sizeof (struct abbrev_info *)));
15054   memset (abbrev_table->abbrevs, 0,
15055           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15056
15057   dwarf2_read_section (objfile, section);
15058   abbrev_ptr = section->buffer + offset.sect_off;
15059   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15060   abbrev_ptr += bytes_read;
15061
15062   allocated_attrs = ATTR_ALLOC_CHUNK;
15063   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
15064
15065   /* Loop until we reach an abbrev number of 0.  */
15066   while (abbrev_number)
15067     {
15068       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15069
15070       /* read in abbrev header */
15071       cur_abbrev->number = abbrev_number;
15072       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15073       abbrev_ptr += bytes_read;
15074       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15075       abbrev_ptr += 1;
15076
15077       /* now read in declarations */
15078       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15079       abbrev_ptr += bytes_read;
15080       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15081       abbrev_ptr += bytes_read;
15082       while (abbrev_name)
15083         {
15084           if (cur_abbrev->num_attrs == allocated_attrs)
15085             {
15086               allocated_attrs += ATTR_ALLOC_CHUNK;
15087               cur_attrs
15088                 = xrealloc (cur_attrs, (allocated_attrs
15089                                         * sizeof (struct attr_abbrev)));
15090             }
15091
15092           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
15093           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
15094           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15095           abbrev_ptr += bytes_read;
15096           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15097           abbrev_ptr += bytes_read;
15098         }
15099
15100       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
15101                                          (cur_abbrev->num_attrs
15102                                           * sizeof (struct attr_abbrev)));
15103       memcpy (cur_abbrev->attrs, cur_attrs,
15104               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15105
15106       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15107
15108       /* Get next abbreviation.
15109          Under Irix6 the abbreviations for a compilation unit are not
15110          always properly terminated with an abbrev number of 0.
15111          Exit loop if we encounter an abbreviation which we have
15112          already read (which means we are about to read the abbreviations
15113          for the next compile unit) or if the end of the abbreviation
15114          table is reached.  */
15115       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15116         break;
15117       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15118       abbrev_ptr += bytes_read;
15119       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15120         break;
15121     }
15122
15123   xfree (cur_attrs);
15124   return abbrev_table;
15125 }
15126
15127 /* Free the resources held by ABBREV_TABLE.  */
15128
15129 static void
15130 abbrev_table_free (struct abbrev_table *abbrev_table)
15131 {
15132   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15133   xfree (abbrev_table);
15134 }
15135
15136 /* Same as abbrev_table_free but as a cleanup.
15137    We pass in a pointer to the pointer to the table so that we can
15138    set the pointer to NULL when we're done.  It also simplifies
15139    build_type_psymtabs_1.  */
15140
15141 static void
15142 abbrev_table_free_cleanup (void *table_ptr)
15143 {
15144   struct abbrev_table **abbrev_table_ptr = table_ptr;
15145
15146   if (*abbrev_table_ptr != NULL)
15147     abbrev_table_free (*abbrev_table_ptr);
15148   *abbrev_table_ptr = NULL;
15149 }
15150
15151 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15152
15153 static void
15154 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15155                      struct dwarf2_section_info *abbrev_section)
15156 {
15157   cu->abbrev_table =
15158     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
15159 }
15160
15161 /* Release the memory used by the abbrev table for a compilation unit.  */
15162
15163 static void
15164 dwarf2_free_abbrev_table (void *ptr_to_cu)
15165 {
15166   struct dwarf2_cu *cu = ptr_to_cu;
15167
15168   if (cu->abbrev_table != NULL)
15169     abbrev_table_free (cu->abbrev_table);
15170   /* Set this to NULL so that we SEGV if we try to read it later,
15171      and also because free_comp_unit verifies this is NULL.  */
15172   cu->abbrev_table = NULL;
15173 }
15174 \f
15175 /* Returns nonzero if TAG represents a type that we might generate a partial
15176    symbol for.  */
15177
15178 static int
15179 is_type_tag_for_partial (int tag)
15180 {
15181   switch (tag)
15182     {
15183 #if 0
15184     /* Some types that would be reasonable to generate partial symbols for,
15185        that we don't at present.  */
15186     case DW_TAG_array_type:
15187     case DW_TAG_file_type:
15188     case DW_TAG_ptr_to_member_type:
15189     case DW_TAG_set_type:
15190     case DW_TAG_string_type:
15191     case DW_TAG_subroutine_type:
15192 #endif
15193     case DW_TAG_base_type:
15194     case DW_TAG_class_type:
15195     case DW_TAG_interface_type:
15196     case DW_TAG_enumeration_type:
15197     case DW_TAG_structure_type:
15198     case DW_TAG_subrange_type:
15199     case DW_TAG_typedef:
15200     case DW_TAG_union_type:
15201       return 1;
15202     default:
15203       return 0;
15204     }
15205 }
15206
15207 /* Load all DIEs that are interesting for partial symbols into memory.  */
15208
15209 static struct partial_die_info *
15210 load_partial_dies (const struct die_reader_specs *reader,
15211                    const gdb_byte *info_ptr, int building_psymtab)
15212 {
15213   struct dwarf2_cu *cu = reader->cu;
15214   struct objfile *objfile = cu->objfile;
15215   struct partial_die_info *part_die;
15216   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15217   struct abbrev_info *abbrev;
15218   unsigned int bytes_read;
15219   unsigned int load_all = 0;
15220   int nesting_level = 1;
15221
15222   parent_die = NULL;
15223   last_die = NULL;
15224
15225   gdb_assert (cu->per_cu != NULL);
15226   if (cu->per_cu->load_all_dies)
15227     load_all = 1;
15228
15229   cu->partial_dies
15230     = htab_create_alloc_ex (cu->header.length / 12,
15231                             partial_die_hash,
15232                             partial_die_eq,
15233                             NULL,
15234                             &cu->comp_unit_obstack,
15235                             hashtab_obstack_allocate,
15236                             dummy_obstack_deallocate);
15237
15238   part_die = obstack_alloc (&cu->comp_unit_obstack,
15239                             sizeof (struct partial_die_info));
15240
15241   while (1)
15242     {
15243       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
15244
15245       /* A NULL abbrev means the end of a series of children.  */
15246       if (abbrev == NULL)
15247         {
15248           if (--nesting_level == 0)
15249             {
15250               /* PART_DIE was probably the last thing allocated on the
15251                  comp_unit_obstack, so we could call obstack_free
15252                  here.  We don't do that because the waste is small,
15253                  and will be cleaned up when we're done with this
15254                  compilation unit.  This way, we're also more robust
15255                  against other users of the comp_unit_obstack.  */
15256               return first_die;
15257             }
15258           info_ptr += bytes_read;
15259           last_die = parent_die;
15260           parent_die = parent_die->die_parent;
15261           continue;
15262         }
15263
15264       /* Check for template arguments.  We never save these; if
15265          they're seen, we just mark the parent, and go on our way.  */
15266       if (parent_die != NULL
15267           && cu->language == language_cplus
15268           && (abbrev->tag == DW_TAG_template_type_param
15269               || abbrev->tag == DW_TAG_template_value_param))
15270         {
15271           parent_die->has_template_arguments = 1;
15272
15273           if (!load_all)
15274             {
15275               /* We don't need a partial DIE for the template argument.  */
15276               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15277               continue;
15278             }
15279         }
15280
15281       /* We only recurse into c++ subprograms looking for template arguments.
15282          Skip their other children.  */
15283       if (!load_all
15284           && cu->language == language_cplus
15285           && parent_die != NULL
15286           && parent_die->tag == DW_TAG_subprogram)
15287         {
15288           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15289           continue;
15290         }
15291
15292       /* Check whether this DIE is interesting enough to save.  Normally
15293          we would not be interested in members here, but there may be
15294          later variables referencing them via DW_AT_specification (for
15295          static members).  */
15296       if (!load_all
15297           && !is_type_tag_for_partial (abbrev->tag)
15298           && abbrev->tag != DW_TAG_constant
15299           && abbrev->tag != DW_TAG_enumerator
15300           && abbrev->tag != DW_TAG_subprogram
15301           && abbrev->tag != DW_TAG_lexical_block
15302           && abbrev->tag != DW_TAG_variable
15303           && abbrev->tag != DW_TAG_namespace
15304           && abbrev->tag != DW_TAG_module
15305           && abbrev->tag != DW_TAG_member
15306           && abbrev->tag != DW_TAG_imported_unit
15307           && abbrev->tag != DW_TAG_imported_declaration)
15308         {
15309           /* Otherwise we skip to the next sibling, if any.  */
15310           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15311           continue;
15312         }
15313
15314       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
15315                                    info_ptr);
15316
15317       /* This two-pass algorithm for processing partial symbols has a
15318          high cost in cache pressure.  Thus, handle some simple cases
15319          here which cover the majority of C partial symbols.  DIEs
15320          which neither have specification tags in them, nor could have
15321          specification tags elsewhere pointing at them, can simply be
15322          processed and discarded.
15323
15324          This segment is also optional; scan_partial_symbols and
15325          add_partial_symbol will handle these DIEs if we chain
15326          them in normally.  When compilers which do not emit large
15327          quantities of duplicate debug information are more common,
15328          this code can probably be removed.  */
15329
15330       /* Any complete simple types at the top level (pretty much all
15331          of them, for a language without namespaces), can be processed
15332          directly.  */
15333       if (parent_die == NULL
15334           && part_die->has_specification == 0
15335           && part_die->is_declaration == 0
15336           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
15337               || part_die->tag == DW_TAG_base_type
15338               || part_die->tag == DW_TAG_subrange_type))
15339         {
15340           if (building_psymtab && part_die->name != NULL)
15341             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
15342                                  VAR_DOMAIN, LOC_TYPEDEF,
15343                                  &objfile->static_psymbols,
15344                                  0, (CORE_ADDR) 0, cu->language, objfile);
15345           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
15346           continue;
15347         }
15348
15349       /* The exception for DW_TAG_typedef with has_children above is
15350          a workaround of GCC PR debug/47510.  In the case of this complaint
15351          type_name_no_tag_or_error will error on such types later.
15352
15353          GDB skipped children of DW_TAG_typedef by the shortcut above and then
15354          it could not find the child DIEs referenced later, this is checked
15355          above.  In correct DWARF DW_TAG_typedef should have no children.  */
15356
15357       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
15358         complaint (&symfile_complaints,
15359                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
15360                      "- DIE at 0x%x [in module %s]"),
15361                    part_die->offset.sect_off, objfile_name (objfile));
15362
15363       /* If we're at the second level, and we're an enumerator, and
15364          our parent has no specification (meaning possibly lives in a
15365          namespace elsewhere), then we can add the partial symbol now
15366          instead of queueing it.  */
15367       if (part_die->tag == DW_TAG_enumerator
15368           && parent_die != NULL
15369           && parent_die->die_parent == NULL
15370           && parent_die->tag == DW_TAG_enumeration_type
15371           && parent_die->has_specification == 0)
15372         {
15373           if (part_die->name == NULL)
15374             complaint (&symfile_complaints,
15375                        _("malformed enumerator DIE ignored"));
15376           else if (building_psymtab)
15377             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
15378                                  VAR_DOMAIN, LOC_CONST,
15379                                  (cu->language == language_cplus
15380                                   || cu->language == language_java)
15381                                  ? &objfile->global_psymbols
15382                                  : &objfile->static_psymbols,
15383                                  0, (CORE_ADDR) 0, cu->language, objfile);
15384
15385           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
15386           continue;
15387         }
15388
15389       /* We'll save this DIE so link it in.  */
15390       part_die->die_parent = parent_die;
15391       part_die->die_sibling = NULL;
15392       part_die->die_child = NULL;
15393
15394       if (last_die && last_die == parent_die)
15395         last_die->die_child = part_die;
15396       else if (last_die)
15397         last_die->die_sibling = part_die;
15398
15399       last_die = part_die;
15400
15401       if (first_die == NULL)
15402         first_die = part_die;
15403
15404       /* Maybe add the DIE to the hash table.  Not all DIEs that we
15405          find interesting need to be in the hash table, because we
15406          also have the parent/sibling/child chains; only those that we
15407          might refer to by offset later during partial symbol reading.
15408
15409          For now this means things that might have be the target of a
15410          DW_AT_specification, DW_AT_abstract_origin, or
15411          DW_AT_extension.  DW_AT_extension will refer only to
15412          namespaces; DW_AT_abstract_origin refers to functions (and
15413          many things under the function DIE, but we do not recurse
15414          into function DIEs during partial symbol reading) and
15415          possibly variables as well; DW_AT_specification refers to
15416          declarations.  Declarations ought to have the DW_AT_declaration
15417          flag.  It happens that GCC forgets to put it in sometimes, but
15418          only for functions, not for types.
15419
15420          Adding more things than necessary to the hash table is harmless
15421          except for the performance cost.  Adding too few will result in
15422          wasted time in find_partial_die, when we reread the compilation
15423          unit with load_all_dies set.  */
15424
15425       if (load_all
15426           || abbrev->tag == DW_TAG_constant
15427           || abbrev->tag == DW_TAG_subprogram
15428           || abbrev->tag == DW_TAG_variable
15429           || abbrev->tag == DW_TAG_namespace
15430           || part_die->is_declaration)
15431         {
15432           void **slot;
15433
15434           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
15435                                            part_die->offset.sect_off, INSERT);
15436           *slot = part_die;
15437         }
15438
15439       part_die = obstack_alloc (&cu->comp_unit_obstack,
15440                                 sizeof (struct partial_die_info));
15441
15442       /* For some DIEs we want to follow their children (if any).  For C
15443          we have no reason to follow the children of structures; for other
15444          languages we have to, so that we can get at method physnames
15445          to infer fully qualified class names, for DW_AT_specification,
15446          and for C++ template arguments.  For C++, we also look one level
15447          inside functions to find template arguments (if the name of the
15448          function does not already contain the template arguments).
15449
15450          For Ada, we need to scan the children of subprograms and lexical
15451          blocks as well because Ada allows the definition of nested
15452          entities that could be interesting for the debugger, such as
15453          nested subprograms for instance.  */
15454       if (last_die->has_children
15455           && (load_all
15456               || last_die->tag == DW_TAG_namespace
15457               || last_die->tag == DW_TAG_module
15458               || last_die->tag == DW_TAG_enumeration_type
15459               || (cu->language == language_cplus
15460                   && last_die->tag == DW_TAG_subprogram
15461                   && (last_die->name == NULL
15462                       || strchr (last_die->name, '<') == NULL))
15463               || (cu->language != language_c
15464                   && (last_die->tag == DW_TAG_class_type
15465                       || last_die->tag == DW_TAG_interface_type
15466                       || last_die->tag == DW_TAG_structure_type
15467                       || last_die->tag == DW_TAG_union_type))
15468               || (cu->language == language_ada
15469                   && (last_die->tag == DW_TAG_subprogram
15470                       || last_die->tag == DW_TAG_lexical_block))))
15471         {
15472           nesting_level++;
15473           parent_die = last_die;
15474           continue;
15475         }
15476
15477       /* Otherwise we skip to the next sibling, if any.  */
15478       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
15479
15480       /* Back to the top, do it again.  */
15481     }
15482 }
15483
15484 /* Read a minimal amount of information into the minimal die structure.  */
15485
15486 static const gdb_byte *
15487 read_partial_die (const struct die_reader_specs *reader,
15488                   struct partial_die_info *part_die,
15489                   struct abbrev_info *abbrev, unsigned int abbrev_len,
15490                   const gdb_byte *info_ptr)
15491 {
15492   struct dwarf2_cu *cu = reader->cu;
15493   struct objfile *objfile = cu->objfile;
15494   const gdb_byte *buffer = reader->buffer;
15495   unsigned int i;
15496   struct attribute attr;
15497   int has_low_pc_attr = 0;
15498   int has_high_pc_attr = 0;
15499   int high_pc_relative = 0;
15500
15501   memset (part_die, 0, sizeof (struct partial_die_info));
15502
15503   part_die->offset.sect_off = info_ptr - buffer;
15504
15505   info_ptr += abbrev_len;
15506
15507   if (abbrev == NULL)
15508     return info_ptr;
15509
15510   part_die->tag = abbrev->tag;
15511   part_die->has_children = abbrev->has_children;
15512
15513   for (i = 0; i < abbrev->num_attrs; ++i)
15514     {
15515       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
15516
15517       /* Store the data if it is of an attribute we want to keep in a
15518          partial symbol table.  */
15519       switch (attr.name)
15520         {
15521         case DW_AT_name:
15522           switch (part_die->tag)
15523             {
15524             case DW_TAG_compile_unit:
15525             case DW_TAG_partial_unit:
15526             case DW_TAG_type_unit:
15527               /* Compilation units have a DW_AT_name that is a filename, not
15528                  a source language identifier.  */
15529             case DW_TAG_enumeration_type:
15530             case DW_TAG_enumerator:
15531               /* These tags always have simple identifiers already; no need
15532                  to canonicalize them.  */
15533               part_die->name = DW_STRING (&attr);
15534               break;
15535             default:
15536               part_die->name
15537                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
15538                                             &objfile->per_bfd->storage_obstack);
15539               break;
15540             }
15541           break;
15542         case DW_AT_linkage_name:
15543         case DW_AT_MIPS_linkage_name:
15544           /* Note that both forms of linkage name might appear.  We
15545              assume they will be the same, and we only store the last
15546              one we see.  */
15547           if (cu->language == language_ada)
15548             part_die->name = DW_STRING (&attr);
15549           part_die->linkage_name = DW_STRING (&attr);
15550           break;
15551         case DW_AT_low_pc:
15552           has_low_pc_attr = 1;
15553           part_die->lowpc = attr_value_as_address (&attr);
15554           break;
15555         case DW_AT_high_pc:
15556           has_high_pc_attr = 1;
15557           part_die->highpc = attr_value_as_address (&attr);
15558           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
15559                 high_pc_relative = 1;
15560           break;
15561         case DW_AT_location:
15562           /* Support the .debug_loc offsets.  */
15563           if (attr_form_is_block (&attr))
15564             {
15565                part_die->d.locdesc = DW_BLOCK (&attr);
15566             }
15567           else if (attr_form_is_section_offset (&attr))
15568             {
15569               dwarf2_complex_location_expr_complaint ();
15570             }
15571           else
15572             {
15573               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15574                                                      "partial symbol information");
15575             }
15576           break;
15577         case DW_AT_external:
15578           part_die->is_external = DW_UNSND (&attr);
15579           break;
15580         case DW_AT_declaration:
15581           part_die->is_declaration = DW_UNSND (&attr);
15582           break;
15583         case DW_AT_type:
15584           part_die->has_type = 1;
15585           break;
15586         case DW_AT_abstract_origin:
15587         case DW_AT_specification:
15588         case DW_AT_extension:
15589           part_die->has_specification = 1;
15590           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
15591           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15592                                    || cu->per_cu->is_dwz);
15593           break;
15594         case DW_AT_sibling:
15595           /* Ignore absolute siblings, they might point outside of
15596              the current compile unit.  */
15597           if (attr.form == DW_FORM_ref_addr)
15598             complaint (&symfile_complaints,
15599                        _("ignoring absolute DW_AT_sibling"));
15600           else
15601             {
15602               unsigned int off = dwarf2_get_ref_die_offset (&attr).sect_off;
15603               const gdb_byte *sibling_ptr = buffer + off;
15604
15605               if (sibling_ptr < info_ptr)
15606                 complaint (&symfile_complaints,
15607                            _("DW_AT_sibling points backwards"));
15608               else if (sibling_ptr > reader->buffer_end)
15609                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
15610               else
15611                 part_die->sibling = sibling_ptr;
15612             }
15613           break;
15614         case DW_AT_byte_size:
15615           part_die->has_byte_size = 1;
15616           break;
15617         case DW_AT_calling_convention:
15618           /* DWARF doesn't provide a way to identify a program's source-level
15619              entry point.  DW_AT_calling_convention attributes are only meant
15620              to describe functions' calling conventions.
15621
15622              However, because it's a necessary piece of information in
15623              Fortran, and because DW_CC_program is the only piece of debugging
15624              information whose definition refers to a 'main program' at all,
15625              several compilers have begun marking Fortran main programs with
15626              DW_CC_program --- even when those functions use the standard
15627              calling conventions.
15628
15629              So until DWARF specifies a way to provide this information and
15630              compilers pick up the new representation, we'll support this
15631              practice.  */
15632           if (DW_UNSND (&attr) == DW_CC_program
15633               && cu->language == language_fortran)
15634             set_objfile_main_name (objfile, part_die->name, language_fortran);
15635           break;
15636         case DW_AT_inline:
15637           if (DW_UNSND (&attr) == DW_INL_inlined
15638               || DW_UNSND (&attr) == DW_INL_declared_inlined)
15639             part_die->may_be_inlined = 1;
15640           break;
15641
15642         case DW_AT_import:
15643           if (part_die->tag == DW_TAG_imported_unit)
15644             {
15645               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
15646               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15647                                   || cu->per_cu->is_dwz);
15648             }
15649           break;
15650
15651         default:
15652           break;
15653         }
15654     }
15655
15656   if (high_pc_relative)
15657     part_die->highpc += part_die->lowpc;
15658
15659   if (has_low_pc_attr && has_high_pc_attr)
15660     {
15661       /* When using the GNU linker, .gnu.linkonce. sections are used to
15662          eliminate duplicate copies of functions and vtables and such.
15663          The linker will arbitrarily choose one and discard the others.
15664          The AT_*_pc values for such functions refer to local labels in
15665          these sections.  If the section from that file was discarded, the
15666          labels are not in the output, so the relocs get a value of 0.
15667          If this is a discarded function, mark the pc bounds as invalid,
15668          so that GDB will ignore it.  */
15669       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
15670         {
15671           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15672
15673           complaint (&symfile_complaints,
15674                      _("DW_AT_low_pc %s is zero "
15675                        "for DIE at 0x%x [in module %s]"),
15676                      paddress (gdbarch, part_die->lowpc),
15677                      part_die->offset.sect_off, objfile_name (objfile));
15678         }
15679       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
15680       else if (part_die->lowpc >= part_die->highpc)
15681         {
15682           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15683
15684           complaint (&symfile_complaints,
15685                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
15686                        "for DIE at 0x%x [in module %s]"),
15687                      paddress (gdbarch, part_die->lowpc),
15688                      paddress (gdbarch, part_die->highpc),
15689                      part_die->offset.sect_off, objfile_name (objfile));
15690         }
15691       else
15692         part_die->has_pc_info = 1;
15693     }
15694
15695   return info_ptr;
15696 }
15697
15698 /* Find a cached partial DIE at OFFSET in CU.  */
15699
15700 static struct partial_die_info *
15701 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
15702 {
15703   struct partial_die_info *lookup_die = NULL;
15704   struct partial_die_info part_die;
15705
15706   part_die.offset = offset;
15707   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
15708                                     offset.sect_off);
15709
15710   return lookup_die;
15711 }
15712
15713 /* Find a partial DIE at OFFSET, which may or may not be in CU,
15714    except in the case of .debug_types DIEs which do not reference
15715    outside their CU (they do however referencing other types via
15716    DW_FORM_ref_sig8).  */
15717
15718 static struct partial_die_info *
15719 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
15720 {
15721   struct objfile *objfile = cu->objfile;
15722   struct dwarf2_per_cu_data *per_cu = NULL;
15723   struct partial_die_info *pd = NULL;
15724
15725   if (offset_in_dwz == cu->per_cu->is_dwz
15726       && offset_in_cu_p (&cu->header, offset))
15727     {
15728       pd = find_partial_die_in_comp_unit (offset, cu);
15729       if (pd != NULL)
15730         return pd;
15731       /* We missed recording what we needed.
15732          Load all dies and try again.  */
15733       per_cu = cu->per_cu;
15734     }
15735   else
15736     {
15737       /* TUs don't reference other CUs/TUs (except via type signatures).  */
15738       if (cu->per_cu->is_debug_types)
15739         {
15740           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
15741                    " external reference to offset 0x%lx [in module %s].\n"),
15742                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
15743                  bfd_get_filename (objfile->obfd));
15744         }
15745       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
15746                                                  objfile);
15747
15748       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
15749         load_partial_comp_unit (per_cu);
15750
15751       per_cu->cu->last_used = 0;
15752       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15753     }
15754
15755   /* If we didn't find it, and not all dies have been loaded,
15756      load them all and try again.  */
15757
15758   if (pd == NULL && per_cu->load_all_dies == 0)
15759     {
15760       per_cu->load_all_dies = 1;
15761
15762       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
15763          THIS_CU->cu may already be in use.  So we can't just free it and
15764          replace its DIEs with the ones we read in.  Instead, we leave those
15765          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
15766          and clobber THIS_CU->cu->partial_dies with the hash table for the new
15767          set.  */
15768       load_partial_comp_unit (per_cu);
15769
15770       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15771     }
15772
15773   if (pd == NULL)
15774     internal_error (__FILE__, __LINE__,
15775                     _("could not find partial DIE 0x%x "
15776                       "in cache [from module %s]\n"),
15777                     offset.sect_off, bfd_get_filename (objfile->obfd));
15778   return pd;
15779 }
15780
15781 /* See if we can figure out if the class lives in a namespace.  We do
15782    this by looking for a member function; its demangled name will
15783    contain namespace info, if there is any.  */
15784
15785 static void
15786 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
15787                                   struct dwarf2_cu *cu)
15788 {
15789   /* NOTE: carlton/2003-10-07: Getting the info this way changes
15790      what template types look like, because the demangler
15791      frequently doesn't give the same name as the debug info.  We
15792      could fix this by only using the demangled name to get the
15793      prefix (but see comment in read_structure_type).  */
15794
15795   struct partial_die_info *real_pdi;
15796   struct partial_die_info *child_pdi;
15797
15798   /* If this DIE (this DIE's specification, if any) has a parent, then
15799      we should not do this.  We'll prepend the parent's fully qualified
15800      name when we create the partial symbol.  */
15801
15802   real_pdi = struct_pdi;
15803   while (real_pdi->has_specification)
15804     real_pdi = find_partial_die (real_pdi->spec_offset,
15805                                  real_pdi->spec_is_dwz, cu);
15806
15807   if (real_pdi->die_parent != NULL)
15808     return;
15809
15810   for (child_pdi = struct_pdi->die_child;
15811        child_pdi != NULL;
15812        child_pdi = child_pdi->die_sibling)
15813     {
15814       if (child_pdi->tag == DW_TAG_subprogram
15815           && child_pdi->linkage_name != NULL)
15816         {
15817           char *actual_class_name
15818             = language_class_name_from_physname (cu->language_defn,
15819                                                  child_pdi->linkage_name);
15820           if (actual_class_name != NULL)
15821             {
15822               struct_pdi->name
15823                 = obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
15824                                  actual_class_name,
15825                                  strlen (actual_class_name));
15826               xfree (actual_class_name);
15827             }
15828           break;
15829         }
15830     }
15831 }
15832
15833 /* Adjust PART_DIE before generating a symbol for it.  This function
15834    may set the is_external flag or change the DIE's name.  */
15835
15836 static void
15837 fixup_partial_die (struct partial_die_info *part_die,
15838                    struct dwarf2_cu *cu)
15839 {
15840   /* Once we've fixed up a die, there's no point in doing so again.
15841      This also avoids a memory leak if we were to call
15842      guess_partial_die_structure_name multiple times.  */
15843   if (part_die->fixup_called)
15844     return;
15845
15846   /* If we found a reference attribute and the DIE has no name, try
15847      to find a name in the referred to DIE.  */
15848
15849   if (part_die->name == NULL && part_die->has_specification)
15850     {
15851       struct partial_die_info *spec_die;
15852
15853       spec_die = find_partial_die (part_die->spec_offset,
15854                                    part_die->spec_is_dwz, cu);
15855
15856       fixup_partial_die (spec_die, cu);
15857
15858       if (spec_die->name)
15859         {
15860           part_die->name = spec_die->name;
15861
15862           /* Copy DW_AT_external attribute if it is set.  */
15863           if (spec_die->is_external)
15864             part_die->is_external = spec_die->is_external;
15865         }
15866     }
15867
15868   /* Set default names for some unnamed DIEs.  */
15869
15870   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
15871     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
15872
15873   /* If there is no parent die to provide a namespace, and there are
15874      children, see if we can determine the namespace from their linkage
15875      name.  */
15876   if (cu->language == language_cplus
15877       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
15878       && part_die->die_parent == NULL
15879       && part_die->has_children
15880       && (part_die->tag == DW_TAG_class_type
15881           || part_die->tag == DW_TAG_structure_type
15882           || part_die->tag == DW_TAG_union_type))
15883     guess_partial_die_structure_name (part_die, cu);
15884
15885   /* GCC might emit a nameless struct or union that has a linkage
15886      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15887   if (part_die->name == NULL
15888       && (part_die->tag == DW_TAG_class_type
15889           || part_die->tag == DW_TAG_interface_type
15890           || part_die->tag == DW_TAG_structure_type
15891           || part_die->tag == DW_TAG_union_type)
15892       && part_die->linkage_name != NULL)
15893     {
15894       char *demangled;
15895
15896       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
15897       if (demangled)
15898         {
15899           const char *base;
15900
15901           /* Strip any leading namespaces/classes, keep only the base name.
15902              DW_AT_name for named DIEs does not contain the prefixes.  */
15903           base = strrchr (demangled, ':');
15904           if (base && base > demangled && base[-1] == ':')
15905             base++;
15906           else
15907             base = demangled;
15908
15909           part_die->name
15910             = obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
15911                              base, strlen (base));
15912           xfree (demangled);
15913         }
15914     }
15915
15916   part_die->fixup_called = 1;
15917 }
15918
15919 /* Read an attribute value described by an attribute form.  */
15920
15921 static const gdb_byte *
15922 read_attribute_value (const struct die_reader_specs *reader,
15923                       struct attribute *attr, unsigned form,
15924                       const gdb_byte *info_ptr)
15925 {
15926   struct dwarf2_cu *cu = reader->cu;
15927   bfd *abfd = reader->abfd;
15928   struct comp_unit_head *cu_header = &cu->header;
15929   unsigned int bytes_read;
15930   struct dwarf_block *blk;
15931
15932   attr->form = form;
15933   switch (form)
15934     {
15935     case DW_FORM_ref_addr:
15936       if (cu->header.version == 2)
15937         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15938       else
15939         DW_UNSND (attr) = read_offset (abfd, info_ptr,
15940                                        &cu->header, &bytes_read);
15941       info_ptr += bytes_read;
15942       break;
15943     case DW_FORM_GNU_ref_alt:
15944       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15945       info_ptr += bytes_read;
15946       break;
15947     case DW_FORM_addr:
15948       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15949       info_ptr += bytes_read;
15950       break;
15951     case DW_FORM_block2:
15952       blk = dwarf_alloc_block (cu);
15953       blk->size = read_2_bytes (abfd, info_ptr);
15954       info_ptr += 2;
15955       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15956       info_ptr += blk->size;
15957       DW_BLOCK (attr) = blk;
15958       break;
15959     case DW_FORM_block4:
15960       blk = dwarf_alloc_block (cu);
15961       blk->size = read_4_bytes (abfd, info_ptr);
15962       info_ptr += 4;
15963       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15964       info_ptr += blk->size;
15965       DW_BLOCK (attr) = blk;
15966       break;
15967     case DW_FORM_data2:
15968       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
15969       info_ptr += 2;
15970       break;
15971     case DW_FORM_data4:
15972       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
15973       info_ptr += 4;
15974       break;
15975     case DW_FORM_data8:
15976       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
15977       info_ptr += 8;
15978       break;
15979     case DW_FORM_sec_offset:
15980       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15981       info_ptr += bytes_read;
15982       break;
15983     case DW_FORM_string:
15984       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
15985       DW_STRING_IS_CANONICAL (attr) = 0;
15986       info_ptr += bytes_read;
15987       break;
15988     case DW_FORM_strp:
15989       if (!cu->per_cu->is_dwz)
15990         {
15991           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
15992                                                    &bytes_read);
15993           DW_STRING_IS_CANONICAL (attr) = 0;
15994           info_ptr += bytes_read;
15995           break;
15996         }
15997       /* FALLTHROUGH */
15998     case DW_FORM_GNU_strp_alt:
15999       {
16000         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16001         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16002                                           &bytes_read);
16003
16004         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16005         DW_STRING_IS_CANONICAL (attr) = 0;
16006         info_ptr += bytes_read;
16007       }
16008       break;
16009     case DW_FORM_exprloc:
16010     case DW_FORM_block:
16011       blk = dwarf_alloc_block (cu);
16012       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16013       info_ptr += bytes_read;
16014       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16015       info_ptr += blk->size;
16016       DW_BLOCK (attr) = blk;
16017       break;
16018     case DW_FORM_block1:
16019       blk = dwarf_alloc_block (cu);
16020       blk->size = read_1_byte (abfd, info_ptr);
16021       info_ptr += 1;
16022       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16023       info_ptr += blk->size;
16024       DW_BLOCK (attr) = blk;
16025       break;
16026     case DW_FORM_data1:
16027       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16028       info_ptr += 1;
16029       break;
16030     case DW_FORM_flag:
16031       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16032       info_ptr += 1;
16033       break;
16034     case DW_FORM_flag_present:
16035       DW_UNSND (attr) = 1;
16036       break;
16037     case DW_FORM_sdata:
16038       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16039       info_ptr += bytes_read;
16040       break;
16041     case DW_FORM_udata:
16042       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16043       info_ptr += bytes_read;
16044       break;
16045     case DW_FORM_ref1:
16046       DW_UNSND (attr) = (cu->header.offset.sect_off
16047                          + read_1_byte (abfd, info_ptr));
16048       info_ptr += 1;
16049       break;
16050     case DW_FORM_ref2:
16051       DW_UNSND (attr) = (cu->header.offset.sect_off
16052                          + read_2_bytes (abfd, info_ptr));
16053       info_ptr += 2;
16054       break;
16055     case DW_FORM_ref4:
16056       DW_UNSND (attr) = (cu->header.offset.sect_off
16057                          + read_4_bytes (abfd, info_ptr));
16058       info_ptr += 4;
16059       break;
16060     case DW_FORM_ref8:
16061       DW_UNSND (attr) = (cu->header.offset.sect_off
16062                          + read_8_bytes (abfd, info_ptr));
16063       info_ptr += 8;
16064       break;
16065     case DW_FORM_ref_sig8:
16066       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16067       info_ptr += 8;
16068       break;
16069     case DW_FORM_ref_udata:
16070       DW_UNSND (attr) = (cu->header.offset.sect_off
16071                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16072       info_ptr += bytes_read;
16073       break;
16074     case DW_FORM_indirect:
16075       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16076       info_ptr += bytes_read;
16077       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
16078       break;
16079     case DW_FORM_GNU_addr_index:
16080       if (reader->dwo_file == NULL)
16081         {
16082           /* For now flag a hard error.
16083              Later we can turn this into a complaint.  */
16084           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16085                  dwarf_form_name (form),
16086                  bfd_get_filename (abfd));
16087         }
16088       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16089       info_ptr += bytes_read;
16090       break;
16091     case DW_FORM_GNU_str_index:
16092       if (reader->dwo_file == NULL)
16093         {
16094           /* For now flag a hard error.
16095              Later we can turn this into a complaint if warranted.  */
16096           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16097                  dwarf_form_name (form),
16098                  bfd_get_filename (abfd));
16099         }
16100       {
16101         ULONGEST str_index =
16102           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16103
16104         DW_STRING (attr) = read_str_index (reader, str_index);
16105         DW_STRING_IS_CANONICAL (attr) = 0;
16106         info_ptr += bytes_read;
16107       }
16108       break;
16109     default:
16110       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16111              dwarf_form_name (form),
16112              bfd_get_filename (abfd));
16113     }
16114
16115   /* Super hack.  */
16116   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16117     attr->form = DW_FORM_GNU_ref_alt;
16118
16119   /* We have seen instances where the compiler tried to emit a byte
16120      size attribute of -1 which ended up being encoded as an unsigned
16121      0xffffffff.  Although 0xffffffff is technically a valid size value,
16122      an object of this size seems pretty unlikely so we can relatively
16123      safely treat these cases as if the size attribute was invalid and
16124      treat them as zero by default.  */
16125   if (attr->name == DW_AT_byte_size
16126       && form == DW_FORM_data4
16127       && DW_UNSND (attr) >= 0xffffffff)
16128     {
16129       complaint
16130         (&symfile_complaints,
16131          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16132          hex_string (DW_UNSND (attr)));
16133       DW_UNSND (attr) = 0;
16134     }
16135
16136   return info_ptr;
16137 }
16138
16139 /* Read an attribute described by an abbreviated attribute.  */
16140
16141 static const gdb_byte *
16142 read_attribute (const struct die_reader_specs *reader,
16143                 struct attribute *attr, struct attr_abbrev *abbrev,
16144                 const gdb_byte *info_ptr)
16145 {
16146   attr->name = abbrev->name;
16147   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
16148 }
16149
16150 /* Read dwarf information from a buffer.  */
16151
16152 static unsigned int
16153 read_1_byte (bfd *abfd, const gdb_byte *buf)
16154 {
16155   return bfd_get_8 (abfd, buf);
16156 }
16157
16158 static int
16159 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16160 {
16161   return bfd_get_signed_8 (abfd, buf);
16162 }
16163
16164 static unsigned int
16165 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16166 {
16167   return bfd_get_16 (abfd, buf);
16168 }
16169
16170 static int
16171 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16172 {
16173   return bfd_get_signed_16 (abfd, buf);
16174 }
16175
16176 static unsigned int
16177 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16178 {
16179   return bfd_get_32 (abfd, buf);
16180 }
16181
16182 static int
16183 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16184 {
16185   return bfd_get_signed_32 (abfd, buf);
16186 }
16187
16188 static ULONGEST
16189 read_8_bytes (bfd *abfd, const gdb_byte *buf)
16190 {
16191   return bfd_get_64 (abfd, buf);
16192 }
16193
16194 static CORE_ADDR
16195 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
16196               unsigned int *bytes_read)
16197 {
16198   struct comp_unit_head *cu_header = &cu->header;
16199   CORE_ADDR retval = 0;
16200
16201   if (cu_header->signed_addr_p)
16202     {
16203       switch (cu_header->addr_size)
16204         {
16205         case 2:
16206           retval = bfd_get_signed_16 (abfd, buf);
16207           break;
16208         case 4:
16209           retval = bfd_get_signed_32 (abfd, buf);
16210           break;
16211         case 8:
16212           retval = bfd_get_signed_64 (abfd, buf);
16213           break;
16214         default:
16215           internal_error (__FILE__, __LINE__,
16216                           _("read_address: bad switch, signed [in module %s]"),
16217                           bfd_get_filename (abfd));
16218         }
16219     }
16220   else
16221     {
16222       switch (cu_header->addr_size)
16223         {
16224         case 2:
16225           retval = bfd_get_16 (abfd, buf);
16226           break;
16227         case 4:
16228           retval = bfd_get_32 (abfd, buf);
16229           break;
16230         case 8:
16231           retval = bfd_get_64 (abfd, buf);
16232           break;
16233         default:
16234           internal_error (__FILE__, __LINE__,
16235                           _("read_address: bad switch, "
16236                             "unsigned [in module %s]"),
16237                           bfd_get_filename (abfd));
16238         }
16239     }
16240
16241   *bytes_read = cu_header->addr_size;
16242   return retval;
16243 }
16244
16245 /* Read the initial length from a section.  The (draft) DWARF 3
16246    specification allows the initial length to take up either 4 bytes
16247    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
16248    bytes describe the length and all offsets will be 8 bytes in length
16249    instead of 4.
16250
16251    An older, non-standard 64-bit format is also handled by this
16252    function.  The older format in question stores the initial length
16253    as an 8-byte quantity without an escape value.  Lengths greater
16254    than 2^32 aren't very common which means that the initial 4 bytes
16255    is almost always zero.  Since a length value of zero doesn't make
16256    sense for the 32-bit format, this initial zero can be considered to
16257    be an escape value which indicates the presence of the older 64-bit
16258    format.  As written, the code can't detect (old format) lengths
16259    greater than 4GB.  If it becomes necessary to handle lengths
16260    somewhat larger than 4GB, we could allow other small values (such
16261    as the non-sensical values of 1, 2, and 3) to also be used as
16262    escape values indicating the presence of the old format.
16263
16264    The value returned via bytes_read should be used to increment the
16265    relevant pointer after calling read_initial_length().
16266
16267    [ Note:  read_initial_length() and read_offset() are based on the
16268      document entitled "DWARF Debugging Information Format", revision
16269      3, draft 8, dated November 19, 2001.  This document was obtained
16270      from:
16271
16272         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
16273
16274      This document is only a draft and is subject to change.  (So beware.)
16275
16276      Details regarding the older, non-standard 64-bit format were
16277      determined empirically by examining 64-bit ELF files produced by
16278      the SGI toolchain on an IRIX 6.5 machine.
16279
16280      - Kevin, July 16, 2002
16281    ] */
16282
16283 static LONGEST
16284 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
16285 {
16286   LONGEST length = bfd_get_32 (abfd, buf);
16287
16288   if (length == 0xffffffff)
16289     {
16290       length = bfd_get_64 (abfd, buf + 4);
16291       *bytes_read = 12;
16292     }
16293   else if (length == 0)
16294     {
16295       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
16296       length = bfd_get_64 (abfd, buf);
16297       *bytes_read = 8;
16298     }
16299   else
16300     {
16301       *bytes_read = 4;
16302     }
16303
16304   return length;
16305 }
16306
16307 /* Cover function for read_initial_length.
16308    Returns the length of the object at BUF, and stores the size of the
16309    initial length in *BYTES_READ and stores the size that offsets will be in
16310    *OFFSET_SIZE.
16311    If the initial length size is not equivalent to that specified in
16312    CU_HEADER then issue a complaint.
16313    This is useful when reading non-comp-unit headers.  */
16314
16315 static LONGEST
16316 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
16317                                         const struct comp_unit_head *cu_header,
16318                                         unsigned int *bytes_read,
16319                                         unsigned int *offset_size)
16320 {
16321   LONGEST length = read_initial_length (abfd, buf, bytes_read);
16322
16323   gdb_assert (cu_header->initial_length_size == 4
16324               || cu_header->initial_length_size == 8
16325               || cu_header->initial_length_size == 12);
16326
16327   if (cu_header->initial_length_size != *bytes_read)
16328     complaint (&symfile_complaints,
16329                _("intermixed 32-bit and 64-bit DWARF sections"));
16330
16331   *offset_size = (*bytes_read == 4) ? 4 : 8;
16332   return length;
16333 }
16334
16335 /* Read an offset from the data stream.  The size of the offset is
16336    given by cu_header->offset_size.  */
16337
16338 static LONGEST
16339 read_offset (bfd *abfd, const gdb_byte *buf,
16340              const struct comp_unit_head *cu_header,
16341              unsigned int *bytes_read)
16342 {
16343   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
16344
16345   *bytes_read = cu_header->offset_size;
16346   return offset;
16347 }
16348
16349 /* Read an offset from the data stream.  */
16350
16351 static LONGEST
16352 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
16353 {
16354   LONGEST retval = 0;
16355
16356   switch (offset_size)
16357     {
16358     case 4:
16359       retval = bfd_get_32 (abfd, buf);
16360       break;
16361     case 8:
16362       retval = bfd_get_64 (abfd, buf);
16363       break;
16364     default:
16365       internal_error (__FILE__, __LINE__,
16366                       _("read_offset_1: bad switch [in module %s]"),
16367                       bfd_get_filename (abfd));
16368     }
16369
16370   return retval;
16371 }
16372
16373 static const gdb_byte *
16374 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
16375 {
16376   /* If the size of a host char is 8 bits, we can return a pointer
16377      to the buffer, otherwise we have to copy the data to a buffer
16378      allocated on the temporary obstack.  */
16379   gdb_assert (HOST_CHAR_BIT == 8);
16380   return buf;
16381 }
16382
16383 static const char *
16384 read_direct_string (bfd *abfd, const gdb_byte *buf,
16385                     unsigned int *bytes_read_ptr)
16386 {
16387   /* If the size of a host char is 8 bits, we can return a pointer
16388      to the string, otherwise we have to copy the string to a buffer
16389      allocated on the temporary obstack.  */
16390   gdb_assert (HOST_CHAR_BIT == 8);
16391   if (*buf == '\0')
16392     {
16393       *bytes_read_ptr = 1;
16394       return NULL;
16395     }
16396   *bytes_read_ptr = strlen ((const char *) buf) + 1;
16397   return (const char *) buf;
16398 }
16399
16400 static const char *
16401 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
16402 {
16403   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
16404   if (dwarf2_per_objfile->str.buffer == NULL)
16405     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
16406            bfd_get_filename (abfd));
16407   if (str_offset >= dwarf2_per_objfile->str.size)
16408     error (_("DW_FORM_strp pointing outside of "
16409              ".debug_str section [in module %s]"),
16410            bfd_get_filename (abfd));
16411   gdb_assert (HOST_CHAR_BIT == 8);
16412   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
16413     return NULL;
16414   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
16415 }
16416
16417 /* Read a string at offset STR_OFFSET in the .debug_str section from
16418    the .dwz file DWZ.  Throw an error if the offset is too large.  If
16419    the string consists of a single NUL byte, return NULL; otherwise
16420    return a pointer to the string.  */
16421
16422 static const char *
16423 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
16424 {
16425   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
16426
16427   if (dwz->str.buffer == NULL)
16428     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
16429              "section [in module %s]"),
16430            bfd_get_filename (dwz->dwz_bfd));
16431   if (str_offset >= dwz->str.size)
16432     error (_("DW_FORM_GNU_strp_alt pointing outside of "
16433              ".debug_str section [in module %s]"),
16434            bfd_get_filename (dwz->dwz_bfd));
16435   gdb_assert (HOST_CHAR_BIT == 8);
16436   if (dwz->str.buffer[str_offset] == '\0')
16437     return NULL;
16438   return (const char *) (dwz->str.buffer + str_offset);
16439 }
16440
16441 static const char *
16442 read_indirect_string (bfd *abfd, const gdb_byte *buf,
16443                       const struct comp_unit_head *cu_header,
16444                       unsigned int *bytes_read_ptr)
16445 {
16446   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
16447
16448   return read_indirect_string_at_offset (abfd, str_offset);
16449 }
16450
16451 static ULONGEST
16452 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
16453                       unsigned int *bytes_read_ptr)
16454 {
16455   ULONGEST result;
16456   unsigned int num_read;
16457   int i, shift;
16458   unsigned char byte;
16459
16460   result = 0;
16461   shift = 0;
16462   num_read = 0;
16463   i = 0;
16464   while (1)
16465     {
16466       byte = bfd_get_8 (abfd, buf);
16467       buf++;
16468       num_read++;
16469       result |= ((ULONGEST) (byte & 127) << shift);
16470       if ((byte & 128) == 0)
16471         {
16472           break;
16473         }
16474       shift += 7;
16475     }
16476   *bytes_read_ptr = num_read;
16477   return result;
16478 }
16479
16480 static LONGEST
16481 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
16482                     unsigned int *bytes_read_ptr)
16483 {
16484   LONGEST result;
16485   int i, shift, num_read;
16486   unsigned char byte;
16487
16488   result = 0;
16489   shift = 0;
16490   num_read = 0;
16491   i = 0;
16492   while (1)
16493     {
16494       byte = bfd_get_8 (abfd, buf);
16495       buf++;
16496       num_read++;
16497       result |= ((LONGEST) (byte & 127) << shift);
16498       shift += 7;
16499       if ((byte & 128) == 0)
16500         {
16501           break;
16502         }
16503     }
16504   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
16505     result |= -(((LONGEST) 1) << shift);
16506   *bytes_read_ptr = num_read;
16507   return result;
16508 }
16509
16510 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
16511    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
16512    ADDR_SIZE is the size of addresses from the CU header.  */
16513
16514 static CORE_ADDR
16515 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
16516 {
16517   struct objfile *objfile = dwarf2_per_objfile->objfile;
16518   bfd *abfd = objfile->obfd;
16519   const gdb_byte *info_ptr;
16520
16521   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
16522   if (dwarf2_per_objfile->addr.buffer == NULL)
16523     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
16524            objfile_name (objfile));
16525   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
16526     error (_("DW_FORM_addr_index pointing outside of "
16527              ".debug_addr section [in module %s]"),
16528            objfile_name (objfile));
16529   info_ptr = (dwarf2_per_objfile->addr.buffer
16530               + addr_base + addr_index * addr_size);
16531   if (addr_size == 4)
16532     return bfd_get_32 (abfd, info_ptr);
16533   else
16534     return bfd_get_64 (abfd, info_ptr);
16535 }
16536
16537 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
16538
16539 static CORE_ADDR
16540 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
16541 {
16542   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
16543 }
16544
16545 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
16546
16547 static CORE_ADDR
16548 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
16549                              unsigned int *bytes_read)
16550 {
16551   bfd *abfd = cu->objfile->obfd;
16552   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
16553
16554   return read_addr_index (cu, addr_index);
16555 }
16556
16557 /* Data structure to pass results from dwarf2_read_addr_index_reader
16558    back to dwarf2_read_addr_index.  */
16559
16560 struct dwarf2_read_addr_index_data
16561 {
16562   ULONGEST addr_base;
16563   int addr_size;
16564 };
16565
16566 /* die_reader_func for dwarf2_read_addr_index.  */
16567
16568 static void
16569 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
16570                                const gdb_byte *info_ptr,
16571                                struct die_info *comp_unit_die,
16572                                int has_children,
16573                                void *data)
16574 {
16575   struct dwarf2_cu *cu = reader->cu;
16576   struct dwarf2_read_addr_index_data *aidata =
16577     (struct dwarf2_read_addr_index_data *) data;
16578
16579   aidata->addr_base = cu->addr_base;
16580   aidata->addr_size = cu->header.addr_size;
16581 }
16582
16583 /* Given an index in .debug_addr, fetch the value.
16584    NOTE: This can be called during dwarf expression evaluation,
16585    long after the debug information has been read, and thus per_cu->cu
16586    may no longer exist.  */
16587
16588 CORE_ADDR
16589 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
16590                         unsigned int addr_index)
16591 {
16592   struct objfile *objfile = per_cu->objfile;
16593   struct dwarf2_cu *cu = per_cu->cu;
16594   ULONGEST addr_base;
16595   int addr_size;
16596
16597   /* This is intended to be called from outside this file.  */
16598   dw2_setup (objfile);
16599
16600   /* We need addr_base and addr_size.
16601      If we don't have PER_CU->cu, we have to get it.
16602      Nasty, but the alternative is storing the needed info in PER_CU,
16603      which at this point doesn't seem justified: it's not clear how frequently
16604      it would get used and it would increase the size of every PER_CU.
16605      Entry points like dwarf2_per_cu_addr_size do a similar thing
16606      so we're not in uncharted territory here.
16607      Alas we need to be a bit more complicated as addr_base is contained
16608      in the DIE.
16609
16610      We don't need to read the entire CU(/TU).
16611      We just need the header and top level die.
16612
16613      IWBN to use the aging mechanism to let us lazily later discard the CU.
16614      For now we skip this optimization.  */
16615
16616   if (cu != NULL)
16617     {
16618       addr_base = cu->addr_base;
16619       addr_size = cu->header.addr_size;
16620     }
16621   else
16622     {
16623       struct dwarf2_read_addr_index_data aidata;
16624
16625       /* Note: We can't use init_cutu_and_read_dies_simple here,
16626          we need addr_base.  */
16627       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
16628                                dwarf2_read_addr_index_reader, &aidata);
16629       addr_base = aidata.addr_base;
16630       addr_size = aidata.addr_size;
16631     }
16632
16633   return read_addr_index_1 (addr_index, addr_base, addr_size);
16634 }
16635
16636 /* Given a DW_FORM_GNU_str_index, fetch the string.
16637    This is only used by the Fission support.  */
16638
16639 static const char *
16640 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
16641 {
16642   struct objfile *objfile = dwarf2_per_objfile->objfile;
16643   const char *objf_name = objfile_name (objfile);
16644   bfd *abfd = objfile->obfd;
16645   struct dwarf2_cu *cu = reader->cu;
16646   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
16647   struct dwarf2_section_info *str_offsets_section =
16648     &reader->dwo_file->sections.str_offsets;
16649   const gdb_byte *info_ptr;
16650   ULONGEST str_offset;
16651   static const char form_name[] = "DW_FORM_GNU_str_index";
16652
16653   dwarf2_read_section (objfile, str_section);
16654   dwarf2_read_section (objfile, str_offsets_section);
16655   if (str_section->buffer == NULL)
16656     error (_("%s used without .debug_str.dwo section"
16657              " in CU at offset 0x%lx [in module %s]"),
16658            form_name, (long) cu->header.offset.sect_off, objf_name);
16659   if (str_offsets_section->buffer == NULL)
16660     error (_("%s used without .debug_str_offsets.dwo section"
16661              " in CU at offset 0x%lx [in module %s]"),
16662            form_name, (long) cu->header.offset.sect_off, objf_name);
16663   if (str_index * cu->header.offset_size >= str_offsets_section->size)
16664     error (_("%s pointing outside of .debug_str_offsets.dwo"
16665              " section in CU at offset 0x%lx [in module %s]"),
16666            form_name, (long) cu->header.offset.sect_off, objf_name);
16667   info_ptr = (str_offsets_section->buffer
16668               + str_index * cu->header.offset_size);
16669   if (cu->header.offset_size == 4)
16670     str_offset = bfd_get_32 (abfd, info_ptr);
16671   else
16672     str_offset = bfd_get_64 (abfd, info_ptr);
16673   if (str_offset >= str_section->size)
16674     error (_("Offset from %s pointing outside of"
16675              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
16676            form_name, (long) cu->header.offset.sect_off, objf_name);
16677   return (const char *) (str_section->buffer + str_offset);
16678 }
16679
16680 /* Return the length of an LEB128 number in BUF.  */
16681
16682 static int
16683 leb128_size (const gdb_byte *buf)
16684 {
16685   const gdb_byte *begin = buf;
16686   gdb_byte byte;
16687
16688   while (1)
16689     {
16690       byte = *buf++;
16691       if ((byte & 128) == 0)
16692         return buf - begin;
16693     }
16694 }
16695
16696 static void
16697 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
16698 {
16699   switch (lang)
16700     {
16701     case DW_LANG_C89:
16702     case DW_LANG_C99:
16703     case DW_LANG_C:
16704     case DW_LANG_UPC:
16705       cu->language = language_c;
16706       break;
16707     case DW_LANG_C_plus_plus:
16708       cu->language = language_cplus;
16709       break;
16710     case DW_LANG_D:
16711       cu->language = language_d;
16712       break;
16713     case DW_LANG_Fortran77:
16714     case DW_LANG_Fortran90:
16715     case DW_LANG_Fortran95:
16716       cu->language = language_fortran;
16717       break;
16718     case DW_LANG_Go:
16719       cu->language = language_go;
16720       break;
16721     case DW_LANG_Mips_Assembler:
16722       cu->language = language_asm;
16723       break;
16724     case DW_LANG_Java:
16725       cu->language = language_java;
16726       break;
16727     case DW_LANG_Ada83:
16728     case DW_LANG_Ada95:
16729       cu->language = language_ada;
16730       break;
16731     case DW_LANG_Modula2:
16732       cu->language = language_m2;
16733       break;
16734     case DW_LANG_Pascal83:
16735       cu->language = language_pascal;
16736       break;
16737     case DW_LANG_ObjC:
16738       cu->language = language_objc;
16739       break;
16740     case DW_LANG_Cobol74:
16741     case DW_LANG_Cobol85:
16742     default:
16743       cu->language = language_minimal;
16744       break;
16745     }
16746   cu->language_defn = language_def (cu->language);
16747 }
16748
16749 /* Return the named attribute or NULL if not there.  */
16750
16751 static struct attribute *
16752 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
16753 {
16754   for (;;)
16755     {
16756       unsigned int i;
16757       struct attribute *spec = NULL;
16758
16759       for (i = 0; i < die->num_attrs; ++i)
16760         {
16761           if (die->attrs[i].name == name)
16762             return &die->attrs[i];
16763           if (die->attrs[i].name == DW_AT_specification
16764               || die->attrs[i].name == DW_AT_abstract_origin)
16765             spec = &die->attrs[i];
16766         }
16767
16768       if (!spec)
16769         break;
16770
16771       die = follow_die_ref (die, spec, &cu);
16772     }
16773
16774   return NULL;
16775 }
16776
16777 /* Return the named attribute or NULL if not there,
16778    but do not follow DW_AT_specification, etc.
16779    This is for use in contexts where we're reading .debug_types dies.
16780    Following DW_AT_specification, DW_AT_abstract_origin will take us
16781    back up the chain, and we want to go down.  */
16782
16783 static struct attribute *
16784 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
16785 {
16786   unsigned int i;
16787
16788   for (i = 0; i < die->num_attrs; ++i)
16789     if (die->attrs[i].name == name)
16790       return &die->attrs[i];
16791
16792   return NULL;
16793 }
16794
16795 /* Return non-zero iff the attribute NAME is defined for the given DIE,
16796    and holds a non-zero value.  This function should only be used for
16797    DW_FORM_flag or DW_FORM_flag_present attributes.  */
16798
16799 static int
16800 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
16801 {
16802   struct attribute *attr = dwarf2_attr (die, name, cu);
16803
16804   return (attr && DW_UNSND (attr));
16805 }
16806
16807 static int
16808 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
16809 {
16810   /* A DIE is a declaration if it has a DW_AT_declaration attribute
16811      which value is non-zero.  However, we have to be careful with
16812      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
16813      (via dwarf2_flag_true_p) follows this attribute.  So we may
16814      end up accidently finding a declaration attribute that belongs
16815      to a different DIE referenced by the specification attribute,
16816      even though the given DIE does not have a declaration attribute.  */
16817   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
16818           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
16819 }
16820
16821 /* Return the die giving the specification for DIE, if there is
16822    one.  *SPEC_CU is the CU containing DIE on input, and the CU
16823    containing the return value on output.  If there is no
16824    specification, but there is an abstract origin, that is
16825    returned.  */
16826
16827 static struct die_info *
16828 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
16829 {
16830   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
16831                                              *spec_cu);
16832
16833   if (spec_attr == NULL)
16834     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
16835
16836   if (spec_attr == NULL)
16837     return NULL;
16838   else
16839     return follow_die_ref (die, spec_attr, spec_cu);
16840 }
16841
16842 /* Free the line_header structure *LH, and any arrays and strings it
16843    refers to.
16844    NOTE: This is also used as a "cleanup" function.  */
16845
16846 static void
16847 free_line_header (struct line_header *lh)
16848 {
16849   if (lh->standard_opcode_lengths)
16850     xfree (lh->standard_opcode_lengths);
16851
16852   /* Remember that all the lh->file_names[i].name pointers are
16853      pointers into debug_line_buffer, and don't need to be freed.  */
16854   if (lh->file_names)
16855     xfree (lh->file_names);
16856
16857   /* Similarly for the include directory names.  */
16858   if (lh->include_dirs)
16859     xfree (lh->include_dirs);
16860
16861   xfree (lh);
16862 }
16863
16864 /* Add an entry to LH's include directory table.  */
16865
16866 static void
16867 add_include_dir (struct line_header *lh, const char *include_dir)
16868 {
16869   /* Grow the array if necessary.  */
16870   if (lh->include_dirs_size == 0)
16871     {
16872       lh->include_dirs_size = 1; /* for testing */
16873       lh->include_dirs = xmalloc (lh->include_dirs_size
16874                                   * sizeof (*lh->include_dirs));
16875     }
16876   else if (lh->num_include_dirs >= lh->include_dirs_size)
16877     {
16878       lh->include_dirs_size *= 2;
16879       lh->include_dirs = xrealloc (lh->include_dirs,
16880                                    (lh->include_dirs_size
16881                                     * sizeof (*lh->include_dirs)));
16882     }
16883
16884   lh->include_dirs[lh->num_include_dirs++] = include_dir;
16885 }
16886
16887 /* Add an entry to LH's file name table.  */
16888
16889 static void
16890 add_file_name (struct line_header *lh,
16891                const char *name,
16892                unsigned int dir_index,
16893                unsigned int mod_time,
16894                unsigned int length)
16895 {
16896   struct file_entry *fe;
16897
16898   /* Grow the array if necessary.  */
16899   if (lh->file_names_size == 0)
16900     {
16901       lh->file_names_size = 1; /* for testing */
16902       lh->file_names = xmalloc (lh->file_names_size
16903                                 * sizeof (*lh->file_names));
16904     }
16905   else if (lh->num_file_names >= lh->file_names_size)
16906     {
16907       lh->file_names_size *= 2;
16908       lh->file_names = xrealloc (lh->file_names,
16909                                  (lh->file_names_size
16910                                   * sizeof (*lh->file_names)));
16911     }
16912
16913   fe = &lh->file_names[lh->num_file_names++];
16914   fe->name = name;
16915   fe->dir_index = dir_index;
16916   fe->mod_time = mod_time;
16917   fe->length = length;
16918   fe->included_p = 0;
16919   fe->symtab = NULL;
16920 }
16921
16922 /* A convenience function to find the proper .debug_line section for a
16923    CU.  */
16924
16925 static struct dwarf2_section_info *
16926 get_debug_line_section (struct dwarf2_cu *cu)
16927 {
16928   struct dwarf2_section_info *section;
16929
16930   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
16931      DWO file.  */
16932   if (cu->dwo_unit && cu->per_cu->is_debug_types)
16933     section = &cu->dwo_unit->dwo_file->sections.line;
16934   else if (cu->per_cu->is_dwz)
16935     {
16936       struct dwz_file *dwz = dwarf2_get_dwz_file ();
16937
16938       section = &dwz->line;
16939     }
16940   else
16941     section = &dwarf2_per_objfile->line;
16942
16943   return section;
16944 }
16945
16946 /* Read the statement program header starting at OFFSET in
16947    .debug_line, or .debug_line.dwo.  Return a pointer
16948    to a struct line_header, allocated using xmalloc.
16949
16950    NOTE: the strings in the include directory and file name tables of
16951    the returned object point into the dwarf line section buffer,
16952    and must not be freed.  */
16953
16954 static struct line_header *
16955 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
16956 {
16957   struct cleanup *back_to;
16958   struct line_header *lh;
16959   const gdb_byte *line_ptr;
16960   unsigned int bytes_read, offset_size;
16961   int i;
16962   const char *cur_dir, *cur_file;
16963   struct dwarf2_section_info *section;
16964   bfd *abfd;
16965
16966   section = get_debug_line_section (cu);
16967   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
16968   if (section->buffer == NULL)
16969     {
16970       if (cu->dwo_unit && cu->per_cu->is_debug_types)
16971         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
16972       else
16973         complaint (&symfile_complaints, _("missing .debug_line section"));
16974       return 0;
16975     }
16976
16977   /* We can't do this until we know the section is non-empty.
16978      Only then do we know we have such a section.  */
16979   abfd = get_section_bfd_owner (section);
16980
16981   /* Make sure that at least there's room for the total_length field.
16982      That could be 12 bytes long, but we're just going to fudge that.  */
16983   if (offset + 4 >= section->size)
16984     {
16985       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16986       return 0;
16987     }
16988
16989   lh = xmalloc (sizeof (*lh));
16990   memset (lh, 0, sizeof (*lh));
16991   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
16992                           (void *) lh);
16993
16994   line_ptr = section->buffer + offset;
16995
16996   /* Read in the header.  */
16997   lh->total_length =
16998     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
16999                                             &bytes_read, &offset_size);
17000   line_ptr += bytes_read;
17001   if (line_ptr + lh->total_length > (section->buffer + section->size))
17002     {
17003       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17004       do_cleanups (back_to);
17005       return 0;
17006     }
17007   lh->statement_program_end = line_ptr + lh->total_length;
17008   lh->version = read_2_bytes (abfd, line_ptr);
17009   line_ptr += 2;
17010   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
17011   line_ptr += offset_size;
17012   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
17013   line_ptr += 1;
17014   if (lh->version >= 4)
17015     {
17016       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
17017       line_ptr += 1;
17018     }
17019   else
17020     lh->maximum_ops_per_instruction = 1;
17021
17022   if (lh->maximum_ops_per_instruction == 0)
17023     {
17024       lh->maximum_ops_per_instruction = 1;
17025       complaint (&symfile_complaints,
17026                  _("invalid maximum_ops_per_instruction "
17027                    "in `.debug_line' section"));
17028     }
17029
17030   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
17031   line_ptr += 1;
17032   lh->line_base = read_1_signed_byte (abfd, line_ptr);
17033   line_ptr += 1;
17034   lh->line_range = read_1_byte (abfd, line_ptr);
17035   line_ptr += 1;
17036   lh->opcode_base = read_1_byte (abfd, line_ptr);
17037   line_ptr += 1;
17038   lh->standard_opcode_lengths
17039     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
17040
17041   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
17042   for (i = 1; i < lh->opcode_base; ++i)
17043     {
17044       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
17045       line_ptr += 1;
17046     }
17047
17048   /* Read directory table.  */
17049   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
17050     {
17051       line_ptr += bytes_read;
17052       add_include_dir (lh, cur_dir);
17053     }
17054   line_ptr += bytes_read;
17055
17056   /* Read file name table.  */
17057   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
17058     {
17059       unsigned int dir_index, mod_time, length;
17060
17061       line_ptr += bytes_read;
17062       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17063       line_ptr += bytes_read;
17064       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17065       line_ptr += bytes_read;
17066       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17067       line_ptr += bytes_read;
17068
17069       add_file_name (lh, cur_file, dir_index, mod_time, length);
17070     }
17071   line_ptr += bytes_read;
17072   lh->statement_program_start = line_ptr;
17073
17074   if (line_ptr > (section->buffer + section->size))
17075     complaint (&symfile_complaints,
17076                _("line number info header doesn't "
17077                  "fit in `.debug_line' section"));
17078
17079   discard_cleanups (back_to);
17080   return lh;
17081 }
17082
17083 /* Subroutine of dwarf_decode_lines to simplify it.
17084    Return the file name of the psymtab for included file FILE_INDEX
17085    in line header LH of PST.
17086    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
17087    If space for the result is malloc'd, it will be freed by a cleanup.
17088    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
17089
17090    The function creates dangling cleanup registration.  */
17091
17092 static const char *
17093 psymtab_include_file_name (const struct line_header *lh, int file_index,
17094                            const struct partial_symtab *pst,
17095                            const char *comp_dir)
17096 {
17097   const struct file_entry fe = lh->file_names [file_index];
17098   const char *include_name = fe.name;
17099   const char *include_name_to_compare = include_name;
17100   const char *dir_name = NULL;
17101   const char *pst_filename;
17102   char *copied_name = NULL;
17103   int file_is_pst;
17104
17105   if (fe.dir_index)
17106     dir_name = lh->include_dirs[fe.dir_index - 1];
17107
17108   if (!IS_ABSOLUTE_PATH (include_name)
17109       && (dir_name != NULL || comp_dir != NULL))
17110     {
17111       /* Avoid creating a duplicate psymtab for PST.
17112          We do this by comparing INCLUDE_NAME and PST_FILENAME.
17113          Before we do the comparison, however, we need to account
17114          for DIR_NAME and COMP_DIR.
17115          First prepend dir_name (if non-NULL).  If we still don't
17116          have an absolute path prepend comp_dir (if non-NULL).
17117          However, the directory we record in the include-file's
17118          psymtab does not contain COMP_DIR (to match the
17119          corresponding symtab(s)).
17120
17121          Example:
17122
17123          bash$ cd /tmp
17124          bash$ gcc -g ./hello.c
17125          include_name = "hello.c"
17126          dir_name = "."
17127          DW_AT_comp_dir = comp_dir = "/tmp"
17128          DW_AT_name = "./hello.c"
17129
17130       */
17131
17132       if (dir_name != NULL)
17133         {
17134           char *tem = concat (dir_name, SLASH_STRING,
17135                               include_name, (char *)NULL);
17136
17137           make_cleanup (xfree, tem);
17138           include_name = tem;
17139           include_name_to_compare = include_name;
17140         }
17141       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
17142         {
17143           char *tem = concat (comp_dir, SLASH_STRING,
17144                               include_name, (char *)NULL);
17145
17146           make_cleanup (xfree, tem);
17147           include_name_to_compare = tem;
17148         }
17149     }
17150
17151   pst_filename = pst->filename;
17152   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
17153     {
17154       copied_name = concat (pst->dirname, SLASH_STRING,
17155                             pst_filename, (char *)NULL);
17156       pst_filename = copied_name;
17157     }
17158
17159   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
17160
17161   if (copied_name != NULL)
17162     xfree (copied_name);
17163
17164   if (file_is_pst)
17165     return NULL;
17166   return include_name;
17167 }
17168
17169 /* Ignore this record_line request.  */
17170
17171 static void
17172 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
17173 {
17174   return;
17175 }
17176
17177 /* Return non-zero if we should add LINE to the line number table.
17178    LINE is the line to add, LAST_LINE is the last line that was added,
17179    LAST_SUBFILE is the subfile for LAST_LINE.
17180    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
17181    had a non-zero discriminator.
17182
17183    We have to be careful in the presence of discriminators.
17184    E.g., for this line:
17185
17186      for (i = 0; i < 100000; i++);
17187
17188    clang can emit four line number entries for that one line,
17189    each with a different discriminator.
17190    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
17191
17192    However, we want gdb to coalesce all four entries into one.
17193    Otherwise the user could stepi into the middle of the line and
17194    gdb would get confused about whether the pc really was in the
17195    middle of the line.
17196
17197    Things are further complicated by the fact that two consecutive
17198    line number entries for the same line is a heuristic used by gcc
17199    to denote the end of the prologue.  So we can't just discard duplicate
17200    entries, we have to be selective about it.  The heuristic we use is
17201    that we only collapse consecutive entries for the same line if at least
17202    one of those entries has a non-zero discriminator.  PR 17276.
17203
17204    Note: Addresses in the line number state machine can never go backwards
17205    within one sequence, thus this coalescing is ok.  */
17206
17207 static int
17208 dwarf_record_line_p (unsigned int line, unsigned int last_line,
17209                      int line_has_non_zero_discriminator,
17210                      struct subfile *last_subfile)
17211 {
17212   if (current_subfile != last_subfile)
17213     return 1;
17214   if (line != last_line)
17215     return 1;
17216   /* Same line for the same file that we've seen already.
17217      As a last check, for pr 17276, only record the line if the line
17218      has never had a non-zero discriminator.  */
17219   if (!line_has_non_zero_discriminator)
17220     return 1;
17221   return 0;
17222 }
17223
17224 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
17225    in the line table of subfile SUBFILE.  */
17226
17227 static void
17228 dwarf_record_line (struct gdbarch *gdbarch, struct subfile *subfile,
17229                    unsigned int line, CORE_ADDR address,
17230                    record_line_ftype p_record_line)
17231 {
17232   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
17233
17234   (*p_record_line) (subfile, line, addr);
17235 }
17236
17237 /* Subroutine of dwarf_decode_lines_1 to simplify it.
17238    Mark the end of a set of line number records.
17239    The arguments are the same as for dwarf_record_line.
17240    If SUBFILE is NULL the request is ignored.  */
17241
17242 static void
17243 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
17244                    CORE_ADDR address, record_line_ftype p_record_line)
17245 {
17246   if (subfile != NULL)
17247     dwarf_record_line (gdbarch, subfile, 0, address, p_record_line);
17248 }
17249
17250 /* Subroutine of dwarf_decode_lines to simplify it.
17251    Process the line number information in LH.  */
17252
17253 static void
17254 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
17255                       struct dwarf2_cu *cu, const int decode_for_pst_p)
17256 {
17257   const gdb_byte *line_ptr, *extended_end;
17258   const gdb_byte *line_end;
17259   unsigned int bytes_read, extended_len;
17260   unsigned char op_code, extended_op;
17261   CORE_ADDR baseaddr;
17262   struct objfile *objfile = cu->objfile;
17263   bfd *abfd = objfile->obfd;
17264   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17265   struct subfile *last_subfile = NULL;
17266   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
17267     = record_line;
17268
17269   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17270
17271   line_ptr = lh->statement_program_start;
17272   line_end = lh->statement_program_end;
17273
17274   /* Read the statement sequences until there's nothing left.  */
17275   while (line_ptr < line_end)
17276     {
17277       /* state machine registers  */
17278       CORE_ADDR address = 0;
17279       unsigned int file = 1;
17280       unsigned int line = 1;
17281       int is_stmt = lh->default_is_stmt;
17282       int end_sequence = 0;
17283       unsigned char op_index = 0;
17284       unsigned int discriminator = 0;
17285       /* The last line number that was recorded, used to coalesce
17286          consecutive entries for the same line.  This can happen, for
17287          example, when discriminators are present.  PR 17276.  */
17288       unsigned int last_line = 0;
17289       int line_has_non_zero_discriminator = 0;
17290
17291       if (!decode_for_pst_p && lh->num_file_names >= file)
17292         {
17293           /* Start a subfile for the current file of the state machine.  */
17294           /* lh->include_dirs and lh->file_names are 0-based, but the
17295              directory and file name numbers in the statement program
17296              are 1-based.  */
17297           struct file_entry *fe = &lh->file_names[file - 1];
17298           const char *dir = NULL;
17299
17300           if (fe->dir_index)
17301             dir = lh->include_dirs[fe->dir_index - 1];
17302
17303           dwarf2_start_subfile (fe->name, dir, comp_dir);
17304         }
17305
17306       /* Decode the table.  */
17307       while (!end_sequence)
17308         {
17309           op_code = read_1_byte (abfd, line_ptr);
17310           line_ptr += 1;
17311           if (line_ptr > line_end)
17312             {
17313               dwarf2_debug_line_missing_end_sequence_complaint ();
17314               break;
17315             }
17316
17317           if (op_code >= lh->opcode_base)
17318             {
17319               /* Special opcode.  */
17320               unsigned char adj_opcode;
17321               int line_delta;
17322
17323               adj_opcode = op_code - lh->opcode_base;
17324               address += (((op_index + (adj_opcode / lh->line_range))
17325                            / lh->maximum_ops_per_instruction)
17326                           * lh->minimum_instruction_length);
17327               op_index = ((op_index + (adj_opcode / lh->line_range))
17328                           % lh->maximum_ops_per_instruction);
17329               line_delta = lh->line_base + (adj_opcode % lh->line_range);
17330               line += line_delta;
17331               if (line_delta != 0)
17332                 line_has_non_zero_discriminator = discriminator != 0;
17333               if (lh->num_file_names < file || file == 0)
17334                 dwarf2_debug_line_missing_file_complaint ();
17335               /* For now we ignore lines not starting on an
17336                  instruction boundary.  */
17337               else if (op_index == 0)
17338                 {
17339                   lh->file_names[file - 1].included_p = 1;
17340                   if (!decode_for_pst_p && is_stmt)
17341                     {
17342                       if (last_subfile != current_subfile)
17343                         {
17344                           dwarf_finish_line (gdbarch, last_subfile,
17345                                              address, p_record_line);
17346                         }
17347                       if (dwarf_record_line_p (line, last_line,
17348                                                line_has_non_zero_discriminator,
17349                                                last_subfile))
17350                         {
17351                           dwarf_record_line (gdbarch, current_subfile,
17352                                              line, address, p_record_line);
17353                         }
17354                       last_subfile = current_subfile;
17355                       last_line = line;
17356                     }
17357                 }
17358               discriminator = 0;
17359             }
17360           else switch (op_code)
17361             {
17362             case DW_LNS_extended_op:
17363               extended_len = read_unsigned_leb128 (abfd, line_ptr,
17364                                                    &bytes_read);
17365               line_ptr += bytes_read;
17366               extended_end = line_ptr + extended_len;
17367               extended_op = read_1_byte (abfd, line_ptr);
17368               line_ptr += 1;
17369               switch (extended_op)
17370                 {
17371                 case DW_LNE_end_sequence:
17372                   p_record_line = record_line;
17373                   end_sequence = 1;
17374                   break;
17375                 case DW_LNE_set_address:
17376                   address = read_address (abfd, line_ptr, cu, &bytes_read);
17377
17378                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
17379                     {
17380                       /* This line table is for a function which has been
17381                          GCd by the linker.  Ignore it.  PR gdb/12528 */
17382
17383                       long line_offset
17384                         = line_ptr - get_debug_line_section (cu)->buffer;
17385
17386                       complaint (&symfile_complaints,
17387                                  _(".debug_line address at offset 0x%lx is 0 "
17388                                    "[in module %s]"),
17389                                  line_offset, objfile_name (objfile));
17390                       p_record_line = noop_record_line;
17391                       /* Note: p_record_line is left as noop_record_line
17392                          until we see DW_LNE_end_sequence.  */
17393                     }
17394
17395                   op_index = 0;
17396                   line_ptr += bytes_read;
17397                   address += baseaddr;
17398                   break;
17399                 case DW_LNE_define_file:
17400                   {
17401                     const char *cur_file;
17402                     unsigned int dir_index, mod_time, length;
17403
17404                     cur_file = read_direct_string (abfd, line_ptr,
17405                                                    &bytes_read);
17406                     line_ptr += bytes_read;
17407                     dir_index =
17408                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17409                     line_ptr += bytes_read;
17410                     mod_time =
17411                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17412                     line_ptr += bytes_read;
17413                     length =
17414                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17415                     line_ptr += bytes_read;
17416                     add_file_name (lh, cur_file, dir_index, mod_time, length);
17417                   }
17418                   break;
17419                 case DW_LNE_set_discriminator:
17420                   /* The discriminator is not interesting to the debugger;
17421                      just ignore it.  We still need to check its value though:
17422                      if there are consecutive entries for the same
17423                      (non-prologue) line we want to coalesce them.
17424                      PR 17276.  */
17425                   discriminator = read_unsigned_leb128 (abfd, line_ptr,
17426                                                         &bytes_read);
17427                   line_has_non_zero_discriminator |= discriminator != 0;
17428                   line_ptr += bytes_read;
17429                   break;
17430                 default:
17431                   complaint (&symfile_complaints,
17432                              _("mangled .debug_line section"));
17433                   return;
17434                 }
17435               /* Make sure that we parsed the extended op correctly.  If e.g.
17436                  we expected a different address size than the producer used,
17437                  we may have read the wrong number of bytes.  */
17438               if (line_ptr != extended_end)
17439                 {
17440                   complaint (&symfile_complaints,
17441                              _("mangled .debug_line section"));
17442                   return;
17443                 }
17444               break;
17445             case DW_LNS_copy:
17446               if (lh->num_file_names < file || file == 0)
17447                 dwarf2_debug_line_missing_file_complaint ();
17448               else
17449                 {
17450                   lh->file_names[file - 1].included_p = 1;
17451                   if (!decode_for_pst_p && is_stmt)
17452                     {
17453                       if (last_subfile != current_subfile)
17454                         {
17455                           dwarf_finish_line (gdbarch, last_subfile,
17456                                              address, p_record_line);
17457                         }
17458                       if (dwarf_record_line_p (line, last_line,
17459                                                line_has_non_zero_discriminator,
17460                                                last_subfile))
17461                         {
17462                           dwarf_record_line (gdbarch, current_subfile,
17463                                              line, address, p_record_line);
17464                         }
17465                       last_subfile = current_subfile;
17466                       last_line = line;
17467                     }
17468                 }
17469               discriminator = 0;
17470               break;
17471             case DW_LNS_advance_pc:
17472               {
17473                 CORE_ADDR adjust
17474                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17475
17476                 address += (((op_index + adjust)
17477                              / lh->maximum_ops_per_instruction)
17478                             * lh->minimum_instruction_length);
17479                 op_index = ((op_index + adjust)
17480                             % lh->maximum_ops_per_instruction);
17481                 line_ptr += bytes_read;
17482               }
17483               break;
17484             case DW_LNS_advance_line:
17485               {
17486                 int line_delta
17487                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
17488
17489                 line += line_delta;
17490                 if (line_delta != 0)
17491                   line_has_non_zero_discriminator = discriminator != 0;
17492                 line_ptr += bytes_read;
17493               }
17494               break;
17495             case DW_LNS_set_file:
17496               {
17497                 /* The arrays lh->include_dirs and lh->file_names are
17498                    0-based, but the directory and file name numbers in
17499                    the statement program are 1-based.  */
17500                 struct file_entry *fe;
17501                 const char *dir = NULL;
17502
17503                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17504                 line_ptr += bytes_read;
17505                 if (lh->num_file_names < file || file == 0)
17506                   dwarf2_debug_line_missing_file_complaint ();
17507                 else
17508                   {
17509                     fe = &lh->file_names[file - 1];
17510                     if (fe->dir_index)
17511                       dir = lh->include_dirs[fe->dir_index - 1];
17512                     if (!decode_for_pst_p)
17513                       {
17514                         last_subfile = current_subfile;
17515                         line_has_non_zero_discriminator = discriminator != 0;
17516                         dwarf2_start_subfile (fe->name, dir, comp_dir);
17517                       }
17518                   }
17519               }
17520               break;
17521             case DW_LNS_set_column:
17522               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17523               line_ptr += bytes_read;
17524               break;
17525             case DW_LNS_negate_stmt:
17526               is_stmt = (!is_stmt);
17527               break;
17528             case DW_LNS_set_basic_block:
17529               break;
17530             /* Add to the address register of the state machine the
17531                address increment value corresponding to special opcode
17532                255.  I.e., this value is scaled by the minimum
17533                instruction length since special opcode 255 would have
17534                scaled the increment.  */
17535             case DW_LNS_const_add_pc:
17536               {
17537                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
17538
17539                 address += (((op_index + adjust)
17540                              / lh->maximum_ops_per_instruction)
17541                             * lh->minimum_instruction_length);
17542                 op_index = ((op_index + adjust)
17543                             % lh->maximum_ops_per_instruction);
17544               }
17545               break;
17546             case DW_LNS_fixed_advance_pc:
17547               address += read_2_bytes (abfd, line_ptr);
17548               op_index = 0;
17549               line_ptr += 2;
17550               break;
17551             default:
17552               {
17553                 /* Unknown standard opcode, ignore it.  */
17554                 int i;
17555
17556                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
17557                   {
17558                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17559                     line_ptr += bytes_read;
17560                   }
17561               }
17562             }
17563         }
17564       if (lh->num_file_names < file || file == 0)
17565         dwarf2_debug_line_missing_file_complaint ();
17566       else
17567         {
17568           lh->file_names[file - 1].included_p = 1;
17569           if (!decode_for_pst_p)
17570             {
17571               dwarf_finish_line (gdbarch, current_subfile, address,
17572                                  p_record_line);
17573             }
17574         }
17575     }
17576 }
17577
17578 /* Decode the Line Number Program (LNP) for the given line_header
17579    structure and CU.  The actual information extracted and the type
17580    of structures created from the LNP depends on the value of PST.
17581
17582    1. If PST is NULL, then this procedure uses the data from the program
17583       to create all necessary symbol tables, and their linetables.
17584
17585    2. If PST is not NULL, this procedure reads the program to determine
17586       the list of files included by the unit represented by PST, and
17587       builds all the associated partial symbol tables.
17588
17589    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
17590    It is used for relative paths in the line table.
17591    NOTE: When processing partial symtabs (pst != NULL),
17592    comp_dir == pst->dirname.
17593
17594    NOTE: It is important that psymtabs have the same file name (via strcmp)
17595    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
17596    symtab we don't use it in the name of the psymtabs we create.
17597    E.g. expand_line_sal requires this when finding psymtabs to expand.
17598    A good testcase for this is mb-inline.exp.  */
17599
17600 static void
17601 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
17602                     struct dwarf2_cu *cu, struct partial_symtab *pst)
17603 {
17604   struct objfile *objfile = cu->objfile;
17605   const int decode_for_pst_p = (pst != NULL);
17606   struct subfile *first_subfile = current_subfile;
17607
17608   dwarf_decode_lines_1 (lh, comp_dir, cu, decode_for_pst_p);
17609
17610   if (decode_for_pst_p)
17611     {
17612       int file_index;
17613
17614       /* Now that we're done scanning the Line Header Program, we can
17615          create the psymtab of each included file.  */
17616       for (file_index = 0; file_index < lh->num_file_names; file_index++)
17617         if (lh->file_names[file_index].included_p == 1)
17618           {
17619             const char *include_name =
17620               psymtab_include_file_name (lh, file_index, pst, comp_dir);
17621             if (include_name != NULL)
17622               dwarf2_create_include_psymtab (include_name, pst, objfile);
17623           }
17624     }
17625   else
17626     {
17627       /* Make sure a symtab is created for every file, even files
17628          which contain only variables (i.e. no code with associated
17629          line numbers).  */
17630       int i;
17631
17632       for (i = 0; i < lh->num_file_names; i++)
17633         {
17634           const char *dir = NULL;
17635           struct file_entry *fe;
17636
17637           fe = &lh->file_names[i];
17638           if (fe->dir_index)
17639             dir = lh->include_dirs[fe->dir_index - 1];
17640           dwarf2_start_subfile (fe->name, dir, comp_dir);
17641
17642           /* Skip the main file; we don't need it, and it must be
17643              allocated last, so that it will show up before the
17644              non-primary symtabs in the objfile's symtab list.  */
17645           if (current_subfile == first_subfile)
17646             continue;
17647
17648           if (current_subfile->symtab == NULL)
17649             current_subfile->symtab = allocate_symtab (current_subfile->name,
17650                                                        objfile);
17651           fe->symtab = current_subfile->symtab;
17652         }
17653     }
17654 }
17655
17656 /* Start a subfile for DWARF.  FILENAME is the name of the file and
17657    DIRNAME the name of the source directory which contains FILENAME
17658    or NULL if not known.  COMP_DIR is the compilation directory for the
17659    linetable's compilation unit or NULL if not known.
17660    This routine tries to keep line numbers from identical absolute and
17661    relative file names in a common subfile.
17662
17663    Using the `list' example from the GDB testsuite, which resides in
17664    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
17665    of /srcdir/list0.c yields the following debugging information for list0.c:
17666
17667    DW_AT_name:          /srcdir/list0.c
17668    DW_AT_comp_dir:              /compdir
17669    files.files[0].name: list0.h
17670    files.files[0].dir:  /srcdir
17671    files.files[1].name: list0.c
17672    files.files[1].dir:  /srcdir
17673
17674    The line number information for list0.c has to end up in a single
17675    subfile, so that `break /srcdir/list0.c:1' works as expected.
17676    start_subfile will ensure that this happens provided that we pass the
17677    concatenation of files.files[1].dir and files.files[1].name as the
17678    subfile's name.  */
17679
17680 static void
17681 dwarf2_start_subfile (const char *filename, const char *dirname,
17682                       const char *comp_dir)
17683 {
17684   char *copy = NULL;
17685
17686   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
17687      `start_symtab' will always pass the contents of DW_AT_comp_dir as
17688      second argument to start_subfile.  To be consistent, we do the
17689      same here.  In order not to lose the line information directory,
17690      we concatenate it to the filename when it makes sense.
17691      Note that the Dwarf3 standard says (speaking of filenames in line
17692      information): ``The directory index is ignored for file names
17693      that represent full path names''.  Thus ignoring dirname in the
17694      `else' branch below isn't an issue.  */
17695
17696   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
17697     {
17698       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
17699       filename = copy;
17700     }
17701
17702   start_subfile (filename, comp_dir);
17703
17704   if (copy != NULL)
17705     xfree (copy);
17706 }
17707
17708 /* Start a symtab for DWARF.
17709    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
17710
17711 static void
17712 dwarf2_start_symtab (struct dwarf2_cu *cu,
17713                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
17714 {
17715   start_symtab (name, comp_dir, low_pc);
17716   record_debugformat ("DWARF 2");
17717   record_producer (cu->producer);
17718
17719   /* We assume that we're processing GCC output.  */
17720   processing_gcc_compilation = 2;
17721
17722   cu->processing_has_namespace_info = 0;
17723 }
17724
17725 static void
17726 var_decode_location (struct attribute *attr, struct symbol *sym,
17727                      struct dwarf2_cu *cu)
17728 {
17729   struct objfile *objfile = cu->objfile;
17730   struct comp_unit_head *cu_header = &cu->header;
17731
17732   /* NOTE drow/2003-01-30: There used to be a comment and some special
17733      code here to turn a symbol with DW_AT_external and a
17734      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
17735      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
17736      with some versions of binutils) where shared libraries could have
17737      relocations against symbols in their debug information - the
17738      minimal symbol would have the right address, but the debug info
17739      would not.  It's no longer necessary, because we will explicitly
17740      apply relocations when we read in the debug information now.  */
17741
17742   /* A DW_AT_location attribute with no contents indicates that a
17743      variable has been optimized away.  */
17744   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
17745     {
17746       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17747       return;
17748     }
17749
17750   /* Handle one degenerate form of location expression specially, to
17751      preserve GDB's previous behavior when section offsets are
17752      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
17753      then mark this symbol as LOC_STATIC.  */
17754
17755   if (attr_form_is_block (attr)
17756       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
17757            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
17758           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
17759               && (DW_BLOCK (attr)->size
17760                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
17761     {
17762       unsigned int dummy;
17763
17764       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
17765         SYMBOL_VALUE_ADDRESS (sym) =
17766           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
17767       else
17768         SYMBOL_VALUE_ADDRESS (sym) =
17769           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
17770       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
17771       fixup_symbol_section (sym, objfile);
17772       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
17773                                               SYMBOL_SECTION (sym));
17774       return;
17775     }
17776
17777   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
17778      expression evaluator, and use LOC_COMPUTED only when necessary
17779      (i.e. when the value of a register or memory location is
17780      referenced, or a thread-local block, etc.).  Then again, it might
17781      not be worthwhile.  I'm assuming that it isn't unless performance
17782      or memory numbers show me otherwise.  */
17783
17784   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
17785
17786   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
17787     cu->has_loclist = 1;
17788 }
17789
17790 /* Given a pointer to a DWARF information entry, figure out if we need
17791    to make a symbol table entry for it, and if so, create a new entry
17792    and return a pointer to it.
17793    If TYPE is NULL, determine symbol type from the die, otherwise
17794    used the passed type.
17795    If SPACE is not NULL, use it to hold the new symbol.  If it is
17796    NULL, allocate a new symbol on the objfile's obstack.  */
17797
17798 static struct symbol *
17799 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
17800                  struct symbol *space)
17801 {
17802   struct objfile *objfile = cu->objfile;
17803   struct symbol *sym = NULL;
17804   const char *name;
17805   struct attribute *attr = NULL;
17806   struct attribute *attr2 = NULL;
17807   CORE_ADDR baseaddr;
17808   struct pending **list_to_add = NULL;
17809
17810   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
17811
17812   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17813
17814   name = dwarf2_name (die, cu);
17815   if (name)
17816     {
17817       const char *linkagename;
17818       int suppress_add = 0;
17819
17820       if (space)
17821         sym = space;
17822       else
17823         sym = allocate_symbol (objfile);
17824       OBJSTAT (objfile, n_syms++);
17825
17826       /* Cache this symbol's name and the name's demangled form (if any).  */
17827       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
17828       linkagename = dwarf2_physname (name, die, cu);
17829       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
17830
17831       /* Fortran does not have mangling standard and the mangling does differ
17832          between gfortran, iFort etc.  */
17833       if (cu->language == language_fortran
17834           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
17835         symbol_set_demangled_name (&(sym->ginfo),
17836                                    dwarf2_full_name (name, die, cu),
17837                                    NULL);
17838
17839       /* Default assumptions.
17840          Use the passed type or decode it from the die.  */
17841       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17842       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17843       if (type != NULL)
17844         SYMBOL_TYPE (sym) = type;
17845       else
17846         SYMBOL_TYPE (sym) = die_type (die, cu);
17847       attr = dwarf2_attr (die,
17848                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
17849                           cu);
17850       if (attr)
17851         {
17852           SYMBOL_LINE (sym) = DW_UNSND (attr);
17853         }
17854
17855       attr = dwarf2_attr (die,
17856                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
17857                           cu);
17858       if (attr)
17859         {
17860           int file_index = DW_UNSND (attr);
17861
17862           if (cu->line_header == NULL
17863               || file_index > cu->line_header->num_file_names)
17864             complaint (&symfile_complaints,
17865                        _("file index out of range"));
17866           else if (file_index > 0)
17867             {
17868               struct file_entry *fe;
17869
17870               fe = &cu->line_header->file_names[file_index - 1];
17871               SYMBOL_SYMTAB (sym) = fe->symtab;
17872             }
17873         }
17874
17875       switch (die->tag)
17876         {
17877         case DW_TAG_label:
17878           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
17879           if (attr)
17880             SYMBOL_VALUE_ADDRESS (sym)
17881               = attr_value_as_address (attr) + baseaddr;
17882           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
17883           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
17884           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
17885           add_symbol_to_list (sym, cu->list_in_scope);
17886           break;
17887         case DW_TAG_subprogram:
17888           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17889              finish_block.  */
17890           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17891           attr2 = dwarf2_attr (die, DW_AT_external, cu);
17892           if ((attr2 && (DW_UNSND (attr2) != 0))
17893               || cu->language == language_ada)
17894             {
17895               /* Subprograms marked external are stored as a global symbol.
17896                  Ada subprograms, whether marked external or not, are always
17897                  stored as a global symbol, because we want to be able to
17898                  access them globally.  For instance, we want to be able
17899                  to break on a nested subprogram without having to
17900                  specify the context.  */
17901               list_to_add = &global_symbols;
17902             }
17903           else
17904             {
17905               list_to_add = cu->list_in_scope;
17906             }
17907           break;
17908         case DW_TAG_inlined_subroutine:
17909           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17910              finish_block.  */
17911           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17912           SYMBOL_INLINED (sym) = 1;
17913           list_to_add = cu->list_in_scope;
17914           break;
17915         case DW_TAG_template_value_param:
17916           suppress_add = 1;
17917           /* Fall through.  */
17918         case DW_TAG_constant:
17919         case DW_TAG_variable:
17920         case DW_TAG_member:
17921           /* Compilation with minimal debug info may result in
17922              variables with missing type entries.  Change the
17923              misleading `void' type to something sensible.  */
17924           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
17925             SYMBOL_TYPE (sym)
17926               = objfile_type (objfile)->nodebug_data_symbol;
17927
17928           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17929           /* In the case of DW_TAG_member, we should only be called for
17930              static const members.  */
17931           if (die->tag == DW_TAG_member)
17932             {
17933               /* dwarf2_add_field uses die_is_declaration,
17934                  so we do the same.  */
17935               gdb_assert (die_is_declaration (die, cu));
17936               gdb_assert (attr);
17937             }
17938           if (attr)
17939             {
17940               dwarf2_const_value (attr, sym, cu);
17941               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17942               if (!suppress_add)
17943                 {
17944                   if (attr2 && (DW_UNSND (attr2) != 0))
17945                     list_to_add = &global_symbols;
17946                   else
17947                     list_to_add = cu->list_in_scope;
17948                 }
17949               break;
17950             }
17951           attr = dwarf2_attr (die, DW_AT_location, cu);
17952           if (attr)
17953             {
17954               var_decode_location (attr, sym, cu);
17955               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17956
17957               /* Fortran explicitly imports any global symbols to the local
17958                  scope by DW_TAG_common_block.  */
17959               if (cu->language == language_fortran && die->parent
17960                   && die->parent->tag == DW_TAG_common_block)
17961                 attr2 = NULL;
17962
17963               if (SYMBOL_CLASS (sym) == LOC_STATIC
17964                   && SYMBOL_VALUE_ADDRESS (sym) == 0
17965                   && !dwarf2_per_objfile->has_section_at_zero)
17966                 {
17967                   /* When a static variable is eliminated by the linker,
17968                      the corresponding debug information is not stripped
17969                      out, but the variable address is set to null;
17970                      do not add such variables into symbol table.  */
17971                 }
17972               else if (attr2 && (DW_UNSND (attr2) != 0))
17973                 {
17974                   /* Workaround gfortran PR debug/40040 - it uses
17975                      DW_AT_location for variables in -fPIC libraries which may
17976                      get overriden by other libraries/executable and get
17977                      a different address.  Resolve it by the minimal symbol
17978                      which may come from inferior's executable using copy
17979                      relocation.  Make this workaround only for gfortran as for
17980                      other compilers GDB cannot guess the minimal symbol
17981                      Fortran mangling kind.  */
17982                   if (cu->language == language_fortran && die->parent
17983                       && die->parent->tag == DW_TAG_module
17984                       && cu->producer
17985                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
17986                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17987
17988                   /* A variable with DW_AT_external is never static,
17989                      but it may be block-scoped.  */
17990                   list_to_add = (cu->list_in_scope == &file_symbols
17991                                  ? &global_symbols : cu->list_in_scope);
17992                 }
17993               else
17994                 list_to_add = cu->list_in_scope;
17995             }
17996           else
17997             {
17998               /* We do not know the address of this symbol.
17999                  If it is an external symbol and we have type information
18000                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
18001                  The address of the variable will then be determined from
18002                  the minimal symbol table whenever the variable is
18003                  referenced.  */
18004               attr2 = dwarf2_attr (die, DW_AT_external, cu);
18005
18006               /* Fortran explicitly imports any global symbols to the local
18007                  scope by DW_TAG_common_block.  */
18008               if (cu->language == language_fortran && die->parent
18009                   && die->parent->tag == DW_TAG_common_block)
18010                 {
18011                   /* SYMBOL_CLASS doesn't matter here because
18012                      read_common_block is going to reset it.  */
18013                   if (!suppress_add)
18014                     list_to_add = cu->list_in_scope;
18015                 }
18016               else if (attr2 && (DW_UNSND (attr2) != 0)
18017                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
18018                 {
18019                   /* A variable with DW_AT_external is never static, but it
18020                      may be block-scoped.  */
18021                   list_to_add = (cu->list_in_scope == &file_symbols
18022                                  ? &global_symbols : cu->list_in_scope);
18023
18024                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
18025                 }
18026               else if (!die_is_declaration (die, cu))
18027                 {
18028                   /* Use the default LOC_OPTIMIZED_OUT class.  */
18029                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
18030                   if (!suppress_add)
18031                     list_to_add = cu->list_in_scope;
18032                 }
18033             }
18034           break;
18035         case DW_TAG_formal_parameter:
18036           /* If we are inside a function, mark this as an argument.  If
18037              not, we might be looking at an argument to an inlined function
18038              when we do not have enough information to show inlined frames;
18039              pretend it's a local variable in that case so that the user can
18040              still see it.  */
18041           if (context_stack_depth > 0
18042               && context_stack[context_stack_depth - 1].name != NULL)
18043             SYMBOL_IS_ARGUMENT (sym) = 1;
18044           attr = dwarf2_attr (die, DW_AT_location, cu);
18045           if (attr)
18046             {
18047               var_decode_location (attr, sym, cu);
18048             }
18049           attr = dwarf2_attr (die, DW_AT_const_value, cu);
18050           if (attr)
18051             {
18052               dwarf2_const_value (attr, sym, cu);
18053             }
18054
18055           list_to_add = cu->list_in_scope;
18056           break;
18057         case DW_TAG_unspecified_parameters:
18058           /* From varargs functions; gdb doesn't seem to have any
18059              interest in this information, so just ignore it for now.
18060              (FIXME?) */
18061           break;
18062         case DW_TAG_template_type_param:
18063           suppress_add = 1;
18064           /* Fall through.  */
18065         case DW_TAG_class_type:
18066         case DW_TAG_interface_type:
18067         case DW_TAG_structure_type:
18068         case DW_TAG_union_type:
18069         case DW_TAG_set_type:
18070         case DW_TAG_enumeration_type:
18071           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
18072           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
18073
18074           {
18075             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
18076                really ever be static objects: otherwise, if you try
18077                to, say, break of a class's method and you're in a file
18078                which doesn't mention that class, it won't work unless
18079                the check for all static symbols in lookup_symbol_aux
18080                saves you.  See the OtherFileClass tests in
18081                gdb.c++/namespace.exp.  */
18082
18083             if (!suppress_add)
18084               {
18085                 list_to_add = (cu->list_in_scope == &file_symbols
18086                                && (cu->language == language_cplus
18087                                    || cu->language == language_java)
18088                                ? &global_symbols : cu->list_in_scope);
18089
18090                 /* The semantics of C++ state that "struct foo {
18091                    ... }" also defines a typedef for "foo".  A Java
18092                    class declaration also defines a typedef for the
18093                    class.  */
18094                 if (cu->language == language_cplus
18095                     || cu->language == language_java
18096                     || cu->language == language_ada)
18097                   {
18098                     /* The symbol's name is already allocated along
18099                        with this objfile, so we don't need to
18100                        duplicate it for the type.  */
18101                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
18102                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
18103                   }
18104               }
18105           }
18106           break;
18107         case DW_TAG_typedef:
18108           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
18109           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
18110           list_to_add = cu->list_in_scope;
18111           break;
18112         case DW_TAG_base_type:
18113         case DW_TAG_subrange_type:
18114           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
18115           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
18116           list_to_add = cu->list_in_scope;
18117           break;
18118         case DW_TAG_enumerator:
18119           attr = dwarf2_attr (die, DW_AT_const_value, cu);
18120           if (attr)
18121             {
18122               dwarf2_const_value (attr, sym, cu);
18123             }
18124           {
18125             /* NOTE: carlton/2003-11-10: See comment above in the
18126                DW_TAG_class_type, etc. block.  */
18127
18128             list_to_add = (cu->list_in_scope == &file_symbols
18129                            && (cu->language == language_cplus
18130                                || cu->language == language_java)
18131                            ? &global_symbols : cu->list_in_scope);
18132           }
18133           break;
18134         case DW_TAG_imported_declaration:
18135         case DW_TAG_namespace:
18136           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
18137           list_to_add = &global_symbols;
18138           break;
18139         case DW_TAG_module:
18140           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
18141           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
18142           list_to_add = &global_symbols;
18143           break;
18144         case DW_TAG_common_block:
18145           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
18146           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
18147           add_symbol_to_list (sym, cu->list_in_scope);
18148           break;
18149         default:
18150           /* Not a tag we recognize.  Hopefully we aren't processing
18151              trash data, but since we must specifically ignore things
18152              we don't recognize, there is nothing else we should do at
18153              this point.  */
18154           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
18155                      dwarf_tag_name (die->tag));
18156           break;
18157         }
18158
18159       if (suppress_add)
18160         {
18161           sym->hash_next = objfile->template_symbols;
18162           objfile->template_symbols = sym;
18163           list_to_add = NULL;
18164         }
18165
18166       if (list_to_add != NULL)
18167         add_symbol_to_list (sym, list_to_add);
18168
18169       /* For the benefit of old versions of GCC, check for anonymous
18170          namespaces based on the demangled name.  */
18171       if (!cu->processing_has_namespace_info
18172           && cu->language == language_cplus)
18173         cp_scan_for_anonymous_namespaces (sym, objfile);
18174     }
18175   return (sym);
18176 }
18177
18178 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
18179
18180 static struct symbol *
18181 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
18182 {
18183   return new_symbol_full (die, type, cu, NULL);
18184 }
18185
18186 /* Given an attr with a DW_FORM_dataN value in host byte order,
18187    zero-extend it as appropriate for the symbol's type.  The DWARF
18188    standard (v4) is not entirely clear about the meaning of using
18189    DW_FORM_dataN for a constant with a signed type, where the type is
18190    wider than the data.  The conclusion of a discussion on the DWARF
18191    list was that this is unspecified.  We choose to always zero-extend
18192    because that is the interpretation long in use by GCC.  */
18193
18194 static gdb_byte *
18195 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
18196                          struct dwarf2_cu *cu, LONGEST *value, int bits)
18197 {
18198   struct objfile *objfile = cu->objfile;
18199   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
18200                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
18201   LONGEST l = DW_UNSND (attr);
18202
18203   if (bits < sizeof (*value) * 8)
18204     {
18205       l &= ((LONGEST) 1 << bits) - 1;
18206       *value = l;
18207     }
18208   else if (bits == sizeof (*value) * 8)
18209     *value = l;
18210   else
18211     {
18212       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
18213       store_unsigned_integer (bytes, bits / 8, byte_order, l);
18214       return bytes;
18215     }
18216
18217   return NULL;
18218 }
18219
18220 /* Read a constant value from an attribute.  Either set *VALUE, or if
18221    the value does not fit in *VALUE, set *BYTES - either already
18222    allocated on the objfile obstack, or newly allocated on OBSTACK,
18223    or, set *BATON, if we translated the constant to a location
18224    expression.  */
18225
18226 static void
18227 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
18228                          const char *name, struct obstack *obstack,
18229                          struct dwarf2_cu *cu,
18230                          LONGEST *value, const gdb_byte **bytes,
18231                          struct dwarf2_locexpr_baton **baton)
18232 {
18233   struct objfile *objfile = cu->objfile;
18234   struct comp_unit_head *cu_header = &cu->header;
18235   struct dwarf_block *blk;
18236   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
18237                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18238
18239   *value = 0;
18240   *bytes = NULL;
18241   *baton = NULL;
18242
18243   switch (attr->form)
18244     {
18245     case DW_FORM_addr:
18246     case DW_FORM_GNU_addr_index:
18247       {
18248         gdb_byte *data;
18249
18250         if (TYPE_LENGTH (type) != cu_header->addr_size)
18251           dwarf2_const_value_length_mismatch_complaint (name,
18252                                                         cu_header->addr_size,
18253                                                         TYPE_LENGTH (type));
18254         /* Symbols of this form are reasonably rare, so we just
18255            piggyback on the existing location code rather than writing
18256            a new implementation of symbol_computed_ops.  */
18257         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
18258         (*baton)->per_cu = cu->per_cu;
18259         gdb_assert ((*baton)->per_cu);
18260
18261         (*baton)->size = 2 + cu_header->addr_size;
18262         data = obstack_alloc (obstack, (*baton)->size);
18263         (*baton)->data = data;
18264
18265         data[0] = DW_OP_addr;
18266         store_unsigned_integer (&data[1], cu_header->addr_size,
18267                                 byte_order, DW_ADDR (attr));
18268         data[cu_header->addr_size + 1] = DW_OP_stack_value;
18269       }
18270       break;
18271     case DW_FORM_string:
18272     case DW_FORM_strp:
18273     case DW_FORM_GNU_str_index:
18274     case DW_FORM_GNU_strp_alt:
18275       /* DW_STRING is already allocated on the objfile obstack, point
18276          directly to it.  */
18277       *bytes = (const gdb_byte *) DW_STRING (attr);
18278       break;
18279     case DW_FORM_block1:
18280     case DW_FORM_block2:
18281     case DW_FORM_block4:
18282     case DW_FORM_block:
18283     case DW_FORM_exprloc:
18284       blk = DW_BLOCK (attr);
18285       if (TYPE_LENGTH (type) != blk->size)
18286         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
18287                                                       TYPE_LENGTH (type));
18288       *bytes = blk->data;
18289       break;
18290
18291       /* The DW_AT_const_value attributes are supposed to carry the
18292          symbol's value "represented as it would be on the target
18293          architecture."  By the time we get here, it's already been
18294          converted to host endianness, so we just need to sign- or
18295          zero-extend it as appropriate.  */
18296     case DW_FORM_data1:
18297       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
18298       break;
18299     case DW_FORM_data2:
18300       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
18301       break;
18302     case DW_FORM_data4:
18303       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
18304       break;
18305     case DW_FORM_data8:
18306       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
18307       break;
18308
18309     case DW_FORM_sdata:
18310       *value = DW_SND (attr);
18311       break;
18312
18313     case DW_FORM_udata:
18314       *value = DW_UNSND (attr);
18315       break;
18316
18317     default:
18318       complaint (&symfile_complaints,
18319                  _("unsupported const value attribute form: '%s'"),
18320                  dwarf_form_name (attr->form));
18321       *value = 0;
18322       break;
18323     }
18324 }
18325
18326
18327 /* Copy constant value from an attribute to a symbol.  */
18328
18329 static void
18330 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
18331                     struct dwarf2_cu *cu)
18332 {
18333   struct objfile *objfile = cu->objfile;
18334   struct comp_unit_head *cu_header = &cu->header;
18335   LONGEST value;
18336   const gdb_byte *bytes;
18337   struct dwarf2_locexpr_baton *baton;
18338
18339   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
18340                            SYMBOL_PRINT_NAME (sym),
18341                            &objfile->objfile_obstack, cu,
18342                            &value, &bytes, &baton);
18343
18344   if (baton != NULL)
18345     {
18346       SYMBOL_LOCATION_BATON (sym) = baton;
18347       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
18348     }
18349   else if (bytes != NULL)
18350      {
18351       SYMBOL_VALUE_BYTES (sym) = bytes;
18352       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
18353     }
18354   else
18355     {
18356       SYMBOL_VALUE (sym) = value;
18357       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
18358     }
18359 }
18360
18361 /* Return the type of the die in question using its DW_AT_type attribute.  */
18362
18363 static struct type *
18364 die_type (struct die_info *die, struct dwarf2_cu *cu)
18365 {
18366   struct attribute *type_attr;
18367
18368   type_attr = dwarf2_attr (die, DW_AT_type, cu);
18369   if (!type_attr)
18370     {
18371       /* A missing DW_AT_type represents a void type.  */
18372       return objfile_type (cu->objfile)->builtin_void;
18373     }
18374
18375   return lookup_die_type (die, type_attr, cu);
18376 }
18377
18378 /* True iff CU's producer generates GNAT Ada auxiliary information
18379    that allows to find parallel types through that information instead
18380    of having to do expensive parallel lookups by type name.  */
18381
18382 static int
18383 need_gnat_info (struct dwarf2_cu *cu)
18384 {
18385   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
18386      of GNAT produces this auxiliary information, without any indication
18387      that it is produced.  Part of enhancing the FSF version of GNAT
18388      to produce that information will be to put in place an indicator
18389      that we can use in order to determine whether the descriptive type
18390      info is available or not.  One suggestion that has been made is
18391      to use a new attribute, attached to the CU die.  For now, assume
18392      that the descriptive type info is not available.  */
18393   return 0;
18394 }
18395
18396 /* Return the auxiliary type of the die in question using its
18397    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
18398    attribute is not present.  */
18399
18400 static struct type *
18401 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
18402 {
18403   struct attribute *type_attr;
18404
18405   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
18406   if (!type_attr)
18407     return NULL;
18408
18409   return lookup_die_type (die, type_attr, cu);
18410 }
18411
18412 /* If DIE has a descriptive_type attribute, then set the TYPE's
18413    descriptive type accordingly.  */
18414
18415 static void
18416 set_descriptive_type (struct type *type, struct die_info *die,
18417                       struct dwarf2_cu *cu)
18418 {
18419   struct type *descriptive_type = die_descriptive_type (die, cu);
18420
18421   if (descriptive_type)
18422     {
18423       ALLOCATE_GNAT_AUX_TYPE (type);
18424       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
18425     }
18426 }
18427
18428 /* Return the containing type of the die in question using its
18429    DW_AT_containing_type attribute.  */
18430
18431 static struct type *
18432 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
18433 {
18434   struct attribute *type_attr;
18435
18436   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
18437   if (!type_attr)
18438     error (_("Dwarf Error: Problem turning containing type into gdb type "
18439              "[in module %s]"), objfile_name (cu->objfile));
18440
18441   return lookup_die_type (die, type_attr, cu);
18442 }
18443
18444 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
18445
18446 static struct type *
18447 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
18448 {
18449   struct objfile *objfile = dwarf2_per_objfile->objfile;
18450   char *message, *saved;
18451
18452   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
18453                         objfile_name (objfile),
18454                         cu->header.offset.sect_off,
18455                         die->offset.sect_off);
18456   saved = obstack_copy0 (&objfile->objfile_obstack,
18457                          message, strlen (message));
18458   xfree (message);
18459
18460   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
18461 }
18462
18463 /* Look up the type of DIE in CU using its type attribute ATTR.
18464    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
18465    DW_AT_containing_type.
18466    If there is no type substitute an error marker.  */
18467
18468 static struct type *
18469 lookup_die_type (struct die_info *die, const struct attribute *attr,
18470                  struct dwarf2_cu *cu)
18471 {
18472   struct objfile *objfile = cu->objfile;
18473   struct type *this_type;
18474
18475   gdb_assert (attr->name == DW_AT_type
18476               || attr->name == DW_AT_GNAT_descriptive_type
18477               || attr->name == DW_AT_containing_type);
18478
18479   /* First see if we have it cached.  */
18480
18481   if (attr->form == DW_FORM_GNU_ref_alt)
18482     {
18483       struct dwarf2_per_cu_data *per_cu;
18484       sect_offset offset = dwarf2_get_ref_die_offset (attr);
18485
18486       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
18487       this_type = get_die_type_at_offset (offset, per_cu);
18488     }
18489   else if (attr_form_is_ref (attr))
18490     {
18491       sect_offset offset = dwarf2_get_ref_die_offset (attr);
18492
18493       this_type = get_die_type_at_offset (offset, cu->per_cu);
18494     }
18495   else if (attr->form == DW_FORM_ref_sig8)
18496     {
18497       ULONGEST signature = DW_SIGNATURE (attr);
18498
18499       return get_signatured_type (die, signature, cu);
18500     }
18501   else
18502     {
18503       complaint (&symfile_complaints,
18504                  _("Dwarf Error: Bad type attribute %s in DIE"
18505                    " at 0x%x [in module %s]"),
18506                  dwarf_attr_name (attr->name), die->offset.sect_off,
18507                  objfile_name (objfile));
18508       return build_error_marker_type (cu, die);
18509     }
18510
18511   /* If not cached we need to read it in.  */
18512
18513   if (this_type == NULL)
18514     {
18515       struct die_info *type_die = NULL;
18516       struct dwarf2_cu *type_cu = cu;
18517
18518       if (attr_form_is_ref (attr))
18519         type_die = follow_die_ref (die, attr, &type_cu);
18520       if (type_die == NULL)
18521         return build_error_marker_type (cu, die);
18522       /* If we find the type now, it's probably because the type came
18523          from an inter-CU reference and the type's CU got expanded before
18524          ours.  */
18525       this_type = read_type_die (type_die, type_cu);
18526     }
18527
18528   /* If we still don't have a type use an error marker.  */
18529
18530   if (this_type == NULL)
18531     return build_error_marker_type (cu, die);
18532
18533   return this_type;
18534 }
18535
18536 /* Return the type in DIE, CU.
18537    Returns NULL for invalid types.
18538
18539    This first does a lookup in die_type_hash,
18540    and only reads the die in if necessary.
18541
18542    NOTE: This can be called when reading in partial or full symbols.  */
18543
18544 static struct type *
18545 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
18546 {
18547   struct type *this_type;
18548
18549   this_type = get_die_type (die, cu);
18550   if (this_type)
18551     return this_type;
18552
18553   return read_type_die_1 (die, cu);
18554 }
18555
18556 /* Read the type in DIE, CU.
18557    Returns NULL for invalid types.  */
18558
18559 static struct type *
18560 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
18561 {
18562   struct type *this_type = NULL;
18563
18564   switch (die->tag)
18565     {
18566     case DW_TAG_class_type:
18567     case DW_TAG_interface_type:
18568     case DW_TAG_structure_type:
18569     case DW_TAG_union_type:
18570       this_type = read_structure_type (die, cu);
18571       break;
18572     case DW_TAG_enumeration_type:
18573       this_type = read_enumeration_type (die, cu);
18574       break;
18575     case DW_TAG_subprogram:
18576     case DW_TAG_subroutine_type:
18577     case DW_TAG_inlined_subroutine:
18578       this_type = read_subroutine_type (die, cu);
18579       break;
18580     case DW_TAG_array_type:
18581       this_type = read_array_type (die, cu);
18582       break;
18583     case DW_TAG_set_type:
18584       this_type = read_set_type (die, cu);
18585       break;
18586     case DW_TAG_pointer_type:
18587       this_type = read_tag_pointer_type (die, cu);
18588       break;
18589     case DW_TAG_ptr_to_member_type:
18590       this_type = read_tag_ptr_to_member_type (die, cu);
18591       break;
18592     case DW_TAG_reference_type:
18593       this_type = read_tag_reference_type (die, cu);
18594       break;
18595     case DW_TAG_const_type:
18596       this_type = read_tag_const_type (die, cu);
18597       break;
18598     case DW_TAG_volatile_type:
18599       this_type = read_tag_volatile_type (die, cu);
18600       break;
18601     case DW_TAG_restrict_type:
18602       this_type = read_tag_restrict_type (die, cu);
18603       break;
18604     case DW_TAG_string_type:
18605       this_type = read_tag_string_type (die, cu);
18606       break;
18607     case DW_TAG_typedef:
18608       this_type = read_typedef (die, cu);
18609       break;
18610     case DW_TAG_subrange_type:
18611       this_type = read_subrange_type (die, cu);
18612       break;
18613     case DW_TAG_base_type:
18614       this_type = read_base_type (die, cu);
18615       break;
18616     case DW_TAG_unspecified_type:
18617       this_type = read_unspecified_type (die, cu);
18618       break;
18619     case DW_TAG_namespace:
18620       this_type = read_namespace_type (die, cu);
18621       break;
18622     case DW_TAG_module:
18623       this_type = read_module_type (die, cu);
18624       break;
18625     default:
18626       complaint (&symfile_complaints,
18627                  _("unexpected tag in read_type_die: '%s'"),
18628                  dwarf_tag_name (die->tag));
18629       break;
18630     }
18631
18632   return this_type;
18633 }
18634
18635 /* See if we can figure out if the class lives in a namespace.  We do
18636    this by looking for a member function; its demangled name will
18637    contain namespace info, if there is any.
18638    Return the computed name or NULL.
18639    Space for the result is allocated on the objfile's obstack.
18640    This is the full-die version of guess_partial_die_structure_name.
18641    In this case we know DIE has no useful parent.  */
18642
18643 static char *
18644 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
18645 {
18646   struct die_info *spec_die;
18647   struct dwarf2_cu *spec_cu;
18648   struct die_info *child;
18649
18650   spec_cu = cu;
18651   spec_die = die_specification (die, &spec_cu);
18652   if (spec_die != NULL)
18653     {
18654       die = spec_die;
18655       cu = spec_cu;
18656     }
18657
18658   for (child = die->child;
18659        child != NULL;
18660        child = child->sibling)
18661     {
18662       if (child->tag == DW_TAG_subprogram)
18663         {
18664           struct attribute *attr;
18665
18666           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
18667           if (attr == NULL)
18668             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
18669           if (attr != NULL)
18670             {
18671               char *actual_name
18672                 = language_class_name_from_physname (cu->language_defn,
18673                                                      DW_STRING (attr));
18674               char *name = NULL;
18675
18676               if (actual_name != NULL)
18677                 {
18678                   const char *die_name = dwarf2_name (die, cu);
18679
18680                   if (die_name != NULL
18681                       && strcmp (die_name, actual_name) != 0)
18682                     {
18683                       /* Strip off the class name from the full name.
18684                          We want the prefix.  */
18685                       int die_name_len = strlen (die_name);
18686                       int actual_name_len = strlen (actual_name);
18687
18688                       /* Test for '::' as a sanity check.  */
18689                       if (actual_name_len > die_name_len + 2
18690                           && actual_name[actual_name_len
18691                                          - die_name_len - 1] == ':')
18692                         name =
18693                           obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18694                                          actual_name,
18695                                          actual_name_len - die_name_len - 2);
18696                     }
18697                 }
18698               xfree (actual_name);
18699               return name;
18700             }
18701         }
18702     }
18703
18704   return NULL;
18705 }
18706
18707 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
18708    prefix part in such case.  See
18709    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18710
18711 static char *
18712 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
18713 {
18714   struct attribute *attr;
18715   char *base;
18716
18717   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
18718       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
18719     return NULL;
18720
18721   attr = dwarf2_attr (die, DW_AT_name, cu);
18722   if (attr != NULL && DW_STRING (attr) != NULL)
18723     return NULL;
18724
18725   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18726   if (attr == NULL)
18727     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18728   if (attr == NULL || DW_STRING (attr) == NULL)
18729     return NULL;
18730
18731   /* dwarf2_name had to be already called.  */
18732   gdb_assert (DW_STRING_IS_CANONICAL (attr));
18733
18734   /* Strip the base name, keep any leading namespaces/classes.  */
18735   base = strrchr (DW_STRING (attr), ':');
18736   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
18737     return "";
18738
18739   return obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18740                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
18741 }
18742
18743 /* Return the name of the namespace/class that DIE is defined within,
18744    or "" if we can't tell.  The caller should not xfree the result.
18745
18746    For example, if we're within the method foo() in the following
18747    code:
18748
18749    namespace N {
18750      class C {
18751        void foo () {
18752        }
18753      };
18754    }
18755
18756    then determine_prefix on foo's die will return "N::C".  */
18757
18758 static const char *
18759 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
18760 {
18761   struct die_info *parent, *spec_die;
18762   struct dwarf2_cu *spec_cu;
18763   struct type *parent_type;
18764   char *retval;
18765
18766   if (cu->language != language_cplus && cu->language != language_java
18767       && cu->language != language_fortran)
18768     return "";
18769
18770   retval = anonymous_struct_prefix (die, cu);
18771   if (retval)
18772     return retval;
18773
18774   /* We have to be careful in the presence of DW_AT_specification.
18775      For example, with GCC 3.4, given the code
18776
18777      namespace N {
18778        void foo() {
18779          // Definition of N::foo.
18780        }
18781      }
18782
18783      then we'll have a tree of DIEs like this:
18784
18785      1: DW_TAG_compile_unit
18786        2: DW_TAG_namespace        // N
18787          3: DW_TAG_subprogram     // declaration of N::foo
18788        4: DW_TAG_subprogram       // definition of N::foo
18789             DW_AT_specification   // refers to die #3
18790
18791      Thus, when processing die #4, we have to pretend that we're in
18792      the context of its DW_AT_specification, namely the contex of die
18793      #3.  */
18794   spec_cu = cu;
18795   spec_die = die_specification (die, &spec_cu);
18796   if (spec_die == NULL)
18797     parent = die->parent;
18798   else
18799     {
18800       parent = spec_die->parent;
18801       cu = spec_cu;
18802     }
18803
18804   if (parent == NULL)
18805     return "";
18806   else if (parent->building_fullname)
18807     {
18808       const char *name;
18809       const char *parent_name;
18810
18811       /* It has been seen on RealView 2.2 built binaries,
18812          DW_TAG_template_type_param types actually _defined_ as
18813          children of the parent class:
18814
18815          enum E {};
18816          template class <class Enum> Class{};
18817          Class<enum E> class_e;
18818
18819          1: DW_TAG_class_type (Class)
18820            2: DW_TAG_enumeration_type (E)
18821              3: DW_TAG_enumerator (enum1:0)
18822              3: DW_TAG_enumerator (enum2:1)
18823              ...
18824            2: DW_TAG_template_type_param
18825               DW_AT_type  DW_FORM_ref_udata (E)
18826
18827          Besides being broken debug info, it can put GDB into an
18828          infinite loop.  Consider:
18829
18830          When we're building the full name for Class<E>, we'll start
18831          at Class, and go look over its template type parameters,
18832          finding E.  We'll then try to build the full name of E, and
18833          reach here.  We're now trying to build the full name of E,
18834          and look over the parent DIE for containing scope.  In the
18835          broken case, if we followed the parent DIE of E, we'd again
18836          find Class, and once again go look at its template type
18837          arguments, etc., etc.  Simply don't consider such parent die
18838          as source-level parent of this die (it can't be, the language
18839          doesn't allow it), and break the loop here.  */
18840       name = dwarf2_name (die, cu);
18841       parent_name = dwarf2_name (parent, cu);
18842       complaint (&symfile_complaints,
18843                  _("template param type '%s' defined within parent '%s'"),
18844                  name ? name : "<unknown>",
18845                  parent_name ? parent_name : "<unknown>");
18846       return "";
18847     }
18848   else
18849     switch (parent->tag)
18850       {
18851       case DW_TAG_namespace:
18852         parent_type = read_type_die (parent, cu);
18853         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
18854            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
18855            Work around this problem here.  */
18856         if (cu->language == language_cplus
18857             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
18858           return "";
18859         /* We give a name to even anonymous namespaces.  */
18860         return TYPE_TAG_NAME (parent_type);
18861       case DW_TAG_class_type:
18862       case DW_TAG_interface_type:
18863       case DW_TAG_structure_type:
18864       case DW_TAG_union_type:
18865       case DW_TAG_module:
18866         parent_type = read_type_die (parent, cu);
18867         if (TYPE_TAG_NAME (parent_type) != NULL)
18868           return TYPE_TAG_NAME (parent_type);
18869         else
18870           /* An anonymous structure is only allowed non-static data
18871              members; no typedefs, no member functions, et cetera.
18872              So it does not need a prefix.  */
18873           return "";
18874       case DW_TAG_compile_unit:
18875       case DW_TAG_partial_unit:
18876         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
18877         if (cu->language == language_cplus
18878             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18879             && die->child != NULL
18880             && (die->tag == DW_TAG_class_type
18881                 || die->tag == DW_TAG_structure_type
18882                 || die->tag == DW_TAG_union_type))
18883           {
18884             char *name = guess_full_die_structure_name (die, cu);
18885             if (name != NULL)
18886               return name;
18887           }
18888         return "";
18889       case DW_TAG_enumeration_type:
18890         parent_type = read_type_die (parent, cu);
18891         if (TYPE_DECLARED_CLASS (parent_type))
18892           {
18893             if (TYPE_TAG_NAME (parent_type) != NULL)
18894               return TYPE_TAG_NAME (parent_type);
18895             return "";
18896           }
18897         /* Fall through.  */
18898       default:
18899         return determine_prefix (parent, cu);
18900       }
18901 }
18902
18903 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
18904    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
18905    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
18906    an obconcat, otherwise allocate storage for the result.  The CU argument is
18907    used to determine the language and hence, the appropriate separator.  */
18908
18909 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
18910
18911 static char *
18912 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
18913                  int physname, struct dwarf2_cu *cu)
18914 {
18915   const char *lead = "";
18916   const char *sep;
18917
18918   if (suffix == NULL || suffix[0] == '\0'
18919       || prefix == NULL || prefix[0] == '\0')
18920     sep = "";
18921   else if (cu->language == language_java)
18922     sep = ".";
18923   else if (cu->language == language_fortran && physname)
18924     {
18925       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
18926          DW_AT_MIPS_linkage_name is preferred and used instead.  */
18927
18928       lead = "__";
18929       sep = "_MOD_";
18930     }
18931   else
18932     sep = "::";
18933
18934   if (prefix == NULL)
18935     prefix = "";
18936   if (suffix == NULL)
18937     suffix = "";
18938
18939   if (obs == NULL)
18940     {
18941       char *retval
18942         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
18943
18944       strcpy (retval, lead);
18945       strcat (retval, prefix);
18946       strcat (retval, sep);
18947       strcat (retval, suffix);
18948       return retval;
18949     }
18950   else
18951     {
18952       /* We have an obstack.  */
18953       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
18954     }
18955 }
18956
18957 /* Return sibling of die, NULL if no sibling.  */
18958
18959 static struct die_info *
18960 sibling_die (struct die_info *die)
18961 {
18962   return die->sibling;
18963 }
18964
18965 /* Get name of a die, return NULL if not found.  */
18966
18967 static const char *
18968 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
18969                           struct obstack *obstack)
18970 {
18971   if (name && cu->language == language_cplus)
18972     {
18973       char *canon_name = cp_canonicalize_string (name);
18974
18975       if (canon_name != NULL)
18976         {
18977           if (strcmp (canon_name, name) != 0)
18978             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
18979           xfree (canon_name);
18980         }
18981     }
18982
18983   return name;
18984 }
18985
18986 /* Get name of a die, return NULL if not found.  */
18987
18988 static const char *
18989 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
18990 {
18991   struct attribute *attr;
18992
18993   attr = dwarf2_attr (die, DW_AT_name, cu);
18994   if ((!attr || !DW_STRING (attr))
18995       && die->tag != DW_TAG_class_type
18996       && die->tag != DW_TAG_interface_type
18997       && die->tag != DW_TAG_structure_type
18998       && die->tag != DW_TAG_union_type)
18999     return NULL;
19000
19001   switch (die->tag)
19002     {
19003     case DW_TAG_compile_unit:
19004     case DW_TAG_partial_unit:
19005       /* Compilation units have a DW_AT_name that is a filename, not
19006          a source language identifier.  */
19007     case DW_TAG_enumeration_type:
19008     case DW_TAG_enumerator:
19009       /* These tags always have simple identifiers already; no need
19010          to canonicalize them.  */
19011       return DW_STRING (attr);
19012
19013     case DW_TAG_subprogram:
19014       /* Java constructors will all be named "<init>", so return
19015          the class name when we see this special case.  */
19016       if (cu->language == language_java
19017           && DW_STRING (attr) != NULL
19018           && strcmp (DW_STRING (attr), "<init>") == 0)
19019         {
19020           struct dwarf2_cu *spec_cu = cu;
19021           struct die_info *spec_die;
19022
19023           /* GCJ will output '<init>' for Java constructor names.
19024              For this special case, return the name of the parent class.  */
19025
19026           /* GCJ may output subprogram DIEs with AT_specification set.
19027              If so, use the name of the specified DIE.  */
19028           spec_die = die_specification (die, &spec_cu);
19029           if (spec_die != NULL)
19030             return dwarf2_name (spec_die, spec_cu);
19031
19032           do
19033             {
19034               die = die->parent;
19035               if (die->tag == DW_TAG_class_type)
19036                 return dwarf2_name (die, cu);
19037             }
19038           while (die->tag != DW_TAG_compile_unit
19039                  && die->tag != DW_TAG_partial_unit);
19040         }
19041       break;
19042
19043     case DW_TAG_class_type:
19044     case DW_TAG_interface_type:
19045     case DW_TAG_structure_type:
19046     case DW_TAG_union_type:
19047       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
19048          structures or unions.  These were of the form "._%d" in GCC 4.1,
19049          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
19050          and GCC 4.4.  We work around this problem by ignoring these.  */
19051       if (attr && DW_STRING (attr)
19052           && (strncmp (DW_STRING (attr), "._", 2) == 0
19053               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
19054         return NULL;
19055
19056       /* GCC might emit a nameless typedef that has a linkage name.  See
19057          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19058       if (!attr || DW_STRING (attr) == NULL)
19059         {
19060           char *demangled = NULL;
19061
19062           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
19063           if (attr == NULL)
19064             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
19065
19066           if (attr == NULL || DW_STRING (attr) == NULL)
19067             return NULL;
19068
19069           /* Avoid demangling DW_STRING (attr) the second time on a second
19070              call for the same DIE.  */
19071           if (!DW_STRING_IS_CANONICAL (attr))
19072             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
19073
19074           if (demangled)
19075             {
19076               char *base;
19077
19078               /* FIXME: we already did this for the partial symbol... */
19079               DW_STRING (attr)
19080                 = obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19081                                  demangled, strlen (demangled));
19082               DW_STRING_IS_CANONICAL (attr) = 1;
19083               xfree (demangled);
19084
19085               /* Strip any leading namespaces/classes, keep only the base name.
19086                  DW_AT_name for named DIEs does not contain the prefixes.  */
19087               base = strrchr (DW_STRING (attr), ':');
19088               if (base && base > DW_STRING (attr) && base[-1] == ':')
19089                 return &base[1];
19090               else
19091                 return DW_STRING (attr);
19092             }
19093         }
19094       break;
19095
19096     default:
19097       break;
19098     }
19099
19100   if (!DW_STRING_IS_CANONICAL (attr))
19101     {
19102       DW_STRING (attr)
19103         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
19104                                     &cu->objfile->per_bfd->storage_obstack);
19105       DW_STRING_IS_CANONICAL (attr) = 1;
19106     }
19107   return DW_STRING (attr);
19108 }
19109
19110 /* Return the die that this die in an extension of, or NULL if there
19111    is none.  *EXT_CU is the CU containing DIE on input, and the CU
19112    containing the return value on output.  */
19113
19114 static struct die_info *
19115 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
19116 {
19117   struct attribute *attr;
19118
19119   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
19120   if (attr == NULL)
19121     return NULL;
19122
19123   return follow_die_ref (die, attr, ext_cu);
19124 }
19125
19126 /* Convert a DIE tag into its string name.  */
19127
19128 static const char *
19129 dwarf_tag_name (unsigned tag)
19130 {
19131   const char *name = get_DW_TAG_name (tag);
19132
19133   if (name == NULL)
19134     return "DW_TAG_<unknown>";
19135
19136   return name;
19137 }
19138
19139 /* Convert a DWARF attribute code into its string name.  */
19140
19141 static const char *
19142 dwarf_attr_name (unsigned attr)
19143 {
19144   const char *name;
19145
19146 #ifdef MIPS /* collides with DW_AT_HP_block_index */
19147   if (attr == DW_AT_MIPS_fde)
19148     return "DW_AT_MIPS_fde";
19149 #else
19150   if (attr == DW_AT_HP_block_index)
19151     return "DW_AT_HP_block_index";
19152 #endif
19153
19154   name = get_DW_AT_name (attr);
19155
19156   if (name == NULL)
19157     return "DW_AT_<unknown>";
19158
19159   return name;
19160 }
19161
19162 /* Convert a DWARF value form code into its string name.  */
19163
19164 static const char *
19165 dwarf_form_name (unsigned form)
19166 {
19167   const char *name = get_DW_FORM_name (form);
19168
19169   if (name == NULL)
19170     return "DW_FORM_<unknown>";
19171
19172   return name;
19173 }
19174
19175 static char *
19176 dwarf_bool_name (unsigned mybool)
19177 {
19178   if (mybool)
19179     return "TRUE";
19180   else
19181     return "FALSE";
19182 }
19183
19184 /* Convert a DWARF type code into its string name.  */
19185
19186 static const char *
19187 dwarf_type_encoding_name (unsigned enc)
19188 {
19189   const char *name = get_DW_ATE_name (enc);
19190
19191   if (name == NULL)
19192     return "DW_ATE_<unknown>";
19193
19194   return name;
19195 }
19196
19197 static void
19198 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
19199 {
19200   unsigned int i;
19201
19202   print_spaces (indent, f);
19203   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
19204            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
19205
19206   if (die->parent != NULL)
19207     {
19208       print_spaces (indent, f);
19209       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
19210                           die->parent->offset.sect_off);
19211     }
19212
19213   print_spaces (indent, f);
19214   fprintf_unfiltered (f, "  has children: %s\n",
19215            dwarf_bool_name (die->child != NULL));
19216
19217   print_spaces (indent, f);
19218   fprintf_unfiltered (f, "  attributes:\n");
19219
19220   for (i = 0; i < die->num_attrs; ++i)
19221     {
19222       print_spaces (indent, f);
19223       fprintf_unfiltered (f, "    %s (%s) ",
19224                dwarf_attr_name (die->attrs[i].name),
19225                dwarf_form_name (die->attrs[i].form));
19226
19227       switch (die->attrs[i].form)
19228         {
19229         case DW_FORM_addr:
19230         case DW_FORM_GNU_addr_index:
19231           fprintf_unfiltered (f, "address: ");
19232           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
19233           break;
19234         case DW_FORM_block2:
19235         case DW_FORM_block4:
19236         case DW_FORM_block:
19237         case DW_FORM_block1:
19238           fprintf_unfiltered (f, "block: size %s",
19239                               pulongest (DW_BLOCK (&die->attrs[i])->size));
19240           break;
19241         case DW_FORM_exprloc:
19242           fprintf_unfiltered (f, "expression: size %s",
19243                               pulongest (DW_BLOCK (&die->attrs[i])->size));
19244           break;
19245         case DW_FORM_ref_addr:
19246           fprintf_unfiltered (f, "ref address: ");
19247           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
19248           break;
19249         case DW_FORM_GNU_ref_alt:
19250           fprintf_unfiltered (f, "alt ref address: ");
19251           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
19252           break;
19253         case DW_FORM_ref1:
19254         case DW_FORM_ref2:
19255         case DW_FORM_ref4:
19256         case DW_FORM_ref8:
19257         case DW_FORM_ref_udata:
19258           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
19259                               (long) (DW_UNSND (&die->attrs[i])));
19260           break;
19261         case DW_FORM_data1:
19262         case DW_FORM_data2:
19263         case DW_FORM_data4:
19264         case DW_FORM_data8:
19265         case DW_FORM_udata:
19266         case DW_FORM_sdata:
19267           fprintf_unfiltered (f, "constant: %s",
19268                               pulongest (DW_UNSND (&die->attrs[i])));
19269           break;
19270         case DW_FORM_sec_offset:
19271           fprintf_unfiltered (f, "section offset: %s",
19272                               pulongest (DW_UNSND (&die->attrs[i])));
19273           break;
19274         case DW_FORM_ref_sig8:
19275           fprintf_unfiltered (f, "signature: %s",
19276                               hex_string (DW_SIGNATURE (&die->attrs[i])));
19277           break;
19278         case DW_FORM_string:
19279         case DW_FORM_strp:
19280         case DW_FORM_GNU_str_index:
19281         case DW_FORM_GNU_strp_alt:
19282           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
19283                    DW_STRING (&die->attrs[i])
19284                    ? DW_STRING (&die->attrs[i]) : "",
19285                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
19286           break;
19287         case DW_FORM_flag:
19288           if (DW_UNSND (&die->attrs[i]))
19289             fprintf_unfiltered (f, "flag: TRUE");
19290           else
19291             fprintf_unfiltered (f, "flag: FALSE");
19292           break;
19293         case DW_FORM_flag_present:
19294           fprintf_unfiltered (f, "flag: TRUE");
19295           break;
19296         case DW_FORM_indirect:
19297           /* The reader will have reduced the indirect form to
19298              the "base form" so this form should not occur.  */
19299           fprintf_unfiltered (f, 
19300                               "unexpected attribute form: DW_FORM_indirect");
19301           break;
19302         default:
19303           fprintf_unfiltered (f, "unsupported attribute form: %d.",
19304                    die->attrs[i].form);
19305           break;
19306         }
19307       fprintf_unfiltered (f, "\n");
19308     }
19309 }
19310
19311 static void
19312 dump_die_for_error (struct die_info *die)
19313 {
19314   dump_die_shallow (gdb_stderr, 0, die);
19315 }
19316
19317 static void
19318 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
19319 {
19320   int indent = level * 4;
19321
19322   gdb_assert (die != NULL);
19323
19324   if (level >= max_level)
19325     return;
19326
19327   dump_die_shallow (f, indent, die);
19328
19329   if (die->child != NULL)
19330     {
19331       print_spaces (indent, f);
19332       fprintf_unfiltered (f, "  Children:");
19333       if (level + 1 < max_level)
19334         {
19335           fprintf_unfiltered (f, "\n");
19336           dump_die_1 (f, level + 1, max_level, die->child);
19337         }
19338       else
19339         {
19340           fprintf_unfiltered (f,
19341                               " [not printed, max nesting level reached]\n");
19342         }
19343     }
19344
19345   if (die->sibling != NULL && level > 0)
19346     {
19347       dump_die_1 (f, level, max_level, die->sibling);
19348     }
19349 }
19350
19351 /* This is called from the pdie macro in gdbinit.in.
19352    It's not static so gcc will keep a copy callable from gdb.  */
19353
19354 void
19355 dump_die (struct die_info *die, int max_level)
19356 {
19357   dump_die_1 (gdb_stdlog, 0, max_level, die);
19358 }
19359
19360 static void
19361 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
19362 {
19363   void **slot;
19364
19365   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
19366                                    INSERT);
19367
19368   *slot = die;
19369 }
19370
19371 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
19372    required kind.  */
19373
19374 static sect_offset
19375 dwarf2_get_ref_die_offset (const struct attribute *attr)
19376 {
19377   sect_offset retval = { DW_UNSND (attr) };
19378
19379   if (attr_form_is_ref (attr))
19380     return retval;
19381
19382   retval.sect_off = 0;
19383   complaint (&symfile_complaints,
19384              _("unsupported die ref attribute form: '%s'"),
19385              dwarf_form_name (attr->form));
19386   return retval;
19387 }
19388
19389 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
19390  * the value held by the attribute is not constant.  */
19391
19392 static LONGEST
19393 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
19394 {
19395   if (attr->form == DW_FORM_sdata)
19396     return DW_SND (attr);
19397   else if (attr->form == DW_FORM_udata
19398            || attr->form == DW_FORM_data1
19399            || attr->form == DW_FORM_data2
19400            || attr->form == DW_FORM_data4
19401            || attr->form == DW_FORM_data8)
19402     return DW_UNSND (attr);
19403   else
19404     {
19405       complaint (&symfile_complaints,
19406                  _("Attribute value is not a constant (%s)"),
19407                  dwarf_form_name (attr->form));
19408       return default_value;
19409     }
19410 }
19411
19412 /* Follow reference or signature attribute ATTR of SRC_DIE.
19413    On entry *REF_CU is the CU of SRC_DIE.
19414    On exit *REF_CU is the CU of the result.  */
19415
19416 static struct die_info *
19417 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
19418                        struct dwarf2_cu **ref_cu)
19419 {
19420   struct die_info *die;
19421
19422   if (attr_form_is_ref (attr))
19423     die = follow_die_ref (src_die, attr, ref_cu);
19424   else if (attr->form == DW_FORM_ref_sig8)
19425     die = follow_die_sig (src_die, attr, ref_cu);
19426   else
19427     {
19428       dump_die_for_error (src_die);
19429       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
19430              objfile_name ((*ref_cu)->objfile));
19431     }
19432
19433   return die;
19434 }
19435
19436 /* Follow reference OFFSET.
19437    On entry *REF_CU is the CU of the source die referencing OFFSET.
19438    On exit *REF_CU is the CU of the result.
19439    Returns NULL if OFFSET is invalid.  */
19440
19441 static struct die_info *
19442 follow_die_offset (sect_offset offset, int offset_in_dwz,
19443                    struct dwarf2_cu **ref_cu)
19444 {
19445   struct die_info temp_die;
19446   struct dwarf2_cu *target_cu, *cu = *ref_cu;
19447
19448   gdb_assert (cu->per_cu != NULL);
19449
19450   target_cu = cu;
19451
19452   if (cu->per_cu->is_debug_types)
19453     {
19454       /* .debug_types CUs cannot reference anything outside their CU.
19455          If they need to, they have to reference a signatured type via
19456          DW_FORM_ref_sig8.  */
19457       if (! offset_in_cu_p (&cu->header, offset))
19458         return NULL;
19459     }
19460   else if (offset_in_dwz != cu->per_cu->is_dwz
19461            || ! offset_in_cu_p (&cu->header, offset))
19462     {
19463       struct dwarf2_per_cu_data *per_cu;
19464
19465       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
19466                                                  cu->objfile);
19467
19468       /* If necessary, add it to the queue and load its DIEs.  */
19469       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
19470         load_full_comp_unit (per_cu, cu->language);
19471
19472       target_cu = per_cu->cu;
19473     }
19474   else if (cu->dies == NULL)
19475     {
19476       /* We're loading full DIEs during partial symbol reading.  */
19477       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
19478       load_full_comp_unit (cu->per_cu, language_minimal);
19479     }
19480
19481   *ref_cu = target_cu;
19482   temp_die.offset = offset;
19483   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
19484 }
19485
19486 /* Follow reference attribute ATTR of SRC_DIE.
19487    On entry *REF_CU is the CU of SRC_DIE.
19488    On exit *REF_CU is the CU of the result.  */
19489
19490 static struct die_info *
19491 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
19492                 struct dwarf2_cu **ref_cu)
19493 {
19494   sect_offset offset = dwarf2_get_ref_die_offset (attr);
19495   struct dwarf2_cu *cu = *ref_cu;
19496   struct die_info *die;
19497
19498   die = follow_die_offset (offset,
19499                            (attr->form == DW_FORM_GNU_ref_alt
19500                             || cu->per_cu->is_dwz),
19501                            ref_cu);
19502   if (!die)
19503     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
19504            "at 0x%x [in module %s]"),
19505            offset.sect_off, src_die->offset.sect_off,
19506            objfile_name (cu->objfile));
19507
19508   return die;
19509 }
19510
19511 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
19512    Returned value is intended for DW_OP_call*.  Returned
19513    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
19514
19515 struct dwarf2_locexpr_baton
19516 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
19517                                struct dwarf2_per_cu_data *per_cu,
19518                                CORE_ADDR (*get_frame_pc) (void *baton),
19519                                void *baton)
19520 {
19521   struct dwarf2_cu *cu;
19522   struct die_info *die;
19523   struct attribute *attr;
19524   struct dwarf2_locexpr_baton retval;
19525
19526   dw2_setup (per_cu->objfile);
19527
19528   if (per_cu->cu == NULL)
19529     load_cu (per_cu);
19530   cu = per_cu->cu;
19531
19532   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
19533   if (!die)
19534     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
19535            offset.sect_off, objfile_name (per_cu->objfile));
19536
19537   attr = dwarf2_attr (die, DW_AT_location, cu);
19538   if (!attr)
19539     {
19540       /* DWARF: "If there is no such attribute, then there is no effect.".
19541          DATA is ignored if SIZE is 0.  */
19542
19543       retval.data = NULL;
19544       retval.size = 0;
19545     }
19546   else if (attr_form_is_section_offset (attr))
19547     {
19548       struct dwarf2_loclist_baton loclist_baton;
19549       CORE_ADDR pc = (*get_frame_pc) (baton);
19550       size_t size;
19551
19552       fill_in_loclist_baton (cu, &loclist_baton, attr);
19553
19554       retval.data = dwarf2_find_location_expression (&loclist_baton,
19555                                                      &size, pc);
19556       retval.size = size;
19557     }
19558   else
19559     {
19560       if (!attr_form_is_block (attr))
19561         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
19562                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
19563                offset.sect_off, objfile_name (per_cu->objfile));
19564
19565       retval.data = DW_BLOCK (attr)->data;
19566       retval.size = DW_BLOCK (attr)->size;
19567     }
19568   retval.per_cu = cu->per_cu;
19569
19570   age_cached_comp_units ();
19571
19572   return retval;
19573 }
19574
19575 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
19576    offset.  */
19577
19578 struct dwarf2_locexpr_baton
19579 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
19580                              struct dwarf2_per_cu_data *per_cu,
19581                              CORE_ADDR (*get_frame_pc) (void *baton),
19582                              void *baton)
19583 {
19584   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
19585
19586   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
19587 }
19588
19589 /* Write a constant of a given type as target-ordered bytes into
19590    OBSTACK.  */
19591
19592 static const gdb_byte *
19593 write_constant_as_bytes (struct obstack *obstack,
19594                          enum bfd_endian byte_order,
19595                          struct type *type,
19596                          ULONGEST value,
19597                          LONGEST *len)
19598 {
19599   gdb_byte *result;
19600
19601   *len = TYPE_LENGTH (type);
19602   result = obstack_alloc (obstack, *len);
19603   store_unsigned_integer (result, *len, byte_order, value);
19604
19605   return result;
19606 }
19607
19608 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
19609    pointer to the constant bytes and set LEN to the length of the
19610    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
19611    does not have a DW_AT_const_value, return NULL.  */
19612
19613 const gdb_byte *
19614 dwarf2_fetch_constant_bytes (sect_offset offset,
19615                              struct dwarf2_per_cu_data *per_cu,
19616                              struct obstack *obstack,
19617                              LONGEST *len)
19618 {
19619   struct dwarf2_cu *cu;
19620   struct die_info *die;
19621   struct attribute *attr;
19622   const gdb_byte *result = NULL;
19623   struct type *type;
19624   LONGEST value;
19625   enum bfd_endian byte_order;
19626
19627   dw2_setup (per_cu->objfile);
19628
19629   if (per_cu->cu == NULL)
19630     load_cu (per_cu);
19631   cu = per_cu->cu;
19632
19633   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
19634   if (!die)
19635     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
19636            offset.sect_off, objfile_name (per_cu->objfile));
19637
19638
19639   attr = dwarf2_attr (die, DW_AT_const_value, cu);
19640   if (attr == NULL)
19641     return NULL;
19642
19643   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
19644                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19645
19646   switch (attr->form)
19647     {
19648     case DW_FORM_addr:
19649     case DW_FORM_GNU_addr_index:
19650       {
19651         gdb_byte *tem;
19652
19653         *len = cu->header.addr_size;
19654         tem = obstack_alloc (obstack, *len);
19655         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
19656         result = tem;
19657       }
19658       break;
19659     case DW_FORM_string:
19660     case DW_FORM_strp:
19661     case DW_FORM_GNU_str_index:
19662     case DW_FORM_GNU_strp_alt:
19663       /* DW_STRING is already allocated on the objfile obstack, point
19664          directly to it.  */
19665       result = (const gdb_byte *) DW_STRING (attr);
19666       *len = strlen (DW_STRING (attr));
19667       break;
19668     case DW_FORM_block1:
19669     case DW_FORM_block2:
19670     case DW_FORM_block4:
19671     case DW_FORM_block:
19672     case DW_FORM_exprloc:
19673       result = DW_BLOCK (attr)->data;
19674       *len = DW_BLOCK (attr)->size;
19675       break;
19676
19677       /* The DW_AT_const_value attributes are supposed to carry the
19678          symbol's value "represented as it would be on the target
19679          architecture."  By the time we get here, it's already been
19680          converted to host endianness, so we just need to sign- or
19681          zero-extend it as appropriate.  */
19682     case DW_FORM_data1:
19683       type = die_type (die, cu);
19684       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
19685       if (result == NULL)
19686         result = write_constant_as_bytes (obstack, byte_order,
19687                                           type, value, len);
19688       break;
19689     case DW_FORM_data2:
19690       type = die_type (die, cu);
19691       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
19692       if (result == NULL)
19693         result = write_constant_as_bytes (obstack, byte_order,
19694                                           type, value, len);
19695       break;
19696     case DW_FORM_data4:
19697       type = die_type (die, cu);
19698       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
19699       if (result == NULL)
19700         result = write_constant_as_bytes (obstack, byte_order,
19701                                           type, value, len);
19702       break;
19703     case DW_FORM_data8:
19704       type = die_type (die, cu);
19705       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
19706       if (result == NULL)
19707         result = write_constant_as_bytes (obstack, byte_order,
19708                                           type, value, len);
19709       break;
19710
19711     case DW_FORM_sdata:
19712       type = die_type (die, cu);
19713       result = write_constant_as_bytes (obstack, byte_order,
19714                                         type, DW_SND (attr), len);
19715       break;
19716
19717     case DW_FORM_udata:
19718       type = die_type (die, cu);
19719       result = write_constant_as_bytes (obstack, byte_order,
19720                                         type, DW_UNSND (attr), len);
19721       break;
19722
19723     default:
19724       complaint (&symfile_complaints,
19725                  _("unsupported const value attribute form: '%s'"),
19726                  dwarf_form_name (attr->form));
19727       break;
19728     }
19729
19730   return result;
19731 }
19732
19733 /* Return the type of the DIE at DIE_OFFSET in the CU named by
19734    PER_CU.  */
19735
19736 struct type *
19737 dwarf2_get_die_type (cu_offset die_offset,
19738                      struct dwarf2_per_cu_data *per_cu)
19739 {
19740   sect_offset die_offset_sect;
19741
19742   dw2_setup (per_cu->objfile);
19743
19744   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
19745   return get_die_type_at_offset (die_offset_sect, per_cu);
19746 }
19747
19748 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
19749    On entry *REF_CU is the CU of SRC_DIE.
19750    On exit *REF_CU is the CU of the result.
19751    Returns NULL if the referenced DIE isn't found.  */
19752
19753 static struct die_info *
19754 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
19755                   struct dwarf2_cu **ref_cu)
19756 {
19757   struct objfile *objfile = (*ref_cu)->objfile;
19758   struct die_info temp_die;
19759   struct dwarf2_cu *sig_cu;
19760   struct die_info *die;
19761
19762   /* While it might be nice to assert sig_type->type == NULL here,
19763      we can get here for DW_AT_imported_declaration where we need
19764      the DIE not the type.  */
19765
19766   /* If necessary, add it to the queue and load its DIEs.  */
19767
19768   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
19769     read_signatured_type (sig_type);
19770
19771   sig_cu = sig_type->per_cu.cu;
19772   gdb_assert (sig_cu != NULL);
19773   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
19774   temp_die.offset = sig_type->type_offset_in_section;
19775   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
19776                              temp_die.offset.sect_off);
19777   if (die)
19778     {
19779       /* For .gdb_index version 7 keep track of included TUs.
19780          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
19781       if (dwarf2_per_objfile->index_table != NULL
19782           && dwarf2_per_objfile->index_table->version <= 7)
19783         {
19784           VEC_safe_push (dwarf2_per_cu_ptr,
19785                          (*ref_cu)->per_cu->imported_symtabs,
19786                          sig_cu->per_cu);
19787         }
19788
19789       *ref_cu = sig_cu;
19790       return die;
19791     }
19792
19793   return NULL;
19794 }
19795
19796 /* Follow signatured type referenced by ATTR in SRC_DIE.
19797    On entry *REF_CU is the CU of SRC_DIE.
19798    On exit *REF_CU is the CU of the result.
19799    The result is the DIE of the type.
19800    If the referenced type cannot be found an error is thrown.  */
19801
19802 static struct die_info *
19803 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
19804                 struct dwarf2_cu **ref_cu)
19805 {
19806   ULONGEST signature = DW_SIGNATURE (attr);
19807   struct signatured_type *sig_type;
19808   struct die_info *die;
19809
19810   gdb_assert (attr->form == DW_FORM_ref_sig8);
19811
19812   sig_type = lookup_signatured_type (*ref_cu, signature);
19813   /* sig_type will be NULL if the signatured type is missing from
19814      the debug info.  */
19815   if (sig_type == NULL)
19816     {
19817       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
19818                " from DIE at 0x%x [in module %s]"),
19819              hex_string (signature), src_die->offset.sect_off,
19820              objfile_name ((*ref_cu)->objfile));
19821     }
19822
19823   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
19824   if (die == NULL)
19825     {
19826       dump_die_for_error (src_die);
19827       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
19828                " from DIE at 0x%x [in module %s]"),
19829              hex_string (signature), src_die->offset.sect_off,
19830              objfile_name ((*ref_cu)->objfile));
19831     }
19832
19833   return die;
19834 }
19835
19836 /* Get the type specified by SIGNATURE referenced in DIE/CU,
19837    reading in and processing the type unit if necessary.  */
19838
19839 static struct type *
19840 get_signatured_type (struct die_info *die, ULONGEST signature,
19841                      struct dwarf2_cu *cu)
19842 {
19843   struct signatured_type *sig_type;
19844   struct dwarf2_cu *type_cu;
19845   struct die_info *type_die;
19846   struct type *type;
19847
19848   sig_type = lookup_signatured_type (cu, signature);
19849   /* sig_type will be NULL if the signatured type is missing from
19850      the debug info.  */
19851   if (sig_type == NULL)
19852     {
19853       complaint (&symfile_complaints,
19854                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
19855                    " from DIE at 0x%x [in module %s]"),
19856                  hex_string (signature), die->offset.sect_off,
19857                  objfile_name (dwarf2_per_objfile->objfile));
19858       return build_error_marker_type (cu, die);
19859     }
19860
19861   /* If we already know the type we're done.  */
19862   if (sig_type->type != NULL)
19863     return sig_type->type;
19864
19865   type_cu = cu;
19866   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
19867   if (type_die != NULL)
19868     {
19869       /* N.B. We need to call get_die_type to ensure only one type for this DIE
19870          is created.  This is important, for example, because for c++ classes
19871          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
19872       type = read_type_die (type_die, type_cu);
19873       if (type == NULL)
19874         {
19875           complaint (&symfile_complaints,
19876                      _("Dwarf Error: Cannot build signatured type %s"
19877                        " referenced from DIE at 0x%x [in module %s]"),
19878                      hex_string (signature), die->offset.sect_off,
19879                      objfile_name (dwarf2_per_objfile->objfile));
19880           type = build_error_marker_type (cu, die);
19881         }
19882     }
19883   else
19884     {
19885       complaint (&symfile_complaints,
19886                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
19887                    " from DIE at 0x%x [in module %s]"),
19888                  hex_string (signature), die->offset.sect_off,
19889                  objfile_name (dwarf2_per_objfile->objfile));
19890       type = build_error_marker_type (cu, die);
19891     }
19892   sig_type->type = type;
19893
19894   return type;
19895 }
19896
19897 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
19898    reading in and processing the type unit if necessary.  */
19899
19900 static struct type *
19901 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
19902                           struct dwarf2_cu *cu) /* ARI: editCase function */
19903 {
19904   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
19905   if (attr_form_is_ref (attr))
19906     {
19907       struct dwarf2_cu *type_cu = cu;
19908       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
19909
19910       return read_type_die (type_die, type_cu);
19911     }
19912   else if (attr->form == DW_FORM_ref_sig8)
19913     {
19914       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
19915     }
19916   else
19917     {
19918       complaint (&symfile_complaints,
19919                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
19920                    " at 0x%x [in module %s]"),
19921                  dwarf_form_name (attr->form), die->offset.sect_off,
19922                  objfile_name (dwarf2_per_objfile->objfile));
19923       return build_error_marker_type (cu, die);
19924     }
19925 }
19926
19927 /* Load the DIEs associated with type unit PER_CU into memory.  */
19928
19929 static void
19930 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
19931 {
19932   struct signatured_type *sig_type;
19933
19934   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
19935   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
19936
19937   /* We have the per_cu, but we need the signatured_type.
19938      Fortunately this is an easy translation.  */
19939   gdb_assert (per_cu->is_debug_types);
19940   sig_type = (struct signatured_type *) per_cu;
19941
19942   gdb_assert (per_cu->cu == NULL);
19943
19944   read_signatured_type (sig_type);
19945
19946   gdb_assert (per_cu->cu != NULL);
19947 }
19948
19949 /* die_reader_func for read_signatured_type.
19950    This is identical to load_full_comp_unit_reader,
19951    but is kept separate for now.  */
19952
19953 static void
19954 read_signatured_type_reader (const struct die_reader_specs *reader,
19955                              const gdb_byte *info_ptr,
19956                              struct die_info *comp_unit_die,
19957                              int has_children,
19958                              void *data)
19959 {
19960   struct dwarf2_cu *cu = reader->cu;
19961
19962   gdb_assert (cu->die_hash == NULL);
19963   cu->die_hash =
19964     htab_create_alloc_ex (cu->header.length / 12,
19965                           die_hash,
19966                           die_eq,
19967                           NULL,
19968                           &cu->comp_unit_obstack,
19969                           hashtab_obstack_allocate,
19970                           dummy_obstack_deallocate);
19971
19972   if (has_children)
19973     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
19974                                                   &info_ptr, comp_unit_die);
19975   cu->dies = comp_unit_die;
19976   /* comp_unit_die is not stored in die_hash, no need.  */
19977
19978   /* We try not to read any attributes in this function, because not
19979      all CUs needed for references have been loaded yet, and symbol
19980      table processing isn't initialized.  But we have to set the CU language,
19981      or we won't be able to build types correctly.
19982      Similarly, if we do not read the producer, we can not apply
19983      producer-specific interpretation.  */
19984   prepare_one_comp_unit (cu, cu->dies, language_minimal);
19985 }
19986
19987 /* Read in a signatured type and build its CU and DIEs.
19988    If the type is a stub for the real type in a DWO file,
19989    read in the real type from the DWO file as well.  */
19990
19991 static void
19992 read_signatured_type (struct signatured_type *sig_type)
19993 {
19994   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
19995
19996   gdb_assert (per_cu->is_debug_types);
19997   gdb_assert (per_cu->cu == NULL);
19998
19999   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
20000                            read_signatured_type_reader, NULL);
20001   sig_type->per_cu.tu_read = 1;
20002 }
20003
20004 /* Decode simple location descriptions.
20005    Given a pointer to a dwarf block that defines a location, compute
20006    the location and return the value.
20007
20008    NOTE drow/2003-11-18: This function is called in two situations
20009    now: for the address of static or global variables (partial symbols
20010    only) and for offsets into structures which are expected to be
20011    (more or less) constant.  The partial symbol case should go away,
20012    and only the constant case should remain.  That will let this
20013    function complain more accurately.  A few special modes are allowed
20014    without complaint for global variables (for instance, global
20015    register values and thread-local values).
20016
20017    A location description containing no operations indicates that the
20018    object is optimized out.  The return value is 0 for that case.
20019    FIXME drow/2003-11-16: No callers check for this case any more; soon all
20020    callers will only want a very basic result and this can become a
20021    complaint.
20022
20023    Note that stack[0] is unused except as a default error return.  */
20024
20025 static CORE_ADDR
20026 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
20027 {
20028   struct objfile *objfile = cu->objfile;
20029   size_t i;
20030   size_t size = blk->size;
20031   const gdb_byte *data = blk->data;
20032   CORE_ADDR stack[64];
20033   int stacki;
20034   unsigned int bytes_read, unsnd;
20035   gdb_byte op;
20036
20037   i = 0;
20038   stacki = 0;
20039   stack[stacki] = 0;
20040   stack[++stacki] = 0;
20041
20042   while (i < size)
20043     {
20044       op = data[i++];
20045       switch (op)
20046         {
20047         case DW_OP_lit0:
20048         case DW_OP_lit1:
20049         case DW_OP_lit2:
20050         case DW_OP_lit3:
20051         case DW_OP_lit4:
20052         case DW_OP_lit5:
20053         case DW_OP_lit6:
20054         case DW_OP_lit7:
20055         case DW_OP_lit8:
20056         case DW_OP_lit9:
20057         case DW_OP_lit10:
20058         case DW_OP_lit11:
20059         case DW_OP_lit12:
20060         case DW_OP_lit13:
20061         case DW_OP_lit14:
20062         case DW_OP_lit15:
20063         case DW_OP_lit16:
20064         case DW_OP_lit17:
20065         case DW_OP_lit18:
20066         case DW_OP_lit19:
20067         case DW_OP_lit20:
20068         case DW_OP_lit21:
20069         case DW_OP_lit22:
20070         case DW_OP_lit23:
20071         case DW_OP_lit24:
20072         case DW_OP_lit25:
20073         case DW_OP_lit26:
20074         case DW_OP_lit27:
20075         case DW_OP_lit28:
20076         case DW_OP_lit29:
20077         case DW_OP_lit30:
20078         case DW_OP_lit31:
20079           stack[++stacki] = op - DW_OP_lit0;
20080           break;
20081
20082         case DW_OP_reg0:
20083         case DW_OP_reg1:
20084         case DW_OP_reg2:
20085         case DW_OP_reg3:
20086         case DW_OP_reg4:
20087         case DW_OP_reg5:
20088         case DW_OP_reg6:
20089         case DW_OP_reg7:
20090         case DW_OP_reg8:
20091         case DW_OP_reg9:
20092         case DW_OP_reg10:
20093         case DW_OP_reg11:
20094         case DW_OP_reg12:
20095         case DW_OP_reg13:
20096         case DW_OP_reg14:
20097         case DW_OP_reg15:
20098         case DW_OP_reg16:
20099         case DW_OP_reg17:
20100         case DW_OP_reg18:
20101         case DW_OP_reg19:
20102         case DW_OP_reg20:
20103         case DW_OP_reg21:
20104         case DW_OP_reg22:
20105         case DW_OP_reg23:
20106         case DW_OP_reg24:
20107         case DW_OP_reg25:
20108         case DW_OP_reg26:
20109         case DW_OP_reg27:
20110         case DW_OP_reg28:
20111         case DW_OP_reg29:
20112         case DW_OP_reg30:
20113         case DW_OP_reg31:
20114           stack[++stacki] = op - DW_OP_reg0;
20115           if (i < size)
20116             dwarf2_complex_location_expr_complaint ();
20117           break;
20118
20119         case DW_OP_regx:
20120           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
20121           i += bytes_read;
20122           stack[++stacki] = unsnd;
20123           if (i < size)
20124             dwarf2_complex_location_expr_complaint ();
20125           break;
20126
20127         case DW_OP_addr:
20128           stack[++stacki] = read_address (objfile->obfd, &data[i],
20129                                           cu, &bytes_read);
20130           i += bytes_read;
20131           break;
20132
20133         case DW_OP_const1u:
20134           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
20135           i += 1;
20136           break;
20137
20138         case DW_OP_const1s:
20139           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
20140           i += 1;
20141           break;
20142
20143         case DW_OP_const2u:
20144           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
20145           i += 2;
20146           break;
20147
20148         case DW_OP_const2s:
20149           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
20150           i += 2;
20151           break;
20152
20153         case DW_OP_const4u:
20154           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
20155           i += 4;
20156           break;
20157
20158         case DW_OP_const4s:
20159           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
20160           i += 4;
20161           break;
20162
20163         case DW_OP_const8u:
20164           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
20165           i += 8;
20166           break;
20167
20168         case DW_OP_constu:
20169           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
20170                                                   &bytes_read);
20171           i += bytes_read;
20172           break;
20173
20174         case DW_OP_consts:
20175           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
20176           i += bytes_read;
20177           break;
20178
20179         case DW_OP_dup:
20180           stack[stacki + 1] = stack[stacki];
20181           stacki++;
20182           break;
20183
20184         case DW_OP_plus:
20185           stack[stacki - 1] += stack[stacki];
20186           stacki--;
20187           break;
20188
20189         case DW_OP_plus_uconst:
20190           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
20191                                                  &bytes_read);
20192           i += bytes_read;
20193           break;
20194
20195         case DW_OP_minus:
20196           stack[stacki - 1] -= stack[stacki];
20197           stacki--;
20198           break;
20199
20200         case DW_OP_deref:
20201           /* If we're not the last op, then we definitely can't encode
20202              this using GDB's address_class enum.  This is valid for partial
20203              global symbols, although the variable's address will be bogus
20204              in the psymtab.  */
20205           if (i < size)
20206             dwarf2_complex_location_expr_complaint ();
20207           break;
20208
20209         case DW_OP_GNU_push_tls_address:
20210           /* The top of the stack has the offset from the beginning
20211              of the thread control block at which the variable is located.  */
20212           /* Nothing should follow this operator, so the top of stack would
20213              be returned.  */
20214           /* This is valid for partial global symbols, but the variable's
20215              address will be bogus in the psymtab.  Make it always at least
20216              non-zero to not look as a variable garbage collected by linker
20217              which have DW_OP_addr 0.  */
20218           if (i < size)
20219             dwarf2_complex_location_expr_complaint ();
20220           stack[stacki]++;
20221           break;
20222
20223         case DW_OP_GNU_uninit:
20224           break;
20225
20226         case DW_OP_GNU_addr_index:
20227         case DW_OP_GNU_const_index:
20228           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
20229                                                          &bytes_read);
20230           i += bytes_read;
20231           break;
20232
20233         default:
20234           {
20235             const char *name = get_DW_OP_name (op);
20236
20237             if (name)
20238               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
20239                          name);
20240             else
20241               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
20242                          op);
20243           }
20244
20245           return (stack[stacki]);
20246         }
20247
20248       /* Enforce maximum stack depth of SIZE-1 to avoid writing
20249          outside of the allocated space.  Also enforce minimum>0.  */
20250       if (stacki >= ARRAY_SIZE (stack) - 1)
20251         {
20252           complaint (&symfile_complaints,
20253                      _("location description stack overflow"));
20254           return 0;
20255         }
20256
20257       if (stacki <= 0)
20258         {
20259           complaint (&symfile_complaints,
20260                      _("location description stack underflow"));
20261           return 0;
20262         }
20263     }
20264   return (stack[stacki]);
20265 }
20266
20267 /* memory allocation interface */
20268
20269 static struct dwarf_block *
20270 dwarf_alloc_block (struct dwarf2_cu *cu)
20271 {
20272   struct dwarf_block *blk;
20273
20274   blk = (struct dwarf_block *)
20275     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
20276   return (blk);
20277 }
20278
20279 static struct die_info *
20280 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
20281 {
20282   struct die_info *die;
20283   size_t size = sizeof (struct die_info);
20284
20285   if (num_attrs > 1)
20286     size += (num_attrs - 1) * sizeof (struct attribute);
20287
20288   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
20289   memset (die, 0, sizeof (struct die_info));
20290   return (die);
20291 }
20292
20293 \f
20294 /* Macro support.  */
20295
20296 /* Return file name relative to the compilation directory of file number I in
20297    *LH's file name table.  The result is allocated using xmalloc; the caller is
20298    responsible for freeing it.  */
20299
20300 static char *
20301 file_file_name (int file, struct line_header *lh)
20302 {
20303   /* Is the file number a valid index into the line header's file name
20304      table?  Remember that file numbers start with one, not zero.  */
20305   if (1 <= file && file <= lh->num_file_names)
20306     {
20307       struct file_entry *fe = &lh->file_names[file - 1];
20308
20309       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
20310         return xstrdup (fe->name);
20311       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
20312                      fe->name, NULL);
20313     }
20314   else
20315     {
20316       /* The compiler produced a bogus file number.  We can at least
20317          record the macro definitions made in the file, even if we
20318          won't be able to find the file by name.  */
20319       char fake_name[80];
20320
20321       xsnprintf (fake_name, sizeof (fake_name),
20322                  "<bad macro file number %d>", file);
20323
20324       complaint (&symfile_complaints,
20325                  _("bad file number in macro information (%d)"),
20326                  file);
20327
20328       return xstrdup (fake_name);
20329     }
20330 }
20331
20332 /* Return the full name of file number I in *LH's file name table.
20333    Use COMP_DIR as the name of the current directory of the
20334    compilation.  The result is allocated using xmalloc; the caller is
20335    responsible for freeing it.  */
20336 static char *
20337 file_full_name (int file, struct line_header *lh, const char *comp_dir)
20338 {
20339   /* Is the file number a valid index into the line header's file name
20340      table?  Remember that file numbers start with one, not zero.  */
20341   if (1 <= file && file <= lh->num_file_names)
20342     {
20343       char *relative = file_file_name (file, lh);
20344
20345       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
20346         return relative;
20347       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
20348     }
20349   else
20350     return file_file_name (file, lh);
20351 }
20352
20353
20354 static struct macro_source_file *
20355 macro_start_file (int file, int line,
20356                   struct macro_source_file *current_file,
20357                   const char *comp_dir,
20358                   struct line_header *lh, struct objfile *objfile)
20359 {
20360   /* File name relative to the compilation directory of this source file.  */
20361   char *file_name = file_file_name (file, lh);
20362
20363   if (! current_file)
20364     {
20365       /* Note: We don't create a macro table for this compilation unit
20366          at all until we actually get a filename.  */
20367       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
20368
20369       /* If we have no current file, then this must be the start_file
20370          directive for the compilation unit's main source file.  */
20371       current_file = macro_set_main (macro_table, file_name);
20372       macro_define_special (macro_table);
20373     }
20374   else
20375     current_file = macro_include (current_file, line, file_name);
20376
20377   xfree (file_name);
20378
20379   return current_file;
20380 }
20381
20382
20383 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
20384    followed by a null byte.  */
20385 static char *
20386 copy_string (const char *buf, int len)
20387 {
20388   char *s = xmalloc (len + 1);
20389
20390   memcpy (s, buf, len);
20391   s[len] = '\0';
20392   return s;
20393 }
20394
20395
20396 static const char *
20397 consume_improper_spaces (const char *p, const char *body)
20398 {
20399   if (*p == ' ')
20400     {
20401       complaint (&symfile_complaints,
20402                  _("macro definition contains spaces "
20403                    "in formal argument list:\n`%s'"),
20404                  body);
20405
20406       while (*p == ' ')
20407         p++;
20408     }
20409
20410   return p;
20411 }
20412
20413
20414 static void
20415 parse_macro_definition (struct macro_source_file *file, int line,
20416                         const char *body)
20417 {
20418   const char *p;
20419
20420   /* The body string takes one of two forms.  For object-like macro
20421      definitions, it should be:
20422
20423         <macro name> " " <definition>
20424
20425      For function-like macro definitions, it should be:
20426
20427         <macro name> "() " <definition>
20428      or
20429         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
20430
20431      Spaces may appear only where explicitly indicated, and in the
20432      <definition>.
20433
20434      The Dwarf 2 spec says that an object-like macro's name is always
20435      followed by a space, but versions of GCC around March 2002 omit
20436      the space when the macro's definition is the empty string.
20437
20438      The Dwarf 2 spec says that there should be no spaces between the
20439      formal arguments in a function-like macro's formal argument list,
20440      but versions of GCC around March 2002 include spaces after the
20441      commas.  */
20442
20443
20444   /* Find the extent of the macro name.  The macro name is terminated
20445      by either a space or null character (for an object-like macro) or
20446      an opening paren (for a function-like macro).  */
20447   for (p = body; *p; p++)
20448     if (*p == ' ' || *p == '(')
20449       break;
20450
20451   if (*p == ' ' || *p == '\0')
20452     {
20453       /* It's an object-like macro.  */
20454       int name_len = p - body;
20455       char *name = copy_string (body, name_len);
20456       const char *replacement;
20457
20458       if (*p == ' ')
20459         replacement = body + name_len + 1;
20460       else
20461         {
20462           dwarf2_macro_malformed_definition_complaint (body);
20463           replacement = body + name_len;
20464         }
20465
20466       macro_define_object (file, line, name, replacement);
20467
20468       xfree (name);
20469     }
20470   else if (*p == '(')
20471     {
20472       /* It's a function-like macro.  */
20473       char *name = copy_string (body, p - body);
20474       int argc = 0;
20475       int argv_size = 1;
20476       char **argv = xmalloc (argv_size * sizeof (*argv));
20477
20478       p++;
20479
20480       p = consume_improper_spaces (p, body);
20481
20482       /* Parse the formal argument list.  */
20483       while (*p && *p != ')')
20484         {
20485           /* Find the extent of the current argument name.  */
20486           const char *arg_start = p;
20487
20488           while (*p && *p != ',' && *p != ')' && *p != ' ')
20489             p++;
20490
20491           if (! *p || p == arg_start)
20492             dwarf2_macro_malformed_definition_complaint (body);
20493           else
20494             {
20495               /* Make sure argv has room for the new argument.  */
20496               if (argc >= argv_size)
20497                 {
20498                   argv_size *= 2;
20499                   argv = xrealloc (argv, argv_size * sizeof (*argv));
20500                 }
20501
20502               argv[argc++] = copy_string (arg_start, p - arg_start);
20503             }
20504
20505           p = consume_improper_spaces (p, body);
20506
20507           /* Consume the comma, if present.  */
20508           if (*p == ',')
20509             {
20510               p++;
20511
20512               p = consume_improper_spaces (p, body);
20513             }
20514         }
20515
20516       if (*p == ')')
20517         {
20518           p++;
20519
20520           if (*p == ' ')
20521             /* Perfectly formed definition, no complaints.  */
20522             macro_define_function (file, line, name,
20523                                    argc, (const char **) argv,
20524                                    p + 1);
20525           else if (*p == '\0')
20526             {
20527               /* Complain, but do define it.  */
20528               dwarf2_macro_malformed_definition_complaint (body);
20529               macro_define_function (file, line, name,
20530                                      argc, (const char **) argv,
20531                                      p);
20532             }
20533           else
20534             /* Just complain.  */
20535             dwarf2_macro_malformed_definition_complaint (body);
20536         }
20537       else
20538         /* Just complain.  */
20539         dwarf2_macro_malformed_definition_complaint (body);
20540
20541       xfree (name);
20542       {
20543         int i;
20544
20545         for (i = 0; i < argc; i++)
20546           xfree (argv[i]);
20547       }
20548       xfree (argv);
20549     }
20550   else
20551     dwarf2_macro_malformed_definition_complaint (body);
20552 }
20553
20554 /* Skip some bytes from BYTES according to the form given in FORM.
20555    Returns the new pointer.  */
20556
20557 static const gdb_byte *
20558 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
20559                  enum dwarf_form form,
20560                  unsigned int offset_size,
20561                  struct dwarf2_section_info *section)
20562 {
20563   unsigned int bytes_read;
20564
20565   switch (form)
20566     {
20567     case DW_FORM_data1:
20568     case DW_FORM_flag:
20569       ++bytes;
20570       break;
20571
20572     case DW_FORM_data2:
20573       bytes += 2;
20574       break;
20575
20576     case DW_FORM_data4:
20577       bytes += 4;
20578       break;
20579
20580     case DW_FORM_data8:
20581       bytes += 8;
20582       break;
20583
20584     case DW_FORM_string:
20585       read_direct_string (abfd, bytes, &bytes_read);
20586       bytes += bytes_read;
20587       break;
20588
20589     case DW_FORM_sec_offset:
20590     case DW_FORM_strp:
20591     case DW_FORM_GNU_strp_alt:
20592       bytes += offset_size;
20593       break;
20594
20595     case DW_FORM_block:
20596       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
20597       bytes += bytes_read;
20598       break;
20599
20600     case DW_FORM_block1:
20601       bytes += 1 + read_1_byte (abfd, bytes);
20602       break;
20603     case DW_FORM_block2:
20604       bytes += 2 + read_2_bytes (abfd, bytes);
20605       break;
20606     case DW_FORM_block4:
20607       bytes += 4 + read_4_bytes (abfd, bytes);
20608       break;
20609
20610     case DW_FORM_sdata:
20611     case DW_FORM_udata:
20612     case DW_FORM_GNU_addr_index:
20613     case DW_FORM_GNU_str_index:
20614       bytes = gdb_skip_leb128 (bytes, buffer_end);
20615       if (bytes == NULL)
20616         {
20617           dwarf2_section_buffer_overflow_complaint (section);
20618           return NULL;
20619         }
20620       break;
20621
20622     default:
20623       {
20624       complain:
20625         complaint (&symfile_complaints,
20626                    _("invalid form 0x%x in `%s'"),
20627                    form, get_section_name (section));
20628         return NULL;
20629       }
20630     }
20631
20632   return bytes;
20633 }
20634
20635 /* A helper for dwarf_decode_macros that handles skipping an unknown
20636    opcode.  Returns an updated pointer to the macro data buffer; or,
20637    on error, issues a complaint and returns NULL.  */
20638
20639 static const gdb_byte *
20640 skip_unknown_opcode (unsigned int opcode,
20641                      const gdb_byte **opcode_definitions,
20642                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20643                      bfd *abfd,
20644                      unsigned int offset_size,
20645                      struct dwarf2_section_info *section)
20646 {
20647   unsigned int bytes_read, i;
20648   unsigned long arg;
20649   const gdb_byte *defn;
20650
20651   if (opcode_definitions[opcode] == NULL)
20652     {
20653       complaint (&symfile_complaints,
20654                  _("unrecognized DW_MACFINO opcode 0x%x"),
20655                  opcode);
20656       return NULL;
20657     }
20658
20659   defn = opcode_definitions[opcode];
20660   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
20661   defn += bytes_read;
20662
20663   for (i = 0; i < arg; ++i)
20664     {
20665       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
20666                                  section);
20667       if (mac_ptr == NULL)
20668         {
20669           /* skip_form_bytes already issued the complaint.  */
20670           return NULL;
20671         }
20672     }
20673
20674   return mac_ptr;
20675 }
20676
20677 /* A helper function which parses the header of a macro section.
20678    If the macro section is the extended (for now called "GNU") type,
20679    then this updates *OFFSET_SIZE.  Returns a pointer to just after
20680    the header, or issues a complaint and returns NULL on error.  */
20681
20682 static const gdb_byte *
20683 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
20684                           bfd *abfd,
20685                           const gdb_byte *mac_ptr,
20686                           unsigned int *offset_size,
20687                           int section_is_gnu)
20688 {
20689   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
20690
20691   if (section_is_gnu)
20692     {
20693       unsigned int version, flags;
20694
20695       version = read_2_bytes (abfd, mac_ptr);
20696       if (version != 4)
20697         {
20698           complaint (&symfile_complaints,
20699                      _("unrecognized version `%d' in .debug_macro section"),
20700                      version);
20701           return NULL;
20702         }
20703       mac_ptr += 2;
20704
20705       flags = read_1_byte (abfd, mac_ptr);
20706       ++mac_ptr;
20707       *offset_size = (flags & 1) ? 8 : 4;
20708
20709       if ((flags & 2) != 0)
20710         /* We don't need the line table offset.  */
20711         mac_ptr += *offset_size;
20712
20713       /* Vendor opcode descriptions.  */
20714       if ((flags & 4) != 0)
20715         {
20716           unsigned int i, count;
20717
20718           count = read_1_byte (abfd, mac_ptr);
20719           ++mac_ptr;
20720           for (i = 0; i < count; ++i)
20721             {
20722               unsigned int opcode, bytes_read;
20723               unsigned long arg;
20724
20725               opcode = read_1_byte (abfd, mac_ptr);
20726               ++mac_ptr;
20727               opcode_definitions[opcode] = mac_ptr;
20728               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20729               mac_ptr += bytes_read;
20730               mac_ptr += arg;
20731             }
20732         }
20733     }
20734
20735   return mac_ptr;
20736 }
20737
20738 /* A helper for dwarf_decode_macros that handles the GNU extensions,
20739    including DW_MACRO_GNU_transparent_include.  */
20740
20741 static void
20742 dwarf_decode_macro_bytes (bfd *abfd,
20743                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20744                           struct macro_source_file *current_file,
20745                           struct line_header *lh, const char *comp_dir,
20746                           struct dwarf2_section_info *section,
20747                           int section_is_gnu, int section_is_dwz,
20748                           unsigned int offset_size,
20749                           struct objfile *objfile,
20750                           htab_t include_hash)
20751 {
20752   enum dwarf_macro_record_type macinfo_type;
20753   int at_commandline;
20754   const gdb_byte *opcode_definitions[256];
20755
20756   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20757                                       &offset_size, section_is_gnu);
20758   if (mac_ptr == NULL)
20759     {
20760       /* We already issued a complaint.  */
20761       return;
20762     }
20763
20764   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
20765      GDB is still reading the definitions from command line.  First
20766      DW_MACINFO_start_file will need to be ignored as it was already executed
20767      to create CURRENT_FILE for the main source holding also the command line
20768      definitions.  On first met DW_MACINFO_start_file this flag is reset to
20769      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
20770
20771   at_commandline = 1;
20772
20773   do
20774     {
20775       /* Do we at least have room for a macinfo type byte?  */
20776       if (mac_ptr >= mac_end)
20777         {
20778           dwarf2_section_buffer_overflow_complaint (section);
20779           break;
20780         }
20781
20782       macinfo_type = read_1_byte (abfd, mac_ptr);
20783       mac_ptr++;
20784
20785       /* Note that we rely on the fact that the corresponding GNU and
20786          DWARF constants are the same.  */
20787       switch (macinfo_type)
20788         {
20789           /* A zero macinfo type indicates the end of the macro
20790              information.  */
20791         case 0:
20792           break;
20793
20794         case DW_MACRO_GNU_define:
20795         case DW_MACRO_GNU_undef:
20796         case DW_MACRO_GNU_define_indirect:
20797         case DW_MACRO_GNU_undef_indirect:
20798         case DW_MACRO_GNU_define_indirect_alt:
20799         case DW_MACRO_GNU_undef_indirect_alt:
20800           {
20801             unsigned int bytes_read;
20802             int line;
20803             const char *body;
20804             int is_define;
20805
20806             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20807             mac_ptr += bytes_read;
20808
20809             if (macinfo_type == DW_MACRO_GNU_define
20810                 || macinfo_type == DW_MACRO_GNU_undef)
20811               {
20812                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
20813                 mac_ptr += bytes_read;
20814               }
20815             else
20816               {
20817                 LONGEST str_offset;
20818
20819                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
20820                 mac_ptr += offset_size;
20821
20822                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
20823                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
20824                     || section_is_dwz)
20825                   {
20826                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
20827
20828                     body = read_indirect_string_from_dwz (dwz, str_offset);
20829                   }
20830                 else
20831                   body = read_indirect_string_at_offset (abfd, str_offset);
20832               }
20833
20834             is_define = (macinfo_type == DW_MACRO_GNU_define
20835                          || macinfo_type == DW_MACRO_GNU_define_indirect
20836                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
20837             if (! current_file)
20838               {
20839                 /* DWARF violation as no main source is present.  */
20840                 complaint (&symfile_complaints,
20841                            _("debug info with no main source gives macro %s "
20842                              "on line %d: %s"),
20843                            is_define ? _("definition") : _("undefinition"),
20844                            line, body);
20845                 break;
20846               }
20847             if ((line == 0 && !at_commandline)
20848                 || (line != 0 && at_commandline))
20849               complaint (&symfile_complaints,
20850                          _("debug info gives %s macro %s with %s line %d: %s"),
20851                          at_commandline ? _("command-line") : _("in-file"),
20852                          is_define ? _("definition") : _("undefinition"),
20853                          line == 0 ? _("zero") : _("non-zero"), line, body);
20854
20855             if (is_define)
20856               parse_macro_definition (current_file, line, body);
20857             else
20858               {
20859                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
20860                             || macinfo_type == DW_MACRO_GNU_undef_indirect
20861                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
20862                 macro_undef (current_file, line, body);
20863               }
20864           }
20865           break;
20866
20867         case DW_MACRO_GNU_start_file:
20868           {
20869             unsigned int bytes_read;
20870             int line, file;
20871
20872             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20873             mac_ptr += bytes_read;
20874             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20875             mac_ptr += bytes_read;
20876
20877             if ((line == 0 && !at_commandline)
20878                 || (line != 0 && at_commandline))
20879               complaint (&symfile_complaints,
20880                          _("debug info gives source %d included "
20881                            "from %s at %s line %d"),
20882                          file, at_commandline ? _("command-line") : _("file"),
20883                          line == 0 ? _("zero") : _("non-zero"), line);
20884
20885             if (at_commandline)
20886               {
20887                 /* This DW_MACRO_GNU_start_file was executed in the
20888                    pass one.  */
20889                 at_commandline = 0;
20890               }
20891             else
20892               current_file = macro_start_file (file, line,
20893                                                current_file, comp_dir,
20894                                                lh, objfile);
20895           }
20896           break;
20897
20898         case DW_MACRO_GNU_end_file:
20899           if (! current_file)
20900             complaint (&symfile_complaints,
20901                        _("macro debug info has an unmatched "
20902                          "`close_file' directive"));
20903           else
20904             {
20905               current_file = current_file->included_by;
20906               if (! current_file)
20907                 {
20908                   enum dwarf_macro_record_type next_type;
20909
20910                   /* GCC circa March 2002 doesn't produce the zero
20911                      type byte marking the end of the compilation
20912                      unit.  Complain if it's not there, but exit no
20913                      matter what.  */
20914
20915                   /* Do we at least have room for a macinfo type byte?  */
20916                   if (mac_ptr >= mac_end)
20917                     {
20918                       dwarf2_section_buffer_overflow_complaint (section);
20919                       return;
20920                     }
20921
20922                   /* We don't increment mac_ptr here, so this is just
20923                      a look-ahead.  */
20924                   next_type = read_1_byte (abfd, mac_ptr);
20925                   if (next_type != 0)
20926                     complaint (&symfile_complaints,
20927                                _("no terminating 0-type entry for "
20928                                  "macros in `.debug_macinfo' section"));
20929
20930                   return;
20931                 }
20932             }
20933           break;
20934
20935         case DW_MACRO_GNU_transparent_include:
20936         case DW_MACRO_GNU_transparent_include_alt:
20937           {
20938             LONGEST offset;
20939             void **slot;
20940             bfd *include_bfd = abfd;
20941             struct dwarf2_section_info *include_section = section;
20942             struct dwarf2_section_info alt_section;
20943             const gdb_byte *include_mac_end = mac_end;
20944             int is_dwz = section_is_dwz;
20945             const gdb_byte *new_mac_ptr;
20946
20947             offset = read_offset_1 (abfd, mac_ptr, offset_size);
20948             mac_ptr += offset_size;
20949
20950             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
20951               {
20952                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
20953
20954                 dwarf2_read_section (dwarf2_per_objfile->objfile,
20955                                      &dwz->macro);
20956
20957                 include_section = &dwz->macro;
20958                 include_bfd = get_section_bfd_owner (include_section);
20959                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
20960                 is_dwz = 1;
20961               }
20962
20963             new_mac_ptr = include_section->buffer + offset;
20964             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
20965
20966             if (*slot != NULL)
20967               {
20968                 /* This has actually happened; see
20969                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
20970                 complaint (&symfile_complaints,
20971                            _("recursive DW_MACRO_GNU_transparent_include in "
20972                              ".debug_macro section"));
20973               }
20974             else
20975               {
20976                 *slot = (void *) new_mac_ptr;
20977
20978                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
20979                                           include_mac_end, current_file,
20980                                           lh, comp_dir,
20981                                           section, section_is_gnu, is_dwz,
20982                                           offset_size, objfile, include_hash);
20983
20984                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
20985               }
20986           }
20987           break;
20988
20989         case DW_MACINFO_vendor_ext:
20990           if (!section_is_gnu)
20991             {
20992               unsigned int bytes_read;
20993               int constant;
20994
20995               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20996               mac_ptr += bytes_read;
20997               read_direct_string (abfd, mac_ptr, &bytes_read);
20998               mac_ptr += bytes_read;
20999
21000               /* We don't recognize any vendor extensions.  */
21001               break;
21002             }
21003           /* FALLTHROUGH */
21004
21005         default:
21006           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
21007                                          mac_ptr, mac_end, abfd, offset_size,
21008                                          section);
21009           if (mac_ptr == NULL)
21010             return;
21011           break;
21012         }
21013     } while (macinfo_type != 0);
21014 }
21015
21016 static void
21017 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
21018                      const char *comp_dir, int section_is_gnu)
21019 {
21020   struct objfile *objfile = dwarf2_per_objfile->objfile;
21021   struct line_header *lh = cu->line_header;
21022   bfd *abfd;
21023   const gdb_byte *mac_ptr, *mac_end;
21024   struct macro_source_file *current_file = 0;
21025   enum dwarf_macro_record_type macinfo_type;
21026   unsigned int offset_size = cu->header.offset_size;
21027   const gdb_byte *opcode_definitions[256];
21028   struct cleanup *cleanup;
21029   htab_t include_hash;
21030   void **slot;
21031   struct dwarf2_section_info *section;
21032   const char *section_name;
21033
21034   if (cu->dwo_unit != NULL)
21035     {
21036       if (section_is_gnu)
21037         {
21038           section = &cu->dwo_unit->dwo_file->sections.macro;
21039           section_name = ".debug_macro.dwo";
21040         }
21041       else
21042         {
21043           section = &cu->dwo_unit->dwo_file->sections.macinfo;
21044           section_name = ".debug_macinfo.dwo";
21045         }
21046     }
21047   else
21048     {
21049       if (section_is_gnu)
21050         {
21051           section = &dwarf2_per_objfile->macro;
21052           section_name = ".debug_macro";
21053         }
21054       else
21055         {
21056           section = &dwarf2_per_objfile->macinfo;
21057           section_name = ".debug_macinfo";
21058         }
21059     }
21060
21061   dwarf2_read_section (objfile, section);
21062   if (section->buffer == NULL)
21063     {
21064       complaint (&symfile_complaints, _("missing %s section"), section_name);
21065       return;
21066     }
21067   abfd = get_section_bfd_owner (section);
21068
21069   /* First pass: Find the name of the base filename.
21070      This filename is needed in order to process all macros whose definition
21071      (or undefinition) comes from the command line.  These macros are defined
21072      before the first DW_MACINFO_start_file entry, and yet still need to be
21073      associated to the base file.
21074
21075      To determine the base file name, we scan the macro definitions until we
21076      reach the first DW_MACINFO_start_file entry.  We then initialize
21077      CURRENT_FILE accordingly so that any macro definition found before the
21078      first DW_MACINFO_start_file can still be associated to the base file.  */
21079
21080   mac_ptr = section->buffer + offset;
21081   mac_end = section->buffer + section->size;
21082
21083   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
21084                                       &offset_size, section_is_gnu);
21085   if (mac_ptr == NULL)
21086     {
21087       /* We already issued a complaint.  */
21088       return;
21089     }
21090
21091   do
21092     {
21093       /* Do we at least have room for a macinfo type byte?  */
21094       if (mac_ptr >= mac_end)
21095         {
21096           /* Complaint is printed during the second pass as GDB will probably
21097              stop the first pass earlier upon finding
21098              DW_MACINFO_start_file.  */
21099           break;
21100         }
21101
21102       macinfo_type = read_1_byte (abfd, mac_ptr);
21103       mac_ptr++;
21104
21105       /* Note that we rely on the fact that the corresponding GNU and
21106          DWARF constants are the same.  */
21107       switch (macinfo_type)
21108         {
21109           /* A zero macinfo type indicates the end of the macro
21110              information.  */
21111         case 0:
21112           break;
21113
21114         case DW_MACRO_GNU_define:
21115         case DW_MACRO_GNU_undef:
21116           /* Only skip the data by MAC_PTR.  */
21117           {
21118             unsigned int bytes_read;
21119
21120             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21121             mac_ptr += bytes_read;
21122             read_direct_string (abfd, mac_ptr, &bytes_read);
21123             mac_ptr += bytes_read;
21124           }
21125           break;
21126
21127         case DW_MACRO_GNU_start_file:
21128           {
21129             unsigned int bytes_read;
21130             int line, file;
21131
21132             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21133             mac_ptr += bytes_read;
21134             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21135             mac_ptr += bytes_read;
21136
21137             current_file = macro_start_file (file, line, current_file,
21138                                              comp_dir, lh, objfile);
21139           }
21140           break;
21141
21142         case DW_MACRO_GNU_end_file:
21143           /* No data to skip by MAC_PTR.  */
21144           break;
21145
21146         case DW_MACRO_GNU_define_indirect:
21147         case DW_MACRO_GNU_undef_indirect:
21148         case DW_MACRO_GNU_define_indirect_alt:
21149         case DW_MACRO_GNU_undef_indirect_alt:
21150           {
21151             unsigned int bytes_read;
21152
21153             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21154             mac_ptr += bytes_read;
21155             mac_ptr += offset_size;
21156           }
21157           break;
21158
21159         case DW_MACRO_GNU_transparent_include:
21160         case DW_MACRO_GNU_transparent_include_alt:
21161           /* Note that, according to the spec, a transparent include
21162              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
21163              skip this opcode.  */
21164           mac_ptr += offset_size;
21165           break;
21166
21167         case DW_MACINFO_vendor_ext:
21168           /* Only skip the data by MAC_PTR.  */
21169           if (!section_is_gnu)
21170             {
21171               unsigned int bytes_read;
21172
21173               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21174               mac_ptr += bytes_read;
21175               read_direct_string (abfd, mac_ptr, &bytes_read);
21176               mac_ptr += bytes_read;
21177             }
21178           /* FALLTHROUGH */
21179
21180         default:
21181           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
21182                                          mac_ptr, mac_end, abfd, offset_size,
21183                                          section);
21184           if (mac_ptr == NULL)
21185             return;
21186           break;
21187         }
21188     } while (macinfo_type != 0 && current_file == NULL);
21189
21190   /* Second pass: Process all entries.
21191
21192      Use the AT_COMMAND_LINE flag to determine whether we are still processing
21193      command-line macro definitions/undefinitions.  This flag is unset when we
21194      reach the first DW_MACINFO_start_file entry.  */
21195
21196   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
21197                                     NULL, xcalloc, xfree);
21198   cleanup = make_cleanup_htab_delete (include_hash);
21199   mac_ptr = section->buffer + offset;
21200   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
21201   *slot = (void *) mac_ptr;
21202   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
21203                             current_file, lh, comp_dir, section,
21204                             section_is_gnu, 0,
21205                             offset_size, objfile, include_hash);
21206   do_cleanups (cleanup);
21207 }
21208
21209 /* Check if the attribute's form is a DW_FORM_block*
21210    if so return true else false.  */
21211
21212 static int
21213 attr_form_is_block (const struct attribute *attr)
21214 {
21215   return (attr == NULL ? 0 :
21216       attr->form == DW_FORM_block1
21217       || attr->form == DW_FORM_block2
21218       || attr->form == DW_FORM_block4
21219       || attr->form == DW_FORM_block
21220       || attr->form == DW_FORM_exprloc);
21221 }
21222
21223 /* Return non-zero if ATTR's value is a section offset --- classes
21224    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
21225    You may use DW_UNSND (attr) to retrieve such offsets.
21226
21227    Section 7.5.4, "Attribute Encodings", explains that no attribute
21228    may have a value that belongs to more than one of these classes; it
21229    would be ambiguous if we did, because we use the same forms for all
21230    of them.  */
21231
21232 static int
21233 attr_form_is_section_offset (const struct attribute *attr)
21234 {
21235   return (attr->form == DW_FORM_data4
21236           || attr->form == DW_FORM_data8
21237           || attr->form == DW_FORM_sec_offset);
21238 }
21239
21240 /* Return non-zero if ATTR's value falls in the 'constant' class, or
21241    zero otherwise.  When this function returns true, you can apply
21242    dwarf2_get_attr_constant_value to it.
21243
21244    However, note that for some attributes you must check
21245    attr_form_is_section_offset before using this test.  DW_FORM_data4
21246    and DW_FORM_data8 are members of both the constant class, and of
21247    the classes that contain offsets into other debug sections
21248    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
21249    that, if an attribute's can be either a constant or one of the
21250    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
21251    taken as section offsets, not constants.  */
21252
21253 static int
21254 attr_form_is_constant (const struct attribute *attr)
21255 {
21256   switch (attr->form)
21257     {
21258     case DW_FORM_sdata:
21259     case DW_FORM_udata:
21260     case DW_FORM_data1:
21261     case DW_FORM_data2:
21262     case DW_FORM_data4:
21263     case DW_FORM_data8:
21264       return 1;
21265     default:
21266       return 0;
21267     }
21268 }
21269
21270
21271 /* DW_ADDR is always stored already as sect_offset; despite for the forms
21272    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
21273
21274 static int
21275 attr_form_is_ref (const struct attribute *attr)
21276 {
21277   switch (attr->form)
21278     {
21279     case DW_FORM_ref_addr:
21280     case DW_FORM_ref1:
21281     case DW_FORM_ref2:
21282     case DW_FORM_ref4:
21283     case DW_FORM_ref8:
21284     case DW_FORM_ref_udata:
21285     case DW_FORM_GNU_ref_alt:
21286       return 1;
21287     default:
21288       return 0;
21289     }
21290 }
21291
21292 /* Return the .debug_loc section to use for CU.
21293    For DWO files use .debug_loc.dwo.  */
21294
21295 static struct dwarf2_section_info *
21296 cu_debug_loc_section (struct dwarf2_cu *cu)
21297 {
21298   if (cu->dwo_unit)
21299     return &cu->dwo_unit->dwo_file->sections.loc;
21300   return &dwarf2_per_objfile->loc;
21301 }
21302
21303 /* A helper function that fills in a dwarf2_loclist_baton.  */
21304
21305 static void
21306 fill_in_loclist_baton (struct dwarf2_cu *cu,
21307                        struct dwarf2_loclist_baton *baton,
21308                        const struct attribute *attr)
21309 {
21310   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
21311
21312   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
21313
21314   baton->per_cu = cu->per_cu;
21315   gdb_assert (baton->per_cu);
21316   /* We don't know how long the location list is, but make sure we
21317      don't run off the edge of the section.  */
21318   baton->size = section->size - DW_UNSND (attr);
21319   baton->data = section->buffer + DW_UNSND (attr);
21320   baton->base_address = cu->base_address;
21321   baton->from_dwo = cu->dwo_unit != NULL;
21322 }
21323
21324 static void
21325 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
21326                              struct dwarf2_cu *cu, int is_block)
21327 {
21328   struct objfile *objfile = dwarf2_per_objfile->objfile;
21329   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
21330
21331   if (attr_form_is_section_offset (attr)
21332       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
21333          the section.  If so, fall through to the complaint in the
21334          other branch.  */
21335       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
21336     {
21337       struct dwarf2_loclist_baton *baton;
21338
21339       baton = obstack_alloc (&objfile->objfile_obstack,
21340                              sizeof (struct dwarf2_loclist_baton));
21341
21342       fill_in_loclist_baton (cu, baton, attr);
21343
21344       if (cu->base_known == 0)
21345         complaint (&symfile_complaints,
21346                    _("Location list used without "
21347                      "specifying the CU base address."));
21348
21349       SYMBOL_ACLASS_INDEX (sym) = (is_block
21350                                    ? dwarf2_loclist_block_index
21351                                    : dwarf2_loclist_index);
21352       SYMBOL_LOCATION_BATON (sym) = baton;
21353     }
21354   else
21355     {
21356       struct dwarf2_locexpr_baton *baton;
21357
21358       baton = obstack_alloc (&objfile->objfile_obstack,
21359                              sizeof (struct dwarf2_locexpr_baton));
21360       baton->per_cu = cu->per_cu;
21361       gdb_assert (baton->per_cu);
21362
21363       if (attr_form_is_block (attr))
21364         {
21365           /* Note that we're just copying the block's data pointer
21366              here, not the actual data.  We're still pointing into the
21367              info_buffer for SYM's objfile; right now we never release
21368              that buffer, but when we do clean up properly this may
21369              need to change.  */
21370           baton->size = DW_BLOCK (attr)->size;
21371           baton->data = DW_BLOCK (attr)->data;
21372         }
21373       else
21374         {
21375           dwarf2_invalid_attrib_class_complaint ("location description",
21376                                                  SYMBOL_NATURAL_NAME (sym));
21377           baton->size = 0;
21378         }
21379
21380       SYMBOL_ACLASS_INDEX (sym) = (is_block
21381                                    ? dwarf2_locexpr_block_index
21382                                    : dwarf2_locexpr_index);
21383       SYMBOL_LOCATION_BATON (sym) = baton;
21384     }
21385 }
21386
21387 /* Return the OBJFILE associated with the compilation unit CU.  If CU
21388    came from a separate debuginfo file, then the master objfile is
21389    returned.  */
21390
21391 struct objfile *
21392 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
21393 {
21394   struct objfile *objfile = per_cu->objfile;
21395
21396   /* Return the master objfile, so that we can report and look up the
21397      correct file containing this variable.  */
21398   if (objfile->separate_debug_objfile_backlink)
21399     objfile = objfile->separate_debug_objfile_backlink;
21400
21401   return objfile;
21402 }
21403
21404 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
21405    (CU_HEADERP is unused in such case) or prepare a temporary copy at
21406    CU_HEADERP first.  */
21407
21408 static const struct comp_unit_head *
21409 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
21410                        struct dwarf2_per_cu_data *per_cu)
21411 {
21412   const gdb_byte *info_ptr;
21413
21414   if (per_cu->cu)
21415     return &per_cu->cu->header;
21416
21417   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
21418
21419   memset (cu_headerp, 0, sizeof (*cu_headerp));
21420   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
21421
21422   return cu_headerp;
21423 }
21424
21425 /* Return the address size given in the compilation unit header for CU.  */
21426
21427 int
21428 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
21429 {
21430   struct comp_unit_head cu_header_local;
21431   const struct comp_unit_head *cu_headerp;
21432
21433   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
21434
21435   return cu_headerp->addr_size;
21436 }
21437
21438 /* Return the offset size given in the compilation unit header for CU.  */
21439
21440 int
21441 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
21442 {
21443   struct comp_unit_head cu_header_local;
21444   const struct comp_unit_head *cu_headerp;
21445
21446   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
21447
21448   return cu_headerp->offset_size;
21449 }
21450
21451 /* See its dwarf2loc.h declaration.  */
21452
21453 int
21454 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
21455 {
21456   struct comp_unit_head cu_header_local;
21457   const struct comp_unit_head *cu_headerp;
21458
21459   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
21460
21461   if (cu_headerp->version == 2)
21462     return cu_headerp->addr_size;
21463   else
21464     return cu_headerp->offset_size;
21465 }
21466
21467 /* Return the text offset of the CU.  The returned offset comes from
21468    this CU's objfile.  If this objfile came from a separate debuginfo
21469    file, then the offset may be different from the corresponding
21470    offset in the parent objfile.  */
21471
21472 CORE_ADDR
21473 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
21474 {
21475   struct objfile *objfile = per_cu->objfile;
21476
21477   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21478 }
21479
21480 /* Locate the .debug_info compilation unit from CU's objfile which contains
21481    the DIE at OFFSET.  Raises an error on failure.  */
21482
21483 static struct dwarf2_per_cu_data *
21484 dwarf2_find_containing_comp_unit (sect_offset offset,
21485                                   unsigned int offset_in_dwz,
21486                                   struct objfile *objfile)
21487 {
21488   struct dwarf2_per_cu_data *this_cu;
21489   int low, high;
21490   const sect_offset *cu_off;
21491
21492   low = 0;
21493   high = dwarf2_per_objfile->n_comp_units - 1;
21494   while (high > low)
21495     {
21496       struct dwarf2_per_cu_data *mid_cu;
21497       int mid = low + (high - low) / 2;
21498
21499       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
21500       cu_off = &mid_cu->offset;
21501       if (mid_cu->is_dwz > offset_in_dwz
21502           || (mid_cu->is_dwz == offset_in_dwz
21503               && cu_off->sect_off >= offset.sect_off))
21504         high = mid;
21505       else
21506         low = mid + 1;
21507     }
21508   gdb_assert (low == high);
21509   this_cu = dwarf2_per_objfile->all_comp_units[low];
21510   cu_off = &this_cu->offset;
21511   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
21512     {
21513       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
21514         error (_("Dwarf Error: could not find partial DIE containing "
21515                "offset 0x%lx [in module %s]"),
21516                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
21517
21518       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
21519                   <= offset.sect_off);
21520       return dwarf2_per_objfile->all_comp_units[low-1];
21521     }
21522   else
21523     {
21524       this_cu = dwarf2_per_objfile->all_comp_units[low];
21525       if (low == dwarf2_per_objfile->n_comp_units - 1
21526           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
21527         error (_("invalid dwarf2 offset %u"), offset.sect_off);
21528       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
21529       return this_cu;
21530     }
21531 }
21532
21533 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
21534
21535 static void
21536 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
21537 {
21538   memset (cu, 0, sizeof (*cu));
21539   per_cu->cu = cu;
21540   cu->per_cu = per_cu;
21541   cu->objfile = per_cu->objfile;
21542   obstack_init (&cu->comp_unit_obstack);
21543 }
21544
21545 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
21546
21547 static void
21548 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
21549                        enum language pretend_language)
21550 {
21551   struct attribute *attr;
21552
21553   /* Set the language we're debugging.  */
21554   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
21555   if (attr)
21556     set_cu_language (DW_UNSND (attr), cu);
21557   else
21558     {
21559       cu->language = pretend_language;
21560       cu->language_defn = language_def (cu->language);
21561     }
21562
21563   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
21564   if (attr)
21565     cu->producer = DW_STRING (attr);
21566 }
21567
21568 /* Release one cached compilation unit, CU.  We unlink it from the tree
21569    of compilation units, but we don't remove it from the read_in_chain;
21570    the caller is responsible for that.
21571    NOTE: DATA is a void * because this function is also used as a
21572    cleanup routine.  */
21573
21574 static void
21575 free_heap_comp_unit (void *data)
21576 {
21577   struct dwarf2_cu *cu = data;
21578
21579   gdb_assert (cu->per_cu != NULL);
21580   cu->per_cu->cu = NULL;
21581   cu->per_cu = NULL;
21582
21583   obstack_free (&cu->comp_unit_obstack, NULL);
21584
21585   xfree (cu);
21586 }
21587
21588 /* This cleanup function is passed the address of a dwarf2_cu on the stack
21589    when we're finished with it.  We can't free the pointer itself, but be
21590    sure to unlink it from the cache.  Also release any associated storage.  */
21591
21592 static void
21593 free_stack_comp_unit (void *data)
21594 {
21595   struct dwarf2_cu *cu = data;
21596
21597   gdb_assert (cu->per_cu != NULL);
21598   cu->per_cu->cu = NULL;
21599   cu->per_cu = NULL;
21600
21601   obstack_free (&cu->comp_unit_obstack, NULL);
21602   cu->partial_dies = NULL;
21603 }
21604
21605 /* Free all cached compilation units.  */
21606
21607 static void
21608 free_cached_comp_units (void *data)
21609 {
21610   struct dwarf2_per_cu_data *per_cu, **last_chain;
21611
21612   per_cu = dwarf2_per_objfile->read_in_chain;
21613   last_chain = &dwarf2_per_objfile->read_in_chain;
21614   while (per_cu != NULL)
21615     {
21616       struct dwarf2_per_cu_data *next_cu;
21617
21618       next_cu = per_cu->cu->read_in_chain;
21619
21620       free_heap_comp_unit (per_cu->cu);
21621       *last_chain = next_cu;
21622
21623       per_cu = next_cu;
21624     }
21625 }
21626
21627 /* Increase the age counter on each cached compilation unit, and free
21628    any that are too old.  */
21629
21630 static void
21631 age_cached_comp_units (void)
21632 {
21633   struct dwarf2_per_cu_data *per_cu, **last_chain;
21634
21635   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
21636   per_cu = dwarf2_per_objfile->read_in_chain;
21637   while (per_cu != NULL)
21638     {
21639       per_cu->cu->last_used ++;
21640       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
21641         dwarf2_mark (per_cu->cu);
21642       per_cu = per_cu->cu->read_in_chain;
21643     }
21644
21645   per_cu = dwarf2_per_objfile->read_in_chain;
21646   last_chain = &dwarf2_per_objfile->read_in_chain;
21647   while (per_cu != NULL)
21648     {
21649       struct dwarf2_per_cu_data *next_cu;
21650
21651       next_cu = per_cu->cu->read_in_chain;
21652
21653       if (!per_cu->cu->mark)
21654         {
21655           free_heap_comp_unit (per_cu->cu);
21656           *last_chain = next_cu;
21657         }
21658       else
21659         last_chain = &per_cu->cu->read_in_chain;
21660
21661       per_cu = next_cu;
21662     }
21663 }
21664
21665 /* Remove a single compilation unit from the cache.  */
21666
21667 static void
21668 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
21669 {
21670   struct dwarf2_per_cu_data *per_cu, **last_chain;
21671
21672   per_cu = dwarf2_per_objfile->read_in_chain;
21673   last_chain = &dwarf2_per_objfile->read_in_chain;
21674   while (per_cu != NULL)
21675     {
21676       struct dwarf2_per_cu_data *next_cu;
21677
21678       next_cu = per_cu->cu->read_in_chain;
21679
21680       if (per_cu == target_per_cu)
21681         {
21682           free_heap_comp_unit (per_cu->cu);
21683           per_cu->cu = NULL;
21684           *last_chain = next_cu;
21685           break;
21686         }
21687       else
21688         last_chain = &per_cu->cu->read_in_chain;
21689
21690       per_cu = next_cu;
21691     }
21692 }
21693
21694 /* Release all extra memory associated with OBJFILE.  */
21695
21696 void
21697 dwarf2_free_objfile (struct objfile *objfile)
21698 {
21699   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21700
21701   if (dwarf2_per_objfile == NULL)
21702     return;
21703
21704   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
21705   free_cached_comp_units (NULL);
21706
21707   if (dwarf2_per_objfile->quick_file_names_table)
21708     htab_delete (dwarf2_per_objfile->quick_file_names_table);
21709
21710   /* Everything else should be on the objfile obstack.  */
21711 }
21712
21713 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
21714    We store these in a hash table separate from the DIEs, and preserve them
21715    when the DIEs are flushed out of cache.
21716
21717    The CU "per_cu" pointer is needed because offset alone is not enough to
21718    uniquely identify the type.  A file may have multiple .debug_types sections,
21719    or the type may come from a DWO file.  Furthermore, while it's more logical
21720    to use per_cu->section+offset, with Fission the section with the data is in
21721    the DWO file but we don't know that section at the point we need it.
21722    We have to use something in dwarf2_per_cu_data (or the pointer to it)
21723    because we can enter the lookup routine, get_die_type_at_offset, from
21724    outside this file, and thus won't necessarily have PER_CU->cu.
21725    Fortunately, PER_CU is stable for the life of the objfile.  */
21726
21727 struct dwarf2_per_cu_offset_and_type
21728 {
21729   const struct dwarf2_per_cu_data *per_cu;
21730   sect_offset offset;
21731   struct type *type;
21732 };
21733
21734 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
21735
21736 static hashval_t
21737 per_cu_offset_and_type_hash (const void *item)
21738 {
21739   const struct dwarf2_per_cu_offset_and_type *ofs = item;
21740
21741   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
21742 }
21743
21744 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
21745
21746 static int
21747 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
21748 {
21749   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
21750   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
21751
21752   return (ofs_lhs->per_cu == ofs_rhs->per_cu
21753           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
21754 }
21755
21756 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
21757    table if necessary.  For convenience, return TYPE.
21758
21759    The DIEs reading must have careful ordering to:
21760     * Not cause infite loops trying to read in DIEs as a prerequisite for
21761       reading current DIE.
21762     * Not trying to dereference contents of still incompletely read in types
21763       while reading in other DIEs.
21764     * Enable referencing still incompletely read in types just by a pointer to
21765       the type without accessing its fields.
21766
21767    Therefore caller should follow these rules:
21768      * Try to fetch any prerequisite types we may need to build this DIE type
21769        before building the type and calling set_die_type.
21770      * After building type call set_die_type for current DIE as soon as
21771        possible before fetching more types to complete the current type.
21772      * Make the type as complete as possible before fetching more types.  */
21773
21774 static struct type *
21775 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21776 {
21777   struct dwarf2_per_cu_offset_and_type **slot, ofs;
21778   struct objfile *objfile = cu->objfile;
21779   struct attribute *attr;
21780   struct dynamic_prop prop;
21781
21782   /* For Ada types, make sure that the gnat-specific data is always
21783      initialized (if not already set).  There are a few types where
21784      we should not be doing so, because the type-specific area is
21785      already used to hold some other piece of info (eg: TYPE_CODE_FLT
21786      where the type-specific area is used to store the floatformat).
21787      But this is not a problem, because the gnat-specific information
21788      is actually not needed for these types.  */
21789   if (need_gnat_info (cu)
21790       && TYPE_CODE (type) != TYPE_CODE_FUNC
21791       && TYPE_CODE (type) != TYPE_CODE_FLT
21792       && !HAVE_GNAT_AUX_INFO (type))
21793     INIT_GNAT_SPECIFIC (type);
21794
21795   /* Read DW_AT_data_location and set in type.  */
21796   attr = dwarf2_attr (die, DW_AT_data_location, cu);
21797   if (attr_to_dynamic_prop (attr, die, cu, &prop))
21798     {
21799       TYPE_DATA_LOCATION (type)
21800         = obstack_alloc (&objfile->objfile_obstack, sizeof (prop));
21801       *TYPE_DATA_LOCATION (type) = prop;
21802     }
21803
21804   if (dwarf2_per_objfile->die_type_hash == NULL)
21805     {
21806       dwarf2_per_objfile->die_type_hash =
21807         htab_create_alloc_ex (127,
21808                               per_cu_offset_and_type_hash,
21809                               per_cu_offset_and_type_eq,
21810                               NULL,
21811                               &objfile->objfile_obstack,
21812                               hashtab_obstack_allocate,
21813                               dummy_obstack_deallocate);
21814     }
21815
21816   ofs.per_cu = cu->per_cu;
21817   ofs.offset = die->offset;
21818   ofs.type = type;
21819   slot = (struct dwarf2_per_cu_offset_and_type **)
21820     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
21821   if (*slot)
21822     complaint (&symfile_complaints,
21823                _("A problem internal to GDB: DIE 0x%x has type already set"),
21824                die->offset.sect_off);
21825   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
21826   **slot = ofs;
21827   return type;
21828 }
21829
21830 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
21831    or return NULL if the die does not have a saved type.  */
21832
21833 static struct type *
21834 get_die_type_at_offset (sect_offset offset,
21835                         struct dwarf2_per_cu_data *per_cu)
21836 {
21837   struct dwarf2_per_cu_offset_and_type *slot, ofs;
21838
21839   if (dwarf2_per_objfile->die_type_hash == NULL)
21840     return NULL;
21841
21842   ofs.per_cu = per_cu;
21843   ofs.offset = offset;
21844   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
21845   if (slot)
21846     return slot->type;
21847   else
21848     return NULL;
21849 }
21850
21851 /* Look up the type for DIE in CU in die_type_hash,
21852    or return NULL if DIE does not have a saved type.  */
21853
21854 static struct type *
21855 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
21856 {
21857   return get_die_type_at_offset (die->offset, cu->per_cu);
21858 }
21859
21860 /* Add a dependence relationship from CU to REF_PER_CU.  */
21861
21862 static void
21863 dwarf2_add_dependence (struct dwarf2_cu *cu,
21864                        struct dwarf2_per_cu_data *ref_per_cu)
21865 {
21866   void **slot;
21867
21868   if (cu->dependencies == NULL)
21869     cu->dependencies
21870       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
21871                               NULL, &cu->comp_unit_obstack,
21872                               hashtab_obstack_allocate,
21873                               dummy_obstack_deallocate);
21874
21875   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
21876   if (*slot == NULL)
21877     *slot = ref_per_cu;
21878 }
21879
21880 /* Subroutine of dwarf2_mark to pass to htab_traverse.
21881    Set the mark field in every compilation unit in the
21882    cache that we must keep because we are keeping CU.  */
21883
21884 static int
21885 dwarf2_mark_helper (void **slot, void *data)
21886 {
21887   struct dwarf2_per_cu_data *per_cu;
21888
21889   per_cu = (struct dwarf2_per_cu_data *) *slot;
21890
21891   /* cu->dependencies references may not yet have been ever read if QUIT aborts
21892      reading of the chain.  As such dependencies remain valid it is not much
21893      useful to track and undo them during QUIT cleanups.  */
21894   if (per_cu->cu == NULL)
21895     return 1;
21896
21897   if (per_cu->cu->mark)
21898     return 1;
21899   per_cu->cu->mark = 1;
21900
21901   if (per_cu->cu->dependencies != NULL)
21902     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
21903
21904   return 1;
21905 }
21906
21907 /* Set the mark field in CU and in every other compilation unit in the
21908    cache that we must keep because we are keeping CU.  */
21909
21910 static void
21911 dwarf2_mark (struct dwarf2_cu *cu)
21912 {
21913   if (cu->mark)
21914     return;
21915   cu->mark = 1;
21916   if (cu->dependencies != NULL)
21917     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
21918 }
21919
21920 static void
21921 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
21922 {
21923   while (per_cu)
21924     {
21925       per_cu->cu->mark = 0;
21926       per_cu = per_cu->cu->read_in_chain;
21927     }
21928 }
21929
21930 /* Trivial hash function for partial_die_info: the hash value of a DIE
21931    is its offset in .debug_info for this objfile.  */
21932
21933 static hashval_t
21934 partial_die_hash (const void *item)
21935 {
21936   const struct partial_die_info *part_die = item;
21937
21938   return part_die->offset.sect_off;
21939 }
21940
21941 /* Trivial comparison function for partial_die_info structures: two DIEs
21942    are equal if they have the same offset.  */
21943
21944 static int
21945 partial_die_eq (const void *item_lhs, const void *item_rhs)
21946 {
21947   const struct partial_die_info *part_die_lhs = item_lhs;
21948   const struct partial_die_info *part_die_rhs = item_rhs;
21949
21950   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
21951 }
21952
21953 static struct cmd_list_element *set_dwarf2_cmdlist;
21954 static struct cmd_list_element *show_dwarf2_cmdlist;
21955
21956 static void
21957 set_dwarf2_cmd (char *args, int from_tty)
21958 {
21959   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", all_commands,
21960              gdb_stdout);
21961 }
21962
21963 static void
21964 show_dwarf2_cmd (char *args, int from_tty)
21965 {
21966   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
21967 }
21968
21969 /* Free data associated with OBJFILE, if necessary.  */
21970
21971 static void
21972 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
21973 {
21974   struct dwarf2_per_objfile *data = d;
21975   int ix;
21976
21977   /* Make sure we don't accidentally use dwarf2_per_objfile while
21978      cleaning up.  */
21979   dwarf2_per_objfile = NULL;
21980
21981   for (ix = 0; ix < data->n_comp_units; ++ix)
21982    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
21983
21984   for (ix = 0; ix < data->n_type_units; ++ix)
21985     VEC_free (dwarf2_per_cu_ptr,
21986               data->all_type_units[ix]->per_cu.imported_symtabs);
21987   xfree (data->all_type_units);
21988
21989   VEC_free (dwarf2_section_info_def, data->types);
21990
21991   if (data->dwo_files)
21992     free_dwo_files (data->dwo_files, objfile);
21993   if (data->dwp_file)
21994     gdb_bfd_unref (data->dwp_file->dbfd);
21995
21996   if (data->dwz_file && data->dwz_file->dwz_bfd)
21997     gdb_bfd_unref (data->dwz_file->dwz_bfd);
21998 }
21999
22000 \f
22001 /* The "save gdb-index" command.  */
22002
22003 /* The contents of the hash table we create when building the string
22004    table.  */
22005 struct strtab_entry
22006 {
22007   offset_type offset;
22008   const char *str;
22009 };
22010
22011 /* Hash function for a strtab_entry.
22012
22013    Function is used only during write_hash_table so no index format backward
22014    compatibility is needed.  */
22015
22016 static hashval_t
22017 hash_strtab_entry (const void *e)
22018 {
22019   const struct strtab_entry *entry = e;
22020   return mapped_index_string_hash (INT_MAX, entry->str);
22021 }
22022
22023 /* Equality function for a strtab_entry.  */
22024
22025 static int
22026 eq_strtab_entry (const void *a, const void *b)
22027 {
22028   const struct strtab_entry *ea = a;
22029   const struct strtab_entry *eb = b;
22030   return !strcmp (ea->str, eb->str);
22031 }
22032
22033 /* Create a strtab_entry hash table.  */
22034
22035 static htab_t
22036 create_strtab (void)
22037 {
22038   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
22039                             xfree, xcalloc, xfree);
22040 }
22041
22042 /* Add a string to the constant pool.  Return the string's offset in
22043    host order.  */
22044
22045 static offset_type
22046 add_string (htab_t table, struct obstack *cpool, const char *str)
22047 {
22048   void **slot;
22049   struct strtab_entry entry;
22050   struct strtab_entry *result;
22051
22052   entry.str = str;
22053   slot = htab_find_slot (table, &entry, INSERT);
22054   if (*slot)
22055     result = *slot;
22056   else
22057     {
22058       result = XNEW (struct strtab_entry);
22059       result->offset = obstack_object_size (cpool);
22060       result->str = str;
22061       obstack_grow_str0 (cpool, str);
22062       *slot = result;
22063     }
22064   return result->offset;
22065 }
22066
22067 /* An entry in the symbol table.  */
22068 struct symtab_index_entry
22069 {
22070   /* The name of the symbol.  */
22071   const char *name;
22072   /* The offset of the name in the constant pool.  */
22073   offset_type index_offset;
22074   /* A sorted vector of the indices of all the CUs that hold an object
22075      of this name.  */
22076   VEC (offset_type) *cu_indices;
22077 };
22078
22079 /* The symbol table.  This is a power-of-2-sized hash table.  */
22080 struct mapped_symtab
22081 {
22082   offset_type n_elements;
22083   offset_type size;
22084   struct symtab_index_entry **data;
22085 };
22086
22087 /* Hash function for a symtab_index_entry.  */
22088
22089 static hashval_t
22090 hash_symtab_entry (const void *e)
22091 {
22092   const struct symtab_index_entry *entry = e;
22093   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
22094                          sizeof (offset_type) * VEC_length (offset_type,
22095                                                             entry->cu_indices),
22096                          0);
22097 }
22098
22099 /* Equality function for a symtab_index_entry.  */
22100
22101 static int
22102 eq_symtab_entry (const void *a, const void *b)
22103 {
22104   const struct symtab_index_entry *ea = a;
22105   const struct symtab_index_entry *eb = b;
22106   int len = VEC_length (offset_type, ea->cu_indices);
22107   if (len != VEC_length (offset_type, eb->cu_indices))
22108     return 0;
22109   return !memcmp (VEC_address (offset_type, ea->cu_indices),
22110                   VEC_address (offset_type, eb->cu_indices),
22111                   sizeof (offset_type) * len);
22112 }
22113
22114 /* Destroy a symtab_index_entry.  */
22115
22116 static void
22117 delete_symtab_entry (void *p)
22118 {
22119   struct symtab_index_entry *entry = p;
22120   VEC_free (offset_type, entry->cu_indices);
22121   xfree (entry);
22122 }
22123
22124 /* Create a hash table holding symtab_index_entry objects.  */
22125
22126 static htab_t
22127 create_symbol_hash_table (void)
22128 {
22129   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
22130                             delete_symtab_entry, xcalloc, xfree);
22131 }
22132
22133 /* Create a new mapped symtab object.  */
22134
22135 static struct mapped_symtab *
22136 create_mapped_symtab (void)
22137 {
22138   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
22139   symtab->n_elements = 0;
22140   symtab->size = 1024;
22141   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
22142   return symtab;
22143 }
22144
22145 /* Destroy a mapped_symtab.  */
22146
22147 static void
22148 cleanup_mapped_symtab (void *p)
22149 {
22150   struct mapped_symtab *symtab = p;
22151   /* The contents of the array are freed when the other hash table is
22152      destroyed.  */
22153   xfree (symtab->data);
22154   xfree (symtab);
22155 }
22156
22157 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
22158    the slot.
22159    
22160    Function is used only during write_hash_table so no index format backward
22161    compatibility is needed.  */
22162
22163 static struct symtab_index_entry **
22164 find_slot (struct mapped_symtab *symtab, const char *name)
22165 {
22166   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
22167
22168   index = hash & (symtab->size - 1);
22169   step = ((hash * 17) & (symtab->size - 1)) | 1;
22170
22171   for (;;)
22172     {
22173       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
22174         return &symtab->data[index];
22175       index = (index + step) & (symtab->size - 1);
22176     }
22177 }
22178
22179 /* Expand SYMTAB's hash table.  */
22180
22181 static void
22182 hash_expand (struct mapped_symtab *symtab)
22183 {
22184   offset_type old_size = symtab->size;
22185   offset_type i;
22186   struct symtab_index_entry **old_entries = symtab->data;
22187
22188   symtab->size *= 2;
22189   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
22190
22191   for (i = 0; i < old_size; ++i)
22192     {
22193       if (old_entries[i])
22194         {
22195           struct symtab_index_entry **slot = find_slot (symtab,
22196                                                         old_entries[i]->name);
22197           *slot = old_entries[i];
22198         }
22199     }
22200
22201   xfree (old_entries);
22202 }
22203
22204 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
22205    CU_INDEX is the index of the CU in which the symbol appears.
22206    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
22207
22208 static void
22209 add_index_entry (struct mapped_symtab *symtab, const char *name,
22210                  int is_static, gdb_index_symbol_kind kind,
22211                  offset_type cu_index)
22212 {
22213   struct symtab_index_entry **slot;
22214   offset_type cu_index_and_attrs;
22215
22216   ++symtab->n_elements;
22217   if (4 * symtab->n_elements / 3 >= symtab->size)
22218     hash_expand (symtab);
22219
22220   slot = find_slot (symtab, name);
22221   if (!*slot)
22222     {
22223       *slot = XNEW (struct symtab_index_entry);
22224       (*slot)->name = name;
22225       /* index_offset is set later.  */
22226       (*slot)->cu_indices = NULL;
22227     }
22228
22229   cu_index_and_attrs = 0;
22230   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
22231   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
22232   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
22233
22234   /* We don't want to record an index value twice as we want to avoid the
22235      duplication.
22236      We process all global symbols and then all static symbols
22237      (which would allow us to avoid the duplication by only having to check
22238      the last entry pushed), but a symbol could have multiple kinds in one CU.
22239      To keep things simple we don't worry about the duplication here and
22240      sort and uniqufy the list after we've processed all symbols.  */
22241   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
22242 }
22243
22244 /* qsort helper routine for uniquify_cu_indices.  */
22245
22246 static int
22247 offset_type_compare (const void *ap, const void *bp)
22248 {
22249   offset_type a = *(offset_type *) ap;
22250   offset_type b = *(offset_type *) bp;
22251
22252   return (a > b) - (b > a);
22253 }
22254
22255 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
22256
22257 static void
22258 uniquify_cu_indices (struct mapped_symtab *symtab)
22259 {
22260   int i;
22261
22262   for (i = 0; i < symtab->size; ++i)
22263     {
22264       struct symtab_index_entry *entry = symtab->data[i];
22265
22266       if (entry
22267           && entry->cu_indices != NULL)
22268         {
22269           unsigned int next_to_insert, next_to_check;
22270           offset_type last_value;
22271
22272           qsort (VEC_address (offset_type, entry->cu_indices),
22273                  VEC_length (offset_type, entry->cu_indices),
22274                  sizeof (offset_type), offset_type_compare);
22275
22276           last_value = VEC_index (offset_type, entry->cu_indices, 0);
22277           next_to_insert = 1;
22278           for (next_to_check = 1;
22279                next_to_check < VEC_length (offset_type, entry->cu_indices);
22280                ++next_to_check)
22281             {
22282               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
22283                   != last_value)
22284                 {
22285                   last_value = VEC_index (offset_type, entry->cu_indices,
22286                                           next_to_check);
22287                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
22288                                last_value);
22289                   ++next_to_insert;
22290                 }
22291             }
22292           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
22293         }
22294     }
22295 }
22296
22297 /* Add a vector of indices to the constant pool.  */
22298
22299 static offset_type
22300 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
22301                       struct symtab_index_entry *entry)
22302 {
22303   void **slot;
22304
22305   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
22306   if (!*slot)
22307     {
22308       offset_type len = VEC_length (offset_type, entry->cu_indices);
22309       offset_type val = MAYBE_SWAP (len);
22310       offset_type iter;
22311       int i;
22312
22313       *slot = entry;
22314       entry->index_offset = obstack_object_size (cpool);
22315
22316       obstack_grow (cpool, &val, sizeof (val));
22317       for (i = 0;
22318            VEC_iterate (offset_type, entry->cu_indices, i, iter);
22319            ++i)
22320         {
22321           val = MAYBE_SWAP (iter);
22322           obstack_grow (cpool, &val, sizeof (val));
22323         }
22324     }
22325   else
22326     {
22327       struct symtab_index_entry *old_entry = *slot;
22328       entry->index_offset = old_entry->index_offset;
22329       entry = old_entry;
22330     }
22331   return entry->index_offset;
22332 }
22333
22334 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
22335    constant pool entries going into the obstack CPOOL.  */
22336
22337 static void
22338 write_hash_table (struct mapped_symtab *symtab,
22339                   struct obstack *output, struct obstack *cpool)
22340 {
22341   offset_type i;
22342   htab_t symbol_hash_table;
22343   htab_t str_table;
22344
22345   symbol_hash_table = create_symbol_hash_table ();
22346   str_table = create_strtab ();
22347
22348   /* We add all the index vectors to the constant pool first, to
22349      ensure alignment is ok.  */
22350   for (i = 0; i < symtab->size; ++i)
22351     {
22352       if (symtab->data[i])
22353         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
22354     }
22355
22356   /* Now write out the hash table.  */
22357   for (i = 0; i < symtab->size; ++i)
22358     {
22359       offset_type str_off, vec_off;
22360
22361       if (symtab->data[i])
22362         {
22363           str_off = add_string (str_table, cpool, symtab->data[i]->name);
22364           vec_off = symtab->data[i]->index_offset;
22365         }
22366       else
22367         {
22368           /* While 0 is a valid constant pool index, it is not valid
22369              to have 0 for both offsets.  */
22370           str_off = 0;
22371           vec_off = 0;
22372         }
22373
22374       str_off = MAYBE_SWAP (str_off);
22375       vec_off = MAYBE_SWAP (vec_off);
22376
22377       obstack_grow (output, &str_off, sizeof (str_off));
22378       obstack_grow (output, &vec_off, sizeof (vec_off));
22379     }
22380
22381   htab_delete (str_table);
22382   htab_delete (symbol_hash_table);
22383 }
22384
22385 /* Struct to map psymtab to CU index in the index file.  */
22386 struct psymtab_cu_index_map
22387 {
22388   struct partial_symtab *psymtab;
22389   unsigned int cu_index;
22390 };
22391
22392 static hashval_t
22393 hash_psymtab_cu_index (const void *item)
22394 {
22395   const struct psymtab_cu_index_map *map = item;
22396
22397   return htab_hash_pointer (map->psymtab);
22398 }
22399
22400 static int
22401 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
22402 {
22403   const struct psymtab_cu_index_map *lhs = item_lhs;
22404   const struct psymtab_cu_index_map *rhs = item_rhs;
22405
22406   return lhs->psymtab == rhs->psymtab;
22407 }
22408
22409 /* Helper struct for building the address table.  */
22410 struct addrmap_index_data
22411 {
22412   struct objfile *objfile;
22413   struct obstack *addr_obstack;
22414   htab_t cu_index_htab;
22415
22416   /* Non-zero if the previous_* fields are valid.
22417      We can't write an entry until we see the next entry (since it is only then
22418      that we know the end of the entry).  */
22419   int previous_valid;
22420   /* Index of the CU in the table of all CUs in the index file.  */
22421   unsigned int previous_cu_index;
22422   /* Start address of the CU.  */
22423   CORE_ADDR previous_cu_start;
22424 };
22425
22426 /* Write an address entry to OBSTACK.  */
22427
22428 static void
22429 add_address_entry (struct objfile *objfile, struct obstack *obstack,
22430                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
22431 {
22432   offset_type cu_index_to_write;
22433   gdb_byte addr[8];
22434   CORE_ADDR baseaddr;
22435
22436   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22437
22438   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
22439   obstack_grow (obstack, addr, 8);
22440   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
22441   obstack_grow (obstack, addr, 8);
22442   cu_index_to_write = MAYBE_SWAP (cu_index);
22443   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
22444 }
22445
22446 /* Worker function for traversing an addrmap to build the address table.  */
22447
22448 static int
22449 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
22450 {
22451   struct addrmap_index_data *data = datap;
22452   struct partial_symtab *pst = obj;
22453
22454   if (data->previous_valid)
22455     add_address_entry (data->objfile, data->addr_obstack,
22456                        data->previous_cu_start, start_addr,
22457                        data->previous_cu_index);
22458
22459   data->previous_cu_start = start_addr;
22460   if (pst != NULL)
22461     {
22462       struct psymtab_cu_index_map find_map, *map;
22463       find_map.psymtab = pst;
22464       map = htab_find (data->cu_index_htab, &find_map);
22465       gdb_assert (map != NULL);
22466       data->previous_cu_index = map->cu_index;
22467       data->previous_valid = 1;
22468     }
22469   else
22470       data->previous_valid = 0;
22471
22472   return 0;
22473 }
22474
22475 /* Write OBJFILE's address map to OBSTACK.
22476    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
22477    in the index file.  */
22478
22479 static void
22480 write_address_map (struct objfile *objfile, struct obstack *obstack,
22481                    htab_t cu_index_htab)
22482 {
22483   struct addrmap_index_data addrmap_index_data;
22484
22485   /* When writing the address table, we have to cope with the fact that
22486      the addrmap iterator only provides the start of a region; we have to
22487      wait until the next invocation to get the start of the next region.  */
22488
22489   addrmap_index_data.objfile = objfile;
22490   addrmap_index_data.addr_obstack = obstack;
22491   addrmap_index_data.cu_index_htab = cu_index_htab;
22492   addrmap_index_data.previous_valid = 0;
22493
22494   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
22495                    &addrmap_index_data);
22496
22497   /* It's highly unlikely the last entry (end address = 0xff...ff)
22498      is valid, but we should still handle it.
22499      The end address is recorded as the start of the next region, but that
22500      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
22501      anyway.  */
22502   if (addrmap_index_data.previous_valid)
22503     add_address_entry (objfile, obstack,
22504                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
22505                        addrmap_index_data.previous_cu_index);
22506 }
22507
22508 /* Return the symbol kind of PSYM.  */
22509
22510 static gdb_index_symbol_kind
22511 symbol_kind (struct partial_symbol *psym)
22512 {
22513   domain_enum domain = PSYMBOL_DOMAIN (psym);
22514   enum address_class aclass = PSYMBOL_CLASS (psym);
22515
22516   switch (domain)
22517     {
22518     case VAR_DOMAIN:
22519       switch (aclass)
22520         {
22521         case LOC_BLOCK:
22522           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
22523         case LOC_TYPEDEF:
22524           return GDB_INDEX_SYMBOL_KIND_TYPE;
22525         case LOC_COMPUTED:
22526         case LOC_CONST_BYTES:
22527         case LOC_OPTIMIZED_OUT:
22528         case LOC_STATIC:
22529           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
22530         case LOC_CONST:
22531           /* Note: It's currently impossible to recognize psyms as enum values
22532              short of reading the type info.  For now punt.  */
22533           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
22534         default:
22535           /* There are other LOC_FOO values that one might want to classify
22536              as variables, but dwarf2read.c doesn't currently use them.  */
22537           return GDB_INDEX_SYMBOL_KIND_OTHER;
22538         }
22539     case STRUCT_DOMAIN:
22540       return GDB_INDEX_SYMBOL_KIND_TYPE;
22541     default:
22542       return GDB_INDEX_SYMBOL_KIND_OTHER;
22543     }
22544 }
22545
22546 /* Add a list of partial symbols to SYMTAB.  */
22547
22548 static void
22549 write_psymbols (struct mapped_symtab *symtab,
22550                 htab_t psyms_seen,
22551                 struct partial_symbol **psymp,
22552                 int count,
22553                 offset_type cu_index,
22554                 int is_static)
22555 {
22556   for (; count-- > 0; ++psymp)
22557     {
22558       struct partial_symbol *psym = *psymp;
22559       void **slot;
22560
22561       if (SYMBOL_LANGUAGE (psym) == language_ada)
22562         error (_("Ada is not currently supported by the index"));
22563
22564       /* Only add a given psymbol once.  */
22565       slot = htab_find_slot (psyms_seen, psym, INSERT);
22566       if (!*slot)
22567         {
22568           gdb_index_symbol_kind kind = symbol_kind (psym);
22569
22570           *slot = psym;
22571           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
22572                            is_static, kind, cu_index);
22573         }
22574     }
22575 }
22576
22577 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
22578    exception if there is an error.  */
22579
22580 static void
22581 write_obstack (FILE *file, struct obstack *obstack)
22582 {
22583   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
22584               file)
22585       != obstack_object_size (obstack))
22586     error (_("couldn't data write to file"));
22587 }
22588
22589 /* Unlink a file if the argument is not NULL.  */
22590
22591 static void
22592 unlink_if_set (void *p)
22593 {
22594   char **filename = p;
22595   if (*filename)
22596     unlink (*filename);
22597 }
22598
22599 /* A helper struct used when iterating over debug_types.  */
22600 struct signatured_type_index_data
22601 {
22602   struct objfile *objfile;
22603   struct mapped_symtab *symtab;
22604   struct obstack *types_list;
22605   htab_t psyms_seen;
22606   int cu_index;
22607 };
22608
22609 /* A helper function that writes a single signatured_type to an
22610    obstack.  */
22611
22612 static int
22613 write_one_signatured_type (void **slot, void *d)
22614 {
22615   struct signatured_type_index_data *info = d;
22616   struct signatured_type *entry = (struct signatured_type *) *slot;
22617   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
22618   gdb_byte val[8];
22619
22620   write_psymbols (info->symtab,
22621                   info->psyms_seen,
22622                   info->objfile->global_psymbols.list
22623                   + psymtab->globals_offset,
22624                   psymtab->n_global_syms, info->cu_index,
22625                   0);
22626   write_psymbols (info->symtab,
22627                   info->psyms_seen,
22628                   info->objfile->static_psymbols.list
22629                   + psymtab->statics_offset,
22630                   psymtab->n_static_syms, info->cu_index,
22631                   1);
22632
22633   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22634                           entry->per_cu.offset.sect_off);
22635   obstack_grow (info->types_list, val, 8);
22636   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22637                           entry->type_offset_in_tu.cu_off);
22638   obstack_grow (info->types_list, val, 8);
22639   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
22640   obstack_grow (info->types_list, val, 8);
22641
22642   ++info->cu_index;
22643
22644   return 1;
22645 }
22646
22647 /* Recurse into all "included" dependencies and write their symbols as
22648    if they appeared in this psymtab.  */
22649
22650 static void
22651 recursively_write_psymbols (struct objfile *objfile,
22652                             struct partial_symtab *psymtab,
22653                             struct mapped_symtab *symtab,
22654                             htab_t psyms_seen,
22655                             offset_type cu_index)
22656 {
22657   int i;
22658
22659   for (i = 0; i < psymtab->number_of_dependencies; ++i)
22660     if (psymtab->dependencies[i]->user != NULL)
22661       recursively_write_psymbols (objfile, psymtab->dependencies[i],
22662                                   symtab, psyms_seen, cu_index);
22663
22664   write_psymbols (symtab,
22665                   psyms_seen,
22666                   objfile->global_psymbols.list + psymtab->globals_offset,
22667                   psymtab->n_global_syms, cu_index,
22668                   0);
22669   write_psymbols (symtab,
22670                   psyms_seen,
22671                   objfile->static_psymbols.list + psymtab->statics_offset,
22672                   psymtab->n_static_syms, cu_index,
22673                   1);
22674 }
22675
22676 /* Create an index file for OBJFILE in the directory DIR.  */
22677
22678 static void
22679 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
22680 {
22681   struct cleanup *cleanup;
22682   char *filename, *cleanup_filename;
22683   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
22684   struct obstack cu_list, types_cu_list;
22685   int i;
22686   FILE *out_file;
22687   struct mapped_symtab *symtab;
22688   offset_type val, size_of_contents, total_len;
22689   struct stat st;
22690   htab_t psyms_seen;
22691   htab_t cu_index_htab;
22692   struct psymtab_cu_index_map *psymtab_cu_index_map;
22693
22694   if (dwarf2_per_objfile->using_index)
22695     error (_("Cannot use an index to create the index"));
22696
22697   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
22698     error (_("Cannot make an index when the file has multiple .debug_types sections"));
22699
22700   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
22701     return;
22702
22703   if (stat (objfile_name (objfile), &st) < 0)
22704     perror_with_name (objfile_name (objfile));
22705
22706   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
22707                      INDEX_SUFFIX, (char *) NULL);
22708   cleanup = make_cleanup (xfree, filename);
22709
22710   out_file = gdb_fopen_cloexec (filename, "wb");
22711   if (!out_file)
22712     error (_("Can't open `%s' for writing"), filename);
22713
22714   cleanup_filename = filename;
22715   make_cleanup (unlink_if_set, &cleanup_filename);
22716
22717   symtab = create_mapped_symtab ();
22718   make_cleanup (cleanup_mapped_symtab, symtab);
22719
22720   obstack_init (&addr_obstack);
22721   make_cleanup_obstack_free (&addr_obstack);
22722
22723   obstack_init (&cu_list);
22724   make_cleanup_obstack_free (&cu_list);
22725
22726   obstack_init (&types_cu_list);
22727   make_cleanup_obstack_free (&types_cu_list);
22728
22729   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
22730                                   NULL, xcalloc, xfree);
22731   make_cleanup_htab_delete (psyms_seen);
22732
22733   /* While we're scanning CU's create a table that maps a psymtab pointer
22734      (which is what addrmap records) to its index (which is what is recorded
22735      in the index file).  This will later be needed to write the address
22736      table.  */
22737   cu_index_htab = htab_create_alloc (100,
22738                                      hash_psymtab_cu_index,
22739                                      eq_psymtab_cu_index,
22740                                      NULL, xcalloc, xfree);
22741   make_cleanup_htab_delete (cu_index_htab);
22742   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
22743     xmalloc (sizeof (struct psymtab_cu_index_map)
22744              * dwarf2_per_objfile->n_comp_units);
22745   make_cleanup (xfree, psymtab_cu_index_map);
22746
22747   /* The CU list is already sorted, so we don't need to do additional
22748      work here.  Also, the debug_types entries do not appear in
22749      all_comp_units, but only in their own hash table.  */
22750   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
22751     {
22752       struct dwarf2_per_cu_data *per_cu
22753         = dwarf2_per_objfile->all_comp_units[i];
22754       struct partial_symtab *psymtab = per_cu->v.psymtab;
22755       gdb_byte val[8];
22756       struct psymtab_cu_index_map *map;
22757       void **slot;
22758
22759       /* CU of a shared file from 'dwz -m' may be unused by this main file.
22760          It may be referenced from a local scope but in such case it does not
22761          need to be present in .gdb_index.  */
22762       if (psymtab == NULL)
22763         continue;
22764
22765       if (psymtab->user == NULL)
22766         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
22767
22768       map = &psymtab_cu_index_map[i];
22769       map->psymtab = psymtab;
22770       map->cu_index = i;
22771       slot = htab_find_slot (cu_index_htab, map, INSERT);
22772       gdb_assert (slot != NULL);
22773       gdb_assert (*slot == NULL);
22774       *slot = map;
22775
22776       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22777                               per_cu->offset.sect_off);
22778       obstack_grow (&cu_list, val, 8);
22779       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
22780       obstack_grow (&cu_list, val, 8);
22781     }
22782
22783   /* Dump the address map.  */
22784   write_address_map (objfile, &addr_obstack, cu_index_htab);
22785
22786   /* Write out the .debug_type entries, if any.  */
22787   if (dwarf2_per_objfile->signatured_types)
22788     {
22789       struct signatured_type_index_data sig_data;
22790
22791       sig_data.objfile = objfile;
22792       sig_data.symtab = symtab;
22793       sig_data.types_list = &types_cu_list;
22794       sig_data.psyms_seen = psyms_seen;
22795       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
22796       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
22797                               write_one_signatured_type, &sig_data);
22798     }
22799
22800   /* Now that we've processed all symbols we can shrink their cu_indices
22801      lists.  */
22802   uniquify_cu_indices (symtab);
22803
22804   obstack_init (&constant_pool);
22805   make_cleanup_obstack_free (&constant_pool);
22806   obstack_init (&symtab_obstack);
22807   make_cleanup_obstack_free (&symtab_obstack);
22808   write_hash_table (symtab, &symtab_obstack, &constant_pool);
22809
22810   obstack_init (&contents);
22811   make_cleanup_obstack_free (&contents);
22812   size_of_contents = 6 * sizeof (offset_type);
22813   total_len = size_of_contents;
22814
22815   /* The version number.  */
22816   val = MAYBE_SWAP (8);
22817   obstack_grow (&contents, &val, sizeof (val));
22818
22819   /* The offset of the CU list from the start of the file.  */
22820   val = MAYBE_SWAP (total_len);
22821   obstack_grow (&contents, &val, sizeof (val));
22822   total_len += obstack_object_size (&cu_list);
22823
22824   /* The offset of the types CU list from the start of the file.  */
22825   val = MAYBE_SWAP (total_len);
22826   obstack_grow (&contents, &val, sizeof (val));
22827   total_len += obstack_object_size (&types_cu_list);
22828
22829   /* The offset of the address table from the start of the file.  */
22830   val = MAYBE_SWAP (total_len);
22831   obstack_grow (&contents, &val, sizeof (val));
22832   total_len += obstack_object_size (&addr_obstack);
22833
22834   /* The offset of the symbol table from the start of the file.  */
22835   val = MAYBE_SWAP (total_len);
22836   obstack_grow (&contents, &val, sizeof (val));
22837   total_len += obstack_object_size (&symtab_obstack);
22838
22839   /* The offset of the constant pool from the start of the file.  */
22840   val = MAYBE_SWAP (total_len);
22841   obstack_grow (&contents, &val, sizeof (val));
22842   total_len += obstack_object_size (&constant_pool);
22843
22844   gdb_assert (obstack_object_size (&contents) == size_of_contents);
22845
22846   write_obstack (out_file, &contents);
22847   write_obstack (out_file, &cu_list);
22848   write_obstack (out_file, &types_cu_list);
22849   write_obstack (out_file, &addr_obstack);
22850   write_obstack (out_file, &symtab_obstack);
22851   write_obstack (out_file, &constant_pool);
22852
22853   fclose (out_file);
22854
22855   /* We want to keep the file, so we set cleanup_filename to NULL
22856      here.  See unlink_if_set.  */
22857   cleanup_filename = NULL;
22858
22859   do_cleanups (cleanup);
22860 }
22861
22862 /* Implementation of the `save gdb-index' command.
22863    
22864    Note that the file format used by this command is documented in the
22865    GDB manual.  Any changes here must be documented there.  */
22866
22867 static void
22868 save_gdb_index_command (char *arg, int from_tty)
22869 {
22870   struct objfile *objfile;
22871
22872   if (!arg || !*arg)
22873     error (_("usage: save gdb-index DIRECTORY"));
22874
22875   ALL_OBJFILES (objfile)
22876   {
22877     struct stat st;
22878
22879     /* If the objfile does not correspond to an actual file, skip it.  */
22880     if (stat (objfile_name (objfile), &st) < 0)
22881       continue;
22882
22883     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
22884     if (dwarf2_per_objfile)
22885       {
22886         volatile struct gdb_exception except;
22887
22888         TRY_CATCH (except, RETURN_MASK_ERROR)
22889           {
22890             write_psymtabs_to_index (objfile, arg);
22891           }
22892         if (except.reason < 0)
22893           exception_fprintf (gdb_stderr, except,
22894                              _("Error while writing index for `%s': "),
22895                              objfile_name (objfile));
22896       }
22897   }
22898 }
22899
22900 \f
22901
22902 int dwarf2_always_disassemble;
22903
22904 static void
22905 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
22906                                 struct cmd_list_element *c, const char *value)
22907 {
22908   fprintf_filtered (file,
22909                     _("Whether to always disassemble "
22910                       "DWARF expressions is %s.\n"),
22911                     value);
22912 }
22913
22914 static void
22915 show_check_physname (struct ui_file *file, int from_tty,
22916                      struct cmd_list_element *c, const char *value)
22917 {
22918   fprintf_filtered (file,
22919                     _("Whether to check \"physname\" is %s.\n"),
22920                     value);
22921 }
22922
22923 void _initialize_dwarf2_read (void);
22924
22925 void
22926 _initialize_dwarf2_read (void)
22927 {
22928   struct cmd_list_element *c;
22929
22930   dwarf2_objfile_data_key
22931     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
22932
22933   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
22934 Set DWARF 2 specific variables.\n\
22935 Configure DWARF 2 variables such as the cache size"),
22936                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
22937                   0/*allow-unknown*/, &maintenance_set_cmdlist);
22938
22939   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
22940 Show DWARF 2 specific variables\n\
22941 Show DWARF 2 variables such as the cache size"),
22942                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
22943                   0/*allow-unknown*/, &maintenance_show_cmdlist);
22944
22945   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
22946                             &dwarf2_max_cache_age, _("\
22947 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
22948 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
22949 A higher limit means that cached compilation units will be stored\n\
22950 in memory longer, and more total memory will be used.  Zero disables\n\
22951 caching, which can slow down startup."),
22952                             NULL,
22953                             show_dwarf2_max_cache_age,
22954                             &set_dwarf2_cmdlist,
22955                             &show_dwarf2_cmdlist);
22956
22957   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
22958                            &dwarf2_always_disassemble, _("\
22959 Set whether `info address' always disassembles DWARF expressions."), _("\
22960 Show whether `info address' always disassembles DWARF expressions."), _("\
22961 When enabled, DWARF expressions are always printed in an assembly-like\n\
22962 syntax.  When disabled, expressions will be printed in a more\n\
22963 conversational style, when possible."),
22964                            NULL,
22965                            show_dwarf2_always_disassemble,
22966                            &set_dwarf2_cmdlist,
22967                            &show_dwarf2_cmdlist);
22968
22969   add_setshow_zuinteger_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
22970 Set debugging of the dwarf2 reader."), _("\
22971 Show debugging of the dwarf2 reader."), _("\
22972 When enabled (non-zero), debugging messages are printed during dwarf2\n\
22973 reading and symtab expansion.  A value of 1 (one) provides basic\n\
22974 information.  A value greater than 1 provides more verbose information."),
22975                             NULL,
22976                             NULL,
22977                             &setdebuglist, &showdebuglist);
22978
22979   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
22980 Set debugging of the dwarf2 DIE reader."), _("\
22981 Show debugging of the dwarf2 DIE reader."), _("\
22982 When enabled (non-zero), DIEs are dumped after they are read in.\n\
22983 The value is the maximum depth to print."),
22984                              NULL,
22985                              NULL,
22986                              &setdebuglist, &showdebuglist);
22987
22988   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
22989 Set cross-checking of \"physname\" code against demangler."), _("\
22990 Show cross-checking of \"physname\" code against demangler."), _("\
22991 When enabled, GDB's internal \"physname\" code is checked against\n\
22992 the demangler."),
22993                            NULL, show_check_physname,
22994                            &setdebuglist, &showdebuglist);
22995
22996   add_setshow_boolean_cmd ("use-deprecated-index-sections",
22997                            no_class, &use_deprecated_index_sections, _("\
22998 Set whether to use deprecated gdb_index sections."), _("\
22999 Show whether to use deprecated gdb_index sections."), _("\
23000 When enabled, deprecated .gdb_index sections are used anyway.\n\
23001 Normally they are ignored either because of a missing feature or\n\
23002 performance issue.\n\
23003 Warning: This option must be enabled before gdb reads the file."),
23004                            NULL,
23005                            NULL,
23006                            &setlist, &showlist);
23007
23008   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
23009                _("\
23010 Save a gdb-index file.\n\
23011 Usage: save gdb-index DIRECTORY"),
23012                &save_cmdlist);
23013   set_cmd_completer (c, filename_completer);
23014
23015   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
23016                                                         &dwarf2_locexpr_funcs);
23017   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
23018                                                         &dwarf2_loclist_funcs);
23019
23020   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
23021                                         &dwarf2_block_frame_base_locexpr_funcs);
23022   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
23023                                         &dwarf2_block_frame_base_loclist_funcs);
23024 }