2012-05-25 Sriraman Tallam <tmsriram@google.com>
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2012 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 "symtab.h"
34 #include "gdbtypes.h"
35 #include "objfiles.h"
36 #include "dwarf2.h"
37 #include "buildsym.h"
38 #include "demangle.h"
39 #include "gdb-demangle.h"
40 #include "expression.h"
41 #include "filenames.h"  /* for DOSish file names */
42 #include "macrotab.h"
43 #include "language.h"
44 #include "complaints.h"
45 #include "bcache.h"
46 #include "dwarf2expr.h"
47 #include "dwarf2loc.h"
48 #include "cp-support.h"
49 #include "hashtab.h"
50 #include "command.h"
51 #include "gdbcmd.h"
52 #include "block.h"
53 #include "addrmap.h"
54 #include "typeprint.h"
55 #include "jv-lang.h"
56 #include "psympriv.h"
57 #include "exceptions.h"
58 #include "gdb_stat.h"
59 #include "completer.h"
60 #include "vec.h"
61 #include "c-lang.h"
62 #include "go-lang.h"
63 #include "valprint.h"
64 #include "gdbcore.h" /* for gnutarget */
65 #include <ctype.h>
66
67 #include <fcntl.h>
68 #include "gdb_string.h"
69 #include "gdb_assert.h"
70 #include <sys/types.h>
71 #ifdef HAVE_ZLIB_H
72 #include <zlib.h>
73 #endif
74 #ifdef HAVE_MMAP
75 #include <sys/mman.h>
76 #ifndef MAP_FAILED
77 #define MAP_FAILED ((void *) -1)
78 #endif
79 #endif
80
81 typedef struct symbol *symbolp;
82 DEF_VEC_P (symbolp);
83
84 /* When non-zero, dump DIEs after they are read in.  */
85 static 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 int use_deprecated_index_sections = 0;
92
93 static int pagesize;
94
95 /* When set, the file that we're processing is known to have debugging
96    info for C++ namespaces.  GCC 3.3.x did not produce this information,
97    but later versions do.  */
98
99 static int processing_has_namespace_info;
100
101 static const struct objfile_data *dwarf2_objfile_data_key;
102
103 struct dwarf2_section_info
104 {
105   asection *asection;
106   gdb_byte *buffer;
107   bfd_size_type size;
108   /* Not NULL if the section was actually mmapped.  */
109   void *map_addr;
110   /* Page aligned size of mmapped area.  */
111   bfd_size_type map_len;
112   /* True if we have tried to read this section.  */
113   int readin;
114 };
115
116 typedef struct dwarf2_section_info dwarf2_section_info_def;
117 DEF_VEC_O (dwarf2_section_info_def);
118
119 /* All offsets in the index are of this type.  It must be
120    architecture-independent.  */
121 typedef uint32_t offset_type;
122
123 DEF_VEC_I (offset_type);
124
125 /* A description of the mapped index.  The file format is described in
126    a comment by the code that writes the index.  */
127 struct mapped_index
128 {
129   /* Index data format version.  */
130   int version;
131
132   /* The total length of the buffer.  */
133   off_t total_size;
134
135   /* A pointer to the address table data.  */
136   const gdb_byte *address_table;
137
138   /* Size of the address table data in bytes.  */
139   offset_type address_table_size;
140
141   /* The symbol table, implemented as a hash table.  */
142   const offset_type *symbol_table;
143
144   /* Size in slots, each slot is 2 offset_types.  */
145   offset_type symbol_table_slots;
146
147   /* A pointer to the constant pool.  */
148   const char *constant_pool;
149 };
150
151 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
152 DEF_VEC_P (dwarf2_per_cu_ptr);
153
154 /* Collection of data recorded per objfile.
155    This hangs off of dwarf2_objfile_data_key.  */
156
157 struct dwarf2_per_objfile
158 {
159   struct dwarf2_section_info info;
160   struct dwarf2_section_info abbrev;
161   struct dwarf2_section_info line;
162   struct dwarf2_section_info loc;
163   struct dwarf2_section_info macinfo;
164   struct dwarf2_section_info macro;
165   struct dwarf2_section_info str;
166   struct dwarf2_section_info ranges;
167   struct dwarf2_section_info addr;
168   struct dwarf2_section_info frame;
169   struct dwarf2_section_info eh_frame;
170   struct dwarf2_section_info gdb_index;
171
172   VEC (dwarf2_section_info_def) *types;
173
174   /* Back link.  */
175   struct objfile *objfile;
176
177   /* Table of all the compilation units.  This is used to locate
178      the target compilation unit of a particular reference.  */
179   struct dwarf2_per_cu_data **all_comp_units;
180
181   /* The number of compilation units in ALL_COMP_UNITS.  */
182   int n_comp_units;
183
184   /* The number of .debug_types-related CUs.  */
185   int n_type_units;
186
187   /* The .debug_types-related CUs (TUs).  */
188   struct dwarf2_per_cu_data **all_type_units;
189
190   /* A chain of compilation units that are currently read in, so that
191      they can be freed later.  */
192   struct dwarf2_per_cu_data *read_in_chain;
193
194   /* A table mapping .debug_types signatures to its signatured_type entry.
195      This is NULL if the .debug_types section hasn't been read in yet.  */
196   htab_t signatured_types;
197
198   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
199      This is NULL if the table hasn't been allocated yet.  */
200   htab_t dwo_files;
201
202   /* A flag indicating wether this objfile has a section loaded at a
203      VMA of 0.  */
204   int has_section_at_zero;
205
206   /* True if we are using the mapped index,
207      or we are faking it for OBJF_READNOW's sake.  */
208   unsigned char using_index;
209
210   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
211   struct mapped_index *index_table;
212
213   /* When using index_table, this keeps track of all quick_file_names entries.
214      TUs can share line table entries with CUs or other TUs, and there can be
215      a lot more TUs than unique line tables, so we maintain a separate table
216      of all line table entries to support the sharing.  */
217   htab_t quick_file_names_table;
218
219   /* Set during partial symbol reading, to prevent queueing of full
220      symbols.  */
221   int reading_partial_symbols;
222
223   /* Table mapping type DIEs to their struct type *.
224      This is NULL if not allocated yet.
225      The mapping is done via (CU/TU signature + DIE offset) -> type.  */
226   htab_t die_type_hash;
227
228   /* The CUs we recently read.  */
229   VEC (dwarf2_per_cu_ptr) *just_read_cus;
230 };
231
232 static struct dwarf2_per_objfile *dwarf2_per_objfile;
233
234 /* Default names of the debugging sections.  */
235
236 /* Note that if the debugging section has been compressed, it might
237    have a name like .zdebug_info.  */
238
239 static const struct dwarf2_debug_sections dwarf2_elf_names =
240 {
241   { ".debug_info", ".zdebug_info" },
242   { ".debug_abbrev", ".zdebug_abbrev" },
243   { ".debug_line", ".zdebug_line" },
244   { ".debug_loc", ".zdebug_loc" },
245   { ".debug_macinfo", ".zdebug_macinfo" },
246   { ".debug_macro", ".zdebug_macro" },
247   { ".debug_str", ".zdebug_str" },
248   { ".debug_ranges", ".zdebug_ranges" },
249   { ".debug_types", ".zdebug_types" },
250   { ".debug_addr", ".zdebug_addr" },
251   { ".debug_frame", ".zdebug_frame" },
252   { ".eh_frame", NULL },
253   { ".gdb_index", ".zgdb_index" },
254   23
255 };
256
257 /* List of DWO sections.  */
258
259 static const struct dwo_section_names
260 {
261   struct dwarf2_section_names abbrev_dwo;
262   struct dwarf2_section_names info_dwo;
263   struct dwarf2_section_names line_dwo;
264   struct dwarf2_section_names loc_dwo;
265   struct dwarf2_section_names str_dwo;
266   struct dwarf2_section_names str_offsets_dwo;
267   struct dwarf2_section_names types_dwo;
268 }
269 dwo_section_names =
270 {
271   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
272   { ".debug_info.dwo", ".zdebug_info.dwo" },
273   { ".debug_line.dwo", ".zdebug_line.dwo" },
274   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
275   { ".debug_str.dwo", ".zdebug_str.dwo" },
276   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
277   { ".debug_types.dwo", ".zdebug_types.dwo" },
278 };
279
280 /* local data types */
281
282 /* We hold several abbreviation tables in memory at the same time.  */
283 #ifndef ABBREV_HASH_SIZE
284 #define ABBREV_HASH_SIZE 121
285 #endif
286
287 /* The data in a compilation unit header, after target2host
288    translation, looks like this.  */
289 struct comp_unit_head
290 {
291   unsigned int length;
292   short version;
293   unsigned char addr_size;
294   unsigned char signed_addr_p;
295   sect_offset abbrev_offset;
296
297   /* Size of file offsets; either 4 or 8.  */
298   unsigned int offset_size;
299
300   /* Size of the length field; either 4 or 12.  */
301   unsigned int initial_length_size;
302
303   /* Offset to the first byte of this compilation unit header in the
304      .debug_info section, for resolving relative reference dies.  */
305   sect_offset offset;
306
307   /* Offset to first die in this cu from the start of the cu.
308      This will be the first byte following the compilation unit header.  */
309   cu_offset first_die_offset;
310 };
311
312 /* Type used for delaying computation of method physnames.
313    See comments for compute_delayed_physnames.  */
314 struct delayed_method_info
315 {
316   /* The type to which the method is attached, i.e., its parent class.  */
317   struct type *type;
318
319   /* The index of the method in the type's function fieldlists.  */
320   int fnfield_index;
321
322   /* The index of the method in the fieldlist.  */
323   int index;
324
325   /* The name of the DIE.  */
326   const char *name;
327
328   /*  The DIE associated with this method.  */
329   struct die_info *die;
330 };
331
332 typedef struct delayed_method_info delayed_method_info;
333 DEF_VEC_O (delayed_method_info);
334
335 /* Internal state when decoding a particular compilation unit.  */
336 struct dwarf2_cu
337 {
338   /* The objfile containing this compilation unit.  */
339   struct objfile *objfile;
340
341   /* The header of the compilation unit.  */
342   struct comp_unit_head header;
343
344   /* Base address of this compilation unit.  */
345   CORE_ADDR base_address;
346
347   /* Non-zero if base_address has been set.  */
348   int base_known;
349
350   /* The language we are debugging.  */
351   enum language language;
352   const struct language_defn *language_defn;
353
354   const char *producer;
355
356   /* The generic symbol table building routines have separate lists for
357      file scope symbols and all all other scopes (local scopes).  So
358      we need to select the right one to pass to add_symbol_to_list().
359      We do it by keeping a pointer to the correct list in list_in_scope.
360
361      FIXME: The original dwarf code just treated the file scope as the
362      first local scope, and all other local scopes as nested local
363      scopes, and worked fine.  Check to see if we really need to
364      distinguish these in buildsym.c.  */
365   struct pending **list_in_scope;
366
367   /* DWARF abbreviation table associated with this compilation unit.  */
368   struct abbrev_info **dwarf2_abbrevs;
369
370   /* Storage for the abbrev table.  */
371   struct obstack abbrev_obstack;
372
373   /* Hash table holding all the loaded partial DIEs
374      with partial_die->offset.SECT_OFF as hash.  */
375   htab_t partial_dies;
376
377   /* Storage for things with the same lifetime as this read-in compilation
378      unit, including partial DIEs.  */
379   struct obstack comp_unit_obstack;
380
381   /* When multiple dwarf2_cu structures are living in memory, this field
382      chains them all together, so that they can be released efficiently.
383      We will probably also want a generation counter so that most-recently-used
384      compilation units are cached...  */
385   struct dwarf2_per_cu_data *read_in_chain;
386
387   /* Backchain to our per_cu entry if the tree has been built.  */
388   struct dwarf2_per_cu_data *per_cu;
389
390   /* How many compilation units ago was this CU last referenced?  */
391   int last_used;
392
393   /* A hash table of DIE cu_offset for following references with
394      die_info->offset.sect_off as hash.  */
395   htab_t die_hash;
396
397   /* Full DIEs if read in.  */
398   struct die_info *dies;
399
400   /* A set of pointers to dwarf2_per_cu_data objects for compilation
401      units referenced by this one.  Only set during full symbol processing;
402      partial symbol tables do not have dependencies.  */
403   htab_t dependencies;
404
405   /* Header data from the line table, during full symbol processing.  */
406   struct line_header *line_header;
407
408   /* A list of methods which need to have physnames computed
409      after all type information has been read.  */
410   VEC (delayed_method_info) *method_list;
411
412   /* To be copied to symtab->call_site_htab.  */
413   htab_t call_site_htab;
414
415   /* Non-NULL if this CU came from a DWO file.  */
416   struct dwo_unit *dwo_unit;
417
418   /* The DW_AT_addr_base attribute if present, zero otherwise
419      (zero is a valid value though).
420      Note this value comes from the stub CU/TU's DIE.  */
421   ULONGEST addr_base;
422
423   /* Mark used when releasing cached dies.  */
424   unsigned int mark : 1;
425
426   /* This CU references .debug_loc.  See the symtab->locations_valid field.
427      This test is imperfect as there may exist optimized debug code not using
428      any location list and still facing inlining issues if handled as
429      unoptimized code.  For a future better test see GCC PR other/32998.  */
430   unsigned int has_loclist : 1;
431
432   /* These cache the results for producer_is_gxx_lt_4_6 and producer_is_icc.
433      CHECKED_PRODUCER is set if both PRODUCER_IS_GXX_LT_4_6 and PRODUCER_IS_ICC
434      are valid.  This information is cached because profiling CU expansion
435      showed excessive time spent in producer_is_gxx_lt_4_6.  */
436   unsigned int checked_producer : 1;
437   unsigned int producer_is_gxx_lt_4_6 : 1;
438   unsigned int producer_is_icc : 1;
439
440   /* Non-zero if DW_AT_addr_base was found.
441      Used when processing DWO files.  */
442   unsigned int have_addr_base : 1;
443 };
444
445 /* Persistent data held for a compilation unit, even when not
446    processing it.  We put a pointer to this structure in the
447    read_symtab_private field of the psymtab.  */
448
449 struct dwarf2_per_cu_data
450 {
451   /* The start offset and length of this compilation unit.  2**29-1
452      bytes should suffice to store the length of any compilation unit
453      - if it doesn't, GDB will fall over anyway.
454      NOTE: Unlike comp_unit_head.length, this length includes
455      initial_length_size.
456      If the DIE refers to a DWO file, this is always of the original die,
457      not the DWO file.  */
458   sect_offset offset;
459   unsigned int length : 29;
460
461   /* Flag indicating this compilation unit will be read in before
462      any of the current compilation units are processed.  */
463   unsigned int queued : 1;
464
465   /* This flag will be set when reading partial DIEs if we need to load
466      absolutely all DIEs for this compilation unit, instead of just the ones
467      we think are interesting.  It gets set if we look for a DIE in the
468      hash table and don't find it.  */
469   unsigned int load_all_dies : 1;
470
471   /* Non-zero if this CU is from .debug_types.  */
472   unsigned int is_debug_types : 1;
473
474   /* The section this CU/TU lives in.
475      If the DIE refers to a DWO file, this is always the original die,
476      not the DWO file.  */
477   struct dwarf2_section_info *info_or_types_section;
478
479   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
480      of the CU cache it gets reset to NULL again.  */
481   struct dwarf2_cu *cu;
482
483   /* The corresponding objfile.
484      Normally we can get the objfile from dwarf2_per_objfile.
485      However we can enter this file with just a "per_cu" handle.  */
486   struct objfile *objfile;
487
488   /* When using partial symbol tables, the 'psymtab' field is active.
489      Otherwise the 'quick' field is active.  */
490   union
491   {
492     /* The partial symbol table associated with this compilation unit,
493        or NULL for unread partial units.  */
494     struct partial_symtab *psymtab;
495
496     /* Data needed by the "quick" functions.  */
497     struct dwarf2_per_cu_quick_data *quick;
498   } v;
499
500   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
501      while reading psymtabs, used to compute the psymtab dependencies,
502      and then cleared.  Then it is filled in again while reading full
503      symbols, and only deleted when the objfile is destroyed.  */
504   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
505 };
506
507 /* Entry in the signatured_types hash table.  */
508
509 struct signatured_type
510 {
511   /* The type's signature.  */
512   ULONGEST signature;
513
514   /* Offset in the TU of the type's DIE, as read from the TU header.
515      If the definition lives in a DWO file, this value is unusable.  */
516   cu_offset type_offset_in_tu;
517
518   /* Offset in the section of the type's DIE.
519      If the definition lives in a DWO file, this is the offset in the
520      .debug_types.dwo section.
521      The value is zero until the actual value is known.
522      Zero is otherwise not a valid section offset.  */
523   sect_offset type_offset_in_section;
524
525   /* The CU(/TU) of this type.  */
526   struct dwarf2_per_cu_data per_cu;
527 };
528
529 /* These sections are what may appear in a "dwo" file.  */
530
531 struct dwo_sections
532 {
533   struct dwarf2_section_info abbrev;
534   struct dwarf2_section_info info;
535   struct dwarf2_section_info line;
536   struct dwarf2_section_info loc;
537   struct dwarf2_section_info str;
538   struct dwarf2_section_info str_offsets;
539   VEC (dwarf2_section_info_def) *types;
540 };
541
542 /* Common bits of DWO CUs/TUs.  */
543
544 struct dwo_unit
545 {
546   /* Backlink to the containing struct dwo_file.  */
547   struct dwo_file *dwo_file;
548
549   /* The "id" that distinguishes this CU/TU.
550      .debug_info calls this "dwo_id", .debug_types calls this "signature".
551      Since signatures came first, we stick with it for consistency.  */
552   ULONGEST signature;
553
554   /* The section this CU/TU lives in, in the DWO file.  */
555   struct dwarf2_section_info *info_or_types_section;
556
557   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
558   sect_offset offset;
559   unsigned int length;
560
561   /* For types, offset in the type's DIE of the type defined by this TU.  */
562   cu_offset type_offset_in_tu;
563 };
564
565 /* Data for one DWO file.  */
566
567 struct dwo_file
568 {
569   /* The DW_AT_GNU_dwo_name attribute.
570      We don't manage space for this, it's an attribute.  */
571   const char *dwo_name;
572
573   /* The bfd, when the file is open.  Otherwise this is NULL.  */
574   bfd *dwo_bfd;
575
576   /* Section info for this file.  */
577   struct dwo_sections sections;
578
579   /* Table of CUs in the file.
580      Each element is a struct dwo_unit.  */
581   htab_t cus;
582
583   /* Table of TUs in the file.
584      Each element is a struct dwo_unit.  */
585   htab_t tus;
586 };
587
588 /* Struct used to pass misc. parameters to read_die_and_children, et
589    al.  which are used for both .debug_info and .debug_types dies.
590    All parameters here are unchanging for the life of the call.  This
591    struct exists to abstract away the constant parameters of die reading.  */
592
593 struct die_reader_specs
594 {
595   /* die_section->asection->owner.  */
596   bfd* abfd;
597
598   /* The CU of the DIE we are parsing.  */
599   struct dwarf2_cu *cu;
600
601   /* Non-NULL if reading a DWO file.  */
602   struct dwo_file *dwo_file;
603
604   /* The section the die comes from.
605      This is either .debug_info or .debug_types, or the .dwo variants.  */
606   struct dwarf2_section_info *die_section;
607
608   /* die_section->buffer.  */
609   gdb_byte *buffer;
610
611   /* The end of the buffer.  */
612   const gdb_byte *buffer_end;
613 };
614
615 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
616 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
617                                       gdb_byte *info_ptr,
618                                       struct die_info *comp_unit_die,
619                                       int has_children,
620                                       void *data);
621
622 /* The line number information for a compilation unit (found in the
623    .debug_line section) begins with a "statement program header",
624    which contains the following information.  */
625 struct line_header
626 {
627   unsigned int total_length;
628   unsigned short version;
629   unsigned int header_length;
630   unsigned char minimum_instruction_length;
631   unsigned char maximum_ops_per_instruction;
632   unsigned char default_is_stmt;
633   int line_base;
634   unsigned char line_range;
635   unsigned char opcode_base;
636
637   /* standard_opcode_lengths[i] is the number of operands for the
638      standard opcode whose value is i.  This means that
639      standard_opcode_lengths[0] is unused, and the last meaningful
640      element is standard_opcode_lengths[opcode_base - 1].  */
641   unsigned char *standard_opcode_lengths;
642
643   /* The include_directories table.  NOTE!  These strings are not
644      allocated with xmalloc; instead, they are pointers into
645      debug_line_buffer.  If you try to free them, `free' will get
646      indigestion.  */
647   unsigned int num_include_dirs, include_dirs_size;
648   char **include_dirs;
649
650   /* The file_names table.  NOTE!  These strings are not allocated
651      with xmalloc; instead, they are pointers into debug_line_buffer.
652      Don't try to free them directly.  */
653   unsigned int num_file_names, file_names_size;
654   struct file_entry
655   {
656     char *name;
657     unsigned int dir_index;
658     unsigned int mod_time;
659     unsigned int length;
660     int included_p; /* Non-zero if referenced by the Line Number Program.  */
661     struct symtab *symtab; /* The associated symbol table, if any.  */
662   } *file_names;
663
664   /* The start and end of the statement program following this
665      header.  These point into dwarf2_per_objfile->line_buffer.  */
666   gdb_byte *statement_program_start, *statement_program_end;
667 };
668
669 /* When we construct a partial symbol table entry we only
670    need this much information.  */
671 struct partial_die_info
672   {
673     /* Offset of this DIE.  */
674     sect_offset offset;
675
676     /* DWARF-2 tag for this DIE.  */
677     ENUM_BITFIELD(dwarf_tag) tag : 16;
678
679     /* Assorted flags describing the data found in this DIE.  */
680     unsigned int has_children : 1;
681     unsigned int is_external : 1;
682     unsigned int is_declaration : 1;
683     unsigned int has_type : 1;
684     unsigned int has_specification : 1;
685     unsigned int has_pc_info : 1;
686     unsigned int may_be_inlined : 1;
687
688     /* Flag set if the SCOPE field of this structure has been
689        computed.  */
690     unsigned int scope_set : 1;
691
692     /* Flag set if the DIE has a byte_size attribute.  */
693     unsigned int has_byte_size : 1;
694
695     /* Flag set if any of the DIE's children are template arguments.  */
696     unsigned int has_template_arguments : 1;
697
698     /* Flag set if fixup_partial_die has been called on this die.  */
699     unsigned int fixup_called : 1;
700
701     /* The name of this DIE.  Normally the value of DW_AT_name, but
702        sometimes a default name for unnamed DIEs.  */
703     char *name;
704
705     /* The linkage name, if present.  */
706     const char *linkage_name;
707
708     /* The scope to prepend to our children.  This is generally
709        allocated on the comp_unit_obstack, so will disappear
710        when this compilation unit leaves the cache.  */
711     char *scope;
712
713     /* Some data associated with the partial DIE.  The tag determines
714        which field is live.  */
715     union
716     {
717       /* The location description associated with this DIE, if any.  */
718       struct dwarf_block *locdesc;
719       /* The offset of an import, for DW_TAG_imported_unit.  */
720       sect_offset offset;
721     } d;
722
723     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
724     CORE_ADDR lowpc;
725     CORE_ADDR highpc;
726
727     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
728        DW_AT_sibling, if any.  */
729     /* NOTE: This member isn't strictly necessary, read_partial_die could
730        return DW_AT_sibling values to its caller load_partial_dies.  */
731     gdb_byte *sibling;
732
733     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
734        DW_AT_specification (or DW_AT_abstract_origin or
735        DW_AT_extension).  */
736     sect_offset spec_offset;
737
738     /* Pointers to this DIE's parent, first child, and next sibling,
739        if any.  */
740     struct partial_die_info *die_parent, *die_child, *die_sibling;
741   };
742
743 /* This data structure holds the information of an abbrev.  */
744 struct abbrev_info
745   {
746     unsigned int number;        /* number identifying abbrev */
747     enum dwarf_tag tag;         /* dwarf tag */
748     unsigned short has_children;                /* boolean */
749     unsigned short num_attrs;   /* number of attributes */
750     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
751     struct abbrev_info *next;   /* next in chain */
752   };
753
754 struct attr_abbrev
755   {
756     ENUM_BITFIELD(dwarf_attribute) name : 16;
757     ENUM_BITFIELD(dwarf_form) form : 16;
758   };
759
760 /* Attributes have a name and a value.  */
761 struct attribute
762   {
763     ENUM_BITFIELD(dwarf_attribute) name : 16;
764     ENUM_BITFIELD(dwarf_form) form : 15;
765
766     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
767        field should be in u.str (existing only for DW_STRING) but it is kept
768        here for better struct attribute alignment.  */
769     unsigned int string_is_canonical : 1;
770
771     union
772       {
773         char *str;
774         struct dwarf_block *blk;
775         ULONGEST unsnd;
776         LONGEST snd;
777         CORE_ADDR addr;
778         struct signatured_type *signatured_type;
779       }
780     u;
781   };
782
783 /* This data structure holds a complete die structure.  */
784 struct die_info
785   {
786     /* DWARF-2 tag for this DIE.  */
787     ENUM_BITFIELD(dwarf_tag) tag : 16;
788
789     /* Number of attributes */
790     unsigned char num_attrs;
791
792     /* True if we're presently building the full type name for the
793        type derived from this DIE.  */
794     unsigned char building_fullname : 1;
795
796     /* Abbrev number */
797     unsigned int abbrev;
798
799     /* Offset in .debug_info or .debug_types section.  */
800     sect_offset offset;
801
802     /* The dies in a compilation unit form an n-ary tree.  PARENT
803        points to this die's parent; CHILD points to the first child of
804        this node; and all the children of a given node are chained
805        together via their SIBLING fields.  */
806     struct die_info *child;     /* Its first child, if any.  */
807     struct die_info *sibling;   /* Its next sibling, if any.  */
808     struct die_info *parent;    /* Its parent, if any.  */
809
810     /* An array of attributes, with NUM_ATTRS elements.  There may be
811        zero, but it's not common and zero-sized arrays are not
812        sufficiently portable C.  */
813     struct attribute attrs[1];
814   };
815
816 /* Get at parts of an attribute structure.  */
817
818 #define DW_STRING(attr)    ((attr)->u.str)
819 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
820 #define DW_UNSND(attr)     ((attr)->u.unsnd)
821 #define DW_BLOCK(attr)     ((attr)->u.blk)
822 #define DW_SND(attr)       ((attr)->u.snd)
823 #define DW_ADDR(attr)      ((attr)->u.addr)
824 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
825
826 /* Blocks are a bunch of untyped bytes.  */
827 struct dwarf_block
828   {
829     unsigned int size;
830
831     /* Valid only if SIZE is not zero.  */
832     gdb_byte *data;
833   };
834
835 #ifndef ATTR_ALLOC_CHUNK
836 #define ATTR_ALLOC_CHUNK 4
837 #endif
838
839 /* Allocate fields for structs, unions and enums in this size.  */
840 #ifndef DW_FIELD_ALLOC_CHUNK
841 #define DW_FIELD_ALLOC_CHUNK 4
842 #endif
843
844 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
845    but this would require a corresponding change in unpack_field_as_long
846    and friends.  */
847 static int bits_per_byte = 8;
848
849 /* The routines that read and process dies for a C struct or C++ class
850    pass lists of data member fields and lists of member function fields
851    in an instance of a field_info structure, as defined below.  */
852 struct field_info
853   {
854     /* List of data member and baseclasses fields.  */
855     struct nextfield
856       {
857         struct nextfield *next;
858         int accessibility;
859         int virtuality;
860         struct field field;
861       }
862      *fields, *baseclasses;
863
864     /* Number of fields (including baseclasses).  */
865     int nfields;
866
867     /* Number of baseclasses.  */
868     int nbaseclasses;
869
870     /* Set if the accesibility of one of the fields is not public.  */
871     int non_public_fields;
872
873     /* Member function fields array, entries are allocated in the order they
874        are encountered in the object file.  */
875     struct nextfnfield
876       {
877         struct nextfnfield *next;
878         struct fn_field fnfield;
879       }
880      *fnfields;
881
882     /* Member function fieldlist array, contains name of possibly overloaded
883        member function, number of overloaded member functions and a pointer
884        to the head of the member function field chain.  */
885     struct fnfieldlist
886       {
887         char *name;
888         int length;
889         struct nextfnfield *head;
890       }
891      *fnfieldlists;
892
893     /* Number of entries in the fnfieldlists array.  */
894     int nfnfields;
895
896     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
897        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
898     struct typedef_field_list
899       {
900         struct typedef_field field;
901         struct typedef_field_list *next;
902       }
903     *typedef_field_list;
904     unsigned typedef_field_list_count;
905   };
906
907 /* One item on the queue of compilation units to read in full symbols
908    for.  */
909 struct dwarf2_queue_item
910 {
911   struct dwarf2_per_cu_data *per_cu;
912   enum language pretend_language;
913   struct dwarf2_queue_item *next;
914 };
915
916 /* The current queue.  */
917 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
918
919 /* Loaded secondary compilation units are kept in memory until they
920    have not been referenced for the processing of this many
921    compilation units.  Set this to zero to disable caching.  Cache
922    sizes of up to at least twenty will improve startup time for
923    typical inter-CU-reference binaries, at an obvious memory cost.  */
924 static int dwarf2_max_cache_age = 5;
925 static void
926 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
927                            struct cmd_list_element *c, const char *value)
928 {
929   fprintf_filtered (file, _("The upper bound on the age of cached "
930                             "dwarf2 compilation units is %s.\n"),
931                     value);
932 }
933
934
935 /* Various complaints about symbol reading that don't abort the process.  */
936
937 static void
938 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
939 {
940   complaint (&symfile_complaints,
941              _("statement list doesn't fit in .debug_line section"));
942 }
943
944 static void
945 dwarf2_debug_line_missing_file_complaint (void)
946 {
947   complaint (&symfile_complaints,
948              _(".debug_line section has line data without a file"));
949 }
950
951 static void
952 dwarf2_debug_line_missing_end_sequence_complaint (void)
953 {
954   complaint (&symfile_complaints,
955              _(".debug_line section has line "
956                "program sequence without an end"));
957 }
958
959 static void
960 dwarf2_complex_location_expr_complaint (void)
961 {
962   complaint (&symfile_complaints, _("location expression too complex"));
963 }
964
965 static void
966 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
967                                               int arg3)
968 {
969   complaint (&symfile_complaints,
970              _("const value length mismatch for '%s', got %d, expected %d"),
971              arg1, arg2, arg3);
972 }
973
974 static void
975 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
976 {
977   complaint (&symfile_complaints,
978              _("debug info runs off end of %s section"
979                " [in module %s]"),
980              section->asection->name,
981              bfd_get_filename (section->asection->owner));
982 }
983
984 static void
985 dwarf2_macro_malformed_definition_complaint (const char *arg1)
986 {
987   complaint (&symfile_complaints,
988              _("macro debug info contains a "
989                "malformed macro definition:\n`%s'"),
990              arg1);
991 }
992
993 static void
994 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
995 {
996   complaint (&symfile_complaints,
997              _("invalid attribute class or form for '%s' in '%s'"),
998              arg1, arg2);
999 }
1000
1001 /* local function prototypes */
1002
1003 static void dwarf2_locate_sections (bfd *, asection *, void *);
1004
1005 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1006                                            struct objfile *);
1007
1008 static void dwarf2_find_base_address (struct die_info *die,
1009                                       struct dwarf2_cu *cu);
1010
1011 static void dwarf2_build_psymtabs_hard (struct objfile *);
1012
1013 static void scan_partial_symbols (struct partial_die_info *,
1014                                   CORE_ADDR *, CORE_ADDR *,
1015                                   int, struct dwarf2_cu *);
1016
1017 static void add_partial_symbol (struct partial_die_info *,
1018                                 struct dwarf2_cu *);
1019
1020 static void add_partial_namespace (struct partial_die_info *pdi,
1021                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1022                                    int need_pc, struct dwarf2_cu *cu);
1023
1024 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1025                                 CORE_ADDR *highpc, int need_pc,
1026                                 struct dwarf2_cu *cu);
1027
1028 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1029                                      struct dwarf2_cu *cu);
1030
1031 static void add_partial_subprogram (struct partial_die_info *pdi,
1032                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1033                                     int need_pc, struct dwarf2_cu *cu);
1034
1035 static void dwarf2_psymtab_to_symtab (struct partial_symtab *);
1036
1037 static void psymtab_to_symtab_1 (struct partial_symtab *);
1038
1039 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1040                                  struct dwarf2_section_info *);
1041
1042 static void dwarf2_free_abbrev_table (void *);
1043
1044 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1045
1046 static struct abbrev_info *peek_die_abbrev (gdb_byte *, unsigned int *,
1047                                             struct dwarf2_cu *);
1048
1049 static struct abbrev_info *dwarf2_lookup_abbrev (unsigned int,
1050                                                  struct dwarf2_cu *);
1051
1052 static struct partial_die_info *load_partial_dies
1053   (const struct die_reader_specs *, gdb_byte *, int);
1054
1055 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1056                                    struct partial_die_info *,
1057                                    struct abbrev_info *,
1058                                    unsigned int,
1059                                    gdb_byte *);
1060
1061 static struct partial_die_info *find_partial_die (sect_offset,
1062                                                   struct dwarf2_cu *);
1063
1064 static void fixup_partial_die (struct partial_die_info *,
1065                                struct dwarf2_cu *);
1066
1067 static gdb_byte *read_attribute (const struct die_reader_specs *,
1068                                  struct attribute *, struct attr_abbrev *,
1069                                  gdb_byte *);
1070
1071 static unsigned int read_1_byte (bfd *, gdb_byte *);
1072
1073 static int read_1_signed_byte (bfd *, gdb_byte *);
1074
1075 static unsigned int read_2_bytes (bfd *, gdb_byte *);
1076
1077 static unsigned int read_4_bytes (bfd *, gdb_byte *);
1078
1079 static ULONGEST read_8_bytes (bfd *, gdb_byte *);
1080
1081 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1082                                unsigned int *);
1083
1084 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1085
1086 static LONGEST read_checked_initial_length_and_offset
1087   (bfd *, gdb_byte *, const struct comp_unit_head *,
1088    unsigned int *, unsigned int *);
1089
1090 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1091                             unsigned int *);
1092
1093 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1094
1095 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1096
1097 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1098
1099 static char *read_indirect_string (bfd *, gdb_byte *,
1100                                    const struct comp_unit_head *,
1101                                    unsigned int *);
1102
1103 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1104
1105 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1106
1107 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1108                                               unsigned int *);
1109
1110 static char *read_str_index (const struct die_reader_specs *reader,
1111                              struct dwarf2_cu *cu, ULONGEST str_index);
1112
1113 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1114
1115 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1116                                       struct dwarf2_cu *);
1117
1118 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1119                                                 unsigned int,
1120                                                 struct dwarf2_cu *);
1121
1122 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1123                                struct dwarf2_cu *cu);
1124
1125 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1126
1127 static struct die_info *die_specification (struct die_info *die,
1128                                            struct dwarf2_cu **);
1129
1130 static void free_line_header (struct line_header *lh);
1131
1132 static void add_file_name (struct line_header *, char *, unsigned int,
1133                            unsigned int, unsigned int);
1134
1135 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1136                                                      struct dwarf2_cu *cu);
1137
1138 static void dwarf_decode_lines (struct line_header *, const char *,
1139                                 struct dwarf2_cu *, struct partial_symtab *,
1140                                 int);
1141
1142 static void dwarf2_start_subfile (char *, const char *, const char *);
1143
1144 static struct symbol *new_symbol (struct die_info *, struct type *,
1145                                   struct dwarf2_cu *);
1146
1147 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1148                                        struct dwarf2_cu *, struct symbol *);
1149
1150 static void dwarf2_const_value (struct attribute *, struct symbol *,
1151                                 struct dwarf2_cu *);
1152
1153 static void dwarf2_const_value_attr (struct attribute *attr,
1154                                      struct type *type,
1155                                      const char *name,
1156                                      struct obstack *obstack,
1157                                      struct dwarf2_cu *cu, LONGEST *value,
1158                                      gdb_byte **bytes,
1159                                      struct dwarf2_locexpr_baton **baton);
1160
1161 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1162
1163 static int need_gnat_info (struct dwarf2_cu *);
1164
1165 static struct type *die_descriptive_type (struct die_info *,
1166                                           struct dwarf2_cu *);
1167
1168 static void set_descriptive_type (struct type *, struct die_info *,
1169                                   struct dwarf2_cu *);
1170
1171 static struct type *die_containing_type (struct die_info *,
1172                                          struct dwarf2_cu *);
1173
1174 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1175                                      struct dwarf2_cu *);
1176
1177 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1178
1179 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1180
1181 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1182
1183 static char *typename_concat (struct obstack *obs, const char *prefix,
1184                               const char *suffix, int physname,
1185                               struct dwarf2_cu *cu);
1186
1187 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1188
1189 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1190
1191 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1192
1193 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1194
1195 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1196
1197 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1198                                struct dwarf2_cu *, struct partial_symtab *);
1199
1200 static int dwarf2_get_pc_bounds (struct die_info *,
1201                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1202                                  struct partial_symtab *);
1203
1204 static void get_scope_pc_bounds (struct die_info *,
1205                                  CORE_ADDR *, CORE_ADDR *,
1206                                  struct dwarf2_cu *);
1207
1208 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1209                                         CORE_ADDR, struct dwarf2_cu *);
1210
1211 static void dwarf2_add_field (struct field_info *, struct die_info *,
1212                               struct dwarf2_cu *);
1213
1214 static void dwarf2_attach_fields_to_type (struct field_info *,
1215                                           struct type *, struct dwarf2_cu *);
1216
1217 static void dwarf2_add_member_fn (struct field_info *,
1218                                   struct die_info *, struct type *,
1219                                   struct dwarf2_cu *);
1220
1221 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1222                                              struct type *,
1223                                              struct dwarf2_cu *);
1224
1225 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1226
1227 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1228
1229 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1230
1231 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1232
1233 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1234
1235 static struct type *read_module_type (struct die_info *die,
1236                                       struct dwarf2_cu *cu);
1237
1238 static const char *namespace_name (struct die_info *die,
1239                                    int *is_anonymous, struct dwarf2_cu *);
1240
1241 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1242
1243 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1244
1245 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1246                                                        struct dwarf2_cu *);
1247
1248 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1249                                                gdb_byte *info_ptr,
1250                                                gdb_byte **new_info_ptr,
1251                                                struct die_info *parent);
1252
1253 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1254                                                gdb_byte *info_ptr,
1255                                                gdb_byte **new_info_ptr,
1256                                                struct die_info *parent);
1257
1258 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1259                                   struct die_info **, gdb_byte *, int *, int);
1260
1261 static gdb_byte *read_full_die (const struct die_reader_specs *,
1262                                 struct die_info **, gdb_byte *, int *);
1263
1264 static void process_die (struct die_info *, struct dwarf2_cu *);
1265
1266 static char *dwarf2_canonicalize_name (char *, struct dwarf2_cu *,
1267                                        struct obstack *);
1268
1269 static char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1270
1271 static const char *dwarf2_full_name (char *name,
1272                                      struct die_info *die,
1273                                      struct dwarf2_cu *cu);
1274
1275 static struct die_info *dwarf2_extension (struct die_info *die,
1276                                           struct dwarf2_cu **);
1277
1278 static const char *dwarf_tag_name (unsigned int);
1279
1280 static const char *dwarf_attr_name (unsigned int);
1281
1282 static const char *dwarf_form_name (unsigned int);
1283
1284 static char *dwarf_bool_name (unsigned int);
1285
1286 static const char *dwarf_type_encoding_name (unsigned int);
1287
1288 static struct die_info *sibling_die (struct die_info *);
1289
1290 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1291
1292 static void dump_die_for_error (struct die_info *);
1293
1294 static void dump_die_1 (struct ui_file *, int level, int max_level,
1295                         struct die_info *);
1296
1297 /*static*/ void dump_die (struct die_info *, int max_level);
1298
1299 static void store_in_ref_table (struct die_info *,
1300                                 struct dwarf2_cu *);
1301
1302 static int is_ref_attr (struct attribute *);
1303
1304 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1305
1306 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1307
1308 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1309                                                struct attribute *,
1310                                                struct dwarf2_cu **);
1311
1312 static struct die_info *follow_die_ref (struct die_info *,
1313                                         struct attribute *,
1314                                         struct dwarf2_cu **);
1315
1316 static struct die_info *follow_die_sig (struct die_info *,
1317                                         struct attribute *,
1318                                         struct dwarf2_cu **);
1319
1320 static struct signatured_type *lookup_signatured_type_at_offset
1321     (struct objfile *objfile,
1322      struct dwarf2_section_info *section, sect_offset offset);
1323
1324 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1325
1326 static void read_signatured_type (struct signatured_type *);
1327
1328 /* memory allocation interface */
1329
1330 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1331
1332 static struct abbrev_info *dwarf_alloc_abbrev (struct dwarf2_cu *);
1333
1334 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1335
1336 static void dwarf_decode_macros (struct line_header *, unsigned int,
1337                                  char *, bfd *, struct dwarf2_cu *,
1338                                  struct dwarf2_section_info *,
1339                                  int, const char *);
1340
1341 static int attr_form_is_block (struct attribute *);
1342
1343 static int attr_form_is_section_offset (struct attribute *);
1344
1345 static int attr_form_is_constant (struct attribute *);
1346
1347 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1348                                    struct dwarf2_loclist_baton *baton,
1349                                    struct attribute *attr);
1350
1351 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1352                                          struct symbol *sym,
1353                                          struct dwarf2_cu *cu);
1354
1355 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1356                                gdb_byte *info_ptr,
1357                                struct abbrev_info *abbrev);
1358
1359 static void free_stack_comp_unit (void *);
1360
1361 static hashval_t partial_die_hash (const void *item);
1362
1363 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1364
1365 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1366   (sect_offset offset, struct objfile *objfile);
1367
1368 static void init_one_comp_unit (struct dwarf2_cu *cu,
1369                                 struct dwarf2_per_cu_data *per_cu);
1370
1371 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1372                                    struct die_info *comp_unit_die,
1373                                    enum language pretend_language);
1374
1375 static void free_heap_comp_unit (void *);
1376
1377 static void free_cached_comp_units (void *);
1378
1379 static void age_cached_comp_units (void);
1380
1381 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1382
1383 static struct type *set_die_type (struct die_info *, struct type *,
1384                                   struct dwarf2_cu *);
1385
1386 static void create_all_comp_units (struct objfile *);
1387
1388 static int create_all_type_units (struct objfile *);
1389
1390 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1391                                  enum language);
1392
1393 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1394                                     enum language);
1395
1396 static void dwarf2_add_dependence (struct dwarf2_cu *,
1397                                    struct dwarf2_per_cu_data *);
1398
1399 static void dwarf2_mark (struct dwarf2_cu *);
1400
1401 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1402
1403 static struct type *get_die_type_at_offset (sect_offset,
1404                                             struct dwarf2_per_cu_data *per_cu);
1405
1406 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1407
1408 static void dwarf2_release_queue (void *dummy);
1409
1410 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1411                              enum language pretend_language);
1412
1413 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1414                                   struct dwarf2_per_cu_data *per_cu,
1415                                   enum language pretend_language);
1416
1417 static void process_queue (void);
1418
1419 static void find_file_and_directory (struct die_info *die,
1420                                      struct dwarf2_cu *cu,
1421                                      char **name, char **comp_dir);
1422
1423 static char *file_full_name (int file, struct line_header *lh,
1424                              const char *comp_dir);
1425
1426 static gdb_byte *read_and_check_comp_unit_head
1427   (struct comp_unit_head *header,
1428    struct dwarf2_section_info *section, gdb_byte *info_ptr,
1429    int is_debug_types_section);
1430
1431 static void init_cutu_and_read_dies
1432   (struct dwarf2_per_cu_data *this_cu, int use_existing_cu, int keep,
1433    die_reader_func_ftype *die_reader_func, void *data);
1434
1435 static void init_cutu_and_read_dies_simple
1436   (struct dwarf2_per_cu_data *this_cu,
1437    die_reader_func_ftype *die_reader_func, void *data);
1438
1439 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1440
1441 static void process_psymtab_comp_unit (struct dwarf2_per_cu_data *, int);
1442
1443 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1444
1445 static struct dwo_unit *lookup_dwo_comp_unit
1446   (struct dwarf2_per_cu_data *, char *, const char *, ULONGEST);
1447
1448 static struct dwo_unit *lookup_dwo_type_unit
1449   (struct signatured_type *, char *, const char *);
1450
1451 static void free_dwo_file_cleanup (void *);
1452
1453 static void munmap_section_buffer (struct dwarf2_section_info *);
1454
1455 static void process_cu_includes (void);
1456
1457 #if WORDS_BIGENDIAN
1458
1459 /* Convert VALUE between big- and little-endian.  */
1460 static offset_type
1461 byte_swap (offset_type value)
1462 {
1463   offset_type result;
1464
1465   result = (value & 0xff) << 24;
1466   result |= (value & 0xff00) << 8;
1467   result |= (value & 0xff0000) >> 8;
1468   result |= (value & 0xff000000) >> 24;
1469   return result;
1470 }
1471
1472 #define MAYBE_SWAP(V)  byte_swap (V)
1473
1474 #else
1475 #define MAYBE_SWAP(V) (V)
1476 #endif /* WORDS_BIGENDIAN */
1477
1478 /* The suffix for an index file.  */
1479 #define INDEX_SUFFIX ".gdb-index"
1480
1481 static const char *dwarf2_physname (char *name, struct die_info *die,
1482                                     struct dwarf2_cu *cu);
1483
1484 /* Try to locate the sections we need for DWARF 2 debugging
1485    information and return true if we have enough to do something.
1486    NAMES points to the dwarf2 section names, or is NULL if the standard
1487    ELF names are used.  */
1488
1489 int
1490 dwarf2_has_info (struct objfile *objfile,
1491                  const struct dwarf2_debug_sections *names)
1492 {
1493   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1494   if (!dwarf2_per_objfile)
1495     {
1496       /* Initialize per-objfile state.  */
1497       struct dwarf2_per_objfile *data
1498         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1499
1500       memset (data, 0, sizeof (*data));
1501       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1502       dwarf2_per_objfile = data;
1503
1504       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1505                              (void *) names);
1506       dwarf2_per_objfile->objfile = objfile;
1507     }
1508   return (dwarf2_per_objfile->info.asection != NULL
1509           && dwarf2_per_objfile->abbrev.asection != NULL);
1510 }
1511
1512 /* When loading sections, we look either for uncompressed section or for
1513    compressed section names.  */
1514
1515 static int
1516 section_is_p (const char *section_name,
1517               const struct dwarf2_section_names *names)
1518 {
1519   if (names->normal != NULL
1520       && strcmp (section_name, names->normal) == 0)
1521     return 1;
1522   if (names->compressed != NULL
1523       && strcmp (section_name, names->compressed) == 0)
1524     return 1;
1525   return 0;
1526 }
1527
1528 /* This function is mapped across the sections and remembers the
1529    offset and size of each of the debugging sections we are interested
1530    in.  */
1531
1532 static void
1533 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1534 {
1535   const struct dwarf2_debug_sections *names;
1536
1537   if (vnames == NULL)
1538     names = &dwarf2_elf_names;
1539   else
1540     names = (const struct dwarf2_debug_sections *) vnames;
1541
1542   if (section_is_p (sectp->name, &names->info))
1543     {
1544       dwarf2_per_objfile->info.asection = sectp;
1545       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1546     }
1547   else if (section_is_p (sectp->name, &names->abbrev))
1548     {
1549       dwarf2_per_objfile->abbrev.asection = sectp;
1550       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1551     }
1552   else if (section_is_p (sectp->name, &names->line))
1553     {
1554       dwarf2_per_objfile->line.asection = sectp;
1555       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1556     }
1557   else if (section_is_p (sectp->name, &names->loc))
1558     {
1559       dwarf2_per_objfile->loc.asection = sectp;
1560       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1561     }
1562   else if (section_is_p (sectp->name, &names->macinfo))
1563     {
1564       dwarf2_per_objfile->macinfo.asection = sectp;
1565       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1566     }
1567   else if (section_is_p (sectp->name, &names->macro))
1568     {
1569       dwarf2_per_objfile->macro.asection = sectp;
1570       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1571     }
1572   else if (section_is_p (sectp->name, &names->str))
1573     {
1574       dwarf2_per_objfile->str.asection = sectp;
1575       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1576     }
1577   else if (section_is_p (sectp->name, &names->addr))
1578     {
1579       dwarf2_per_objfile->addr.asection = sectp;
1580       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1581     }
1582   else if (section_is_p (sectp->name, &names->frame))
1583     {
1584       dwarf2_per_objfile->frame.asection = sectp;
1585       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1586     }
1587   else if (section_is_p (sectp->name, &names->eh_frame))
1588     {
1589       flagword aflag = bfd_get_section_flags (abfd, sectp);
1590
1591       if (aflag & SEC_HAS_CONTENTS)
1592         {
1593           dwarf2_per_objfile->eh_frame.asection = sectp;
1594           dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1595         }
1596     }
1597   else if (section_is_p (sectp->name, &names->ranges))
1598     {
1599       dwarf2_per_objfile->ranges.asection = sectp;
1600       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1601     }
1602   else if (section_is_p (sectp->name, &names->types))
1603     {
1604       struct dwarf2_section_info type_section;
1605
1606       memset (&type_section, 0, sizeof (type_section));
1607       type_section.asection = sectp;
1608       type_section.size = bfd_get_section_size (sectp);
1609
1610       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1611                      &type_section);
1612     }
1613   else if (section_is_p (sectp->name, &names->gdb_index))
1614     {
1615       dwarf2_per_objfile->gdb_index.asection = sectp;
1616       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1617     }
1618
1619   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1620       && bfd_section_vma (abfd, sectp) == 0)
1621     dwarf2_per_objfile->has_section_at_zero = 1;
1622 }
1623
1624 /* Decompress a section that was compressed using zlib.  Store the
1625    decompressed buffer, and its size, in OUTBUF and OUTSIZE.  */
1626
1627 static void
1628 zlib_decompress_section (struct objfile *objfile, asection *sectp,
1629                          gdb_byte **outbuf, bfd_size_type *outsize)
1630 {
1631   bfd *abfd = sectp->owner;
1632 #ifndef HAVE_ZLIB_H
1633   error (_("Support for zlib-compressed DWARF data (from '%s') "
1634            "is disabled in this copy of GDB"),
1635          bfd_get_filename (abfd));
1636 #else
1637   bfd_size_type compressed_size = bfd_get_section_size (sectp);
1638   gdb_byte *compressed_buffer = xmalloc (compressed_size);
1639   struct cleanup *cleanup = make_cleanup (xfree, compressed_buffer);
1640   bfd_size_type uncompressed_size;
1641   gdb_byte *uncompressed_buffer;
1642   z_stream strm;
1643   int rc;
1644   int header_size = 12;
1645
1646   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1647       || bfd_bread (compressed_buffer,
1648                     compressed_size, abfd) != compressed_size)
1649     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1650            bfd_get_filename (abfd));
1651
1652   /* Read the zlib header.  In this case, it should be "ZLIB" followed
1653      by the uncompressed section size, 8 bytes in big-endian order.  */
1654   if (compressed_size < header_size
1655       || strncmp (compressed_buffer, "ZLIB", 4) != 0)
1656     error (_("Dwarf Error: Corrupt DWARF ZLIB header from '%s'"),
1657            bfd_get_filename (abfd));
1658   uncompressed_size = compressed_buffer[4]; uncompressed_size <<= 8;
1659   uncompressed_size += compressed_buffer[5]; uncompressed_size <<= 8;
1660   uncompressed_size += compressed_buffer[6]; uncompressed_size <<= 8;
1661   uncompressed_size += compressed_buffer[7]; uncompressed_size <<= 8;
1662   uncompressed_size += compressed_buffer[8]; uncompressed_size <<= 8;
1663   uncompressed_size += compressed_buffer[9]; uncompressed_size <<= 8;
1664   uncompressed_size += compressed_buffer[10]; uncompressed_size <<= 8;
1665   uncompressed_size += compressed_buffer[11];
1666
1667   /* It is possible the section consists of several compressed
1668      buffers concatenated together, so we uncompress in a loop.  */
1669   strm.zalloc = NULL;
1670   strm.zfree = NULL;
1671   strm.opaque = NULL;
1672   strm.avail_in = compressed_size - header_size;
1673   strm.next_in = (Bytef*) compressed_buffer + header_size;
1674   strm.avail_out = uncompressed_size;
1675   uncompressed_buffer = obstack_alloc (&objfile->objfile_obstack,
1676                                        uncompressed_size);
1677   rc = inflateInit (&strm);
1678   while (strm.avail_in > 0)
1679     {
1680       if (rc != Z_OK)
1681         error (_("Dwarf Error: setting up DWARF uncompression in '%s': %d"),
1682                bfd_get_filename (abfd), rc);
1683       strm.next_out = ((Bytef*) uncompressed_buffer
1684                        + (uncompressed_size - strm.avail_out));
1685       rc = inflate (&strm, Z_FINISH);
1686       if (rc != Z_STREAM_END)
1687         error (_("Dwarf Error: zlib error uncompressing from '%s': %d"),
1688                bfd_get_filename (abfd), rc);
1689       rc = inflateReset (&strm);
1690     }
1691   rc = inflateEnd (&strm);
1692   if (rc != Z_OK
1693       || strm.avail_out != 0)
1694     error (_("Dwarf Error: concluding DWARF uncompression in '%s': %d"),
1695            bfd_get_filename (abfd), rc);
1696
1697   do_cleanups (cleanup);
1698   *outbuf = uncompressed_buffer;
1699   *outsize = uncompressed_size;
1700 #endif
1701 }
1702
1703 /* A helper function that decides whether a section is empty,
1704    or not present.  */
1705
1706 static int
1707 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1708 {
1709   return info->asection == NULL || info->size == 0;
1710 }
1711
1712 /* Read the contents of the section INFO.
1713    OBJFILE is the main object file, but not necessarily the file where
1714    the section comes from.  E.g., for DWO files INFO->asection->owner
1715    is the bfd of the DWO file.
1716    If the section is compressed, uncompress it before returning.  */
1717
1718 static void
1719 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1720 {
1721   asection *sectp = info->asection;
1722   bfd *abfd;
1723   gdb_byte *buf, *retbuf;
1724   unsigned char header[4];
1725
1726   if (info->readin)
1727     return;
1728   info->buffer = NULL;
1729   info->map_addr = NULL;
1730   info->readin = 1;
1731
1732   if (dwarf2_section_empty_p (info))
1733     return;
1734
1735   /* Note that ABFD may not be from OBJFILE, e.g. a DWO section.  */
1736   abfd = sectp->owner;
1737
1738   /* Check if the file has a 4-byte header indicating compression.  */
1739   if (info->size > sizeof (header)
1740       && bfd_seek (abfd, sectp->filepos, SEEK_SET) == 0
1741       && bfd_bread (header, sizeof (header), abfd) == sizeof (header))
1742     {
1743       /* Upon decompression, update the buffer and its size.  */
1744       if (strncmp (header, "ZLIB", sizeof (header)) == 0)
1745         {
1746           zlib_decompress_section (objfile, sectp, &info->buffer,
1747                                    &info->size);
1748           return;
1749         }
1750     }
1751
1752 #ifdef HAVE_MMAP
1753   if (pagesize == 0)
1754     pagesize = getpagesize ();
1755
1756   /* Only try to mmap sections which are large enough: we don't want to
1757      waste space due to fragmentation.  Also, only try mmap for sections
1758      without relocations.  */
1759
1760   if (info->size > 4 * pagesize && (sectp->flags & SEC_RELOC) == 0)
1761     {
1762       info->buffer = bfd_mmap (abfd, 0, info->size, PROT_READ,
1763                          MAP_PRIVATE, sectp->filepos,
1764                          &info->map_addr, &info->map_len);
1765
1766       if ((caddr_t)info->buffer != MAP_FAILED)
1767         {
1768 #if HAVE_POSIX_MADVISE
1769           posix_madvise (info->map_addr, info->map_len, POSIX_MADV_WILLNEED);
1770 #endif
1771           return;
1772         }
1773     }
1774 #endif
1775
1776   /* If we get here, we are a normal, not-compressed section.  */
1777   info->buffer = buf
1778     = obstack_alloc (&objfile->objfile_obstack, info->size);
1779
1780   /* When debugging .o files, we may need to apply relocations; see
1781      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1782      We never compress sections in .o files, so we only need to
1783      try this when the section is not compressed.  */
1784   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1785   if (retbuf != NULL)
1786     {
1787       info->buffer = retbuf;
1788       return;
1789     }
1790
1791   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1792       || bfd_bread (buf, info->size, abfd) != info->size)
1793     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1794            bfd_get_filename (abfd));
1795 }
1796
1797 /* A helper function that returns the size of a section in a safe way.
1798    If you are positive that the section has been read before using the
1799    size, then it is safe to refer to the dwarf2_section_info object's
1800    "size" field directly.  In other cases, you must call this
1801    function, because for compressed sections the size field is not set
1802    correctly until the section has been read.  */
1803
1804 static bfd_size_type
1805 dwarf2_section_size (struct objfile *objfile,
1806                      struct dwarf2_section_info *info)
1807 {
1808   if (!info->readin)
1809     dwarf2_read_section (objfile, info);
1810   return info->size;
1811 }
1812
1813 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1814    SECTION_NAME.  */
1815
1816 void
1817 dwarf2_get_section_info (struct objfile *objfile,
1818                          enum dwarf2_section_enum sect,
1819                          asection **sectp, gdb_byte **bufp,
1820                          bfd_size_type *sizep)
1821 {
1822   struct dwarf2_per_objfile *data
1823     = objfile_data (objfile, dwarf2_objfile_data_key);
1824   struct dwarf2_section_info *info;
1825
1826   /* We may see an objfile without any DWARF, in which case we just
1827      return nothing.  */
1828   if (data == NULL)
1829     {
1830       *sectp = NULL;
1831       *bufp = NULL;
1832       *sizep = 0;
1833       return;
1834     }
1835   switch (sect)
1836     {
1837     case DWARF2_DEBUG_FRAME:
1838       info = &data->frame;
1839       break;
1840     case DWARF2_EH_FRAME:
1841       info = &data->eh_frame;
1842       break;
1843     default:
1844       gdb_assert_not_reached ("unexpected section");
1845     }
1846
1847   dwarf2_read_section (objfile, info);
1848
1849   *sectp = info->asection;
1850   *bufp = info->buffer;
1851   *sizep = info->size;
1852 }
1853
1854 \f
1855 /* DWARF quick_symbols_functions support.  */
1856
1857 /* TUs can share .debug_line entries, and there can be a lot more TUs than
1858    unique line tables, so we maintain a separate table of all .debug_line
1859    derived entries to support the sharing.
1860    All the quick functions need is the list of file names.  We discard the
1861    line_header when we're done and don't need to record it here.  */
1862 struct quick_file_names
1863 {
1864   /* The offset in .debug_line of the line table.  We hash on this.  */
1865   unsigned int offset;
1866
1867   /* The number of entries in file_names, real_names.  */
1868   unsigned int num_file_names;
1869
1870   /* The file names from the line table, after being run through
1871      file_full_name.  */
1872   const char **file_names;
1873
1874   /* The file names from the line table after being run through
1875      gdb_realpath.  These are computed lazily.  */
1876   const char **real_names;
1877 };
1878
1879 /* When using the index (and thus not using psymtabs), each CU has an
1880    object of this type.  This is used to hold information needed by
1881    the various "quick" methods.  */
1882 struct dwarf2_per_cu_quick_data
1883 {
1884   /* The file table.  This can be NULL if there was no file table
1885      or it's currently not read in.
1886      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
1887   struct quick_file_names *file_names;
1888
1889   /* The corresponding symbol table.  This is NULL if symbols for this
1890      CU have not yet been read.  */
1891   struct symtab *symtab;
1892
1893   /* A temporary mark bit used when iterating over all CUs in
1894      expand_symtabs_matching.  */
1895   unsigned int mark : 1;
1896
1897   /* True if we've tried to read the file table and found there isn't one.
1898      There will be no point in trying to read it again next time.  */
1899   unsigned int no_file_data : 1;
1900 };
1901
1902 /* Hash function for a quick_file_names.  */
1903
1904 static hashval_t
1905 hash_file_name_entry (const void *e)
1906 {
1907   const struct quick_file_names *file_data = e;
1908
1909   return file_data->offset;
1910 }
1911
1912 /* Equality function for a quick_file_names.  */
1913
1914 static int
1915 eq_file_name_entry (const void *a, const void *b)
1916 {
1917   const struct quick_file_names *ea = a;
1918   const struct quick_file_names *eb = b;
1919
1920   return ea->offset == eb->offset;
1921 }
1922
1923 /* Delete function for a quick_file_names.  */
1924
1925 static void
1926 delete_file_name_entry (void *e)
1927 {
1928   struct quick_file_names *file_data = e;
1929   int i;
1930
1931   for (i = 0; i < file_data->num_file_names; ++i)
1932     {
1933       xfree ((void*) file_data->file_names[i]);
1934       if (file_data->real_names)
1935         xfree ((void*) file_data->real_names[i]);
1936     }
1937
1938   /* The space for the struct itself lives on objfile_obstack,
1939      so we don't free it here.  */
1940 }
1941
1942 /* Create a quick_file_names hash table.  */
1943
1944 static htab_t
1945 create_quick_file_names_table (unsigned int nr_initial_entries)
1946 {
1947   return htab_create_alloc (nr_initial_entries,
1948                             hash_file_name_entry, eq_file_name_entry,
1949                             delete_file_name_entry, xcalloc, xfree);
1950 }
1951
1952 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
1953    have to be created afterwards.  You should call age_cached_comp_units after
1954    processing PER_CU->CU.  dw2_setup must have been already called.  */
1955
1956 static void
1957 load_cu (struct dwarf2_per_cu_data *per_cu)
1958 {
1959   if (per_cu->is_debug_types)
1960     load_full_type_unit (per_cu);
1961   else
1962     load_full_comp_unit (per_cu, language_minimal);
1963
1964   gdb_assert (per_cu->cu != NULL);
1965
1966   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
1967 }
1968
1969 /* Read in the symbols for PER_CU.  */
1970
1971 static void
1972 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
1973 {
1974   struct cleanup *back_to;
1975
1976   back_to = make_cleanup (dwarf2_release_queue, NULL);
1977
1978   if (dwarf2_per_objfile->using_index
1979       ? per_cu->v.quick->symtab == NULL
1980       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
1981     {
1982       queue_comp_unit (per_cu, language_minimal);
1983       load_cu (per_cu);
1984     }
1985
1986   process_queue ();
1987
1988   /* Age the cache, releasing compilation units that have not
1989      been used recently.  */
1990   age_cached_comp_units ();
1991
1992   do_cleanups (back_to);
1993 }
1994
1995 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
1996    the objfile from which this CU came.  Returns the resulting symbol
1997    table.  */
1998
1999 static struct symtab *
2000 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2001 {
2002   gdb_assert (dwarf2_per_objfile->using_index);
2003   if (!per_cu->v.quick->symtab)
2004     {
2005       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2006       increment_reading_symtab ();
2007       dw2_do_instantiate_symtab (per_cu);
2008       process_cu_includes ();
2009       do_cleanups (back_to);
2010     }
2011   return per_cu->v.quick->symtab;
2012 }
2013
2014 /* Return the CU given its index.  */
2015
2016 static struct dwarf2_per_cu_data *
2017 dw2_get_cu (int index)
2018 {
2019   if (index >= dwarf2_per_objfile->n_comp_units)
2020     {
2021       index -= dwarf2_per_objfile->n_comp_units;
2022       return dwarf2_per_objfile->all_type_units[index];
2023     }
2024   return dwarf2_per_objfile->all_comp_units[index];
2025 }
2026
2027 /* A helper function that knows how to read a 64-bit value in a way
2028    that doesn't make gdb die.  Returns 1 if the conversion went ok, 0
2029    otherwise.  */
2030
2031 static int
2032 extract_cu_value (const char *bytes, ULONGEST *result)
2033 {
2034   if (sizeof (ULONGEST) < 8)
2035     {
2036       int i;
2037
2038       /* Ignore the upper 4 bytes if they are all zero.  */
2039       for (i = 0; i < 4; ++i)
2040         if (bytes[i + 4] != 0)
2041           return 0;
2042
2043       *result = extract_unsigned_integer (bytes, 4, BFD_ENDIAN_LITTLE);
2044     }
2045   else
2046     *result = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2047   return 1;
2048 }
2049
2050 /* Read the CU list from the mapped index, and use it to create all
2051    the CU objects for this objfile.  Return 0 if something went wrong,
2052    1 if everything went ok.  */
2053
2054 static int
2055 create_cus_from_index (struct objfile *objfile, const gdb_byte *cu_list,
2056                        offset_type cu_list_elements)
2057 {
2058   offset_type i;
2059
2060   dwarf2_per_objfile->n_comp_units = cu_list_elements / 2;
2061   dwarf2_per_objfile->all_comp_units
2062     = obstack_alloc (&objfile->objfile_obstack,
2063                      dwarf2_per_objfile->n_comp_units
2064                      * sizeof (struct dwarf2_per_cu_data *));
2065
2066   for (i = 0; i < cu_list_elements; i += 2)
2067     {
2068       struct dwarf2_per_cu_data *the_cu;
2069       ULONGEST offset, length;
2070
2071       if (!extract_cu_value (cu_list, &offset)
2072           || !extract_cu_value (cu_list + 8, &length))
2073         return 0;
2074       cu_list += 2 * 8;
2075
2076       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2077                                struct dwarf2_per_cu_data);
2078       the_cu->offset.sect_off = offset;
2079       the_cu->length = length;
2080       the_cu->objfile = objfile;
2081       the_cu->info_or_types_section = &dwarf2_per_objfile->info;
2082       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2083                                         struct dwarf2_per_cu_quick_data);
2084       dwarf2_per_objfile->all_comp_units[i / 2] = the_cu;
2085     }
2086
2087   return 1;
2088 }
2089
2090 /* Create the signatured type hash table from the index.  */
2091
2092 static int
2093 create_signatured_type_table_from_index (struct objfile *objfile,
2094                                          struct dwarf2_section_info *section,
2095                                          const gdb_byte *bytes,
2096                                          offset_type elements)
2097 {
2098   offset_type i;
2099   htab_t sig_types_hash;
2100
2101   dwarf2_per_objfile->n_type_units = elements / 3;
2102   dwarf2_per_objfile->all_type_units
2103     = obstack_alloc (&objfile->objfile_obstack,
2104                      dwarf2_per_objfile->n_type_units
2105                      * sizeof (struct dwarf2_per_cu_data *));
2106
2107   sig_types_hash = allocate_signatured_type_table (objfile);
2108
2109   for (i = 0; i < elements; i += 3)
2110     {
2111       struct signatured_type *sig_type;
2112       ULONGEST offset, type_offset_in_tu, signature;
2113       void **slot;
2114
2115       if (!extract_cu_value (bytes, &offset)
2116           || !extract_cu_value (bytes + 8, &type_offset_in_tu))
2117         return 0;
2118       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2119       bytes += 3 * 8;
2120
2121       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2122                                  struct signatured_type);
2123       sig_type->signature = signature;
2124       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2125       sig_type->per_cu.is_debug_types = 1;
2126       sig_type->per_cu.info_or_types_section = section;
2127       sig_type->per_cu.offset.sect_off = offset;
2128       sig_type->per_cu.objfile = objfile;
2129       sig_type->per_cu.v.quick
2130         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2131                           struct dwarf2_per_cu_quick_data);
2132
2133       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2134       *slot = sig_type;
2135
2136       dwarf2_per_objfile->all_type_units[i / 3] = &sig_type->per_cu;
2137     }
2138
2139   dwarf2_per_objfile->signatured_types = sig_types_hash;
2140
2141   return 1;
2142 }
2143
2144 /* Read the address map data from the mapped index, and use it to
2145    populate the objfile's psymtabs_addrmap.  */
2146
2147 static void
2148 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2149 {
2150   const gdb_byte *iter, *end;
2151   struct obstack temp_obstack;
2152   struct addrmap *mutable_map;
2153   struct cleanup *cleanup;
2154   CORE_ADDR baseaddr;
2155
2156   obstack_init (&temp_obstack);
2157   cleanup = make_cleanup_obstack_free (&temp_obstack);
2158   mutable_map = addrmap_create_mutable (&temp_obstack);
2159
2160   iter = index->address_table;
2161   end = iter + index->address_table_size;
2162
2163   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2164
2165   while (iter < end)
2166     {
2167       ULONGEST hi, lo, cu_index;
2168       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2169       iter += 8;
2170       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2171       iter += 8;
2172       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2173       iter += 4;
2174       
2175       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2176                          dw2_get_cu (cu_index));
2177     }
2178
2179   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2180                                                     &objfile->objfile_obstack);
2181   do_cleanups (cleanup);
2182 }
2183
2184 /* The hash function for strings in the mapped index.  This is the same as
2185    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2186    implementation.  This is necessary because the hash function is tied to the
2187    format of the mapped index file.  The hash values do not have to match with
2188    SYMBOL_HASH_NEXT.
2189    
2190    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2191
2192 static hashval_t
2193 mapped_index_string_hash (int index_version, const void *p)
2194 {
2195   const unsigned char *str = (const unsigned char *) p;
2196   hashval_t r = 0;
2197   unsigned char c;
2198
2199   while ((c = *str++) != 0)
2200     {
2201       if (index_version >= 5)
2202         c = tolower (c);
2203       r = r * 67 + c - 113;
2204     }
2205
2206   return r;
2207 }
2208
2209 /* Find a slot in the mapped index INDEX for the object named NAME.
2210    If NAME is found, set *VEC_OUT to point to the CU vector in the
2211    constant pool and return 1.  If NAME cannot be found, return 0.  */
2212
2213 static int
2214 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2215                           offset_type **vec_out)
2216 {
2217   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2218   offset_type hash;
2219   offset_type slot, step;
2220   int (*cmp) (const char *, const char *);
2221
2222   if (current_language->la_language == language_cplus
2223       || current_language->la_language == language_java
2224       || current_language->la_language == language_fortran)
2225     {
2226       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2227          not contain any.  */
2228       const char *paren = strchr (name, '(');
2229
2230       if (paren)
2231         {
2232           char *dup;
2233
2234           dup = xmalloc (paren - name + 1);
2235           memcpy (dup, name, paren - name);
2236           dup[paren - name] = 0;
2237
2238           make_cleanup (xfree, dup);
2239           name = dup;
2240         }
2241     }
2242
2243   /* Index version 4 did not support case insensitive searches.  But the
2244      indices for case insensitive languages are built in lowercase, therefore
2245      simulate our NAME being searched is also lowercased.  */
2246   hash = mapped_index_string_hash ((index->version == 4
2247                                     && case_sensitivity == case_sensitive_off
2248                                     ? 5 : index->version),
2249                                    name);
2250
2251   slot = hash & (index->symbol_table_slots - 1);
2252   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2253   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2254
2255   for (;;)
2256     {
2257       /* Convert a slot number to an offset into the table.  */
2258       offset_type i = 2 * slot;
2259       const char *str;
2260       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2261         {
2262           do_cleanups (back_to);
2263           return 0;
2264         }
2265
2266       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2267       if (!cmp (name, str))
2268         {
2269           *vec_out = (offset_type *) (index->constant_pool
2270                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2271           do_cleanups (back_to);
2272           return 1;
2273         }
2274
2275       slot = (slot + step) & (index->symbol_table_slots - 1);
2276     }
2277 }
2278
2279 /* Read the index file.  If everything went ok, initialize the "quick"
2280    elements of all the CUs and return 1.  Otherwise, return 0.  */
2281
2282 static int
2283 dwarf2_read_index (struct objfile *objfile)
2284 {
2285   char *addr;
2286   struct mapped_index *map;
2287   offset_type *metadata;
2288   const gdb_byte *cu_list;
2289   const gdb_byte *types_list = NULL;
2290   offset_type version, cu_list_elements;
2291   offset_type types_list_elements = 0;
2292   int i;
2293
2294   if (dwarf2_section_empty_p (&dwarf2_per_objfile->gdb_index))
2295     return 0;
2296
2297   /* Older elfutils strip versions could keep the section in the main
2298      executable while splitting it for the separate debug info file.  */
2299   if ((bfd_get_file_flags (dwarf2_per_objfile->gdb_index.asection)
2300        & SEC_HAS_CONTENTS) == 0)
2301     return 0;
2302
2303   dwarf2_read_section (objfile, &dwarf2_per_objfile->gdb_index);
2304
2305   addr = dwarf2_per_objfile->gdb_index.buffer;
2306   /* Version check.  */
2307   version = MAYBE_SWAP (*(offset_type *) addr);
2308   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2309      causes the index to behave very poorly for certain requests.  Version 3
2310      contained incomplete addrmap.  So, it seems better to just ignore such
2311      indices.  */
2312   if (version < 4)
2313     {
2314       static int warning_printed = 0;
2315       if (!warning_printed)
2316         {
2317           warning (_("Skipping obsolete .gdb_index section in %s."),
2318                    objfile->name);
2319           warning_printed = 1;
2320         }
2321       return 0;
2322     }
2323   /* Index version 4 uses a different hash function than index version
2324      5 and later.
2325
2326      Versions earlier than 6 did not emit psymbols for inlined
2327      functions.  Using these files will cause GDB not to be able to
2328      set breakpoints on inlined functions by name, so we ignore these
2329      indices unless the --use-deprecated-index-sections command line
2330      option was supplied.  */
2331   if (version < 6 && !use_deprecated_index_sections)
2332     {
2333       static int warning_printed = 0;
2334       if (!warning_printed)
2335         {
2336           warning (_("Skipping deprecated .gdb_index section in %s, pass "
2337                      "--use-deprecated-index-sections to use them anyway"),
2338                    objfile->name);
2339           warning_printed = 1;
2340         }
2341       return 0;
2342     }
2343   /* Indexes with higher version than the one supported by GDB may be no
2344      longer backward compatible.  */
2345   if (version > 6)
2346     return 0;
2347
2348   map = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct mapped_index);
2349   map->version = version;
2350   map->total_size = dwarf2_per_objfile->gdb_index.size;
2351
2352   metadata = (offset_type *) (addr + sizeof (offset_type));
2353
2354   i = 0;
2355   cu_list = addr + MAYBE_SWAP (metadata[i]);
2356   cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2357                       / 8);
2358   ++i;
2359
2360   types_list = addr + MAYBE_SWAP (metadata[i]);
2361   types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2362                           - MAYBE_SWAP (metadata[i]))
2363                          / 8);
2364   ++i;
2365
2366   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2367   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2368                              - MAYBE_SWAP (metadata[i]));
2369   ++i;
2370
2371   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2372   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2373                               - MAYBE_SWAP (metadata[i]))
2374                              / (2 * sizeof (offset_type)));
2375   ++i;
2376
2377   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2378
2379   /* Don't use the index if it's empty.  */
2380   if (map->symbol_table_slots == 0)
2381     return 0;
2382
2383   if (!create_cus_from_index (objfile, cu_list, cu_list_elements))
2384     return 0;
2385
2386   if (types_list_elements)
2387     {
2388       struct dwarf2_section_info *section;
2389
2390       /* We can only handle a single .debug_types when we have an
2391          index.  */
2392       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2393         return 0;
2394
2395       section = VEC_index (dwarf2_section_info_def,
2396                            dwarf2_per_objfile->types, 0);
2397
2398       if (!create_signatured_type_table_from_index (objfile, section,
2399                                                     types_list,
2400                                                     types_list_elements))
2401         return 0;
2402     }
2403
2404   create_addrmap_from_index (objfile, map);
2405
2406   dwarf2_per_objfile->index_table = map;
2407   dwarf2_per_objfile->using_index = 1;
2408   dwarf2_per_objfile->quick_file_names_table =
2409     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2410
2411   return 1;
2412 }
2413
2414 /* A helper for the "quick" functions which sets the global
2415    dwarf2_per_objfile according to OBJFILE.  */
2416
2417 static void
2418 dw2_setup (struct objfile *objfile)
2419 {
2420   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2421   gdb_assert (dwarf2_per_objfile);
2422 }
2423
2424 /* die_reader_func for dw2_get_file_names.  */
2425
2426 static void
2427 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2428                            gdb_byte *info_ptr,
2429                            struct die_info *comp_unit_die,
2430                            int has_children,
2431                            void *data)
2432 {
2433   struct dwarf2_cu *cu = reader->cu;
2434   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2435   struct objfile *objfile = dwarf2_per_objfile->objfile;
2436   struct line_header *lh;
2437   struct attribute *attr;
2438   int i;
2439   char *name, *comp_dir;
2440   void **slot;
2441   struct quick_file_names *qfn;
2442   unsigned int line_offset;
2443
2444   lh = NULL;
2445   slot = NULL;
2446   line_offset = 0;
2447
2448   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2449   if (attr)
2450     {
2451       struct quick_file_names find_entry;
2452
2453       line_offset = DW_UNSND (attr);
2454
2455       /* We may have already read in this line header (TU line header sharing).
2456          If we have we're done.  */
2457       find_entry.offset = line_offset;
2458       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2459                              &find_entry, INSERT);
2460       if (*slot != NULL)
2461         {
2462           this_cu->v.quick->file_names = *slot;
2463           return;
2464         }
2465
2466       lh = dwarf_decode_line_header (line_offset, cu);
2467     }
2468   if (lh == NULL)
2469     {
2470       this_cu->v.quick->no_file_data = 1;
2471       return;
2472     }
2473
2474   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2475   qfn->offset = line_offset;
2476   gdb_assert (slot != NULL);
2477   *slot = qfn;
2478
2479   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2480
2481   qfn->num_file_names = lh->num_file_names;
2482   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2483                                    lh->num_file_names * sizeof (char *));
2484   for (i = 0; i < lh->num_file_names; ++i)
2485     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2486   qfn->real_names = NULL;
2487
2488   free_line_header (lh);
2489
2490   this_cu->v.quick->file_names = qfn;
2491 }
2492
2493 /* A helper for the "quick" functions which attempts to read the line
2494    table for THIS_CU.  */
2495
2496 static struct quick_file_names *
2497 dw2_get_file_names (struct objfile *objfile,
2498                     struct dwarf2_per_cu_data *this_cu)
2499 {
2500   if (this_cu->v.quick->file_names != NULL)
2501     return this_cu->v.quick->file_names;
2502   /* If we know there is no line data, no point in looking again.  */
2503   if (this_cu->v.quick->no_file_data)
2504     return NULL;
2505
2506   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2507      in the stub for CUs, there's is no need to lookup the DWO file.
2508      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2509      DWO file.  */
2510   if (this_cu->is_debug_types)
2511     init_cutu_and_read_dies (this_cu, 0, 0, dw2_get_file_names_reader, NULL);
2512   else
2513     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2514
2515   if (this_cu->v.quick->no_file_data)
2516     return NULL;
2517   return this_cu->v.quick->file_names;
2518 }
2519
2520 /* A helper for the "quick" functions which computes and caches the
2521    real path for a given file name from the line table.  */
2522
2523 static const char *
2524 dw2_get_real_path (struct objfile *objfile,
2525                    struct quick_file_names *qfn, int index)
2526 {
2527   if (qfn->real_names == NULL)
2528     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2529                                       qfn->num_file_names, sizeof (char *));
2530
2531   if (qfn->real_names[index] == NULL)
2532     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2533
2534   return qfn->real_names[index];
2535 }
2536
2537 static struct symtab *
2538 dw2_find_last_source_symtab (struct objfile *objfile)
2539 {
2540   int index;
2541
2542   dw2_setup (objfile);
2543   index = dwarf2_per_objfile->n_comp_units - 1;
2544   return dw2_instantiate_symtab (dw2_get_cu (index));
2545 }
2546
2547 /* Traversal function for dw2_forget_cached_source_info.  */
2548
2549 static int
2550 dw2_free_cached_file_names (void **slot, void *info)
2551 {
2552   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2553
2554   if (file_data->real_names)
2555     {
2556       int i;
2557
2558       for (i = 0; i < file_data->num_file_names; ++i)
2559         {
2560           xfree ((void*) file_data->real_names[i]);
2561           file_data->real_names[i] = NULL;
2562         }
2563     }
2564
2565   return 1;
2566 }
2567
2568 static void
2569 dw2_forget_cached_source_info (struct objfile *objfile)
2570 {
2571   dw2_setup (objfile);
2572
2573   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
2574                           dw2_free_cached_file_names, NULL);
2575 }
2576
2577 /* Helper function for dw2_map_symtabs_matching_filename that expands
2578    the symtabs and calls the iterator.  */
2579
2580 static int
2581 dw2_map_expand_apply (struct objfile *objfile,
2582                       struct dwarf2_per_cu_data *per_cu,
2583                       const char *name,
2584                       const char *full_path, const char *real_path,
2585                       int (*callback) (struct symtab *, void *),
2586                       void *data)
2587 {
2588   struct symtab *last_made = objfile->symtabs;
2589
2590   /* Don't visit already-expanded CUs.  */
2591   if (per_cu->v.quick->symtab)
2592     return 0;
2593
2594   /* This may expand more than one symtab, and we want to iterate over
2595      all of them.  */
2596   dw2_instantiate_symtab (per_cu);
2597
2598   return iterate_over_some_symtabs (name, full_path, real_path, callback, data,
2599                                     objfile->symtabs, last_made);
2600 }
2601
2602 /* Implementation of the map_symtabs_matching_filename method.  */
2603
2604 static int
2605 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
2606                                    const char *full_path, const char *real_path,
2607                                    int (*callback) (struct symtab *, void *),
2608                                    void *data)
2609 {
2610   int i;
2611   const char *name_basename = lbasename (name);
2612   int name_len = strlen (name);
2613   int is_abs = IS_ABSOLUTE_PATH (name);
2614
2615   dw2_setup (objfile);
2616
2617   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2618                    + dwarf2_per_objfile->n_type_units); ++i)
2619     {
2620       int j;
2621       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2622       struct quick_file_names *file_data;
2623
2624       /* We only need to look at symtabs not already expanded.  */
2625       if (per_cu->v.quick->symtab)
2626         continue;
2627
2628       file_data = dw2_get_file_names (objfile, per_cu);
2629       if (file_data == NULL)
2630         continue;
2631
2632       for (j = 0; j < file_data->num_file_names; ++j)
2633         {
2634           const char *this_name = file_data->file_names[j];
2635
2636           if (FILENAME_CMP (name, this_name) == 0
2637               || (!is_abs && compare_filenames_for_search (this_name,
2638                                                            name, name_len)))
2639             {
2640               if (dw2_map_expand_apply (objfile, per_cu,
2641                                         name, full_path, real_path,
2642                                         callback, data))
2643                 return 1;
2644             }
2645
2646           /* Before we invoke realpath, which can get expensive when many
2647              files are involved, do a quick comparison of the basenames.  */
2648           if (! basenames_may_differ
2649               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
2650             continue;
2651
2652           if (full_path != NULL)
2653             {
2654               const char *this_real_name = dw2_get_real_path (objfile,
2655                                                               file_data, j);
2656
2657               if (this_real_name != NULL
2658                   && (FILENAME_CMP (full_path, this_real_name) == 0
2659                       || (!is_abs
2660                           && compare_filenames_for_search (this_real_name,
2661                                                            name, name_len))))
2662                 {
2663                   if (dw2_map_expand_apply (objfile, per_cu,
2664                                             name, full_path, real_path,
2665                                             callback, data))
2666                     return 1;
2667                 }
2668             }
2669
2670           if (real_path != NULL)
2671             {
2672               const char *this_real_name = dw2_get_real_path (objfile,
2673                                                               file_data, j);
2674
2675               if (this_real_name != NULL
2676                   && (FILENAME_CMP (real_path, this_real_name) == 0
2677                       || (!is_abs
2678                           && compare_filenames_for_search (this_real_name,
2679                                                            name, name_len))))
2680                 {
2681                   if (dw2_map_expand_apply (objfile, per_cu,
2682                                             name, full_path, real_path,
2683                                             callback, data))
2684                     return 1;
2685                 }
2686             }
2687         }
2688     }
2689
2690   return 0;
2691 }
2692
2693 static struct symtab *
2694 dw2_lookup_symbol (struct objfile *objfile, int block_index,
2695                    const char *name, domain_enum domain)
2696 {
2697   /* We do all the work in the pre_expand_symtabs_matching hook
2698      instead.  */
2699   return NULL;
2700 }
2701
2702 /* A helper function that expands all symtabs that hold an object
2703    named NAME.  */
2704
2705 static void
2706 dw2_do_expand_symtabs_matching (struct objfile *objfile, const char *name)
2707 {
2708   dw2_setup (objfile);
2709
2710   /* index_table is NULL if OBJF_READNOW.  */
2711   if (dwarf2_per_objfile->index_table)
2712     {
2713       offset_type *vec;
2714
2715       if (find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
2716                                     name, &vec))
2717         {
2718           offset_type i, len = MAYBE_SWAP (*vec);
2719           for (i = 0; i < len; ++i)
2720             {
2721               offset_type cu_index = MAYBE_SWAP (vec[i + 1]);
2722               struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
2723
2724               dw2_instantiate_symtab (per_cu);
2725             }
2726         }
2727     }
2728 }
2729
2730 static void
2731 dw2_pre_expand_symtabs_matching (struct objfile *objfile,
2732                                  enum block_enum block_kind, const char *name,
2733                                  domain_enum domain)
2734 {
2735   dw2_do_expand_symtabs_matching (objfile, name);
2736 }
2737
2738 static void
2739 dw2_print_stats (struct objfile *objfile)
2740 {
2741   int i, count;
2742
2743   dw2_setup (objfile);
2744   count = 0;
2745   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2746                    + dwarf2_per_objfile->n_type_units); ++i)
2747     {
2748       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2749
2750       if (!per_cu->v.quick->symtab)
2751         ++count;
2752     }
2753   printf_filtered (_("  Number of unread CUs: %d\n"), count);
2754 }
2755
2756 static void
2757 dw2_dump (struct objfile *objfile)
2758 {
2759   /* Nothing worth printing.  */
2760 }
2761
2762 static void
2763 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
2764               struct section_offsets *delta)
2765 {
2766   /* There's nothing to relocate here.  */
2767 }
2768
2769 static void
2770 dw2_expand_symtabs_for_function (struct objfile *objfile,
2771                                  const char *func_name)
2772 {
2773   dw2_do_expand_symtabs_matching (objfile, func_name);
2774 }
2775
2776 static void
2777 dw2_expand_all_symtabs (struct objfile *objfile)
2778 {
2779   int i;
2780
2781   dw2_setup (objfile);
2782
2783   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2784                    + dwarf2_per_objfile->n_type_units); ++i)
2785     {
2786       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2787
2788       dw2_instantiate_symtab (per_cu);
2789     }
2790 }
2791
2792 static void
2793 dw2_expand_symtabs_with_filename (struct objfile *objfile,
2794                                   const char *filename)
2795 {
2796   int i;
2797
2798   dw2_setup (objfile);
2799
2800   /* We don't need to consider type units here.
2801      This is only called for examining code, e.g. expand_line_sal.
2802      There can be an order of magnitude (or more) more type units
2803      than comp units, and we avoid them if we can.  */
2804
2805   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
2806     {
2807       int j;
2808       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2809       struct quick_file_names *file_data;
2810
2811       /* We only need to look at symtabs not already expanded.  */
2812       if (per_cu->v.quick->symtab)
2813         continue;
2814
2815       file_data = dw2_get_file_names (objfile, per_cu);
2816       if (file_data == NULL)
2817         continue;
2818
2819       for (j = 0; j < file_data->num_file_names; ++j)
2820         {
2821           const char *this_name = file_data->file_names[j];
2822           if (FILENAME_CMP (this_name, filename) == 0)
2823             {
2824               dw2_instantiate_symtab (per_cu);
2825               break;
2826             }
2827         }
2828     }
2829 }
2830
2831 static const char *
2832 dw2_find_symbol_file (struct objfile *objfile, const char *name)
2833 {
2834   struct dwarf2_per_cu_data *per_cu;
2835   offset_type *vec;
2836   struct quick_file_names *file_data;
2837
2838   dw2_setup (objfile);
2839
2840   /* index_table is NULL if OBJF_READNOW.  */
2841   if (!dwarf2_per_objfile->index_table)
2842     {
2843       struct symtab *s;
2844
2845       ALL_OBJFILE_SYMTABS (objfile, s)
2846         if (s->primary)
2847           {
2848             struct blockvector *bv = BLOCKVECTOR (s);
2849             const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
2850             struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
2851
2852             if (sym)
2853               return sym->symtab->filename;
2854           }
2855       return NULL;
2856     }
2857
2858   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
2859                                  name, &vec))
2860     return NULL;
2861
2862   /* Note that this just looks at the very first one named NAME -- but
2863      actually we are looking for a function.  find_main_filename
2864      should be rewritten so that it doesn't require a custom hook.  It
2865      could just use the ordinary symbol tables.  */
2866   /* vec[0] is the length, which must always be >0.  */
2867   per_cu = dw2_get_cu (MAYBE_SWAP (vec[1]));
2868
2869   file_data = dw2_get_file_names (objfile, per_cu);
2870   if (file_data == NULL
2871       || file_data->num_file_names == 0)
2872     return NULL;
2873
2874   return file_data->file_names[file_data->num_file_names - 1];
2875 }
2876
2877 static void
2878 dw2_map_matching_symbols (const char * name, domain_enum namespace,
2879                           struct objfile *objfile, int global,
2880                           int (*callback) (struct block *,
2881                                            struct symbol *, void *),
2882                           void *data, symbol_compare_ftype *match,
2883                           symbol_compare_ftype *ordered_compare)
2884 {
2885   /* Currently unimplemented; used for Ada.  The function can be called if the
2886      current language is Ada for a non-Ada objfile using GNU index.  As Ada
2887      does not look for non-Ada symbols this function should just return.  */
2888 }
2889
2890 static void
2891 dw2_expand_symtabs_matching
2892   (struct objfile *objfile,
2893    int (*file_matcher) (const char *, void *),
2894    int (*name_matcher) (const char *, void *),
2895    enum search_domain kind,
2896    void *data)
2897 {
2898   int i;
2899   offset_type iter;
2900   struct mapped_index *index;
2901
2902   dw2_setup (objfile);
2903
2904   /* index_table is NULL if OBJF_READNOW.  */
2905   if (!dwarf2_per_objfile->index_table)
2906     return;
2907   index = dwarf2_per_objfile->index_table;
2908
2909   if (file_matcher != NULL)
2910     {
2911       struct cleanup *cleanup;
2912       htab_t visited_found, visited_not_found;
2913
2914       visited_found = htab_create_alloc (10,
2915                                          htab_hash_pointer, htab_eq_pointer,
2916                                          NULL, xcalloc, xfree);
2917       cleanup = make_cleanup_htab_delete (visited_found);
2918       visited_not_found = htab_create_alloc (10,
2919                                              htab_hash_pointer, htab_eq_pointer,
2920                                              NULL, xcalloc, xfree);
2921       make_cleanup_htab_delete (visited_not_found);
2922
2923       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2924                        + dwarf2_per_objfile->n_type_units); ++i)
2925         {
2926           int j;
2927           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2928           struct quick_file_names *file_data;
2929           void **slot;
2930
2931           per_cu->v.quick->mark = 0;
2932
2933           /* We only need to look at symtabs not already expanded.  */
2934           if (per_cu->v.quick->symtab)
2935             continue;
2936
2937           file_data = dw2_get_file_names (objfile, per_cu);
2938           if (file_data == NULL)
2939             continue;
2940
2941           if (htab_find (visited_not_found, file_data) != NULL)
2942             continue;
2943           else if (htab_find (visited_found, file_data) != NULL)
2944             {
2945               per_cu->v.quick->mark = 1;
2946               continue;
2947             }
2948
2949           for (j = 0; j < file_data->num_file_names; ++j)
2950             {
2951               if (file_matcher (file_data->file_names[j], data))
2952                 {
2953                   per_cu->v.quick->mark = 1;
2954                   break;
2955                 }
2956             }
2957
2958           slot = htab_find_slot (per_cu->v.quick->mark
2959                                  ? visited_found
2960                                  : visited_not_found,
2961                                  file_data, INSERT);
2962           *slot = file_data;
2963         }
2964
2965       do_cleanups (cleanup);
2966     }
2967
2968   for (iter = 0; iter < index->symbol_table_slots; ++iter)
2969     {
2970       offset_type idx = 2 * iter;
2971       const char *name;
2972       offset_type *vec, vec_len, vec_idx;
2973
2974       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
2975         continue;
2976
2977       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
2978
2979       if (! (*name_matcher) (name, data))
2980         continue;
2981
2982       /* The name was matched, now expand corresponding CUs that were
2983          marked.  */
2984       vec = (offset_type *) (index->constant_pool
2985                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
2986       vec_len = MAYBE_SWAP (vec[0]);
2987       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
2988         {
2989           struct dwarf2_per_cu_data *per_cu;
2990
2991           per_cu = dw2_get_cu (MAYBE_SWAP (vec[vec_idx + 1]));
2992           if (file_matcher == NULL || per_cu->v.quick->mark)
2993             dw2_instantiate_symtab (per_cu);
2994         }
2995     }
2996 }
2997
2998 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
2999    symtab.  */
3000
3001 static struct symtab *
3002 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3003 {
3004   int i;
3005
3006   if (BLOCKVECTOR (symtab) != NULL
3007       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3008     return symtab;
3009
3010   if (symtab->includes == NULL)
3011     return NULL;
3012
3013   for (i = 0; symtab->includes[i]; ++i)
3014     {
3015       struct symtab *s = symtab->includes[i];
3016
3017       s = recursively_find_pc_sect_symtab (s, pc);
3018       if (s != NULL)
3019         return s;
3020     }
3021
3022   return NULL;
3023 }
3024
3025 static struct symtab *
3026 dw2_find_pc_sect_symtab (struct objfile *objfile,
3027                          struct minimal_symbol *msymbol,
3028                          CORE_ADDR pc,
3029                          struct obj_section *section,
3030                          int warn_if_readin)
3031 {
3032   struct dwarf2_per_cu_data *data;
3033   struct symtab *result;
3034
3035   dw2_setup (objfile);
3036
3037   if (!objfile->psymtabs_addrmap)
3038     return NULL;
3039
3040   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3041   if (!data)
3042     return NULL;
3043
3044   if (warn_if_readin && data->v.quick->symtab)
3045     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3046              paddress (get_objfile_arch (objfile), pc));
3047
3048   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3049   gdb_assert (result != NULL);
3050   return result;
3051 }
3052
3053 static void
3054 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3055                           void *data, int need_fullname)
3056 {
3057   int i;
3058   struct cleanup *cleanup;
3059   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3060                                       NULL, xcalloc, xfree);
3061
3062   cleanup = make_cleanup_htab_delete (visited);
3063   dw2_setup (objfile);
3064
3065   /* We can ignore file names coming from already-expanded CUs.  */
3066   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3067                    + dwarf2_per_objfile->n_type_units); ++i)
3068     {
3069       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3070
3071       if (per_cu->v.quick->symtab)
3072         {
3073           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3074                                         INSERT);
3075
3076           *slot = per_cu->v.quick->file_names;
3077         }
3078     }
3079
3080   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3081                    + dwarf2_per_objfile->n_type_units); ++i)
3082     {
3083       int j;
3084       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3085       struct quick_file_names *file_data;
3086       void **slot;
3087
3088       /* We only need to look at symtabs not already expanded.  */
3089       if (per_cu->v.quick->symtab)
3090         continue;
3091
3092       file_data = dw2_get_file_names (objfile, per_cu);
3093       if (file_data == NULL)
3094         continue;
3095
3096       slot = htab_find_slot (visited, file_data, INSERT);
3097       if (*slot)
3098         {
3099           /* Already visited.  */
3100           continue;
3101         }
3102       *slot = file_data;
3103
3104       for (j = 0; j < file_data->num_file_names; ++j)
3105         {
3106           const char *this_real_name;
3107
3108           if (need_fullname)
3109             this_real_name = dw2_get_real_path (objfile, file_data, j);
3110           else
3111             this_real_name = NULL;
3112           (*fun) (file_data->file_names[j], this_real_name, data);
3113         }
3114     }
3115
3116   do_cleanups (cleanup);
3117 }
3118
3119 static int
3120 dw2_has_symbols (struct objfile *objfile)
3121 {
3122   return 1;
3123 }
3124
3125 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3126 {
3127   dw2_has_symbols,
3128   dw2_find_last_source_symtab,
3129   dw2_forget_cached_source_info,
3130   dw2_map_symtabs_matching_filename,
3131   dw2_lookup_symbol,
3132   dw2_pre_expand_symtabs_matching,
3133   dw2_print_stats,
3134   dw2_dump,
3135   dw2_relocate,
3136   dw2_expand_symtabs_for_function,
3137   dw2_expand_all_symtabs,
3138   dw2_expand_symtabs_with_filename,
3139   dw2_find_symbol_file,
3140   dw2_map_matching_symbols,
3141   dw2_expand_symtabs_matching,
3142   dw2_find_pc_sect_symtab,
3143   dw2_map_symbol_filenames
3144 };
3145
3146 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3147    file will use psymtabs, or 1 if using the GNU index.  */
3148
3149 int
3150 dwarf2_initialize_objfile (struct objfile *objfile)
3151 {
3152   /* If we're about to read full symbols, don't bother with the
3153      indices.  In this case we also don't care if some other debug
3154      format is making psymtabs, because they are all about to be
3155      expanded anyway.  */
3156   if ((objfile->flags & OBJF_READNOW))
3157     {
3158       int i;
3159
3160       dwarf2_per_objfile->using_index = 1;
3161       create_all_comp_units (objfile);
3162       create_all_type_units (objfile);
3163       dwarf2_per_objfile->quick_file_names_table =
3164         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3165
3166       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3167                        + dwarf2_per_objfile->n_type_units); ++i)
3168         {
3169           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3170
3171           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3172                                             struct dwarf2_per_cu_quick_data);
3173         }
3174
3175       /* Return 1 so that gdb sees the "quick" functions.  However,
3176          these functions will be no-ops because we will have expanded
3177          all symtabs.  */
3178       return 1;
3179     }
3180
3181   if (dwarf2_read_index (objfile))
3182     return 1;
3183
3184   return 0;
3185 }
3186
3187 \f
3188
3189 /* Build a partial symbol table.  */
3190
3191 void
3192 dwarf2_build_psymtabs (struct objfile *objfile)
3193 {
3194   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3195     {
3196       init_psymbol_list (objfile, 1024);
3197     }
3198
3199   dwarf2_build_psymtabs_hard (objfile);
3200 }
3201
3202 /* Return TRUE if OFFSET is within CU_HEADER.  */
3203
3204 static inline int
3205 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3206 {
3207   sect_offset bottom = { cu_header->offset.sect_off };
3208   sect_offset top = { (cu_header->offset.sect_off + cu_header->length
3209                        + cu_header->initial_length_size) };
3210
3211   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3212 }
3213
3214 /* Read in the comp unit header information from the debug_info at info_ptr.
3215    NOTE: This leaves members offset, first_die_offset to be filled in
3216    by the caller.  */
3217
3218 static gdb_byte *
3219 read_comp_unit_head (struct comp_unit_head *cu_header,
3220                      gdb_byte *info_ptr, bfd *abfd)
3221 {
3222   int signed_addr;
3223   unsigned int bytes_read;
3224
3225   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3226   cu_header->initial_length_size = bytes_read;
3227   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3228   info_ptr += bytes_read;
3229   cu_header->version = read_2_bytes (abfd, info_ptr);
3230   info_ptr += 2;
3231   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3232                                              &bytes_read);
3233   info_ptr += bytes_read;
3234   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3235   info_ptr += 1;
3236   signed_addr = bfd_get_sign_extend_vma (abfd);
3237   if (signed_addr < 0)
3238     internal_error (__FILE__, __LINE__,
3239                     _("read_comp_unit_head: dwarf from non elf file"));
3240   cu_header->signed_addr_p = signed_addr;
3241
3242   return info_ptr;
3243 }
3244
3245 /* Subroutine of read_and_check_comp_unit_head and
3246    read_and_check_type_unit_head to simplify them.
3247    Perform various error checking on the header.  */
3248
3249 static void
3250 error_check_comp_unit_head (struct comp_unit_head *header,
3251                             struct dwarf2_section_info *section)
3252 {
3253   bfd *abfd = section->asection->owner;
3254   const char *filename = bfd_get_filename (abfd);
3255
3256   if (header->version != 2 && header->version != 3 && header->version != 4)
3257     error (_("Dwarf Error: wrong version in compilation unit header "
3258            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3259            filename);
3260
3261   if (header->abbrev_offset.sect_off
3262       >= dwarf2_section_size (dwarf2_per_objfile->objfile,
3263                               &dwarf2_per_objfile->abbrev))
3264     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3265            "(offset 0x%lx + 6) [in module %s]"),
3266            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3267            filename);
3268
3269   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3270      avoid potential 32-bit overflow.  */
3271   if (((unsigned long) header->offset.sect_off
3272        + header->length + header->initial_length_size)
3273       > section->size)
3274     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3275            "(offset 0x%lx + 0) [in module %s]"),
3276            (long) header->length, (long) header->offset.sect_off,
3277            filename);
3278 }
3279
3280 /* Read in a CU/TU header and perform some basic error checking.
3281    The contents of the header are stored in HEADER.
3282    The result is a pointer to the start of the first DIE.  */
3283
3284 static gdb_byte *
3285 read_and_check_comp_unit_head (struct comp_unit_head *header,
3286                                struct dwarf2_section_info *section,
3287                                gdb_byte *info_ptr,
3288                                int is_debug_types_section)
3289 {
3290   gdb_byte *beg_of_comp_unit = info_ptr;
3291   bfd *abfd = section->asection->owner;
3292
3293   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3294
3295   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3296
3297   /* If we're reading a type unit, skip over the signature and
3298      type_offset fields.  */
3299   if (is_debug_types_section)
3300     info_ptr += 8 /*signature*/ + header->offset_size;
3301
3302   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3303
3304   error_check_comp_unit_head (header, section);
3305
3306   return info_ptr;
3307 }
3308
3309 /* Read in the types comp unit header information from .debug_types entry at
3310    types_ptr.  The result is a pointer to one past the end of the header.  */
3311
3312 static gdb_byte *
3313 read_and_check_type_unit_head (struct comp_unit_head *header,
3314                                struct dwarf2_section_info *section,
3315                                gdb_byte *info_ptr,
3316                                ULONGEST *signature,
3317                                cu_offset *type_offset_in_tu)
3318 {
3319   gdb_byte *beg_of_comp_unit = info_ptr;
3320   bfd *abfd = section->asection->owner;
3321
3322   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3323
3324   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3325
3326   /* If we're reading a type unit, skip over the signature and
3327      type_offset fields.  */
3328   if (signature != NULL)
3329     *signature = read_8_bytes (abfd, info_ptr);
3330   info_ptr += 8;
3331   if (type_offset_in_tu != NULL)
3332     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
3333                                                header->offset_size);
3334   info_ptr += header->offset_size;
3335
3336   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3337
3338   error_check_comp_unit_head (header, section);
3339
3340   return info_ptr;
3341 }
3342
3343 /* Allocate a new partial symtab for file named NAME and mark this new
3344    partial symtab as being an include of PST.  */
3345
3346 static void
3347 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
3348                                struct objfile *objfile)
3349 {
3350   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
3351
3352   subpst->section_offsets = pst->section_offsets;
3353   subpst->textlow = 0;
3354   subpst->texthigh = 0;
3355
3356   subpst->dependencies = (struct partial_symtab **)
3357     obstack_alloc (&objfile->objfile_obstack,
3358                    sizeof (struct partial_symtab *));
3359   subpst->dependencies[0] = pst;
3360   subpst->number_of_dependencies = 1;
3361
3362   subpst->globals_offset = 0;
3363   subpst->n_global_syms = 0;
3364   subpst->statics_offset = 0;
3365   subpst->n_static_syms = 0;
3366   subpst->symtab = NULL;
3367   subpst->read_symtab = pst->read_symtab;
3368   subpst->readin = 0;
3369
3370   /* No private part is necessary for include psymtabs.  This property
3371      can be used to differentiate between such include psymtabs and
3372      the regular ones.  */
3373   subpst->read_symtab_private = NULL;
3374 }
3375
3376 /* Read the Line Number Program data and extract the list of files
3377    included by the source file represented by PST.  Build an include
3378    partial symtab for each of these included files.  */
3379
3380 static void
3381 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
3382                                struct die_info *die,
3383                                struct partial_symtab *pst)
3384 {
3385   struct line_header *lh = NULL;
3386   struct attribute *attr;
3387
3388   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
3389   if (attr)
3390     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
3391   if (lh == NULL)
3392     return;  /* No linetable, so no includes.  */
3393
3394   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
3395   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
3396
3397   free_line_header (lh);
3398 }
3399
3400 static hashval_t
3401 hash_signatured_type (const void *item)
3402 {
3403   const struct signatured_type *sig_type = item;
3404
3405   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
3406   return sig_type->signature;
3407 }
3408
3409 static int
3410 eq_signatured_type (const void *item_lhs, const void *item_rhs)
3411 {
3412   const struct signatured_type *lhs = item_lhs;
3413   const struct signatured_type *rhs = item_rhs;
3414
3415   return lhs->signature == rhs->signature;
3416 }
3417
3418 /* Allocate a hash table for signatured types.  */
3419
3420 static htab_t
3421 allocate_signatured_type_table (struct objfile *objfile)
3422 {
3423   return htab_create_alloc_ex (41,
3424                                hash_signatured_type,
3425                                eq_signatured_type,
3426                                NULL,
3427                                &objfile->objfile_obstack,
3428                                hashtab_obstack_allocate,
3429                                dummy_obstack_deallocate);
3430 }
3431
3432 /* A helper function to add a signatured type CU to a table.  */
3433
3434 static int
3435 add_signatured_type_cu_to_table (void **slot, void *datum)
3436 {
3437   struct signatured_type *sigt = *slot;
3438   struct dwarf2_per_cu_data ***datap = datum;
3439
3440   **datap = &sigt->per_cu;
3441   ++*datap;
3442
3443   return 1;
3444 }
3445
3446 /* Create the hash table of all entries in the .debug_types section.
3447    DWO_FILE is a pointer to the DWO file for .debug_types.dwo, NULL otherwise.
3448    The result is a pointer to the hash table or NULL if there are
3449    no types.  */
3450
3451 static htab_t
3452 create_debug_types_hash_table (struct dwo_file *dwo_file,
3453                                VEC (dwarf2_section_info_def) *types)
3454 {
3455   struct objfile *objfile = dwarf2_per_objfile->objfile;
3456   htab_t types_htab = NULL;
3457   int ix;
3458   struct dwarf2_section_info *section;
3459
3460   if (VEC_empty (dwarf2_section_info_def, types))
3461     return NULL;
3462
3463   for (ix = 0;
3464        VEC_iterate (dwarf2_section_info_def, types, ix, section);
3465        ++ix)
3466     {
3467       bfd *abfd;
3468       gdb_byte *info_ptr, *end_ptr;
3469
3470       dwarf2_read_section (objfile, section);
3471       info_ptr = section->buffer;
3472
3473       if (info_ptr == NULL)
3474         continue;
3475
3476       /* We can't set abfd until now because the section may be empty or
3477          not present, in which case section->asection will be NULL.  */
3478       abfd = section->asection->owner;
3479
3480       if (types_htab == NULL)
3481         {
3482           if (dwo_file)
3483             types_htab = allocate_dwo_unit_table (objfile);
3484           else
3485             types_htab = allocate_signatured_type_table (objfile);
3486         }
3487
3488       if (dwarf2_die_debug)
3489         fprintf_unfiltered (gdb_stdlog, "Reading signatured types for %s:\n",
3490                             bfd_get_filename (abfd));
3491
3492       /* We don't use init_cutu_and_read_dies_simple, or some such, here
3493          because we don't need to read any dies: the signature is in the
3494          header.  */
3495
3496       end_ptr = info_ptr + section->size;
3497       while (info_ptr < end_ptr)
3498         {
3499           sect_offset offset;
3500           cu_offset type_offset_in_tu;
3501           ULONGEST signature;
3502           struct signatured_type *sig_type;
3503           struct dwo_unit *dwo_tu;
3504           void **slot;
3505           gdb_byte *ptr = info_ptr;
3506           struct comp_unit_head header;
3507           unsigned int length;
3508
3509           offset.sect_off = ptr - section->buffer;
3510
3511           /* We need to read the type's signature in order to build the hash
3512              table, but we don't need anything else just yet.  */
3513
3514           ptr = read_and_check_type_unit_head (&header, section, ptr,
3515                                                &signature, &type_offset_in_tu);
3516
3517           length = header.initial_length_size + header.length;
3518
3519           /* Skip dummy type units.  */
3520           if (ptr >= info_ptr + length
3521               || peek_abbrev_code (abfd, ptr) == 0)
3522             {
3523               info_ptr += header.initial_length_size + header.length;
3524               continue;
3525             }
3526
3527           if (dwo_file)
3528             {
3529               sig_type = NULL;
3530               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3531                                        struct dwo_unit);
3532               dwo_tu->dwo_file = dwo_file;
3533               dwo_tu->signature = signature;
3534               dwo_tu->type_offset_in_tu = type_offset_in_tu;
3535               dwo_tu->info_or_types_section = section;
3536               dwo_tu->offset = offset;
3537               dwo_tu->length = length;
3538             }
3539           else
3540             {
3541               /* N.B.: type_offset is not usable if this type uses a DWO file.
3542                  The real type_offset is in the DWO file.  */
3543               dwo_tu = NULL;
3544               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3545                                          struct signatured_type);
3546               sig_type->signature = signature;
3547               sig_type->type_offset_in_tu = type_offset_in_tu;
3548               sig_type->per_cu.objfile = objfile;
3549               sig_type->per_cu.is_debug_types = 1;
3550               sig_type->per_cu.info_or_types_section = section;
3551               sig_type->per_cu.offset = offset;
3552               sig_type->per_cu.length = length;
3553             }
3554
3555           slot = htab_find_slot (types_htab,
3556                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
3557                                  INSERT);
3558           gdb_assert (slot != NULL);
3559           if (*slot != NULL)
3560             {
3561               sect_offset dup_offset;
3562
3563               if (dwo_file)
3564                 {
3565                   const struct dwo_unit *dup_tu = *slot;
3566
3567                   dup_offset = dup_tu->offset;
3568                 }
3569               else
3570                 {
3571                   const struct signatured_type *dup_tu = *slot;
3572
3573                   dup_offset = dup_tu->per_cu.offset;
3574                 }
3575
3576               complaint (&symfile_complaints,
3577                          _("debug type entry at offset 0x%x is duplicate to the "
3578                            "entry at offset 0x%x, signature 0x%s"),
3579                          offset.sect_off, dup_offset.sect_off,
3580                          phex (signature, sizeof (signature)));
3581             }
3582           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
3583
3584           if (dwarf2_die_debug)
3585             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
3586                                 offset.sect_off,
3587                                 phex (signature, sizeof (signature)));
3588
3589           info_ptr += length;
3590         }
3591     }
3592
3593   return types_htab;
3594 }
3595
3596 /* Create the hash table of all entries in the .debug_types section,
3597    and initialize all_type_units.
3598    The result is zero if there is an error (e.g. missing .debug_types section),
3599    otherwise non-zero.  */
3600
3601 static int
3602 create_all_type_units (struct objfile *objfile)
3603 {
3604   htab_t types_htab;
3605   struct dwarf2_per_cu_data **iter;
3606
3607   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
3608   if (types_htab == NULL)
3609     {
3610       dwarf2_per_objfile->signatured_types = NULL;
3611       return 0;
3612     }
3613
3614   dwarf2_per_objfile->signatured_types = types_htab;
3615
3616   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
3617   dwarf2_per_objfile->all_type_units
3618     = obstack_alloc (&objfile->objfile_obstack,
3619                      dwarf2_per_objfile->n_type_units
3620                      * sizeof (struct dwarf2_per_cu_data *));
3621   iter = &dwarf2_per_objfile->all_type_units[0];
3622   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
3623   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
3624               == dwarf2_per_objfile->n_type_units);
3625
3626   return 1;
3627 }
3628
3629 /* Lookup a signature based type for DW_FORM_ref_sig8.
3630    Returns NULL if signature SIG is not present in the table.  */
3631
3632 static struct signatured_type *
3633 lookup_signatured_type (ULONGEST sig)
3634 {
3635   struct signatured_type find_entry, *entry;
3636
3637   if (dwarf2_per_objfile->signatured_types == NULL)
3638     {
3639       complaint (&symfile_complaints,
3640                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
3641       return NULL;
3642     }
3643
3644   find_entry.signature = sig;
3645   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
3646   return entry;
3647 }
3648
3649 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
3650
3651 static void
3652 init_cu_die_reader (struct die_reader_specs *reader,
3653                     struct dwarf2_cu *cu,
3654                     struct dwarf2_section_info *section,
3655                     struct dwo_file *dwo_file)
3656 {
3657   gdb_assert (section->readin && section->buffer != NULL);
3658   reader->abfd = section->asection->owner;
3659   reader->cu = cu;
3660   reader->dwo_file = dwo_file;
3661   reader->die_section = section;
3662   reader->buffer = section->buffer;
3663   reader->buffer_end = section->buffer + section->size;
3664 }
3665
3666 /* Find the base address of the compilation unit for range lists and
3667    location lists.  It will normally be specified by DW_AT_low_pc.
3668    In DWARF-3 draft 4, the base address could be overridden by
3669    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3670    compilation units with discontinuous ranges.  */
3671
3672 static void
3673 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3674 {
3675   struct attribute *attr;
3676
3677   cu->base_known = 0;
3678   cu->base_address = 0;
3679
3680   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3681   if (attr)
3682     {
3683       cu->base_address = DW_ADDR (attr);
3684       cu->base_known = 1;
3685     }
3686   else
3687     {
3688       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3689       if (attr)
3690         {
3691           cu->base_address = DW_ADDR (attr);
3692           cu->base_known = 1;
3693         }
3694     }
3695 }
3696
3697 /* Initialize a CU (or TU) and read its DIEs.
3698    If the CU defers to a DWO file, read the DWO file as well.
3699
3700    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
3701    Otherwise, a new CU is allocated with xmalloc.
3702
3703    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
3704    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
3705
3706    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
3707    linker) then DIE_READER_FUNC will not get called.  */
3708
3709 static void
3710 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
3711                          int use_existing_cu, int keep,
3712                          die_reader_func_ftype *die_reader_func,
3713                          void *data)
3714 {
3715   struct objfile *objfile = dwarf2_per_objfile->objfile;
3716   struct dwarf2_section_info *section = this_cu->info_or_types_section;
3717   bfd *abfd = section->asection->owner;
3718   struct dwarf2_cu *cu;
3719   gdb_byte *begin_info_ptr, *info_ptr;
3720   struct die_reader_specs reader;
3721   struct die_info *comp_unit_die;
3722   int has_children;
3723   struct attribute *attr;
3724   struct cleanup *cleanups, *free_cu_cleanup = NULL;
3725   struct signatured_type *sig_type = NULL;
3726
3727   if (use_existing_cu)
3728     gdb_assert (keep);
3729
3730   cleanups = make_cleanup (null_cleanup, NULL);
3731
3732   /* This is cheap if the section is already read in.  */
3733   dwarf2_read_section (objfile, section);
3734
3735   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
3736
3737   if (use_existing_cu && this_cu->cu != NULL)
3738     {
3739       cu = this_cu->cu;
3740       info_ptr += cu->header.first_die_offset.cu_off;
3741     }
3742   else
3743     {
3744       /* If !use_existing_cu, this_cu->cu must be NULL.  */
3745       gdb_assert (this_cu->cu == NULL);
3746
3747       cu = xmalloc (sizeof (*cu));
3748       init_one_comp_unit (cu, this_cu);
3749
3750       /* If an error occurs while loading, release our storage.  */
3751       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
3752
3753       if (this_cu->is_debug_types)
3754         {
3755           ULONGEST signature;
3756
3757           info_ptr = read_and_check_type_unit_head (&cu->header,
3758                                                     section, info_ptr,
3759                                                     &signature, NULL);
3760
3761           /* There's no way to get from PER_CU to its containing
3762              struct signatured_type.
3763              But we have the signature so we can use that.  */
3764           sig_type = lookup_signatured_type (signature);
3765           /* We've already scanned all the signatured types,
3766              this must succeed.  */
3767           gdb_assert (sig_type != NULL);
3768           gdb_assert (&sig_type->per_cu == this_cu);
3769           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
3770
3771           /* LENGTH has not been set yet for type units.  */
3772           this_cu->length = cu->header.length + cu->header.initial_length_size;
3773
3774           /* Establish the type offset that can be used to lookup the type.  */
3775           sig_type->type_offset_in_section.sect_off =
3776             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
3777         }
3778       else
3779         {
3780           info_ptr = read_and_check_comp_unit_head (&cu->header,
3781                                                     section, info_ptr, 0);
3782
3783           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
3784           gdb_assert (this_cu->length
3785                       == cu->header.length + cu->header.initial_length_size);
3786         }
3787     }
3788
3789   /* Skip dummy compilation units.  */
3790   if (info_ptr >= begin_info_ptr + this_cu->length
3791       || peek_abbrev_code (abfd, info_ptr) == 0)
3792     {
3793       do_cleanups (cleanups);
3794       return;
3795     }
3796
3797   /* Read the abbrevs for this compilation unit into a table.  */
3798   if (cu->dwarf2_abbrevs == NULL)
3799     {
3800       dwarf2_read_abbrevs (cu, &dwarf2_per_objfile->abbrev);
3801       make_cleanup (dwarf2_free_abbrev_table, cu);
3802     }
3803
3804   /* Read the top level CU/TU die.  */
3805   init_cu_die_reader (&reader, cu, section, NULL);
3806   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
3807
3808   /* If we have a DWO stub, process it and then read in the DWO file.
3809      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
3810      a DWO CU, that this test will fail.  */
3811   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
3812   if (attr)
3813     {
3814       char *dwo_name = DW_STRING (attr);
3815       const char *comp_dir;
3816       struct dwo_unit *dwo_unit;
3817       ULONGEST signature; /* Or dwo_id.  */
3818       struct attribute *stmt_list, *low_pc, *high_pc, *ranges;
3819       int i,num_extra_attrs;
3820
3821       if (has_children)
3822         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
3823                  " has children (offset 0x%x) [in module %s]"),
3824                this_cu->offset.sect_off, bfd_get_filename (abfd));
3825
3826       /* These attributes aren't processed until later:
3827          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
3828          However, the attribute is found in the stub which we won't have later.
3829          In order to not impose this complication on the rest of the code,
3830          we read them here and copy them to the DWO CU/TU die.  */
3831       stmt_list = low_pc = high_pc = ranges = NULL;
3832
3833       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
3834          DWO file.  */
3835       if (! this_cu->is_debug_types)
3836         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3837       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
3838       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
3839       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
3840
3841       /* There should be a DW_AT_addr_base attribute here (if needed).
3842          We need the value before we can process DW_FORM_GNU_addr_index.  */
3843       cu->addr_base = 0;
3844       cu->have_addr_base = 0;
3845       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
3846       if (attr)
3847         {
3848           cu->addr_base = DW_UNSND (attr);
3849           cu->have_addr_base = 1;
3850         }
3851
3852       if (this_cu->is_debug_types)
3853         {
3854           gdb_assert (sig_type != NULL);
3855           signature = sig_type->signature;
3856         }
3857       else
3858         {
3859           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
3860           if (! attr)
3861             error (_("Dwarf Error: missing dwo_id [in module %s]"),
3862                    dwo_name);
3863           signature = DW_UNSND (attr);
3864         }
3865
3866       /* We may need the comp_dir in order to find the DWO file.  */
3867       comp_dir = NULL;
3868       attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
3869       if (attr)
3870         comp_dir = DW_STRING (attr);
3871
3872       if (this_cu->is_debug_types)
3873         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
3874       else
3875         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
3876                                          signature);
3877
3878       if (dwo_unit == NULL)
3879         {
3880           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
3881                    " with ID %s [in module %s]"),
3882                  this_cu->offset.sect_off,
3883                  phex (signature, sizeof (signature)),
3884                  objfile->name);
3885         }
3886
3887       /* Set up for reading the DWO CU/TU.  */
3888       cu->dwo_unit = dwo_unit;
3889       section = dwo_unit->info_or_types_section;
3890       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
3891       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
3892
3893       if (this_cu->is_debug_types)
3894         {
3895           ULONGEST signature;
3896
3897           info_ptr = read_and_check_type_unit_head (&cu->header,
3898                                                     section, info_ptr,
3899                                                     &signature, NULL);
3900           gdb_assert (sig_type->signature == signature);
3901           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
3902           gdb_assert (dwo_unit->length
3903                       == cu->header.length + cu->header.initial_length_size);
3904
3905           /* Establish the type offset that can be used to lookup the type.
3906              For DWO files, we don't know it until now.  */
3907           sig_type->type_offset_in_section.sect_off =
3908             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
3909         }
3910       else
3911         {
3912           info_ptr = read_and_check_comp_unit_head (&cu->header,
3913                                                     section, info_ptr, 0);
3914           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
3915           gdb_assert (dwo_unit->length
3916                       == cu->header.length + cu->header.initial_length_size);
3917         }
3918
3919       /* Discard the original CU's abbrev table, and read the DWO's.  */
3920       dwarf2_free_abbrev_table (cu);
3921       dwarf2_read_abbrevs (cu, &dwo_unit->dwo_file->sections.abbrev);
3922
3923       /* Read in the die, but leave space to copy over the attributes
3924          from the stub.  This has the benefit of simplifying the rest of
3925          the code - all the real work is done here.  */
3926       num_extra_attrs = ((stmt_list != NULL)
3927                          + (low_pc != NULL)
3928                          + (high_pc != NULL)
3929                          + (ranges != NULL));
3930       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
3931                                   &has_children, num_extra_attrs);
3932
3933       /* Copy over the attributes from the stub to the DWO die.  */
3934       i = comp_unit_die->num_attrs;
3935       if (stmt_list != NULL)
3936         comp_unit_die->attrs[i++] = *stmt_list;
3937       if (low_pc != NULL)
3938         comp_unit_die->attrs[i++] = *low_pc;
3939       if (high_pc != NULL)
3940         comp_unit_die->attrs[i++] = *high_pc;
3941       if (ranges != NULL)
3942         comp_unit_die->attrs[i++] = *ranges;
3943       comp_unit_die->num_attrs += num_extra_attrs;
3944
3945       /* Skip dummy compilation units.  */
3946       if (info_ptr >= begin_info_ptr + dwo_unit->length
3947           || peek_abbrev_code (abfd, info_ptr) == 0)
3948         {
3949           do_cleanups (cleanups);
3950           return;
3951         }
3952     }
3953
3954   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
3955
3956   if (free_cu_cleanup != NULL)
3957     {
3958       if (keep)
3959         {
3960           /* We've successfully allocated this compilation unit.  Let our
3961              caller clean it up when finished with it.  */
3962           discard_cleanups (free_cu_cleanup);
3963
3964           /* We can only discard free_cu_cleanup and all subsequent cleanups.
3965              So we have to manually free the abbrev table.  */
3966           dwarf2_free_abbrev_table (cu);
3967
3968           /* Link this CU into read_in_chain.  */
3969           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
3970           dwarf2_per_objfile->read_in_chain = this_cu;
3971         }
3972       else
3973         do_cleanups (free_cu_cleanup);
3974     }
3975
3976   do_cleanups (cleanups);
3977 }
3978
3979 /* Read CU/TU THIS_CU in section SECTION,
3980    but do not follow DW_AT_GNU_dwo_name if present.
3981    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed to
3982    have already done the lookup to find the DWO file).
3983
3984    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
3985    THIS_CU->is_debug_types, but nothing else.
3986
3987    We fill in THIS_CU->length.
3988
3989    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
3990    linker) then DIE_READER_FUNC will not get called.
3991
3992    THIS_CU->cu is always freed when done.
3993    This is done in order to not leave THIS_CU->cu in a state where we have
3994    to care whether it refers to the "main" CU or the DWO CU.  */
3995
3996 static void
3997 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
3998                                    struct dwarf2_section_info *abbrev_section,
3999                                    struct dwo_file *dwo_file,
4000                                    die_reader_func_ftype *die_reader_func,
4001                                    void *data)
4002 {
4003   struct objfile *objfile = dwarf2_per_objfile->objfile;
4004   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4005   bfd *abfd = section->asection->owner;
4006   struct dwarf2_cu cu;
4007   gdb_byte *begin_info_ptr, *info_ptr;
4008   struct die_reader_specs reader;
4009   struct cleanup *cleanups;
4010   struct die_info *comp_unit_die;
4011   int has_children;
4012
4013   gdb_assert (this_cu->cu == NULL);
4014
4015   /* This is cheap if the section is already read in.  */
4016   dwarf2_read_section (objfile, section);
4017
4018   init_one_comp_unit (&cu, this_cu);
4019
4020   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4021
4022   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4023   info_ptr = read_and_check_comp_unit_head (&cu.header, section, info_ptr,
4024                                             this_cu->is_debug_types);
4025
4026   this_cu->length = cu.header.length + cu.header.initial_length_size;
4027
4028   /* Skip dummy compilation units.  */
4029   if (info_ptr >= begin_info_ptr + this_cu->length
4030       || peek_abbrev_code (abfd, info_ptr) == 0)
4031     {
4032       do_cleanups (cleanups);
4033       return;
4034     }
4035
4036   dwarf2_read_abbrevs (&cu, abbrev_section);
4037   make_cleanup (dwarf2_free_abbrev_table, &cu);
4038
4039   init_cu_die_reader (&reader, &cu, section, dwo_file);
4040   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4041
4042   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4043
4044   do_cleanups (cleanups);
4045 }
4046
4047 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4048    does not lookup the specified DWO file.
4049    This cannot be used to read DWO files.
4050
4051    THIS_CU->cu is always freed when done.
4052    This is done in order to not leave THIS_CU->cu in a state where we have
4053    to care whether it refers to the "main" CU or the DWO CU.
4054    We can revisit this if the data shows there's a performance issue.  */
4055
4056 static void
4057 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4058                                 die_reader_func_ftype *die_reader_func,
4059                                 void *data)
4060 {
4061   init_cutu_and_read_dies_no_follow (this_cu,
4062                                      &dwarf2_per_objfile->abbrev,
4063                                      NULL,
4064                                      die_reader_func, data);
4065 }
4066
4067 /* die_reader_func for process_psymtab_comp_unit.  */
4068
4069 static void
4070 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4071                                   gdb_byte *info_ptr,
4072                                   struct die_info *comp_unit_die,
4073                                   int has_children,
4074                                   void *data)
4075 {
4076   struct dwarf2_cu *cu = reader->cu;
4077   struct objfile *objfile = cu->objfile;
4078   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4079   struct attribute *attr;
4080   CORE_ADDR baseaddr;
4081   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4082   struct partial_symtab *pst;
4083   int has_pc_info;
4084   const char *filename;
4085   int *want_partial_unit_ptr = data;
4086
4087   if (comp_unit_die->tag == DW_TAG_partial_unit
4088       && (want_partial_unit_ptr == NULL
4089           || !*want_partial_unit_ptr))
4090     return;
4091
4092   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4093
4094   cu->list_in_scope = &file_symbols;
4095
4096   /* Allocate a new partial symbol table structure.  */
4097   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4098   if (attr == NULL || !DW_STRING (attr))
4099     filename = "";
4100   else
4101     filename = DW_STRING (attr);
4102   pst = start_psymtab_common (objfile, objfile->section_offsets,
4103                               filename,
4104                               /* TEXTLOW and TEXTHIGH are set below.  */
4105                               0,
4106                               objfile->global_psymbols.next,
4107                               objfile->static_psymbols.next);
4108   pst->psymtabs_addrmap_supported = 1;
4109
4110   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4111   if (attr != NULL)
4112     pst->dirname = DW_STRING (attr);
4113
4114   pst->read_symtab_private = per_cu;
4115
4116   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4117
4118   /* Store the function that reads in the rest of the symbol table.  */
4119   pst->read_symtab = dwarf2_psymtab_to_symtab;
4120
4121   per_cu->v.psymtab = pst;
4122
4123   dwarf2_find_base_address (comp_unit_die, cu);
4124
4125   /* Possibly set the default values of LOWPC and HIGHPC from
4126      `DW_AT_ranges'.  */
4127   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4128                                       &best_highpc, cu, pst);
4129   if (has_pc_info == 1 && best_lowpc < best_highpc)
4130     /* Store the contiguous range if it is not empty; it can be empty for
4131        CUs with no code.  */
4132     addrmap_set_empty (objfile->psymtabs_addrmap,
4133                        best_lowpc + baseaddr,
4134                        best_highpc + baseaddr - 1, pst);
4135
4136   /* Check if comp unit has_children.
4137      If so, read the rest of the partial symbols from this comp unit.
4138      If not, there's no more debug_info for this comp unit.  */
4139   if (has_children)
4140     {
4141       struct partial_die_info *first_die;
4142       CORE_ADDR lowpc, highpc;
4143
4144       lowpc = ((CORE_ADDR) -1);
4145       highpc = ((CORE_ADDR) 0);
4146
4147       first_die = load_partial_dies (reader, info_ptr, 1);
4148
4149       scan_partial_symbols (first_die, &lowpc, &highpc,
4150                             ! has_pc_info, cu);
4151
4152       /* If we didn't find a lowpc, set it to highpc to avoid
4153          complaints from `maint check'.  */
4154       if (lowpc == ((CORE_ADDR) -1))
4155         lowpc = highpc;
4156
4157       /* If the compilation unit didn't have an explicit address range,
4158          then use the information extracted from its child dies.  */
4159       if (! has_pc_info)
4160         {
4161           best_lowpc = lowpc;
4162           best_highpc = highpc;
4163         }
4164     }
4165   pst->textlow = best_lowpc + baseaddr;
4166   pst->texthigh = best_highpc + baseaddr;
4167
4168   pst->n_global_syms = objfile->global_psymbols.next -
4169     (objfile->global_psymbols.list + pst->globals_offset);
4170   pst->n_static_syms = objfile->static_psymbols.next -
4171     (objfile->static_psymbols.list + pst->statics_offset);
4172   sort_pst_symbols (pst);
4173
4174   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
4175     {
4176       int i;
4177       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4178       struct dwarf2_per_cu_data *iter;
4179
4180       /* Fill in 'dependencies' here; we fill in 'users' in a
4181          post-pass.  */
4182       pst->number_of_dependencies = len;
4183       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4184                                          len * sizeof (struct symtab *));
4185       for (i = 0;
4186            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
4187                         i, iter);
4188            ++i)
4189         pst->dependencies[i] = iter->v.psymtab;
4190
4191       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4192     }
4193
4194   if (per_cu->is_debug_types)
4195     {
4196       /* It's not clear we want to do anything with stmt lists here.
4197          Waiting to see what gcc ultimately does.  */
4198     }
4199   else
4200     {
4201       /* Get the list of files included in the current compilation unit,
4202          and build a psymtab for each of them.  */
4203       dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
4204     }
4205 }
4206
4207 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4208    Process compilation unit THIS_CU for a psymtab.  */
4209
4210 static void
4211 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
4212                            int want_partial_unit)
4213 {
4214   /* If this compilation unit was already read in, free the
4215      cached copy in order to read it in again.  This is
4216      necessary because we skipped some symbols when we first
4217      read in the compilation unit (see load_partial_dies).
4218      This problem could be avoided, but the benefit is unclear.  */
4219   if (this_cu->cu != NULL)
4220     free_one_cached_comp_unit (this_cu);
4221
4222   gdb_assert (! this_cu->is_debug_types);
4223   init_cutu_and_read_dies (this_cu, 0, 0, process_psymtab_comp_unit_reader,
4224                            &want_partial_unit);
4225
4226   /* Age out any secondary CUs.  */
4227   age_cached_comp_units ();
4228 }
4229
4230 /* Traversal function for htab_traverse_noresize.
4231    Process one .debug_types comp-unit.  */
4232
4233 static int
4234 process_psymtab_type_unit (void **slot, void *info)
4235 {
4236   struct signatured_type *sig_type = (struct signatured_type *) *slot;
4237   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
4238
4239   gdb_assert (per_cu->is_debug_types);
4240   gdb_assert (info == NULL);
4241
4242   /* If this compilation unit was already read in, free the
4243      cached copy in order to read it in again.  This is
4244      necessary because we skipped some symbols when we first
4245      read in the compilation unit (see load_partial_dies).
4246      This problem could be avoided, but the benefit is unclear.  */
4247   if (per_cu->cu != NULL)
4248     free_one_cached_comp_unit (per_cu);
4249
4250   init_cutu_and_read_dies (per_cu, 0, 0, process_psymtab_comp_unit_reader,
4251                            NULL);
4252
4253   /* Age out any secondary CUs.  */
4254   age_cached_comp_units ();
4255
4256   return 1;
4257 }
4258
4259 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4260    Build partial symbol tables for the .debug_types comp-units.  */
4261
4262 static void
4263 build_type_psymtabs (struct objfile *objfile)
4264 {
4265   if (! create_all_type_units (objfile))
4266     return;
4267
4268   htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
4269                           process_psymtab_type_unit, NULL);
4270 }
4271
4272 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
4273
4274 static void
4275 psymtabs_addrmap_cleanup (void *o)
4276 {
4277   struct objfile *objfile = o;
4278
4279   objfile->psymtabs_addrmap = NULL;
4280 }
4281
4282 /* Compute the 'user' field for each psymtab in OBJFILE.  */
4283
4284 static void
4285 set_partial_user (struct objfile *objfile)
4286 {
4287   int i;
4288
4289   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4290     {
4291       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4292       struct partial_symtab *pst = per_cu->v.psymtab;
4293       int j;
4294
4295       for (j = 0; j < pst->number_of_dependencies; ++j)
4296         {
4297           /* Set the 'user' field only if it is not already set.  */
4298           if (pst->dependencies[j]->user == NULL)
4299             pst->dependencies[j]->user = pst;
4300         }
4301     }
4302 }
4303
4304 /* Build the partial symbol table by doing a quick pass through the
4305    .debug_info and .debug_abbrev sections.  */
4306
4307 static void
4308 dwarf2_build_psymtabs_hard (struct objfile *objfile)
4309 {
4310   struct cleanup *back_to, *addrmap_cleanup;
4311   struct obstack temp_obstack;
4312   int i;
4313
4314   dwarf2_per_objfile->reading_partial_symbols = 1;
4315
4316   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
4317
4318   /* Any cached compilation units will be linked by the per-objfile
4319      read_in_chain.  Make sure to free them when we're done.  */
4320   back_to = make_cleanup (free_cached_comp_units, NULL);
4321
4322   build_type_psymtabs (objfile);
4323
4324   create_all_comp_units (objfile);
4325
4326   /* Create a temporary address map on a temporary obstack.  We later
4327      copy this to the final obstack.  */
4328   obstack_init (&temp_obstack);
4329   make_cleanup_obstack_free (&temp_obstack);
4330   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
4331   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
4332
4333   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4334     {
4335       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4336
4337       process_psymtab_comp_unit (per_cu, 0);
4338     }
4339
4340   set_partial_user (objfile);
4341
4342   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
4343                                                     &objfile->objfile_obstack);
4344   discard_cleanups (addrmap_cleanup);
4345
4346   do_cleanups (back_to);
4347 }
4348
4349 /* die_reader_func for load_partial_comp_unit.  */
4350
4351 static void
4352 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
4353                                gdb_byte *info_ptr,
4354                                struct die_info *comp_unit_die,
4355                                int has_children,
4356                                void *data)
4357 {
4358   struct dwarf2_cu *cu = reader->cu;
4359
4360   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4361
4362   /* Check if comp unit has_children.
4363      If so, read the rest of the partial symbols from this comp unit.
4364      If not, there's no more debug_info for this comp unit.  */
4365   if (has_children)
4366     load_partial_dies (reader, info_ptr, 0);
4367 }
4368
4369 /* Load the partial DIEs for a secondary CU into memory.
4370    This is also used when rereading a primary CU with load_all_dies.  */
4371
4372 static void
4373 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
4374 {
4375   init_cutu_and_read_dies (this_cu, 1, 1, load_partial_comp_unit_reader, NULL);
4376 }
4377
4378 /* Create a list of all compilation units in OBJFILE.
4379    This is only done for -readnow and building partial symtabs.  */
4380
4381 static void
4382 create_all_comp_units (struct objfile *objfile)
4383 {
4384   int n_allocated;
4385   int n_comp_units;
4386   struct dwarf2_per_cu_data **all_comp_units;
4387   gdb_byte *info_ptr;
4388
4389   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
4390   info_ptr = dwarf2_per_objfile->info.buffer;
4391
4392   n_comp_units = 0;
4393   n_allocated = 10;
4394   all_comp_units = xmalloc (n_allocated
4395                             * sizeof (struct dwarf2_per_cu_data *));
4396
4397   while (info_ptr < dwarf2_per_objfile->info.buffer
4398          + dwarf2_per_objfile->info.size)
4399     {
4400       unsigned int length, initial_length_size;
4401       struct dwarf2_per_cu_data *this_cu;
4402       sect_offset offset;
4403
4404       offset.sect_off = info_ptr - dwarf2_per_objfile->info.buffer;
4405
4406       /* Read just enough information to find out where the next
4407          compilation unit is.  */
4408       length = read_initial_length (objfile->obfd, info_ptr,
4409                                     &initial_length_size);
4410
4411       /* Save the compilation unit for later lookup.  */
4412       this_cu = obstack_alloc (&objfile->objfile_obstack,
4413                                sizeof (struct dwarf2_per_cu_data));
4414       memset (this_cu, 0, sizeof (*this_cu));
4415       this_cu->offset = offset;
4416       this_cu->length = length + initial_length_size;
4417       this_cu->objfile = objfile;
4418       this_cu->info_or_types_section = &dwarf2_per_objfile->info;
4419
4420       if (n_comp_units == n_allocated)
4421         {
4422           n_allocated *= 2;
4423           all_comp_units = xrealloc (all_comp_units,
4424                                      n_allocated
4425                                      * sizeof (struct dwarf2_per_cu_data *));
4426         }
4427       all_comp_units[n_comp_units++] = this_cu;
4428
4429       info_ptr = info_ptr + this_cu->length;
4430     }
4431
4432   dwarf2_per_objfile->all_comp_units
4433     = obstack_alloc (&objfile->objfile_obstack,
4434                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
4435   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
4436           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
4437   xfree (all_comp_units);
4438   dwarf2_per_objfile->n_comp_units = n_comp_units;
4439 }
4440
4441 /* Process all loaded DIEs for compilation unit CU, starting at
4442    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
4443    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
4444    DW_AT_ranges).  If NEED_PC is set, then this function will set
4445    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
4446    and record the covered ranges in the addrmap.  */
4447
4448 static void
4449 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
4450                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
4451 {
4452   struct partial_die_info *pdi;
4453
4454   /* Now, march along the PDI's, descending into ones which have
4455      interesting children but skipping the children of the other ones,
4456      until we reach the end of the compilation unit.  */
4457
4458   pdi = first_die;
4459
4460   while (pdi != NULL)
4461     {
4462       fixup_partial_die (pdi, cu);
4463
4464       /* Anonymous namespaces or modules have no name but have interesting
4465          children, so we need to look at them.  Ditto for anonymous
4466          enums.  */
4467
4468       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
4469           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
4470           || pdi->tag == DW_TAG_imported_unit)
4471         {
4472           switch (pdi->tag)
4473             {
4474             case DW_TAG_subprogram:
4475               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
4476               break;
4477             case DW_TAG_constant:
4478             case DW_TAG_variable:
4479             case DW_TAG_typedef:
4480             case DW_TAG_union_type:
4481               if (!pdi->is_declaration)
4482                 {
4483                   add_partial_symbol (pdi, cu);
4484                 }
4485               break;
4486             case DW_TAG_class_type:
4487             case DW_TAG_interface_type:
4488             case DW_TAG_structure_type:
4489               if (!pdi->is_declaration)
4490                 {
4491                   add_partial_symbol (pdi, cu);
4492                 }
4493               break;
4494             case DW_TAG_enumeration_type:
4495               if (!pdi->is_declaration)
4496                 add_partial_enumeration (pdi, cu);
4497               break;
4498             case DW_TAG_base_type:
4499             case DW_TAG_subrange_type:
4500               /* File scope base type definitions are added to the partial
4501                  symbol table.  */
4502               add_partial_symbol (pdi, cu);
4503               break;
4504             case DW_TAG_namespace:
4505               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
4506               break;
4507             case DW_TAG_module:
4508               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
4509               break;
4510             case DW_TAG_imported_unit:
4511               {
4512                 struct dwarf2_per_cu_data *per_cu;
4513
4514                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
4515                                                            cu->objfile);
4516
4517                 /* Go read the partial unit, if needed.  */
4518                 if (per_cu->v.psymtab == NULL)
4519                   process_psymtab_comp_unit (per_cu, 1);
4520
4521                 VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
4522                                per_cu);
4523               }
4524               break;
4525             default:
4526               break;
4527             }
4528         }
4529
4530       /* If the die has a sibling, skip to the sibling.  */
4531
4532       pdi = pdi->die_sibling;
4533     }
4534 }
4535
4536 /* Functions used to compute the fully scoped name of a partial DIE.
4537
4538    Normally, this is simple.  For C++, the parent DIE's fully scoped
4539    name is concatenated with "::" and the partial DIE's name.  For
4540    Java, the same thing occurs except that "." is used instead of "::".
4541    Enumerators are an exception; they use the scope of their parent
4542    enumeration type, i.e. the name of the enumeration type is not
4543    prepended to the enumerator.
4544
4545    There are two complexities.  One is DW_AT_specification; in this
4546    case "parent" means the parent of the target of the specification,
4547    instead of the direct parent of the DIE.  The other is compilers
4548    which do not emit DW_TAG_namespace; in this case we try to guess
4549    the fully qualified name of structure types from their members'
4550    linkage names.  This must be done using the DIE's children rather
4551    than the children of any DW_AT_specification target.  We only need
4552    to do this for structures at the top level, i.e. if the target of
4553    any DW_AT_specification (if any; otherwise the DIE itself) does not
4554    have a parent.  */
4555
4556 /* Compute the scope prefix associated with PDI's parent, in
4557    compilation unit CU.  The result will be allocated on CU's
4558    comp_unit_obstack, or a copy of the already allocated PDI->NAME
4559    field.  NULL is returned if no prefix is necessary.  */
4560 static char *
4561 partial_die_parent_scope (struct partial_die_info *pdi,
4562                           struct dwarf2_cu *cu)
4563 {
4564   char *grandparent_scope;
4565   struct partial_die_info *parent, *real_pdi;
4566
4567   /* We need to look at our parent DIE; if we have a DW_AT_specification,
4568      then this means the parent of the specification DIE.  */
4569
4570   real_pdi = pdi;
4571   while (real_pdi->has_specification)
4572     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
4573
4574   parent = real_pdi->die_parent;
4575   if (parent == NULL)
4576     return NULL;
4577
4578   if (parent->scope_set)
4579     return parent->scope;
4580
4581   fixup_partial_die (parent, cu);
4582
4583   grandparent_scope = partial_die_parent_scope (parent, cu);
4584
4585   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
4586      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
4587      Work around this problem here.  */
4588   if (cu->language == language_cplus
4589       && parent->tag == DW_TAG_namespace
4590       && strcmp (parent->name, "::") == 0
4591       && grandparent_scope == NULL)
4592     {
4593       parent->scope = NULL;
4594       parent->scope_set = 1;
4595       return NULL;
4596     }
4597
4598   if (pdi->tag == DW_TAG_enumerator)
4599     /* Enumerators should not get the name of the enumeration as a prefix.  */
4600     parent->scope = grandparent_scope;
4601   else if (parent->tag == DW_TAG_namespace
4602       || parent->tag == DW_TAG_module
4603       || parent->tag == DW_TAG_structure_type
4604       || parent->tag == DW_TAG_class_type
4605       || parent->tag == DW_TAG_interface_type
4606       || parent->tag == DW_TAG_union_type
4607       || parent->tag == DW_TAG_enumeration_type)
4608     {
4609       if (grandparent_scope == NULL)
4610         parent->scope = parent->name;
4611       else
4612         parent->scope = typename_concat (&cu->comp_unit_obstack,
4613                                          grandparent_scope,
4614                                          parent->name, 0, cu);
4615     }
4616   else
4617     {
4618       /* FIXME drow/2004-04-01: What should we be doing with
4619          function-local names?  For partial symbols, we should probably be
4620          ignoring them.  */
4621       complaint (&symfile_complaints,
4622                  _("unhandled containing DIE tag %d for DIE at %d"),
4623                  parent->tag, pdi->offset.sect_off);
4624       parent->scope = grandparent_scope;
4625     }
4626
4627   parent->scope_set = 1;
4628   return parent->scope;
4629 }
4630
4631 /* Return the fully scoped name associated with PDI, from compilation unit
4632    CU.  The result will be allocated with malloc.  */
4633
4634 static char *
4635 partial_die_full_name (struct partial_die_info *pdi,
4636                        struct dwarf2_cu *cu)
4637 {
4638   char *parent_scope;
4639
4640   /* If this is a template instantiation, we can not work out the
4641      template arguments from partial DIEs.  So, unfortunately, we have
4642      to go through the full DIEs.  At least any work we do building
4643      types here will be reused if full symbols are loaded later.  */
4644   if (pdi->has_template_arguments)
4645     {
4646       fixup_partial_die (pdi, cu);
4647
4648       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
4649         {
4650           struct die_info *die;
4651           struct attribute attr;
4652           struct dwarf2_cu *ref_cu = cu;
4653
4654           /* DW_FORM_ref_addr is using section offset.  */
4655           attr.name = 0;
4656           attr.form = DW_FORM_ref_addr;
4657           attr.u.unsnd = pdi->offset.sect_off;
4658           die = follow_die_ref (NULL, &attr, &ref_cu);
4659
4660           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
4661         }
4662     }
4663
4664   parent_scope = partial_die_parent_scope (pdi, cu);
4665   if (parent_scope == NULL)
4666     return NULL;
4667   else
4668     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
4669 }
4670
4671 static void
4672 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
4673 {
4674   struct objfile *objfile = cu->objfile;
4675   CORE_ADDR addr = 0;
4676   char *actual_name = NULL;
4677   CORE_ADDR baseaddr;
4678   int built_actual_name = 0;
4679
4680   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4681
4682   actual_name = partial_die_full_name (pdi, cu);
4683   if (actual_name)
4684     built_actual_name = 1;
4685
4686   if (actual_name == NULL)
4687     actual_name = pdi->name;
4688
4689   switch (pdi->tag)
4690     {
4691     case DW_TAG_subprogram:
4692       if (pdi->is_external || cu->language == language_ada)
4693         {
4694           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
4695              of the global scope.  But in Ada, we want to be able to access
4696              nested procedures globally.  So all Ada subprograms are stored
4697              in the global scope.  */
4698           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
4699              mst_text, objfile); */
4700           add_psymbol_to_list (actual_name, strlen (actual_name),
4701                                built_actual_name,
4702                                VAR_DOMAIN, LOC_BLOCK,
4703                                &objfile->global_psymbols,
4704                                0, pdi->lowpc + baseaddr,
4705                                cu->language, objfile);
4706         }
4707       else
4708         {
4709           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
4710              mst_file_text, objfile); */
4711           add_psymbol_to_list (actual_name, strlen (actual_name),
4712                                built_actual_name,
4713                                VAR_DOMAIN, LOC_BLOCK,
4714                                &objfile->static_psymbols,
4715                                0, pdi->lowpc + baseaddr,
4716                                cu->language, objfile);
4717         }
4718       break;
4719     case DW_TAG_constant:
4720       {
4721         struct psymbol_allocation_list *list;
4722
4723         if (pdi->is_external)
4724           list = &objfile->global_psymbols;
4725         else
4726           list = &objfile->static_psymbols;
4727         add_psymbol_to_list (actual_name, strlen (actual_name),
4728                              built_actual_name, VAR_DOMAIN, LOC_STATIC,
4729                              list, 0, 0, cu->language, objfile);
4730       }
4731       break;
4732     case DW_TAG_variable:
4733       if (pdi->d.locdesc)
4734         addr = decode_locdesc (pdi->d.locdesc, cu);
4735
4736       if (pdi->d.locdesc
4737           && addr == 0
4738           && !dwarf2_per_objfile->has_section_at_zero)
4739         {
4740           /* A global or static variable may also have been stripped
4741              out by the linker if unused, in which case its address
4742              will be nullified; do not add such variables into partial
4743              symbol table then.  */
4744         }
4745       else if (pdi->is_external)
4746         {
4747           /* Global Variable.
4748              Don't enter into the minimal symbol tables as there is
4749              a minimal symbol table entry from the ELF symbols already.
4750              Enter into partial symbol table if it has a location
4751              descriptor or a type.
4752              If the location descriptor is missing, new_symbol will create
4753              a LOC_UNRESOLVED symbol, the address of the variable will then
4754              be determined from the minimal symbol table whenever the variable
4755              is referenced.
4756              The address for the partial symbol table entry is not
4757              used by GDB, but it comes in handy for debugging partial symbol
4758              table building.  */
4759
4760           if (pdi->d.locdesc || pdi->has_type)
4761             add_psymbol_to_list (actual_name, strlen (actual_name),
4762                                  built_actual_name,
4763                                  VAR_DOMAIN, LOC_STATIC,
4764                                  &objfile->global_psymbols,
4765                                  0, addr + baseaddr,
4766                                  cu->language, objfile);
4767         }
4768       else
4769         {
4770           /* Static Variable.  Skip symbols without location descriptors.  */
4771           if (pdi->d.locdesc == NULL)
4772             {
4773               if (built_actual_name)
4774                 xfree (actual_name);
4775               return;
4776             }
4777           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
4778              mst_file_data, objfile); */
4779           add_psymbol_to_list (actual_name, strlen (actual_name),
4780                                built_actual_name,
4781                                VAR_DOMAIN, LOC_STATIC,
4782                                &objfile->static_psymbols,
4783                                0, addr + baseaddr,
4784                                cu->language, objfile);
4785         }
4786       break;
4787     case DW_TAG_typedef:
4788     case DW_TAG_base_type:
4789     case DW_TAG_subrange_type:
4790       add_psymbol_to_list (actual_name, strlen (actual_name),
4791                            built_actual_name,
4792                            VAR_DOMAIN, LOC_TYPEDEF,
4793                            &objfile->static_psymbols,
4794                            0, (CORE_ADDR) 0, cu->language, objfile);
4795       break;
4796     case DW_TAG_namespace:
4797       add_psymbol_to_list (actual_name, strlen (actual_name),
4798                            built_actual_name,
4799                            VAR_DOMAIN, LOC_TYPEDEF,
4800                            &objfile->global_psymbols,
4801                            0, (CORE_ADDR) 0, cu->language, objfile);
4802       break;
4803     case DW_TAG_class_type:
4804     case DW_TAG_interface_type:
4805     case DW_TAG_structure_type:
4806     case DW_TAG_union_type:
4807     case DW_TAG_enumeration_type:
4808       /* Skip external references.  The DWARF standard says in the section
4809          about "Structure, Union, and Class Type Entries": "An incomplete
4810          structure, union or class type is represented by a structure,
4811          union or class entry that does not have a byte size attribute
4812          and that has a DW_AT_declaration attribute."  */
4813       if (!pdi->has_byte_size && pdi->is_declaration)
4814         {
4815           if (built_actual_name)
4816             xfree (actual_name);
4817           return;
4818         }
4819
4820       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
4821          static vs. global.  */
4822       add_psymbol_to_list (actual_name, strlen (actual_name),
4823                            built_actual_name,
4824                            STRUCT_DOMAIN, LOC_TYPEDEF,
4825                            (cu->language == language_cplus
4826                             || cu->language == language_java)
4827                            ? &objfile->global_psymbols
4828                            : &objfile->static_psymbols,
4829                            0, (CORE_ADDR) 0, cu->language, objfile);
4830
4831       break;
4832     case DW_TAG_enumerator:
4833       add_psymbol_to_list (actual_name, strlen (actual_name),
4834                            built_actual_name,
4835                            VAR_DOMAIN, LOC_CONST,
4836                            (cu->language == language_cplus
4837                             || cu->language == language_java)
4838                            ? &objfile->global_psymbols
4839                            : &objfile->static_psymbols,
4840                            0, (CORE_ADDR) 0, cu->language, objfile);
4841       break;
4842     default:
4843       break;
4844     }
4845
4846   if (built_actual_name)
4847     xfree (actual_name);
4848 }
4849
4850 /* Read a partial die corresponding to a namespace; also, add a symbol
4851    corresponding to that namespace to the symbol table.  NAMESPACE is
4852    the name of the enclosing namespace.  */
4853
4854 static void
4855 add_partial_namespace (struct partial_die_info *pdi,
4856                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
4857                        int need_pc, struct dwarf2_cu *cu)
4858 {
4859   /* Add a symbol for the namespace.  */
4860
4861   add_partial_symbol (pdi, cu);
4862
4863   /* Now scan partial symbols in that namespace.  */
4864
4865   if (pdi->has_children)
4866     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
4867 }
4868
4869 /* Read a partial die corresponding to a Fortran module.  */
4870
4871 static void
4872 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
4873                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
4874 {
4875   /* Now scan partial symbols in that module.  */
4876
4877   if (pdi->has_children)
4878     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
4879 }
4880
4881 /* Read a partial die corresponding to a subprogram and create a partial
4882    symbol for that subprogram.  When the CU language allows it, this
4883    routine also defines a partial symbol for each nested subprogram
4884    that this subprogram contains.
4885
4886    DIE my also be a lexical block, in which case we simply search
4887    recursively for suprograms defined inside that lexical block.
4888    Again, this is only performed when the CU language allows this
4889    type of definitions.  */
4890
4891 static void
4892 add_partial_subprogram (struct partial_die_info *pdi,
4893                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
4894                         int need_pc, struct dwarf2_cu *cu)
4895 {
4896   if (pdi->tag == DW_TAG_subprogram)
4897     {
4898       if (pdi->has_pc_info)
4899         {
4900           if (pdi->lowpc < *lowpc)
4901             *lowpc = pdi->lowpc;
4902           if (pdi->highpc > *highpc)
4903             *highpc = pdi->highpc;
4904           if (need_pc)
4905             {
4906               CORE_ADDR baseaddr;
4907               struct objfile *objfile = cu->objfile;
4908
4909               baseaddr = ANOFFSET (objfile->section_offsets,
4910                                    SECT_OFF_TEXT (objfile));
4911               addrmap_set_empty (objfile->psymtabs_addrmap,
4912                                  pdi->lowpc + baseaddr,
4913                                  pdi->highpc - 1 + baseaddr,
4914                                  cu->per_cu->v.psymtab);
4915             }
4916         }
4917
4918       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
4919         {
4920           if (!pdi->is_declaration)
4921             /* Ignore subprogram DIEs that do not have a name, they are
4922                illegal.  Do not emit a complaint at this point, we will
4923                do so when we convert this psymtab into a symtab.  */
4924             if (pdi->name)
4925               add_partial_symbol (pdi, cu);
4926         }
4927     }
4928
4929   if (! pdi->has_children)
4930     return;
4931
4932   if (cu->language == language_ada)
4933     {
4934       pdi = pdi->die_child;
4935       while (pdi != NULL)
4936         {
4937           fixup_partial_die (pdi, cu);
4938           if (pdi->tag == DW_TAG_subprogram
4939               || pdi->tag == DW_TAG_lexical_block)
4940             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
4941           pdi = pdi->die_sibling;
4942         }
4943     }
4944 }
4945
4946 /* Read a partial die corresponding to an enumeration type.  */
4947
4948 static void
4949 add_partial_enumeration (struct partial_die_info *enum_pdi,
4950                          struct dwarf2_cu *cu)
4951 {
4952   struct partial_die_info *pdi;
4953
4954   if (enum_pdi->name != NULL)
4955     add_partial_symbol (enum_pdi, cu);
4956
4957   pdi = enum_pdi->die_child;
4958   while (pdi)
4959     {
4960       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
4961         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
4962       else
4963         add_partial_symbol (pdi, cu);
4964       pdi = pdi->die_sibling;
4965     }
4966 }
4967
4968 /* Return the initial uleb128 in the die at INFO_PTR.  */
4969
4970 static unsigned int
4971 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
4972 {
4973   unsigned int bytes_read;
4974
4975   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
4976 }
4977
4978 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
4979    Return the corresponding abbrev, or NULL if the number is zero (indicating
4980    an empty DIE).  In either case *BYTES_READ will be set to the length of
4981    the initial number.  */
4982
4983 static struct abbrev_info *
4984 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
4985                  struct dwarf2_cu *cu)
4986 {
4987   bfd *abfd = cu->objfile->obfd;
4988   unsigned int abbrev_number;
4989   struct abbrev_info *abbrev;
4990
4991   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
4992
4993   if (abbrev_number == 0)
4994     return NULL;
4995
4996   abbrev = dwarf2_lookup_abbrev (abbrev_number, cu);
4997   if (!abbrev)
4998     {
4999       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
5000              abbrev_number, bfd_get_filename (abfd));
5001     }
5002
5003   return abbrev;
5004 }
5005
5006 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5007    Returns a pointer to the end of a series of DIEs, terminated by an empty
5008    DIE.  Any children of the skipped DIEs will also be skipped.  */
5009
5010 static gdb_byte *
5011 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
5012 {
5013   struct dwarf2_cu *cu = reader->cu;
5014   struct abbrev_info *abbrev;
5015   unsigned int bytes_read;
5016
5017   while (1)
5018     {
5019       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
5020       if (abbrev == NULL)
5021         return info_ptr + bytes_read;
5022       else
5023         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
5024     }
5025 }
5026
5027 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5028    INFO_PTR should point just after the initial uleb128 of a DIE, and the
5029    abbrev corresponding to that skipped uleb128 should be passed in
5030    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
5031    children.  */
5032
5033 static gdb_byte *
5034 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
5035               struct abbrev_info *abbrev)
5036 {
5037   unsigned int bytes_read;
5038   struct attribute attr;
5039   bfd *abfd = reader->abfd;
5040   struct dwarf2_cu *cu = reader->cu;
5041   gdb_byte *buffer = reader->buffer;
5042   const gdb_byte *buffer_end = reader->buffer_end;
5043   gdb_byte *start_info_ptr = info_ptr;
5044   unsigned int form, i;
5045
5046   for (i = 0; i < abbrev->num_attrs; i++)
5047     {
5048       /* The only abbrev we care about is DW_AT_sibling.  */
5049       if (abbrev->attrs[i].name == DW_AT_sibling)
5050         {
5051           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
5052           if (attr.form == DW_FORM_ref_addr)
5053             complaint (&symfile_complaints,
5054                        _("ignoring absolute DW_AT_sibling"));
5055           else
5056             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
5057         }
5058
5059       /* If it isn't DW_AT_sibling, skip this attribute.  */
5060       form = abbrev->attrs[i].form;
5061     skip_attribute:
5062       switch (form)
5063         {
5064         case DW_FORM_ref_addr:
5065           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
5066              and later it is offset sized.  */
5067           if (cu->header.version == 2)
5068             info_ptr += cu->header.addr_size;
5069           else
5070             info_ptr += cu->header.offset_size;
5071           break;
5072         case DW_FORM_addr:
5073           info_ptr += cu->header.addr_size;
5074           break;
5075         case DW_FORM_data1:
5076         case DW_FORM_ref1:
5077         case DW_FORM_flag:
5078           info_ptr += 1;
5079           break;
5080         case DW_FORM_flag_present:
5081           break;
5082         case DW_FORM_data2:
5083         case DW_FORM_ref2:
5084           info_ptr += 2;
5085           break;
5086         case DW_FORM_data4:
5087         case DW_FORM_ref4:
5088           info_ptr += 4;
5089           break;
5090         case DW_FORM_data8:
5091         case DW_FORM_ref8:
5092         case DW_FORM_ref_sig8:
5093           info_ptr += 8;
5094           break;
5095         case DW_FORM_string:
5096           read_direct_string (abfd, info_ptr, &bytes_read);
5097           info_ptr += bytes_read;
5098           break;
5099         case DW_FORM_sec_offset:
5100         case DW_FORM_strp:
5101           info_ptr += cu->header.offset_size;
5102           break;
5103         case DW_FORM_exprloc:
5104         case DW_FORM_block:
5105           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5106           info_ptr += bytes_read;
5107           break;
5108         case DW_FORM_block1:
5109           info_ptr += 1 + read_1_byte (abfd, info_ptr);
5110           break;
5111         case DW_FORM_block2:
5112           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
5113           break;
5114         case DW_FORM_block4:
5115           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
5116           break;
5117         case DW_FORM_sdata:
5118         case DW_FORM_udata:
5119         case DW_FORM_ref_udata:
5120         case DW_FORM_GNU_addr_index:
5121         case DW_FORM_GNU_str_index:
5122           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
5123           break;
5124         case DW_FORM_indirect:
5125           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5126           info_ptr += bytes_read;
5127           /* We need to continue parsing from here, so just go back to
5128              the top.  */
5129           goto skip_attribute;
5130
5131         default:
5132           error (_("Dwarf Error: Cannot handle %s "
5133                    "in DWARF reader [in module %s]"),
5134                  dwarf_form_name (form),
5135                  bfd_get_filename (abfd));
5136         }
5137     }
5138
5139   if (abbrev->has_children)
5140     return skip_children (reader, info_ptr);
5141   else
5142     return info_ptr;
5143 }
5144
5145 /* Locate ORIG_PDI's sibling.
5146    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
5147
5148 static gdb_byte *
5149 locate_pdi_sibling (const struct die_reader_specs *reader,
5150                     struct partial_die_info *orig_pdi,
5151                     gdb_byte *info_ptr)
5152 {
5153   /* Do we know the sibling already?  */
5154
5155   if (orig_pdi->sibling)
5156     return orig_pdi->sibling;
5157
5158   /* Are there any children to deal with?  */
5159
5160   if (!orig_pdi->has_children)
5161     return info_ptr;
5162
5163   /* Skip the children the long way.  */
5164
5165   return skip_children (reader, info_ptr);
5166 }
5167
5168 /* Expand this partial symbol table into a full symbol table.  */
5169
5170 static void
5171 dwarf2_psymtab_to_symtab (struct partial_symtab *pst)
5172 {
5173   if (pst != NULL)
5174     {
5175       if (pst->readin)
5176         {
5177           warning (_("bug: psymtab for %s is already read in."),
5178                    pst->filename);
5179         }
5180       else
5181         {
5182           if (info_verbose)
5183             {
5184               printf_filtered (_("Reading in symbols for %s..."),
5185                                pst->filename);
5186               gdb_flush (gdb_stdout);
5187             }
5188
5189           /* Restore our global data.  */
5190           dwarf2_per_objfile = objfile_data (pst->objfile,
5191                                              dwarf2_objfile_data_key);
5192
5193           /* If this psymtab is constructed from a debug-only objfile, the
5194              has_section_at_zero flag will not necessarily be correct.  We
5195              can get the correct value for this flag by looking at the data
5196              associated with the (presumably stripped) associated objfile.  */
5197           if (pst->objfile->separate_debug_objfile_backlink)
5198             {
5199               struct dwarf2_per_objfile *dpo_backlink
5200                 = objfile_data (pst->objfile->separate_debug_objfile_backlink,
5201                                 dwarf2_objfile_data_key);
5202
5203               dwarf2_per_objfile->has_section_at_zero
5204                 = dpo_backlink->has_section_at_zero;
5205             }
5206
5207           dwarf2_per_objfile->reading_partial_symbols = 0;
5208
5209           psymtab_to_symtab_1 (pst);
5210
5211           /* Finish up the debug error message.  */
5212           if (info_verbose)
5213             printf_filtered (_("done.\n"));
5214         }
5215     }
5216
5217   process_cu_includes ();
5218 }
5219 \f
5220 /* Reading in full CUs.  */
5221
5222 /* Add PER_CU to the queue.  */
5223
5224 static void
5225 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
5226                  enum language pretend_language)
5227 {
5228   struct dwarf2_queue_item *item;
5229
5230   per_cu->queued = 1;
5231   item = xmalloc (sizeof (*item));
5232   item->per_cu = per_cu;
5233   item->pretend_language = pretend_language;
5234   item->next = NULL;
5235
5236   if (dwarf2_queue == NULL)
5237     dwarf2_queue = item;
5238   else
5239     dwarf2_queue_tail->next = item;
5240
5241   dwarf2_queue_tail = item;
5242 }
5243
5244 /* Process the queue.  */
5245
5246 static void
5247 process_queue (void)
5248 {
5249   struct dwarf2_queue_item *item, *next_item;
5250
5251   /* The queue starts out with one item, but following a DIE reference
5252      may load a new CU, adding it to the end of the queue.  */
5253   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
5254     {
5255       if (dwarf2_per_objfile->using_index
5256           ? !item->per_cu->v.quick->symtab
5257           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
5258         process_full_comp_unit (item->per_cu, item->pretend_language);
5259
5260       item->per_cu->queued = 0;
5261       next_item = item->next;
5262       xfree (item);
5263     }
5264
5265   dwarf2_queue_tail = NULL;
5266 }
5267
5268 /* Free all allocated queue entries.  This function only releases anything if
5269    an error was thrown; if the queue was processed then it would have been
5270    freed as we went along.  */
5271
5272 static void
5273 dwarf2_release_queue (void *dummy)
5274 {
5275   struct dwarf2_queue_item *item, *last;
5276
5277   item = dwarf2_queue;
5278   while (item)
5279     {
5280       /* Anything still marked queued is likely to be in an
5281          inconsistent state, so discard it.  */
5282       if (item->per_cu->queued)
5283         {
5284           if (item->per_cu->cu != NULL)
5285             free_one_cached_comp_unit (item->per_cu);
5286           item->per_cu->queued = 0;
5287         }
5288
5289       last = item;
5290       item = item->next;
5291       xfree (last);
5292     }
5293
5294   dwarf2_queue = dwarf2_queue_tail = NULL;
5295 }
5296
5297 /* Read in full symbols for PST, and anything it depends on.  */
5298
5299 static void
5300 psymtab_to_symtab_1 (struct partial_symtab *pst)
5301 {
5302   struct dwarf2_per_cu_data *per_cu;
5303   int i;
5304
5305   if (pst->readin)
5306     return;
5307
5308   for (i = 0; i < pst->number_of_dependencies; i++)
5309     if (!pst->dependencies[i]->readin
5310         && pst->dependencies[i]->user == NULL)
5311       {
5312         /* Inform about additional files that need to be read in.  */
5313         if (info_verbose)
5314           {
5315             /* FIXME: i18n: Need to make this a single string.  */
5316             fputs_filtered (" ", gdb_stdout);
5317             wrap_here ("");
5318             fputs_filtered ("and ", gdb_stdout);
5319             wrap_here ("");
5320             printf_filtered ("%s...", pst->dependencies[i]->filename);
5321             wrap_here ("");     /* Flush output.  */
5322             gdb_flush (gdb_stdout);
5323           }
5324         psymtab_to_symtab_1 (pst->dependencies[i]);
5325       }
5326
5327   per_cu = pst->read_symtab_private;
5328
5329   if (per_cu == NULL)
5330     {
5331       /* It's an include file, no symbols to read for it.
5332          Everything is in the parent symtab.  */
5333       pst->readin = 1;
5334       return;
5335     }
5336
5337   dw2_do_instantiate_symtab (per_cu);
5338 }
5339
5340 /* Trivial hash function for die_info: the hash value of a DIE
5341    is its offset in .debug_info for this objfile.  */
5342
5343 static hashval_t
5344 die_hash (const void *item)
5345 {
5346   const struct die_info *die = item;
5347
5348   return die->offset.sect_off;
5349 }
5350
5351 /* Trivial comparison function for die_info structures: two DIEs
5352    are equal if they have the same offset.  */
5353
5354 static int
5355 die_eq (const void *item_lhs, const void *item_rhs)
5356 {
5357   const struct die_info *die_lhs = item_lhs;
5358   const struct die_info *die_rhs = item_rhs;
5359
5360   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
5361 }
5362
5363 /* die_reader_func for load_full_comp_unit.
5364    This is identical to read_signatured_type_reader,
5365    but is kept separate for now.  */
5366
5367 static void
5368 load_full_comp_unit_reader (const struct die_reader_specs *reader,
5369                             gdb_byte *info_ptr,
5370                             struct die_info *comp_unit_die,
5371                             int has_children,
5372                             void *data)
5373 {
5374   struct dwarf2_cu *cu = reader->cu;
5375   enum language *language_ptr = data;
5376
5377   gdb_assert (cu->die_hash == NULL);
5378   cu->die_hash =
5379     htab_create_alloc_ex (cu->header.length / 12,
5380                           die_hash,
5381                           die_eq,
5382                           NULL,
5383                           &cu->comp_unit_obstack,
5384                           hashtab_obstack_allocate,
5385                           dummy_obstack_deallocate);
5386
5387   if (has_children)
5388     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
5389                                                   &info_ptr, comp_unit_die);
5390   cu->dies = comp_unit_die;
5391   /* comp_unit_die is not stored in die_hash, no need.  */
5392
5393   /* We try not to read any attributes in this function, because not
5394      all CUs needed for references have been loaded yet, and symbol
5395      table processing isn't initialized.  But we have to set the CU language,
5396      or we won't be able to build types correctly.
5397      Similarly, if we do not read the producer, we can not apply
5398      producer-specific interpretation.  */
5399   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
5400 }
5401
5402 /* Load the DIEs associated with PER_CU into memory.  */
5403
5404 static void
5405 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
5406                      enum language pretend_language)
5407 {
5408   gdb_assert (! this_cu->is_debug_types);
5409
5410   init_cutu_and_read_dies (this_cu, 1, 1, load_full_comp_unit_reader,
5411                            &pretend_language);
5412 }
5413
5414 /* Add a DIE to the delayed physname list.  */
5415
5416 static void
5417 add_to_method_list (struct type *type, int fnfield_index, int index,
5418                     const char *name, struct die_info *die,
5419                     struct dwarf2_cu *cu)
5420 {
5421   struct delayed_method_info mi;
5422   mi.type = type;
5423   mi.fnfield_index = fnfield_index;
5424   mi.index = index;
5425   mi.name = name;
5426   mi.die = die;
5427   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
5428 }
5429
5430 /* A cleanup for freeing the delayed method list.  */
5431
5432 static void
5433 free_delayed_list (void *ptr)
5434 {
5435   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
5436   if (cu->method_list != NULL)
5437     {
5438       VEC_free (delayed_method_info, cu->method_list);
5439       cu->method_list = NULL;
5440     }
5441 }
5442
5443 /* Compute the physnames of any methods on the CU's method list.
5444
5445    The computation of method physnames is delayed in order to avoid the
5446    (bad) condition that one of the method's formal parameters is of an as yet
5447    incomplete type.  */
5448
5449 static void
5450 compute_delayed_physnames (struct dwarf2_cu *cu)
5451 {
5452   int i;
5453   struct delayed_method_info *mi;
5454   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
5455     {
5456       const char *physname;
5457       struct fn_fieldlist *fn_flp
5458         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
5459       physname = dwarf2_physname ((char *) mi->name, mi->die, cu);
5460       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
5461     }
5462 }
5463
5464 /* Go objects should be embedded in a DW_TAG_module DIE,
5465    and it's not clear if/how imported objects will appear.
5466    To keep Go support simple until that's worked out,
5467    go back through what we've read and create something usable.
5468    We could do this while processing each DIE, and feels kinda cleaner,
5469    but that way is more invasive.
5470    This is to, for example, allow the user to type "p var" or "b main"
5471    without having to specify the package name, and allow lookups
5472    of module.object to work in contexts that use the expression
5473    parser.  */
5474
5475 static void
5476 fixup_go_packaging (struct dwarf2_cu *cu)
5477 {
5478   char *package_name = NULL;
5479   struct pending *list;
5480   int i;
5481
5482   for (list = global_symbols; list != NULL; list = list->next)
5483     {
5484       for (i = 0; i < list->nsyms; ++i)
5485         {
5486           struct symbol *sym = list->symbol[i];
5487
5488           if (SYMBOL_LANGUAGE (sym) == language_go
5489               && SYMBOL_CLASS (sym) == LOC_BLOCK)
5490             {
5491               char *this_package_name = go_symbol_package_name (sym);
5492
5493               if (this_package_name == NULL)
5494                 continue;
5495               if (package_name == NULL)
5496                 package_name = this_package_name;
5497               else
5498                 {
5499                   if (strcmp (package_name, this_package_name) != 0)
5500                     complaint (&symfile_complaints,
5501                                _("Symtab %s has objects from two different Go packages: %s and %s"),
5502                                (sym->symtab && sym->symtab->filename
5503                                 ? sym->symtab->filename
5504                                 : cu->objfile->name),
5505                                this_package_name, package_name);
5506                   xfree (this_package_name);
5507                 }
5508             }
5509         }
5510     }
5511
5512   if (package_name != NULL)
5513     {
5514       struct objfile *objfile = cu->objfile;
5515       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
5516                                      package_name, objfile);
5517       struct symbol *sym;
5518
5519       TYPE_TAG_NAME (type) = TYPE_NAME (type);
5520
5521       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
5522       SYMBOL_SET_LANGUAGE (sym, language_go);
5523       SYMBOL_SET_NAMES (sym, package_name, strlen (package_name), 1, objfile);
5524       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
5525          e.g., "main" finds the "main" module and not C's main().  */
5526       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
5527       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
5528       SYMBOL_TYPE (sym) = type;
5529
5530       add_symbol_to_list (sym, &global_symbols);
5531
5532       xfree (package_name);
5533     }
5534 }
5535
5536 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
5537
5538 /* Return the symtab for PER_CU.  This works properly regardless of
5539    whether we're using the index or psymtabs.  */
5540
5541 static struct symtab *
5542 get_symtab (struct dwarf2_per_cu_data *per_cu)
5543 {
5544   return (dwarf2_per_objfile->using_index
5545           ? per_cu->v.quick->symtab
5546           : per_cu->v.psymtab->symtab);
5547 }
5548
5549 /* A helper function for computing the list of all symbol tables
5550    included by PER_CU.  */
5551
5552 static void
5553 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
5554                                 htab_t all_children,
5555                                 struct dwarf2_per_cu_data *per_cu)
5556 {
5557   void **slot;
5558   int ix;
5559   struct dwarf2_per_cu_data *iter;
5560
5561   slot = htab_find_slot (all_children, per_cu, INSERT);
5562   if (*slot != NULL)
5563     {
5564       /* This inclusion and its children have been processed.  */
5565       return;
5566     }
5567
5568   *slot = per_cu;
5569   /* Only add a CU if it has a symbol table.  */
5570   if (get_symtab (per_cu) != NULL)
5571     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
5572
5573   for (ix = 0;
5574        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
5575        ++ix)
5576     recursively_compute_inclusions (result, all_children, iter);
5577 }
5578
5579 /* Compute the symtab 'includes' fields for the symtab related to
5580    PER_CU.  */
5581
5582 static void
5583 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
5584 {
5585   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
5586     {
5587       int ix, len;
5588       struct dwarf2_per_cu_data *iter;
5589       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
5590       htab_t all_children;
5591       struct symtab *symtab = get_symtab (per_cu);
5592
5593       /* If we don't have a symtab, we can just skip this case.  */
5594       if (symtab == NULL)
5595         return;
5596
5597       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
5598                                         NULL, xcalloc, xfree);
5599
5600       for (ix = 0;
5601            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
5602                         ix, iter);
5603            ++ix)
5604         recursively_compute_inclusions (&result_children, all_children, iter);
5605
5606       /* Now we have a transitive closure of all the included CUs, so
5607          we can convert it to a list of symtabs.  */
5608       len = VEC_length (dwarf2_per_cu_ptr, result_children);
5609       symtab->includes
5610         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
5611                          (len + 1) * sizeof (struct symtab *));
5612       for (ix = 0;
5613            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
5614            ++ix)
5615         symtab->includes[ix] = get_symtab (iter);
5616       symtab->includes[len] = NULL;
5617
5618       VEC_free (dwarf2_per_cu_ptr, result_children);
5619       htab_delete (all_children);
5620     }
5621 }
5622
5623 /* Compute the 'includes' field for the symtabs of all the CUs we just
5624    read.  */
5625
5626 static void
5627 process_cu_includes (void)
5628 {
5629   int ix;
5630   struct dwarf2_per_cu_data *iter;
5631
5632   for (ix = 0;
5633        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
5634                     ix, iter);
5635        ++ix)
5636     compute_symtab_includes (iter);
5637
5638   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
5639 }
5640
5641 /* Generate full symbol information for PER_CU, whose DIEs have
5642    already been loaded into memory.  */
5643
5644 static void
5645 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
5646                         enum language pretend_language)
5647 {
5648   struct dwarf2_cu *cu = per_cu->cu;
5649   struct objfile *objfile = per_cu->objfile;
5650   CORE_ADDR lowpc, highpc;
5651   struct symtab *symtab;
5652   struct cleanup *back_to, *delayed_list_cleanup;
5653   CORE_ADDR baseaddr;
5654
5655   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5656
5657   buildsym_init ();
5658   back_to = make_cleanup (really_free_pendings, NULL);
5659   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
5660
5661   cu->list_in_scope = &file_symbols;
5662
5663   cu->language = pretend_language;
5664   cu->language_defn = language_def (cu->language);
5665
5666   /* Do line number decoding in read_file_scope () */
5667   process_die (cu->dies, cu);
5668
5669   /* For now fudge the Go package.  */
5670   if (cu->language == language_go)
5671     fixup_go_packaging (cu);
5672
5673   /* Now that we have processed all the DIEs in the CU, all the types 
5674      should be complete, and it should now be safe to compute all of the
5675      physnames.  */
5676   compute_delayed_physnames (cu);
5677   do_cleanups (delayed_list_cleanup);
5678
5679   /* Some compilers don't define a DW_AT_high_pc attribute for the
5680      compilation unit.  If the DW_AT_high_pc is missing, synthesize
5681      it, by scanning the DIE's below the compilation unit.  */
5682   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
5683
5684   symtab = end_symtab (highpc + baseaddr, objfile, SECT_OFF_TEXT (objfile));
5685
5686   if (symtab != NULL)
5687     {
5688       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
5689
5690       /* Set symtab language to language from DW_AT_language.  If the
5691          compilation is from a C file generated by language preprocessors, do
5692          not set the language if it was already deduced by start_subfile.  */
5693       if (!(cu->language == language_c && symtab->language != language_c))
5694         symtab->language = cu->language;
5695
5696       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
5697          produce DW_AT_location with location lists but it can be possibly
5698          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
5699          there were bugs in prologue debug info, fixed later in GCC-4.5
5700          by "unwind info for epilogues" patch (which is not directly related).
5701
5702          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
5703          needed, it would be wrong due to missing DW_AT_producer there.
5704
5705          Still one can confuse GDB by using non-standard GCC compilation
5706          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
5707          */ 
5708       if (cu->has_loclist && gcc_4_minor >= 5)
5709         symtab->locations_valid = 1;
5710
5711       if (gcc_4_minor >= 5)
5712         symtab->epilogue_unwind_valid = 1;
5713
5714       symtab->call_site_htab = cu->call_site_htab;
5715     }
5716
5717   if (dwarf2_per_objfile->using_index)
5718     per_cu->v.quick->symtab = symtab;
5719   else
5720     {
5721       struct partial_symtab *pst = per_cu->v.psymtab;
5722       pst->symtab = symtab;
5723       pst->readin = 1;
5724     }
5725
5726   /* Push it for inclusion processing later.  */
5727   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
5728
5729   do_cleanups (back_to);
5730 }
5731
5732 /* Process an imported unit DIE.  */
5733
5734 static void
5735 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
5736 {
5737   struct attribute *attr;
5738
5739   attr = dwarf2_attr (die, DW_AT_import, cu);
5740   if (attr != NULL)
5741     {
5742       struct dwarf2_per_cu_data *per_cu;
5743       struct symtab *imported_symtab;
5744       sect_offset offset;
5745
5746       offset = dwarf2_get_ref_die_offset (attr);
5747       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
5748
5749       /* Queue the unit, if needed.  */
5750       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
5751         load_full_comp_unit (per_cu, cu->language);
5752
5753       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5754                      per_cu);
5755     }
5756 }
5757
5758 /* Process a die and its children.  */
5759
5760 static void
5761 process_die (struct die_info *die, struct dwarf2_cu *cu)
5762 {
5763   switch (die->tag)
5764     {
5765     case DW_TAG_padding:
5766       break;
5767     case DW_TAG_compile_unit:
5768     case DW_TAG_partial_unit:
5769       read_file_scope (die, cu);
5770       break;
5771     case DW_TAG_type_unit:
5772       read_type_unit_scope (die, cu);
5773       break;
5774     case DW_TAG_subprogram:
5775     case DW_TAG_inlined_subroutine:
5776       read_func_scope (die, cu);
5777       break;
5778     case DW_TAG_lexical_block:
5779     case DW_TAG_try_block:
5780     case DW_TAG_catch_block:
5781       read_lexical_block_scope (die, cu);
5782       break;
5783     case DW_TAG_GNU_call_site:
5784       read_call_site_scope (die, cu);
5785       break;
5786     case DW_TAG_class_type:
5787     case DW_TAG_interface_type:
5788     case DW_TAG_structure_type:
5789     case DW_TAG_union_type:
5790       process_structure_scope (die, cu);
5791       break;
5792     case DW_TAG_enumeration_type:
5793       process_enumeration_scope (die, cu);
5794       break;
5795
5796     /* These dies have a type, but processing them does not create
5797        a symbol or recurse to process the children.  Therefore we can
5798        read them on-demand through read_type_die.  */
5799     case DW_TAG_subroutine_type:
5800     case DW_TAG_set_type:
5801     case DW_TAG_array_type:
5802     case DW_TAG_pointer_type:
5803     case DW_TAG_ptr_to_member_type:
5804     case DW_TAG_reference_type:
5805     case DW_TAG_string_type:
5806       break;
5807
5808     case DW_TAG_base_type:
5809     case DW_TAG_subrange_type:
5810     case DW_TAG_typedef:
5811       /* Add a typedef symbol for the type definition, if it has a
5812          DW_AT_name.  */
5813       new_symbol (die, read_type_die (die, cu), cu);
5814       break;
5815     case DW_TAG_common_block:
5816       read_common_block (die, cu);
5817       break;
5818     case DW_TAG_common_inclusion:
5819       break;
5820     case DW_TAG_namespace:
5821       processing_has_namespace_info = 1;
5822       read_namespace (die, cu);
5823       break;
5824     case DW_TAG_module:
5825       processing_has_namespace_info = 1;
5826       read_module (die, cu);
5827       break;
5828     case DW_TAG_imported_declaration:
5829     case DW_TAG_imported_module:
5830       processing_has_namespace_info = 1;
5831       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
5832                                  || cu->language != language_fortran))
5833         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
5834                    dwarf_tag_name (die->tag));
5835       read_import_statement (die, cu);
5836       break;
5837
5838     case DW_TAG_imported_unit:
5839       process_imported_unit_die (die, cu);
5840       break;
5841
5842     default:
5843       new_symbol (die, NULL, cu);
5844       break;
5845     }
5846 }
5847
5848 /* A helper function for dwarf2_compute_name which determines whether DIE
5849    needs to have the name of the scope prepended to the name listed in the
5850    die.  */
5851
5852 static int
5853 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
5854 {
5855   struct attribute *attr;
5856
5857   switch (die->tag)
5858     {
5859     case DW_TAG_namespace:
5860     case DW_TAG_typedef:
5861     case DW_TAG_class_type:
5862     case DW_TAG_interface_type:
5863     case DW_TAG_structure_type:
5864     case DW_TAG_union_type:
5865     case DW_TAG_enumeration_type:
5866     case DW_TAG_enumerator:
5867     case DW_TAG_subprogram:
5868     case DW_TAG_member:
5869       return 1;
5870
5871     case DW_TAG_variable:
5872     case DW_TAG_constant:
5873       /* We only need to prefix "globally" visible variables.  These include
5874          any variable marked with DW_AT_external or any variable that
5875          lives in a namespace.  [Variables in anonymous namespaces
5876          require prefixing, but they are not DW_AT_external.]  */
5877
5878       if (dwarf2_attr (die, DW_AT_specification, cu))
5879         {
5880           struct dwarf2_cu *spec_cu = cu;
5881
5882           return die_needs_namespace (die_specification (die, &spec_cu),
5883                                       spec_cu);
5884         }
5885
5886       attr = dwarf2_attr (die, DW_AT_external, cu);
5887       if (attr == NULL && die->parent->tag != DW_TAG_namespace
5888           && die->parent->tag != DW_TAG_module)
5889         return 0;
5890       /* A variable in a lexical block of some kind does not need a
5891          namespace, even though in C++ such variables may be external
5892          and have a mangled name.  */
5893       if (die->parent->tag ==  DW_TAG_lexical_block
5894           || die->parent->tag ==  DW_TAG_try_block
5895           || die->parent->tag ==  DW_TAG_catch_block
5896           || die->parent->tag == DW_TAG_subprogram)
5897         return 0;
5898       return 1;
5899
5900     default:
5901       return 0;
5902     }
5903 }
5904
5905 /* Retrieve the last character from a mem_file.  */
5906
5907 static void
5908 do_ui_file_peek_last (void *object, const char *buffer, long length)
5909 {
5910   char *last_char_p = (char *) object;
5911
5912   if (length > 0)
5913     *last_char_p = buffer[length - 1];
5914 }
5915
5916 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
5917    compute the physname for the object, which include a method's:
5918    - formal parameters (C++/Java),
5919    - receiver type (Go),
5920    - return type (Java).
5921
5922    The term "physname" is a bit confusing.
5923    For C++, for example, it is the demangled name.
5924    For Go, for example, it's the mangled name.
5925
5926    For Ada, return the DIE's linkage name rather than the fully qualified
5927    name.  PHYSNAME is ignored..
5928
5929    The result is allocated on the objfile_obstack and canonicalized.  */
5930
5931 static const char *
5932 dwarf2_compute_name (char *name, struct die_info *die, struct dwarf2_cu *cu,
5933                      int physname)
5934 {
5935   struct objfile *objfile = cu->objfile;
5936
5937   if (name == NULL)
5938     name = dwarf2_name (die, cu);
5939
5940   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
5941      compute it by typename_concat inside GDB.  */
5942   if (cu->language == language_ada
5943       || (cu->language == language_fortran && physname))
5944     {
5945       /* For Ada unit, we prefer the linkage name over the name, as
5946          the former contains the exported name, which the user expects
5947          to be able to reference.  Ideally, we want the user to be able
5948          to reference this entity using either natural or linkage name,
5949          but we haven't started looking at this enhancement yet.  */
5950       struct attribute *attr;
5951
5952       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
5953       if (attr == NULL)
5954         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
5955       if (attr && DW_STRING (attr))
5956         return DW_STRING (attr);
5957     }
5958
5959   /* These are the only languages we know how to qualify names in.  */
5960   if (name != NULL
5961       && (cu->language == language_cplus || cu->language == language_java
5962           || cu->language == language_fortran))
5963     {
5964       if (die_needs_namespace (die, cu))
5965         {
5966           long length;
5967           const char *prefix;
5968           struct ui_file *buf;
5969
5970           prefix = determine_prefix (die, cu);
5971           buf = mem_fileopen ();
5972           if (*prefix != '\0')
5973             {
5974               char *prefixed_name = typename_concat (NULL, prefix, name,
5975                                                      physname, cu);
5976
5977               fputs_unfiltered (prefixed_name, buf);
5978               xfree (prefixed_name);
5979             }
5980           else
5981             fputs_unfiltered (name, buf);
5982
5983           /* Template parameters may be specified in the DIE's DW_AT_name, or
5984              as children with DW_TAG_template_type_param or
5985              DW_TAG_value_type_param.  If the latter, add them to the name
5986              here.  If the name already has template parameters, then
5987              skip this step; some versions of GCC emit both, and
5988              it is more efficient to use the pre-computed name.
5989
5990              Something to keep in mind about this process: it is very
5991              unlikely, or in some cases downright impossible, to produce
5992              something that will match the mangled name of a function.
5993              If the definition of the function has the same debug info,
5994              we should be able to match up with it anyway.  But fallbacks
5995              using the minimal symbol, for instance to find a method
5996              implemented in a stripped copy of libstdc++, will not work.
5997              If we do not have debug info for the definition, we will have to
5998              match them up some other way.
5999
6000              When we do name matching there is a related problem with function
6001              templates; two instantiated function templates are allowed to
6002              differ only by their return types, which we do not add here.  */
6003
6004           if (cu->language == language_cplus && strchr (name, '<') == NULL)
6005             {
6006               struct attribute *attr;
6007               struct die_info *child;
6008               int first = 1;
6009
6010               die->building_fullname = 1;
6011
6012               for (child = die->child; child != NULL; child = child->sibling)
6013                 {
6014                   struct type *type;
6015                   LONGEST value;
6016                   gdb_byte *bytes;
6017                   struct dwarf2_locexpr_baton *baton;
6018                   struct value *v;
6019
6020                   if (child->tag != DW_TAG_template_type_param
6021                       && child->tag != DW_TAG_template_value_param)
6022                     continue;
6023
6024                   if (first)
6025                     {
6026                       fputs_unfiltered ("<", buf);
6027                       first = 0;
6028                     }
6029                   else
6030                     fputs_unfiltered (", ", buf);
6031
6032                   attr = dwarf2_attr (child, DW_AT_type, cu);
6033                   if (attr == NULL)
6034                     {
6035                       complaint (&symfile_complaints,
6036                                  _("template parameter missing DW_AT_type"));
6037                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
6038                       continue;
6039                     }
6040                   type = die_type (child, cu);
6041
6042                   if (child->tag == DW_TAG_template_type_param)
6043                     {
6044                       c_print_type (type, "", buf, -1, 0);
6045                       continue;
6046                     }
6047
6048                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
6049                   if (attr == NULL)
6050                     {
6051                       complaint (&symfile_complaints,
6052                                  _("template parameter missing "
6053                                    "DW_AT_const_value"));
6054                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
6055                       continue;
6056                     }
6057
6058                   dwarf2_const_value_attr (attr, type, name,
6059                                            &cu->comp_unit_obstack, cu,
6060                                            &value, &bytes, &baton);
6061
6062                   if (TYPE_NOSIGN (type))
6063                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
6064                        changed, this can use value_print instead.  */
6065                     c_printchar (value, type, buf);
6066                   else
6067                     {
6068                       struct value_print_options opts;
6069
6070                       if (baton != NULL)
6071                         v = dwarf2_evaluate_loc_desc (type, NULL,
6072                                                       baton->data,
6073                                                       baton->size,
6074                                                       baton->per_cu);
6075                       else if (bytes != NULL)
6076                         {
6077                           v = allocate_value (type);
6078                           memcpy (value_contents_writeable (v), bytes,
6079                                   TYPE_LENGTH (type));
6080                         }
6081                       else
6082                         v = value_from_longest (type, value);
6083
6084                       /* Specify decimal so that we do not depend on
6085                          the radix.  */
6086                       get_formatted_print_options (&opts, 'd');
6087                       opts.raw = 1;
6088                       value_print (v, buf, &opts);
6089                       release_value (v);
6090                       value_free (v);
6091                     }
6092                 }
6093
6094               die->building_fullname = 0;
6095
6096               if (!first)
6097                 {
6098                   /* Close the argument list, with a space if necessary
6099                      (nested templates).  */
6100                   char last_char = '\0';
6101                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
6102                   if (last_char == '>')
6103                     fputs_unfiltered (" >", buf);
6104                   else
6105                     fputs_unfiltered (">", buf);
6106                 }
6107             }
6108
6109           /* For Java and C++ methods, append formal parameter type
6110              information, if PHYSNAME.  */
6111
6112           if (physname && die->tag == DW_TAG_subprogram
6113               && (cu->language == language_cplus
6114                   || cu->language == language_java))
6115             {
6116               struct type *type = read_type_die (die, cu);
6117
6118               c_type_print_args (type, buf, 1, cu->language);
6119
6120               if (cu->language == language_java)
6121                 {
6122                   /* For java, we must append the return type to method
6123                      names.  */
6124                   if (die->tag == DW_TAG_subprogram)
6125                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
6126                                      0, 0);
6127                 }
6128               else if (cu->language == language_cplus)
6129                 {
6130                   /* Assume that an artificial first parameter is
6131                      "this", but do not crash if it is not.  RealView
6132                      marks unnamed (and thus unused) parameters as
6133                      artificial; there is no way to differentiate
6134                      the two cases.  */
6135                   if (TYPE_NFIELDS (type) > 0
6136                       && TYPE_FIELD_ARTIFICIAL (type, 0)
6137                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
6138                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
6139                                                                         0))))
6140                     fputs_unfiltered (" const", buf);
6141                 }
6142             }
6143
6144           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
6145                                        &length);
6146           ui_file_delete (buf);
6147
6148           if (cu->language == language_cplus)
6149             {
6150               char *cname
6151                 = dwarf2_canonicalize_name (name, cu,
6152                                             &objfile->objfile_obstack);
6153
6154               if (cname != NULL)
6155                 name = cname;
6156             }
6157         }
6158     }
6159
6160   return name;
6161 }
6162
6163 /* Return the fully qualified name of DIE, based on its DW_AT_name.
6164    If scope qualifiers are appropriate they will be added.  The result
6165    will be allocated on the objfile_obstack, or NULL if the DIE does
6166    not have a name.  NAME may either be from a previous call to
6167    dwarf2_name or NULL.
6168
6169    The output string will be canonicalized (if C++/Java).  */
6170
6171 static const char *
6172 dwarf2_full_name (char *name, struct die_info *die, struct dwarf2_cu *cu)
6173 {
6174   return dwarf2_compute_name (name, die, cu, 0);
6175 }
6176
6177 /* Construct a physname for the given DIE in CU.  NAME may either be
6178    from a previous call to dwarf2_name or NULL.  The result will be
6179    allocated on the objfile_objstack or NULL if the DIE does not have a
6180    name.
6181
6182    The output string will be canonicalized (if C++/Java).  */
6183
6184 static const char *
6185 dwarf2_physname (char *name, struct die_info *die, struct dwarf2_cu *cu)
6186 {
6187   struct objfile *objfile = cu->objfile;
6188   struct attribute *attr;
6189   const char *retval, *mangled = NULL, *canon = NULL;
6190   struct cleanup *back_to;
6191   int need_copy = 1;
6192
6193   /* In this case dwarf2_compute_name is just a shortcut not building anything
6194      on its own.  */
6195   if (!die_needs_namespace (die, cu))
6196     return dwarf2_compute_name (name, die, cu, 1);
6197
6198   back_to = make_cleanup (null_cleanup, NULL);
6199
6200   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
6201   if (!attr)
6202     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
6203
6204   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
6205      has computed.  */
6206   if (attr && DW_STRING (attr))
6207     {
6208       char *demangled;
6209
6210       mangled = DW_STRING (attr);
6211
6212       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
6213          type.  It is easier for GDB users to search for such functions as
6214          `name(params)' than `long name(params)'.  In such case the minimal
6215          symbol names do not match the full symbol names but for template
6216          functions there is never a need to look up their definition from their
6217          declaration so the only disadvantage remains the minimal symbol
6218          variant `long name(params)' does not have the proper inferior type.
6219          */
6220
6221       if (cu->language == language_go)
6222         {
6223           /* This is a lie, but we already lie to the caller new_symbol_full.
6224              new_symbol_full assumes we return the mangled name.
6225              This just undoes that lie until things are cleaned up.  */
6226           demangled = NULL;
6227         }
6228       else
6229         {
6230           demangled = cplus_demangle (mangled,
6231                                       (DMGL_PARAMS | DMGL_ANSI
6232                                        | (cu->language == language_java
6233                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
6234                                           : DMGL_RET_DROP)));
6235         }
6236       if (demangled)
6237         {
6238           make_cleanup (xfree, demangled);
6239           canon = demangled;
6240         }
6241       else
6242         {
6243           canon = mangled;
6244           need_copy = 0;
6245         }
6246     }
6247
6248   if (canon == NULL || check_physname)
6249     {
6250       const char *physname = dwarf2_compute_name (name, die, cu, 1);
6251
6252       if (canon != NULL && strcmp (physname, canon) != 0)
6253         {
6254           /* It may not mean a bug in GDB.  The compiler could also
6255              compute DW_AT_linkage_name incorrectly.  But in such case
6256              GDB would need to be bug-to-bug compatible.  */
6257
6258           complaint (&symfile_complaints,
6259                      _("Computed physname <%s> does not match demangled <%s> "
6260                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
6261                      physname, canon, mangled, die->offset.sect_off, objfile->name);
6262
6263           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
6264              is available here - over computed PHYSNAME.  It is safer
6265              against both buggy GDB and buggy compilers.  */
6266
6267           retval = canon;
6268         }
6269       else
6270         {
6271           retval = physname;
6272           need_copy = 0;
6273         }
6274     }
6275   else
6276     retval = canon;
6277
6278   if (need_copy)
6279     retval = obsavestring (retval, strlen (retval),
6280                            &objfile->objfile_obstack);
6281
6282   do_cleanups (back_to);
6283   return retval;
6284 }
6285
6286 /* Read the import statement specified by the given die and record it.  */
6287
6288 static void
6289 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
6290 {
6291   struct objfile *objfile = cu->objfile;
6292   struct attribute *import_attr;
6293   struct die_info *imported_die, *child_die;
6294   struct dwarf2_cu *imported_cu;
6295   const char *imported_name;
6296   const char *imported_name_prefix;
6297   const char *canonical_name;
6298   const char *import_alias;
6299   const char *imported_declaration = NULL;
6300   const char *import_prefix;
6301   VEC (const_char_ptr) *excludes = NULL;
6302   struct cleanup *cleanups;
6303
6304   char *temp;
6305
6306   import_attr = dwarf2_attr (die, DW_AT_import, cu);
6307   if (import_attr == NULL)
6308     {
6309       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
6310                  dwarf_tag_name (die->tag));
6311       return;
6312     }
6313
6314   imported_cu = cu;
6315   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
6316   imported_name = dwarf2_name (imported_die, imported_cu);
6317   if (imported_name == NULL)
6318     {
6319       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
6320
6321         The import in the following code:
6322         namespace A
6323           {
6324             typedef int B;
6325           }
6326
6327         int main ()
6328           {
6329             using A::B;
6330             B b;
6331             return b;
6332           }
6333
6334         ...
6335          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
6336             <52>   DW_AT_decl_file   : 1
6337             <53>   DW_AT_decl_line   : 6
6338             <54>   DW_AT_import      : <0x75>
6339          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
6340             <59>   DW_AT_name        : B
6341             <5b>   DW_AT_decl_file   : 1
6342             <5c>   DW_AT_decl_line   : 2
6343             <5d>   DW_AT_type        : <0x6e>
6344         ...
6345          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
6346             <76>   DW_AT_byte_size   : 4
6347             <77>   DW_AT_encoding    : 5        (signed)
6348
6349         imports the wrong die ( 0x75 instead of 0x58 ).
6350         This case will be ignored until the gcc bug is fixed.  */
6351       return;
6352     }
6353
6354   /* Figure out the local name after import.  */
6355   import_alias = dwarf2_name (die, cu);
6356
6357   /* Figure out where the statement is being imported to.  */
6358   import_prefix = determine_prefix (die, cu);
6359
6360   /* Figure out what the scope of the imported die is and prepend it
6361      to the name of the imported die.  */
6362   imported_name_prefix = determine_prefix (imported_die, imported_cu);
6363
6364   if (imported_die->tag != DW_TAG_namespace
6365       && imported_die->tag != DW_TAG_module)
6366     {
6367       imported_declaration = imported_name;
6368       canonical_name = imported_name_prefix;
6369     }
6370   else if (strlen (imported_name_prefix) > 0)
6371     {
6372       temp = alloca (strlen (imported_name_prefix)
6373                      + 2 + strlen (imported_name) + 1);
6374       strcpy (temp, imported_name_prefix);
6375       strcat (temp, "::");
6376       strcat (temp, imported_name);
6377       canonical_name = temp;
6378     }
6379   else
6380     canonical_name = imported_name;
6381
6382   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
6383
6384   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
6385     for (child_die = die->child; child_die && child_die->tag;
6386          child_die = sibling_die (child_die))
6387       {
6388         /* DWARF-4: A Fortran use statement with a “rename list” may be
6389            represented by an imported module entry with an import attribute
6390            referring to the module and owned entries corresponding to those
6391            entities that are renamed as part of being imported.  */
6392
6393         if (child_die->tag != DW_TAG_imported_declaration)
6394           {
6395             complaint (&symfile_complaints,
6396                        _("child DW_TAG_imported_declaration expected "
6397                          "- DIE at 0x%x [in module %s]"),
6398                        child_die->offset.sect_off, objfile->name);
6399             continue;
6400           }
6401
6402         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
6403         if (import_attr == NULL)
6404           {
6405             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
6406                        dwarf_tag_name (child_die->tag));
6407             continue;
6408           }
6409
6410         imported_cu = cu;
6411         imported_die = follow_die_ref_or_sig (child_die, import_attr,
6412                                               &imported_cu);
6413         imported_name = dwarf2_name (imported_die, imported_cu);
6414         if (imported_name == NULL)
6415           {
6416             complaint (&symfile_complaints,
6417                        _("child DW_TAG_imported_declaration has unknown "
6418                          "imported name - DIE at 0x%x [in module %s]"),
6419                        child_die->offset.sect_off, objfile->name);
6420             continue;
6421           }
6422
6423         VEC_safe_push (const_char_ptr, excludes, imported_name);
6424
6425         process_die (child_die, cu);
6426       }
6427
6428   cp_add_using_directive (import_prefix,
6429                           canonical_name,
6430                           import_alias,
6431                           imported_declaration,
6432                           excludes,
6433                           &objfile->objfile_obstack);
6434
6435   do_cleanups (cleanups);
6436 }
6437
6438 /* Cleanup function for read_file_scope.  */
6439
6440 static void
6441 free_cu_line_header (void *arg)
6442 {
6443   struct dwarf2_cu *cu = arg;
6444
6445   free_line_header (cu->line_header);
6446   cu->line_header = NULL;
6447 }
6448
6449 static void
6450 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
6451                          char **name, char **comp_dir)
6452 {
6453   struct attribute *attr;
6454
6455   *name = NULL;
6456   *comp_dir = NULL;
6457
6458   /* Find the filename.  Do not use dwarf2_name here, since the filename
6459      is not a source language identifier.  */
6460   attr = dwarf2_attr (die, DW_AT_name, cu);
6461   if (attr)
6462     {
6463       *name = DW_STRING (attr);
6464     }
6465
6466   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
6467   if (attr)
6468     *comp_dir = DW_STRING (attr);
6469   else if (*name != NULL && IS_ABSOLUTE_PATH (*name))
6470     {
6471       *comp_dir = ldirname (*name);
6472       if (*comp_dir != NULL)
6473         make_cleanup (xfree, *comp_dir);
6474     }
6475   if (*comp_dir != NULL)
6476     {
6477       /* Irix 6.2 native cc prepends <machine>.: to the compilation
6478          directory, get rid of it.  */
6479       char *cp = strchr (*comp_dir, ':');
6480
6481       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
6482         *comp_dir = cp + 1;
6483     }
6484
6485   if (*name == NULL)
6486     *name = "<unknown>";
6487 }
6488
6489 /* Handle DW_AT_stmt_list for a compilation unit or type unit.
6490    DIE is the DW_TAG_compile_unit or DW_TAG_type_unit die for CU.
6491    COMP_DIR is the compilation directory.
6492    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
6493
6494 static void
6495 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
6496                         const char *comp_dir, int want_line_info)
6497 {
6498   struct attribute *attr;
6499
6500   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6501   if (attr)
6502     {
6503       unsigned int line_offset = DW_UNSND (attr);
6504       struct line_header *line_header
6505         = dwarf_decode_line_header (line_offset, cu);
6506
6507       if (line_header)
6508         {
6509           cu->line_header = line_header;
6510           make_cleanup (free_cu_line_header, cu);
6511           dwarf_decode_lines (line_header, comp_dir, cu, NULL, want_line_info);
6512         }
6513     }
6514 }
6515
6516 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
6517
6518 static void
6519 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
6520 {
6521   struct objfile *objfile = dwarf2_per_objfile->objfile;
6522   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
6523   CORE_ADDR lowpc = ((CORE_ADDR) -1);
6524   CORE_ADDR highpc = ((CORE_ADDR) 0);
6525   struct attribute *attr;
6526   char *name = NULL;
6527   char *comp_dir = NULL;
6528   struct die_info *child_die;
6529   bfd *abfd = objfile->obfd;
6530   CORE_ADDR baseaddr;
6531
6532   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6533
6534   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
6535
6536   /* If we didn't find a lowpc, set it to highpc to avoid complaints
6537      from finish_block.  */
6538   if (lowpc == ((CORE_ADDR) -1))
6539     lowpc = highpc;
6540   lowpc += baseaddr;
6541   highpc += baseaddr;
6542
6543   find_file_and_directory (die, cu, &name, &comp_dir);
6544
6545   prepare_one_comp_unit (cu, die, cu->language);
6546
6547   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
6548      standardised yet.  As a workaround for the language detection we fall
6549      back to the DW_AT_producer string.  */
6550   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
6551     cu->language = language_opencl;
6552
6553   /* Similar hack for Go.  */
6554   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
6555     set_cu_language (DW_LANG_Go, cu);
6556
6557   /* We assume that we're processing GCC output.  */
6558   processing_gcc_compilation = 2;
6559
6560   processing_has_namespace_info = 0;
6561
6562   start_symtab (name, comp_dir, lowpc);
6563   record_debugformat ("DWARF 2");
6564   record_producer (cu->producer);
6565
6566   /* Decode line number information if present.  We do this before
6567      processing child DIEs, so that the line header table is available
6568      for DW_AT_decl_file.  */
6569   handle_DW_AT_stmt_list (die, cu, comp_dir, 1);
6570
6571   /* Process all dies in compilation unit.  */
6572   if (die->child != NULL)
6573     {
6574       child_die = die->child;
6575       while (child_die && child_die->tag)
6576         {
6577           process_die (child_die, cu);
6578           child_die = sibling_die (child_die);
6579         }
6580     }
6581
6582   /* Decode macro information, if present.  Dwarf 2 macro information
6583      refers to information in the line number info statement program
6584      header, so we can only read it if we've read the header
6585      successfully.  */
6586   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
6587   if (attr && cu->line_header)
6588     {
6589       if (dwarf2_attr (die, DW_AT_macro_info, cu))
6590         complaint (&symfile_complaints,
6591                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
6592
6593       dwarf_decode_macros (cu->line_header, DW_UNSND (attr),
6594                            comp_dir, abfd, cu,
6595                            &dwarf2_per_objfile->macro, 1,
6596                            ".debug_macro");
6597     }
6598   else
6599     {
6600       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
6601       if (attr && cu->line_header)
6602         {
6603           unsigned int macro_offset = DW_UNSND (attr);
6604
6605           dwarf_decode_macros (cu->line_header, macro_offset,
6606                                comp_dir, abfd, cu,
6607                                &dwarf2_per_objfile->macinfo, 0,
6608                                ".debug_macinfo");
6609         }
6610     }
6611
6612   do_cleanups (back_to);
6613 }
6614
6615 /* Process DW_TAG_type_unit.
6616    For TUs we want to skip the first top level sibling if it's not the
6617    actual type being defined by this TU.  In this case the first top
6618    level sibling is there to provide context only.  */
6619
6620 static void
6621 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
6622 {
6623   struct objfile *objfile = cu->objfile;
6624   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
6625   CORE_ADDR lowpc;
6626   struct attribute *attr;
6627   char *name = NULL;
6628   char *comp_dir = NULL;
6629   struct die_info *child_die;
6630   bfd *abfd = objfile->obfd;
6631
6632   /* start_symtab needs a low pc, but we don't really have one.
6633      Do what read_file_scope would do in the absence of such info.  */
6634   lowpc = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6635
6636   /* Find the filename.  Do not use dwarf2_name here, since the filename
6637      is not a source language identifier.  */
6638   attr = dwarf2_attr (die, DW_AT_name, cu);
6639   if (attr)
6640     name = DW_STRING (attr);
6641
6642   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
6643   if (attr)
6644     comp_dir = DW_STRING (attr);
6645   else if (name != NULL && IS_ABSOLUTE_PATH (name))
6646     {
6647       comp_dir = ldirname (name);
6648       if (comp_dir != NULL)
6649         make_cleanup (xfree, comp_dir);
6650     }
6651
6652   if (name == NULL)
6653     name = "<unknown>";
6654
6655   prepare_one_comp_unit (cu, die, language_minimal);
6656
6657   /* We assume that we're processing GCC output.  */
6658   processing_gcc_compilation = 2;
6659
6660   processing_has_namespace_info = 0;
6661
6662   start_symtab (name, comp_dir, lowpc);
6663   record_debugformat ("DWARF 2");
6664   record_producer (cu->producer);
6665
6666   /* Decode line number information if present.  We do this before
6667      processing child DIEs, so that the line header table is available
6668      for DW_AT_decl_file.
6669      We don't need the pc/line-number mapping for type units.  */
6670   handle_DW_AT_stmt_list (die, cu, comp_dir, 0);
6671
6672   /* Process the dies in the type unit.  */
6673   if (die->child == NULL)
6674     {
6675       dump_die_for_error (die);
6676       error (_("Dwarf Error: Missing children for type unit [in module %s]"),
6677              bfd_get_filename (abfd));
6678     }
6679
6680   child_die = die->child;
6681
6682   while (child_die && child_die->tag)
6683     {
6684       process_die (child_die, cu);
6685
6686       child_die = sibling_die (child_die);
6687     }
6688
6689   do_cleanups (back_to);
6690 }
6691 \f
6692 /* DWO files.  */
6693
6694 static hashval_t
6695 hash_dwo_file (const void *item)
6696 {
6697   const struct dwo_file *dwo_file = item;
6698
6699   return htab_hash_string (dwo_file->dwo_name);
6700 }
6701
6702 static int
6703 eq_dwo_file (const void *item_lhs, const void *item_rhs)
6704 {
6705   const struct dwo_file *lhs = item_lhs;
6706   const struct dwo_file *rhs = item_rhs;
6707
6708   return strcmp (lhs->dwo_name, rhs->dwo_name) == 0;
6709 }
6710
6711 /* Allocate a hash table for DWO files.  */
6712
6713 static htab_t
6714 allocate_dwo_file_hash_table (void)
6715 {
6716   struct objfile *objfile = dwarf2_per_objfile->objfile;
6717
6718   return htab_create_alloc_ex (41,
6719                                hash_dwo_file,
6720                                eq_dwo_file,
6721                                NULL,
6722                                &objfile->objfile_obstack,
6723                                hashtab_obstack_allocate,
6724                                dummy_obstack_deallocate);
6725 }
6726
6727 static hashval_t
6728 hash_dwo_unit (const void *item)
6729 {
6730   const struct dwo_unit *dwo_unit = item;
6731
6732   /* This drops the top 32 bits of the id, but is ok for a hash.  */
6733   return dwo_unit->signature;
6734 }
6735
6736 static int
6737 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
6738 {
6739   const struct dwo_unit *lhs = item_lhs;
6740   const struct dwo_unit *rhs = item_rhs;
6741
6742   /* The signature is assumed to be unique within the DWO file.
6743      So while object file CU dwo_id's always have the value zero,
6744      that's OK, assuming each object file DWO file has only one CU,
6745      and that's the rule for now.  */
6746   return lhs->signature == rhs->signature;
6747 }
6748
6749 /* Allocate a hash table for DWO CUs,TUs.
6750    There is one of these tables for each of CUs,TUs for each DWO file.  */
6751
6752 static htab_t
6753 allocate_dwo_unit_table (struct objfile *objfile)
6754 {
6755   /* Start out with a pretty small number.
6756      Generally DWO files contain only one CU and maybe some TUs.  */
6757   return htab_create_alloc_ex (3,
6758                                hash_dwo_unit,
6759                                eq_dwo_unit,
6760                                NULL,
6761                                &objfile->objfile_obstack,
6762                                hashtab_obstack_allocate,
6763                                dummy_obstack_deallocate);
6764 }
6765
6766 /* This function is mapped across the sections and remembers the offset and
6767    size of each of the DWO debugging sections we are interested in.  */
6768
6769 static void
6770 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_file_ptr)
6771 {
6772   struct dwo_file *dwo_file = dwo_file_ptr;
6773   const struct dwo_section_names *names = &dwo_section_names;
6774
6775   if (section_is_p (sectp->name, &names->abbrev_dwo))
6776     {
6777       dwo_file->sections.abbrev.asection = sectp;
6778       dwo_file->sections.abbrev.size = bfd_get_section_size (sectp);
6779     }
6780   else if (section_is_p (sectp->name, &names->info_dwo))
6781     {
6782       dwo_file->sections.info.asection = sectp;
6783       dwo_file->sections.info.size = bfd_get_section_size (sectp);
6784     }
6785   else if (section_is_p (sectp->name, &names->line_dwo))
6786     {
6787       dwo_file->sections.line.asection = sectp;
6788       dwo_file->sections.line.size = bfd_get_section_size (sectp);
6789     }
6790   else if (section_is_p (sectp->name, &names->loc_dwo))
6791     {
6792       dwo_file->sections.loc.asection = sectp;
6793       dwo_file->sections.loc.size = bfd_get_section_size (sectp);
6794     }
6795   else if (section_is_p (sectp->name, &names->str_dwo))
6796     {
6797       dwo_file->sections.str.asection = sectp;
6798       dwo_file->sections.str.size = bfd_get_section_size (sectp);
6799     }
6800   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
6801     {
6802       dwo_file->sections.str_offsets.asection = sectp;
6803       dwo_file->sections.str_offsets.size = bfd_get_section_size (sectp);
6804     }
6805   else if (section_is_p (sectp->name, &names->types_dwo))
6806     {
6807       struct dwarf2_section_info type_section;
6808
6809       memset (&type_section, 0, sizeof (type_section));
6810       type_section.asection = sectp;
6811       type_section.size = bfd_get_section_size (sectp);
6812       VEC_safe_push (dwarf2_section_info_def, dwo_file->sections.types,
6813                      &type_section);
6814     }
6815 }
6816
6817 /* Structure used to pass data to create_debug_info_hash_table_reader.  */
6818
6819 struct create_dwo_info_table_data
6820 {
6821   struct dwo_file *dwo_file;
6822   htab_t cu_htab;
6823 };
6824
6825 /* die_reader_func for create_debug_info_hash_table.  */
6826
6827 static void
6828 create_debug_info_hash_table_reader (const struct die_reader_specs *reader,
6829                                      gdb_byte *info_ptr,
6830                                      struct die_info *comp_unit_die,
6831                                      int has_children,
6832                                      void *datap)
6833 {
6834   struct dwarf2_cu *cu = reader->cu;
6835   struct objfile *objfile = dwarf2_per_objfile->objfile;
6836   sect_offset offset = cu->per_cu->offset;
6837   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
6838   struct create_dwo_info_table_data *data = datap;
6839   struct dwo_file *dwo_file = data->dwo_file;
6840   htab_t cu_htab = data->cu_htab;
6841   void **slot;
6842   struct attribute *attr;
6843   struct dwo_unit *dwo_unit;
6844
6845   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6846   if (attr == NULL)
6847     {
6848       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
6849                " its dwo_id [in module %s]"),
6850              offset.sect_off, dwo_file->dwo_name);
6851       return;
6852     }
6853
6854   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
6855   dwo_unit->dwo_file = dwo_file;
6856   dwo_unit->signature = DW_UNSND (attr);
6857   dwo_unit->info_or_types_section = section;
6858   dwo_unit->offset = offset;
6859   dwo_unit->length = cu->per_cu->length;
6860
6861   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
6862   gdb_assert (slot != NULL);
6863   if (*slot != NULL)
6864     {
6865       const struct dwo_unit *dup_dwo_unit = *slot;
6866
6867       complaint (&symfile_complaints,
6868                  _("debug entry at offset 0x%x is duplicate to the entry at"
6869                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
6870                  offset.sect_off, dup_dwo_unit->offset.sect_off,
6871                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
6872                  dwo_file->dwo_name);
6873     }
6874   else
6875     *slot = dwo_unit;
6876
6877   if (dwarf2_die_debug)
6878     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
6879                         offset.sect_off,
6880                         phex (dwo_unit->signature,
6881                               sizeof (dwo_unit->signature)));
6882 }
6883
6884 /* Create a hash table to map DWO IDs to their CU entry in .debug_info.dwo.  */
6885
6886 static htab_t
6887 create_debug_info_hash_table (struct dwo_file *dwo_file)
6888 {
6889   struct objfile *objfile = dwarf2_per_objfile->objfile;
6890   struct dwarf2_section_info *section = &dwo_file->sections.info;
6891   bfd *abfd;
6892   htab_t cu_htab;
6893   gdb_byte *info_ptr, *end_ptr;
6894   struct create_dwo_info_table_data create_dwo_info_table_data;
6895
6896   dwarf2_read_section (objfile, section);
6897   info_ptr = section->buffer;
6898
6899   if (info_ptr == NULL)
6900     return NULL;
6901
6902   /* We can't set abfd until now because the section may be empty or
6903      not present, in which case section->asection will be NULL.  */
6904   abfd = section->asection->owner;
6905
6906   if (dwarf2_die_debug)
6907     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
6908                         bfd_get_filename (abfd));
6909
6910   cu_htab = allocate_dwo_unit_table (objfile);
6911
6912   create_dwo_info_table_data.dwo_file = dwo_file;
6913   create_dwo_info_table_data.cu_htab = cu_htab;
6914
6915   end_ptr = info_ptr + section->size;
6916   while (info_ptr < end_ptr)
6917     {
6918       struct dwarf2_per_cu_data per_cu;
6919
6920       memset (&per_cu, 0, sizeof (per_cu));
6921       per_cu.objfile = objfile;
6922       per_cu.is_debug_types = 0;
6923       per_cu.offset.sect_off = info_ptr - section->buffer;
6924       per_cu.info_or_types_section = section;
6925
6926       init_cutu_and_read_dies_no_follow (&per_cu,
6927                                          &dwo_file->sections.abbrev,
6928                                          dwo_file,
6929                                          create_debug_info_hash_table_reader,
6930                                          &create_dwo_info_table_data);
6931
6932       info_ptr += per_cu.length;
6933     }
6934
6935   return cu_htab;
6936 }
6937
6938 /* Subroutine of open_dwo_file to simplify it.
6939    Open the file specified by FILE_NAME and hand it off to BFD for
6940    preliminary analysis.  Return a newly initialized bfd *, which
6941    includes a canonicalized copy of FILE_NAME.
6942    In case of trouble, return NULL.
6943    NOTE: This function is derived from symfile_bfd_open.  */
6944
6945 static bfd *
6946 try_open_dwo_file (const char *file_name)
6947 {
6948   bfd *sym_bfd;
6949   int desc;
6950   char *absolute_name;
6951
6952   desc = openp (debug_file_directory, OPF_TRY_CWD_FIRST, file_name,
6953                 O_RDONLY | O_BINARY, &absolute_name);
6954   if (desc < 0)
6955     return NULL;
6956
6957   sym_bfd = bfd_fopen (absolute_name, gnutarget, FOPEN_RB, desc);
6958   if (!sym_bfd)
6959     {
6960       close (desc);
6961       xfree (absolute_name);
6962       return NULL;
6963     }
6964   bfd_set_cacheable (sym_bfd, 1);
6965
6966   if (!bfd_check_format (sym_bfd, bfd_object))
6967     {
6968       bfd_close (sym_bfd); /* This also closes desc.  */
6969       xfree (absolute_name);
6970       return NULL;
6971     }
6972
6973   /* bfd_usrdata exists for applications and libbfd must not touch it.  */
6974   gdb_assert (bfd_usrdata (sym_bfd) == NULL);
6975
6976   return sym_bfd;
6977 }
6978
6979 /* Try to open DWO file DWO_NAME.
6980    COMP_DIR is the DW_AT_comp_dir attribute.
6981    The result is the bfd handle of the file.
6982    If there is a problem finding or opening the file, return NULL.
6983    Upon success, the canonicalized path of the file is stored in the bfd,
6984    same as symfile_bfd_open.  */
6985
6986 static bfd *
6987 open_dwo_file (const char *dwo_name, const char *comp_dir)
6988 {
6989   bfd *abfd;
6990
6991   if (IS_ABSOLUTE_PATH (dwo_name))
6992     return try_open_dwo_file (dwo_name);
6993
6994   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
6995
6996   if (comp_dir != NULL)
6997     {
6998       char *path_to_try = concat (comp_dir, SLASH_STRING, dwo_name, NULL);
6999
7000       /* NOTE: If comp_dir is a relative path, this will also try the
7001          search path, which seems useful.  */
7002       abfd = try_open_dwo_file (path_to_try);
7003       xfree (path_to_try);
7004       if (abfd != NULL)
7005         return abfd;
7006     }
7007
7008   /* That didn't work, try debug-file-directory, which, despite its name,
7009      is a list of paths.  */
7010
7011   if (*debug_file_directory == '\0')
7012     return NULL;
7013
7014   return try_open_dwo_file (dwo_name);
7015 }
7016
7017 /* Initialize the use of the DWO file specified by DWO_NAME.  */
7018
7019 static struct dwo_file *
7020 init_dwo_file (const char *dwo_name, const char *comp_dir)
7021 {
7022   struct objfile *objfile = dwarf2_per_objfile->objfile;
7023   struct dwo_file *dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7024                                               struct dwo_file);
7025   bfd *abfd;
7026   struct cleanup *cleanups;
7027
7028   if (dwarf2_die_debug)
7029     fprintf_unfiltered (gdb_stdlog, "Reading DWO file %s:\n", dwo_name);
7030
7031   abfd = open_dwo_file (dwo_name, comp_dir);
7032   if (abfd == NULL)
7033     return NULL;
7034   dwo_file->dwo_name = dwo_name;
7035   dwo_file->dwo_bfd = abfd;
7036
7037   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
7038
7039   bfd_map_over_sections (abfd, dwarf2_locate_dwo_sections, dwo_file);
7040
7041   dwo_file->cus = create_debug_info_hash_table (dwo_file);
7042
7043   dwo_file->tus = create_debug_types_hash_table (dwo_file,
7044                                                  dwo_file->sections.types);
7045
7046   discard_cleanups (cleanups);
7047
7048   return dwo_file;
7049 }
7050
7051 /* Lookup DWO file DWO_NAME.  */
7052
7053 static struct dwo_file *
7054 lookup_dwo_file (char *dwo_name, const char *comp_dir)
7055 {
7056   struct dwo_file *dwo_file;
7057   struct dwo_file find_entry;
7058   void **slot;
7059
7060   if (dwarf2_per_objfile->dwo_files == NULL)
7061     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
7062
7063   /* Have we already seen this DWO file?  */
7064   find_entry.dwo_name = dwo_name;
7065   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
7066
7067   /* If not, read it in and build a table of the DWOs it contains.  */
7068   if (*slot == NULL)
7069     *slot = init_dwo_file (dwo_name, comp_dir);
7070
7071   /* NOTE: This will be NULL if unable to open the file.  */
7072   dwo_file = *slot;
7073
7074   return dwo_file;
7075 }
7076
7077 /* Lookup the DWO CU referenced from THIS_CU in DWO file DWO_NAME.
7078    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
7079    SIGNATURE is the "dwo_id" of the CU (for consistency we use the same
7080    nomenclature as TUs).
7081    The result is the DWO CU or NULL if we didn't find it
7082    (dwo_id mismatch or couldn't find the DWO file).  */
7083
7084 static struct dwo_unit *
7085 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
7086                       char *dwo_name, const char *comp_dir,
7087                       ULONGEST signature)
7088 {
7089   struct objfile *objfile = dwarf2_per_objfile->objfile;
7090   struct dwo_file *dwo_file;
7091
7092   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
7093   if (dwo_file == NULL)
7094     return NULL;
7095
7096   /* Look up the DWO using its signature(dwo_id).  */
7097
7098   if (dwo_file->cus != NULL)
7099     {
7100       struct dwo_unit find_dwo_cu, *dwo_cu;
7101
7102       find_dwo_cu.signature = signature;
7103       dwo_cu = htab_find (dwo_file->cus, &find_dwo_cu);
7104
7105       if (dwo_cu != NULL)
7106         return dwo_cu;
7107     }
7108
7109   /* We didn't find it.  This must mean a dwo_id mismatch.  */
7110
7111   complaint (&symfile_complaints,
7112              _("Could not find DWO CU referenced by CU at offset 0x%x"
7113                " [in module %s]"),
7114              this_cu->offset.sect_off, objfile->name);
7115   return NULL;
7116 }
7117
7118 /* Lookup the DWO TU referenced from THIS_TU in DWO file DWO_NAME.
7119    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
7120    The result is the DWO CU or NULL if we didn't find it
7121    (dwo_id mismatch or couldn't find the DWO file).  */
7122
7123 static struct dwo_unit *
7124 lookup_dwo_type_unit (struct signatured_type *this_tu,
7125                       char *dwo_name, const char *comp_dir)
7126 {
7127   struct objfile *objfile = dwarf2_per_objfile->objfile;
7128   struct dwo_file *dwo_file;
7129
7130   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
7131   if (dwo_file == NULL)
7132     return NULL;
7133
7134   /* Look up the DWO using its signature(dwo_id).  */
7135
7136   if (dwo_file->tus != NULL)
7137     {
7138       struct dwo_unit find_dwo_tu, *dwo_tu;
7139
7140       find_dwo_tu.signature = this_tu->signature;
7141       dwo_tu = htab_find (dwo_file->tus, &find_dwo_tu);
7142
7143       if (dwo_tu != NULL)
7144         return dwo_tu;
7145     }
7146
7147   /* We didn't find it.  This must mean a dwo_id mismatch.  */
7148
7149   complaint (&symfile_complaints,
7150              _("Could not find DWO TU referenced by TU at offset 0x%x"
7151                " [in module %s]"),
7152              this_tu->per_cu.offset.sect_off, objfile->name);
7153   return NULL;
7154 }
7155
7156 /* Free all resources associated with DWO_FILE.
7157    Close the DWO file and munmap the sections.
7158    All memory should be on the objfile obstack.  */
7159
7160 static void
7161 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
7162 {
7163   int ix;
7164   struct dwarf2_section_info *section;
7165
7166   gdb_assert (dwo_file->dwo_bfd != objfile->obfd);
7167   bfd_close (dwo_file->dwo_bfd);
7168
7169   munmap_section_buffer (&dwo_file->sections.abbrev);
7170   munmap_section_buffer (&dwo_file->sections.info);
7171   munmap_section_buffer (&dwo_file->sections.line);
7172   munmap_section_buffer (&dwo_file->sections.loc);
7173   munmap_section_buffer (&dwo_file->sections.str);
7174   munmap_section_buffer (&dwo_file->sections.str_offsets);
7175
7176   for (ix = 0;
7177        VEC_iterate (dwarf2_section_info_def, dwo_file->sections.types,
7178                     ix, section);
7179        ++ix)
7180     munmap_section_buffer (section);
7181
7182   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
7183 }
7184
7185 /* Wrapper for free_dwo_file for use in cleanups.  */
7186
7187 static void
7188 free_dwo_file_cleanup (void *arg)
7189 {
7190   struct dwo_file *dwo_file = (struct dwo_file *) arg;
7191   struct objfile *objfile = dwarf2_per_objfile->objfile;
7192
7193   free_dwo_file (dwo_file, objfile);
7194 }
7195
7196 /* Traversal function for free_dwo_files.  */
7197
7198 static int
7199 free_dwo_file_from_slot (void **slot, void *info)
7200 {
7201   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7202   struct objfile *objfile = (struct objfile *) info;
7203
7204   free_dwo_file (dwo_file, objfile);
7205
7206   return 1;
7207 }
7208
7209 /* Free all resources associated with DWO_FILES.  */
7210
7211 static void
7212 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
7213 {
7214   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
7215 }
7216 \f
7217 /* Read in various DIEs.  */
7218
7219 /* qsort helper for inherit_abstract_dies.  */
7220
7221 static int
7222 unsigned_int_compar (const void *ap, const void *bp)
7223 {
7224   unsigned int a = *(unsigned int *) ap;
7225   unsigned int b = *(unsigned int *) bp;
7226
7227   return (a > b) - (b > a);
7228 }
7229
7230 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
7231    Inherit only the children of the DW_AT_abstract_origin DIE not being
7232    already referenced by DW_AT_abstract_origin from the children of the
7233    current DIE.  */
7234
7235 static void
7236 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
7237 {
7238   struct die_info *child_die;
7239   unsigned die_children_count;
7240   /* CU offsets which were referenced by children of the current DIE.  */
7241   sect_offset *offsets;
7242   sect_offset *offsets_end, *offsetp;
7243   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
7244   struct die_info *origin_die;
7245   /* Iterator of the ORIGIN_DIE children.  */
7246   struct die_info *origin_child_die;
7247   struct cleanup *cleanups;
7248   struct attribute *attr;
7249   struct dwarf2_cu *origin_cu;
7250   struct pending **origin_previous_list_in_scope;
7251
7252   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
7253   if (!attr)
7254     return;
7255
7256   /* Note that following die references may follow to a die in a
7257      different cu.  */
7258
7259   origin_cu = cu;
7260   origin_die = follow_die_ref (die, attr, &origin_cu);
7261
7262   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
7263      symbols in.  */
7264   origin_previous_list_in_scope = origin_cu->list_in_scope;
7265   origin_cu->list_in_scope = cu->list_in_scope;
7266
7267   if (die->tag != origin_die->tag
7268       && !(die->tag == DW_TAG_inlined_subroutine
7269            && origin_die->tag == DW_TAG_subprogram))
7270     complaint (&symfile_complaints,
7271                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
7272                die->offset.sect_off, origin_die->offset.sect_off);
7273
7274   child_die = die->child;
7275   die_children_count = 0;
7276   while (child_die && child_die->tag)
7277     {
7278       child_die = sibling_die (child_die);
7279       die_children_count++;
7280     }
7281   offsets = xmalloc (sizeof (*offsets) * die_children_count);
7282   cleanups = make_cleanup (xfree, offsets);
7283
7284   offsets_end = offsets;
7285   child_die = die->child;
7286   while (child_die && child_die->tag)
7287     {
7288       /* For each CHILD_DIE, find the corresponding child of
7289          ORIGIN_DIE.  If there is more than one layer of
7290          DW_AT_abstract_origin, follow them all; there shouldn't be,
7291          but GCC versions at least through 4.4 generate this (GCC PR
7292          40573).  */
7293       struct die_info *child_origin_die = child_die;
7294       struct dwarf2_cu *child_origin_cu = cu;
7295
7296       while (1)
7297         {
7298           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
7299                               child_origin_cu);
7300           if (attr == NULL)
7301             break;
7302           child_origin_die = follow_die_ref (child_origin_die, attr,
7303                                              &child_origin_cu);
7304         }
7305
7306       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
7307          counterpart may exist.  */
7308       if (child_origin_die != child_die)
7309         {
7310           if (child_die->tag != child_origin_die->tag
7311               && !(child_die->tag == DW_TAG_inlined_subroutine
7312                    && child_origin_die->tag == DW_TAG_subprogram))
7313             complaint (&symfile_complaints,
7314                        _("Child DIE 0x%x and its abstract origin 0x%x have "
7315                          "different tags"), child_die->offset.sect_off,
7316                        child_origin_die->offset.sect_off);
7317           if (child_origin_die->parent != origin_die)
7318             complaint (&symfile_complaints,
7319                        _("Child DIE 0x%x and its abstract origin 0x%x have "
7320                          "different parents"), child_die->offset.sect_off,
7321                        child_origin_die->offset.sect_off);
7322           else
7323             *offsets_end++ = child_origin_die->offset;
7324         }
7325       child_die = sibling_die (child_die);
7326     }
7327   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
7328          unsigned_int_compar);
7329   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
7330     if (offsetp[-1].sect_off == offsetp->sect_off)
7331       complaint (&symfile_complaints,
7332                  _("Multiple children of DIE 0x%x refer "
7333                    "to DIE 0x%x as their abstract origin"),
7334                  die->offset.sect_off, offsetp->sect_off);
7335
7336   offsetp = offsets;
7337   origin_child_die = origin_die->child;
7338   while (origin_child_die && origin_child_die->tag)
7339     {
7340       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
7341       while (offsetp < offsets_end
7342              && offsetp->sect_off < origin_child_die->offset.sect_off)
7343         offsetp++;
7344       if (offsetp >= offsets_end
7345           || offsetp->sect_off > origin_child_die->offset.sect_off)
7346         {
7347           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
7348           process_die (origin_child_die, origin_cu);
7349         }
7350       origin_child_die = sibling_die (origin_child_die);
7351     }
7352   origin_cu->list_in_scope = origin_previous_list_in_scope;
7353
7354   do_cleanups (cleanups);
7355 }
7356
7357 static void
7358 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
7359 {
7360   struct objfile *objfile = cu->objfile;
7361   struct context_stack *new;
7362   CORE_ADDR lowpc;
7363   CORE_ADDR highpc;
7364   struct die_info *child_die;
7365   struct attribute *attr, *call_line, *call_file;
7366   char *name;
7367   CORE_ADDR baseaddr;
7368   struct block *block;
7369   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
7370   VEC (symbolp) *template_args = NULL;
7371   struct template_symbol *templ_func = NULL;
7372
7373   if (inlined_func)
7374     {
7375       /* If we do not have call site information, we can't show the
7376          caller of this inlined function.  That's too confusing, so
7377          only use the scope for local variables.  */
7378       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
7379       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
7380       if (call_line == NULL || call_file == NULL)
7381         {
7382           read_lexical_block_scope (die, cu);
7383           return;
7384         }
7385     }
7386
7387   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7388
7389   name = dwarf2_name (die, cu);
7390
7391   /* Ignore functions with missing or empty names.  These are actually
7392      illegal according to the DWARF standard.  */
7393   if (name == NULL)
7394     {
7395       complaint (&symfile_complaints,
7396                  _("missing name for subprogram DIE at %d"),
7397                  die->offset.sect_off);
7398       return;
7399     }
7400
7401   /* Ignore functions with missing or invalid low and high pc attributes.  */
7402   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
7403     {
7404       attr = dwarf2_attr (die, DW_AT_external, cu);
7405       if (!attr || !DW_UNSND (attr))
7406         complaint (&symfile_complaints,
7407                    _("cannot get low and high bounds "
7408                      "for subprogram DIE at %d"),
7409                    die->offset.sect_off);
7410       return;
7411     }
7412
7413   lowpc += baseaddr;
7414   highpc += baseaddr;
7415
7416   /* If we have any template arguments, then we must allocate a
7417      different sort of symbol.  */
7418   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
7419     {
7420       if (child_die->tag == DW_TAG_template_type_param
7421           || child_die->tag == DW_TAG_template_value_param)
7422         {
7423           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7424                                        struct template_symbol);
7425           templ_func->base.is_cplus_template_function = 1;
7426           break;
7427         }
7428     }
7429
7430   new = push_context (0, lowpc);
7431   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
7432                                (struct symbol *) templ_func);
7433
7434   /* If there is a location expression for DW_AT_frame_base, record
7435      it.  */
7436   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
7437   if (attr)
7438     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
7439        expression is being recorded directly in the function's symbol
7440        and not in a separate frame-base object.  I guess this hack is
7441        to avoid adding some sort of frame-base adjunct/annex to the
7442        function's symbol :-(.  The problem with doing this is that it
7443        results in a function symbol with a location expression that
7444        has nothing to do with the location of the function, ouch!  The
7445        relationship should be: a function's symbol has-a frame base; a
7446        frame-base has-a location expression.  */
7447     dwarf2_symbol_mark_computed (attr, new->name, cu);
7448
7449   cu->list_in_scope = &local_symbols;
7450
7451   if (die->child != NULL)
7452     {
7453       child_die = die->child;
7454       while (child_die && child_die->tag)
7455         {
7456           if (child_die->tag == DW_TAG_template_type_param
7457               || child_die->tag == DW_TAG_template_value_param)
7458             {
7459               struct symbol *arg = new_symbol (child_die, NULL, cu);
7460
7461               if (arg != NULL)
7462                 VEC_safe_push (symbolp, template_args, arg);
7463             }
7464           else
7465             process_die (child_die, cu);
7466           child_die = sibling_die (child_die);
7467         }
7468     }
7469
7470   inherit_abstract_dies (die, cu);
7471
7472   /* If we have a DW_AT_specification, we might need to import using
7473      directives from the context of the specification DIE.  See the
7474      comment in determine_prefix.  */
7475   if (cu->language == language_cplus
7476       && dwarf2_attr (die, DW_AT_specification, cu))
7477     {
7478       struct dwarf2_cu *spec_cu = cu;
7479       struct die_info *spec_die = die_specification (die, &spec_cu);
7480
7481       while (spec_die)
7482         {
7483           child_die = spec_die->child;
7484           while (child_die && child_die->tag)
7485             {
7486               if (child_die->tag == DW_TAG_imported_module)
7487                 process_die (child_die, spec_cu);
7488               child_die = sibling_die (child_die);
7489             }
7490
7491           /* In some cases, GCC generates specification DIEs that
7492              themselves contain DW_AT_specification attributes.  */
7493           spec_die = die_specification (spec_die, &spec_cu);
7494         }
7495     }
7496
7497   new = pop_context ();
7498   /* Make a block for the local symbols within.  */
7499   block = finish_block (new->name, &local_symbols, new->old_blocks,
7500                         lowpc, highpc, objfile);
7501
7502   /* For C++, set the block's scope.  */
7503   if (cu->language == language_cplus || cu->language == language_fortran)
7504     cp_set_block_scope (new->name, block, &objfile->objfile_obstack,
7505                         determine_prefix (die, cu),
7506                         processing_has_namespace_info);
7507
7508   /* If we have address ranges, record them.  */
7509   dwarf2_record_block_ranges (die, block, baseaddr, cu);
7510
7511   /* Attach template arguments to function.  */
7512   if (! VEC_empty (symbolp, template_args))
7513     {
7514       gdb_assert (templ_func != NULL);
7515
7516       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
7517       templ_func->template_arguments
7518         = obstack_alloc (&objfile->objfile_obstack,
7519                          (templ_func->n_template_arguments
7520                           * sizeof (struct symbol *)));
7521       memcpy (templ_func->template_arguments,
7522               VEC_address (symbolp, template_args),
7523               (templ_func->n_template_arguments * sizeof (struct symbol *)));
7524       VEC_free (symbolp, template_args);
7525     }
7526
7527   /* In C++, we can have functions nested inside functions (e.g., when
7528      a function declares a class that has methods).  This means that
7529      when we finish processing a function scope, we may need to go
7530      back to building a containing block's symbol lists.  */
7531   local_symbols = new->locals;
7532   param_symbols = new->params;
7533   using_directives = new->using_directives;
7534
7535   /* If we've finished processing a top-level function, subsequent
7536      symbols go in the file symbol list.  */
7537   if (outermost_context_p ())
7538     cu->list_in_scope = &file_symbols;
7539 }
7540
7541 /* Process all the DIES contained within a lexical block scope.  Start
7542    a new scope, process the dies, and then close the scope.  */
7543
7544 static void
7545 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
7546 {
7547   struct objfile *objfile = cu->objfile;
7548   struct context_stack *new;
7549   CORE_ADDR lowpc, highpc;
7550   struct die_info *child_die;
7551   CORE_ADDR baseaddr;
7552
7553   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7554
7555   /* Ignore blocks with missing or invalid low and high pc attributes.  */
7556   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
7557      as multiple lexical blocks?  Handling children in a sane way would
7558      be nasty.  Might be easier to properly extend generic blocks to
7559      describe ranges.  */
7560   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
7561     return;
7562   lowpc += baseaddr;
7563   highpc += baseaddr;
7564
7565   push_context (0, lowpc);
7566   if (die->child != NULL)
7567     {
7568       child_die = die->child;
7569       while (child_die && child_die->tag)
7570         {
7571           process_die (child_die, cu);
7572           child_die = sibling_die (child_die);
7573         }
7574     }
7575   new = pop_context ();
7576
7577   if (local_symbols != NULL || using_directives != NULL)
7578     {
7579       struct block *block
7580         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
7581                         highpc, objfile);
7582
7583       /* Note that recording ranges after traversing children, as we
7584          do here, means that recording a parent's ranges entails
7585          walking across all its children's ranges as they appear in
7586          the address map, which is quadratic behavior.
7587
7588          It would be nicer to record the parent's ranges before
7589          traversing its children, simply overriding whatever you find
7590          there.  But since we don't even decide whether to create a
7591          block until after we've traversed its children, that's hard
7592          to do.  */
7593       dwarf2_record_block_ranges (die, block, baseaddr, cu);
7594     }
7595   local_symbols = new->locals;
7596   using_directives = new->using_directives;
7597 }
7598
7599 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
7600
7601 static void
7602 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
7603 {
7604   struct objfile *objfile = cu->objfile;
7605   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7606   CORE_ADDR pc, baseaddr;
7607   struct attribute *attr;
7608   struct call_site *call_site, call_site_local;
7609   void **slot;
7610   int nparams;
7611   struct die_info *child_die;
7612
7613   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7614
7615   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
7616   if (!attr)
7617     {
7618       complaint (&symfile_complaints,
7619                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
7620                    "DIE 0x%x [in module %s]"),
7621                  die->offset.sect_off, objfile->name);
7622       return;
7623     }
7624   pc = DW_ADDR (attr) + baseaddr;
7625
7626   if (cu->call_site_htab == NULL)
7627     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
7628                                                NULL, &objfile->objfile_obstack,
7629                                                hashtab_obstack_allocate, NULL);
7630   call_site_local.pc = pc;
7631   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
7632   if (*slot != NULL)
7633     {
7634       complaint (&symfile_complaints,
7635                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
7636                    "DIE 0x%x [in module %s]"),
7637                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
7638       return;
7639     }
7640
7641   /* Count parameters at the caller.  */
7642
7643   nparams = 0;
7644   for (child_die = die->child; child_die && child_die->tag;
7645        child_die = sibling_die (child_die))
7646     {
7647       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
7648         {
7649           complaint (&symfile_complaints,
7650                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
7651                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7652                      child_die->tag, child_die->offset.sect_off, objfile->name);
7653           continue;
7654         }
7655
7656       nparams++;
7657     }
7658
7659   call_site = obstack_alloc (&objfile->objfile_obstack,
7660                              (sizeof (*call_site)
7661                               + (sizeof (*call_site->parameter)
7662                                  * (nparams - 1))));
7663   *slot = call_site;
7664   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
7665   call_site->pc = pc;
7666
7667   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
7668     {
7669       struct die_info *func_die;
7670
7671       /* Skip also over DW_TAG_inlined_subroutine.  */
7672       for (func_die = die->parent;
7673            func_die && func_die->tag != DW_TAG_subprogram
7674            && func_die->tag != DW_TAG_subroutine_type;
7675            func_die = func_die->parent);
7676
7677       /* DW_AT_GNU_all_call_sites is a superset
7678          of DW_AT_GNU_all_tail_call_sites.  */
7679       if (func_die
7680           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
7681           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
7682         {
7683           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
7684              not complete.  But keep CALL_SITE for look ups via call_site_htab,
7685              both the initial caller containing the real return address PC and
7686              the final callee containing the current PC of a chain of tail
7687              calls do not need to have the tail call list complete.  But any
7688              function candidate for a virtual tail call frame searched via
7689              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
7690              determined unambiguously.  */
7691         }
7692       else
7693         {
7694           struct type *func_type = NULL;
7695
7696           if (func_die)
7697             func_type = get_die_type (func_die, cu);
7698           if (func_type != NULL)
7699             {
7700               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
7701
7702               /* Enlist this call site to the function.  */
7703               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
7704               TYPE_TAIL_CALL_LIST (func_type) = call_site;
7705             }
7706           else
7707             complaint (&symfile_complaints,
7708                        _("Cannot find function owning DW_TAG_GNU_call_site "
7709                          "DIE 0x%x [in module %s]"),
7710                        die->offset.sect_off, objfile->name);
7711         }
7712     }
7713
7714   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
7715   if (attr == NULL)
7716     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
7717   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
7718   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
7719     /* Keep NULL DWARF_BLOCK.  */;
7720   else if (attr_form_is_block (attr))
7721     {
7722       struct dwarf2_locexpr_baton *dlbaton;
7723
7724       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
7725       dlbaton->data = DW_BLOCK (attr)->data;
7726       dlbaton->size = DW_BLOCK (attr)->size;
7727       dlbaton->per_cu = cu->per_cu;
7728
7729       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
7730     }
7731   else if (is_ref_attr (attr))
7732     {
7733       struct dwarf2_cu *target_cu = cu;
7734       struct die_info *target_die;
7735
7736       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
7737       gdb_assert (target_cu->objfile == objfile);
7738       if (die_is_declaration (target_die, target_cu))
7739         {
7740           const char *target_physname;
7741
7742           target_physname = dwarf2_physname (NULL, target_die, target_cu);
7743           if (target_physname == NULL)
7744             complaint (&symfile_complaints,
7745                        _("DW_AT_GNU_call_site_target target DIE has invalid "
7746                          "physname, for referencing DIE 0x%x [in module %s]"),
7747                        die->offset.sect_off, objfile->name);
7748           else
7749             SET_FIELD_PHYSNAME (call_site->target, (char *) target_physname);
7750         }
7751       else
7752         {
7753           CORE_ADDR lowpc;
7754
7755           /* DW_AT_entry_pc should be preferred.  */
7756           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
7757             complaint (&symfile_complaints,
7758                        _("DW_AT_GNU_call_site_target target DIE has invalid "
7759                          "low pc, for referencing DIE 0x%x [in module %s]"),
7760                        die->offset.sect_off, objfile->name);
7761           else
7762             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
7763         }
7764     }
7765   else
7766     complaint (&symfile_complaints,
7767                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
7768                  "block nor reference, for DIE 0x%x [in module %s]"),
7769                die->offset.sect_off, objfile->name);
7770
7771   call_site->per_cu = cu->per_cu;
7772
7773   for (child_die = die->child;
7774        child_die && child_die->tag;
7775        child_die = sibling_die (child_die))
7776     {
7777       struct call_site_parameter *parameter;
7778
7779       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
7780         {
7781           /* Already printed the complaint above.  */
7782           continue;
7783         }
7784
7785       gdb_assert (call_site->parameter_count < nparams);
7786       parameter = &call_site->parameter[call_site->parameter_count];
7787
7788       /* DW_AT_location specifies the register number.  Value of the data
7789          assumed for the register is contained in DW_AT_GNU_call_site_value.  */
7790
7791       attr = dwarf2_attr (child_die, DW_AT_location, cu);
7792       if (!attr || !attr_form_is_block (attr))
7793         {
7794           complaint (&symfile_complaints,
7795                      _("No DW_FORM_block* DW_AT_location for "
7796                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7797                      child_die->offset.sect_off, objfile->name);
7798           continue;
7799         }
7800       parameter->dwarf_reg = dwarf_block_to_dwarf_reg (DW_BLOCK (attr)->data,
7801                                  &DW_BLOCK (attr)->data[DW_BLOCK (attr)->size]);
7802       if (parameter->dwarf_reg == -1
7803           && !dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (attr)->data,
7804                                   &DW_BLOCK (attr)->data[DW_BLOCK (attr)->size],
7805                                         &parameter->fb_offset))
7806         {
7807           complaint (&symfile_complaints,
7808                      _("Only single DW_OP_reg or DW_OP_fbreg is supported "
7809                        "for DW_FORM_block* DW_AT_location for "
7810                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7811                      child_die->offset.sect_off, objfile->name);
7812           continue;
7813         }
7814
7815       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
7816       if (!attr_form_is_block (attr))
7817         {
7818           complaint (&symfile_complaints,
7819                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
7820                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7821                      child_die->offset.sect_off, objfile->name);
7822           continue;
7823         }
7824       parameter->value = DW_BLOCK (attr)->data;
7825       parameter->value_size = DW_BLOCK (attr)->size;
7826
7827       /* Parameters are not pre-cleared by memset above.  */
7828       parameter->data_value = NULL;
7829       parameter->data_value_size = 0;
7830       call_site->parameter_count++;
7831
7832       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
7833       if (attr)
7834         {
7835           if (!attr_form_is_block (attr))
7836             complaint (&symfile_complaints,
7837                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
7838                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7839                        child_die->offset.sect_off, objfile->name);
7840           else
7841             {
7842               parameter->data_value = DW_BLOCK (attr)->data;
7843               parameter->data_value_size = DW_BLOCK (attr)->size;
7844             }
7845         }
7846     }
7847 }
7848
7849 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
7850    Return 1 if the attributes are present and valid, otherwise, return 0.
7851    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
7852
7853 static int
7854 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
7855                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
7856                     struct partial_symtab *ranges_pst)
7857 {
7858   struct objfile *objfile = cu->objfile;
7859   struct comp_unit_head *cu_header = &cu->header;
7860   bfd *obfd = objfile->obfd;
7861   unsigned int addr_size = cu_header->addr_size;
7862   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
7863   /* Base address selection entry.  */
7864   CORE_ADDR base;
7865   int found_base;
7866   unsigned int dummy;
7867   gdb_byte *buffer;
7868   CORE_ADDR marker;
7869   int low_set;
7870   CORE_ADDR low = 0;
7871   CORE_ADDR high = 0;
7872   CORE_ADDR baseaddr;
7873
7874   found_base = cu->base_known;
7875   base = cu->base_address;
7876
7877   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
7878   if (offset >= dwarf2_per_objfile->ranges.size)
7879     {
7880       complaint (&symfile_complaints,
7881                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
7882                  offset);
7883       return 0;
7884     }
7885   buffer = dwarf2_per_objfile->ranges.buffer + offset;
7886
7887   /* Read in the largest possible address.  */
7888   marker = read_address (obfd, buffer, cu, &dummy);
7889   if ((marker & mask) == mask)
7890     {
7891       /* If we found the largest possible address, then
7892          read the base address.  */
7893       base = read_address (obfd, buffer + addr_size, cu, &dummy);
7894       buffer += 2 * addr_size;
7895       offset += 2 * addr_size;
7896       found_base = 1;
7897     }
7898
7899   low_set = 0;
7900
7901   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7902
7903   while (1)
7904     {
7905       CORE_ADDR range_beginning, range_end;
7906
7907       range_beginning = read_address (obfd, buffer, cu, &dummy);
7908       buffer += addr_size;
7909       range_end = read_address (obfd, buffer, cu, &dummy);
7910       buffer += addr_size;
7911       offset += 2 * addr_size;
7912
7913       /* An end of list marker is a pair of zero addresses.  */
7914       if (range_beginning == 0 && range_end == 0)
7915         /* Found the end of list entry.  */
7916         break;
7917
7918       /* Each base address selection entry is a pair of 2 values.
7919          The first is the largest possible address, the second is
7920          the base address.  Check for a base address here.  */
7921       if ((range_beginning & mask) == mask)
7922         {
7923           /* If we found the largest possible address, then
7924              read the base address.  */
7925           base = read_address (obfd, buffer + addr_size, cu, &dummy);
7926           found_base = 1;
7927           continue;
7928         }
7929
7930       if (!found_base)
7931         {
7932           /* We have no valid base address for the ranges
7933              data.  */
7934           complaint (&symfile_complaints,
7935                      _("Invalid .debug_ranges data (no base address)"));
7936           return 0;
7937         }
7938
7939       if (range_beginning > range_end)
7940         {
7941           /* Inverted range entries are invalid.  */
7942           complaint (&symfile_complaints,
7943                      _("Invalid .debug_ranges data (inverted range)"));
7944           return 0;
7945         }
7946
7947       /* Empty range entries have no effect.  */
7948       if (range_beginning == range_end)
7949         continue;
7950
7951       range_beginning += base;
7952       range_end += base;
7953
7954       if (ranges_pst != NULL)
7955         addrmap_set_empty (objfile->psymtabs_addrmap,
7956                            range_beginning + baseaddr,
7957                            range_end - 1 + baseaddr,
7958                            ranges_pst);
7959
7960       /* FIXME: This is recording everything as a low-high
7961          segment of consecutive addresses.  We should have a
7962          data structure for discontiguous block ranges
7963          instead.  */
7964       if (! low_set)
7965         {
7966           low = range_beginning;
7967           high = range_end;
7968           low_set = 1;
7969         }
7970       else
7971         {
7972           if (range_beginning < low)
7973             low = range_beginning;
7974           if (range_end > high)
7975             high = range_end;
7976         }
7977     }
7978
7979   if (! low_set)
7980     /* If the first entry is an end-of-list marker, the range
7981        describes an empty scope, i.e. no instructions.  */
7982     return 0;
7983
7984   if (low_return)
7985     *low_return = low;
7986   if (high_return)
7987     *high_return = high;
7988   return 1;
7989 }
7990
7991 /* Get low and high pc attributes from a die.  Return 1 if the attributes
7992    are present and valid, otherwise, return 0.  Return -1 if the range is
7993    discontinuous, i.e. derived from DW_AT_ranges information.  */
7994
7995 static int
7996 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
7997                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
7998                       struct partial_symtab *pst)
7999 {
8000   struct attribute *attr;
8001   struct attribute *attr_high;
8002   CORE_ADDR low = 0;
8003   CORE_ADDR high = 0;
8004   int ret = 0;
8005
8006   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
8007   if (attr_high)
8008     {
8009       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
8010       if (attr)
8011         {
8012           low = DW_ADDR (attr);
8013           if (attr_high->form == DW_FORM_addr
8014               || attr_high->form == DW_FORM_GNU_addr_index)
8015             high = DW_ADDR (attr_high);
8016           else
8017             high = low + DW_UNSND (attr_high);
8018         }
8019       else
8020         /* Found high w/o low attribute.  */
8021         return 0;
8022
8023       /* Found consecutive range of addresses.  */
8024       ret = 1;
8025     }
8026   else
8027     {
8028       attr = dwarf2_attr (die, DW_AT_ranges, cu);
8029       if (attr != NULL)
8030         {
8031           /* Value of the DW_AT_ranges attribute is the offset in the
8032              .debug_ranges section.  */
8033           if (!dwarf2_ranges_read (DW_UNSND (attr), &low, &high, cu, pst))
8034             return 0;
8035           /* Found discontinuous range of addresses.  */
8036           ret = -1;
8037         }
8038     }
8039
8040   /* read_partial_die has also the strict LOW < HIGH requirement.  */
8041   if (high <= low)
8042     return 0;
8043
8044   /* When using the GNU linker, .gnu.linkonce. sections are used to
8045      eliminate duplicate copies of functions and vtables and such.
8046      The linker will arbitrarily choose one and discard the others.
8047      The AT_*_pc values for such functions refer to local labels in
8048      these sections.  If the section from that file was discarded, the
8049      labels are not in the output, so the relocs get a value of 0.
8050      If this is a discarded function, mark the pc bounds as invalid,
8051      so that GDB will ignore it.  */
8052   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
8053     return 0;
8054
8055   *lowpc = low;
8056   if (highpc)
8057     *highpc = high;
8058   return ret;
8059 }
8060
8061 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
8062    its low and high PC addresses.  Do nothing if these addresses could not
8063    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
8064    and HIGHPC to the high address if greater than HIGHPC.  */
8065
8066 static void
8067 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
8068                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
8069                                  struct dwarf2_cu *cu)
8070 {
8071   CORE_ADDR low, high;
8072   struct die_info *child = die->child;
8073
8074   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
8075     {
8076       *lowpc = min (*lowpc, low);
8077       *highpc = max (*highpc, high);
8078     }
8079
8080   /* If the language does not allow nested subprograms (either inside
8081      subprograms or lexical blocks), we're done.  */
8082   if (cu->language != language_ada)
8083     return;
8084
8085   /* Check all the children of the given DIE.  If it contains nested
8086      subprograms, then check their pc bounds.  Likewise, we need to
8087      check lexical blocks as well, as they may also contain subprogram
8088      definitions.  */
8089   while (child && child->tag)
8090     {
8091       if (child->tag == DW_TAG_subprogram
8092           || child->tag == DW_TAG_lexical_block)
8093         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
8094       child = sibling_die (child);
8095     }
8096 }
8097
8098 /* Get the low and high pc's represented by the scope DIE, and store
8099    them in *LOWPC and *HIGHPC.  If the correct values can't be
8100    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
8101
8102 static void
8103 get_scope_pc_bounds (struct die_info *die,
8104                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
8105                      struct dwarf2_cu *cu)
8106 {
8107   CORE_ADDR best_low = (CORE_ADDR) -1;
8108   CORE_ADDR best_high = (CORE_ADDR) 0;
8109   CORE_ADDR current_low, current_high;
8110
8111   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
8112     {
8113       best_low = current_low;
8114       best_high = current_high;
8115     }
8116   else
8117     {
8118       struct die_info *child = die->child;
8119
8120       while (child && child->tag)
8121         {
8122           switch (child->tag) {
8123           case DW_TAG_subprogram:
8124             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
8125             break;
8126           case DW_TAG_namespace:
8127           case DW_TAG_module:
8128             /* FIXME: carlton/2004-01-16: Should we do this for
8129                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
8130                that current GCC's always emit the DIEs corresponding
8131                to definitions of methods of classes as children of a
8132                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
8133                the DIEs giving the declarations, which could be
8134                anywhere).  But I don't see any reason why the
8135                standards says that they have to be there.  */
8136             get_scope_pc_bounds (child, &current_low, &current_high, cu);
8137
8138             if (current_low != ((CORE_ADDR) -1))
8139               {
8140                 best_low = min (best_low, current_low);
8141                 best_high = max (best_high, current_high);
8142               }
8143             break;
8144           default:
8145             /* Ignore.  */
8146             break;
8147           }
8148
8149           child = sibling_die (child);
8150         }
8151     }
8152
8153   *lowpc = best_low;
8154   *highpc = best_high;
8155 }
8156
8157 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
8158    in DIE.  */
8159
8160 static void
8161 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
8162                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
8163 {
8164   struct objfile *objfile = cu->objfile;
8165   struct attribute *attr;
8166   struct attribute *attr_high;
8167
8168   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
8169   if (attr_high)
8170     {
8171       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
8172       if (attr)
8173         {
8174           CORE_ADDR low = DW_ADDR (attr);
8175           CORE_ADDR high;
8176           if (attr_high->form == DW_FORM_addr
8177               || attr_high->form == DW_FORM_GNU_addr_index)
8178             high = DW_ADDR (attr_high);
8179           else
8180             high = low + DW_UNSND (attr_high);
8181
8182           record_block_range (block, baseaddr + low, baseaddr + high - 1);
8183         }
8184     }
8185
8186   attr = dwarf2_attr (die, DW_AT_ranges, cu);
8187   if (attr)
8188     {
8189       bfd *obfd = objfile->obfd;
8190
8191       /* The value of the DW_AT_ranges attribute is the offset of the
8192          address range list in the .debug_ranges section.  */
8193       unsigned long offset = DW_UNSND (attr);
8194       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
8195
8196       /* For some target architectures, but not others, the
8197          read_address function sign-extends the addresses it returns.
8198          To recognize base address selection entries, we need a
8199          mask.  */
8200       unsigned int addr_size = cu->header.addr_size;
8201       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
8202
8203       /* The base address, to which the next pair is relative.  Note
8204          that this 'base' is a DWARF concept: most entries in a range
8205          list are relative, to reduce the number of relocs against the
8206          debugging information.  This is separate from this function's
8207          'baseaddr' argument, which GDB uses to relocate debugging
8208          information from a shared library based on the address at
8209          which the library was loaded.  */
8210       CORE_ADDR base = cu->base_address;
8211       int base_known = cu->base_known;
8212
8213       gdb_assert (dwarf2_per_objfile->ranges.readin);
8214       if (offset >= dwarf2_per_objfile->ranges.size)
8215         {
8216           complaint (&symfile_complaints,
8217                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
8218                      offset);
8219           return;
8220         }
8221
8222       for (;;)
8223         {
8224           unsigned int bytes_read;
8225           CORE_ADDR start, end;
8226
8227           start = read_address (obfd, buffer, cu, &bytes_read);
8228           buffer += bytes_read;
8229           end = read_address (obfd, buffer, cu, &bytes_read);
8230           buffer += bytes_read;
8231
8232           /* Did we find the end of the range list?  */
8233           if (start == 0 && end == 0)
8234             break;
8235
8236           /* Did we find a base address selection entry?  */
8237           else if ((start & base_select_mask) == base_select_mask)
8238             {
8239               base = end;
8240               base_known = 1;
8241             }
8242
8243           /* We found an ordinary address range.  */
8244           else
8245             {
8246               if (!base_known)
8247                 {
8248                   complaint (&symfile_complaints,
8249                              _("Invalid .debug_ranges data "
8250                                "(no base address)"));
8251                   return;
8252                 }
8253
8254               if (start > end)
8255                 {
8256                   /* Inverted range entries are invalid.  */
8257                   complaint (&symfile_complaints,
8258                              _("Invalid .debug_ranges data "
8259                                "(inverted range)"));
8260                   return;
8261                 }
8262
8263               /* Empty range entries have no effect.  */
8264               if (start == end)
8265                 continue;
8266
8267               record_block_range (block,
8268                                   baseaddr + base + start,
8269                                   baseaddr + base + end - 1);
8270             }
8271         }
8272     }
8273 }
8274
8275 /* Check whether the producer field indicates either of GCC < 4.6, or the
8276    Intel C/C++ compiler, and cache the result in CU.  */
8277
8278 static void
8279 check_producer (struct dwarf2_cu *cu)
8280 {
8281   const char *cs;
8282   int major, minor, release;
8283
8284   if (cu->producer == NULL)
8285     {
8286       /* For unknown compilers expect their behavior is DWARF version
8287          compliant.
8288
8289          GCC started to support .debug_types sections by -gdwarf-4 since
8290          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
8291          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
8292          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
8293          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
8294     }
8295   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
8296     {
8297       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
8298
8299       cs = &cu->producer[strlen ("GNU ")];
8300       while (*cs && !isdigit (*cs))
8301         cs++;
8302       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
8303         {
8304           /* Not recognized as GCC.  */
8305         }
8306       else
8307         cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
8308     }
8309   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
8310     cu->producer_is_icc = 1;
8311   else
8312     {
8313       /* For other non-GCC compilers, expect their behavior is DWARF version
8314          compliant.  */
8315     }
8316
8317   cu->checked_producer = 1;
8318 }
8319
8320 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
8321    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
8322    during 4.6.0 experimental.  */
8323
8324 static int
8325 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
8326 {
8327   if (!cu->checked_producer)
8328     check_producer (cu);
8329
8330   return cu->producer_is_gxx_lt_4_6;
8331 }
8332
8333 /* Return the default accessibility type if it is not overriden by
8334    DW_AT_accessibility.  */
8335
8336 static enum dwarf_access_attribute
8337 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
8338 {
8339   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
8340     {
8341       /* The default DWARF 2 accessibility for members is public, the default
8342          accessibility for inheritance is private.  */
8343
8344       if (die->tag != DW_TAG_inheritance)
8345         return DW_ACCESS_public;
8346       else
8347         return DW_ACCESS_private;
8348     }
8349   else
8350     {
8351       /* DWARF 3+ defines the default accessibility a different way.  The same
8352          rules apply now for DW_TAG_inheritance as for the members and it only
8353          depends on the container kind.  */
8354
8355       if (die->parent->tag == DW_TAG_class_type)
8356         return DW_ACCESS_private;
8357       else
8358         return DW_ACCESS_public;
8359     }
8360 }
8361
8362 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
8363    offset.  If the attribute was not found return 0, otherwise return
8364    1.  If it was found but could not properly be handled, set *OFFSET
8365    to 0.  */
8366
8367 static int
8368 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
8369                              LONGEST *offset)
8370 {
8371   struct attribute *attr;
8372
8373   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
8374   if (attr != NULL)
8375     {
8376       *offset = 0;
8377
8378       /* Note that we do not check for a section offset first here.
8379          This is because DW_AT_data_member_location is new in DWARF 4,
8380          so if we see it, we can assume that a constant form is really
8381          a constant and not a section offset.  */
8382       if (attr_form_is_constant (attr))
8383         *offset = dwarf2_get_attr_constant_value (attr, 0);
8384       else if (attr_form_is_section_offset (attr))
8385         dwarf2_complex_location_expr_complaint ();
8386       else if (attr_form_is_block (attr))
8387         *offset = decode_locdesc (DW_BLOCK (attr), cu);
8388       else
8389         dwarf2_complex_location_expr_complaint ();
8390
8391       return 1;
8392     }
8393
8394   return 0;
8395 }
8396
8397 /* Add an aggregate field to the field list.  */
8398
8399 static void
8400 dwarf2_add_field (struct field_info *fip, struct die_info *die,
8401                   struct dwarf2_cu *cu)
8402 {
8403   struct objfile *objfile = cu->objfile;
8404   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8405   struct nextfield *new_field;
8406   struct attribute *attr;
8407   struct field *fp;
8408   char *fieldname = "";
8409
8410   /* Allocate a new field list entry and link it in.  */
8411   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
8412   make_cleanup (xfree, new_field);
8413   memset (new_field, 0, sizeof (struct nextfield));
8414
8415   if (die->tag == DW_TAG_inheritance)
8416     {
8417       new_field->next = fip->baseclasses;
8418       fip->baseclasses = new_field;
8419     }
8420   else
8421     {
8422       new_field->next = fip->fields;
8423       fip->fields = new_field;
8424     }
8425   fip->nfields++;
8426
8427   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
8428   if (attr)
8429     new_field->accessibility = DW_UNSND (attr);
8430   else
8431     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
8432   if (new_field->accessibility != DW_ACCESS_public)
8433     fip->non_public_fields = 1;
8434
8435   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
8436   if (attr)
8437     new_field->virtuality = DW_UNSND (attr);
8438   else
8439     new_field->virtuality = DW_VIRTUALITY_none;
8440
8441   fp = &new_field->field;
8442
8443   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
8444     {
8445       LONGEST offset;
8446
8447       /* Data member other than a C++ static data member.  */
8448
8449       /* Get type of field.  */
8450       fp->type = die_type (die, cu);
8451
8452       SET_FIELD_BITPOS (*fp, 0);
8453
8454       /* Get bit size of field (zero if none).  */
8455       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
8456       if (attr)
8457         {
8458           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
8459         }
8460       else
8461         {
8462           FIELD_BITSIZE (*fp) = 0;
8463         }
8464
8465       /* Get bit offset of field.  */
8466       if (handle_data_member_location (die, cu, &offset))
8467         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
8468       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
8469       if (attr)
8470         {
8471           if (gdbarch_bits_big_endian (gdbarch))
8472             {
8473               /* For big endian bits, the DW_AT_bit_offset gives the
8474                  additional bit offset from the MSB of the containing
8475                  anonymous object to the MSB of the field.  We don't
8476                  have to do anything special since we don't need to
8477                  know the size of the anonymous object.  */
8478               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
8479             }
8480           else
8481             {
8482               /* For little endian bits, compute the bit offset to the
8483                  MSB of the anonymous object, subtract off the number of
8484                  bits from the MSB of the field to the MSB of the
8485                  object, and then subtract off the number of bits of
8486                  the field itself.  The result is the bit offset of
8487                  the LSB of the field.  */
8488               int anonymous_size;
8489               int bit_offset = DW_UNSND (attr);
8490
8491               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
8492               if (attr)
8493                 {
8494                   /* The size of the anonymous object containing
8495                      the bit field is explicit, so use the
8496                      indicated size (in bytes).  */
8497                   anonymous_size = DW_UNSND (attr);
8498                 }
8499               else
8500                 {
8501                   /* The size of the anonymous object containing
8502                      the bit field must be inferred from the type
8503                      attribute of the data member containing the
8504                      bit field.  */
8505                   anonymous_size = TYPE_LENGTH (fp->type);
8506                 }
8507               SET_FIELD_BITPOS (*fp,
8508                                 (FIELD_BITPOS (*fp)
8509                                  + anonymous_size * bits_per_byte
8510                                  - bit_offset - FIELD_BITSIZE (*fp)));
8511             }
8512         }
8513
8514       /* Get name of field.  */
8515       fieldname = dwarf2_name (die, cu);
8516       if (fieldname == NULL)
8517         fieldname = "";
8518
8519       /* The name is already allocated along with this objfile, so we don't
8520          need to duplicate it for the type.  */
8521       fp->name = fieldname;
8522
8523       /* Change accessibility for artificial fields (e.g. virtual table
8524          pointer or virtual base class pointer) to private.  */
8525       if (dwarf2_attr (die, DW_AT_artificial, cu))
8526         {
8527           FIELD_ARTIFICIAL (*fp) = 1;
8528           new_field->accessibility = DW_ACCESS_private;
8529           fip->non_public_fields = 1;
8530         }
8531     }
8532   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
8533     {
8534       /* C++ static member.  */
8535
8536       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
8537          is a declaration, but all versions of G++ as of this writing
8538          (so through at least 3.2.1) incorrectly generate
8539          DW_TAG_variable tags.  */
8540
8541       const char *physname;
8542
8543       /* Get name of field.  */
8544       fieldname = dwarf2_name (die, cu);
8545       if (fieldname == NULL)
8546         return;
8547
8548       attr = dwarf2_attr (die, DW_AT_const_value, cu);
8549       if (attr
8550           /* Only create a symbol if this is an external value.
8551              new_symbol checks this and puts the value in the global symbol
8552              table, which we want.  If it is not external, new_symbol
8553              will try to put the value in cu->list_in_scope which is wrong.  */
8554           && dwarf2_flag_true_p (die, DW_AT_external, cu))
8555         {
8556           /* A static const member, not much different than an enum as far as
8557              we're concerned, except that we can support more types.  */
8558           new_symbol (die, NULL, cu);
8559         }
8560
8561       /* Get physical name.  */
8562       physname = dwarf2_physname (fieldname, die, cu);
8563
8564       /* The name is already allocated along with this objfile, so we don't
8565          need to duplicate it for the type.  */
8566       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
8567       FIELD_TYPE (*fp) = die_type (die, cu);
8568       FIELD_NAME (*fp) = fieldname;
8569     }
8570   else if (die->tag == DW_TAG_inheritance)
8571     {
8572       LONGEST offset;
8573
8574       /* C++ base class field.  */
8575       if (handle_data_member_location (die, cu, &offset))
8576         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
8577       FIELD_BITSIZE (*fp) = 0;
8578       FIELD_TYPE (*fp) = die_type (die, cu);
8579       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
8580       fip->nbaseclasses++;
8581     }
8582 }
8583
8584 /* Add a typedef defined in the scope of the FIP's class.  */
8585
8586 static void
8587 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
8588                     struct dwarf2_cu *cu)
8589 {
8590   struct objfile *objfile = cu->objfile;
8591   struct typedef_field_list *new_field;
8592   struct attribute *attr;
8593   struct typedef_field *fp;
8594   char *fieldname = "";
8595
8596   /* Allocate a new field list entry and link it in.  */
8597   new_field = xzalloc (sizeof (*new_field));
8598   make_cleanup (xfree, new_field);
8599
8600   gdb_assert (die->tag == DW_TAG_typedef);
8601
8602   fp = &new_field->field;
8603
8604   /* Get name of field.  */
8605   fp->name = dwarf2_name (die, cu);
8606   if (fp->name == NULL)
8607     return;
8608
8609   fp->type = read_type_die (die, cu);
8610
8611   new_field->next = fip->typedef_field_list;
8612   fip->typedef_field_list = new_field;
8613   fip->typedef_field_list_count++;
8614 }
8615
8616 /* Create the vector of fields, and attach it to the type.  */
8617
8618 static void
8619 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
8620                               struct dwarf2_cu *cu)
8621 {
8622   int nfields = fip->nfields;
8623
8624   /* Record the field count, allocate space for the array of fields,
8625      and create blank accessibility bitfields if necessary.  */
8626   TYPE_NFIELDS (type) = nfields;
8627   TYPE_FIELDS (type) = (struct field *)
8628     TYPE_ALLOC (type, sizeof (struct field) * nfields);
8629   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
8630
8631   if (fip->non_public_fields && cu->language != language_ada)
8632     {
8633       ALLOCATE_CPLUS_STRUCT_TYPE (type);
8634
8635       TYPE_FIELD_PRIVATE_BITS (type) =
8636         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
8637       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
8638
8639       TYPE_FIELD_PROTECTED_BITS (type) =
8640         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
8641       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
8642
8643       TYPE_FIELD_IGNORE_BITS (type) =
8644         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
8645       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
8646     }
8647
8648   /* If the type has baseclasses, allocate and clear a bit vector for
8649      TYPE_FIELD_VIRTUAL_BITS.  */
8650   if (fip->nbaseclasses && cu->language != language_ada)
8651     {
8652       int num_bytes = B_BYTES (fip->nbaseclasses);
8653       unsigned char *pointer;
8654
8655       ALLOCATE_CPLUS_STRUCT_TYPE (type);
8656       pointer = TYPE_ALLOC (type, num_bytes);
8657       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
8658       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
8659       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
8660     }
8661
8662   /* Copy the saved-up fields into the field vector.  Start from the head of
8663      the list, adding to the tail of the field array, so that they end up in
8664      the same order in the array in which they were added to the list.  */
8665   while (nfields-- > 0)
8666     {
8667       struct nextfield *fieldp;
8668
8669       if (fip->fields)
8670         {
8671           fieldp = fip->fields;
8672           fip->fields = fieldp->next;
8673         }
8674       else
8675         {
8676           fieldp = fip->baseclasses;
8677           fip->baseclasses = fieldp->next;
8678         }
8679
8680       TYPE_FIELD (type, nfields) = fieldp->field;
8681       switch (fieldp->accessibility)
8682         {
8683         case DW_ACCESS_private:
8684           if (cu->language != language_ada)
8685             SET_TYPE_FIELD_PRIVATE (type, nfields);
8686           break;
8687
8688         case DW_ACCESS_protected:
8689           if (cu->language != language_ada)
8690             SET_TYPE_FIELD_PROTECTED (type, nfields);
8691           break;
8692
8693         case DW_ACCESS_public:
8694           break;
8695
8696         default:
8697           /* Unknown accessibility.  Complain and treat it as public.  */
8698           {
8699             complaint (&symfile_complaints, _("unsupported accessibility %d"),
8700                        fieldp->accessibility);
8701           }
8702           break;
8703         }
8704       if (nfields < fip->nbaseclasses)
8705         {
8706           switch (fieldp->virtuality)
8707             {
8708             case DW_VIRTUALITY_virtual:
8709             case DW_VIRTUALITY_pure_virtual:
8710               if (cu->language == language_ada)
8711                 error (_("unexpected virtuality in component of Ada type"));
8712               SET_TYPE_FIELD_VIRTUAL (type, nfields);
8713               break;
8714             }
8715         }
8716     }
8717 }
8718
8719 /* Add a member function to the proper fieldlist.  */
8720
8721 static void
8722 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
8723                       struct type *type, struct dwarf2_cu *cu)
8724 {
8725   struct objfile *objfile = cu->objfile;
8726   struct attribute *attr;
8727   struct fnfieldlist *flp;
8728   int i;
8729   struct fn_field *fnp;
8730   char *fieldname;
8731   struct nextfnfield *new_fnfield;
8732   struct type *this_type;
8733   enum dwarf_access_attribute accessibility;
8734
8735   if (cu->language == language_ada)
8736     error (_("unexpected member function in Ada type"));
8737
8738   /* Get name of member function.  */
8739   fieldname = dwarf2_name (die, cu);
8740   if (fieldname == NULL)
8741     return;
8742
8743   /* Look up member function name in fieldlist.  */
8744   for (i = 0; i < fip->nfnfields; i++)
8745     {
8746       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
8747         break;
8748     }
8749
8750   /* Create new list element if necessary.  */
8751   if (i < fip->nfnfields)
8752     flp = &fip->fnfieldlists[i];
8753   else
8754     {
8755       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
8756         {
8757           fip->fnfieldlists = (struct fnfieldlist *)
8758             xrealloc (fip->fnfieldlists,
8759                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
8760                       * sizeof (struct fnfieldlist));
8761           if (fip->nfnfields == 0)
8762             make_cleanup (free_current_contents, &fip->fnfieldlists);
8763         }
8764       flp = &fip->fnfieldlists[fip->nfnfields];
8765       flp->name = fieldname;
8766       flp->length = 0;
8767       flp->head = NULL;
8768       i = fip->nfnfields++;
8769     }
8770
8771   /* Create a new member function field and chain it to the field list
8772      entry.  */
8773   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
8774   make_cleanup (xfree, new_fnfield);
8775   memset (new_fnfield, 0, sizeof (struct nextfnfield));
8776   new_fnfield->next = flp->head;
8777   flp->head = new_fnfield;
8778   flp->length++;
8779
8780   /* Fill in the member function field info.  */
8781   fnp = &new_fnfield->fnfield;
8782
8783   /* Delay processing of the physname until later.  */
8784   if (cu->language == language_cplus || cu->language == language_java)
8785     {
8786       add_to_method_list (type, i, flp->length - 1, fieldname,
8787                           die, cu);
8788     }
8789   else
8790     {
8791       const char *physname = dwarf2_physname (fieldname, die, cu);
8792       fnp->physname = physname ? physname : "";
8793     }
8794
8795   fnp->type = alloc_type (objfile);
8796   this_type = read_type_die (die, cu);
8797   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
8798     {
8799       int nparams = TYPE_NFIELDS (this_type);
8800
8801       /* TYPE is the domain of this method, and THIS_TYPE is the type
8802            of the method itself (TYPE_CODE_METHOD).  */
8803       smash_to_method_type (fnp->type, type,
8804                             TYPE_TARGET_TYPE (this_type),
8805                             TYPE_FIELDS (this_type),
8806                             TYPE_NFIELDS (this_type),
8807                             TYPE_VARARGS (this_type));
8808
8809       /* Handle static member functions.
8810          Dwarf2 has no clean way to discern C++ static and non-static
8811          member functions.  G++ helps GDB by marking the first
8812          parameter for non-static member functions (which is the this
8813          pointer) as artificial.  We obtain this information from
8814          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
8815       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
8816         fnp->voffset = VOFFSET_STATIC;
8817     }
8818   else
8819     complaint (&symfile_complaints, _("member function type missing for '%s'"),
8820                dwarf2_full_name (fieldname, die, cu));
8821
8822   /* Get fcontext from DW_AT_containing_type if present.  */
8823   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
8824     fnp->fcontext = die_containing_type (die, cu);
8825
8826   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
8827      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
8828
8829   /* Get accessibility.  */
8830   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
8831   if (attr)
8832     accessibility = DW_UNSND (attr);
8833   else
8834     accessibility = dwarf2_default_access_attribute (die, cu);
8835   switch (accessibility)
8836     {
8837     case DW_ACCESS_private:
8838       fnp->is_private = 1;
8839       break;
8840     case DW_ACCESS_protected:
8841       fnp->is_protected = 1;
8842       break;
8843     }
8844
8845   /* Check for artificial methods.  */
8846   attr = dwarf2_attr (die, DW_AT_artificial, cu);
8847   if (attr && DW_UNSND (attr) != 0)
8848     fnp->is_artificial = 1;
8849
8850   /* Get index in virtual function table if it is a virtual member
8851      function.  For older versions of GCC, this is an offset in the
8852      appropriate virtual table, as specified by DW_AT_containing_type.
8853      For everyone else, it is an expression to be evaluated relative
8854      to the object address.  */
8855
8856   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
8857   if (attr)
8858     {
8859       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
8860         {
8861           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
8862             {
8863               /* Old-style GCC.  */
8864               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
8865             }
8866           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
8867                    || (DW_BLOCK (attr)->size > 1
8868                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
8869                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
8870             {
8871               struct dwarf_block blk;
8872               int offset;
8873
8874               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
8875                         ? 1 : 2);
8876               blk.size = DW_BLOCK (attr)->size - offset;
8877               blk.data = DW_BLOCK (attr)->data + offset;
8878               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
8879               if ((fnp->voffset % cu->header.addr_size) != 0)
8880                 dwarf2_complex_location_expr_complaint ();
8881               else
8882                 fnp->voffset /= cu->header.addr_size;
8883               fnp->voffset += 2;
8884             }
8885           else
8886             dwarf2_complex_location_expr_complaint ();
8887
8888           if (!fnp->fcontext)
8889             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
8890         }
8891       else if (attr_form_is_section_offset (attr))
8892         {
8893           dwarf2_complex_location_expr_complaint ();
8894         }
8895       else
8896         {
8897           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
8898                                                  fieldname);
8899         }
8900     }
8901   else
8902     {
8903       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
8904       if (attr && DW_UNSND (attr))
8905         {
8906           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
8907           complaint (&symfile_complaints,
8908                      _("Member function \"%s\" (offset %d) is virtual "
8909                        "but the vtable offset is not specified"),
8910                      fieldname, die->offset.sect_off);
8911           ALLOCATE_CPLUS_STRUCT_TYPE (type);
8912           TYPE_CPLUS_DYNAMIC (type) = 1;
8913         }
8914     }
8915 }
8916
8917 /* Create the vector of member function fields, and attach it to the type.  */
8918
8919 static void
8920 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
8921                                  struct dwarf2_cu *cu)
8922 {
8923   struct fnfieldlist *flp;
8924   int i;
8925
8926   if (cu->language == language_ada)
8927     error (_("unexpected member functions in Ada type"));
8928
8929   ALLOCATE_CPLUS_STRUCT_TYPE (type);
8930   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
8931     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
8932
8933   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
8934     {
8935       struct nextfnfield *nfp = flp->head;
8936       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
8937       int k;
8938
8939       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
8940       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
8941       fn_flp->fn_fields = (struct fn_field *)
8942         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
8943       for (k = flp->length; (k--, nfp); nfp = nfp->next)
8944         fn_flp->fn_fields[k] = nfp->fnfield;
8945     }
8946
8947   TYPE_NFN_FIELDS (type) = fip->nfnfields;
8948 }
8949
8950 /* Returns non-zero if NAME is the name of a vtable member in CU's
8951    language, zero otherwise.  */
8952 static int
8953 is_vtable_name (const char *name, struct dwarf2_cu *cu)
8954 {
8955   static const char vptr[] = "_vptr";
8956   static const char vtable[] = "vtable";
8957
8958   /* Look for the C++ and Java forms of the vtable.  */
8959   if ((cu->language == language_java
8960        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
8961        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
8962        && is_cplus_marker (name[sizeof (vptr) - 1])))
8963     return 1;
8964
8965   return 0;
8966 }
8967
8968 /* GCC outputs unnamed structures that are really pointers to member
8969    functions, with the ABI-specified layout.  If TYPE describes
8970    such a structure, smash it into a member function type.
8971
8972    GCC shouldn't do this; it should just output pointer to member DIEs.
8973    This is GCC PR debug/28767.  */
8974
8975 static void
8976 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
8977 {
8978   struct type *pfn_type, *domain_type, *new_type;
8979
8980   /* Check for a structure with no name and two children.  */
8981   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
8982     return;
8983
8984   /* Check for __pfn and __delta members.  */
8985   if (TYPE_FIELD_NAME (type, 0) == NULL
8986       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
8987       || TYPE_FIELD_NAME (type, 1) == NULL
8988       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
8989     return;
8990
8991   /* Find the type of the method.  */
8992   pfn_type = TYPE_FIELD_TYPE (type, 0);
8993   if (pfn_type == NULL
8994       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
8995       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
8996     return;
8997
8998   /* Look for the "this" argument.  */
8999   pfn_type = TYPE_TARGET_TYPE (pfn_type);
9000   if (TYPE_NFIELDS (pfn_type) == 0
9001       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
9002       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
9003     return;
9004
9005   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
9006   new_type = alloc_type (objfile);
9007   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
9008                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
9009                         TYPE_VARARGS (pfn_type));
9010   smash_to_methodptr_type (type, new_type);
9011 }
9012
9013 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
9014    (icc).  */
9015
9016 static int
9017 producer_is_icc (struct dwarf2_cu *cu)
9018 {
9019   if (!cu->checked_producer)
9020     check_producer (cu);
9021
9022   return cu->producer_is_icc;
9023 }
9024
9025 /* Called when we find the DIE that starts a structure or union scope
9026    (definition) to create a type for the structure or union.  Fill in
9027    the type's name and general properties; the members will not be
9028    processed until process_structure_type.
9029
9030    NOTE: we need to call these functions regardless of whether or not the
9031    DIE has a DW_AT_name attribute, since it might be an anonymous
9032    structure or union.  This gets the type entered into our set of
9033    user defined types.
9034
9035    However, if the structure is incomplete (an opaque struct/union)
9036    then suppress creating a symbol table entry for it since gdb only
9037    wants to find the one with the complete definition.  Note that if
9038    it is complete, we just call new_symbol, which does it's own
9039    checking about whether the struct/union is anonymous or not (and
9040    suppresses creating a symbol table entry itself).  */
9041
9042 static struct type *
9043 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
9044 {
9045   struct objfile *objfile = cu->objfile;
9046   struct type *type;
9047   struct attribute *attr;
9048   char *name;
9049
9050   /* If the definition of this type lives in .debug_types, read that type.
9051      Don't follow DW_AT_specification though, that will take us back up
9052      the chain and we want to go down.  */
9053   attr = dwarf2_attr_no_follow (die, DW_AT_signature, cu);
9054   if (attr)
9055     {
9056       struct dwarf2_cu *type_cu = cu;
9057       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
9058
9059       /* We could just recurse on read_structure_type, but we need to call
9060          get_die_type to ensure only one type for this DIE is created.
9061          This is important, for example, because for c++ classes we need
9062          TYPE_NAME set which is only done by new_symbol.  Blech.  */
9063       type = read_type_die (type_die, type_cu);
9064
9065       /* TYPE_CU may not be the same as CU.
9066          Ensure TYPE is recorded in CU's type_hash table.  */
9067       return set_die_type (die, type, cu);
9068     }
9069
9070   type = alloc_type (objfile);
9071   INIT_CPLUS_SPECIFIC (type);
9072
9073   name = dwarf2_name (die, cu);
9074   if (name != NULL)
9075     {
9076       if (cu->language == language_cplus
9077           || cu->language == language_java)
9078         {
9079           char *full_name = (char *) dwarf2_full_name (name, die, cu);
9080
9081           /* dwarf2_full_name might have already finished building the DIE's
9082              type.  If so, there is no need to continue.  */
9083           if (get_die_type (die, cu) != NULL)
9084             return get_die_type (die, cu);
9085
9086           TYPE_TAG_NAME (type) = full_name;
9087           if (die->tag == DW_TAG_structure_type
9088               || die->tag == DW_TAG_class_type)
9089             TYPE_NAME (type) = TYPE_TAG_NAME (type);
9090         }
9091       else
9092         {
9093           /* The name is already allocated along with this objfile, so
9094              we don't need to duplicate it for the type.  */
9095           TYPE_TAG_NAME (type) = (char *) name;
9096           if (die->tag == DW_TAG_class_type)
9097             TYPE_NAME (type) = TYPE_TAG_NAME (type);
9098         }
9099     }
9100
9101   if (die->tag == DW_TAG_structure_type)
9102     {
9103       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9104     }
9105   else if (die->tag == DW_TAG_union_type)
9106     {
9107       TYPE_CODE (type) = TYPE_CODE_UNION;
9108     }
9109   else
9110     {
9111       TYPE_CODE (type) = TYPE_CODE_CLASS;
9112     }
9113
9114   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
9115     TYPE_DECLARED_CLASS (type) = 1;
9116
9117   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9118   if (attr)
9119     {
9120       TYPE_LENGTH (type) = DW_UNSND (attr);
9121     }
9122   else
9123     {
9124       TYPE_LENGTH (type) = 0;
9125     }
9126
9127   if (producer_is_icc (cu))
9128     {
9129       /* ICC does not output the required DW_AT_declaration
9130          on incomplete types, but gives them a size of zero.  */
9131     }
9132   else
9133     TYPE_STUB_SUPPORTED (type) = 1;
9134
9135   if (die_is_declaration (die, cu))
9136     TYPE_STUB (type) = 1;
9137   else if (attr == NULL && die->child == NULL
9138            && producer_is_realview (cu->producer))
9139     /* RealView does not output the required DW_AT_declaration
9140        on incomplete types.  */
9141     TYPE_STUB (type) = 1;
9142
9143   /* We need to add the type field to the die immediately so we don't
9144      infinitely recurse when dealing with pointers to the structure
9145      type within the structure itself.  */
9146   set_die_type (die, type, cu);
9147
9148   /* set_die_type should be already done.  */
9149   set_descriptive_type (type, die, cu);
9150
9151   return type;
9152 }
9153
9154 /* Finish creating a structure or union type, including filling in
9155    its members and creating a symbol for it.  */
9156
9157 static void
9158 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
9159 {
9160   struct objfile *objfile = cu->objfile;
9161   struct die_info *child_die = die->child;
9162   struct type *type;
9163
9164   type = get_die_type (die, cu);
9165   if (type == NULL)
9166     type = read_structure_type (die, cu);
9167
9168   if (die->child != NULL && ! die_is_declaration (die, cu))
9169     {
9170       struct field_info fi;
9171       struct die_info *child_die;
9172       VEC (symbolp) *template_args = NULL;
9173       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
9174
9175       memset (&fi, 0, sizeof (struct field_info));
9176
9177       child_die = die->child;
9178
9179       while (child_die && child_die->tag)
9180         {
9181           if (child_die->tag == DW_TAG_member
9182               || child_die->tag == DW_TAG_variable)
9183             {
9184               /* NOTE: carlton/2002-11-05: A C++ static data member
9185                  should be a DW_TAG_member that is a declaration, but
9186                  all versions of G++ as of this writing (so through at
9187                  least 3.2.1) incorrectly generate DW_TAG_variable
9188                  tags for them instead.  */
9189               dwarf2_add_field (&fi, child_die, cu);
9190             }
9191           else if (child_die->tag == DW_TAG_subprogram)
9192             {
9193               /* C++ member function.  */
9194               dwarf2_add_member_fn (&fi, child_die, type, cu);
9195             }
9196           else if (child_die->tag == DW_TAG_inheritance)
9197             {
9198               /* C++ base class field.  */
9199               dwarf2_add_field (&fi, child_die, cu);
9200             }
9201           else if (child_die->tag == DW_TAG_typedef)
9202             dwarf2_add_typedef (&fi, child_die, cu);
9203           else if (child_die->tag == DW_TAG_template_type_param
9204                    || child_die->tag == DW_TAG_template_value_param)
9205             {
9206               struct symbol *arg = new_symbol (child_die, NULL, cu);
9207
9208               if (arg != NULL)
9209                 VEC_safe_push (symbolp, template_args, arg);
9210             }
9211
9212           child_die = sibling_die (child_die);
9213         }
9214
9215       /* Attach template arguments to type.  */
9216       if (! VEC_empty (symbolp, template_args))
9217         {
9218           ALLOCATE_CPLUS_STRUCT_TYPE (type);
9219           TYPE_N_TEMPLATE_ARGUMENTS (type)
9220             = VEC_length (symbolp, template_args);
9221           TYPE_TEMPLATE_ARGUMENTS (type)
9222             = obstack_alloc (&objfile->objfile_obstack,
9223                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
9224                               * sizeof (struct symbol *)));
9225           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
9226                   VEC_address (symbolp, template_args),
9227                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
9228                    * sizeof (struct symbol *)));
9229           VEC_free (symbolp, template_args);
9230         }
9231
9232       /* Attach fields and member functions to the type.  */
9233       if (fi.nfields)
9234         dwarf2_attach_fields_to_type (&fi, type, cu);
9235       if (fi.nfnfields)
9236         {
9237           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
9238
9239           /* Get the type which refers to the base class (possibly this
9240              class itself) which contains the vtable pointer for the current
9241              class from the DW_AT_containing_type attribute.  This use of
9242              DW_AT_containing_type is a GNU extension.  */
9243
9244           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
9245             {
9246               struct type *t = die_containing_type (die, cu);
9247
9248               TYPE_VPTR_BASETYPE (type) = t;
9249               if (type == t)
9250                 {
9251                   int i;
9252
9253                   /* Our own class provides vtbl ptr.  */
9254                   for (i = TYPE_NFIELDS (t) - 1;
9255                        i >= TYPE_N_BASECLASSES (t);
9256                        --i)
9257                     {
9258                       const char *fieldname = TYPE_FIELD_NAME (t, i);
9259
9260                       if (is_vtable_name (fieldname, cu))
9261                         {
9262                           TYPE_VPTR_FIELDNO (type) = i;
9263                           break;
9264                         }
9265                     }
9266
9267                   /* Complain if virtual function table field not found.  */
9268                   if (i < TYPE_N_BASECLASSES (t))
9269                     complaint (&symfile_complaints,
9270                                _("virtual function table pointer "
9271                                  "not found when defining class '%s'"),
9272                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
9273                                "");
9274                 }
9275               else
9276                 {
9277                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
9278                 }
9279             }
9280           else if (cu->producer
9281                    && strncmp (cu->producer,
9282                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
9283             {
9284               /* The IBM XLC compiler does not provide direct indication
9285                  of the containing type, but the vtable pointer is
9286                  always named __vfp.  */
9287
9288               int i;
9289
9290               for (i = TYPE_NFIELDS (type) - 1;
9291                    i >= TYPE_N_BASECLASSES (type);
9292                    --i)
9293                 {
9294                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
9295                     {
9296                       TYPE_VPTR_FIELDNO (type) = i;
9297                       TYPE_VPTR_BASETYPE (type) = type;
9298                       break;
9299                     }
9300                 }
9301             }
9302         }
9303
9304       /* Copy fi.typedef_field_list linked list elements content into the
9305          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
9306       if (fi.typedef_field_list)
9307         {
9308           int i = fi.typedef_field_list_count;
9309
9310           ALLOCATE_CPLUS_STRUCT_TYPE (type);
9311           TYPE_TYPEDEF_FIELD_ARRAY (type)
9312             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
9313           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
9314
9315           /* Reverse the list order to keep the debug info elements order.  */
9316           while (--i >= 0)
9317             {
9318               struct typedef_field *dest, *src;
9319
9320               dest = &TYPE_TYPEDEF_FIELD (type, i);
9321               src = &fi.typedef_field_list->field;
9322               fi.typedef_field_list = fi.typedef_field_list->next;
9323               *dest = *src;
9324             }
9325         }
9326
9327       do_cleanups (back_to);
9328
9329       if (HAVE_CPLUS_STRUCT (type))
9330         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
9331     }
9332
9333   quirk_gcc_member_function_pointer (type, objfile);
9334
9335   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
9336      snapshots) has been known to create a die giving a declaration
9337      for a class that has, as a child, a die giving a definition for a
9338      nested class.  So we have to process our children even if the
9339      current die is a declaration.  Normally, of course, a declaration
9340      won't have any children at all.  */
9341
9342   while (child_die != NULL && child_die->tag)
9343     {
9344       if (child_die->tag == DW_TAG_member
9345           || child_die->tag == DW_TAG_variable
9346           || child_die->tag == DW_TAG_inheritance
9347           || child_die->tag == DW_TAG_template_value_param
9348           || child_die->tag == DW_TAG_template_type_param)
9349         {
9350           /* Do nothing.  */
9351         }
9352       else
9353         process_die (child_die, cu);
9354
9355       child_die = sibling_die (child_die);
9356     }
9357
9358   /* Do not consider external references.  According to the DWARF standard,
9359      these DIEs are identified by the fact that they have no byte_size
9360      attribute, and a declaration attribute.  */
9361   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
9362       || !die_is_declaration (die, cu))
9363     new_symbol (die, type, cu);
9364 }
9365
9366 /* Given a DW_AT_enumeration_type die, set its type.  We do not
9367    complete the type's fields yet, or create any symbols.  */
9368
9369 static struct type *
9370 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
9371 {
9372   struct objfile *objfile = cu->objfile;
9373   struct type *type;
9374   struct attribute *attr;
9375   const char *name;
9376
9377   /* If the definition of this type lives in .debug_types, read that type.
9378      Don't follow DW_AT_specification though, that will take us back up
9379      the chain and we want to go down.  */
9380   attr = dwarf2_attr_no_follow (die, DW_AT_signature, cu);
9381   if (attr)
9382     {
9383       struct dwarf2_cu *type_cu = cu;
9384       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
9385
9386       type = read_type_die (type_die, type_cu);
9387
9388       /* TYPE_CU may not be the same as CU.
9389          Ensure TYPE is recorded in CU's type_hash table.  */
9390       return set_die_type (die, type, cu);
9391     }
9392
9393   type = alloc_type (objfile);
9394
9395   TYPE_CODE (type) = TYPE_CODE_ENUM;
9396   name = dwarf2_full_name (NULL, die, cu);
9397   if (name != NULL)
9398     TYPE_TAG_NAME (type) = (char *) name;
9399
9400   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9401   if (attr)
9402     {
9403       TYPE_LENGTH (type) = DW_UNSND (attr);
9404     }
9405   else
9406     {
9407       TYPE_LENGTH (type) = 0;
9408     }
9409
9410   /* The enumeration DIE can be incomplete.  In Ada, any type can be
9411      declared as private in the package spec, and then defined only
9412      inside the package body.  Such types are known as Taft Amendment
9413      Types.  When another package uses such a type, an incomplete DIE
9414      may be generated by the compiler.  */
9415   if (die_is_declaration (die, cu))
9416     TYPE_STUB (type) = 1;
9417
9418   return set_die_type (die, type, cu);
9419 }
9420
9421 /* Given a pointer to a die which begins an enumeration, process all
9422    the dies that define the members of the enumeration, and create the
9423    symbol for the enumeration type.
9424
9425    NOTE: We reverse the order of the element list.  */
9426
9427 static void
9428 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
9429 {
9430   struct type *this_type;
9431
9432   this_type = get_die_type (die, cu);
9433   if (this_type == NULL)
9434     this_type = read_enumeration_type (die, cu);
9435
9436   if (die->child != NULL)
9437     {
9438       struct die_info *child_die;
9439       struct symbol *sym;
9440       struct field *fields = NULL;
9441       int num_fields = 0;
9442       int unsigned_enum = 1;
9443       char *name;
9444       int flag_enum = 1;
9445       ULONGEST mask = 0;
9446
9447       child_die = die->child;
9448       while (child_die && child_die->tag)
9449         {
9450           if (child_die->tag != DW_TAG_enumerator)
9451             {
9452               process_die (child_die, cu);
9453             }
9454           else
9455             {
9456               name = dwarf2_name (child_die, cu);
9457               if (name)
9458                 {
9459                   sym = new_symbol (child_die, this_type, cu);
9460                   if (SYMBOL_VALUE (sym) < 0)
9461                     {
9462                       unsigned_enum = 0;
9463                       flag_enum = 0;
9464                     }
9465                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
9466                     flag_enum = 0;
9467                   else
9468                     mask |= SYMBOL_VALUE (sym);
9469
9470                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
9471                     {
9472                       fields = (struct field *)
9473                         xrealloc (fields,
9474                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
9475                                   * sizeof (struct field));
9476                     }
9477
9478                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
9479                   FIELD_TYPE (fields[num_fields]) = NULL;
9480                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
9481                   FIELD_BITSIZE (fields[num_fields]) = 0;
9482
9483                   num_fields++;
9484                 }
9485             }
9486
9487           child_die = sibling_die (child_die);
9488         }
9489
9490       if (num_fields)
9491         {
9492           TYPE_NFIELDS (this_type) = num_fields;
9493           TYPE_FIELDS (this_type) = (struct field *)
9494             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
9495           memcpy (TYPE_FIELDS (this_type), fields,
9496                   sizeof (struct field) * num_fields);
9497           xfree (fields);
9498         }
9499       if (unsigned_enum)
9500         TYPE_UNSIGNED (this_type) = 1;
9501       if (flag_enum)
9502         TYPE_FLAG_ENUM (this_type) = 1;
9503     }
9504
9505   /* If we are reading an enum from a .debug_types unit, and the enum
9506      is a declaration, and the enum is not the signatured type in the
9507      unit, then we do not want to add a symbol for it.  Adding a
9508      symbol would in some cases obscure the true definition of the
9509      enum, giving users an incomplete type when the definition is
9510      actually available.  Note that we do not want to do this for all
9511      enums which are just declarations, because C++0x allows forward
9512      enum declarations.  */
9513   if (cu->per_cu->is_debug_types
9514       && die_is_declaration (die, cu))
9515     {
9516       struct signatured_type *sig_type;
9517
9518       sig_type
9519         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
9520                                             cu->per_cu->info_or_types_section,
9521                                             cu->per_cu->offset);
9522       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
9523       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
9524         return;
9525     }
9526
9527   new_symbol (die, this_type, cu);
9528 }
9529
9530 /* Extract all information from a DW_TAG_array_type DIE and put it in
9531    the DIE's type field.  For now, this only handles one dimensional
9532    arrays.  */
9533
9534 static struct type *
9535 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
9536 {
9537   struct objfile *objfile = cu->objfile;
9538   struct die_info *child_die;
9539   struct type *type;
9540   struct type *element_type, *range_type, *index_type;
9541   struct type **range_types = NULL;
9542   struct attribute *attr;
9543   int ndim = 0;
9544   struct cleanup *back_to;
9545   char *name;
9546
9547   element_type = die_type (die, cu);
9548
9549   /* The die_type call above may have already set the type for this DIE.  */
9550   type = get_die_type (die, cu);
9551   if (type)
9552     return type;
9553
9554   /* Irix 6.2 native cc creates array types without children for
9555      arrays with unspecified length.  */
9556   if (die->child == NULL)
9557     {
9558       index_type = objfile_type (objfile)->builtin_int;
9559       range_type = create_range_type (NULL, index_type, 0, -1);
9560       type = create_array_type (NULL, element_type, range_type);
9561       return set_die_type (die, type, cu);
9562     }
9563
9564   back_to = make_cleanup (null_cleanup, NULL);
9565   child_die = die->child;
9566   while (child_die && child_die->tag)
9567     {
9568       if (child_die->tag == DW_TAG_subrange_type)
9569         {
9570           struct type *child_type = read_type_die (child_die, cu);
9571
9572           if (child_type != NULL)
9573             {
9574               /* The range type was succesfully read.  Save it for the
9575                  array type creation.  */
9576               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
9577                 {
9578                   range_types = (struct type **)
9579                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
9580                               * sizeof (struct type *));
9581                   if (ndim == 0)
9582                     make_cleanup (free_current_contents, &range_types);
9583                 }
9584               range_types[ndim++] = child_type;
9585             }
9586         }
9587       child_die = sibling_die (child_die);
9588     }
9589
9590   /* Dwarf2 dimensions are output from left to right, create the
9591      necessary array types in backwards order.  */
9592
9593   type = element_type;
9594
9595   if (read_array_order (die, cu) == DW_ORD_col_major)
9596     {
9597       int i = 0;
9598
9599       while (i < ndim)
9600         type = create_array_type (NULL, type, range_types[i++]);
9601     }
9602   else
9603     {
9604       while (ndim-- > 0)
9605         type = create_array_type (NULL, type, range_types[ndim]);
9606     }
9607
9608   /* Understand Dwarf2 support for vector types (like they occur on
9609      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
9610      array type.  This is not part of the Dwarf2/3 standard yet, but a
9611      custom vendor extension.  The main difference between a regular
9612      array and the vector variant is that vectors are passed by value
9613      to functions.  */
9614   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
9615   if (attr)
9616     make_vector_type (type);
9617
9618   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
9619      implementation may choose to implement triple vectors using this
9620      attribute.  */
9621   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9622   if (attr)
9623     {
9624       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
9625         TYPE_LENGTH (type) = DW_UNSND (attr);
9626       else
9627         complaint (&symfile_complaints,
9628                    _("DW_AT_byte_size for array type smaller "
9629                      "than the total size of elements"));
9630     }
9631
9632   name = dwarf2_name (die, cu);
9633   if (name)
9634     TYPE_NAME (type) = name;
9635
9636   /* Install the type in the die.  */
9637   set_die_type (die, type, cu);
9638
9639   /* set_die_type should be already done.  */
9640   set_descriptive_type (type, die, cu);
9641
9642   do_cleanups (back_to);
9643
9644   return type;
9645 }
9646
9647 static enum dwarf_array_dim_ordering
9648 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
9649 {
9650   struct attribute *attr;
9651
9652   attr = dwarf2_attr (die, DW_AT_ordering, cu);
9653
9654   if (attr) return DW_SND (attr);
9655
9656   /* GNU F77 is a special case, as at 08/2004 array type info is the
9657      opposite order to the dwarf2 specification, but data is still
9658      laid out as per normal fortran.
9659
9660      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
9661      version checking.  */
9662
9663   if (cu->language == language_fortran
9664       && cu->producer && strstr (cu->producer, "GNU F77"))
9665     {
9666       return DW_ORD_row_major;
9667     }
9668
9669   switch (cu->language_defn->la_array_ordering)
9670     {
9671     case array_column_major:
9672       return DW_ORD_col_major;
9673     case array_row_major:
9674     default:
9675       return DW_ORD_row_major;
9676     };
9677 }
9678
9679 /* Extract all information from a DW_TAG_set_type DIE and put it in
9680    the DIE's type field.  */
9681
9682 static struct type *
9683 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
9684 {
9685   struct type *domain_type, *set_type;
9686   struct attribute *attr;
9687
9688   domain_type = die_type (die, cu);
9689
9690   /* The die_type call above may have already set the type for this DIE.  */
9691   set_type = get_die_type (die, cu);
9692   if (set_type)
9693     return set_type;
9694
9695   set_type = create_set_type (NULL, domain_type);
9696
9697   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9698   if (attr)
9699     TYPE_LENGTH (set_type) = DW_UNSND (attr);
9700
9701   return set_die_type (die, set_type, cu);
9702 }
9703
9704 /* First cut: install each common block member as a global variable.  */
9705
9706 static void
9707 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
9708 {
9709   struct die_info *child_die;
9710   struct attribute *attr;
9711   struct symbol *sym;
9712   CORE_ADDR base = (CORE_ADDR) 0;
9713
9714   attr = dwarf2_attr (die, DW_AT_location, cu);
9715   if (attr)
9716     {
9717       /* Support the .debug_loc offsets.  */
9718       if (attr_form_is_block (attr))
9719         {
9720           base = decode_locdesc (DW_BLOCK (attr), cu);
9721         }
9722       else if (attr_form_is_section_offset (attr))
9723         {
9724           dwarf2_complex_location_expr_complaint ();
9725         }
9726       else
9727         {
9728           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
9729                                                  "common block member");
9730         }
9731     }
9732   if (die->child != NULL)
9733     {
9734       child_die = die->child;
9735       while (child_die && child_die->tag)
9736         {
9737           LONGEST offset;
9738
9739           sym = new_symbol (child_die, NULL, cu);
9740           if (sym != NULL
9741               && handle_data_member_location (child_die, cu, &offset))
9742             {
9743               SYMBOL_VALUE_ADDRESS (sym) = base + offset;
9744               add_symbol_to_list (sym, &global_symbols);
9745             }
9746           child_die = sibling_die (child_die);
9747         }
9748     }
9749 }
9750
9751 /* Create a type for a C++ namespace.  */
9752
9753 static struct type *
9754 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
9755 {
9756   struct objfile *objfile = cu->objfile;
9757   const char *previous_prefix, *name;
9758   int is_anonymous;
9759   struct type *type;
9760
9761   /* For extensions, reuse the type of the original namespace.  */
9762   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
9763     {
9764       struct die_info *ext_die;
9765       struct dwarf2_cu *ext_cu = cu;
9766
9767       ext_die = dwarf2_extension (die, &ext_cu);
9768       type = read_type_die (ext_die, ext_cu);
9769
9770       /* EXT_CU may not be the same as CU.
9771          Ensure TYPE is recorded in CU's type_hash table.  */
9772       return set_die_type (die, type, cu);
9773     }
9774
9775   name = namespace_name (die, &is_anonymous, cu);
9776
9777   /* Now build the name of the current namespace.  */
9778
9779   previous_prefix = determine_prefix (die, cu);
9780   if (previous_prefix[0] != '\0')
9781     name = typename_concat (&objfile->objfile_obstack,
9782                             previous_prefix, name, 0, cu);
9783
9784   /* Create the type.  */
9785   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
9786                     objfile);
9787   TYPE_NAME (type) = (char *) name;
9788   TYPE_TAG_NAME (type) = TYPE_NAME (type);
9789
9790   return set_die_type (die, type, cu);
9791 }
9792
9793 /* Read a C++ namespace.  */
9794
9795 static void
9796 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
9797 {
9798   struct objfile *objfile = cu->objfile;
9799   int is_anonymous;
9800
9801   /* Add a symbol associated to this if we haven't seen the namespace
9802      before.  Also, add a using directive if it's an anonymous
9803      namespace.  */
9804
9805   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
9806     {
9807       struct type *type;
9808
9809       type = read_type_die (die, cu);
9810       new_symbol (die, type, cu);
9811
9812       namespace_name (die, &is_anonymous, cu);
9813       if (is_anonymous)
9814         {
9815           const char *previous_prefix = determine_prefix (die, cu);
9816
9817           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
9818                                   NULL, NULL, &objfile->objfile_obstack);
9819         }
9820     }
9821
9822   if (die->child != NULL)
9823     {
9824       struct die_info *child_die = die->child;
9825
9826       while (child_die && child_die->tag)
9827         {
9828           process_die (child_die, cu);
9829           child_die = sibling_die (child_die);
9830         }
9831     }
9832 }
9833
9834 /* Read a Fortran module as type.  This DIE can be only a declaration used for
9835    imported module.  Still we need that type as local Fortran "use ... only"
9836    declaration imports depend on the created type in determine_prefix.  */
9837
9838 static struct type *
9839 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
9840 {
9841   struct objfile *objfile = cu->objfile;
9842   char *module_name;
9843   struct type *type;
9844
9845   module_name = dwarf2_name (die, cu);
9846   if (!module_name)
9847     complaint (&symfile_complaints,
9848                _("DW_TAG_module has no name, offset 0x%x"),
9849                die->offset.sect_off);
9850   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
9851
9852   /* determine_prefix uses TYPE_TAG_NAME.  */
9853   TYPE_TAG_NAME (type) = TYPE_NAME (type);
9854
9855   return set_die_type (die, type, cu);
9856 }
9857
9858 /* Read a Fortran module.  */
9859
9860 static void
9861 read_module (struct die_info *die, struct dwarf2_cu *cu)
9862 {
9863   struct die_info *child_die = die->child;
9864
9865   while (child_die && child_die->tag)
9866     {
9867       process_die (child_die, cu);
9868       child_die = sibling_die (child_die);
9869     }
9870 }
9871
9872 /* Return the name of the namespace represented by DIE.  Set
9873    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
9874    namespace.  */
9875
9876 static const char *
9877 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
9878 {
9879   struct die_info *current_die;
9880   const char *name = NULL;
9881
9882   /* Loop through the extensions until we find a name.  */
9883
9884   for (current_die = die;
9885        current_die != NULL;
9886        current_die = dwarf2_extension (die, &cu))
9887     {
9888       name = dwarf2_name (current_die, cu);
9889       if (name != NULL)
9890         break;
9891     }
9892
9893   /* Is it an anonymous namespace?  */
9894
9895   *is_anonymous = (name == NULL);
9896   if (*is_anonymous)
9897     name = CP_ANONYMOUS_NAMESPACE_STR;
9898
9899   return name;
9900 }
9901
9902 /* Extract all information from a DW_TAG_pointer_type DIE and add to
9903    the user defined type vector.  */
9904
9905 static struct type *
9906 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
9907 {
9908   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
9909   struct comp_unit_head *cu_header = &cu->header;
9910   struct type *type;
9911   struct attribute *attr_byte_size;
9912   struct attribute *attr_address_class;
9913   int byte_size, addr_class;
9914   struct type *target_type;
9915
9916   target_type = die_type (die, cu);
9917
9918   /* The die_type call above may have already set the type for this DIE.  */
9919   type = get_die_type (die, cu);
9920   if (type)
9921     return type;
9922
9923   type = lookup_pointer_type (target_type);
9924
9925   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
9926   if (attr_byte_size)
9927     byte_size = DW_UNSND (attr_byte_size);
9928   else
9929     byte_size = cu_header->addr_size;
9930
9931   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
9932   if (attr_address_class)
9933     addr_class = DW_UNSND (attr_address_class);
9934   else
9935     addr_class = DW_ADDR_none;
9936
9937   /* If the pointer size or address class is different than the
9938      default, create a type variant marked as such and set the
9939      length accordingly.  */
9940   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
9941     {
9942       if (gdbarch_address_class_type_flags_p (gdbarch))
9943         {
9944           int type_flags;
9945
9946           type_flags = gdbarch_address_class_type_flags
9947                          (gdbarch, byte_size, addr_class);
9948           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
9949                       == 0);
9950           type = make_type_with_address_space (type, type_flags);
9951         }
9952       else if (TYPE_LENGTH (type) != byte_size)
9953         {
9954           complaint (&symfile_complaints,
9955                      _("invalid pointer size %d"), byte_size);
9956         }
9957       else
9958         {
9959           /* Should we also complain about unhandled address classes?  */
9960         }
9961     }
9962
9963   TYPE_LENGTH (type) = byte_size;
9964   return set_die_type (die, type, cu);
9965 }
9966
9967 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
9968    the user defined type vector.  */
9969
9970 static struct type *
9971 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
9972 {
9973   struct type *type;
9974   struct type *to_type;
9975   struct type *domain;
9976
9977   to_type = die_type (die, cu);
9978   domain = die_containing_type (die, cu);
9979
9980   /* The calls above may have already set the type for this DIE.  */
9981   type = get_die_type (die, cu);
9982   if (type)
9983     return type;
9984
9985   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
9986     type = lookup_methodptr_type (to_type);
9987   else
9988     type = lookup_memberptr_type (to_type, domain);
9989
9990   return set_die_type (die, type, cu);
9991 }
9992
9993 /* Extract all information from a DW_TAG_reference_type DIE and add to
9994    the user defined type vector.  */
9995
9996 static struct type *
9997 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
9998 {
9999   struct comp_unit_head *cu_header = &cu->header;
10000   struct type *type, *target_type;
10001   struct attribute *attr;
10002
10003   target_type = die_type (die, cu);
10004
10005   /* The die_type call above may have already set the type for this DIE.  */
10006   type = get_die_type (die, cu);
10007   if (type)
10008     return type;
10009
10010   type = lookup_reference_type (target_type);
10011   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10012   if (attr)
10013     {
10014       TYPE_LENGTH (type) = DW_UNSND (attr);
10015     }
10016   else
10017     {
10018       TYPE_LENGTH (type) = cu_header->addr_size;
10019     }
10020   return set_die_type (die, type, cu);
10021 }
10022
10023 static struct type *
10024 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
10025 {
10026   struct type *base_type, *cv_type;
10027
10028   base_type = die_type (die, cu);
10029
10030   /* The die_type call above may have already set the type for this DIE.  */
10031   cv_type = get_die_type (die, cu);
10032   if (cv_type)
10033     return cv_type;
10034
10035   /* In case the const qualifier is applied to an array type, the element type
10036      is so qualified, not the array type (section 6.7.3 of C99).  */
10037   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
10038     {
10039       struct type *el_type, *inner_array;
10040
10041       base_type = copy_type (base_type);
10042       inner_array = base_type;
10043
10044       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
10045         {
10046           TYPE_TARGET_TYPE (inner_array) =
10047             copy_type (TYPE_TARGET_TYPE (inner_array));
10048           inner_array = TYPE_TARGET_TYPE (inner_array);
10049         }
10050
10051       el_type = TYPE_TARGET_TYPE (inner_array);
10052       TYPE_TARGET_TYPE (inner_array) =
10053         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
10054
10055       return set_die_type (die, base_type, cu);
10056     }
10057
10058   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
10059   return set_die_type (die, cv_type, cu);
10060 }
10061
10062 static struct type *
10063 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
10064 {
10065   struct type *base_type, *cv_type;
10066
10067   base_type = die_type (die, cu);
10068
10069   /* The die_type call above may have already set the type for this DIE.  */
10070   cv_type = get_die_type (die, cu);
10071   if (cv_type)
10072     return cv_type;
10073
10074   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
10075   return set_die_type (die, cv_type, cu);
10076 }
10077
10078 /* Extract all information from a DW_TAG_string_type DIE and add to
10079    the user defined type vector.  It isn't really a user defined type,
10080    but it behaves like one, with other DIE's using an AT_user_def_type
10081    attribute to reference it.  */
10082
10083 static struct type *
10084 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
10085 {
10086   struct objfile *objfile = cu->objfile;
10087   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10088   struct type *type, *range_type, *index_type, *char_type;
10089   struct attribute *attr;
10090   unsigned int length;
10091
10092   attr = dwarf2_attr (die, DW_AT_string_length, cu);
10093   if (attr)
10094     {
10095       length = DW_UNSND (attr);
10096     }
10097   else
10098     {
10099       /* Check for the DW_AT_byte_size attribute.  */
10100       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10101       if (attr)
10102         {
10103           length = DW_UNSND (attr);
10104         }
10105       else
10106         {
10107           length = 1;
10108         }
10109     }
10110
10111   index_type = objfile_type (objfile)->builtin_int;
10112   range_type = create_range_type (NULL, index_type, 1, length);
10113   char_type = language_string_char_type (cu->language_defn, gdbarch);
10114   type = create_string_type (NULL, char_type, range_type);
10115
10116   return set_die_type (die, type, cu);
10117 }
10118
10119 /* Handle DIES due to C code like:
10120
10121    struct foo
10122    {
10123    int (*funcp)(int a, long l);
10124    int b;
10125    };
10126
10127    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
10128
10129 static struct type *
10130 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
10131 {
10132   struct objfile *objfile = cu->objfile;
10133   struct type *type;            /* Type that this function returns.  */
10134   struct type *ftype;           /* Function that returns above type.  */
10135   struct attribute *attr;
10136
10137   type = die_type (die, cu);
10138
10139   /* The die_type call above may have already set the type for this DIE.  */
10140   ftype = get_die_type (die, cu);
10141   if (ftype)
10142     return ftype;
10143
10144   ftype = lookup_function_type (type);
10145
10146   /* All functions in C++, Pascal and Java have prototypes.  */
10147   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
10148   if ((attr && (DW_UNSND (attr) != 0))
10149       || cu->language == language_cplus
10150       || cu->language == language_java
10151       || cu->language == language_pascal)
10152     TYPE_PROTOTYPED (ftype) = 1;
10153   else if (producer_is_realview (cu->producer))
10154     /* RealView does not emit DW_AT_prototyped.  We can not
10155        distinguish prototyped and unprototyped functions; default to
10156        prototyped, since that is more common in modern code (and
10157        RealView warns about unprototyped functions).  */
10158     TYPE_PROTOTYPED (ftype) = 1;
10159
10160   /* Store the calling convention in the type if it's available in
10161      the subroutine die.  Otherwise set the calling convention to
10162      the default value DW_CC_normal.  */
10163   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
10164   if (attr)
10165     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
10166   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
10167     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
10168   else
10169     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
10170
10171   /* We need to add the subroutine type to the die immediately so
10172      we don't infinitely recurse when dealing with parameters
10173      declared as the same subroutine type.  */
10174   set_die_type (die, ftype, cu);
10175
10176   if (die->child != NULL)
10177     {
10178       struct type *void_type = objfile_type (objfile)->builtin_void;
10179       struct die_info *child_die;
10180       int nparams, iparams;
10181
10182       /* Count the number of parameters.
10183          FIXME: GDB currently ignores vararg functions, but knows about
10184          vararg member functions.  */
10185       nparams = 0;
10186       child_die = die->child;
10187       while (child_die && child_die->tag)
10188         {
10189           if (child_die->tag == DW_TAG_formal_parameter)
10190             nparams++;
10191           else if (child_die->tag == DW_TAG_unspecified_parameters)
10192             TYPE_VARARGS (ftype) = 1;
10193           child_die = sibling_die (child_die);
10194         }
10195
10196       /* Allocate storage for parameters and fill them in.  */
10197       TYPE_NFIELDS (ftype) = nparams;
10198       TYPE_FIELDS (ftype) = (struct field *)
10199         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
10200
10201       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
10202          even if we error out during the parameters reading below.  */
10203       for (iparams = 0; iparams < nparams; iparams++)
10204         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
10205
10206       iparams = 0;
10207       child_die = die->child;
10208       while (child_die && child_die->tag)
10209         {
10210           if (child_die->tag == DW_TAG_formal_parameter)
10211             {
10212               struct type *arg_type;
10213
10214               /* DWARF version 2 has no clean way to discern C++
10215                  static and non-static member functions.  G++ helps
10216                  GDB by marking the first parameter for non-static
10217                  member functions (which is the this pointer) as
10218                  artificial.  We pass this information to
10219                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
10220
10221                  DWARF version 3 added DW_AT_object_pointer, which GCC
10222                  4.5 does not yet generate.  */
10223               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
10224               if (attr)
10225                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
10226               else
10227                 {
10228                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
10229
10230                   /* GCC/43521: In java, the formal parameter
10231                      "this" is sometimes not marked with DW_AT_artificial.  */
10232                   if (cu->language == language_java)
10233                     {
10234                       const char *name = dwarf2_name (child_die, cu);
10235
10236                       if (name && !strcmp (name, "this"))
10237                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
10238                     }
10239                 }
10240               arg_type = die_type (child_die, cu);
10241
10242               /* RealView does not mark THIS as const, which the testsuite
10243                  expects.  GCC marks THIS as const in method definitions,
10244                  but not in the class specifications (GCC PR 43053).  */
10245               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
10246                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
10247                 {
10248                   int is_this = 0;
10249                   struct dwarf2_cu *arg_cu = cu;
10250                   const char *name = dwarf2_name (child_die, cu);
10251
10252                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
10253                   if (attr)
10254                     {
10255                       /* If the compiler emits this, use it.  */
10256                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
10257                         is_this = 1;
10258                     }
10259                   else if (name && strcmp (name, "this") == 0)
10260                     /* Function definitions will have the argument names.  */
10261                     is_this = 1;
10262                   else if (name == NULL && iparams == 0)
10263                     /* Declarations may not have the names, so like
10264                        elsewhere in GDB, assume an artificial first
10265                        argument is "this".  */
10266                     is_this = 1;
10267
10268                   if (is_this)
10269                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
10270                                              arg_type, 0);
10271                 }
10272
10273               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
10274               iparams++;
10275             }
10276           child_die = sibling_die (child_die);
10277         }
10278     }
10279
10280   return ftype;
10281 }
10282
10283 static struct type *
10284 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
10285 {
10286   struct objfile *objfile = cu->objfile;
10287   const char *name = NULL;
10288   struct type *this_type, *target_type;
10289
10290   name = dwarf2_full_name (NULL, die, cu);
10291   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
10292                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
10293   TYPE_NAME (this_type) = (char *) name;
10294   set_die_type (die, this_type, cu);
10295   target_type = die_type (die, cu);
10296   if (target_type != this_type)
10297     TYPE_TARGET_TYPE (this_type) = target_type;
10298   else
10299     {
10300       /* Self-referential typedefs are, it seems, not allowed by the DWARF
10301          spec and cause infinite loops in GDB.  */
10302       complaint (&symfile_complaints,
10303                  _("Self-referential DW_TAG_typedef "
10304                    "- DIE at 0x%x [in module %s]"),
10305                  die->offset.sect_off, objfile->name);
10306       TYPE_TARGET_TYPE (this_type) = NULL;
10307     }
10308   return this_type;
10309 }
10310
10311 /* Find a representation of a given base type and install
10312    it in the TYPE field of the die.  */
10313
10314 static struct type *
10315 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
10316 {
10317   struct objfile *objfile = cu->objfile;
10318   struct type *type;
10319   struct attribute *attr;
10320   int encoding = 0, size = 0;
10321   char *name;
10322   enum type_code code = TYPE_CODE_INT;
10323   int type_flags = 0;
10324   struct type *target_type = NULL;
10325
10326   attr = dwarf2_attr (die, DW_AT_encoding, cu);
10327   if (attr)
10328     {
10329       encoding = DW_UNSND (attr);
10330     }
10331   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10332   if (attr)
10333     {
10334       size = DW_UNSND (attr);
10335     }
10336   name = dwarf2_name (die, cu);
10337   if (!name)
10338     {
10339       complaint (&symfile_complaints,
10340                  _("DW_AT_name missing from DW_TAG_base_type"));
10341     }
10342
10343   switch (encoding)
10344     {
10345       case DW_ATE_address:
10346         /* Turn DW_ATE_address into a void * pointer.  */
10347         code = TYPE_CODE_PTR;
10348         type_flags |= TYPE_FLAG_UNSIGNED;
10349         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
10350         break;
10351       case DW_ATE_boolean:
10352         code = TYPE_CODE_BOOL;
10353         type_flags |= TYPE_FLAG_UNSIGNED;
10354         break;
10355       case DW_ATE_complex_float:
10356         code = TYPE_CODE_COMPLEX;
10357         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
10358         break;
10359       case DW_ATE_decimal_float:
10360         code = TYPE_CODE_DECFLOAT;
10361         break;
10362       case DW_ATE_float:
10363         code = TYPE_CODE_FLT;
10364         break;
10365       case DW_ATE_signed:
10366         break;
10367       case DW_ATE_unsigned:
10368         type_flags |= TYPE_FLAG_UNSIGNED;
10369         if (cu->language == language_fortran
10370             && name
10371             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
10372           code = TYPE_CODE_CHAR;
10373         break;
10374       case DW_ATE_signed_char:
10375         if (cu->language == language_ada || cu->language == language_m2
10376             || cu->language == language_pascal
10377             || cu->language == language_fortran)
10378           code = TYPE_CODE_CHAR;
10379         break;
10380       case DW_ATE_unsigned_char:
10381         if (cu->language == language_ada || cu->language == language_m2
10382             || cu->language == language_pascal
10383             || cu->language == language_fortran)
10384           code = TYPE_CODE_CHAR;
10385         type_flags |= TYPE_FLAG_UNSIGNED;
10386         break;
10387       case DW_ATE_UTF:
10388         /* We just treat this as an integer and then recognize the
10389            type by name elsewhere.  */
10390         break;
10391
10392       default:
10393         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
10394                    dwarf_type_encoding_name (encoding));
10395         break;
10396     }
10397
10398   type = init_type (code, size, type_flags, NULL, objfile);
10399   TYPE_NAME (type) = name;
10400   TYPE_TARGET_TYPE (type) = target_type;
10401
10402   if (name && strcmp (name, "char") == 0)
10403     TYPE_NOSIGN (type) = 1;
10404
10405   return set_die_type (die, type, cu);
10406 }
10407
10408 /* Read the given DW_AT_subrange DIE.  */
10409
10410 static struct type *
10411 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
10412 {
10413   struct type *base_type;
10414   struct type *range_type;
10415   struct attribute *attr;
10416   LONGEST low, high;
10417   int low_default_is_valid;
10418   char *name;
10419   LONGEST negative_mask;
10420
10421   base_type = die_type (die, cu);
10422   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
10423   check_typedef (base_type);
10424
10425   /* The die_type call above may have already set the type for this DIE.  */
10426   range_type = get_die_type (die, cu);
10427   if (range_type)
10428     return range_type;
10429
10430   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
10431      omitting DW_AT_lower_bound.  */
10432   switch (cu->language)
10433     {
10434     case language_c:
10435     case language_cplus:
10436       low = 0;
10437       low_default_is_valid = 1;
10438       break;
10439     case language_fortran:
10440       low = 1;
10441       low_default_is_valid = 1;
10442       break;
10443     case language_d:
10444     case language_java:
10445     case language_objc:
10446       low = 0;
10447       low_default_is_valid = (cu->header.version >= 4);
10448       break;
10449     case language_ada:
10450     case language_m2:
10451     case language_pascal:
10452       low = 1;
10453       low_default_is_valid = (cu->header.version >= 4);
10454       break;
10455     default:
10456       low = 0;
10457       low_default_is_valid = 0;
10458       break;
10459     }
10460
10461   /* FIXME: For variable sized arrays either of these could be
10462      a variable rather than a constant value.  We'll allow it,
10463      but we don't know how to handle it.  */
10464   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
10465   if (attr)
10466     low = dwarf2_get_attr_constant_value (attr, low);
10467   else if (!low_default_is_valid)
10468     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
10469                                       "- DIE at 0x%x [in module %s]"),
10470                die->offset.sect_off, cu->objfile->name);
10471
10472   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
10473   if (attr)
10474     {
10475       if (attr_form_is_block (attr) || is_ref_attr (attr))
10476         {
10477           /* GCC encodes arrays with unspecified or dynamic length
10478              with a DW_FORM_block1 attribute or a reference attribute.
10479              FIXME: GDB does not yet know how to handle dynamic
10480              arrays properly, treat them as arrays with unspecified
10481              length for now.
10482
10483              FIXME: jimb/2003-09-22: GDB does not really know
10484              how to handle arrays of unspecified length
10485              either; we just represent them as zero-length
10486              arrays.  Choose an appropriate upper bound given
10487              the lower bound we've computed above.  */
10488           high = low - 1;
10489         }
10490       else
10491         high = dwarf2_get_attr_constant_value (attr, 1);
10492     }
10493   else
10494     {
10495       attr = dwarf2_attr (die, DW_AT_count, cu);
10496       if (attr)
10497         {
10498           int count = dwarf2_get_attr_constant_value (attr, 1);
10499           high = low + count - 1;
10500         }
10501       else
10502         {
10503           /* Unspecified array length.  */
10504           high = low - 1;
10505         }
10506     }
10507
10508   /* Dwarf-2 specifications explicitly allows to create subrange types
10509      without specifying a base type.
10510      In that case, the base type must be set to the type of
10511      the lower bound, upper bound or count, in that order, if any of these
10512      three attributes references an object that has a type.
10513      If no base type is found, the Dwarf-2 specifications say that
10514      a signed integer type of size equal to the size of an address should
10515      be used.
10516      For the following C code: `extern char gdb_int [];'
10517      GCC produces an empty range DIE.
10518      FIXME: muller/2010-05-28: Possible references to object for low bound,
10519      high bound or count are not yet handled by this code.  */
10520   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
10521     {
10522       struct objfile *objfile = cu->objfile;
10523       struct gdbarch *gdbarch = get_objfile_arch (objfile);
10524       int addr_size = gdbarch_addr_bit (gdbarch) /8;
10525       struct type *int_type = objfile_type (objfile)->builtin_int;
10526
10527       /* Test "int", "long int", and "long long int" objfile types,
10528          and select the first one having a size above or equal to the
10529          architecture address size.  */
10530       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
10531         base_type = int_type;
10532       else
10533         {
10534           int_type = objfile_type (objfile)->builtin_long;
10535           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
10536             base_type = int_type;
10537           else
10538             {
10539               int_type = objfile_type (objfile)->builtin_long_long;
10540               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
10541                 base_type = int_type;
10542             }
10543         }
10544     }
10545
10546   negative_mask =
10547     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
10548   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
10549     low |= negative_mask;
10550   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
10551     high |= negative_mask;
10552
10553   range_type = create_range_type (NULL, base_type, low, high);
10554
10555   /* Mark arrays with dynamic length at least as an array of unspecified
10556      length.  GDB could check the boundary but before it gets implemented at
10557      least allow accessing the array elements.  */
10558   if (attr && attr_form_is_block (attr))
10559     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
10560
10561   /* Ada expects an empty array on no boundary attributes.  */
10562   if (attr == NULL && cu->language != language_ada)
10563     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
10564
10565   name = dwarf2_name (die, cu);
10566   if (name)
10567     TYPE_NAME (range_type) = name;
10568
10569   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10570   if (attr)
10571     TYPE_LENGTH (range_type) = DW_UNSND (attr);
10572
10573   set_die_type (die, range_type, cu);
10574
10575   /* set_die_type should be already done.  */
10576   set_descriptive_type (range_type, die, cu);
10577
10578   return range_type;
10579 }
10580
10581 static struct type *
10582 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
10583 {
10584   struct type *type;
10585
10586   /* For now, we only support the C meaning of an unspecified type: void.  */
10587
10588   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
10589   TYPE_NAME (type) = dwarf2_name (die, cu);
10590
10591   return set_die_type (die, type, cu);
10592 }
10593
10594 /* Read a single die and all its descendents.  Set the die's sibling
10595    field to NULL; set other fields in the die correctly, and set all
10596    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
10597    location of the info_ptr after reading all of those dies.  PARENT
10598    is the parent of the die in question.  */
10599
10600 static struct die_info *
10601 read_die_and_children (const struct die_reader_specs *reader,
10602                        gdb_byte *info_ptr,
10603                        gdb_byte **new_info_ptr,
10604                        struct die_info *parent)
10605 {
10606   struct die_info *die;
10607   gdb_byte *cur_ptr;
10608   int has_children;
10609
10610   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
10611   if (die == NULL)
10612     {
10613       *new_info_ptr = cur_ptr;
10614       return NULL;
10615     }
10616   store_in_ref_table (die, reader->cu);
10617
10618   if (has_children)
10619     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
10620   else
10621     {
10622       die->child = NULL;
10623       *new_info_ptr = cur_ptr;
10624     }
10625
10626   die->sibling = NULL;
10627   die->parent = parent;
10628   return die;
10629 }
10630
10631 /* Read a die, all of its descendents, and all of its siblings; set
10632    all of the fields of all of the dies correctly.  Arguments are as
10633    in read_die_and_children.  */
10634
10635 static struct die_info *
10636 read_die_and_siblings (const struct die_reader_specs *reader,
10637                        gdb_byte *info_ptr,
10638                        gdb_byte **new_info_ptr,
10639                        struct die_info *parent)
10640 {
10641   struct die_info *first_die, *last_sibling;
10642   gdb_byte *cur_ptr;
10643
10644   cur_ptr = info_ptr;
10645   first_die = last_sibling = NULL;
10646
10647   while (1)
10648     {
10649       struct die_info *die
10650         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
10651
10652       if (die == NULL)
10653         {
10654           *new_info_ptr = cur_ptr;
10655           return first_die;
10656         }
10657
10658       if (!first_die)
10659         first_die = die;
10660       else
10661         last_sibling->sibling = die;
10662
10663       last_sibling = die;
10664     }
10665 }
10666
10667 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
10668    attributes.
10669    The caller is responsible for filling in the extra attributes
10670    and updating (*DIEP)->num_attrs.
10671    Set DIEP to point to a newly allocated die with its information,
10672    except for its child, sibling, and parent fields.
10673    Set HAS_CHILDREN to tell whether the die has children or not.  */
10674
10675 static gdb_byte *
10676 read_full_die_1 (const struct die_reader_specs *reader,
10677                  struct die_info **diep, gdb_byte *info_ptr,
10678                  int *has_children, int num_extra_attrs)
10679 {
10680   unsigned int abbrev_number, bytes_read, i;
10681   sect_offset offset;
10682   struct abbrev_info *abbrev;
10683   struct die_info *die;
10684   struct dwarf2_cu *cu = reader->cu;
10685   bfd *abfd = reader->abfd;
10686
10687   offset.sect_off = info_ptr - reader->buffer;
10688   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
10689   info_ptr += bytes_read;
10690   if (!abbrev_number)
10691     {
10692       *diep = NULL;
10693       *has_children = 0;
10694       return info_ptr;
10695     }
10696
10697   abbrev = dwarf2_lookup_abbrev (abbrev_number, cu);
10698   if (!abbrev)
10699     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
10700            abbrev_number,
10701            bfd_get_filename (abfd));
10702
10703   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
10704   die->offset = offset;
10705   die->tag = abbrev->tag;
10706   die->abbrev = abbrev_number;
10707
10708   /* Make the result usable.
10709      The caller needs to update num_attrs after adding the extra
10710      attributes.  */
10711   die->num_attrs = abbrev->num_attrs;
10712
10713   for (i = 0; i < abbrev->num_attrs; ++i)
10714     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
10715                                info_ptr);
10716
10717   *diep = die;
10718   *has_children = abbrev->has_children;
10719   return info_ptr;
10720 }
10721
10722 /* Read a die and all its attributes.
10723    Set DIEP to point to a newly allocated die with its information,
10724    except for its child, sibling, and parent fields.
10725    Set HAS_CHILDREN to tell whether the die has children or not.  */
10726
10727 static gdb_byte *
10728 read_full_die (const struct die_reader_specs *reader,
10729                struct die_info **diep, gdb_byte *info_ptr,
10730                int *has_children)
10731 {
10732   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
10733 }
10734
10735 /* In DWARF version 2, the description of the debugging information is
10736    stored in a separate .debug_abbrev section.  Before we read any
10737    dies from a section we read in all abbreviations and install them
10738    in a hash table.  This function also sets flags in CU describing
10739    the data found in the abbrev table.  */
10740
10741 static void
10742 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
10743                      struct dwarf2_section_info *abbrev_section)
10744
10745 {
10746   bfd *abfd = abbrev_section->asection->owner;
10747   struct comp_unit_head *cu_header = &cu->header;
10748   gdb_byte *abbrev_ptr;
10749   struct abbrev_info *cur_abbrev;
10750   unsigned int abbrev_number, bytes_read, abbrev_name;
10751   unsigned int abbrev_form, hash_number;
10752   struct attr_abbrev *cur_attrs;
10753   unsigned int allocated_attrs;
10754
10755   /* Initialize dwarf2 abbrevs.  */
10756   obstack_init (&cu->abbrev_obstack);
10757   cu->dwarf2_abbrevs = obstack_alloc (&cu->abbrev_obstack,
10758                                       (ABBREV_HASH_SIZE
10759                                        * sizeof (struct abbrev_info *)));
10760   memset (cu->dwarf2_abbrevs, 0,
10761           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
10762
10763   dwarf2_read_section (cu->objfile, abbrev_section);
10764   abbrev_ptr = abbrev_section->buffer + cu_header->abbrev_offset.sect_off;
10765   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10766   abbrev_ptr += bytes_read;
10767
10768   allocated_attrs = ATTR_ALLOC_CHUNK;
10769   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
10770
10771   /* Loop until we reach an abbrev number of 0.  */
10772   while (abbrev_number)
10773     {
10774       cur_abbrev = dwarf_alloc_abbrev (cu);
10775
10776       /* read in abbrev header */
10777       cur_abbrev->number = abbrev_number;
10778       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10779       abbrev_ptr += bytes_read;
10780       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
10781       abbrev_ptr += 1;
10782
10783       /* now read in declarations */
10784       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10785       abbrev_ptr += bytes_read;
10786       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10787       abbrev_ptr += bytes_read;
10788       while (abbrev_name)
10789         {
10790           if (cur_abbrev->num_attrs == allocated_attrs)
10791             {
10792               allocated_attrs += ATTR_ALLOC_CHUNK;
10793               cur_attrs
10794                 = xrealloc (cur_attrs, (allocated_attrs
10795                                         * sizeof (struct attr_abbrev)));
10796             }
10797
10798           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
10799           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
10800           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10801           abbrev_ptr += bytes_read;
10802           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10803           abbrev_ptr += bytes_read;
10804         }
10805
10806       cur_abbrev->attrs = obstack_alloc (&cu->abbrev_obstack,
10807                                          (cur_abbrev->num_attrs
10808                                           * sizeof (struct attr_abbrev)));
10809       memcpy (cur_abbrev->attrs, cur_attrs,
10810               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
10811
10812       hash_number = abbrev_number % ABBREV_HASH_SIZE;
10813       cur_abbrev->next = cu->dwarf2_abbrevs[hash_number];
10814       cu->dwarf2_abbrevs[hash_number] = cur_abbrev;
10815
10816       /* Get next abbreviation.
10817          Under Irix6 the abbreviations for a compilation unit are not
10818          always properly terminated with an abbrev number of 0.
10819          Exit loop if we encounter an abbreviation which we have
10820          already read (which means we are about to read the abbreviations
10821          for the next compile unit) or if the end of the abbreviation
10822          table is reached.  */
10823       if ((unsigned int) (abbrev_ptr - abbrev_section->buffer)
10824           >= abbrev_section->size)
10825         break;
10826       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10827       abbrev_ptr += bytes_read;
10828       if (dwarf2_lookup_abbrev (abbrev_number, cu) != NULL)
10829         break;
10830     }
10831
10832   xfree (cur_attrs);
10833 }
10834
10835 /* Release the memory used by the abbrev table for a compilation unit.  */
10836
10837 static void
10838 dwarf2_free_abbrev_table (void *ptr_to_cu)
10839 {
10840   struct dwarf2_cu *cu = ptr_to_cu;
10841
10842   obstack_free (&cu->abbrev_obstack, NULL);
10843   cu->dwarf2_abbrevs = NULL;
10844 }
10845
10846 /* Lookup an abbrev_info structure in the abbrev hash table.  */
10847
10848 static struct abbrev_info *
10849 dwarf2_lookup_abbrev (unsigned int number, struct dwarf2_cu *cu)
10850 {
10851   unsigned int hash_number;
10852   struct abbrev_info *abbrev;
10853
10854   hash_number = number % ABBREV_HASH_SIZE;
10855   abbrev = cu->dwarf2_abbrevs[hash_number];
10856
10857   while (abbrev)
10858     {
10859       if (abbrev->number == number)
10860         return abbrev;
10861       else
10862         abbrev = abbrev->next;
10863     }
10864   return NULL;
10865 }
10866
10867 /* Returns nonzero if TAG represents a type that we might generate a partial
10868    symbol for.  */
10869
10870 static int
10871 is_type_tag_for_partial (int tag)
10872 {
10873   switch (tag)
10874     {
10875 #if 0
10876     /* Some types that would be reasonable to generate partial symbols for,
10877        that we don't at present.  */
10878     case DW_TAG_array_type:
10879     case DW_TAG_file_type:
10880     case DW_TAG_ptr_to_member_type:
10881     case DW_TAG_set_type:
10882     case DW_TAG_string_type:
10883     case DW_TAG_subroutine_type:
10884 #endif
10885     case DW_TAG_base_type:
10886     case DW_TAG_class_type:
10887     case DW_TAG_interface_type:
10888     case DW_TAG_enumeration_type:
10889     case DW_TAG_structure_type:
10890     case DW_TAG_subrange_type:
10891     case DW_TAG_typedef:
10892     case DW_TAG_union_type:
10893       return 1;
10894     default:
10895       return 0;
10896     }
10897 }
10898
10899 /* Load all DIEs that are interesting for partial symbols into memory.  */
10900
10901 static struct partial_die_info *
10902 load_partial_dies (const struct die_reader_specs *reader,
10903                    gdb_byte *info_ptr, int building_psymtab)
10904 {
10905   struct dwarf2_cu *cu = reader->cu;
10906   struct objfile *objfile = cu->objfile;
10907   struct partial_die_info *part_die;
10908   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
10909   struct abbrev_info *abbrev;
10910   unsigned int bytes_read;
10911   unsigned int load_all = 0;
10912   int nesting_level = 1;
10913
10914   parent_die = NULL;
10915   last_die = NULL;
10916
10917   gdb_assert (cu->per_cu != NULL);
10918   if (cu->per_cu->load_all_dies)
10919     load_all = 1;
10920
10921   cu->partial_dies
10922     = htab_create_alloc_ex (cu->header.length / 12,
10923                             partial_die_hash,
10924                             partial_die_eq,
10925                             NULL,
10926                             &cu->comp_unit_obstack,
10927                             hashtab_obstack_allocate,
10928                             dummy_obstack_deallocate);
10929
10930   part_die = obstack_alloc (&cu->comp_unit_obstack,
10931                             sizeof (struct partial_die_info));
10932
10933   while (1)
10934     {
10935       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
10936
10937       /* A NULL abbrev means the end of a series of children.  */
10938       if (abbrev == NULL)
10939         {
10940           if (--nesting_level == 0)
10941             {
10942               /* PART_DIE was probably the last thing allocated on the
10943                  comp_unit_obstack, so we could call obstack_free
10944                  here.  We don't do that because the waste is small,
10945                  and will be cleaned up when we're done with this
10946                  compilation unit.  This way, we're also more robust
10947                  against other users of the comp_unit_obstack.  */
10948               return first_die;
10949             }
10950           info_ptr += bytes_read;
10951           last_die = parent_die;
10952           parent_die = parent_die->die_parent;
10953           continue;
10954         }
10955
10956       /* Check for template arguments.  We never save these; if
10957          they're seen, we just mark the parent, and go on our way.  */
10958       if (parent_die != NULL
10959           && cu->language == language_cplus
10960           && (abbrev->tag == DW_TAG_template_type_param
10961               || abbrev->tag == DW_TAG_template_value_param))
10962         {
10963           parent_die->has_template_arguments = 1;
10964
10965           if (!load_all)
10966             {
10967               /* We don't need a partial DIE for the template argument.  */
10968               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
10969               continue;
10970             }
10971         }
10972
10973       /* We only recurse into c++ subprograms looking for template arguments.
10974          Skip their other children.  */
10975       if (!load_all
10976           && cu->language == language_cplus
10977           && parent_die != NULL
10978           && parent_die->tag == DW_TAG_subprogram)
10979         {
10980           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
10981           continue;
10982         }
10983
10984       /* Check whether this DIE is interesting enough to save.  Normally
10985          we would not be interested in members here, but there may be
10986          later variables referencing them via DW_AT_specification (for
10987          static members).  */
10988       if (!load_all
10989           && !is_type_tag_for_partial (abbrev->tag)
10990           && abbrev->tag != DW_TAG_constant
10991           && abbrev->tag != DW_TAG_enumerator
10992           && abbrev->tag != DW_TAG_subprogram
10993           && abbrev->tag != DW_TAG_lexical_block
10994           && abbrev->tag != DW_TAG_variable
10995           && abbrev->tag != DW_TAG_namespace
10996           && abbrev->tag != DW_TAG_module
10997           && abbrev->tag != DW_TAG_member
10998           && abbrev->tag != DW_TAG_imported_unit)
10999         {
11000           /* Otherwise we skip to the next sibling, if any.  */
11001           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
11002           continue;
11003         }
11004
11005       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
11006                                    info_ptr);
11007
11008       /* This two-pass algorithm for processing partial symbols has a
11009          high cost in cache pressure.  Thus, handle some simple cases
11010          here which cover the majority of C partial symbols.  DIEs
11011          which neither have specification tags in them, nor could have
11012          specification tags elsewhere pointing at them, can simply be
11013          processed and discarded.
11014
11015          This segment is also optional; scan_partial_symbols and
11016          add_partial_symbol will handle these DIEs if we chain
11017          them in normally.  When compilers which do not emit large
11018          quantities of duplicate debug information are more common,
11019          this code can probably be removed.  */
11020
11021       /* Any complete simple types at the top level (pretty much all
11022          of them, for a language without namespaces), can be processed
11023          directly.  */
11024       if (parent_die == NULL
11025           && part_die->has_specification == 0
11026           && part_die->is_declaration == 0
11027           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
11028               || part_die->tag == DW_TAG_base_type
11029               || part_die->tag == DW_TAG_subrange_type))
11030         {
11031           if (building_psymtab && part_die->name != NULL)
11032             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
11033                                  VAR_DOMAIN, LOC_TYPEDEF,
11034                                  &objfile->static_psymbols,
11035                                  0, (CORE_ADDR) 0, cu->language, objfile);
11036           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
11037           continue;
11038         }
11039
11040       /* The exception for DW_TAG_typedef with has_children above is
11041          a workaround of GCC PR debug/47510.  In the case of this complaint
11042          type_name_no_tag_or_error will error on such types later.
11043
11044          GDB skipped children of DW_TAG_typedef by the shortcut above and then
11045          it could not find the child DIEs referenced later, this is checked
11046          above.  In correct DWARF DW_TAG_typedef should have no children.  */
11047
11048       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
11049         complaint (&symfile_complaints,
11050                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
11051                      "- DIE at 0x%x [in module %s]"),
11052                    part_die->offset.sect_off, objfile->name);
11053
11054       /* If we're at the second level, and we're an enumerator, and
11055          our parent has no specification (meaning possibly lives in a
11056          namespace elsewhere), then we can add the partial symbol now
11057          instead of queueing it.  */
11058       if (part_die->tag == DW_TAG_enumerator
11059           && parent_die != NULL
11060           && parent_die->die_parent == NULL
11061           && parent_die->tag == DW_TAG_enumeration_type
11062           && parent_die->has_specification == 0)
11063         {
11064           if (part_die->name == NULL)
11065             complaint (&symfile_complaints,
11066                        _("malformed enumerator DIE ignored"));
11067           else if (building_psymtab)
11068             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
11069                                  VAR_DOMAIN, LOC_CONST,
11070                                  (cu->language == language_cplus
11071                                   || cu->language == language_java)
11072                                  ? &objfile->global_psymbols
11073                                  : &objfile->static_psymbols,
11074                                  0, (CORE_ADDR) 0, cu->language, objfile);
11075
11076           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
11077           continue;
11078         }
11079
11080       /* We'll save this DIE so link it in.  */
11081       part_die->die_parent = parent_die;
11082       part_die->die_sibling = NULL;
11083       part_die->die_child = NULL;
11084
11085       if (last_die && last_die == parent_die)
11086         last_die->die_child = part_die;
11087       else if (last_die)
11088         last_die->die_sibling = part_die;
11089
11090       last_die = part_die;
11091
11092       if (first_die == NULL)
11093         first_die = part_die;
11094
11095       /* Maybe add the DIE to the hash table.  Not all DIEs that we
11096          find interesting need to be in the hash table, because we
11097          also have the parent/sibling/child chains; only those that we
11098          might refer to by offset later during partial symbol reading.
11099
11100          For now this means things that might have be the target of a
11101          DW_AT_specification, DW_AT_abstract_origin, or
11102          DW_AT_extension.  DW_AT_extension will refer only to
11103          namespaces; DW_AT_abstract_origin refers to functions (and
11104          many things under the function DIE, but we do not recurse
11105          into function DIEs during partial symbol reading) and
11106          possibly variables as well; DW_AT_specification refers to
11107          declarations.  Declarations ought to have the DW_AT_declaration
11108          flag.  It happens that GCC forgets to put it in sometimes, but
11109          only for functions, not for types.
11110
11111          Adding more things than necessary to the hash table is harmless
11112          except for the performance cost.  Adding too few will result in
11113          wasted time in find_partial_die, when we reread the compilation
11114          unit with load_all_dies set.  */
11115
11116       if (load_all
11117           || abbrev->tag == DW_TAG_constant
11118           || abbrev->tag == DW_TAG_subprogram
11119           || abbrev->tag == DW_TAG_variable
11120           || abbrev->tag == DW_TAG_namespace
11121           || part_die->is_declaration)
11122         {
11123           void **slot;
11124
11125           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
11126                                            part_die->offset.sect_off, INSERT);
11127           *slot = part_die;
11128         }
11129
11130       part_die = obstack_alloc (&cu->comp_unit_obstack,
11131                                 sizeof (struct partial_die_info));
11132
11133       /* For some DIEs we want to follow their children (if any).  For C
11134          we have no reason to follow the children of structures; for other
11135          languages we have to, so that we can get at method physnames
11136          to infer fully qualified class names, for DW_AT_specification,
11137          and for C++ template arguments.  For C++, we also look one level
11138          inside functions to find template arguments (if the name of the
11139          function does not already contain the template arguments).
11140
11141          For Ada, we need to scan the children of subprograms and lexical
11142          blocks as well because Ada allows the definition of nested
11143          entities that could be interesting for the debugger, such as
11144          nested subprograms for instance.  */
11145       if (last_die->has_children
11146           && (load_all
11147               || last_die->tag == DW_TAG_namespace
11148               || last_die->tag == DW_TAG_module
11149               || last_die->tag == DW_TAG_enumeration_type
11150               || (cu->language == language_cplus
11151                   && last_die->tag == DW_TAG_subprogram
11152                   && (last_die->name == NULL
11153                       || strchr (last_die->name, '<') == NULL))
11154               || (cu->language != language_c
11155                   && (last_die->tag == DW_TAG_class_type
11156                       || last_die->tag == DW_TAG_interface_type
11157                       || last_die->tag == DW_TAG_structure_type
11158                       || last_die->tag == DW_TAG_union_type))
11159               || (cu->language == language_ada
11160                   && (last_die->tag == DW_TAG_subprogram
11161                       || last_die->tag == DW_TAG_lexical_block))))
11162         {
11163           nesting_level++;
11164           parent_die = last_die;
11165           continue;
11166         }
11167
11168       /* Otherwise we skip to the next sibling, if any.  */
11169       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
11170
11171       /* Back to the top, do it again.  */
11172     }
11173 }
11174
11175 /* Read a minimal amount of information into the minimal die structure.  */
11176
11177 static gdb_byte *
11178 read_partial_die (const struct die_reader_specs *reader,
11179                   struct partial_die_info *part_die,
11180                   struct abbrev_info *abbrev, unsigned int abbrev_len,
11181                   gdb_byte *info_ptr)
11182 {
11183   struct dwarf2_cu *cu = reader->cu;
11184   struct objfile *objfile = cu->objfile;
11185   gdb_byte *buffer = reader->buffer;
11186   unsigned int i;
11187   struct attribute attr;
11188   int has_low_pc_attr = 0;
11189   int has_high_pc_attr = 0;
11190   int high_pc_relative = 0;
11191
11192   memset (part_die, 0, sizeof (struct partial_die_info));
11193
11194   part_die->offset.sect_off = info_ptr - buffer;
11195
11196   info_ptr += abbrev_len;
11197
11198   if (abbrev == NULL)
11199     return info_ptr;
11200
11201   part_die->tag = abbrev->tag;
11202   part_die->has_children = abbrev->has_children;
11203
11204   for (i = 0; i < abbrev->num_attrs; ++i)
11205     {
11206       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
11207
11208       /* Store the data if it is of an attribute we want to keep in a
11209          partial symbol table.  */
11210       switch (attr.name)
11211         {
11212         case DW_AT_name:
11213           switch (part_die->tag)
11214             {
11215             case DW_TAG_compile_unit:
11216             case DW_TAG_partial_unit:
11217             case DW_TAG_type_unit:
11218               /* Compilation units have a DW_AT_name that is a filename, not
11219                  a source language identifier.  */
11220             case DW_TAG_enumeration_type:
11221             case DW_TAG_enumerator:
11222               /* These tags always have simple identifiers already; no need
11223                  to canonicalize them.  */
11224               part_die->name = DW_STRING (&attr);
11225               break;
11226             default:
11227               part_die->name
11228                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
11229                                             &objfile->objfile_obstack);
11230               break;
11231             }
11232           break;
11233         case DW_AT_linkage_name:
11234         case DW_AT_MIPS_linkage_name:
11235           /* Note that both forms of linkage name might appear.  We
11236              assume they will be the same, and we only store the last
11237              one we see.  */
11238           if (cu->language == language_ada)
11239             part_die->name = DW_STRING (&attr);
11240           part_die->linkage_name = DW_STRING (&attr);
11241           break;
11242         case DW_AT_low_pc:
11243           has_low_pc_attr = 1;
11244           part_die->lowpc = DW_ADDR (&attr);
11245           break;
11246         case DW_AT_high_pc:
11247           has_high_pc_attr = 1;
11248           if (attr.form == DW_FORM_addr
11249               || attr.form == DW_FORM_GNU_addr_index)
11250             part_die->highpc = DW_ADDR (&attr);
11251           else
11252             {
11253               high_pc_relative = 1;
11254               part_die->highpc = DW_UNSND (&attr);
11255             }
11256           break;
11257         case DW_AT_location:
11258           /* Support the .debug_loc offsets.  */
11259           if (attr_form_is_block (&attr))
11260             {
11261                part_die->d.locdesc = DW_BLOCK (&attr);
11262             }
11263           else if (attr_form_is_section_offset (&attr))
11264             {
11265               dwarf2_complex_location_expr_complaint ();
11266             }
11267           else
11268             {
11269               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
11270                                                      "partial symbol information");
11271             }
11272           break;
11273         case DW_AT_external:
11274           part_die->is_external = DW_UNSND (&attr);
11275           break;
11276         case DW_AT_declaration:
11277           part_die->is_declaration = DW_UNSND (&attr);
11278           break;
11279         case DW_AT_type:
11280           part_die->has_type = 1;
11281           break;
11282         case DW_AT_abstract_origin:
11283         case DW_AT_specification:
11284         case DW_AT_extension:
11285           part_die->has_specification = 1;
11286           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
11287           break;
11288         case DW_AT_sibling:
11289           /* Ignore absolute siblings, they might point outside of
11290              the current compile unit.  */
11291           if (attr.form == DW_FORM_ref_addr)
11292             complaint (&symfile_complaints,
11293                        _("ignoring absolute DW_AT_sibling"));
11294           else
11295             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
11296           break;
11297         case DW_AT_byte_size:
11298           part_die->has_byte_size = 1;
11299           break;
11300         case DW_AT_calling_convention:
11301           /* DWARF doesn't provide a way to identify a program's source-level
11302              entry point.  DW_AT_calling_convention attributes are only meant
11303              to describe functions' calling conventions.
11304
11305              However, because it's a necessary piece of information in
11306              Fortran, and because DW_CC_program is the only piece of debugging
11307              information whose definition refers to a 'main program' at all,
11308              several compilers have begun marking Fortran main programs with
11309              DW_CC_program --- even when those functions use the standard
11310              calling conventions.
11311
11312              So until DWARF specifies a way to provide this information and
11313              compilers pick up the new representation, we'll support this
11314              practice.  */
11315           if (DW_UNSND (&attr) == DW_CC_program
11316               && cu->language == language_fortran)
11317             {
11318               set_main_name (part_die->name);
11319
11320               /* As this DIE has a static linkage the name would be difficult
11321                  to look up later.  */
11322               language_of_main = language_fortran;
11323             }
11324           break;
11325         case DW_AT_inline:
11326           if (DW_UNSND (&attr) == DW_INL_inlined
11327               || DW_UNSND (&attr) == DW_INL_declared_inlined)
11328             part_die->may_be_inlined = 1;
11329           break;
11330
11331         case DW_AT_import:
11332           if (part_die->tag == DW_TAG_imported_unit)
11333             part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
11334           break;
11335
11336         default:
11337           break;
11338         }
11339     }
11340
11341   if (high_pc_relative)
11342     part_die->highpc += part_die->lowpc;
11343
11344   if (has_low_pc_attr && has_high_pc_attr)
11345     {
11346       /* When using the GNU linker, .gnu.linkonce. sections are used to
11347          eliminate duplicate copies of functions and vtables and such.
11348          The linker will arbitrarily choose one and discard the others.
11349          The AT_*_pc values for such functions refer to local labels in
11350          these sections.  If the section from that file was discarded, the
11351          labels are not in the output, so the relocs get a value of 0.
11352          If this is a discarded function, mark the pc bounds as invalid,
11353          so that GDB will ignore it.  */
11354       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
11355         {
11356           struct gdbarch *gdbarch = get_objfile_arch (objfile);
11357
11358           complaint (&symfile_complaints,
11359                      _("DW_AT_low_pc %s is zero "
11360                        "for DIE at 0x%x [in module %s]"),
11361                      paddress (gdbarch, part_die->lowpc),
11362                      part_die->offset.sect_off, objfile->name);
11363         }
11364       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
11365       else if (part_die->lowpc >= part_die->highpc)
11366         {
11367           struct gdbarch *gdbarch = get_objfile_arch (objfile);
11368
11369           complaint (&symfile_complaints,
11370                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
11371                        "for DIE at 0x%x [in module %s]"),
11372                      paddress (gdbarch, part_die->lowpc),
11373                      paddress (gdbarch, part_die->highpc),
11374                      part_die->offset.sect_off, objfile->name);
11375         }
11376       else
11377         part_die->has_pc_info = 1;
11378     }
11379
11380   return info_ptr;
11381 }
11382
11383 /* Find a cached partial DIE at OFFSET in CU.  */
11384
11385 static struct partial_die_info *
11386 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
11387 {
11388   struct partial_die_info *lookup_die = NULL;
11389   struct partial_die_info part_die;
11390
11391   part_die.offset = offset;
11392   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
11393                                     offset.sect_off);
11394
11395   return lookup_die;
11396 }
11397
11398 /* Find a partial DIE at OFFSET, which may or may not be in CU,
11399    except in the case of .debug_types DIEs which do not reference
11400    outside their CU (they do however referencing other types via
11401    DW_FORM_ref_sig8).  */
11402
11403 static struct partial_die_info *
11404 find_partial_die (sect_offset offset, struct dwarf2_cu *cu)
11405 {
11406   struct objfile *objfile = cu->objfile;
11407   struct dwarf2_per_cu_data *per_cu = NULL;
11408   struct partial_die_info *pd = NULL;
11409
11410   if (offset_in_cu_p (&cu->header, offset))
11411     {
11412       pd = find_partial_die_in_comp_unit (offset, cu);
11413       if (pd != NULL)
11414         return pd;
11415       /* We missed recording what we needed.
11416          Load all dies and try again.  */
11417       per_cu = cu->per_cu;
11418     }
11419   else
11420     {
11421       /* TUs don't reference other CUs/TUs (except via type signatures).  */
11422       if (cu->per_cu->is_debug_types)
11423         {
11424           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
11425                    " external reference to offset 0x%lx [in module %s].\n"),
11426                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
11427                  bfd_get_filename (objfile->obfd));
11428         }
11429       per_cu = dwarf2_find_containing_comp_unit (offset, objfile);
11430
11431       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
11432         load_partial_comp_unit (per_cu);
11433
11434       per_cu->cu->last_used = 0;
11435       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
11436     }
11437
11438   /* If we didn't find it, and not all dies have been loaded,
11439      load them all and try again.  */
11440
11441   if (pd == NULL && per_cu->load_all_dies == 0)
11442     {
11443       per_cu->load_all_dies = 1;
11444
11445       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
11446          THIS_CU->cu may already be in use.  So we can't just free it and
11447          replace its DIEs with the ones we read in.  Instead, we leave those
11448          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
11449          and clobber THIS_CU->cu->partial_dies with the hash table for the new
11450          set.  */
11451       load_partial_comp_unit (per_cu);
11452
11453       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
11454     }
11455
11456   if (pd == NULL)
11457     internal_error (__FILE__, __LINE__,
11458                     _("could not find partial DIE 0x%x "
11459                       "in cache [from module %s]\n"),
11460                     offset.sect_off, bfd_get_filename (objfile->obfd));
11461   return pd;
11462 }
11463
11464 /* See if we can figure out if the class lives in a namespace.  We do
11465    this by looking for a member function; its demangled name will
11466    contain namespace info, if there is any.  */
11467
11468 static void
11469 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
11470                                   struct dwarf2_cu *cu)
11471 {
11472   /* NOTE: carlton/2003-10-07: Getting the info this way changes
11473      what template types look like, because the demangler
11474      frequently doesn't give the same name as the debug info.  We
11475      could fix this by only using the demangled name to get the
11476      prefix (but see comment in read_structure_type).  */
11477
11478   struct partial_die_info *real_pdi;
11479   struct partial_die_info *child_pdi;
11480
11481   /* If this DIE (this DIE's specification, if any) has a parent, then
11482      we should not do this.  We'll prepend the parent's fully qualified
11483      name when we create the partial symbol.  */
11484
11485   real_pdi = struct_pdi;
11486   while (real_pdi->has_specification)
11487     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
11488
11489   if (real_pdi->die_parent != NULL)
11490     return;
11491
11492   for (child_pdi = struct_pdi->die_child;
11493        child_pdi != NULL;
11494        child_pdi = child_pdi->die_sibling)
11495     {
11496       if (child_pdi->tag == DW_TAG_subprogram
11497           && child_pdi->linkage_name != NULL)
11498         {
11499           char *actual_class_name
11500             = language_class_name_from_physname (cu->language_defn,
11501                                                  child_pdi->linkage_name);
11502           if (actual_class_name != NULL)
11503             {
11504               struct_pdi->name
11505                 = obsavestring (actual_class_name,
11506                                 strlen (actual_class_name),
11507                                 &cu->objfile->objfile_obstack);
11508               xfree (actual_class_name);
11509             }
11510           break;
11511         }
11512     }
11513 }
11514
11515 /* Adjust PART_DIE before generating a symbol for it.  This function
11516    may set the is_external flag or change the DIE's name.  */
11517
11518 static void
11519 fixup_partial_die (struct partial_die_info *part_die,
11520                    struct dwarf2_cu *cu)
11521 {
11522   /* Once we've fixed up a die, there's no point in doing so again.
11523      This also avoids a memory leak if we were to call
11524      guess_partial_die_structure_name multiple times.  */
11525   if (part_die->fixup_called)
11526     return;
11527
11528   /* If we found a reference attribute and the DIE has no name, try
11529      to find a name in the referred to DIE.  */
11530
11531   if (part_die->name == NULL && part_die->has_specification)
11532     {
11533       struct partial_die_info *spec_die;
11534
11535       spec_die = find_partial_die (part_die->spec_offset, cu);
11536
11537       fixup_partial_die (spec_die, cu);
11538
11539       if (spec_die->name)
11540         {
11541           part_die->name = spec_die->name;
11542
11543           /* Copy DW_AT_external attribute if it is set.  */
11544           if (spec_die->is_external)
11545             part_die->is_external = spec_die->is_external;
11546         }
11547     }
11548
11549   /* Set default names for some unnamed DIEs.  */
11550
11551   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
11552     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
11553
11554   /* If there is no parent die to provide a namespace, and there are
11555      children, see if we can determine the namespace from their linkage
11556      name.  */
11557   if (cu->language == language_cplus
11558       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
11559       && part_die->die_parent == NULL
11560       && part_die->has_children
11561       && (part_die->tag == DW_TAG_class_type
11562           || part_die->tag == DW_TAG_structure_type
11563           || part_die->tag == DW_TAG_union_type))
11564     guess_partial_die_structure_name (part_die, cu);
11565
11566   /* GCC might emit a nameless struct or union that has a linkage
11567      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
11568   if (part_die->name == NULL
11569       && (part_die->tag == DW_TAG_class_type
11570           || part_die->tag == DW_TAG_interface_type
11571           || part_die->tag == DW_TAG_structure_type
11572           || part_die->tag == DW_TAG_union_type)
11573       && part_die->linkage_name != NULL)
11574     {
11575       char *demangled;
11576
11577       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
11578       if (demangled)
11579         {
11580           const char *base;
11581
11582           /* Strip any leading namespaces/classes, keep only the base name.
11583              DW_AT_name for named DIEs does not contain the prefixes.  */
11584           base = strrchr (demangled, ':');
11585           if (base && base > demangled && base[-1] == ':')
11586             base++;
11587           else
11588             base = demangled;
11589
11590           part_die->name = obsavestring (base, strlen (base),
11591                                          &cu->objfile->objfile_obstack);
11592           xfree (demangled);
11593         }
11594     }
11595
11596   part_die->fixup_called = 1;
11597 }
11598
11599 /* Read an attribute value described by an attribute form.  */
11600
11601 static gdb_byte *
11602 read_attribute_value (const struct die_reader_specs *reader,
11603                       struct attribute *attr, unsigned form,
11604                       gdb_byte *info_ptr)
11605 {
11606   struct dwarf2_cu *cu = reader->cu;
11607   bfd *abfd = reader->abfd;
11608   struct comp_unit_head *cu_header = &cu->header;
11609   unsigned int bytes_read;
11610   struct dwarf_block *blk;
11611
11612   attr->form = form;
11613   switch (form)
11614     {
11615     case DW_FORM_ref_addr:
11616       if (cu->header.version == 2)
11617         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
11618       else
11619         DW_UNSND (attr) = read_offset (abfd, info_ptr,
11620                                        &cu->header, &bytes_read);
11621       info_ptr += bytes_read;
11622       break;
11623     case DW_FORM_addr:
11624       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
11625       info_ptr += bytes_read;
11626       break;
11627     case DW_FORM_block2:
11628       blk = dwarf_alloc_block (cu);
11629       blk->size = read_2_bytes (abfd, info_ptr);
11630       info_ptr += 2;
11631       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11632       info_ptr += blk->size;
11633       DW_BLOCK (attr) = blk;
11634       break;
11635     case DW_FORM_block4:
11636       blk = dwarf_alloc_block (cu);
11637       blk->size = read_4_bytes (abfd, info_ptr);
11638       info_ptr += 4;
11639       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11640       info_ptr += blk->size;
11641       DW_BLOCK (attr) = blk;
11642       break;
11643     case DW_FORM_data2:
11644       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
11645       info_ptr += 2;
11646       break;
11647     case DW_FORM_data4:
11648       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
11649       info_ptr += 4;
11650       break;
11651     case DW_FORM_data8:
11652       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
11653       info_ptr += 8;
11654       break;
11655     case DW_FORM_sec_offset:
11656       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
11657       info_ptr += bytes_read;
11658       break;
11659     case DW_FORM_string:
11660       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
11661       DW_STRING_IS_CANONICAL (attr) = 0;
11662       info_ptr += bytes_read;
11663       break;
11664     case DW_FORM_strp:
11665       DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
11666                                                &bytes_read);
11667       DW_STRING_IS_CANONICAL (attr) = 0;
11668       info_ptr += bytes_read;
11669       break;
11670     case DW_FORM_exprloc:
11671     case DW_FORM_block:
11672       blk = dwarf_alloc_block (cu);
11673       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11674       info_ptr += bytes_read;
11675       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11676       info_ptr += blk->size;
11677       DW_BLOCK (attr) = blk;
11678       break;
11679     case DW_FORM_block1:
11680       blk = dwarf_alloc_block (cu);
11681       blk->size = read_1_byte (abfd, info_ptr);
11682       info_ptr += 1;
11683       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11684       info_ptr += blk->size;
11685       DW_BLOCK (attr) = blk;
11686       break;
11687     case DW_FORM_data1:
11688       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
11689       info_ptr += 1;
11690       break;
11691     case DW_FORM_flag:
11692       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
11693       info_ptr += 1;
11694       break;
11695     case DW_FORM_flag_present:
11696       DW_UNSND (attr) = 1;
11697       break;
11698     case DW_FORM_sdata:
11699       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
11700       info_ptr += bytes_read;
11701       break;
11702     case DW_FORM_udata:
11703       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11704       info_ptr += bytes_read;
11705       break;
11706     case DW_FORM_ref1:
11707       DW_UNSND (attr) = (cu->header.offset.sect_off
11708                          + read_1_byte (abfd, info_ptr));
11709       info_ptr += 1;
11710       break;
11711     case DW_FORM_ref2:
11712       DW_UNSND (attr) = (cu->header.offset.sect_off
11713                          + read_2_bytes (abfd, info_ptr));
11714       info_ptr += 2;
11715       break;
11716     case DW_FORM_ref4:
11717       DW_UNSND (attr) = (cu->header.offset.sect_off
11718                          + read_4_bytes (abfd, info_ptr));
11719       info_ptr += 4;
11720       break;
11721     case DW_FORM_ref8:
11722       DW_UNSND (attr) = (cu->header.offset.sect_off
11723                          + read_8_bytes (abfd, info_ptr));
11724       info_ptr += 8;
11725       break;
11726     case DW_FORM_ref_sig8:
11727       /* Convert the signature to something we can record in DW_UNSND
11728          for later lookup.
11729          NOTE: This is NULL if the type wasn't found.  */
11730       DW_SIGNATURED_TYPE (attr) =
11731         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
11732       info_ptr += 8;
11733       break;
11734     case DW_FORM_ref_udata:
11735       DW_UNSND (attr) = (cu->header.offset.sect_off
11736                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
11737       info_ptr += bytes_read;
11738       break;
11739     case DW_FORM_indirect:
11740       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11741       info_ptr += bytes_read;
11742       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
11743       break;
11744     case DW_FORM_GNU_addr_index:
11745       if (reader->dwo_file == NULL)
11746         {
11747           /* For now flag a hard error.
11748              Later we can turn this into a complaint.  */
11749           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
11750                  dwarf_form_name (form),
11751                  bfd_get_filename (abfd));
11752         }
11753       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
11754       info_ptr += bytes_read;
11755       break;
11756     case DW_FORM_GNU_str_index:
11757       if (reader->dwo_file == NULL)
11758         {
11759           /* For now flag a hard error.
11760              Later we can turn this into a complaint if warranted.  */
11761           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
11762                  dwarf_form_name (form),
11763                  bfd_get_filename (abfd));
11764         }
11765       {
11766         ULONGEST str_index =
11767           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11768
11769         DW_STRING (attr) = read_str_index (reader, cu, str_index);
11770         DW_STRING_IS_CANONICAL (attr) = 0;
11771         info_ptr += bytes_read;
11772       }
11773       break;
11774     default:
11775       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
11776              dwarf_form_name (form),
11777              bfd_get_filename (abfd));
11778     }
11779
11780   /* We have seen instances where the compiler tried to emit a byte
11781      size attribute of -1 which ended up being encoded as an unsigned
11782      0xffffffff.  Although 0xffffffff is technically a valid size value,
11783      an object of this size seems pretty unlikely so we can relatively
11784      safely treat these cases as if the size attribute was invalid and
11785      treat them as zero by default.  */
11786   if (attr->name == DW_AT_byte_size
11787       && form == DW_FORM_data4
11788       && DW_UNSND (attr) >= 0xffffffff)
11789     {
11790       complaint
11791         (&symfile_complaints,
11792          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
11793          hex_string (DW_UNSND (attr)));
11794       DW_UNSND (attr) = 0;
11795     }
11796
11797   return info_ptr;
11798 }
11799
11800 /* Read an attribute described by an abbreviated attribute.  */
11801
11802 static gdb_byte *
11803 read_attribute (const struct die_reader_specs *reader,
11804                 struct attribute *attr, struct attr_abbrev *abbrev,
11805                 gdb_byte *info_ptr)
11806 {
11807   attr->name = abbrev->name;
11808   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
11809 }
11810
11811 /* Read dwarf information from a buffer.  */
11812
11813 static unsigned int
11814 read_1_byte (bfd *abfd, gdb_byte *buf)
11815 {
11816   return bfd_get_8 (abfd, buf);
11817 }
11818
11819 static int
11820 read_1_signed_byte (bfd *abfd, gdb_byte *buf)
11821 {
11822   return bfd_get_signed_8 (abfd, buf);
11823 }
11824
11825 static unsigned int
11826 read_2_bytes (bfd *abfd, gdb_byte *buf)
11827 {
11828   return bfd_get_16 (abfd, buf);
11829 }
11830
11831 static int
11832 read_2_signed_bytes (bfd *abfd, gdb_byte *buf)
11833 {
11834   return bfd_get_signed_16 (abfd, buf);
11835 }
11836
11837 static unsigned int
11838 read_4_bytes (bfd *abfd, gdb_byte *buf)
11839 {
11840   return bfd_get_32 (abfd, buf);
11841 }
11842
11843 static int
11844 read_4_signed_bytes (bfd *abfd, gdb_byte *buf)
11845 {
11846   return bfd_get_signed_32 (abfd, buf);
11847 }
11848
11849 static ULONGEST
11850 read_8_bytes (bfd *abfd, gdb_byte *buf)
11851 {
11852   return bfd_get_64 (abfd, buf);
11853 }
11854
11855 static CORE_ADDR
11856 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
11857               unsigned int *bytes_read)
11858 {
11859   struct comp_unit_head *cu_header = &cu->header;
11860   CORE_ADDR retval = 0;
11861
11862   if (cu_header->signed_addr_p)
11863     {
11864       switch (cu_header->addr_size)
11865         {
11866         case 2:
11867           retval = bfd_get_signed_16 (abfd, buf);
11868           break;
11869         case 4:
11870           retval = bfd_get_signed_32 (abfd, buf);
11871           break;
11872         case 8:
11873           retval = bfd_get_signed_64 (abfd, buf);
11874           break;
11875         default:
11876           internal_error (__FILE__, __LINE__,
11877                           _("read_address: bad switch, signed [in module %s]"),
11878                           bfd_get_filename (abfd));
11879         }
11880     }
11881   else
11882     {
11883       switch (cu_header->addr_size)
11884         {
11885         case 2:
11886           retval = bfd_get_16 (abfd, buf);
11887           break;
11888         case 4:
11889           retval = bfd_get_32 (abfd, buf);
11890           break;
11891         case 8:
11892           retval = bfd_get_64 (abfd, buf);
11893           break;
11894         default:
11895           internal_error (__FILE__, __LINE__,
11896                           _("read_address: bad switch, "
11897                             "unsigned [in module %s]"),
11898                           bfd_get_filename (abfd));
11899         }
11900     }
11901
11902   *bytes_read = cu_header->addr_size;
11903   return retval;
11904 }
11905
11906 /* Read the initial length from a section.  The (draft) DWARF 3
11907    specification allows the initial length to take up either 4 bytes
11908    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
11909    bytes describe the length and all offsets will be 8 bytes in length
11910    instead of 4.
11911
11912    An older, non-standard 64-bit format is also handled by this
11913    function.  The older format in question stores the initial length
11914    as an 8-byte quantity without an escape value.  Lengths greater
11915    than 2^32 aren't very common which means that the initial 4 bytes
11916    is almost always zero.  Since a length value of zero doesn't make
11917    sense for the 32-bit format, this initial zero can be considered to
11918    be an escape value which indicates the presence of the older 64-bit
11919    format.  As written, the code can't detect (old format) lengths
11920    greater than 4GB.  If it becomes necessary to handle lengths
11921    somewhat larger than 4GB, we could allow other small values (such
11922    as the non-sensical values of 1, 2, and 3) to also be used as
11923    escape values indicating the presence of the old format.
11924
11925    The value returned via bytes_read should be used to increment the
11926    relevant pointer after calling read_initial_length().
11927
11928    [ Note:  read_initial_length() and read_offset() are based on the
11929      document entitled "DWARF Debugging Information Format", revision
11930      3, draft 8, dated November 19, 2001.  This document was obtained
11931      from:
11932
11933         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
11934
11935      This document is only a draft and is subject to change.  (So beware.)
11936
11937      Details regarding the older, non-standard 64-bit format were
11938      determined empirically by examining 64-bit ELF files produced by
11939      the SGI toolchain on an IRIX 6.5 machine.
11940
11941      - Kevin, July 16, 2002
11942    ] */
11943
11944 static LONGEST
11945 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
11946 {
11947   LONGEST length = bfd_get_32 (abfd, buf);
11948
11949   if (length == 0xffffffff)
11950     {
11951       length = bfd_get_64 (abfd, buf + 4);
11952       *bytes_read = 12;
11953     }
11954   else if (length == 0)
11955     {
11956       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
11957       length = bfd_get_64 (abfd, buf);
11958       *bytes_read = 8;
11959     }
11960   else
11961     {
11962       *bytes_read = 4;
11963     }
11964
11965   return length;
11966 }
11967
11968 /* Cover function for read_initial_length.
11969    Returns the length of the object at BUF, and stores the size of the
11970    initial length in *BYTES_READ and stores the size that offsets will be in
11971    *OFFSET_SIZE.
11972    If the initial length size is not equivalent to that specified in
11973    CU_HEADER then issue a complaint.
11974    This is useful when reading non-comp-unit headers.  */
11975
11976 static LONGEST
11977 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
11978                                         const struct comp_unit_head *cu_header,
11979                                         unsigned int *bytes_read,
11980                                         unsigned int *offset_size)
11981 {
11982   LONGEST length = read_initial_length (abfd, buf, bytes_read);
11983
11984   gdb_assert (cu_header->initial_length_size == 4
11985               || cu_header->initial_length_size == 8
11986               || cu_header->initial_length_size == 12);
11987
11988   if (cu_header->initial_length_size != *bytes_read)
11989     complaint (&symfile_complaints,
11990                _("intermixed 32-bit and 64-bit DWARF sections"));
11991
11992   *offset_size = (*bytes_read == 4) ? 4 : 8;
11993   return length;
11994 }
11995
11996 /* Read an offset from the data stream.  The size of the offset is
11997    given by cu_header->offset_size.  */
11998
11999 static LONGEST
12000 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
12001              unsigned int *bytes_read)
12002 {
12003   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
12004
12005   *bytes_read = cu_header->offset_size;
12006   return offset;
12007 }
12008
12009 /* Read an offset from the data stream.  */
12010
12011 static LONGEST
12012 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
12013 {
12014   LONGEST retval = 0;
12015
12016   switch (offset_size)
12017     {
12018     case 4:
12019       retval = bfd_get_32 (abfd, buf);
12020       break;
12021     case 8:
12022       retval = bfd_get_64 (abfd, buf);
12023       break;
12024     default:
12025       internal_error (__FILE__, __LINE__,
12026                       _("read_offset_1: bad switch [in module %s]"),
12027                       bfd_get_filename (abfd));
12028     }
12029
12030   return retval;
12031 }
12032
12033 static gdb_byte *
12034 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
12035 {
12036   /* If the size of a host char is 8 bits, we can return a pointer
12037      to the buffer, otherwise we have to copy the data to a buffer
12038      allocated on the temporary obstack.  */
12039   gdb_assert (HOST_CHAR_BIT == 8);
12040   return buf;
12041 }
12042
12043 static char *
12044 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
12045 {
12046   /* If the size of a host char is 8 bits, we can return a pointer
12047      to the string, otherwise we have to copy the string to a buffer
12048      allocated on the temporary obstack.  */
12049   gdb_assert (HOST_CHAR_BIT == 8);
12050   if (*buf == '\0')
12051     {
12052       *bytes_read_ptr = 1;
12053       return NULL;
12054     }
12055   *bytes_read_ptr = strlen ((char *) buf) + 1;
12056   return (char *) buf;
12057 }
12058
12059 static char *
12060 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
12061 {
12062   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
12063   if (dwarf2_per_objfile->str.buffer == NULL)
12064     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
12065            bfd_get_filename (abfd));
12066   if (str_offset >= dwarf2_per_objfile->str.size)
12067     error (_("DW_FORM_strp pointing outside of "
12068              ".debug_str section [in module %s]"),
12069            bfd_get_filename (abfd));
12070   gdb_assert (HOST_CHAR_BIT == 8);
12071   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
12072     return NULL;
12073   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
12074 }
12075
12076 static char *
12077 read_indirect_string (bfd *abfd, gdb_byte *buf,
12078                       const struct comp_unit_head *cu_header,
12079                       unsigned int *bytes_read_ptr)
12080 {
12081   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
12082
12083   return read_indirect_string_at_offset (abfd, str_offset);
12084 }
12085
12086 static ULONGEST
12087 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
12088 {
12089   ULONGEST result;
12090   unsigned int num_read;
12091   int i, shift;
12092   unsigned char byte;
12093
12094   result = 0;
12095   shift = 0;
12096   num_read = 0;
12097   i = 0;
12098   while (1)
12099     {
12100       byte = bfd_get_8 (abfd, buf);
12101       buf++;
12102       num_read++;
12103       result |= ((ULONGEST) (byte & 127) << shift);
12104       if ((byte & 128) == 0)
12105         {
12106           break;
12107         }
12108       shift += 7;
12109     }
12110   *bytes_read_ptr = num_read;
12111   return result;
12112 }
12113
12114 static LONGEST
12115 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
12116 {
12117   LONGEST result;
12118   int i, shift, num_read;
12119   unsigned char byte;
12120
12121   result = 0;
12122   shift = 0;
12123   num_read = 0;
12124   i = 0;
12125   while (1)
12126     {
12127       byte = bfd_get_8 (abfd, buf);
12128       buf++;
12129       num_read++;
12130       result |= ((LONGEST) (byte & 127) << shift);
12131       shift += 7;
12132       if ((byte & 128) == 0)
12133         {
12134           break;
12135         }
12136     }
12137   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
12138     result |= -(((LONGEST) 1) << shift);
12139   *bytes_read_ptr = num_read;
12140   return result;
12141 }
12142
12143 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
12144    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
12145    ADDR_SIZE is the size of addresses from the CU header.  */
12146
12147 static CORE_ADDR
12148 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
12149 {
12150   struct objfile *objfile = dwarf2_per_objfile->objfile;
12151   bfd *abfd = objfile->obfd;
12152   const gdb_byte *info_ptr;
12153
12154   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
12155   if (dwarf2_per_objfile->addr.buffer == NULL)
12156     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
12157            objfile->name);
12158   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
12159     error (_("DW_FORM_addr_index pointing outside of "
12160              ".debug_addr section [in module %s]"),
12161            objfile->name);
12162   info_ptr = (dwarf2_per_objfile->addr.buffer
12163               + addr_base + addr_index * addr_size);
12164   if (addr_size == 4)
12165     return bfd_get_32 (abfd, info_ptr);
12166   else
12167     return bfd_get_64 (abfd, info_ptr);
12168 }
12169
12170 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
12171
12172 static CORE_ADDR
12173 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
12174 {
12175   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
12176 }
12177
12178 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
12179
12180 static CORE_ADDR
12181 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
12182                              unsigned int *bytes_read)
12183 {
12184   bfd *abfd = cu->objfile->obfd;
12185   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
12186
12187   return read_addr_index (cu, addr_index);
12188 }
12189
12190 /* Data structure to pass results from dwarf2_read_addr_index_reader
12191    back to dwarf2_read_addr_index.  */
12192
12193 struct dwarf2_read_addr_index_data
12194 {
12195   ULONGEST addr_base;
12196   int addr_size;
12197 };
12198
12199 /* die_reader_func for dwarf2_read_addr_index.  */
12200
12201 static void
12202 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
12203                                gdb_byte *info_ptr,
12204                                struct die_info *comp_unit_die,
12205                                int has_children,
12206                                void *data)
12207 {
12208   struct dwarf2_cu *cu = reader->cu;
12209   struct dwarf2_read_addr_index_data *aidata =
12210     (struct dwarf2_read_addr_index_data *) data;
12211
12212   aidata->addr_base = cu->addr_base;
12213   aidata->addr_size = cu->header.addr_size;
12214 }
12215
12216 /* Given an index in .debug_addr, fetch the value.
12217    NOTE: This can be called during dwarf expression evaluation,
12218    long after the debug information has been read, and thus per_cu->cu
12219    may no longer exist.  */
12220
12221 CORE_ADDR
12222 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
12223                         unsigned int addr_index)
12224 {
12225   struct objfile *objfile = per_cu->objfile;
12226   struct dwarf2_cu *cu = per_cu->cu;
12227   ULONGEST addr_base;
12228   int addr_size;
12229
12230   /* This is intended to be called from outside this file.  */
12231   dw2_setup (objfile);
12232
12233   /* We need addr_base and addr_size.
12234      If we don't have PER_CU->cu, we have to get it.
12235      Nasty, but the alternative is storing the needed info in PER_CU,
12236      which at this point doesn't seem justified: it's not clear how frequently
12237      it would get used and it would increase the size of every PER_CU.
12238      Entry points like dwarf2_per_cu_addr_size do a similar thing
12239      so we're not in uncharted territory here.
12240      Alas we need to be a bit more complicated as addr_base is contained
12241      in the DIE.
12242
12243      We don't need to read the entire CU(/TU).
12244      We just need the header and top level die.
12245      IWBN to use the aging mechanism to let us lazily later discard the CU.
12246      See however init_cutu_and_read_dies_simple.  */
12247
12248   if (cu != NULL)
12249     {
12250       addr_base = cu->addr_base;
12251       addr_size = cu->header.addr_size;
12252     }
12253   else
12254     {
12255       struct dwarf2_read_addr_index_data aidata;
12256
12257       init_cutu_and_read_dies_simple (per_cu, dwarf2_read_addr_index_reader,
12258                                       &aidata);
12259       addr_base = aidata.addr_base;
12260       addr_size = aidata.addr_size;
12261     }
12262
12263   return read_addr_index_1 (addr_index, addr_base, addr_size);
12264 }
12265
12266 /* Given a DW_AT_str_index, fetch the string.  */
12267
12268 static char *
12269 read_str_index (const struct die_reader_specs *reader,
12270                 struct dwarf2_cu *cu, ULONGEST str_index)
12271 {
12272   struct objfile *objfile = dwarf2_per_objfile->objfile;
12273   const char *dwo_name = objfile->name;
12274   bfd *abfd = objfile->obfd;
12275   struct dwo_sections *sections = &reader->dwo_file->sections;
12276   gdb_byte *info_ptr;
12277   ULONGEST str_offset;
12278
12279   dwarf2_read_section (objfile, &sections->str);
12280   dwarf2_read_section (objfile, &sections->str_offsets);
12281   if (sections->str.buffer == NULL)
12282     error (_("DW_FORM_str_index used without .debug_str.dwo section"
12283              " in CU at offset 0x%lx [in module %s]"),
12284            (long) cu->header.offset.sect_off, dwo_name);
12285   if (sections->str_offsets.buffer == NULL)
12286     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
12287              " in CU at offset 0x%lx [in module %s]"),
12288            (long) cu->header.offset.sect_off, dwo_name);
12289   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
12290     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
12291              " section in CU at offset 0x%lx [in module %s]"),
12292            (long) cu->header.offset.sect_off, dwo_name);
12293   info_ptr = (sections->str_offsets.buffer
12294               + str_index * cu->header.offset_size);
12295   if (cu->header.offset_size == 4)
12296     str_offset = bfd_get_32 (abfd, info_ptr);
12297   else
12298     str_offset = bfd_get_64 (abfd, info_ptr);
12299   if (str_offset >= sections->str.size)
12300     error (_("Offset from DW_FORM_str_index pointing outside of"
12301              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
12302            (long) cu->header.offset.sect_off, dwo_name);
12303   return (char *) (sections->str.buffer + str_offset);
12304 }
12305
12306 /* Return the length of an LEB128 number in BUF.  */
12307
12308 static int
12309 leb128_size (const gdb_byte *buf)
12310 {
12311   const gdb_byte *begin = buf;
12312   gdb_byte byte;
12313
12314   while (1)
12315     {
12316       byte = *buf++;
12317       if ((byte & 128) == 0)
12318         return buf - begin;
12319     }
12320 }
12321
12322 static void
12323 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
12324 {
12325   switch (lang)
12326     {
12327     case DW_LANG_C89:
12328     case DW_LANG_C99:
12329     case DW_LANG_C:
12330       cu->language = language_c;
12331       break;
12332     case DW_LANG_C_plus_plus:
12333       cu->language = language_cplus;
12334       break;
12335     case DW_LANG_D:
12336       cu->language = language_d;
12337       break;
12338     case DW_LANG_Fortran77:
12339     case DW_LANG_Fortran90:
12340     case DW_LANG_Fortran95:
12341       cu->language = language_fortran;
12342       break;
12343     case DW_LANG_Go:
12344       cu->language = language_go;
12345       break;
12346     case DW_LANG_Mips_Assembler:
12347       cu->language = language_asm;
12348       break;
12349     case DW_LANG_Java:
12350       cu->language = language_java;
12351       break;
12352     case DW_LANG_Ada83:
12353     case DW_LANG_Ada95:
12354       cu->language = language_ada;
12355       break;
12356     case DW_LANG_Modula2:
12357       cu->language = language_m2;
12358       break;
12359     case DW_LANG_Pascal83:
12360       cu->language = language_pascal;
12361       break;
12362     case DW_LANG_ObjC:
12363       cu->language = language_objc;
12364       break;
12365     case DW_LANG_Cobol74:
12366     case DW_LANG_Cobol85:
12367     default:
12368       cu->language = language_minimal;
12369       break;
12370     }
12371   cu->language_defn = language_def (cu->language);
12372 }
12373
12374 /* Return the named attribute or NULL if not there.  */
12375
12376 static struct attribute *
12377 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
12378 {
12379   for (;;)
12380     {
12381       unsigned int i;
12382       struct attribute *spec = NULL;
12383
12384       for (i = 0; i < die->num_attrs; ++i)
12385         {
12386           if (die->attrs[i].name == name)
12387             return &die->attrs[i];
12388           if (die->attrs[i].name == DW_AT_specification
12389               || die->attrs[i].name == DW_AT_abstract_origin)
12390             spec = &die->attrs[i];
12391         }
12392
12393       if (!spec)
12394         break;
12395
12396       die = follow_die_ref (die, spec, &cu);
12397     }
12398
12399   return NULL;
12400 }
12401
12402 /* Return the named attribute or NULL if not there,
12403    but do not follow DW_AT_specification, etc.
12404    This is for use in contexts where we're reading .debug_types dies.
12405    Following DW_AT_specification, DW_AT_abstract_origin will take us
12406    back up the chain, and we want to go down.  */
12407
12408 static struct attribute *
12409 dwarf2_attr_no_follow (struct die_info *die, unsigned int name,
12410                        struct dwarf2_cu *cu)
12411 {
12412   unsigned int i;
12413
12414   for (i = 0; i < die->num_attrs; ++i)
12415     if (die->attrs[i].name == name)
12416       return &die->attrs[i];
12417
12418   return NULL;
12419 }
12420
12421 /* Return non-zero iff the attribute NAME is defined for the given DIE,
12422    and holds a non-zero value.  This function should only be used for
12423    DW_FORM_flag or DW_FORM_flag_present attributes.  */
12424
12425 static int
12426 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
12427 {
12428   struct attribute *attr = dwarf2_attr (die, name, cu);
12429
12430   return (attr && DW_UNSND (attr));
12431 }
12432
12433 static int
12434 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
12435 {
12436   /* A DIE is a declaration if it has a DW_AT_declaration attribute
12437      which value is non-zero.  However, we have to be careful with
12438      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
12439      (via dwarf2_flag_true_p) follows this attribute.  So we may
12440      end up accidently finding a declaration attribute that belongs
12441      to a different DIE referenced by the specification attribute,
12442      even though the given DIE does not have a declaration attribute.  */
12443   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
12444           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
12445 }
12446
12447 /* Return the die giving the specification for DIE, if there is
12448    one.  *SPEC_CU is the CU containing DIE on input, and the CU
12449    containing the return value on output.  If there is no
12450    specification, but there is an abstract origin, that is
12451    returned.  */
12452
12453 static struct die_info *
12454 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
12455 {
12456   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
12457                                              *spec_cu);
12458
12459   if (spec_attr == NULL)
12460     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
12461
12462   if (spec_attr == NULL)
12463     return NULL;
12464   else
12465     return follow_die_ref (die, spec_attr, spec_cu);
12466 }
12467
12468 /* Free the line_header structure *LH, and any arrays and strings it
12469    refers to.
12470    NOTE: This is also used as a "cleanup" function.  */
12471
12472 static void
12473 free_line_header (struct line_header *lh)
12474 {
12475   if (lh->standard_opcode_lengths)
12476     xfree (lh->standard_opcode_lengths);
12477
12478   /* Remember that all the lh->file_names[i].name pointers are
12479      pointers into debug_line_buffer, and don't need to be freed.  */
12480   if (lh->file_names)
12481     xfree (lh->file_names);
12482
12483   /* Similarly for the include directory names.  */
12484   if (lh->include_dirs)
12485     xfree (lh->include_dirs);
12486
12487   xfree (lh);
12488 }
12489
12490 /* Add an entry to LH's include directory table.  */
12491
12492 static void
12493 add_include_dir (struct line_header *lh, char *include_dir)
12494 {
12495   /* Grow the array if necessary.  */
12496   if (lh->include_dirs_size == 0)
12497     {
12498       lh->include_dirs_size = 1; /* for testing */
12499       lh->include_dirs = xmalloc (lh->include_dirs_size
12500                                   * sizeof (*lh->include_dirs));
12501     }
12502   else if (lh->num_include_dirs >= lh->include_dirs_size)
12503     {
12504       lh->include_dirs_size *= 2;
12505       lh->include_dirs = xrealloc (lh->include_dirs,
12506                                    (lh->include_dirs_size
12507                                     * sizeof (*lh->include_dirs)));
12508     }
12509
12510   lh->include_dirs[lh->num_include_dirs++] = include_dir;
12511 }
12512
12513 /* Add an entry to LH's file name table.  */
12514
12515 static void
12516 add_file_name (struct line_header *lh,
12517                char *name,
12518                unsigned int dir_index,
12519                unsigned int mod_time,
12520                unsigned int length)
12521 {
12522   struct file_entry *fe;
12523
12524   /* Grow the array if necessary.  */
12525   if (lh->file_names_size == 0)
12526     {
12527       lh->file_names_size = 1; /* for testing */
12528       lh->file_names = xmalloc (lh->file_names_size
12529                                 * sizeof (*lh->file_names));
12530     }
12531   else if (lh->num_file_names >= lh->file_names_size)
12532     {
12533       lh->file_names_size *= 2;
12534       lh->file_names = xrealloc (lh->file_names,
12535                                  (lh->file_names_size
12536                                   * sizeof (*lh->file_names)));
12537     }
12538
12539   fe = &lh->file_names[lh->num_file_names++];
12540   fe->name = name;
12541   fe->dir_index = dir_index;
12542   fe->mod_time = mod_time;
12543   fe->length = length;
12544   fe->included_p = 0;
12545   fe->symtab = NULL;
12546 }
12547
12548 /* Read the statement program header starting at OFFSET in
12549    .debug_line, or .debug_line.dwo.  Return a pointer
12550    to a struct line_header, allocated using xmalloc.
12551
12552    NOTE: the strings in the include directory and file name tables of
12553    the returned object point into the dwarf line section buffer,
12554    and must not be freed.  */
12555
12556 static struct line_header *
12557 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
12558 {
12559   struct cleanup *back_to;
12560   struct line_header *lh;
12561   gdb_byte *line_ptr;
12562   unsigned int bytes_read, offset_size;
12563   int i;
12564   char *cur_dir, *cur_file;
12565   struct dwarf2_section_info *section;
12566   bfd *abfd;
12567
12568   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
12569      DWO file.  */
12570   if (cu->dwo_unit && cu->per_cu->is_debug_types)
12571     section = &cu->dwo_unit->dwo_file->sections.line;
12572   else
12573     section = &dwarf2_per_objfile->line;
12574
12575   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
12576   if (section->buffer == NULL)
12577     {
12578       if (cu->dwo_unit && cu->per_cu->is_debug_types)
12579         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
12580       else
12581         complaint (&symfile_complaints, _("missing .debug_line section"));
12582       return 0;
12583     }
12584
12585   /* We can't do this until we know the section is non-empty.
12586      Only then do we know we have such a section.  */
12587   abfd = section->asection->owner;
12588
12589   /* Make sure that at least there's room for the total_length field.
12590      That could be 12 bytes long, but we're just going to fudge that.  */
12591   if (offset + 4 >= section->size)
12592     {
12593       dwarf2_statement_list_fits_in_line_number_section_complaint ();
12594       return 0;
12595     }
12596
12597   lh = xmalloc (sizeof (*lh));
12598   memset (lh, 0, sizeof (*lh));
12599   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
12600                           (void *) lh);
12601
12602   line_ptr = section->buffer + offset;
12603
12604   /* Read in the header.  */
12605   lh->total_length =
12606     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
12607                                             &bytes_read, &offset_size);
12608   line_ptr += bytes_read;
12609   if (line_ptr + lh->total_length > (section->buffer + section->size))
12610     {
12611       dwarf2_statement_list_fits_in_line_number_section_complaint ();
12612       return 0;
12613     }
12614   lh->statement_program_end = line_ptr + lh->total_length;
12615   lh->version = read_2_bytes (abfd, line_ptr);
12616   line_ptr += 2;
12617   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
12618   line_ptr += offset_size;
12619   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
12620   line_ptr += 1;
12621   if (lh->version >= 4)
12622     {
12623       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
12624       line_ptr += 1;
12625     }
12626   else
12627     lh->maximum_ops_per_instruction = 1;
12628
12629   if (lh->maximum_ops_per_instruction == 0)
12630     {
12631       lh->maximum_ops_per_instruction = 1;
12632       complaint (&symfile_complaints,
12633                  _("invalid maximum_ops_per_instruction "
12634                    "in `.debug_line' section"));
12635     }
12636
12637   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
12638   line_ptr += 1;
12639   lh->line_base = read_1_signed_byte (abfd, line_ptr);
12640   line_ptr += 1;
12641   lh->line_range = read_1_byte (abfd, line_ptr);
12642   line_ptr += 1;
12643   lh->opcode_base = read_1_byte (abfd, line_ptr);
12644   line_ptr += 1;
12645   lh->standard_opcode_lengths
12646     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
12647
12648   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
12649   for (i = 1; i < lh->opcode_base; ++i)
12650     {
12651       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
12652       line_ptr += 1;
12653     }
12654
12655   /* Read directory table.  */
12656   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
12657     {
12658       line_ptr += bytes_read;
12659       add_include_dir (lh, cur_dir);
12660     }
12661   line_ptr += bytes_read;
12662
12663   /* Read file name table.  */
12664   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
12665     {
12666       unsigned int dir_index, mod_time, length;
12667
12668       line_ptr += bytes_read;
12669       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12670       line_ptr += bytes_read;
12671       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12672       line_ptr += bytes_read;
12673       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12674       line_ptr += bytes_read;
12675
12676       add_file_name (lh, cur_file, dir_index, mod_time, length);
12677     }
12678   line_ptr += bytes_read;
12679   lh->statement_program_start = line_ptr;
12680
12681   if (line_ptr > (section->buffer + section->size))
12682     complaint (&symfile_complaints,
12683                _("line number info header doesn't "
12684                  "fit in `.debug_line' section"));
12685
12686   discard_cleanups (back_to);
12687   return lh;
12688 }
12689
12690 /* Subroutine of dwarf_decode_lines to simplify it.
12691    Return the file name of the psymtab for included file FILE_INDEX
12692    in line header LH of PST.
12693    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
12694    If space for the result is malloc'd, it will be freed by a cleanup.
12695    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
12696
12697 static char *
12698 psymtab_include_file_name (const struct line_header *lh, int file_index,
12699                            const struct partial_symtab *pst,
12700                            const char *comp_dir)
12701 {
12702   const struct file_entry fe = lh->file_names [file_index];
12703   char *include_name = fe.name;
12704   char *include_name_to_compare = include_name;
12705   char *dir_name = NULL;
12706   const char *pst_filename;
12707   char *copied_name = NULL;
12708   int file_is_pst;
12709
12710   if (fe.dir_index)
12711     dir_name = lh->include_dirs[fe.dir_index - 1];
12712
12713   if (!IS_ABSOLUTE_PATH (include_name)
12714       && (dir_name != NULL || comp_dir != NULL))
12715     {
12716       /* Avoid creating a duplicate psymtab for PST.
12717          We do this by comparing INCLUDE_NAME and PST_FILENAME.
12718          Before we do the comparison, however, we need to account
12719          for DIR_NAME and COMP_DIR.
12720          First prepend dir_name (if non-NULL).  If we still don't
12721          have an absolute path prepend comp_dir (if non-NULL).
12722          However, the directory we record in the include-file's
12723          psymtab does not contain COMP_DIR (to match the
12724          corresponding symtab(s)).
12725
12726          Example:
12727
12728          bash$ cd /tmp
12729          bash$ gcc -g ./hello.c
12730          include_name = "hello.c"
12731          dir_name = "."
12732          DW_AT_comp_dir = comp_dir = "/tmp"
12733          DW_AT_name = "./hello.c"  */
12734
12735       if (dir_name != NULL)
12736         {
12737           include_name = concat (dir_name, SLASH_STRING,
12738                                  include_name, (char *)NULL);
12739           include_name_to_compare = include_name;
12740           make_cleanup (xfree, include_name);
12741         }
12742       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
12743         {
12744           include_name_to_compare = concat (comp_dir, SLASH_STRING,
12745                                             include_name, (char *)NULL);
12746         }
12747     }
12748
12749   pst_filename = pst->filename;
12750   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
12751     {
12752       copied_name = concat (pst->dirname, SLASH_STRING,
12753                             pst_filename, (char *)NULL);
12754       pst_filename = copied_name;
12755     }
12756
12757   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
12758
12759   if (include_name_to_compare != include_name)
12760     xfree (include_name_to_compare);
12761   if (copied_name != NULL)
12762     xfree (copied_name);
12763
12764   if (file_is_pst)
12765     return NULL;
12766   return include_name;
12767 }
12768
12769 /* Ignore this record_line request.  */
12770
12771 static void
12772 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
12773 {
12774   return;
12775 }
12776
12777 /* Subroutine of dwarf_decode_lines to simplify it.
12778    Process the line number information in LH.  */
12779
12780 static void
12781 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
12782                       struct dwarf2_cu *cu, struct partial_symtab *pst)
12783 {
12784   gdb_byte *line_ptr, *extended_end;
12785   gdb_byte *line_end;
12786   unsigned int bytes_read, extended_len;
12787   unsigned char op_code, extended_op, adj_opcode;
12788   CORE_ADDR baseaddr;
12789   struct objfile *objfile = cu->objfile;
12790   bfd *abfd = objfile->obfd;
12791   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12792   const int decode_for_pst_p = (pst != NULL);
12793   struct subfile *last_subfile = NULL;
12794   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
12795     = record_line;
12796
12797   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12798
12799   line_ptr = lh->statement_program_start;
12800   line_end = lh->statement_program_end;
12801
12802   /* Read the statement sequences until there's nothing left.  */
12803   while (line_ptr < line_end)
12804     {
12805       /* state machine registers  */
12806       CORE_ADDR address = 0;
12807       unsigned int file = 1;
12808       unsigned int line = 1;
12809       unsigned int column = 0;
12810       int is_stmt = lh->default_is_stmt;
12811       int basic_block = 0;
12812       int end_sequence = 0;
12813       CORE_ADDR addr;
12814       unsigned char op_index = 0;
12815
12816       if (!decode_for_pst_p && lh->num_file_names >= file)
12817         {
12818           /* Start a subfile for the current file of the state machine.  */
12819           /* lh->include_dirs and lh->file_names are 0-based, but the
12820              directory and file name numbers in the statement program
12821              are 1-based.  */
12822           struct file_entry *fe = &lh->file_names[file - 1];
12823           char *dir = NULL;
12824
12825           if (fe->dir_index)
12826             dir = lh->include_dirs[fe->dir_index - 1];
12827
12828           dwarf2_start_subfile (fe->name, dir, comp_dir);
12829         }
12830
12831       /* Decode the table.  */
12832       while (!end_sequence)
12833         {
12834           op_code = read_1_byte (abfd, line_ptr);
12835           line_ptr += 1;
12836           if (line_ptr > line_end)
12837             {
12838               dwarf2_debug_line_missing_end_sequence_complaint ();
12839               break;
12840             }
12841
12842           if (op_code >= lh->opcode_base)
12843             {
12844               /* Special operand.  */
12845               adj_opcode = op_code - lh->opcode_base;
12846               address += (((op_index + (adj_opcode / lh->line_range))
12847                            / lh->maximum_ops_per_instruction)
12848                           * lh->minimum_instruction_length);
12849               op_index = ((op_index + (adj_opcode / lh->line_range))
12850                           % lh->maximum_ops_per_instruction);
12851               line += lh->line_base + (adj_opcode % lh->line_range);
12852               if (lh->num_file_names < file || file == 0)
12853                 dwarf2_debug_line_missing_file_complaint ();
12854               /* For now we ignore lines not starting on an
12855                  instruction boundary.  */
12856               else if (op_index == 0)
12857                 {
12858                   lh->file_names[file - 1].included_p = 1;
12859                   if (!decode_for_pst_p && is_stmt)
12860                     {
12861                       if (last_subfile != current_subfile)
12862                         {
12863                           addr = gdbarch_addr_bits_remove (gdbarch, address);
12864                           if (last_subfile)
12865                             (*p_record_line) (last_subfile, 0, addr);
12866                           last_subfile = current_subfile;
12867                         }
12868                       /* Append row to matrix using current values.  */
12869                       addr = gdbarch_addr_bits_remove (gdbarch, address);
12870                       (*p_record_line) (current_subfile, line, addr);
12871                     }
12872                 }
12873               basic_block = 0;
12874             }
12875           else switch (op_code)
12876             {
12877             case DW_LNS_extended_op:
12878               extended_len = read_unsigned_leb128 (abfd, line_ptr,
12879                                                    &bytes_read);
12880               line_ptr += bytes_read;
12881               extended_end = line_ptr + extended_len;
12882               extended_op = read_1_byte (abfd, line_ptr);
12883               line_ptr += 1;
12884               switch (extended_op)
12885                 {
12886                 case DW_LNE_end_sequence:
12887                   p_record_line = record_line;
12888                   end_sequence = 1;
12889                   break;
12890                 case DW_LNE_set_address:
12891                   address = read_address (abfd, line_ptr, cu, &bytes_read);
12892
12893                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
12894                     {
12895                       /* This line table is for a function which has been
12896                          GCd by the linker.  Ignore it.  PR gdb/12528 */
12897
12898                       long line_offset
12899                         = line_ptr - dwarf2_per_objfile->line.buffer;
12900
12901                       complaint (&symfile_complaints,
12902                                  _(".debug_line address at offset 0x%lx is 0 "
12903                                    "[in module %s]"),
12904                                  line_offset, objfile->name);
12905                       p_record_line = noop_record_line;
12906                     }
12907
12908                   op_index = 0;
12909                   line_ptr += bytes_read;
12910                   address += baseaddr;
12911                   break;
12912                 case DW_LNE_define_file:
12913                   {
12914                     char *cur_file;
12915                     unsigned int dir_index, mod_time, length;
12916
12917                     cur_file = read_direct_string (abfd, line_ptr,
12918                                                    &bytes_read);
12919                     line_ptr += bytes_read;
12920                     dir_index =
12921                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12922                     line_ptr += bytes_read;
12923                     mod_time =
12924                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12925                     line_ptr += bytes_read;
12926                     length =
12927                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12928                     line_ptr += bytes_read;
12929                     add_file_name (lh, cur_file, dir_index, mod_time, length);
12930                   }
12931                   break;
12932                 case DW_LNE_set_discriminator:
12933                   /* The discriminator is not interesting to the debugger;
12934                      just ignore it.  */
12935                   line_ptr = extended_end;
12936                   break;
12937                 default:
12938                   complaint (&symfile_complaints,
12939                              _("mangled .debug_line section"));
12940                   return;
12941                 }
12942               /* Make sure that we parsed the extended op correctly.  If e.g.
12943                  we expected a different address size than the producer used,
12944                  we may have read the wrong number of bytes.  */
12945               if (line_ptr != extended_end)
12946                 {
12947                   complaint (&symfile_complaints,
12948                              _("mangled .debug_line section"));
12949                   return;
12950                 }
12951               break;
12952             case DW_LNS_copy:
12953               if (lh->num_file_names < file || file == 0)
12954                 dwarf2_debug_line_missing_file_complaint ();
12955               else
12956                 {
12957                   lh->file_names[file - 1].included_p = 1;
12958                   if (!decode_for_pst_p && is_stmt)
12959                     {
12960                       if (last_subfile != current_subfile)
12961                         {
12962                           addr = gdbarch_addr_bits_remove (gdbarch, address);
12963                           if (last_subfile)
12964                             (*p_record_line) (last_subfile, 0, addr);
12965                           last_subfile = current_subfile;
12966                         }
12967                       addr = gdbarch_addr_bits_remove (gdbarch, address);
12968                       (*p_record_line) (current_subfile, line, addr);
12969                     }
12970                 }
12971               basic_block = 0;
12972               break;
12973             case DW_LNS_advance_pc:
12974               {
12975                 CORE_ADDR adjust
12976                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12977
12978                 address += (((op_index + adjust)
12979                              / lh->maximum_ops_per_instruction)
12980                             * lh->minimum_instruction_length);
12981                 op_index = ((op_index + adjust)
12982                             % lh->maximum_ops_per_instruction);
12983                 line_ptr += bytes_read;
12984               }
12985               break;
12986             case DW_LNS_advance_line:
12987               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
12988               line_ptr += bytes_read;
12989               break;
12990             case DW_LNS_set_file:
12991               {
12992                 /* The arrays lh->include_dirs and lh->file_names are
12993                    0-based, but the directory and file name numbers in
12994                    the statement program are 1-based.  */
12995                 struct file_entry *fe;
12996                 char *dir = NULL;
12997
12998                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12999                 line_ptr += bytes_read;
13000                 if (lh->num_file_names < file || file == 0)
13001                   dwarf2_debug_line_missing_file_complaint ();
13002                 else
13003                   {
13004                     fe = &lh->file_names[file - 1];
13005                     if (fe->dir_index)
13006                       dir = lh->include_dirs[fe->dir_index - 1];
13007                     if (!decode_for_pst_p)
13008                       {
13009                         last_subfile = current_subfile;
13010                         dwarf2_start_subfile (fe->name, dir, comp_dir);
13011                       }
13012                   }
13013               }
13014               break;
13015             case DW_LNS_set_column:
13016               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13017               line_ptr += bytes_read;
13018               break;
13019             case DW_LNS_negate_stmt:
13020               is_stmt = (!is_stmt);
13021               break;
13022             case DW_LNS_set_basic_block:
13023               basic_block = 1;
13024               break;
13025             /* Add to the address register of the state machine the
13026                address increment value corresponding to special opcode
13027                255.  I.e., this value is scaled by the minimum
13028                instruction length since special opcode 255 would have
13029                scaled the increment.  */
13030             case DW_LNS_const_add_pc:
13031               {
13032                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
13033
13034                 address += (((op_index + adjust)
13035                              / lh->maximum_ops_per_instruction)
13036                             * lh->minimum_instruction_length);
13037                 op_index = ((op_index + adjust)
13038                             % lh->maximum_ops_per_instruction);
13039               }
13040               break;
13041             case DW_LNS_fixed_advance_pc:
13042               address += read_2_bytes (abfd, line_ptr);
13043               op_index = 0;
13044               line_ptr += 2;
13045               break;
13046             default:
13047               {
13048                 /* Unknown standard opcode, ignore it.  */
13049                 int i;
13050
13051                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
13052                   {
13053                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13054                     line_ptr += bytes_read;
13055                   }
13056               }
13057             }
13058         }
13059       if (lh->num_file_names < file || file == 0)
13060         dwarf2_debug_line_missing_file_complaint ();
13061       else
13062         {
13063           lh->file_names[file - 1].included_p = 1;
13064           if (!decode_for_pst_p)
13065             {
13066               addr = gdbarch_addr_bits_remove (gdbarch, address);
13067               (*p_record_line) (current_subfile, 0, addr);
13068             }
13069         }
13070     }
13071 }
13072
13073 /* Decode the Line Number Program (LNP) for the given line_header
13074    structure and CU.  The actual information extracted and the type
13075    of structures created from the LNP depends on the value of PST.
13076
13077    1. If PST is NULL, then this procedure uses the data from the program
13078       to create all necessary symbol tables, and their linetables.
13079
13080    2. If PST is not NULL, this procedure reads the program to determine
13081       the list of files included by the unit represented by PST, and
13082       builds all the associated partial symbol tables.
13083
13084    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
13085    It is used for relative paths in the line table.
13086    NOTE: When processing partial symtabs (pst != NULL),
13087    comp_dir == pst->dirname.
13088
13089    NOTE: It is important that psymtabs have the same file name (via strcmp)
13090    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
13091    symtab we don't use it in the name of the psymtabs we create.
13092    E.g. expand_line_sal requires this when finding psymtabs to expand.
13093    A good testcase for this is mb-inline.exp.  */
13094
13095 static void
13096 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
13097                     struct dwarf2_cu *cu, struct partial_symtab *pst,
13098                     int want_line_info)
13099 {
13100   struct objfile *objfile = cu->objfile;
13101   const int decode_for_pst_p = (pst != NULL);
13102   struct subfile *first_subfile = current_subfile;
13103
13104   if (want_line_info)
13105     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
13106
13107   if (decode_for_pst_p)
13108     {
13109       int file_index;
13110
13111       /* Now that we're done scanning the Line Header Program, we can
13112          create the psymtab of each included file.  */
13113       for (file_index = 0; file_index < lh->num_file_names; file_index++)
13114         if (lh->file_names[file_index].included_p == 1)
13115           {
13116             char *include_name =
13117               psymtab_include_file_name (lh, file_index, pst, comp_dir);
13118             if (include_name != NULL)
13119               dwarf2_create_include_psymtab (include_name, pst, objfile);
13120           }
13121     }
13122   else
13123     {
13124       /* Make sure a symtab is created for every file, even files
13125          which contain only variables (i.e. no code with associated
13126          line numbers).  */
13127       int i;
13128
13129       for (i = 0; i < lh->num_file_names; i++)
13130         {
13131           char *dir = NULL;
13132           struct file_entry *fe;
13133
13134           fe = &lh->file_names[i];
13135           if (fe->dir_index)
13136             dir = lh->include_dirs[fe->dir_index - 1];
13137           dwarf2_start_subfile (fe->name, dir, comp_dir);
13138
13139           /* Skip the main file; we don't need it, and it must be
13140              allocated last, so that it will show up before the
13141              non-primary symtabs in the objfile's symtab list.  */
13142           if (current_subfile == first_subfile)
13143             continue;
13144
13145           if (current_subfile->symtab == NULL)
13146             current_subfile->symtab = allocate_symtab (current_subfile->name,
13147                                                        objfile);
13148           fe->symtab = current_subfile->symtab;
13149         }
13150     }
13151 }
13152
13153 /* Start a subfile for DWARF.  FILENAME is the name of the file and
13154    DIRNAME the name of the source directory which contains FILENAME
13155    or NULL if not known.  COMP_DIR is the compilation directory for the
13156    linetable's compilation unit or NULL if not known.
13157    This routine tries to keep line numbers from identical absolute and
13158    relative file names in a common subfile.
13159
13160    Using the `list' example from the GDB testsuite, which resides in
13161    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
13162    of /srcdir/list0.c yields the following debugging information for list0.c:
13163
13164    DW_AT_name:          /srcdir/list0.c
13165    DW_AT_comp_dir:              /compdir
13166    files.files[0].name: list0.h
13167    files.files[0].dir:  /srcdir
13168    files.files[1].name: list0.c
13169    files.files[1].dir:  /srcdir
13170
13171    The line number information for list0.c has to end up in a single
13172    subfile, so that `break /srcdir/list0.c:1' works as expected.
13173    start_subfile will ensure that this happens provided that we pass the
13174    concatenation of files.files[1].dir and files.files[1].name as the
13175    subfile's name.  */
13176
13177 static void
13178 dwarf2_start_subfile (char *filename, const char *dirname,
13179                       const char *comp_dir)
13180 {
13181   char *fullname;
13182
13183   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
13184      `start_symtab' will always pass the contents of DW_AT_comp_dir as
13185      second argument to start_subfile.  To be consistent, we do the
13186      same here.  In order not to lose the line information directory,
13187      we concatenate it to the filename when it makes sense.
13188      Note that the Dwarf3 standard says (speaking of filenames in line
13189      information): ``The directory index is ignored for file names
13190      that represent full path names''.  Thus ignoring dirname in the
13191      `else' branch below isn't an issue.  */
13192
13193   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
13194     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
13195   else
13196     fullname = filename;
13197
13198   start_subfile (fullname, comp_dir);
13199
13200   if (fullname != filename)
13201     xfree (fullname);
13202 }
13203
13204 static void
13205 var_decode_location (struct attribute *attr, struct symbol *sym,
13206                      struct dwarf2_cu *cu)
13207 {
13208   struct objfile *objfile = cu->objfile;
13209   struct comp_unit_head *cu_header = &cu->header;
13210
13211   /* NOTE drow/2003-01-30: There used to be a comment and some special
13212      code here to turn a symbol with DW_AT_external and a
13213      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
13214      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
13215      with some versions of binutils) where shared libraries could have
13216      relocations against symbols in their debug information - the
13217      minimal symbol would have the right address, but the debug info
13218      would not.  It's no longer necessary, because we will explicitly
13219      apply relocations when we read in the debug information now.  */
13220
13221   /* A DW_AT_location attribute with no contents indicates that a
13222      variable has been optimized away.  */
13223   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
13224     {
13225       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
13226       return;
13227     }
13228
13229   /* Handle one degenerate form of location expression specially, to
13230      preserve GDB's previous behavior when section offsets are
13231      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
13232      then mark this symbol as LOC_STATIC.  */
13233
13234   if (attr_form_is_block (attr)
13235       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
13236            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
13237           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
13238               && (DW_BLOCK (attr)->size
13239                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
13240     {
13241       unsigned int dummy;
13242
13243       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
13244         SYMBOL_VALUE_ADDRESS (sym) =
13245           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
13246       else
13247         SYMBOL_VALUE_ADDRESS (sym) =
13248           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
13249       SYMBOL_CLASS (sym) = LOC_STATIC;
13250       fixup_symbol_section (sym, objfile);
13251       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
13252                                               SYMBOL_SECTION (sym));
13253       return;
13254     }
13255
13256   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
13257      expression evaluator, and use LOC_COMPUTED only when necessary
13258      (i.e. when the value of a register or memory location is
13259      referenced, or a thread-local block, etc.).  Then again, it might
13260      not be worthwhile.  I'm assuming that it isn't unless performance
13261      or memory numbers show me otherwise.  */
13262
13263   dwarf2_symbol_mark_computed (attr, sym, cu);
13264   SYMBOL_CLASS (sym) = LOC_COMPUTED;
13265
13266   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
13267     cu->has_loclist = 1;
13268 }
13269
13270 /* Given a pointer to a DWARF information entry, figure out if we need
13271    to make a symbol table entry for it, and if so, create a new entry
13272    and return a pointer to it.
13273    If TYPE is NULL, determine symbol type from the die, otherwise
13274    used the passed type.
13275    If SPACE is not NULL, use it to hold the new symbol.  If it is
13276    NULL, allocate a new symbol on the objfile's obstack.  */
13277
13278 static struct symbol *
13279 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
13280                  struct symbol *space)
13281 {
13282   struct objfile *objfile = cu->objfile;
13283   struct symbol *sym = NULL;
13284   char *name;
13285   struct attribute *attr = NULL;
13286   struct attribute *attr2 = NULL;
13287   CORE_ADDR baseaddr;
13288   struct pending **list_to_add = NULL;
13289
13290   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13291
13292   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13293
13294   name = dwarf2_name (die, cu);
13295   if (name)
13296     {
13297       const char *linkagename;
13298       int suppress_add = 0;
13299
13300       if (space)
13301         sym = space;
13302       else
13303         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
13304       OBJSTAT (objfile, n_syms++);
13305
13306       /* Cache this symbol's name and the name's demangled form (if any).  */
13307       SYMBOL_SET_LANGUAGE (sym, cu->language);
13308       linkagename = dwarf2_physname (name, die, cu);
13309       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
13310
13311       /* Fortran does not have mangling standard and the mangling does differ
13312          between gfortran, iFort etc.  */
13313       if (cu->language == language_fortran
13314           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
13315         symbol_set_demangled_name (&(sym->ginfo),
13316                                    (char *) dwarf2_full_name (name, die, cu),
13317                                    NULL);
13318
13319       /* Default assumptions.
13320          Use the passed type or decode it from the die.  */
13321       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
13322       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
13323       if (type != NULL)
13324         SYMBOL_TYPE (sym) = type;
13325       else
13326         SYMBOL_TYPE (sym) = die_type (die, cu);
13327       attr = dwarf2_attr (die,
13328                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
13329                           cu);
13330       if (attr)
13331         {
13332           SYMBOL_LINE (sym) = DW_UNSND (attr);
13333         }
13334
13335       attr = dwarf2_attr (die,
13336                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
13337                           cu);
13338       if (attr)
13339         {
13340           int file_index = DW_UNSND (attr);
13341
13342           if (cu->line_header == NULL
13343               || file_index > cu->line_header->num_file_names)
13344             complaint (&symfile_complaints,
13345                        _("file index out of range"));
13346           else if (file_index > 0)
13347             {
13348               struct file_entry *fe;
13349
13350               fe = &cu->line_header->file_names[file_index - 1];
13351               SYMBOL_SYMTAB (sym) = fe->symtab;
13352             }
13353         }
13354
13355       switch (die->tag)
13356         {
13357         case DW_TAG_label:
13358           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13359           if (attr)
13360             {
13361               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
13362             }
13363           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
13364           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
13365           SYMBOL_CLASS (sym) = LOC_LABEL;
13366           add_symbol_to_list (sym, cu->list_in_scope);
13367           break;
13368         case DW_TAG_subprogram:
13369           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
13370              finish_block.  */
13371           SYMBOL_CLASS (sym) = LOC_BLOCK;
13372           attr2 = dwarf2_attr (die, DW_AT_external, cu);
13373           if ((attr2 && (DW_UNSND (attr2) != 0))
13374               || cu->language == language_ada)
13375             {
13376               /* Subprograms marked external are stored as a global symbol.
13377                  Ada subprograms, whether marked external or not, are always
13378                  stored as a global symbol, because we want to be able to
13379                  access them globally.  For instance, we want to be able
13380                  to break on a nested subprogram without having to
13381                  specify the context.  */
13382               list_to_add = &global_symbols;
13383             }
13384           else
13385             {
13386               list_to_add = cu->list_in_scope;
13387             }
13388           break;
13389         case DW_TAG_inlined_subroutine:
13390           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
13391              finish_block.  */
13392           SYMBOL_CLASS (sym) = LOC_BLOCK;
13393           SYMBOL_INLINED (sym) = 1;
13394           list_to_add = cu->list_in_scope;
13395           break;
13396         case DW_TAG_template_value_param:
13397           suppress_add = 1;
13398           /* Fall through.  */
13399         case DW_TAG_constant:
13400         case DW_TAG_variable:
13401         case DW_TAG_member:
13402           /* Compilation with minimal debug info may result in
13403              variables with missing type entries.  Change the
13404              misleading `void' type to something sensible.  */
13405           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
13406             SYMBOL_TYPE (sym)
13407               = objfile_type (objfile)->nodebug_data_symbol;
13408
13409           attr = dwarf2_attr (die, DW_AT_const_value, cu);
13410           /* In the case of DW_TAG_member, we should only be called for
13411              static const members.  */
13412           if (die->tag == DW_TAG_member)
13413             {
13414               /* dwarf2_add_field uses die_is_declaration,
13415                  so we do the same.  */
13416               gdb_assert (die_is_declaration (die, cu));
13417               gdb_assert (attr);
13418             }
13419           if (attr)
13420             {
13421               dwarf2_const_value (attr, sym, cu);
13422               attr2 = dwarf2_attr (die, DW_AT_external, cu);
13423               if (!suppress_add)
13424                 {
13425                   if (attr2 && (DW_UNSND (attr2) != 0))
13426                     list_to_add = &global_symbols;
13427                   else
13428                     list_to_add = cu->list_in_scope;
13429                 }
13430               break;
13431             }
13432           attr = dwarf2_attr (die, DW_AT_location, cu);
13433           if (attr)
13434             {
13435               var_decode_location (attr, sym, cu);
13436               attr2 = dwarf2_attr (die, DW_AT_external, cu);
13437               if (SYMBOL_CLASS (sym) == LOC_STATIC
13438                   && SYMBOL_VALUE_ADDRESS (sym) == 0
13439                   && !dwarf2_per_objfile->has_section_at_zero)
13440                 {
13441                   /* When a static variable is eliminated by the linker,
13442                      the corresponding debug information is not stripped
13443                      out, but the variable address is set to null;
13444                      do not add such variables into symbol table.  */
13445                 }
13446               else if (attr2 && (DW_UNSND (attr2) != 0))
13447                 {
13448                   /* Workaround gfortran PR debug/40040 - it uses
13449                      DW_AT_location for variables in -fPIC libraries which may
13450                      get overriden by other libraries/executable and get
13451                      a different address.  Resolve it by the minimal symbol
13452                      which may come from inferior's executable using copy
13453                      relocation.  Make this workaround only for gfortran as for
13454                      other compilers GDB cannot guess the minimal symbol
13455                      Fortran mangling kind.  */
13456                   if (cu->language == language_fortran && die->parent
13457                       && die->parent->tag == DW_TAG_module
13458                       && cu->producer
13459                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
13460                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
13461
13462                   /* A variable with DW_AT_external is never static,
13463                      but it may be block-scoped.  */
13464                   list_to_add = (cu->list_in_scope == &file_symbols
13465                                  ? &global_symbols : cu->list_in_scope);
13466                 }
13467               else
13468                 list_to_add = cu->list_in_scope;
13469             }
13470           else
13471             {
13472               /* We do not know the address of this symbol.
13473                  If it is an external symbol and we have type information
13474                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
13475                  The address of the variable will then be determined from
13476                  the minimal symbol table whenever the variable is
13477                  referenced.  */
13478               attr2 = dwarf2_attr (die, DW_AT_external, cu);
13479               if (attr2 && (DW_UNSND (attr2) != 0)
13480                   && dwarf2_attr (die, DW_AT_type, cu) != NULL)
13481                 {
13482                   /* A variable with DW_AT_external is never static, but it
13483                      may be block-scoped.  */
13484                   list_to_add = (cu->list_in_scope == &file_symbols
13485                                  ? &global_symbols : cu->list_in_scope);
13486
13487                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
13488                 }
13489               else if (!die_is_declaration (die, cu))
13490                 {
13491                   /* Use the default LOC_OPTIMIZED_OUT class.  */
13492                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
13493                   if (!suppress_add)
13494                     list_to_add = cu->list_in_scope;
13495                 }
13496             }
13497           break;
13498         case DW_TAG_formal_parameter:
13499           /* If we are inside a function, mark this as an argument.  If
13500              not, we might be looking at an argument to an inlined function
13501              when we do not have enough information to show inlined frames;
13502              pretend it's a local variable in that case so that the user can
13503              still see it.  */
13504           if (context_stack_depth > 0
13505               && context_stack[context_stack_depth - 1].name != NULL)
13506             SYMBOL_IS_ARGUMENT (sym) = 1;
13507           attr = dwarf2_attr (die, DW_AT_location, cu);
13508           if (attr)
13509             {
13510               var_decode_location (attr, sym, cu);
13511             }
13512           attr = dwarf2_attr (die, DW_AT_const_value, cu);
13513           if (attr)
13514             {
13515               dwarf2_const_value (attr, sym, cu);
13516             }
13517
13518           list_to_add = cu->list_in_scope;
13519           break;
13520         case DW_TAG_unspecified_parameters:
13521           /* From varargs functions; gdb doesn't seem to have any
13522              interest in this information, so just ignore it for now.
13523              (FIXME?) */
13524           break;
13525         case DW_TAG_template_type_param:
13526           suppress_add = 1;
13527           /* Fall through.  */
13528         case DW_TAG_class_type:
13529         case DW_TAG_interface_type:
13530         case DW_TAG_structure_type:
13531         case DW_TAG_union_type:
13532         case DW_TAG_set_type:
13533         case DW_TAG_enumeration_type:
13534           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13535           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
13536
13537           {
13538             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
13539                really ever be static objects: otherwise, if you try
13540                to, say, break of a class's method and you're in a file
13541                which doesn't mention that class, it won't work unless
13542                the check for all static symbols in lookup_symbol_aux
13543                saves you.  See the OtherFileClass tests in
13544                gdb.c++/namespace.exp.  */
13545
13546             if (!suppress_add)
13547               {
13548                 list_to_add = (cu->list_in_scope == &file_symbols
13549                                && (cu->language == language_cplus
13550                                    || cu->language == language_java)
13551                                ? &global_symbols : cu->list_in_scope);
13552
13553                 /* The semantics of C++ state that "struct foo {
13554                    ... }" also defines a typedef for "foo".  A Java
13555                    class declaration also defines a typedef for the
13556                    class.  */
13557                 if (cu->language == language_cplus
13558                     || cu->language == language_java
13559                     || cu->language == language_ada)
13560                   {
13561                     /* The symbol's name is already allocated along
13562                        with this objfile, so we don't need to
13563                        duplicate it for the type.  */
13564                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
13565                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
13566                   }
13567               }
13568           }
13569           break;
13570         case DW_TAG_typedef:
13571           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13572           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
13573           list_to_add = cu->list_in_scope;
13574           break;
13575         case DW_TAG_base_type:
13576         case DW_TAG_subrange_type:
13577           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13578           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
13579           list_to_add = cu->list_in_scope;
13580           break;
13581         case DW_TAG_enumerator:
13582           attr = dwarf2_attr (die, DW_AT_const_value, cu);
13583           if (attr)
13584             {
13585               dwarf2_const_value (attr, sym, cu);
13586             }
13587           {
13588             /* NOTE: carlton/2003-11-10: See comment above in the
13589                DW_TAG_class_type, etc. block.  */
13590
13591             list_to_add = (cu->list_in_scope == &file_symbols
13592                            && (cu->language == language_cplus
13593                                || cu->language == language_java)
13594                            ? &global_symbols : cu->list_in_scope);
13595           }
13596           break;
13597         case DW_TAG_namespace:
13598           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13599           list_to_add = &global_symbols;
13600           break;
13601         default:
13602           /* Not a tag we recognize.  Hopefully we aren't processing
13603              trash data, but since we must specifically ignore things
13604              we don't recognize, there is nothing else we should do at
13605              this point.  */
13606           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
13607                      dwarf_tag_name (die->tag));
13608           break;
13609         }
13610
13611       if (suppress_add)
13612         {
13613           sym->hash_next = objfile->template_symbols;
13614           objfile->template_symbols = sym;
13615           list_to_add = NULL;
13616         }
13617
13618       if (list_to_add != NULL)
13619         add_symbol_to_list (sym, list_to_add);
13620
13621       /* For the benefit of old versions of GCC, check for anonymous
13622          namespaces based on the demangled name.  */
13623       if (!processing_has_namespace_info
13624           && cu->language == language_cplus)
13625         cp_scan_for_anonymous_namespaces (sym, objfile);
13626     }
13627   return (sym);
13628 }
13629
13630 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
13631
13632 static struct symbol *
13633 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
13634 {
13635   return new_symbol_full (die, type, cu, NULL);
13636 }
13637
13638 /* Given an attr with a DW_FORM_dataN value in host byte order,
13639    zero-extend it as appropriate for the symbol's type.  The DWARF
13640    standard (v4) is not entirely clear about the meaning of using
13641    DW_FORM_dataN for a constant with a signed type, where the type is
13642    wider than the data.  The conclusion of a discussion on the DWARF
13643    list was that this is unspecified.  We choose to always zero-extend
13644    because that is the interpretation long in use by GCC.  */
13645
13646 static gdb_byte *
13647 dwarf2_const_value_data (struct attribute *attr, struct type *type,
13648                          const char *name, struct obstack *obstack,
13649                          struct dwarf2_cu *cu, LONGEST *value, int bits)
13650 {
13651   struct objfile *objfile = cu->objfile;
13652   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
13653                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
13654   LONGEST l = DW_UNSND (attr);
13655
13656   if (bits < sizeof (*value) * 8)
13657     {
13658       l &= ((LONGEST) 1 << bits) - 1;
13659       *value = l;
13660     }
13661   else if (bits == sizeof (*value) * 8)
13662     *value = l;
13663   else
13664     {
13665       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
13666       store_unsigned_integer (bytes, bits / 8, byte_order, l);
13667       return bytes;
13668     }
13669
13670   return NULL;
13671 }
13672
13673 /* Read a constant value from an attribute.  Either set *VALUE, or if
13674    the value does not fit in *VALUE, set *BYTES - either already
13675    allocated on the objfile obstack, or newly allocated on OBSTACK,
13676    or, set *BATON, if we translated the constant to a location
13677    expression.  */
13678
13679 static void
13680 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
13681                          const char *name, struct obstack *obstack,
13682                          struct dwarf2_cu *cu,
13683                          LONGEST *value, gdb_byte **bytes,
13684                          struct dwarf2_locexpr_baton **baton)
13685 {
13686   struct objfile *objfile = cu->objfile;
13687   struct comp_unit_head *cu_header = &cu->header;
13688   struct dwarf_block *blk;
13689   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
13690                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
13691
13692   *value = 0;
13693   *bytes = NULL;
13694   *baton = NULL;
13695
13696   switch (attr->form)
13697     {
13698     case DW_FORM_addr:
13699     case DW_FORM_GNU_addr_index:
13700       {
13701         gdb_byte *data;
13702
13703         if (TYPE_LENGTH (type) != cu_header->addr_size)
13704           dwarf2_const_value_length_mismatch_complaint (name,
13705                                                         cu_header->addr_size,
13706                                                         TYPE_LENGTH (type));
13707         /* Symbols of this form are reasonably rare, so we just
13708            piggyback on the existing location code rather than writing
13709            a new implementation of symbol_computed_ops.  */
13710         *baton = obstack_alloc (&objfile->objfile_obstack,
13711                                 sizeof (struct dwarf2_locexpr_baton));
13712         (*baton)->per_cu = cu->per_cu;
13713         gdb_assert ((*baton)->per_cu);
13714
13715         (*baton)->size = 2 + cu_header->addr_size;
13716         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
13717         (*baton)->data = data;
13718
13719         data[0] = DW_OP_addr;
13720         store_unsigned_integer (&data[1], cu_header->addr_size,
13721                                 byte_order, DW_ADDR (attr));
13722         data[cu_header->addr_size + 1] = DW_OP_stack_value;
13723       }
13724       break;
13725     case DW_FORM_string:
13726     case DW_FORM_strp:
13727     case DW_FORM_GNU_str_index:
13728       /* DW_STRING is already allocated on the objfile obstack, point
13729          directly to it.  */
13730       *bytes = (gdb_byte *) DW_STRING (attr);
13731       break;
13732     case DW_FORM_block1:
13733     case DW_FORM_block2:
13734     case DW_FORM_block4:
13735     case DW_FORM_block:
13736     case DW_FORM_exprloc:
13737       blk = DW_BLOCK (attr);
13738       if (TYPE_LENGTH (type) != blk->size)
13739         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
13740                                                       TYPE_LENGTH (type));
13741       *bytes = blk->data;
13742       break;
13743
13744       /* The DW_AT_const_value attributes are supposed to carry the
13745          symbol's value "represented as it would be on the target
13746          architecture."  By the time we get here, it's already been
13747          converted to host endianness, so we just need to sign- or
13748          zero-extend it as appropriate.  */
13749     case DW_FORM_data1:
13750       *bytes = dwarf2_const_value_data (attr, type, name,
13751                                         obstack, cu, value, 8);
13752       break;
13753     case DW_FORM_data2:
13754       *bytes = dwarf2_const_value_data (attr, type, name,
13755                                         obstack, cu, value, 16);
13756       break;
13757     case DW_FORM_data4:
13758       *bytes = dwarf2_const_value_data (attr, type, name,
13759                                         obstack, cu, value, 32);
13760       break;
13761     case DW_FORM_data8:
13762       *bytes = dwarf2_const_value_data (attr, type, name,
13763                                         obstack, cu, value, 64);
13764       break;
13765
13766     case DW_FORM_sdata:
13767       *value = DW_SND (attr);
13768       break;
13769
13770     case DW_FORM_udata:
13771       *value = DW_UNSND (attr);
13772       break;
13773
13774     default:
13775       complaint (&symfile_complaints,
13776                  _("unsupported const value attribute form: '%s'"),
13777                  dwarf_form_name (attr->form));
13778       *value = 0;
13779       break;
13780     }
13781 }
13782
13783
13784 /* Copy constant value from an attribute to a symbol.  */
13785
13786 static void
13787 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
13788                     struct dwarf2_cu *cu)
13789 {
13790   struct objfile *objfile = cu->objfile;
13791   struct comp_unit_head *cu_header = &cu->header;
13792   LONGEST value;
13793   gdb_byte *bytes;
13794   struct dwarf2_locexpr_baton *baton;
13795
13796   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
13797                            SYMBOL_PRINT_NAME (sym),
13798                            &objfile->objfile_obstack, cu,
13799                            &value, &bytes, &baton);
13800
13801   if (baton != NULL)
13802     {
13803       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
13804       SYMBOL_LOCATION_BATON (sym) = baton;
13805       SYMBOL_CLASS (sym) = LOC_COMPUTED;
13806     }
13807   else if (bytes != NULL)
13808      {
13809       SYMBOL_VALUE_BYTES (sym) = bytes;
13810       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
13811     }
13812   else
13813     {
13814       SYMBOL_VALUE (sym) = value;
13815       SYMBOL_CLASS (sym) = LOC_CONST;
13816     }
13817 }
13818
13819 /* Return the type of the die in question using its DW_AT_type attribute.  */
13820
13821 static struct type *
13822 die_type (struct die_info *die, struct dwarf2_cu *cu)
13823 {
13824   struct attribute *type_attr;
13825
13826   type_attr = dwarf2_attr (die, DW_AT_type, cu);
13827   if (!type_attr)
13828     {
13829       /* A missing DW_AT_type represents a void type.  */
13830       return objfile_type (cu->objfile)->builtin_void;
13831     }
13832
13833   return lookup_die_type (die, type_attr, cu);
13834 }
13835
13836 /* True iff CU's producer generates GNAT Ada auxiliary information
13837    that allows to find parallel types through that information instead
13838    of having to do expensive parallel lookups by type name.  */
13839
13840 static int
13841 need_gnat_info (struct dwarf2_cu *cu)
13842 {
13843   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
13844      of GNAT produces this auxiliary information, without any indication
13845      that it is produced.  Part of enhancing the FSF version of GNAT
13846      to produce that information will be to put in place an indicator
13847      that we can use in order to determine whether the descriptive type
13848      info is available or not.  One suggestion that has been made is
13849      to use a new attribute, attached to the CU die.  For now, assume
13850      that the descriptive type info is not available.  */
13851   return 0;
13852 }
13853
13854 /* Return the auxiliary type of the die in question using its
13855    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
13856    attribute is not present.  */
13857
13858 static struct type *
13859 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
13860 {
13861   struct attribute *type_attr;
13862
13863   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
13864   if (!type_attr)
13865     return NULL;
13866
13867   return lookup_die_type (die, type_attr, cu);
13868 }
13869
13870 /* If DIE has a descriptive_type attribute, then set the TYPE's
13871    descriptive type accordingly.  */
13872
13873 static void
13874 set_descriptive_type (struct type *type, struct die_info *die,
13875                       struct dwarf2_cu *cu)
13876 {
13877   struct type *descriptive_type = die_descriptive_type (die, cu);
13878
13879   if (descriptive_type)
13880     {
13881       ALLOCATE_GNAT_AUX_TYPE (type);
13882       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
13883     }
13884 }
13885
13886 /* Return the containing type of the die in question using its
13887    DW_AT_containing_type attribute.  */
13888
13889 static struct type *
13890 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13891 {
13892   struct attribute *type_attr;
13893
13894   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
13895   if (!type_attr)
13896     error (_("Dwarf Error: Problem turning containing type into gdb type "
13897              "[in module %s]"), cu->objfile->name);
13898
13899   return lookup_die_type (die, type_attr, cu);
13900 }
13901
13902 /* Look up the type of DIE in CU using its type attribute ATTR.
13903    If there is no type substitute an error marker.  */
13904
13905 static struct type *
13906 lookup_die_type (struct die_info *die, struct attribute *attr,
13907                  struct dwarf2_cu *cu)
13908 {
13909   struct objfile *objfile = cu->objfile;
13910   struct type *this_type;
13911
13912   /* First see if we have it cached.  */
13913
13914   if (is_ref_attr (attr))
13915     {
13916       sect_offset offset = dwarf2_get_ref_die_offset (attr);
13917
13918       this_type = get_die_type_at_offset (offset, cu->per_cu);
13919     }
13920   else if (attr->form == DW_FORM_ref_sig8)
13921     {
13922       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
13923
13924       /* sig_type will be NULL if the signatured type is missing from
13925          the debug info.  */
13926       if (sig_type == NULL)
13927         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
13928                  "at 0x%x [in module %s]"),
13929                die->offset.sect_off, objfile->name);
13930
13931       gdb_assert (sig_type->per_cu.is_debug_types);
13932       /* If we haven't filled in type_offset_in_section yet, then we
13933          haven't read the type in yet.  */
13934       this_type = NULL;
13935       if (sig_type->type_offset_in_section.sect_off != 0)
13936         {
13937           this_type =
13938             get_die_type_at_offset (sig_type->type_offset_in_section,
13939                                     &sig_type->per_cu);
13940         }
13941     }
13942   else
13943     {
13944       dump_die_for_error (die);
13945       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
13946              dwarf_attr_name (attr->name), objfile->name);
13947     }
13948
13949   /* If not cached we need to read it in.  */
13950
13951   if (this_type == NULL)
13952     {
13953       struct die_info *type_die;
13954       struct dwarf2_cu *type_cu = cu;
13955
13956       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
13957       /* If we found the type now, it's probably because the type came
13958          from an inter-CU reference and the type's CU got expanded before
13959          ours.  */
13960       this_type = get_die_type (type_die, type_cu);
13961       if (this_type == NULL)
13962         this_type = read_type_die_1 (type_die, type_cu);
13963     }
13964
13965   /* If we still don't have a type use an error marker.  */
13966
13967   if (this_type == NULL)
13968     {
13969       char *message, *saved;
13970
13971       /* read_type_die already issued a complaint.  */
13972       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
13973                             objfile->name,
13974                             cu->header.offset.sect_off,
13975                             die->offset.sect_off);
13976       saved = obstack_copy0 (&objfile->objfile_obstack,
13977                              message, strlen (message));
13978       xfree (message);
13979
13980       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
13981     }
13982
13983   return this_type;
13984 }
13985
13986 /* Return the type in DIE, CU.
13987    Returns NULL for invalid types.
13988
13989    This first does a lookup in the appropriate type_hash table,
13990    and only reads the die in if necessary.
13991
13992    NOTE: This can be called when reading in partial or full symbols.  */
13993
13994 static struct type *
13995 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
13996 {
13997   struct type *this_type;
13998
13999   this_type = get_die_type (die, cu);
14000   if (this_type)
14001     return this_type;
14002
14003   return read_type_die_1 (die, cu);
14004 }
14005
14006 /* Read the type in DIE, CU.
14007    Returns NULL for invalid types.  */
14008
14009 static struct type *
14010 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
14011 {
14012   struct type *this_type = NULL;
14013
14014   switch (die->tag)
14015     {
14016     case DW_TAG_class_type:
14017     case DW_TAG_interface_type:
14018     case DW_TAG_structure_type:
14019     case DW_TAG_union_type:
14020       this_type = read_structure_type (die, cu);
14021       break;
14022     case DW_TAG_enumeration_type:
14023       this_type = read_enumeration_type (die, cu);
14024       break;
14025     case DW_TAG_subprogram:
14026     case DW_TAG_subroutine_type:
14027     case DW_TAG_inlined_subroutine:
14028       this_type = read_subroutine_type (die, cu);
14029       break;
14030     case DW_TAG_array_type:
14031       this_type = read_array_type (die, cu);
14032       break;
14033     case DW_TAG_set_type:
14034       this_type = read_set_type (die, cu);
14035       break;
14036     case DW_TAG_pointer_type:
14037       this_type = read_tag_pointer_type (die, cu);
14038       break;
14039     case DW_TAG_ptr_to_member_type:
14040       this_type = read_tag_ptr_to_member_type (die, cu);
14041       break;
14042     case DW_TAG_reference_type:
14043       this_type = read_tag_reference_type (die, cu);
14044       break;
14045     case DW_TAG_const_type:
14046       this_type = read_tag_const_type (die, cu);
14047       break;
14048     case DW_TAG_volatile_type:
14049       this_type = read_tag_volatile_type (die, cu);
14050       break;
14051     case DW_TAG_string_type:
14052       this_type = read_tag_string_type (die, cu);
14053       break;
14054     case DW_TAG_typedef:
14055       this_type = read_typedef (die, cu);
14056       break;
14057     case DW_TAG_subrange_type:
14058       this_type = read_subrange_type (die, cu);
14059       break;
14060     case DW_TAG_base_type:
14061       this_type = read_base_type (die, cu);
14062       break;
14063     case DW_TAG_unspecified_type:
14064       this_type = read_unspecified_type (die, cu);
14065       break;
14066     case DW_TAG_namespace:
14067       this_type = read_namespace_type (die, cu);
14068       break;
14069     case DW_TAG_module:
14070       this_type = read_module_type (die, cu);
14071       break;
14072     default:
14073       complaint (&symfile_complaints,
14074                  _("unexpected tag in read_type_die: '%s'"),
14075                  dwarf_tag_name (die->tag));
14076       break;
14077     }
14078
14079   return this_type;
14080 }
14081
14082 /* See if we can figure out if the class lives in a namespace.  We do
14083    this by looking for a member function; its demangled name will
14084    contain namespace info, if there is any.
14085    Return the computed name or NULL.
14086    Space for the result is allocated on the objfile's obstack.
14087    This is the full-die version of guess_partial_die_structure_name.
14088    In this case we know DIE has no useful parent.  */
14089
14090 static char *
14091 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
14092 {
14093   struct die_info *spec_die;
14094   struct dwarf2_cu *spec_cu;
14095   struct die_info *child;
14096
14097   spec_cu = cu;
14098   spec_die = die_specification (die, &spec_cu);
14099   if (spec_die != NULL)
14100     {
14101       die = spec_die;
14102       cu = spec_cu;
14103     }
14104
14105   for (child = die->child;
14106        child != NULL;
14107        child = child->sibling)
14108     {
14109       if (child->tag == DW_TAG_subprogram)
14110         {
14111           struct attribute *attr;
14112
14113           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
14114           if (attr == NULL)
14115             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
14116           if (attr != NULL)
14117             {
14118               char *actual_name
14119                 = language_class_name_from_physname (cu->language_defn,
14120                                                      DW_STRING (attr));
14121               char *name = NULL;
14122
14123               if (actual_name != NULL)
14124                 {
14125                   char *die_name = dwarf2_name (die, cu);
14126
14127                   if (die_name != NULL
14128                       && strcmp (die_name, actual_name) != 0)
14129                     {
14130                       /* Strip off the class name from the full name.
14131                          We want the prefix.  */
14132                       int die_name_len = strlen (die_name);
14133                       int actual_name_len = strlen (actual_name);
14134
14135                       /* Test for '::' as a sanity check.  */
14136                       if (actual_name_len > die_name_len + 2
14137                           && actual_name[actual_name_len
14138                                          - die_name_len - 1] == ':')
14139                         name =
14140                           obsavestring (actual_name,
14141                                         actual_name_len - die_name_len - 2,
14142                                         &cu->objfile->objfile_obstack);
14143                     }
14144                 }
14145               xfree (actual_name);
14146               return name;
14147             }
14148         }
14149     }
14150
14151   return NULL;
14152 }
14153
14154 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
14155    prefix part in such case.  See
14156    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14157
14158 static char *
14159 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
14160 {
14161   struct attribute *attr;
14162   char *base;
14163
14164   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
14165       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
14166     return NULL;
14167
14168   attr = dwarf2_attr (die, DW_AT_name, cu);
14169   if (attr != NULL && DW_STRING (attr) != NULL)
14170     return NULL;
14171
14172   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
14173   if (attr == NULL)
14174     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
14175   if (attr == NULL || DW_STRING (attr) == NULL)
14176     return NULL;
14177
14178   /* dwarf2_name had to be already called.  */
14179   gdb_assert (DW_STRING_IS_CANONICAL (attr));
14180
14181   /* Strip the base name, keep any leading namespaces/classes.  */
14182   base = strrchr (DW_STRING (attr), ':');
14183   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
14184     return "";
14185
14186   return obsavestring (DW_STRING (attr), &base[-1] - DW_STRING (attr),
14187                        &cu->objfile->objfile_obstack);
14188 }
14189
14190 /* Return the name of the namespace/class that DIE is defined within,
14191    or "" if we can't tell.  The caller should not xfree the result.
14192
14193    For example, if we're within the method foo() in the following
14194    code:
14195
14196    namespace N {
14197      class C {
14198        void foo () {
14199        }
14200      };
14201    }
14202
14203    then determine_prefix on foo's die will return "N::C".  */
14204
14205 static const char *
14206 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
14207 {
14208   struct die_info *parent, *spec_die;
14209   struct dwarf2_cu *spec_cu;
14210   struct type *parent_type;
14211   char *retval;
14212
14213   if (cu->language != language_cplus && cu->language != language_java
14214       && cu->language != language_fortran)
14215     return "";
14216
14217   retval = anonymous_struct_prefix (die, cu);
14218   if (retval)
14219     return retval;
14220
14221   /* We have to be careful in the presence of DW_AT_specification.
14222      For example, with GCC 3.4, given the code
14223
14224      namespace N {
14225        void foo() {
14226          // Definition of N::foo.
14227        }
14228      }
14229
14230      then we'll have a tree of DIEs like this:
14231
14232      1: DW_TAG_compile_unit
14233        2: DW_TAG_namespace        // N
14234          3: DW_TAG_subprogram     // declaration of N::foo
14235        4: DW_TAG_subprogram       // definition of N::foo
14236             DW_AT_specification   // refers to die #3
14237
14238      Thus, when processing die #4, we have to pretend that we're in
14239      the context of its DW_AT_specification, namely the contex of die
14240      #3.  */
14241   spec_cu = cu;
14242   spec_die = die_specification (die, &spec_cu);
14243   if (spec_die == NULL)
14244     parent = die->parent;
14245   else
14246     {
14247       parent = spec_die->parent;
14248       cu = spec_cu;
14249     }
14250
14251   if (parent == NULL)
14252     return "";
14253   else if (parent->building_fullname)
14254     {
14255       const char *name;
14256       const char *parent_name;
14257
14258       /* It has been seen on RealView 2.2 built binaries,
14259          DW_TAG_template_type_param types actually _defined_ as
14260          children of the parent class:
14261
14262          enum E {};
14263          template class <class Enum> Class{};
14264          Class<enum E> class_e;
14265
14266          1: DW_TAG_class_type (Class)
14267            2: DW_TAG_enumeration_type (E)
14268              3: DW_TAG_enumerator (enum1:0)
14269              3: DW_TAG_enumerator (enum2:1)
14270              ...
14271            2: DW_TAG_template_type_param
14272               DW_AT_type  DW_FORM_ref_udata (E)
14273
14274          Besides being broken debug info, it can put GDB into an
14275          infinite loop.  Consider:
14276
14277          When we're building the full name for Class<E>, we'll start
14278          at Class, and go look over its template type parameters,
14279          finding E.  We'll then try to build the full name of E, and
14280          reach here.  We're now trying to build the full name of E,
14281          and look over the parent DIE for containing scope.  In the
14282          broken case, if we followed the parent DIE of E, we'd again
14283          find Class, and once again go look at its template type
14284          arguments, etc., etc.  Simply don't consider such parent die
14285          as source-level parent of this die (it can't be, the language
14286          doesn't allow it), and break the loop here.  */
14287       name = dwarf2_name (die, cu);
14288       parent_name = dwarf2_name (parent, cu);
14289       complaint (&symfile_complaints,
14290                  _("template param type '%s' defined within parent '%s'"),
14291                  name ? name : "<unknown>",
14292                  parent_name ? parent_name : "<unknown>");
14293       return "";
14294     }
14295   else
14296     switch (parent->tag)
14297       {
14298       case DW_TAG_namespace:
14299         parent_type = read_type_die (parent, cu);
14300         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
14301            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
14302            Work around this problem here.  */
14303         if (cu->language == language_cplus
14304             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
14305           return "";
14306         /* We give a name to even anonymous namespaces.  */
14307         return TYPE_TAG_NAME (parent_type);
14308       case DW_TAG_class_type:
14309       case DW_TAG_interface_type:
14310       case DW_TAG_structure_type:
14311       case DW_TAG_union_type:
14312       case DW_TAG_module:
14313         parent_type = read_type_die (parent, cu);
14314         if (TYPE_TAG_NAME (parent_type) != NULL)
14315           return TYPE_TAG_NAME (parent_type);
14316         else
14317           /* An anonymous structure is only allowed non-static data
14318              members; no typedefs, no member functions, et cetera.
14319              So it does not need a prefix.  */
14320           return "";
14321       case DW_TAG_compile_unit:
14322       case DW_TAG_partial_unit:
14323         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
14324         if (cu->language == language_cplus
14325             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14326             && die->child != NULL
14327             && (die->tag == DW_TAG_class_type
14328                 || die->tag == DW_TAG_structure_type
14329                 || die->tag == DW_TAG_union_type))
14330           {
14331             char *name = guess_full_die_structure_name (die, cu);
14332             if (name != NULL)
14333               return name;
14334           }
14335         return "";
14336       default:
14337         return determine_prefix (parent, cu);
14338       }
14339 }
14340
14341 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
14342    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
14343    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
14344    an obconcat, otherwise allocate storage for the result.  The CU argument is
14345    used to determine the language and hence, the appropriate separator.  */
14346
14347 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
14348
14349 static char *
14350 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
14351                  int physname, struct dwarf2_cu *cu)
14352 {
14353   const char *lead = "";
14354   const char *sep;
14355
14356   if (suffix == NULL || suffix[0] == '\0'
14357       || prefix == NULL || prefix[0] == '\0')
14358     sep = "";
14359   else if (cu->language == language_java)
14360     sep = ".";
14361   else if (cu->language == language_fortran && physname)
14362     {
14363       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
14364          DW_AT_MIPS_linkage_name is preferred and used instead.  */
14365
14366       lead = "__";
14367       sep = "_MOD_";
14368     }
14369   else
14370     sep = "::";
14371
14372   if (prefix == NULL)
14373     prefix = "";
14374   if (suffix == NULL)
14375     suffix = "";
14376
14377   if (obs == NULL)
14378     {
14379       char *retval
14380         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
14381
14382       strcpy (retval, lead);
14383       strcat (retval, prefix);
14384       strcat (retval, sep);
14385       strcat (retval, suffix);
14386       return retval;
14387     }
14388   else
14389     {
14390       /* We have an obstack.  */
14391       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
14392     }
14393 }
14394
14395 /* Return sibling of die, NULL if no sibling.  */
14396
14397 static struct die_info *
14398 sibling_die (struct die_info *die)
14399 {
14400   return die->sibling;
14401 }
14402
14403 /* Get name of a die, return NULL if not found.  */
14404
14405 static char *
14406 dwarf2_canonicalize_name (char *name, struct dwarf2_cu *cu,
14407                           struct obstack *obstack)
14408 {
14409   if (name && cu->language == language_cplus)
14410     {
14411       char *canon_name = cp_canonicalize_string (name);
14412
14413       if (canon_name != NULL)
14414         {
14415           if (strcmp (canon_name, name) != 0)
14416             name = obsavestring (canon_name, strlen (canon_name),
14417                                  obstack);
14418           xfree (canon_name);
14419         }
14420     }
14421
14422   return name;
14423 }
14424
14425 /* Get name of a die, return NULL if not found.  */
14426
14427 static char *
14428 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
14429 {
14430   struct attribute *attr;
14431
14432   attr = dwarf2_attr (die, DW_AT_name, cu);
14433   if ((!attr || !DW_STRING (attr))
14434       && die->tag != DW_TAG_class_type
14435       && die->tag != DW_TAG_interface_type
14436       && die->tag != DW_TAG_structure_type
14437       && die->tag != DW_TAG_union_type)
14438     return NULL;
14439
14440   switch (die->tag)
14441     {
14442     case DW_TAG_compile_unit:
14443     case DW_TAG_partial_unit:
14444       /* Compilation units have a DW_AT_name that is a filename, not
14445          a source language identifier.  */
14446     case DW_TAG_enumeration_type:
14447     case DW_TAG_enumerator:
14448       /* These tags always have simple identifiers already; no need
14449          to canonicalize them.  */
14450       return DW_STRING (attr);
14451
14452     case DW_TAG_subprogram:
14453       /* Java constructors will all be named "<init>", so return
14454          the class name when we see this special case.  */
14455       if (cu->language == language_java
14456           && DW_STRING (attr) != NULL
14457           && strcmp (DW_STRING (attr), "<init>") == 0)
14458         {
14459           struct dwarf2_cu *spec_cu = cu;
14460           struct die_info *spec_die;
14461
14462           /* GCJ will output '<init>' for Java constructor names.
14463              For this special case, return the name of the parent class.  */
14464
14465           /* GCJ may output suprogram DIEs with AT_specification set.
14466              If so, use the name of the specified DIE.  */
14467           spec_die = die_specification (die, &spec_cu);
14468           if (spec_die != NULL)
14469             return dwarf2_name (spec_die, spec_cu);
14470
14471           do
14472             {
14473               die = die->parent;
14474               if (die->tag == DW_TAG_class_type)
14475                 return dwarf2_name (die, cu);
14476             }
14477           while (die->tag != DW_TAG_compile_unit
14478                  && die->tag != DW_TAG_partial_unit);
14479         }
14480       break;
14481
14482     case DW_TAG_class_type:
14483     case DW_TAG_interface_type:
14484     case DW_TAG_structure_type:
14485     case DW_TAG_union_type:
14486       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
14487          structures or unions.  These were of the form "._%d" in GCC 4.1,
14488          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
14489          and GCC 4.4.  We work around this problem by ignoring these.  */
14490       if (attr && DW_STRING (attr)
14491           && (strncmp (DW_STRING (attr), "._", 2) == 0
14492               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
14493         return NULL;
14494
14495       /* GCC might emit a nameless typedef that has a linkage name.  See
14496          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14497       if (!attr || DW_STRING (attr) == NULL)
14498         {
14499           char *demangled = NULL;
14500
14501           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
14502           if (attr == NULL)
14503             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
14504
14505           if (attr == NULL || DW_STRING (attr) == NULL)
14506             return NULL;
14507
14508           /* Avoid demangling DW_STRING (attr) the second time on a second
14509              call for the same DIE.  */
14510           if (!DW_STRING_IS_CANONICAL (attr))
14511             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
14512
14513           if (demangled)
14514             {
14515               char *base;
14516
14517               /* FIXME: we already did this for the partial symbol... */
14518               DW_STRING (attr) = obsavestring (demangled, strlen (demangled),
14519                                                &cu->objfile->objfile_obstack);
14520               DW_STRING_IS_CANONICAL (attr) = 1;
14521               xfree (demangled);
14522
14523               /* Strip any leading namespaces/classes, keep only the base name.
14524                  DW_AT_name for named DIEs does not contain the prefixes.  */
14525               base = strrchr (DW_STRING (attr), ':');
14526               if (base && base > DW_STRING (attr) && base[-1] == ':')
14527                 return &base[1];
14528               else
14529                 return DW_STRING (attr);
14530             }
14531         }
14532       break;
14533
14534     default:
14535       break;
14536     }
14537
14538   if (!DW_STRING_IS_CANONICAL (attr))
14539     {
14540       DW_STRING (attr)
14541         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
14542                                     &cu->objfile->objfile_obstack);
14543       DW_STRING_IS_CANONICAL (attr) = 1;
14544     }
14545   return DW_STRING (attr);
14546 }
14547
14548 /* Return the die that this die in an extension of, or NULL if there
14549    is none.  *EXT_CU is the CU containing DIE on input, and the CU
14550    containing the return value on output.  */
14551
14552 static struct die_info *
14553 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
14554 {
14555   struct attribute *attr;
14556
14557   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
14558   if (attr == NULL)
14559     return NULL;
14560
14561   return follow_die_ref (die, attr, ext_cu);
14562 }
14563
14564 /* Convert a DIE tag into its string name.  */
14565
14566 static const char *
14567 dwarf_tag_name (unsigned tag)
14568 {
14569   const char *name = get_DW_TAG_name (tag);
14570
14571   if (name == NULL)
14572     return "DW_TAG_<unknown>";
14573
14574   return name;
14575 }
14576
14577 /* Convert a DWARF attribute code into its string name.  */
14578
14579 static const char *
14580 dwarf_attr_name (unsigned attr)
14581 {
14582   const char *name;
14583
14584 #ifdef MIPS /* collides with DW_AT_HP_block_index */
14585   if (attr == DW_AT_MIPS_fde)
14586     return "DW_AT_MIPS_fde";
14587 #else
14588   if (attr == DW_AT_HP_block_index)
14589     return "DW_AT_HP_block_index";
14590 #endif
14591
14592   name = get_DW_AT_name (attr);
14593
14594   if (name == NULL)
14595     return "DW_AT_<unknown>";
14596
14597   return name;
14598 }
14599
14600 /* Convert a DWARF value form code into its string name.  */
14601
14602 static const char *
14603 dwarf_form_name (unsigned form)
14604 {
14605   const char *name = get_DW_FORM_name (form);
14606
14607   if (name == NULL)
14608     return "DW_FORM_<unknown>";
14609
14610   return name;
14611 }
14612
14613 static char *
14614 dwarf_bool_name (unsigned mybool)
14615 {
14616   if (mybool)
14617     return "TRUE";
14618   else
14619     return "FALSE";
14620 }
14621
14622 /* Convert a DWARF type code into its string name.  */
14623
14624 static const char *
14625 dwarf_type_encoding_name (unsigned enc)
14626 {
14627   const char *name = get_DW_ATE_name (enc);
14628
14629   if (name == NULL)
14630     return "DW_ATE_<unknown>";
14631
14632   return name;
14633 }
14634
14635 static void
14636 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
14637 {
14638   unsigned int i;
14639
14640   print_spaces (indent, f);
14641   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
14642            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
14643
14644   if (die->parent != NULL)
14645     {
14646       print_spaces (indent, f);
14647       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
14648                           die->parent->offset.sect_off);
14649     }
14650
14651   print_spaces (indent, f);
14652   fprintf_unfiltered (f, "  has children: %s\n",
14653            dwarf_bool_name (die->child != NULL));
14654
14655   print_spaces (indent, f);
14656   fprintf_unfiltered (f, "  attributes:\n");
14657
14658   for (i = 0; i < die->num_attrs; ++i)
14659     {
14660       print_spaces (indent, f);
14661       fprintf_unfiltered (f, "    %s (%s) ",
14662                dwarf_attr_name (die->attrs[i].name),
14663                dwarf_form_name (die->attrs[i].form));
14664
14665       switch (die->attrs[i].form)
14666         {
14667         case DW_FORM_addr:
14668         case DW_FORM_GNU_addr_index:
14669           fprintf_unfiltered (f, "address: ");
14670           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
14671           break;
14672         case DW_FORM_block2:
14673         case DW_FORM_block4:
14674         case DW_FORM_block:
14675         case DW_FORM_block1:
14676           fprintf_unfiltered (f, "block: size %d",
14677                               DW_BLOCK (&die->attrs[i])->size);
14678           break;
14679         case DW_FORM_exprloc:
14680           fprintf_unfiltered (f, "expression: size %u",
14681                               DW_BLOCK (&die->attrs[i])->size);
14682           break;
14683         case DW_FORM_ref_addr:
14684           fprintf_unfiltered (f, "ref address: ");
14685           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
14686           break;
14687         case DW_FORM_ref1:
14688         case DW_FORM_ref2:
14689         case DW_FORM_ref4:
14690         case DW_FORM_ref8:
14691         case DW_FORM_ref_udata:
14692           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
14693                               (long) (DW_UNSND (&die->attrs[i])));
14694           break;
14695         case DW_FORM_data1:
14696         case DW_FORM_data2:
14697         case DW_FORM_data4:
14698         case DW_FORM_data8:
14699         case DW_FORM_udata:
14700         case DW_FORM_sdata:
14701           fprintf_unfiltered (f, "constant: %s",
14702                               pulongest (DW_UNSND (&die->attrs[i])));
14703           break;
14704         case DW_FORM_sec_offset:
14705           fprintf_unfiltered (f, "section offset: %s",
14706                               pulongest (DW_UNSND (&die->attrs[i])));
14707           break;
14708         case DW_FORM_ref_sig8:
14709           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
14710             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
14711                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
14712           else
14713             fprintf_unfiltered (f, "signatured type, offset: unknown");
14714           break;
14715         case DW_FORM_string:
14716         case DW_FORM_strp:
14717         case DW_FORM_GNU_str_index:
14718           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
14719                    DW_STRING (&die->attrs[i])
14720                    ? DW_STRING (&die->attrs[i]) : "",
14721                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
14722           break;
14723         case DW_FORM_flag:
14724           if (DW_UNSND (&die->attrs[i]))
14725             fprintf_unfiltered (f, "flag: TRUE");
14726           else
14727             fprintf_unfiltered (f, "flag: FALSE");
14728           break;
14729         case DW_FORM_flag_present:
14730           fprintf_unfiltered (f, "flag: TRUE");
14731           break;
14732         case DW_FORM_indirect:
14733           /* The reader will have reduced the indirect form to
14734              the "base form" so this form should not occur.  */
14735           fprintf_unfiltered (f, 
14736                               "unexpected attribute form: DW_FORM_indirect");
14737           break;
14738         default:
14739           fprintf_unfiltered (f, "unsupported attribute form: %d.",
14740                    die->attrs[i].form);
14741           break;
14742         }
14743       fprintf_unfiltered (f, "\n");
14744     }
14745 }
14746
14747 static void
14748 dump_die_for_error (struct die_info *die)
14749 {
14750   dump_die_shallow (gdb_stderr, 0, die);
14751 }
14752
14753 static void
14754 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
14755 {
14756   int indent = level * 4;
14757
14758   gdb_assert (die != NULL);
14759
14760   if (level >= max_level)
14761     return;
14762
14763   dump_die_shallow (f, indent, die);
14764
14765   if (die->child != NULL)
14766     {
14767       print_spaces (indent, f);
14768       fprintf_unfiltered (f, "  Children:");
14769       if (level + 1 < max_level)
14770         {
14771           fprintf_unfiltered (f, "\n");
14772           dump_die_1 (f, level + 1, max_level, die->child);
14773         }
14774       else
14775         {
14776           fprintf_unfiltered (f,
14777                               " [not printed, max nesting level reached]\n");
14778         }
14779     }
14780
14781   if (die->sibling != NULL && level > 0)
14782     {
14783       dump_die_1 (f, level, max_level, die->sibling);
14784     }
14785 }
14786
14787 /* This is called from the pdie macro in gdbinit.in.
14788    It's not static so gcc will keep a copy callable from gdb.  */
14789
14790 void
14791 dump_die (struct die_info *die, int max_level)
14792 {
14793   dump_die_1 (gdb_stdlog, 0, max_level, die);
14794 }
14795
14796 static void
14797 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
14798 {
14799   void **slot;
14800
14801   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
14802                                    INSERT);
14803
14804   *slot = die;
14805 }
14806
14807 /* DW_ADDR is always stored already as sect_offset; despite for the forms
14808    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
14809
14810 static int
14811 is_ref_attr (struct attribute *attr)
14812 {
14813   switch (attr->form)
14814     {
14815     case DW_FORM_ref_addr:
14816     case DW_FORM_ref1:
14817     case DW_FORM_ref2:
14818     case DW_FORM_ref4:
14819     case DW_FORM_ref8:
14820     case DW_FORM_ref_udata:
14821       return 1;
14822     default:
14823       return 0;
14824     }
14825 }
14826
14827 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
14828    required kind.  */
14829
14830 static sect_offset
14831 dwarf2_get_ref_die_offset (struct attribute *attr)
14832 {
14833   sect_offset retval = { DW_UNSND (attr) };
14834
14835   if (is_ref_attr (attr))
14836     return retval;
14837
14838   retval.sect_off = 0;
14839   complaint (&symfile_complaints,
14840              _("unsupported die ref attribute form: '%s'"),
14841              dwarf_form_name (attr->form));
14842   return retval;
14843 }
14844
14845 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
14846  * the value held by the attribute is not constant.  */
14847
14848 static LONGEST
14849 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
14850 {
14851   if (attr->form == DW_FORM_sdata)
14852     return DW_SND (attr);
14853   else if (attr->form == DW_FORM_udata
14854            || attr->form == DW_FORM_data1
14855            || attr->form == DW_FORM_data2
14856            || attr->form == DW_FORM_data4
14857            || attr->form == DW_FORM_data8)
14858     return DW_UNSND (attr);
14859   else
14860     {
14861       complaint (&symfile_complaints,
14862                  _("Attribute value is not a constant (%s)"),
14863                  dwarf_form_name (attr->form));
14864       return default_value;
14865     }
14866 }
14867
14868 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
14869    unit and add it to our queue.
14870    The result is non-zero if PER_CU was queued, otherwise the result is zero
14871    meaning either PER_CU is already queued or it is already loaded.  */
14872
14873 static int
14874 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
14875                        struct dwarf2_per_cu_data *per_cu,
14876                        enum language pretend_language)
14877 {
14878   /* We may arrive here during partial symbol reading, if we need full
14879      DIEs to process an unusual case (e.g. template arguments).  Do
14880      not queue PER_CU, just tell our caller to load its DIEs.  */
14881   if (dwarf2_per_objfile->reading_partial_symbols)
14882     {
14883       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
14884         return 1;
14885       return 0;
14886     }
14887
14888   /* Mark the dependence relation so that we don't flush PER_CU
14889      too early.  */
14890   dwarf2_add_dependence (this_cu, per_cu);
14891
14892   /* If it's already on the queue, we have nothing to do.  */
14893   if (per_cu->queued)
14894     return 0;
14895
14896   /* If the compilation unit is already loaded, just mark it as
14897      used.  */
14898   if (per_cu->cu != NULL)
14899     {
14900       per_cu->cu->last_used = 0;
14901       return 0;
14902     }
14903
14904   /* Add it to the queue.  */
14905   queue_comp_unit (per_cu, pretend_language);
14906
14907   return 1;
14908 }
14909
14910 /* Follow reference or signature attribute ATTR of SRC_DIE.
14911    On entry *REF_CU is the CU of SRC_DIE.
14912    On exit *REF_CU is the CU of the result.  */
14913
14914 static struct die_info *
14915 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
14916                        struct dwarf2_cu **ref_cu)
14917 {
14918   struct die_info *die;
14919
14920   if (is_ref_attr (attr))
14921     die = follow_die_ref (src_die, attr, ref_cu);
14922   else if (attr->form == DW_FORM_ref_sig8)
14923     die = follow_die_sig (src_die, attr, ref_cu);
14924   else
14925     {
14926       dump_die_for_error (src_die);
14927       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
14928              (*ref_cu)->objfile->name);
14929     }
14930
14931   return die;
14932 }
14933
14934 /* Follow reference OFFSET.
14935    On entry *REF_CU is the CU of the source die referencing OFFSET.
14936    On exit *REF_CU is the CU of the result.
14937    Returns NULL if OFFSET is invalid.  */
14938
14939 static struct die_info *
14940 follow_die_offset (sect_offset offset, struct dwarf2_cu **ref_cu)
14941 {
14942   struct die_info temp_die;
14943   struct dwarf2_cu *target_cu, *cu = *ref_cu;
14944
14945   gdb_assert (cu->per_cu != NULL);
14946
14947   target_cu = cu;
14948
14949   if (cu->per_cu->is_debug_types)
14950     {
14951       /* .debug_types CUs cannot reference anything outside their CU.
14952          If they need to, they have to reference a signatured type via
14953          DW_FORM_ref_sig8.  */
14954       if (! offset_in_cu_p (&cu->header, offset))
14955         return NULL;
14956     }
14957   else if (! offset_in_cu_p (&cu->header, offset))
14958     {
14959       struct dwarf2_per_cu_data *per_cu;
14960
14961       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
14962
14963       /* If necessary, add it to the queue and load its DIEs.  */
14964       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
14965         load_full_comp_unit (per_cu, cu->language);
14966
14967       target_cu = per_cu->cu;
14968     }
14969   else if (cu->dies == NULL)
14970     {
14971       /* We're loading full DIEs during partial symbol reading.  */
14972       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
14973       load_full_comp_unit (cu->per_cu, language_minimal);
14974     }
14975
14976   *ref_cu = target_cu;
14977   temp_die.offset = offset;
14978   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
14979 }
14980
14981 /* Follow reference attribute ATTR of SRC_DIE.
14982    On entry *REF_CU is the CU of SRC_DIE.
14983    On exit *REF_CU is the CU of the result.  */
14984
14985 static struct die_info *
14986 follow_die_ref (struct die_info *src_die, struct attribute *attr,
14987                 struct dwarf2_cu **ref_cu)
14988 {
14989   sect_offset offset = dwarf2_get_ref_die_offset (attr);
14990   struct dwarf2_cu *cu = *ref_cu;
14991   struct die_info *die;
14992
14993   die = follow_die_offset (offset, ref_cu);
14994   if (!die)
14995     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
14996            "at 0x%x [in module %s]"),
14997            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
14998
14999   return die;
15000 }
15001
15002 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
15003    Returned value is intended for DW_OP_call*.  Returned
15004    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
15005
15006 struct dwarf2_locexpr_baton
15007 dwarf2_fetch_die_location_block (cu_offset offset_in_cu,
15008                                  struct dwarf2_per_cu_data *per_cu,
15009                                  CORE_ADDR (*get_frame_pc) (void *baton),
15010                                  void *baton)
15011 {
15012   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
15013   struct dwarf2_cu *cu;
15014   struct die_info *die;
15015   struct attribute *attr;
15016   struct dwarf2_locexpr_baton retval;
15017
15018   dw2_setup (per_cu->objfile);
15019
15020   if (per_cu->cu == NULL)
15021     load_cu (per_cu);
15022   cu = per_cu->cu;
15023
15024   die = follow_die_offset (offset, &cu);
15025   if (!die)
15026     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
15027            offset.sect_off, per_cu->objfile->name);
15028
15029   attr = dwarf2_attr (die, DW_AT_location, cu);
15030   if (!attr)
15031     {
15032       /* DWARF: "If there is no such attribute, then there is no effect.".
15033          DATA is ignored if SIZE is 0.  */
15034
15035       retval.data = NULL;
15036       retval.size = 0;
15037     }
15038   else if (attr_form_is_section_offset (attr))
15039     {
15040       struct dwarf2_loclist_baton loclist_baton;
15041       CORE_ADDR pc = (*get_frame_pc) (baton);
15042       size_t size;
15043
15044       fill_in_loclist_baton (cu, &loclist_baton, attr);
15045
15046       retval.data = dwarf2_find_location_expression (&loclist_baton,
15047                                                      &size, pc);
15048       retval.size = size;
15049     }
15050   else
15051     {
15052       if (!attr_form_is_block (attr))
15053         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
15054                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
15055                offset.sect_off, per_cu->objfile->name);
15056
15057       retval.data = DW_BLOCK (attr)->data;
15058       retval.size = DW_BLOCK (attr)->size;
15059     }
15060   retval.per_cu = cu->per_cu;
15061
15062   age_cached_comp_units ();
15063
15064   return retval;
15065 }
15066
15067 /* Return the type of the DIE at DIE_OFFSET in the CU named by
15068    PER_CU.  */
15069
15070 struct type *
15071 dwarf2_get_die_type (cu_offset die_offset,
15072                      struct dwarf2_per_cu_data *per_cu)
15073 {
15074   sect_offset die_offset_sect;
15075
15076   dw2_setup (per_cu->objfile);
15077
15078   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
15079   return get_die_type_at_offset (die_offset_sect, per_cu);
15080 }
15081
15082 /* Follow the signature attribute ATTR in SRC_DIE.
15083    On entry *REF_CU is the CU of SRC_DIE.
15084    On exit *REF_CU is the CU of the result.  */
15085
15086 static struct die_info *
15087 follow_die_sig (struct die_info *src_die, struct attribute *attr,
15088                 struct dwarf2_cu **ref_cu)
15089 {
15090   struct objfile *objfile = (*ref_cu)->objfile;
15091   struct die_info temp_die;
15092   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
15093   struct dwarf2_cu *sig_cu;
15094   struct die_info *die;
15095
15096   /* sig_type will be NULL if the signatured type is missing from
15097      the debug info.  */
15098   if (sig_type == NULL)
15099     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
15100              "at 0x%x [in module %s]"),
15101            src_die->offset.sect_off, objfile->name);
15102
15103   /* If necessary, add it to the queue and load its DIEs.  */
15104
15105   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
15106     read_signatured_type (sig_type);
15107
15108   gdb_assert (sig_type->per_cu.cu != NULL);
15109
15110   sig_cu = sig_type->per_cu.cu;
15111   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
15112   temp_die.offset = sig_type->type_offset_in_section;
15113   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
15114                              temp_die.offset.sect_off);
15115   if (die)
15116     {
15117       *ref_cu = sig_cu;
15118       return die;
15119     }
15120
15121   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
15122          "from DIE at 0x%x [in module %s]"),
15123          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
15124 }
15125
15126 /* Given an offset of a signatured type, return its signatured_type.  */
15127
15128 static struct signatured_type *
15129 lookup_signatured_type_at_offset (struct objfile *objfile,
15130                                   struct dwarf2_section_info *section,
15131                                   sect_offset offset)
15132 {
15133   gdb_byte *info_ptr = section->buffer + offset.sect_off;
15134   unsigned int length, initial_length_size;
15135   unsigned int sig_offset;
15136   struct signatured_type find_entry, *sig_type;
15137
15138   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
15139   sig_offset = (initial_length_size
15140                 + 2 /*version*/
15141                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
15142                 + 1 /*address_size*/);
15143   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
15144   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
15145
15146   /* This is only used to lookup previously recorded types.
15147      If we didn't find it, it's our bug.  */
15148   gdb_assert (sig_type != NULL);
15149   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
15150
15151   return sig_type;
15152 }
15153
15154 /* Load the DIEs associated with type unit PER_CU into memory.  */
15155
15156 static void
15157 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
15158 {
15159   struct objfile *objfile = per_cu->objfile;
15160   struct dwarf2_section_info *sect = per_cu->info_or_types_section;
15161   sect_offset offset = per_cu->offset;
15162   struct signatured_type *sig_type;
15163
15164   dwarf2_read_section (objfile, sect);
15165
15166   /* We have the section offset, but we need the signature to do the
15167      hash table lookup.  */
15168   /* FIXME: This is sorta unnecessary, read_signatured_type only uses
15169      the signature to assert we found the right one.
15170      Ok, but it's a lot of work.  We should simplify things so any needed
15171      assert doesn't require all this clumsiness.  */
15172   sig_type = lookup_signatured_type_at_offset (objfile, sect, offset);
15173
15174   gdb_assert (&sig_type->per_cu == per_cu);
15175   gdb_assert (sig_type->per_cu.cu == NULL);
15176
15177   read_signatured_type (sig_type);
15178
15179   gdb_assert (sig_type->per_cu.cu != NULL);
15180 }
15181
15182 /* die_reader_func for read_signatured_type.
15183    This is identical to load_full_comp_unit_reader,
15184    but is kept separate for now.  */
15185
15186 static void
15187 read_signatured_type_reader (const struct die_reader_specs *reader,
15188                              gdb_byte *info_ptr,
15189                              struct die_info *comp_unit_die,
15190                              int has_children,
15191                              void *data)
15192 {
15193   struct dwarf2_cu *cu = reader->cu;
15194
15195   gdb_assert (cu->die_hash == NULL);
15196   cu->die_hash =
15197     htab_create_alloc_ex (cu->header.length / 12,
15198                           die_hash,
15199                           die_eq,
15200                           NULL,
15201                           &cu->comp_unit_obstack,
15202                           hashtab_obstack_allocate,
15203                           dummy_obstack_deallocate);
15204
15205   if (has_children)
15206     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
15207                                                   &info_ptr, comp_unit_die);
15208   cu->dies = comp_unit_die;
15209   /* comp_unit_die is not stored in die_hash, no need.  */
15210
15211   /* We try not to read any attributes in this function, because not
15212      all CUs needed for references have been loaded yet, and symbol
15213      table processing isn't initialized.  But we have to set the CU language,
15214      or we won't be able to build types correctly.
15215      Similarly, if we do not read the producer, we can not apply
15216      producer-specific interpretation.  */
15217   prepare_one_comp_unit (cu, cu->dies, language_minimal);
15218 }
15219
15220 /* Read in a signatured type and build its CU and DIEs.
15221    If the type is a stub for the real type in a DWO file,
15222    read in the real type from the DWO file as well.  */
15223
15224 static void
15225 read_signatured_type (struct signatured_type *sig_type)
15226 {
15227   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
15228
15229   gdb_assert (per_cu->is_debug_types);
15230   gdb_assert (per_cu->cu == NULL);
15231
15232   init_cutu_and_read_dies (per_cu, 0, 1, read_signatured_type_reader, NULL);
15233 }
15234
15235 /* Decode simple location descriptions.
15236    Given a pointer to a dwarf block that defines a location, compute
15237    the location and return the value.
15238
15239    NOTE drow/2003-11-18: This function is called in two situations
15240    now: for the address of static or global variables (partial symbols
15241    only) and for offsets into structures which are expected to be
15242    (more or less) constant.  The partial symbol case should go away,
15243    and only the constant case should remain.  That will let this
15244    function complain more accurately.  A few special modes are allowed
15245    without complaint for global variables (for instance, global
15246    register values and thread-local values).
15247
15248    A location description containing no operations indicates that the
15249    object is optimized out.  The return value is 0 for that case.
15250    FIXME drow/2003-11-16: No callers check for this case any more; soon all
15251    callers will only want a very basic result and this can become a
15252    complaint.
15253
15254    Note that stack[0] is unused except as a default error return.  */
15255
15256 static CORE_ADDR
15257 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
15258 {
15259   struct objfile *objfile = cu->objfile;
15260   int i;
15261   int size = blk->size;
15262   gdb_byte *data = blk->data;
15263   CORE_ADDR stack[64];
15264   int stacki;
15265   unsigned int bytes_read, unsnd;
15266   gdb_byte op;
15267
15268   i = 0;
15269   stacki = 0;
15270   stack[stacki] = 0;
15271   stack[++stacki] = 0;
15272
15273   while (i < size)
15274     {
15275       op = data[i++];
15276       switch (op)
15277         {
15278         case DW_OP_lit0:
15279         case DW_OP_lit1:
15280         case DW_OP_lit2:
15281         case DW_OP_lit3:
15282         case DW_OP_lit4:
15283         case DW_OP_lit5:
15284         case DW_OP_lit6:
15285         case DW_OP_lit7:
15286         case DW_OP_lit8:
15287         case DW_OP_lit9:
15288         case DW_OP_lit10:
15289         case DW_OP_lit11:
15290         case DW_OP_lit12:
15291         case DW_OP_lit13:
15292         case DW_OP_lit14:
15293         case DW_OP_lit15:
15294         case DW_OP_lit16:
15295         case DW_OP_lit17:
15296         case DW_OP_lit18:
15297         case DW_OP_lit19:
15298         case DW_OP_lit20:
15299         case DW_OP_lit21:
15300         case DW_OP_lit22:
15301         case DW_OP_lit23:
15302         case DW_OP_lit24:
15303         case DW_OP_lit25:
15304         case DW_OP_lit26:
15305         case DW_OP_lit27:
15306         case DW_OP_lit28:
15307         case DW_OP_lit29:
15308         case DW_OP_lit30:
15309         case DW_OP_lit31:
15310           stack[++stacki] = op - DW_OP_lit0;
15311           break;
15312
15313         case DW_OP_reg0:
15314         case DW_OP_reg1:
15315         case DW_OP_reg2:
15316         case DW_OP_reg3:
15317         case DW_OP_reg4:
15318         case DW_OP_reg5:
15319         case DW_OP_reg6:
15320         case DW_OP_reg7:
15321         case DW_OP_reg8:
15322         case DW_OP_reg9:
15323         case DW_OP_reg10:
15324         case DW_OP_reg11:
15325         case DW_OP_reg12:
15326         case DW_OP_reg13:
15327         case DW_OP_reg14:
15328         case DW_OP_reg15:
15329         case DW_OP_reg16:
15330         case DW_OP_reg17:
15331         case DW_OP_reg18:
15332         case DW_OP_reg19:
15333         case DW_OP_reg20:
15334         case DW_OP_reg21:
15335         case DW_OP_reg22:
15336         case DW_OP_reg23:
15337         case DW_OP_reg24:
15338         case DW_OP_reg25:
15339         case DW_OP_reg26:
15340         case DW_OP_reg27:
15341         case DW_OP_reg28:
15342         case DW_OP_reg29:
15343         case DW_OP_reg30:
15344         case DW_OP_reg31:
15345           stack[++stacki] = op - DW_OP_reg0;
15346           if (i < size)
15347             dwarf2_complex_location_expr_complaint ();
15348           break;
15349
15350         case DW_OP_regx:
15351           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
15352           i += bytes_read;
15353           stack[++stacki] = unsnd;
15354           if (i < size)
15355             dwarf2_complex_location_expr_complaint ();
15356           break;
15357
15358         case DW_OP_addr:
15359           stack[++stacki] = read_address (objfile->obfd, &data[i],
15360                                           cu, &bytes_read);
15361           i += bytes_read;
15362           break;
15363
15364         case DW_OP_const1u:
15365           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
15366           i += 1;
15367           break;
15368
15369         case DW_OP_const1s:
15370           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
15371           i += 1;
15372           break;
15373
15374         case DW_OP_const2u:
15375           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
15376           i += 2;
15377           break;
15378
15379         case DW_OP_const2s:
15380           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
15381           i += 2;
15382           break;
15383
15384         case DW_OP_const4u:
15385           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
15386           i += 4;
15387           break;
15388
15389         case DW_OP_const4s:
15390           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
15391           i += 4;
15392           break;
15393
15394         case DW_OP_const8u:
15395           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
15396           i += 8;
15397           break;
15398
15399         case DW_OP_constu:
15400           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
15401                                                   &bytes_read);
15402           i += bytes_read;
15403           break;
15404
15405         case DW_OP_consts:
15406           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
15407           i += bytes_read;
15408           break;
15409
15410         case DW_OP_dup:
15411           stack[stacki + 1] = stack[stacki];
15412           stacki++;
15413           break;
15414
15415         case DW_OP_plus:
15416           stack[stacki - 1] += stack[stacki];
15417           stacki--;
15418           break;
15419
15420         case DW_OP_plus_uconst:
15421           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
15422                                                  &bytes_read);
15423           i += bytes_read;
15424           break;
15425
15426         case DW_OP_minus:
15427           stack[stacki - 1] -= stack[stacki];
15428           stacki--;
15429           break;
15430
15431         case DW_OP_deref:
15432           /* If we're not the last op, then we definitely can't encode
15433              this using GDB's address_class enum.  This is valid for partial
15434              global symbols, although the variable's address will be bogus
15435              in the psymtab.  */
15436           if (i < size)
15437             dwarf2_complex_location_expr_complaint ();
15438           break;
15439
15440         case DW_OP_GNU_push_tls_address:
15441           /* The top of the stack has the offset from the beginning
15442              of the thread control block at which the variable is located.  */
15443           /* Nothing should follow this operator, so the top of stack would
15444              be returned.  */
15445           /* This is valid for partial global symbols, but the variable's
15446              address will be bogus in the psymtab.  Make it always at least
15447              non-zero to not look as a variable garbage collected by linker
15448              which have DW_OP_addr 0.  */
15449           if (i < size)
15450             dwarf2_complex_location_expr_complaint ();
15451           stack[stacki]++;
15452           break;
15453
15454         case DW_OP_GNU_uninit:
15455           break;
15456
15457         case DW_OP_GNU_addr_index:
15458           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
15459                                                          &bytes_read);
15460           i += bytes_read;
15461           break;
15462
15463         default:
15464           {
15465             const char *name = get_DW_OP_name (op);
15466
15467             if (name)
15468               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
15469                          name);
15470             else
15471               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
15472                          op);
15473           }
15474
15475           return (stack[stacki]);
15476         }
15477
15478       /* Enforce maximum stack depth of SIZE-1 to avoid writing
15479          outside of the allocated space.  Also enforce minimum>0.  */
15480       if (stacki >= ARRAY_SIZE (stack) - 1)
15481         {
15482           complaint (&symfile_complaints,
15483                      _("location description stack overflow"));
15484           return 0;
15485         }
15486
15487       if (stacki <= 0)
15488         {
15489           complaint (&symfile_complaints,
15490                      _("location description stack underflow"));
15491           return 0;
15492         }
15493     }
15494   return (stack[stacki]);
15495 }
15496
15497 /* memory allocation interface */
15498
15499 static struct dwarf_block *
15500 dwarf_alloc_block (struct dwarf2_cu *cu)
15501 {
15502   struct dwarf_block *blk;
15503
15504   blk = (struct dwarf_block *)
15505     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
15506   return (blk);
15507 }
15508
15509 static struct abbrev_info *
15510 dwarf_alloc_abbrev (struct dwarf2_cu *cu)
15511 {
15512   struct abbrev_info *abbrev;
15513
15514   abbrev = (struct abbrev_info *)
15515     obstack_alloc (&cu->abbrev_obstack, sizeof (struct abbrev_info));
15516   memset (abbrev, 0, sizeof (struct abbrev_info));
15517   return (abbrev);
15518 }
15519
15520 static struct die_info *
15521 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
15522 {
15523   struct die_info *die;
15524   size_t size = sizeof (struct die_info);
15525
15526   if (num_attrs > 1)
15527     size += (num_attrs - 1) * sizeof (struct attribute);
15528
15529   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
15530   memset (die, 0, sizeof (struct die_info));
15531   return (die);
15532 }
15533
15534 \f
15535 /* Macro support.  */
15536
15537 /* Return the full name of file number I in *LH's file name table.
15538    Use COMP_DIR as the name of the current directory of the
15539    compilation.  The result is allocated using xmalloc; the caller is
15540    responsible for freeing it.  */
15541 static char *
15542 file_full_name (int file, struct line_header *lh, const char *comp_dir)
15543 {
15544   /* Is the file number a valid index into the line header's file name
15545      table?  Remember that file numbers start with one, not zero.  */
15546   if (1 <= file && file <= lh->num_file_names)
15547     {
15548       struct file_entry *fe = &lh->file_names[file - 1];
15549
15550       if (IS_ABSOLUTE_PATH (fe->name))
15551         return xstrdup (fe->name);
15552       else
15553         {
15554           const char *dir;
15555           int dir_len;
15556           char *full_name;
15557
15558           if (fe->dir_index)
15559             dir = lh->include_dirs[fe->dir_index - 1];
15560           else
15561             dir = comp_dir;
15562
15563           if (dir)
15564             {
15565               dir_len = strlen (dir);
15566               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
15567               strcpy (full_name, dir);
15568               full_name[dir_len] = '/';
15569               strcpy (full_name + dir_len + 1, fe->name);
15570               return full_name;
15571             }
15572           else
15573             return xstrdup (fe->name);
15574         }
15575     }
15576   else
15577     {
15578       /* The compiler produced a bogus file number.  We can at least
15579          record the macro definitions made in the file, even if we
15580          won't be able to find the file by name.  */
15581       char fake_name[80];
15582
15583       sprintf (fake_name, "<bad macro file number %d>", file);
15584
15585       complaint (&symfile_complaints,
15586                  _("bad file number in macro information (%d)"),
15587                  file);
15588
15589       return xstrdup (fake_name);
15590     }
15591 }
15592
15593
15594 static struct macro_source_file *
15595 macro_start_file (int file, int line,
15596                   struct macro_source_file *current_file,
15597                   const char *comp_dir,
15598                   struct line_header *lh, struct objfile *objfile)
15599 {
15600   /* The full name of this source file.  */
15601   char *full_name = file_full_name (file, lh, comp_dir);
15602
15603   /* We don't create a macro table for this compilation unit
15604      at all until we actually get a filename.  */
15605   if (! pending_macros)
15606     pending_macros = new_macro_table (&objfile->objfile_obstack,
15607                                       objfile->macro_cache);
15608
15609   if (! current_file)
15610     {
15611       /* If we have no current file, then this must be the start_file
15612          directive for the compilation unit's main source file.  */
15613       current_file = macro_set_main (pending_macros, full_name);
15614       macro_define_special (pending_macros);
15615     }
15616   else
15617     current_file = macro_include (current_file, line, full_name);
15618
15619   xfree (full_name);
15620
15621   return current_file;
15622 }
15623
15624
15625 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
15626    followed by a null byte.  */
15627 static char *
15628 copy_string (const char *buf, int len)
15629 {
15630   char *s = xmalloc (len + 1);
15631
15632   memcpy (s, buf, len);
15633   s[len] = '\0';
15634   return s;
15635 }
15636
15637
15638 static const char *
15639 consume_improper_spaces (const char *p, const char *body)
15640 {
15641   if (*p == ' ')
15642     {
15643       complaint (&symfile_complaints,
15644                  _("macro definition contains spaces "
15645                    "in formal argument list:\n`%s'"),
15646                  body);
15647
15648       while (*p == ' ')
15649         p++;
15650     }
15651
15652   return p;
15653 }
15654
15655
15656 static void
15657 parse_macro_definition (struct macro_source_file *file, int line,
15658                         const char *body)
15659 {
15660   const char *p;
15661
15662   /* The body string takes one of two forms.  For object-like macro
15663      definitions, it should be:
15664
15665         <macro name> " " <definition>
15666
15667      For function-like macro definitions, it should be:
15668
15669         <macro name> "() " <definition>
15670      or
15671         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
15672
15673      Spaces may appear only where explicitly indicated, and in the
15674      <definition>.
15675
15676      The Dwarf 2 spec says that an object-like macro's name is always
15677      followed by a space, but versions of GCC around March 2002 omit
15678      the space when the macro's definition is the empty string.
15679
15680      The Dwarf 2 spec says that there should be no spaces between the
15681      formal arguments in a function-like macro's formal argument list,
15682      but versions of GCC around March 2002 include spaces after the
15683      commas.  */
15684
15685
15686   /* Find the extent of the macro name.  The macro name is terminated
15687      by either a space or null character (for an object-like macro) or
15688      an opening paren (for a function-like macro).  */
15689   for (p = body; *p; p++)
15690     if (*p == ' ' || *p == '(')
15691       break;
15692
15693   if (*p == ' ' || *p == '\0')
15694     {
15695       /* It's an object-like macro.  */
15696       int name_len = p - body;
15697       char *name = copy_string (body, name_len);
15698       const char *replacement;
15699
15700       if (*p == ' ')
15701         replacement = body + name_len + 1;
15702       else
15703         {
15704           dwarf2_macro_malformed_definition_complaint (body);
15705           replacement = body + name_len;
15706         }
15707
15708       macro_define_object (file, line, name, replacement);
15709
15710       xfree (name);
15711     }
15712   else if (*p == '(')
15713     {
15714       /* It's a function-like macro.  */
15715       char *name = copy_string (body, p - body);
15716       int argc = 0;
15717       int argv_size = 1;
15718       char **argv = xmalloc (argv_size * sizeof (*argv));
15719
15720       p++;
15721
15722       p = consume_improper_spaces (p, body);
15723
15724       /* Parse the formal argument list.  */
15725       while (*p && *p != ')')
15726         {
15727           /* Find the extent of the current argument name.  */
15728           const char *arg_start = p;
15729
15730           while (*p && *p != ',' && *p != ')' && *p != ' ')
15731             p++;
15732
15733           if (! *p || p == arg_start)
15734             dwarf2_macro_malformed_definition_complaint (body);
15735           else
15736             {
15737               /* Make sure argv has room for the new argument.  */
15738               if (argc >= argv_size)
15739                 {
15740                   argv_size *= 2;
15741                   argv = xrealloc (argv, argv_size * sizeof (*argv));
15742                 }
15743
15744               argv[argc++] = copy_string (arg_start, p - arg_start);
15745             }
15746
15747           p = consume_improper_spaces (p, body);
15748
15749           /* Consume the comma, if present.  */
15750           if (*p == ',')
15751             {
15752               p++;
15753
15754               p = consume_improper_spaces (p, body);
15755             }
15756         }
15757
15758       if (*p == ')')
15759         {
15760           p++;
15761
15762           if (*p == ' ')
15763             /* Perfectly formed definition, no complaints.  */
15764             macro_define_function (file, line, name,
15765                                    argc, (const char **) argv,
15766                                    p + 1);
15767           else if (*p == '\0')
15768             {
15769               /* Complain, but do define it.  */
15770               dwarf2_macro_malformed_definition_complaint (body);
15771               macro_define_function (file, line, name,
15772                                      argc, (const char **) argv,
15773                                      p);
15774             }
15775           else
15776             /* Just complain.  */
15777             dwarf2_macro_malformed_definition_complaint (body);
15778         }
15779       else
15780         /* Just complain.  */
15781         dwarf2_macro_malformed_definition_complaint (body);
15782
15783       xfree (name);
15784       {
15785         int i;
15786
15787         for (i = 0; i < argc; i++)
15788           xfree (argv[i]);
15789       }
15790       xfree (argv);
15791     }
15792   else
15793     dwarf2_macro_malformed_definition_complaint (body);
15794 }
15795
15796 /* Skip some bytes from BYTES according to the form given in FORM.
15797    Returns the new pointer.  */
15798
15799 static gdb_byte *
15800 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
15801                  enum dwarf_form form,
15802                  unsigned int offset_size,
15803                  struct dwarf2_section_info *section)
15804 {
15805   unsigned int bytes_read;
15806
15807   switch (form)
15808     {
15809     case DW_FORM_data1:
15810     case DW_FORM_flag:
15811       ++bytes;
15812       break;
15813
15814     case DW_FORM_data2:
15815       bytes += 2;
15816       break;
15817
15818     case DW_FORM_data4:
15819       bytes += 4;
15820       break;
15821
15822     case DW_FORM_data8:
15823       bytes += 8;
15824       break;
15825
15826     case DW_FORM_string:
15827       read_direct_string (abfd, bytes, &bytes_read);
15828       bytes += bytes_read;
15829       break;
15830
15831     case DW_FORM_sec_offset:
15832     case DW_FORM_strp:
15833       bytes += offset_size;
15834       break;
15835
15836     case DW_FORM_block:
15837       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
15838       bytes += bytes_read;
15839       break;
15840
15841     case DW_FORM_block1:
15842       bytes += 1 + read_1_byte (abfd, bytes);
15843       break;
15844     case DW_FORM_block2:
15845       bytes += 2 + read_2_bytes (abfd, bytes);
15846       break;
15847     case DW_FORM_block4:
15848       bytes += 4 + read_4_bytes (abfd, bytes);
15849       break;
15850
15851     case DW_FORM_sdata:
15852     case DW_FORM_udata:
15853     case DW_FORM_GNU_addr_index:
15854     case DW_FORM_GNU_str_index:
15855       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
15856       if (bytes == NULL)
15857         {
15858           dwarf2_section_buffer_overflow_complaint (section);
15859           return NULL;
15860         }
15861       break;
15862
15863     default:
15864       {
15865       complain:
15866         complaint (&symfile_complaints,
15867                    _("invalid form 0x%x in `%s'"),
15868                    form,
15869                    section->asection->name);
15870         return NULL;
15871       }
15872     }
15873
15874   return bytes;
15875 }
15876
15877 /* A helper for dwarf_decode_macros that handles skipping an unknown
15878    opcode.  Returns an updated pointer to the macro data buffer; or,
15879    on error, issues a complaint and returns NULL.  */
15880
15881 static gdb_byte *
15882 skip_unknown_opcode (unsigned int opcode,
15883                      gdb_byte **opcode_definitions,
15884                      gdb_byte *mac_ptr, gdb_byte *mac_end,
15885                      bfd *abfd,
15886                      unsigned int offset_size,
15887                      struct dwarf2_section_info *section)
15888 {
15889   unsigned int bytes_read, i;
15890   unsigned long arg;
15891   gdb_byte *defn;
15892
15893   if (opcode_definitions[opcode] == NULL)
15894     {
15895       complaint (&symfile_complaints,
15896                  _("unrecognized DW_MACFINO opcode 0x%x"),
15897                  opcode);
15898       return NULL;
15899     }
15900
15901   defn = opcode_definitions[opcode];
15902   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
15903   defn += bytes_read;
15904
15905   for (i = 0; i < arg; ++i)
15906     {
15907       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
15908                                  section);
15909       if (mac_ptr == NULL)
15910         {
15911           /* skip_form_bytes already issued the complaint.  */
15912           return NULL;
15913         }
15914     }
15915
15916   return mac_ptr;
15917 }
15918
15919 /* A helper function which parses the header of a macro section.
15920    If the macro section is the extended (for now called "GNU") type,
15921    then this updates *OFFSET_SIZE.  Returns a pointer to just after
15922    the header, or issues a complaint and returns NULL on error.  */
15923
15924 static gdb_byte *
15925 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
15926                           bfd *abfd,
15927                           gdb_byte *mac_ptr,
15928                           unsigned int *offset_size,
15929                           int section_is_gnu)
15930 {
15931   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
15932
15933   if (section_is_gnu)
15934     {
15935       unsigned int version, flags;
15936
15937       version = read_2_bytes (abfd, mac_ptr);
15938       if (version != 4)
15939         {
15940           complaint (&symfile_complaints,
15941                      _("unrecognized version `%d' in .debug_macro section"),
15942                      version);
15943           return NULL;
15944         }
15945       mac_ptr += 2;
15946
15947       flags = read_1_byte (abfd, mac_ptr);
15948       ++mac_ptr;
15949       *offset_size = (flags & 1) ? 8 : 4;
15950
15951       if ((flags & 2) != 0)
15952         /* We don't need the line table offset.  */
15953         mac_ptr += *offset_size;
15954
15955       /* Vendor opcode descriptions.  */
15956       if ((flags & 4) != 0)
15957         {
15958           unsigned int i, count;
15959
15960           count = read_1_byte (abfd, mac_ptr);
15961           ++mac_ptr;
15962           for (i = 0; i < count; ++i)
15963             {
15964               unsigned int opcode, bytes_read;
15965               unsigned long arg;
15966
15967               opcode = read_1_byte (abfd, mac_ptr);
15968               ++mac_ptr;
15969               opcode_definitions[opcode] = mac_ptr;
15970               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
15971               mac_ptr += bytes_read;
15972               mac_ptr += arg;
15973             }
15974         }
15975     }
15976
15977   return mac_ptr;
15978 }
15979
15980 /* A helper for dwarf_decode_macros that handles the GNU extensions,
15981    including DW_MACRO_GNU_transparent_include.  */
15982
15983 static void
15984 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
15985                           struct macro_source_file *current_file,
15986                           struct line_header *lh, char *comp_dir,
15987                           struct dwarf2_section_info *section,
15988                           int section_is_gnu,
15989                           unsigned int offset_size,
15990                           struct objfile *objfile,
15991                           htab_t include_hash)
15992 {
15993   enum dwarf_macro_record_type macinfo_type;
15994   int at_commandline;
15995   gdb_byte *opcode_definitions[256];
15996
15997   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
15998                                       &offset_size, section_is_gnu);
15999   if (mac_ptr == NULL)
16000     {
16001       /* We already issued a complaint.  */
16002       return;
16003     }
16004
16005   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
16006      GDB is still reading the definitions from command line.  First
16007      DW_MACINFO_start_file will need to be ignored as it was already executed
16008      to create CURRENT_FILE for the main source holding also the command line
16009      definitions.  On first met DW_MACINFO_start_file this flag is reset to
16010      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
16011
16012   at_commandline = 1;
16013
16014   do
16015     {
16016       /* Do we at least have room for a macinfo type byte?  */
16017       if (mac_ptr >= mac_end)
16018         {
16019           dwarf2_section_buffer_overflow_complaint (section);
16020           break;
16021         }
16022
16023       macinfo_type = read_1_byte (abfd, mac_ptr);
16024       mac_ptr++;
16025
16026       /* Note that we rely on the fact that the corresponding GNU and
16027          DWARF constants are the same.  */
16028       switch (macinfo_type)
16029         {
16030           /* A zero macinfo type indicates the end of the macro
16031              information.  */
16032         case 0:
16033           break;
16034
16035         case DW_MACRO_GNU_define:
16036         case DW_MACRO_GNU_undef:
16037         case DW_MACRO_GNU_define_indirect:
16038         case DW_MACRO_GNU_undef_indirect:
16039           {
16040             unsigned int bytes_read;
16041             int line;
16042             char *body;
16043             int is_define;
16044
16045             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16046             mac_ptr += bytes_read;
16047
16048             if (macinfo_type == DW_MACRO_GNU_define
16049                 || macinfo_type == DW_MACRO_GNU_undef)
16050               {
16051                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
16052                 mac_ptr += bytes_read;
16053               }
16054             else
16055               {
16056                 LONGEST str_offset;
16057
16058                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
16059                 mac_ptr += offset_size;
16060
16061                 body = read_indirect_string_at_offset (abfd, str_offset);
16062               }
16063
16064             is_define = (macinfo_type == DW_MACRO_GNU_define
16065                          || macinfo_type == DW_MACRO_GNU_define_indirect);
16066             if (! current_file)
16067               {
16068                 /* DWARF violation as no main source is present.  */
16069                 complaint (&symfile_complaints,
16070                            _("debug info with no main source gives macro %s "
16071                              "on line %d: %s"),
16072                            is_define ? _("definition") : _("undefinition"),
16073                            line, body);
16074                 break;
16075               }
16076             if ((line == 0 && !at_commandline)
16077                 || (line != 0 && at_commandline))
16078               complaint (&symfile_complaints,
16079                          _("debug info gives %s macro %s with %s line %d: %s"),
16080                          at_commandline ? _("command-line") : _("in-file"),
16081                          is_define ? _("definition") : _("undefinition"),
16082                          line == 0 ? _("zero") : _("non-zero"), line, body);
16083
16084             if (is_define)
16085               parse_macro_definition (current_file, line, body);
16086             else
16087               {
16088                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
16089                             || macinfo_type == DW_MACRO_GNU_undef_indirect);
16090                 macro_undef (current_file, line, body);
16091               }
16092           }
16093           break;
16094
16095         case DW_MACRO_GNU_start_file:
16096           {
16097             unsigned int bytes_read;
16098             int line, file;
16099
16100             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16101             mac_ptr += bytes_read;
16102             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16103             mac_ptr += bytes_read;
16104
16105             if ((line == 0 && !at_commandline)
16106                 || (line != 0 && at_commandline))
16107               complaint (&symfile_complaints,
16108                          _("debug info gives source %d included "
16109                            "from %s at %s line %d"),
16110                          file, at_commandline ? _("command-line") : _("file"),
16111                          line == 0 ? _("zero") : _("non-zero"), line);
16112
16113             if (at_commandline)
16114               {
16115                 /* This DW_MACRO_GNU_start_file was executed in the
16116                    pass one.  */
16117                 at_commandline = 0;
16118               }
16119             else
16120               current_file = macro_start_file (file, line,
16121                                                current_file, comp_dir,
16122                                                lh, objfile);
16123           }
16124           break;
16125
16126         case DW_MACRO_GNU_end_file:
16127           if (! current_file)
16128             complaint (&symfile_complaints,
16129                        _("macro debug info has an unmatched "
16130                          "`close_file' directive"));
16131           else
16132             {
16133               current_file = current_file->included_by;
16134               if (! current_file)
16135                 {
16136                   enum dwarf_macro_record_type next_type;
16137
16138                   /* GCC circa March 2002 doesn't produce the zero
16139                      type byte marking the end of the compilation
16140                      unit.  Complain if it's not there, but exit no
16141                      matter what.  */
16142
16143                   /* Do we at least have room for a macinfo type byte?  */
16144                   if (mac_ptr >= mac_end)
16145                     {
16146                       dwarf2_section_buffer_overflow_complaint (section);
16147                       return;
16148                     }
16149
16150                   /* We don't increment mac_ptr here, so this is just
16151                      a look-ahead.  */
16152                   next_type = read_1_byte (abfd, mac_ptr);
16153                   if (next_type != 0)
16154                     complaint (&symfile_complaints,
16155                                _("no terminating 0-type entry for "
16156                                  "macros in `.debug_macinfo' section"));
16157
16158                   return;
16159                 }
16160             }
16161           break;
16162
16163         case DW_MACRO_GNU_transparent_include:
16164           {
16165             LONGEST offset;
16166             void **slot;
16167
16168             offset = read_offset_1 (abfd, mac_ptr, offset_size);
16169             mac_ptr += offset_size;
16170
16171             slot = htab_find_slot (include_hash, mac_ptr, INSERT);
16172             if (*slot != NULL)
16173               {
16174                 /* This has actually happened; see
16175                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
16176                 complaint (&symfile_complaints,
16177                            _("recursive DW_MACRO_GNU_transparent_include in "
16178                              ".debug_macro section"));
16179               }
16180             else
16181               {
16182                 *slot = mac_ptr;
16183
16184                 dwarf_decode_macro_bytes (abfd,
16185                                           section->buffer + offset,
16186                                           mac_end, current_file,
16187                                           lh, comp_dir,
16188                                           section, section_is_gnu,
16189                                           offset_size, objfile, include_hash);
16190
16191                 htab_remove_elt (include_hash, mac_ptr);
16192               }
16193           }
16194           break;
16195
16196         case DW_MACINFO_vendor_ext:
16197           if (!section_is_gnu)
16198             {
16199               unsigned int bytes_read;
16200               int constant;
16201
16202               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16203               mac_ptr += bytes_read;
16204               read_direct_string (abfd, mac_ptr, &bytes_read);
16205               mac_ptr += bytes_read;
16206
16207               /* We don't recognize any vendor extensions.  */
16208               break;
16209             }
16210           /* FALLTHROUGH */
16211
16212         default:
16213           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
16214                                          mac_ptr, mac_end, abfd, offset_size,
16215                                          section);
16216           if (mac_ptr == NULL)
16217             return;
16218           break;
16219         }
16220     } while (macinfo_type != 0);
16221 }
16222
16223 static void
16224 dwarf_decode_macros (struct line_header *lh, unsigned int offset,
16225                      char *comp_dir, bfd *abfd,
16226                      struct dwarf2_cu *cu,
16227                      struct dwarf2_section_info *section,
16228                      int section_is_gnu, const char *section_name)
16229 {
16230   struct objfile *objfile = dwarf2_per_objfile->objfile;
16231   gdb_byte *mac_ptr, *mac_end;
16232   struct macro_source_file *current_file = 0;
16233   enum dwarf_macro_record_type macinfo_type;
16234   unsigned int offset_size = cu->header.offset_size;
16235   gdb_byte *opcode_definitions[256];
16236   struct cleanup *cleanup;
16237   htab_t include_hash;
16238   void **slot;
16239
16240   dwarf2_read_section (objfile, section);
16241   if (section->buffer == NULL)
16242     {
16243       complaint (&symfile_complaints, _("missing %s section"), section_name);
16244       return;
16245     }
16246
16247   /* First pass: Find the name of the base filename.
16248      This filename is needed in order to process all macros whose definition
16249      (or undefinition) comes from the command line.  These macros are defined
16250      before the first DW_MACINFO_start_file entry, and yet still need to be
16251      associated to the base file.
16252
16253      To determine the base file name, we scan the macro definitions until we
16254      reach the first DW_MACINFO_start_file entry.  We then initialize
16255      CURRENT_FILE accordingly so that any macro definition found before the
16256      first DW_MACINFO_start_file can still be associated to the base file.  */
16257
16258   mac_ptr = section->buffer + offset;
16259   mac_end = section->buffer + section->size;
16260
16261   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
16262                                       &offset_size, section_is_gnu);
16263   if (mac_ptr == NULL)
16264     {
16265       /* We already issued a complaint.  */
16266       return;
16267     }
16268
16269   do
16270     {
16271       /* Do we at least have room for a macinfo type byte?  */
16272       if (mac_ptr >= mac_end)
16273         {
16274           /* Complaint is printed during the second pass as GDB will probably
16275              stop the first pass earlier upon finding
16276              DW_MACINFO_start_file.  */
16277           break;
16278         }
16279
16280       macinfo_type = read_1_byte (abfd, mac_ptr);
16281       mac_ptr++;
16282
16283       /* Note that we rely on the fact that the corresponding GNU and
16284          DWARF constants are the same.  */
16285       switch (macinfo_type)
16286         {
16287           /* A zero macinfo type indicates the end of the macro
16288              information.  */
16289         case 0:
16290           break;
16291
16292         case DW_MACRO_GNU_define:
16293         case DW_MACRO_GNU_undef:
16294           /* Only skip the data by MAC_PTR.  */
16295           {
16296             unsigned int bytes_read;
16297
16298             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16299             mac_ptr += bytes_read;
16300             read_direct_string (abfd, mac_ptr, &bytes_read);
16301             mac_ptr += bytes_read;
16302           }
16303           break;
16304
16305         case DW_MACRO_GNU_start_file:
16306           {
16307             unsigned int bytes_read;
16308             int line, file;
16309
16310             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16311             mac_ptr += bytes_read;
16312             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16313             mac_ptr += bytes_read;
16314
16315             current_file = macro_start_file (file, line, current_file,
16316                                              comp_dir, lh, objfile);
16317           }
16318           break;
16319
16320         case DW_MACRO_GNU_end_file:
16321           /* No data to skip by MAC_PTR.  */
16322           break;
16323
16324         case DW_MACRO_GNU_define_indirect:
16325         case DW_MACRO_GNU_undef_indirect:
16326           {
16327             unsigned int bytes_read;
16328
16329             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16330             mac_ptr += bytes_read;
16331             mac_ptr += offset_size;
16332           }
16333           break;
16334
16335         case DW_MACRO_GNU_transparent_include:
16336           /* Note that, according to the spec, a transparent include
16337              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
16338              skip this opcode.  */
16339           mac_ptr += offset_size;
16340           break;
16341
16342         case DW_MACINFO_vendor_ext:
16343           /* Only skip the data by MAC_PTR.  */
16344           if (!section_is_gnu)
16345             {
16346               unsigned int bytes_read;
16347
16348               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16349               mac_ptr += bytes_read;
16350               read_direct_string (abfd, mac_ptr, &bytes_read);
16351               mac_ptr += bytes_read;
16352             }
16353           /* FALLTHROUGH */
16354
16355         default:
16356           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
16357                                          mac_ptr, mac_end, abfd, offset_size,
16358                                          section);
16359           if (mac_ptr == NULL)
16360             return;
16361           break;
16362         }
16363     } while (macinfo_type != 0 && current_file == NULL);
16364
16365   /* Second pass: Process all entries.
16366
16367      Use the AT_COMMAND_LINE flag to determine whether we are still processing
16368      command-line macro definitions/undefinitions.  This flag is unset when we
16369      reach the first DW_MACINFO_start_file entry.  */
16370
16371   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
16372                                     NULL, xcalloc, xfree);
16373   cleanup = make_cleanup_htab_delete (include_hash);
16374   mac_ptr = section->buffer + offset;
16375   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
16376   *slot = mac_ptr;
16377   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
16378                             current_file, lh, comp_dir, section, section_is_gnu,
16379                             offset_size, objfile, include_hash);
16380   do_cleanups (cleanup);
16381 }
16382
16383 /* Check if the attribute's form is a DW_FORM_block*
16384    if so return true else false.  */
16385
16386 static int
16387 attr_form_is_block (struct attribute *attr)
16388 {
16389   return (attr == NULL ? 0 :
16390       attr->form == DW_FORM_block1
16391       || attr->form == DW_FORM_block2
16392       || attr->form == DW_FORM_block4
16393       || attr->form == DW_FORM_block
16394       || attr->form == DW_FORM_exprloc);
16395 }
16396
16397 /* Return non-zero if ATTR's value is a section offset --- classes
16398    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
16399    You may use DW_UNSND (attr) to retrieve such offsets.
16400
16401    Section 7.5.4, "Attribute Encodings", explains that no attribute
16402    may have a value that belongs to more than one of these classes; it
16403    would be ambiguous if we did, because we use the same forms for all
16404    of them.  */
16405
16406 static int
16407 attr_form_is_section_offset (struct attribute *attr)
16408 {
16409   return (attr->form == DW_FORM_data4
16410           || attr->form == DW_FORM_data8
16411           || attr->form == DW_FORM_sec_offset);
16412 }
16413
16414 /* Return non-zero if ATTR's value falls in the 'constant' class, or
16415    zero otherwise.  When this function returns true, you can apply
16416    dwarf2_get_attr_constant_value to it.
16417
16418    However, note that for some attributes you must check
16419    attr_form_is_section_offset before using this test.  DW_FORM_data4
16420    and DW_FORM_data8 are members of both the constant class, and of
16421    the classes that contain offsets into other debug sections
16422    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
16423    that, if an attribute's can be either a constant or one of the
16424    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
16425    taken as section offsets, not constants.  */
16426
16427 static int
16428 attr_form_is_constant (struct attribute *attr)
16429 {
16430   switch (attr->form)
16431     {
16432     case DW_FORM_sdata:
16433     case DW_FORM_udata:
16434     case DW_FORM_data1:
16435     case DW_FORM_data2:
16436     case DW_FORM_data4:
16437     case DW_FORM_data8:
16438       return 1;
16439     default:
16440       return 0;
16441     }
16442 }
16443
16444 /* Return the .debug_loc section to use for CU.
16445    For DWO files use .debug_loc.dwo.  */
16446
16447 static struct dwarf2_section_info *
16448 cu_debug_loc_section (struct dwarf2_cu *cu)
16449 {
16450   if (cu->dwo_unit)
16451     return &cu->dwo_unit->dwo_file->sections.loc;
16452   return &dwarf2_per_objfile->loc;
16453 }
16454
16455 /* A helper function that fills in a dwarf2_loclist_baton.  */
16456
16457 static void
16458 fill_in_loclist_baton (struct dwarf2_cu *cu,
16459                        struct dwarf2_loclist_baton *baton,
16460                        struct attribute *attr)
16461 {
16462   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
16463
16464   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
16465
16466   baton->per_cu = cu->per_cu;
16467   gdb_assert (baton->per_cu);
16468   /* We don't know how long the location list is, but make sure we
16469      don't run off the edge of the section.  */
16470   baton->size = section->size - DW_UNSND (attr);
16471   baton->data = section->buffer + DW_UNSND (attr);
16472   baton->base_address = cu->base_address;
16473   baton->from_dwo = cu->dwo_unit != NULL;
16474 }
16475
16476 static void
16477 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
16478                              struct dwarf2_cu *cu)
16479 {
16480   struct objfile *objfile = dwarf2_per_objfile->objfile;
16481   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
16482
16483   if (attr_form_is_section_offset (attr)
16484       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
16485          the section.  If so, fall through to the complaint in the
16486          other branch.  */
16487       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
16488     {
16489       struct dwarf2_loclist_baton *baton;
16490
16491       baton = obstack_alloc (&objfile->objfile_obstack,
16492                              sizeof (struct dwarf2_loclist_baton));
16493
16494       fill_in_loclist_baton (cu, baton, attr);
16495
16496       if (cu->base_known == 0)
16497         complaint (&symfile_complaints,
16498                    _("Location list used without "
16499                      "specifying the CU base address."));
16500
16501       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
16502       SYMBOL_LOCATION_BATON (sym) = baton;
16503     }
16504   else
16505     {
16506       struct dwarf2_locexpr_baton *baton;
16507
16508       baton = obstack_alloc (&objfile->objfile_obstack,
16509                              sizeof (struct dwarf2_locexpr_baton));
16510       baton->per_cu = cu->per_cu;
16511       gdb_assert (baton->per_cu);
16512
16513       if (attr_form_is_block (attr))
16514         {
16515           /* Note that we're just copying the block's data pointer
16516              here, not the actual data.  We're still pointing into the
16517              info_buffer for SYM's objfile; right now we never release
16518              that buffer, but when we do clean up properly this may
16519              need to change.  */
16520           baton->size = DW_BLOCK (attr)->size;
16521           baton->data = DW_BLOCK (attr)->data;
16522         }
16523       else
16524         {
16525           dwarf2_invalid_attrib_class_complaint ("location description",
16526                                                  SYMBOL_NATURAL_NAME (sym));
16527           baton->size = 0;
16528         }
16529
16530       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
16531       SYMBOL_LOCATION_BATON (sym) = baton;
16532     }
16533 }
16534
16535 /* Return the OBJFILE associated with the compilation unit CU.  If CU
16536    came from a separate debuginfo file, then the master objfile is
16537    returned.  */
16538
16539 struct objfile *
16540 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
16541 {
16542   struct objfile *objfile = per_cu->objfile;
16543
16544   /* Return the master objfile, so that we can report and look up the
16545      correct file containing this variable.  */
16546   if (objfile->separate_debug_objfile_backlink)
16547     objfile = objfile->separate_debug_objfile_backlink;
16548
16549   return objfile;
16550 }
16551
16552 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
16553    (CU_HEADERP is unused in such case) or prepare a temporary copy at
16554    CU_HEADERP first.  */
16555
16556 static const struct comp_unit_head *
16557 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
16558                        struct dwarf2_per_cu_data *per_cu)
16559 {
16560   struct objfile *objfile;
16561   struct dwarf2_per_objfile *per_objfile;
16562   gdb_byte *info_ptr;
16563
16564   if (per_cu->cu)
16565     return &per_cu->cu->header;
16566
16567   objfile = per_cu->objfile;
16568   per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
16569   info_ptr = per_objfile->info.buffer + per_cu->offset.sect_off;
16570
16571   memset (cu_headerp, 0, sizeof (*cu_headerp));
16572   read_comp_unit_head (cu_headerp, info_ptr, objfile->obfd);
16573
16574   return cu_headerp;
16575 }
16576
16577 /* Return the address size given in the compilation unit header for CU.  */
16578
16579 int
16580 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
16581 {
16582   struct comp_unit_head cu_header_local;
16583   const struct comp_unit_head *cu_headerp;
16584
16585   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
16586
16587   return cu_headerp->addr_size;
16588 }
16589
16590 /* Return the offset size given in the compilation unit header for CU.  */
16591
16592 int
16593 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
16594 {
16595   struct comp_unit_head cu_header_local;
16596   const struct comp_unit_head *cu_headerp;
16597
16598   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
16599
16600   return cu_headerp->offset_size;
16601 }
16602
16603 /* See its dwarf2loc.h declaration.  */
16604
16605 int
16606 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
16607 {
16608   struct comp_unit_head cu_header_local;
16609   const struct comp_unit_head *cu_headerp;
16610
16611   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
16612
16613   if (cu_headerp->version == 2)
16614     return cu_headerp->addr_size;
16615   else
16616     return cu_headerp->offset_size;
16617 }
16618
16619 /* Return the text offset of the CU.  The returned offset comes from
16620    this CU's objfile.  If this objfile came from a separate debuginfo
16621    file, then the offset may be different from the corresponding
16622    offset in the parent objfile.  */
16623
16624 CORE_ADDR
16625 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
16626 {
16627   struct objfile *objfile = per_cu->objfile;
16628
16629   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16630 }
16631
16632 /* Locate the .debug_info compilation unit from CU's objfile which contains
16633    the DIE at OFFSET.  Raises an error on failure.  */
16634
16635 static struct dwarf2_per_cu_data *
16636 dwarf2_find_containing_comp_unit (sect_offset offset,
16637                                   struct objfile *objfile)
16638 {
16639   struct dwarf2_per_cu_data *this_cu;
16640   int low, high;
16641
16642   low = 0;
16643   high = dwarf2_per_objfile->n_comp_units - 1;
16644   while (high > low)
16645     {
16646       int mid = low + (high - low) / 2;
16647
16648       if (dwarf2_per_objfile->all_comp_units[mid]->offset.sect_off
16649           >= offset.sect_off)
16650         high = mid;
16651       else
16652         low = mid + 1;
16653     }
16654   gdb_assert (low == high);
16655   if (dwarf2_per_objfile->all_comp_units[low]->offset.sect_off
16656       > offset.sect_off)
16657     {
16658       if (low == 0)
16659         error (_("Dwarf Error: could not find partial DIE containing "
16660                "offset 0x%lx [in module %s]"),
16661                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
16662
16663       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
16664                   <= offset.sect_off);
16665       return dwarf2_per_objfile->all_comp_units[low-1];
16666     }
16667   else
16668     {
16669       this_cu = dwarf2_per_objfile->all_comp_units[low];
16670       if (low == dwarf2_per_objfile->n_comp_units - 1
16671           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
16672         error (_("invalid dwarf2 offset %u"), offset.sect_off);
16673       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
16674       return this_cu;
16675     }
16676 }
16677
16678 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
16679
16680 static void
16681 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
16682 {
16683   memset (cu, 0, sizeof (*cu));
16684   per_cu->cu = cu;
16685   cu->per_cu = per_cu;
16686   cu->objfile = per_cu->objfile;
16687   obstack_init (&cu->comp_unit_obstack);
16688 }
16689
16690 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
16691
16692 static void
16693 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
16694                        enum language pretend_language)
16695 {
16696   struct attribute *attr;
16697
16698   /* Set the language we're debugging.  */
16699   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
16700   if (attr)
16701     set_cu_language (DW_UNSND (attr), cu);
16702   else
16703     {
16704       cu->language = pretend_language;
16705       cu->language_defn = language_def (cu->language);
16706     }
16707
16708   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
16709   if (attr)
16710     cu->producer = DW_STRING (attr);
16711 }
16712
16713 /* Release one cached compilation unit, CU.  We unlink it from the tree
16714    of compilation units, but we don't remove it from the read_in_chain;
16715    the caller is responsible for that.
16716    NOTE: DATA is a void * because this function is also used as a
16717    cleanup routine.  */
16718
16719 static void
16720 free_heap_comp_unit (void *data)
16721 {
16722   struct dwarf2_cu *cu = data;
16723
16724   gdb_assert (cu->per_cu != NULL);
16725   cu->per_cu->cu = NULL;
16726   cu->per_cu = NULL;
16727
16728   obstack_free (&cu->comp_unit_obstack, NULL);
16729
16730   xfree (cu);
16731 }
16732
16733 /* This cleanup function is passed the address of a dwarf2_cu on the stack
16734    when we're finished with it.  We can't free the pointer itself, but be
16735    sure to unlink it from the cache.  Also release any associated storage.  */
16736
16737 static void
16738 free_stack_comp_unit (void *data)
16739 {
16740   struct dwarf2_cu *cu = data;
16741
16742   gdb_assert (cu->per_cu != NULL);
16743   cu->per_cu->cu = NULL;
16744   cu->per_cu = NULL;
16745
16746   obstack_free (&cu->comp_unit_obstack, NULL);
16747   cu->partial_dies = NULL;
16748 }
16749
16750 /* Free all cached compilation units.  */
16751
16752 static void
16753 free_cached_comp_units (void *data)
16754 {
16755   struct dwarf2_per_cu_data *per_cu, **last_chain;
16756
16757   per_cu = dwarf2_per_objfile->read_in_chain;
16758   last_chain = &dwarf2_per_objfile->read_in_chain;
16759   while (per_cu != NULL)
16760     {
16761       struct dwarf2_per_cu_data *next_cu;
16762
16763       next_cu = per_cu->cu->read_in_chain;
16764
16765       free_heap_comp_unit (per_cu->cu);
16766       *last_chain = next_cu;
16767
16768       per_cu = next_cu;
16769     }
16770 }
16771
16772 /* Increase the age counter on each cached compilation unit, and free
16773    any that are too old.  */
16774
16775 static void
16776 age_cached_comp_units (void)
16777 {
16778   struct dwarf2_per_cu_data *per_cu, **last_chain;
16779
16780   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
16781   per_cu = dwarf2_per_objfile->read_in_chain;
16782   while (per_cu != NULL)
16783     {
16784       per_cu->cu->last_used ++;
16785       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
16786         dwarf2_mark (per_cu->cu);
16787       per_cu = per_cu->cu->read_in_chain;
16788     }
16789
16790   per_cu = dwarf2_per_objfile->read_in_chain;
16791   last_chain = &dwarf2_per_objfile->read_in_chain;
16792   while (per_cu != NULL)
16793     {
16794       struct dwarf2_per_cu_data *next_cu;
16795
16796       next_cu = per_cu->cu->read_in_chain;
16797
16798       if (!per_cu->cu->mark)
16799         {
16800           free_heap_comp_unit (per_cu->cu);
16801           *last_chain = next_cu;
16802         }
16803       else
16804         last_chain = &per_cu->cu->read_in_chain;
16805
16806       per_cu = next_cu;
16807     }
16808 }
16809
16810 /* Remove a single compilation unit from the cache.  */
16811
16812 static void
16813 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
16814 {
16815   struct dwarf2_per_cu_data *per_cu, **last_chain;
16816
16817   per_cu = dwarf2_per_objfile->read_in_chain;
16818   last_chain = &dwarf2_per_objfile->read_in_chain;
16819   while (per_cu != NULL)
16820     {
16821       struct dwarf2_per_cu_data *next_cu;
16822
16823       next_cu = per_cu->cu->read_in_chain;
16824
16825       if (per_cu == target_per_cu)
16826         {
16827           free_heap_comp_unit (per_cu->cu);
16828           per_cu->cu = NULL;
16829           *last_chain = next_cu;
16830           break;
16831         }
16832       else
16833         last_chain = &per_cu->cu->read_in_chain;
16834
16835       per_cu = next_cu;
16836     }
16837 }
16838
16839 /* Release all extra memory associated with OBJFILE.  */
16840
16841 void
16842 dwarf2_free_objfile (struct objfile *objfile)
16843 {
16844   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
16845
16846   if (dwarf2_per_objfile == NULL)
16847     return;
16848
16849   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
16850   free_cached_comp_units (NULL);
16851
16852   if (dwarf2_per_objfile->quick_file_names_table)
16853     htab_delete (dwarf2_per_objfile->quick_file_names_table);
16854
16855   /* Everything else should be on the objfile obstack.  */
16856 }
16857
16858 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
16859    We store these in a hash table separate from the DIEs, and preserve them
16860    when the DIEs are flushed out of cache.
16861
16862    The CU "per_cu" pointer is needed because offset alone is not enough to
16863    uniquely identify the type.  A file may have multiple .debug_types sections,
16864    or the type may come from a DWO file.  We have to use something in
16865    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
16866    routine, get_die_type_at_offset, from outside this file, and thus won't
16867    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
16868    of the objfile.  */
16869
16870 struct dwarf2_per_cu_offset_and_type
16871 {
16872   const struct dwarf2_per_cu_data *per_cu;
16873   sect_offset offset;
16874   struct type *type;
16875 };
16876
16877 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
16878
16879 static hashval_t
16880 per_cu_offset_and_type_hash (const void *item)
16881 {
16882   const struct dwarf2_per_cu_offset_and_type *ofs = item;
16883
16884   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
16885 }
16886
16887 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
16888
16889 static int
16890 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
16891 {
16892   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
16893   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
16894
16895   return (ofs_lhs->per_cu == ofs_rhs->per_cu
16896           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
16897 }
16898
16899 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
16900    table if necessary.  For convenience, return TYPE.
16901
16902    The DIEs reading must have careful ordering to:
16903     * Not cause infite loops trying to read in DIEs as a prerequisite for
16904       reading current DIE.
16905     * Not trying to dereference contents of still incompletely read in types
16906       while reading in other DIEs.
16907     * Enable referencing still incompletely read in types just by a pointer to
16908       the type without accessing its fields.
16909
16910    Therefore caller should follow these rules:
16911      * Try to fetch any prerequisite types we may need to build this DIE type
16912        before building the type and calling set_die_type.
16913      * After building type call set_die_type for current DIE as soon as
16914        possible before fetching more types to complete the current type.
16915      * Make the type as complete as possible before fetching more types.  */
16916
16917 static struct type *
16918 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16919 {
16920   struct dwarf2_per_cu_offset_and_type **slot, ofs;
16921   struct objfile *objfile = cu->objfile;
16922
16923   /* For Ada types, make sure that the gnat-specific data is always
16924      initialized (if not already set).  There are a few types where
16925      we should not be doing so, because the type-specific area is
16926      already used to hold some other piece of info (eg: TYPE_CODE_FLT
16927      where the type-specific area is used to store the floatformat).
16928      But this is not a problem, because the gnat-specific information
16929      is actually not needed for these types.  */
16930   if (need_gnat_info (cu)
16931       && TYPE_CODE (type) != TYPE_CODE_FUNC
16932       && TYPE_CODE (type) != TYPE_CODE_FLT
16933       && !HAVE_GNAT_AUX_INFO (type))
16934     INIT_GNAT_SPECIFIC (type);
16935
16936   if (dwarf2_per_objfile->die_type_hash == NULL)
16937     {
16938       dwarf2_per_objfile->die_type_hash =
16939         htab_create_alloc_ex (127,
16940                               per_cu_offset_and_type_hash,
16941                               per_cu_offset_and_type_eq,
16942                               NULL,
16943                               &objfile->objfile_obstack,
16944                               hashtab_obstack_allocate,
16945                               dummy_obstack_deallocate);
16946     }
16947
16948   ofs.per_cu = cu->per_cu;
16949   ofs.offset = die->offset;
16950   ofs.type = type;
16951   slot = (struct dwarf2_per_cu_offset_and_type **)
16952     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
16953   if (*slot)
16954     complaint (&symfile_complaints,
16955                _("A problem internal to GDB: DIE 0x%x has type already set"),
16956                die->offset.sect_off);
16957   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
16958   **slot = ofs;
16959   return type;
16960 }
16961
16962 /* Look up the type for the die at OFFSET in the appropriate type_hash
16963    table, or return NULL if the die does not have a saved type.  */
16964
16965 static struct type *
16966 get_die_type_at_offset (sect_offset offset,
16967                         struct dwarf2_per_cu_data *per_cu)
16968 {
16969   struct dwarf2_per_cu_offset_and_type *slot, ofs;
16970
16971   if (dwarf2_per_objfile->die_type_hash == NULL)
16972     return NULL;
16973
16974   ofs.per_cu = per_cu;
16975   ofs.offset = offset;
16976   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
16977   if (slot)
16978     return slot->type;
16979   else
16980     return NULL;
16981 }
16982
16983 /* Look up the type for DIE in the appropriate type_hash table,
16984    or return NULL if DIE does not have a saved type.  */
16985
16986 static struct type *
16987 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
16988 {
16989   return get_die_type_at_offset (die->offset, cu->per_cu);
16990 }
16991
16992 /* Add a dependence relationship from CU to REF_PER_CU.  */
16993
16994 static void
16995 dwarf2_add_dependence (struct dwarf2_cu *cu,
16996                        struct dwarf2_per_cu_data *ref_per_cu)
16997 {
16998   void **slot;
16999
17000   if (cu->dependencies == NULL)
17001     cu->dependencies
17002       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
17003                               NULL, &cu->comp_unit_obstack,
17004                               hashtab_obstack_allocate,
17005                               dummy_obstack_deallocate);
17006
17007   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
17008   if (*slot == NULL)
17009     *slot = ref_per_cu;
17010 }
17011
17012 /* Subroutine of dwarf2_mark to pass to htab_traverse.
17013    Set the mark field in every compilation unit in the
17014    cache that we must keep because we are keeping CU.  */
17015
17016 static int
17017 dwarf2_mark_helper (void **slot, void *data)
17018 {
17019   struct dwarf2_per_cu_data *per_cu;
17020
17021   per_cu = (struct dwarf2_per_cu_data *) *slot;
17022
17023   /* cu->dependencies references may not yet have been ever read if QUIT aborts
17024      reading of the chain.  As such dependencies remain valid it is not much
17025      useful to track and undo them during QUIT cleanups.  */
17026   if (per_cu->cu == NULL)
17027     return 1;
17028
17029   if (per_cu->cu->mark)
17030     return 1;
17031   per_cu->cu->mark = 1;
17032
17033   if (per_cu->cu->dependencies != NULL)
17034     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
17035
17036   return 1;
17037 }
17038
17039 /* Set the mark field in CU and in every other compilation unit in the
17040    cache that we must keep because we are keeping CU.  */
17041
17042 static void
17043 dwarf2_mark (struct dwarf2_cu *cu)
17044 {
17045   if (cu->mark)
17046     return;
17047   cu->mark = 1;
17048   if (cu->dependencies != NULL)
17049     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
17050 }
17051
17052 static void
17053 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
17054 {
17055   while (per_cu)
17056     {
17057       per_cu->cu->mark = 0;
17058       per_cu = per_cu->cu->read_in_chain;
17059     }
17060 }
17061
17062 /* Trivial hash function for partial_die_info: the hash value of a DIE
17063    is its offset in .debug_info for this objfile.  */
17064
17065 static hashval_t
17066 partial_die_hash (const void *item)
17067 {
17068   const struct partial_die_info *part_die = item;
17069
17070   return part_die->offset.sect_off;
17071 }
17072
17073 /* Trivial comparison function for partial_die_info structures: two DIEs
17074    are equal if they have the same offset.  */
17075
17076 static int
17077 partial_die_eq (const void *item_lhs, const void *item_rhs)
17078 {
17079   const struct partial_die_info *part_die_lhs = item_lhs;
17080   const struct partial_die_info *part_die_rhs = item_rhs;
17081
17082   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
17083 }
17084
17085 static struct cmd_list_element *set_dwarf2_cmdlist;
17086 static struct cmd_list_element *show_dwarf2_cmdlist;
17087
17088 static void
17089 set_dwarf2_cmd (char *args, int from_tty)
17090 {
17091   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
17092 }
17093
17094 static void
17095 show_dwarf2_cmd (char *args, int from_tty)
17096 {
17097   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
17098 }
17099
17100 /* If section described by INFO was mmapped, munmap it now.  */
17101
17102 static void
17103 munmap_section_buffer (struct dwarf2_section_info *info)
17104 {
17105   if (info->map_addr != NULL)
17106     {
17107 #ifdef HAVE_MMAP
17108       int res;
17109
17110       res = munmap (info->map_addr, info->map_len);
17111       gdb_assert (res == 0);
17112 #else
17113       /* Without HAVE_MMAP, we should never be here to begin with.  */
17114       gdb_assert_not_reached ("no mmap support");
17115 #endif
17116     }
17117 }
17118
17119 /* munmap debug sections for OBJFILE, if necessary.  */
17120
17121 static void
17122 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
17123 {
17124   struct dwarf2_per_objfile *data = d;
17125   int ix;
17126   struct dwarf2_section_info *section;
17127
17128   /* This is sorted according to the order they're defined in to make it easier
17129      to keep in sync.  */
17130   munmap_section_buffer (&data->info);
17131   munmap_section_buffer (&data->abbrev);
17132   munmap_section_buffer (&data->line);
17133   munmap_section_buffer (&data->loc);
17134   munmap_section_buffer (&data->macinfo);
17135   munmap_section_buffer (&data->macro);
17136   munmap_section_buffer (&data->str);
17137   munmap_section_buffer (&data->ranges);
17138   munmap_section_buffer (&data->addr);
17139   munmap_section_buffer (&data->frame);
17140   munmap_section_buffer (&data->eh_frame);
17141   munmap_section_buffer (&data->gdb_index);
17142
17143   for (ix = 0;
17144        VEC_iterate (dwarf2_section_info_def, data->types, ix, section);
17145        ++ix)
17146     munmap_section_buffer (section);
17147
17148   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
17149     VEC_free (dwarf2_per_cu_ptr,
17150               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
17151
17152   VEC_free (dwarf2_section_info_def, data->types);
17153
17154   if (data->dwo_files)
17155     free_dwo_files (data->dwo_files, objfile);
17156 }
17157
17158 \f
17159 /* The "save gdb-index" command.  */
17160
17161 /* The contents of the hash table we create when building the string
17162    table.  */
17163 struct strtab_entry
17164 {
17165   offset_type offset;
17166   const char *str;
17167 };
17168
17169 /* Hash function for a strtab_entry.
17170
17171    Function is used only during write_hash_table so no index format backward
17172    compatibility is needed.  */
17173
17174 static hashval_t
17175 hash_strtab_entry (const void *e)
17176 {
17177   const struct strtab_entry *entry = e;
17178   return mapped_index_string_hash (INT_MAX, entry->str);
17179 }
17180
17181 /* Equality function for a strtab_entry.  */
17182
17183 static int
17184 eq_strtab_entry (const void *a, const void *b)
17185 {
17186   const struct strtab_entry *ea = a;
17187   const struct strtab_entry *eb = b;
17188   return !strcmp (ea->str, eb->str);
17189 }
17190
17191 /* Create a strtab_entry hash table.  */
17192
17193 static htab_t
17194 create_strtab (void)
17195 {
17196   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
17197                             xfree, xcalloc, xfree);
17198 }
17199
17200 /* Add a string to the constant pool.  Return the string's offset in
17201    host order.  */
17202
17203 static offset_type
17204 add_string (htab_t table, struct obstack *cpool, const char *str)
17205 {
17206   void **slot;
17207   struct strtab_entry entry;
17208   struct strtab_entry *result;
17209
17210   entry.str = str;
17211   slot = htab_find_slot (table, &entry, INSERT);
17212   if (*slot)
17213     result = *slot;
17214   else
17215     {
17216       result = XNEW (struct strtab_entry);
17217       result->offset = obstack_object_size (cpool);
17218       result->str = str;
17219       obstack_grow_str0 (cpool, str);
17220       *slot = result;
17221     }
17222   return result->offset;
17223 }
17224
17225 /* An entry in the symbol table.  */
17226 struct symtab_index_entry
17227 {
17228   /* The name of the symbol.  */
17229   const char *name;
17230   /* The offset of the name in the constant pool.  */
17231   offset_type index_offset;
17232   /* A sorted vector of the indices of all the CUs that hold an object
17233      of this name.  */
17234   VEC (offset_type) *cu_indices;
17235 };
17236
17237 /* The symbol table.  This is a power-of-2-sized hash table.  */
17238 struct mapped_symtab
17239 {
17240   offset_type n_elements;
17241   offset_type size;
17242   struct symtab_index_entry **data;
17243 };
17244
17245 /* Hash function for a symtab_index_entry.  */
17246
17247 static hashval_t
17248 hash_symtab_entry (const void *e)
17249 {
17250   const struct symtab_index_entry *entry = e;
17251   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
17252                          sizeof (offset_type) * VEC_length (offset_type,
17253                                                             entry->cu_indices),
17254                          0);
17255 }
17256
17257 /* Equality function for a symtab_index_entry.  */
17258
17259 static int
17260 eq_symtab_entry (const void *a, const void *b)
17261 {
17262   const struct symtab_index_entry *ea = a;
17263   const struct symtab_index_entry *eb = b;
17264   int len = VEC_length (offset_type, ea->cu_indices);
17265   if (len != VEC_length (offset_type, eb->cu_indices))
17266     return 0;
17267   return !memcmp (VEC_address (offset_type, ea->cu_indices),
17268                   VEC_address (offset_type, eb->cu_indices),
17269                   sizeof (offset_type) * len);
17270 }
17271
17272 /* Destroy a symtab_index_entry.  */
17273
17274 static void
17275 delete_symtab_entry (void *p)
17276 {
17277   struct symtab_index_entry *entry = p;
17278   VEC_free (offset_type, entry->cu_indices);
17279   xfree (entry);
17280 }
17281
17282 /* Create a hash table holding symtab_index_entry objects.  */
17283
17284 static htab_t
17285 create_symbol_hash_table (void)
17286 {
17287   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
17288                             delete_symtab_entry, xcalloc, xfree);
17289 }
17290
17291 /* Create a new mapped symtab object.  */
17292
17293 static struct mapped_symtab *
17294 create_mapped_symtab (void)
17295 {
17296   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
17297   symtab->n_elements = 0;
17298   symtab->size = 1024;
17299   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
17300   return symtab;
17301 }
17302
17303 /* Destroy a mapped_symtab.  */
17304
17305 static void
17306 cleanup_mapped_symtab (void *p)
17307 {
17308   struct mapped_symtab *symtab = p;
17309   /* The contents of the array are freed when the other hash table is
17310      destroyed.  */
17311   xfree (symtab->data);
17312   xfree (symtab);
17313 }
17314
17315 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
17316    the slot.
17317    
17318    Function is used only during write_hash_table so no index format backward
17319    compatibility is needed.  */
17320
17321 static struct symtab_index_entry **
17322 find_slot (struct mapped_symtab *symtab, const char *name)
17323 {
17324   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
17325
17326   index = hash & (symtab->size - 1);
17327   step = ((hash * 17) & (symtab->size - 1)) | 1;
17328
17329   for (;;)
17330     {
17331       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
17332         return &symtab->data[index];
17333       index = (index + step) & (symtab->size - 1);
17334     }
17335 }
17336
17337 /* Expand SYMTAB's hash table.  */
17338
17339 static void
17340 hash_expand (struct mapped_symtab *symtab)
17341 {
17342   offset_type old_size = symtab->size;
17343   offset_type i;
17344   struct symtab_index_entry **old_entries = symtab->data;
17345
17346   symtab->size *= 2;
17347   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
17348
17349   for (i = 0; i < old_size; ++i)
17350     {
17351       if (old_entries[i])
17352         {
17353           struct symtab_index_entry **slot = find_slot (symtab,
17354                                                         old_entries[i]->name);
17355           *slot = old_entries[i];
17356         }
17357     }
17358
17359   xfree (old_entries);
17360 }
17361
17362 /* Add an entry to SYMTAB.  NAME is the name of the symbol.  CU_INDEX
17363    is the index of the CU in which the symbol appears.  */
17364
17365 static void
17366 add_index_entry (struct mapped_symtab *symtab, const char *name,
17367                  offset_type cu_index)
17368 {
17369   struct symtab_index_entry **slot;
17370
17371   ++symtab->n_elements;
17372   if (4 * symtab->n_elements / 3 >= symtab->size)
17373     hash_expand (symtab);
17374
17375   slot = find_slot (symtab, name);
17376   if (!*slot)
17377     {
17378       *slot = XNEW (struct symtab_index_entry);
17379       (*slot)->name = name;
17380       (*slot)->cu_indices = NULL;
17381     }
17382   /* Don't push an index twice.  Due to how we add entries we only
17383      have to check the last one.  */ 
17384   if (VEC_empty (offset_type, (*slot)->cu_indices)
17385       || VEC_last (offset_type, (*slot)->cu_indices) != cu_index)
17386     VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index);
17387 }
17388
17389 /* Add a vector of indices to the constant pool.  */
17390
17391 static offset_type
17392 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
17393                       struct symtab_index_entry *entry)
17394 {
17395   void **slot;
17396
17397   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
17398   if (!*slot)
17399     {
17400       offset_type len = VEC_length (offset_type, entry->cu_indices);
17401       offset_type val = MAYBE_SWAP (len);
17402       offset_type iter;
17403       int i;
17404
17405       *slot = entry;
17406       entry->index_offset = obstack_object_size (cpool);
17407
17408       obstack_grow (cpool, &val, sizeof (val));
17409       for (i = 0;
17410            VEC_iterate (offset_type, entry->cu_indices, i, iter);
17411            ++i)
17412         {
17413           val = MAYBE_SWAP (iter);
17414           obstack_grow (cpool, &val, sizeof (val));
17415         }
17416     }
17417   else
17418     {
17419       struct symtab_index_entry *old_entry = *slot;
17420       entry->index_offset = old_entry->index_offset;
17421       entry = old_entry;
17422     }
17423   return entry->index_offset;
17424 }
17425
17426 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
17427    constant pool entries going into the obstack CPOOL.  */
17428
17429 static void
17430 write_hash_table (struct mapped_symtab *symtab,
17431                   struct obstack *output, struct obstack *cpool)
17432 {
17433   offset_type i;
17434   htab_t symbol_hash_table;
17435   htab_t str_table;
17436
17437   symbol_hash_table = create_symbol_hash_table ();
17438   str_table = create_strtab ();
17439
17440   /* We add all the index vectors to the constant pool first, to
17441      ensure alignment is ok.  */
17442   for (i = 0; i < symtab->size; ++i)
17443     {
17444       if (symtab->data[i])
17445         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
17446     }
17447
17448   /* Now write out the hash table.  */
17449   for (i = 0; i < symtab->size; ++i)
17450     {
17451       offset_type str_off, vec_off;
17452
17453       if (symtab->data[i])
17454         {
17455           str_off = add_string (str_table, cpool, symtab->data[i]->name);
17456           vec_off = symtab->data[i]->index_offset;
17457         }
17458       else
17459         {
17460           /* While 0 is a valid constant pool index, it is not valid
17461              to have 0 for both offsets.  */
17462           str_off = 0;
17463           vec_off = 0;
17464         }
17465
17466       str_off = MAYBE_SWAP (str_off);
17467       vec_off = MAYBE_SWAP (vec_off);
17468
17469       obstack_grow (output, &str_off, sizeof (str_off));
17470       obstack_grow (output, &vec_off, sizeof (vec_off));
17471     }
17472
17473   htab_delete (str_table);
17474   htab_delete (symbol_hash_table);
17475 }
17476
17477 /* Struct to map psymtab to CU index in the index file.  */
17478 struct psymtab_cu_index_map
17479 {
17480   struct partial_symtab *psymtab;
17481   unsigned int cu_index;
17482 };
17483
17484 static hashval_t
17485 hash_psymtab_cu_index (const void *item)
17486 {
17487   const struct psymtab_cu_index_map *map = item;
17488
17489   return htab_hash_pointer (map->psymtab);
17490 }
17491
17492 static int
17493 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
17494 {
17495   const struct psymtab_cu_index_map *lhs = item_lhs;
17496   const struct psymtab_cu_index_map *rhs = item_rhs;
17497
17498   return lhs->psymtab == rhs->psymtab;
17499 }
17500
17501 /* Helper struct for building the address table.  */
17502 struct addrmap_index_data
17503 {
17504   struct objfile *objfile;
17505   struct obstack *addr_obstack;
17506   htab_t cu_index_htab;
17507
17508   /* Non-zero if the previous_* fields are valid.
17509      We can't write an entry until we see the next entry (since it is only then
17510      that we know the end of the entry).  */
17511   int previous_valid;
17512   /* Index of the CU in the table of all CUs in the index file.  */
17513   unsigned int previous_cu_index;
17514   /* Start address of the CU.  */
17515   CORE_ADDR previous_cu_start;
17516 };
17517
17518 /* Write an address entry to OBSTACK.  */
17519
17520 static void
17521 add_address_entry (struct objfile *objfile, struct obstack *obstack,
17522                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
17523 {
17524   offset_type cu_index_to_write;
17525   char addr[8];
17526   CORE_ADDR baseaddr;
17527
17528   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17529
17530   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
17531   obstack_grow (obstack, addr, 8);
17532   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
17533   obstack_grow (obstack, addr, 8);
17534   cu_index_to_write = MAYBE_SWAP (cu_index);
17535   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
17536 }
17537
17538 /* Worker function for traversing an addrmap to build the address table.  */
17539
17540 static int
17541 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
17542 {
17543   struct addrmap_index_data *data = datap;
17544   struct partial_symtab *pst = obj;
17545
17546   if (data->previous_valid)
17547     add_address_entry (data->objfile, data->addr_obstack,
17548                        data->previous_cu_start, start_addr,
17549                        data->previous_cu_index);
17550
17551   data->previous_cu_start = start_addr;
17552   if (pst != NULL)
17553     {
17554       struct psymtab_cu_index_map find_map, *map;
17555       find_map.psymtab = pst;
17556       map = htab_find (data->cu_index_htab, &find_map);
17557       gdb_assert (map != NULL);
17558       data->previous_cu_index = map->cu_index;
17559       data->previous_valid = 1;
17560     }
17561   else
17562       data->previous_valid = 0;
17563
17564   return 0;
17565 }
17566
17567 /* Write OBJFILE's address map to OBSTACK.
17568    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
17569    in the index file.  */
17570
17571 static void
17572 write_address_map (struct objfile *objfile, struct obstack *obstack,
17573                    htab_t cu_index_htab)
17574 {
17575   struct addrmap_index_data addrmap_index_data;
17576
17577   /* When writing the address table, we have to cope with the fact that
17578      the addrmap iterator only provides the start of a region; we have to
17579      wait until the next invocation to get the start of the next region.  */
17580
17581   addrmap_index_data.objfile = objfile;
17582   addrmap_index_data.addr_obstack = obstack;
17583   addrmap_index_data.cu_index_htab = cu_index_htab;
17584   addrmap_index_data.previous_valid = 0;
17585
17586   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
17587                    &addrmap_index_data);
17588
17589   /* It's highly unlikely the last entry (end address = 0xff...ff)
17590      is valid, but we should still handle it.
17591      The end address is recorded as the start of the next region, but that
17592      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
17593      anyway.  */
17594   if (addrmap_index_data.previous_valid)
17595     add_address_entry (objfile, obstack,
17596                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
17597                        addrmap_index_data.previous_cu_index);
17598 }
17599
17600 /* Add a list of partial symbols to SYMTAB.  */
17601
17602 static void
17603 write_psymbols (struct mapped_symtab *symtab,
17604                 htab_t psyms_seen,
17605                 struct partial_symbol **psymp,
17606                 int count,
17607                 offset_type cu_index,
17608                 int is_static)
17609 {
17610   for (; count-- > 0; ++psymp)
17611     {
17612       void **slot, *lookup;
17613
17614       if (SYMBOL_LANGUAGE (*psymp) == language_ada)
17615         error (_("Ada is not currently supported by the index"));
17616
17617       /* We only want to add a given psymbol once.  However, we also
17618          want to account for whether it is global or static.  So, we
17619          may add it twice, using slightly different values.  */
17620       if (is_static)
17621         {
17622           uintptr_t val = 1 | (uintptr_t) *psymp;
17623
17624           lookup = (void *) val;
17625         }
17626       else
17627         lookup = *psymp;
17628
17629       /* Only add a given psymbol once.  */
17630       slot = htab_find_slot (psyms_seen, lookup, INSERT);
17631       if (!*slot)
17632         {
17633           *slot = lookup;
17634           add_index_entry (symtab, SYMBOL_SEARCH_NAME (*psymp), cu_index);
17635         }
17636     }
17637 }
17638
17639 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
17640    exception if there is an error.  */
17641
17642 static void
17643 write_obstack (FILE *file, struct obstack *obstack)
17644 {
17645   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
17646               file)
17647       != obstack_object_size (obstack))
17648     error (_("couldn't data write to file"));
17649 }
17650
17651 /* Unlink a file if the argument is not NULL.  */
17652
17653 static void
17654 unlink_if_set (void *p)
17655 {
17656   char **filename = p;
17657   if (*filename)
17658     unlink (*filename);
17659 }
17660
17661 /* A helper struct used when iterating over debug_types.  */
17662 struct signatured_type_index_data
17663 {
17664   struct objfile *objfile;
17665   struct mapped_symtab *symtab;
17666   struct obstack *types_list;
17667   htab_t psyms_seen;
17668   int cu_index;
17669 };
17670
17671 /* A helper function that writes a single signatured_type to an
17672    obstack.  */
17673
17674 static int
17675 write_one_signatured_type (void **slot, void *d)
17676 {
17677   struct signatured_type_index_data *info = d;
17678   struct signatured_type *entry = (struct signatured_type *) *slot;
17679   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
17680   struct partial_symtab *psymtab = per_cu->v.psymtab;
17681   gdb_byte val[8];
17682
17683   write_psymbols (info->symtab,
17684                   info->psyms_seen,
17685                   info->objfile->global_psymbols.list
17686                   + psymtab->globals_offset,
17687                   psymtab->n_global_syms, info->cu_index,
17688                   0);
17689   write_psymbols (info->symtab,
17690                   info->psyms_seen,
17691                   info->objfile->static_psymbols.list
17692                   + psymtab->statics_offset,
17693                   psymtab->n_static_syms, info->cu_index,
17694                   1);
17695
17696   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
17697                           entry->per_cu.offset.sect_off);
17698   obstack_grow (info->types_list, val, 8);
17699   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
17700                           entry->type_offset_in_tu.cu_off);
17701   obstack_grow (info->types_list, val, 8);
17702   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
17703   obstack_grow (info->types_list, val, 8);
17704
17705   ++info->cu_index;
17706
17707   return 1;
17708 }
17709
17710 /* Recurse into all "included" dependencies and write their symbols as
17711    if they appeared in this psymtab.  */
17712
17713 static void
17714 recursively_write_psymbols (struct objfile *objfile,
17715                             struct partial_symtab *psymtab,
17716                             struct mapped_symtab *symtab,
17717                             htab_t psyms_seen,
17718                             offset_type cu_index)
17719 {
17720   int i;
17721
17722   for (i = 0; i < psymtab->number_of_dependencies; ++i)
17723     if (psymtab->dependencies[i]->user != NULL)
17724       recursively_write_psymbols (objfile, psymtab->dependencies[i],
17725                                   symtab, psyms_seen, cu_index);
17726
17727   write_psymbols (symtab,
17728                   psyms_seen,
17729                   objfile->global_psymbols.list + psymtab->globals_offset,
17730                   psymtab->n_global_syms, cu_index,
17731                   0);
17732   write_psymbols (symtab,
17733                   psyms_seen,
17734                   objfile->static_psymbols.list + psymtab->statics_offset,
17735                   psymtab->n_static_syms, cu_index,
17736                   1);
17737 }
17738
17739 /* Create an index file for OBJFILE in the directory DIR.  */
17740
17741 static void
17742 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
17743 {
17744   struct cleanup *cleanup;
17745   char *filename, *cleanup_filename;
17746   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
17747   struct obstack cu_list, types_cu_list;
17748   int i;
17749   FILE *out_file;
17750   struct mapped_symtab *symtab;
17751   offset_type val, size_of_contents, total_len;
17752   struct stat st;
17753   htab_t psyms_seen;
17754   htab_t cu_index_htab;
17755   struct psymtab_cu_index_map *psymtab_cu_index_map;
17756
17757   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
17758     return;
17759
17760   if (dwarf2_per_objfile->using_index)
17761     error (_("Cannot use an index to create the index"));
17762
17763   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
17764     error (_("Cannot make an index when the file has multiple .debug_types sections"));
17765
17766   if (stat (objfile->name, &st) < 0)
17767     perror_with_name (objfile->name);
17768
17769   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
17770                      INDEX_SUFFIX, (char *) NULL);
17771   cleanup = make_cleanup (xfree, filename);
17772
17773   out_file = fopen (filename, "wb");
17774   if (!out_file)
17775     error (_("Can't open `%s' for writing"), filename);
17776
17777   cleanup_filename = filename;
17778   make_cleanup (unlink_if_set, &cleanup_filename);
17779
17780   symtab = create_mapped_symtab ();
17781   make_cleanup (cleanup_mapped_symtab, symtab);
17782
17783   obstack_init (&addr_obstack);
17784   make_cleanup_obstack_free (&addr_obstack);
17785
17786   obstack_init (&cu_list);
17787   make_cleanup_obstack_free (&cu_list);
17788
17789   obstack_init (&types_cu_list);
17790   make_cleanup_obstack_free (&types_cu_list);
17791
17792   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
17793                                   NULL, xcalloc, xfree);
17794   make_cleanup_htab_delete (psyms_seen);
17795
17796   /* While we're scanning CU's create a table that maps a psymtab pointer
17797      (which is what addrmap records) to its index (which is what is recorded
17798      in the index file).  This will later be needed to write the address
17799      table.  */
17800   cu_index_htab = htab_create_alloc (100,
17801                                      hash_psymtab_cu_index,
17802                                      eq_psymtab_cu_index,
17803                                      NULL, xcalloc, xfree);
17804   make_cleanup_htab_delete (cu_index_htab);
17805   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
17806     xmalloc (sizeof (struct psymtab_cu_index_map)
17807              * dwarf2_per_objfile->n_comp_units);
17808   make_cleanup (xfree, psymtab_cu_index_map);
17809
17810   /* The CU list is already sorted, so we don't need to do additional
17811      work here.  Also, the debug_types entries do not appear in
17812      all_comp_units, but only in their own hash table.  */
17813   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
17814     {
17815       struct dwarf2_per_cu_data *per_cu
17816         = dwarf2_per_objfile->all_comp_units[i];
17817       struct partial_symtab *psymtab = per_cu->v.psymtab;
17818       gdb_byte val[8];
17819       struct psymtab_cu_index_map *map;
17820       void **slot;
17821
17822       if (psymtab->user == NULL)
17823         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
17824
17825       map = &psymtab_cu_index_map[i];
17826       map->psymtab = psymtab;
17827       map->cu_index = i;
17828       slot = htab_find_slot (cu_index_htab, map, INSERT);
17829       gdb_assert (slot != NULL);
17830       gdb_assert (*slot == NULL);
17831       *slot = map;
17832
17833       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
17834                               per_cu->offset.sect_off);
17835       obstack_grow (&cu_list, val, 8);
17836       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
17837       obstack_grow (&cu_list, val, 8);
17838     }
17839
17840   /* Dump the address map.  */
17841   write_address_map (objfile, &addr_obstack, cu_index_htab);
17842
17843   /* Write out the .debug_type entries, if any.  */
17844   if (dwarf2_per_objfile->signatured_types)
17845     {
17846       struct signatured_type_index_data sig_data;
17847
17848       sig_data.objfile = objfile;
17849       sig_data.symtab = symtab;
17850       sig_data.types_list = &types_cu_list;
17851       sig_data.psyms_seen = psyms_seen;
17852       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
17853       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
17854                               write_one_signatured_type, &sig_data);
17855     }
17856
17857   obstack_init (&constant_pool);
17858   make_cleanup_obstack_free (&constant_pool);
17859   obstack_init (&symtab_obstack);
17860   make_cleanup_obstack_free (&symtab_obstack);
17861   write_hash_table (symtab, &symtab_obstack, &constant_pool);
17862
17863   obstack_init (&contents);
17864   make_cleanup_obstack_free (&contents);
17865   size_of_contents = 6 * sizeof (offset_type);
17866   total_len = size_of_contents;
17867
17868   /* The version number.  */
17869   val = MAYBE_SWAP (6);
17870   obstack_grow (&contents, &val, sizeof (val));
17871
17872   /* The offset of the CU list from the start of the file.  */
17873   val = MAYBE_SWAP (total_len);
17874   obstack_grow (&contents, &val, sizeof (val));
17875   total_len += obstack_object_size (&cu_list);
17876
17877   /* The offset of the types CU list from the start of the file.  */
17878   val = MAYBE_SWAP (total_len);
17879   obstack_grow (&contents, &val, sizeof (val));
17880   total_len += obstack_object_size (&types_cu_list);
17881
17882   /* The offset of the address table from the start of the file.  */
17883   val = MAYBE_SWAP (total_len);
17884   obstack_grow (&contents, &val, sizeof (val));
17885   total_len += obstack_object_size (&addr_obstack);
17886
17887   /* The offset of the symbol table from the start of the file.  */
17888   val = MAYBE_SWAP (total_len);
17889   obstack_grow (&contents, &val, sizeof (val));
17890   total_len += obstack_object_size (&symtab_obstack);
17891
17892   /* The offset of the constant pool from the start of the file.  */
17893   val = MAYBE_SWAP (total_len);
17894   obstack_grow (&contents, &val, sizeof (val));
17895   total_len += obstack_object_size (&constant_pool);
17896
17897   gdb_assert (obstack_object_size (&contents) == size_of_contents);
17898
17899   write_obstack (out_file, &contents);
17900   write_obstack (out_file, &cu_list);
17901   write_obstack (out_file, &types_cu_list);
17902   write_obstack (out_file, &addr_obstack);
17903   write_obstack (out_file, &symtab_obstack);
17904   write_obstack (out_file, &constant_pool);
17905
17906   fclose (out_file);
17907
17908   /* We want to keep the file, so we set cleanup_filename to NULL
17909      here.  See unlink_if_set.  */
17910   cleanup_filename = NULL;
17911
17912   do_cleanups (cleanup);
17913 }
17914
17915 /* Implementation of the `save gdb-index' command.
17916    
17917    Note that the file format used by this command is documented in the
17918    GDB manual.  Any changes here must be documented there.  */
17919
17920 static void
17921 save_gdb_index_command (char *arg, int from_tty)
17922 {
17923   struct objfile *objfile;
17924
17925   if (!arg || !*arg)
17926     error (_("usage: save gdb-index DIRECTORY"));
17927
17928   ALL_OBJFILES (objfile)
17929   {
17930     struct stat st;
17931
17932     /* If the objfile does not correspond to an actual file, skip it.  */
17933     if (stat (objfile->name, &st) < 0)
17934       continue;
17935
17936     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
17937     if (dwarf2_per_objfile)
17938       {
17939         volatile struct gdb_exception except;
17940
17941         TRY_CATCH (except, RETURN_MASK_ERROR)
17942           {
17943             write_psymtabs_to_index (objfile, arg);
17944           }
17945         if (except.reason < 0)
17946           exception_fprintf (gdb_stderr, except,
17947                              _("Error while writing index for `%s': "),
17948                              objfile->name);
17949       }
17950   }
17951 }
17952
17953 \f
17954
17955 int dwarf2_always_disassemble;
17956
17957 static void
17958 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
17959                                 struct cmd_list_element *c, const char *value)
17960 {
17961   fprintf_filtered (file,
17962                     _("Whether to always disassemble "
17963                       "DWARF expressions is %s.\n"),
17964                     value);
17965 }
17966
17967 static void
17968 show_check_physname (struct ui_file *file, int from_tty,
17969                      struct cmd_list_element *c, const char *value)
17970 {
17971   fprintf_filtered (file,
17972                     _("Whether to check \"physname\" is %s.\n"),
17973                     value);
17974 }
17975
17976 void _initialize_dwarf2_read (void);
17977
17978 void
17979 _initialize_dwarf2_read (void)
17980 {
17981   struct cmd_list_element *c;
17982
17983   dwarf2_objfile_data_key
17984     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
17985
17986   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
17987 Set DWARF 2 specific variables.\n\
17988 Configure DWARF 2 variables such as the cache size"),
17989                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
17990                   0/*allow-unknown*/, &maintenance_set_cmdlist);
17991
17992   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
17993 Show DWARF 2 specific variables\n\
17994 Show DWARF 2 variables such as the cache size"),
17995                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
17996                   0/*allow-unknown*/, &maintenance_show_cmdlist);
17997
17998   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
17999                             &dwarf2_max_cache_age, _("\
18000 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
18001 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
18002 A higher limit means that cached compilation units will be stored\n\
18003 in memory longer, and more total memory will be used.  Zero disables\n\
18004 caching, which can slow down startup."),
18005                             NULL,
18006                             show_dwarf2_max_cache_age,
18007                             &set_dwarf2_cmdlist,
18008                             &show_dwarf2_cmdlist);
18009
18010   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
18011                            &dwarf2_always_disassemble, _("\
18012 Set whether `info address' always disassembles DWARF expressions."), _("\
18013 Show whether `info address' always disassembles DWARF expressions."), _("\
18014 When enabled, DWARF expressions are always printed in an assembly-like\n\
18015 syntax.  When disabled, expressions will be printed in a more\n\
18016 conversational style, when possible."),
18017                            NULL,
18018                            show_dwarf2_always_disassemble,
18019                            &set_dwarf2_cmdlist,
18020                            &show_dwarf2_cmdlist);
18021
18022   add_setshow_zinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
18023 Set debugging of the dwarf2 DIE reader."), _("\
18024 Show debugging of the dwarf2 DIE reader."), _("\
18025 When enabled (non-zero), DIEs are dumped after they are read in.\n\
18026 The value is the maximum depth to print."),
18027                             NULL,
18028                             NULL,
18029                             &setdebuglist, &showdebuglist);
18030
18031   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
18032 Set cross-checking of \"physname\" code against demangler."), _("\
18033 Show cross-checking of \"physname\" code against demangler."), _("\
18034 When enabled, GDB's internal \"physname\" code is checked against\n\
18035 the demangler."),
18036                            NULL, show_check_physname,
18037                            &setdebuglist, &showdebuglist);
18038
18039   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
18040                _("\
18041 Save a gdb-index file.\n\
18042 Usage: save gdb-index DIRECTORY"),
18043                &save_cmdlist);
18044   set_cmd_completer (c, filename_completer);
18045 }