* dwarf2read.c (free_dwo_file): Add comment.
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71
72 #include <fcntl.h>
73 #include "gdb_string.h"
74 #include "gdb_assert.h"
75 #include <sys/types.h>
76
77 typedef struct symbol *symbolp;
78 DEF_VEC_P (symbolp);
79
80 /* When non-zero, print basic high level tracing messages.
81    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
82 static int dwarf2_read_debug = 0;
83
84 /* When non-zero, dump DIEs after they are read in.  */
85 static unsigned int dwarf2_die_debug = 0;
86
87 /* When non-zero, cross-check physname against demangler.  */
88 static int check_physname = 0;
89
90 /* When non-zero, do not reject deprecated .gdb_index sections.  */
91 static int use_deprecated_index_sections = 0;
92
93 static const struct objfile_data *dwarf2_objfile_data_key;
94
95 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
96
97 static int dwarf2_locexpr_index;
98 static int dwarf2_loclist_index;
99 static int dwarf2_locexpr_block_index;
100 static int dwarf2_loclist_block_index;
101
102 struct dwarf2_section_info
103 {
104   asection *asection;
105   gdb_byte *buffer;
106   bfd_size_type size;
107   /* True if we have tried to read this section.  */
108   int readin;
109 };
110
111 typedef struct dwarf2_section_info dwarf2_section_info_def;
112 DEF_VEC_O (dwarf2_section_info_def);
113
114 /* All offsets in the index are of this type.  It must be
115    architecture-independent.  */
116 typedef uint32_t offset_type;
117
118 DEF_VEC_I (offset_type);
119
120 /* Ensure only legit values are used.  */
121 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
122   do { \
123     gdb_assert ((unsigned int) (value) <= 1); \
124     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
125   } while (0)
126
127 /* Ensure only legit values are used.  */
128 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
129   do { \
130     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
131                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
132     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
133   } while (0)
134
135 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
136 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
137   do { \
138     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
139     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
140   } while (0)
141
142 /* A description of the mapped index.  The file format is described in
143    a comment by the code that writes the index.  */
144 struct mapped_index
145 {
146   /* Index data format version.  */
147   int version;
148
149   /* The total length of the buffer.  */
150   off_t total_size;
151
152   /* A pointer to the address table data.  */
153   const gdb_byte *address_table;
154
155   /* Size of the address table data in bytes.  */
156   offset_type address_table_size;
157
158   /* The symbol table, implemented as a hash table.  */
159   const offset_type *symbol_table;
160
161   /* Size in slots, each slot is 2 offset_types.  */
162   offset_type symbol_table_slots;
163
164   /* A pointer to the constant pool.  */
165   const char *constant_pool;
166 };
167
168 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
169 DEF_VEC_P (dwarf2_per_cu_ptr);
170
171 /* Collection of data recorded per objfile.
172    This hangs off of dwarf2_objfile_data_key.  */
173
174 struct dwarf2_per_objfile
175 {
176   struct dwarf2_section_info info;
177   struct dwarf2_section_info abbrev;
178   struct dwarf2_section_info line;
179   struct dwarf2_section_info loc;
180   struct dwarf2_section_info macinfo;
181   struct dwarf2_section_info macro;
182   struct dwarf2_section_info str;
183   struct dwarf2_section_info ranges;
184   struct dwarf2_section_info addr;
185   struct dwarf2_section_info frame;
186   struct dwarf2_section_info eh_frame;
187   struct dwarf2_section_info gdb_index;
188
189   VEC (dwarf2_section_info_def) *types;
190
191   /* Back link.  */
192   struct objfile *objfile;
193
194   /* Table of all the compilation units.  This is used to locate
195      the target compilation unit of a particular reference.  */
196   struct dwarf2_per_cu_data **all_comp_units;
197
198   /* The number of compilation units in ALL_COMP_UNITS.  */
199   int n_comp_units;
200
201   /* The number of .debug_types-related CUs.  */
202   int n_type_units;
203
204   /* The .debug_types-related CUs (TUs).  */
205   struct signatured_type **all_type_units;
206
207   /* The number of entries in all_type_unit_groups.  */
208   int n_type_unit_groups;
209
210   /* Table of type unit groups.
211      This exists to make it easy to iterate over all CUs and TU groups.  */
212   struct type_unit_group **all_type_unit_groups;
213
214   /* Table of struct type_unit_group objects.
215      The hash key is the DW_AT_stmt_list value.  */
216   htab_t type_unit_groups;
217
218   /* A table mapping .debug_types signatures to its signatured_type entry.
219      This is NULL if the .debug_types section hasn't been read in yet.  */
220   htab_t signatured_types;
221
222   /* Type unit statistics, to see how well the scaling improvements
223      are doing.  */
224   struct tu_stats
225   {
226     int nr_uniq_abbrev_tables;
227     int nr_symtabs;
228     int nr_symtab_sharers;
229     int nr_stmt_less_type_units;
230   } tu_stats;
231
232   /* A chain of compilation units that are currently read in, so that
233      they can be freed later.  */
234   struct dwarf2_per_cu_data *read_in_chain;
235
236   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
237      This is NULL if the table hasn't been allocated yet.  */
238   htab_t dwo_files;
239
240   /* Non-zero if we've check for whether there is a DWP file.  */
241   int dwp_checked;
242
243   /* The DWP file if there is one, or NULL.  */
244   struct dwp_file *dwp_file;
245
246   /* The shared '.dwz' file, if one exists.  This is used when the
247      original data was compressed using 'dwz -m'.  */
248   struct dwz_file *dwz_file;
249
250   /* A flag indicating wether this objfile has a section loaded at a
251      VMA of 0.  */
252   int has_section_at_zero;
253
254   /* True if we are using the mapped index,
255      or we are faking it for OBJF_READNOW's sake.  */
256   unsigned char using_index;
257
258   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
259   struct mapped_index *index_table;
260
261   /* When using index_table, this keeps track of all quick_file_names entries.
262      TUs typically share line table entries with a CU, so we maintain a
263      separate table of all line table entries to support the sharing.
264      Note that while there can be way more TUs than CUs, we've already
265      sorted all the TUs into "type unit groups", grouped by their
266      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
267      CU and its associated TU group if there is one.  */
268   htab_t quick_file_names_table;
269
270   /* Set during partial symbol reading, to prevent queueing of full
271      symbols.  */
272   int reading_partial_symbols;
273
274   /* Table mapping type DIEs to their struct type *.
275      This is NULL if not allocated yet.
276      The mapping is done via (CU/TU signature + DIE offset) -> type.  */
277   htab_t die_type_hash;
278
279   /* The CUs we recently read.  */
280   VEC (dwarf2_per_cu_ptr) *just_read_cus;
281 };
282
283 static struct dwarf2_per_objfile *dwarf2_per_objfile;
284
285 /* Default names of the debugging sections.  */
286
287 /* Note that if the debugging section has been compressed, it might
288    have a name like .zdebug_info.  */
289
290 static const struct dwarf2_debug_sections dwarf2_elf_names =
291 {
292   { ".debug_info", ".zdebug_info" },
293   { ".debug_abbrev", ".zdebug_abbrev" },
294   { ".debug_line", ".zdebug_line" },
295   { ".debug_loc", ".zdebug_loc" },
296   { ".debug_macinfo", ".zdebug_macinfo" },
297   { ".debug_macro", ".zdebug_macro" },
298   { ".debug_str", ".zdebug_str" },
299   { ".debug_ranges", ".zdebug_ranges" },
300   { ".debug_types", ".zdebug_types" },
301   { ".debug_addr", ".zdebug_addr" },
302   { ".debug_frame", ".zdebug_frame" },
303   { ".eh_frame", NULL },
304   { ".gdb_index", ".zgdb_index" },
305   23
306 };
307
308 /* List of DWO/DWP sections.  */
309
310 static const struct dwop_section_names
311 {
312   struct dwarf2_section_names abbrev_dwo;
313   struct dwarf2_section_names info_dwo;
314   struct dwarf2_section_names line_dwo;
315   struct dwarf2_section_names loc_dwo;
316   struct dwarf2_section_names macinfo_dwo;
317   struct dwarf2_section_names macro_dwo;
318   struct dwarf2_section_names str_dwo;
319   struct dwarf2_section_names str_offsets_dwo;
320   struct dwarf2_section_names types_dwo;
321   struct dwarf2_section_names cu_index;
322   struct dwarf2_section_names tu_index;
323 }
324 dwop_section_names =
325 {
326   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
327   { ".debug_info.dwo", ".zdebug_info.dwo" },
328   { ".debug_line.dwo", ".zdebug_line.dwo" },
329   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
330   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
331   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
332   { ".debug_str.dwo", ".zdebug_str.dwo" },
333   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
334   { ".debug_types.dwo", ".zdebug_types.dwo" },
335   { ".debug_cu_index", ".zdebug_cu_index" },
336   { ".debug_tu_index", ".zdebug_tu_index" },
337 };
338
339 /* local data types */
340
341 /* The data in a compilation unit header, after target2host
342    translation, looks like this.  */
343 struct comp_unit_head
344 {
345   unsigned int length;
346   short version;
347   unsigned char addr_size;
348   unsigned char signed_addr_p;
349   sect_offset abbrev_offset;
350
351   /* Size of file offsets; either 4 or 8.  */
352   unsigned int offset_size;
353
354   /* Size of the length field; either 4 or 12.  */
355   unsigned int initial_length_size;
356
357   /* Offset to the first byte of this compilation unit header in the
358      .debug_info section, for resolving relative reference dies.  */
359   sect_offset offset;
360
361   /* Offset to first die in this cu from the start of the cu.
362      This will be the first byte following the compilation unit header.  */
363   cu_offset first_die_offset;
364 };
365
366 /* Type used for delaying computation of method physnames.
367    See comments for compute_delayed_physnames.  */
368 struct delayed_method_info
369 {
370   /* The type to which the method is attached, i.e., its parent class.  */
371   struct type *type;
372
373   /* The index of the method in the type's function fieldlists.  */
374   int fnfield_index;
375
376   /* The index of the method in the fieldlist.  */
377   int index;
378
379   /* The name of the DIE.  */
380   const char *name;
381
382   /*  The DIE associated with this method.  */
383   struct die_info *die;
384 };
385
386 typedef struct delayed_method_info delayed_method_info;
387 DEF_VEC_O (delayed_method_info);
388
389 /* Internal state when decoding a particular compilation unit.  */
390 struct dwarf2_cu
391 {
392   /* The objfile containing this compilation unit.  */
393   struct objfile *objfile;
394
395   /* The header of the compilation unit.  */
396   struct comp_unit_head header;
397
398   /* Base address of this compilation unit.  */
399   CORE_ADDR base_address;
400
401   /* Non-zero if base_address has been set.  */
402   int base_known;
403
404   /* The language we are debugging.  */
405   enum language language;
406   const struct language_defn *language_defn;
407
408   const char *producer;
409
410   /* The generic symbol table building routines have separate lists for
411      file scope symbols and all all other scopes (local scopes).  So
412      we need to select the right one to pass to add_symbol_to_list().
413      We do it by keeping a pointer to the correct list in list_in_scope.
414
415      FIXME: The original dwarf code just treated the file scope as the
416      first local scope, and all other local scopes as nested local
417      scopes, and worked fine.  Check to see if we really need to
418      distinguish these in buildsym.c.  */
419   struct pending **list_in_scope;
420
421   /* The abbrev table for this CU.
422      Normally this points to the abbrev table in the objfile.
423      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
424   struct abbrev_table *abbrev_table;
425
426   /* Hash table holding all the loaded partial DIEs
427      with partial_die->offset.SECT_OFF as hash.  */
428   htab_t partial_dies;
429
430   /* Storage for things with the same lifetime as this read-in compilation
431      unit, including partial DIEs.  */
432   struct obstack comp_unit_obstack;
433
434   /* When multiple dwarf2_cu structures are living in memory, this field
435      chains them all together, so that they can be released efficiently.
436      We will probably also want a generation counter so that most-recently-used
437      compilation units are cached...  */
438   struct dwarf2_per_cu_data *read_in_chain;
439
440   /* Backchain to our per_cu entry if the tree has been built.  */
441   struct dwarf2_per_cu_data *per_cu;
442
443   /* How many compilation units ago was this CU last referenced?  */
444   int last_used;
445
446   /* A hash table of DIE cu_offset for following references with
447      die_info->offset.sect_off as hash.  */
448   htab_t die_hash;
449
450   /* Full DIEs if read in.  */
451   struct die_info *dies;
452
453   /* A set of pointers to dwarf2_per_cu_data objects for compilation
454      units referenced by this one.  Only set during full symbol processing;
455      partial symbol tables do not have dependencies.  */
456   htab_t dependencies;
457
458   /* Header data from the line table, during full symbol processing.  */
459   struct line_header *line_header;
460
461   /* A list of methods which need to have physnames computed
462      after all type information has been read.  */
463   VEC (delayed_method_info) *method_list;
464
465   /* To be copied to symtab->call_site_htab.  */
466   htab_t call_site_htab;
467
468   /* Non-NULL if this CU came from a DWO file.
469      There is an invariant here that is important to remember:
470      Except for attributes copied from the top level DIE in the "main"
471      (or "stub") file in preparation for reading the DWO file
472      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
473      Either there isn't a DWO file (in which case this is NULL and the point
474      is moot), or there is and either we're not going to read it (in which
475      case this is NULL) or there is and we are reading it (in which case this
476      is non-NULL).  */
477   struct dwo_unit *dwo_unit;
478
479   /* The DW_AT_addr_base attribute if present, zero otherwise
480      (zero is a valid value though).
481      Note this value comes from the stub CU/TU's DIE.  */
482   ULONGEST addr_base;
483
484   /* The DW_AT_ranges_base attribute if present, zero otherwise
485      (zero is a valid value though).
486      Note this value comes from the stub CU/TU's DIE.
487      Also note that the value is zero in the non-DWO case so this value can
488      be used without needing to know whether DWO files are in use or not.
489      N.B. This does not apply to DW_AT_ranges appearing in
490      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
491      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
492      DW_AT_ranges_base *would* have to be applied, and we'd have to care
493      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
494   ULONGEST ranges_base;
495
496   /* Mark used when releasing cached dies.  */
497   unsigned int mark : 1;
498
499   /* This CU references .debug_loc.  See the symtab->locations_valid field.
500      This test is imperfect as there may exist optimized debug code not using
501      any location list and still facing inlining issues if handled as
502      unoptimized code.  For a future better test see GCC PR other/32998.  */
503   unsigned int has_loclist : 1;
504
505   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
506      if all the producer_is_* fields are valid.  This information is cached
507      because profiling CU expansion showed excessive time spent in
508      producer_is_gxx_lt_4_6.  */
509   unsigned int checked_producer : 1;
510   unsigned int producer_is_gxx_lt_4_6 : 1;
511   unsigned int producer_is_gcc_lt_4_3 : 1;
512   unsigned int producer_is_icc : 1;
513
514   /* When set, the file that we're processing is known to have
515      debugging info for C++ namespaces.  GCC 3.3.x did not produce
516      this information, but later versions do.  */
517
518   unsigned int processing_has_namespace_info : 1;
519 };
520
521 /* Persistent data held for a compilation unit, even when not
522    processing it.  We put a pointer to this structure in the
523    read_symtab_private field of the psymtab.  */
524
525 struct dwarf2_per_cu_data
526 {
527   /* The start offset and length of this compilation unit.
528      NOTE: Unlike comp_unit_head.length, this length includes
529      initial_length_size.
530      If the DIE refers to a DWO file, this is always of the original die,
531      not the DWO file.  */
532   sect_offset offset;
533   unsigned int length;
534
535   /* Flag indicating this compilation unit will be read in before
536      any of the current compilation units are processed.  */
537   unsigned int queued : 1;
538
539   /* This flag will be set when reading partial DIEs if we need to load
540      absolutely all DIEs for this compilation unit, instead of just the ones
541      we think are interesting.  It gets set if we look for a DIE in the
542      hash table and don't find it.  */
543   unsigned int load_all_dies : 1;
544
545   /* Non-zero if this CU is from .debug_types.  */
546   unsigned int is_debug_types : 1;
547
548   /* Non-zero if this CU is from the .dwz file.  */
549   unsigned int is_dwz : 1;
550
551   /* The section this CU/TU lives in.
552      If the DIE refers to a DWO file, this is always the original die,
553      not the DWO file.  */
554   struct dwarf2_section_info *section;
555
556   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
557      of the CU cache it gets reset to NULL again.  */
558   struct dwarf2_cu *cu;
559
560   /* The corresponding objfile.
561      Normally we can get the objfile from dwarf2_per_objfile.
562      However we can enter this file with just a "per_cu" handle.  */
563   struct objfile *objfile;
564
565   /* When using partial symbol tables, the 'psymtab' field is active.
566      Otherwise the 'quick' field is active.  */
567   union
568   {
569     /* The partial symbol table associated with this compilation unit,
570        or NULL for unread partial units.  */
571     struct partial_symtab *psymtab;
572
573     /* Data needed by the "quick" functions.  */
574     struct dwarf2_per_cu_quick_data *quick;
575   } v;
576
577   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
578      while reading psymtabs, used to compute the psymtab dependencies,
579      and then cleared.  Then it is filled in again while reading full
580      symbols, and only deleted when the objfile is destroyed.
581
582      This is also used to work around a difference between the way gold
583      generates .gdb_index version <=7 and the way gdb does.  Arguably this
584      is a gold bug.  For symbols coming from TUs, gold records in the index
585      the CU that includes the TU instead of the TU itself.  This breaks
586      dw2_lookup_symbol: It assumes that if the index says symbol X lives
587      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
588      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
589      we need to look in TU Z to find X.  Fortunately, this is akin to
590      DW_TAG_imported_unit, so we just use the same mechanism: For
591      .gdb_index version <=7 this also records the TUs that the CU referred
592      to.  Concurrently with this change gdb was modified to emit version 8
593      indices so we only pay a price for gold generated indices.  */
594   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
595
596   /* Type units are grouped by their DW_AT_stmt_list entry so that they
597      can share them.  If this is a TU, this points to the containing
598      symtab.  */
599   struct type_unit_group *type_unit_group;
600 };
601
602 /* Entry in the signatured_types hash table.  */
603
604 struct signatured_type
605 {
606   /* The "per_cu" object of this type.
607      N.B.: This is the first member so that it's easy to convert pointers
608      between them.  */
609   struct dwarf2_per_cu_data per_cu;
610
611   /* The type's signature.  */
612   ULONGEST signature;
613
614   /* Offset in the TU of the type's DIE, as read from the TU header.
615      If this TU is a DWO stub and the definition lives in a DWO file
616      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
617   cu_offset type_offset_in_tu;
618
619   /* Offset in the section of the type's DIE.
620      If the definition lives in a DWO file, this is the offset in the
621      .debug_types.dwo section.
622      The value is zero until the actual value is known.
623      Zero is otherwise not a valid section offset.  */
624   sect_offset type_offset_in_section;
625 };
626
627 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
628    This includes type_unit_group and quick_file_names.  */
629
630 struct stmt_list_hash
631 {
632   /* The DWO unit this table is from or NULL if there is none.  */
633   struct dwo_unit *dwo_unit;
634
635   /* Offset in .debug_line or .debug_line.dwo.  */
636   sect_offset line_offset;
637 };
638
639 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
640    an object of this type.  */
641
642 struct type_unit_group
643 {
644   /* dwarf2read.c's main "handle" on the symtab.
645      To simplify things we create an artificial CU that "includes" all the
646      type units using this stmt_list so that the rest of the code still has
647      a "per_cu" handle on the symtab.
648      This PER_CU is recognized by having no section.  */
649 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
650   struct dwarf2_per_cu_data per_cu;
651
652   union
653   {
654     /* The TUs that share this DW_AT_stmt_list entry.
655        This is added to while parsing type units to build partial symtabs,
656        and is deleted afterwards and not used again.  */
657     VEC (dwarf2_per_cu_ptr) *tus;
658
659     /* When reading the line table in "quick" functions, we need a real TU.
660        Any will do, we know they all share the same DW_AT_stmt_list entry.
661        For simplicity's sake, we pick the first one.  */
662     struct dwarf2_per_cu_data *first_tu;
663   } t;
664
665   /* The primary symtab.
666      Type units in a group needn't all be defined in the same source file,
667      so we create an essentially anonymous symtab as the primary symtab.  */
668   struct symtab *primary_symtab;
669
670   /* The data used to construct the hash key.  */
671   struct stmt_list_hash hash;
672
673   /* The number of symtabs from the line header.
674      The value here must match line_header.num_file_names.  */
675   unsigned int num_symtabs;
676
677   /* The symbol tables for this TU (obtained from the files listed in
678      DW_AT_stmt_list).
679      WARNING: The order of entries here must match the order of entries
680      in the line header.  After the first TU using this type_unit_group, the
681      line header for the subsequent TUs is recreated from this.  This is done
682      because we need to use the same symtabs for each TU using the same
683      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
684      there's no guarantee the line header doesn't have duplicate entries.  */
685   struct symtab **symtabs;
686 };
687
688 /* These sections are what may appear in a DWO file.  */
689
690 struct dwo_sections
691 {
692   struct dwarf2_section_info abbrev;
693   struct dwarf2_section_info line;
694   struct dwarf2_section_info loc;
695   struct dwarf2_section_info macinfo;
696   struct dwarf2_section_info macro;
697   struct dwarf2_section_info str;
698   struct dwarf2_section_info str_offsets;
699   /* In the case of a virtual DWO file, these two are unused.  */
700   struct dwarf2_section_info info;
701   VEC (dwarf2_section_info_def) *types;
702 };
703
704 /* CUs/TUs in DWP/DWO files.  */
705
706 struct dwo_unit
707 {
708   /* Backlink to the containing struct dwo_file.  */
709   struct dwo_file *dwo_file;
710
711   /* The "id" that distinguishes this CU/TU.
712      .debug_info calls this "dwo_id", .debug_types calls this "signature".
713      Since signatures came first, we stick with it for consistency.  */
714   ULONGEST signature;
715
716   /* The section this CU/TU lives in, in the DWO file.  */
717   struct dwarf2_section_info *section;
718
719   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
720   sect_offset offset;
721   unsigned int length;
722
723   /* For types, offset in the type's DIE of the type defined by this TU.  */
724   cu_offset type_offset_in_tu;
725 };
726
727 /* Data for one DWO file.
728    This includes virtual DWO files that have been packaged into a
729    DWP file.  */
730
731 struct dwo_file
732 {
733   /* The DW_AT_GNU_dwo_name attribute.  This is the hash key.
734      For virtual DWO files the name is constructed from the section offsets
735      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
736      from related CU+TUs.  */
737   const char *name;
738
739   /* The bfd, when the file is open.  Otherwise this is NULL.
740      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
741   bfd *dbfd;
742
743   /* Section info for this file.  */
744   struct dwo_sections sections;
745
746   /* Table of CUs in the file.
747      Each element is a struct dwo_unit.  */
748   htab_t cus;
749
750   /* Table of TUs in the file.
751      Each element is a struct dwo_unit.  */
752   htab_t tus;
753 };
754
755 /* These sections are what may appear in a DWP file.  */
756
757 struct dwp_sections
758 {
759   struct dwarf2_section_info str;
760   struct dwarf2_section_info cu_index;
761   struct dwarf2_section_info tu_index;
762   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
763      by section number.  We don't need to record them here.  */
764 };
765
766 /* These sections are what may appear in a virtual DWO file.  */
767
768 struct virtual_dwo_sections
769 {
770   struct dwarf2_section_info abbrev;
771   struct dwarf2_section_info line;
772   struct dwarf2_section_info loc;
773   struct dwarf2_section_info macinfo;
774   struct dwarf2_section_info macro;
775   struct dwarf2_section_info str_offsets;
776   /* Each DWP hash table entry records one CU or one TU.
777      That is recorded here, and copied to dwo_unit.section.  */
778   struct dwarf2_section_info info_or_types;
779 };
780
781 /* Contents of DWP hash tables.  */
782
783 struct dwp_hash_table
784 {
785   uint32_t nr_units, nr_slots;
786   const gdb_byte *hash_table, *unit_table, *section_pool;
787 };
788
789 /* Data for one DWP file.  */
790
791 struct dwp_file
792 {
793   /* Name of the file.  */
794   const char *name;
795
796   /* The bfd, when the file is open.  Otherwise this is NULL.  */
797   bfd *dbfd;
798
799   /* Section info for this file.  */
800   struct dwp_sections sections;
801
802   /* Table of CUs in the file. */
803   const struct dwp_hash_table *cus;
804
805   /* Table of TUs in the file.  */
806   const struct dwp_hash_table *tus;
807
808   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
809   htab_t loaded_cutus;
810
811   /* Table to map ELF section numbers to their sections.  */
812   unsigned int num_sections;
813   asection **elf_sections;
814 };
815
816 /* This represents a '.dwz' file.  */
817
818 struct dwz_file
819 {
820   /* A dwz file can only contain a few sections.  */
821   struct dwarf2_section_info abbrev;
822   struct dwarf2_section_info info;
823   struct dwarf2_section_info str;
824   struct dwarf2_section_info line;
825   struct dwarf2_section_info macro;
826   struct dwarf2_section_info gdb_index;
827
828   /* The dwz's BFD.  */
829   bfd *dwz_bfd;
830 };
831
832 /* Struct used to pass misc. parameters to read_die_and_children, et
833    al.  which are used for both .debug_info and .debug_types dies.
834    All parameters here are unchanging for the life of the call.  This
835    struct exists to abstract away the constant parameters of die reading.  */
836
837 struct die_reader_specs
838 {
839   /* die_section->asection->owner.  */
840   bfd* abfd;
841
842   /* The CU of the DIE we are parsing.  */
843   struct dwarf2_cu *cu;
844
845   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
846   struct dwo_file *dwo_file;
847
848   /* The section the die comes from.
849      This is either .debug_info or .debug_types, or the .dwo variants.  */
850   struct dwarf2_section_info *die_section;
851
852   /* die_section->buffer.  */
853   gdb_byte *buffer;
854
855   /* The end of the buffer.  */
856   const gdb_byte *buffer_end;
857 };
858
859 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
860 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
861                                       gdb_byte *info_ptr,
862                                       struct die_info *comp_unit_die,
863                                       int has_children,
864                                       void *data);
865
866 /* The line number information for a compilation unit (found in the
867    .debug_line section) begins with a "statement program header",
868    which contains the following information.  */
869 struct line_header
870 {
871   unsigned int total_length;
872   unsigned short version;
873   unsigned int header_length;
874   unsigned char minimum_instruction_length;
875   unsigned char maximum_ops_per_instruction;
876   unsigned char default_is_stmt;
877   int line_base;
878   unsigned char line_range;
879   unsigned char opcode_base;
880
881   /* standard_opcode_lengths[i] is the number of operands for the
882      standard opcode whose value is i.  This means that
883      standard_opcode_lengths[0] is unused, and the last meaningful
884      element is standard_opcode_lengths[opcode_base - 1].  */
885   unsigned char *standard_opcode_lengths;
886
887   /* The include_directories table.  NOTE!  These strings are not
888      allocated with xmalloc; instead, they are pointers into
889      debug_line_buffer.  If you try to free them, `free' will get
890      indigestion.  */
891   unsigned int num_include_dirs, include_dirs_size;
892   char **include_dirs;
893
894   /* The file_names table.  NOTE!  These strings are not allocated
895      with xmalloc; instead, they are pointers into debug_line_buffer.
896      Don't try to free them directly.  */
897   unsigned int num_file_names, file_names_size;
898   struct file_entry
899   {
900     char *name;
901     unsigned int dir_index;
902     unsigned int mod_time;
903     unsigned int length;
904     int included_p; /* Non-zero if referenced by the Line Number Program.  */
905     struct symtab *symtab; /* The associated symbol table, if any.  */
906   } *file_names;
907
908   /* The start and end of the statement program following this
909      header.  These point into dwarf2_per_objfile->line_buffer.  */
910   gdb_byte *statement_program_start, *statement_program_end;
911 };
912
913 /* When we construct a partial symbol table entry we only
914    need this much information.  */
915 struct partial_die_info
916   {
917     /* Offset of this DIE.  */
918     sect_offset offset;
919
920     /* DWARF-2 tag for this DIE.  */
921     ENUM_BITFIELD(dwarf_tag) tag : 16;
922
923     /* Assorted flags describing the data found in this DIE.  */
924     unsigned int has_children : 1;
925     unsigned int is_external : 1;
926     unsigned int is_declaration : 1;
927     unsigned int has_type : 1;
928     unsigned int has_specification : 1;
929     unsigned int has_pc_info : 1;
930     unsigned int may_be_inlined : 1;
931
932     /* Flag set if the SCOPE field of this structure has been
933        computed.  */
934     unsigned int scope_set : 1;
935
936     /* Flag set if the DIE has a byte_size attribute.  */
937     unsigned int has_byte_size : 1;
938
939     /* Flag set if any of the DIE's children are template arguments.  */
940     unsigned int has_template_arguments : 1;
941
942     /* Flag set if fixup_partial_die has been called on this die.  */
943     unsigned int fixup_called : 1;
944
945     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
946     unsigned int is_dwz : 1;
947
948     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
949     unsigned int spec_is_dwz : 1;
950
951     /* The name of this DIE.  Normally the value of DW_AT_name, but
952        sometimes a default name for unnamed DIEs.  */
953     const char *name;
954
955     /* The linkage name, if present.  */
956     const char *linkage_name;
957
958     /* The scope to prepend to our children.  This is generally
959        allocated on the comp_unit_obstack, so will disappear
960        when this compilation unit leaves the cache.  */
961     const char *scope;
962
963     /* Some data associated with the partial DIE.  The tag determines
964        which field is live.  */
965     union
966     {
967       /* The location description associated with this DIE, if any.  */
968       struct dwarf_block *locdesc;
969       /* The offset of an import, for DW_TAG_imported_unit.  */
970       sect_offset offset;
971     } d;
972
973     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
974     CORE_ADDR lowpc;
975     CORE_ADDR highpc;
976
977     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
978        DW_AT_sibling, if any.  */
979     /* NOTE: This member isn't strictly necessary, read_partial_die could
980        return DW_AT_sibling values to its caller load_partial_dies.  */
981     gdb_byte *sibling;
982
983     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
984        DW_AT_specification (or DW_AT_abstract_origin or
985        DW_AT_extension).  */
986     sect_offset spec_offset;
987
988     /* Pointers to this DIE's parent, first child, and next sibling,
989        if any.  */
990     struct partial_die_info *die_parent, *die_child, *die_sibling;
991   };
992
993 /* This data structure holds the information of an abbrev.  */
994 struct abbrev_info
995   {
996     unsigned int number;        /* number identifying abbrev */
997     enum dwarf_tag tag;         /* dwarf tag */
998     unsigned short has_children;                /* boolean */
999     unsigned short num_attrs;   /* number of attributes */
1000     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1001     struct abbrev_info *next;   /* next in chain */
1002   };
1003
1004 struct attr_abbrev
1005   {
1006     ENUM_BITFIELD(dwarf_attribute) name : 16;
1007     ENUM_BITFIELD(dwarf_form) form : 16;
1008   };
1009
1010 /* Size of abbrev_table.abbrev_hash_table.  */
1011 #define ABBREV_HASH_SIZE 121
1012
1013 /* Top level data structure to contain an abbreviation table.  */
1014
1015 struct abbrev_table
1016 {
1017   /* Where the abbrev table came from.
1018      This is used as a sanity check when the table is used.  */
1019   sect_offset offset;
1020
1021   /* Storage for the abbrev table.  */
1022   struct obstack abbrev_obstack;
1023
1024   /* Hash table of abbrevs.
1025      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1026      It could be statically allocated, but the previous code didn't so we
1027      don't either.  */
1028   struct abbrev_info **abbrevs;
1029 };
1030
1031 /* Attributes have a name and a value.  */
1032 struct attribute
1033   {
1034     ENUM_BITFIELD(dwarf_attribute) name : 16;
1035     ENUM_BITFIELD(dwarf_form) form : 15;
1036
1037     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1038        field should be in u.str (existing only for DW_STRING) but it is kept
1039        here for better struct attribute alignment.  */
1040     unsigned int string_is_canonical : 1;
1041
1042     union
1043       {
1044         const char *str;
1045         struct dwarf_block *blk;
1046         ULONGEST unsnd;
1047         LONGEST snd;
1048         CORE_ADDR addr;
1049         struct signatured_type *signatured_type;
1050       }
1051     u;
1052   };
1053
1054 /* This data structure holds a complete die structure.  */
1055 struct die_info
1056   {
1057     /* DWARF-2 tag for this DIE.  */
1058     ENUM_BITFIELD(dwarf_tag) tag : 16;
1059
1060     /* Number of attributes */
1061     unsigned char num_attrs;
1062
1063     /* True if we're presently building the full type name for the
1064        type derived from this DIE.  */
1065     unsigned char building_fullname : 1;
1066
1067     /* Abbrev number */
1068     unsigned int abbrev;
1069
1070     /* Offset in .debug_info or .debug_types section.  */
1071     sect_offset offset;
1072
1073     /* The dies in a compilation unit form an n-ary tree.  PARENT
1074        points to this die's parent; CHILD points to the first child of
1075        this node; and all the children of a given node are chained
1076        together via their SIBLING fields.  */
1077     struct die_info *child;     /* Its first child, if any.  */
1078     struct die_info *sibling;   /* Its next sibling, if any.  */
1079     struct die_info *parent;    /* Its parent, if any.  */
1080
1081     /* An array of attributes, with NUM_ATTRS elements.  There may be
1082        zero, but it's not common and zero-sized arrays are not
1083        sufficiently portable C.  */
1084     struct attribute attrs[1];
1085   };
1086
1087 /* Get at parts of an attribute structure.  */
1088
1089 #define DW_STRING(attr)    ((attr)->u.str)
1090 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1091 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1092 #define DW_BLOCK(attr)     ((attr)->u.blk)
1093 #define DW_SND(attr)       ((attr)->u.snd)
1094 #define DW_ADDR(attr)      ((attr)->u.addr)
1095 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
1096
1097 /* Blocks are a bunch of untyped bytes.  */
1098 struct dwarf_block
1099   {
1100     size_t size;
1101
1102     /* Valid only if SIZE is not zero.  */
1103     gdb_byte *data;
1104   };
1105
1106 #ifndef ATTR_ALLOC_CHUNK
1107 #define ATTR_ALLOC_CHUNK 4
1108 #endif
1109
1110 /* Allocate fields for structs, unions and enums in this size.  */
1111 #ifndef DW_FIELD_ALLOC_CHUNK
1112 #define DW_FIELD_ALLOC_CHUNK 4
1113 #endif
1114
1115 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1116    but this would require a corresponding change in unpack_field_as_long
1117    and friends.  */
1118 static int bits_per_byte = 8;
1119
1120 /* The routines that read and process dies for a C struct or C++ class
1121    pass lists of data member fields and lists of member function fields
1122    in an instance of a field_info structure, as defined below.  */
1123 struct field_info
1124   {
1125     /* List of data member and baseclasses fields.  */
1126     struct nextfield
1127       {
1128         struct nextfield *next;
1129         int accessibility;
1130         int virtuality;
1131         struct field field;
1132       }
1133      *fields, *baseclasses;
1134
1135     /* Number of fields (including baseclasses).  */
1136     int nfields;
1137
1138     /* Number of baseclasses.  */
1139     int nbaseclasses;
1140
1141     /* Set if the accesibility of one of the fields is not public.  */
1142     int non_public_fields;
1143
1144     /* Member function fields array, entries are allocated in the order they
1145        are encountered in the object file.  */
1146     struct nextfnfield
1147       {
1148         struct nextfnfield *next;
1149         struct fn_field fnfield;
1150       }
1151      *fnfields;
1152
1153     /* Member function fieldlist array, contains name of possibly overloaded
1154        member function, number of overloaded member functions and a pointer
1155        to the head of the member function field chain.  */
1156     struct fnfieldlist
1157       {
1158         const char *name;
1159         int length;
1160         struct nextfnfield *head;
1161       }
1162      *fnfieldlists;
1163
1164     /* Number of entries in the fnfieldlists array.  */
1165     int nfnfields;
1166
1167     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1168        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1169     struct typedef_field_list
1170       {
1171         struct typedef_field field;
1172         struct typedef_field_list *next;
1173       }
1174     *typedef_field_list;
1175     unsigned typedef_field_list_count;
1176   };
1177
1178 /* One item on the queue of compilation units to read in full symbols
1179    for.  */
1180 struct dwarf2_queue_item
1181 {
1182   struct dwarf2_per_cu_data *per_cu;
1183   enum language pretend_language;
1184   struct dwarf2_queue_item *next;
1185 };
1186
1187 /* The current queue.  */
1188 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1189
1190 /* Loaded secondary compilation units are kept in memory until they
1191    have not been referenced for the processing of this many
1192    compilation units.  Set this to zero to disable caching.  Cache
1193    sizes of up to at least twenty will improve startup time for
1194    typical inter-CU-reference binaries, at an obvious memory cost.  */
1195 static int dwarf2_max_cache_age = 5;
1196 static void
1197 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1198                            struct cmd_list_element *c, const char *value)
1199 {
1200   fprintf_filtered (file, _("The upper bound on the age of cached "
1201                             "dwarf2 compilation units is %s.\n"),
1202                     value);
1203 }
1204
1205
1206 /* Various complaints about symbol reading that don't abort the process.  */
1207
1208 static void
1209 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1210 {
1211   complaint (&symfile_complaints,
1212              _("statement list doesn't fit in .debug_line section"));
1213 }
1214
1215 static void
1216 dwarf2_debug_line_missing_file_complaint (void)
1217 {
1218   complaint (&symfile_complaints,
1219              _(".debug_line section has line data without a file"));
1220 }
1221
1222 static void
1223 dwarf2_debug_line_missing_end_sequence_complaint (void)
1224 {
1225   complaint (&symfile_complaints,
1226              _(".debug_line section has line "
1227                "program sequence without an end"));
1228 }
1229
1230 static void
1231 dwarf2_complex_location_expr_complaint (void)
1232 {
1233   complaint (&symfile_complaints, _("location expression too complex"));
1234 }
1235
1236 static void
1237 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1238                                               int arg3)
1239 {
1240   complaint (&symfile_complaints,
1241              _("const value length mismatch for '%s', got %d, expected %d"),
1242              arg1, arg2, arg3);
1243 }
1244
1245 static void
1246 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1247 {
1248   complaint (&symfile_complaints,
1249              _("debug info runs off end of %s section"
1250                " [in module %s]"),
1251              section->asection->name,
1252              bfd_get_filename (section->asection->owner));
1253 }
1254
1255 static void
1256 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1257 {
1258   complaint (&symfile_complaints,
1259              _("macro debug info contains a "
1260                "malformed macro definition:\n`%s'"),
1261              arg1);
1262 }
1263
1264 static void
1265 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1266 {
1267   complaint (&symfile_complaints,
1268              _("invalid attribute class or form for '%s' in '%s'"),
1269              arg1, arg2);
1270 }
1271
1272 /* local function prototypes */
1273
1274 static void dwarf2_locate_sections (bfd *, asection *, void *);
1275
1276 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1277                                            struct objfile *);
1278
1279 static void dwarf2_find_base_address (struct die_info *die,
1280                                       struct dwarf2_cu *cu);
1281
1282 static struct partial_symtab *create_partial_symtab
1283   (struct dwarf2_per_cu_data *per_cu, const char *name);
1284
1285 static void dwarf2_build_psymtabs_hard (struct objfile *);
1286
1287 static void scan_partial_symbols (struct partial_die_info *,
1288                                   CORE_ADDR *, CORE_ADDR *,
1289                                   int, struct dwarf2_cu *);
1290
1291 static void add_partial_symbol (struct partial_die_info *,
1292                                 struct dwarf2_cu *);
1293
1294 static void add_partial_namespace (struct partial_die_info *pdi,
1295                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1296                                    int need_pc, struct dwarf2_cu *cu);
1297
1298 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1299                                 CORE_ADDR *highpc, int need_pc,
1300                                 struct dwarf2_cu *cu);
1301
1302 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1303                                      struct dwarf2_cu *cu);
1304
1305 static void add_partial_subprogram (struct partial_die_info *pdi,
1306                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1307                                     int need_pc, struct dwarf2_cu *cu);
1308
1309 static void dwarf2_read_symtab (struct partial_symtab *,
1310                                 struct objfile *);
1311
1312 static void psymtab_to_symtab_1 (struct partial_symtab *);
1313
1314 static struct abbrev_info *abbrev_table_lookup_abbrev
1315   (const struct abbrev_table *, unsigned int);
1316
1317 static struct abbrev_table *abbrev_table_read_table
1318   (struct dwarf2_section_info *, sect_offset);
1319
1320 static void abbrev_table_free (struct abbrev_table *);
1321
1322 static void abbrev_table_free_cleanup (void *);
1323
1324 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1325                                  struct dwarf2_section_info *);
1326
1327 static void dwarf2_free_abbrev_table (void *);
1328
1329 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1330
1331 static struct partial_die_info *load_partial_dies
1332   (const struct die_reader_specs *, gdb_byte *, int);
1333
1334 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1335                                    struct partial_die_info *,
1336                                    struct abbrev_info *,
1337                                    unsigned int,
1338                                    gdb_byte *);
1339
1340 static struct partial_die_info *find_partial_die (sect_offset, int,
1341                                                   struct dwarf2_cu *);
1342
1343 static void fixup_partial_die (struct partial_die_info *,
1344                                struct dwarf2_cu *);
1345
1346 static gdb_byte *read_attribute (const struct die_reader_specs *,
1347                                  struct attribute *, struct attr_abbrev *,
1348                                  gdb_byte *);
1349
1350 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1351
1352 static int read_1_signed_byte (bfd *, const gdb_byte *);
1353
1354 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1355
1356 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1357
1358 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1359
1360 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1361                                unsigned int *);
1362
1363 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1364
1365 static LONGEST read_checked_initial_length_and_offset
1366   (bfd *, gdb_byte *, const struct comp_unit_head *,
1367    unsigned int *, unsigned int *);
1368
1369 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1370                             unsigned int *);
1371
1372 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1373
1374 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1375                                        sect_offset);
1376
1377 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1378
1379 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1380
1381 static char *read_indirect_string (bfd *, gdb_byte *,
1382                                    const struct comp_unit_head *,
1383                                    unsigned int *);
1384
1385 static char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1386
1387 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1388
1389 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1390
1391 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1392                                               unsigned int *);
1393
1394 static char *read_str_index (const struct die_reader_specs *reader,
1395                              struct dwarf2_cu *cu, ULONGEST str_index);
1396
1397 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1398
1399 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1400                                       struct dwarf2_cu *);
1401
1402 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1403                                                 unsigned int);
1404
1405 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1406                                struct dwarf2_cu *cu);
1407
1408 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1409
1410 static struct die_info *die_specification (struct die_info *die,
1411                                            struct dwarf2_cu **);
1412
1413 static void free_line_header (struct line_header *lh);
1414
1415 static void add_file_name (struct line_header *, char *, unsigned int,
1416                            unsigned int, unsigned int);
1417
1418 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1419                                                      struct dwarf2_cu *cu);
1420
1421 static void dwarf_decode_lines (struct line_header *, const char *,
1422                                 struct dwarf2_cu *, struct partial_symtab *,
1423                                 int);
1424
1425 static void dwarf2_start_subfile (char *, const char *, const char *);
1426
1427 static void dwarf2_start_symtab (struct dwarf2_cu *,
1428                                  const char *, const char *, CORE_ADDR);
1429
1430 static struct symbol *new_symbol (struct die_info *, struct type *,
1431                                   struct dwarf2_cu *);
1432
1433 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1434                                        struct dwarf2_cu *, struct symbol *);
1435
1436 static void dwarf2_const_value (struct attribute *, struct symbol *,
1437                                 struct dwarf2_cu *);
1438
1439 static void dwarf2_const_value_attr (struct attribute *attr,
1440                                      struct type *type,
1441                                      const char *name,
1442                                      struct obstack *obstack,
1443                                      struct dwarf2_cu *cu, LONGEST *value,
1444                                      gdb_byte **bytes,
1445                                      struct dwarf2_locexpr_baton **baton);
1446
1447 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1448
1449 static int need_gnat_info (struct dwarf2_cu *);
1450
1451 static struct type *die_descriptive_type (struct die_info *,
1452                                           struct dwarf2_cu *);
1453
1454 static void set_descriptive_type (struct type *, struct die_info *,
1455                                   struct dwarf2_cu *);
1456
1457 static struct type *die_containing_type (struct die_info *,
1458                                          struct dwarf2_cu *);
1459
1460 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1461                                      struct dwarf2_cu *);
1462
1463 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1464
1465 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1466
1467 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1468
1469 static char *typename_concat (struct obstack *obs, const char *prefix,
1470                               const char *suffix, int physname,
1471                               struct dwarf2_cu *cu);
1472
1473 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1474
1475 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1476
1477 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1478
1479 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1480
1481 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1482
1483 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1484                                struct dwarf2_cu *, struct partial_symtab *);
1485
1486 static int dwarf2_get_pc_bounds (struct die_info *,
1487                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1488                                  struct partial_symtab *);
1489
1490 static void get_scope_pc_bounds (struct die_info *,
1491                                  CORE_ADDR *, CORE_ADDR *,
1492                                  struct dwarf2_cu *);
1493
1494 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1495                                         CORE_ADDR, struct dwarf2_cu *);
1496
1497 static void dwarf2_add_field (struct field_info *, struct die_info *,
1498                               struct dwarf2_cu *);
1499
1500 static void dwarf2_attach_fields_to_type (struct field_info *,
1501                                           struct type *, struct dwarf2_cu *);
1502
1503 static void dwarf2_add_member_fn (struct field_info *,
1504                                   struct die_info *, struct type *,
1505                                   struct dwarf2_cu *);
1506
1507 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1508                                              struct type *,
1509                                              struct dwarf2_cu *);
1510
1511 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1512
1513 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1514
1515 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1516
1517 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1518
1519 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1520
1521 static struct type *read_module_type (struct die_info *die,
1522                                       struct dwarf2_cu *cu);
1523
1524 static const char *namespace_name (struct die_info *die,
1525                                    int *is_anonymous, struct dwarf2_cu *);
1526
1527 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1528
1529 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1530
1531 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1532                                                        struct dwarf2_cu *);
1533
1534 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1535                                                gdb_byte *info_ptr,
1536                                                gdb_byte **new_info_ptr,
1537                                                struct die_info *parent);
1538
1539 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1540                                                gdb_byte *info_ptr,
1541                                                gdb_byte **new_info_ptr,
1542                                                struct die_info *parent);
1543
1544 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1545                                   struct die_info **, gdb_byte *, int *, int);
1546
1547 static gdb_byte *read_full_die (const struct die_reader_specs *,
1548                                 struct die_info **, gdb_byte *, int *);
1549
1550 static void process_die (struct die_info *, struct dwarf2_cu *);
1551
1552 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1553                                              struct obstack *);
1554
1555 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1556
1557 static const char *dwarf2_full_name (const char *name,
1558                                      struct die_info *die,
1559                                      struct dwarf2_cu *cu);
1560
1561 static const char *dwarf2_physname (const char *name, struct die_info *die,
1562                                     struct dwarf2_cu *cu);
1563
1564 static struct die_info *dwarf2_extension (struct die_info *die,
1565                                           struct dwarf2_cu **);
1566
1567 static const char *dwarf_tag_name (unsigned int);
1568
1569 static const char *dwarf_attr_name (unsigned int);
1570
1571 static const char *dwarf_form_name (unsigned int);
1572
1573 static char *dwarf_bool_name (unsigned int);
1574
1575 static const char *dwarf_type_encoding_name (unsigned int);
1576
1577 static struct die_info *sibling_die (struct die_info *);
1578
1579 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1580
1581 static void dump_die_for_error (struct die_info *);
1582
1583 static void dump_die_1 (struct ui_file *, int level, int max_level,
1584                         struct die_info *);
1585
1586 /*static*/ void dump_die (struct die_info *, int max_level);
1587
1588 static void store_in_ref_table (struct die_info *,
1589                                 struct dwarf2_cu *);
1590
1591 static int is_ref_attr (struct attribute *);
1592
1593 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1594
1595 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1596
1597 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1598                                                struct attribute *,
1599                                                struct dwarf2_cu **);
1600
1601 static struct die_info *follow_die_ref (struct die_info *,
1602                                         struct attribute *,
1603                                         struct dwarf2_cu **);
1604
1605 static struct die_info *follow_die_sig (struct die_info *,
1606                                         struct attribute *,
1607                                         struct dwarf2_cu **);
1608
1609 static struct signatured_type *lookup_signatured_type_at_offset
1610     (struct objfile *objfile,
1611      struct dwarf2_section_info *section, sect_offset offset);
1612
1613 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1614
1615 static void read_signatured_type (struct signatured_type *);
1616
1617 static struct type_unit_group *get_type_unit_group
1618     (struct dwarf2_cu *, struct attribute *);
1619
1620 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1621
1622 /* memory allocation interface */
1623
1624 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1625
1626 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1627
1628 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1629                                  const char *, int);
1630
1631 static int attr_form_is_block (struct attribute *);
1632
1633 static int attr_form_is_section_offset (struct attribute *);
1634
1635 static int attr_form_is_constant (struct attribute *);
1636
1637 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1638                                    struct dwarf2_loclist_baton *baton,
1639                                    struct attribute *attr);
1640
1641 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1642                                          struct symbol *sym,
1643                                          struct dwarf2_cu *cu,
1644                                          int is_block);
1645
1646 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1647                                gdb_byte *info_ptr,
1648                                struct abbrev_info *abbrev);
1649
1650 static void free_stack_comp_unit (void *);
1651
1652 static hashval_t partial_die_hash (const void *item);
1653
1654 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1655
1656 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1657   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1658
1659 static void init_one_comp_unit (struct dwarf2_cu *cu,
1660                                 struct dwarf2_per_cu_data *per_cu);
1661
1662 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1663                                    struct die_info *comp_unit_die,
1664                                    enum language pretend_language);
1665
1666 static void free_heap_comp_unit (void *);
1667
1668 static void free_cached_comp_units (void *);
1669
1670 static void age_cached_comp_units (void);
1671
1672 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1673
1674 static struct type *set_die_type (struct die_info *, struct type *,
1675                                   struct dwarf2_cu *);
1676
1677 static void create_all_comp_units (struct objfile *);
1678
1679 static int create_all_type_units (struct objfile *);
1680
1681 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1682                                  enum language);
1683
1684 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1685                                     enum language);
1686
1687 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1688                                     enum language);
1689
1690 static void dwarf2_add_dependence (struct dwarf2_cu *,
1691                                    struct dwarf2_per_cu_data *);
1692
1693 static void dwarf2_mark (struct dwarf2_cu *);
1694
1695 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1696
1697 static struct type *get_die_type_at_offset (sect_offset,
1698                                             struct dwarf2_per_cu_data *per_cu);
1699
1700 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1701
1702 static void dwarf2_release_queue (void *dummy);
1703
1704 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1705                              enum language pretend_language);
1706
1707 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1708                                   struct dwarf2_per_cu_data *per_cu,
1709                                   enum language pretend_language);
1710
1711 static void process_queue (void);
1712
1713 static void find_file_and_directory (struct die_info *die,
1714                                      struct dwarf2_cu *cu,
1715                                      const char **name, const char **comp_dir);
1716
1717 static char *file_full_name (int file, struct line_header *lh,
1718                              const char *comp_dir);
1719
1720 static gdb_byte *read_and_check_comp_unit_head
1721   (struct comp_unit_head *header,
1722    struct dwarf2_section_info *section,
1723    struct dwarf2_section_info *abbrev_section, gdb_byte *info_ptr,
1724    int is_debug_types_section);
1725
1726 static void init_cutu_and_read_dies
1727   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1728    int use_existing_cu, int keep,
1729    die_reader_func_ftype *die_reader_func, void *data);
1730
1731 static void init_cutu_and_read_dies_simple
1732   (struct dwarf2_per_cu_data *this_cu,
1733    die_reader_func_ftype *die_reader_func, void *data);
1734
1735 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1736
1737 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1738
1739 static struct dwo_unit *lookup_dwo_comp_unit
1740   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1741
1742 static struct dwo_unit *lookup_dwo_type_unit
1743   (struct signatured_type *, const char *, const char *);
1744
1745 static void free_dwo_file_cleanup (void *);
1746
1747 static void process_cu_includes (void);
1748
1749 static void check_producer (struct dwarf2_cu *cu);
1750
1751 #if WORDS_BIGENDIAN
1752
1753 /* Convert VALUE between big- and little-endian.  */
1754 static offset_type
1755 byte_swap (offset_type value)
1756 {
1757   offset_type result;
1758
1759   result = (value & 0xff) << 24;
1760   result |= (value & 0xff00) << 8;
1761   result |= (value & 0xff0000) >> 8;
1762   result |= (value & 0xff000000) >> 24;
1763   return result;
1764 }
1765
1766 #define MAYBE_SWAP(V)  byte_swap (V)
1767
1768 #else
1769 #define MAYBE_SWAP(V) (V)
1770 #endif /* WORDS_BIGENDIAN */
1771
1772 /* The suffix for an index file.  */
1773 #define INDEX_SUFFIX ".gdb-index"
1774
1775 /* Try to locate the sections we need for DWARF 2 debugging
1776    information and return true if we have enough to do something.
1777    NAMES points to the dwarf2 section names, or is NULL if the standard
1778    ELF names are used.  */
1779
1780 int
1781 dwarf2_has_info (struct objfile *objfile,
1782                  const struct dwarf2_debug_sections *names)
1783 {
1784   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1785   if (!dwarf2_per_objfile)
1786     {
1787       /* Initialize per-objfile state.  */
1788       struct dwarf2_per_objfile *data
1789         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1790
1791       memset (data, 0, sizeof (*data));
1792       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1793       dwarf2_per_objfile = data;
1794
1795       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1796                              (void *) names);
1797       dwarf2_per_objfile->objfile = objfile;
1798     }
1799   return (dwarf2_per_objfile->info.asection != NULL
1800           && dwarf2_per_objfile->abbrev.asection != NULL);
1801 }
1802
1803 /* When loading sections, we look either for uncompressed section or for
1804    compressed section names.  */
1805
1806 static int
1807 section_is_p (const char *section_name,
1808               const struct dwarf2_section_names *names)
1809 {
1810   if (names->normal != NULL
1811       && strcmp (section_name, names->normal) == 0)
1812     return 1;
1813   if (names->compressed != NULL
1814       && strcmp (section_name, names->compressed) == 0)
1815     return 1;
1816   return 0;
1817 }
1818
1819 /* This function is mapped across the sections and remembers the
1820    offset and size of each of the debugging sections we are interested
1821    in.  */
1822
1823 static void
1824 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1825 {
1826   const struct dwarf2_debug_sections *names;
1827   flagword aflag = bfd_get_section_flags (abfd, sectp);
1828
1829   if (vnames == NULL)
1830     names = &dwarf2_elf_names;
1831   else
1832     names = (const struct dwarf2_debug_sections *) vnames;
1833
1834   if ((aflag & SEC_HAS_CONTENTS) == 0)
1835     {
1836     }
1837   else if (section_is_p (sectp->name, &names->info))
1838     {
1839       dwarf2_per_objfile->info.asection = sectp;
1840       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1841     }
1842   else if (section_is_p (sectp->name, &names->abbrev))
1843     {
1844       dwarf2_per_objfile->abbrev.asection = sectp;
1845       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1846     }
1847   else if (section_is_p (sectp->name, &names->line))
1848     {
1849       dwarf2_per_objfile->line.asection = sectp;
1850       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1851     }
1852   else if (section_is_p (sectp->name, &names->loc))
1853     {
1854       dwarf2_per_objfile->loc.asection = sectp;
1855       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1856     }
1857   else if (section_is_p (sectp->name, &names->macinfo))
1858     {
1859       dwarf2_per_objfile->macinfo.asection = sectp;
1860       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1861     }
1862   else if (section_is_p (sectp->name, &names->macro))
1863     {
1864       dwarf2_per_objfile->macro.asection = sectp;
1865       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1866     }
1867   else if (section_is_p (sectp->name, &names->str))
1868     {
1869       dwarf2_per_objfile->str.asection = sectp;
1870       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1871     }
1872   else if (section_is_p (sectp->name, &names->addr))
1873     {
1874       dwarf2_per_objfile->addr.asection = sectp;
1875       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1876     }
1877   else if (section_is_p (sectp->name, &names->frame))
1878     {
1879       dwarf2_per_objfile->frame.asection = sectp;
1880       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1881     }
1882   else if (section_is_p (sectp->name, &names->eh_frame))
1883     {
1884       dwarf2_per_objfile->eh_frame.asection = sectp;
1885       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1886     }
1887   else if (section_is_p (sectp->name, &names->ranges))
1888     {
1889       dwarf2_per_objfile->ranges.asection = sectp;
1890       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1891     }
1892   else if (section_is_p (sectp->name, &names->types))
1893     {
1894       struct dwarf2_section_info type_section;
1895
1896       memset (&type_section, 0, sizeof (type_section));
1897       type_section.asection = sectp;
1898       type_section.size = bfd_get_section_size (sectp);
1899
1900       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1901                      &type_section);
1902     }
1903   else if (section_is_p (sectp->name, &names->gdb_index))
1904     {
1905       dwarf2_per_objfile->gdb_index.asection = sectp;
1906       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1907     }
1908
1909   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1910       && bfd_section_vma (abfd, sectp) == 0)
1911     dwarf2_per_objfile->has_section_at_zero = 1;
1912 }
1913
1914 /* A helper function that decides whether a section is empty,
1915    or not present.  */
1916
1917 static int
1918 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1919 {
1920   return info->asection == NULL || info->size == 0;
1921 }
1922
1923 /* Read the contents of the section INFO.
1924    OBJFILE is the main object file, but not necessarily the file where
1925    the section comes from.  E.g., for DWO files INFO->asection->owner
1926    is the bfd of the DWO file.
1927    If the section is compressed, uncompress it before returning.  */
1928
1929 static void
1930 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1931 {
1932   asection *sectp = info->asection;
1933   bfd *abfd;
1934   gdb_byte *buf, *retbuf;
1935   unsigned char header[4];
1936
1937   if (info->readin)
1938     return;
1939   info->buffer = NULL;
1940   info->readin = 1;
1941
1942   if (dwarf2_section_empty_p (info))
1943     return;
1944
1945   abfd = sectp->owner;
1946
1947   /* If the section has relocations, we must read it ourselves.
1948      Otherwise we attach it to the BFD.  */
1949   if ((sectp->flags & SEC_RELOC) == 0)
1950     {
1951       const gdb_byte *bytes = gdb_bfd_map_section (sectp, &info->size);
1952
1953       /* We have to cast away const here for historical reasons.
1954          Fixing dwarf2read to be const-correct would be quite nice.  */
1955       info->buffer = (gdb_byte *) bytes;
1956       return;
1957     }
1958
1959   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1960   info->buffer = buf;
1961
1962   /* When debugging .o files, we may need to apply relocations; see
1963      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1964      We never compress sections in .o files, so we only need to
1965      try this when the section is not compressed.  */
1966   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1967   if (retbuf != NULL)
1968     {
1969       info->buffer = retbuf;
1970       return;
1971     }
1972
1973   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1974       || bfd_bread (buf, info->size, abfd) != info->size)
1975     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1976            bfd_get_filename (abfd));
1977 }
1978
1979 /* A helper function that returns the size of a section in a safe way.
1980    If you are positive that the section has been read before using the
1981    size, then it is safe to refer to the dwarf2_section_info object's
1982    "size" field directly.  In other cases, you must call this
1983    function, because for compressed sections the size field is not set
1984    correctly until the section has been read.  */
1985
1986 static bfd_size_type
1987 dwarf2_section_size (struct objfile *objfile,
1988                      struct dwarf2_section_info *info)
1989 {
1990   if (!info->readin)
1991     dwarf2_read_section (objfile, info);
1992   return info->size;
1993 }
1994
1995 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1996    SECTION_NAME.  */
1997
1998 void
1999 dwarf2_get_section_info (struct objfile *objfile,
2000                          enum dwarf2_section_enum sect,
2001                          asection **sectp, gdb_byte **bufp,
2002                          bfd_size_type *sizep)
2003 {
2004   struct dwarf2_per_objfile *data
2005     = objfile_data (objfile, dwarf2_objfile_data_key);
2006   struct dwarf2_section_info *info;
2007
2008   /* We may see an objfile without any DWARF, in which case we just
2009      return nothing.  */
2010   if (data == NULL)
2011     {
2012       *sectp = NULL;
2013       *bufp = NULL;
2014       *sizep = 0;
2015       return;
2016     }
2017   switch (sect)
2018     {
2019     case DWARF2_DEBUG_FRAME:
2020       info = &data->frame;
2021       break;
2022     case DWARF2_EH_FRAME:
2023       info = &data->eh_frame;
2024       break;
2025     default:
2026       gdb_assert_not_reached ("unexpected section");
2027     }
2028
2029   dwarf2_read_section (objfile, info);
2030
2031   *sectp = info->asection;
2032   *bufp = info->buffer;
2033   *sizep = info->size;
2034 }
2035
2036 /* A helper function to find the sections for a .dwz file.  */
2037
2038 static void
2039 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2040 {
2041   struct dwz_file *dwz_file = arg;
2042
2043   /* Note that we only support the standard ELF names, because .dwz
2044      is ELF-only (at the time of writing).  */
2045   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2046     {
2047       dwz_file->abbrev.asection = sectp;
2048       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2049     }
2050   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2051     {
2052       dwz_file->info.asection = sectp;
2053       dwz_file->info.size = bfd_get_section_size (sectp);
2054     }
2055   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2056     {
2057       dwz_file->str.asection = sectp;
2058       dwz_file->str.size = bfd_get_section_size (sectp);
2059     }
2060   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2061     {
2062       dwz_file->line.asection = sectp;
2063       dwz_file->line.size = bfd_get_section_size (sectp);
2064     }
2065   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2066     {
2067       dwz_file->macro.asection = sectp;
2068       dwz_file->macro.size = bfd_get_section_size (sectp);
2069     }
2070   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2071     {
2072       dwz_file->gdb_index.asection = sectp;
2073       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2074     }
2075 }
2076
2077 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2078    cannot be found.  */
2079
2080 static struct dwz_file *
2081 dwarf2_get_dwz_file (void)
2082 {
2083   bfd *abfd, *dwz_bfd;
2084   asection *section;
2085   gdb_byte *data;
2086   struct cleanup *cleanup;
2087   const char *filename;
2088   struct dwz_file *result;
2089
2090   if (dwarf2_per_objfile->dwz_file != NULL)
2091     return dwarf2_per_objfile->dwz_file;
2092
2093   abfd = dwarf2_per_objfile->objfile->obfd;
2094   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2095   if (section == NULL)
2096     error (_("could not find '.gnu_debugaltlink' section"));
2097   if (!bfd_malloc_and_get_section (abfd, section, &data))
2098     error (_("could not read '.gnu_debugaltlink' section: %s"),
2099            bfd_errmsg (bfd_get_error ()));
2100   cleanup = make_cleanup (xfree, data);
2101
2102   filename = data;
2103   if (!IS_ABSOLUTE_PATH (filename))
2104     {
2105       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2106       char *rel;
2107
2108       make_cleanup (xfree, abs);
2109       abs = ldirname (abs);
2110       make_cleanup (xfree, abs);
2111
2112       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2113       make_cleanup (xfree, rel);
2114       filename = rel;
2115     }
2116
2117   /* The format is just a NUL-terminated file name, followed by the
2118      build-id.  For now, though, we ignore the build-id.  */
2119   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2120   if (dwz_bfd == NULL)
2121     error (_("could not read '%s': %s"), filename,
2122            bfd_errmsg (bfd_get_error ()));
2123
2124   if (!bfd_check_format (dwz_bfd, bfd_object))
2125     {
2126       gdb_bfd_unref (dwz_bfd);
2127       error (_("file '%s' was not usable: %s"), filename,
2128              bfd_errmsg (bfd_get_error ()));
2129     }
2130
2131   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2132                            struct dwz_file);
2133   result->dwz_bfd = dwz_bfd;
2134
2135   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2136
2137   do_cleanups (cleanup);
2138
2139   dwarf2_per_objfile->dwz_file = result;
2140   return result;
2141 }
2142 \f
2143 /* DWARF quick_symbols_functions support.  */
2144
2145 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2146    unique line tables, so we maintain a separate table of all .debug_line
2147    derived entries to support the sharing.
2148    All the quick functions need is the list of file names.  We discard the
2149    line_header when we're done and don't need to record it here.  */
2150 struct quick_file_names
2151 {
2152   /* The data used to construct the hash key.  */
2153   struct stmt_list_hash hash;
2154
2155   /* The number of entries in file_names, real_names.  */
2156   unsigned int num_file_names;
2157
2158   /* The file names from the line table, after being run through
2159      file_full_name.  */
2160   const char **file_names;
2161
2162   /* The file names from the line table after being run through
2163      gdb_realpath.  These are computed lazily.  */
2164   const char **real_names;
2165 };
2166
2167 /* When using the index (and thus not using psymtabs), each CU has an
2168    object of this type.  This is used to hold information needed by
2169    the various "quick" methods.  */
2170 struct dwarf2_per_cu_quick_data
2171 {
2172   /* The file table.  This can be NULL if there was no file table
2173      or it's currently not read in.
2174      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2175   struct quick_file_names *file_names;
2176
2177   /* The corresponding symbol table.  This is NULL if symbols for this
2178      CU have not yet been read.  */
2179   struct symtab *symtab;
2180
2181   /* A temporary mark bit used when iterating over all CUs in
2182      expand_symtabs_matching.  */
2183   unsigned int mark : 1;
2184
2185   /* True if we've tried to read the file table and found there isn't one.
2186      There will be no point in trying to read it again next time.  */
2187   unsigned int no_file_data : 1;
2188 };
2189
2190 /* Utility hash function for a stmt_list_hash.  */
2191
2192 static hashval_t
2193 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2194 {
2195   hashval_t v = 0;
2196
2197   if (stmt_list_hash->dwo_unit != NULL)
2198     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2199   v += stmt_list_hash->line_offset.sect_off;
2200   return v;
2201 }
2202
2203 /* Utility equality function for a stmt_list_hash.  */
2204
2205 static int
2206 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2207                     const struct stmt_list_hash *rhs)
2208 {
2209   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2210     return 0;
2211   if (lhs->dwo_unit != NULL
2212       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2213     return 0;
2214
2215   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2216 }
2217
2218 /* Hash function for a quick_file_names.  */
2219
2220 static hashval_t
2221 hash_file_name_entry (const void *e)
2222 {
2223   const struct quick_file_names *file_data = e;
2224
2225   return hash_stmt_list_entry (&file_data->hash);
2226 }
2227
2228 /* Equality function for a quick_file_names.  */
2229
2230 static int
2231 eq_file_name_entry (const void *a, const void *b)
2232 {
2233   const struct quick_file_names *ea = a;
2234   const struct quick_file_names *eb = b;
2235
2236   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2237 }
2238
2239 /* Delete function for a quick_file_names.  */
2240
2241 static void
2242 delete_file_name_entry (void *e)
2243 {
2244   struct quick_file_names *file_data = e;
2245   int i;
2246
2247   for (i = 0; i < file_data->num_file_names; ++i)
2248     {
2249       xfree ((void*) file_data->file_names[i]);
2250       if (file_data->real_names)
2251         xfree ((void*) file_data->real_names[i]);
2252     }
2253
2254   /* The space for the struct itself lives on objfile_obstack,
2255      so we don't free it here.  */
2256 }
2257
2258 /* Create a quick_file_names hash table.  */
2259
2260 static htab_t
2261 create_quick_file_names_table (unsigned int nr_initial_entries)
2262 {
2263   return htab_create_alloc (nr_initial_entries,
2264                             hash_file_name_entry, eq_file_name_entry,
2265                             delete_file_name_entry, xcalloc, xfree);
2266 }
2267
2268 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2269    have to be created afterwards.  You should call age_cached_comp_units after
2270    processing PER_CU->CU.  dw2_setup must have been already called.  */
2271
2272 static void
2273 load_cu (struct dwarf2_per_cu_data *per_cu)
2274 {
2275   if (per_cu->is_debug_types)
2276     load_full_type_unit (per_cu);
2277   else
2278     load_full_comp_unit (per_cu, language_minimal);
2279
2280   gdb_assert (per_cu->cu != NULL);
2281
2282   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2283 }
2284
2285 /* Read in the symbols for PER_CU.  */
2286
2287 static void
2288 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2289 {
2290   struct cleanup *back_to;
2291
2292   /* Skip type_unit_groups, reading the type units they contain
2293      is handled elsewhere.  */
2294   if (IS_TYPE_UNIT_GROUP (per_cu))
2295     return;
2296
2297   back_to = make_cleanup (dwarf2_release_queue, NULL);
2298
2299   if (dwarf2_per_objfile->using_index
2300       ? per_cu->v.quick->symtab == NULL
2301       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2302     {
2303       queue_comp_unit (per_cu, language_minimal);
2304       load_cu (per_cu);
2305     }
2306
2307   process_queue ();
2308
2309   /* Age the cache, releasing compilation units that have not
2310      been used recently.  */
2311   age_cached_comp_units ();
2312
2313   do_cleanups (back_to);
2314 }
2315
2316 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2317    the objfile from which this CU came.  Returns the resulting symbol
2318    table.  */
2319
2320 static struct symtab *
2321 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2322 {
2323   gdb_assert (dwarf2_per_objfile->using_index);
2324   if (!per_cu->v.quick->symtab)
2325     {
2326       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2327       increment_reading_symtab ();
2328       dw2_do_instantiate_symtab (per_cu);
2329       process_cu_includes ();
2330       do_cleanups (back_to);
2331     }
2332   return per_cu->v.quick->symtab;
2333 }
2334
2335 /* Return the CU given its index.
2336
2337    This is intended for loops like:
2338
2339    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2340                     + dwarf2_per_objfile->n_type_units); ++i)
2341      {
2342        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2343
2344        ...;
2345      }
2346 */
2347
2348 static struct dwarf2_per_cu_data *
2349 dw2_get_cu (int index)
2350 {
2351   if (index >= dwarf2_per_objfile->n_comp_units)
2352     {
2353       index -= dwarf2_per_objfile->n_comp_units;
2354       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2355       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2356     }
2357
2358   return dwarf2_per_objfile->all_comp_units[index];
2359 }
2360
2361 /* Return the primary CU given its index.
2362    The difference between this function and dw2_get_cu is in the handling
2363    of type units (TUs).  Here we return the type_unit_group object.
2364
2365    This is intended for loops like:
2366
2367    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2368                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2369      {
2370        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2371
2372        ...;
2373      }
2374 */
2375
2376 static struct dwarf2_per_cu_data *
2377 dw2_get_primary_cu (int index)
2378 {
2379   if (index >= dwarf2_per_objfile->n_comp_units)
2380     {
2381       index -= dwarf2_per_objfile->n_comp_units;
2382       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2383       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2384     }
2385
2386   return dwarf2_per_objfile->all_comp_units[index];
2387 }
2388
2389 /* A helper for create_cus_from_index that handles a given list of
2390    CUs.  */
2391
2392 static void
2393 create_cus_from_index_list (struct objfile *objfile,
2394                             const gdb_byte *cu_list, offset_type n_elements,
2395                             struct dwarf2_section_info *section,
2396                             int is_dwz,
2397                             int base_offset)
2398 {
2399   offset_type i;
2400
2401   for (i = 0; i < n_elements; i += 2)
2402     {
2403       struct dwarf2_per_cu_data *the_cu;
2404       ULONGEST offset, length;
2405
2406       gdb_static_assert (sizeof (ULONGEST) >= 8);
2407       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2408       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2409       cu_list += 2 * 8;
2410
2411       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2412                                struct dwarf2_per_cu_data);
2413       the_cu->offset.sect_off = offset;
2414       the_cu->length = length;
2415       the_cu->objfile = objfile;
2416       the_cu->section = section;
2417       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2418                                         struct dwarf2_per_cu_quick_data);
2419       the_cu->is_dwz = is_dwz;
2420       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2421     }
2422 }
2423
2424 /* Read the CU list from the mapped index, and use it to create all
2425    the CU objects for this objfile.  */
2426
2427 static void
2428 create_cus_from_index (struct objfile *objfile,
2429                        const gdb_byte *cu_list, offset_type cu_list_elements,
2430                        const gdb_byte *dwz_list, offset_type dwz_elements)
2431 {
2432   struct dwz_file *dwz;
2433
2434   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2435   dwarf2_per_objfile->all_comp_units
2436     = obstack_alloc (&objfile->objfile_obstack,
2437                      dwarf2_per_objfile->n_comp_units
2438                      * sizeof (struct dwarf2_per_cu_data *));
2439
2440   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2441                               &dwarf2_per_objfile->info, 0, 0);
2442
2443   if (dwz_elements == 0)
2444     return;
2445
2446   dwz = dwarf2_get_dwz_file ();
2447   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2448                               cu_list_elements / 2);
2449 }
2450
2451 /* Create the signatured type hash table from the index.  */
2452
2453 static void
2454 create_signatured_type_table_from_index (struct objfile *objfile,
2455                                          struct dwarf2_section_info *section,
2456                                          const gdb_byte *bytes,
2457                                          offset_type elements)
2458 {
2459   offset_type i;
2460   htab_t sig_types_hash;
2461
2462   dwarf2_per_objfile->n_type_units = elements / 3;
2463   dwarf2_per_objfile->all_type_units
2464     = obstack_alloc (&objfile->objfile_obstack,
2465                      dwarf2_per_objfile->n_type_units
2466                      * sizeof (struct signatured_type *));
2467
2468   sig_types_hash = allocate_signatured_type_table (objfile);
2469
2470   for (i = 0; i < elements; i += 3)
2471     {
2472       struct signatured_type *sig_type;
2473       ULONGEST offset, type_offset_in_tu, signature;
2474       void **slot;
2475
2476       gdb_static_assert (sizeof (ULONGEST) >= 8);
2477       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2478       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2479                                                     BFD_ENDIAN_LITTLE);
2480       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2481       bytes += 3 * 8;
2482
2483       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2484                                  struct signatured_type);
2485       sig_type->signature = signature;
2486       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2487       sig_type->per_cu.is_debug_types = 1;
2488       sig_type->per_cu.section = section;
2489       sig_type->per_cu.offset.sect_off = offset;
2490       sig_type->per_cu.objfile = objfile;
2491       sig_type->per_cu.v.quick
2492         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2493                           struct dwarf2_per_cu_quick_data);
2494
2495       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2496       *slot = sig_type;
2497
2498       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2499     }
2500
2501   dwarf2_per_objfile->signatured_types = sig_types_hash;
2502 }
2503
2504 /* Read the address map data from the mapped index, and use it to
2505    populate the objfile's psymtabs_addrmap.  */
2506
2507 static void
2508 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2509 {
2510   const gdb_byte *iter, *end;
2511   struct obstack temp_obstack;
2512   struct addrmap *mutable_map;
2513   struct cleanup *cleanup;
2514   CORE_ADDR baseaddr;
2515
2516   obstack_init (&temp_obstack);
2517   cleanup = make_cleanup_obstack_free (&temp_obstack);
2518   mutable_map = addrmap_create_mutable (&temp_obstack);
2519
2520   iter = index->address_table;
2521   end = iter + index->address_table_size;
2522
2523   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2524
2525   while (iter < end)
2526     {
2527       ULONGEST hi, lo, cu_index;
2528       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2529       iter += 8;
2530       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2531       iter += 8;
2532       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2533       iter += 4;
2534
2535       if (cu_index < dwarf2_per_objfile->n_comp_units)
2536         {
2537           addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2538                              dw2_get_cu (cu_index));
2539         }
2540       else
2541         {
2542           complaint (&symfile_complaints,
2543                      _(".gdb_index address table has invalid CU number %u"),
2544                      (unsigned) cu_index);
2545         }
2546     }
2547
2548   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2549                                                     &objfile->objfile_obstack);
2550   do_cleanups (cleanup);
2551 }
2552
2553 /* The hash function for strings in the mapped index.  This is the same as
2554    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2555    implementation.  This is necessary because the hash function is tied to the
2556    format of the mapped index file.  The hash values do not have to match with
2557    SYMBOL_HASH_NEXT.
2558    
2559    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2560
2561 static hashval_t
2562 mapped_index_string_hash (int index_version, const void *p)
2563 {
2564   const unsigned char *str = (const unsigned char *) p;
2565   hashval_t r = 0;
2566   unsigned char c;
2567
2568   while ((c = *str++) != 0)
2569     {
2570       if (index_version >= 5)
2571         c = tolower (c);
2572       r = r * 67 + c - 113;
2573     }
2574
2575   return r;
2576 }
2577
2578 /* Find a slot in the mapped index INDEX for the object named NAME.
2579    If NAME is found, set *VEC_OUT to point to the CU vector in the
2580    constant pool and return 1.  If NAME cannot be found, return 0.  */
2581
2582 static int
2583 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2584                           offset_type **vec_out)
2585 {
2586   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2587   offset_type hash;
2588   offset_type slot, step;
2589   int (*cmp) (const char *, const char *);
2590
2591   if (current_language->la_language == language_cplus
2592       || current_language->la_language == language_java
2593       || current_language->la_language == language_fortran)
2594     {
2595       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2596          not contain any.  */
2597       const char *paren = strchr (name, '(');
2598
2599       if (paren)
2600         {
2601           char *dup;
2602
2603           dup = xmalloc (paren - name + 1);
2604           memcpy (dup, name, paren - name);
2605           dup[paren - name] = 0;
2606
2607           make_cleanup (xfree, dup);
2608           name = dup;
2609         }
2610     }
2611
2612   /* Index version 4 did not support case insensitive searches.  But the
2613      indices for case insensitive languages are built in lowercase, therefore
2614      simulate our NAME being searched is also lowercased.  */
2615   hash = mapped_index_string_hash ((index->version == 4
2616                                     && case_sensitivity == case_sensitive_off
2617                                     ? 5 : index->version),
2618                                    name);
2619
2620   slot = hash & (index->symbol_table_slots - 1);
2621   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2622   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2623
2624   for (;;)
2625     {
2626       /* Convert a slot number to an offset into the table.  */
2627       offset_type i = 2 * slot;
2628       const char *str;
2629       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2630         {
2631           do_cleanups (back_to);
2632           return 0;
2633         }
2634
2635       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2636       if (!cmp (name, str))
2637         {
2638           *vec_out = (offset_type *) (index->constant_pool
2639                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2640           do_cleanups (back_to);
2641           return 1;
2642         }
2643
2644       slot = (slot + step) & (index->symbol_table_slots - 1);
2645     }
2646 }
2647
2648 /* A helper function that reads the .gdb_index from SECTION and fills
2649    in MAP.  FILENAME is the name of the file containing the section;
2650    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2651    ok to use deprecated sections.
2652
2653    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2654    out parameters that are filled in with information about the CU and
2655    TU lists in the section.
2656
2657    Returns 1 if all went well, 0 otherwise.  */
2658
2659 static int
2660 read_index_from_section (struct objfile *objfile,
2661                          const char *filename,
2662                          int deprecated_ok,
2663                          struct dwarf2_section_info *section,
2664                          struct mapped_index *map,
2665                          const gdb_byte **cu_list,
2666                          offset_type *cu_list_elements,
2667                          const gdb_byte **types_list,
2668                          offset_type *types_list_elements)
2669 {
2670   char *addr;
2671   offset_type version;
2672   offset_type *metadata;
2673   int i;
2674
2675   if (dwarf2_section_empty_p (section))
2676     return 0;
2677
2678   /* Older elfutils strip versions could keep the section in the main
2679      executable while splitting it for the separate debug info file.  */
2680   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2681     return 0;
2682
2683   dwarf2_read_section (objfile, section);
2684
2685   addr = section->buffer;
2686   /* Version check.  */
2687   version = MAYBE_SWAP (*(offset_type *) addr);
2688   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2689      causes the index to behave very poorly for certain requests.  Version 3
2690      contained incomplete addrmap.  So, it seems better to just ignore such
2691      indices.  */
2692   if (version < 4)
2693     {
2694       static int warning_printed = 0;
2695       if (!warning_printed)
2696         {
2697           warning (_("Skipping obsolete .gdb_index section in %s."),
2698                    filename);
2699           warning_printed = 1;
2700         }
2701       return 0;
2702     }
2703   /* Index version 4 uses a different hash function than index version
2704      5 and later.
2705
2706      Versions earlier than 6 did not emit psymbols for inlined
2707      functions.  Using these files will cause GDB not to be able to
2708      set breakpoints on inlined functions by name, so we ignore these
2709      indices unless the user has done
2710      "set use-deprecated-index-sections on".  */
2711   if (version < 6 && !deprecated_ok)
2712     {
2713       static int warning_printed = 0;
2714       if (!warning_printed)
2715         {
2716           warning (_("\
2717 Skipping deprecated .gdb_index section in %s.\n\
2718 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2719 to use the section anyway."),
2720                    filename);
2721           warning_printed = 1;
2722         }
2723       return 0;
2724     }
2725   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2726      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2727      we can't distinguish gdb-generated indices from gold-generated ones, so
2728      nothing to do here.  */
2729
2730   /* Indexes with higher version than the one supported by GDB may be no
2731      longer backward compatible.  */
2732   if (version > 8)
2733     return 0;
2734
2735   map->version = version;
2736   map->total_size = section->size;
2737
2738   metadata = (offset_type *) (addr + sizeof (offset_type));
2739
2740   i = 0;
2741   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2742   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2743                        / 8);
2744   ++i;
2745
2746   *types_list = addr + MAYBE_SWAP (metadata[i]);
2747   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2748                            - MAYBE_SWAP (metadata[i]))
2749                           / 8);
2750   ++i;
2751
2752   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2753   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2754                              - MAYBE_SWAP (metadata[i]));
2755   ++i;
2756
2757   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2758   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2759                               - MAYBE_SWAP (metadata[i]))
2760                              / (2 * sizeof (offset_type)));
2761   ++i;
2762
2763   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2764
2765   return 1;
2766 }
2767
2768
2769 /* Read the index file.  If everything went ok, initialize the "quick"
2770    elements of all the CUs and return 1.  Otherwise, return 0.  */
2771
2772 static int
2773 dwarf2_read_index (struct objfile *objfile)
2774 {
2775   struct mapped_index local_map, *map;
2776   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2777   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2778
2779   if (!read_index_from_section (objfile, objfile->name,
2780                                 use_deprecated_index_sections,
2781                                 &dwarf2_per_objfile->gdb_index, &local_map,
2782                                 &cu_list, &cu_list_elements,
2783                                 &types_list, &types_list_elements))
2784     return 0;
2785
2786   /* Don't use the index if it's empty.  */
2787   if (local_map.symbol_table_slots == 0)
2788     return 0;
2789
2790   /* If there is a .dwz file, read it so we can get its CU list as
2791      well.  */
2792   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2793     {
2794       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2795       struct mapped_index dwz_map;
2796       const gdb_byte *dwz_types_ignore;
2797       offset_type dwz_types_elements_ignore;
2798
2799       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2800                                     1,
2801                                     &dwz->gdb_index, &dwz_map,
2802                                     &dwz_list, &dwz_list_elements,
2803                                     &dwz_types_ignore,
2804                                     &dwz_types_elements_ignore))
2805         {
2806           warning (_("could not read '.gdb_index' section from %s; skipping"),
2807                    bfd_get_filename (dwz->dwz_bfd));
2808           return 0;
2809         }
2810     }
2811
2812   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2813                          dwz_list_elements);
2814
2815   if (types_list_elements)
2816     {
2817       struct dwarf2_section_info *section;
2818
2819       /* We can only handle a single .debug_types when we have an
2820          index.  */
2821       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2822         return 0;
2823
2824       section = VEC_index (dwarf2_section_info_def,
2825                            dwarf2_per_objfile->types, 0);
2826
2827       create_signatured_type_table_from_index (objfile, section, types_list,
2828                                                types_list_elements);
2829     }
2830
2831   create_addrmap_from_index (objfile, &local_map);
2832
2833   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2834   *map = local_map;
2835
2836   dwarf2_per_objfile->index_table = map;
2837   dwarf2_per_objfile->using_index = 1;
2838   dwarf2_per_objfile->quick_file_names_table =
2839     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2840
2841   return 1;
2842 }
2843
2844 /* A helper for the "quick" functions which sets the global
2845    dwarf2_per_objfile according to OBJFILE.  */
2846
2847 static void
2848 dw2_setup (struct objfile *objfile)
2849 {
2850   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2851   gdb_assert (dwarf2_per_objfile);
2852 }
2853
2854 /* die_reader_func for dw2_get_file_names.  */
2855
2856 static void
2857 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2858                            gdb_byte *info_ptr,
2859                            struct die_info *comp_unit_die,
2860                            int has_children,
2861                            void *data)
2862 {
2863   struct dwarf2_cu *cu = reader->cu;
2864   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2865   struct objfile *objfile = dwarf2_per_objfile->objfile;
2866   struct dwarf2_per_cu_data *lh_cu;
2867   struct line_header *lh;
2868   struct attribute *attr;
2869   int i;
2870   const char *name, *comp_dir;
2871   void **slot;
2872   struct quick_file_names *qfn;
2873   unsigned int line_offset;
2874
2875   /* Our callers never want to match partial units -- instead they
2876      will match the enclosing full CU.  */
2877   if (comp_unit_die->tag == DW_TAG_partial_unit)
2878     {
2879       this_cu->v.quick->no_file_data = 1;
2880       return;
2881     }
2882
2883   /* If we're reading the line header for TUs, store it in the "per_cu"
2884      for tu_group.  */
2885   if (this_cu->is_debug_types)
2886     {
2887       struct type_unit_group *tu_group = data;
2888
2889       gdb_assert (tu_group != NULL);
2890       lh_cu = &tu_group->per_cu;
2891     }
2892   else
2893     lh_cu = this_cu;
2894
2895   lh = NULL;
2896   slot = NULL;
2897   line_offset = 0;
2898
2899   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2900   if (attr)
2901     {
2902       struct quick_file_names find_entry;
2903
2904       line_offset = DW_UNSND (attr);
2905
2906       /* We may have already read in this line header (TU line header sharing).
2907          If we have we're done.  */
2908       find_entry.hash.dwo_unit = cu->dwo_unit;
2909       find_entry.hash.line_offset.sect_off = line_offset;
2910       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2911                              &find_entry, INSERT);
2912       if (*slot != NULL)
2913         {
2914           lh_cu->v.quick->file_names = *slot;
2915           return;
2916         }
2917
2918       lh = dwarf_decode_line_header (line_offset, cu);
2919     }
2920   if (lh == NULL)
2921     {
2922       lh_cu->v.quick->no_file_data = 1;
2923       return;
2924     }
2925
2926   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2927   qfn->hash.dwo_unit = cu->dwo_unit;
2928   qfn->hash.line_offset.sect_off = line_offset;
2929   gdb_assert (slot != NULL);
2930   *slot = qfn;
2931
2932   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2933
2934   qfn->num_file_names = lh->num_file_names;
2935   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2936                                    lh->num_file_names * sizeof (char *));
2937   for (i = 0; i < lh->num_file_names; ++i)
2938     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2939   qfn->real_names = NULL;
2940
2941   free_line_header (lh);
2942
2943   lh_cu->v.quick->file_names = qfn;
2944 }
2945
2946 /* A helper for the "quick" functions which attempts to read the line
2947    table for THIS_CU.  */
2948
2949 static struct quick_file_names *
2950 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2951 {
2952   /* For TUs this should only be called on the parent group.  */
2953   if (this_cu->is_debug_types)
2954     gdb_assert (IS_TYPE_UNIT_GROUP (this_cu));
2955
2956   if (this_cu->v.quick->file_names != NULL)
2957     return this_cu->v.quick->file_names;
2958   /* If we know there is no line data, no point in looking again.  */
2959   if (this_cu->v.quick->no_file_data)
2960     return NULL;
2961
2962   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2963      in the stub for CUs, there's is no need to lookup the DWO file.
2964      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2965      DWO file.  */
2966   if (this_cu->is_debug_types)
2967     {
2968       struct type_unit_group *tu_group = this_cu->type_unit_group;
2969
2970       init_cutu_and_read_dies (tu_group->t.first_tu, NULL, 0, 0,
2971                                dw2_get_file_names_reader, tu_group);
2972     }
2973   else
2974     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2975
2976   if (this_cu->v.quick->no_file_data)
2977     return NULL;
2978   return this_cu->v.quick->file_names;
2979 }
2980
2981 /* A helper for the "quick" functions which computes and caches the
2982    real path for a given file name from the line table.  */
2983
2984 static const char *
2985 dw2_get_real_path (struct objfile *objfile,
2986                    struct quick_file_names *qfn, int index)
2987 {
2988   if (qfn->real_names == NULL)
2989     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2990                                       qfn->num_file_names, sizeof (char *));
2991
2992   if (qfn->real_names[index] == NULL)
2993     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2994
2995   return qfn->real_names[index];
2996 }
2997
2998 static struct symtab *
2999 dw2_find_last_source_symtab (struct objfile *objfile)
3000 {
3001   int index;
3002
3003   dw2_setup (objfile);
3004   index = dwarf2_per_objfile->n_comp_units - 1;
3005   return dw2_instantiate_symtab (dw2_get_cu (index));
3006 }
3007
3008 /* Traversal function for dw2_forget_cached_source_info.  */
3009
3010 static int
3011 dw2_free_cached_file_names (void **slot, void *info)
3012 {
3013   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3014
3015   if (file_data->real_names)
3016     {
3017       int i;
3018
3019       for (i = 0; i < file_data->num_file_names; ++i)
3020         {
3021           xfree ((void*) file_data->real_names[i]);
3022           file_data->real_names[i] = NULL;
3023         }
3024     }
3025
3026   return 1;
3027 }
3028
3029 static void
3030 dw2_forget_cached_source_info (struct objfile *objfile)
3031 {
3032   dw2_setup (objfile);
3033
3034   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3035                           dw2_free_cached_file_names, NULL);
3036 }
3037
3038 /* Helper function for dw2_map_symtabs_matching_filename that expands
3039    the symtabs and calls the iterator.  */
3040
3041 static int
3042 dw2_map_expand_apply (struct objfile *objfile,
3043                       struct dwarf2_per_cu_data *per_cu,
3044                       const char *name, const char *real_path,
3045                       int (*callback) (struct symtab *, void *),
3046                       void *data)
3047 {
3048   struct symtab *last_made = objfile->symtabs;
3049
3050   /* Don't visit already-expanded CUs.  */
3051   if (per_cu->v.quick->symtab)
3052     return 0;
3053
3054   /* This may expand more than one symtab, and we want to iterate over
3055      all of them.  */
3056   dw2_instantiate_symtab (per_cu);
3057
3058   return iterate_over_some_symtabs (name, real_path, callback, data,
3059                                     objfile->symtabs, last_made);
3060 }
3061
3062 /* Implementation of the map_symtabs_matching_filename method.  */
3063
3064 static int
3065 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3066                                    const char *real_path,
3067                                    int (*callback) (struct symtab *, void *),
3068                                    void *data)
3069 {
3070   int i;
3071   const char *name_basename = lbasename (name);
3072
3073   dw2_setup (objfile);
3074
3075   /* The rule is CUs specify all the files, including those used by
3076      any TU, so there's no need to scan TUs here.  */
3077
3078   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3079     {
3080       int j;
3081       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3082       struct quick_file_names *file_data;
3083
3084       /* We only need to look at symtabs not already expanded.  */
3085       if (per_cu->v.quick->symtab)
3086         continue;
3087
3088       file_data = dw2_get_file_names (per_cu);
3089       if (file_data == NULL)
3090         continue;
3091
3092       for (j = 0; j < file_data->num_file_names; ++j)
3093         {
3094           const char *this_name = file_data->file_names[j];
3095           const char *this_real_name;
3096
3097           if (compare_filenames_for_search (this_name, name))
3098             {
3099               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3100                                         callback, data))
3101                 return 1;
3102               continue;
3103             }
3104
3105           /* Before we invoke realpath, which can get expensive when many
3106              files are involved, do a quick comparison of the basenames.  */
3107           if (! basenames_may_differ
3108               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3109             continue;
3110
3111           this_real_name = dw2_get_real_path (objfile, file_data, j);
3112           if (compare_filenames_for_search (this_real_name, name))
3113             {
3114               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3115                                         callback, data))
3116                 return 1;
3117               continue;
3118             }
3119
3120           if (real_path != NULL)
3121             {
3122               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3123               gdb_assert (IS_ABSOLUTE_PATH (name));
3124               if (this_real_name != NULL
3125                   && FILENAME_CMP (real_path, this_real_name) == 0)
3126                 {
3127                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3128                                             callback, data))
3129                     return 1;
3130                   continue;
3131                 }
3132             }
3133         }
3134     }
3135
3136   return 0;
3137 }
3138
3139 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3140
3141 struct dw2_symtab_iterator
3142 {
3143   /* The internalized form of .gdb_index.  */
3144   struct mapped_index *index;
3145   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3146   int want_specific_block;
3147   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3148      Unused if !WANT_SPECIFIC_BLOCK.  */
3149   int block_index;
3150   /* The kind of symbol we're looking for.  */
3151   domain_enum domain;
3152   /* The list of CUs from the index entry of the symbol,
3153      or NULL if not found.  */
3154   offset_type *vec;
3155   /* The next element in VEC to look at.  */
3156   int next;
3157   /* The number of elements in VEC, or zero if there is no match.  */
3158   int length;
3159 };
3160
3161 /* Initialize the index symtab iterator ITER.
3162    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3163    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3164
3165 static void
3166 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3167                       struct mapped_index *index,
3168                       int want_specific_block,
3169                       int block_index,
3170                       domain_enum domain,
3171                       const char *name)
3172 {
3173   iter->index = index;
3174   iter->want_specific_block = want_specific_block;
3175   iter->block_index = block_index;
3176   iter->domain = domain;
3177   iter->next = 0;
3178
3179   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3180     iter->length = MAYBE_SWAP (*iter->vec);
3181   else
3182     {
3183       iter->vec = NULL;
3184       iter->length = 0;
3185     }
3186 }
3187
3188 /* Return the next matching CU or NULL if there are no more.  */
3189
3190 static struct dwarf2_per_cu_data *
3191 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3192 {
3193   for ( ; iter->next < iter->length; ++iter->next)
3194     {
3195       offset_type cu_index_and_attrs =
3196         MAYBE_SWAP (iter->vec[iter->next + 1]);
3197       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3198       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3199       int want_static = iter->block_index != GLOBAL_BLOCK;
3200       /* This value is only valid for index versions >= 7.  */
3201       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3202       gdb_index_symbol_kind symbol_kind =
3203         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3204       /* Only check the symbol attributes if they're present.
3205          Indices prior to version 7 don't record them,
3206          and indices >= 7 may elide them for certain symbols
3207          (gold does this).  */
3208       int attrs_valid =
3209         (iter->index->version >= 7
3210          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3211
3212       /* Skip if already read in.  */
3213       if (per_cu->v.quick->symtab)
3214         continue;
3215
3216       if (attrs_valid
3217           && iter->want_specific_block
3218           && want_static != is_static)
3219         continue;
3220
3221       /* Only check the symbol's kind if it has one.  */
3222       if (attrs_valid)
3223         {
3224           switch (iter->domain)
3225             {
3226             case VAR_DOMAIN:
3227               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3228                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3229                   /* Some types are also in VAR_DOMAIN.  */
3230                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3231                 continue;
3232               break;
3233             case STRUCT_DOMAIN:
3234               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3235                 continue;
3236               break;
3237             case LABEL_DOMAIN:
3238               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3239                 continue;
3240               break;
3241             default:
3242               break;
3243             }
3244         }
3245
3246       ++iter->next;
3247       return per_cu;
3248     }
3249
3250   return NULL;
3251 }
3252
3253 static struct symtab *
3254 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3255                    const char *name, domain_enum domain)
3256 {
3257   struct symtab *stab_best = NULL;
3258   struct mapped_index *index;
3259
3260   dw2_setup (objfile);
3261
3262   index = dwarf2_per_objfile->index_table;
3263
3264   /* index is NULL if OBJF_READNOW.  */
3265   if (index)
3266     {
3267       struct dw2_symtab_iterator iter;
3268       struct dwarf2_per_cu_data *per_cu;
3269
3270       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3271
3272       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3273         {
3274           struct symbol *sym = NULL;
3275           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3276
3277           /* Some caution must be observed with overloaded functions
3278              and methods, since the index will not contain any overload
3279              information (but NAME might contain it).  */
3280           if (stab->primary)
3281             {
3282               struct blockvector *bv = BLOCKVECTOR (stab);
3283               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3284
3285               sym = lookup_block_symbol (block, name, domain);
3286             }
3287
3288           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3289             {
3290               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3291                 return stab;
3292
3293               stab_best = stab;
3294             }
3295
3296           /* Keep looking through other CUs.  */
3297         }
3298     }
3299
3300   return stab_best;
3301 }
3302
3303 static void
3304 dw2_print_stats (struct objfile *objfile)
3305 {
3306   int i, total, count;
3307
3308   dw2_setup (objfile);
3309   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3310   count = 0;
3311   for (i = 0; i < total; ++i)
3312     {
3313       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3314
3315       if (!per_cu->v.quick->symtab)
3316         ++count;
3317     }
3318   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3319   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3320 }
3321
3322 static void
3323 dw2_dump (struct objfile *objfile)
3324 {
3325   /* Nothing worth printing.  */
3326 }
3327
3328 static void
3329 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3330               struct section_offsets *delta)
3331 {
3332   /* There's nothing to relocate here.  */
3333 }
3334
3335 static void
3336 dw2_expand_symtabs_for_function (struct objfile *objfile,
3337                                  const char *func_name)
3338 {
3339   struct mapped_index *index;
3340
3341   dw2_setup (objfile);
3342
3343   index = dwarf2_per_objfile->index_table;
3344
3345   /* index is NULL if OBJF_READNOW.  */
3346   if (index)
3347     {
3348       struct dw2_symtab_iterator iter;
3349       struct dwarf2_per_cu_data *per_cu;
3350
3351       /* Note: It doesn't matter what we pass for block_index here.  */
3352       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3353                             func_name);
3354
3355       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3356         dw2_instantiate_symtab (per_cu);
3357     }
3358 }
3359
3360 static void
3361 dw2_expand_all_symtabs (struct objfile *objfile)
3362 {
3363   int i;
3364
3365   dw2_setup (objfile);
3366
3367   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3368                    + dwarf2_per_objfile->n_type_units); ++i)
3369     {
3370       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3371
3372       dw2_instantiate_symtab (per_cu);
3373     }
3374 }
3375
3376 static void
3377 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3378                                   const char *fullname)
3379 {
3380   int i;
3381
3382   dw2_setup (objfile);
3383
3384   /* We don't need to consider type units here.
3385      This is only called for examining code, e.g. expand_line_sal.
3386      There can be an order of magnitude (or more) more type units
3387      than comp units, and we avoid them if we can.  */
3388
3389   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3390     {
3391       int j;
3392       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3393       struct quick_file_names *file_data;
3394
3395       /* We only need to look at symtabs not already expanded.  */
3396       if (per_cu->v.quick->symtab)
3397         continue;
3398
3399       file_data = dw2_get_file_names (per_cu);
3400       if (file_data == NULL)
3401         continue;
3402
3403       for (j = 0; j < file_data->num_file_names; ++j)
3404         {
3405           const char *this_fullname = file_data->file_names[j];
3406
3407           if (filename_cmp (this_fullname, fullname) == 0)
3408             {
3409               dw2_instantiate_symtab (per_cu);
3410               break;
3411             }
3412         }
3413     }
3414 }
3415
3416 /* A helper function for dw2_find_symbol_file that finds the primary
3417    file name for a given CU.  This is a die_reader_func.  */
3418
3419 static void
3420 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3421                                  gdb_byte *info_ptr,
3422                                  struct die_info *comp_unit_die,
3423                                  int has_children,
3424                                  void *data)
3425 {
3426   const char **result_ptr = data;
3427   struct dwarf2_cu *cu = reader->cu;
3428   struct attribute *attr;
3429
3430   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3431   if (attr == NULL)
3432     *result_ptr = NULL;
3433   else
3434     *result_ptr = DW_STRING (attr);
3435 }
3436
3437 static const char *
3438 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3439 {
3440   struct dwarf2_per_cu_data *per_cu;
3441   offset_type *vec;
3442   const char *filename;
3443
3444   dw2_setup (objfile);
3445
3446   /* index_table is NULL if OBJF_READNOW.  */
3447   if (!dwarf2_per_objfile->index_table)
3448     {
3449       struct symtab *s;
3450
3451       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3452         {
3453           struct blockvector *bv = BLOCKVECTOR (s);
3454           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3455           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3456
3457           if (sym)
3458             {
3459               /* Only file extension of returned filename is recognized.  */
3460               return SYMBOL_SYMTAB (sym)->filename;
3461             }
3462         }
3463       return NULL;
3464     }
3465
3466   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3467                                  name, &vec))
3468     return NULL;
3469
3470   /* Note that this just looks at the very first one named NAME -- but
3471      actually we are looking for a function.  find_main_filename
3472      should be rewritten so that it doesn't require a custom hook.  It
3473      could just use the ordinary symbol tables.  */
3474   /* vec[0] is the length, which must always be >0.  */
3475   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3476
3477   if (per_cu->v.quick->symtab != NULL)
3478     {
3479       /* Only file extension of returned filename is recognized.  */
3480       return per_cu->v.quick->symtab->filename;
3481     }
3482
3483   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3484                            dw2_get_primary_filename_reader, &filename);
3485
3486   /* Only file extension of returned filename is recognized.  */
3487   return filename;
3488 }
3489
3490 static void
3491 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3492                           struct objfile *objfile, int global,
3493                           int (*callback) (struct block *,
3494                                            struct symbol *, void *),
3495                           void *data, symbol_compare_ftype *match,
3496                           symbol_compare_ftype *ordered_compare)
3497 {
3498   /* Currently unimplemented; used for Ada.  The function can be called if the
3499      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3500      does not look for non-Ada symbols this function should just return.  */
3501 }
3502
3503 static void
3504 dw2_expand_symtabs_matching
3505   (struct objfile *objfile,
3506    int (*file_matcher) (const char *, void *, int basenames),
3507    int (*name_matcher) (const char *, void *),
3508    enum search_domain kind,
3509    void *data)
3510 {
3511   int i;
3512   offset_type iter;
3513   struct mapped_index *index;
3514
3515   dw2_setup (objfile);
3516
3517   /* index_table is NULL if OBJF_READNOW.  */
3518   if (!dwarf2_per_objfile->index_table)
3519     return;
3520   index = dwarf2_per_objfile->index_table;
3521
3522   if (file_matcher != NULL)
3523     {
3524       struct cleanup *cleanup;
3525       htab_t visited_found, visited_not_found;
3526
3527       visited_found = htab_create_alloc (10,
3528                                          htab_hash_pointer, htab_eq_pointer,
3529                                          NULL, xcalloc, xfree);
3530       cleanup = make_cleanup_htab_delete (visited_found);
3531       visited_not_found = htab_create_alloc (10,
3532                                              htab_hash_pointer, htab_eq_pointer,
3533                                              NULL, xcalloc, xfree);
3534       make_cleanup_htab_delete (visited_not_found);
3535
3536       /* The rule is CUs specify all the files, including those used by
3537          any TU, so there's no need to scan TUs here.  */
3538
3539       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3540         {
3541           int j;
3542           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3543           struct quick_file_names *file_data;
3544           void **slot;
3545
3546           per_cu->v.quick->mark = 0;
3547
3548           /* We only need to look at symtabs not already expanded.  */
3549           if (per_cu->v.quick->symtab)
3550             continue;
3551
3552           file_data = dw2_get_file_names (per_cu);
3553           if (file_data == NULL)
3554             continue;
3555
3556           if (htab_find (visited_not_found, file_data) != NULL)
3557             continue;
3558           else if (htab_find (visited_found, file_data) != NULL)
3559             {
3560               per_cu->v.quick->mark = 1;
3561               continue;
3562             }
3563
3564           for (j = 0; j < file_data->num_file_names; ++j)
3565             {
3566               const char *this_real_name;
3567
3568               if (file_matcher (file_data->file_names[j], data, 0))
3569                 {
3570                   per_cu->v.quick->mark = 1;
3571                   break;
3572                 }
3573
3574               /* Before we invoke realpath, which can get expensive when many
3575                  files are involved, do a quick comparison of the basenames.  */
3576               if (!basenames_may_differ
3577                   && !file_matcher (lbasename (file_data->file_names[j]),
3578                                     data, 1))
3579                 continue;
3580
3581               this_real_name = dw2_get_real_path (objfile, file_data, j);
3582               if (file_matcher (this_real_name, data, 0))
3583                 {
3584                   per_cu->v.quick->mark = 1;
3585                   break;
3586                 }
3587             }
3588
3589           slot = htab_find_slot (per_cu->v.quick->mark
3590                                  ? visited_found
3591                                  : visited_not_found,
3592                                  file_data, INSERT);
3593           *slot = file_data;
3594         }
3595
3596       do_cleanups (cleanup);
3597     }
3598
3599   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3600     {
3601       offset_type idx = 2 * iter;
3602       const char *name;
3603       offset_type *vec, vec_len, vec_idx;
3604
3605       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3606         continue;
3607
3608       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3609
3610       if (! (*name_matcher) (name, data))
3611         continue;
3612
3613       /* The name was matched, now expand corresponding CUs that were
3614          marked.  */
3615       vec = (offset_type *) (index->constant_pool
3616                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3617       vec_len = MAYBE_SWAP (vec[0]);
3618       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3619         {
3620           struct dwarf2_per_cu_data *per_cu;
3621           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3622           gdb_index_symbol_kind symbol_kind =
3623             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3624           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3625
3626           /* Don't crash on bad data.  */
3627           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3628                            + dwarf2_per_objfile->n_type_units))
3629             continue;
3630
3631           /* Only check the symbol's kind if it has one.
3632              Indices prior to version 7 don't record it.  */
3633           if (index->version >= 7)
3634             {
3635               switch (kind)
3636                 {
3637                 case VARIABLES_DOMAIN:
3638                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3639                     continue;
3640                   break;
3641                 case FUNCTIONS_DOMAIN:
3642                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3643                     continue;
3644                   break;
3645                 case TYPES_DOMAIN:
3646                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3647                     continue;
3648                   break;
3649                 default:
3650                   break;
3651                 }
3652             }
3653
3654           per_cu = dw2_get_cu (cu_index);
3655           if (file_matcher == NULL || per_cu->v.quick->mark)
3656             dw2_instantiate_symtab (per_cu);
3657         }
3658     }
3659 }
3660
3661 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3662    symtab.  */
3663
3664 static struct symtab *
3665 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3666 {
3667   int i;
3668
3669   if (BLOCKVECTOR (symtab) != NULL
3670       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3671     return symtab;
3672
3673   if (symtab->includes == NULL)
3674     return NULL;
3675
3676   for (i = 0; symtab->includes[i]; ++i)
3677     {
3678       struct symtab *s = symtab->includes[i];
3679
3680       s = recursively_find_pc_sect_symtab (s, pc);
3681       if (s != NULL)
3682         return s;
3683     }
3684
3685   return NULL;
3686 }
3687
3688 static struct symtab *
3689 dw2_find_pc_sect_symtab (struct objfile *objfile,
3690                          struct minimal_symbol *msymbol,
3691                          CORE_ADDR pc,
3692                          struct obj_section *section,
3693                          int warn_if_readin)
3694 {
3695   struct dwarf2_per_cu_data *data;
3696   struct symtab *result;
3697
3698   dw2_setup (objfile);
3699
3700   if (!objfile->psymtabs_addrmap)
3701     return NULL;
3702
3703   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3704   if (!data)
3705     return NULL;
3706
3707   if (warn_if_readin && data->v.quick->symtab)
3708     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3709              paddress (get_objfile_arch (objfile), pc));
3710
3711   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3712   gdb_assert (result != NULL);
3713   return result;
3714 }
3715
3716 static void
3717 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3718                           void *data, int need_fullname)
3719 {
3720   int i;
3721   struct cleanup *cleanup;
3722   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3723                                       NULL, xcalloc, xfree);
3724
3725   cleanup = make_cleanup_htab_delete (visited);
3726   dw2_setup (objfile);
3727
3728   /* The rule is CUs specify all the files, including those used by
3729      any TU, so there's no need to scan TUs here.
3730      We can ignore file names coming from already-expanded CUs.  */
3731
3732   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3733     {
3734       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3735
3736       if (per_cu->v.quick->symtab)
3737         {
3738           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3739                                         INSERT);
3740
3741           *slot = per_cu->v.quick->file_names;
3742         }
3743     }
3744
3745   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3746     {
3747       int j;
3748       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3749       struct quick_file_names *file_data;
3750       void **slot;
3751
3752       /* We only need to look at symtabs not already expanded.  */
3753       if (per_cu->v.quick->symtab)
3754         continue;
3755
3756       file_data = dw2_get_file_names (per_cu);
3757       if (file_data == NULL)
3758         continue;
3759
3760       slot = htab_find_slot (visited, file_data, INSERT);
3761       if (*slot)
3762         {
3763           /* Already visited.  */
3764           continue;
3765         }
3766       *slot = file_data;
3767
3768       for (j = 0; j < file_data->num_file_names; ++j)
3769         {
3770           const char *this_real_name;
3771
3772           if (need_fullname)
3773             this_real_name = dw2_get_real_path (objfile, file_data, j);
3774           else
3775             this_real_name = NULL;
3776           (*fun) (file_data->file_names[j], this_real_name, data);
3777         }
3778     }
3779
3780   do_cleanups (cleanup);
3781 }
3782
3783 static int
3784 dw2_has_symbols (struct objfile *objfile)
3785 {
3786   return 1;
3787 }
3788
3789 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3790 {
3791   dw2_has_symbols,
3792   dw2_find_last_source_symtab,
3793   dw2_forget_cached_source_info,
3794   dw2_map_symtabs_matching_filename,
3795   dw2_lookup_symbol,
3796   dw2_print_stats,
3797   dw2_dump,
3798   dw2_relocate,
3799   dw2_expand_symtabs_for_function,
3800   dw2_expand_all_symtabs,
3801   dw2_expand_symtabs_with_fullname,
3802   dw2_find_symbol_file,
3803   dw2_map_matching_symbols,
3804   dw2_expand_symtabs_matching,
3805   dw2_find_pc_sect_symtab,
3806   dw2_map_symbol_filenames
3807 };
3808
3809 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3810    file will use psymtabs, or 1 if using the GNU index.  */
3811
3812 int
3813 dwarf2_initialize_objfile (struct objfile *objfile)
3814 {
3815   /* If we're about to read full symbols, don't bother with the
3816      indices.  In this case we also don't care if some other debug
3817      format is making psymtabs, because they are all about to be
3818      expanded anyway.  */
3819   if ((objfile->flags & OBJF_READNOW))
3820     {
3821       int i;
3822
3823       dwarf2_per_objfile->using_index = 1;
3824       create_all_comp_units (objfile);
3825       create_all_type_units (objfile);
3826       dwarf2_per_objfile->quick_file_names_table =
3827         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3828
3829       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3830                        + dwarf2_per_objfile->n_type_units); ++i)
3831         {
3832           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3833
3834           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3835                                             struct dwarf2_per_cu_quick_data);
3836         }
3837
3838       /* Return 1 so that gdb sees the "quick" functions.  However,
3839          these functions will be no-ops because we will have expanded
3840          all symtabs.  */
3841       return 1;
3842     }
3843
3844   if (dwarf2_read_index (objfile))
3845     return 1;
3846
3847   return 0;
3848 }
3849
3850 \f
3851
3852 /* Build a partial symbol table.  */
3853
3854 void
3855 dwarf2_build_psymtabs (struct objfile *objfile)
3856 {
3857   volatile struct gdb_exception except;
3858
3859   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3860     {
3861       init_psymbol_list (objfile, 1024);
3862     }
3863
3864   TRY_CATCH (except, RETURN_MASK_ERROR)
3865     {
3866       /* This isn't really ideal: all the data we allocate on the
3867          objfile's obstack is still uselessly kept around.  However,
3868          freeing it seems unsafe.  */
3869       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3870
3871       dwarf2_build_psymtabs_hard (objfile);
3872       discard_cleanups (cleanups);
3873     }
3874   if (except.reason < 0)
3875     exception_print (gdb_stderr, except);
3876 }
3877
3878 /* Return the total length of the CU described by HEADER.  */
3879
3880 static unsigned int
3881 get_cu_length (const struct comp_unit_head *header)
3882 {
3883   return header->initial_length_size + header->length;
3884 }
3885
3886 /* Return TRUE if OFFSET is within CU_HEADER.  */
3887
3888 static inline int
3889 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3890 {
3891   sect_offset bottom = { cu_header->offset.sect_off };
3892   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3893
3894   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3895 }
3896
3897 /* Find the base address of the compilation unit for range lists and
3898    location lists.  It will normally be specified by DW_AT_low_pc.
3899    In DWARF-3 draft 4, the base address could be overridden by
3900    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3901    compilation units with discontinuous ranges.  */
3902
3903 static void
3904 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3905 {
3906   struct attribute *attr;
3907
3908   cu->base_known = 0;
3909   cu->base_address = 0;
3910
3911   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3912   if (attr)
3913     {
3914       cu->base_address = DW_ADDR (attr);
3915       cu->base_known = 1;
3916     }
3917   else
3918     {
3919       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3920       if (attr)
3921         {
3922           cu->base_address = DW_ADDR (attr);
3923           cu->base_known = 1;
3924         }
3925     }
3926 }
3927
3928 /* Read in the comp unit header information from the debug_info at info_ptr.
3929    NOTE: This leaves members offset, first_die_offset to be filled in
3930    by the caller.  */
3931
3932 static gdb_byte *
3933 read_comp_unit_head (struct comp_unit_head *cu_header,
3934                      gdb_byte *info_ptr, bfd *abfd)
3935 {
3936   int signed_addr;
3937   unsigned int bytes_read;
3938
3939   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3940   cu_header->initial_length_size = bytes_read;
3941   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3942   info_ptr += bytes_read;
3943   cu_header->version = read_2_bytes (abfd, info_ptr);
3944   info_ptr += 2;
3945   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3946                                              &bytes_read);
3947   info_ptr += bytes_read;
3948   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3949   info_ptr += 1;
3950   signed_addr = bfd_get_sign_extend_vma (abfd);
3951   if (signed_addr < 0)
3952     internal_error (__FILE__, __LINE__,
3953                     _("read_comp_unit_head: dwarf from non elf file"));
3954   cu_header->signed_addr_p = signed_addr;
3955
3956   return info_ptr;
3957 }
3958
3959 /* Helper function that returns the proper abbrev section for
3960    THIS_CU.  */
3961
3962 static struct dwarf2_section_info *
3963 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3964 {
3965   struct dwarf2_section_info *abbrev;
3966
3967   if (this_cu->is_dwz)
3968     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3969   else
3970     abbrev = &dwarf2_per_objfile->abbrev;
3971
3972   return abbrev;
3973 }
3974
3975 /* Subroutine of read_and_check_comp_unit_head and
3976    read_and_check_type_unit_head to simplify them.
3977    Perform various error checking on the header.  */
3978
3979 static void
3980 error_check_comp_unit_head (struct comp_unit_head *header,
3981                             struct dwarf2_section_info *section,
3982                             struct dwarf2_section_info *abbrev_section)
3983 {
3984   bfd *abfd = section->asection->owner;
3985   const char *filename = bfd_get_filename (abfd);
3986
3987   if (header->version != 2 && header->version != 3 && header->version != 4)
3988     error (_("Dwarf Error: wrong version in compilation unit header "
3989            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3990            filename);
3991
3992   if (header->abbrev_offset.sect_off
3993       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3994     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3995            "(offset 0x%lx + 6) [in module %s]"),
3996            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3997            filename);
3998
3999   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4000      avoid potential 32-bit overflow.  */
4001   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4002       > section->size)
4003     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4004            "(offset 0x%lx + 0) [in module %s]"),
4005            (long) header->length, (long) header->offset.sect_off,
4006            filename);
4007 }
4008
4009 /* Read in a CU/TU header and perform some basic error checking.
4010    The contents of the header are stored in HEADER.
4011    The result is a pointer to the start of the first DIE.  */
4012
4013 static gdb_byte *
4014 read_and_check_comp_unit_head (struct comp_unit_head *header,
4015                                struct dwarf2_section_info *section,
4016                                struct dwarf2_section_info *abbrev_section,
4017                                gdb_byte *info_ptr,
4018                                int is_debug_types_section)
4019 {
4020   gdb_byte *beg_of_comp_unit = info_ptr;
4021   bfd *abfd = section->asection->owner;
4022
4023   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4024
4025   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4026
4027   /* If we're reading a type unit, skip over the signature and
4028      type_offset fields.  */
4029   if (is_debug_types_section)
4030     info_ptr += 8 /*signature*/ + header->offset_size;
4031
4032   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4033
4034   error_check_comp_unit_head (header, section, abbrev_section);
4035
4036   return info_ptr;
4037 }
4038
4039 /* Read in the types comp unit header information from .debug_types entry at
4040    types_ptr.  The result is a pointer to one past the end of the header.  */
4041
4042 static gdb_byte *
4043 read_and_check_type_unit_head (struct comp_unit_head *header,
4044                                struct dwarf2_section_info *section,
4045                                struct dwarf2_section_info *abbrev_section,
4046                                gdb_byte *info_ptr,
4047                                ULONGEST *signature,
4048                                cu_offset *type_offset_in_tu)
4049 {
4050   gdb_byte *beg_of_comp_unit = info_ptr;
4051   bfd *abfd = section->asection->owner;
4052
4053   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4054
4055   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4056
4057   /* If we're reading a type unit, skip over the signature and
4058      type_offset fields.  */
4059   if (signature != NULL)
4060     *signature = read_8_bytes (abfd, info_ptr);
4061   info_ptr += 8;
4062   if (type_offset_in_tu != NULL)
4063     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4064                                                header->offset_size);
4065   info_ptr += header->offset_size;
4066
4067   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4068
4069   error_check_comp_unit_head (header, section, abbrev_section);
4070
4071   return info_ptr;
4072 }
4073
4074 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4075
4076 static sect_offset
4077 read_abbrev_offset (struct dwarf2_section_info *section,
4078                     sect_offset offset)
4079 {
4080   bfd *abfd = section->asection->owner;
4081   gdb_byte *info_ptr;
4082   unsigned int length, initial_length_size, offset_size;
4083   sect_offset abbrev_offset;
4084
4085   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4086   info_ptr = section->buffer + offset.sect_off;
4087   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4088   offset_size = initial_length_size == 4 ? 4 : 8;
4089   info_ptr += initial_length_size + 2 /*version*/;
4090   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4091   return abbrev_offset;
4092 }
4093
4094 /* Allocate a new partial symtab for file named NAME and mark this new
4095    partial symtab as being an include of PST.  */
4096
4097 static void
4098 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
4099                                struct objfile *objfile)
4100 {
4101   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4102
4103   if (!IS_ABSOLUTE_PATH (subpst->filename))
4104     {
4105       /* It shares objfile->objfile_obstack.  */
4106       subpst->dirname = pst->dirname;
4107     }
4108
4109   subpst->section_offsets = pst->section_offsets;
4110   subpst->textlow = 0;
4111   subpst->texthigh = 0;
4112
4113   subpst->dependencies = (struct partial_symtab **)
4114     obstack_alloc (&objfile->objfile_obstack,
4115                    sizeof (struct partial_symtab *));
4116   subpst->dependencies[0] = pst;
4117   subpst->number_of_dependencies = 1;
4118
4119   subpst->globals_offset = 0;
4120   subpst->n_global_syms = 0;
4121   subpst->statics_offset = 0;
4122   subpst->n_static_syms = 0;
4123   subpst->symtab = NULL;
4124   subpst->read_symtab = pst->read_symtab;
4125   subpst->readin = 0;
4126
4127   /* No private part is necessary for include psymtabs.  This property
4128      can be used to differentiate between such include psymtabs and
4129      the regular ones.  */
4130   subpst->read_symtab_private = NULL;
4131 }
4132
4133 /* Read the Line Number Program data and extract the list of files
4134    included by the source file represented by PST.  Build an include
4135    partial symtab for each of these included files.  */
4136
4137 static void
4138 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4139                                struct die_info *die,
4140                                struct partial_symtab *pst)
4141 {
4142   struct line_header *lh = NULL;
4143   struct attribute *attr;
4144
4145   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4146   if (attr)
4147     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4148   if (lh == NULL)
4149     return;  /* No linetable, so no includes.  */
4150
4151   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4152   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4153
4154   free_line_header (lh);
4155 }
4156
4157 static hashval_t
4158 hash_signatured_type (const void *item)
4159 {
4160   const struct signatured_type *sig_type = item;
4161
4162   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4163   return sig_type->signature;
4164 }
4165
4166 static int
4167 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4168 {
4169   const struct signatured_type *lhs = item_lhs;
4170   const struct signatured_type *rhs = item_rhs;
4171
4172   return lhs->signature == rhs->signature;
4173 }
4174
4175 /* Allocate a hash table for signatured types.  */
4176
4177 static htab_t
4178 allocate_signatured_type_table (struct objfile *objfile)
4179 {
4180   return htab_create_alloc_ex (41,
4181                                hash_signatured_type,
4182                                eq_signatured_type,
4183                                NULL,
4184                                &objfile->objfile_obstack,
4185                                hashtab_obstack_allocate,
4186                                dummy_obstack_deallocate);
4187 }
4188
4189 /* A helper function to add a signatured type CU to a table.  */
4190
4191 static int
4192 add_signatured_type_cu_to_table (void **slot, void *datum)
4193 {
4194   struct signatured_type *sigt = *slot;
4195   struct signatured_type ***datap = datum;
4196
4197   **datap = sigt;
4198   ++*datap;
4199
4200   return 1;
4201 }
4202
4203 /* Create the hash table of all entries in the .debug_types
4204    (or .debug_types.dwo) section(s).
4205    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4206    otherwise it is NULL.
4207
4208    The result is a pointer to the hash table or NULL if there are no types.
4209
4210    Note: This function processes DWO files only, not DWP files.  */
4211
4212 static htab_t
4213 create_debug_types_hash_table (struct dwo_file *dwo_file,
4214                                VEC (dwarf2_section_info_def) *types)
4215 {
4216   struct objfile *objfile = dwarf2_per_objfile->objfile;
4217   htab_t types_htab = NULL;
4218   int ix;
4219   struct dwarf2_section_info *section;
4220   struct dwarf2_section_info *abbrev_section;
4221
4222   if (VEC_empty (dwarf2_section_info_def, types))
4223     return NULL;
4224
4225   abbrev_section = (dwo_file != NULL
4226                     ? &dwo_file->sections.abbrev
4227                     : &dwarf2_per_objfile->abbrev);
4228
4229   if (dwarf2_read_debug)
4230     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4231                         dwo_file ? ".dwo" : "",
4232                         bfd_get_filename (abbrev_section->asection->owner));
4233
4234   for (ix = 0;
4235        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4236        ++ix)
4237     {
4238       bfd *abfd;
4239       gdb_byte *info_ptr, *end_ptr;
4240       struct dwarf2_section_info *abbrev_section;
4241
4242       dwarf2_read_section (objfile, section);
4243       info_ptr = section->buffer;
4244
4245       if (info_ptr == NULL)
4246         continue;
4247
4248       /* We can't set abfd until now because the section may be empty or
4249          not present, in which case section->asection will be NULL.  */
4250       abfd = section->asection->owner;
4251
4252       if (dwo_file)
4253         abbrev_section = &dwo_file->sections.abbrev;
4254       else
4255         abbrev_section = &dwarf2_per_objfile->abbrev;
4256
4257       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4258          because we don't need to read any dies: the signature is in the
4259          header.  */
4260
4261       end_ptr = info_ptr + section->size;
4262       while (info_ptr < end_ptr)
4263         {
4264           sect_offset offset;
4265           cu_offset type_offset_in_tu;
4266           ULONGEST signature;
4267           struct signatured_type *sig_type;
4268           struct dwo_unit *dwo_tu;
4269           void **slot;
4270           gdb_byte *ptr = info_ptr;
4271           struct comp_unit_head header;
4272           unsigned int length;
4273
4274           offset.sect_off = ptr - section->buffer;
4275
4276           /* We need to read the type's signature in order to build the hash
4277              table, but we don't need anything else just yet.  */
4278
4279           ptr = read_and_check_type_unit_head (&header, section,
4280                                                abbrev_section, ptr,
4281                                                &signature, &type_offset_in_tu);
4282
4283           length = get_cu_length (&header);
4284
4285           /* Skip dummy type units.  */
4286           if (ptr >= info_ptr + length
4287               || peek_abbrev_code (abfd, ptr) == 0)
4288             {
4289               info_ptr += length;
4290               continue;
4291             }
4292
4293           if (types_htab == NULL)
4294             {
4295               if (dwo_file)
4296                 types_htab = allocate_dwo_unit_table (objfile);
4297               else
4298                 types_htab = allocate_signatured_type_table (objfile);
4299             }
4300
4301           if (dwo_file)
4302             {
4303               sig_type = NULL;
4304               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4305                                        struct dwo_unit);
4306               dwo_tu->dwo_file = dwo_file;
4307               dwo_tu->signature = signature;
4308               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4309               dwo_tu->section = section;
4310               dwo_tu->offset = offset;
4311               dwo_tu->length = length;
4312             }
4313           else
4314             {
4315               /* N.B.: type_offset is not usable if this type uses a DWO file.
4316                  The real type_offset is in the DWO file.  */
4317               dwo_tu = NULL;
4318               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4319                                          struct signatured_type);
4320               sig_type->signature = signature;
4321               sig_type->type_offset_in_tu = type_offset_in_tu;
4322               sig_type->per_cu.objfile = objfile;
4323               sig_type->per_cu.is_debug_types = 1;
4324               sig_type->per_cu.section = section;
4325               sig_type->per_cu.offset = offset;
4326               sig_type->per_cu.length = length;
4327             }
4328
4329           slot = htab_find_slot (types_htab,
4330                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4331                                  INSERT);
4332           gdb_assert (slot != NULL);
4333           if (*slot != NULL)
4334             {
4335               sect_offset dup_offset;
4336
4337               if (dwo_file)
4338                 {
4339                   const struct dwo_unit *dup_tu = *slot;
4340
4341                   dup_offset = dup_tu->offset;
4342                 }
4343               else
4344                 {
4345                   const struct signatured_type *dup_tu = *slot;
4346
4347                   dup_offset = dup_tu->per_cu.offset;
4348                 }
4349
4350               complaint (&symfile_complaints,
4351                          _("debug type entry at offset 0x%x is duplicate to"
4352                            " the entry at offset 0x%x, signature 0x%s"),
4353                          offset.sect_off, dup_offset.sect_off,
4354                          phex (signature, sizeof (signature)));
4355             }
4356           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4357
4358           if (dwarf2_read_debug)
4359             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4360                                 offset.sect_off,
4361                                 phex (signature, sizeof (signature)));
4362
4363           info_ptr += length;
4364         }
4365     }
4366
4367   return types_htab;
4368 }
4369
4370 /* Create the hash table of all entries in the .debug_types section,
4371    and initialize all_type_units.
4372    The result is zero if there is an error (e.g. missing .debug_types section),
4373    otherwise non-zero.  */
4374
4375 static int
4376 create_all_type_units (struct objfile *objfile)
4377 {
4378   htab_t types_htab;
4379   struct signatured_type **iter;
4380
4381   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4382   if (types_htab == NULL)
4383     {
4384       dwarf2_per_objfile->signatured_types = NULL;
4385       return 0;
4386     }
4387
4388   dwarf2_per_objfile->signatured_types = types_htab;
4389
4390   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4391   dwarf2_per_objfile->all_type_units
4392     = obstack_alloc (&objfile->objfile_obstack,
4393                      dwarf2_per_objfile->n_type_units
4394                      * sizeof (struct signatured_type *));
4395   iter = &dwarf2_per_objfile->all_type_units[0];
4396   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4397   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4398               == dwarf2_per_objfile->n_type_units);
4399
4400   return 1;
4401 }
4402
4403 /* Lookup a signature based type for DW_FORM_ref_sig8.
4404    Returns NULL if signature SIG is not present in the table.
4405    It is up to the caller to complain about this.  */
4406
4407 static struct signatured_type *
4408 lookup_signatured_type (ULONGEST sig)
4409 {
4410   struct signatured_type find_entry, *entry;
4411
4412   if (dwarf2_per_objfile->signatured_types == NULL)
4413     return NULL;
4414   find_entry.signature = sig;
4415   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4416   return entry;
4417 }
4418 \f
4419 /* Low level DIE reading support.  */
4420
4421 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4422
4423 static void
4424 init_cu_die_reader (struct die_reader_specs *reader,
4425                     struct dwarf2_cu *cu,
4426                     struct dwarf2_section_info *section,
4427                     struct dwo_file *dwo_file)
4428 {
4429   gdb_assert (section->readin && section->buffer != NULL);
4430   reader->abfd = section->asection->owner;
4431   reader->cu = cu;
4432   reader->dwo_file = dwo_file;
4433   reader->die_section = section;
4434   reader->buffer = section->buffer;
4435   reader->buffer_end = section->buffer + section->size;
4436 }
4437
4438 /* Subroutine of init_cutu_and_read_dies to simplify it.
4439    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4440    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4441    already.
4442
4443    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4444    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4445    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4446    are filled in with the info of the DIE from the DWO file.
4447    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4448    provided an abbrev table to use.
4449    The result is non-zero if a valid (non-dummy) DIE was found.  */
4450
4451 static int
4452 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4453                         struct dwo_unit *dwo_unit,
4454                         int abbrev_table_provided,
4455                         struct die_info *stub_comp_unit_die,
4456                         struct die_reader_specs *result_reader,
4457                         gdb_byte **result_info_ptr,
4458                         struct die_info **result_comp_unit_die,
4459                         int *result_has_children)
4460 {
4461   struct objfile *objfile = dwarf2_per_objfile->objfile;
4462   struct dwarf2_cu *cu = this_cu->cu;
4463   struct dwarf2_section_info *section;
4464   bfd *abfd;
4465   gdb_byte *begin_info_ptr, *info_ptr;
4466   const char *comp_dir_string;
4467   ULONGEST signature; /* Or dwo_id.  */
4468   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4469   int i,num_extra_attrs;
4470   struct dwarf2_section_info *dwo_abbrev_section;
4471   struct attribute *attr;
4472   struct die_info *comp_unit_die;
4473
4474   /* These attributes aren't processed until later:
4475      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4476      However, the attribute is found in the stub which we won't have later.
4477      In order to not impose this complication on the rest of the code,
4478      we read them here and copy them to the DWO CU/TU die.  */
4479
4480   stmt_list = NULL;
4481   low_pc = NULL;
4482   high_pc = NULL;
4483   ranges = NULL;
4484   comp_dir = NULL;
4485
4486   if (stub_comp_unit_die != NULL)
4487     {
4488       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4489          DWO file.  */
4490       if (! this_cu->is_debug_types)
4491         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4492       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4493       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4494       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4495       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4496
4497       /* There should be a DW_AT_addr_base attribute here (if needed).
4498          We need the value before we can process DW_FORM_GNU_addr_index.  */
4499       cu->addr_base = 0;
4500       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4501       if (attr)
4502         cu->addr_base = DW_UNSND (attr);
4503
4504       /* There should be a DW_AT_ranges_base attribute here (if needed).
4505          We need the value before we can process DW_AT_ranges.  */
4506       cu->ranges_base = 0;
4507       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4508       if (attr)
4509         cu->ranges_base = DW_UNSND (attr);
4510     }
4511
4512   /* Set up for reading the DWO CU/TU.  */
4513   cu->dwo_unit = dwo_unit;
4514   section = dwo_unit->section;
4515   dwarf2_read_section (objfile, section);
4516   abfd = section->asection->owner;
4517   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4518   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4519   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4520
4521   if (this_cu->is_debug_types)
4522     {
4523       ULONGEST header_signature;
4524       cu_offset type_offset_in_tu;
4525       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4526
4527       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4528                                                 dwo_abbrev_section,
4529                                                 info_ptr,
4530                                                 &header_signature,
4531                                                 &type_offset_in_tu);
4532       gdb_assert (sig_type->signature == header_signature);
4533       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4534       /* For DWOs coming from DWP files, we don't know the CU length
4535          nor the type's offset in the TU until now.  */
4536       dwo_unit->length = get_cu_length (&cu->header);
4537       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4538
4539       /* Establish the type offset that can be used to lookup the type.
4540          For DWO files, we don't know it until now.  */
4541       sig_type->type_offset_in_section.sect_off =
4542         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4543     }
4544   else
4545     {
4546       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4547                                                 dwo_abbrev_section,
4548                                                 info_ptr, 0);
4549       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4550       /* For DWOs coming from DWP files, we don't know the CU length
4551          until now.  */
4552       dwo_unit->length = get_cu_length (&cu->header);
4553     }
4554
4555   /* Replace the CU's original abbrev table with the DWO's.  */
4556   if (abbrev_table_provided)
4557     {
4558       /* Don't free the provided abbrev table, the caller of
4559          init_cutu_and_read_dies owns it.  */
4560       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4561       make_cleanup (dwarf2_free_abbrev_table, cu);
4562     }
4563   else
4564     {
4565       dwarf2_free_abbrev_table (cu);
4566       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4567     }
4568
4569   /* Read in the die, but leave space to copy over the attributes
4570      from the stub.  This has the benefit of simplifying the rest of
4571      the code - all the work to maintain the illusion of a single
4572      DW_TAG_{compile,type}_unit DIE is done here.  */
4573   num_extra_attrs = ((stmt_list != NULL)
4574                      + (low_pc != NULL)
4575                      + (high_pc != NULL)
4576                      + (ranges != NULL)
4577                      + (comp_dir != NULL));
4578   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4579                               result_has_children, num_extra_attrs);
4580
4581   /* Copy over the attributes from the stub to the DIE we just read in.  */
4582   comp_unit_die = *result_comp_unit_die;
4583   i = comp_unit_die->num_attrs;
4584   if (stmt_list != NULL)
4585     comp_unit_die->attrs[i++] = *stmt_list;
4586   if (low_pc != NULL)
4587     comp_unit_die->attrs[i++] = *low_pc;
4588   if (high_pc != NULL)
4589     comp_unit_die->attrs[i++] = *high_pc;
4590   if (ranges != NULL)
4591     comp_unit_die->attrs[i++] = *ranges;
4592   if (comp_dir != NULL)
4593     comp_unit_die->attrs[i++] = *comp_dir;
4594   comp_unit_die->num_attrs += num_extra_attrs;
4595
4596   /* Skip dummy compilation units.  */
4597   if (info_ptr >= begin_info_ptr + dwo_unit->length
4598       || peek_abbrev_code (abfd, info_ptr) == 0)
4599     return 0;
4600
4601   *result_info_ptr = info_ptr;
4602   return 1;
4603 }
4604
4605 /* Subroutine of init_cutu_and_read_dies to simplify it.
4606    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4607    If the specified DWO unit cannot be found an error is thrown.  */
4608
4609 static struct dwo_unit *
4610 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4611                  struct die_info *comp_unit_die)
4612 {
4613   struct dwarf2_cu *cu = this_cu->cu;
4614   struct attribute *attr;
4615   ULONGEST signature;
4616   struct dwo_unit *dwo_unit;
4617   const char *comp_dir, *dwo_name;
4618
4619   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4620   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4621   gdb_assert (attr != NULL);
4622   dwo_name = DW_STRING (attr);
4623   comp_dir = NULL;
4624   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4625   if (attr)
4626     comp_dir = DW_STRING (attr);
4627
4628   if (this_cu->is_debug_types)
4629     {
4630       struct signatured_type *sig_type;
4631
4632       /* Since this_cu is the first member of struct signatured_type,
4633          we can go from a pointer to one to a pointer to the other.  */
4634       sig_type = (struct signatured_type *) this_cu;
4635       signature = sig_type->signature;
4636       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4637     }
4638   else
4639     {
4640       struct attribute *attr;
4641
4642       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4643       if (! attr)
4644         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4645                  " [in module %s]"),
4646                dwo_name, this_cu->objfile->name);
4647       signature = DW_UNSND (attr);
4648       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4649                                        signature);
4650     }
4651
4652   if (dwo_unit == NULL)
4653     {
4654       error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4655                " with ID %s [in module %s]"),
4656              this_cu->offset.sect_off,
4657              phex (signature, sizeof (signature)),
4658              this_cu->objfile->name);
4659     }
4660
4661   return dwo_unit;
4662 }
4663
4664 /* Initialize a CU (or TU) and read its DIEs.
4665    If the CU defers to a DWO file, read the DWO file as well.
4666
4667    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4668    Otherwise the table specified in the comp unit header is read in and used.
4669    This is an optimization for when we already have the abbrev table.
4670
4671    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4672    Otherwise, a new CU is allocated with xmalloc.
4673
4674    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4675    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4676
4677    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4678    linker) then DIE_READER_FUNC will not get called.  */
4679
4680 static void
4681 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4682                          struct abbrev_table *abbrev_table,
4683                          int use_existing_cu, int keep,
4684                          die_reader_func_ftype *die_reader_func,
4685                          void *data)
4686 {
4687   struct objfile *objfile = dwarf2_per_objfile->objfile;
4688   struct dwarf2_section_info *section = this_cu->section;
4689   bfd *abfd = section->asection->owner;
4690   struct dwarf2_cu *cu;
4691   gdb_byte *begin_info_ptr, *info_ptr;
4692   struct die_reader_specs reader;
4693   struct die_info *comp_unit_die;
4694   int has_children;
4695   struct attribute *attr;
4696   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4697   struct signatured_type *sig_type = NULL;
4698   struct dwarf2_section_info *abbrev_section;
4699   /* Non-zero if CU currently points to a DWO file and we need to
4700      reread it.  When this happens we need to reread the skeleton die
4701      before we can reread the DWO file.  */
4702   int rereading_dwo_cu = 0;
4703
4704   if (dwarf2_die_debug)
4705     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4706                         this_cu->is_debug_types ? "type" : "comp",
4707                         this_cu->offset.sect_off);
4708
4709   if (use_existing_cu)
4710     gdb_assert (keep);
4711
4712   cleanups = make_cleanup (null_cleanup, NULL);
4713
4714   /* This is cheap if the section is already read in.  */
4715   dwarf2_read_section (objfile, section);
4716
4717   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4718
4719   abbrev_section = get_abbrev_section_for_cu (this_cu);
4720
4721   if (use_existing_cu && this_cu->cu != NULL)
4722     {
4723       cu = this_cu->cu;
4724
4725       /* If this CU is from a DWO file we need to start over, we need to
4726          refetch the attributes from the skeleton CU.
4727          This could be optimized by retrieving those attributes from when we
4728          were here the first time: the previous comp_unit_die was stored in
4729          comp_unit_obstack.  But there's no data yet that we need this
4730          optimization.  */
4731       if (cu->dwo_unit != NULL)
4732         rereading_dwo_cu = 1;
4733     }
4734   else
4735     {
4736       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4737       gdb_assert (this_cu->cu == NULL);
4738
4739       cu = xmalloc (sizeof (*cu));
4740       init_one_comp_unit (cu, this_cu);
4741
4742       /* If an error occurs while loading, release our storage.  */
4743       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4744     }
4745
4746   /* Get the header.  */
4747   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4748     {
4749       /* We already have the header, there's no need to read it in again.  */
4750       info_ptr += cu->header.first_die_offset.cu_off;
4751     }
4752   else
4753     {
4754       if (this_cu->is_debug_types)
4755         {
4756           ULONGEST signature;
4757           cu_offset type_offset_in_tu;
4758
4759           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4760                                                     abbrev_section, info_ptr,
4761                                                     &signature,
4762                                                     &type_offset_in_tu);
4763
4764           /* Since per_cu is the first member of struct signatured_type,
4765              we can go from a pointer to one to a pointer to the other.  */
4766           sig_type = (struct signatured_type *) this_cu;
4767           gdb_assert (sig_type->signature == signature);
4768           gdb_assert (sig_type->type_offset_in_tu.cu_off
4769                       == type_offset_in_tu.cu_off);
4770           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4771
4772           /* LENGTH has not been set yet for type units if we're
4773              using .gdb_index.  */
4774           this_cu->length = get_cu_length (&cu->header);
4775
4776           /* Establish the type offset that can be used to lookup the type.  */
4777           sig_type->type_offset_in_section.sect_off =
4778             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4779         }
4780       else
4781         {
4782           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4783                                                     abbrev_section,
4784                                                     info_ptr, 0);
4785
4786           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4787           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4788         }
4789     }
4790
4791   /* Skip dummy compilation units.  */
4792   if (info_ptr >= begin_info_ptr + this_cu->length
4793       || peek_abbrev_code (abfd, info_ptr) == 0)
4794     {
4795       do_cleanups (cleanups);
4796       return;
4797     }
4798
4799   /* If we don't have them yet, read the abbrevs for this compilation unit.
4800      And if we need to read them now, make sure they're freed when we're
4801      done.  Note that it's important that if the CU had an abbrev table
4802      on entry we don't free it when we're done: Somewhere up the call stack
4803      it may be in use.  */
4804   if (abbrev_table != NULL)
4805     {
4806       gdb_assert (cu->abbrev_table == NULL);
4807       gdb_assert (cu->header.abbrev_offset.sect_off
4808                   == abbrev_table->offset.sect_off);
4809       cu->abbrev_table = abbrev_table;
4810     }
4811   else if (cu->abbrev_table == NULL)
4812     {
4813       dwarf2_read_abbrevs (cu, abbrev_section);
4814       make_cleanup (dwarf2_free_abbrev_table, cu);
4815     }
4816   else if (rereading_dwo_cu)
4817     {
4818       dwarf2_free_abbrev_table (cu);
4819       dwarf2_read_abbrevs (cu, abbrev_section);
4820     }
4821
4822   /* Read the top level CU/TU die.  */
4823   init_cu_die_reader (&reader, cu, section, NULL);
4824   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4825
4826   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
4827      from the DWO file.
4828      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
4829      DWO CU, that this test will fail (the attribute will not be present).  */
4830   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4831   if (attr)
4832     {
4833       struct dwo_unit *dwo_unit;
4834       struct die_info *dwo_comp_unit_die;
4835
4836       if (has_children)
4837         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4838                  " has children (offset 0x%x) [in module %s]"),
4839                this_cu->offset.sect_off, bfd_get_filename (abfd));
4840       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
4841       if (read_cutu_die_from_dwo (this_cu, dwo_unit,
4842                                   abbrev_table != NULL,
4843                                   comp_unit_die,
4844                                   &reader, &info_ptr,
4845                                   &dwo_comp_unit_die, &has_children) == 0)
4846         {
4847           /* Dummy die.  */
4848           do_cleanups (cleanups);
4849           return;
4850         }
4851       comp_unit_die = dwo_comp_unit_die;
4852     }
4853
4854   /* All of the above is setup for this call.  Yikes.  */
4855   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4856
4857   /* Done, clean up.  */
4858   if (free_cu_cleanup != NULL)
4859     {
4860       if (keep)
4861         {
4862           /* We've successfully allocated this compilation unit.  Let our
4863              caller clean it up when finished with it.  */
4864           discard_cleanups (free_cu_cleanup);
4865
4866           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4867              So we have to manually free the abbrev table.  */
4868           dwarf2_free_abbrev_table (cu);
4869
4870           /* Link this CU into read_in_chain.  */
4871           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4872           dwarf2_per_objfile->read_in_chain = this_cu;
4873         }
4874       else
4875         do_cleanups (free_cu_cleanup);
4876     }
4877
4878   do_cleanups (cleanups);
4879 }
4880
4881 /* Read CU/TU THIS_CU in section SECTION,
4882    but do not follow DW_AT_GNU_dwo_name if present.
4883    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4884    to have already done the lookup to find the DWO/DWP file).
4885
4886    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4887    THIS_CU->is_debug_types, but nothing else.
4888
4889    We fill in THIS_CU->length.
4890
4891    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4892    linker) then DIE_READER_FUNC will not get called.
4893
4894    THIS_CU->cu is always freed when done.
4895    This is done in order to not leave THIS_CU->cu in a state where we have
4896    to care whether it refers to the "main" CU or the DWO CU.  */
4897
4898 static void
4899 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4900                                    struct dwarf2_section_info *abbrev_section,
4901                                    struct dwo_file *dwo_file,
4902                                    die_reader_func_ftype *die_reader_func,
4903                                    void *data)
4904 {
4905   struct objfile *objfile = dwarf2_per_objfile->objfile;
4906   struct dwarf2_section_info *section = this_cu->section;
4907   bfd *abfd = section->asection->owner;
4908   struct dwarf2_cu cu;
4909   gdb_byte *begin_info_ptr, *info_ptr;
4910   struct die_reader_specs reader;
4911   struct cleanup *cleanups;
4912   struct die_info *comp_unit_die;
4913   int has_children;
4914
4915   if (dwarf2_die_debug)
4916     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4917                         this_cu->is_debug_types ? "type" : "comp",
4918                         this_cu->offset.sect_off);
4919
4920   gdb_assert (this_cu->cu == NULL);
4921
4922   /* This is cheap if the section is already read in.  */
4923   dwarf2_read_section (objfile, section);
4924
4925   init_one_comp_unit (&cu, this_cu);
4926
4927   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4928
4929   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4930   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4931                                             abbrev_section, info_ptr,
4932                                             this_cu->is_debug_types);
4933
4934   this_cu->length = get_cu_length (&cu.header);
4935
4936   /* Skip dummy compilation units.  */
4937   if (info_ptr >= begin_info_ptr + this_cu->length
4938       || peek_abbrev_code (abfd, info_ptr) == 0)
4939     {
4940       do_cleanups (cleanups);
4941       return;
4942     }
4943
4944   dwarf2_read_abbrevs (&cu, abbrev_section);
4945   make_cleanup (dwarf2_free_abbrev_table, &cu);
4946
4947   init_cu_die_reader (&reader, &cu, section, dwo_file);
4948   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4949
4950   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4951
4952   do_cleanups (cleanups);
4953 }
4954
4955 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4956    does not lookup the specified DWO file.
4957    This cannot be used to read DWO files.
4958
4959    THIS_CU->cu is always freed when done.
4960    This is done in order to not leave THIS_CU->cu in a state where we have
4961    to care whether it refers to the "main" CU or the DWO CU.
4962    We can revisit this if the data shows there's a performance issue.  */
4963
4964 static void
4965 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4966                                 die_reader_func_ftype *die_reader_func,
4967                                 void *data)
4968 {
4969   init_cutu_and_read_dies_no_follow (this_cu,
4970                                      get_abbrev_section_for_cu (this_cu),
4971                                      NULL,
4972                                      die_reader_func, data);
4973 }
4974 \f
4975 /* Type Unit Groups.
4976
4977    Type Unit Groups are a way to collapse the set of all TUs (type units) into
4978    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
4979    so that all types coming from the same compilation (.o file) are grouped
4980    together.  A future step could be to put the types in the same symtab as
4981    the CU the types ultimately came from.  */
4982
4983 static hashval_t
4984 hash_type_unit_group (const void *item)
4985 {
4986   const struct type_unit_group *tu_group = item;
4987
4988   return hash_stmt_list_entry (&tu_group->hash);
4989 }
4990
4991 static int
4992 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
4993 {
4994   const struct type_unit_group *lhs = item_lhs;
4995   const struct type_unit_group *rhs = item_rhs;
4996
4997   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
4998 }
4999
5000 /* Allocate a hash table for type unit groups.  */
5001
5002 static htab_t
5003 allocate_type_unit_groups_table (void)
5004 {
5005   return htab_create_alloc_ex (3,
5006                                hash_type_unit_group,
5007                                eq_type_unit_group,
5008                                NULL,
5009                                &dwarf2_per_objfile->objfile->objfile_obstack,
5010                                hashtab_obstack_allocate,
5011                                dummy_obstack_deallocate);
5012 }
5013
5014 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5015    partial symtabs.  We combine several TUs per psymtab to not let the size
5016    of any one psymtab grow too big.  */
5017 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5018 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5019
5020 /* Helper routine for get_type_unit_group.
5021    Create the type_unit_group object used to hold one or more TUs.  */
5022
5023 static struct type_unit_group *
5024 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5025 {
5026   struct objfile *objfile = dwarf2_per_objfile->objfile;
5027   struct dwarf2_per_cu_data *per_cu;
5028   struct type_unit_group *tu_group;
5029
5030   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5031                              struct type_unit_group);
5032   per_cu = &tu_group->per_cu;
5033   per_cu->objfile = objfile;
5034   per_cu->is_debug_types = 1;
5035   per_cu->type_unit_group = tu_group;
5036
5037   if (dwarf2_per_objfile->using_index)
5038     {
5039       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5040                                         struct dwarf2_per_cu_quick_data);
5041       tu_group->t.first_tu = cu->per_cu;
5042     }
5043   else
5044     {
5045       unsigned int line_offset = line_offset_struct.sect_off;
5046       struct partial_symtab *pst;
5047       char *name;
5048
5049       /* Give the symtab a useful name for debug purposes.  */
5050       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5051         name = xstrprintf ("<type_units_%d>",
5052                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5053       else
5054         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5055
5056       pst = create_partial_symtab (per_cu, name);
5057       pst->anonymous = 1;
5058
5059       xfree (name);
5060     }
5061
5062   tu_group->hash.dwo_unit = cu->dwo_unit;
5063   tu_group->hash.line_offset = line_offset_struct;
5064
5065   return tu_group;
5066 }
5067
5068 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5069    STMT_LIST is a DW_AT_stmt_list attribute.  */
5070
5071 static struct type_unit_group *
5072 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5073 {
5074   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5075   struct type_unit_group *tu_group;
5076   void **slot;
5077   unsigned int line_offset;
5078   struct type_unit_group type_unit_group_for_lookup;
5079
5080   if (dwarf2_per_objfile->type_unit_groups == NULL)
5081     {
5082       dwarf2_per_objfile->type_unit_groups =
5083         allocate_type_unit_groups_table ();
5084     }
5085
5086   /* Do we need to create a new group, or can we use an existing one?  */
5087
5088   if (stmt_list)
5089     {
5090       line_offset = DW_UNSND (stmt_list);
5091       ++tu_stats->nr_symtab_sharers;
5092     }
5093   else
5094     {
5095       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5096          We can do various things here like create one group per TU or
5097          spread them over multiple groups to split up the expansion work.
5098          To avoid worst case scenarios (too many groups or too large groups)
5099          we, umm, group them in bunches.  */
5100       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5101                      | (tu_stats->nr_stmt_less_type_units
5102                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5103       ++tu_stats->nr_stmt_less_type_units;
5104     }
5105
5106   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5107   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5108   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5109                          &type_unit_group_for_lookup, INSERT);
5110   if (*slot != NULL)
5111     {
5112       tu_group = *slot;
5113       gdb_assert (tu_group != NULL);
5114     }
5115   else
5116     {
5117       sect_offset line_offset_struct;
5118
5119       line_offset_struct.sect_off = line_offset;
5120       tu_group = create_type_unit_group (cu, line_offset_struct);
5121       *slot = tu_group;
5122       ++tu_stats->nr_symtabs;
5123     }
5124
5125   return tu_group;
5126 }
5127
5128 /* Struct used to sort TUs by their abbreviation table offset.  */
5129
5130 struct tu_abbrev_offset
5131 {
5132   struct signatured_type *sig_type;
5133   sect_offset abbrev_offset;
5134 };
5135
5136 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5137
5138 static int
5139 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5140 {
5141   const struct tu_abbrev_offset * const *a = ap;
5142   const struct tu_abbrev_offset * const *b = bp;
5143   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5144   unsigned int boff = (*b)->abbrev_offset.sect_off;
5145
5146   return (aoff > boff) - (aoff < boff);
5147 }
5148
5149 /* A helper function to add a type_unit_group to a table.  */
5150
5151 static int
5152 add_type_unit_group_to_table (void **slot, void *datum)
5153 {
5154   struct type_unit_group *tu_group = *slot;
5155   struct type_unit_group ***datap = datum;
5156
5157   **datap = tu_group;
5158   ++*datap;
5159
5160   return 1;
5161 }
5162
5163 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5164    each one passing FUNC,DATA.
5165
5166    The efficiency is because we sort TUs by the abbrev table they use and
5167    only read each abbrev table once.  In one program there are 200K TUs
5168    sharing 8K abbrev tables.
5169
5170    The main purpose of this function is to support building the
5171    dwarf2_per_objfile->type_unit_groups table.
5172    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5173    can collapse the search space by grouping them by stmt_list.
5174    The savings can be significant, in the same program from above the 200K TUs
5175    share 8K stmt_list tables.
5176
5177    FUNC is expected to call get_type_unit_group, which will create the
5178    struct type_unit_group if necessary and add it to
5179    dwarf2_per_objfile->type_unit_groups.  */
5180
5181 static void
5182 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5183 {
5184   struct objfile *objfile = dwarf2_per_objfile->objfile;
5185   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5186   struct cleanup *cleanups;
5187   struct abbrev_table *abbrev_table;
5188   sect_offset abbrev_offset;
5189   struct tu_abbrev_offset *sorted_by_abbrev;
5190   struct type_unit_group **iter;
5191   int i;
5192
5193   /* It's up to the caller to not call us multiple times.  */
5194   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5195
5196   if (dwarf2_per_objfile->n_type_units == 0)
5197     return;
5198
5199   /* TUs typically share abbrev tables, and there can be way more TUs than
5200      abbrev tables.  Sort by abbrev table to reduce the number of times we
5201      read each abbrev table in.
5202      Alternatives are to punt or to maintain a cache of abbrev tables.
5203      This is simpler and efficient enough for now.
5204
5205      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5206      symtab to use).  Typically TUs with the same abbrev offset have the same
5207      stmt_list value too so in practice this should work well.
5208
5209      The basic algorithm here is:
5210
5211       sort TUs by abbrev table
5212       for each TU with same abbrev table:
5213         read abbrev table if first user
5214         read TU top level DIE
5215           [IWBN if DWO skeletons had DW_AT_stmt_list]
5216         call FUNC  */
5217
5218   if (dwarf2_read_debug)
5219     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5220
5221   /* Sort in a separate table to maintain the order of all_type_units
5222      for .gdb_index: TU indices directly index all_type_units.  */
5223   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5224                               dwarf2_per_objfile->n_type_units);
5225   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5226     {
5227       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5228
5229       sorted_by_abbrev[i].sig_type = sig_type;
5230       sorted_by_abbrev[i].abbrev_offset =
5231         read_abbrev_offset (sig_type->per_cu.section,
5232                             sig_type->per_cu.offset);
5233     }
5234   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5235   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5236          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5237
5238   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5239      called any number of times, so we don't reset tu_stats here.  */
5240
5241   abbrev_offset.sect_off = ~(unsigned) 0;
5242   abbrev_table = NULL;
5243   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5244
5245   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5246     {
5247       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5248
5249       /* Switch to the next abbrev table if necessary.  */
5250       if (abbrev_table == NULL
5251           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5252         {
5253           if (abbrev_table != NULL)
5254             {
5255               abbrev_table_free (abbrev_table);
5256               /* Reset to NULL in case abbrev_table_read_table throws
5257                  an error: abbrev_table_free_cleanup will get called.  */
5258               abbrev_table = NULL;
5259             }
5260           abbrev_offset = tu->abbrev_offset;
5261           abbrev_table =
5262             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5263                                      abbrev_offset);
5264           ++tu_stats->nr_uniq_abbrev_tables;
5265         }
5266
5267       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5268                                func, data);
5269     }
5270
5271   /* Create a vector of pointers to primary type units to make it easy to
5272      iterate over them and CUs.  See dw2_get_primary_cu.  */
5273   dwarf2_per_objfile->n_type_unit_groups =
5274     htab_elements (dwarf2_per_objfile->type_unit_groups);
5275   dwarf2_per_objfile->all_type_unit_groups =
5276     obstack_alloc (&objfile->objfile_obstack,
5277                    dwarf2_per_objfile->n_type_unit_groups
5278                    * sizeof (struct type_unit_group *));
5279   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5280   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5281                           add_type_unit_group_to_table, &iter);
5282   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5283               == dwarf2_per_objfile->n_type_unit_groups);
5284
5285   do_cleanups (cleanups);
5286
5287   if (dwarf2_read_debug)
5288     {
5289       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5290       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5291                           dwarf2_per_objfile->n_type_units);
5292       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5293                           tu_stats->nr_uniq_abbrev_tables);
5294       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5295                           tu_stats->nr_symtabs);
5296       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5297                           tu_stats->nr_symtab_sharers);
5298       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5299                           tu_stats->nr_stmt_less_type_units);
5300     }
5301 }
5302 \f
5303 /* Partial symbol tables.  */
5304
5305 /* Create a psymtab named NAME and assign it to PER_CU.
5306
5307    The caller must fill in the following details:
5308    dirname, textlow, texthigh.  */
5309
5310 static struct partial_symtab *
5311 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5312 {
5313   struct objfile *objfile = per_cu->objfile;
5314   struct partial_symtab *pst;
5315
5316   pst = start_psymtab_common (objfile, objfile->section_offsets,
5317                               name, 0,
5318                               objfile->global_psymbols.next,
5319                               objfile->static_psymbols.next);
5320
5321   pst->psymtabs_addrmap_supported = 1;
5322
5323   /* This is the glue that links PST into GDB's symbol API.  */
5324   pst->read_symtab_private = per_cu;
5325   pst->read_symtab = dwarf2_read_symtab;
5326   per_cu->v.psymtab = pst;
5327
5328   return pst;
5329 }
5330
5331 /* die_reader_func for process_psymtab_comp_unit.  */
5332
5333 static void
5334 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5335                                   gdb_byte *info_ptr,
5336                                   struct die_info *comp_unit_die,
5337                                   int has_children,
5338                                   void *data)
5339 {
5340   struct dwarf2_cu *cu = reader->cu;
5341   struct objfile *objfile = cu->objfile;
5342   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5343   struct attribute *attr;
5344   CORE_ADDR baseaddr;
5345   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5346   struct partial_symtab *pst;
5347   int has_pc_info;
5348   const char *filename;
5349   int *want_partial_unit_ptr = data;
5350
5351   if (comp_unit_die->tag == DW_TAG_partial_unit
5352       && (want_partial_unit_ptr == NULL
5353           || !*want_partial_unit_ptr))
5354     return;
5355
5356   gdb_assert (! per_cu->is_debug_types);
5357
5358   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5359
5360   cu->list_in_scope = &file_symbols;
5361
5362   /* Allocate a new partial symbol table structure.  */
5363   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5364   if (attr == NULL || !DW_STRING (attr))
5365     filename = "";
5366   else
5367     filename = DW_STRING (attr);
5368
5369   pst = create_partial_symtab (per_cu, filename);
5370
5371   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5372   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5373   if (attr != NULL)
5374     pst->dirname = DW_STRING (attr);
5375
5376   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5377
5378   dwarf2_find_base_address (comp_unit_die, cu);
5379
5380   /* Possibly set the default values of LOWPC and HIGHPC from
5381      `DW_AT_ranges'.  */
5382   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5383                                       &best_highpc, cu, pst);
5384   if (has_pc_info == 1 && best_lowpc < best_highpc)
5385     /* Store the contiguous range if it is not empty; it can be empty for
5386        CUs with no code.  */
5387     addrmap_set_empty (objfile->psymtabs_addrmap,
5388                        best_lowpc + baseaddr,
5389                        best_highpc + baseaddr - 1, pst);
5390
5391   /* Check if comp unit has_children.
5392      If so, read the rest of the partial symbols from this comp unit.
5393      If not, there's no more debug_info for this comp unit.  */
5394   if (has_children)
5395     {
5396       struct partial_die_info *first_die;
5397       CORE_ADDR lowpc, highpc;
5398
5399       lowpc = ((CORE_ADDR) -1);
5400       highpc = ((CORE_ADDR) 0);
5401
5402       first_die = load_partial_dies (reader, info_ptr, 1);
5403
5404       scan_partial_symbols (first_die, &lowpc, &highpc,
5405                             ! has_pc_info, cu);
5406
5407       /* If we didn't find a lowpc, set it to highpc to avoid
5408          complaints from `maint check'.  */
5409       if (lowpc == ((CORE_ADDR) -1))
5410         lowpc = highpc;
5411
5412       /* If the compilation unit didn't have an explicit address range,
5413          then use the information extracted from its child dies.  */
5414       if (! has_pc_info)
5415         {
5416           best_lowpc = lowpc;
5417           best_highpc = highpc;
5418         }
5419     }
5420   pst->textlow = best_lowpc + baseaddr;
5421   pst->texthigh = best_highpc + baseaddr;
5422
5423   pst->n_global_syms = objfile->global_psymbols.next -
5424     (objfile->global_psymbols.list + pst->globals_offset);
5425   pst->n_static_syms = objfile->static_psymbols.next -
5426     (objfile->static_psymbols.list + pst->statics_offset);
5427   sort_pst_symbols (objfile, pst);
5428
5429   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5430     {
5431       int i;
5432       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5433       struct dwarf2_per_cu_data *iter;
5434
5435       /* Fill in 'dependencies' here; we fill in 'users' in a
5436          post-pass.  */
5437       pst->number_of_dependencies = len;
5438       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5439                                          len * sizeof (struct symtab *));
5440       for (i = 0;
5441            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5442                         i, iter);
5443            ++i)
5444         pst->dependencies[i] = iter->v.psymtab;
5445
5446       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5447     }
5448
5449   /* Get the list of files included in the current compilation unit,
5450      and build a psymtab for each of them.  */
5451   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5452
5453   if (dwarf2_read_debug)
5454     {
5455       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5456
5457       fprintf_unfiltered (gdb_stdlog,
5458                           "Psymtab for %s unit @0x%x: %s - %s"
5459                           ", %d global, %d static syms\n",
5460                           per_cu->is_debug_types ? "type" : "comp",
5461                           per_cu->offset.sect_off,
5462                           paddress (gdbarch, pst->textlow),
5463                           paddress (gdbarch, pst->texthigh),
5464                           pst->n_global_syms, pst->n_static_syms);
5465     }
5466 }
5467
5468 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5469    Process compilation unit THIS_CU for a psymtab.  */
5470
5471 static void
5472 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5473                            int want_partial_unit)
5474 {
5475   /* If this compilation unit was already read in, free the
5476      cached copy in order to read it in again.  This is
5477      necessary because we skipped some symbols when we first
5478      read in the compilation unit (see load_partial_dies).
5479      This problem could be avoided, but the benefit is unclear.  */
5480   if (this_cu->cu != NULL)
5481     free_one_cached_comp_unit (this_cu);
5482
5483   gdb_assert (! this_cu->is_debug_types);
5484   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5485                            process_psymtab_comp_unit_reader,
5486                            &want_partial_unit);
5487
5488   /* Age out any secondary CUs.  */
5489   age_cached_comp_units ();
5490 }
5491
5492 /* Reader function for build_type_psymtabs.  */
5493
5494 static void
5495 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5496                             gdb_byte *info_ptr,
5497                             struct die_info *type_unit_die,
5498                             int has_children,
5499                             void *data)
5500 {
5501   struct objfile *objfile = dwarf2_per_objfile->objfile;
5502   struct dwarf2_cu *cu = reader->cu;
5503   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5504   struct type_unit_group *tu_group;
5505   struct attribute *attr;
5506   struct partial_die_info *first_die;
5507   CORE_ADDR lowpc, highpc;
5508   struct partial_symtab *pst;
5509
5510   gdb_assert (data == NULL);
5511
5512   if (! has_children)
5513     return;
5514
5515   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5516   tu_group = get_type_unit_group (cu, attr);
5517
5518   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->t.tus, per_cu);
5519
5520   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5521   cu->list_in_scope = &file_symbols;
5522   pst = create_partial_symtab (per_cu, "");
5523   pst->anonymous = 1;
5524
5525   first_die = load_partial_dies (reader, info_ptr, 1);
5526
5527   lowpc = (CORE_ADDR) -1;
5528   highpc = (CORE_ADDR) 0;
5529   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5530
5531   pst->n_global_syms = objfile->global_psymbols.next -
5532     (objfile->global_psymbols.list + pst->globals_offset);
5533   pst->n_static_syms = objfile->static_psymbols.next -
5534     (objfile->static_psymbols.list + pst->statics_offset);
5535   sort_pst_symbols (objfile, pst);
5536 }
5537
5538 /* Traversal function for build_type_psymtabs.  */
5539
5540 static int
5541 build_type_psymtab_dependencies (void **slot, void *info)
5542 {
5543   struct objfile *objfile = dwarf2_per_objfile->objfile;
5544   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5545   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5546   struct partial_symtab *pst = per_cu->v.psymtab;
5547   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->t.tus);
5548   struct dwarf2_per_cu_data *iter;
5549   int i;
5550
5551   gdb_assert (len > 0);
5552
5553   pst->number_of_dependencies = len;
5554   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5555                                      len * sizeof (struct psymtab *));
5556   for (i = 0;
5557        VEC_iterate (dwarf2_per_cu_ptr, tu_group->t.tus, i, iter);
5558        ++i)
5559     {
5560       pst->dependencies[i] = iter->v.psymtab;
5561       iter->type_unit_group = tu_group;
5562     }
5563
5564   VEC_free (dwarf2_per_cu_ptr, tu_group->t.tus);
5565
5566   return 1;
5567 }
5568
5569 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5570    Build partial symbol tables for the .debug_types comp-units.  */
5571
5572 static void
5573 build_type_psymtabs (struct objfile *objfile)
5574 {
5575   if (! create_all_type_units (objfile))
5576     return;
5577
5578   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5579
5580   /* Now that all TUs have been processed we can fill in the dependencies.  */
5581   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5582                           build_type_psymtab_dependencies, NULL);
5583 }
5584
5585 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5586
5587 static void
5588 psymtabs_addrmap_cleanup (void *o)
5589 {
5590   struct objfile *objfile = o;
5591
5592   objfile->psymtabs_addrmap = NULL;
5593 }
5594
5595 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5596
5597 static void
5598 set_partial_user (struct objfile *objfile)
5599 {
5600   int i;
5601
5602   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5603     {
5604       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5605       struct partial_symtab *pst = per_cu->v.psymtab;
5606       int j;
5607
5608       if (pst == NULL)
5609         continue;
5610
5611       for (j = 0; j < pst->number_of_dependencies; ++j)
5612         {
5613           /* Set the 'user' field only if it is not already set.  */
5614           if (pst->dependencies[j]->user == NULL)
5615             pst->dependencies[j]->user = pst;
5616         }
5617     }
5618 }
5619
5620 /* Build the partial symbol table by doing a quick pass through the
5621    .debug_info and .debug_abbrev sections.  */
5622
5623 static void
5624 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5625 {
5626   struct cleanup *back_to, *addrmap_cleanup;
5627   struct obstack temp_obstack;
5628   int i;
5629
5630   if (dwarf2_read_debug)
5631     {
5632       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5633                           objfile->name);
5634     }
5635
5636   dwarf2_per_objfile->reading_partial_symbols = 1;
5637
5638   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5639
5640   /* Any cached compilation units will be linked by the per-objfile
5641      read_in_chain.  Make sure to free them when we're done.  */
5642   back_to = make_cleanup (free_cached_comp_units, NULL);
5643
5644   build_type_psymtabs (objfile);
5645
5646   create_all_comp_units (objfile);
5647
5648   /* Create a temporary address map on a temporary obstack.  We later
5649      copy this to the final obstack.  */
5650   obstack_init (&temp_obstack);
5651   make_cleanup_obstack_free (&temp_obstack);
5652   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5653   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5654
5655   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5656     {
5657       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5658
5659       process_psymtab_comp_unit (per_cu, 0);
5660     }
5661
5662   set_partial_user (objfile);
5663
5664   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5665                                                     &objfile->objfile_obstack);
5666   discard_cleanups (addrmap_cleanup);
5667
5668   do_cleanups (back_to);
5669
5670   if (dwarf2_read_debug)
5671     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5672                         objfile->name);
5673 }
5674
5675 /* die_reader_func for load_partial_comp_unit.  */
5676
5677 static void
5678 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5679                                gdb_byte *info_ptr,
5680                                struct die_info *comp_unit_die,
5681                                int has_children,
5682                                void *data)
5683 {
5684   struct dwarf2_cu *cu = reader->cu;
5685
5686   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5687
5688   /* Check if comp unit has_children.
5689      If so, read the rest of the partial symbols from this comp unit.
5690      If not, there's no more debug_info for this comp unit.  */
5691   if (has_children)
5692     load_partial_dies (reader, info_ptr, 0);
5693 }
5694
5695 /* Load the partial DIEs for a secondary CU into memory.
5696    This is also used when rereading a primary CU with load_all_dies.  */
5697
5698 static void
5699 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5700 {
5701   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5702                            load_partial_comp_unit_reader, NULL);
5703 }
5704
5705 static void
5706 read_comp_units_from_section (struct objfile *objfile,
5707                               struct dwarf2_section_info *section,
5708                               unsigned int is_dwz,
5709                               int *n_allocated,
5710                               int *n_comp_units,
5711                               struct dwarf2_per_cu_data ***all_comp_units)
5712 {
5713   gdb_byte *info_ptr;
5714   bfd *abfd = section->asection->owner;
5715
5716   dwarf2_read_section (objfile, section);
5717
5718   info_ptr = section->buffer;
5719
5720   while (info_ptr < section->buffer + section->size)
5721     {
5722       unsigned int length, initial_length_size;
5723       struct dwarf2_per_cu_data *this_cu;
5724       sect_offset offset;
5725
5726       offset.sect_off = info_ptr - section->buffer;
5727
5728       /* Read just enough information to find out where the next
5729          compilation unit is.  */
5730       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5731
5732       /* Save the compilation unit for later lookup.  */
5733       this_cu = obstack_alloc (&objfile->objfile_obstack,
5734                                sizeof (struct dwarf2_per_cu_data));
5735       memset (this_cu, 0, sizeof (*this_cu));
5736       this_cu->offset = offset;
5737       this_cu->length = length + initial_length_size;
5738       this_cu->is_dwz = is_dwz;
5739       this_cu->objfile = objfile;
5740       this_cu->section = section;
5741
5742       if (*n_comp_units == *n_allocated)
5743         {
5744           *n_allocated *= 2;
5745           *all_comp_units = xrealloc (*all_comp_units,
5746                                       *n_allocated
5747                                       * sizeof (struct dwarf2_per_cu_data *));
5748         }
5749       (*all_comp_units)[*n_comp_units] = this_cu;
5750       ++*n_comp_units;
5751
5752       info_ptr = info_ptr + this_cu->length;
5753     }
5754 }
5755
5756 /* Create a list of all compilation units in OBJFILE.
5757    This is only done for -readnow and building partial symtabs.  */
5758
5759 static void
5760 create_all_comp_units (struct objfile *objfile)
5761 {
5762   int n_allocated;
5763   int n_comp_units;
5764   struct dwarf2_per_cu_data **all_comp_units;
5765
5766   n_comp_units = 0;
5767   n_allocated = 10;
5768   all_comp_units = xmalloc (n_allocated
5769                             * sizeof (struct dwarf2_per_cu_data *));
5770
5771   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5772                                 &n_allocated, &n_comp_units, &all_comp_units);
5773
5774   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5775     {
5776       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5777
5778       read_comp_units_from_section (objfile, &dwz->info, 1,
5779                                     &n_allocated, &n_comp_units,
5780                                     &all_comp_units);
5781     }
5782
5783   dwarf2_per_objfile->all_comp_units
5784     = obstack_alloc (&objfile->objfile_obstack,
5785                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5786   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5787           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5788   xfree (all_comp_units);
5789   dwarf2_per_objfile->n_comp_units = n_comp_units;
5790 }
5791
5792 /* Process all loaded DIEs for compilation unit CU, starting at
5793    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5794    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5795    DW_AT_ranges).  If NEED_PC is set, then this function will set
5796    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5797    and record the covered ranges in the addrmap.  */
5798
5799 static void
5800 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5801                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5802 {
5803   struct partial_die_info *pdi;
5804
5805   /* Now, march along the PDI's, descending into ones which have
5806      interesting children but skipping the children of the other ones,
5807      until we reach the end of the compilation unit.  */
5808
5809   pdi = first_die;
5810
5811   while (pdi != NULL)
5812     {
5813       fixup_partial_die (pdi, cu);
5814
5815       /* Anonymous namespaces or modules have no name but have interesting
5816          children, so we need to look at them.  Ditto for anonymous
5817          enums.  */
5818
5819       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5820           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5821           || pdi->tag == DW_TAG_imported_unit)
5822         {
5823           switch (pdi->tag)
5824             {
5825             case DW_TAG_subprogram:
5826               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5827               break;
5828             case DW_TAG_constant:
5829             case DW_TAG_variable:
5830             case DW_TAG_typedef:
5831             case DW_TAG_union_type:
5832               if (!pdi->is_declaration)
5833                 {
5834                   add_partial_symbol (pdi, cu);
5835                 }
5836               break;
5837             case DW_TAG_class_type:
5838             case DW_TAG_interface_type:
5839             case DW_TAG_structure_type:
5840               if (!pdi->is_declaration)
5841                 {
5842                   add_partial_symbol (pdi, cu);
5843                 }
5844               break;
5845             case DW_TAG_enumeration_type:
5846               if (!pdi->is_declaration)
5847                 add_partial_enumeration (pdi, cu);
5848               break;
5849             case DW_TAG_base_type:
5850             case DW_TAG_subrange_type:
5851               /* File scope base type definitions are added to the partial
5852                  symbol table.  */
5853               add_partial_symbol (pdi, cu);
5854               break;
5855             case DW_TAG_namespace:
5856               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5857               break;
5858             case DW_TAG_module:
5859               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5860               break;
5861             case DW_TAG_imported_unit:
5862               {
5863                 struct dwarf2_per_cu_data *per_cu;
5864
5865                 /* For now we don't handle imported units in type units.  */
5866                 if (cu->per_cu->is_debug_types)
5867                   {
5868                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5869                              " supported in type units [in module %s]"),
5870                            cu->objfile->name);
5871                   }
5872
5873                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5874                                                            pdi->is_dwz,
5875                                                            cu->objfile);
5876
5877                 /* Go read the partial unit, if needed.  */
5878                 if (per_cu->v.psymtab == NULL)
5879                   process_psymtab_comp_unit (per_cu, 1);
5880
5881                 VEC_safe_push (dwarf2_per_cu_ptr,
5882                                cu->per_cu->imported_symtabs, per_cu);
5883               }
5884               break;
5885             default:
5886               break;
5887             }
5888         }
5889
5890       /* If the die has a sibling, skip to the sibling.  */
5891
5892       pdi = pdi->die_sibling;
5893     }
5894 }
5895
5896 /* Functions used to compute the fully scoped name of a partial DIE.
5897
5898    Normally, this is simple.  For C++, the parent DIE's fully scoped
5899    name is concatenated with "::" and the partial DIE's name.  For
5900    Java, the same thing occurs except that "." is used instead of "::".
5901    Enumerators are an exception; they use the scope of their parent
5902    enumeration type, i.e. the name of the enumeration type is not
5903    prepended to the enumerator.
5904
5905    There are two complexities.  One is DW_AT_specification; in this
5906    case "parent" means the parent of the target of the specification,
5907    instead of the direct parent of the DIE.  The other is compilers
5908    which do not emit DW_TAG_namespace; in this case we try to guess
5909    the fully qualified name of structure types from their members'
5910    linkage names.  This must be done using the DIE's children rather
5911    than the children of any DW_AT_specification target.  We only need
5912    to do this for structures at the top level, i.e. if the target of
5913    any DW_AT_specification (if any; otherwise the DIE itself) does not
5914    have a parent.  */
5915
5916 /* Compute the scope prefix associated with PDI's parent, in
5917    compilation unit CU.  The result will be allocated on CU's
5918    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5919    field.  NULL is returned if no prefix is necessary.  */
5920 static const char *
5921 partial_die_parent_scope (struct partial_die_info *pdi,
5922                           struct dwarf2_cu *cu)
5923 {
5924   const char *grandparent_scope;
5925   struct partial_die_info *parent, *real_pdi;
5926
5927   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5928      then this means the parent of the specification DIE.  */
5929
5930   real_pdi = pdi;
5931   while (real_pdi->has_specification)
5932     real_pdi = find_partial_die (real_pdi->spec_offset,
5933                                  real_pdi->spec_is_dwz, cu);
5934
5935   parent = real_pdi->die_parent;
5936   if (parent == NULL)
5937     return NULL;
5938
5939   if (parent->scope_set)
5940     return parent->scope;
5941
5942   fixup_partial_die (parent, cu);
5943
5944   grandparent_scope = partial_die_parent_scope (parent, cu);
5945
5946   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5947      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5948      Work around this problem here.  */
5949   if (cu->language == language_cplus
5950       && parent->tag == DW_TAG_namespace
5951       && strcmp (parent->name, "::") == 0
5952       && grandparent_scope == NULL)
5953     {
5954       parent->scope = NULL;
5955       parent->scope_set = 1;
5956       return NULL;
5957     }
5958
5959   if (pdi->tag == DW_TAG_enumerator)
5960     /* Enumerators should not get the name of the enumeration as a prefix.  */
5961     parent->scope = grandparent_scope;
5962   else if (parent->tag == DW_TAG_namespace
5963       || parent->tag == DW_TAG_module
5964       || parent->tag == DW_TAG_structure_type
5965       || parent->tag == DW_TAG_class_type
5966       || parent->tag == DW_TAG_interface_type
5967       || parent->tag == DW_TAG_union_type
5968       || parent->tag == DW_TAG_enumeration_type)
5969     {
5970       if (grandparent_scope == NULL)
5971         parent->scope = parent->name;
5972       else
5973         parent->scope = typename_concat (&cu->comp_unit_obstack,
5974                                          grandparent_scope,
5975                                          parent->name, 0, cu);
5976     }
5977   else
5978     {
5979       /* FIXME drow/2004-04-01: What should we be doing with
5980          function-local names?  For partial symbols, we should probably be
5981          ignoring them.  */
5982       complaint (&symfile_complaints,
5983                  _("unhandled containing DIE tag %d for DIE at %d"),
5984                  parent->tag, pdi->offset.sect_off);
5985       parent->scope = grandparent_scope;
5986     }
5987
5988   parent->scope_set = 1;
5989   return parent->scope;
5990 }
5991
5992 /* Return the fully scoped name associated with PDI, from compilation unit
5993    CU.  The result will be allocated with malloc.  */
5994
5995 static char *
5996 partial_die_full_name (struct partial_die_info *pdi,
5997                        struct dwarf2_cu *cu)
5998 {
5999   const char *parent_scope;
6000
6001   /* If this is a template instantiation, we can not work out the
6002      template arguments from partial DIEs.  So, unfortunately, we have
6003      to go through the full DIEs.  At least any work we do building
6004      types here will be reused if full symbols are loaded later.  */
6005   if (pdi->has_template_arguments)
6006     {
6007       fixup_partial_die (pdi, cu);
6008
6009       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6010         {
6011           struct die_info *die;
6012           struct attribute attr;
6013           struct dwarf2_cu *ref_cu = cu;
6014
6015           /* DW_FORM_ref_addr is using section offset.  */
6016           attr.name = 0;
6017           attr.form = DW_FORM_ref_addr;
6018           attr.u.unsnd = pdi->offset.sect_off;
6019           die = follow_die_ref (NULL, &attr, &ref_cu);
6020
6021           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6022         }
6023     }
6024
6025   parent_scope = partial_die_parent_scope (pdi, cu);
6026   if (parent_scope == NULL)
6027     return NULL;
6028   else
6029     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6030 }
6031
6032 static void
6033 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6034 {
6035   struct objfile *objfile = cu->objfile;
6036   CORE_ADDR addr = 0;
6037   const char *actual_name = NULL;
6038   CORE_ADDR baseaddr;
6039   char *built_actual_name;
6040
6041   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6042
6043   built_actual_name = partial_die_full_name (pdi, cu);
6044   if (built_actual_name != NULL)
6045     actual_name = built_actual_name;
6046
6047   if (actual_name == NULL)
6048     actual_name = pdi->name;
6049
6050   switch (pdi->tag)
6051     {
6052     case DW_TAG_subprogram:
6053       if (pdi->is_external || cu->language == language_ada)
6054         {
6055           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6056              of the global scope.  But in Ada, we want to be able to access
6057              nested procedures globally.  So all Ada subprograms are stored
6058              in the global scope.  */
6059           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6060              mst_text, objfile); */
6061           add_psymbol_to_list (actual_name, strlen (actual_name),
6062                                built_actual_name != NULL,
6063                                VAR_DOMAIN, LOC_BLOCK,
6064                                &objfile->global_psymbols,
6065                                0, pdi->lowpc + baseaddr,
6066                                cu->language, objfile);
6067         }
6068       else
6069         {
6070           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6071              mst_file_text, objfile); */
6072           add_psymbol_to_list (actual_name, strlen (actual_name),
6073                                built_actual_name != NULL,
6074                                VAR_DOMAIN, LOC_BLOCK,
6075                                &objfile->static_psymbols,
6076                                0, pdi->lowpc + baseaddr,
6077                                cu->language, objfile);
6078         }
6079       break;
6080     case DW_TAG_constant:
6081       {
6082         struct psymbol_allocation_list *list;
6083
6084         if (pdi->is_external)
6085           list = &objfile->global_psymbols;
6086         else
6087           list = &objfile->static_psymbols;
6088         add_psymbol_to_list (actual_name, strlen (actual_name),
6089                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6090                              list, 0, 0, cu->language, objfile);
6091       }
6092       break;
6093     case DW_TAG_variable:
6094       if (pdi->d.locdesc)
6095         addr = decode_locdesc (pdi->d.locdesc, cu);
6096
6097       if (pdi->d.locdesc
6098           && addr == 0
6099           && !dwarf2_per_objfile->has_section_at_zero)
6100         {
6101           /* A global or static variable may also have been stripped
6102              out by the linker if unused, in which case its address
6103              will be nullified; do not add such variables into partial
6104              symbol table then.  */
6105         }
6106       else if (pdi->is_external)
6107         {
6108           /* Global Variable.
6109              Don't enter into the minimal symbol tables as there is
6110              a minimal symbol table entry from the ELF symbols already.
6111              Enter into partial symbol table if it has a location
6112              descriptor or a type.
6113              If the location descriptor is missing, new_symbol will create
6114              a LOC_UNRESOLVED symbol, the address of the variable will then
6115              be determined from the minimal symbol table whenever the variable
6116              is referenced.
6117              The address for the partial symbol table entry is not
6118              used by GDB, but it comes in handy for debugging partial symbol
6119              table building.  */
6120
6121           if (pdi->d.locdesc || pdi->has_type)
6122             add_psymbol_to_list (actual_name, strlen (actual_name),
6123                                  built_actual_name != NULL,
6124                                  VAR_DOMAIN, LOC_STATIC,
6125                                  &objfile->global_psymbols,
6126                                  0, addr + baseaddr,
6127                                  cu->language, objfile);
6128         }
6129       else
6130         {
6131           /* Static Variable.  Skip symbols without location descriptors.  */
6132           if (pdi->d.locdesc == NULL)
6133             {
6134               xfree (built_actual_name);
6135               return;
6136             }
6137           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6138              mst_file_data, objfile); */
6139           add_psymbol_to_list (actual_name, strlen (actual_name),
6140                                built_actual_name != NULL,
6141                                VAR_DOMAIN, LOC_STATIC,
6142                                &objfile->static_psymbols,
6143                                0, addr + baseaddr,
6144                                cu->language, objfile);
6145         }
6146       break;
6147     case DW_TAG_typedef:
6148     case DW_TAG_base_type:
6149     case DW_TAG_subrange_type:
6150       add_psymbol_to_list (actual_name, strlen (actual_name),
6151                            built_actual_name != NULL,
6152                            VAR_DOMAIN, LOC_TYPEDEF,
6153                            &objfile->static_psymbols,
6154                            0, (CORE_ADDR) 0, cu->language, objfile);
6155       break;
6156     case DW_TAG_namespace:
6157       add_psymbol_to_list (actual_name, strlen (actual_name),
6158                            built_actual_name != NULL,
6159                            VAR_DOMAIN, LOC_TYPEDEF,
6160                            &objfile->global_psymbols,
6161                            0, (CORE_ADDR) 0, cu->language, objfile);
6162       break;
6163     case DW_TAG_class_type:
6164     case DW_TAG_interface_type:
6165     case DW_TAG_structure_type:
6166     case DW_TAG_union_type:
6167     case DW_TAG_enumeration_type:
6168       /* Skip external references.  The DWARF standard says in the section
6169          about "Structure, Union, and Class Type Entries": "An incomplete
6170          structure, union or class type is represented by a structure,
6171          union or class entry that does not have a byte size attribute
6172          and that has a DW_AT_declaration attribute."  */
6173       if (!pdi->has_byte_size && pdi->is_declaration)
6174         {
6175           xfree (built_actual_name);
6176           return;
6177         }
6178
6179       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6180          static vs. global.  */
6181       add_psymbol_to_list (actual_name, strlen (actual_name),
6182                            built_actual_name != NULL,
6183                            STRUCT_DOMAIN, LOC_TYPEDEF,
6184                            (cu->language == language_cplus
6185                             || cu->language == language_java)
6186                            ? &objfile->global_psymbols
6187                            : &objfile->static_psymbols,
6188                            0, (CORE_ADDR) 0, cu->language, objfile);
6189
6190       break;
6191     case DW_TAG_enumerator:
6192       add_psymbol_to_list (actual_name, strlen (actual_name),
6193                            built_actual_name != NULL,
6194                            VAR_DOMAIN, LOC_CONST,
6195                            (cu->language == language_cplus
6196                             || cu->language == language_java)
6197                            ? &objfile->global_psymbols
6198                            : &objfile->static_psymbols,
6199                            0, (CORE_ADDR) 0, cu->language, objfile);
6200       break;
6201     default:
6202       break;
6203     }
6204
6205   xfree (built_actual_name);
6206 }
6207
6208 /* Read a partial die corresponding to a namespace; also, add a symbol
6209    corresponding to that namespace to the symbol table.  NAMESPACE is
6210    the name of the enclosing namespace.  */
6211
6212 static void
6213 add_partial_namespace (struct partial_die_info *pdi,
6214                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6215                        int need_pc, struct dwarf2_cu *cu)
6216 {
6217   /* Add a symbol for the namespace.  */
6218
6219   add_partial_symbol (pdi, cu);
6220
6221   /* Now scan partial symbols in that namespace.  */
6222
6223   if (pdi->has_children)
6224     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6225 }
6226
6227 /* Read a partial die corresponding to a Fortran module.  */
6228
6229 static void
6230 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6231                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6232 {
6233   /* Now scan partial symbols in that module.  */
6234
6235   if (pdi->has_children)
6236     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6237 }
6238
6239 /* Read a partial die corresponding to a subprogram and create a partial
6240    symbol for that subprogram.  When the CU language allows it, this
6241    routine also defines a partial symbol for each nested subprogram
6242    that this subprogram contains.
6243
6244    DIE my also be a lexical block, in which case we simply search
6245    recursively for suprograms defined inside that lexical block.
6246    Again, this is only performed when the CU language allows this
6247    type of definitions.  */
6248
6249 static void
6250 add_partial_subprogram (struct partial_die_info *pdi,
6251                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6252                         int need_pc, struct dwarf2_cu *cu)
6253 {
6254   if (pdi->tag == DW_TAG_subprogram)
6255     {
6256       if (pdi->has_pc_info)
6257         {
6258           if (pdi->lowpc < *lowpc)
6259             *lowpc = pdi->lowpc;
6260           if (pdi->highpc > *highpc)
6261             *highpc = pdi->highpc;
6262           if (need_pc)
6263             {
6264               CORE_ADDR baseaddr;
6265               struct objfile *objfile = cu->objfile;
6266
6267               baseaddr = ANOFFSET (objfile->section_offsets,
6268                                    SECT_OFF_TEXT (objfile));
6269               addrmap_set_empty (objfile->psymtabs_addrmap,
6270                                  pdi->lowpc + baseaddr,
6271                                  pdi->highpc - 1 + baseaddr,
6272                                  cu->per_cu->v.psymtab);
6273             }
6274         }
6275
6276       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6277         {
6278           if (!pdi->is_declaration)
6279             /* Ignore subprogram DIEs that do not have a name, they are
6280                illegal.  Do not emit a complaint at this point, we will
6281                do so when we convert this psymtab into a symtab.  */
6282             if (pdi->name)
6283               add_partial_symbol (pdi, cu);
6284         }
6285     }
6286
6287   if (! pdi->has_children)
6288     return;
6289
6290   if (cu->language == language_ada)
6291     {
6292       pdi = pdi->die_child;
6293       while (pdi != NULL)
6294         {
6295           fixup_partial_die (pdi, cu);
6296           if (pdi->tag == DW_TAG_subprogram
6297               || pdi->tag == DW_TAG_lexical_block)
6298             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6299           pdi = pdi->die_sibling;
6300         }
6301     }
6302 }
6303
6304 /* Read a partial die corresponding to an enumeration type.  */
6305
6306 static void
6307 add_partial_enumeration (struct partial_die_info *enum_pdi,
6308                          struct dwarf2_cu *cu)
6309 {
6310   struct partial_die_info *pdi;
6311
6312   if (enum_pdi->name != NULL)
6313     add_partial_symbol (enum_pdi, cu);
6314
6315   pdi = enum_pdi->die_child;
6316   while (pdi)
6317     {
6318       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6319         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6320       else
6321         add_partial_symbol (pdi, cu);
6322       pdi = pdi->die_sibling;
6323     }
6324 }
6325
6326 /* Return the initial uleb128 in the die at INFO_PTR.  */
6327
6328 static unsigned int
6329 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
6330 {
6331   unsigned int bytes_read;
6332
6333   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6334 }
6335
6336 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6337    Return the corresponding abbrev, or NULL if the number is zero (indicating
6338    an empty DIE).  In either case *BYTES_READ will be set to the length of
6339    the initial number.  */
6340
6341 static struct abbrev_info *
6342 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
6343                  struct dwarf2_cu *cu)
6344 {
6345   bfd *abfd = cu->objfile->obfd;
6346   unsigned int abbrev_number;
6347   struct abbrev_info *abbrev;
6348
6349   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6350
6351   if (abbrev_number == 0)
6352     return NULL;
6353
6354   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6355   if (!abbrev)
6356     {
6357       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6358              abbrev_number, bfd_get_filename (abfd));
6359     }
6360
6361   return abbrev;
6362 }
6363
6364 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6365    Returns a pointer to the end of a series of DIEs, terminated by an empty
6366    DIE.  Any children of the skipped DIEs will also be skipped.  */
6367
6368 static gdb_byte *
6369 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
6370 {
6371   struct dwarf2_cu *cu = reader->cu;
6372   struct abbrev_info *abbrev;
6373   unsigned int bytes_read;
6374
6375   while (1)
6376     {
6377       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6378       if (abbrev == NULL)
6379         return info_ptr + bytes_read;
6380       else
6381         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6382     }
6383 }
6384
6385 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6386    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6387    abbrev corresponding to that skipped uleb128 should be passed in
6388    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6389    children.  */
6390
6391 static gdb_byte *
6392 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
6393               struct abbrev_info *abbrev)
6394 {
6395   unsigned int bytes_read;
6396   struct attribute attr;
6397   bfd *abfd = reader->abfd;
6398   struct dwarf2_cu *cu = reader->cu;
6399   gdb_byte *buffer = reader->buffer;
6400   const gdb_byte *buffer_end = reader->buffer_end;
6401   gdb_byte *start_info_ptr = info_ptr;
6402   unsigned int form, i;
6403
6404   for (i = 0; i < abbrev->num_attrs; i++)
6405     {
6406       /* The only abbrev we care about is DW_AT_sibling.  */
6407       if (abbrev->attrs[i].name == DW_AT_sibling)
6408         {
6409           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6410           if (attr.form == DW_FORM_ref_addr)
6411             complaint (&symfile_complaints,
6412                        _("ignoring absolute DW_AT_sibling"));
6413           else
6414             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6415         }
6416
6417       /* If it isn't DW_AT_sibling, skip this attribute.  */
6418       form = abbrev->attrs[i].form;
6419     skip_attribute:
6420       switch (form)
6421         {
6422         case DW_FORM_ref_addr:
6423           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6424              and later it is offset sized.  */
6425           if (cu->header.version == 2)
6426             info_ptr += cu->header.addr_size;
6427           else
6428             info_ptr += cu->header.offset_size;
6429           break;
6430         case DW_FORM_GNU_ref_alt:
6431           info_ptr += cu->header.offset_size;
6432           break;
6433         case DW_FORM_addr:
6434           info_ptr += cu->header.addr_size;
6435           break;
6436         case DW_FORM_data1:
6437         case DW_FORM_ref1:
6438         case DW_FORM_flag:
6439           info_ptr += 1;
6440           break;
6441         case DW_FORM_flag_present:
6442           break;
6443         case DW_FORM_data2:
6444         case DW_FORM_ref2:
6445           info_ptr += 2;
6446           break;
6447         case DW_FORM_data4:
6448         case DW_FORM_ref4:
6449           info_ptr += 4;
6450           break;
6451         case DW_FORM_data8:
6452         case DW_FORM_ref8:
6453         case DW_FORM_ref_sig8:
6454           info_ptr += 8;
6455           break;
6456         case DW_FORM_string:
6457           read_direct_string (abfd, info_ptr, &bytes_read);
6458           info_ptr += bytes_read;
6459           break;
6460         case DW_FORM_sec_offset:
6461         case DW_FORM_strp:
6462         case DW_FORM_GNU_strp_alt:
6463           info_ptr += cu->header.offset_size;
6464           break;
6465         case DW_FORM_exprloc:
6466         case DW_FORM_block:
6467           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6468           info_ptr += bytes_read;
6469           break;
6470         case DW_FORM_block1:
6471           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6472           break;
6473         case DW_FORM_block2:
6474           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6475           break;
6476         case DW_FORM_block4:
6477           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6478           break;
6479         case DW_FORM_sdata:
6480         case DW_FORM_udata:
6481         case DW_FORM_ref_udata:
6482         case DW_FORM_GNU_addr_index:
6483         case DW_FORM_GNU_str_index:
6484           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
6485           break;
6486         case DW_FORM_indirect:
6487           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6488           info_ptr += bytes_read;
6489           /* We need to continue parsing from here, so just go back to
6490              the top.  */
6491           goto skip_attribute;
6492
6493         default:
6494           error (_("Dwarf Error: Cannot handle %s "
6495                    "in DWARF reader [in module %s]"),
6496                  dwarf_form_name (form),
6497                  bfd_get_filename (abfd));
6498         }
6499     }
6500
6501   if (abbrev->has_children)
6502     return skip_children (reader, info_ptr);
6503   else
6504     return info_ptr;
6505 }
6506
6507 /* Locate ORIG_PDI's sibling.
6508    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6509
6510 static gdb_byte *
6511 locate_pdi_sibling (const struct die_reader_specs *reader,
6512                     struct partial_die_info *orig_pdi,
6513                     gdb_byte *info_ptr)
6514 {
6515   /* Do we know the sibling already?  */
6516
6517   if (orig_pdi->sibling)
6518     return orig_pdi->sibling;
6519
6520   /* Are there any children to deal with?  */
6521
6522   if (!orig_pdi->has_children)
6523     return info_ptr;
6524
6525   /* Skip the children the long way.  */
6526
6527   return skip_children (reader, info_ptr);
6528 }
6529
6530 /* Expand this partial symbol table into a full symbol table.  SELF is
6531    not NULL.  */
6532
6533 static void
6534 dwarf2_read_symtab (struct partial_symtab *self,
6535                     struct objfile *objfile)
6536 {
6537   if (self->readin)
6538     {
6539       warning (_("bug: psymtab for %s is already read in."),
6540                self->filename);
6541     }
6542   else
6543     {
6544       if (info_verbose)
6545         {
6546           printf_filtered (_("Reading in symbols for %s..."),
6547                            self->filename);
6548           gdb_flush (gdb_stdout);
6549         }
6550
6551       /* Restore our global data.  */
6552       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6553
6554       /* If this psymtab is constructed from a debug-only objfile, the
6555          has_section_at_zero flag will not necessarily be correct.  We
6556          can get the correct value for this flag by looking at the data
6557          associated with the (presumably stripped) associated objfile.  */
6558       if (objfile->separate_debug_objfile_backlink)
6559         {
6560           struct dwarf2_per_objfile *dpo_backlink
6561             = objfile_data (objfile->separate_debug_objfile_backlink,
6562                             dwarf2_objfile_data_key);
6563
6564           dwarf2_per_objfile->has_section_at_zero
6565             = dpo_backlink->has_section_at_zero;
6566         }
6567
6568       dwarf2_per_objfile->reading_partial_symbols = 0;
6569
6570       psymtab_to_symtab_1 (self);
6571
6572       /* Finish up the debug error message.  */
6573       if (info_verbose)
6574         printf_filtered (_("done.\n"));
6575     }
6576
6577   process_cu_includes ();
6578 }
6579 \f
6580 /* Reading in full CUs.  */
6581
6582 /* Add PER_CU to the queue.  */
6583
6584 static void
6585 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6586                  enum language pretend_language)
6587 {
6588   struct dwarf2_queue_item *item;
6589
6590   per_cu->queued = 1;
6591   item = xmalloc (sizeof (*item));
6592   item->per_cu = per_cu;
6593   item->pretend_language = pretend_language;
6594   item->next = NULL;
6595
6596   if (dwarf2_queue == NULL)
6597     dwarf2_queue = item;
6598   else
6599     dwarf2_queue_tail->next = item;
6600
6601   dwarf2_queue_tail = item;
6602 }
6603
6604 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6605    unit and add it to our queue.
6606    The result is non-zero if PER_CU was queued, otherwise the result is zero
6607    meaning either PER_CU is already queued or it is already loaded.  */
6608
6609 static int
6610 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6611                        struct dwarf2_per_cu_data *per_cu,
6612                        enum language pretend_language)
6613 {
6614   /* We may arrive here during partial symbol reading, if we need full
6615      DIEs to process an unusual case (e.g. template arguments).  Do
6616      not queue PER_CU, just tell our caller to load its DIEs.  */
6617   if (dwarf2_per_objfile->reading_partial_symbols)
6618     {
6619       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6620         return 1;
6621       return 0;
6622     }
6623
6624   /* Mark the dependence relation so that we don't flush PER_CU
6625      too early.  */
6626   dwarf2_add_dependence (this_cu, per_cu);
6627
6628   /* If it's already on the queue, we have nothing to do.  */
6629   if (per_cu->queued)
6630     return 0;
6631
6632   /* If the compilation unit is already loaded, just mark it as
6633      used.  */
6634   if (per_cu->cu != NULL)
6635     {
6636       per_cu->cu->last_used = 0;
6637       return 0;
6638     }
6639
6640   /* Add it to the queue.  */
6641   queue_comp_unit (per_cu, pretend_language);
6642
6643   return 1;
6644 }
6645
6646 /* Process the queue.  */
6647
6648 static void
6649 process_queue (void)
6650 {
6651   struct dwarf2_queue_item *item, *next_item;
6652
6653   if (dwarf2_read_debug)
6654     {
6655       fprintf_unfiltered (gdb_stdlog,
6656                           "Expanding one or more symtabs of objfile %s ...\n",
6657                           dwarf2_per_objfile->objfile->name);
6658     }
6659
6660   /* The queue starts out with one item, but following a DIE reference
6661      may load a new CU, adding it to the end of the queue.  */
6662   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6663     {
6664       if (dwarf2_per_objfile->using_index
6665           ? !item->per_cu->v.quick->symtab
6666           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6667         {
6668           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6669
6670           if (dwarf2_read_debug)
6671             {
6672               fprintf_unfiltered (gdb_stdlog,
6673                                   "Expanding symtab of %s at offset 0x%x\n",
6674                                   per_cu->is_debug_types ? "TU" : "CU",
6675                                   per_cu->offset.sect_off);
6676             }
6677
6678           if (per_cu->is_debug_types)
6679             process_full_type_unit (per_cu, item->pretend_language);
6680           else
6681             process_full_comp_unit (per_cu, item->pretend_language);
6682
6683           if (dwarf2_read_debug)
6684             {
6685               fprintf_unfiltered (gdb_stdlog,
6686                                   "Done expanding %s at offset 0x%x\n",
6687                                   per_cu->is_debug_types ? "TU" : "CU",
6688                                   per_cu->offset.sect_off);
6689             }
6690         }
6691
6692       item->per_cu->queued = 0;
6693       next_item = item->next;
6694       xfree (item);
6695     }
6696
6697   dwarf2_queue_tail = NULL;
6698
6699   if (dwarf2_read_debug)
6700     {
6701       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6702                           dwarf2_per_objfile->objfile->name);
6703     }
6704 }
6705
6706 /* Free all allocated queue entries.  This function only releases anything if
6707    an error was thrown; if the queue was processed then it would have been
6708    freed as we went along.  */
6709
6710 static void
6711 dwarf2_release_queue (void *dummy)
6712 {
6713   struct dwarf2_queue_item *item, *last;
6714
6715   item = dwarf2_queue;
6716   while (item)
6717     {
6718       /* Anything still marked queued is likely to be in an
6719          inconsistent state, so discard it.  */
6720       if (item->per_cu->queued)
6721         {
6722           if (item->per_cu->cu != NULL)
6723             free_one_cached_comp_unit (item->per_cu);
6724           item->per_cu->queued = 0;
6725         }
6726
6727       last = item;
6728       item = item->next;
6729       xfree (last);
6730     }
6731
6732   dwarf2_queue = dwarf2_queue_tail = NULL;
6733 }
6734
6735 /* Read in full symbols for PST, and anything it depends on.  */
6736
6737 static void
6738 psymtab_to_symtab_1 (struct partial_symtab *pst)
6739 {
6740   struct dwarf2_per_cu_data *per_cu;
6741   int i;
6742
6743   if (pst->readin)
6744     return;
6745
6746   for (i = 0; i < pst->number_of_dependencies; i++)
6747     if (!pst->dependencies[i]->readin
6748         && pst->dependencies[i]->user == NULL)
6749       {
6750         /* Inform about additional files that need to be read in.  */
6751         if (info_verbose)
6752           {
6753             /* FIXME: i18n: Need to make this a single string.  */
6754             fputs_filtered (" ", gdb_stdout);
6755             wrap_here ("");
6756             fputs_filtered ("and ", gdb_stdout);
6757             wrap_here ("");
6758             printf_filtered ("%s...", pst->dependencies[i]->filename);
6759             wrap_here ("");     /* Flush output.  */
6760             gdb_flush (gdb_stdout);
6761           }
6762         psymtab_to_symtab_1 (pst->dependencies[i]);
6763       }
6764
6765   per_cu = pst->read_symtab_private;
6766
6767   if (per_cu == NULL)
6768     {
6769       /* It's an include file, no symbols to read for it.
6770          Everything is in the parent symtab.  */
6771       pst->readin = 1;
6772       return;
6773     }
6774
6775   dw2_do_instantiate_symtab (per_cu);
6776 }
6777
6778 /* Trivial hash function for die_info: the hash value of a DIE
6779    is its offset in .debug_info for this objfile.  */
6780
6781 static hashval_t
6782 die_hash (const void *item)
6783 {
6784   const struct die_info *die = item;
6785
6786   return die->offset.sect_off;
6787 }
6788
6789 /* Trivial comparison function for die_info structures: two DIEs
6790    are equal if they have the same offset.  */
6791
6792 static int
6793 die_eq (const void *item_lhs, const void *item_rhs)
6794 {
6795   const struct die_info *die_lhs = item_lhs;
6796   const struct die_info *die_rhs = item_rhs;
6797
6798   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6799 }
6800
6801 /* die_reader_func for load_full_comp_unit.
6802    This is identical to read_signatured_type_reader,
6803    but is kept separate for now.  */
6804
6805 static void
6806 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6807                             gdb_byte *info_ptr,
6808                             struct die_info *comp_unit_die,
6809                             int has_children,
6810                             void *data)
6811 {
6812   struct dwarf2_cu *cu = reader->cu;
6813   enum language *language_ptr = data;
6814
6815   gdb_assert (cu->die_hash == NULL);
6816   cu->die_hash =
6817     htab_create_alloc_ex (cu->header.length / 12,
6818                           die_hash,
6819                           die_eq,
6820                           NULL,
6821                           &cu->comp_unit_obstack,
6822                           hashtab_obstack_allocate,
6823                           dummy_obstack_deallocate);
6824
6825   if (has_children)
6826     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6827                                                   &info_ptr, comp_unit_die);
6828   cu->dies = comp_unit_die;
6829   /* comp_unit_die is not stored in die_hash, no need.  */
6830
6831   /* We try not to read any attributes in this function, because not
6832      all CUs needed for references have been loaded yet, and symbol
6833      table processing isn't initialized.  But we have to set the CU language,
6834      or we won't be able to build types correctly.
6835      Similarly, if we do not read the producer, we can not apply
6836      producer-specific interpretation.  */
6837   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6838 }
6839
6840 /* Load the DIEs associated with PER_CU into memory.  */
6841
6842 static void
6843 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6844                      enum language pretend_language)
6845 {
6846   gdb_assert (! this_cu->is_debug_types);
6847
6848   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6849                            load_full_comp_unit_reader, &pretend_language);
6850 }
6851
6852 /* Add a DIE to the delayed physname list.  */
6853
6854 static void
6855 add_to_method_list (struct type *type, int fnfield_index, int index,
6856                     const char *name, struct die_info *die,
6857                     struct dwarf2_cu *cu)
6858 {
6859   struct delayed_method_info mi;
6860   mi.type = type;
6861   mi.fnfield_index = fnfield_index;
6862   mi.index = index;
6863   mi.name = name;
6864   mi.die = die;
6865   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6866 }
6867
6868 /* A cleanup for freeing the delayed method list.  */
6869
6870 static void
6871 free_delayed_list (void *ptr)
6872 {
6873   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6874   if (cu->method_list != NULL)
6875     {
6876       VEC_free (delayed_method_info, cu->method_list);
6877       cu->method_list = NULL;
6878     }
6879 }
6880
6881 /* Compute the physnames of any methods on the CU's method list.
6882
6883    The computation of method physnames is delayed in order to avoid the
6884    (bad) condition that one of the method's formal parameters is of an as yet
6885    incomplete type.  */
6886
6887 static void
6888 compute_delayed_physnames (struct dwarf2_cu *cu)
6889 {
6890   int i;
6891   struct delayed_method_info *mi;
6892   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6893     {
6894       const char *physname;
6895       struct fn_fieldlist *fn_flp
6896         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6897       physname = dwarf2_physname (mi->name, mi->die, cu);
6898       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6899     }
6900 }
6901
6902 /* Go objects should be embedded in a DW_TAG_module DIE,
6903    and it's not clear if/how imported objects will appear.
6904    To keep Go support simple until that's worked out,
6905    go back through what we've read and create something usable.
6906    We could do this while processing each DIE, and feels kinda cleaner,
6907    but that way is more invasive.
6908    This is to, for example, allow the user to type "p var" or "b main"
6909    without having to specify the package name, and allow lookups
6910    of module.object to work in contexts that use the expression
6911    parser.  */
6912
6913 static void
6914 fixup_go_packaging (struct dwarf2_cu *cu)
6915 {
6916   char *package_name = NULL;
6917   struct pending *list;
6918   int i;
6919
6920   for (list = global_symbols; list != NULL; list = list->next)
6921     {
6922       for (i = 0; i < list->nsyms; ++i)
6923         {
6924           struct symbol *sym = list->symbol[i];
6925
6926           if (SYMBOL_LANGUAGE (sym) == language_go
6927               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6928             {
6929               char *this_package_name = go_symbol_package_name (sym);
6930
6931               if (this_package_name == NULL)
6932                 continue;
6933               if (package_name == NULL)
6934                 package_name = this_package_name;
6935               else
6936                 {
6937                   if (strcmp (package_name, this_package_name) != 0)
6938                     complaint (&symfile_complaints,
6939                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6940                                (SYMBOL_SYMTAB (sym)
6941                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
6942                                 : cu->objfile->name),
6943                                this_package_name, package_name);
6944                   xfree (this_package_name);
6945                 }
6946             }
6947         }
6948     }
6949
6950   if (package_name != NULL)
6951     {
6952       struct objfile *objfile = cu->objfile;
6953       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6954                                                       package_name,
6955                                                       strlen (package_name));
6956       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6957                                      saved_package_name, objfile);
6958       struct symbol *sym;
6959
6960       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6961
6962       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6963       SYMBOL_SET_LANGUAGE (sym, language_go);
6964       SYMBOL_SET_NAMES (sym, saved_package_name,
6965                         strlen (saved_package_name), 0, objfile);
6966       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6967          e.g., "main" finds the "main" module and not C's main().  */
6968       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6969       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
6970       SYMBOL_TYPE (sym) = type;
6971
6972       add_symbol_to_list (sym, &global_symbols);
6973
6974       xfree (package_name);
6975     }
6976 }
6977
6978 /* Return the symtab for PER_CU.  This works properly regardless of
6979    whether we're using the index or psymtabs.  */
6980
6981 static struct symtab *
6982 get_symtab (struct dwarf2_per_cu_data *per_cu)
6983 {
6984   return (dwarf2_per_objfile->using_index
6985           ? per_cu->v.quick->symtab
6986           : per_cu->v.psymtab->symtab);
6987 }
6988
6989 /* A helper function for computing the list of all symbol tables
6990    included by PER_CU.  */
6991
6992 static void
6993 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6994                                 htab_t all_children,
6995                                 struct dwarf2_per_cu_data *per_cu)
6996 {
6997   void **slot;
6998   int ix;
6999   struct dwarf2_per_cu_data *iter;
7000
7001   slot = htab_find_slot (all_children, per_cu, INSERT);
7002   if (*slot != NULL)
7003     {
7004       /* This inclusion and its children have been processed.  */
7005       return;
7006     }
7007
7008   *slot = per_cu;
7009   /* Only add a CU if it has a symbol table.  */
7010   if (get_symtab (per_cu) != NULL)
7011     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
7012
7013   for (ix = 0;
7014        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7015        ++ix)
7016     recursively_compute_inclusions (result, all_children, iter);
7017 }
7018
7019 /* Compute the symtab 'includes' fields for the symtab related to
7020    PER_CU.  */
7021
7022 static void
7023 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7024 {
7025   gdb_assert (! per_cu->is_debug_types);
7026
7027   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7028     {
7029       int ix, len;
7030       struct dwarf2_per_cu_data *iter;
7031       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
7032       htab_t all_children;
7033       struct symtab *symtab = get_symtab (per_cu);
7034
7035       /* If we don't have a symtab, we can just skip this case.  */
7036       if (symtab == NULL)
7037         return;
7038
7039       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7040                                         NULL, xcalloc, xfree);
7041
7042       for (ix = 0;
7043            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7044                         ix, iter);
7045            ++ix)
7046         recursively_compute_inclusions (&result_children, all_children, iter);
7047
7048       /* Now we have a transitive closure of all the included CUs, and
7049          for .gdb_index version 7 the included TUs, so we can convert it
7050          to a list of symtabs.  */
7051       len = VEC_length (dwarf2_per_cu_ptr, result_children);
7052       symtab->includes
7053         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7054                          (len + 1) * sizeof (struct symtab *));
7055       for (ix = 0;
7056            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
7057            ++ix)
7058         symtab->includes[ix] = get_symtab (iter);
7059       symtab->includes[len] = NULL;
7060
7061       VEC_free (dwarf2_per_cu_ptr, result_children);
7062       htab_delete (all_children);
7063     }
7064 }
7065
7066 /* Compute the 'includes' field for the symtabs of all the CUs we just
7067    read.  */
7068
7069 static void
7070 process_cu_includes (void)
7071 {
7072   int ix;
7073   struct dwarf2_per_cu_data *iter;
7074
7075   for (ix = 0;
7076        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7077                     ix, iter);
7078        ++ix)
7079     {
7080       if (! iter->is_debug_types)
7081         compute_symtab_includes (iter);
7082     }
7083
7084   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7085 }
7086
7087 /* Generate full symbol information for PER_CU, whose DIEs have
7088    already been loaded into memory.  */
7089
7090 static void
7091 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7092                         enum language pretend_language)
7093 {
7094   struct dwarf2_cu *cu = per_cu->cu;
7095   struct objfile *objfile = per_cu->objfile;
7096   CORE_ADDR lowpc, highpc;
7097   struct symtab *symtab;
7098   struct cleanup *back_to, *delayed_list_cleanup;
7099   CORE_ADDR baseaddr;
7100   struct block *static_block;
7101
7102   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7103
7104   buildsym_init ();
7105   back_to = make_cleanup (really_free_pendings, NULL);
7106   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7107
7108   cu->list_in_scope = &file_symbols;
7109
7110   cu->language = pretend_language;
7111   cu->language_defn = language_def (cu->language);
7112
7113   /* Do line number decoding in read_file_scope () */
7114   process_die (cu->dies, cu);
7115
7116   /* For now fudge the Go package.  */
7117   if (cu->language == language_go)
7118     fixup_go_packaging (cu);
7119
7120   /* Now that we have processed all the DIEs in the CU, all the types 
7121      should be complete, and it should now be safe to compute all of the
7122      physnames.  */
7123   compute_delayed_physnames (cu);
7124   do_cleanups (delayed_list_cleanup);
7125
7126   /* Some compilers don't define a DW_AT_high_pc attribute for the
7127      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7128      it, by scanning the DIE's below the compilation unit.  */
7129   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7130
7131   static_block
7132     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
7133                                    per_cu->imported_symtabs != NULL);
7134
7135   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7136      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7137      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7138      addrmap to help ensure it has an accurate map of pc values belonging to
7139      this comp unit.  */
7140   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7141
7142   symtab = end_symtab_from_static_block (static_block, objfile,
7143                                          SECT_OFF_TEXT (objfile), 0);
7144
7145   if (symtab != NULL)
7146     {
7147       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7148
7149       /* Set symtab language to language from DW_AT_language.  If the
7150          compilation is from a C file generated by language preprocessors, do
7151          not set the language if it was already deduced by start_subfile.  */
7152       if (!(cu->language == language_c && symtab->language != language_c))
7153         symtab->language = cu->language;
7154
7155       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7156          produce DW_AT_location with location lists but it can be possibly
7157          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7158          there were bugs in prologue debug info, fixed later in GCC-4.5
7159          by "unwind info for epilogues" patch (which is not directly related).
7160
7161          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7162          needed, it would be wrong due to missing DW_AT_producer there.
7163
7164          Still one can confuse GDB by using non-standard GCC compilation
7165          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7166          */ 
7167       if (cu->has_loclist && gcc_4_minor >= 5)
7168         symtab->locations_valid = 1;
7169
7170       if (gcc_4_minor >= 5)
7171         symtab->epilogue_unwind_valid = 1;
7172
7173       symtab->call_site_htab = cu->call_site_htab;
7174     }
7175
7176   if (dwarf2_per_objfile->using_index)
7177     per_cu->v.quick->symtab = symtab;
7178   else
7179     {
7180       struct partial_symtab *pst = per_cu->v.psymtab;
7181       pst->symtab = symtab;
7182       pst->readin = 1;
7183     }
7184
7185   /* Push it for inclusion processing later.  */
7186   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7187
7188   do_cleanups (back_to);
7189 }
7190
7191 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7192    already been loaded into memory.  */
7193
7194 static void
7195 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7196                         enum language pretend_language)
7197 {
7198   struct dwarf2_cu *cu = per_cu->cu;
7199   struct objfile *objfile = per_cu->objfile;
7200   struct symtab *symtab;
7201   struct cleanup *back_to, *delayed_list_cleanup;
7202
7203   buildsym_init ();
7204   back_to = make_cleanup (really_free_pendings, NULL);
7205   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7206
7207   cu->list_in_scope = &file_symbols;
7208
7209   cu->language = pretend_language;
7210   cu->language_defn = language_def (cu->language);
7211
7212   /* The symbol tables are set up in read_type_unit_scope.  */
7213   process_die (cu->dies, cu);
7214
7215   /* For now fudge the Go package.  */
7216   if (cu->language == language_go)
7217     fixup_go_packaging (cu);
7218
7219   /* Now that we have processed all the DIEs in the CU, all the types 
7220      should be complete, and it should now be safe to compute all of the
7221      physnames.  */
7222   compute_delayed_physnames (cu);
7223   do_cleanups (delayed_list_cleanup);
7224
7225   /* TUs share symbol tables.
7226      If this is the first TU to use this symtab, complete the construction
7227      of it with end_expandable_symtab.  Otherwise, complete the addition of
7228      this TU's symbols to the existing symtab.  */
7229   if (per_cu->type_unit_group->primary_symtab == NULL)
7230     {
7231       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7232       per_cu->type_unit_group->primary_symtab = symtab;
7233
7234       if (symtab != NULL)
7235         {
7236           /* Set symtab language to language from DW_AT_language.  If the
7237              compilation is from a C file generated by language preprocessors,
7238              do not set the language if it was already deduced by
7239              start_subfile.  */
7240           if (!(cu->language == language_c && symtab->language != language_c))
7241             symtab->language = cu->language;
7242         }
7243     }
7244   else
7245     {
7246       augment_type_symtab (objfile,
7247                            per_cu->type_unit_group->primary_symtab);
7248       symtab = per_cu->type_unit_group->primary_symtab;
7249     }
7250
7251   if (dwarf2_per_objfile->using_index)
7252     per_cu->v.quick->symtab = symtab;
7253   else
7254     {
7255       struct partial_symtab *pst = per_cu->v.psymtab;
7256       pst->symtab = symtab;
7257       pst->readin = 1;
7258     }
7259
7260   do_cleanups (back_to);
7261 }
7262
7263 /* Process an imported unit DIE.  */
7264
7265 static void
7266 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7267 {
7268   struct attribute *attr;
7269
7270   /* For now we don't handle imported units in type units.  */
7271   if (cu->per_cu->is_debug_types)
7272     {
7273       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7274                " supported in type units [in module %s]"),
7275              cu->objfile->name);
7276     }
7277
7278   attr = dwarf2_attr (die, DW_AT_import, cu);
7279   if (attr != NULL)
7280     {
7281       struct dwarf2_per_cu_data *per_cu;
7282       struct symtab *imported_symtab;
7283       sect_offset offset;
7284       int is_dwz;
7285
7286       offset = dwarf2_get_ref_die_offset (attr);
7287       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7288       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7289
7290       /* Queue the unit, if needed.  */
7291       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7292         load_full_comp_unit (per_cu, cu->language);
7293
7294       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7295                      per_cu);
7296     }
7297 }
7298
7299 /* Process a die and its children.  */
7300
7301 static void
7302 process_die (struct die_info *die, struct dwarf2_cu *cu)
7303 {
7304   switch (die->tag)
7305     {
7306     case DW_TAG_padding:
7307       break;
7308     case DW_TAG_compile_unit:
7309     case DW_TAG_partial_unit:
7310       read_file_scope (die, cu);
7311       break;
7312     case DW_TAG_type_unit:
7313       read_type_unit_scope (die, cu);
7314       break;
7315     case DW_TAG_subprogram:
7316     case DW_TAG_inlined_subroutine:
7317       read_func_scope (die, cu);
7318       break;
7319     case DW_TAG_lexical_block:
7320     case DW_TAG_try_block:
7321     case DW_TAG_catch_block:
7322       read_lexical_block_scope (die, cu);
7323       break;
7324     case DW_TAG_GNU_call_site:
7325       read_call_site_scope (die, cu);
7326       break;
7327     case DW_TAG_class_type:
7328     case DW_TAG_interface_type:
7329     case DW_TAG_structure_type:
7330     case DW_TAG_union_type:
7331       process_structure_scope (die, cu);
7332       break;
7333     case DW_TAG_enumeration_type:
7334       process_enumeration_scope (die, cu);
7335       break;
7336
7337     /* These dies have a type, but processing them does not create
7338        a symbol or recurse to process the children.  Therefore we can
7339        read them on-demand through read_type_die.  */
7340     case DW_TAG_subroutine_type:
7341     case DW_TAG_set_type:
7342     case DW_TAG_array_type:
7343     case DW_TAG_pointer_type:
7344     case DW_TAG_ptr_to_member_type:
7345     case DW_TAG_reference_type:
7346     case DW_TAG_string_type:
7347       break;
7348
7349     case DW_TAG_base_type:
7350     case DW_TAG_subrange_type:
7351     case DW_TAG_typedef:
7352       /* Add a typedef symbol for the type definition, if it has a
7353          DW_AT_name.  */
7354       new_symbol (die, read_type_die (die, cu), cu);
7355       break;
7356     case DW_TAG_common_block:
7357       read_common_block (die, cu);
7358       break;
7359     case DW_TAG_common_inclusion:
7360       break;
7361     case DW_TAG_namespace:
7362       cu->processing_has_namespace_info = 1;
7363       read_namespace (die, cu);
7364       break;
7365     case DW_TAG_module:
7366       cu->processing_has_namespace_info = 1;
7367       read_module (die, cu);
7368       break;
7369     case DW_TAG_imported_declaration:
7370     case DW_TAG_imported_module:
7371       cu->processing_has_namespace_info = 1;
7372       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7373                                  || cu->language != language_fortran))
7374         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7375                    dwarf_tag_name (die->tag));
7376       read_import_statement (die, cu);
7377       break;
7378
7379     case DW_TAG_imported_unit:
7380       process_imported_unit_die (die, cu);
7381       break;
7382
7383     default:
7384       new_symbol (die, NULL, cu);
7385       break;
7386     }
7387 }
7388 \f
7389 /* DWARF name computation.  */
7390
7391 /* A helper function for dwarf2_compute_name which determines whether DIE
7392    needs to have the name of the scope prepended to the name listed in the
7393    die.  */
7394
7395 static int
7396 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7397 {
7398   struct attribute *attr;
7399
7400   switch (die->tag)
7401     {
7402     case DW_TAG_namespace:
7403     case DW_TAG_typedef:
7404     case DW_TAG_class_type:
7405     case DW_TAG_interface_type:
7406     case DW_TAG_structure_type:
7407     case DW_TAG_union_type:
7408     case DW_TAG_enumeration_type:
7409     case DW_TAG_enumerator:
7410     case DW_TAG_subprogram:
7411     case DW_TAG_member:
7412       return 1;
7413
7414     case DW_TAG_variable:
7415     case DW_TAG_constant:
7416       /* We only need to prefix "globally" visible variables.  These include
7417          any variable marked with DW_AT_external or any variable that
7418          lives in a namespace.  [Variables in anonymous namespaces
7419          require prefixing, but they are not DW_AT_external.]  */
7420
7421       if (dwarf2_attr (die, DW_AT_specification, cu))
7422         {
7423           struct dwarf2_cu *spec_cu = cu;
7424
7425           return die_needs_namespace (die_specification (die, &spec_cu),
7426                                       spec_cu);
7427         }
7428
7429       attr = dwarf2_attr (die, DW_AT_external, cu);
7430       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7431           && die->parent->tag != DW_TAG_module)
7432         return 0;
7433       /* A variable in a lexical block of some kind does not need a
7434          namespace, even though in C++ such variables may be external
7435          and have a mangled name.  */
7436       if (die->parent->tag ==  DW_TAG_lexical_block
7437           || die->parent->tag ==  DW_TAG_try_block
7438           || die->parent->tag ==  DW_TAG_catch_block
7439           || die->parent->tag == DW_TAG_subprogram)
7440         return 0;
7441       return 1;
7442
7443     default:
7444       return 0;
7445     }
7446 }
7447
7448 /* Retrieve the last character from a mem_file.  */
7449
7450 static void
7451 do_ui_file_peek_last (void *object, const char *buffer, long length)
7452 {
7453   char *last_char_p = (char *) object;
7454
7455   if (length > 0)
7456     *last_char_p = buffer[length - 1];
7457 }
7458
7459 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7460    compute the physname for the object, which include a method's:
7461    - formal parameters (C++/Java),
7462    - receiver type (Go),
7463    - return type (Java).
7464
7465    The term "physname" is a bit confusing.
7466    For C++, for example, it is the demangled name.
7467    For Go, for example, it's the mangled name.
7468
7469    For Ada, return the DIE's linkage name rather than the fully qualified
7470    name.  PHYSNAME is ignored..
7471
7472    The result is allocated on the objfile_obstack and canonicalized.  */
7473
7474 static const char *
7475 dwarf2_compute_name (const char *name,
7476                      struct die_info *die, struct dwarf2_cu *cu,
7477                      int physname)
7478 {
7479   struct objfile *objfile = cu->objfile;
7480
7481   if (name == NULL)
7482     name = dwarf2_name (die, cu);
7483
7484   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7485      compute it by typename_concat inside GDB.  */
7486   if (cu->language == language_ada
7487       || (cu->language == language_fortran && physname))
7488     {
7489       /* For Ada unit, we prefer the linkage name over the name, as
7490          the former contains the exported name, which the user expects
7491          to be able to reference.  Ideally, we want the user to be able
7492          to reference this entity using either natural or linkage name,
7493          but we haven't started looking at this enhancement yet.  */
7494       struct attribute *attr;
7495
7496       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7497       if (attr == NULL)
7498         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7499       if (attr && DW_STRING (attr))
7500         return DW_STRING (attr);
7501     }
7502
7503   /* These are the only languages we know how to qualify names in.  */
7504   if (name != NULL
7505       && (cu->language == language_cplus || cu->language == language_java
7506           || cu->language == language_fortran))
7507     {
7508       if (die_needs_namespace (die, cu))
7509         {
7510           long length;
7511           const char *prefix;
7512           struct ui_file *buf;
7513
7514           prefix = determine_prefix (die, cu);
7515           buf = mem_fileopen ();
7516           if (*prefix != '\0')
7517             {
7518               char *prefixed_name = typename_concat (NULL, prefix, name,
7519                                                      physname, cu);
7520
7521               fputs_unfiltered (prefixed_name, buf);
7522               xfree (prefixed_name);
7523             }
7524           else
7525             fputs_unfiltered (name, buf);
7526
7527           /* Template parameters may be specified in the DIE's DW_AT_name, or
7528              as children with DW_TAG_template_type_param or
7529              DW_TAG_value_type_param.  If the latter, add them to the name
7530              here.  If the name already has template parameters, then
7531              skip this step; some versions of GCC emit both, and
7532              it is more efficient to use the pre-computed name.
7533
7534              Something to keep in mind about this process: it is very
7535              unlikely, or in some cases downright impossible, to produce
7536              something that will match the mangled name of a function.
7537              If the definition of the function has the same debug info,
7538              we should be able to match up with it anyway.  But fallbacks
7539              using the minimal symbol, for instance to find a method
7540              implemented in a stripped copy of libstdc++, will not work.
7541              If we do not have debug info for the definition, we will have to
7542              match them up some other way.
7543
7544              When we do name matching there is a related problem with function
7545              templates; two instantiated function templates are allowed to
7546              differ only by their return types, which we do not add here.  */
7547
7548           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7549             {
7550               struct attribute *attr;
7551               struct die_info *child;
7552               int first = 1;
7553
7554               die->building_fullname = 1;
7555
7556               for (child = die->child; child != NULL; child = child->sibling)
7557                 {
7558                   struct type *type;
7559                   LONGEST value;
7560                   gdb_byte *bytes;
7561                   struct dwarf2_locexpr_baton *baton;
7562                   struct value *v;
7563
7564                   if (child->tag != DW_TAG_template_type_param
7565                       && child->tag != DW_TAG_template_value_param)
7566                     continue;
7567
7568                   if (first)
7569                     {
7570                       fputs_unfiltered ("<", buf);
7571                       first = 0;
7572                     }
7573                   else
7574                     fputs_unfiltered (", ", buf);
7575
7576                   attr = dwarf2_attr (child, DW_AT_type, cu);
7577                   if (attr == NULL)
7578                     {
7579                       complaint (&symfile_complaints,
7580                                  _("template parameter missing DW_AT_type"));
7581                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7582                       continue;
7583                     }
7584                   type = die_type (child, cu);
7585
7586                   if (child->tag == DW_TAG_template_type_param)
7587                     {
7588                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7589                       continue;
7590                     }
7591
7592                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7593                   if (attr == NULL)
7594                     {
7595                       complaint (&symfile_complaints,
7596                                  _("template parameter missing "
7597                                    "DW_AT_const_value"));
7598                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7599                       continue;
7600                     }
7601
7602                   dwarf2_const_value_attr (attr, type, name,
7603                                            &cu->comp_unit_obstack, cu,
7604                                            &value, &bytes, &baton);
7605
7606                   if (TYPE_NOSIGN (type))
7607                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7608                        changed, this can use value_print instead.  */
7609                     c_printchar (value, type, buf);
7610                   else
7611                     {
7612                       struct value_print_options opts;
7613
7614                       if (baton != NULL)
7615                         v = dwarf2_evaluate_loc_desc (type, NULL,
7616                                                       baton->data,
7617                                                       baton->size,
7618                                                       baton->per_cu);
7619                       else if (bytes != NULL)
7620                         {
7621                           v = allocate_value (type);
7622                           memcpy (value_contents_writeable (v), bytes,
7623                                   TYPE_LENGTH (type));
7624                         }
7625                       else
7626                         v = value_from_longest (type, value);
7627
7628                       /* Specify decimal so that we do not depend on
7629                          the radix.  */
7630                       get_formatted_print_options (&opts, 'd');
7631                       opts.raw = 1;
7632                       value_print (v, buf, &opts);
7633                       release_value (v);
7634                       value_free (v);
7635                     }
7636                 }
7637
7638               die->building_fullname = 0;
7639
7640               if (!first)
7641                 {
7642                   /* Close the argument list, with a space if necessary
7643                      (nested templates).  */
7644                   char last_char = '\0';
7645                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7646                   if (last_char == '>')
7647                     fputs_unfiltered (" >", buf);
7648                   else
7649                     fputs_unfiltered (">", buf);
7650                 }
7651             }
7652
7653           /* For Java and C++ methods, append formal parameter type
7654              information, if PHYSNAME.  */
7655
7656           if (physname && die->tag == DW_TAG_subprogram
7657               && (cu->language == language_cplus
7658                   || cu->language == language_java))
7659             {
7660               struct type *type = read_type_die (die, cu);
7661
7662               c_type_print_args (type, buf, 1, cu->language,
7663                                  &type_print_raw_options);
7664
7665               if (cu->language == language_java)
7666                 {
7667                   /* For java, we must append the return type to method
7668                      names.  */
7669                   if (die->tag == DW_TAG_subprogram)
7670                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7671                                      0, 0, &type_print_raw_options);
7672                 }
7673               else if (cu->language == language_cplus)
7674                 {
7675                   /* Assume that an artificial first parameter is
7676                      "this", but do not crash if it is not.  RealView
7677                      marks unnamed (and thus unused) parameters as
7678                      artificial; there is no way to differentiate
7679                      the two cases.  */
7680                   if (TYPE_NFIELDS (type) > 0
7681                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7682                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7683                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7684                                                                         0))))
7685                     fputs_unfiltered (" const", buf);
7686                 }
7687             }
7688
7689           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7690                                        &length);
7691           ui_file_delete (buf);
7692
7693           if (cu->language == language_cplus)
7694             {
7695               const char *cname
7696                 = dwarf2_canonicalize_name (name, cu,
7697                                             &objfile->objfile_obstack);
7698
7699               if (cname != NULL)
7700                 name = cname;
7701             }
7702         }
7703     }
7704
7705   return name;
7706 }
7707
7708 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7709    If scope qualifiers are appropriate they will be added.  The result
7710    will be allocated on the objfile_obstack, or NULL if the DIE does
7711    not have a name.  NAME may either be from a previous call to
7712    dwarf2_name or NULL.
7713
7714    The output string will be canonicalized (if C++/Java).  */
7715
7716 static const char *
7717 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7718 {
7719   return dwarf2_compute_name (name, die, cu, 0);
7720 }
7721
7722 /* Construct a physname for the given DIE in CU.  NAME may either be
7723    from a previous call to dwarf2_name or NULL.  The result will be
7724    allocated on the objfile_objstack or NULL if the DIE does not have a
7725    name.
7726
7727    The output string will be canonicalized (if C++/Java).  */
7728
7729 static const char *
7730 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7731 {
7732   struct objfile *objfile = cu->objfile;
7733   struct attribute *attr;
7734   const char *retval, *mangled = NULL, *canon = NULL;
7735   struct cleanup *back_to;
7736   int need_copy = 1;
7737
7738   /* In this case dwarf2_compute_name is just a shortcut not building anything
7739      on its own.  */
7740   if (!die_needs_namespace (die, cu))
7741     return dwarf2_compute_name (name, die, cu, 1);
7742
7743   back_to = make_cleanup (null_cleanup, NULL);
7744
7745   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7746   if (!attr)
7747     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7748
7749   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7750      has computed.  */
7751   if (attr && DW_STRING (attr))
7752     {
7753       char *demangled;
7754
7755       mangled = DW_STRING (attr);
7756
7757       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7758          type.  It is easier for GDB users to search for such functions as
7759          `name(params)' than `long name(params)'.  In such case the minimal
7760          symbol names do not match the full symbol names but for template
7761          functions there is never a need to look up their definition from their
7762          declaration so the only disadvantage remains the minimal symbol
7763          variant `long name(params)' does not have the proper inferior type.
7764          */
7765
7766       if (cu->language == language_go)
7767         {
7768           /* This is a lie, but we already lie to the caller new_symbol_full.
7769              new_symbol_full assumes we return the mangled name.
7770              This just undoes that lie until things are cleaned up.  */
7771           demangled = NULL;
7772         }
7773       else
7774         {
7775           demangled = cplus_demangle (mangled,
7776                                       (DMGL_PARAMS | DMGL_ANSI
7777                                        | (cu->language == language_java
7778                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7779                                           : DMGL_RET_DROP)));
7780         }
7781       if (demangled)
7782         {
7783           make_cleanup (xfree, demangled);
7784           canon = demangled;
7785         }
7786       else
7787         {
7788           canon = mangled;
7789           need_copy = 0;
7790         }
7791     }
7792
7793   if (canon == NULL || check_physname)
7794     {
7795       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7796
7797       if (canon != NULL && strcmp (physname, canon) != 0)
7798         {
7799           /* It may not mean a bug in GDB.  The compiler could also
7800              compute DW_AT_linkage_name incorrectly.  But in such case
7801              GDB would need to be bug-to-bug compatible.  */
7802
7803           complaint (&symfile_complaints,
7804                      _("Computed physname <%s> does not match demangled <%s> "
7805                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7806                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7807
7808           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7809              is available here - over computed PHYSNAME.  It is safer
7810              against both buggy GDB and buggy compilers.  */
7811
7812           retval = canon;
7813         }
7814       else
7815         {
7816           retval = physname;
7817           need_copy = 0;
7818         }
7819     }
7820   else
7821     retval = canon;
7822
7823   if (need_copy)
7824     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7825
7826   do_cleanups (back_to);
7827   return retval;
7828 }
7829
7830 /* Read the import statement specified by the given die and record it.  */
7831
7832 static void
7833 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7834 {
7835   struct objfile *objfile = cu->objfile;
7836   struct attribute *import_attr;
7837   struct die_info *imported_die, *child_die;
7838   struct dwarf2_cu *imported_cu;
7839   const char *imported_name;
7840   const char *imported_name_prefix;
7841   const char *canonical_name;
7842   const char *import_alias;
7843   const char *imported_declaration = NULL;
7844   const char *import_prefix;
7845   VEC (const_char_ptr) *excludes = NULL;
7846   struct cleanup *cleanups;
7847
7848   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7849   if (import_attr == NULL)
7850     {
7851       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7852                  dwarf_tag_name (die->tag));
7853       return;
7854     }
7855
7856   imported_cu = cu;
7857   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7858   imported_name = dwarf2_name (imported_die, imported_cu);
7859   if (imported_name == NULL)
7860     {
7861       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7862
7863         The import in the following code:
7864         namespace A
7865           {
7866             typedef int B;
7867           }
7868
7869         int main ()
7870           {
7871             using A::B;
7872             B b;
7873             return b;
7874           }
7875
7876         ...
7877          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7878             <52>   DW_AT_decl_file   : 1
7879             <53>   DW_AT_decl_line   : 6
7880             <54>   DW_AT_import      : <0x75>
7881          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7882             <59>   DW_AT_name        : B
7883             <5b>   DW_AT_decl_file   : 1
7884             <5c>   DW_AT_decl_line   : 2
7885             <5d>   DW_AT_type        : <0x6e>
7886         ...
7887          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7888             <76>   DW_AT_byte_size   : 4
7889             <77>   DW_AT_encoding    : 5        (signed)
7890
7891         imports the wrong die ( 0x75 instead of 0x58 ).
7892         This case will be ignored until the gcc bug is fixed.  */
7893       return;
7894     }
7895
7896   /* Figure out the local name after import.  */
7897   import_alias = dwarf2_name (die, cu);
7898
7899   /* Figure out where the statement is being imported to.  */
7900   import_prefix = determine_prefix (die, cu);
7901
7902   /* Figure out what the scope of the imported die is and prepend it
7903      to the name of the imported die.  */
7904   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7905
7906   if (imported_die->tag != DW_TAG_namespace
7907       && imported_die->tag != DW_TAG_module)
7908     {
7909       imported_declaration = imported_name;
7910       canonical_name = imported_name_prefix;
7911     }
7912   else if (strlen (imported_name_prefix) > 0)
7913     canonical_name = obconcat (&objfile->objfile_obstack,
7914                                imported_name_prefix, "::", imported_name,
7915                                (char *) NULL);
7916   else
7917     canonical_name = imported_name;
7918
7919   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7920
7921   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7922     for (child_die = die->child; child_die && child_die->tag;
7923          child_die = sibling_die (child_die))
7924       {
7925         /* DWARF-4: A Fortran use statement with a “rename list” may be
7926            represented by an imported module entry with an import attribute
7927            referring to the module and owned entries corresponding to those
7928            entities that are renamed as part of being imported.  */
7929
7930         if (child_die->tag != DW_TAG_imported_declaration)
7931           {
7932             complaint (&symfile_complaints,
7933                        _("child DW_TAG_imported_declaration expected "
7934                          "- DIE at 0x%x [in module %s]"),
7935                        child_die->offset.sect_off, objfile->name);
7936             continue;
7937           }
7938
7939         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7940         if (import_attr == NULL)
7941           {
7942             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7943                        dwarf_tag_name (child_die->tag));
7944             continue;
7945           }
7946
7947         imported_cu = cu;
7948         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7949                                               &imported_cu);
7950         imported_name = dwarf2_name (imported_die, imported_cu);
7951         if (imported_name == NULL)
7952           {
7953             complaint (&symfile_complaints,
7954                        _("child DW_TAG_imported_declaration has unknown "
7955                          "imported name - DIE at 0x%x [in module %s]"),
7956                        child_die->offset.sect_off, objfile->name);
7957             continue;
7958           }
7959
7960         VEC_safe_push (const_char_ptr, excludes, imported_name);
7961
7962         process_die (child_die, cu);
7963       }
7964
7965   cp_add_using_directive (import_prefix,
7966                           canonical_name,
7967                           import_alias,
7968                           imported_declaration,
7969                           excludes,
7970                           0,
7971                           &objfile->objfile_obstack);
7972
7973   do_cleanups (cleanups);
7974 }
7975
7976 /* Cleanup function for handle_DW_AT_stmt_list.  */
7977
7978 static void
7979 free_cu_line_header (void *arg)
7980 {
7981   struct dwarf2_cu *cu = arg;
7982
7983   free_line_header (cu->line_header);
7984   cu->line_header = NULL;
7985 }
7986
7987 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
7988    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
7989    this, it was first present in GCC release 4.3.0.  */
7990
7991 static int
7992 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
7993 {
7994   if (!cu->checked_producer)
7995     check_producer (cu);
7996
7997   return cu->producer_is_gcc_lt_4_3;
7998 }
7999
8000 static void
8001 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8002                          const char **name, const char **comp_dir)
8003 {
8004   struct attribute *attr;
8005
8006   *name = NULL;
8007   *comp_dir = NULL;
8008
8009   /* Find the filename.  Do not use dwarf2_name here, since the filename
8010      is not a source language identifier.  */
8011   attr = dwarf2_attr (die, DW_AT_name, cu);
8012   if (attr)
8013     {
8014       *name = DW_STRING (attr);
8015     }
8016
8017   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8018   if (attr)
8019     *comp_dir = DW_STRING (attr);
8020   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8021            && IS_ABSOLUTE_PATH (*name))
8022     {
8023       char *d = ldirname (*name);
8024
8025       *comp_dir = d;
8026       if (d != NULL)
8027         make_cleanup (xfree, d);
8028     }
8029   if (*comp_dir != NULL)
8030     {
8031       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8032          directory, get rid of it.  */
8033       char *cp = strchr (*comp_dir, ':');
8034
8035       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8036         *comp_dir = cp + 1;
8037     }
8038
8039   if (*name == NULL)
8040     *name = "<unknown>";
8041 }
8042
8043 /* Handle DW_AT_stmt_list for a compilation unit.
8044    DIE is the DW_TAG_compile_unit die for CU.
8045    COMP_DIR is the compilation directory.
8046    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8047
8048 static void
8049 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8050                         const char *comp_dir)
8051 {
8052   struct attribute *attr;
8053
8054   gdb_assert (! cu->per_cu->is_debug_types);
8055
8056   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8057   if (attr)
8058     {
8059       unsigned int line_offset = DW_UNSND (attr);
8060       struct line_header *line_header
8061         = dwarf_decode_line_header (line_offset, cu);
8062
8063       if (line_header)
8064         {
8065           cu->line_header = line_header;
8066           make_cleanup (free_cu_line_header, cu);
8067           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8068         }
8069     }
8070 }
8071
8072 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8073
8074 static void
8075 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8076 {
8077   struct objfile *objfile = dwarf2_per_objfile->objfile;
8078   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8079   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8080   CORE_ADDR highpc = ((CORE_ADDR) 0);
8081   struct attribute *attr;
8082   const char *name = NULL;
8083   const char *comp_dir = NULL;
8084   struct die_info *child_die;
8085   bfd *abfd = objfile->obfd;
8086   CORE_ADDR baseaddr;
8087
8088   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8089
8090   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8091
8092   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8093      from finish_block.  */
8094   if (lowpc == ((CORE_ADDR) -1))
8095     lowpc = highpc;
8096   lowpc += baseaddr;
8097   highpc += baseaddr;
8098
8099   find_file_and_directory (die, cu, &name, &comp_dir);
8100
8101   prepare_one_comp_unit (cu, die, cu->language);
8102
8103   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8104      standardised yet.  As a workaround for the language detection we fall
8105      back to the DW_AT_producer string.  */
8106   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8107     cu->language = language_opencl;
8108
8109   /* Similar hack for Go.  */
8110   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8111     set_cu_language (DW_LANG_Go, cu);
8112
8113   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8114
8115   /* Decode line number information if present.  We do this before
8116      processing child DIEs, so that the line header table is available
8117      for DW_AT_decl_file.  */
8118   handle_DW_AT_stmt_list (die, cu, comp_dir);
8119
8120   /* Process all dies in compilation unit.  */
8121   if (die->child != NULL)
8122     {
8123       child_die = die->child;
8124       while (child_die && child_die->tag)
8125         {
8126           process_die (child_die, cu);
8127           child_die = sibling_die (child_die);
8128         }
8129     }
8130
8131   /* Decode macro information, if present.  Dwarf 2 macro information
8132      refers to information in the line number info statement program
8133      header, so we can only read it if we've read the header
8134      successfully.  */
8135   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8136   if (attr && cu->line_header)
8137     {
8138       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8139         complaint (&symfile_complaints,
8140                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8141
8142       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8143     }
8144   else
8145     {
8146       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8147       if (attr && cu->line_header)
8148         {
8149           unsigned int macro_offset = DW_UNSND (attr);
8150
8151           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8152         }
8153     }
8154
8155   do_cleanups (back_to);
8156 }
8157
8158 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8159    Create the set of symtabs used by this TU, or if this TU is sharing
8160    symtabs with another TU and the symtabs have already been created
8161    then restore those symtabs in the line header.
8162    We don't need the pc/line-number mapping for type units.  */
8163
8164 static void
8165 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8166 {
8167   struct objfile *objfile = dwarf2_per_objfile->objfile;
8168   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8169   struct type_unit_group *tu_group;
8170   int first_time;
8171   struct line_header *lh;
8172   struct attribute *attr;
8173   unsigned int i, line_offset;
8174
8175   gdb_assert (per_cu->is_debug_types);
8176
8177   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8178
8179   /* If we're using .gdb_index (includes -readnow) then
8180      per_cu->s.type_unit_group may not have been set up yet.  */
8181   if (per_cu->type_unit_group == NULL)
8182     per_cu->type_unit_group = get_type_unit_group (cu, attr);
8183   tu_group = per_cu->type_unit_group;
8184
8185   /* If we've already processed this stmt_list there's no real need to
8186      do it again, we could fake it and just recreate the part we need
8187      (file name,index -> symtab mapping).  If data shows this optimization
8188      is useful we can do it then.  */
8189   first_time = tu_group->primary_symtab == NULL;
8190
8191   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8192      debug info.  */
8193   lh = NULL;
8194   if (attr != NULL)
8195     {
8196       line_offset = DW_UNSND (attr);
8197       lh = dwarf_decode_line_header (line_offset, cu);
8198     }
8199   if (lh == NULL)
8200     {
8201       if (first_time)
8202         dwarf2_start_symtab (cu, "", NULL, 0);
8203       else
8204         {
8205           gdb_assert (tu_group->symtabs == NULL);
8206           restart_symtab (0);
8207         }
8208       /* Note: The primary symtab will get allocated at the end.  */
8209       return;
8210     }
8211
8212   cu->line_header = lh;
8213   make_cleanup (free_cu_line_header, cu);
8214
8215   if (first_time)
8216     {
8217       dwarf2_start_symtab (cu, "", NULL, 0);
8218
8219       tu_group->num_symtabs = lh->num_file_names;
8220       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8221
8222       for (i = 0; i < lh->num_file_names; ++i)
8223         {
8224           char *dir = NULL;
8225           struct file_entry *fe = &lh->file_names[i];
8226
8227           if (fe->dir_index)
8228             dir = lh->include_dirs[fe->dir_index - 1];
8229           dwarf2_start_subfile (fe->name, dir, NULL);
8230
8231           /* Note: We don't have to watch for the main subfile here, type units
8232              don't have DW_AT_name.  */
8233
8234           if (current_subfile->symtab == NULL)
8235             {
8236               /* NOTE: start_subfile will recognize when it's been passed
8237                  a file it has already seen.  So we can't assume there's a
8238                  simple mapping from lh->file_names to subfiles,
8239                  lh->file_names may contain dups.  */
8240               current_subfile->symtab = allocate_symtab (current_subfile->name,
8241                                                          objfile);
8242             }
8243
8244           fe->symtab = current_subfile->symtab;
8245           tu_group->symtabs[i] = fe->symtab;
8246         }
8247     }
8248   else
8249     {
8250       restart_symtab (0);
8251
8252       for (i = 0; i < lh->num_file_names; ++i)
8253         {
8254           struct file_entry *fe = &lh->file_names[i];
8255
8256           fe->symtab = tu_group->symtabs[i];
8257         }
8258     }
8259
8260   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8261      so they don't have a "real" (so to speak) symtab anyway.
8262      There is later code that will assign the main symtab to all symbols
8263      that don't have one.  We need to handle the case of a symbol with a
8264      missing symtab (DW_AT_decl_file) anyway.  */
8265 }
8266
8267 /* Process DW_TAG_type_unit.
8268    For TUs we want to skip the first top level sibling if it's not the
8269    actual type being defined by this TU.  In this case the first top
8270    level sibling is there to provide context only.  */
8271
8272 static void
8273 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8274 {
8275   struct die_info *child_die;
8276
8277   prepare_one_comp_unit (cu, die, language_minimal);
8278
8279   /* Initialize (or reinitialize) the machinery for building symtabs.
8280      We do this before processing child DIEs, so that the line header table
8281      is available for DW_AT_decl_file.  */
8282   setup_type_unit_groups (die, cu);
8283
8284   if (die->child != NULL)
8285     {
8286       child_die = die->child;
8287       while (child_die && child_die->tag)
8288         {
8289           process_die (child_die, cu);
8290           child_die = sibling_die (child_die);
8291         }
8292     }
8293 }
8294 \f
8295 /* DWO/DWP files.
8296
8297    http://gcc.gnu.org/wiki/DebugFission
8298    http://gcc.gnu.org/wiki/DebugFissionDWP
8299
8300    To simplify handling of both DWO files ("object" files with the DWARF info)
8301    and DWP files (a file with the DWOs packaged up into one file), we treat
8302    DWP files as having a collection of virtual DWO files.  */
8303
8304 static hashval_t
8305 hash_dwo_file (const void *item)
8306 {
8307   const struct dwo_file *dwo_file = item;
8308
8309   return htab_hash_string (dwo_file->name);
8310 }
8311
8312 static int
8313 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8314 {
8315   const struct dwo_file *lhs = item_lhs;
8316   const struct dwo_file *rhs = item_rhs;
8317
8318   return strcmp (lhs->name, rhs->name) == 0;
8319 }
8320
8321 /* Allocate a hash table for DWO files.  */
8322
8323 static htab_t
8324 allocate_dwo_file_hash_table (void)
8325 {
8326   struct objfile *objfile = dwarf2_per_objfile->objfile;
8327
8328   return htab_create_alloc_ex (41,
8329                                hash_dwo_file,
8330                                eq_dwo_file,
8331                                NULL,
8332                                &objfile->objfile_obstack,
8333                                hashtab_obstack_allocate,
8334                                dummy_obstack_deallocate);
8335 }
8336
8337 /* Lookup DWO file DWO_NAME.  */
8338
8339 static void **
8340 lookup_dwo_file_slot (const char *dwo_name)
8341 {
8342   struct dwo_file find_entry;
8343   void **slot;
8344
8345   if (dwarf2_per_objfile->dwo_files == NULL)
8346     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8347
8348   memset (&find_entry, 0, sizeof (find_entry));
8349   find_entry.name = dwo_name;
8350   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8351
8352   return slot;
8353 }
8354
8355 static hashval_t
8356 hash_dwo_unit (const void *item)
8357 {
8358   const struct dwo_unit *dwo_unit = item;
8359
8360   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8361   return dwo_unit->signature;
8362 }
8363
8364 static int
8365 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8366 {
8367   const struct dwo_unit *lhs = item_lhs;
8368   const struct dwo_unit *rhs = item_rhs;
8369
8370   /* The signature is assumed to be unique within the DWO file.
8371      So while object file CU dwo_id's always have the value zero,
8372      that's OK, assuming each object file DWO file has only one CU,
8373      and that's the rule for now.  */
8374   return lhs->signature == rhs->signature;
8375 }
8376
8377 /* Allocate a hash table for DWO CUs,TUs.
8378    There is one of these tables for each of CUs,TUs for each DWO file.  */
8379
8380 static htab_t
8381 allocate_dwo_unit_table (struct objfile *objfile)
8382 {
8383   /* Start out with a pretty small number.
8384      Generally DWO files contain only one CU and maybe some TUs.  */
8385   return htab_create_alloc_ex (3,
8386                                hash_dwo_unit,
8387                                eq_dwo_unit,
8388                                NULL,
8389                                &objfile->objfile_obstack,
8390                                hashtab_obstack_allocate,
8391                                dummy_obstack_deallocate);
8392 }
8393
8394 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8395
8396 struct create_dwo_info_table_data
8397 {
8398   struct dwo_file *dwo_file;
8399   htab_t cu_htab;
8400 };
8401
8402 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8403
8404 static void
8405 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8406                                          gdb_byte *info_ptr,
8407                                          struct die_info *comp_unit_die,
8408                                          int has_children,
8409                                          void *datap)
8410 {
8411   struct dwarf2_cu *cu = reader->cu;
8412   struct objfile *objfile = dwarf2_per_objfile->objfile;
8413   sect_offset offset = cu->per_cu->offset;
8414   struct dwarf2_section_info *section = cu->per_cu->section;
8415   struct create_dwo_info_table_data *data = datap;
8416   struct dwo_file *dwo_file = data->dwo_file;
8417   htab_t cu_htab = data->cu_htab;
8418   void **slot;
8419   struct attribute *attr;
8420   struct dwo_unit *dwo_unit;
8421
8422   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8423   if (attr == NULL)
8424     {
8425       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8426                " its dwo_id [in module %s]"),
8427              offset.sect_off, dwo_file->name);
8428       return;
8429     }
8430
8431   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8432   dwo_unit->dwo_file = dwo_file;
8433   dwo_unit->signature = DW_UNSND (attr);
8434   dwo_unit->section = section;
8435   dwo_unit->offset = offset;
8436   dwo_unit->length = cu->per_cu->length;
8437
8438   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8439   gdb_assert (slot != NULL);
8440   if (*slot != NULL)
8441     {
8442       const struct dwo_unit *dup_dwo_unit = *slot;
8443
8444       complaint (&symfile_complaints,
8445                  _("debug entry at offset 0x%x is duplicate to the entry at"
8446                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8447                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8448                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8449                  dwo_file->name);
8450     }
8451   else
8452     *slot = dwo_unit;
8453
8454   if (dwarf2_read_debug)
8455     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8456                         offset.sect_off,
8457                         phex (dwo_unit->signature,
8458                               sizeof (dwo_unit->signature)));
8459 }
8460
8461 /* Create a hash table to map DWO IDs to their CU entry in
8462    .debug_info.dwo in DWO_FILE.
8463    Note: This function processes DWO files only, not DWP files.
8464    Note: A DWO file generally contains one CU, but we don't assume this.  */
8465
8466 static htab_t
8467 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8468 {
8469   struct objfile *objfile = dwarf2_per_objfile->objfile;
8470   struct dwarf2_section_info *section = &dwo_file->sections.info;
8471   bfd *abfd;
8472   htab_t cu_htab;
8473   gdb_byte *info_ptr, *end_ptr;
8474   struct create_dwo_info_table_data create_dwo_info_table_data;
8475
8476   dwarf2_read_section (objfile, section);
8477   info_ptr = section->buffer;
8478
8479   if (info_ptr == NULL)
8480     return NULL;
8481
8482   /* We can't set abfd until now because the section may be empty or
8483      not present, in which case section->asection will be NULL.  */
8484   abfd = section->asection->owner;
8485
8486   if (dwarf2_read_debug)
8487     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8488                         bfd_get_filename (abfd));
8489
8490   cu_htab = allocate_dwo_unit_table (objfile);
8491
8492   create_dwo_info_table_data.dwo_file = dwo_file;
8493   create_dwo_info_table_data.cu_htab = cu_htab;
8494
8495   end_ptr = info_ptr + section->size;
8496   while (info_ptr < end_ptr)
8497     {
8498       struct dwarf2_per_cu_data per_cu;
8499
8500       memset (&per_cu, 0, sizeof (per_cu));
8501       per_cu.objfile = objfile;
8502       per_cu.is_debug_types = 0;
8503       per_cu.offset.sect_off = info_ptr - section->buffer;
8504       per_cu.section = section;
8505
8506       init_cutu_and_read_dies_no_follow (&per_cu,
8507                                          &dwo_file->sections.abbrev,
8508                                          dwo_file,
8509                                          create_dwo_debug_info_hash_table_reader,
8510                                          &create_dwo_info_table_data);
8511
8512       info_ptr += per_cu.length;
8513     }
8514
8515   return cu_htab;
8516 }
8517
8518 /* DWP file .debug_{cu,tu}_index section format:
8519    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8520
8521    Both index sections have the same format, and serve to map a 64-bit
8522    signature to a set of section numbers.  Each section begins with a header,
8523    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8524    indexes, and a pool of 32-bit section numbers.  The index sections will be
8525    aligned at 8-byte boundaries in the file.
8526
8527    The index section header contains two unsigned 32-bit values (using the
8528    byte order of the application binary):
8529
8530     N, the number of compilation units or type units in the index
8531     M, the number of slots in the hash table
8532
8533   (We assume that N and M will not exceed 2^32 - 1.)
8534
8535   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8536
8537   The hash table begins at offset 8 in the section, and consists of an array
8538   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8539   order of the application binary).  Unused slots in the hash table are 0.
8540   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8541
8542   The parallel table begins immediately after the hash table
8543   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8544   array of 32-bit indexes (using the byte order of the application binary),
8545   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8546   table contains a 32-bit index into the pool of section numbers.  For unused
8547   hash table slots, the corresponding entry in the parallel table will be 0.
8548
8549   Given a 64-bit compilation unit signature or a type signature S, an entry
8550   in the hash table is located as follows:
8551
8552   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8553      the low-order k bits all set to 1.
8554
8555   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8556
8557   3) If the hash table entry at index H matches the signature, use that
8558      entry.  If the hash table entry at index H is unused (all zeroes),
8559      terminate the search: the signature is not present in the table.
8560
8561   4) Let H = (H + H') modulo M. Repeat at Step 3.
8562
8563   Because M > N and H' and M are relatively prime, the search is guaranteed
8564   to stop at an unused slot or find the match.
8565
8566   The pool of section numbers begins immediately following the hash table
8567   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8568   section numbers consists of an array of 32-bit words (using the byte order
8569   of the application binary).  Each item in the array is indexed starting
8570   from 0.  The hash table entry provides the index of the first section
8571   number in the set.  Additional section numbers in the set follow, and the
8572   set is terminated by a 0 entry (section number 0 is not used in ELF).
8573
8574   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8575   section must be the first entry in the set, and the .debug_abbrev.dwo must
8576   be the second entry. Other members of the set may follow in any order.  */
8577
8578 /* Create a hash table to map DWO IDs to their CU/TU entry in
8579    .debug_{info,types}.dwo in DWP_FILE.
8580    Returns NULL if there isn't one.
8581    Note: This function processes DWP files only, not DWO files.  */
8582
8583 static struct dwp_hash_table *
8584 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8585 {
8586   struct objfile *objfile = dwarf2_per_objfile->objfile;
8587   bfd *dbfd = dwp_file->dbfd;
8588   char *index_ptr, *index_end;
8589   struct dwarf2_section_info *index;
8590   uint32_t version, nr_units, nr_slots;
8591   struct dwp_hash_table *htab;
8592
8593   if (is_debug_types)
8594     index = &dwp_file->sections.tu_index;
8595   else
8596     index = &dwp_file->sections.cu_index;
8597
8598   if (dwarf2_section_empty_p (index))
8599     return NULL;
8600   dwarf2_read_section (objfile, index);
8601
8602   index_ptr = index->buffer;
8603   index_end = index_ptr + index->size;
8604
8605   version = read_4_bytes (dbfd, index_ptr);
8606   index_ptr += 8; /* Skip the unused word.  */
8607   nr_units = read_4_bytes (dbfd, index_ptr);
8608   index_ptr += 4;
8609   nr_slots = read_4_bytes (dbfd, index_ptr);
8610   index_ptr += 4;
8611
8612   if (version != 1)
8613     {
8614       error (_("Dwarf Error: unsupported DWP file version (%u)"
8615                " [in module %s]"),
8616              version, dwp_file->name);
8617     }
8618   if (nr_slots != (nr_slots & -nr_slots))
8619     {
8620       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8621                " is not power of 2 [in module %s]"),
8622              nr_slots, dwp_file->name);
8623     }
8624
8625   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8626   htab->nr_units = nr_units;
8627   htab->nr_slots = nr_slots;
8628   htab->hash_table = index_ptr;
8629   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8630   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8631
8632   return htab;
8633 }
8634
8635 /* Update SECTIONS with the data from SECTP.
8636
8637    This function is like the other "locate" section routines that are
8638    passed to bfd_map_over_sections, but in this context the sections to
8639    read comes from the DWP hash table, not the full ELF section table.
8640
8641    The result is non-zero for success, or zero if an error was found.  */
8642
8643 static int
8644 locate_virtual_dwo_sections (asection *sectp,
8645                              struct virtual_dwo_sections *sections)
8646 {
8647   const struct dwop_section_names *names = &dwop_section_names;
8648
8649   if (section_is_p (sectp->name, &names->abbrev_dwo))
8650     {
8651       /* There can be only one.  */
8652       if (sections->abbrev.asection != NULL)
8653         return 0;
8654       sections->abbrev.asection = sectp;
8655       sections->abbrev.size = bfd_get_section_size (sectp);
8656     }
8657   else if (section_is_p (sectp->name, &names->info_dwo)
8658            || section_is_p (sectp->name, &names->types_dwo))
8659     {
8660       /* There can be only one.  */
8661       if (sections->info_or_types.asection != NULL)
8662         return 0;
8663       sections->info_or_types.asection = sectp;
8664       sections->info_or_types.size = bfd_get_section_size (sectp);
8665     }
8666   else if (section_is_p (sectp->name, &names->line_dwo))
8667     {
8668       /* There can be only one.  */
8669       if (sections->line.asection != NULL)
8670         return 0;
8671       sections->line.asection = sectp;
8672       sections->line.size = bfd_get_section_size (sectp);
8673     }
8674   else if (section_is_p (sectp->name, &names->loc_dwo))
8675     {
8676       /* There can be only one.  */
8677       if (sections->loc.asection != NULL)
8678         return 0;
8679       sections->loc.asection = sectp;
8680       sections->loc.size = bfd_get_section_size (sectp);
8681     }
8682   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8683     {
8684       /* There can be only one.  */
8685       if (sections->macinfo.asection != NULL)
8686         return 0;
8687       sections->macinfo.asection = sectp;
8688       sections->macinfo.size = bfd_get_section_size (sectp);
8689     }
8690   else if (section_is_p (sectp->name, &names->macro_dwo))
8691     {
8692       /* There can be only one.  */
8693       if (sections->macro.asection != NULL)
8694         return 0;
8695       sections->macro.asection = sectp;
8696       sections->macro.size = bfd_get_section_size (sectp);
8697     }
8698   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8699     {
8700       /* There can be only one.  */
8701       if (sections->str_offsets.asection != NULL)
8702         return 0;
8703       sections->str_offsets.asection = sectp;
8704       sections->str_offsets.size = bfd_get_section_size (sectp);
8705     }
8706   else
8707     {
8708       /* No other kind of section is valid.  */
8709       return 0;
8710     }
8711
8712   return 1;
8713 }
8714
8715 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8716    HTAB is the hash table from the DWP file.
8717    SECTION_INDEX is the index of the DWO in HTAB.  */
8718
8719 static struct dwo_unit *
8720 create_dwo_in_dwp (struct dwp_file *dwp_file,
8721                    const struct dwp_hash_table *htab,
8722                    uint32_t section_index,
8723                    ULONGEST signature, int is_debug_types)
8724 {
8725   struct objfile *objfile = dwarf2_per_objfile->objfile;
8726   bfd *dbfd = dwp_file->dbfd;
8727   const char *kind = is_debug_types ? "TU" : "CU";
8728   struct dwo_file *dwo_file;
8729   struct dwo_unit *dwo_unit;
8730   struct virtual_dwo_sections sections;
8731   void **dwo_file_slot;
8732   char *virtual_dwo_name;
8733   struct dwarf2_section_info *cutu;
8734   struct cleanup *cleanups;
8735   int i;
8736
8737   if (dwarf2_read_debug)
8738     {
8739       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/0x%s in DWP file: %s\n",
8740                           kind,
8741                           section_index, phex (signature, sizeof (signature)),
8742                           dwp_file->name);
8743     }
8744
8745   /* Fetch the sections of this DWO.
8746      Put a limit on the number of sections we look for so that bad data
8747      doesn't cause us to loop forever.  */
8748
8749 #define MAX_NR_DWO_SECTIONS \
8750   (1 /* .debug_info or .debug_types */ \
8751    + 1 /* .debug_abbrev */ \
8752    + 1 /* .debug_line */ \
8753    + 1 /* .debug_loc */ \
8754    + 1 /* .debug_str_offsets */ \
8755    + 1 /* .debug_macro */ \
8756    + 1 /* .debug_macinfo */ \
8757    + 1 /* trailing zero */)
8758
8759   memset (&sections, 0, sizeof (sections));
8760   cleanups = make_cleanup (null_cleanup, 0);
8761
8762   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8763     {
8764       asection *sectp;
8765       uint32_t section_nr =
8766         read_4_bytes (dbfd,
8767                       htab->section_pool
8768                       + (section_index + i) * sizeof (uint32_t));
8769
8770       if (section_nr == 0)
8771         break;
8772       if (section_nr >= dwp_file->num_sections)
8773         {
8774           error (_("Dwarf Error: bad DWP hash table, section number too large"
8775                    " [in module %s]"),
8776                  dwp_file->name);
8777         }
8778
8779       sectp = dwp_file->elf_sections[section_nr];
8780       if (! locate_virtual_dwo_sections (sectp, &sections))
8781         {
8782           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8783                    " [in module %s]"),
8784                  dwp_file->name);
8785         }
8786     }
8787
8788   if (i < 2
8789       || sections.info_or_types.asection == NULL
8790       || sections.abbrev.asection == NULL)
8791     {
8792       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8793                " [in module %s]"),
8794              dwp_file->name);
8795     }
8796   if (i == MAX_NR_DWO_SECTIONS)
8797     {
8798       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8799                " [in module %s]"),
8800              dwp_file->name);
8801     }
8802
8803   /* It's easier for the rest of the code if we fake a struct dwo_file and
8804      have dwo_unit "live" in that.  At least for now.
8805
8806      The DWP file can be made up of a random collection of CUs and TUs.
8807      However, for each CU + set of TUs that came from the same original DWO
8808      file, we want to combine them back into a virtual DWO file to save space
8809      (fewer struct dwo_file objects to allocated).  Remember that for really
8810      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8811
8812   virtual_dwo_name =
8813     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8814                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8815                 sections.line.asection ? sections.line.asection->id : 0,
8816                 sections.loc.asection ? sections.loc.asection->id : 0,
8817                 (sections.str_offsets.asection
8818                 ? sections.str_offsets.asection->id
8819                 : 0));
8820   make_cleanup (xfree, virtual_dwo_name);
8821   /* Can we use an existing virtual DWO file?  */
8822   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name);
8823   /* Create one if necessary.  */
8824   if (*dwo_file_slot == NULL)
8825     {
8826       if (dwarf2_read_debug)
8827         {
8828           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8829                               virtual_dwo_name);
8830         }
8831       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8832       dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8833                                       virtual_dwo_name,
8834                                       strlen (virtual_dwo_name));
8835       dwo_file->sections.abbrev = sections.abbrev;
8836       dwo_file->sections.line = sections.line;
8837       dwo_file->sections.loc = sections.loc;
8838       dwo_file->sections.macinfo = sections.macinfo;
8839       dwo_file->sections.macro = sections.macro;
8840       dwo_file->sections.str_offsets = sections.str_offsets;
8841       /* The "str" section is global to the entire DWP file.  */
8842       dwo_file->sections.str = dwp_file->sections.str;
8843       /* The info or types section is assigned later to dwo_unit,
8844          there's no need to record it in dwo_file.
8845          Also, we can't simply record type sections in dwo_file because
8846          we record a pointer into the vector in dwo_unit.  As we collect more
8847          types we'll grow the vector and eventually have to reallocate space
8848          for it, invalidating all the pointers into the current copy.  */
8849       *dwo_file_slot = dwo_file;
8850     }
8851   else
8852     {
8853       if (dwarf2_read_debug)
8854         {
8855           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8856                               virtual_dwo_name);
8857         }
8858       dwo_file = *dwo_file_slot;
8859     }
8860   do_cleanups (cleanups);
8861
8862   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8863   dwo_unit->dwo_file = dwo_file;
8864   dwo_unit->signature = signature;
8865   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
8866                                      sizeof (struct dwarf2_section_info));
8867   *dwo_unit->section = sections.info_or_types;
8868   /* offset, length, type_offset_in_tu are set later.  */
8869
8870   return dwo_unit;
8871 }
8872
8873 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8874
8875 static struct dwo_unit *
8876 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8877                    const struct dwp_hash_table *htab,
8878                    ULONGEST signature, int is_debug_types)
8879 {
8880   bfd *dbfd = dwp_file->dbfd;
8881   uint32_t mask = htab->nr_slots - 1;
8882   uint32_t hash = signature & mask;
8883   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8884   unsigned int i;
8885   void **slot;
8886   struct dwo_unit find_dwo_cu, *dwo_cu;
8887
8888   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8889   find_dwo_cu.signature = signature;
8890   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8891
8892   if (*slot != NULL)
8893     return *slot;
8894
8895   /* Use a for loop so that we don't loop forever on bad debug info.  */
8896   for (i = 0; i < htab->nr_slots; ++i)
8897     {
8898       ULONGEST signature_in_table;
8899
8900       signature_in_table =
8901         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8902       if (signature_in_table == signature)
8903         {
8904           uint32_t section_index =
8905             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8906
8907           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8908                                      signature, is_debug_types);
8909           return *slot;
8910         }
8911       if (signature_in_table == 0)
8912         return NULL;
8913       hash = (hash + hash2) & mask;
8914     }
8915
8916   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8917            " [in module %s]"),
8918          dwp_file->name);
8919 }
8920
8921 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
8922    Open the file specified by FILE_NAME and hand it off to BFD for
8923    preliminary analysis.  Return a newly initialized bfd *, which
8924    includes a canonicalized copy of FILE_NAME.
8925    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8926    In case of trouble, return NULL.
8927    NOTE: This function is derived from symfile_bfd_open.  */
8928
8929 static bfd *
8930 try_open_dwop_file (const char *file_name, int is_dwp)
8931 {
8932   bfd *sym_bfd;
8933   int desc, flags;
8934   char *absolute_name;
8935
8936   flags = OPF_TRY_CWD_FIRST;
8937   if (is_dwp)
8938     flags |= OPF_SEARCH_IN_PATH;
8939   desc = openp (debug_file_directory, flags, file_name,
8940                 O_RDONLY | O_BINARY, &absolute_name);
8941   if (desc < 0)
8942     return NULL;
8943
8944   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8945   if (!sym_bfd)
8946     {
8947       xfree (absolute_name);
8948       return NULL;
8949     }
8950   xfree (absolute_name);
8951   bfd_set_cacheable (sym_bfd, 1);
8952
8953   if (!bfd_check_format (sym_bfd, bfd_object))
8954     {
8955       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8956       return NULL;
8957     }
8958
8959   return sym_bfd;
8960 }
8961
8962 /* Try to open DWO file FILE_NAME.
8963    COMP_DIR is the DW_AT_comp_dir attribute.
8964    The result is the bfd handle of the file.
8965    If there is a problem finding or opening the file, return NULL.
8966    Upon success, the canonicalized path of the file is stored in the bfd,
8967    same as symfile_bfd_open.  */
8968
8969 static bfd *
8970 open_dwo_file (const char *file_name, const char *comp_dir)
8971 {
8972   bfd *abfd;
8973
8974   if (IS_ABSOLUTE_PATH (file_name))
8975     return try_open_dwop_file (file_name, 0 /*is_dwp*/);
8976
8977   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8978
8979   if (comp_dir != NULL)
8980     {
8981       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8982
8983       /* NOTE: If comp_dir is a relative path, this will also try the
8984          search path, which seems useful.  */
8985       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/);
8986       xfree (path_to_try);
8987       if (abfd != NULL)
8988         return abfd;
8989     }
8990
8991   /* That didn't work, try debug-file-directory, which, despite its name,
8992      is a list of paths.  */
8993
8994   if (*debug_file_directory == '\0')
8995     return NULL;
8996
8997   return try_open_dwop_file (file_name, 0 /*is_dwp*/);
8998 }
8999
9000 /* This function is mapped across the sections and remembers the offset and
9001    size of each of the DWO debugging sections we are interested in.  */
9002
9003 static void
9004 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9005 {
9006   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9007   const struct dwop_section_names *names = &dwop_section_names;
9008
9009   if (section_is_p (sectp->name, &names->abbrev_dwo))
9010     {
9011       dwo_sections->abbrev.asection = sectp;
9012       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9013     }
9014   else if (section_is_p (sectp->name, &names->info_dwo))
9015     {
9016       dwo_sections->info.asection = sectp;
9017       dwo_sections->info.size = bfd_get_section_size (sectp);
9018     }
9019   else if (section_is_p (sectp->name, &names->line_dwo))
9020     {
9021       dwo_sections->line.asection = sectp;
9022       dwo_sections->line.size = bfd_get_section_size (sectp);
9023     }
9024   else if (section_is_p (sectp->name, &names->loc_dwo))
9025     {
9026       dwo_sections->loc.asection = sectp;
9027       dwo_sections->loc.size = bfd_get_section_size (sectp);
9028     }
9029   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9030     {
9031       dwo_sections->macinfo.asection = sectp;
9032       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9033     }
9034   else if (section_is_p (sectp->name, &names->macro_dwo))
9035     {
9036       dwo_sections->macro.asection = sectp;
9037       dwo_sections->macro.size = bfd_get_section_size (sectp);
9038     }
9039   else if (section_is_p (sectp->name, &names->str_dwo))
9040     {
9041       dwo_sections->str.asection = sectp;
9042       dwo_sections->str.size = bfd_get_section_size (sectp);
9043     }
9044   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9045     {
9046       dwo_sections->str_offsets.asection = sectp;
9047       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9048     }
9049   else if (section_is_p (sectp->name, &names->types_dwo))
9050     {
9051       struct dwarf2_section_info type_section;
9052
9053       memset (&type_section, 0, sizeof (type_section));
9054       type_section.asection = sectp;
9055       type_section.size = bfd_get_section_size (sectp);
9056       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9057                      &type_section);
9058     }
9059 }
9060
9061 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9062    by PER_CU.
9063    The result is NULL if DWO_NAME can't be found.  */
9064
9065 static struct dwo_file *
9066 open_and_init_dwo_file (const char *dwo_name, const char *comp_dir)
9067 {
9068   struct objfile *objfile = dwarf2_per_objfile->objfile;
9069   struct dwo_file *dwo_file;
9070   bfd *dbfd;
9071   struct cleanup *cleanups;
9072
9073   dbfd = open_dwo_file (dwo_name, comp_dir);
9074   if (dbfd == NULL)
9075     {
9076       if (dwarf2_read_debug)
9077         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9078       return NULL;
9079     }
9080   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9081   dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
9082                                   dwo_name, strlen (dwo_name));
9083   dwo_file->dbfd = dbfd;
9084
9085   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9086
9087   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9088
9089   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
9090
9091   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9092                                                  dwo_file->sections.types);
9093
9094   discard_cleanups (cleanups);
9095
9096   if (dwarf2_read_debug)
9097     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9098
9099   return dwo_file;
9100 }
9101
9102 /* This function is mapped across the sections and remembers the offset and
9103    size of each of the DWP debugging sections we are interested in.  */
9104
9105 static void
9106 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9107 {
9108   struct dwp_file *dwp_file = dwp_file_ptr;
9109   const struct dwop_section_names *names = &dwop_section_names;
9110   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9111
9112   /* Record the ELF section number for later lookup: this is what the
9113      .debug_cu_index,.debug_tu_index tables use.  */
9114   gdb_assert (elf_section_nr < dwp_file->num_sections);
9115   dwp_file->elf_sections[elf_section_nr] = sectp;
9116
9117   /* Look for specific sections that we need.  */
9118   if (section_is_p (sectp->name, &names->str_dwo))
9119     {
9120       dwp_file->sections.str.asection = sectp;
9121       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9122     }
9123   else if (section_is_p (sectp->name, &names->cu_index))
9124     {
9125       dwp_file->sections.cu_index.asection = sectp;
9126       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9127     }
9128   else if (section_is_p (sectp->name, &names->tu_index))
9129     {
9130       dwp_file->sections.tu_index.asection = sectp;
9131       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9132     }
9133 }
9134
9135 /* Hash function for dwp_file loaded CUs/TUs.  */
9136
9137 static hashval_t
9138 hash_dwp_loaded_cutus (const void *item)
9139 {
9140   const struct dwo_unit *dwo_unit = item;
9141
9142   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9143   return dwo_unit->signature;
9144 }
9145
9146 /* Equality function for dwp_file loaded CUs/TUs.  */
9147
9148 static int
9149 eq_dwp_loaded_cutus (const void *a, const void *b)
9150 {
9151   const struct dwo_unit *dua = a;
9152   const struct dwo_unit *dub = b;
9153
9154   return dua->signature == dub->signature;
9155 }
9156
9157 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9158
9159 static htab_t
9160 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9161 {
9162   return htab_create_alloc_ex (3,
9163                                hash_dwp_loaded_cutus,
9164                                eq_dwp_loaded_cutus,
9165                                NULL,
9166                                &objfile->objfile_obstack,
9167                                hashtab_obstack_allocate,
9168                                dummy_obstack_deallocate);
9169 }
9170
9171 /* Try to open DWP file FILE_NAME.
9172    The result is the bfd handle of the file.
9173    If there is a problem finding or opening the file, return NULL.
9174    Upon success, the canonicalized path of the file is stored in the bfd,
9175    same as symfile_bfd_open.  */
9176
9177 static bfd *
9178 open_dwp_file (const char *file_name)
9179 {
9180   return try_open_dwop_file (file_name, 1 /*is_dwp*/);
9181 }
9182
9183 /* Initialize the use of the DWP file for the current objfile.
9184    By convention the name of the DWP file is ${objfile}.dwp.
9185    The result is NULL if it can't be found.  */
9186
9187 static struct dwp_file *
9188 open_and_init_dwp_file (void)
9189 {
9190   struct objfile *objfile = dwarf2_per_objfile->objfile;
9191   struct dwp_file *dwp_file;
9192   char *dwp_name;
9193   bfd *dbfd;
9194   struct cleanup *cleanups;
9195
9196   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9197   cleanups = make_cleanup (xfree, dwp_name);
9198
9199   dbfd = open_dwp_file (dwp_name);
9200   if (dbfd == NULL)
9201     {
9202       if (dwarf2_read_debug)
9203         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9204       do_cleanups (cleanups);
9205       return NULL;
9206     }
9207   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9208   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9209                                   dwp_name, strlen (dwp_name));
9210   dwp_file->dbfd = dbfd;
9211   do_cleanups (cleanups);
9212
9213   /* +1: section 0 is unused */
9214   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9215   dwp_file->elf_sections =
9216     OBSTACK_CALLOC (&objfile->objfile_obstack,
9217                     dwp_file->num_sections, asection *);
9218
9219   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9220
9221   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9222
9223   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9224
9225   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9226
9227   if (dwarf2_read_debug)
9228     {
9229       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9230       fprintf_unfiltered (gdb_stdlog,
9231                           "    %u CUs, %u TUs\n",
9232                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9233                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9234     }
9235
9236   return dwp_file;
9237 }
9238
9239 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9240
9241 static struct dwp_file *
9242 get_dwp_file (void)
9243 {
9244   if (! dwarf2_per_objfile->dwp_checked)
9245     {
9246       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9247       dwarf2_per_objfile->dwp_checked = 1;
9248     }
9249   return dwarf2_per_objfile->dwp_file;
9250 }
9251
9252 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9253    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9254    or in the DWP file for the objfile, referenced by THIS_UNIT.
9255    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9256    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9257
9258    This is called, for example, when wanting to read a variable with a
9259    complex location.  Therefore we don't want to do file i/o for every call.
9260    Therefore we don't want to look for a DWO file on every call.
9261    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9262    then we check if we've already seen DWO_NAME, and only THEN do we check
9263    for a DWO file.
9264
9265    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9266    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9267
9268 static struct dwo_unit *
9269 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9270                  const char *dwo_name, const char *comp_dir,
9271                  ULONGEST signature, int is_debug_types)
9272 {
9273   struct objfile *objfile = dwarf2_per_objfile->objfile;
9274   const char *kind = is_debug_types ? "TU" : "CU";
9275   void **dwo_file_slot;
9276   struct dwo_file *dwo_file;
9277   struct dwp_file *dwp_file;
9278
9279   /* Have we already read SIGNATURE from a DWP file?  */
9280
9281   dwp_file = get_dwp_file ();
9282   if (dwp_file != NULL)
9283     {
9284       const struct dwp_hash_table *dwp_htab =
9285         is_debug_types ? dwp_file->tus : dwp_file->cus;
9286
9287       if (dwp_htab != NULL)
9288         {
9289           struct dwo_unit *dwo_cutu =
9290             lookup_dwo_in_dwp (dwp_file, dwp_htab, signature, is_debug_types);
9291
9292           if (dwo_cutu != NULL)
9293             {
9294               if (dwarf2_read_debug)
9295                 {
9296                   fprintf_unfiltered (gdb_stdlog,
9297                                       "Virtual DWO %s %s found: @%s\n",
9298                                       kind, hex_string (signature),
9299                                       host_address_to_string (dwo_cutu));
9300                 }
9301               return dwo_cutu;
9302             }
9303         }
9304     }
9305
9306   /* Have we already seen DWO_NAME?  */
9307
9308   dwo_file_slot = lookup_dwo_file_slot (dwo_name);
9309   if (*dwo_file_slot == NULL)
9310     {
9311       /* Read in the file and build a table of the DWOs it contains.  */
9312       *dwo_file_slot = open_and_init_dwo_file (dwo_name, comp_dir);
9313     }
9314   /* NOTE: This will be NULL if unable to open the file.  */
9315   dwo_file = *dwo_file_slot;
9316
9317   if (dwo_file != NULL)
9318     {
9319       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9320
9321       if (htab != NULL)
9322         {
9323           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9324
9325           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9326           find_dwo_cutu.signature = signature;
9327           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9328
9329           if (dwo_cutu != NULL)
9330             {
9331               if (dwarf2_read_debug)
9332                 {
9333                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9334                                       kind, dwo_name, hex_string (signature),
9335                                       host_address_to_string (dwo_cutu));
9336                 }
9337               return dwo_cutu;
9338             }
9339         }
9340     }
9341
9342   /* We didn't find it.  This could mean a dwo_id mismatch, or
9343      someone deleted the DWO/DWP file, or the search path isn't set up
9344      correctly to find the file.  */
9345
9346   if (dwarf2_read_debug)
9347     {
9348       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9349                           kind, dwo_name, hex_string (signature));
9350     }
9351
9352   complaint (&symfile_complaints,
9353              _("Could not find DWO %s referenced by CU at offset 0x%x"
9354                " [in module %s]"),
9355              kind, this_unit->offset.sect_off, objfile->name);
9356   return NULL;
9357 }
9358
9359 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9360    See lookup_dwo_cutu_unit for details.  */
9361
9362 static struct dwo_unit *
9363 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9364                       const char *dwo_name, const char *comp_dir,
9365                       ULONGEST signature)
9366 {
9367   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9368 }
9369
9370 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9371    See lookup_dwo_cutu_unit for details.  */
9372
9373 static struct dwo_unit *
9374 lookup_dwo_type_unit (struct signatured_type *this_tu,
9375                       const char *dwo_name, const char *comp_dir)
9376 {
9377   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9378 }
9379
9380 /* Free all resources associated with DWO_FILE.
9381    Close the DWO file and munmap the sections.
9382    All memory should be on the objfile obstack.  */
9383
9384 static void
9385 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9386 {
9387   int ix;
9388   struct dwarf2_section_info *section;
9389
9390   /* Note: dbfd is NULL for virtual DWO files.  */
9391   gdb_bfd_unref (dwo_file->dbfd);
9392
9393   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9394 }
9395
9396 /* Wrapper for free_dwo_file for use in cleanups.  */
9397
9398 static void
9399 free_dwo_file_cleanup (void *arg)
9400 {
9401   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9402   struct objfile *objfile = dwarf2_per_objfile->objfile;
9403
9404   free_dwo_file (dwo_file, objfile);
9405 }
9406
9407 /* Traversal function for free_dwo_files.  */
9408
9409 static int
9410 free_dwo_file_from_slot (void **slot, void *info)
9411 {
9412   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9413   struct objfile *objfile = (struct objfile *) info;
9414
9415   free_dwo_file (dwo_file, objfile);
9416
9417   return 1;
9418 }
9419
9420 /* Free all resources associated with DWO_FILES.  */
9421
9422 static void
9423 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9424 {
9425   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9426 }
9427 \f
9428 /* Read in various DIEs.  */
9429
9430 /* qsort helper for inherit_abstract_dies.  */
9431
9432 static int
9433 unsigned_int_compar (const void *ap, const void *bp)
9434 {
9435   unsigned int a = *(unsigned int *) ap;
9436   unsigned int b = *(unsigned int *) bp;
9437
9438   return (a > b) - (b > a);
9439 }
9440
9441 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9442    Inherit only the children of the DW_AT_abstract_origin DIE not being
9443    already referenced by DW_AT_abstract_origin from the children of the
9444    current DIE.  */
9445
9446 static void
9447 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9448 {
9449   struct die_info *child_die;
9450   unsigned die_children_count;
9451   /* CU offsets which were referenced by children of the current DIE.  */
9452   sect_offset *offsets;
9453   sect_offset *offsets_end, *offsetp;
9454   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9455   struct die_info *origin_die;
9456   /* Iterator of the ORIGIN_DIE children.  */
9457   struct die_info *origin_child_die;
9458   struct cleanup *cleanups;
9459   struct attribute *attr;
9460   struct dwarf2_cu *origin_cu;
9461   struct pending **origin_previous_list_in_scope;
9462
9463   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9464   if (!attr)
9465     return;
9466
9467   /* Note that following die references may follow to a die in a
9468      different cu.  */
9469
9470   origin_cu = cu;
9471   origin_die = follow_die_ref (die, attr, &origin_cu);
9472
9473   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9474      symbols in.  */
9475   origin_previous_list_in_scope = origin_cu->list_in_scope;
9476   origin_cu->list_in_scope = cu->list_in_scope;
9477
9478   if (die->tag != origin_die->tag
9479       && !(die->tag == DW_TAG_inlined_subroutine
9480            && origin_die->tag == DW_TAG_subprogram))
9481     complaint (&symfile_complaints,
9482                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9483                die->offset.sect_off, origin_die->offset.sect_off);
9484
9485   child_die = die->child;
9486   die_children_count = 0;
9487   while (child_die && child_die->tag)
9488     {
9489       child_die = sibling_die (child_die);
9490       die_children_count++;
9491     }
9492   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9493   cleanups = make_cleanup (xfree, offsets);
9494
9495   offsets_end = offsets;
9496   child_die = die->child;
9497   while (child_die && child_die->tag)
9498     {
9499       /* For each CHILD_DIE, find the corresponding child of
9500          ORIGIN_DIE.  If there is more than one layer of
9501          DW_AT_abstract_origin, follow them all; there shouldn't be,
9502          but GCC versions at least through 4.4 generate this (GCC PR
9503          40573).  */
9504       struct die_info *child_origin_die = child_die;
9505       struct dwarf2_cu *child_origin_cu = cu;
9506
9507       while (1)
9508         {
9509           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9510                               child_origin_cu);
9511           if (attr == NULL)
9512             break;
9513           child_origin_die = follow_die_ref (child_origin_die, attr,
9514                                              &child_origin_cu);
9515         }
9516
9517       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9518          counterpart may exist.  */
9519       if (child_origin_die != child_die)
9520         {
9521           if (child_die->tag != child_origin_die->tag
9522               && !(child_die->tag == DW_TAG_inlined_subroutine
9523                    && child_origin_die->tag == DW_TAG_subprogram))
9524             complaint (&symfile_complaints,
9525                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9526                          "different tags"), child_die->offset.sect_off,
9527                        child_origin_die->offset.sect_off);
9528           if (child_origin_die->parent != origin_die)
9529             complaint (&symfile_complaints,
9530                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9531                          "different parents"), child_die->offset.sect_off,
9532                        child_origin_die->offset.sect_off);
9533           else
9534             *offsets_end++ = child_origin_die->offset;
9535         }
9536       child_die = sibling_die (child_die);
9537     }
9538   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9539          unsigned_int_compar);
9540   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9541     if (offsetp[-1].sect_off == offsetp->sect_off)
9542       complaint (&symfile_complaints,
9543                  _("Multiple children of DIE 0x%x refer "
9544                    "to DIE 0x%x as their abstract origin"),
9545                  die->offset.sect_off, offsetp->sect_off);
9546
9547   offsetp = offsets;
9548   origin_child_die = origin_die->child;
9549   while (origin_child_die && origin_child_die->tag)
9550     {
9551       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9552       while (offsetp < offsets_end
9553              && offsetp->sect_off < origin_child_die->offset.sect_off)
9554         offsetp++;
9555       if (offsetp >= offsets_end
9556           || offsetp->sect_off > origin_child_die->offset.sect_off)
9557         {
9558           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9559           process_die (origin_child_die, origin_cu);
9560         }
9561       origin_child_die = sibling_die (origin_child_die);
9562     }
9563   origin_cu->list_in_scope = origin_previous_list_in_scope;
9564
9565   do_cleanups (cleanups);
9566 }
9567
9568 static void
9569 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9570 {
9571   struct objfile *objfile = cu->objfile;
9572   struct context_stack *new;
9573   CORE_ADDR lowpc;
9574   CORE_ADDR highpc;
9575   struct die_info *child_die;
9576   struct attribute *attr, *call_line, *call_file;
9577   const char *name;
9578   CORE_ADDR baseaddr;
9579   struct block *block;
9580   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9581   VEC (symbolp) *template_args = NULL;
9582   struct template_symbol *templ_func = NULL;
9583
9584   if (inlined_func)
9585     {
9586       /* If we do not have call site information, we can't show the
9587          caller of this inlined function.  That's too confusing, so
9588          only use the scope for local variables.  */
9589       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9590       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9591       if (call_line == NULL || call_file == NULL)
9592         {
9593           read_lexical_block_scope (die, cu);
9594           return;
9595         }
9596     }
9597
9598   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9599
9600   name = dwarf2_name (die, cu);
9601
9602   /* Ignore functions with missing or empty names.  These are actually
9603      illegal according to the DWARF standard.  */
9604   if (name == NULL)
9605     {
9606       complaint (&symfile_complaints,
9607                  _("missing name for subprogram DIE at %d"),
9608                  die->offset.sect_off);
9609       return;
9610     }
9611
9612   /* Ignore functions with missing or invalid low and high pc attributes.  */
9613   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9614     {
9615       attr = dwarf2_attr (die, DW_AT_external, cu);
9616       if (!attr || !DW_UNSND (attr))
9617         complaint (&symfile_complaints,
9618                    _("cannot get low and high bounds "
9619                      "for subprogram DIE at %d"),
9620                    die->offset.sect_off);
9621       return;
9622     }
9623
9624   lowpc += baseaddr;
9625   highpc += baseaddr;
9626
9627   /* If we have any template arguments, then we must allocate a
9628      different sort of symbol.  */
9629   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9630     {
9631       if (child_die->tag == DW_TAG_template_type_param
9632           || child_die->tag == DW_TAG_template_value_param)
9633         {
9634           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9635                                        struct template_symbol);
9636           templ_func->base.is_cplus_template_function = 1;
9637           break;
9638         }
9639     }
9640
9641   new = push_context (0, lowpc);
9642   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9643                                (struct symbol *) templ_func);
9644
9645   /* If there is a location expression for DW_AT_frame_base, record
9646      it.  */
9647   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9648   if (attr)
9649     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
9650
9651   cu->list_in_scope = &local_symbols;
9652
9653   if (die->child != NULL)
9654     {
9655       child_die = die->child;
9656       while (child_die && child_die->tag)
9657         {
9658           if (child_die->tag == DW_TAG_template_type_param
9659               || child_die->tag == DW_TAG_template_value_param)
9660             {
9661               struct symbol *arg = new_symbol (child_die, NULL, cu);
9662
9663               if (arg != NULL)
9664                 VEC_safe_push (symbolp, template_args, arg);
9665             }
9666           else
9667             process_die (child_die, cu);
9668           child_die = sibling_die (child_die);
9669         }
9670     }
9671
9672   inherit_abstract_dies (die, cu);
9673
9674   /* If we have a DW_AT_specification, we might need to import using
9675      directives from the context of the specification DIE.  See the
9676      comment in determine_prefix.  */
9677   if (cu->language == language_cplus
9678       && dwarf2_attr (die, DW_AT_specification, cu))
9679     {
9680       struct dwarf2_cu *spec_cu = cu;
9681       struct die_info *spec_die = die_specification (die, &spec_cu);
9682
9683       while (spec_die)
9684         {
9685           child_die = spec_die->child;
9686           while (child_die && child_die->tag)
9687             {
9688               if (child_die->tag == DW_TAG_imported_module)
9689                 process_die (child_die, spec_cu);
9690               child_die = sibling_die (child_die);
9691             }
9692
9693           /* In some cases, GCC generates specification DIEs that
9694              themselves contain DW_AT_specification attributes.  */
9695           spec_die = die_specification (spec_die, &spec_cu);
9696         }
9697     }
9698
9699   new = pop_context ();
9700   /* Make a block for the local symbols within.  */
9701   block = finish_block (new->name, &local_symbols, new->old_blocks,
9702                         lowpc, highpc, objfile);
9703
9704   /* For C++, set the block's scope.  */
9705   if ((cu->language == language_cplus || cu->language == language_fortran)
9706       && cu->processing_has_namespace_info)
9707     block_set_scope (block, determine_prefix (die, cu),
9708                      &objfile->objfile_obstack);
9709
9710   /* If we have address ranges, record them.  */
9711   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9712
9713   /* Attach template arguments to function.  */
9714   if (! VEC_empty (symbolp, template_args))
9715     {
9716       gdb_assert (templ_func != NULL);
9717
9718       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9719       templ_func->template_arguments
9720         = obstack_alloc (&objfile->objfile_obstack,
9721                          (templ_func->n_template_arguments
9722                           * sizeof (struct symbol *)));
9723       memcpy (templ_func->template_arguments,
9724               VEC_address (symbolp, template_args),
9725               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9726       VEC_free (symbolp, template_args);
9727     }
9728
9729   /* In C++, we can have functions nested inside functions (e.g., when
9730      a function declares a class that has methods).  This means that
9731      when we finish processing a function scope, we may need to go
9732      back to building a containing block's symbol lists.  */
9733   local_symbols = new->locals;
9734   using_directives = new->using_directives;
9735
9736   /* If we've finished processing a top-level function, subsequent
9737      symbols go in the file symbol list.  */
9738   if (outermost_context_p ())
9739     cu->list_in_scope = &file_symbols;
9740 }
9741
9742 /* Process all the DIES contained within a lexical block scope.  Start
9743    a new scope, process the dies, and then close the scope.  */
9744
9745 static void
9746 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9747 {
9748   struct objfile *objfile = cu->objfile;
9749   struct context_stack *new;
9750   CORE_ADDR lowpc, highpc;
9751   struct die_info *child_die;
9752   CORE_ADDR baseaddr;
9753
9754   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9755
9756   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9757   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9758      as multiple lexical blocks?  Handling children in a sane way would
9759      be nasty.  Might be easier to properly extend generic blocks to
9760      describe ranges.  */
9761   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9762     return;
9763   lowpc += baseaddr;
9764   highpc += baseaddr;
9765
9766   push_context (0, lowpc);
9767   if (die->child != NULL)
9768     {
9769       child_die = die->child;
9770       while (child_die && child_die->tag)
9771         {
9772           process_die (child_die, cu);
9773           child_die = sibling_die (child_die);
9774         }
9775     }
9776   new = pop_context ();
9777
9778   if (local_symbols != NULL || using_directives != NULL)
9779     {
9780       struct block *block
9781         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9782                         highpc, objfile);
9783
9784       /* Note that recording ranges after traversing children, as we
9785          do here, means that recording a parent's ranges entails
9786          walking across all its children's ranges as they appear in
9787          the address map, which is quadratic behavior.
9788
9789          It would be nicer to record the parent's ranges before
9790          traversing its children, simply overriding whatever you find
9791          there.  But since we don't even decide whether to create a
9792          block until after we've traversed its children, that's hard
9793          to do.  */
9794       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9795     }
9796   local_symbols = new->locals;
9797   using_directives = new->using_directives;
9798 }
9799
9800 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9801
9802 static void
9803 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9804 {
9805   struct objfile *objfile = cu->objfile;
9806   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9807   CORE_ADDR pc, baseaddr;
9808   struct attribute *attr;
9809   struct call_site *call_site, call_site_local;
9810   void **slot;
9811   int nparams;
9812   struct die_info *child_die;
9813
9814   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9815
9816   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9817   if (!attr)
9818     {
9819       complaint (&symfile_complaints,
9820                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9821                    "DIE 0x%x [in module %s]"),
9822                  die->offset.sect_off, objfile->name);
9823       return;
9824     }
9825   pc = DW_ADDR (attr) + baseaddr;
9826
9827   if (cu->call_site_htab == NULL)
9828     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9829                                                NULL, &objfile->objfile_obstack,
9830                                                hashtab_obstack_allocate, NULL);
9831   call_site_local.pc = pc;
9832   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9833   if (*slot != NULL)
9834     {
9835       complaint (&symfile_complaints,
9836                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9837                    "DIE 0x%x [in module %s]"),
9838                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9839       return;
9840     }
9841
9842   /* Count parameters at the caller.  */
9843
9844   nparams = 0;
9845   for (child_die = die->child; child_die && child_die->tag;
9846        child_die = sibling_die (child_die))
9847     {
9848       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9849         {
9850           complaint (&symfile_complaints,
9851                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9852                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9853                      child_die->tag, child_die->offset.sect_off, objfile->name);
9854           continue;
9855         }
9856
9857       nparams++;
9858     }
9859
9860   call_site = obstack_alloc (&objfile->objfile_obstack,
9861                              (sizeof (*call_site)
9862                               + (sizeof (*call_site->parameter)
9863                                  * (nparams - 1))));
9864   *slot = call_site;
9865   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9866   call_site->pc = pc;
9867
9868   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9869     {
9870       struct die_info *func_die;
9871
9872       /* Skip also over DW_TAG_inlined_subroutine.  */
9873       for (func_die = die->parent;
9874            func_die && func_die->tag != DW_TAG_subprogram
9875            && func_die->tag != DW_TAG_subroutine_type;
9876            func_die = func_die->parent);
9877
9878       /* DW_AT_GNU_all_call_sites is a superset
9879          of DW_AT_GNU_all_tail_call_sites.  */
9880       if (func_die
9881           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9882           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9883         {
9884           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9885              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9886              both the initial caller containing the real return address PC and
9887              the final callee containing the current PC of a chain of tail
9888              calls do not need to have the tail call list complete.  But any
9889              function candidate for a virtual tail call frame searched via
9890              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9891              determined unambiguously.  */
9892         }
9893       else
9894         {
9895           struct type *func_type = NULL;
9896
9897           if (func_die)
9898             func_type = get_die_type (func_die, cu);
9899           if (func_type != NULL)
9900             {
9901               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9902
9903               /* Enlist this call site to the function.  */
9904               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9905               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9906             }
9907           else
9908             complaint (&symfile_complaints,
9909                        _("Cannot find function owning DW_TAG_GNU_call_site "
9910                          "DIE 0x%x [in module %s]"),
9911                        die->offset.sect_off, objfile->name);
9912         }
9913     }
9914
9915   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9916   if (attr == NULL)
9917     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9918   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9919   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9920     /* Keep NULL DWARF_BLOCK.  */;
9921   else if (attr_form_is_block (attr))
9922     {
9923       struct dwarf2_locexpr_baton *dlbaton;
9924
9925       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9926       dlbaton->data = DW_BLOCK (attr)->data;
9927       dlbaton->size = DW_BLOCK (attr)->size;
9928       dlbaton->per_cu = cu->per_cu;
9929
9930       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9931     }
9932   else if (is_ref_attr (attr))
9933     {
9934       struct dwarf2_cu *target_cu = cu;
9935       struct die_info *target_die;
9936
9937       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9938       gdb_assert (target_cu->objfile == objfile);
9939       if (die_is_declaration (target_die, target_cu))
9940         {
9941           const char *target_physname = NULL;
9942           struct attribute *target_attr;
9943
9944           /* Prefer the mangled name; otherwise compute the demangled one.  */
9945           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
9946           if (target_attr == NULL)
9947             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
9948                                        target_cu);
9949           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
9950             target_physname = DW_STRING (target_attr);
9951           else
9952             target_physname = dwarf2_physname (NULL, target_die, target_cu);
9953           if (target_physname == NULL)
9954             complaint (&symfile_complaints,
9955                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9956                          "physname, for referencing DIE 0x%x [in module %s]"),
9957                        die->offset.sect_off, objfile->name);
9958           else
9959             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9960         }
9961       else
9962         {
9963           CORE_ADDR lowpc;
9964
9965           /* DW_AT_entry_pc should be preferred.  */
9966           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9967             complaint (&symfile_complaints,
9968                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9969                          "low pc, for referencing DIE 0x%x [in module %s]"),
9970                        die->offset.sect_off, objfile->name);
9971           else
9972             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9973         }
9974     }
9975   else
9976     complaint (&symfile_complaints,
9977                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9978                  "block nor reference, for DIE 0x%x [in module %s]"),
9979                die->offset.sect_off, objfile->name);
9980
9981   call_site->per_cu = cu->per_cu;
9982
9983   for (child_die = die->child;
9984        child_die && child_die->tag;
9985        child_die = sibling_die (child_die))
9986     {
9987       struct call_site_parameter *parameter;
9988       struct attribute *loc, *origin;
9989
9990       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9991         {
9992           /* Already printed the complaint above.  */
9993           continue;
9994         }
9995
9996       gdb_assert (call_site->parameter_count < nparams);
9997       parameter = &call_site->parameter[call_site->parameter_count];
9998
9999       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10000          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10001          register is contained in DW_AT_GNU_call_site_value.  */
10002
10003       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10004       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10005       if (loc == NULL && origin != NULL && is_ref_attr (origin))
10006         {
10007           sect_offset offset;
10008
10009           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10010           offset = dwarf2_get_ref_die_offset (origin);
10011           if (!offset_in_cu_p (&cu->header, offset))
10012             {
10013               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10014                  binding can be done only inside one CU.  Such referenced DIE
10015                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10016               complaint (&symfile_complaints,
10017                          _("DW_AT_abstract_origin offset is not in CU for "
10018                            "DW_TAG_GNU_call_site child DIE 0x%x "
10019                            "[in module %s]"),
10020                          child_die->offset.sect_off, objfile->name);
10021               continue;
10022             }
10023           parameter->u.param_offset.cu_off = (offset.sect_off
10024                                               - cu->header.offset.sect_off);
10025         }
10026       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10027         {
10028           complaint (&symfile_complaints,
10029                      _("No DW_FORM_block* DW_AT_location for "
10030                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10031                      child_die->offset.sect_off, objfile->name);
10032           continue;
10033         }
10034       else
10035         {
10036           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10037             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10038           if (parameter->u.dwarf_reg != -1)
10039             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10040           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10041                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10042                                              &parameter->u.fb_offset))
10043             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10044           else
10045             {
10046               complaint (&symfile_complaints,
10047                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10048                            "for DW_FORM_block* DW_AT_location is supported for "
10049                            "DW_TAG_GNU_call_site child DIE 0x%x "
10050                            "[in module %s]"),
10051                          child_die->offset.sect_off, objfile->name);
10052               continue;
10053             }
10054         }
10055
10056       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10057       if (!attr_form_is_block (attr))
10058         {
10059           complaint (&symfile_complaints,
10060                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10061                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10062                      child_die->offset.sect_off, objfile->name);
10063           continue;
10064         }
10065       parameter->value = DW_BLOCK (attr)->data;
10066       parameter->value_size = DW_BLOCK (attr)->size;
10067
10068       /* Parameters are not pre-cleared by memset above.  */
10069       parameter->data_value = NULL;
10070       parameter->data_value_size = 0;
10071       call_site->parameter_count++;
10072
10073       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10074       if (attr)
10075         {
10076           if (!attr_form_is_block (attr))
10077             complaint (&symfile_complaints,
10078                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10079                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10080                        child_die->offset.sect_off, objfile->name);
10081           else
10082             {
10083               parameter->data_value = DW_BLOCK (attr)->data;
10084               parameter->data_value_size = DW_BLOCK (attr)->size;
10085             }
10086         }
10087     }
10088 }
10089
10090 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10091    Return 1 if the attributes are present and valid, otherwise, return 0.
10092    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10093
10094 static int
10095 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10096                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10097                     struct partial_symtab *ranges_pst)
10098 {
10099   struct objfile *objfile = cu->objfile;
10100   struct comp_unit_head *cu_header = &cu->header;
10101   bfd *obfd = objfile->obfd;
10102   unsigned int addr_size = cu_header->addr_size;
10103   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10104   /* Base address selection entry.  */
10105   CORE_ADDR base;
10106   int found_base;
10107   unsigned int dummy;
10108   gdb_byte *buffer;
10109   CORE_ADDR marker;
10110   int low_set;
10111   CORE_ADDR low = 0;
10112   CORE_ADDR high = 0;
10113   CORE_ADDR baseaddr;
10114
10115   found_base = cu->base_known;
10116   base = cu->base_address;
10117
10118   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10119   if (offset >= dwarf2_per_objfile->ranges.size)
10120     {
10121       complaint (&symfile_complaints,
10122                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10123                  offset);
10124       return 0;
10125     }
10126   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10127
10128   /* Read in the largest possible address.  */
10129   marker = read_address (obfd, buffer, cu, &dummy);
10130   if ((marker & mask) == mask)
10131     {
10132       /* If we found the largest possible address, then
10133          read the base address.  */
10134       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10135       buffer += 2 * addr_size;
10136       offset += 2 * addr_size;
10137       found_base = 1;
10138     }
10139
10140   low_set = 0;
10141
10142   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10143
10144   while (1)
10145     {
10146       CORE_ADDR range_beginning, range_end;
10147
10148       range_beginning = read_address (obfd, buffer, cu, &dummy);
10149       buffer += addr_size;
10150       range_end = read_address (obfd, buffer, cu, &dummy);
10151       buffer += addr_size;
10152       offset += 2 * addr_size;
10153
10154       /* An end of list marker is a pair of zero addresses.  */
10155       if (range_beginning == 0 && range_end == 0)
10156         /* Found the end of list entry.  */
10157         break;
10158
10159       /* Each base address selection entry is a pair of 2 values.
10160          The first is the largest possible address, the second is
10161          the base address.  Check for a base address here.  */
10162       if ((range_beginning & mask) == mask)
10163         {
10164           /* If we found the largest possible address, then
10165              read the base address.  */
10166           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10167           found_base = 1;
10168           continue;
10169         }
10170
10171       if (!found_base)
10172         {
10173           /* We have no valid base address for the ranges
10174              data.  */
10175           complaint (&symfile_complaints,
10176                      _("Invalid .debug_ranges data (no base address)"));
10177           return 0;
10178         }
10179
10180       if (range_beginning > range_end)
10181         {
10182           /* Inverted range entries are invalid.  */
10183           complaint (&symfile_complaints,
10184                      _("Invalid .debug_ranges data (inverted range)"));
10185           return 0;
10186         }
10187
10188       /* Empty range entries have no effect.  */
10189       if (range_beginning == range_end)
10190         continue;
10191
10192       range_beginning += base;
10193       range_end += base;
10194
10195       /* A not-uncommon case of bad debug info.
10196          Don't pollute the addrmap with bad data.  */
10197       if (range_beginning + baseaddr == 0
10198           && !dwarf2_per_objfile->has_section_at_zero)
10199         {
10200           complaint (&symfile_complaints,
10201                      _(".debug_ranges entry has start address of zero"
10202                        " [in module %s]"), objfile->name);
10203           continue;
10204         }
10205
10206       if (ranges_pst != NULL)
10207         addrmap_set_empty (objfile->psymtabs_addrmap,
10208                            range_beginning + baseaddr,
10209                            range_end - 1 + baseaddr,
10210                            ranges_pst);
10211
10212       /* FIXME: This is recording everything as a low-high
10213          segment of consecutive addresses.  We should have a
10214          data structure for discontiguous block ranges
10215          instead.  */
10216       if (! low_set)
10217         {
10218           low = range_beginning;
10219           high = range_end;
10220           low_set = 1;
10221         }
10222       else
10223         {
10224           if (range_beginning < low)
10225             low = range_beginning;
10226           if (range_end > high)
10227             high = range_end;
10228         }
10229     }
10230
10231   if (! low_set)
10232     /* If the first entry is an end-of-list marker, the range
10233        describes an empty scope, i.e. no instructions.  */
10234     return 0;
10235
10236   if (low_return)
10237     *low_return = low;
10238   if (high_return)
10239     *high_return = high;
10240   return 1;
10241 }
10242
10243 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10244    are present and valid, otherwise, return 0.  Return -1 if the range is
10245    discontinuous, i.e. derived from DW_AT_ranges information.  */
10246
10247 static int
10248 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10249                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10250                       struct partial_symtab *pst)
10251 {
10252   struct attribute *attr;
10253   struct attribute *attr_high;
10254   CORE_ADDR low = 0;
10255   CORE_ADDR high = 0;
10256   int ret = 0;
10257
10258   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10259   if (attr_high)
10260     {
10261       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10262       if (attr)
10263         {
10264           low = DW_ADDR (attr);
10265           if (attr_high->form == DW_FORM_addr
10266               || attr_high->form == DW_FORM_GNU_addr_index)
10267             high = DW_ADDR (attr_high);
10268           else
10269             high = low + DW_UNSND (attr_high);
10270         }
10271       else
10272         /* Found high w/o low attribute.  */
10273         return 0;
10274
10275       /* Found consecutive range of addresses.  */
10276       ret = 1;
10277     }
10278   else
10279     {
10280       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10281       if (attr != NULL)
10282         {
10283           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10284              We take advantage of the fact that DW_AT_ranges does not appear
10285              in DW_TAG_compile_unit of DWO files.  */
10286           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10287           unsigned int ranges_offset = (DW_UNSND (attr)
10288                                         + (need_ranges_base
10289                                            ? cu->ranges_base
10290                                            : 0));
10291
10292           /* Value of the DW_AT_ranges attribute is the offset in the
10293              .debug_ranges section.  */
10294           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10295             return 0;
10296           /* Found discontinuous range of addresses.  */
10297           ret = -1;
10298         }
10299     }
10300
10301   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10302   if (high <= low)
10303     return 0;
10304
10305   /* When using the GNU linker, .gnu.linkonce. sections are used to
10306      eliminate duplicate copies of functions and vtables and such.
10307      The linker will arbitrarily choose one and discard the others.
10308      The AT_*_pc values for such functions refer to local labels in
10309      these sections.  If the section from that file was discarded, the
10310      labels are not in the output, so the relocs get a value of 0.
10311      If this is a discarded function, mark the pc bounds as invalid,
10312      so that GDB will ignore it.  */
10313   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10314     return 0;
10315
10316   *lowpc = low;
10317   if (highpc)
10318     *highpc = high;
10319   return ret;
10320 }
10321
10322 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10323    its low and high PC addresses.  Do nothing if these addresses could not
10324    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10325    and HIGHPC to the high address if greater than HIGHPC.  */
10326
10327 static void
10328 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10329                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10330                                  struct dwarf2_cu *cu)
10331 {
10332   CORE_ADDR low, high;
10333   struct die_info *child = die->child;
10334
10335   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10336     {
10337       *lowpc = min (*lowpc, low);
10338       *highpc = max (*highpc, high);
10339     }
10340
10341   /* If the language does not allow nested subprograms (either inside
10342      subprograms or lexical blocks), we're done.  */
10343   if (cu->language != language_ada)
10344     return;
10345
10346   /* Check all the children of the given DIE.  If it contains nested
10347      subprograms, then check their pc bounds.  Likewise, we need to
10348      check lexical blocks as well, as they may also contain subprogram
10349      definitions.  */
10350   while (child && child->tag)
10351     {
10352       if (child->tag == DW_TAG_subprogram
10353           || child->tag == DW_TAG_lexical_block)
10354         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10355       child = sibling_die (child);
10356     }
10357 }
10358
10359 /* Get the low and high pc's represented by the scope DIE, and store
10360    them in *LOWPC and *HIGHPC.  If the correct values can't be
10361    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10362
10363 static void
10364 get_scope_pc_bounds (struct die_info *die,
10365                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10366                      struct dwarf2_cu *cu)
10367 {
10368   CORE_ADDR best_low = (CORE_ADDR) -1;
10369   CORE_ADDR best_high = (CORE_ADDR) 0;
10370   CORE_ADDR current_low, current_high;
10371
10372   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10373     {
10374       best_low = current_low;
10375       best_high = current_high;
10376     }
10377   else
10378     {
10379       struct die_info *child = die->child;
10380
10381       while (child && child->tag)
10382         {
10383           switch (child->tag) {
10384           case DW_TAG_subprogram:
10385             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10386             break;
10387           case DW_TAG_namespace:
10388           case DW_TAG_module:
10389             /* FIXME: carlton/2004-01-16: Should we do this for
10390                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10391                that current GCC's always emit the DIEs corresponding
10392                to definitions of methods of classes as children of a
10393                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10394                the DIEs giving the declarations, which could be
10395                anywhere).  But I don't see any reason why the
10396                standards says that they have to be there.  */
10397             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10398
10399             if (current_low != ((CORE_ADDR) -1))
10400               {
10401                 best_low = min (best_low, current_low);
10402                 best_high = max (best_high, current_high);
10403               }
10404             break;
10405           default:
10406             /* Ignore.  */
10407             break;
10408           }
10409
10410           child = sibling_die (child);
10411         }
10412     }
10413
10414   *lowpc = best_low;
10415   *highpc = best_high;
10416 }
10417
10418 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10419    in DIE.  */
10420
10421 static void
10422 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10423                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10424 {
10425   struct objfile *objfile = cu->objfile;
10426   struct attribute *attr;
10427   struct attribute *attr_high;
10428
10429   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10430   if (attr_high)
10431     {
10432       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10433       if (attr)
10434         {
10435           CORE_ADDR low = DW_ADDR (attr);
10436           CORE_ADDR high;
10437           if (attr_high->form == DW_FORM_addr
10438               || attr_high->form == DW_FORM_GNU_addr_index)
10439             high = DW_ADDR (attr_high);
10440           else
10441             high = low + DW_UNSND (attr_high);
10442
10443           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10444         }
10445     }
10446
10447   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10448   if (attr)
10449     {
10450       bfd *obfd = objfile->obfd;
10451       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10452          We take advantage of the fact that DW_AT_ranges does not appear
10453          in DW_TAG_compile_unit of DWO files.  */
10454       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10455
10456       /* The value of the DW_AT_ranges attribute is the offset of the
10457          address range list in the .debug_ranges section.  */
10458       unsigned long offset = (DW_UNSND (attr)
10459                               + (need_ranges_base ? cu->ranges_base : 0));
10460       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10461
10462       /* For some target architectures, but not others, the
10463          read_address function sign-extends the addresses it returns.
10464          To recognize base address selection entries, we need a
10465          mask.  */
10466       unsigned int addr_size = cu->header.addr_size;
10467       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10468
10469       /* The base address, to which the next pair is relative.  Note
10470          that this 'base' is a DWARF concept: most entries in a range
10471          list are relative, to reduce the number of relocs against the
10472          debugging information.  This is separate from this function's
10473          'baseaddr' argument, which GDB uses to relocate debugging
10474          information from a shared library based on the address at
10475          which the library was loaded.  */
10476       CORE_ADDR base = cu->base_address;
10477       int base_known = cu->base_known;
10478
10479       gdb_assert (dwarf2_per_objfile->ranges.readin);
10480       if (offset >= dwarf2_per_objfile->ranges.size)
10481         {
10482           complaint (&symfile_complaints,
10483                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10484                      offset);
10485           return;
10486         }
10487
10488       for (;;)
10489         {
10490           unsigned int bytes_read;
10491           CORE_ADDR start, end;
10492
10493           start = read_address (obfd, buffer, cu, &bytes_read);
10494           buffer += bytes_read;
10495           end = read_address (obfd, buffer, cu, &bytes_read);
10496           buffer += bytes_read;
10497
10498           /* Did we find the end of the range list?  */
10499           if (start == 0 && end == 0)
10500             break;
10501
10502           /* Did we find a base address selection entry?  */
10503           else if ((start & base_select_mask) == base_select_mask)
10504             {
10505               base = end;
10506               base_known = 1;
10507             }
10508
10509           /* We found an ordinary address range.  */
10510           else
10511             {
10512               if (!base_known)
10513                 {
10514                   complaint (&symfile_complaints,
10515                              _("Invalid .debug_ranges data "
10516                                "(no base address)"));
10517                   return;
10518                 }
10519
10520               if (start > end)
10521                 {
10522                   /* Inverted range entries are invalid.  */
10523                   complaint (&symfile_complaints,
10524                              _("Invalid .debug_ranges data "
10525                                "(inverted range)"));
10526                   return;
10527                 }
10528
10529               /* Empty range entries have no effect.  */
10530               if (start == end)
10531                 continue;
10532
10533               start += base + baseaddr;
10534               end += base + baseaddr;
10535
10536               /* A not-uncommon case of bad debug info.
10537                  Don't pollute the addrmap with bad data.  */
10538               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10539                 {
10540                   complaint (&symfile_complaints,
10541                              _(".debug_ranges entry has start address of zero"
10542                                " [in module %s]"), objfile->name);
10543                   continue;
10544                 }
10545
10546               record_block_range (block, start, end - 1);
10547             }
10548         }
10549     }
10550 }
10551
10552 /* Check whether the producer field indicates either of GCC < 4.6, or the
10553    Intel C/C++ compiler, and cache the result in CU.  */
10554
10555 static void
10556 check_producer (struct dwarf2_cu *cu)
10557 {
10558   const char *cs;
10559   int major, minor, release;
10560
10561   if (cu->producer == NULL)
10562     {
10563       /* For unknown compilers expect their behavior is DWARF version
10564          compliant.
10565
10566          GCC started to support .debug_types sections by -gdwarf-4 since
10567          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10568          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10569          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10570          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10571     }
10572   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10573     {
10574       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10575
10576       cs = &cu->producer[strlen ("GNU ")];
10577       while (*cs && !isdigit (*cs))
10578         cs++;
10579       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10580         {
10581           /* Not recognized as GCC.  */
10582         }
10583       else
10584         {
10585           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10586           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10587         }
10588     }
10589   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10590     cu->producer_is_icc = 1;
10591   else
10592     {
10593       /* For other non-GCC compilers, expect their behavior is DWARF version
10594          compliant.  */
10595     }
10596
10597   cu->checked_producer = 1;
10598 }
10599
10600 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10601    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10602    during 4.6.0 experimental.  */
10603
10604 static int
10605 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10606 {
10607   if (!cu->checked_producer)
10608     check_producer (cu);
10609
10610   return cu->producer_is_gxx_lt_4_6;
10611 }
10612
10613 /* Return the default accessibility type if it is not overriden by
10614    DW_AT_accessibility.  */
10615
10616 static enum dwarf_access_attribute
10617 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10618 {
10619   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10620     {
10621       /* The default DWARF 2 accessibility for members is public, the default
10622          accessibility for inheritance is private.  */
10623
10624       if (die->tag != DW_TAG_inheritance)
10625         return DW_ACCESS_public;
10626       else
10627         return DW_ACCESS_private;
10628     }
10629   else
10630     {
10631       /* DWARF 3+ defines the default accessibility a different way.  The same
10632          rules apply now for DW_TAG_inheritance as for the members and it only
10633          depends on the container kind.  */
10634
10635       if (die->parent->tag == DW_TAG_class_type)
10636         return DW_ACCESS_private;
10637       else
10638         return DW_ACCESS_public;
10639     }
10640 }
10641
10642 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10643    offset.  If the attribute was not found return 0, otherwise return
10644    1.  If it was found but could not properly be handled, set *OFFSET
10645    to 0.  */
10646
10647 static int
10648 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10649                              LONGEST *offset)
10650 {
10651   struct attribute *attr;
10652
10653   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10654   if (attr != NULL)
10655     {
10656       *offset = 0;
10657
10658       /* Note that we do not check for a section offset first here.
10659          This is because DW_AT_data_member_location is new in DWARF 4,
10660          so if we see it, we can assume that a constant form is really
10661          a constant and not a section offset.  */
10662       if (attr_form_is_constant (attr))
10663         *offset = dwarf2_get_attr_constant_value (attr, 0);
10664       else if (attr_form_is_section_offset (attr))
10665         dwarf2_complex_location_expr_complaint ();
10666       else if (attr_form_is_block (attr))
10667         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10668       else
10669         dwarf2_complex_location_expr_complaint ();
10670
10671       return 1;
10672     }
10673
10674   return 0;
10675 }
10676
10677 /* Add an aggregate field to the field list.  */
10678
10679 static void
10680 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10681                   struct dwarf2_cu *cu)
10682 {
10683   struct objfile *objfile = cu->objfile;
10684   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10685   struct nextfield *new_field;
10686   struct attribute *attr;
10687   struct field *fp;
10688   const char *fieldname = "";
10689
10690   /* Allocate a new field list entry and link it in.  */
10691   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10692   make_cleanup (xfree, new_field);
10693   memset (new_field, 0, sizeof (struct nextfield));
10694
10695   if (die->tag == DW_TAG_inheritance)
10696     {
10697       new_field->next = fip->baseclasses;
10698       fip->baseclasses = new_field;
10699     }
10700   else
10701     {
10702       new_field->next = fip->fields;
10703       fip->fields = new_field;
10704     }
10705   fip->nfields++;
10706
10707   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10708   if (attr)
10709     new_field->accessibility = DW_UNSND (attr);
10710   else
10711     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10712   if (new_field->accessibility != DW_ACCESS_public)
10713     fip->non_public_fields = 1;
10714
10715   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10716   if (attr)
10717     new_field->virtuality = DW_UNSND (attr);
10718   else
10719     new_field->virtuality = DW_VIRTUALITY_none;
10720
10721   fp = &new_field->field;
10722
10723   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10724     {
10725       LONGEST offset;
10726
10727       /* Data member other than a C++ static data member.  */
10728
10729       /* Get type of field.  */
10730       fp->type = die_type (die, cu);
10731
10732       SET_FIELD_BITPOS (*fp, 0);
10733
10734       /* Get bit size of field (zero if none).  */
10735       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10736       if (attr)
10737         {
10738           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10739         }
10740       else
10741         {
10742           FIELD_BITSIZE (*fp) = 0;
10743         }
10744
10745       /* Get bit offset of field.  */
10746       if (handle_data_member_location (die, cu, &offset))
10747         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10748       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10749       if (attr)
10750         {
10751           if (gdbarch_bits_big_endian (gdbarch))
10752             {
10753               /* For big endian bits, the DW_AT_bit_offset gives the
10754                  additional bit offset from the MSB of the containing
10755                  anonymous object to the MSB of the field.  We don't
10756                  have to do anything special since we don't need to
10757                  know the size of the anonymous object.  */
10758               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10759             }
10760           else
10761             {
10762               /* For little endian bits, compute the bit offset to the
10763                  MSB of the anonymous object, subtract off the number of
10764                  bits from the MSB of the field to the MSB of the
10765                  object, and then subtract off the number of bits of
10766                  the field itself.  The result is the bit offset of
10767                  the LSB of the field.  */
10768               int anonymous_size;
10769               int bit_offset = DW_UNSND (attr);
10770
10771               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10772               if (attr)
10773                 {
10774                   /* The size of the anonymous object containing
10775                      the bit field is explicit, so use the
10776                      indicated size (in bytes).  */
10777                   anonymous_size = DW_UNSND (attr);
10778                 }
10779               else
10780                 {
10781                   /* The size of the anonymous object containing
10782                      the bit field must be inferred from the type
10783                      attribute of the data member containing the
10784                      bit field.  */
10785                   anonymous_size = TYPE_LENGTH (fp->type);
10786                 }
10787               SET_FIELD_BITPOS (*fp,
10788                                 (FIELD_BITPOS (*fp)
10789                                  + anonymous_size * bits_per_byte
10790                                  - bit_offset - FIELD_BITSIZE (*fp)));
10791             }
10792         }
10793
10794       /* Get name of field.  */
10795       fieldname = dwarf2_name (die, cu);
10796       if (fieldname == NULL)
10797         fieldname = "";
10798
10799       /* The name is already allocated along with this objfile, so we don't
10800          need to duplicate it for the type.  */
10801       fp->name = fieldname;
10802
10803       /* Change accessibility for artificial fields (e.g. virtual table
10804          pointer or virtual base class pointer) to private.  */
10805       if (dwarf2_attr (die, DW_AT_artificial, cu))
10806         {
10807           FIELD_ARTIFICIAL (*fp) = 1;
10808           new_field->accessibility = DW_ACCESS_private;
10809           fip->non_public_fields = 1;
10810         }
10811     }
10812   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10813     {
10814       /* C++ static member.  */
10815
10816       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10817          is a declaration, but all versions of G++ as of this writing
10818          (so through at least 3.2.1) incorrectly generate
10819          DW_TAG_variable tags.  */
10820
10821       const char *physname;
10822
10823       /* Get name of field.  */
10824       fieldname = dwarf2_name (die, cu);
10825       if (fieldname == NULL)
10826         return;
10827
10828       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10829       if (attr
10830           /* Only create a symbol if this is an external value.
10831              new_symbol checks this and puts the value in the global symbol
10832              table, which we want.  If it is not external, new_symbol
10833              will try to put the value in cu->list_in_scope which is wrong.  */
10834           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10835         {
10836           /* A static const member, not much different than an enum as far as
10837              we're concerned, except that we can support more types.  */
10838           new_symbol (die, NULL, cu);
10839         }
10840
10841       /* Get physical name.  */
10842       physname = dwarf2_physname (fieldname, die, cu);
10843
10844       /* The name is already allocated along with this objfile, so we don't
10845          need to duplicate it for the type.  */
10846       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10847       FIELD_TYPE (*fp) = die_type (die, cu);
10848       FIELD_NAME (*fp) = fieldname;
10849     }
10850   else if (die->tag == DW_TAG_inheritance)
10851     {
10852       LONGEST offset;
10853
10854       /* C++ base class field.  */
10855       if (handle_data_member_location (die, cu, &offset))
10856         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10857       FIELD_BITSIZE (*fp) = 0;
10858       FIELD_TYPE (*fp) = die_type (die, cu);
10859       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10860       fip->nbaseclasses++;
10861     }
10862 }
10863
10864 /* Add a typedef defined in the scope of the FIP's class.  */
10865
10866 static void
10867 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10868                     struct dwarf2_cu *cu)
10869 {
10870   struct objfile *objfile = cu->objfile;
10871   struct typedef_field_list *new_field;
10872   struct attribute *attr;
10873   struct typedef_field *fp;
10874   char *fieldname = "";
10875
10876   /* Allocate a new field list entry and link it in.  */
10877   new_field = xzalloc (sizeof (*new_field));
10878   make_cleanup (xfree, new_field);
10879
10880   gdb_assert (die->tag == DW_TAG_typedef);
10881
10882   fp = &new_field->field;
10883
10884   /* Get name of field.  */
10885   fp->name = dwarf2_name (die, cu);
10886   if (fp->name == NULL)
10887     return;
10888
10889   fp->type = read_type_die (die, cu);
10890
10891   new_field->next = fip->typedef_field_list;
10892   fip->typedef_field_list = new_field;
10893   fip->typedef_field_list_count++;
10894 }
10895
10896 /* Create the vector of fields, and attach it to the type.  */
10897
10898 static void
10899 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10900                               struct dwarf2_cu *cu)
10901 {
10902   int nfields = fip->nfields;
10903
10904   /* Record the field count, allocate space for the array of fields,
10905      and create blank accessibility bitfields if necessary.  */
10906   TYPE_NFIELDS (type) = nfields;
10907   TYPE_FIELDS (type) = (struct field *)
10908     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10909   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10910
10911   if (fip->non_public_fields && cu->language != language_ada)
10912     {
10913       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10914
10915       TYPE_FIELD_PRIVATE_BITS (type) =
10916         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10917       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10918
10919       TYPE_FIELD_PROTECTED_BITS (type) =
10920         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10921       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10922
10923       TYPE_FIELD_IGNORE_BITS (type) =
10924         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10925       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10926     }
10927
10928   /* If the type has baseclasses, allocate and clear a bit vector for
10929      TYPE_FIELD_VIRTUAL_BITS.  */
10930   if (fip->nbaseclasses && cu->language != language_ada)
10931     {
10932       int num_bytes = B_BYTES (fip->nbaseclasses);
10933       unsigned char *pointer;
10934
10935       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10936       pointer = TYPE_ALLOC (type, num_bytes);
10937       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10938       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10939       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10940     }
10941
10942   /* Copy the saved-up fields into the field vector.  Start from the head of
10943      the list, adding to the tail of the field array, so that they end up in
10944      the same order in the array in which they were added to the list.  */
10945   while (nfields-- > 0)
10946     {
10947       struct nextfield *fieldp;
10948
10949       if (fip->fields)
10950         {
10951           fieldp = fip->fields;
10952           fip->fields = fieldp->next;
10953         }
10954       else
10955         {
10956           fieldp = fip->baseclasses;
10957           fip->baseclasses = fieldp->next;
10958         }
10959
10960       TYPE_FIELD (type, nfields) = fieldp->field;
10961       switch (fieldp->accessibility)
10962         {
10963         case DW_ACCESS_private:
10964           if (cu->language != language_ada)
10965             SET_TYPE_FIELD_PRIVATE (type, nfields);
10966           break;
10967
10968         case DW_ACCESS_protected:
10969           if (cu->language != language_ada)
10970             SET_TYPE_FIELD_PROTECTED (type, nfields);
10971           break;
10972
10973         case DW_ACCESS_public:
10974           break;
10975
10976         default:
10977           /* Unknown accessibility.  Complain and treat it as public.  */
10978           {
10979             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10980                        fieldp->accessibility);
10981           }
10982           break;
10983         }
10984       if (nfields < fip->nbaseclasses)
10985         {
10986           switch (fieldp->virtuality)
10987             {
10988             case DW_VIRTUALITY_virtual:
10989             case DW_VIRTUALITY_pure_virtual:
10990               if (cu->language == language_ada)
10991                 error (_("unexpected virtuality in component of Ada type"));
10992               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10993               break;
10994             }
10995         }
10996     }
10997 }
10998
10999 /* Return true if this member function is a constructor, false
11000    otherwise.  */
11001
11002 static int
11003 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11004 {
11005   const char *fieldname;
11006   const char *typename;
11007   int len;
11008
11009   if (die->parent == NULL)
11010     return 0;
11011
11012   if (die->parent->tag != DW_TAG_structure_type
11013       && die->parent->tag != DW_TAG_union_type
11014       && die->parent->tag != DW_TAG_class_type)
11015     return 0;
11016
11017   fieldname = dwarf2_name (die, cu);
11018   typename = dwarf2_name (die->parent, cu);
11019   if (fieldname == NULL || typename == NULL)
11020     return 0;
11021
11022   len = strlen (fieldname);
11023   return (strncmp (fieldname, typename, len) == 0
11024           && (typename[len] == '\0' || typename[len] == '<'));
11025 }
11026
11027 /* Add a member function to the proper fieldlist.  */
11028
11029 static void
11030 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11031                       struct type *type, struct dwarf2_cu *cu)
11032 {
11033   struct objfile *objfile = cu->objfile;
11034   struct attribute *attr;
11035   struct fnfieldlist *flp;
11036   int i;
11037   struct fn_field *fnp;
11038   const char *fieldname;
11039   struct nextfnfield *new_fnfield;
11040   struct type *this_type;
11041   enum dwarf_access_attribute accessibility;
11042
11043   if (cu->language == language_ada)
11044     error (_("unexpected member function in Ada type"));
11045
11046   /* Get name of member function.  */
11047   fieldname = dwarf2_name (die, cu);
11048   if (fieldname == NULL)
11049     return;
11050
11051   /* Look up member function name in fieldlist.  */
11052   for (i = 0; i < fip->nfnfields; i++)
11053     {
11054       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11055         break;
11056     }
11057
11058   /* Create new list element if necessary.  */
11059   if (i < fip->nfnfields)
11060     flp = &fip->fnfieldlists[i];
11061   else
11062     {
11063       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11064         {
11065           fip->fnfieldlists = (struct fnfieldlist *)
11066             xrealloc (fip->fnfieldlists,
11067                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11068                       * sizeof (struct fnfieldlist));
11069           if (fip->nfnfields == 0)
11070             make_cleanup (free_current_contents, &fip->fnfieldlists);
11071         }
11072       flp = &fip->fnfieldlists[fip->nfnfields];
11073       flp->name = fieldname;
11074       flp->length = 0;
11075       flp->head = NULL;
11076       i = fip->nfnfields++;
11077     }
11078
11079   /* Create a new member function field and chain it to the field list
11080      entry.  */
11081   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11082   make_cleanup (xfree, new_fnfield);
11083   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11084   new_fnfield->next = flp->head;
11085   flp->head = new_fnfield;
11086   flp->length++;
11087
11088   /* Fill in the member function field info.  */
11089   fnp = &new_fnfield->fnfield;
11090
11091   /* Delay processing of the physname until later.  */
11092   if (cu->language == language_cplus || cu->language == language_java)
11093     {
11094       add_to_method_list (type, i, flp->length - 1, fieldname,
11095                           die, cu);
11096     }
11097   else
11098     {
11099       const char *physname = dwarf2_physname (fieldname, die, cu);
11100       fnp->physname = physname ? physname : "";
11101     }
11102
11103   fnp->type = alloc_type (objfile);
11104   this_type = read_type_die (die, cu);
11105   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11106     {
11107       int nparams = TYPE_NFIELDS (this_type);
11108
11109       /* TYPE is the domain of this method, and THIS_TYPE is the type
11110            of the method itself (TYPE_CODE_METHOD).  */
11111       smash_to_method_type (fnp->type, type,
11112                             TYPE_TARGET_TYPE (this_type),
11113                             TYPE_FIELDS (this_type),
11114                             TYPE_NFIELDS (this_type),
11115                             TYPE_VARARGS (this_type));
11116
11117       /* Handle static member functions.
11118          Dwarf2 has no clean way to discern C++ static and non-static
11119          member functions.  G++ helps GDB by marking the first
11120          parameter for non-static member functions (which is the this
11121          pointer) as artificial.  We obtain this information from
11122          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11123       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11124         fnp->voffset = VOFFSET_STATIC;
11125     }
11126   else
11127     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11128                dwarf2_full_name (fieldname, die, cu));
11129
11130   /* Get fcontext from DW_AT_containing_type if present.  */
11131   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11132     fnp->fcontext = die_containing_type (die, cu);
11133
11134   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11135      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11136
11137   /* Get accessibility.  */
11138   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11139   if (attr)
11140     accessibility = DW_UNSND (attr);
11141   else
11142     accessibility = dwarf2_default_access_attribute (die, cu);
11143   switch (accessibility)
11144     {
11145     case DW_ACCESS_private:
11146       fnp->is_private = 1;
11147       break;
11148     case DW_ACCESS_protected:
11149       fnp->is_protected = 1;
11150       break;
11151     }
11152
11153   /* Check for artificial methods.  */
11154   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11155   if (attr && DW_UNSND (attr) != 0)
11156     fnp->is_artificial = 1;
11157
11158   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11159
11160   /* Get index in virtual function table if it is a virtual member
11161      function.  For older versions of GCC, this is an offset in the
11162      appropriate virtual table, as specified by DW_AT_containing_type.
11163      For everyone else, it is an expression to be evaluated relative
11164      to the object address.  */
11165
11166   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11167   if (attr)
11168     {
11169       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11170         {
11171           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11172             {
11173               /* Old-style GCC.  */
11174               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11175             }
11176           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11177                    || (DW_BLOCK (attr)->size > 1
11178                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11179                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11180             {
11181               struct dwarf_block blk;
11182               int offset;
11183
11184               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11185                         ? 1 : 2);
11186               blk.size = DW_BLOCK (attr)->size - offset;
11187               blk.data = DW_BLOCK (attr)->data + offset;
11188               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11189               if ((fnp->voffset % cu->header.addr_size) != 0)
11190                 dwarf2_complex_location_expr_complaint ();
11191               else
11192                 fnp->voffset /= cu->header.addr_size;
11193               fnp->voffset += 2;
11194             }
11195           else
11196             dwarf2_complex_location_expr_complaint ();
11197
11198           if (!fnp->fcontext)
11199             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11200         }
11201       else if (attr_form_is_section_offset (attr))
11202         {
11203           dwarf2_complex_location_expr_complaint ();
11204         }
11205       else
11206         {
11207           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11208                                                  fieldname);
11209         }
11210     }
11211   else
11212     {
11213       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11214       if (attr && DW_UNSND (attr))
11215         {
11216           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11217           complaint (&symfile_complaints,
11218                      _("Member function \"%s\" (offset %d) is virtual "
11219                        "but the vtable offset is not specified"),
11220                      fieldname, die->offset.sect_off);
11221           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11222           TYPE_CPLUS_DYNAMIC (type) = 1;
11223         }
11224     }
11225 }
11226
11227 /* Create the vector of member function fields, and attach it to the type.  */
11228
11229 static void
11230 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11231                                  struct dwarf2_cu *cu)
11232 {
11233   struct fnfieldlist *flp;
11234   int i;
11235
11236   if (cu->language == language_ada)
11237     error (_("unexpected member functions in Ada type"));
11238
11239   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11240   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11241     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11242
11243   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11244     {
11245       struct nextfnfield *nfp = flp->head;
11246       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11247       int k;
11248
11249       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11250       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11251       fn_flp->fn_fields = (struct fn_field *)
11252         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11253       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11254         fn_flp->fn_fields[k] = nfp->fnfield;
11255     }
11256
11257   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11258 }
11259
11260 /* Returns non-zero if NAME is the name of a vtable member in CU's
11261    language, zero otherwise.  */
11262 static int
11263 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11264 {
11265   static const char vptr[] = "_vptr";
11266   static const char vtable[] = "vtable";
11267
11268   /* Look for the C++ and Java forms of the vtable.  */
11269   if ((cu->language == language_java
11270        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11271        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11272        && is_cplus_marker (name[sizeof (vptr) - 1])))
11273     return 1;
11274
11275   return 0;
11276 }
11277
11278 /* GCC outputs unnamed structures that are really pointers to member
11279    functions, with the ABI-specified layout.  If TYPE describes
11280    such a structure, smash it into a member function type.
11281
11282    GCC shouldn't do this; it should just output pointer to member DIEs.
11283    This is GCC PR debug/28767.  */
11284
11285 static void
11286 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11287 {
11288   struct type *pfn_type, *domain_type, *new_type;
11289
11290   /* Check for a structure with no name and two children.  */
11291   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11292     return;
11293
11294   /* Check for __pfn and __delta members.  */
11295   if (TYPE_FIELD_NAME (type, 0) == NULL
11296       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11297       || TYPE_FIELD_NAME (type, 1) == NULL
11298       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11299     return;
11300
11301   /* Find the type of the method.  */
11302   pfn_type = TYPE_FIELD_TYPE (type, 0);
11303   if (pfn_type == NULL
11304       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11305       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11306     return;
11307
11308   /* Look for the "this" argument.  */
11309   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11310   if (TYPE_NFIELDS (pfn_type) == 0
11311       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11312       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11313     return;
11314
11315   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11316   new_type = alloc_type (objfile);
11317   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11318                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11319                         TYPE_VARARGS (pfn_type));
11320   smash_to_methodptr_type (type, new_type);
11321 }
11322
11323 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11324    (icc).  */
11325
11326 static int
11327 producer_is_icc (struct dwarf2_cu *cu)
11328 {
11329   if (!cu->checked_producer)
11330     check_producer (cu);
11331
11332   return cu->producer_is_icc;
11333 }
11334
11335 /* Called when we find the DIE that starts a structure or union scope
11336    (definition) to create a type for the structure or union.  Fill in
11337    the type's name and general properties; the members will not be
11338    processed until process_structure_type.
11339
11340    NOTE: we need to call these functions regardless of whether or not the
11341    DIE has a DW_AT_name attribute, since it might be an anonymous
11342    structure or union.  This gets the type entered into our set of
11343    user defined types.
11344
11345    However, if the structure is incomplete (an opaque struct/union)
11346    then suppress creating a symbol table entry for it since gdb only
11347    wants to find the one with the complete definition.  Note that if
11348    it is complete, we just call new_symbol, which does it's own
11349    checking about whether the struct/union is anonymous or not (and
11350    suppresses creating a symbol table entry itself).  */
11351
11352 static struct type *
11353 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11354 {
11355   struct objfile *objfile = cu->objfile;
11356   struct type *type;
11357   struct attribute *attr;
11358   const char *name;
11359
11360   /* If the definition of this type lives in .debug_types, read that type.
11361      Don't follow DW_AT_specification though, that will take us back up
11362      the chain and we want to go down.  */
11363   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11364   if (attr)
11365     {
11366       struct dwarf2_cu *type_cu = cu;
11367       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11368
11369       /* We could just recurse on read_structure_type, but we need to call
11370          get_die_type to ensure only one type for this DIE is created.
11371          This is important, for example, because for c++ classes we need
11372          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11373       type = read_type_die (type_die, type_cu);
11374
11375       /* TYPE_CU may not be the same as CU.
11376          Ensure TYPE is recorded in CU's type_hash table.  */
11377       return set_die_type (die, type, cu);
11378     }
11379
11380   type = alloc_type (objfile);
11381   INIT_CPLUS_SPECIFIC (type);
11382
11383   name = dwarf2_name (die, cu);
11384   if (name != NULL)
11385     {
11386       if (cu->language == language_cplus
11387           || cu->language == language_java)
11388         {
11389           const char *full_name = dwarf2_full_name (name, die, cu);
11390
11391           /* dwarf2_full_name might have already finished building the DIE's
11392              type.  If so, there is no need to continue.  */
11393           if (get_die_type (die, cu) != NULL)
11394             return get_die_type (die, cu);
11395
11396           TYPE_TAG_NAME (type) = full_name;
11397           if (die->tag == DW_TAG_structure_type
11398               || die->tag == DW_TAG_class_type)
11399             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11400         }
11401       else
11402         {
11403           /* The name is already allocated along with this objfile, so
11404              we don't need to duplicate it for the type.  */
11405           TYPE_TAG_NAME (type) = name;
11406           if (die->tag == DW_TAG_class_type)
11407             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11408         }
11409     }
11410
11411   if (die->tag == DW_TAG_structure_type)
11412     {
11413       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11414     }
11415   else if (die->tag == DW_TAG_union_type)
11416     {
11417       TYPE_CODE (type) = TYPE_CODE_UNION;
11418     }
11419   else
11420     {
11421       TYPE_CODE (type) = TYPE_CODE_CLASS;
11422     }
11423
11424   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11425     TYPE_DECLARED_CLASS (type) = 1;
11426
11427   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11428   if (attr)
11429     {
11430       TYPE_LENGTH (type) = DW_UNSND (attr);
11431     }
11432   else
11433     {
11434       TYPE_LENGTH (type) = 0;
11435     }
11436
11437   if (producer_is_icc (cu))
11438     {
11439       /* ICC does not output the required DW_AT_declaration
11440          on incomplete types, but gives them a size of zero.  */
11441     }
11442   else
11443     TYPE_STUB_SUPPORTED (type) = 1;
11444
11445   if (die_is_declaration (die, cu))
11446     TYPE_STUB (type) = 1;
11447   else if (attr == NULL && die->child == NULL
11448            && producer_is_realview (cu->producer))
11449     /* RealView does not output the required DW_AT_declaration
11450        on incomplete types.  */
11451     TYPE_STUB (type) = 1;
11452
11453   /* We need to add the type field to the die immediately so we don't
11454      infinitely recurse when dealing with pointers to the structure
11455      type within the structure itself.  */
11456   set_die_type (die, type, cu);
11457
11458   /* set_die_type should be already done.  */
11459   set_descriptive_type (type, die, cu);
11460
11461   return type;
11462 }
11463
11464 /* Finish creating a structure or union type, including filling in
11465    its members and creating a symbol for it.  */
11466
11467 static void
11468 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11469 {
11470   struct objfile *objfile = cu->objfile;
11471   struct die_info *child_die = die->child;
11472   struct type *type;
11473
11474   type = get_die_type (die, cu);
11475   if (type == NULL)
11476     type = read_structure_type (die, cu);
11477
11478   if (die->child != NULL && ! die_is_declaration (die, cu))
11479     {
11480       struct field_info fi;
11481       struct die_info *child_die;
11482       VEC (symbolp) *template_args = NULL;
11483       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11484
11485       memset (&fi, 0, sizeof (struct field_info));
11486
11487       child_die = die->child;
11488
11489       while (child_die && child_die->tag)
11490         {
11491           if (child_die->tag == DW_TAG_member
11492               || child_die->tag == DW_TAG_variable)
11493             {
11494               /* NOTE: carlton/2002-11-05: A C++ static data member
11495                  should be a DW_TAG_member that is a declaration, but
11496                  all versions of G++ as of this writing (so through at
11497                  least 3.2.1) incorrectly generate DW_TAG_variable
11498                  tags for them instead.  */
11499               dwarf2_add_field (&fi, child_die, cu);
11500             }
11501           else if (child_die->tag == DW_TAG_subprogram)
11502             {
11503               /* C++ member function.  */
11504               dwarf2_add_member_fn (&fi, child_die, type, cu);
11505             }
11506           else if (child_die->tag == DW_TAG_inheritance)
11507             {
11508               /* C++ base class field.  */
11509               dwarf2_add_field (&fi, child_die, cu);
11510             }
11511           else if (child_die->tag == DW_TAG_typedef)
11512             dwarf2_add_typedef (&fi, child_die, cu);
11513           else if (child_die->tag == DW_TAG_template_type_param
11514                    || child_die->tag == DW_TAG_template_value_param)
11515             {
11516               struct symbol *arg = new_symbol (child_die, NULL, cu);
11517
11518               if (arg != NULL)
11519                 VEC_safe_push (symbolp, template_args, arg);
11520             }
11521
11522           child_die = sibling_die (child_die);
11523         }
11524
11525       /* Attach template arguments to type.  */
11526       if (! VEC_empty (symbolp, template_args))
11527         {
11528           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11529           TYPE_N_TEMPLATE_ARGUMENTS (type)
11530             = VEC_length (symbolp, template_args);
11531           TYPE_TEMPLATE_ARGUMENTS (type)
11532             = obstack_alloc (&objfile->objfile_obstack,
11533                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11534                               * sizeof (struct symbol *)));
11535           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11536                   VEC_address (symbolp, template_args),
11537                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11538                    * sizeof (struct symbol *)));
11539           VEC_free (symbolp, template_args);
11540         }
11541
11542       /* Attach fields and member functions to the type.  */
11543       if (fi.nfields)
11544         dwarf2_attach_fields_to_type (&fi, type, cu);
11545       if (fi.nfnfields)
11546         {
11547           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11548
11549           /* Get the type which refers to the base class (possibly this
11550              class itself) which contains the vtable pointer for the current
11551              class from the DW_AT_containing_type attribute.  This use of
11552              DW_AT_containing_type is a GNU extension.  */
11553
11554           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11555             {
11556               struct type *t = die_containing_type (die, cu);
11557
11558               TYPE_VPTR_BASETYPE (type) = t;
11559               if (type == t)
11560                 {
11561                   int i;
11562
11563                   /* Our own class provides vtbl ptr.  */
11564                   for (i = TYPE_NFIELDS (t) - 1;
11565                        i >= TYPE_N_BASECLASSES (t);
11566                        --i)
11567                     {
11568                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11569
11570                       if (is_vtable_name (fieldname, cu))
11571                         {
11572                           TYPE_VPTR_FIELDNO (type) = i;
11573                           break;
11574                         }
11575                     }
11576
11577                   /* Complain if virtual function table field not found.  */
11578                   if (i < TYPE_N_BASECLASSES (t))
11579                     complaint (&symfile_complaints,
11580                                _("virtual function table pointer "
11581                                  "not found when defining class '%s'"),
11582                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11583                                "");
11584                 }
11585               else
11586                 {
11587                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11588                 }
11589             }
11590           else if (cu->producer
11591                    && strncmp (cu->producer,
11592                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11593             {
11594               /* The IBM XLC compiler does not provide direct indication
11595                  of the containing type, but the vtable pointer is
11596                  always named __vfp.  */
11597
11598               int i;
11599
11600               for (i = TYPE_NFIELDS (type) - 1;
11601                    i >= TYPE_N_BASECLASSES (type);
11602                    --i)
11603                 {
11604                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11605                     {
11606                       TYPE_VPTR_FIELDNO (type) = i;
11607                       TYPE_VPTR_BASETYPE (type) = type;
11608                       break;
11609                     }
11610                 }
11611             }
11612         }
11613
11614       /* Copy fi.typedef_field_list linked list elements content into the
11615          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11616       if (fi.typedef_field_list)
11617         {
11618           int i = fi.typedef_field_list_count;
11619
11620           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11621           TYPE_TYPEDEF_FIELD_ARRAY (type)
11622             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11623           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11624
11625           /* Reverse the list order to keep the debug info elements order.  */
11626           while (--i >= 0)
11627             {
11628               struct typedef_field *dest, *src;
11629
11630               dest = &TYPE_TYPEDEF_FIELD (type, i);
11631               src = &fi.typedef_field_list->field;
11632               fi.typedef_field_list = fi.typedef_field_list->next;
11633               *dest = *src;
11634             }
11635         }
11636
11637       do_cleanups (back_to);
11638
11639       if (HAVE_CPLUS_STRUCT (type))
11640         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11641     }
11642
11643   quirk_gcc_member_function_pointer (type, objfile);
11644
11645   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11646      snapshots) has been known to create a die giving a declaration
11647      for a class that has, as a child, a die giving a definition for a
11648      nested class.  So we have to process our children even if the
11649      current die is a declaration.  Normally, of course, a declaration
11650      won't have any children at all.  */
11651
11652   while (child_die != NULL && child_die->tag)
11653     {
11654       if (child_die->tag == DW_TAG_member
11655           || child_die->tag == DW_TAG_variable
11656           || child_die->tag == DW_TAG_inheritance
11657           || child_die->tag == DW_TAG_template_value_param
11658           || child_die->tag == DW_TAG_template_type_param)
11659         {
11660           /* Do nothing.  */
11661         }
11662       else
11663         process_die (child_die, cu);
11664
11665       child_die = sibling_die (child_die);
11666     }
11667
11668   /* Do not consider external references.  According to the DWARF standard,
11669      these DIEs are identified by the fact that they have no byte_size
11670      attribute, and a declaration attribute.  */
11671   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11672       || !die_is_declaration (die, cu))
11673     new_symbol (die, type, cu);
11674 }
11675
11676 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11677    complete the type's fields yet, or create any symbols.  */
11678
11679 static struct type *
11680 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11681 {
11682   struct objfile *objfile = cu->objfile;
11683   struct type *type;
11684   struct attribute *attr;
11685   const char *name;
11686
11687   /* If the definition of this type lives in .debug_types, read that type.
11688      Don't follow DW_AT_specification though, that will take us back up
11689      the chain and we want to go down.  */
11690   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11691   if (attr)
11692     {
11693       struct dwarf2_cu *type_cu = cu;
11694       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11695
11696       type = read_type_die (type_die, type_cu);
11697
11698       /* TYPE_CU may not be the same as CU.
11699          Ensure TYPE is recorded in CU's type_hash table.  */
11700       return set_die_type (die, type, cu);
11701     }
11702
11703   type = alloc_type (objfile);
11704
11705   TYPE_CODE (type) = TYPE_CODE_ENUM;
11706   name = dwarf2_full_name (NULL, die, cu);
11707   if (name != NULL)
11708     TYPE_TAG_NAME (type) = name;
11709
11710   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11711   if (attr)
11712     {
11713       TYPE_LENGTH (type) = DW_UNSND (attr);
11714     }
11715   else
11716     {
11717       TYPE_LENGTH (type) = 0;
11718     }
11719
11720   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11721      declared as private in the package spec, and then defined only
11722      inside the package body.  Such types are known as Taft Amendment
11723      Types.  When another package uses such a type, an incomplete DIE
11724      may be generated by the compiler.  */
11725   if (die_is_declaration (die, cu))
11726     TYPE_STUB (type) = 1;
11727
11728   return set_die_type (die, type, cu);
11729 }
11730
11731 /* Given a pointer to a die which begins an enumeration, process all
11732    the dies that define the members of the enumeration, and create the
11733    symbol for the enumeration type.
11734
11735    NOTE: We reverse the order of the element list.  */
11736
11737 static void
11738 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11739 {
11740   struct type *this_type;
11741
11742   this_type = get_die_type (die, cu);
11743   if (this_type == NULL)
11744     this_type = read_enumeration_type (die, cu);
11745
11746   if (die->child != NULL)
11747     {
11748       struct die_info *child_die;
11749       struct symbol *sym;
11750       struct field *fields = NULL;
11751       int num_fields = 0;
11752       int unsigned_enum = 1;
11753       const char *name;
11754       int flag_enum = 1;
11755       ULONGEST mask = 0;
11756
11757       child_die = die->child;
11758       while (child_die && child_die->tag)
11759         {
11760           if (child_die->tag != DW_TAG_enumerator)
11761             {
11762               process_die (child_die, cu);
11763             }
11764           else
11765             {
11766               name = dwarf2_name (child_die, cu);
11767               if (name)
11768                 {
11769                   sym = new_symbol (child_die, this_type, cu);
11770                   if (SYMBOL_VALUE (sym) < 0)
11771                     {
11772                       unsigned_enum = 0;
11773                       flag_enum = 0;
11774                     }
11775                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11776                     flag_enum = 0;
11777                   else
11778                     mask |= SYMBOL_VALUE (sym);
11779
11780                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11781                     {
11782                       fields = (struct field *)
11783                         xrealloc (fields,
11784                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11785                                   * sizeof (struct field));
11786                     }
11787
11788                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11789                   FIELD_TYPE (fields[num_fields]) = NULL;
11790                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11791                   FIELD_BITSIZE (fields[num_fields]) = 0;
11792
11793                   num_fields++;
11794                 }
11795             }
11796
11797           child_die = sibling_die (child_die);
11798         }
11799
11800       if (num_fields)
11801         {
11802           TYPE_NFIELDS (this_type) = num_fields;
11803           TYPE_FIELDS (this_type) = (struct field *)
11804             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11805           memcpy (TYPE_FIELDS (this_type), fields,
11806                   sizeof (struct field) * num_fields);
11807           xfree (fields);
11808         }
11809       if (unsigned_enum)
11810         TYPE_UNSIGNED (this_type) = 1;
11811       if (flag_enum)
11812         TYPE_FLAG_ENUM (this_type) = 1;
11813     }
11814
11815   /* If we are reading an enum from a .debug_types unit, and the enum
11816      is a declaration, and the enum is not the signatured type in the
11817      unit, then we do not want to add a symbol for it.  Adding a
11818      symbol would in some cases obscure the true definition of the
11819      enum, giving users an incomplete type when the definition is
11820      actually available.  Note that we do not want to do this for all
11821      enums which are just declarations, because C++0x allows forward
11822      enum declarations.  */
11823   if (cu->per_cu->is_debug_types
11824       && die_is_declaration (die, cu))
11825     {
11826       struct signatured_type *sig_type;
11827
11828       sig_type
11829         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
11830                                             cu->per_cu->section,
11831                                             cu->per_cu->offset);
11832       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11833       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11834         return;
11835     }
11836
11837   new_symbol (die, this_type, cu);
11838 }
11839
11840 /* Extract all information from a DW_TAG_array_type DIE and put it in
11841    the DIE's type field.  For now, this only handles one dimensional
11842    arrays.  */
11843
11844 static struct type *
11845 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11846 {
11847   struct objfile *objfile = cu->objfile;
11848   struct die_info *child_die;
11849   struct type *type;
11850   struct type *element_type, *range_type, *index_type;
11851   struct type **range_types = NULL;
11852   struct attribute *attr;
11853   int ndim = 0;
11854   struct cleanup *back_to;
11855   const char *name;
11856
11857   element_type = die_type (die, cu);
11858
11859   /* The die_type call above may have already set the type for this DIE.  */
11860   type = get_die_type (die, cu);
11861   if (type)
11862     return type;
11863
11864   /* Irix 6.2 native cc creates array types without children for
11865      arrays with unspecified length.  */
11866   if (die->child == NULL)
11867     {
11868       index_type = objfile_type (objfile)->builtin_int;
11869       range_type = create_range_type (NULL, index_type, 0, -1);
11870       type = create_array_type (NULL, element_type, range_type);
11871       return set_die_type (die, type, cu);
11872     }
11873
11874   back_to = make_cleanup (null_cleanup, NULL);
11875   child_die = die->child;
11876   while (child_die && child_die->tag)
11877     {
11878       if (child_die->tag == DW_TAG_subrange_type)
11879         {
11880           struct type *child_type = read_type_die (child_die, cu);
11881
11882           if (child_type != NULL)
11883             {
11884               /* The range type was succesfully read.  Save it for the
11885                  array type creation.  */
11886               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11887                 {
11888                   range_types = (struct type **)
11889                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11890                               * sizeof (struct type *));
11891                   if (ndim == 0)
11892                     make_cleanup (free_current_contents, &range_types);
11893                 }
11894               range_types[ndim++] = child_type;
11895             }
11896         }
11897       child_die = sibling_die (child_die);
11898     }
11899
11900   /* Dwarf2 dimensions are output from left to right, create the
11901      necessary array types in backwards order.  */
11902
11903   type = element_type;
11904
11905   if (read_array_order (die, cu) == DW_ORD_col_major)
11906     {
11907       int i = 0;
11908
11909       while (i < ndim)
11910         type = create_array_type (NULL, type, range_types[i++]);
11911     }
11912   else
11913     {
11914       while (ndim-- > 0)
11915         type = create_array_type (NULL, type, range_types[ndim]);
11916     }
11917
11918   /* Understand Dwarf2 support for vector types (like they occur on
11919      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11920      array type.  This is not part of the Dwarf2/3 standard yet, but a
11921      custom vendor extension.  The main difference between a regular
11922      array and the vector variant is that vectors are passed by value
11923      to functions.  */
11924   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11925   if (attr)
11926     make_vector_type (type);
11927
11928   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11929      implementation may choose to implement triple vectors using this
11930      attribute.  */
11931   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11932   if (attr)
11933     {
11934       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11935         TYPE_LENGTH (type) = DW_UNSND (attr);
11936       else
11937         complaint (&symfile_complaints,
11938                    _("DW_AT_byte_size for array type smaller "
11939                      "than the total size of elements"));
11940     }
11941
11942   name = dwarf2_name (die, cu);
11943   if (name)
11944     TYPE_NAME (type) = name;
11945
11946   /* Install the type in the die.  */
11947   set_die_type (die, type, cu);
11948
11949   /* set_die_type should be already done.  */
11950   set_descriptive_type (type, die, cu);
11951
11952   do_cleanups (back_to);
11953
11954   return type;
11955 }
11956
11957 static enum dwarf_array_dim_ordering
11958 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11959 {
11960   struct attribute *attr;
11961
11962   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11963
11964   if (attr) return DW_SND (attr);
11965
11966   /* GNU F77 is a special case, as at 08/2004 array type info is the
11967      opposite order to the dwarf2 specification, but data is still
11968      laid out as per normal fortran.
11969
11970      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11971      version checking.  */
11972
11973   if (cu->language == language_fortran
11974       && cu->producer && strstr (cu->producer, "GNU F77"))
11975     {
11976       return DW_ORD_row_major;
11977     }
11978
11979   switch (cu->language_defn->la_array_ordering)
11980     {
11981     case array_column_major:
11982       return DW_ORD_col_major;
11983     case array_row_major:
11984     default:
11985       return DW_ORD_row_major;
11986     };
11987 }
11988
11989 /* Extract all information from a DW_TAG_set_type DIE and put it in
11990    the DIE's type field.  */
11991
11992 static struct type *
11993 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11994 {
11995   struct type *domain_type, *set_type;
11996   struct attribute *attr;
11997
11998   domain_type = die_type (die, cu);
11999
12000   /* The die_type call above may have already set the type for this DIE.  */
12001   set_type = get_die_type (die, cu);
12002   if (set_type)
12003     return set_type;
12004
12005   set_type = create_set_type (NULL, domain_type);
12006
12007   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12008   if (attr)
12009     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12010
12011   return set_die_type (die, set_type, cu);
12012 }
12013
12014 /* A helper for read_common_block that creates a locexpr baton.
12015    SYM is the symbol which we are marking as computed.
12016    COMMON_DIE is the DIE for the common block.
12017    COMMON_LOC is the location expression attribute for the common
12018    block itself.
12019    MEMBER_LOC is the location expression attribute for the particular
12020    member of the common block that we are processing.
12021    CU is the CU from which the above come.  */
12022
12023 static void
12024 mark_common_block_symbol_computed (struct symbol *sym,
12025                                    struct die_info *common_die,
12026                                    struct attribute *common_loc,
12027                                    struct attribute *member_loc,
12028                                    struct dwarf2_cu *cu)
12029 {
12030   struct objfile *objfile = dwarf2_per_objfile->objfile;
12031   struct dwarf2_locexpr_baton *baton;
12032   gdb_byte *ptr;
12033   unsigned int cu_off;
12034   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12035   LONGEST offset = 0;
12036
12037   gdb_assert (common_loc && member_loc);
12038   gdb_assert (attr_form_is_block (common_loc));
12039   gdb_assert (attr_form_is_block (member_loc)
12040               || attr_form_is_constant (member_loc));
12041
12042   baton = obstack_alloc (&objfile->objfile_obstack,
12043                          sizeof (struct dwarf2_locexpr_baton));
12044   baton->per_cu = cu->per_cu;
12045   gdb_assert (baton->per_cu);
12046
12047   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12048
12049   if (attr_form_is_constant (member_loc))
12050     {
12051       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12052       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12053     }
12054   else
12055     baton->size += DW_BLOCK (member_loc)->size;
12056
12057   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12058   baton->data = ptr;
12059
12060   *ptr++ = DW_OP_call4;
12061   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12062   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12063   ptr += 4;
12064
12065   if (attr_form_is_constant (member_loc))
12066     {
12067       *ptr++ = DW_OP_addr;
12068       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12069       ptr += cu->header.addr_size;
12070     }
12071   else
12072     {
12073       /* We have to copy the data here, because DW_OP_call4 will only
12074          use a DW_AT_location attribute.  */
12075       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12076       ptr += DW_BLOCK (member_loc)->size;
12077     }
12078
12079   *ptr++ = DW_OP_plus;
12080   gdb_assert (ptr - baton->data == baton->size);
12081
12082   SYMBOL_LOCATION_BATON (sym) = baton;
12083   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12084 }
12085
12086 /* Create appropriate locally-scoped variables for all the
12087    DW_TAG_common_block entries.  Also create a struct common_block
12088    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12089    is used to sepate the common blocks name namespace from regular
12090    variable names.  */
12091
12092 static void
12093 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12094 {
12095   struct attribute *attr;
12096
12097   attr = dwarf2_attr (die, DW_AT_location, cu);
12098   if (attr)
12099     {
12100       /* Support the .debug_loc offsets.  */
12101       if (attr_form_is_block (attr))
12102         {
12103           /* Ok.  */
12104         }
12105       else if (attr_form_is_section_offset (attr))
12106         {
12107           dwarf2_complex_location_expr_complaint ();
12108           attr = NULL;
12109         }
12110       else
12111         {
12112           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12113                                                  "common block member");
12114           attr = NULL;
12115         }
12116     }
12117
12118   if (die->child != NULL)
12119     {
12120       struct objfile *objfile = cu->objfile;
12121       struct die_info *child_die;
12122       size_t n_entries = 0, size;
12123       struct common_block *common_block;
12124       struct symbol *sym;
12125
12126       for (child_die = die->child;
12127            child_die && child_die->tag;
12128            child_die = sibling_die (child_die))
12129         ++n_entries;
12130
12131       size = (sizeof (struct common_block)
12132               + (n_entries - 1) * sizeof (struct symbol *));
12133       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12134       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12135       common_block->n_entries = 0;
12136
12137       for (child_die = die->child;
12138            child_die && child_die->tag;
12139            child_die = sibling_die (child_die))
12140         {
12141           /* Create the symbol in the DW_TAG_common_block block in the current
12142              symbol scope.  */
12143           sym = new_symbol (child_die, NULL, cu);
12144           if (sym != NULL)
12145             {
12146               struct attribute *member_loc;
12147
12148               common_block->contents[common_block->n_entries++] = sym;
12149
12150               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12151                                         cu);
12152               if (member_loc)
12153                 {
12154                   /* GDB has handled this for a long time, but it is
12155                      not specified by DWARF.  It seems to have been
12156                      emitted by gfortran at least as recently as:
12157                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12158                   complaint (&symfile_complaints,
12159                              _("Variable in common block has "
12160                                "DW_AT_data_member_location "
12161                                "- DIE at 0x%x [in module %s]"),
12162                              child_die->offset.sect_off, cu->objfile->name);
12163
12164                   if (attr_form_is_section_offset (member_loc))
12165                     dwarf2_complex_location_expr_complaint ();
12166                   else if (attr_form_is_constant (member_loc)
12167                            || attr_form_is_block (member_loc))
12168                     {
12169                       if (attr)
12170                         mark_common_block_symbol_computed (sym, die, attr,
12171                                                            member_loc, cu);
12172                     }
12173                   else
12174                     dwarf2_complex_location_expr_complaint ();
12175                 }
12176             }
12177         }
12178
12179       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12180       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12181     }
12182 }
12183
12184 /* Create a type for a C++ namespace.  */
12185
12186 static struct type *
12187 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12188 {
12189   struct objfile *objfile = cu->objfile;
12190   const char *previous_prefix, *name;
12191   int is_anonymous;
12192   struct type *type;
12193
12194   /* For extensions, reuse the type of the original namespace.  */
12195   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12196     {
12197       struct die_info *ext_die;
12198       struct dwarf2_cu *ext_cu = cu;
12199
12200       ext_die = dwarf2_extension (die, &ext_cu);
12201       type = read_type_die (ext_die, ext_cu);
12202
12203       /* EXT_CU may not be the same as CU.
12204          Ensure TYPE is recorded in CU's type_hash table.  */
12205       return set_die_type (die, type, cu);
12206     }
12207
12208   name = namespace_name (die, &is_anonymous, cu);
12209
12210   /* Now build the name of the current namespace.  */
12211
12212   previous_prefix = determine_prefix (die, cu);
12213   if (previous_prefix[0] != '\0')
12214     name = typename_concat (&objfile->objfile_obstack,
12215                             previous_prefix, name, 0, cu);
12216
12217   /* Create the type.  */
12218   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12219                     objfile);
12220   TYPE_NAME (type) = name;
12221   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12222
12223   return set_die_type (die, type, cu);
12224 }
12225
12226 /* Read a C++ namespace.  */
12227
12228 static void
12229 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12230 {
12231   struct objfile *objfile = cu->objfile;
12232   int is_anonymous;
12233
12234   /* Add a symbol associated to this if we haven't seen the namespace
12235      before.  Also, add a using directive if it's an anonymous
12236      namespace.  */
12237
12238   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12239     {
12240       struct type *type;
12241
12242       type = read_type_die (die, cu);
12243       new_symbol (die, type, cu);
12244
12245       namespace_name (die, &is_anonymous, cu);
12246       if (is_anonymous)
12247         {
12248           const char *previous_prefix = determine_prefix (die, cu);
12249
12250           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12251                                   NULL, NULL, 0, &objfile->objfile_obstack);
12252         }
12253     }
12254
12255   if (die->child != NULL)
12256     {
12257       struct die_info *child_die = die->child;
12258
12259       while (child_die && child_die->tag)
12260         {
12261           process_die (child_die, cu);
12262           child_die = sibling_die (child_die);
12263         }
12264     }
12265 }
12266
12267 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12268    imported module.  Still we need that type as local Fortran "use ... only"
12269    declaration imports depend on the created type in determine_prefix.  */
12270
12271 static struct type *
12272 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12273 {
12274   struct objfile *objfile = cu->objfile;
12275   const char *module_name;
12276   struct type *type;
12277
12278   module_name = dwarf2_name (die, cu);
12279   if (!module_name)
12280     complaint (&symfile_complaints,
12281                _("DW_TAG_module has no name, offset 0x%x"),
12282                die->offset.sect_off);
12283   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12284
12285   /* determine_prefix uses TYPE_TAG_NAME.  */
12286   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12287
12288   return set_die_type (die, type, cu);
12289 }
12290
12291 /* Read a Fortran module.  */
12292
12293 static void
12294 read_module (struct die_info *die, struct dwarf2_cu *cu)
12295 {
12296   struct die_info *child_die = die->child;
12297
12298   while (child_die && child_die->tag)
12299     {
12300       process_die (child_die, cu);
12301       child_die = sibling_die (child_die);
12302     }
12303 }
12304
12305 /* Return the name of the namespace represented by DIE.  Set
12306    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12307    namespace.  */
12308
12309 static const char *
12310 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12311 {
12312   struct die_info *current_die;
12313   const char *name = NULL;
12314
12315   /* Loop through the extensions until we find a name.  */
12316
12317   for (current_die = die;
12318        current_die != NULL;
12319        current_die = dwarf2_extension (die, &cu))
12320     {
12321       name = dwarf2_name (current_die, cu);
12322       if (name != NULL)
12323         break;
12324     }
12325
12326   /* Is it an anonymous namespace?  */
12327
12328   *is_anonymous = (name == NULL);
12329   if (*is_anonymous)
12330     name = CP_ANONYMOUS_NAMESPACE_STR;
12331
12332   return name;
12333 }
12334
12335 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12336    the user defined type vector.  */
12337
12338 static struct type *
12339 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12340 {
12341   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12342   struct comp_unit_head *cu_header = &cu->header;
12343   struct type *type;
12344   struct attribute *attr_byte_size;
12345   struct attribute *attr_address_class;
12346   int byte_size, addr_class;
12347   struct type *target_type;
12348
12349   target_type = die_type (die, cu);
12350
12351   /* The die_type call above may have already set the type for this DIE.  */
12352   type = get_die_type (die, cu);
12353   if (type)
12354     return type;
12355
12356   type = lookup_pointer_type (target_type);
12357
12358   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12359   if (attr_byte_size)
12360     byte_size = DW_UNSND (attr_byte_size);
12361   else
12362     byte_size = cu_header->addr_size;
12363
12364   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12365   if (attr_address_class)
12366     addr_class = DW_UNSND (attr_address_class);
12367   else
12368     addr_class = DW_ADDR_none;
12369
12370   /* If the pointer size or address class is different than the
12371      default, create a type variant marked as such and set the
12372      length accordingly.  */
12373   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12374     {
12375       if (gdbarch_address_class_type_flags_p (gdbarch))
12376         {
12377           int type_flags;
12378
12379           type_flags = gdbarch_address_class_type_flags
12380                          (gdbarch, byte_size, addr_class);
12381           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12382                       == 0);
12383           type = make_type_with_address_space (type, type_flags);
12384         }
12385       else if (TYPE_LENGTH (type) != byte_size)
12386         {
12387           complaint (&symfile_complaints,
12388                      _("invalid pointer size %d"), byte_size);
12389         }
12390       else
12391         {
12392           /* Should we also complain about unhandled address classes?  */
12393         }
12394     }
12395
12396   TYPE_LENGTH (type) = byte_size;
12397   return set_die_type (die, type, cu);
12398 }
12399
12400 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12401    the user defined type vector.  */
12402
12403 static struct type *
12404 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12405 {
12406   struct type *type;
12407   struct type *to_type;
12408   struct type *domain;
12409
12410   to_type = die_type (die, cu);
12411   domain = die_containing_type (die, cu);
12412
12413   /* The calls above may have already set the type for this DIE.  */
12414   type = get_die_type (die, cu);
12415   if (type)
12416     return type;
12417
12418   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12419     type = lookup_methodptr_type (to_type);
12420   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12421     {
12422       struct type *new_type = alloc_type (cu->objfile);
12423
12424       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12425                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12426                             TYPE_VARARGS (to_type));
12427       type = lookup_methodptr_type (new_type);
12428     }
12429   else
12430     type = lookup_memberptr_type (to_type, domain);
12431
12432   return set_die_type (die, type, cu);
12433 }
12434
12435 /* Extract all information from a DW_TAG_reference_type DIE and add to
12436    the user defined type vector.  */
12437
12438 static struct type *
12439 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12440 {
12441   struct comp_unit_head *cu_header = &cu->header;
12442   struct type *type, *target_type;
12443   struct attribute *attr;
12444
12445   target_type = die_type (die, cu);
12446
12447   /* The die_type call above may have already set the type for this DIE.  */
12448   type = get_die_type (die, cu);
12449   if (type)
12450     return type;
12451
12452   type = lookup_reference_type (target_type);
12453   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12454   if (attr)
12455     {
12456       TYPE_LENGTH (type) = DW_UNSND (attr);
12457     }
12458   else
12459     {
12460       TYPE_LENGTH (type) = cu_header->addr_size;
12461     }
12462   return set_die_type (die, type, cu);
12463 }
12464
12465 static struct type *
12466 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12467 {
12468   struct type *base_type, *cv_type;
12469
12470   base_type = die_type (die, cu);
12471
12472   /* The die_type call above may have already set the type for this DIE.  */
12473   cv_type = get_die_type (die, cu);
12474   if (cv_type)
12475     return cv_type;
12476
12477   /* In case the const qualifier is applied to an array type, the element type
12478      is so qualified, not the array type (section 6.7.3 of C99).  */
12479   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12480     {
12481       struct type *el_type, *inner_array;
12482
12483       base_type = copy_type (base_type);
12484       inner_array = base_type;
12485
12486       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12487         {
12488           TYPE_TARGET_TYPE (inner_array) =
12489             copy_type (TYPE_TARGET_TYPE (inner_array));
12490           inner_array = TYPE_TARGET_TYPE (inner_array);
12491         }
12492
12493       el_type = TYPE_TARGET_TYPE (inner_array);
12494       TYPE_TARGET_TYPE (inner_array) =
12495         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12496
12497       return set_die_type (die, base_type, cu);
12498     }
12499
12500   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12501   return set_die_type (die, cv_type, cu);
12502 }
12503
12504 static struct type *
12505 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12506 {
12507   struct type *base_type, *cv_type;
12508
12509   base_type = die_type (die, cu);
12510
12511   /* The die_type call above may have already set the type for this DIE.  */
12512   cv_type = get_die_type (die, cu);
12513   if (cv_type)
12514     return cv_type;
12515
12516   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12517   return set_die_type (die, cv_type, cu);
12518 }
12519
12520 /* Handle DW_TAG_restrict_type.  */
12521
12522 static struct type *
12523 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12524 {
12525   struct type *base_type, *cv_type;
12526
12527   base_type = die_type (die, cu);
12528
12529   /* The die_type call above may have already set the type for this DIE.  */
12530   cv_type = get_die_type (die, cu);
12531   if (cv_type)
12532     return cv_type;
12533
12534   cv_type = make_restrict_type (base_type);
12535   return set_die_type (die, cv_type, cu);
12536 }
12537
12538 /* Extract all information from a DW_TAG_string_type DIE and add to
12539    the user defined type vector.  It isn't really a user defined type,
12540    but it behaves like one, with other DIE's using an AT_user_def_type
12541    attribute to reference it.  */
12542
12543 static struct type *
12544 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12545 {
12546   struct objfile *objfile = cu->objfile;
12547   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12548   struct type *type, *range_type, *index_type, *char_type;
12549   struct attribute *attr;
12550   unsigned int length;
12551
12552   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12553   if (attr)
12554     {
12555       length = DW_UNSND (attr);
12556     }
12557   else
12558     {
12559       /* Check for the DW_AT_byte_size attribute.  */
12560       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12561       if (attr)
12562         {
12563           length = DW_UNSND (attr);
12564         }
12565       else
12566         {
12567           length = 1;
12568         }
12569     }
12570
12571   index_type = objfile_type (objfile)->builtin_int;
12572   range_type = create_range_type (NULL, index_type, 1, length);
12573   char_type = language_string_char_type (cu->language_defn, gdbarch);
12574   type = create_string_type (NULL, char_type, range_type);
12575
12576   return set_die_type (die, type, cu);
12577 }
12578
12579 /* Handle DIES due to C code like:
12580
12581    struct foo
12582    {
12583    int (*funcp)(int a, long l);
12584    int b;
12585    };
12586
12587    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12588
12589 static struct type *
12590 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12591 {
12592   struct objfile *objfile = cu->objfile;
12593   struct type *type;            /* Type that this function returns.  */
12594   struct type *ftype;           /* Function that returns above type.  */
12595   struct attribute *attr;
12596
12597   type = die_type (die, cu);
12598
12599   /* The die_type call above may have already set the type for this DIE.  */
12600   ftype = get_die_type (die, cu);
12601   if (ftype)
12602     return ftype;
12603
12604   ftype = lookup_function_type (type);
12605
12606   /* All functions in C++, Pascal and Java have prototypes.  */
12607   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12608   if ((attr && (DW_UNSND (attr) != 0))
12609       || cu->language == language_cplus
12610       || cu->language == language_java
12611       || cu->language == language_pascal)
12612     TYPE_PROTOTYPED (ftype) = 1;
12613   else if (producer_is_realview (cu->producer))
12614     /* RealView does not emit DW_AT_prototyped.  We can not
12615        distinguish prototyped and unprototyped functions; default to
12616        prototyped, since that is more common in modern code (and
12617        RealView warns about unprototyped functions).  */
12618     TYPE_PROTOTYPED (ftype) = 1;
12619
12620   /* Store the calling convention in the type if it's available in
12621      the subroutine die.  Otherwise set the calling convention to
12622      the default value DW_CC_normal.  */
12623   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12624   if (attr)
12625     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12626   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12627     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12628   else
12629     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12630
12631   /* We need to add the subroutine type to the die immediately so
12632      we don't infinitely recurse when dealing with parameters
12633      declared as the same subroutine type.  */
12634   set_die_type (die, ftype, cu);
12635
12636   if (die->child != NULL)
12637     {
12638       struct type *void_type = objfile_type (objfile)->builtin_void;
12639       struct die_info *child_die;
12640       int nparams, iparams;
12641
12642       /* Count the number of parameters.
12643          FIXME: GDB currently ignores vararg functions, but knows about
12644          vararg member functions.  */
12645       nparams = 0;
12646       child_die = die->child;
12647       while (child_die && child_die->tag)
12648         {
12649           if (child_die->tag == DW_TAG_formal_parameter)
12650             nparams++;
12651           else if (child_die->tag == DW_TAG_unspecified_parameters)
12652             TYPE_VARARGS (ftype) = 1;
12653           child_die = sibling_die (child_die);
12654         }
12655
12656       /* Allocate storage for parameters and fill them in.  */
12657       TYPE_NFIELDS (ftype) = nparams;
12658       TYPE_FIELDS (ftype) = (struct field *)
12659         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12660
12661       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12662          even if we error out during the parameters reading below.  */
12663       for (iparams = 0; iparams < nparams; iparams++)
12664         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12665
12666       iparams = 0;
12667       child_die = die->child;
12668       while (child_die && child_die->tag)
12669         {
12670           if (child_die->tag == DW_TAG_formal_parameter)
12671             {
12672               struct type *arg_type;
12673
12674               /* DWARF version 2 has no clean way to discern C++
12675                  static and non-static member functions.  G++ helps
12676                  GDB by marking the first parameter for non-static
12677                  member functions (which is the this pointer) as
12678                  artificial.  We pass this information to
12679                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12680
12681                  DWARF version 3 added DW_AT_object_pointer, which GCC
12682                  4.5 does not yet generate.  */
12683               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12684               if (attr)
12685                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12686               else
12687                 {
12688                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12689
12690                   /* GCC/43521: In java, the formal parameter
12691                      "this" is sometimes not marked with DW_AT_artificial.  */
12692                   if (cu->language == language_java)
12693                     {
12694                       const char *name = dwarf2_name (child_die, cu);
12695
12696                       if (name && !strcmp (name, "this"))
12697                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12698                     }
12699                 }
12700               arg_type = die_type (child_die, cu);
12701
12702               /* RealView does not mark THIS as const, which the testsuite
12703                  expects.  GCC marks THIS as const in method definitions,
12704                  but not in the class specifications (GCC PR 43053).  */
12705               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12706                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12707                 {
12708                   int is_this = 0;
12709                   struct dwarf2_cu *arg_cu = cu;
12710                   const char *name = dwarf2_name (child_die, cu);
12711
12712                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12713                   if (attr)
12714                     {
12715                       /* If the compiler emits this, use it.  */
12716                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12717                         is_this = 1;
12718                     }
12719                   else if (name && strcmp (name, "this") == 0)
12720                     /* Function definitions will have the argument names.  */
12721                     is_this = 1;
12722                   else if (name == NULL && iparams == 0)
12723                     /* Declarations may not have the names, so like
12724                        elsewhere in GDB, assume an artificial first
12725                        argument is "this".  */
12726                     is_this = 1;
12727
12728                   if (is_this)
12729                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12730                                              arg_type, 0);
12731                 }
12732
12733               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12734               iparams++;
12735             }
12736           child_die = sibling_die (child_die);
12737         }
12738     }
12739
12740   return ftype;
12741 }
12742
12743 static struct type *
12744 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12745 {
12746   struct objfile *objfile = cu->objfile;
12747   const char *name = NULL;
12748   struct type *this_type, *target_type;
12749
12750   name = dwarf2_full_name (NULL, die, cu);
12751   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12752                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12753   TYPE_NAME (this_type) = name;
12754   set_die_type (die, this_type, cu);
12755   target_type = die_type (die, cu);
12756   if (target_type != this_type)
12757     TYPE_TARGET_TYPE (this_type) = target_type;
12758   else
12759     {
12760       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12761          spec and cause infinite loops in GDB.  */
12762       complaint (&symfile_complaints,
12763                  _("Self-referential DW_TAG_typedef "
12764                    "- DIE at 0x%x [in module %s]"),
12765                  die->offset.sect_off, objfile->name);
12766       TYPE_TARGET_TYPE (this_type) = NULL;
12767     }
12768   return this_type;
12769 }
12770
12771 /* Find a representation of a given base type and install
12772    it in the TYPE field of the die.  */
12773
12774 static struct type *
12775 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12776 {
12777   struct objfile *objfile = cu->objfile;
12778   struct type *type;
12779   struct attribute *attr;
12780   int encoding = 0, size = 0;
12781   const char *name;
12782   enum type_code code = TYPE_CODE_INT;
12783   int type_flags = 0;
12784   struct type *target_type = NULL;
12785
12786   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12787   if (attr)
12788     {
12789       encoding = DW_UNSND (attr);
12790     }
12791   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12792   if (attr)
12793     {
12794       size = DW_UNSND (attr);
12795     }
12796   name = dwarf2_name (die, cu);
12797   if (!name)
12798     {
12799       complaint (&symfile_complaints,
12800                  _("DW_AT_name missing from DW_TAG_base_type"));
12801     }
12802
12803   switch (encoding)
12804     {
12805       case DW_ATE_address:
12806         /* Turn DW_ATE_address into a void * pointer.  */
12807         code = TYPE_CODE_PTR;
12808         type_flags |= TYPE_FLAG_UNSIGNED;
12809         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12810         break;
12811       case DW_ATE_boolean:
12812         code = TYPE_CODE_BOOL;
12813         type_flags |= TYPE_FLAG_UNSIGNED;
12814         break;
12815       case DW_ATE_complex_float:
12816         code = TYPE_CODE_COMPLEX;
12817         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12818         break;
12819       case DW_ATE_decimal_float:
12820         code = TYPE_CODE_DECFLOAT;
12821         break;
12822       case DW_ATE_float:
12823         code = TYPE_CODE_FLT;
12824         break;
12825       case DW_ATE_signed:
12826         break;
12827       case DW_ATE_unsigned:
12828         type_flags |= TYPE_FLAG_UNSIGNED;
12829         if (cu->language == language_fortran
12830             && name
12831             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12832           code = TYPE_CODE_CHAR;
12833         break;
12834       case DW_ATE_signed_char:
12835         if (cu->language == language_ada || cu->language == language_m2
12836             || cu->language == language_pascal
12837             || cu->language == language_fortran)
12838           code = TYPE_CODE_CHAR;
12839         break;
12840       case DW_ATE_unsigned_char:
12841         if (cu->language == language_ada || cu->language == language_m2
12842             || cu->language == language_pascal
12843             || cu->language == language_fortran)
12844           code = TYPE_CODE_CHAR;
12845         type_flags |= TYPE_FLAG_UNSIGNED;
12846         break;
12847       case DW_ATE_UTF:
12848         /* We just treat this as an integer and then recognize the
12849            type by name elsewhere.  */
12850         break;
12851
12852       default:
12853         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12854                    dwarf_type_encoding_name (encoding));
12855         break;
12856     }
12857
12858   type = init_type (code, size, type_flags, NULL, objfile);
12859   TYPE_NAME (type) = name;
12860   TYPE_TARGET_TYPE (type) = target_type;
12861
12862   if (name && strcmp (name, "char") == 0)
12863     TYPE_NOSIGN (type) = 1;
12864
12865   return set_die_type (die, type, cu);
12866 }
12867
12868 /* Read the given DW_AT_subrange DIE.  */
12869
12870 static struct type *
12871 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12872 {
12873   struct type *base_type, *orig_base_type;
12874   struct type *range_type;
12875   struct attribute *attr;
12876   LONGEST low, high;
12877   int low_default_is_valid;
12878   const char *name;
12879   LONGEST negative_mask;
12880
12881   orig_base_type = die_type (die, cu);
12882   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
12883      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
12884      creating the range type, but we use the result of check_typedef
12885      when examining properties of the type.  */
12886   base_type = check_typedef (orig_base_type);
12887
12888   /* The die_type call above may have already set the type for this DIE.  */
12889   range_type = get_die_type (die, cu);
12890   if (range_type)
12891     return range_type;
12892
12893   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12894      omitting DW_AT_lower_bound.  */
12895   switch (cu->language)
12896     {
12897     case language_c:
12898     case language_cplus:
12899       low = 0;
12900       low_default_is_valid = 1;
12901       break;
12902     case language_fortran:
12903       low = 1;
12904       low_default_is_valid = 1;
12905       break;
12906     case language_d:
12907     case language_java:
12908     case language_objc:
12909       low = 0;
12910       low_default_is_valid = (cu->header.version >= 4);
12911       break;
12912     case language_ada:
12913     case language_m2:
12914     case language_pascal:
12915       low = 1;
12916       low_default_is_valid = (cu->header.version >= 4);
12917       break;
12918     default:
12919       low = 0;
12920       low_default_is_valid = 0;
12921       break;
12922     }
12923
12924   /* FIXME: For variable sized arrays either of these could be
12925      a variable rather than a constant value.  We'll allow it,
12926      but we don't know how to handle it.  */
12927   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12928   if (attr)
12929     low = dwarf2_get_attr_constant_value (attr, low);
12930   else if (!low_default_is_valid)
12931     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12932                                       "- DIE at 0x%x [in module %s]"),
12933                die->offset.sect_off, cu->objfile->name);
12934
12935   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12936   if (attr)
12937     {
12938       if (attr_form_is_block (attr) || is_ref_attr (attr))
12939         {
12940           /* GCC encodes arrays with unspecified or dynamic length
12941              with a DW_FORM_block1 attribute or a reference attribute.
12942              FIXME: GDB does not yet know how to handle dynamic
12943              arrays properly, treat them as arrays with unspecified
12944              length for now.
12945
12946              FIXME: jimb/2003-09-22: GDB does not really know
12947              how to handle arrays of unspecified length
12948              either; we just represent them as zero-length
12949              arrays.  Choose an appropriate upper bound given
12950              the lower bound we've computed above.  */
12951           high = low - 1;
12952         }
12953       else
12954         high = dwarf2_get_attr_constant_value (attr, 1);
12955     }
12956   else
12957     {
12958       attr = dwarf2_attr (die, DW_AT_count, cu);
12959       if (attr)
12960         {
12961           int count = dwarf2_get_attr_constant_value (attr, 1);
12962           high = low + count - 1;
12963         }
12964       else
12965         {
12966           /* Unspecified array length.  */
12967           high = low - 1;
12968         }
12969     }
12970
12971   /* Dwarf-2 specifications explicitly allows to create subrange types
12972      without specifying a base type.
12973      In that case, the base type must be set to the type of
12974      the lower bound, upper bound or count, in that order, if any of these
12975      three attributes references an object that has a type.
12976      If no base type is found, the Dwarf-2 specifications say that
12977      a signed integer type of size equal to the size of an address should
12978      be used.
12979      For the following C code: `extern char gdb_int [];'
12980      GCC produces an empty range DIE.
12981      FIXME: muller/2010-05-28: Possible references to object for low bound,
12982      high bound or count are not yet handled by this code.  */
12983   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12984     {
12985       struct objfile *objfile = cu->objfile;
12986       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12987       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12988       struct type *int_type = objfile_type (objfile)->builtin_int;
12989
12990       /* Test "int", "long int", and "long long int" objfile types,
12991          and select the first one having a size above or equal to the
12992          architecture address size.  */
12993       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12994         base_type = int_type;
12995       else
12996         {
12997           int_type = objfile_type (objfile)->builtin_long;
12998           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12999             base_type = int_type;
13000           else
13001             {
13002               int_type = objfile_type (objfile)->builtin_long_long;
13003               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13004                 base_type = int_type;
13005             }
13006         }
13007     }
13008
13009   negative_mask =
13010     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13011   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13012     low |= negative_mask;
13013   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13014     high |= negative_mask;
13015
13016   range_type = create_range_type (NULL, orig_base_type, low, high);
13017
13018   /* Mark arrays with dynamic length at least as an array of unspecified
13019      length.  GDB could check the boundary but before it gets implemented at
13020      least allow accessing the array elements.  */
13021   if (attr && attr_form_is_block (attr))
13022     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13023
13024   /* Ada expects an empty array on no boundary attributes.  */
13025   if (attr == NULL && cu->language != language_ada)
13026     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13027
13028   name = dwarf2_name (die, cu);
13029   if (name)
13030     TYPE_NAME (range_type) = name;
13031
13032   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13033   if (attr)
13034     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13035
13036   set_die_type (die, range_type, cu);
13037
13038   /* set_die_type should be already done.  */
13039   set_descriptive_type (range_type, die, cu);
13040
13041   return range_type;
13042 }
13043
13044 static struct type *
13045 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13046 {
13047   struct type *type;
13048
13049   /* For now, we only support the C meaning of an unspecified type: void.  */
13050
13051   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13052   TYPE_NAME (type) = dwarf2_name (die, cu);
13053
13054   return set_die_type (die, type, cu);
13055 }
13056
13057 /* Read a single die and all its descendents.  Set the die's sibling
13058    field to NULL; set other fields in the die correctly, and set all
13059    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13060    location of the info_ptr after reading all of those dies.  PARENT
13061    is the parent of the die in question.  */
13062
13063 static struct die_info *
13064 read_die_and_children (const struct die_reader_specs *reader,
13065                        gdb_byte *info_ptr,
13066                        gdb_byte **new_info_ptr,
13067                        struct die_info *parent)
13068 {
13069   struct die_info *die;
13070   gdb_byte *cur_ptr;
13071   int has_children;
13072
13073   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
13074   if (die == NULL)
13075     {
13076       *new_info_ptr = cur_ptr;
13077       return NULL;
13078     }
13079   store_in_ref_table (die, reader->cu);
13080
13081   if (has_children)
13082     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
13083   else
13084     {
13085       die->child = NULL;
13086       *new_info_ptr = cur_ptr;
13087     }
13088
13089   die->sibling = NULL;
13090   die->parent = parent;
13091   return die;
13092 }
13093
13094 /* Read a die, all of its descendents, and all of its siblings; set
13095    all of the fields of all of the dies correctly.  Arguments are as
13096    in read_die_and_children.  */
13097
13098 static struct die_info *
13099 read_die_and_siblings (const struct die_reader_specs *reader,
13100                        gdb_byte *info_ptr,
13101                        gdb_byte **new_info_ptr,
13102                        struct die_info *parent)
13103 {
13104   struct die_info *first_die, *last_sibling;
13105   gdb_byte *cur_ptr;
13106
13107   cur_ptr = info_ptr;
13108   first_die = last_sibling = NULL;
13109
13110   while (1)
13111     {
13112       struct die_info *die
13113         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13114
13115       if (die == NULL)
13116         {
13117           *new_info_ptr = cur_ptr;
13118           return first_die;
13119         }
13120
13121       if (!first_die)
13122         first_die = die;
13123       else
13124         last_sibling->sibling = die;
13125
13126       last_sibling = die;
13127     }
13128 }
13129
13130 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13131    attributes.
13132    The caller is responsible for filling in the extra attributes
13133    and updating (*DIEP)->num_attrs.
13134    Set DIEP to point to a newly allocated die with its information,
13135    except for its child, sibling, and parent fields.
13136    Set HAS_CHILDREN to tell whether the die has children or not.  */
13137
13138 static gdb_byte *
13139 read_full_die_1 (const struct die_reader_specs *reader,
13140                  struct die_info **diep, gdb_byte *info_ptr,
13141                  int *has_children, int num_extra_attrs)
13142 {
13143   unsigned int abbrev_number, bytes_read, i;
13144   sect_offset offset;
13145   struct abbrev_info *abbrev;
13146   struct die_info *die;
13147   struct dwarf2_cu *cu = reader->cu;
13148   bfd *abfd = reader->abfd;
13149
13150   offset.sect_off = info_ptr - reader->buffer;
13151   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13152   info_ptr += bytes_read;
13153   if (!abbrev_number)
13154     {
13155       *diep = NULL;
13156       *has_children = 0;
13157       return info_ptr;
13158     }
13159
13160   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13161   if (!abbrev)
13162     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13163            abbrev_number,
13164            bfd_get_filename (abfd));
13165
13166   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13167   die->offset = offset;
13168   die->tag = abbrev->tag;
13169   die->abbrev = abbrev_number;
13170
13171   /* Make the result usable.
13172      The caller needs to update num_attrs after adding the extra
13173      attributes.  */
13174   die->num_attrs = abbrev->num_attrs;
13175
13176   for (i = 0; i < abbrev->num_attrs; ++i)
13177     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13178                                info_ptr);
13179
13180   *diep = die;
13181   *has_children = abbrev->has_children;
13182   return info_ptr;
13183 }
13184
13185 /* Read a die and all its attributes.
13186    Set DIEP to point to a newly allocated die with its information,
13187    except for its child, sibling, and parent fields.
13188    Set HAS_CHILDREN to tell whether the die has children or not.  */
13189
13190 static gdb_byte *
13191 read_full_die (const struct die_reader_specs *reader,
13192                struct die_info **diep, gdb_byte *info_ptr,
13193                int *has_children)
13194 {
13195   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13196 }
13197 \f
13198 /* Abbreviation tables.
13199
13200    In DWARF version 2, the description of the debugging information is
13201    stored in a separate .debug_abbrev section.  Before we read any
13202    dies from a section we read in all abbreviations and install them
13203    in a hash table.  */
13204
13205 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13206
13207 static struct abbrev_info *
13208 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13209 {
13210   struct abbrev_info *abbrev;
13211
13212   abbrev = (struct abbrev_info *)
13213     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13214   memset (abbrev, 0, sizeof (struct abbrev_info));
13215   return abbrev;
13216 }
13217
13218 /* Add an abbreviation to the table.  */
13219
13220 static void
13221 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13222                          unsigned int abbrev_number,
13223                          struct abbrev_info *abbrev)
13224 {
13225   unsigned int hash_number;
13226
13227   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13228   abbrev->next = abbrev_table->abbrevs[hash_number];
13229   abbrev_table->abbrevs[hash_number] = abbrev;
13230 }
13231
13232 /* Look up an abbrev in the table.
13233    Returns NULL if the abbrev is not found.  */
13234
13235 static struct abbrev_info *
13236 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13237                             unsigned int abbrev_number)
13238 {
13239   unsigned int hash_number;
13240   struct abbrev_info *abbrev;
13241
13242   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13243   abbrev = abbrev_table->abbrevs[hash_number];
13244
13245   while (abbrev)
13246     {
13247       if (abbrev->number == abbrev_number)
13248         return abbrev;
13249       abbrev = abbrev->next;
13250     }
13251   return NULL;
13252 }
13253
13254 /* Read in an abbrev table.  */
13255
13256 static struct abbrev_table *
13257 abbrev_table_read_table (struct dwarf2_section_info *section,
13258                          sect_offset offset)
13259 {
13260   struct objfile *objfile = dwarf2_per_objfile->objfile;
13261   bfd *abfd = section->asection->owner;
13262   struct abbrev_table *abbrev_table;
13263   gdb_byte *abbrev_ptr;
13264   struct abbrev_info *cur_abbrev;
13265   unsigned int abbrev_number, bytes_read, abbrev_name;
13266   unsigned int abbrev_form;
13267   struct attr_abbrev *cur_attrs;
13268   unsigned int allocated_attrs;
13269
13270   abbrev_table = XMALLOC (struct abbrev_table);
13271   abbrev_table->offset = offset;
13272   obstack_init (&abbrev_table->abbrev_obstack);
13273   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13274                                          (ABBREV_HASH_SIZE
13275                                           * sizeof (struct abbrev_info *)));
13276   memset (abbrev_table->abbrevs, 0,
13277           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13278
13279   dwarf2_read_section (objfile, section);
13280   abbrev_ptr = section->buffer + offset.sect_off;
13281   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13282   abbrev_ptr += bytes_read;
13283
13284   allocated_attrs = ATTR_ALLOC_CHUNK;
13285   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13286
13287   /* Loop until we reach an abbrev number of 0.  */
13288   while (abbrev_number)
13289     {
13290       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13291
13292       /* read in abbrev header */
13293       cur_abbrev->number = abbrev_number;
13294       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13295       abbrev_ptr += bytes_read;
13296       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13297       abbrev_ptr += 1;
13298
13299       /* now read in declarations */
13300       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13301       abbrev_ptr += bytes_read;
13302       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13303       abbrev_ptr += bytes_read;
13304       while (abbrev_name)
13305         {
13306           if (cur_abbrev->num_attrs == allocated_attrs)
13307             {
13308               allocated_attrs += ATTR_ALLOC_CHUNK;
13309               cur_attrs
13310                 = xrealloc (cur_attrs, (allocated_attrs
13311                                         * sizeof (struct attr_abbrev)));
13312             }
13313
13314           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13315           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13316           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13317           abbrev_ptr += bytes_read;
13318           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13319           abbrev_ptr += bytes_read;
13320         }
13321
13322       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13323                                          (cur_abbrev->num_attrs
13324                                           * sizeof (struct attr_abbrev)));
13325       memcpy (cur_abbrev->attrs, cur_attrs,
13326               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13327
13328       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13329
13330       /* Get next abbreviation.
13331          Under Irix6 the abbreviations for a compilation unit are not
13332          always properly terminated with an abbrev number of 0.
13333          Exit loop if we encounter an abbreviation which we have
13334          already read (which means we are about to read the abbreviations
13335          for the next compile unit) or if the end of the abbreviation
13336          table is reached.  */
13337       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13338         break;
13339       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13340       abbrev_ptr += bytes_read;
13341       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13342         break;
13343     }
13344
13345   xfree (cur_attrs);
13346   return abbrev_table;
13347 }
13348
13349 /* Free the resources held by ABBREV_TABLE.  */
13350
13351 static void
13352 abbrev_table_free (struct abbrev_table *abbrev_table)
13353 {
13354   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13355   xfree (abbrev_table);
13356 }
13357
13358 /* Same as abbrev_table_free but as a cleanup.
13359    We pass in a pointer to the pointer to the table so that we can
13360    set the pointer to NULL when we're done.  It also simplifies
13361    build_type_unit_groups.  */
13362
13363 static void
13364 abbrev_table_free_cleanup (void *table_ptr)
13365 {
13366   struct abbrev_table **abbrev_table_ptr = table_ptr;
13367
13368   if (*abbrev_table_ptr != NULL)
13369     abbrev_table_free (*abbrev_table_ptr);
13370   *abbrev_table_ptr = NULL;
13371 }
13372
13373 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13374
13375 static void
13376 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13377                      struct dwarf2_section_info *abbrev_section)
13378 {
13379   cu->abbrev_table =
13380     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13381 }
13382
13383 /* Release the memory used by the abbrev table for a compilation unit.  */
13384
13385 static void
13386 dwarf2_free_abbrev_table (void *ptr_to_cu)
13387 {
13388   struct dwarf2_cu *cu = ptr_to_cu;
13389
13390   abbrev_table_free (cu->abbrev_table);
13391   /* Set this to NULL so that we SEGV if we try to read it later,
13392      and also because free_comp_unit verifies this is NULL.  */
13393   cu->abbrev_table = NULL;
13394 }
13395 \f
13396 /* Returns nonzero if TAG represents a type that we might generate a partial
13397    symbol for.  */
13398
13399 static int
13400 is_type_tag_for_partial (int tag)
13401 {
13402   switch (tag)
13403     {
13404 #if 0
13405     /* Some types that would be reasonable to generate partial symbols for,
13406        that we don't at present.  */
13407     case DW_TAG_array_type:
13408     case DW_TAG_file_type:
13409     case DW_TAG_ptr_to_member_type:
13410     case DW_TAG_set_type:
13411     case DW_TAG_string_type:
13412     case DW_TAG_subroutine_type:
13413 #endif
13414     case DW_TAG_base_type:
13415     case DW_TAG_class_type:
13416     case DW_TAG_interface_type:
13417     case DW_TAG_enumeration_type:
13418     case DW_TAG_structure_type:
13419     case DW_TAG_subrange_type:
13420     case DW_TAG_typedef:
13421     case DW_TAG_union_type:
13422       return 1;
13423     default:
13424       return 0;
13425     }
13426 }
13427
13428 /* Load all DIEs that are interesting for partial symbols into memory.  */
13429
13430 static struct partial_die_info *
13431 load_partial_dies (const struct die_reader_specs *reader,
13432                    gdb_byte *info_ptr, int building_psymtab)
13433 {
13434   struct dwarf2_cu *cu = reader->cu;
13435   struct objfile *objfile = cu->objfile;
13436   struct partial_die_info *part_die;
13437   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13438   struct abbrev_info *abbrev;
13439   unsigned int bytes_read;
13440   unsigned int load_all = 0;
13441   int nesting_level = 1;
13442
13443   parent_die = NULL;
13444   last_die = NULL;
13445
13446   gdb_assert (cu->per_cu != NULL);
13447   if (cu->per_cu->load_all_dies)
13448     load_all = 1;
13449
13450   cu->partial_dies
13451     = htab_create_alloc_ex (cu->header.length / 12,
13452                             partial_die_hash,
13453                             partial_die_eq,
13454                             NULL,
13455                             &cu->comp_unit_obstack,
13456                             hashtab_obstack_allocate,
13457                             dummy_obstack_deallocate);
13458
13459   part_die = obstack_alloc (&cu->comp_unit_obstack,
13460                             sizeof (struct partial_die_info));
13461
13462   while (1)
13463     {
13464       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13465
13466       /* A NULL abbrev means the end of a series of children.  */
13467       if (abbrev == NULL)
13468         {
13469           if (--nesting_level == 0)
13470             {
13471               /* PART_DIE was probably the last thing allocated on the
13472                  comp_unit_obstack, so we could call obstack_free
13473                  here.  We don't do that because the waste is small,
13474                  and will be cleaned up when we're done with this
13475                  compilation unit.  This way, we're also more robust
13476                  against other users of the comp_unit_obstack.  */
13477               return first_die;
13478             }
13479           info_ptr += bytes_read;
13480           last_die = parent_die;
13481           parent_die = parent_die->die_parent;
13482           continue;
13483         }
13484
13485       /* Check for template arguments.  We never save these; if
13486          they're seen, we just mark the parent, and go on our way.  */
13487       if (parent_die != NULL
13488           && cu->language == language_cplus
13489           && (abbrev->tag == DW_TAG_template_type_param
13490               || abbrev->tag == DW_TAG_template_value_param))
13491         {
13492           parent_die->has_template_arguments = 1;
13493
13494           if (!load_all)
13495             {
13496               /* We don't need a partial DIE for the template argument.  */
13497               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13498               continue;
13499             }
13500         }
13501
13502       /* We only recurse into c++ subprograms looking for template arguments.
13503          Skip their other children.  */
13504       if (!load_all
13505           && cu->language == language_cplus
13506           && parent_die != NULL
13507           && parent_die->tag == DW_TAG_subprogram)
13508         {
13509           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13510           continue;
13511         }
13512
13513       /* Check whether this DIE is interesting enough to save.  Normally
13514          we would not be interested in members here, but there may be
13515          later variables referencing them via DW_AT_specification (for
13516          static members).  */
13517       if (!load_all
13518           && !is_type_tag_for_partial (abbrev->tag)
13519           && abbrev->tag != DW_TAG_constant
13520           && abbrev->tag != DW_TAG_enumerator
13521           && abbrev->tag != DW_TAG_subprogram
13522           && abbrev->tag != DW_TAG_lexical_block
13523           && abbrev->tag != DW_TAG_variable
13524           && abbrev->tag != DW_TAG_namespace
13525           && abbrev->tag != DW_TAG_module
13526           && abbrev->tag != DW_TAG_member
13527           && abbrev->tag != DW_TAG_imported_unit)
13528         {
13529           /* Otherwise we skip to the next sibling, if any.  */
13530           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13531           continue;
13532         }
13533
13534       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13535                                    info_ptr);
13536
13537       /* This two-pass algorithm for processing partial symbols has a
13538          high cost in cache pressure.  Thus, handle some simple cases
13539          here which cover the majority of C partial symbols.  DIEs
13540          which neither have specification tags in them, nor could have
13541          specification tags elsewhere pointing at them, can simply be
13542          processed and discarded.
13543
13544          This segment is also optional; scan_partial_symbols and
13545          add_partial_symbol will handle these DIEs if we chain
13546          them in normally.  When compilers which do not emit large
13547          quantities of duplicate debug information are more common,
13548          this code can probably be removed.  */
13549
13550       /* Any complete simple types at the top level (pretty much all
13551          of them, for a language without namespaces), can be processed
13552          directly.  */
13553       if (parent_die == NULL
13554           && part_die->has_specification == 0
13555           && part_die->is_declaration == 0
13556           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13557               || part_die->tag == DW_TAG_base_type
13558               || part_die->tag == DW_TAG_subrange_type))
13559         {
13560           if (building_psymtab && part_die->name != NULL)
13561             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13562                                  VAR_DOMAIN, LOC_TYPEDEF,
13563                                  &objfile->static_psymbols,
13564                                  0, (CORE_ADDR) 0, cu->language, objfile);
13565           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13566           continue;
13567         }
13568
13569       /* The exception for DW_TAG_typedef with has_children above is
13570          a workaround of GCC PR debug/47510.  In the case of this complaint
13571          type_name_no_tag_or_error will error on such types later.
13572
13573          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13574          it could not find the child DIEs referenced later, this is checked
13575          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13576
13577       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13578         complaint (&symfile_complaints,
13579                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13580                      "- DIE at 0x%x [in module %s]"),
13581                    part_die->offset.sect_off, objfile->name);
13582
13583       /* If we're at the second level, and we're an enumerator, and
13584          our parent has no specification (meaning possibly lives in a
13585          namespace elsewhere), then we can add the partial symbol now
13586          instead of queueing it.  */
13587       if (part_die->tag == DW_TAG_enumerator
13588           && parent_die != NULL
13589           && parent_die->die_parent == NULL
13590           && parent_die->tag == DW_TAG_enumeration_type
13591           && parent_die->has_specification == 0)
13592         {
13593           if (part_die->name == NULL)
13594             complaint (&symfile_complaints,
13595                        _("malformed enumerator DIE ignored"));
13596           else if (building_psymtab)
13597             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13598                                  VAR_DOMAIN, LOC_CONST,
13599                                  (cu->language == language_cplus
13600                                   || cu->language == language_java)
13601                                  ? &objfile->global_psymbols
13602                                  : &objfile->static_psymbols,
13603                                  0, (CORE_ADDR) 0, cu->language, objfile);
13604
13605           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13606           continue;
13607         }
13608
13609       /* We'll save this DIE so link it in.  */
13610       part_die->die_parent = parent_die;
13611       part_die->die_sibling = NULL;
13612       part_die->die_child = NULL;
13613
13614       if (last_die && last_die == parent_die)
13615         last_die->die_child = part_die;
13616       else if (last_die)
13617         last_die->die_sibling = part_die;
13618
13619       last_die = part_die;
13620
13621       if (first_die == NULL)
13622         first_die = part_die;
13623
13624       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13625          find interesting need to be in the hash table, because we
13626          also have the parent/sibling/child chains; only those that we
13627          might refer to by offset later during partial symbol reading.
13628
13629          For now this means things that might have be the target of a
13630          DW_AT_specification, DW_AT_abstract_origin, or
13631          DW_AT_extension.  DW_AT_extension will refer only to
13632          namespaces; DW_AT_abstract_origin refers to functions (and
13633          many things under the function DIE, but we do not recurse
13634          into function DIEs during partial symbol reading) and
13635          possibly variables as well; DW_AT_specification refers to
13636          declarations.  Declarations ought to have the DW_AT_declaration
13637          flag.  It happens that GCC forgets to put it in sometimes, but
13638          only for functions, not for types.
13639
13640          Adding more things than necessary to the hash table is harmless
13641          except for the performance cost.  Adding too few will result in
13642          wasted time in find_partial_die, when we reread the compilation
13643          unit with load_all_dies set.  */
13644
13645       if (load_all
13646           || abbrev->tag == DW_TAG_constant
13647           || abbrev->tag == DW_TAG_subprogram
13648           || abbrev->tag == DW_TAG_variable
13649           || abbrev->tag == DW_TAG_namespace
13650           || part_die->is_declaration)
13651         {
13652           void **slot;
13653
13654           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13655                                            part_die->offset.sect_off, INSERT);
13656           *slot = part_die;
13657         }
13658
13659       part_die = obstack_alloc (&cu->comp_unit_obstack,
13660                                 sizeof (struct partial_die_info));
13661
13662       /* For some DIEs we want to follow their children (if any).  For C
13663          we have no reason to follow the children of structures; for other
13664          languages we have to, so that we can get at method physnames
13665          to infer fully qualified class names, for DW_AT_specification,
13666          and for C++ template arguments.  For C++, we also look one level
13667          inside functions to find template arguments (if the name of the
13668          function does not already contain the template arguments).
13669
13670          For Ada, we need to scan the children of subprograms and lexical
13671          blocks as well because Ada allows the definition of nested
13672          entities that could be interesting for the debugger, such as
13673          nested subprograms for instance.  */
13674       if (last_die->has_children
13675           && (load_all
13676               || last_die->tag == DW_TAG_namespace
13677               || last_die->tag == DW_TAG_module
13678               || last_die->tag == DW_TAG_enumeration_type
13679               || (cu->language == language_cplus
13680                   && last_die->tag == DW_TAG_subprogram
13681                   && (last_die->name == NULL
13682                       || strchr (last_die->name, '<') == NULL))
13683               || (cu->language != language_c
13684                   && (last_die->tag == DW_TAG_class_type
13685                       || last_die->tag == DW_TAG_interface_type
13686                       || last_die->tag == DW_TAG_structure_type
13687                       || last_die->tag == DW_TAG_union_type))
13688               || (cu->language == language_ada
13689                   && (last_die->tag == DW_TAG_subprogram
13690                       || last_die->tag == DW_TAG_lexical_block))))
13691         {
13692           nesting_level++;
13693           parent_die = last_die;
13694           continue;
13695         }
13696
13697       /* Otherwise we skip to the next sibling, if any.  */
13698       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13699
13700       /* Back to the top, do it again.  */
13701     }
13702 }
13703
13704 /* Read a minimal amount of information into the minimal die structure.  */
13705
13706 static gdb_byte *
13707 read_partial_die (const struct die_reader_specs *reader,
13708                   struct partial_die_info *part_die,
13709                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13710                   gdb_byte *info_ptr)
13711 {
13712   struct dwarf2_cu *cu = reader->cu;
13713   struct objfile *objfile = cu->objfile;
13714   gdb_byte *buffer = reader->buffer;
13715   unsigned int i;
13716   struct attribute attr;
13717   int has_low_pc_attr = 0;
13718   int has_high_pc_attr = 0;
13719   int high_pc_relative = 0;
13720
13721   memset (part_die, 0, sizeof (struct partial_die_info));
13722
13723   part_die->offset.sect_off = info_ptr - buffer;
13724
13725   info_ptr += abbrev_len;
13726
13727   if (abbrev == NULL)
13728     return info_ptr;
13729
13730   part_die->tag = abbrev->tag;
13731   part_die->has_children = abbrev->has_children;
13732
13733   for (i = 0; i < abbrev->num_attrs; ++i)
13734     {
13735       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13736
13737       /* Store the data if it is of an attribute we want to keep in a
13738          partial symbol table.  */
13739       switch (attr.name)
13740         {
13741         case DW_AT_name:
13742           switch (part_die->tag)
13743             {
13744             case DW_TAG_compile_unit:
13745             case DW_TAG_partial_unit:
13746             case DW_TAG_type_unit:
13747               /* Compilation units have a DW_AT_name that is a filename, not
13748                  a source language identifier.  */
13749             case DW_TAG_enumeration_type:
13750             case DW_TAG_enumerator:
13751               /* These tags always have simple identifiers already; no need
13752                  to canonicalize them.  */
13753               part_die->name = DW_STRING (&attr);
13754               break;
13755             default:
13756               part_die->name
13757                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13758                                             &objfile->objfile_obstack);
13759               break;
13760             }
13761           break;
13762         case DW_AT_linkage_name:
13763         case DW_AT_MIPS_linkage_name:
13764           /* Note that both forms of linkage name might appear.  We
13765              assume they will be the same, and we only store the last
13766              one we see.  */
13767           if (cu->language == language_ada)
13768             part_die->name = DW_STRING (&attr);
13769           part_die->linkage_name = DW_STRING (&attr);
13770           break;
13771         case DW_AT_low_pc:
13772           has_low_pc_attr = 1;
13773           part_die->lowpc = DW_ADDR (&attr);
13774           break;
13775         case DW_AT_high_pc:
13776           has_high_pc_attr = 1;
13777           if (attr.form == DW_FORM_addr
13778               || attr.form == DW_FORM_GNU_addr_index)
13779             part_die->highpc = DW_ADDR (&attr);
13780           else
13781             {
13782               high_pc_relative = 1;
13783               part_die->highpc = DW_UNSND (&attr);
13784             }
13785           break;
13786         case DW_AT_location:
13787           /* Support the .debug_loc offsets.  */
13788           if (attr_form_is_block (&attr))
13789             {
13790                part_die->d.locdesc = DW_BLOCK (&attr);
13791             }
13792           else if (attr_form_is_section_offset (&attr))
13793             {
13794               dwarf2_complex_location_expr_complaint ();
13795             }
13796           else
13797             {
13798               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13799                                                      "partial symbol information");
13800             }
13801           break;
13802         case DW_AT_external:
13803           part_die->is_external = DW_UNSND (&attr);
13804           break;
13805         case DW_AT_declaration:
13806           part_die->is_declaration = DW_UNSND (&attr);
13807           break;
13808         case DW_AT_type:
13809           part_die->has_type = 1;
13810           break;
13811         case DW_AT_abstract_origin:
13812         case DW_AT_specification:
13813         case DW_AT_extension:
13814           part_die->has_specification = 1;
13815           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13816           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13817                                    || cu->per_cu->is_dwz);
13818           break;
13819         case DW_AT_sibling:
13820           /* Ignore absolute siblings, they might point outside of
13821              the current compile unit.  */
13822           if (attr.form == DW_FORM_ref_addr)
13823             complaint (&symfile_complaints,
13824                        _("ignoring absolute DW_AT_sibling"));
13825           else
13826             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13827           break;
13828         case DW_AT_byte_size:
13829           part_die->has_byte_size = 1;
13830           break;
13831         case DW_AT_calling_convention:
13832           /* DWARF doesn't provide a way to identify a program's source-level
13833              entry point.  DW_AT_calling_convention attributes are only meant
13834              to describe functions' calling conventions.
13835
13836              However, because it's a necessary piece of information in
13837              Fortran, and because DW_CC_program is the only piece of debugging
13838              information whose definition refers to a 'main program' at all,
13839              several compilers have begun marking Fortran main programs with
13840              DW_CC_program --- even when those functions use the standard
13841              calling conventions.
13842
13843              So until DWARF specifies a way to provide this information and
13844              compilers pick up the new representation, we'll support this
13845              practice.  */
13846           if (DW_UNSND (&attr) == DW_CC_program
13847               && cu->language == language_fortran)
13848             {
13849               set_main_name (part_die->name);
13850
13851               /* As this DIE has a static linkage the name would be difficult
13852                  to look up later.  */
13853               language_of_main = language_fortran;
13854             }
13855           break;
13856         case DW_AT_inline:
13857           if (DW_UNSND (&attr) == DW_INL_inlined
13858               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13859             part_die->may_be_inlined = 1;
13860           break;
13861
13862         case DW_AT_import:
13863           if (part_die->tag == DW_TAG_imported_unit)
13864             {
13865               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13866               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13867                                   || cu->per_cu->is_dwz);
13868             }
13869           break;
13870
13871         default:
13872           break;
13873         }
13874     }
13875
13876   if (high_pc_relative)
13877     part_die->highpc += part_die->lowpc;
13878
13879   if (has_low_pc_attr && has_high_pc_attr)
13880     {
13881       /* When using the GNU linker, .gnu.linkonce. sections are used to
13882          eliminate duplicate copies of functions and vtables and such.
13883          The linker will arbitrarily choose one and discard the others.
13884          The AT_*_pc values for such functions refer to local labels in
13885          these sections.  If the section from that file was discarded, the
13886          labels are not in the output, so the relocs get a value of 0.
13887          If this is a discarded function, mark the pc bounds as invalid,
13888          so that GDB will ignore it.  */
13889       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13890         {
13891           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13892
13893           complaint (&symfile_complaints,
13894                      _("DW_AT_low_pc %s is zero "
13895                        "for DIE at 0x%x [in module %s]"),
13896                      paddress (gdbarch, part_die->lowpc),
13897                      part_die->offset.sect_off, objfile->name);
13898         }
13899       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13900       else if (part_die->lowpc >= part_die->highpc)
13901         {
13902           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13903
13904           complaint (&symfile_complaints,
13905                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13906                        "for DIE at 0x%x [in module %s]"),
13907                      paddress (gdbarch, part_die->lowpc),
13908                      paddress (gdbarch, part_die->highpc),
13909                      part_die->offset.sect_off, objfile->name);
13910         }
13911       else
13912         part_die->has_pc_info = 1;
13913     }
13914
13915   return info_ptr;
13916 }
13917
13918 /* Find a cached partial DIE at OFFSET in CU.  */
13919
13920 static struct partial_die_info *
13921 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13922 {
13923   struct partial_die_info *lookup_die = NULL;
13924   struct partial_die_info part_die;
13925
13926   part_die.offset = offset;
13927   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13928                                     offset.sect_off);
13929
13930   return lookup_die;
13931 }
13932
13933 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13934    except in the case of .debug_types DIEs which do not reference
13935    outside their CU (they do however referencing other types via
13936    DW_FORM_ref_sig8).  */
13937
13938 static struct partial_die_info *
13939 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13940 {
13941   struct objfile *objfile = cu->objfile;
13942   struct dwarf2_per_cu_data *per_cu = NULL;
13943   struct partial_die_info *pd = NULL;
13944
13945   if (offset_in_dwz == cu->per_cu->is_dwz
13946       && offset_in_cu_p (&cu->header, offset))
13947     {
13948       pd = find_partial_die_in_comp_unit (offset, cu);
13949       if (pd != NULL)
13950         return pd;
13951       /* We missed recording what we needed.
13952          Load all dies and try again.  */
13953       per_cu = cu->per_cu;
13954     }
13955   else
13956     {
13957       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13958       if (cu->per_cu->is_debug_types)
13959         {
13960           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
13961                    " external reference to offset 0x%lx [in module %s].\n"),
13962                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
13963                  bfd_get_filename (objfile->obfd));
13964         }
13965       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
13966                                                  objfile);
13967
13968       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
13969         load_partial_comp_unit (per_cu);
13970
13971       per_cu->cu->last_used = 0;
13972       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13973     }
13974
13975   /* If we didn't find it, and not all dies have been loaded,
13976      load them all and try again.  */
13977
13978   if (pd == NULL && per_cu->load_all_dies == 0)
13979     {
13980       per_cu->load_all_dies = 1;
13981
13982       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
13983          THIS_CU->cu may already be in use.  So we can't just free it and
13984          replace its DIEs with the ones we read in.  Instead, we leave those
13985          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
13986          and clobber THIS_CU->cu->partial_dies with the hash table for the new
13987          set.  */
13988       load_partial_comp_unit (per_cu);
13989
13990       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13991     }
13992
13993   if (pd == NULL)
13994     internal_error (__FILE__, __LINE__,
13995                     _("could not find partial DIE 0x%x "
13996                       "in cache [from module %s]\n"),
13997                     offset.sect_off, bfd_get_filename (objfile->obfd));
13998   return pd;
13999 }
14000
14001 /* See if we can figure out if the class lives in a namespace.  We do
14002    this by looking for a member function; its demangled name will
14003    contain namespace info, if there is any.  */
14004
14005 static void
14006 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14007                                   struct dwarf2_cu *cu)
14008 {
14009   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14010      what template types look like, because the demangler
14011      frequently doesn't give the same name as the debug info.  We
14012      could fix this by only using the demangled name to get the
14013      prefix (but see comment in read_structure_type).  */
14014
14015   struct partial_die_info *real_pdi;
14016   struct partial_die_info *child_pdi;
14017
14018   /* If this DIE (this DIE's specification, if any) has a parent, then
14019      we should not do this.  We'll prepend the parent's fully qualified
14020      name when we create the partial symbol.  */
14021
14022   real_pdi = struct_pdi;
14023   while (real_pdi->has_specification)
14024     real_pdi = find_partial_die (real_pdi->spec_offset,
14025                                  real_pdi->spec_is_dwz, cu);
14026
14027   if (real_pdi->die_parent != NULL)
14028     return;
14029
14030   for (child_pdi = struct_pdi->die_child;
14031        child_pdi != NULL;
14032        child_pdi = child_pdi->die_sibling)
14033     {
14034       if (child_pdi->tag == DW_TAG_subprogram
14035           && child_pdi->linkage_name != NULL)
14036         {
14037           char *actual_class_name
14038             = language_class_name_from_physname (cu->language_defn,
14039                                                  child_pdi->linkage_name);
14040           if (actual_class_name != NULL)
14041             {
14042               struct_pdi->name
14043                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14044                                  actual_class_name,
14045                                  strlen (actual_class_name));
14046               xfree (actual_class_name);
14047             }
14048           break;
14049         }
14050     }
14051 }
14052
14053 /* Adjust PART_DIE before generating a symbol for it.  This function
14054    may set the is_external flag or change the DIE's name.  */
14055
14056 static void
14057 fixup_partial_die (struct partial_die_info *part_die,
14058                    struct dwarf2_cu *cu)
14059 {
14060   /* Once we've fixed up a die, there's no point in doing so again.
14061      This also avoids a memory leak if we were to call
14062      guess_partial_die_structure_name multiple times.  */
14063   if (part_die->fixup_called)
14064     return;
14065
14066   /* If we found a reference attribute and the DIE has no name, try
14067      to find a name in the referred to DIE.  */
14068
14069   if (part_die->name == NULL && part_die->has_specification)
14070     {
14071       struct partial_die_info *spec_die;
14072
14073       spec_die = find_partial_die (part_die->spec_offset,
14074                                    part_die->spec_is_dwz, cu);
14075
14076       fixup_partial_die (spec_die, cu);
14077
14078       if (spec_die->name)
14079         {
14080           part_die->name = spec_die->name;
14081
14082           /* Copy DW_AT_external attribute if it is set.  */
14083           if (spec_die->is_external)
14084             part_die->is_external = spec_die->is_external;
14085         }
14086     }
14087
14088   /* Set default names for some unnamed DIEs.  */
14089
14090   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14091     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14092
14093   /* If there is no parent die to provide a namespace, and there are
14094      children, see if we can determine the namespace from their linkage
14095      name.  */
14096   if (cu->language == language_cplus
14097       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14098       && part_die->die_parent == NULL
14099       && part_die->has_children
14100       && (part_die->tag == DW_TAG_class_type
14101           || part_die->tag == DW_TAG_structure_type
14102           || part_die->tag == DW_TAG_union_type))
14103     guess_partial_die_structure_name (part_die, cu);
14104
14105   /* GCC might emit a nameless struct or union that has a linkage
14106      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14107   if (part_die->name == NULL
14108       && (part_die->tag == DW_TAG_class_type
14109           || part_die->tag == DW_TAG_interface_type
14110           || part_die->tag == DW_TAG_structure_type
14111           || part_die->tag == DW_TAG_union_type)
14112       && part_die->linkage_name != NULL)
14113     {
14114       char *demangled;
14115
14116       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
14117       if (demangled)
14118         {
14119           const char *base;
14120
14121           /* Strip any leading namespaces/classes, keep only the base name.
14122              DW_AT_name for named DIEs does not contain the prefixes.  */
14123           base = strrchr (demangled, ':');
14124           if (base && base > demangled && base[-1] == ':')
14125             base++;
14126           else
14127             base = demangled;
14128
14129           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14130                                           base, strlen (base));
14131           xfree (demangled);
14132         }
14133     }
14134
14135   part_die->fixup_called = 1;
14136 }
14137
14138 /* Read an attribute value described by an attribute form.  */
14139
14140 static gdb_byte *
14141 read_attribute_value (const struct die_reader_specs *reader,
14142                       struct attribute *attr, unsigned form,
14143                       gdb_byte *info_ptr)
14144 {
14145   struct dwarf2_cu *cu = reader->cu;
14146   bfd *abfd = reader->abfd;
14147   struct comp_unit_head *cu_header = &cu->header;
14148   unsigned int bytes_read;
14149   struct dwarf_block *blk;
14150
14151   attr->form = form;
14152   switch (form)
14153     {
14154     case DW_FORM_ref_addr:
14155       if (cu->header.version == 2)
14156         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14157       else
14158         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14159                                        &cu->header, &bytes_read);
14160       info_ptr += bytes_read;
14161       break;
14162     case DW_FORM_GNU_ref_alt:
14163       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14164       info_ptr += bytes_read;
14165       break;
14166     case DW_FORM_addr:
14167       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14168       info_ptr += bytes_read;
14169       break;
14170     case DW_FORM_block2:
14171       blk = dwarf_alloc_block (cu);
14172       blk->size = read_2_bytes (abfd, info_ptr);
14173       info_ptr += 2;
14174       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14175       info_ptr += blk->size;
14176       DW_BLOCK (attr) = blk;
14177       break;
14178     case DW_FORM_block4:
14179       blk = dwarf_alloc_block (cu);
14180       blk->size = read_4_bytes (abfd, info_ptr);
14181       info_ptr += 4;
14182       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14183       info_ptr += blk->size;
14184       DW_BLOCK (attr) = blk;
14185       break;
14186     case DW_FORM_data2:
14187       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14188       info_ptr += 2;
14189       break;
14190     case DW_FORM_data4:
14191       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14192       info_ptr += 4;
14193       break;
14194     case DW_FORM_data8:
14195       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14196       info_ptr += 8;
14197       break;
14198     case DW_FORM_sec_offset:
14199       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14200       info_ptr += bytes_read;
14201       break;
14202     case DW_FORM_string:
14203       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14204       DW_STRING_IS_CANONICAL (attr) = 0;
14205       info_ptr += bytes_read;
14206       break;
14207     case DW_FORM_strp:
14208       if (!cu->per_cu->is_dwz)
14209         {
14210           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14211                                                    &bytes_read);
14212           DW_STRING_IS_CANONICAL (attr) = 0;
14213           info_ptr += bytes_read;
14214           break;
14215         }
14216       /* FALLTHROUGH */
14217     case DW_FORM_GNU_strp_alt:
14218       {
14219         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14220         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14221                                           &bytes_read);
14222
14223         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14224         DW_STRING_IS_CANONICAL (attr) = 0;
14225         info_ptr += bytes_read;
14226       }
14227       break;
14228     case DW_FORM_exprloc:
14229     case DW_FORM_block:
14230       blk = dwarf_alloc_block (cu);
14231       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14232       info_ptr += bytes_read;
14233       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14234       info_ptr += blk->size;
14235       DW_BLOCK (attr) = blk;
14236       break;
14237     case DW_FORM_block1:
14238       blk = dwarf_alloc_block (cu);
14239       blk->size = read_1_byte (abfd, info_ptr);
14240       info_ptr += 1;
14241       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14242       info_ptr += blk->size;
14243       DW_BLOCK (attr) = blk;
14244       break;
14245     case DW_FORM_data1:
14246       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14247       info_ptr += 1;
14248       break;
14249     case DW_FORM_flag:
14250       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14251       info_ptr += 1;
14252       break;
14253     case DW_FORM_flag_present:
14254       DW_UNSND (attr) = 1;
14255       break;
14256     case DW_FORM_sdata:
14257       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14258       info_ptr += bytes_read;
14259       break;
14260     case DW_FORM_udata:
14261       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14262       info_ptr += bytes_read;
14263       break;
14264     case DW_FORM_ref1:
14265       DW_UNSND (attr) = (cu->header.offset.sect_off
14266                          + read_1_byte (abfd, info_ptr));
14267       info_ptr += 1;
14268       break;
14269     case DW_FORM_ref2:
14270       DW_UNSND (attr) = (cu->header.offset.sect_off
14271                          + read_2_bytes (abfd, info_ptr));
14272       info_ptr += 2;
14273       break;
14274     case DW_FORM_ref4:
14275       DW_UNSND (attr) = (cu->header.offset.sect_off
14276                          + read_4_bytes (abfd, info_ptr));
14277       info_ptr += 4;
14278       break;
14279     case DW_FORM_ref8:
14280       DW_UNSND (attr) = (cu->header.offset.sect_off
14281                          + read_8_bytes (abfd, info_ptr));
14282       info_ptr += 8;
14283       break;
14284     case DW_FORM_ref_sig8:
14285       /* Convert the signature to something we can record in DW_UNSND
14286          for later lookup.
14287          NOTE: This is NULL if the type wasn't found.  */
14288       DW_SIGNATURED_TYPE (attr) =
14289         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14290       info_ptr += 8;
14291       break;
14292     case DW_FORM_ref_udata:
14293       DW_UNSND (attr) = (cu->header.offset.sect_off
14294                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14295       info_ptr += bytes_read;
14296       break;
14297     case DW_FORM_indirect:
14298       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14299       info_ptr += bytes_read;
14300       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14301       break;
14302     case DW_FORM_GNU_addr_index:
14303       if (reader->dwo_file == NULL)
14304         {
14305           /* For now flag a hard error.
14306              Later we can turn this into a complaint.  */
14307           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14308                  dwarf_form_name (form),
14309                  bfd_get_filename (abfd));
14310         }
14311       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14312       info_ptr += bytes_read;
14313       break;
14314     case DW_FORM_GNU_str_index:
14315       if (reader->dwo_file == NULL)
14316         {
14317           /* For now flag a hard error.
14318              Later we can turn this into a complaint if warranted.  */
14319           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14320                  dwarf_form_name (form),
14321                  bfd_get_filename (abfd));
14322         }
14323       {
14324         ULONGEST str_index =
14325           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14326
14327         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14328         DW_STRING_IS_CANONICAL (attr) = 0;
14329         info_ptr += bytes_read;
14330       }
14331       break;
14332     default:
14333       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14334              dwarf_form_name (form),
14335              bfd_get_filename (abfd));
14336     }
14337
14338   /* Super hack.  */
14339   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14340     attr->form = DW_FORM_GNU_ref_alt;
14341
14342   /* We have seen instances where the compiler tried to emit a byte
14343      size attribute of -1 which ended up being encoded as an unsigned
14344      0xffffffff.  Although 0xffffffff is technically a valid size value,
14345      an object of this size seems pretty unlikely so we can relatively
14346      safely treat these cases as if the size attribute was invalid and
14347      treat them as zero by default.  */
14348   if (attr->name == DW_AT_byte_size
14349       && form == DW_FORM_data4
14350       && DW_UNSND (attr) >= 0xffffffff)
14351     {
14352       complaint
14353         (&symfile_complaints,
14354          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14355          hex_string (DW_UNSND (attr)));
14356       DW_UNSND (attr) = 0;
14357     }
14358
14359   return info_ptr;
14360 }
14361
14362 /* Read an attribute described by an abbreviated attribute.  */
14363
14364 static gdb_byte *
14365 read_attribute (const struct die_reader_specs *reader,
14366                 struct attribute *attr, struct attr_abbrev *abbrev,
14367                 gdb_byte *info_ptr)
14368 {
14369   attr->name = abbrev->name;
14370   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14371 }
14372
14373 /* Read dwarf information from a buffer.  */
14374
14375 static unsigned int
14376 read_1_byte (bfd *abfd, const gdb_byte *buf)
14377 {
14378   return bfd_get_8 (abfd, buf);
14379 }
14380
14381 static int
14382 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14383 {
14384   return bfd_get_signed_8 (abfd, buf);
14385 }
14386
14387 static unsigned int
14388 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14389 {
14390   return bfd_get_16 (abfd, buf);
14391 }
14392
14393 static int
14394 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14395 {
14396   return bfd_get_signed_16 (abfd, buf);
14397 }
14398
14399 static unsigned int
14400 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14401 {
14402   return bfd_get_32 (abfd, buf);
14403 }
14404
14405 static int
14406 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14407 {
14408   return bfd_get_signed_32 (abfd, buf);
14409 }
14410
14411 static ULONGEST
14412 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14413 {
14414   return bfd_get_64 (abfd, buf);
14415 }
14416
14417 static CORE_ADDR
14418 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
14419               unsigned int *bytes_read)
14420 {
14421   struct comp_unit_head *cu_header = &cu->header;
14422   CORE_ADDR retval = 0;
14423
14424   if (cu_header->signed_addr_p)
14425     {
14426       switch (cu_header->addr_size)
14427         {
14428         case 2:
14429           retval = bfd_get_signed_16 (abfd, buf);
14430           break;
14431         case 4:
14432           retval = bfd_get_signed_32 (abfd, buf);
14433           break;
14434         case 8:
14435           retval = bfd_get_signed_64 (abfd, buf);
14436           break;
14437         default:
14438           internal_error (__FILE__, __LINE__,
14439                           _("read_address: bad switch, signed [in module %s]"),
14440                           bfd_get_filename (abfd));
14441         }
14442     }
14443   else
14444     {
14445       switch (cu_header->addr_size)
14446         {
14447         case 2:
14448           retval = bfd_get_16 (abfd, buf);
14449           break;
14450         case 4:
14451           retval = bfd_get_32 (abfd, buf);
14452           break;
14453         case 8:
14454           retval = bfd_get_64 (abfd, buf);
14455           break;
14456         default:
14457           internal_error (__FILE__, __LINE__,
14458                           _("read_address: bad switch, "
14459                             "unsigned [in module %s]"),
14460                           bfd_get_filename (abfd));
14461         }
14462     }
14463
14464   *bytes_read = cu_header->addr_size;
14465   return retval;
14466 }
14467
14468 /* Read the initial length from a section.  The (draft) DWARF 3
14469    specification allows the initial length to take up either 4 bytes
14470    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14471    bytes describe the length and all offsets will be 8 bytes in length
14472    instead of 4.
14473
14474    An older, non-standard 64-bit format is also handled by this
14475    function.  The older format in question stores the initial length
14476    as an 8-byte quantity without an escape value.  Lengths greater
14477    than 2^32 aren't very common which means that the initial 4 bytes
14478    is almost always zero.  Since a length value of zero doesn't make
14479    sense for the 32-bit format, this initial zero can be considered to
14480    be an escape value which indicates the presence of the older 64-bit
14481    format.  As written, the code can't detect (old format) lengths
14482    greater than 4GB.  If it becomes necessary to handle lengths
14483    somewhat larger than 4GB, we could allow other small values (such
14484    as the non-sensical values of 1, 2, and 3) to also be used as
14485    escape values indicating the presence of the old format.
14486
14487    The value returned via bytes_read should be used to increment the
14488    relevant pointer after calling read_initial_length().
14489
14490    [ Note:  read_initial_length() and read_offset() are based on the
14491      document entitled "DWARF Debugging Information Format", revision
14492      3, draft 8, dated November 19, 2001.  This document was obtained
14493      from:
14494
14495         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14496
14497      This document is only a draft and is subject to change.  (So beware.)
14498
14499      Details regarding the older, non-standard 64-bit format were
14500      determined empirically by examining 64-bit ELF files produced by
14501      the SGI toolchain on an IRIX 6.5 machine.
14502
14503      - Kevin, July 16, 2002
14504    ] */
14505
14506 static LONGEST
14507 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
14508 {
14509   LONGEST length = bfd_get_32 (abfd, buf);
14510
14511   if (length == 0xffffffff)
14512     {
14513       length = bfd_get_64 (abfd, buf + 4);
14514       *bytes_read = 12;
14515     }
14516   else if (length == 0)
14517     {
14518       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14519       length = bfd_get_64 (abfd, buf);
14520       *bytes_read = 8;
14521     }
14522   else
14523     {
14524       *bytes_read = 4;
14525     }
14526
14527   return length;
14528 }
14529
14530 /* Cover function for read_initial_length.
14531    Returns the length of the object at BUF, and stores the size of the
14532    initial length in *BYTES_READ and stores the size that offsets will be in
14533    *OFFSET_SIZE.
14534    If the initial length size is not equivalent to that specified in
14535    CU_HEADER then issue a complaint.
14536    This is useful when reading non-comp-unit headers.  */
14537
14538 static LONGEST
14539 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
14540                                         const struct comp_unit_head *cu_header,
14541                                         unsigned int *bytes_read,
14542                                         unsigned int *offset_size)
14543 {
14544   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14545
14546   gdb_assert (cu_header->initial_length_size == 4
14547               || cu_header->initial_length_size == 8
14548               || cu_header->initial_length_size == 12);
14549
14550   if (cu_header->initial_length_size != *bytes_read)
14551     complaint (&symfile_complaints,
14552                _("intermixed 32-bit and 64-bit DWARF sections"));
14553
14554   *offset_size = (*bytes_read == 4) ? 4 : 8;
14555   return length;
14556 }
14557
14558 /* Read an offset from the data stream.  The size of the offset is
14559    given by cu_header->offset_size.  */
14560
14561 static LONGEST
14562 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
14563              unsigned int *bytes_read)
14564 {
14565   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14566
14567   *bytes_read = cu_header->offset_size;
14568   return offset;
14569 }
14570
14571 /* Read an offset from the data stream.  */
14572
14573 static LONGEST
14574 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
14575 {
14576   LONGEST retval = 0;
14577
14578   switch (offset_size)
14579     {
14580     case 4:
14581       retval = bfd_get_32 (abfd, buf);
14582       break;
14583     case 8:
14584       retval = bfd_get_64 (abfd, buf);
14585       break;
14586     default:
14587       internal_error (__FILE__, __LINE__,
14588                       _("read_offset_1: bad switch [in module %s]"),
14589                       bfd_get_filename (abfd));
14590     }
14591
14592   return retval;
14593 }
14594
14595 static gdb_byte *
14596 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
14597 {
14598   /* If the size of a host char is 8 bits, we can return a pointer
14599      to the buffer, otherwise we have to copy the data to a buffer
14600      allocated on the temporary obstack.  */
14601   gdb_assert (HOST_CHAR_BIT == 8);
14602   return buf;
14603 }
14604
14605 static char *
14606 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14607 {
14608   /* If the size of a host char is 8 bits, we can return a pointer
14609      to the string, otherwise we have to copy the string to a buffer
14610      allocated on the temporary obstack.  */
14611   gdb_assert (HOST_CHAR_BIT == 8);
14612   if (*buf == '\0')
14613     {
14614       *bytes_read_ptr = 1;
14615       return NULL;
14616     }
14617   *bytes_read_ptr = strlen ((char *) buf) + 1;
14618   return (char *) buf;
14619 }
14620
14621 static char *
14622 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14623 {
14624   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14625   if (dwarf2_per_objfile->str.buffer == NULL)
14626     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14627            bfd_get_filename (abfd));
14628   if (str_offset >= dwarf2_per_objfile->str.size)
14629     error (_("DW_FORM_strp pointing outside of "
14630              ".debug_str section [in module %s]"),
14631            bfd_get_filename (abfd));
14632   gdb_assert (HOST_CHAR_BIT == 8);
14633   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14634     return NULL;
14635   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
14636 }
14637
14638 /* Read a string at offset STR_OFFSET in the .debug_str section from
14639    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14640    the string consists of a single NUL byte, return NULL; otherwise
14641    return a pointer to the string.  */
14642
14643 static char *
14644 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14645 {
14646   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14647
14648   if (dwz->str.buffer == NULL)
14649     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14650              "section [in module %s]"),
14651            bfd_get_filename (dwz->dwz_bfd));
14652   if (str_offset >= dwz->str.size)
14653     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14654              ".debug_str section [in module %s]"),
14655            bfd_get_filename (dwz->dwz_bfd));
14656   gdb_assert (HOST_CHAR_BIT == 8);
14657   if (dwz->str.buffer[str_offset] == '\0')
14658     return NULL;
14659   return (char *) (dwz->str.buffer + str_offset);
14660 }
14661
14662 static char *
14663 read_indirect_string (bfd *abfd, gdb_byte *buf,
14664                       const struct comp_unit_head *cu_header,
14665                       unsigned int *bytes_read_ptr)
14666 {
14667   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14668
14669   return read_indirect_string_at_offset (abfd, str_offset);
14670 }
14671
14672 static ULONGEST
14673 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14674 {
14675   ULONGEST result;
14676   unsigned int num_read;
14677   int i, shift;
14678   unsigned char byte;
14679
14680   result = 0;
14681   shift = 0;
14682   num_read = 0;
14683   i = 0;
14684   while (1)
14685     {
14686       byte = bfd_get_8 (abfd, buf);
14687       buf++;
14688       num_read++;
14689       result |= ((ULONGEST) (byte & 127) << shift);
14690       if ((byte & 128) == 0)
14691         {
14692           break;
14693         }
14694       shift += 7;
14695     }
14696   *bytes_read_ptr = num_read;
14697   return result;
14698 }
14699
14700 static LONGEST
14701 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14702 {
14703   LONGEST result;
14704   int i, shift, num_read;
14705   unsigned char byte;
14706
14707   result = 0;
14708   shift = 0;
14709   num_read = 0;
14710   i = 0;
14711   while (1)
14712     {
14713       byte = bfd_get_8 (abfd, buf);
14714       buf++;
14715       num_read++;
14716       result |= ((LONGEST) (byte & 127) << shift);
14717       shift += 7;
14718       if ((byte & 128) == 0)
14719         {
14720           break;
14721         }
14722     }
14723   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14724     result |= -(((LONGEST) 1) << shift);
14725   *bytes_read_ptr = num_read;
14726   return result;
14727 }
14728
14729 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14730    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14731    ADDR_SIZE is the size of addresses from the CU header.  */
14732
14733 static CORE_ADDR
14734 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14735 {
14736   struct objfile *objfile = dwarf2_per_objfile->objfile;
14737   bfd *abfd = objfile->obfd;
14738   const gdb_byte *info_ptr;
14739
14740   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14741   if (dwarf2_per_objfile->addr.buffer == NULL)
14742     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14743            objfile->name);
14744   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14745     error (_("DW_FORM_addr_index pointing outside of "
14746              ".debug_addr section [in module %s]"),
14747            objfile->name);
14748   info_ptr = (dwarf2_per_objfile->addr.buffer
14749               + addr_base + addr_index * addr_size);
14750   if (addr_size == 4)
14751     return bfd_get_32 (abfd, info_ptr);
14752   else
14753     return bfd_get_64 (abfd, info_ptr);
14754 }
14755
14756 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14757
14758 static CORE_ADDR
14759 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14760 {
14761   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14762 }
14763
14764 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14765
14766 static CORE_ADDR
14767 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
14768                              unsigned int *bytes_read)
14769 {
14770   bfd *abfd = cu->objfile->obfd;
14771   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14772
14773   return read_addr_index (cu, addr_index);
14774 }
14775
14776 /* Data structure to pass results from dwarf2_read_addr_index_reader
14777    back to dwarf2_read_addr_index.  */
14778
14779 struct dwarf2_read_addr_index_data
14780 {
14781   ULONGEST addr_base;
14782   int addr_size;
14783 };
14784
14785 /* die_reader_func for dwarf2_read_addr_index.  */
14786
14787 static void
14788 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14789                                gdb_byte *info_ptr,
14790                                struct die_info *comp_unit_die,
14791                                int has_children,
14792                                void *data)
14793 {
14794   struct dwarf2_cu *cu = reader->cu;
14795   struct dwarf2_read_addr_index_data *aidata =
14796     (struct dwarf2_read_addr_index_data *) data;
14797
14798   aidata->addr_base = cu->addr_base;
14799   aidata->addr_size = cu->header.addr_size;
14800 }
14801
14802 /* Given an index in .debug_addr, fetch the value.
14803    NOTE: This can be called during dwarf expression evaluation,
14804    long after the debug information has been read, and thus per_cu->cu
14805    may no longer exist.  */
14806
14807 CORE_ADDR
14808 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14809                         unsigned int addr_index)
14810 {
14811   struct objfile *objfile = per_cu->objfile;
14812   struct dwarf2_cu *cu = per_cu->cu;
14813   ULONGEST addr_base;
14814   int addr_size;
14815
14816   /* This is intended to be called from outside this file.  */
14817   dw2_setup (objfile);
14818
14819   /* We need addr_base and addr_size.
14820      If we don't have PER_CU->cu, we have to get it.
14821      Nasty, but the alternative is storing the needed info in PER_CU,
14822      which at this point doesn't seem justified: it's not clear how frequently
14823      it would get used and it would increase the size of every PER_CU.
14824      Entry points like dwarf2_per_cu_addr_size do a similar thing
14825      so we're not in uncharted territory here.
14826      Alas we need to be a bit more complicated as addr_base is contained
14827      in the DIE.
14828
14829      We don't need to read the entire CU(/TU).
14830      We just need the header and top level die.
14831
14832      IWBN to use the aging mechanism to let us lazily later discard the CU.
14833      For now we skip this optimization.  */
14834
14835   if (cu != NULL)
14836     {
14837       addr_base = cu->addr_base;
14838       addr_size = cu->header.addr_size;
14839     }
14840   else
14841     {
14842       struct dwarf2_read_addr_index_data aidata;
14843
14844       /* Note: We can't use init_cutu_and_read_dies_simple here,
14845          we need addr_base.  */
14846       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14847                                dwarf2_read_addr_index_reader, &aidata);
14848       addr_base = aidata.addr_base;
14849       addr_size = aidata.addr_size;
14850     }
14851
14852   return read_addr_index_1 (addr_index, addr_base, addr_size);
14853 }
14854
14855 /* Given a DW_AT_str_index, fetch the string.  */
14856
14857 static char *
14858 read_str_index (const struct die_reader_specs *reader,
14859                 struct dwarf2_cu *cu, ULONGEST str_index)
14860 {
14861   struct objfile *objfile = dwarf2_per_objfile->objfile;
14862   const char *dwo_name = objfile->name;
14863   bfd *abfd = objfile->obfd;
14864   struct dwo_sections *sections = &reader->dwo_file->sections;
14865   gdb_byte *info_ptr;
14866   ULONGEST str_offset;
14867
14868   dwarf2_read_section (objfile, &sections->str);
14869   dwarf2_read_section (objfile, &sections->str_offsets);
14870   if (sections->str.buffer == NULL)
14871     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14872              " in CU at offset 0x%lx [in module %s]"),
14873            (long) cu->header.offset.sect_off, dwo_name);
14874   if (sections->str_offsets.buffer == NULL)
14875     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14876              " in CU at offset 0x%lx [in module %s]"),
14877            (long) cu->header.offset.sect_off, dwo_name);
14878   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14879     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14880              " section in CU at offset 0x%lx [in module %s]"),
14881            (long) cu->header.offset.sect_off, dwo_name);
14882   info_ptr = (sections->str_offsets.buffer
14883               + str_index * cu->header.offset_size);
14884   if (cu->header.offset_size == 4)
14885     str_offset = bfd_get_32 (abfd, info_ptr);
14886   else
14887     str_offset = bfd_get_64 (abfd, info_ptr);
14888   if (str_offset >= sections->str.size)
14889     error (_("Offset from DW_FORM_str_index pointing outside of"
14890              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14891            (long) cu->header.offset.sect_off, dwo_name);
14892   return (char *) (sections->str.buffer + str_offset);
14893 }
14894
14895 /* Return the length of an LEB128 number in BUF.  */
14896
14897 static int
14898 leb128_size (const gdb_byte *buf)
14899 {
14900   const gdb_byte *begin = buf;
14901   gdb_byte byte;
14902
14903   while (1)
14904     {
14905       byte = *buf++;
14906       if ((byte & 128) == 0)
14907         return buf - begin;
14908     }
14909 }
14910
14911 static void
14912 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14913 {
14914   switch (lang)
14915     {
14916     case DW_LANG_C89:
14917     case DW_LANG_C99:
14918     case DW_LANG_C:
14919       cu->language = language_c;
14920       break;
14921     case DW_LANG_C_plus_plus:
14922       cu->language = language_cplus;
14923       break;
14924     case DW_LANG_D:
14925       cu->language = language_d;
14926       break;
14927     case DW_LANG_Fortran77:
14928     case DW_LANG_Fortran90:
14929     case DW_LANG_Fortran95:
14930       cu->language = language_fortran;
14931       break;
14932     case DW_LANG_Go:
14933       cu->language = language_go;
14934       break;
14935     case DW_LANG_Mips_Assembler:
14936       cu->language = language_asm;
14937       break;
14938     case DW_LANG_Java:
14939       cu->language = language_java;
14940       break;
14941     case DW_LANG_Ada83:
14942     case DW_LANG_Ada95:
14943       cu->language = language_ada;
14944       break;
14945     case DW_LANG_Modula2:
14946       cu->language = language_m2;
14947       break;
14948     case DW_LANG_Pascal83:
14949       cu->language = language_pascal;
14950       break;
14951     case DW_LANG_ObjC:
14952       cu->language = language_objc;
14953       break;
14954     case DW_LANG_Cobol74:
14955     case DW_LANG_Cobol85:
14956     default:
14957       cu->language = language_minimal;
14958       break;
14959     }
14960   cu->language_defn = language_def (cu->language);
14961 }
14962
14963 /* Return the named attribute or NULL if not there.  */
14964
14965 static struct attribute *
14966 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
14967 {
14968   for (;;)
14969     {
14970       unsigned int i;
14971       struct attribute *spec = NULL;
14972
14973       for (i = 0; i < die->num_attrs; ++i)
14974         {
14975           if (die->attrs[i].name == name)
14976             return &die->attrs[i];
14977           if (die->attrs[i].name == DW_AT_specification
14978               || die->attrs[i].name == DW_AT_abstract_origin)
14979             spec = &die->attrs[i];
14980         }
14981
14982       if (!spec)
14983         break;
14984
14985       die = follow_die_ref (die, spec, &cu);
14986     }
14987
14988   return NULL;
14989 }
14990
14991 /* Return the named attribute or NULL if not there,
14992    but do not follow DW_AT_specification, etc.
14993    This is for use in contexts where we're reading .debug_types dies.
14994    Following DW_AT_specification, DW_AT_abstract_origin will take us
14995    back up the chain, and we want to go down.  */
14996
14997 static struct attribute *
14998 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
14999 {
15000   unsigned int i;
15001
15002   for (i = 0; i < die->num_attrs; ++i)
15003     if (die->attrs[i].name == name)
15004       return &die->attrs[i];
15005
15006   return NULL;
15007 }
15008
15009 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15010    and holds a non-zero value.  This function should only be used for
15011    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15012
15013 static int
15014 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15015 {
15016   struct attribute *attr = dwarf2_attr (die, name, cu);
15017
15018   return (attr && DW_UNSND (attr));
15019 }
15020
15021 static int
15022 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15023 {
15024   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15025      which value is non-zero.  However, we have to be careful with
15026      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15027      (via dwarf2_flag_true_p) follows this attribute.  So we may
15028      end up accidently finding a declaration attribute that belongs
15029      to a different DIE referenced by the specification attribute,
15030      even though the given DIE does not have a declaration attribute.  */
15031   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15032           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15033 }
15034
15035 /* Return the die giving the specification for DIE, if there is
15036    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15037    containing the return value on output.  If there is no
15038    specification, but there is an abstract origin, that is
15039    returned.  */
15040
15041 static struct die_info *
15042 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15043 {
15044   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15045                                              *spec_cu);
15046
15047   if (spec_attr == NULL)
15048     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15049
15050   if (spec_attr == NULL)
15051     return NULL;
15052   else
15053     return follow_die_ref (die, spec_attr, spec_cu);
15054 }
15055
15056 /* Free the line_header structure *LH, and any arrays and strings it
15057    refers to.
15058    NOTE: This is also used as a "cleanup" function.  */
15059
15060 static void
15061 free_line_header (struct line_header *lh)
15062 {
15063   if (lh->standard_opcode_lengths)
15064     xfree (lh->standard_opcode_lengths);
15065
15066   /* Remember that all the lh->file_names[i].name pointers are
15067      pointers into debug_line_buffer, and don't need to be freed.  */
15068   if (lh->file_names)
15069     xfree (lh->file_names);
15070
15071   /* Similarly for the include directory names.  */
15072   if (lh->include_dirs)
15073     xfree (lh->include_dirs);
15074
15075   xfree (lh);
15076 }
15077
15078 /* Add an entry to LH's include directory table.  */
15079
15080 static void
15081 add_include_dir (struct line_header *lh, char *include_dir)
15082 {
15083   /* Grow the array if necessary.  */
15084   if (lh->include_dirs_size == 0)
15085     {
15086       lh->include_dirs_size = 1; /* for testing */
15087       lh->include_dirs = xmalloc (lh->include_dirs_size
15088                                   * sizeof (*lh->include_dirs));
15089     }
15090   else if (lh->num_include_dirs >= lh->include_dirs_size)
15091     {
15092       lh->include_dirs_size *= 2;
15093       lh->include_dirs = xrealloc (lh->include_dirs,
15094                                    (lh->include_dirs_size
15095                                     * sizeof (*lh->include_dirs)));
15096     }
15097
15098   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15099 }
15100
15101 /* Add an entry to LH's file name table.  */
15102
15103 static void
15104 add_file_name (struct line_header *lh,
15105                char *name,
15106                unsigned int dir_index,
15107                unsigned int mod_time,
15108                unsigned int length)
15109 {
15110   struct file_entry *fe;
15111
15112   /* Grow the array if necessary.  */
15113   if (lh->file_names_size == 0)
15114     {
15115       lh->file_names_size = 1; /* for testing */
15116       lh->file_names = xmalloc (lh->file_names_size
15117                                 * sizeof (*lh->file_names));
15118     }
15119   else if (lh->num_file_names >= lh->file_names_size)
15120     {
15121       lh->file_names_size *= 2;
15122       lh->file_names = xrealloc (lh->file_names,
15123                                  (lh->file_names_size
15124                                   * sizeof (*lh->file_names)));
15125     }
15126
15127   fe = &lh->file_names[lh->num_file_names++];
15128   fe->name = name;
15129   fe->dir_index = dir_index;
15130   fe->mod_time = mod_time;
15131   fe->length = length;
15132   fe->included_p = 0;
15133   fe->symtab = NULL;
15134 }
15135
15136 /* A convenience function to find the proper .debug_line section for a
15137    CU.  */
15138
15139 static struct dwarf2_section_info *
15140 get_debug_line_section (struct dwarf2_cu *cu)
15141 {
15142   struct dwarf2_section_info *section;
15143
15144   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15145      DWO file.  */
15146   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15147     section = &cu->dwo_unit->dwo_file->sections.line;
15148   else if (cu->per_cu->is_dwz)
15149     {
15150       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15151
15152       section = &dwz->line;
15153     }
15154   else
15155     section = &dwarf2_per_objfile->line;
15156
15157   return section;
15158 }
15159
15160 /* Read the statement program header starting at OFFSET in
15161    .debug_line, or .debug_line.dwo.  Return a pointer
15162    to a struct line_header, allocated using xmalloc.
15163
15164    NOTE: the strings in the include directory and file name tables of
15165    the returned object point into the dwarf line section buffer,
15166    and must not be freed.  */
15167
15168 static struct line_header *
15169 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15170 {
15171   struct cleanup *back_to;
15172   struct line_header *lh;
15173   gdb_byte *line_ptr;
15174   unsigned int bytes_read, offset_size;
15175   int i;
15176   char *cur_dir, *cur_file;
15177   struct dwarf2_section_info *section;
15178   bfd *abfd;
15179
15180   section = get_debug_line_section (cu);
15181   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15182   if (section->buffer == NULL)
15183     {
15184       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15185         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15186       else
15187         complaint (&symfile_complaints, _("missing .debug_line section"));
15188       return 0;
15189     }
15190
15191   /* We can't do this until we know the section is non-empty.
15192      Only then do we know we have such a section.  */
15193   abfd = section->asection->owner;
15194
15195   /* Make sure that at least there's room for the total_length field.
15196      That could be 12 bytes long, but we're just going to fudge that.  */
15197   if (offset + 4 >= section->size)
15198     {
15199       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15200       return 0;
15201     }
15202
15203   lh = xmalloc (sizeof (*lh));
15204   memset (lh, 0, sizeof (*lh));
15205   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15206                           (void *) lh);
15207
15208   line_ptr = section->buffer + offset;
15209
15210   /* Read in the header.  */
15211   lh->total_length =
15212     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15213                                             &bytes_read, &offset_size);
15214   line_ptr += bytes_read;
15215   if (line_ptr + lh->total_length > (section->buffer + section->size))
15216     {
15217       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15218       return 0;
15219     }
15220   lh->statement_program_end = line_ptr + lh->total_length;
15221   lh->version = read_2_bytes (abfd, line_ptr);
15222   line_ptr += 2;
15223   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15224   line_ptr += offset_size;
15225   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15226   line_ptr += 1;
15227   if (lh->version >= 4)
15228     {
15229       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15230       line_ptr += 1;
15231     }
15232   else
15233     lh->maximum_ops_per_instruction = 1;
15234
15235   if (lh->maximum_ops_per_instruction == 0)
15236     {
15237       lh->maximum_ops_per_instruction = 1;
15238       complaint (&symfile_complaints,
15239                  _("invalid maximum_ops_per_instruction "
15240                    "in `.debug_line' section"));
15241     }
15242
15243   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15244   line_ptr += 1;
15245   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15246   line_ptr += 1;
15247   lh->line_range = read_1_byte (abfd, line_ptr);
15248   line_ptr += 1;
15249   lh->opcode_base = read_1_byte (abfd, line_ptr);
15250   line_ptr += 1;
15251   lh->standard_opcode_lengths
15252     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15253
15254   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15255   for (i = 1; i < lh->opcode_base; ++i)
15256     {
15257       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15258       line_ptr += 1;
15259     }
15260
15261   /* Read directory table.  */
15262   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15263     {
15264       line_ptr += bytes_read;
15265       add_include_dir (lh, cur_dir);
15266     }
15267   line_ptr += bytes_read;
15268
15269   /* Read file name table.  */
15270   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15271     {
15272       unsigned int dir_index, mod_time, length;
15273
15274       line_ptr += bytes_read;
15275       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15276       line_ptr += bytes_read;
15277       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15278       line_ptr += bytes_read;
15279       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15280       line_ptr += bytes_read;
15281
15282       add_file_name (lh, cur_file, dir_index, mod_time, length);
15283     }
15284   line_ptr += bytes_read;
15285   lh->statement_program_start = line_ptr;
15286
15287   if (line_ptr > (section->buffer + section->size))
15288     complaint (&symfile_complaints,
15289                _("line number info header doesn't "
15290                  "fit in `.debug_line' section"));
15291
15292   discard_cleanups (back_to);
15293   return lh;
15294 }
15295
15296 /* Subroutine of dwarf_decode_lines to simplify it.
15297    Return the file name of the psymtab for included file FILE_INDEX
15298    in line header LH of PST.
15299    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15300    If space for the result is malloc'd, it will be freed by a cleanup.
15301    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15302
15303    The function creates dangling cleanup registration.  */
15304
15305 static char *
15306 psymtab_include_file_name (const struct line_header *lh, int file_index,
15307                            const struct partial_symtab *pst,
15308                            const char *comp_dir)
15309 {
15310   const struct file_entry fe = lh->file_names [file_index];
15311   char *include_name = fe.name;
15312   char *include_name_to_compare = include_name;
15313   char *dir_name = NULL;
15314   const char *pst_filename;
15315   char *copied_name = NULL;
15316   int file_is_pst;
15317
15318   if (fe.dir_index)
15319     dir_name = lh->include_dirs[fe.dir_index - 1];
15320
15321   if (!IS_ABSOLUTE_PATH (include_name)
15322       && (dir_name != NULL || comp_dir != NULL))
15323     {
15324       /* Avoid creating a duplicate psymtab for PST.
15325          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15326          Before we do the comparison, however, we need to account
15327          for DIR_NAME and COMP_DIR.
15328          First prepend dir_name (if non-NULL).  If we still don't
15329          have an absolute path prepend comp_dir (if non-NULL).
15330          However, the directory we record in the include-file's
15331          psymtab does not contain COMP_DIR (to match the
15332          corresponding symtab(s)).
15333
15334          Example:
15335
15336          bash$ cd /tmp
15337          bash$ gcc -g ./hello.c
15338          include_name = "hello.c"
15339          dir_name = "."
15340          DW_AT_comp_dir = comp_dir = "/tmp"
15341          DW_AT_name = "./hello.c"  */
15342
15343       if (dir_name != NULL)
15344         {
15345           include_name = concat (dir_name, SLASH_STRING,
15346                                  include_name, (char *)NULL);
15347           include_name_to_compare = include_name;
15348           make_cleanup (xfree, include_name);
15349         }
15350       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15351         {
15352           include_name_to_compare = concat (comp_dir, SLASH_STRING,
15353                                             include_name, (char *)NULL);
15354         }
15355     }
15356
15357   pst_filename = pst->filename;
15358   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15359     {
15360       copied_name = concat (pst->dirname, SLASH_STRING,
15361                             pst_filename, (char *)NULL);
15362       pst_filename = copied_name;
15363     }
15364
15365   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15366
15367   if (include_name_to_compare != include_name)
15368     xfree (include_name_to_compare);
15369   if (copied_name != NULL)
15370     xfree (copied_name);
15371
15372   if (file_is_pst)
15373     return NULL;
15374   return include_name;
15375 }
15376
15377 /* Ignore this record_line request.  */
15378
15379 static void
15380 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15381 {
15382   return;
15383 }
15384
15385 /* Subroutine of dwarf_decode_lines to simplify it.
15386    Process the line number information in LH.  */
15387
15388 static void
15389 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15390                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15391 {
15392   gdb_byte *line_ptr, *extended_end;
15393   gdb_byte *line_end;
15394   unsigned int bytes_read, extended_len;
15395   unsigned char op_code, extended_op, adj_opcode;
15396   CORE_ADDR baseaddr;
15397   struct objfile *objfile = cu->objfile;
15398   bfd *abfd = objfile->obfd;
15399   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15400   const int decode_for_pst_p = (pst != NULL);
15401   struct subfile *last_subfile = NULL;
15402   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15403     = record_line;
15404
15405   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15406
15407   line_ptr = lh->statement_program_start;
15408   line_end = lh->statement_program_end;
15409
15410   /* Read the statement sequences until there's nothing left.  */
15411   while (line_ptr < line_end)
15412     {
15413       /* state machine registers  */
15414       CORE_ADDR address = 0;
15415       unsigned int file = 1;
15416       unsigned int line = 1;
15417       unsigned int column = 0;
15418       int is_stmt = lh->default_is_stmt;
15419       int basic_block = 0;
15420       int end_sequence = 0;
15421       CORE_ADDR addr;
15422       unsigned char op_index = 0;
15423
15424       if (!decode_for_pst_p && lh->num_file_names >= file)
15425         {
15426           /* Start a subfile for the current file of the state machine.  */
15427           /* lh->include_dirs and lh->file_names are 0-based, but the
15428              directory and file name numbers in the statement program
15429              are 1-based.  */
15430           struct file_entry *fe = &lh->file_names[file - 1];
15431           char *dir = NULL;
15432
15433           if (fe->dir_index)
15434             dir = lh->include_dirs[fe->dir_index - 1];
15435
15436           dwarf2_start_subfile (fe->name, dir, comp_dir);
15437         }
15438
15439       /* Decode the table.  */
15440       while (!end_sequence)
15441         {
15442           op_code = read_1_byte (abfd, line_ptr);
15443           line_ptr += 1;
15444           if (line_ptr > line_end)
15445             {
15446               dwarf2_debug_line_missing_end_sequence_complaint ();
15447               break;
15448             }
15449
15450           if (op_code >= lh->opcode_base)
15451             {
15452               /* Special operand.  */
15453               adj_opcode = op_code - lh->opcode_base;
15454               address += (((op_index + (adj_opcode / lh->line_range))
15455                            / lh->maximum_ops_per_instruction)
15456                           * lh->minimum_instruction_length);
15457               op_index = ((op_index + (adj_opcode / lh->line_range))
15458                           % lh->maximum_ops_per_instruction);
15459               line += lh->line_base + (adj_opcode % lh->line_range);
15460               if (lh->num_file_names < file || file == 0)
15461                 dwarf2_debug_line_missing_file_complaint ();
15462               /* For now we ignore lines not starting on an
15463                  instruction boundary.  */
15464               else if (op_index == 0)
15465                 {
15466                   lh->file_names[file - 1].included_p = 1;
15467                   if (!decode_for_pst_p && is_stmt)
15468                     {
15469                       if (last_subfile != current_subfile)
15470                         {
15471                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15472                           if (last_subfile)
15473                             (*p_record_line) (last_subfile, 0, addr);
15474                           last_subfile = current_subfile;
15475                         }
15476                       /* Append row to matrix using current values.  */
15477                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15478                       (*p_record_line) (current_subfile, line, addr);
15479                     }
15480                 }
15481               basic_block = 0;
15482             }
15483           else switch (op_code)
15484             {
15485             case DW_LNS_extended_op:
15486               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15487                                                    &bytes_read);
15488               line_ptr += bytes_read;
15489               extended_end = line_ptr + extended_len;
15490               extended_op = read_1_byte (abfd, line_ptr);
15491               line_ptr += 1;
15492               switch (extended_op)
15493                 {
15494                 case DW_LNE_end_sequence:
15495                   p_record_line = record_line;
15496                   end_sequence = 1;
15497                   break;
15498                 case DW_LNE_set_address:
15499                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15500
15501                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15502                     {
15503                       /* This line table is for a function which has been
15504                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15505
15506                       long line_offset
15507                         = line_ptr - get_debug_line_section (cu)->buffer;
15508
15509                       complaint (&symfile_complaints,
15510                                  _(".debug_line address at offset 0x%lx is 0 "
15511                                    "[in module %s]"),
15512                                  line_offset, objfile->name);
15513                       p_record_line = noop_record_line;
15514                     }
15515
15516                   op_index = 0;
15517                   line_ptr += bytes_read;
15518                   address += baseaddr;
15519                   break;
15520                 case DW_LNE_define_file:
15521                   {
15522                     char *cur_file;
15523                     unsigned int dir_index, mod_time, length;
15524
15525                     cur_file = read_direct_string (abfd, line_ptr,
15526                                                    &bytes_read);
15527                     line_ptr += bytes_read;
15528                     dir_index =
15529                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15530                     line_ptr += bytes_read;
15531                     mod_time =
15532                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15533                     line_ptr += bytes_read;
15534                     length =
15535                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15536                     line_ptr += bytes_read;
15537                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15538                   }
15539                   break;
15540                 case DW_LNE_set_discriminator:
15541                   /* The discriminator is not interesting to the debugger;
15542                      just ignore it.  */
15543                   line_ptr = extended_end;
15544                   break;
15545                 default:
15546                   complaint (&symfile_complaints,
15547                              _("mangled .debug_line section"));
15548                   return;
15549                 }
15550               /* Make sure that we parsed the extended op correctly.  If e.g.
15551                  we expected a different address size than the producer used,
15552                  we may have read the wrong number of bytes.  */
15553               if (line_ptr != extended_end)
15554                 {
15555                   complaint (&symfile_complaints,
15556                              _("mangled .debug_line section"));
15557                   return;
15558                 }
15559               break;
15560             case DW_LNS_copy:
15561               if (lh->num_file_names < file || file == 0)
15562                 dwarf2_debug_line_missing_file_complaint ();
15563               else
15564                 {
15565                   lh->file_names[file - 1].included_p = 1;
15566                   if (!decode_for_pst_p && is_stmt)
15567                     {
15568                       if (last_subfile != current_subfile)
15569                         {
15570                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15571                           if (last_subfile)
15572                             (*p_record_line) (last_subfile, 0, addr);
15573                           last_subfile = current_subfile;
15574                         }
15575                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15576                       (*p_record_line) (current_subfile, line, addr);
15577                     }
15578                 }
15579               basic_block = 0;
15580               break;
15581             case DW_LNS_advance_pc:
15582               {
15583                 CORE_ADDR adjust
15584                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15585
15586                 address += (((op_index + adjust)
15587                              / lh->maximum_ops_per_instruction)
15588                             * lh->minimum_instruction_length);
15589                 op_index = ((op_index + adjust)
15590                             % lh->maximum_ops_per_instruction);
15591                 line_ptr += bytes_read;
15592               }
15593               break;
15594             case DW_LNS_advance_line:
15595               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15596               line_ptr += bytes_read;
15597               break;
15598             case DW_LNS_set_file:
15599               {
15600                 /* The arrays lh->include_dirs and lh->file_names are
15601                    0-based, but the directory and file name numbers in
15602                    the statement program are 1-based.  */
15603                 struct file_entry *fe;
15604                 char *dir = NULL;
15605
15606                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15607                 line_ptr += bytes_read;
15608                 if (lh->num_file_names < file || file == 0)
15609                   dwarf2_debug_line_missing_file_complaint ();
15610                 else
15611                   {
15612                     fe = &lh->file_names[file - 1];
15613                     if (fe->dir_index)
15614                       dir = lh->include_dirs[fe->dir_index - 1];
15615                     if (!decode_for_pst_p)
15616                       {
15617                         last_subfile = current_subfile;
15618                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15619                       }
15620                   }
15621               }
15622               break;
15623             case DW_LNS_set_column:
15624               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15625               line_ptr += bytes_read;
15626               break;
15627             case DW_LNS_negate_stmt:
15628               is_stmt = (!is_stmt);
15629               break;
15630             case DW_LNS_set_basic_block:
15631               basic_block = 1;
15632               break;
15633             /* Add to the address register of the state machine the
15634                address increment value corresponding to special opcode
15635                255.  I.e., this value is scaled by the minimum
15636                instruction length since special opcode 255 would have
15637                scaled the increment.  */
15638             case DW_LNS_const_add_pc:
15639               {
15640                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15641
15642                 address += (((op_index + adjust)
15643                              / lh->maximum_ops_per_instruction)
15644                             * lh->minimum_instruction_length);
15645                 op_index = ((op_index + adjust)
15646                             % lh->maximum_ops_per_instruction);
15647               }
15648               break;
15649             case DW_LNS_fixed_advance_pc:
15650               address += read_2_bytes (abfd, line_ptr);
15651               op_index = 0;
15652               line_ptr += 2;
15653               break;
15654             default:
15655               {
15656                 /* Unknown standard opcode, ignore it.  */
15657                 int i;
15658
15659                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15660                   {
15661                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15662                     line_ptr += bytes_read;
15663                   }
15664               }
15665             }
15666         }
15667       if (lh->num_file_names < file || file == 0)
15668         dwarf2_debug_line_missing_file_complaint ();
15669       else
15670         {
15671           lh->file_names[file - 1].included_p = 1;
15672           if (!decode_for_pst_p)
15673             {
15674               addr = gdbarch_addr_bits_remove (gdbarch, address);
15675               (*p_record_line) (current_subfile, 0, addr);
15676             }
15677         }
15678     }
15679 }
15680
15681 /* Decode the Line Number Program (LNP) for the given line_header
15682    structure and CU.  The actual information extracted and the type
15683    of structures created from the LNP depends on the value of PST.
15684
15685    1. If PST is NULL, then this procedure uses the data from the program
15686       to create all necessary symbol tables, and their linetables.
15687
15688    2. If PST is not NULL, this procedure reads the program to determine
15689       the list of files included by the unit represented by PST, and
15690       builds all the associated partial symbol tables.
15691
15692    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15693    It is used for relative paths in the line table.
15694    NOTE: When processing partial symtabs (pst != NULL),
15695    comp_dir == pst->dirname.
15696
15697    NOTE: It is important that psymtabs have the same file name (via strcmp)
15698    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15699    symtab we don't use it in the name of the psymtabs we create.
15700    E.g. expand_line_sal requires this when finding psymtabs to expand.
15701    A good testcase for this is mb-inline.exp.  */
15702
15703 static void
15704 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15705                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15706                     int want_line_info)
15707 {
15708   struct objfile *objfile = cu->objfile;
15709   const int decode_for_pst_p = (pst != NULL);
15710   struct subfile *first_subfile = current_subfile;
15711
15712   if (want_line_info)
15713     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15714
15715   if (decode_for_pst_p)
15716     {
15717       int file_index;
15718
15719       /* Now that we're done scanning the Line Header Program, we can
15720          create the psymtab of each included file.  */
15721       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15722         if (lh->file_names[file_index].included_p == 1)
15723           {
15724             char *include_name =
15725               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15726             if (include_name != NULL)
15727               dwarf2_create_include_psymtab (include_name, pst, objfile);
15728           }
15729     }
15730   else
15731     {
15732       /* Make sure a symtab is created for every file, even files
15733          which contain only variables (i.e. no code with associated
15734          line numbers).  */
15735       int i;
15736
15737       for (i = 0; i < lh->num_file_names; i++)
15738         {
15739           char *dir = NULL;
15740           struct file_entry *fe;
15741
15742           fe = &lh->file_names[i];
15743           if (fe->dir_index)
15744             dir = lh->include_dirs[fe->dir_index - 1];
15745           dwarf2_start_subfile (fe->name, dir, comp_dir);
15746
15747           /* Skip the main file; we don't need it, and it must be
15748              allocated last, so that it will show up before the
15749              non-primary symtabs in the objfile's symtab list.  */
15750           if (current_subfile == first_subfile)
15751             continue;
15752
15753           if (current_subfile->symtab == NULL)
15754             current_subfile->symtab = allocate_symtab (current_subfile->name,
15755                                                        objfile);
15756           fe->symtab = current_subfile->symtab;
15757         }
15758     }
15759 }
15760
15761 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15762    DIRNAME the name of the source directory which contains FILENAME
15763    or NULL if not known.  COMP_DIR is the compilation directory for the
15764    linetable's compilation unit or NULL if not known.
15765    This routine tries to keep line numbers from identical absolute and
15766    relative file names in a common subfile.
15767
15768    Using the `list' example from the GDB testsuite, which resides in
15769    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15770    of /srcdir/list0.c yields the following debugging information for list0.c:
15771
15772    DW_AT_name:          /srcdir/list0.c
15773    DW_AT_comp_dir:              /compdir
15774    files.files[0].name: list0.h
15775    files.files[0].dir:  /srcdir
15776    files.files[1].name: list0.c
15777    files.files[1].dir:  /srcdir
15778
15779    The line number information for list0.c has to end up in a single
15780    subfile, so that `break /srcdir/list0.c:1' works as expected.
15781    start_subfile will ensure that this happens provided that we pass the
15782    concatenation of files.files[1].dir and files.files[1].name as the
15783    subfile's name.  */
15784
15785 static void
15786 dwarf2_start_subfile (char *filename, const char *dirname,
15787                       const char *comp_dir)
15788 {
15789   char *fullname;
15790
15791   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15792      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15793      second argument to start_subfile.  To be consistent, we do the
15794      same here.  In order not to lose the line information directory,
15795      we concatenate it to the filename when it makes sense.
15796      Note that the Dwarf3 standard says (speaking of filenames in line
15797      information): ``The directory index is ignored for file names
15798      that represent full path names''.  Thus ignoring dirname in the
15799      `else' branch below isn't an issue.  */
15800
15801   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15802     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15803   else
15804     fullname = filename;
15805
15806   start_subfile (fullname, comp_dir);
15807
15808   if (fullname != filename)
15809     xfree (fullname);
15810 }
15811
15812 /* Start a symtab for DWARF.
15813    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15814
15815 static void
15816 dwarf2_start_symtab (struct dwarf2_cu *cu,
15817                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15818 {
15819   start_symtab (name, comp_dir, low_pc);
15820   record_debugformat ("DWARF 2");
15821   record_producer (cu->producer);
15822
15823   /* We assume that we're processing GCC output.  */
15824   processing_gcc_compilation = 2;
15825
15826   cu->processing_has_namespace_info = 0;
15827 }
15828
15829 static void
15830 var_decode_location (struct attribute *attr, struct symbol *sym,
15831                      struct dwarf2_cu *cu)
15832 {
15833   struct objfile *objfile = cu->objfile;
15834   struct comp_unit_head *cu_header = &cu->header;
15835
15836   /* NOTE drow/2003-01-30: There used to be a comment and some special
15837      code here to turn a symbol with DW_AT_external and a
15838      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15839      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15840      with some versions of binutils) where shared libraries could have
15841      relocations against symbols in their debug information - the
15842      minimal symbol would have the right address, but the debug info
15843      would not.  It's no longer necessary, because we will explicitly
15844      apply relocations when we read in the debug information now.  */
15845
15846   /* A DW_AT_location attribute with no contents indicates that a
15847      variable has been optimized away.  */
15848   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15849     {
15850       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15851       return;
15852     }
15853
15854   /* Handle one degenerate form of location expression specially, to
15855      preserve GDB's previous behavior when section offsets are
15856      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15857      then mark this symbol as LOC_STATIC.  */
15858
15859   if (attr_form_is_block (attr)
15860       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15861            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15862           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15863               && (DW_BLOCK (attr)->size
15864                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15865     {
15866       unsigned int dummy;
15867
15868       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15869         SYMBOL_VALUE_ADDRESS (sym) =
15870           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15871       else
15872         SYMBOL_VALUE_ADDRESS (sym) =
15873           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15874       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
15875       fixup_symbol_section (sym, objfile);
15876       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15877                                               SYMBOL_SECTION (sym));
15878       return;
15879     }
15880
15881   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15882      expression evaluator, and use LOC_COMPUTED only when necessary
15883      (i.e. when the value of a register or memory location is
15884      referenced, or a thread-local block, etc.).  Then again, it might
15885      not be worthwhile.  I'm assuming that it isn't unless performance
15886      or memory numbers show me otherwise.  */
15887
15888   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
15889
15890   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
15891     cu->has_loclist = 1;
15892 }
15893
15894 /* Given a pointer to a DWARF information entry, figure out if we need
15895    to make a symbol table entry for it, and if so, create a new entry
15896    and return a pointer to it.
15897    If TYPE is NULL, determine symbol type from the die, otherwise
15898    used the passed type.
15899    If SPACE is not NULL, use it to hold the new symbol.  If it is
15900    NULL, allocate a new symbol on the objfile's obstack.  */
15901
15902 static struct symbol *
15903 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15904                  struct symbol *space)
15905 {
15906   struct objfile *objfile = cu->objfile;
15907   struct symbol *sym = NULL;
15908   const char *name;
15909   struct attribute *attr = NULL;
15910   struct attribute *attr2 = NULL;
15911   CORE_ADDR baseaddr;
15912   struct pending **list_to_add = NULL;
15913
15914   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15915
15916   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15917
15918   name = dwarf2_name (die, cu);
15919   if (name)
15920     {
15921       const char *linkagename;
15922       int suppress_add = 0;
15923
15924       if (space)
15925         sym = space;
15926       else
15927         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
15928       OBJSTAT (objfile, n_syms++);
15929
15930       /* Cache this symbol's name and the name's demangled form (if any).  */
15931       SYMBOL_SET_LANGUAGE (sym, cu->language);
15932       linkagename = dwarf2_physname (name, die, cu);
15933       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15934
15935       /* Fortran does not have mangling standard and the mangling does differ
15936          between gfortran, iFort etc.  */
15937       if (cu->language == language_fortran
15938           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15939         symbol_set_demangled_name (&(sym->ginfo),
15940                                    dwarf2_full_name (name, die, cu),
15941                                    NULL);
15942
15943       /* Default assumptions.
15944          Use the passed type or decode it from the die.  */
15945       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15946       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15947       if (type != NULL)
15948         SYMBOL_TYPE (sym) = type;
15949       else
15950         SYMBOL_TYPE (sym) = die_type (die, cu);
15951       attr = dwarf2_attr (die,
15952                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
15953                           cu);
15954       if (attr)
15955         {
15956           SYMBOL_LINE (sym) = DW_UNSND (attr);
15957         }
15958
15959       attr = dwarf2_attr (die,
15960                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
15961                           cu);
15962       if (attr)
15963         {
15964           int file_index = DW_UNSND (attr);
15965
15966           if (cu->line_header == NULL
15967               || file_index > cu->line_header->num_file_names)
15968             complaint (&symfile_complaints,
15969                        _("file index out of range"));
15970           else if (file_index > 0)
15971             {
15972               struct file_entry *fe;
15973
15974               fe = &cu->line_header->file_names[file_index - 1];
15975               SYMBOL_SYMTAB (sym) = fe->symtab;
15976             }
15977         }
15978
15979       switch (die->tag)
15980         {
15981         case DW_TAG_label:
15982           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15983           if (attr)
15984             {
15985               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
15986             }
15987           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
15988           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
15989           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
15990           add_symbol_to_list (sym, cu->list_in_scope);
15991           break;
15992         case DW_TAG_subprogram:
15993           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15994              finish_block.  */
15995           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
15996           attr2 = dwarf2_attr (die, DW_AT_external, cu);
15997           if ((attr2 && (DW_UNSND (attr2) != 0))
15998               || cu->language == language_ada)
15999             {
16000               /* Subprograms marked external are stored as a global symbol.
16001                  Ada subprograms, whether marked external or not, are always
16002                  stored as a global symbol, because we want to be able to
16003                  access them globally.  For instance, we want to be able
16004                  to break on a nested subprogram without having to
16005                  specify the context.  */
16006               list_to_add = &global_symbols;
16007             }
16008           else
16009             {
16010               list_to_add = cu->list_in_scope;
16011             }
16012           break;
16013         case DW_TAG_inlined_subroutine:
16014           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16015              finish_block.  */
16016           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16017           SYMBOL_INLINED (sym) = 1;
16018           list_to_add = cu->list_in_scope;
16019           break;
16020         case DW_TAG_template_value_param:
16021           suppress_add = 1;
16022           /* Fall through.  */
16023         case DW_TAG_constant:
16024         case DW_TAG_variable:
16025         case DW_TAG_member:
16026           /* Compilation with minimal debug info may result in
16027              variables with missing type entries.  Change the
16028              misleading `void' type to something sensible.  */
16029           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16030             SYMBOL_TYPE (sym)
16031               = objfile_type (objfile)->nodebug_data_symbol;
16032
16033           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16034           /* In the case of DW_TAG_member, we should only be called for
16035              static const members.  */
16036           if (die->tag == DW_TAG_member)
16037             {
16038               /* dwarf2_add_field uses die_is_declaration,
16039                  so we do the same.  */
16040               gdb_assert (die_is_declaration (die, cu));
16041               gdb_assert (attr);
16042             }
16043           if (attr)
16044             {
16045               dwarf2_const_value (attr, sym, cu);
16046               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16047               if (!suppress_add)
16048                 {
16049                   if (attr2 && (DW_UNSND (attr2) != 0))
16050                     list_to_add = &global_symbols;
16051                   else
16052                     list_to_add = cu->list_in_scope;
16053                 }
16054               break;
16055             }
16056           attr = dwarf2_attr (die, DW_AT_location, cu);
16057           if (attr)
16058             {
16059               var_decode_location (attr, sym, cu);
16060               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16061
16062               /* Fortran explicitly imports any global symbols to the local
16063                  scope by DW_TAG_common_block.  */
16064               if (cu->language == language_fortran && die->parent
16065                   && die->parent->tag == DW_TAG_common_block)
16066                 attr2 = NULL;
16067
16068               if (SYMBOL_CLASS (sym) == LOC_STATIC
16069                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16070                   && !dwarf2_per_objfile->has_section_at_zero)
16071                 {
16072                   /* When a static variable is eliminated by the linker,
16073                      the corresponding debug information is not stripped
16074                      out, but the variable address is set to null;
16075                      do not add such variables into symbol table.  */
16076                 }
16077               else if (attr2 && (DW_UNSND (attr2) != 0))
16078                 {
16079                   /* Workaround gfortran PR debug/40040 - it uses
16080                      DW_AT_location for variables in -fPIC libraries which may
16081                      get overriden by other libraries/executable and get
16082                      a different address.  Resolve it by the minimal symbol
16083                      which may come from inferior's executable using copy
16084                      relocation.  Make this workaround only for gfortran as for
16085                      other compilers GDB cannot guess the minimal symbol
16086                      Fortran mangling kind.  */
16087                   if (cu->language == language_fortran && die->parent
16088                       && die->parent->tag == DW_TAG_module
16089                       && cu->producer
16090                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16091                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16092
16093                   /* A variable with DW_AT_external is never static,
16094                      but it may be block-scoped.  */
16095                   list_to_add = (cu->list_in_scope == &file_symbols
16096                                  ? &global_symbols : cu->list_in_scope);
16097                 }
16098               else
16099                 list_to_add = cu->list_in_scope;
16100             }
16101           else
16102             {
16103               /* We do not know the address of this symbol.
16104                  If it is an external symbol and we have type information
16105                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16106                  The address of the variable will then be determined from
16107                  the minimal symbol table whenever the variable is
16108                  referenced.  */
16109               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16110
16111               /* Fortran explicitly imports any global symbols to the local
16112                  scope by DW_TAG_common_block.  */
16113               if (cu->language == language_fortran && die->parent
16114                   && die->parent->tag == DW_TAG_common_block)
16115                 {
16116                   /* SYMBOL_CLASS doesn't matter here because
16117                      read_common_block is going to reset it.  */
16118                   if (!suppress_add)
16119                     list_to_add = cu->list_in_scope;
16120                 }
16121               else if (attr2 && (DW_UNSND (attr2) != 0)
16122                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16123                 {
16124                   /* A variable with DW_AT_external is never static, but it
16125                      may be block-scoped.  */
16126                   list_to_add = (cu->list_in_scope == &file_symbols
16127                                  ? &global_symbols : cu->list_in_scope);
16128
16129                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16130                 }
16131               else if (!die_is_declaration (die, cu))
16132                 {
16133                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16134                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16135                   if (!suppress_add)
16136                     list_to_add = cu->list_in_scope;
16137                 }
16138             }
16139           break;
16140         case DW_TAG_formal_parameter:
16141           /* If we are inside a function, mark this as an argument.  If
16142              not, we might be looking at an argument to an inlined function
16143              when we do not have enough information to show inlined frames;
16144              pretend it's a local variable in that case so that the user can
16145              still see it.  */
16146           if (context_stack_depth > 0
16147               && context_stack[context_stack_depth - 1].name != NULL)
16148             SYMBOL_IS_ARGUMENT (sym) = 1;
16149           attr = dwarf2_attr (die, DW_AT_location, cu);
16150           if (attr)
16151             {
16152               var_decode_location (attr, sym, cu);
16153             }
16154           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16155           if (attr)
16156             {
16157               dwarf2_const_value (attr, sym, cu);
16158             }
16159
16160           list_to_add = cu->list_in_scope;
16161           break;
16162         case DW_TAG_unspecified_parameters:
16163           /* From varargs functions; gdb doesn't seem to have any
16164              interest in this information, so just ignore it for now.
16165              (FIXME?) */
16166           break;
16167         case DW_TAG_template_type_param:
16168           suppress_add = 1;
16169           /* Fall through.  */
16170         case DW_TAG_class_type:
16171         case DW_TAG_interface_type:
16172         case DW_TAG_structure_type:
16173         case DW_TAG_union_type:
16174         case DW_TAG_set_type:
16175         case DW_TAG_enumeration_type:
16176           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16177           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16178
16179           {
16180             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16181                really ever be static objects: otherwise, if you try
16182                to, say, break of a class's method and you're in a file
16183                which doesn't mention that class, it won't work unless
16184                the check for all static symbols in lookup_symbol_aux
16185                saves you.  See the OtherFileClass tests in
16186                gdb.c++/namespace.exp.  */
16187
16188             if (!suppress_add)
16189               {
16190                 list_to_add = (cu->list_in_scope == &file_symbols
16191                                && (cu->language == language_cplus
16192                                    || cu->language == language_java)
16193                                ? &global_symbols : cu->list_in_scope);
16194
16195                 /* The semantics of C++ state that "struct foo {
16196                    ... }" also defines a typedef for "foo".  A Java
16197                    class declaration also defines a typedef for the
16198                    class.  */
16199                 if (cu->language == language_cplus
16200                     || cu->language == language_java
16201                     || cu->language == language_ada)
16202                   {
16203                     /* The symbol's name is already allocated along
16204                        with this objfile, so we don't need to
16205                        duplicate it for the type.  */
16206                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16207                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16208                   }
16209               }
16210           }
16211           break;
16212         case DW_TAG_typedef:
16213           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16214           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16215           list_to_add = cu->list_in_scope;
16216           break;
16217         case DW_TAG_base_type:
16218         case DW_TAG_subrange_type:
16219           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16220           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16221           list_to_add = cu->list_in_scope;
16222           break;
16223         case DW_TAG_enumerator:
16224           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16225           if (attr)
16226             {
16227               dwarf2_const_value (attr, sym, cu);
16228             }
16229           {
16230             /* NOTE: carlton/2003-11-10: See comment above in the
16231                DW_TAG_class_type, etc. block.  */
16232
16233             list_to_add = (cu->list_in_scope == &file_symbols
16234                            && (cu->language == language_cplus
16235                                || cu->language == language_java)
16236                            ? &global_symbols : cu->list_in_scope);
16237           }
16238           break;
16239         case DW_TAG_namespace:
16240           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16241           list_to_add = &global_symbols;
16242           break;
16243         case DW_TAG_common_block:
16244           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16245           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16246           add_symbol_to_list (sym, cu->list_in_scope);
16247           break;
16248         default:
16249           /* Not a tag we recognize.  Hopefully we aren't processing
16250              trash data, but since we must specifically ignore things
16251              we don't recognize, there is nothing else we should do at
16252              this point.  */
16253           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16254                      dwarf_tag_name (die->tag));
16255           break;
16256         }
16257
16258       if (suppress_add)
16259         {
16260           sym->hash_next = objfile->template_symbols;
16261           objfile->template_symbols = sym;
16262           list_to_add = NULL;
16263         }
16264
16265       if (list_to_add != NULL)
16266         add_symbol_to_list (sym, list_to_add);
16267
16268       /* For the benefit of old versions of GCC, check for anonymous
16269          namespaces based on the demangled name.  */
16270       if (!cu->processing_has_namespace_info
16271           && cu->language == language_cplus)
16272         cp_scan_for_anonymous_namespaces (sym, objfile);
16273     }
16274   return (sym);
16275 }
16276
16277 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16278
16279 static struct symbol *
16280 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16281 {
16282   return new_symbol_full (die, type, cu, NULL);
16283 }
16284
16285 /* Given an attr with a DW_FORM_dataN value in host byte order,
16286    zero-extend it as appropriate for the symbol's type.  The DWARF
16287    standard (v4) is not entirely clear about the meaning of using
16288    DW_FORM_dataN for a constant with a signed type, where the type is
16289    wider than the data.  The conclusion of a discussion on the DWARF
16290    list was that this is unspecified.  We choose to always zero-extend
16291    because that is the interpretation long in use by GCC.  */
16292
16293 static gdb_byte *
16294 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16295                          const char *name, struct obstack *obstack,
16296                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16297 {
16298   struct objfile *objfile = cu->objfile;
16299   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16300                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16301   LONGEST l = DW_UNSND (attr);
16302
16303   if (bits < sizeof (*value) * 8)
16304     {
16305       l &= ((LONGEST) 1 << bits) - 1;
16306       *value = l;
16307     }
16308   else if (bits == sizeof (*value) * 8)
16309     *value = l;
16310   else
16311     {
16312       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16313       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16314       return bytes;
16315     }
16316
16317   return NULL;
16318 }
16319
16320 /* Read a constant value from an attribute.  Either set *VALUE, or if
16321    the value does not fit in *VALUE, set *BYTES - either already
16322    allocated on the objfile obstack, or newly allocated on OBSTACK,
16323    or, set *BATON, if we translated the constant to a location
16324    expression.  */
16325
16326 static void
16327 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16328                          const char *name, struct obstack *obstack,
16329                          struct dwarf2_cu *cu,
16330                          LONGEST *value, gdb_byte **bytes,
16331                          struct dwarf2_locexpr_baton **baton)
16332 {
16333   struct objfile *objfile = cu->objfile;
16334   struct comp_unit_head *cu_header = &cu->header;
16335   struct dwarf_block *blk;
16336   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16337                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16338
16339   *value = 0;
16340   *bytes = NULL;
16341   *baton = NULL;
16342
16343   switch (attr->form)
16344     {
16345     case DW_FORM_addr:
16346     case DW_FORM_GNU_addr_index:
16347       {
16348         gdb_byte *data;
16349
16350         if (TYPE_LENGTH (type) != cu_header->addr_size)
16351           dwarf2_const_value_length_mismatch_complaint (name,
16352                                                         cu_header->addr_size,
16353                                                         TYPE_LENGTH (type));
16354         /* Symbols of this form are reasonably rare, so we just
16355            piggyback on the existing location code rather than writing
16356            a new implementation of symbol_computed_ops.  */
16357         *baton = obstack_alloc (&objfile->objfile_obstack,
16358                                 sizeof (struct dwarf2_locexpr_baton));
16359         (*baton)->per_cu = cu->per_cu;
16360         gdb_assert ((*baton)->per_cu);
16361
16362         (*baton)->size = 2 + cu_header->addr_size;
16363         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16364         (*baton)->data = data;
16365
16366         data[0] = DW_OP_addr;
16367         store_unsigned_integer (&data[1], cu_header->addr_size,
16368                                 byte_order, DW_ADDR (attr));
16369         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16370       }
16371       break;
16372     case DW_FORM_string:
16373     case DW_FORM_strp:
16374     case DW_FORM_GNU_str_index:
16375     case DW_FORM_GNU_strp_alt:
16376       /* DW_STRING is already allocated on the objfile obstack, point
16377          directly to it.  */
16378       *bytes = (gdb_byte *) DW_STRING (attr);
16379       break;
16380     case DW_FORM_block1:
16381     case DW_FORM_block2:
16382     case DW_FORM_block4:
16383     case DW_FORM_block:
16384     case DW_FORM_exprloc:
16385       blk = DW_BLOCK (attr);
16386       if (TYPE_LENGTH (type) != blk->size)
16387         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16388                                                       TYPE_LENGTH (type));
16389       *bytes = blk->data;
16390       break;
16391
16392       /* The DW_AT_const_value attributes are supposed to carry the
16393          symbol's value "represented as it would be on the target
16394          architecture."  By the time we get here, it's already been
16395          converted to host endianness, so we just need to sign- or
16396          zero-extend it as appropriate.  */
16397     case DW_FORM_data1:
16398       *bytes = dwarf2_const_value_data (attr, type, name,
16399                                         obstack, cu, value, 8);
16400       break;
16401     case DW_FORM_data2:
16402       *bytes = dwarf2_const_value_data (attr, type, name,
16403                                         obstack, cu, value, 16);
16404       break;
16405     case DW_FORM_data4:
16406       *bytes = dwarf2_const_value_data (attr, type, name,
16407                                         obstack, cu, value, 32);
16408       break;
16409     case DW_FORM_data8:
16410       *bytes = dwarf2_const_value_data (attr, type, name,
16411                                         obstack, cu, value, 64);
16412       break;
16413
16414     case DW_FORM_sdata:
16415       *value = DW_SND (attr);
16416       break;
16417
16418     case DW_FORM_udata:
16419       *value = DW_UNSND (attr);
16420       break;
16421
16422     default:
16423       complaint (&symfile_complaints,
16424                  _("unsupported const value attribute form: '%s'"),
16425                  dwarf_form_name (attr->form));
16426       *value = 0;
16427       break;
16428     }
16429 }
16430
16431
16432 /* Copy constant value from an attribute to a symbol.  */
16433
16434 static void
16435 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16436                     struct dwarf2_cu *cu)
16437 {
16438   struct objfile *objfile = cu->objfile;
16439   struct comp_unit_head *cu_header = &cu->header;
16440   LONGEST value;
16441   gdb_byte *bytes;
16442   struct dwarf2_locexpr_baton *baton;
16443
16444   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16445                            SYMBOL_PRINT_NAME (sym),
16446                            &objfile->objfile_obstack, cu,
16447                            &value, &bytes, &baton);
16448
16449   if (baton != NULL)
16450     {
16451       SYMBOL_LOCATION_BATON (sym) = baton;
16452       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16453     }
16454   else if (bytes != NULL)
16455      {
16456       SYMBOL_VALUE_BYTES (sym) = bytes;
16457       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16458     }
16459   else
16460     {
16461       SYMBOL_VALUE (sym) = value;
16462       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16463     }
16464 }
16465
16466 /* Return the type of the die in question using its DW_AT_type attribute.  */
16467
16468 static struct type *
16469 die_type (struct die_info *die, struct dwarf2_cu *cu)
16470 {
16471   struct attribute *type_attr;
16472
16473   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16474   if (!type_attr)
16475     {
16476       /* A missing DW_AT_type represents a void type.  */
16477       return objfile_type (cu->objfile)->builtin_void;
16478     }
16479
16480   return lookup_die_type (die, type_attr, cu);
16481 }
16482
16483 /* True iff CU's producer generates GNAT Ada auxiliary information
16484    that allows to find parallel types through that information instead
16485    of having to do expensive parallel lookups by type name.  */
16486
16487 static int
16488 need_gnat_info (struct dwarf2_cu *cu)
16489 {
16490   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16491      of GNAT produces this auxiliary information, without any indication
16492      that it is produced.  Part of enhancing the FSF version of GNAT
16493      to produce that information will be to put in place an indicator
16494      that we can use in order to determine whether the descriptive type
16495      info is available or not.  One suggestion that has been made is
16496      to use a new attribute, attached to the CU die.  For now, assume
16497      that the descriptive type info is not available.  */
16498   return 0;
16499 }
16500
16501 /* Return the auxiliary type of the die in question using its
16502    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16503    attribute is not present.  */
16504
16505 static struct type *
16506 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16507 {
16508   struct attribute *type_attr;
16509
16510   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16511   if (!type_attr)
16512     return NULL;
16513
16514   return lookup_die_type (die, type_attr, cu);
16515 }
16516
16517 /* If DIE has a descriptive_type attribute, then set the TYPE's
16518    descriptive type accordingly.  */
16519
16520 static void
16521 set_descriptive_type (struct type *type, struct die_info *die,
16522                       struct dwarf2_cu *cu)
16523 {
16524   struct type *descriptive_type = die_descriptive_type (die, cu);
16525
16526   if (descriptive_type)
16527     {
16528       ALLOCATE_GNAT_AUX_TYPE (type);
16529       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16530     }
16531 }
16532
16533 /* Return the containing type of the die in question using its
16534    DW_AT_containing_type attribute.  */
16535
16536 static struct type *
16537 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16538 {
16539   struct attribute *type_attr;
16540
16541   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16542   if (!type_attr)
16543     error (_("Dwarf Error: Problem turning containing type into gdb type "
16544              "[in module %s]"), cu->objfile->name);
16545
16546   return lookup_die_type (die, type_attr, cu);
16547 }
16548
16549 /* Look up the type of DIE in CU using its type attribute ATTR.
16550    If there is no type substitute an error marker.  */
16551
16552 static struct type *
16553 lookup_die_type (struct die_info *die, struct attribute *attr,
16554                  struct dwarf2_cu *cu)
16555 {
16556   struct objfile *objfile = cu->objfile;
16557   struct type *this_type;
16558
16559   /* First see if we have it cached.  */
16560
16561   if (attr->form == DW_FORM_GNU_ref_alt)
16562     {
16563       struct dwarf2_per_cu_data *per_cu;
16564       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16565
16566       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16567       this_type = get_die_type_at_offset (offset, per_cu);
16568     }
16569   else if (is_ref_attr (attr))
16570     {
16571       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16572
16573       this_type = get_die_type_at_offset (offset, cu->per_cu);
16574     }
16575   else if (attr->form == DW_FORM_ref_sig8)
16576     {
16577       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16578
16579       /* sig_type will be NULL if the signatured type is missing from
16580          the debug info.  */
16581       if (sig_type == NULL)
16582         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16583                  "at 0x%x [in module %s]"),
16584                die->offset.sect_off, objfile->name);
16585
16586       gdb_assert (sig_type->per_cu.is_debug_types);
16587       /* If we haven't filled in type_offset_in_section yet, then we
16588          haven't read the type in yet.  */
16589       this_type = NULL;
16590       if (sig_type->type_offset_in_section.sect_off != 0)
16591         {
16592           this_type =
16593             get_die_type_at_offset (sig_type->type_offset_in_section,
16594                                     &sig_type->per_cu);
16595         }
16596     }
16597   else
16598     {
16599       dump_die_for_error (die);
16600       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16601              dwarf_attr_name (attr->name), objfile->name);
16602     }
16603
16604   /* If not cached we need to read it in.  */
16605
16606   if (this_type == NULL)
16607     {
16608       struct die_info *type_die;
16609       struct dwarf2_cu *type_cu = cu;
16610
16611       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16612       /* If we found the type now, it's probably because the type came
16613          from an inter-CU reference and the type's CU got expanded before
16614          ours.  */
16615       this_type = get_die_type (type_die, type_cu);
16616       if (this_type == NULL)
16617         this_type = read_type_die_1 (type_die, type_cu);
16618     }
16619
16620   /* If we still don't have a type use an error marker.  */
16621
16622   if (this_type == NULL)
16623     {
16624       char *message, *saved;
16625
16626       /* read_type_die already issued a complaint.  */
16627       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16628                             objfile->name,
16629                             cu->header.offset.sect_off,
16630                             die->offset.sect_off);
16631       saved = obstack_copy0 (&objfile->objfile_obstack,
16632                              message, strlen (message));
16633       xfree (message);
16634
16635       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16636     }
16637
16638   return this_type;
16639 }
16640
16641 /* Return the type in DIE, CU.
16642    Returns NULL for invalid types.
16643
16644    This first does a lookup in the appropriate type_hash table,
16645    and only reads the die in if necessary.
16646
16647    NOTE: This can be called when reading in partial or full symbols.  */
16648
16649 static struct type *
16650 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16651 {
16652   struct type *this_type;
16653
16654   this_type = get_die_type (die, cu);
16655   if (this_type)
16656     return this_type;
16657
16658   return read_type_die_1 (die, cu);
16659 }
16660
16661 /* Read the type in DIE, CU.
16662    Returns NULL for invalid types.  */
16663
16664 static struct type *
16665 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16666 {
16667   struct type *this_type = NULL;
16668
16669   switch (die->tag)
16670     {
16671     case DW_TAG_class_type:
16672     case DW_TAG_interface_type:
16673     case DW_TAG_structure_type:
16674     case DW_TAG_union_type:
16675       this_type = read_structure_type (die, cu);
16676       break;
16677     case DW_TAG_enumeration_type:
16678       this_type = read_enumeration_type (die, cu);
16679       break;
16680     case DW_TAG_subprogram:
16681     case DW_TAG_subroutine_type:
16682     case DW_TAG_inlined_subroutine:
16683       this_type = read_subroutine_type (die, cu);
16684       break;
16685     case DW_TAG_array_type:
16686       this_type = read_array_type (die, cu);
16687       break;
16688     case DW_TAG_set_type:
16689       this_type = read_set_type (die, cu);
16690       break;
16691     case DW_TAG_pointer_type:
16692       this_type = read_tag_pointer_type (die, cu);
16693       break;
16694     case DW_TAG_ptr_to_member_type:
16695       this_type = read_tag_ptr_to_member_type (die, cu);
16696       break;
16697     case DW_TAG_reference_type:
16698       this_type = read_tag_reference_type (die, cu);
16699       break;
16700     case DW_TAG_const_type:
16701       this_type = read_tag_const_type (die, cu);
16702       break;
16703     case DW_TAG_volatile_type:
16704       this_type = read_tag_volatile_type (die, cu);
16705       break;
16706     case DW_TAG_restrict_type:
16707       this_type = read_tag_restrict_type (die, cu);
16708       break;
16709     case DW_TAG_string_type:
16710       this_type = read_tag_string_type (die, cu);
16711       break;
16712     case DW_TAG_typedef:
16713       this_type = read_typedef (die, cu);
16714       break;
16715     case DW_TAG_subrange_type:
16716       this_type = read_subrange_type (die, cu);
16717       break;
16718     case DW_TAG_base_type:
16719       this_type = read_base_type (die, cu);
16720       break;
16721     case DW_TAG_unspecified_type:
16722       this_type = read_unspecified_type (die, cu);
16723       break;
16724     case DW_TAG_namespace:
16725       this_type = read_namespace_type (die, cu);
16726       break;
16727     case DW_TAG_module:
16728       this_type = read_module_type (die, cu);
16729       break;
16730     default:
16731       complaint (&symfile_complaints,
16732                  _("unexpected tag in read_type_die: '%s'"),
16733                  dwarf_tag_name (die->tag));
16734       break;
16735     }
16736
16737   return this_type;
16738 }
16739
16740 /* See if we can figure out if the class lives in a namespace.  We do
16741    this by looking for a member function; its demangled name will
16742    contain namespace info, if there is any.
16743    Return the computed name or NULL.
16744    Space for the result is allocated on the objfile's obstack.
16745    This is the full-die version of guess_partial_die_structure_name.
16746    In this case we know DIE has no useful parent.  */
16747
16748 static char *
16749 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16750 {
16751   struct die_info *spec_die;
16752   struct dwarf2_cu *spec_cu;
16753   struct die_info *child;
16754
16755   spec_cu = cu;
16756   spec_die = die_specification (die, &spec_cu);
16757   if (spec_die != NULL)
16758     {
16759       die = spec_die;
16760       cu = spec_cu;
16761     }
16762
16763   for (child = die->child;
16764        child != NULL;
16765        child = child->sibling)
16766     {
16767       if (child->tag == DW_TAG_subprogram)
16768         {
16769           struct attribute *attr;
16770
16771           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16772           if (attr == NULL)
16773             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16774           if (attr != NULL)
16775             {
16776               char *actual_name
16777                 = language_class_name_from_physname (cu->language_defn,
16778                                                      DW_STRING (attr));
16779               char *name = NULL;
16780
16781               if (actual_name != NULL)
16782                 {
16783                   const char *die_name = dwarf2_name (die, cu);
16784
16785                   if (die_name != NULL
16786                       && strcmp (die_name, actual_name) != 0)
16787                     {
16788                       /* Strip off the class name from the full name.
16789                          We want the prefix.  */
16790                       int die_name_len = strlen (die_name);
16791                       int actual_name_len = strlen (actual_name);
16792
16793                       /* Test for '::' as a sanity check.  */
16794                       if (actual_name_len > die_name_len + 2
16795                           && actual_name[actual_name_len
16796                                          - die_name_len - 1] == ':')
16797                         name =
16798                           obstack_copy0 (&cu->objfile->objfile_obstack,
16799                                          actual_name,
16800                                          actual_name_len - die_name_len - 2);
16801                     }
16802                 }
16803               xfree (actual_name);
16804               return name;
16805             }
16806         }
16807     }
16808
16809   return NULL;
16810 }
16811
16812 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16813    prefix part in such case.  See
16814    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16815
16816 static char *
16817 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16818 {
16819   struct attribute *attr;
16820   char *base;
16821
16822   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16823       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16824     return NULL;
16825
16826   attr = dwarf2_attr (die, DW_AT_name, cu);
16827   if (attr != NULL && DW_STRING (attr) != NULL)
16828     return NULL;
16829
16830   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16831   if (attr == NULL)
16832     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16833   if (attr == NULL || DW_STRING (attr) == NULL)
16834     return NULL;
16835
16836   /* dwarf2_name had to be already called.  */
16837   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16838
16839   /* Strip the base name, keep any leading namespaces/classes.  */
16840   base = strrchr (DW_STRING (attr), ':');
16841   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16842     return "";
16843
16844   return obstack_copy0 (&cu->objfile->objfile_obstack,
16845                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16846 }
16847
16848 /* Return the name of the namespace/class that DIE is defined within,
16849    or "" if we can't tell.  The caller should not xfree the result.
16850
16851    For example, if we're within the method foo() in the following
16852    code:
16853
16854    namespace N {
16855      class C {
16856        void foo () {
16857        }
16858      };
16859    }
16860
16861    then determine_prefix on foo's die will return "N::C".  */
16862
16863 static const char *
16864 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16865 {
16866   struct die_info *parent, *spec_die;
16867   struct dwarf2_cu *spec_cu;
16868   struct type *parent_type;
16869   char *retval;
16870
16871   if (cu->language != language_cplus && cu->language != language_java
16872       && cu->language != language_fortran)
16873     return "";
16874
16875   retval = anonymous_struct_prefix (die, cu);
16876   if (retval)
16877     return retval;
16878
16879   /* We have to be careful in the presence of DW_AT_specification.
16880      For example, with GCC 3.4, given the code
16881
16882      namespace N {
16883        void foo() {
16884          // Definition of N::foo.
16885        }
16886      }
16887
16888      then we'll have a tree of DIEs like this:
16889
16890      1: DW_TAG_compile_unit
16891        2: DW_TAG_namespace        // N
16892          3: DW_TAG_subprogram     // declaration of N::foo
16893        4: DW_TAG_subprogram       // definition of N::foo
16894             DW_AT_specification   // refers to die #3
16895
16896      Thus, when processing die #4, we have to pretend that we're in
16897      the context of its DW_AT_specification, namely the contex of die
16898      #3.  */
16899   spec_cu = cu;
16900   spec_die = die_specification (die, &spec_cu);
16901   if (spec_die == NULL)
16902     parent = die->parent;
16903   else
16904     {
16905       parent = spec_die->parent;
16906       cu = spec_cu;
16907     }
16908
16909   if (parent == NULL)
16910     return "";
16911   else if (parent->building_fullname)
16912     {
16913       const char *name;
16914       const char *parent_name;
16915
16916       /* It has been seen on RealView 2.2 built binaries,
16917          DW_TAG_template_type_param types actually _defined_ as
16918          children of the parent class:
16919
16920          enum E {};
16921          template class <class Enum> Class{};
16922          Class<enum E> class_e;
16923
16924          1: DW_TAG_class_type (Class)
16925            2: DW_TAG_enumeration_type (E)
16926              3: DW_TAG_enumerator (enum1:0)
16927              3: DW_TAG_enumerator (enum2:1)
16928              ...
16929            2: DW_TAG_template_type_param
16930               DW_AT_type  DW_FORM_ref_udata (E)
16931
16932          Besides being broken debug info, it can put GDB into an
16933          infinite loop.  Consider:
16934
16935          When we're building the full name for Class<E>, we'll start
16936          at Class, and go look over its template type parameters,
16937          finding E.  We'll then try to build the full name of E, and
16938          reach here.  We're now trying to build the full name of E,
16939          and look over the parent DIE for containing scope.  In the
16940          broken case, if we followed the parent DIE of E, we'd again
16941          find Class, and once again go look at its template type
16942          arguments, etc., etc.  Simply don't consider such parent die
16943          as source-level parent of this die (it can't be, the language
16944          doesn't allow it), and break the loop here.  */
16945       name = dwarf2_name (die, cu);
16946       parent_name = dwarf2_name (parent, cu);
16947       complaint (&symfile_complaints,
16948                  _("template param type '%s' defined within parent '%s'"),
16949                  name ? name : "<unknown>",
16950                  parent_name ? parent_name : "<unknown>");
16951       return "";
16952     }
16953   else
16954     switch (parent->tag)
16955       {
16956       case DW_TAG_namespace:
16957         parent_type = read_type_die (parent, cu);
16958         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
16959            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
16960            Work around this problem here.  */
16961         if (cu->language == language_cplus
16962             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
16963           return "";
16964         /* We give a name to even anonymous namespaces.  */
16965         return TYPE_TAG_NAME (parent_type);
16966       case DW_TAG_class_type:
16967       case DW_TAG_interface_type:
16968       case DW_TAG_structure_type:
16969       case DW_TAG_union_type:
16970       case DW_TAG_module:
16971         parent_type = read_type_die (parent, cu);
16972         if (TYPE_TAG_NAME (parent_type) != NULL)
16973           return TYPE_TAG_NAME (parent_type);
16974         else
16975           /* An anonymous structure is only allowed non-static data
16976              members; no typedefs, no member functions, et cetera.
16977              So it does not need a prefix.  */
16978           return "";
16979       case DW_TAG_compile_unit:
16980       case DW_TAG_partial_unit:
16981         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
16982         if (cu->language == language_cplus
16983             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16984             && die->child != NULL
16985             && (die->tag == DW_TAG_class_type
16986                 || die->tag == DW_TAG_structure_type
16987                 || die->tag == DW_TAG_union_type))
16988           {
16989             char *name = guess_full_die_structure_name (die, cu);
16990             if (name != NULL)
16991               return name;
16992           }
16993         return "";
16994       default:
16995         return determine_prefix (parent, cu);
16996       }
16997 }
16998
16999 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17000    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17001    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17002    an obconcat, otherwise allocate storage for the result.  The CU argument is
17003    used to determine the language and hence, the appropriate separator.  */
17004
17005 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17006
17007 static char *
17008 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17009                  int physname, struct dwarf2_cu *cu)
17010 {
17011   const char *lead = "";
17012   const char *sep;
17013
17014   if (suffix == NULL || suffix[0] == '\0'
17015       || prefix == NULL || prefix[0] == '\0')
17016     sep = "";
17017   else if (cu->language == language_java)
17018     sep = ".";
17019   else if (cu->language == language_fortran && physname)
17020     {
17021       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17022          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17023
17024       lead = "__";
17025       sep = "_MOD_";
17026     }
17027   else
17028     sep = "::";
17029
17030   if (prefix == NULL)
17031     prefix = "";
17032   if (suffix == NULL)
17033     suffix = "";
17034
17035   if (obs == NULL)
17036     {
17037       char *retval
17038         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17039
17040       strcpy (retval, lead);
17041       strcat (retval, prefix);
17042       strcat (retval, sep);
17043       strcat (retval, suffix);
17044       return retval;
17045     }
17046   else
17047     {
17048       /* We have an obstack.  */
17049       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17050     }
17051 }
17052
17053 /* Return sibling of die, NULL if no sibling.  */
17054
17055 static struct die_info *
17056 sibling_die (struct die_info *die)
17057 {
17058   return die->sibling;
17059 }
17060
17061 /* Get name of a die, return NULL if not found.  */
17062
17063 static const char *
17064 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17065                           struct obstack *obstack)
17066 {
17067   if (name && cu->language == language_cplus)
17068     {
17069       char *canon_name = cp_canonicalize_string (name);
17070
17071       if (canon_name != NULL)
17072         {
17073           if (strcmp (canon_name, name) != 0)
17074             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17075           xfree (canon_name);
17076         }
17077     }
17078
17079   return name;
17080 }
17081
17082 /* Get name of a die, return NULL if not found.  */
17083
17084 static const char *
17085 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17086 {
17087   struct attribute *attr;
17088
17089   attr = dwarf2_attr (die, DW_AT_name, cu);
17090   if ((!attr || !DW_STRING (attr))
17091       && die->tag != DW_TAG_class_type
17092       && die->tag != DW_TAG_interface_type
17093       && die->tag != DW_TAG_structure_type
17094       && die->tag != DW_TAG_union_type)
17095     return NULL;
17096
17097   switch (die->tag)
17098     {
17099     case DW_TAG_compile_unit:
17100     case DW_TAG_partial_unit:
17101       /* Compilation units have a DW_AT_name that is a filename, not
17102          a source language identifier.  */
17103     case DW_TAG_enumeration_type:
17104     case DW_TAG_enumerator:
17105       /* These tags always have simple identifiers already; no need
17106          to canonicalize them.  */
17107       return DW_STRING (attr);
17108
17109     case DW_TAG_subprogram:
17110       /* Java constructors will all be named "<init>", so return
17111          the class name when we see this special case.  */
17112       if (cu->language == language_java
17113           && DW_STRING (attr) != NULL
17114           && strcmp (DW_STRING (attr), "<init>") == 0)
17115         {
17116           struct dwarf2_cu *spec_cu = cu;
17117           struct die_info *spec_die;
17118
17119           /* GCJ will output '<init>' for Java constructor names.
17120              For this special case, return the name of the parent class.  */
17121
17122           /* GCJ may output suprogram DIEs with AT_specification set.
17123              If so, use the name of the specified DIE.  */
17124           spec_die = die_specification (die, &spec_cu);
17125           if (spec_die != NULL)
17126             return dwarf2_name (spec_die, spec_cu);
17127
17128           do
17129             {
17130               die = die->parent;
17131               if (die->tag == DW_TAG_class_type)
17132                 return dwarf2_name (die, cu);
17133             }
17134           while (die->tag != DW_TAG_compile_unit
17135                  && die->tag != DW_TAG_partial_unit);
17136         }
17137       break;
17138
17139     case DW_TAG_class_type:
17140     case DW_TAG_interface_type:
17141     case DW_TAG_structure_type:
17142     case DW_TAG_union_type:
17143       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17144          structures or unions.  These were of the form "._%d" in GCC 4.1,
17145          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17146          and GCC 4.4.  We work around this problem by ignoring these.  */
17147       if (attr && DW_STRING (attr)
17148           && (strncmp (DW_STRING (attr), "._", 2) == 0
17149               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17150         return NULL;
17151
17152       /* GCC might emit a nameless typedef that has a linkage name.  See
17153          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17154       if (!attr || DW_STRING (attr) == NULL)
17155         {
17156           char *demangled = NULL;
17157
17158           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17159           if (attr == NULL)
17160             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17161
17162           if (attr == NULL || DW_STRING (attr) == NULL)
17163             return NULL;
17164
17165           /* Avoid demangling DW_STRING (attr) the second time on a second
17166              call for the same DIE.  */
17167           if (!DW_STRING_IS_CANONICAL (attr))
17168             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
17169
17170           if (demangled)
17171             {
17172               char *base;
17173
17174               /* FIXME: we already did this for the partial symbol... */
17175               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17176                                                 demangled, strlen (demangled));
17177               DW_STRING_IS_CANONICAL (attr) = 1;
17178               xfree (demangled);
17179
17180               /* Strip any leading namespaces/classes, keep only the base name.
17181                  DW_AT_name for named DIEs does not contain the prefixes.  */
17182               base = strrchr (DW_STRING (attr), ':');
17183               if (base && base > DW_STRING (attr) && base[-1] == ':')
17184                 return &base[1];
17185               else
17186                 return DW_STRING (attr);
17187             }
17188         }
17189       break;
17190
17191     default:
17192       break;
17193     }
17194
17195   if (!DW_STRING_IS_CANONICAL (attr))
17196     {
17197       DW_STRING (attr)
17198         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17199                                     &cu->objfile->objfile_obstack);
17200       DW_STRING_IS_CANONICAL (attr) = 1;
17201     }
17202   return DW_STRING (attr);
17203 }
17204
17205 /* Return the die that this die in an extension of, or NULL if there
17206    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17207    containing the return value on output.  */
17208
17209 static struct die_info *
17210 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17211 {
17212   struct attribute *attr;
17213
17214   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17215   if (attr == NULL)
17216     return NULL;
17217
17218   return follow_die_ref (die, attr, ext_cu);
17219 }
17220
17221 /* Convert a DIE tag into its string name.  */
17222
17223 static const char *
17224 dwarf_tag_name (unsigned tag)
17225 {
17226   const char *name = get_DW_TAG_name (tag);
17227
17228   if (name == NULL)
17229     return "DW_TAG_<unknown>";
17230
17231   return name;
17232 }
17233
17234 /* Convert a DWARF attribute code into its string name.  */
17235
17236 static const char *
17237 dwarf_attr_name (unsigned attr)
17238 {
17239   const char *name;
17240
17241 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17242   if (attr == DW_AT_MIPS_fde)
17243     return "DW_AT_MIPS_fde";
17244 #else
17245   if (attr == DW_AT_HP_block_index)
17246     return "DW_AT_HP_block_index";
17247 #endif
17248
17249   name = get_DW_AT_name (attr);
17250
17251   if (name == NULL)
17252     return "DW_AT_<unknown>";
17253
17254   return name;
17255 }
17256
17257 /* Convert a DWARF value form code into its string name.  */
17258
17259 static const char *
17260 dwarf_form_name (unsigned form)
17261 {
17262   const char *name = get_DW_FORM_name (form);
17263
17264   if (name == NULL)
17265     return "DW_FORM_<unknown>";
17266
17267   return name;
17268 }
17269
17270 static char *
17271 dwarf_bool_name (unsigned mybool)
17272 {
17273   if (mybool)
17274     return "TRUE";
17275   else
17276     return "FALSE";
17277 }
17278
17279 /* Convert a DWARF type code into its string name.  */
17280
17281 static const char *
17282 dwarf_type_encoding_name (unsigned enc)
17283 {
17284   const char *name = get_DW_ATE_name (enc);
17285
17286   if (name == NULL)
17287     return "DW_ATE_<unknown>";
17288
17289   return name;
17290 }
17291
17292 static void
17293 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17294 {
17295   unsigned int i;
17296
17297   print_spaces (indent, f);
17298   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17299            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17300
17301   if (die->parent != NULL)
17302     {
17303       print_spaces (indent, f);
17304       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17305                           die->parent->offset.sect_off);
17306     }
17307
17308   print_spaces (indent, f);
17309   fprintf_unfiltered (f, "  has children: %s\n",
17310            dwarf_bool_name (die->child != NULL));
17311
17312   print_spaces (indent, f);
17313   fprintf_unfiltered (f, "  attributes:\n");
17314
17315   for (i = 0; i < die->num_attrs; ++i)
17316     {
17317       print_spaces (indent, f);
17318       fprintf_unfiltered (f, "    %s (%s) ",
17319                dwarf_attr_name (die->attrs[i].name),
17320                dwarf_form_name (die->attrs[i].form));
17321
17322       switch (die->attrs[i].form)
17323         {
17324         case DW_FORM_addr:
17325         case DW_FORM_GNU_addr_index:
17326           fprintf_unfiltered (f, "address: ");
17327           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17328           break;
17329         case DW_FORM_block2:
17330         case DW_FORM_block4:
17331         case DW_FORM_block:
17332         case DW_FORM_block1:
17333           fprintf_unfiltered (f, "block: size %s",
17334                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17335           break;
17336         case DW_FORM_exprloc:
17337           fprintf_unfiltered (f, "expression: size %s",
17338                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17339           break;
17340         case DW_FORM_ref_addr:
17341           fprintf_unfiltered (f, "ref address: ");
17342           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17343           break;
17344         case DW_FORM_GNU_ref_alt:
17345           fprintf_unfiltered (f, "alt ref address: ");
17346           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17347           break;
17348         case DW_FORM_ref1:
17349         case DW_FORM_ref2:
17350         case DW_FORM_ref4:
17351         case DW_FORM_ref8:
17352         case DW_FORM_ref_udata:
17353           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17354                               (long) (DW_UNSND (&die->attrs[i])));
17355           break;
17356         case DW_FORM_data1:
17357         case DW_FORM_data2:
17358         case DW_FORM_data4:
17359         case DW_FORM_data8:
17360         case DW_FORM_udata:
17361         case DW_FORM_sdata:
17362           fprintf_unfiltered (f, "constant: %s",
17363                               pulongest (DW_UNSND (&die->attrs[i])));
17364           break;
17365         case DW_FORM_sec_offset:
17366           fprintf_unfiltered (f, "section offset: %s",
17367                               pulongest (DW_UNSND (&die->attrs[i])));
17368           break;
17369         case DW_FORM_ref_sig8:
17370           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17371             {
17372               struct signatured_type *sig_type =
17373                 DW_SIGNATURED_TYPE (&die->attrs[i]);
17374
17375               fprintf_unfiltered (f, "signatured type: 0x%s, offset 0x%x",
17376                                   hex_string (sig_type->signature),
17377                                   sig_type->per_cu.offset.sect_off);
17378             }
17379           else
17380             fprintf_unfiltered (f, "signatured type, unknown");
17381           break;
17382         case DW_FORM_string:
17383         case DW_FORM_strp:
17384         case DW_FORM_GNU_str_index:
17385         case DW_FORM_GNU_strp_alt:
17386           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17387                    DW_STRING (&die->attrs[i])
17388                    ? DW_STRING (&die->attrs[i]) : "",
17389                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17390           break;
17391         case DW_FORM_flag:
17392           if (DW_UNSND (&die->attrs[i]))
17393             fprintf_unfiltered (f, "flag: TRUE");
17394           else
17395             fprintf_unfiltered (f, "flag: FALSE");
17396           break;
17397         case DW_FORM_flag_present:
17398           fprintf_unfiltered (f, "flag: TRUE");
17399           break;
17400         case DW_FORM_indirect:
17401           /* The reader will have reduced the indirect form to
17402              the "base form" so this form should not occur.  */
17403           fprintf_unfiltered (f, 
17404                               "unexpected attribute form: DW_FORM_indirect");
17405           break;
17406         default:
17407           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17408                    die->attrs[i].form);
17409           break;
17410         }
17411       fprintf_unfiltered (f, "\n");
17412     }
17413 }
17414
17415 static void
17416 dump_die_for_error (struct die_info *die)
17417 {
17418   dump_die_shallow (gdb_stderr, 0, die);
17419 }
17420
17421 static void
17422 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17423 {
17424   int indent = level * 4;
17425
17426   gdb_assert (die != NULL);
17427
17428   if (level >= max_level)
17429     return;
17430
17431   dump_die_shallow (f, indent, die);
17432
17433   if (die->child != NULL)
17434     {
17435       print_spaces (indent, f);
17436       fprintf_unfiltered (f, "  Children:");
17437       if (level + 1 < max_level)
17438         {
17439           fprintf_unfiltered (f, "\n");
17440           dump_die_1 (f, level + 1, max_level, die->child);
17441         }
17442       else
17443         {
17444           fprintf_unfiltered (f,
17445                               " [not printed, max nesting level reached]\n");
17446         }
17447     }
17448
17449   if (die->sibling != NULL && level > 0)
17450     {
17451       dump_die_1 (f, level, max_level, die->sibling);
17452     }
17453 }
17454
17455 /* This is called from the pdie macro in gdbinit.in.
17456    It's not static so gcc will keep a copy callable from gdb.  */
17457
17458 void
17459 dump_die (struct die_info *die, int max_level)
17460 {
17461   dump_die_1 (gdb_stdlog, 0, max_level, die);
17462 }
17463
17464 static void
17465 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17466 {
17467   void **slot;
17468
17469   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17470                                    INSERT);
17471
17472   *slot = die;
17473 }
17474
17475 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17476    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17477
17478 static int
17479 is_ref_attr (struct attribute *attr)
17480 {
17481   switch (attr->form)
17482     {
17483     case DW_FORM_ref_addr:
17484     case DW_FORM_ref1:
17485     case DW_FORM_ref2:
17486     case DW_FORM_ref4:
17487     case DW_FORM_ref8:
17488     case DW_FORM_ref_udata:
17489     case DW_FORM_GNU_ref_alt:
17490       return 1;
17491     default:
17492       return 0;
17493     }
17494 }
17495
17496 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17497    required kind.  */
17498
17499 static sect_offset
17500 dwarf2_get_ref_die_offset (struct attribute *attr)
17501 {
17502   sect_offset retval = { DW_UNSND (attr) };
17503
17504   if (is_ref_attr (attr))
17505     return retval;
17506
17507   retval.sect_off = 0;
17508   complaint (&symfile_complaints,
17509              _("unsupported die ref attribute form: '%s'"),
17510              dwarf_form_name (attr->form));
17511   return retval;
17512 }
17513
17514 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17515  * the value held by the attribute is not constant.  */
17516
17517 static LONGEST
17518 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17519 {
17520   if (attr->form == DW_FORM_sdata)
17521     return DW_SND (attr);
17522   else if (attr->form == DW_FORM_udata
17523            || attr->form == DW_FORM_data1
17524            || attr->form == DW_FORM_data2
17525            || attr->form == DW_FORM_data4
17526            || attr->form == DW_FORM_data8)
17527     return DW_UNSND (attr);
17528   else
17529     {
17530       complaint (&symfile_complaints,
17531                  _("Attribute value is not a constant (%s)"),
17532                  dwarf_form_name (attr->form));
17533       return default_value;
17534     }
17535 }
17536
17537 /* Follow reference or signature attribute ATTR of SRC_DIE.
17538    On entry *REF_CU is the CU of SRC_DIE.
17539    On exit *REF_CU is the CU of the result.  */
17540
17541 static struct die_info *
17542 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17543                        struct dwarf2_cu **ref_cu)
17544 {
17545   struct die_info *die;
17546
17547   if (is_ref_attr (attr))
17548     die = follow_die_ref (src_die, attr, ref_cu);
17549   else if (attr->form == DW_FORM_ref_sig8)
17550     die = follow_die_sig (src_die, attr, ref_cu);
17551   else
17552     {
17553       dump_die_for_error (src_die);
17554       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17555              (*ref_cu)->objfile->name);
17556     }
17557
17558   return die;
17559 }
17560
17561 /* Follow reference OFFSET.
17562    On entry *REF_CU is the CU of the source die referencing OFFSET.
17563    On exit *REF_CU is the CU of the result.
17564    Returns NULL if OFFSET is invalid.  */
17565
17566 static struct die_info *
17567 follow_die_offset (sect_offset offset, int offset_in_dwz,
17568                    struct dwarf2_cu **ref_cu)
17569 {
17570   struct die_info temp_die;
17571   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17572
17573   gdb_assert (cu->per_cu != NULL);
17574
17575   target_cu = cu;
17576
17577   if (cu->per_cu->is_debug_types)
17578     {
17579       /* .debug_types CUs cannot reference anything outside their CU.
17580          If they need to, they have to reference a signatured type via
17581          DW_FORM_ref_sig8.  */
17582       if (! offset_in_cu_p (&cu->header, offset))
17583         return NULL;
17584     }
17585   else if (offset_in_dwz != cu->per_cu->is_dwz
17586            || ! offset_in_cu_p (&cu->header, offset))
17587     {
17588       struct dwarf2_per_cu_data *per_cu;
17589
17590       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17591                                                  cu->objfile);
17592
17593       /* If necessary, add it to the queue and load its DIEs.  */
17594       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17595         load_full_comp_unit (per_cu, cu->language);
17596
17597       target_cu = per_cu->cu;
17598     }
17599   else if (cu->dies == NULL)
17600     {
17601       /* We're loading full DIEs during partial symbol reading.  */
17602       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17603       load_full_comp_unit (cu->per_cu, language_minimal);
17604     }
17605
17606   *ref_cu = target_cu;
17607   temp_die.offset = offset;
17608   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17609 }
17610
17611 /* Follow reference attribute ATTR of SRC_DIE.
17612    On entry *REF_CU is the CU of SRC_DIE.
17613    On exit *REF_CU is the CU of the result.  */
17614
17615 static struct die_info *
17616 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17617                 struct dwarf2_cu **ref_cu)
17618 {
17619   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17620   struct dwarf2_cu *cu = *ref_cu;
17621   struct die_info *die;
17622
17623   die = follow_die_offset (offset,
17624                            (attr->form == DW_FORM_GNU_ref_alt
17625                             || cu->per_cu->is_dwz),
17626                            ref_cu);
17627   if (!die)
17628     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17629            "at 0x%x [in module %s]"),
17630            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17631
17632   return die;
17633 }
17634
17635 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17636    Returned value is intended for DW_OP_call*.  Returned
17637    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17638
17639 struct dwarf2_locexpr_baton
17640 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17641                                struct dwarf2_per_cu_data *per_cu,
17642                                CORE_ADDR (*get_frame_pc) (void *baton),
17643                                void *baton)
17644 {
17645   struct dwarf2_cu *cu;
17646   struct die_info *die;
17647   struct attribute *attr;
17648   struct dwarf2_locexpr_baton retval;
17649
17650   dw2_setup (per_cu->objfile);
17651
17652   if (per_cu->cu == NULL)
17653     load_cu (per_cu);
17654   cu = per_cu->cu;
17655
17656   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17657   if (!die)
17658     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17659            offset.sect_off, per_cu->objfile->name);
17660
17661   attr = dwarf2_attr (die, DW_AT_location, cu);
17662   if (!attr)
17663     {
17664       /* DWARF: "If there is no such attribute, then there is no effect.".
17665          DATA is ignored if SIZE is 0.  */
17666
17667       retval.data = NULL;
17668       retval.size = 0;
17669     }
17670   else if (attr_form_is_section_offset (attr))
17671     {
17672       struct dwarf2_loclist_baton loclist_baton;
17673       CORE_ADDR pc = (*get_frame_pc) (baton);
17674       size_t size;
17675
17676       fill_in_loclist_baton (cu, &loclist_baton, attr);
17677
17678       retval.data = dwarf2_find_location_expression (&loclist_baton,
17679                                                      &size, pc);
17680       retval.size = size;
17681     }
17682   else
17683     {
17684       if (!attr_form_is_block (attr))
17685         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17686                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17687                offset.sect_off, per_cu->objfile->name);
17688
17689       retval.data = DW_BLOCK (attr)->data;
17690       retval.size = DW_BLOCK (attr)->size;
17691     }
17692   retval.per_cu = cu->per_cu;
17693
17694   age_cached_comp_units ();
17695
17696   return retval;
17697 }
17698
17699 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17700    offset.  */
17701
17702 struct dwarf2_locexpr_baton
17703 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17704                              struct dwarf2_per_cu_data *per_cu,
17705                              CORE_ADDR (*get_frame_pc) (void *baton),
17706                              void *baton)
17707 {
17708   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17709
17710   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17711 }
17712
17713 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17714    PER_CU.  */
17715
17716 struct type *
17717 dwarf2_get_die_type (cu_offset die_offset,
17718                      struct dwarf2_per_cu_data *per_cu)
17719 {
17720   sect_offset die_offset_sect;
17721
17722   dw2_setup (per_cu->objfile);
17723
17724   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17725   return get_die_type_at_offset (die_offset_sect, per_cu);
17726 }
17727
17728 /* Follow the signature attribute ATTR in SRC_DIE.
17729    On entry *REF_CU is the CU of SRC_DIE.
17730    On exit *REF_CU is the CU of the result.  */
17731
17732 static struct die_info *
17733 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17734                 struct dwarf2_cu **ref_cu)
17735 {
17736   struct objfile *objfile = (*ref_cu)->objfile;
17737   struct die_info temp_die;
17738   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17739   struct dwarf2_cu *sig_cu;
17740   struct die_info *die;
17741
17742   /* sig_type will be NULL if the signatured type is missing from
17743      the debug info.  */
17744   if (sig_type == NULL)
17745     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17746              "at 0x%x [in module %s]"),
17747            src_die->offset.sect_off, objfile->name);
17748
17749   /* If necessary, add it to the queue and load its DIEs.  */
17750
17751   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17752     read_signatured_type (sig_type);
17753
17754   gdb_assert (sig_type->per_cu.cu != NULL);
17755
17756   sig_cu = sig_type->per_cu.cu;
17757   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17758   temp_die.offset = sig_type->type_offset_in_section;
17759   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17760                              temp_die.offset.sect_off);
17761   if (die)
17762     {
17763       /* For .gdb_index version 7 keep track of included TUs.
17764          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17765       if (dwarf2_per_objfile->index_table != NULL
17766           && dwarf2_per_objfile->index_table->version <= 7)
17767         {
17768           VEC_safe_push (dwarf2_per_cu_ptr,
17769                          (*ref_cu)->per_cu->imported_symtabs,
17770                          sig_cu->per_cu);
17771         }
17772
17773       *ref_cu = sig_cu;
17774       return die;
17775     }
17776
17777   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17778          "from DIE at 0x%x [in module %s]"),
17779          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17780 }
17781
17782 /* Given an offset of a signatured type, return its signatured_type.  */
17783
17784 static struct signatured_type *
17785 lookup_signatured_type_at_offset (struct objfile *objfile,
17786                                   struct dwarf2_section_info *section,
17787                                   sect_offset offset)
17788 {
17789   gdb_byte *info_ptr = section->buffer + offset.sect_off;
17790   unsigned int length, initial_length_size;
17791   unsigned int sig_offset;
17792   struct signatured_type find_entry, *sig_type;
17793
17794   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
17795   sig_offset = (initial_length_size
17796                 + 2 /*version*/
17797                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
17798                 + 1 /*address_size*/);
17799   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
17800   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
17801
17802   /* This is only used to lookup previously recorded types.
17803      If we didn't find it, it's our bug.  */
17804   gdb_assert (sig_type != NULL);
17805   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
17806
17807   return sig_type;
17808 }
17809
17810 /* Load the DIEs associated with type unit PER_CU into memory.  */
17811
17812 static void
17813 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17814 {
17815   struct signatured_type *sig_type;
17816
17817   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17818   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17819
17820   /* We have the per_cu, but we need the signatured_type.
17821      Fortunately this is an easy translation.  */
17822   gdb_assert (per_cu->is_debug_types);
17823   sig_type = (struct signatured_type *) per_cu;
17824
17825   gdb_assert (per_cu->cu == NULL);
17826
17827   read_signatured_type (sig_type);
17828
17829   gdb_assert (per_cu->cu != NULL);
17830 }
17831
17832 /* die_reader_func for read_signatured_type.
17833    This is identical to load_full_comp_unit_reader,
17834    but is kept separate for now.  */
17835
17836 static void
17837 read_signatured_type_reader (const struct die_reader_specs *reader,
17838                              gdb_byte *info_ptr,
17839                              struct die_info *comp_unit_die,
17840                              int has_children,
17841                              void *data)
17842 {
17843   struct dwarf2_cu *cu = reader->cu;
17844
17845   gdb_assert (cu->die_hash == NULL);
17846   cu->die_hash =
17847     htab_create_alloc_ex (cu->header.length / 12,
17848                           die_hash,
17849                           die_eq,
17850                           NULL,
17851                           &cu->comp_unit_obstack,
17852                           hashtab_obstack_allocate,
17853                           dummy_obstack_deallocate);
17854
17855   if (has_children)
17856     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17857                                                   &info_ptr, comp_unit_die);
17858   cu->dies = comp_unit_die;
17859   /* comp_unit_die is not stored in die_hash, no need.  */
17860
17861   /* We try not to read any attributes in this function, because not
17862      all CUs needed for references have been loaded yet, and symbol
17863      table processing isn't initialized.  But we have to set the CU language,
17864      or we won't be able to build types correctly.
17865      Similarly, if we do not read the producer, we can not apply
17866      producer-specific interpretation.  */
17867   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17868 }
17869
17870 /* Read in a signatured type and build its CU and DIEs.
17871    If the type is a stub for the real type in a DWO file,
17872    read in the real type from the DWO file as well.  */
17873
17874 static void
17875 read_signatured_type (struct signatured_type *sig_type)
17876 {
17877   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17878
17879   gdb_assert (per_cu->is_debug_types);
17880   gdb_assert (per_cu->cu == NULL);
17881
17882   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17883                            read_signatured_type_reader, NULL);
17884 }
17885
17886 /* Decode simple location descriptions.
17887    Given a pointer to a dwarf block that defines a location, compute
17888    the location and return the value.
17889
17890    NOTE drow/2003-11-18: This function is called in two situations
17891    now: for the address of static or global variables (partial symbols
17892    only) and for offsets into structures which are expected to be
17893    (more or less) constant.  The partial symbol case should go away,
17894    and only the constant case should remain.  That will let this
17895    function complain more accurately.  A few special modes are allowed
17896    without complaint for global variables (for instance, global
17897    register values and thread-local values).
17898
17899    A location description containing no operations indicates that the
17900    object is optimized out.  The return value is 0 for that case.
17901    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17902    callers will only want a very basic result and this can become a
17903    complaint.
17904
17905    Note that stack[0] is unused except as a default error return.  */
17906
17907 static CORE_ADDR
17908 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17909 {
17910   struct objfile *objfile = cu->objfile;
17911   size_t i;
17912   size_t size = blk->size;
17913   gdb_byte *data = blk->data;
17914   CORE_ADDR stack[64];
17915   int stacki;
17916   unsigned int bytes_read, unsnd;
17917   gdb_byte op;
17918
17919   i = 0;
17920   stacki = 0;
17921   stack[stacki] = 0;
17922   stack[++stacki] = 0;
17923
17924   while (i < size)
17925     {
17926       op = data[i++];
17927       switch (op)
17928         {
17929         case DW_OP_lit0:
17930         case DW_OP_lit1:
17931         case DW_OP_lit2:
17932         case DW_OP_lit3:
17933         case DW_OP_lit4:
17934         case DW_OP_lit5:
17935         case DW_OP_lit6:
17936         case DW_OP_lit7:
17937         case DW_OP_lit8:
17938         case DW_OP_lit9:
17939         case DW_OP_lit10:
17940         case DW_OP_lit11:
17941         case DW_OP_lit12:
17942         case DW_OP_lit13:
17943         case DW_OP_lit14:
17944         case DW_OP_lit15:
17945         case DW_OP_lit16:
17946         case DW_OP_lit17:
17947         case DW_OP_lit18:
17948         case DW_OP_lit19:
17949         case DW_OP_lit20:
17950         case DW_OP_lit21:
17951         case DW_OP_lit22:
17952         case DW_OP_lit23:
17953         case DW_OP_lit24:
17954         case DW_OP_lit25:
17955         case DW_OP_lit26:
17956         case DW_OP_lit27:
17957         case DW_OP_lit28:
17958         case DW_OP_lit29:
17959         case DW_OP_lit30:
17960         case DW_OP_lit31:
17961           stack[++stacki] = op - DW_OP_lit0;
17962           break;
17963
17964         case DW_OP_reg0:
17965         case DW_OP_reg1:
17966         case DW_OP_reg2:
17967         case DW_OP_reg3:
17968         case DW_OP_reg4:
17969         case DW_OP_reg5:
17970         case DW_OP_reg6:
17971         case DW_OP_reg7:
17972         case DW_OP_reg8:
17973         case DW_OP_reg9:
17974         case DW_OP_reg10:
17975         case DW_OP_reg11:
17976         case DW_OP_reg12:
17977         case DW_OP_reg13:
17978         case DW_OP_reg14:
17979         case DW_OP_reg15:
17980         case DW_OP_reg16:
17981         case DW_OP_reg17:
17982         case DW_OP_reg18:
17983         case DW_OP_reg19:
17984         case DW_OP_reg20:
17985         case DW_OP_reg21:
17986         case DW_OP_reg22:
17987         case DW_OP_reg23:
17988         case DW_OP_reg24:
17989         case DW_OP_reg25:
17990         case DW_OP_reg26:
17991         case DW_OP_reg27:
17992         case DW_OP_reg28:
17993         case DW_OP_reg29:
17994         case DW_OP_reg30:
17995         case DW_OP_reg31:
17996           stack[++stacki] = op - DW_OP_reg0;
17997           if (i < size)
17998             dwarf2_complex_location_expr_complaint ();
17999           break;
18000
18001         case DW_OP_regx:
18002           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18003           i += bytes_read;
18004           stack[++stacki] = unsnd;
18005           if (i < size)
18006             dwarf2_complex_location_expr_complaint ();
18007           break;
18008
18009         case DW_OP_addr:
18010           stack[++stacki] = read_address (objfile->obfd, &data[i],
18011                                           cu, &bytes_read);
18012           i += bytes_read;
18013           break;
18014
18015         case DW_OP_const1u:
18016           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18017           i += 1;
18018           break;
18019
18020         case DW_OP_const1s:
18021           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18022           i += 1;
18023           break;
18024
18025         case DW_OP_const2u:
18026           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18027           i += 2;
18028           break;
18029
18030         case DW_OP_const2s:
18031           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18032           i += 2;
18033           break;
18034
18035         case DW_OP_const4u:
18036           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18037           i += 4;
18038           break;
18039
18040         case DW_OP_const4s:
18041           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18042           i += 4;
18043           break;
18044
18045         case DW_OP_const8u:
18046           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18047           i += 8;
18048           break;
18049
18050         case DW_OP_constu:
18051           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18052                                                   &bytes_read);
18053           i += bytes_read;
18054           break;
18055
18056         case DW_OP_consts:
18057           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18058           i += bytes_read;
18059           break;
18060
18061         case DW_OP_dup:
18062           stack[stacki + 1] = stack[stacki];
18063           stacki++;
18064           break;
18065
18066         case DW_OP_plus:
18067           stack[stacki - 1] += stack[stacki];
18068           stacki--;
18069           break;
18070
18071         case DW_OP_plus_uconst:
18072           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18073                                                  &bytes_read);
18074           i += bytes_read;
18075           break;
18076
18077         case DW_OP_minus:
18078           stack[stacki - 1] -= stack[stacki];
18079           stacki--;
18080           break;
18081
18082         case DW_OP_deref:
18083           /* If we're not the last op, then we definitely can't encode
18084              this using GDB's address_class enum.  This is valid for partial
18085              global symbols, although the variable's address will be bogus
18086              in the psymtab.  */
18087           if (i < size)
18088             dwarf2_complex_location_expr_complaint ();
18089           break;
18090
18091         case DW_OP_GNU_push_tls_address:
18092           /* The top of the stack has the offset from the beginning
18093              of the thread control block at which the variable is located.  */
18094           /* Nothing should follow this operator, so the top of stack would
18095              be returned.  */
18096           /* This is valid for partial global symbols, but the variable's
18097              address will be bogus in the psymtab.  Make it always at least
18098              non-zero to not look as a variable garbage collected by linker
18099              which have DW_OP_addr 0.  */
18100           if (i < size)
18101             dwarf2_complex_location_expr_complaint ();
18102           stack[stacki]++;
18103           break;
18104
18105         case DW_OP_GNU_uninit:
18106           break;
18107
18108         case DW_OP_GNU_addr_index:
18109         case DW_OP_GNU_const_index:
18110           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18111                                                          &bytes_read);
18112           i += bytes_read;
18113           break;
18114
18115         default:
18116           {
18117             const char *name = get_DW_OP_name (op);
18118
18119             if (name)
18120               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18121                          name);
18122             else
18123               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18124                          op);
18125           }
18126
18127           return (stack[stacki]);
18128         }
18129
18130       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18131          outside of the allocated space.  Also enforce minimum>0.  */
18132       if (stacki >= ARRAY_SIZE (stack) - 1)
18133         {
18134           complaint (&symfile_complaints,
18135                      _("location description stack overflow"));
18136           return 0;
18137         }
18138
18139       if (stacki <= 0)
18140         {
18141           complaint (&symfile_complaints,
18142                      _("location description stack underflow"));
18143           return 0;
18144         }
18145     }
18146   return (stack[stacki]);
18147 }
18148
18149 /* memory allocation interface */
18150
18151 static struct dwarf_block *
18152 dwarf_alloc_block (struct dwarf2_cu *cu)
18153 {
18154   struct dwarf_block *blk;
18155
18156   blk = (struct dwarf_block *)
18157     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18158   return (blk);
18159 }
18160
18161 static struct die_info *
18162 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18163 {
18164   struct die_info *die;
18165   size_t size = sizeof (struct die_info);
18166
18167   if (num_attrs > 1)
18168     size += (num_attrs - 1) * sizeof (struct attribute);
18169
18170   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18171   memset (die, 0, sizeof (struct die_info));
18172   return (die);
18173 }
18174
18175 \f
18176 /* Macro support.  */
18177
18178 /* Return file name relative to the compilation directory of file number I in
18179    *LH's file name table.  The result is allocated using xmalloc; the caller is
18180    responsible for freeing it.  */
18181
18182 static char *
18183 file_file_name (int file, struct line_header *lh)
18184 {
18185   /* Is the file number a valid index into the line header's file name
18186      table?  Remember that file numbers start with one, not zero.  */
18187   if (1 <= file && file <= lh->num_file_names)
18188     {
18189       struct file_entry *fe = &lh->file_names[file - 1];
18190
18191       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18192         return xstrdup (fe->name);
18193       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18194                      fe->name, NULL);
18195     }
18196   else
18197     {
18198       /* The compiler produced a bogus file number.  We can at least
18199          record the macro definitions made in the file, even if we
18200          won't be able to find the file by name.  */
18201       char fake_name[80];
18202
18203       xsnprintf (fake_name, sizeof (fake_name),
18204                  "<bad macro file number %d>", file);
18205
18206       complaint (&symfile_complaints,
18207                  _("bad file number in macro information (%d)"),
18208                  file);
18209
18210       return xstrdup (fake_name);
18211     }
18212 }
18213
18214 /* Return the full name of file number I in *LH's file name table.
18215    Use COMP_DIR as the name of the current directory of the
18216    compilation.  The result is allocated using xmalloc; the caller is
18217    responsible for freeing it.  */
18218 static char *
18219 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18220 {
18221   /* Is the file number a valid index into the line header's file name
18222      table?  Remember that file numbers start with one, not zero.  */
18223   if (1 <= file && file <= lh->num_file_names)
18224     {
18225       char *relative = file_file_name (file, lh);
18226
18227       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18228         return relative;
18229       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18230     }
18231   else
18232     return file_file_name (file, lh);
18233 }
18234
18235
18236 static struct macro_source_file *
18237 macro_start_file (int file, int line,
18238                   struct macro_source_file *current_file,
18239                   const char *comp_dir,
18240                   struct line_header *lh, struct objfile *objfile)
18241 {
18242   /* File name relative to the compilation directory of this source file.  */
18243   char *file_name = file_file_name (file, lh);
18244
18245   /* We don't create a macro table for this compilation unit
18246      at all until we actually get a filename.  */
18247   if (! pending_macros)
18248     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18249                                       objfile->per_bfd->macro_cache,
18250                                       comp_dir);
18251
18252   if (! current_file)
18253     {
18254       /* If we have no current file, then this must be the start_file
18255          directive for the compilation unit's main source file.  */
18256       current_file = macro_set_main (pending_macros, file_name);
18257       macro_define_special (pending_macros);
18258     }
18259   else
18260     current_file = macro_include (current_file, line, file_name);
18261
18262   xfree (file_name);
18263
18264   return current_file;
18265 }
18266
18267
18268 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18269    followed by a null byte.  */
18270 static char *
18271 copy_string (const char *buf, int len)
18272 {
18273   char *s = xmalloc (len + 1);
18274
18275   memcpy (s, buf, len);
18276   s[len] = '\0';
18277   return s;
18278 }
18279
18280
18281 static const char *
18282 consume_improper_spaces (const char *p, const char *body)
18283 {
18284   if (*p == ' ')
18285     {
18286       complaint (&symfile_complaints,
18287                  _("macro definition contains spaces "
18288                    "in formal argument list:\n`%s'"),
18289                  body);
18290
18291       while (*p == ' ')
18292         p++;
18293     }
18294
18295   return p;
18296 }
18297
18298
18299 static void
18300 parse_macro_definition (struct macro_source_file *file, int line,
18301                         const char *body)
18302 {
18303   const char *p;
18304
18305   /* The body string takes one of two forms.  For object-like macro
18306      definitions, it should be:
18307
18308         <macro name> " " <definition>
18309
18310      For function-like macro definitions, it should be:
18311
18312         <macro name> "() " <definition>
18313      or
18314         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18315
18316      Spaces may appear only where explicitly indicated, and in the
18317      <definition>.
18318
18319      The Dwarf 2 spec says that an object-like macro's name is always
18320      followed by a space, but versions of GCC around March 2002 omit
18321      the space when the macro's definition is the empty string.
18322
18323      The Dwarf 2 spec says that there should be no spaces between the
18324      formal arguments in a function-like macro's formal argument list,
18325      but versions of GCC around March 2002 include spaces after the
18326      commas.  */
18327
18328
18329   /* Find the extent of the macro name.  The macro name is terminated
18330      by either a space or null character (for an object-like macro) or
18331      an opening paren (for a function-like macro).  */
18332   for (p = body; *p; p++)
18333     if (*p == ' ' || *p == '(')
18334       break;
18335
18336   if (*p == ' ' || *p == '\0')
18337     {
18338       /* It's an object-like macro.  */
18339       int name_len = p - body;
18340       char *name = copy_string (body, name_len);
18341       const char *replacement;
18342
18343       if (*p == ' ')
18344         replacement = body + name_len + 1;
18345       else
18346         {
18347           dwarf2_macro_malformed_definition_complaint (body);
18348           replacement = body + name_len;
18349         }
18350
18351       macro_define_object (file, line, name, replacement);
18352
18353       xfree (name);
18354     }
18355   else if (*p == '(')
18356     {
18357       /* It's a function-like macro.  */
18358       char *name = copy_string (body, p - body);
18359       int argc = 0;
18360       int argv_size = 1;
18361       char **argv = xmalloc (argv_size * sizeof (*argv));
18362
18363       p++;
18364
18365       p = consume_improper_spaces (p, body);
18366
18367       /* Parse the formal argument list.  */
18368       while (*p && *p != ')')
18369         {
18370           /* Find the extent of the current argument name.  */
18371           const char *arg_start = p;
18372
18373           while (*p && *p != ',' && *p != ')' && *p != ' ')
18374             p++;
18375
18376           if (! *p || p == arg_start)
18377             dwarf2_macro_malformed_definition_complaint (body);
18378           else
18379             {
18380               /* Make sure argv has room for the new argument.  */
18381               if (argc >= argv_size)
18382                 {
18383                   argv_size *= 2;
18384                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18385                 }
18386
18387               argv[argc++] = copy_string (arg_start, p - arg_start);
18388             }
18389
18390           p = consume_improper_spaces (p, body);
18391
18392           /* Consume the comma, if present.  */
18393           if (*p == ',')
18394             {
18395               p++;
18396
18397               p = consume_improper_spaces (p, body);
18398             }
18399         }
18400
18401       if (*p == ')')
18402         {
18403           p++;
18404
18405           if (*p == ' ')
18406             /* Perfectly formed definition, no complaints.  */
18407             macro_define_function (file, line, name,
18408                                    argc, (const char **) argv,
18409                                    p + 1);
18410           else if (*p == '\0')
18411             {
18412               /* Complain, but do define it.  */
18413               dwarf2_macro_malformed_definition_complaint (body);
18414               macro_define_function (file, line, name,
18415                                      argc, (const char **) argv,
18416                                      p);
18417             }
18418           else
18419             /* Just complain.  */
18420             dwarf2_macro_malformed_definition_complaint (body);
18421         }
18422       else
18423         /* Just complain.  */
18424         dwarf2_macro_malformed_definition_complaint (body);
18425
18426       xfree (name);
18427       {
18428         int i;
18429
18430         for (i = 0; i < argc; i++)
18431           xfree (argv[i]);
18432       }
18433       xfree (argv);
18434     }
18435   else
18436     dwarf2_macro_malformed_definition_complaint (body);
18437 }
18438
18439 /* Skip some bytes from BYTES according to the form given in FORM.
18440    Returns the new pointer.  */
18441
18442 static gdb_byte *
18443 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
18444                  enum dwarf_form form,
18445                  unsigned int offset_size,
18446                  struct dwarf2_section_info *section)
18447 {
18448   unsigned int bytes_read;
18449
18450   switch (form)
18451     {
18452     case DW_FORM_data1:
18453     case DW_FORM_flag:
18454       ++bytes;
18455       break;
18456
18457     case DW_FORM_data2:
18458       bytes += 2;
18459       break;
18460
18461     case DW_FORM_data4:
18462       bytes += 4;
18463       break;
18464
18465     case DW_FORM_data8:
18466       bytes += 8;
18467       break;
18468
18469     case DW_FORM_string:
18470       read_direct_string (abfd, bytes, &bytes_read);
18471       bytes += bytes_read;
18472       break;
18473
18474     case DW_FORM_sec_offset:
18475     case DW_FORM_strp:
18476     case DW_FORM_GNU_strp_alt:
18477       bytes += offset_size;
18478       break;
18479
18480     case DW_FORM_block:
18481       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18482       bytes += bytes_read;
18483       break;
18484
18485     case DW_FORM_block1:
18486       bytes += 1 + read_1_byte (abfd, bytes);
18487       break;
18488     case DW_FORM_block2:
18489       bytes += 2 + read_2_bytes (abfd, bytes);
18490       break;
18491     case DW_FORM_block4:
18492       bytes += 4 + read_4_bytes (abfd, bytes);
18493       break;
18494
18495     case DW_FORM_sdata:
18496     case DW_FORM_udata:
18497     case DW_FORM_GNU_addr_index:
18498     case DW_FORM_GNU_str_index:
18499       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
18500       if (bytes == NULL)
18501         {
18502           dwarf2_section_buffer_overflow_complaint (section);
18503           return NULL;
18504         }
18505       break;
18506
18507     default:
18508       {
18509       complain:
18510         complaint (&symfile_complaints,
18511                    _("invalid form 0x%x in `%s'"),
18512                    form,
18513                    section->asection->name);
18514         return NULL;
18515       }
18516     }
18517
18518   return bytes;
18519 }
18520
18521 /* A helper for dwarf_decode_macros that handles skipping an unknown
18522    opcode.  Returns an updated pointer to the macro data buffer; or,
18523    on error, issues a complaint and returns NULL.  */
18524
18525 static gdb_byte *
18526 skip_unknown_opcode (unsigned int opcode,
18527                      gdb_byte **opcode_definitions,
18528                      gdb_byte *mac_ptr, gdb_byte *mac_end,
18529                      bfd *abfd,
18530                      unsigned int offset_size,
18531                      struct dwarf2_section_info *section)
18532 {
18533   unsigned int bytes_read, i;
18534   unsigned long arg;
18535   gdb_byte *defn;
18536
18537   if (opcode_definitions[opcode] == NULL)
18538     {
18539       complaint (&symfile_complaints,
18540                  _("unrecognized DW_MACFINO opcode 0x%x"),
18541                  opcode);
18542       return NULL;
18543     }
18544
18545   defn = opcode_definitions[opcode];
18546   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18547   defn += bytes_read;
18548
18549   for (i = 0; i < arg; ++i)
18550     {
18551       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18552                                  section);
18553       if (mac_ptr == NULL)
18554         {
18555           /* skip_form_bytes already issued the complaint.  */
18556           return NULL;
18557         }
18558     }
18559
18560   return mac_ptr;
18561 }
18562
18563 /* A helper function which parses the header of a macro section.
18564    If the macro section is the extended (for now called "GNU") type,
18565    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18566    the header, or issues a complaint and returns NULL on error.  */
18567
18568 static gdb_byte *
18569 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
18570                           bfd *abfd,
18571                           gdb_byte *mac_ptr,
18572                           unsigned int *offset_size,
18573                           int section_is_gnu)
18574 {
18575   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18576
18577   if (section_is_gnu)
18578     {
18579       unsigned int version, flags;
18580
18581       version = read_2_bytes (abfd, mac_ptr);
18582       if (version != 4)
18583         {
18584           complaint (&symfile_complaints,
18585                      _("unrecognized version `%d' in .debug_macro section"),
18586                      version);
18587           return NULL;
18588         }
18589       mac_ptr += 2;
18590
18591       flags = read_1_byte (abfd, mac_ptr);
18592       ++mac_ptr;
18593       *offset_size = (flags & 1) ? 8 : 4;
18594
18595       if ((flags & 2) != 0)
18596         /* We don't need the line table offset.  */
18597         mac_ptr += *offset_size;
18598
18599       /* Vendor opcode descriptions.  */
18600       if ((flags & 4) != 0)
18601         {
18602           unsigned int i, count;
18603
18604           count = read_1_byte (abfd, mac_ptr);
18605           ++mac_ptr;
18606           for (i = 0; i < count; ++i)
18607             {
18608               unsigned int opcode, bytes_read;
18609               unsigned long arg;
18610
18611               opcode = read_1_byte (abfd, mac_ptr);
18612               ++mac_ptr;
18613               opcode_definitions[opcode] = mac_ptr;
18614               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18615               mac_ptr += bytes_read;
18616               mac_ptr += arg;
18617             }
18618         }
18619     }
18620
18621   return mac_ptr;
18622 }
18623
18624 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18625    including DW_MACRO_GNU_transparent_include.  */
18626
18627 static void
18628 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
18629                           struct macro_source_file *current_file,
18630                           struct line_header *lh, const char *comp_dir,
18631                           struct dwarf2_section_info *section,
18632                           int section_is_gnu, int section_is_dwz,
18633                           unsigned int offset_size,
18634                           struct objfile *objfile,
18635                           htab_t include_hash)
18636 {
18637   enum dwarf_macro_record_type macinfo_type;
18638   int at_commandline;
18639   gdb_byte *opcode_definitions[256];
18640
18641   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18642                                       &offset_size, section_is_gnu);
18643   if (mac_ptr == NULL)
18644     {
18645       /* We already issued a complaint.  */
18646       return;
18647     }
18648
18649   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18650      GDB is still reading the definitions from command line.  First
18651      DW_MACINFO_start_file will need to be ignored as it was already executed
18652      to create CURRENT_FILE for the main source holding also the command line
18653      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18654      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18655
18656   at_commandline = 1;
18657
18658   do
18659     {
18660       /* Do we at least have room for a macinfo type byte?  */
18661       if (mac_ptr >= mac_end)
18662         {
18663           dwarf2_section_buffer_overflow_complaint (section);
18664           break;
18665         }
18666
18667       macinfo_type = read_1_byte (abfd, mac_ptr);
18668       mac_ptr++;
18669
18670       /* Note that we rely on the fact that the corresponding GNU and
18671          DWARF constants are the same.  */
18672       switch (macinfo_type)
18673         {
18674           /* A zero macinfo type indicates the end of the macro
18675              information.  */
18676         case 0:
18677           break;
18678
18679         case DW_MACRO_GNU_define:
18680         case DW_MACRO_GNU_undef:
18681         case DW_MACRO_GNU_define_indirect:
18682         case DW_MACRO_GNU_undef_indirect:
18683         case DW_MACRO_GNU_define_indirect_alt:
18684         case DW_MACRO_GNU_undef_indirect_alt:
18685           {
18686             unsigned int bytes_read;
18687             int line;
18688             char *body;
18689             int is_define;
18690
18691             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18692             mac_ptr += bytes_read;
18693
18694             if (macinfo_type == DW_MACRO_GNU_define
18695                 || macinfo_type == DW_MACRO_GNU_undef)
18696               {
18697                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18698                 mac_ptr += bytes_read;
18699               }
18700             else
18701               {
18702                 LONGEST str_offset;
18703
18704                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18705                 mac_ptr += offset_size;
18706
18707                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18708                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18709                     || section_is_dwz)
18710                   {
18711                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18712
18713                     body = read_indirect_string_from_dwz (dwz, str_offset);
18714                   }
18715                 else
18716                   body = read_indirect_string_at_offset (abfd, str_offset);
18717               }
18718
18719             is_define = (macinfo_type == DW_MACRO_GNU_define
18720                          || macinfo_type == DW_MACRO_GNU_define_indirect
18721                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18722             if (! current_file)
18723               {
18724                 /* DWARF violation as no main source is present.  */
18725                 complaint (&symfile_complaints,
18726                            _("debug info with no main source gives macro %s "
18727                              "on line %d: %s"),
18728                            is_define ? _("definition") : _("undefinition"),
18729                            line, body);
18730                 break;
18731               }
18732             if ((line == 0 && !at_commandline)
18733                 || (line != 0 && at_commandline))
18734               complaint (&symfile_complaints,
18735                          _("debug info gives %s macro %s with %s line %d: %s"),
18736                          at_commandline ? _("command-line") : _("in-file"),
18737                          is_define ? _("definition") : _("undefinition"),
18738                          line == 0 ? _("zero") : _("non-zero"), line, body);
18739
18740             if (is_define)
18741               parse_macro_definition (current_file, line, body);
18742             else
18743               {
18744                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18745                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18746                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18747                 macro_undef (current_file, line, body);
18748               }
18749           }
18750           break;
18751
18752         case DW_MACRO_GNU_start_file:
18753           {
18754             unsigned int bytes_read;
18755             int line, file;
18756
18757             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18758             mac_ptr += bytes_read;
18759             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18760             mac_ptr += bytes_read;
18761
18762             if ((line == 0 && !at_commandline)
18763                 || (line != 0 && at_commandline))
18764               complaint (&symfile_complaints,
18765                          _("debug info gives source %d included "
18766                            "from %s at %s line %d"),
18767                          file, at_commandline ? _("command-line") : _("file"),
18768                          line == 0 ? _("zero") : _("non-zero"), line);
18769
18770             if (at_commandline)
18771               {
18772                 /* This DW_MACRO_GNU_start_file was executed in the
18773                    pass one.  */
18774                 at_commandline = 0;
18775               }
18776             else
18777               current_file = macro_start_file (file, line,
18778                                                current_file, comp_dir,
18779                                                lh, objfile);
18780           }
18781           break;
18782
18783         case DW_MACRO_GNU_end_file:
18784           if (! current_file)
18785             complaint (&symfile_complaints,
18786                        _("macro debug info has an unmatched "
18787                          "`close_file' directive"));
18788           else
18789             {
18790               current_file = current_file->included_by;
18791               if (! current_file)
18792                 {
18793                   enum dwarf_macro_record_type next_type;
18794
18795                   /* GCC circa March 2002 doesn't produce the zero
18796                      type byte marking the end of the compilation
18797                      unit.  Complain if it's not there, but exit no
18798                      matter what.  */
18799
18800                   /* Do we at least have room for a macinfo type byte?  */
18801                   if (mac_ptr >= mac_end)
18802                     {
18803                       dwarf2_section_buffer_overflow_complaint (section);
18804                       return;
18805                     }
18806
18807                   /* We don't increment mac_ptr here, so this is just
18808                      a look-ahead.  */
18809                   next_type = read_1_byte (abfd, mac_ptr);
18810                   if (next_type != 0)
18811                     complaint (&symfile_complaints,
18812                                _("no terminating 0-type entry for "
18813                                  "macros in `.debug_macinfo' section"));
18814
18815                   return;
18816                 }
18817             }
18818           break;
18819
18820         case DW_MACRO_GNU_transparent_include:
18821         case DW_MACRO_GNU_transparent_include_alt:
18822           {
18823             LONGEST offset;
18824             void **slot;
18825             bfd *include_bfd = abfd;
18826             struct dwarf2_section_info *include_section = section;
18827             struct dwarf2_section_info alt_section;
18828             gdb_byte *include_mac_end = mac_end;
18829             int is_dwz = section_is_dwz;
18830             gdb_byte *new_mac_ptr;
18831
18832             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18833             mac_ptr += offset_size;
18834
18835             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18836               {
18837                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18838
18839                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18840                                      &dwz->macro);
18841
18842                 include_bfd = dwz->macro.asection->owner;
18843                 include_section = &dwz->macro;
18844                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18845                 is_dwz = 1;
18846               }
18847
18848             new_mac_ptr = include_section->buffer + offset;
18849             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18850
18851             if (*slot != NULL)
18852               {
18853                 /* This has actually happened; see
18854                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18855                 complaint (&symfile_complaints,
18856                            _("recursive DW_MACRO_GNU_transparent_include in "
18857                              ".debug_macro section"));
18858               }
18859             else
18860               {
18861                 *slot = new_mac_ptr;
18862
18863                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18864                                           include_mac_end, current_file,
18865                                           lh, comp_dir,
18866                                           section, section_is_gnu, is_dwz,
18867                                           offset_size, objfile, include_hash);
18868
18869                 htab_remove_elt (include_hash, new_mac_ptr);
18870               }
18871           }
18872           break;
18873
18874         case DW_MACINFO_vendor_ext:
18875           if (!section_is_gnu)
18876             {
18877               unsigned int bytes_read;
18878               int constant;
18879
18880               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18881               mac_ptr += bytes_read;
18882               read_direct_string (abfd, mac_ptr, &bytes_read);
18883               mac_ptr += bytes_read;
18884
18885               /* We don't recognize any vendor extensions.  */
18886               break;
18887             }
18888           /* FALLTHROUGH */
18889
18890         default:
18891           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18892                                          mac_ptr, mac_end, abfd, offset_size,
18893                                          section);
18894           if (mac_ptr == NULL)
18895             return;
18896           break;
18897         }
18898     } while (macinfo_type != 0);
18899 }
18900
18901 static void
18902 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18903                      const char *comp_dir, int section_is_gnu)
18904 {
18905   struct objfile *objfile = dwarf2_per_objfile->objfile;
18906   struct line_header *lh = cu->line_header;
18907   bfd *abfd;
18908   gdb_byte *mac_ptr, *mac_end;
18909   struct macro_source_file *current_file = 0;
18910   enum dwarf_macro_record_type macinfo_type;
18911   unsigned int offset_size = cu->header.offset_size;
18912   gdb_byte *opcode_definitions[256];
18913   struct cleanup *cleanup;
18914   htab_t include_hash;
18915   void **slot;
18916   struct dwarf2_section_info *section;
18917   const char *section_name;
18918
18919   if (cu->dwo_unit != NULL)
18920     {
18921       if (section_is_gnu)
18922         {
18923           section = &cu->dwo_unit->dwo_file->sections.macro;
18924           section_name = ".debug_macro.dwo";
18925         }
18926       else
18927         {
18928           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18929           section_name = ".debug_macinfo.dwo";
18930         }
18931     }
18932   else
18933     {
18934       if (section_is_gnu)
18935         {
18936           section = &dwarf2_per_objfile->macro;
18937           section_name = ".debug_macro";
18938         }
18939       else
18940         {
18941           section = &dwarf2_per_objfile->macinfo;
18942           section_name = ".debug_macinfo";
18943         }
18944     }
18945
18946   dwarf2_read_section (objfile, section);
18947   if (section->buffer == NULL)
18948     {
18949       complaint (&symfile_complaints, _("missing %s section"), section_name);
18950       return;
18951     }
18952   abfd = section->asection->owner;
18953
18954   /* First pass: Find the name of the base filename.
18955      This filename is needed in order to process all macros whose definition
18956      (or undefinition) comes from the command line.  These macros are defined
18957      before the first DW_MACINFO_start_file entry, and yet still need to be
18958      associated to the base file.
18959
18960      To determine the base file name, we scan the macro definitions until we
18961      reach the first DW_MACINFO_start_file entry.  We then initialize
18962      CURRENT_FILE accordingly so that any macro definition found before the
18963      first DW_MACINFO_start_file can still be associated to the base file.  */
18964
18965   mac_ptr = section->buffer + offset;
18966   mac_end = section->buffer + section->size;
18967
18968   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18969                                       &offset_size, section_is_gnu);
18970   if (mac_ptr == NULL)
18971     {
18972       /* We already issued a complaint.  */
18973       return;
18974     }
18975
18976   do
18977     {
18978       /* Do we at least have room for a macinfo type byte?  */
18979       if (mac_ptr >= mac_end)
18980         {
18981           /* Complaint is printed during the second pass as GDB will probably
18982              stop the first pass earlier upon finding
18983              DW_MACINFO_start_file.  */
18984           break;
18985         }
18986
18987       macinfo_type = read_1_byte (abfd, mac_ptr);
18988       mac_ptr++;
18989
18990       /* Note that we rely on the fact that the corresponding GNU and
18991          DWARF constants are the same.  */
18992       switch (macinfo_type)
18993         {
18994           /* A zero macinfo type indicates the end of the macro
18995              information.  */
18996         case 0:
18997           break;
18998
18999         case DW_MACRO_GNU_define:
19000         case DW_MACRO_GNU_undef:
19001           /* Only skip the data by MAC_PTR.  */
19002           {
19003             unsigned int bytes_read;
19004
19005             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19006             mac_ptr += bytes_read;
19007             read_direct_string (abfd, mac_ptr, &bytes_read);
19008             mac_ptr += bytes_read;
19009           }
19010           break;
19011
19012         case DW_MACRO_GNU_start_file:
19013           {
19014             unsigned int bytes_read;
19015             int line, file;
19016
19017             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19018             mac_ptr += bytes_read;
19019             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19020             mac_ptr += bytes_read;
19021
19022             current_file = macro_start_file (file, line, current_file,
19023                                              comp_dir, lh, objfile);
19024           }
19025           break;
19026
19027         case DW_MACRO_GNU_end_file:
19028           /* No data to skip by MAC_PTR.  */
19029           break;
19030
19031         case DW_MACRO_GNU_define_indirect:
19032         case DW_MACRO_GNU_undef_indirect:
19033         case DW_MACRO_GNU_define_indirect_alt:
19034         case DW_MACRO_GNU_undef_indirect_alt:
19035           {
19036             unsigned int bytes_read;
19037
19038             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19039             mac_ptr += bytes_read;
19040             mac_ptr += offset_size;
19041           }
19042           break;
19043
19044         case DW_MACRO_GNU_transparent_include:
19045         case DW_MACRO_GNU_transparent_include_alt:
19046           /* Note that, according to the spec, a transparent include
19047              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19048              skip this opcode.  */
19049           mac_ptr += offset_size;
19050           break;
19051
19052         case DW_MACINFO_vendor_ext:
19053           /* Only skip the data by MAC_PTR.  */
19054           if (!section_is_gnu)
19055             {
19056               unsigned int bytes_read;
19057
19058               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19059               mac_ptr += bytes_read;
19060               read_direct_string (abfd, mac_ptr, &bytes_read);
19061               mac_ptr += bytes_read;
19062             }
19063           /* FALLTHROUGH */
19064
19065         default:
19066           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19067                                          mac_ptr, mac_end, abfd, offset_size,
19068                                          section);
19069           if (mac_ptr == NULL)
19070             return;
19071           break;
19072         }
19073     } while (macinfo_type != 0 && current_file == NULL);
19074
19075   /* Second pass: Process all entries.
19076
19077      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19078      command-line macro definitions/undefinitions.  This flag is unset when we
19079      reach the first DW_MACINFO_start_file entry.  */
19080
19081   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19082                                     NULL, xcalloc, xfree);
19083   cleanup = make_cleanup_htab_delete (include_hash);
19084   mac_ptr = section->buffer + offset;
19085   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19086   *slot = mac_ptr;
19087   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19088                             current_file, lh, comp_dir, section,
19089                             section_is_gnu, 0,
19090                             offset_size, objfile, include_hash);
19091   do_cleanups (cleanup);
19092 }
19093
19094 /* Check if the attribute's form is a DW_FORM_block*
19095    if so return true else false.  */
19096
19097 static int
19098 attr_form_is_block (struct attribute *attr)
19099 {
19100   return (attr == NULL ? 0 :
19101       attr->form == DW_FORM_block1
19102       || attr->form == DW_FORM_block2
19103       || attr->form == DW_FORM_block4
19104       || attr->form == DW_FORM_block
19105       || attr->form == DW_FORM_exprloc);
19106 }
19107
19108 /* Return non-zero if ATTR's value is a section offset --- classes
19109    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19110    You may use DW_UNSND (attr) to retrieve such offsets.
19111
19112    Section 7.5.4, "Attribute Encodings", explains that no attribute
19113    may have a value that belongs to more than one of these classes; it
19114    would be ambiguous if we did, because we use the same forms for all
19115    of them.  */
19116
19117 static int
19118 attr_form_is_section_offset (struct attribute *attr)
19119 {
19120   return (attr->form == DW_FORM_data4
19121           || attr->form == DW_FORM_data8
19122           || attr->form == DW_FORM_sec_offset);
19123 }
19124
19125 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19126    zero otherwise.  When this function returns true, you can apply
19127    dwarf2_get_attr_constant_value to it.
19128
19129    However, note that for some attributes you must check
19130    attr_form_is_section_offset before using this test.  DW_FORM_data4
19131    and DW_FORM_data8 are members of both the constant class, and of
19132    the classes that contain offsets into other debug sections
19133    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19134    that, if an attribute's can be either a constant or one of the
19135    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19136    taken as section offsets, not constants.  */
19137
19138 static int
19139 attr_form_is_constant (struct attribute *attr)
19140 {
19141   switch (attr->form)
19142     {
19143     case DW_FORM_sdata:
19144     case DW_FORM_udata:
19145     case DW_FORM_data1:
19146     case DW_FORM_data2:
19147     case DW_FORM_data4:
19148     case DW_FORM_data8:
19149       return 1;
19150     default:
19151       return 0;
19152     }
19153 }
19154
19155 /* Return the .debug_loc section to use for CU.
19156    For DWO files use .debug_loc.dwo.  */
19157
19158 static struct dwarf2_section_info *
19159 cu_debug_loc_section (struct dwarf2_cu *cu)
19160 {
19161   if (cu->dwo_unit)
19162     return &cu->dwo_unit->dwo_file->sections.loc;
19163   return &dwarf2_per_objfile->loc;
19164 }
19165
19166 /* A helper function that fills in a dwarf2_loclist_baton.  */
19167
19168 static void
19169 fill_in_loclist_baton (struct dwarf2_cu *cu,
19170                        struct dwarf2_loclist_baton *baton,
19171                        struct attribute *attr)
19172 {
19173   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19174
19175   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19176
19177   baton->per_cu = cu->per_cu;
19178   gdb_assert (baton->per_cu);
19179   /* We don't know how long the location list is, but make sure we
19180      don't run off the edge of the section.  */
19181   baton->size = section->size - DW_UNSND (attr);
19182   baton->data = section->buffer + DW_UNSND (attr);
19183   baton->base_address = cu->base_address;
19184   baton->from_dwo = cu->dwo_unit != NULL;
19185 }
19186
19187 static void
19188 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19189                              struct dwarf2_cu *cu, int is_block)
19190 {
19191   struct objfile *objfile = dwarf2_per_objfile->objfile;
19192   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19193
19194   if (attr_form_is_section_offset (attr)
19195       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19196          the section.  If so, fall through to the complaint in the
19197          other branch.  */
19198       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19199     {
19200       struct dwarf2_loclist_baton *baton;
19201
19202       baton = obstack_alloc (&objfile->objfile_obstack,
19203                              sizeof (struct dwarf2_loclist_baton));
19204
19205       fill_in_loclist_baton (cu, baton, attr);
19206
19207       if (cu->base_known == 0)
19208         complaint (&symfile_complaints,
19209                    _("Location list used without "
19210                      "specifying the CU base address."));
19211
19212       SYMBOL_ACLASS_INDEX (sym) = (is_block
19213                                    ? dwarf2_loclist_block_index
19214                                    : dwarf2_loclist_index);
19215       SYMBOL_LOCATION_BATON (sym) = baton;
19216     }
19217   else
19218     {
19219       struct dwarf2_locexpr_baton *baton;
19220
19221       baton = obstack_alloc (&objfile->objfile_obstack,
19222                              sizeof (struct dwarf2_locexpr_baton));
19223       baton->per_cu = cu->per_cu;
19224       gdb_assert (baton->per_cu);
19225
19226       if (attr_form_is_block (attr))
19227         {
19228           /* Note that we're just copying the block's data pointer
19229              here, not the actual data.  We're still pointing into the
19230              info_buffer for SYM's objfile; right now we never release
19231              that buffer, but when we do clean up properly this may
19232              need to change.  */
19233           baton->size = DW_BLOCK (attr)->size;
19234           baton->data = DW_BLOCK (attr)->data;
19235         }
19236       else
19237         {
19238           dwarf2_invalid_attrib_class_complaint ("location description",
19239                                                  SYMBOL_NATURAL_NAME (sym));
19240           baton->size = 0;
19241         }
19242
19243       SYMBOL_ACLASS_INDEX (sym) = (is_block
19244                                    ? dwarf2_locexpr_block_index
19245                                    : dwarf2_locexpr_index);
19246       SYMBOL_LOCATION_BATON (sym) = baton;
19247     }
19248 }
19249
19250 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19251    came from a separate debuginfo file, then the master objfile is
19252    returned.  */
19253
19254 struct objfile *
19255 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19256 {
19257   struct objfile *objfile = per_cu->objfile;
19258
19259   /* Return the master objfile, so that we can report and look up the
19260      correct file containing this variable.  */
19261   if (objfile->separate_debug_objfile_backlink)
19262     objfile = objfile->separate_debug_objfile_backlink;
19263
19264   return objfile;
19265 }
19266
19267 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19268    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19269    CU_HEADERP first.  */
19270
19271 static const struct comp_unit_head *
19272 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19273                        struct dwarf2_per_cu_data *per_cu)
19274 {
19275   gdb_byte *info_ptr;
19276
19277   if (per_cu->cu)
19278     return &per_cu->cu->header;
19279
19280   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
19281
19282   memset (cu_headerp, 0, sizeof (*cu_headerp));
19283   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19284
19285   return cu_headerp;
19286 }
19287
19288 /* Return the address size given in the compilation unit header for CU.  */
19289
19290 int
19291 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19292 {
19293   struct comp_unit_head cu_header_local;
19294   const struct comp_unit_head *cu_headerp;
19295
19296   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19297
19298   return cu_headerp->addr_size;
19299 }
19300
19301 /* Return the offset size given in the compilation unit header for CU.  */
19302
19303 int
19304 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19305 {
19306   struct comp_unit_head cu_header_local;
19307   const struct comp_unit_head *cu_headerp;
19308
19309   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19310
19311   return cu_headerp->offset_size;
19312 }
19313
19314 /* See its dwarf2loc.h declaration.  */
19315
19316 int
19317 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19318 {
19319   struct comp_unit_head cu_header_local;
19320   const struct comp_unit_head *cu_headerp;
19321
19322   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19323
19324   if (cu_headerp->version == 2)
19325     return cu_headerp->addr_size;
19326   else
19327     return cu_headerp->offset_size;
19328 }
19329
19330 /* Return the text offset of the CU.  The returned offset comes from
19331    this CU's objfile.  If this objfile came from a separate debuginfo
19332    file, then the offset may be different from the corresponding
19333    offset in the parent objfile.  */
19334
19335 CORE_ADDR
19336 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19337 {
19338   struct objfile *objfile = per_cu->objfile;
19339
19340   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19341 }
19342
19343 /* Locate the .debug_info compilation unit from CU's objfile which contains
19344    the DIE at OFFSET.  Raises an error on failure.  */
19345
19346 static struct dwarf2_per_cu_data *
19347 dwarf2_find_containing_comp_unit (sect_offset offset,
19348                                   unsigned int offset_in_dwz,
19349                                   struct objfile *objfile)
19350 {
19351   struct dwarf2_per_cu_data *this_cu;
19352   int low, high;
19353   const sect_offset *cu_off;
19354
19355   low = 0;
19356   high = dwarf2_per_objfile->n_comp_units - 1;
19357   while (high > low)
19358     {
19359       struct dwarf2_per_cu_data *mid_cu;
19360       int mid = low + (high - low) / 2;
19361
19362       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19363       cu_off = &mid_cu->offset;
19364       if (mid_cu->is_dwz > offset_in_dwz
19365           || (mid_cu->is_dwz == offset_in_dwz
19366               && cu_off->sect_off >= offset.sect_off))
19367         high = mid;
19368       else
19369         low = mid + 1;
19370     }
19371   gdb_assert (low == high);
19372   this_cu = dwarf2_per_objfile->all_comp_units[low];
19373   cu_off = &this_cu->offset;
19374   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19375     {
19376       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19377         error (_("Dwarf Error: could not find partial DIE containing "
19378                "offset 0x%lx [in module %s]"),
19379                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19380
19381       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19382                   <= offset.sect_off);
19383       return dwarf2_per_objfile->all_comp_units[low-1];
19384     }
19385   else
19386     {
19387       this_cu = dwarf2_per_objfile->all_comp_units[low];
19388       if (low == dwarf2_per_objfile->n_comp_units - 1
19389           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19390         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19391       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19392       return this_cu;
19393     }
19394 }
19395
19396 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19397
19398 static void
19399 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19400 {
19401   memset (cu, 0, sizeof (*cu));
19402   per_cu->cu = cu;
19403   cu->per_cu = per_cu;
19404   cu->objfile = per_cu->objfile;
19405   obstack_init (&cu->comp_unit_obstack);
19406 }
19407
19408 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19409
19410 static void
19411 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19412                        enum language pretend_language)
19413 {
19414   struct attribute *attr;
19415
19416   /* Set the language we're debugging.  */
19417   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19418   if (attr)
19419     set_cu_language (DW_UNSND (attr), cu);
19420   else
19421     {
19422       cu->language = pretend_language;
19423       cu->language_defn = language_def (cu->language);
19424     }
19425
19426   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19427   if (attr)
19428     cu->producer = DW_STRING (attr);
19429 }
19430
19431 /* Release one cached compilation unit, CU.  We unlink it from the tree
19432    of compilation units, but we don't remove it from the read_in_chain;
19433    the caller is responsible for that.
19434    NOTE: DATA is a void * because this function is also used as a
19435    cleanup routine.  */
19436
19437 static void
19438 free_heap_comp_unit (void *data)
19439 {
19440   struct dwarf2_cu *cu = data;
19441
19442   gdb_assert (cu->per_cu != NULL);
19443   cu->per_cu->cu = NULL;
19444   cu->per_cu = NULL;
19445
19446   obstack_free (&cu->comp_unit_obstack, NULL);
19447
19448   xfree (cu);
19449 }
19450
19451 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19452    when we're finished with it.  We can't free the pointer itself, but be
19453    sure to unlink it from the cache.  Also release any associated storage.  */
19454
19455 static void
19456 free_stack_comp_unit (void *data)
19457 {
19458   struct dwarf2_cu *cu = data;
19459
19460   gdb_assert (cu->per_cu != NULL);
19461   cu->per_cu->cu = NULL;
19462   cu->per_cu = NULL;
19463
19464   obstack_free (&cu->comp_unit_obstack, NULL);
19465   cu->partial_dies = NULL;
19466 }
19467
19468 /* Free all cached compilation units.  */
19469
19470 static void
19471 free_cached_comp_units (void *data)
19472 {
19473   struct dwarf2_per_cu_data *per_cu, **last_chain;
19474
19475   per_cu = dwarf2_per_objfile->read_in_chain;
19476   last_chain = &dwarf2_per_objfile->read_in_chain;
19477   while (per_cu != NULL)
19478     {
19479       struct dwarf2_per_cu_data *next_cu;
19480
19481       next_cu = per_cu->cu->read_in_chain;
19482
19483       free_heap_comp_unit (per_cu->cu);
19484       *last_chain = next_cu;
19485
19486       per_cu = next_cu;
19487     }
19488 }
19489
19490 /* Increase the age counter on each cached compilation unit, and free
19491    any that are too old.  */
19492
19493 static void
19494 age_cached_comp_units (void)
19495 {
19496   struct dwarf2_per_cu_data *per_cu, **last_chain;
19497
19498   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19499   per_cu = dwarf2_per_objfile->read_in_chain;
19500   while (per_cu != NULL)
19501     {
19502       per_cu->cu->last_used ++;
19503       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19504         dwarf2_mark (per_cu->cu);
19505       per_cu = per_cu->cu->read_in_chain;
19506     }
19507
19508   per_cu = dwarf2_per_objfile->read_in_chain;
19509   last_chain = &dwarf2_per_objfile->read_in_chain;
19510   while (per_cu != NULL)
19511     {
19512       struct dwarf2_per_cu_data *next_cu;
19513
19514       next_cu = per_cu->cu->read_in_chain;
19515
19516       if (!per_cu->cu->mark)
19517         {
19518           free_heap_comp_unit (per_cu->cu);
19519           *last_chain = next_cu;
19520         }
19521       else
19522         last_chain = &per_cu->cu->read_in_chain;
19523
19524       per_cu = next_cu;
19525     }
19526 }
19527
19528 /* Remove a single compilation unit from the cache.  */
19529
19530 static void
19531 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19532 {
19533   struct dwarf2_per_cu_data *per_cu, **last_chain;
19534
19535   per_cu = dwarf2_per_objfile->read_in_chain;
19536   last_chain = &dwarf2_per_objfile->read_in_chain;
19537   while (per_cu != NULL)
19538     {
19539       struct dwarf2_per_cu_data *next_cu;
19540
19541       next_cu = per_cu->cu->read_in_chain;
19542
19543       if (per_cu == target_per_cu)
19544         {
19545           free_heap_comp_unit (per_cu->cu);
19546           per_cu->cu = NULL;
19547           *last_chain = next_cu;
19548           break;
19549         }
19550       else
19551         last_chain = &per_cu->cu->read_in_chain;
19552
19553       per_cu = next_cu;
19554     }
19555 }
19556
19557 /* Release all extra memory associated with OBJFILE.  */
19558
19559 void
19560 dwarf2_free_objfile (struct objfile *objfile)
19561 {
19562   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19563
19564   if (dwarf2_per_objfile == NULL)
19565     return;
19566
19567   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19568   free_cached_comp_units (NULL);
19569
19570   if (dwarf2_per_objfile->quick_file_names_table)
19571     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19572
19573   /* Everything else should be on the objfile obstack.  */
19574 }
19575
19576 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19577    We store these in a hash table separate from the DIEs, and preserve them
19578    when the DIEs are flushed out of cache.
19579
19580    The CU "per_cu" pointer is needed because offset alone is not enough to
19581    uniquely identify the type.  A file may have multiple .debug_types sections,
19582    or the type may come from a DWO file.  Furthermore, while it's more logical
19583    to use per_cu->section+offset, with Fission the section with the data is in
19584    the DWO file but we don't know that section at the point we need it.
19585    We have to use something in dwarf2_per_cu_data (or the pointer to it)
19586    because we can enter the lookup routine, get_die_type_at_offset, from
19587    outside this file, and thus won't necessarily have PER_CU->cu.
19588    Fortunately, PER_CU is stable for the life of the objfile.  */
19589
19590 struct dwarf2_per_cu_offset_and_type
19591 {
19592   const struct dwarf2_per_cu_data *per_cu;
19593   sect_offset offset;
19594   struct type *type;
19595 };
19596
19597 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19598
19599 static hashval_t
19600 per_cu_offset_and_type_hash (const void *item)
19601 {
19602   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19603
19604   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19605 }
19606
19607 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19608
19609 static int
19610 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19611 {
19612   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19613   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19614
19615   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19616           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19617 }
19618
19619 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19620    table if necessary.  For convenience, return TYPE.
19621
19622    The DIEs reading must have careful ordering to:
19623     * Not cause infite loops trying to read in DIEs as a prerequisite for
19624       reading current DIE.
19625     * Not trying to dereference contents of still incompletely read in types
19626       while reading in other DIEs.
19627     * Enable referencing still incompletely read in types just by a pointer to
19628       the type without accessing its fields.
19629
19630    Therefore caller should follow these rules:
19631      * Try to fetch any prerequisite types we may need to build this DIE type
19632        before building the type and calling set_die_type.
19633      * After building type call set_die_type for current DIE as soon as
19634        possible before fetching more types to complete the current type.
19635      * Make the type as complete as possible before fetching more types.  */
19636
19637 static struct type *
19638 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19639 {
19640   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19641   struct objfile *objfile = cu->objfile;
19642
19643   /* For Ada types, make sure that the gnat-specific data is always
19644      initialized (if not already set).  There are a few types where
19645      we should not be doing so, because the type-specific area is
19646      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19647      where the type-specific area is used to store the floatformat).
19648      But this is not a problem, because the gnat-specific information
19649      is actually not needed for these types.  */
19650   if (need_gnat_info (cu)
19651       && TYPE_CODE (type) != TYPE_CODE_FUNC
19652       && TYPE_CODE (type) != TYPE_CODE_FLT
19653       && !HAVE_GNAT_AUX_INFO (type))
19654     INIT_GNAT_SPECIFIC (type);
19655
19656   if (dwarf2_per_objfile->die_type_hash == NULL)
19657     {
19658       dwarf2_per_objfile->die_type_hash =
19659         htab_create_alloc_ex (127,
19660                               per_cu_offset_and_type_hash,
19661                               per_cu_offset_and_type_eq,
19662                               NULL,
19663                               &objfile->objfile_obstack,
19664                               hashtab_obstack_allocate,
19665                               dummy_obstack_deallocate);
19666     }
19667
19668   ofs.per_cu = cu->per_cu;
19669   ofs.offset = die->offset;
19670   ofs.type = type;
19671   slot = (struct dwarf2_per_cu_offset_and_type **)
19672     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19673   if (*slot)
19674     complaint (&symfile_complaints,
19675                _("A problem internal to GDB: DIE 0x%x has type already set"),
19676                die->offset.sect_off);
19677   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19678   **slot = ofs;
19679   return type;
19680 }
19681
19682 /* Look up the type for the die at OFFSET in the appropriate type_hash
19683    table, or return NULL if the die does not have a saved type.  */
19684
19685 static struct type *
19686 get_die_type_at_offset (sect_offset offset,
19687                         struct dwarf2_per_cu_data *per_cu)
19688 {
19689   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19690
19691   if (dwarf2_per_objfile->die_type_hash == NULL)
19692     return NULL;
19693
19694   ofs.per_cu = per_cu;
19695   ofs.offset = offset;
19696   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19697   if (slot)
19698     return slot->type;
19699   else
19700     return NULL;
19701 }
19702
19703 /* Look up the type for DIE in the appropriate type_hash table,
19704    or return NULL if DIE does not have a saved type.  */
19705
19706 static struct type *
19707 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19708 {
19709   return get_die_type_at_offset (die->offset, cu->per_cu);
19710 }
19711
19712 /* Add a dependence relationship from CU to REF_PER_CU.  */
19713
19714 static void
19715 dwarf2_add_dependence (struct dwarf2_cu *cu,
19716                        struct dwarf2_per_cu_data *ref_per_cu)
19717 {
19718   void **slot;
19719
19720   if (cu->dependencies == NULL)
19721     cu->dependencies
19722       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19723                               NULL, &cu->comp_unit_obstack,
19724                               hashtab_obstack_allocate,
19725                               dummy_obstack_deallocate);
19726
19727   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19728   if (*slot == NULL)
19729     *slot = ref_per_cu;
19730 }
19731
19732 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19733    Set the mark field in every compilation unit in the
19734    cache that we must keep because we are keeping CU.  */
19735
19736 static int
19737 dwarf2_mark_helper (void **slot, void *data)
19738 {
19739   struct dwarf2_per_cu_data *per_cu;
19740
19741   per_cu = (struct dwarf2_per_cu_data *) *slot;
19742
19743   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19744      reading of the chain.  As such dependencies remain valid it is not much
19745      useful to track and undo them during QUIT cleanups.  */
19746   if (per_cu->cu == NULL)
19747     return 1;
19748
19749   if (per_cu->cu->mark)
19750     return 1;
19751   per_cu->cu->mark = 1;
19752
19753   if (per_cu->cu->dependencies != NULL)
19754     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19755
19756   return 1;
19757 }
19758
19759 /* Set the mark field in CU and in every other compilation unit in the
19760    cache that we must keep because we are keeping CU.  */
19761
19762 static void
19763 dwarf2_mark (struct dwarf2_cu *cu)
19764 {
19765   if (cu->mark)
19766     return;
19767   cu->mark = 1;
19768   if (cu->dependencies != NULL)
19769     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19770 }
19771
19772 static void
19773 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19774 {
19775   while (per_cu)
19776     {
19777       per_cu->cu->mark = 0;
19778       per_cu = per_cu->cu->read_in_chain;
19779     }
19780 }
19781
19782 /* Trivial hash function for partial_die_info: the hash value of a DIE
19783    is its offset in .debug_info for this objfile.  */
19784
19785 static hashval_t
19786 partial_die_hash (const void *item)
19787 {
19788   const struct partial_die_info *part_die = item;
19789
19790   return part_die->offset.sect_off;
19791 }
19792
19793 /* Trivial comparison function for partial_die_info structures: two DIEs
19794    are equal if they have the same offset.  */
19795
19796 static int
19797 partial_die_eq (const void *item_lhs, const void *item_rhs)
19798 {
19799   const struct partial_die_info *part_die_lhs = item_lhs;
19800   const struct partial_die_info *part_die_rhs = item_rhs;
19801
19802   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19803 }
19804
19805 static struct cmd_list_element *set_dwarf2_cmdlist;
19806 static struct cmd_list_element *show_dwarf2_cmdlist;
19807
19808 static void
19809 set_dwarf2_cmd (char *args, int from_tty)
19810 {
19811   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19812 }
19813
19814 static void
19815 show_dwarf2_cmd (char *args, int from_tty)
19816 {
19817   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19818 }
19819
19820 /* Free data associated with OBJFILE, if necessary.  */
19821
19822 static void
19823 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19824 {
19825   struct dwarf2_per_objfile *data = d;
19826   int ix;
19827
19828   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19829     VEC_free (dwarf2_per_cu_ptr,
19830               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
19831
19832   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
19833     VEC_free (dwarf2_per_cu_ptr,
19834               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
19835
19836   VEC_free (dwarf2_section_info_def, data->types);
19837
19838   if (data->dwo_files)
19839     free_dwo_files (data->dwo_files, objfile);
19840   if (data->dwp_file)
19841     gdb_bfd_unref (data->dwp_file->dbfd);
19842
19843   if (data->dwz_file && data->dwz_file->dwz_bfd)
19844     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19845 }
19846
19847 \f
19848 /* The "save gdb-index" command.  */
19849
19850 /* The contents of the hash table we create when building the string
19851    table.  */
19852 struct strtab_entry
19853 {
19854   offset_type offset;
19855   const char *str;
19856 };
19857
19858 /* Hash function for a strtab_entry.
19859
19860    Function is used only during write_hash_table so no index format backward
19861    compatibility is needed.  */
19862
19863 static hashval_t
19864 hash_strtab_entry (const void *e)
19865 {
19866   const struct strtab_entry *entry = e;
19867   return mapped_index_string_hash (INT_MAX, entry->str);
19868 }
19869
19870 /* Equality function for a strtab_entry.  */
19871
19872 static int
19873 eq_strtab_entry (const void *a, const void *b)
19874 {
19875   const struct strtab_entry *ea = a;
19876   const struct strtab_entry *eb = b;
19877   return !strcmp (ea->str, eb->str);
19878 }
19879
19880 /* Create a strtab_entry hash table.  */
19881
19882 static htab_t
19883 create_strtab (void)
19884 {
19885   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19886                             xfree, xcalloc, xfree);
19887 }
19888
19889 /* Add a string to the constant pool.  Return the string's offset in
19890    host order.  */
19891
19892 static offset_type
19893 add_string (htab_t table, struct obstack *cpool, const char *str)
19894 {
19895   void **slot;
19896   struct strtab_entry entry;
19897   struct strtab_entry *result;
19898
19899   entry.str = str;
19900   slot = htab_find_slot (table, &entry, INSERT);
19901   if (*slot)
19902     result = *slot;
19903   else
19904     {
19905       result = XNEW (struct strtab_entry);
19906       result->offset = obstack_object_size (cpool);
19907       result->str = str;
19908       obstack_grow_str0 (cpool, str);
19909       *slot = result;
19910     }
19911   return result->offset;
19912 }
19913
19914 /* An entry in the symbol table.  */
19915 struct symtab_index_entry
19916 {
19917   /* The name of the symbol.  */
19918   const char *name;
19919   /* The offset of the name in the constant pool.  */
19920   offset_type index_offset;
19921   /* A sorted vector of the indices of all the CUs that hold an object
19922      of this name.  */
19923   VEC (offset_type) *cu_indices;
19924 };
19925
19926 /* The symbol table.  This is a power-of-2-sized hash table.  */
19927 struct mapped_symtab
19928 {
19929   offset_type n_elements;
19930   offset_type size;
19931   struct symtab_index_entry **data;
19932 };
19933
19934 /* Hash function for a symtab_index_entry.  */
19935
19936 static hashval_t
19937 hash_symtab_entry (const void *e)
19938 {
19939   const struct symtab_index_entry *entry = e;
19940   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19941                          sizeof (offset_type) * VEC_length (offset_type,
19942                                                             entry->cu_indices),
19943                          0);
19944 }
19945
19946 /* Equality function for a symtab_index_entry.  */
19947
19948 static int
19949 eq_symtab_entry (const void *a, const void *b)
19950 {
19951   const struct symtab_index_entry *ea = a;
19952   const struct symtab_index_entry *eb = b;
19953   int len = VEC_length (offset_type, ea->cu_indices);
19954   if (len != VEC_length (offset_type, eb->cu_indices))
19955     return 0;
19956   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19957                   VEC_address (offset_type, eb->cu_indices),
19958                   sizeof (offset_type) * len);
19959 }
19960
19961 /* Destroy a symtab_index_entry.  */
19962
19963 static void
19964 delete_symtab_entry (void *p)
19965 {
19966   struct symtab_index_entry *entry = p;
19967   VEC_free (offset_type, entry->cu_indices);
19968   xfree (entry);
19969 }
19970
19971 /* Create a hash table holding symtab_index_entry objects.  */
19972
19973 static htab_t
19974 create_symbol_hash_table (void)
19975 {
19976   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19977                             delete_symtab_entry, xcalloc, xfree);
19978 }
19979
19980 /* Create a new mapped symtab object.  */
19981
19982 static struct mapped_symtab *
19983 create_mapped_symtab (void)
19984 {
19985   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
19986   symtab->n_elements = 0;
19987   symtab->size = 1024;
19988   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19989   return symtab;
19990 }
19991
19992 /* Destroy a mapped_symtab.  */
19993
19994 static void
19995 cleanup_mapped_symtab (void *p)
19996 {
19997   struct mapped_symtab *symtab = p;
19998   /* The contents of the array are freed when the other hash table is
19999      destroyed.  */
20000   xfree (symtab->data);
20001   xfree (symtab);
20002 }
20003
20004 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20005    the slot.
20006    
20007    Function is used only during write_hash_table so no index format backward
20008    compatibility is needed.  */
20009
20010 static struct symtab_index_entry **
20011 find_slot (struct mapped_symtab *symtab, const char *name)
20012 {
20013   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20014
20015   index = hash & (symtab->size - 1);
20016   step = ((hash * 17) & (symtab->size - 1)) | 1;
20017
20018   for (;;)
20019     {
20020       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20021         return &symtab->data[index];
20022       index = (index + step) & (symtab->size - 1);
20023     }
20024 }
20025
20026 /* Expand SYMTAB's hash table.  */
20027
20028 static void
20029 hash_expand (struct mapped_symtab *symtab)
20030 {
20031   offset_type old_size = symtab->size;
20032   offset_type i;
20033   struct symtab_index_entry **old_entries = symtab->data;
20034
20035   symtab->size *= 2;
20036   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20037
20038   for (i = 0; i < old_size; ++i)
20039     {
20040       if (old_entries[i])
20041         {
20042           struct symtab_index_entry **slot = find_slot (symtab,
20043                                                         old_entries[i]->name);
20044           *slot = old_entries[i];
20045         }
20046     }
20047
20048   xfree (old_entries);
20049 }
20050
20051 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20052    CU_INDEX is the index of the CU in which the symbol appears.
20053    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20054
20055 static void
20056 add_index_entry (struct mapped_symtab *symtab, const char *name,
20057                  int is_static, gdb_index_symbol_kind kind,
20058                  offset_type cu_index)
20059 {
20060   struct symtab_index_entry **slot;
20061   offset_type cu_index_and_attrs;
20062
20063   ++symtab->n_elements;
20064   if (4 * symtab->n_elements / 3 >= symtab->size)
20065     hash_expand (symtab);
20066
20067   slot = find_slot (symtab, name);
20068   if (!*slot)
20069     {
20070       *slot = XNEW (struct symtab_index_entry);
20071       (*slot)->name = name;
20072       /* index_offset is set later.  */
20073       (*slot)->cu_indices = NULL;
20074     }
20075
20076   cu_index_and_attrs = 0;
20077   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20078   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20079   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20080
20081   /* We don't want to record an index value twice as we want to avoid the
20082      duplication.
20083      We process all global symbols and then all static symbols
20084      (which would allow us to avoid the duplication by only having to check
20085      the last entry pushed), but a symbol could have multiple kinds in one CU.
20086      To keep things simple we don't worry about the duplication here and
20087      sort and uniqufy the list after we've processed all symbols.  */
20088   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20089 }
20090
20091 /* qsort helper routine for uniquify_cu_indices.  */
20092
20093 static int
20094 offset_type_compare (const void *ap, const void *bp)
20095 {
20096   offset_type a = *(offset_type *) ap;
20097   offset_type b = *(offset_type *) bp;
20098
20099   return (a > b) - (b > a);
20100 }
20101
20102 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20103
20104 static void
20105 uniquify_cu_indices (struct mapped_symtab *symtab)
20106 {
20107   int i;
20108
20109   for (i = 0; i < symtab->size; ++i)
20110     {
20111       struct symtab_index_entry *entry = symtab->data[i];
20112
20113       if (entry
20114           && entry->cu_indices != NULL)
20115         {
20116           unsigned int next_to_insert, next_to_check;
20117           offset_type last_value;
20118
20119           qsort (VEC_address (offset_type, entry->cu_indices),
20120                  VEC_length (offset_type, entry->cu_indices),
20121                  sizeof (offset_type), offset_type_compare);
20122
20123           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20124           next_to_insert = 1;
20125           for (next_to_check = 1;
20126                next_to_check < VEC_length (offset_type, entry->cu_indices);
20127                ++next_to_check)
20128             {
20129               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20130                   != last_value)
20131                 {
20132                   last_value = VEC_index (offset_type, entry->cu_indices,
20133                                           next_to_check);
20134                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20135                                last_value);
20136                   ++next_to_insert;
20137                 }
20138             }
20139           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20140         }
20141     }
20142 }
20143
20144 /* Add a vector of indices to the constant pool.  */
20145
20146 static offset_type
20147 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20148                       struct symtab_index_entry *entry)
20149 {
20150   void **slot;
20151
20152   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20153   if (!*slot)
20154     {
20155       offset_type len = VEC_length (offset_type, entry->cu_indices);
20156       offset_type val = MAYBE_SWAP (len);
20157       offset_type iter;
20158       int i;
20159
20160       *slot = entry;
20161       entry->index_offset = obstack_object_size (cpool);
20162
20163       obstack_grow (cpool, &val, sizeof (val));
20164       for (i = 0;
20165            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20166            ++i)
20167         {
20168           val = MAYBE_SWAP (iter);
20169           obstack_grow (cpool, &val, sizeof (val));
20170         }
20171     }
20172   else
20173     {
20174       struct symtab_index_entry *old_entry = *slot;
20175       entry->index_offset = old_entry->index_offset;
20176       entry = old_entry;
20177     }
20178   return entry->index_offset;
20179 }
20180
20181 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20182    constant pool entries going into the obstack CPOOL.  */
20183
20184 static void
20185 write_hash_table (struct mapped_symtab *symtab,
20186                   struct obstack *output, struct obstack *cpool)
20187 {
20188   offset_type i;
20189   htab_t symbol_hash_table;
20190   htab_t str_table;
20191
20192   symbol_hash_table = create_symbol_hash_table ();
20193   str_table = create_strtab ();
20194
20195   /* We add all the index vectors to the constant pool first, to
20196      ensure alignment is ok.  */
20197   for (i = 0; i < symtab->size; ++i)
20198     {
20199       if (symtab->data[i])
20200         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20201     }
20202
20203   /* Now write out the hash table.  */
20204   for (i = 0; i < symtab->size; ++i)
20205     {
20206       offset_type str_off, vec_off;
20207
20208       if (symtab->data[i])
20209         {
20210           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20211           vec_off = symtab->data[i]->index_offset;
20212         }
20213       else
20214         {
20215           /* While 0 is a valid constant pool index, it is not valid
20216              to have 0 for both offsets.  */
20217           str_off = 0;
20218           vec_off = 0;
20219         }
20220
20221       str_off = MAYBE_SWAP (str_off);
20222       vec_off = MAYBE_SWAP (vec_off);
20223
20224       obstack_grow (output, &str_off, sizeof (str_off));
20225       obstack_grow (output, &vec_off, sizeof (vec_off));
20226     }
20227
20228   htab_delete (str_table);
20229   htab_delete (symbol_hash_table);
20230 }
20231
20232 /* Struct to map psymtab to CU index in the index file.  */
20233 struct psymtab_cu_index_map
20234 {
20235   struct partial_symtab *psymtab;
20236   unsigned int cu_index;
20237 };
20238
20239 static hashval_t
20240 hash_psymtab_cu_index (const void *item)
20241 {
20242   const struct psymtab_cu_index_map *map = item;
20243
20244   return htab_hash_pointer (map->psymtab);
20245 }
20246
20247 static int
20248 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20249 {
20250   const struct psymtab_cu_index_map *lhs = item_lhs;
20251   const struct psymtab_cu_index_map *rhs = item_rhs;
20252
20253   return lhs->psymtab == rhs->psymtab;
20254 }
20255
20256 /* Helper struct for building the address table.  */
20257 struct addrmap_index_data
20258 {
20259   struct objfile *objfile;
20260   struct obstack *addr_obstack;
20261   htab_t cu_index_htab;
20262
20263   /* Non-zero if the previous_* fields are valid.
20264      We can't write an entry until we see the next entry (since it is only then
20265      that we know the end of the entry).  */
20266   int previous_valid;
20267   /* Index of the CU in the table of all CUs in the index file.  */
20268   unsigned int previous_cu_index;
20269   /* Start address of the CU.  */
20270   CORE_ADDR previous_cu_start;
20271 };
20272
20273 /* Write an address entry to OBSTACK.  */
20274
20275 static void
20276 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20277                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20278 {
20279   offset_type cu_index_to_write;
20280   char addr[8];
20281   CORE_ADDR baseaddr;
20282
20283   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20284
20285   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20286   obstack_grow (obstack, addr, 8);
20287   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20288   obstack_grow (obstack, addr, 8);
20289   cu_index_to_write = MAYBE_SWAP (cu_index);
20290   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20291 }
20292
20293 /* Worker function for traversing an addrmap to build the address table.  */
20294
20295 static int
20296 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20297 {
20298   struct addrmap_index_data *data = datap;
20299   struct partial_symtab *pst = obj;
20300
20301   if (data->previous_valid)
20302     add_address_entry (data->objfile, data->addr_obstack,
20303                        data->previous_cu_start, start_addr,
20304                        data->previous_cu_index);
20305
20306   data->previous_cu_start = start_addr;
20307   if (pst != NULL)
20308     {
20309       struct psymtab_cu_index_map find_map, *map;
20310       find_map.psymtab = pst;
20311       map = htab_find (data->cu_index_htab, &find_map);
20312       gdb_assert (map != NULL);
20313       data->previous_cu_index = map->cu_index;
20314       data->previous_valid = 1;
20315     }
20316   else
20317       data->previous_valid = 0;
20318
20319   return 0;
20320 }
20321
20322 /* Write OBJFILE's address map to OBSTACK.
20323    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20324    in the index file.  */
20325
20326 static void
20327 write_address_map (struct objfile *objfile, struct obstack *obstack,
20328                    htab_t cu_index_htab)
20329 {
20330   struct addrmap_index_data addrmap_index_data;
20331
20332   /* When writing the address table, we have to cope with the fact that
20333      the addrmap iterator only provides the start of a region; we have to
20334      wait until the next invocation to get the start of the next region.  */
20335
20336   addrmap_index_data.objfile = objfile;
20337   addrmap_index_data.addr_obstack = obstack;
20338   addrmap_index_data.cu_index_htab = cu_index_htab;
20339   addrmap_index_data.previous_valid = 0;
20340
20341   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20342                    &addrmap_index_data);
20343
20344   /* It's highly unlikely the last entry (end address = 0xff...ff)
20345      is valid, but we should still handle it.
20346      The end address is recorded as the start of the next region, but that
20347      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20348      anyway.  */
20349   if (addrmap_index_data.previous_valid)
20350     add_address_entry (objfile, obstack,
20351                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20352                        addrmap_index_data.previous_cu_index);
20353 }
20354
20355 /* Return the symbol kind of PSYM.  */
20356
20357 static gdb_index_symbol_kind
20358 symbol_kind (struct partial_symbol *psym)
20359 {
20360   domain_enum domain = PSYMBOL_DOMAIN (psym);
20361   enum address_class aclass = PSYMBOL_CLASS (psym);
20362
20363   switch (domain)
20364     {
20365     case VAR_DOMAIN:
20366       switch (aclass)
20367         {
20368         case LOC_BLOCK:
20369           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20370         case LOC_TYPEDEF:
20371           return GDB_INDEX_SYMBOL_KIND_TYPE;
20372         case LOC_COMPUTED:
20373         case LOC_CONST_BYTES:
20374         case LOC_OPTIMIZED_OUT:
20375         case LOC_STATIC:
20376           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20377         case LOC_CONST:
20378           /* Note: It's currently impossible to recognize psyms as enum values
20379              short of reading the type info.  For now punt.  */
20380           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20381         default:
20382           /* There are other LOC_FOO values that one might want to classify
20383              as variables, but dwarf2read.c doesn't currently use them.  */
20384           return GDB_INDEX_SYMBOL_KIND_OTHER;
20385         }
20386     case STRUCT_DOMAIN:
20387       return GDB_INDEX_SYMBOL_KIND_TYPE;
20388     default:
20389       return GDB_INDEX_SYMBOL_KIND_OTHER;
20390     }
20391 }
20392
20393 /* Add a list of partial symbols to SYMTAB.  */
20394
20395 static void
20396 write_psymbols (struct mapped_symtab *symtab,
20397                 htab_t psyms_seen,
20398                 struct partial_symbol **psymp,
20399                 int count,
20400                 offset_type cu_index,
20401                 int is_static)
20402 {
20403   for (; count-- > 0; ++psymp)
20404     {
20405       struct partial_symbol *psym = *psymp;
20406       void **slot;
20407
20408       if (SYMBOL_LANGUAGE (psym) == language_ada)
20409         error (_("Ada is not currently supported by the index"));
20410
20411       /* Only add a given psymbol once.  */
20412       slot = htab_find_slot (psyms_seen, psym, INSERT);
20413       if (!*slot)
20414         {
20415           gdb_index_symbol_kind kind = symbol_kind (psym);
20416
20417           *slot = psym;
20418           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20419                            is_static, kind, cu_index);
20420         }
20421     }
20422 }
20423
20424 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20425    exception if there is an error.  */
20426
20427 static void
20428 write_obstack (FILE *file, struct obstack *obstack)
20429 {
20430   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20431               file)
20432       != obstack_object_size (obstack))
20433     error (_("couldn't data write to file"));
20434 }
20435
20436 /* Unlink a file if the argument is not NULL.  */
20437
20438 static void
20439 unlink_if_set (void *p)
20440 {
20441   char **filename = p;
20442   if (*filename)
20443     unlink (*filename);
20444 }
20445
20446 /* A helper struct used when iterating over debug_types.  */
20447 struct signatured_type_index_data
20448 {
20449   struct objfile *objfile;
20450   struct mapped_symtab *symtab;
20451   struct obstack *types_list;
20452   htab_t psyms_seen;
20453   int cu_index;
20454 };
20455
20456 /* A helper function that writes a single signatured_type to an
20457    obstack.  */
20458
20459 static int
20460 write_one_signatured_type (void **slot, void *d)
20461 {
20462   struct signatured_type_index_data *info = d;
20463   struct signatured_type *entry = (struct signatured_type *) *slot;
20464   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
20465   struct partial_symtab *psymtab = per_cu->v.psymtab;
20466   gdb_byte val[8];
20467
20468   write_psymbols (info->symtab,
20469                   info->psyms_seen,
20470                   info->objfile->global_psymbols.list
20471                   + psymtab->globals_offset,
20472                   psymtab->n_global_syms, info->cu_index,
20473                   0);
20474   write_psymbols (info->symtab,
20475                   info->psyms_seen,
20476                   info->objfile->static_psymbols.list
20477                   + psymtab->statics_offset,
20478                   psymtab->n_static_syms, info->cu_index,
20479                   1);
20480
20481   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20482                           entry->per_cu.offset.sect_off);
20483   obstack_grow (info->types_list, val, 8);
20484   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20485                           entry->type_offset_in_tu.cu_off);
20486   obstack_grow (info->types_list, val, 8);
20487   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20488   obstack_grow (info->types_list, val, 8);
20489
20490   ++info->cu_index;
20491
20492   return 1;
20493 }
20494
20495 /* Recurse into all "included" dependencies and write their symbols as
20496    if they appeared in this psymtab.  */
20497
20498 static void
20499 recursively_write_psymbols (struct objfile *objfile,
20500                             struct partial_symtab *psymtab,
20501                             struct mapped_symtab *symtab,
20502                             htab_t psyms_seen,
20503                             offset_type cu_index)
20504 {
20505   int i;
20506
20507   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20508     if (psymtab->dependencies[i]->user != NULL)
20509       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20510                                   symtab, psyms_seen, cu_index);
20511
20512   write_psymbols (symtab,
20513                   psyms_seen,
20514                   objfile->global_psymbols.list + psymtab->globals_offset,
20515                   psymtab->n_global_syms, cu_index,
20516                   0);
20517   write_psymbols (symtab,
20518                   psyms_seen,
20519                   objfile->static_psymbols.list + psymtab->statics_offset,
20520                   psymtab->n_static_syms, cu_index,
20521                   1);
20522 }
20523
20524 /* Create an index file for OBJFILE in the directory DIR.  */
20525
20526 static void
20527 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20528 {
20529   struct cleanup *cleanup;
20530   char *filename, *cleanup_filename;
20531   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20532   struct obstack cu_list, types_cu_list;
20533   int i;
20534   FILE *out_file;
20535   struct mapped_symtab *symtab;
20536   offset_type val, size_of_contents, total_len;
20537   struct stat st;
20538   htab_t psyms_seen;
20539   htab_t cu_index_htab;
20540   struct psymtab_cu_index_map *psymtab_cu_index_map;
20541
20542   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20543     return;
20544
20545   if (dwarf2_per_objfile->using_index)
20546     error (_("Cannot use an index to create the index"));
20547
20548   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20549     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20550
20551   if (stat (objfile->name, &st) < 0)
20552     perror_with_name (objfile->name);
20553
20554   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20555                      INDEX_SUFFIX, (char *) NULL);
20556   cleanup = make_cleanup (xfree, filename);
20557
20558   out_file = fopen (filename, "wb");
20559   if (!out_file)
20560     error (_("Can't open `%s' for writing"), filename);
20561
20562   cleanup_filename = filename;
20563   make_cleanup (unlink_if_set, &cleanup_filename);
20564
20565   symtab = create_mapped_symtab ();
20566   make_cleanup (cleanup_mapped_symtab, symtab);
20567
20568   obstack_init (&addr_obstack);
20569   make_cleanup_obstack_free (&addr_obstack);
20570
20571   obstack_init (&cu_list);
20572   make_cleanup_obstack_free (&cu_list);
20573
20574   obstack_init (&types_cu_list);
20575   make_cleanup_obstack_free (&types_cu_list);
20576
20577   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20578                                   NULL, xcalloc, xfree);
20579   make_cleanup_htab_delete (psyms_seen);
20580
20581   /* While we're scanning CU's create a table that maps a psymtab pointer
20582      (which is what addrmap records) to its index (which is what is recorded
20583      in the index file).  This will later be needed to write the address
20584      table.  */
20585   cu_index_htab = htab_create_alloc (100,
20586                                      hash_psymtab_cu_index,
20587                                      eq_psymtab_cu_index,
20588                                      NULL, xcalloc, xfree);
20589   make_cleanup_htab_delete (cu_index_htab);
20590   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20591     xmalloc (sizeof (struct psymtab_cu_index_map)
20592              * dwarf2_per_objfile->n_comp_units);
20593   make_cleanup (xfree, psymtab_cu_index_map);
20594
20595   /* The CU list is already sorted, so we don't need to do additional
20596      work here.  Also, the debug_types entries do not appear in
20597      all_comp_units, but only in their own hash table.  */
20598   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20599     {
20600       struct dwarf2_per_cu_data *per_cu
20601         = dwarf2_per_objfile->all_comp_units[i];
20602       struct partial_symtab *psymtab = per_cu->v.psymtab;
20603       gdb_byte val[8];
20604       struct psymtab_cu_index_map *map;
20605       void **slot;
20606
20607       if (psymtab->user == NULL)
20608         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20609
20610       map = &psymtab_cu_index_map[i];
20611       map->psymtab = psymtab;
20612       map->cu_index = i;
20613       slot = htab_find_slot (cu_index_htab, map, INSERT);
20614       gdb_assert (slot != NULL);
20615       gdb_assert (*slot == NULL);
20616       *slot = map;
20617
20618       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20619                               per_cu->offset.sect_off);
20620       obstack_grow (&cu_list, val, 8);
20621       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20622       obstack_grow (&cu_list, val, 8);
20623     }
20624
20625   /* Dump the address map.  */
20626   write_address_map (objfile, &addr_obstack, cu_index_htab);
20627
20628   /* Write out the .debug_type entries, if any.  */
20629   if (dwarf2_per_objfile->signatured_types)
20630     {
20631       struct signatured_type_index_data sig_data;
20632
20633       sig_data.objfile = objfile;
20634       sig_data.symtab = symtab;
20635       sig_data.types_list = &types_cu_list;
20636       sig_data.psyms_seen = psyms_seen;
20637       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20638       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20639                               write_one_signatured_type, &sig_data);
20640     }
20641
20642   /* Now that we've processed all symbols we can shrink their cu_indices
20643      lists.  */
20644   uniquify_cu_indices (symtab);
20645
20646   obstack_init (&constant_pool);
20647   make_cleanup_obstack_free (&constant_pool);
20648   obstack_init (&symtab_obstack);
20649   make_cleanup_obstack_free (&symtab_obstack);
20650   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20651
20652   obstack_init (&contents);
20653   make_cleanup_obstack_free (&contents);
20654   size_of_contents = 6 * sizeof (offset_type);
20655   total_len = size_of_contents;
20656
20657   /* The version number.  */
20658   val = MAYBE_SWAP (8);
20659   obstack_grow (&contents, &val, sizeof (val));
20660
20661   /* The offset of the CU list from the start of the file.  */
20662   val = MAYBE_SWAP (total_len);
20663   obstack_grow (&contents, &val, sizeof (val));
20664   total_len += obstack_object_size (&cu_list);
20665
20666   /* The offset of the types CU list from the start of the file.  */
20667   val = MAYBE_SWAP (total_len);
20668   obstack_grow (&contents, &val, sizeof (val));
20669   total_len += obstack_object_size (&types_cu_list);
20670
20671   /* The offset of the address table from the start of the file.  */
20672   val = MAYBE_SWAP (total_len);
20673   obstack_grow (&contents, &val, sizeof (val));
20674   total_len += obstack_object_size (&addr_obstack);
20675
20676   /* The offset of the symbol table from the start of the file.  */
20677   val = MAYBE_SWAP (total_len);
20678   obstack_grow (&contents, &val, sizeof (val));
20679   total_len += obstack_object_size (&symtab_obstack);
20680
20681   /* The offset of the constant pool from the start of the file.  */
20682   val = MAYBE_SWAP (total_len);
20683   obstack_grow (&contents, &val, sizeof (val));
20684   total_len += obstack_object_size (&constant_pool);
20685
20686   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20687
20688   write_obstack (out_file, &contents);
20689   write_obstack (out_file, &cu_list);
20690   write_obstack (out_file, &types_cu_list);
20691   write_obstack (out_file, &addr_obstack);
20692   write_obstack (out_file, &symtab_obstack);
20693   write_obstack (out_file, &constant_pool);
20694
20695   fclose (out_file);
20696
20697   /* We want to keep the file, so we set cleanup_filename to NULL
20698      here.  See unlink_if_set.  */
20699   cleanup_filename = NULL;
20700
20701   do_cleanups (cleanup);
20702 }
20703
20704 /* Implementation of the `save gdb-index' command.
20705    
20706    Note that the file format used by this command is documented in the
20707    GDB manual.  Any changes here must be documented there.  */
20708
20709 static void
20710 save_gdb_index_command (char *arg, int from_tty)
20711 {
20712   struct objfile *objfile;
20713
20714   if (!arg || !*arg)
20715     error (_("usage: save gdb-index DIRECTORY"));
20716
20717   ALL_OBJFILES (objfile)
20718   {
20719     struct stat st;
20720
20721     /* If the objfile does not correspond to an actual file, skip it.  */
20722     if (stat (objfile->name, &st) < 0)
20723       continue;
20724
20725     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20726     if (dwarf2_per_objfile)
20727       {
20728         volatile struct gdb_exception except;
20729
20730         TRY_CATCH (except, RETURN_MASK_ERROR)
20731           {
20732             write_psymtabs_to_index (objfile, arg);
20733           }
20734         if (except.reason < 0)
20735           exception_fprintf (gdb_stderr, except,
20736                              _("Error while writing index for `%s': "),
20737                              objfile->name);
20738       }
20739   }
20740 }
20741
20742 \f
20743
20744 int dwarf2_always_disassemble;
20745
20746 static void
20747 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20748                                 struct cmd_list_element *c, const char *value)
20749 {
20750   fprintf_filtered (file,
20751                     _("Whether to always disassemble "
20752                       "DWARF expressions is %s.\n"),
20753                     value);
20754 }
20755
20756 static void
20757 show_check_physname (struct ui_file *file, int from_tty,
20758                      struct cmd_list_element *c, const char *value)
20759 {
20760   fprintf_filtered (file,
20761                     _("Whether to check \"physname\" is %s.\n"),
20762                     value);
20763 }
20764
20765 void _initialize_dwarf2_read (void);
20766
20767 void
20768 _initialize_dwarf2_read (void)
20769 {
20770   struct cmd_list_element *c;
20771
20772   dwarf2_objfile_data_key
20773     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20774
20775   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20776 Set DWARF 2 specific variables.\n\
20777 Configure DWARF 2 variables such as the cache size"),
20778                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20779                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20780
20781   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20782 Show DWARF 2 specific variables\n\
20783 Show DWARF 2 variables such as the cache size"),
20784                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20785                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20786
20787   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20788                             &dwarf2_max_cache_age, _("\
20789 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20790 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20791 A higher limit means that cached compilation units will be stored\n\
20792 in memory longer, and more total memory will be used.  Zero disables\n\
20793 caching, which can slow down startup."),
20794                             NULL,
20795                             show_dwarf2_max_cache_age,
20796                             &set_dwarf2_cmdlist,
20797                             &show_dwarf2_cmdlist);
20798
20799   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20800                            &dwarf2_always_disassemble, _("\
20801 Set whether `info address' always disassembles DWARF expressions."), _("\
20802 Show whether `info address' always disassembles DWARF expressions."), _("\
20803 When enabled, DWARF expressions are always printed in an assembly-like\n\
20804 syntax.  When disabled, expressions will be printed in a more\n\
20805 conversational style, when possible."),
20806                            NULL,
20807                            show_dwarf2_always_disassemble,
20808                            &set_dwarf2_cmdlist,
20809                            &show_dwarf2_cmdlist);
20810
20811   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20812 Set debugging of the dwarf2 reader."), _("\
20813 Show debugging of the dwarf2 reader."), _("\
20814 When enabled, debugging messages are printed during dwarf2 reading\n\
20815 and symtab expansion."),
20816                             NULL,
20817                             NULL,
20818                             &setdebuglist, &showdebuglist);
20819
20820   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20821 Set debugging of the dwarf2 DIE reader."), _("\
20822 Show debugging of the dwarf2 DIE reader."), _("\
20823 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20824 The value is the maximum depth to print."),
20825                              NULL,
20826                              NULL,
20827                              &setdebuglist, &showdebuglist);
20828
20829   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20830 Set cross-checking of \"physname\" code against demangler."), _("\
20831 Show cross-checking of \"physname\" code against demangler."), _("\
20832 When enabled, GDB's internal \"physname\" code is checked against\n\
20833 the demangler."),
20834                            NULL, show_check_physname,
20835                            &setdebuglist, &showdebuglist);
20836
20837   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20838                            no_class, &use_deprecated_index_sections, _("\
20839 Set whether to use deprecated gdb_index sections."), _("\
20840 Show whether to use deprecated gdb_index sections."), _("\
20841 When enabled, deprecated .gdb_index sections are used anyway.\n\
20842 Normally they are ignored either because of a missing feature or\n\
20843 performance issue.\n\
20844 Warning: This option must be enabled before gdb reads the file."),
20845                            NULL,
20846                            NULL,
20847                            &setlist, &showlist);
20848
20849   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20850                _("\
20851 Save a gdb-index file.\n\
20852 Usage: save gdb-index DIRECTORY"),
20853                &save_cmdlist);
20854   set_cmd_completer (c, filename_completer);
20855
20856   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
20857                                                         &dwarf2_locexpr_funcs);
20858   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
20859                                                         &dwarf2_loclist_funcs);
20860
20861   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
20862                                         &dwarf2_block_frame_base_locexpr_funcs);
20863   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
20864                                         &dwarf2_block_frame_base_loclist_funcs);
20865 }