* dwarf2read.c (recursively_find_pc_sect_symtab): Initialize "s"
[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 of producer_is_gxx_lt_4_6.
433      CHECKED_PRODUCER is set if PRODUCER_IS_GXX_LT_4_6 is valid.  This
434      information is cached because profiling CU expansion showed
435      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
439   /* Non-zero if DW_AT_addr_base was found.
440      Used when processing DWO files.  */
441   unsigned int have_addr_base : 1;
442 };
443
444 /* Persistent data held for a compilation unit, even when not
445    processing it.  We put a pointer to this structure in the
446    read_symtab_private field of the psymtab.  */
447
448 struct dwarf2_per_cu_data
449 {
450   /* The start offset and length of this compilation unit.  2**29-1
451      bytes should suffice to store the length of any compilation unit
452      - if it doesn't, GDB will fall over anyway.
453      NOTE: Unlike comp_unit_head.length, this length includes
454      initial_length_size.
455      If the DIE refers to a DWO file, this is always of the original die,
456      not the DWO file.  */
457   sect_offset offset;
458   unsigned int length : 29;
459
460   /* Flag indicating this compilation unit will be read in before
461      any of the current compilation units are processed.  */
462   unsigned int queued : 1;
463
464   /* This flag will be set when reading partial DIEs if we need to load
465      absolutely all DIEs for this compilation unit, instead of just the ones
466      we think are interesting.  It gets set if we look for a DIE in the
467      hash table and don't find it.  */
468   unsigned int load_all_dies : 1;
469
470   /* Non-zero if this CU is from .debug_types.  */
471   unsigned int is_debug_types : 1;
472
473   /* The section this CU/TU lives in.
474      If the DIE refers to a DWO file, this is always the original die,
475      not the DWO file.  */
476   struct dwarf2_section_info *info_or_types_section;
477
478   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
479      of the CU cache it gets reset to NULL again.  */
480   struct dwarf2_cu *cu;
481
482   /* The corresponding objfile.
483      Normally we can get the objfile from dwarf2_per_objfile.
484      However we can enter this file with just a "per_cu" handle.  */
485   struct objfile *objfile;
486
487   /* When using partial symbol tables, the 'psymtab' field is active.
488      Otherwise the 'quick' field is active.  */
489   union
490   {
491     /* The partial symbol table associated with this compilation unit,
492        or NULL for unread partial units.  */
493     struct partial_symtab *psymtab;
494
495     /* Data needed by the "quick" functions.  */
496     struct dwarf2_per_cu_quick_data *quick;
497   } v;
498
499   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
500      while reading psymtabs, used to compute the psymtab dependencies,
501      and then cleared.  Then it is filled in again while reading full
502      symbols, and only deleted when the objfile is destroyed.  */
503   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
504 };
505
506 /* Entry in the signatured_types hash table.  */
507
508 struct signatured_type
509 {
510   /* The type's signature.  */
511   ULONGEST signature;
512
513   /* Offset in the TU of the type's DIE, as read from the TU header.
514      If the definition lives in a DWO file, this value is unusable.  */
515   cu_offset type_offset_in_tu;
516
517   /* Offset in the section of the type's DIE.
518      If the definition lives in a DWO file, this is the offset in the
519      .debug_types.dwo section.
520      The value is zero until the actual value is known.
521      Zero is otherwise not a valid section offset.  */
522   sect_offset type_offset_in_section;
523
524   /* The CU(/TU) of this type.  */
525   struct dwarf2_per_cu_data per_cu;
526 };
527
528 /* These sections are what may appear in a "dwo" file.  */
529
530 struct dwo_sections
531 {
532   struct dwarf2_section_info abbrev;
533   struct dwarf2_section_info info;
534   struct dwarf2_section_info line;
535   struct dwarf2_section_info loc;
536   struct dwarf2_section_info str;
537   struct dwarf2_section_info str_offsets;
538   VEC (dwarf2_section_info_def) *types;
539 };
540
541 /* Common bits of DWO CUs/TUs.  */
542
543 struct dwo_unit
544 {
545   /* Backlink to the containing struct dwo_file.  */
546   struct dwo_file *dwo_file;
547
548   /* The "id" that distinguishes this CU/TU.
549      .debug_info calls this "dwo_id", .debug_types calls this "signature".
550      Since signatures came first, we stick with it for consistency.  */
551   ULONGEST signature;
552
553   /* The section this CU/TU lives in, in the DWO file.  */
554   struct dwarf2_section_info *info_or_types_section;
555
556   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
557   sect_offset offset;
558   unsigned int length;
559
560   /* For types, offset in the type's DIE of the type defined by this TU.  */
561   cu_offset type_offset_in_tu;
562 };
563
564 /* Data for one DWO file.  */
565
566 struct dwo_file
567 {
568   /* The DW_AT_GNU_dwo_name attribute.
569      We don't manage space for this, it's an attribute.  */
570   const char *dwo_name;
571
572   /* The bfd, when the file is open.  Otherwise this is NULL.  */
573   bfd *dwo_bfd;
574
575   /* Section info for this file.  */
576   struct dwo_sections sections;
577
578   /* Table of CUs in the file.
579      Each element is a struct dwo_unit.  */
580   htab_t cus;
581
582   /* Table of TUs in the file.
583      Each element is a struct dwo_unit.  */
584   htab_t tus;
585 };
586
587 /* Struct used to pass misc. parameters to read_die_and_children, et
588    al.  which are used for both .debug_info and .debug_types dies.
589    All parameters here are unchanging for the life of the call.  This
590    struct exists to abstract away the constant parameters of die reading.  */
591
592 struct die_reader_specs
593 {
594   /* die_section->asection->owner.  */
595   bfd* abfd;
596
597   /* The CU of the DIE we are parsing.  */
598   struct dwarf2_cu *cu;
599
600   /* Non-NULL if reading a DWO file.  */
601   struct dwo_file *dwo_file;
602
603   /* The section the die comes from.
604      This is either .debug_info or .debug_types, or the .dwo variants.  */
605   struct dwarf2_section_info *die_section;
606
607   /* die_section->buffer.  */
608   gdb_byte *buffer;
609 };
610
611 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
612 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
613                                       gdb_byte *info_ptr,
614                                       struct die_info *comp_unit_die,
615                                       int has_children,
616                                       void *data);
617
618 /* The line number information for a compilation unit (found in the
619    .debug_line section) begins with a "statement program header",
620    which contains the following information.  */
621 struct line_header
622 {
623   unsigned int total_length;
624   unsigned short version;
625   unsigned int header_length;
626   unsigned char minimum_instruction_length;
627   unsigned char maximum_ops_per_instruction;
628   unsigned char default_is_stmt;
629   int line_base;
630   unsigned char line_range;
631   unsigned char opcode_base;
632
633   /* standard_opcode_lengths[i] is the number of operands for the
634      standard opcode whose value is i.  This means that
635      standard_opcode_lengths[0] is unused, and the last meaningful
636      element is standard_opcode_lengths[opcode_base - 1].  */
637   unsigned char *standard_opcode_lengths;
638
639   /* The include_directories table.  NOTE!  These strings are not
640      allocated with xmalloc; instead, they are pointers into
641      debug_line_buffer.  If you try to free them, `free' will get
642      indigestion.  */
643   unsigned int num_include_dirs, include_dirs_size;
644   char **include_dirs;
645
646   /* The file_names table.  NOTE!  These strings are not allocated
647      with xmalloc; instead, they are pointers into debug_line_buffer.
648      Don't try to free them directly.  */
649   unsigned int num_file_names, file_names_size;
650   struct file_entry
651   {
652     char *name;
653     unsigned int dir_index;
654     unsigned int mod_time;
655     unsigned int length;
656     int included_p; /* Non-zero if referenced by the Line Number Program.  */
657     struct symtab *symtab; /* The associated symbol table, if any.  */
658   } *file_names;
659
660   /* The start and end of the statement program following this
661      header.  These point into dwarf2_per_objfile->line_buffer.  */
662   gdb_byte *statement_program_start, *statement_program_end;
663 };
664
665 /* When we construct a partial symbol table entry we only
666    need this much information.  */
667 struct partial_die_info
668   {
669     /* Offset of this DIE.  */
670     sect_offset offset;
671
672     /* DWARF-2 tag for this DIE.  */
673     ENUM_BITFIELD(dwarf_tag) tag : 16;
674
675     /* Assorted flags describing the data found in this DIE.  */
676     unsigned int has_children : 1;
677     unsigned int is_external : 1;
678     unsigned int is_declaration : 1;
679     unsigned int has_type : 1;
680     unsigned int has_specification : 1;
681     unsigned int has_pc_info : 1;
682     unsigned int may_be_inlined : 1;
683
684     /* Flag set if the SCOPE field of this structure has been
685        computed.  */
686     unsigned int scope_set : 1;
687
688     /* Flag set if the DIE has a byte_size attribute.  */
689     unsigned int has_byte_size : 1;
690
691     /* Flag set if any of the DIE's children are template arguments.  */
692     unsigned int has_template_arguments : 1;
693
694     /* Flag set if fixup_partial_die has been called on this die.  */
695     unsigned int fixup_called : 1;
696
697     /* The name of this DIE.  Normally the value of DW_AT_name, but
698        sometimes a default name for unnamed DIEs.  */
699     char *name;
700
701     /* The linkage name, if present.  */
702     const char *linkage_name;
703
704     /* The scope to prepend to our children.  This is generally
705        allocated on the comp_unit_obstack, so will disappear
706        when this compilation unit leaves the cache.  */
707     char *scope;
708
709     /* Some data associated with the partial DIE.  The tag determines
710        which field is live.  */
711     union
712     {
713       /* The location description associated with this DIE, if any.  */
714       struct dwarf_block *locdesc;
715       /* The offset of an import, for DW_TAG_imported_unit.  */
716       sect_offset offset;
717     } d;
718
719     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
720     CORE_ADDR lowpc;
721     CORE_ADDR highpc;
722
723     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
724        DW_AT_sibling, if any.  */
725     /* NOTE: This member isn't strictly necessary, read_partial_die could
726        return DW_AT_sibling values to its caller load_partial_dies.  */
727     gdb_byte *sibling;
728
729     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
730        DW_AT_specification (or DW_AT_abstract_origin or
731        DW_AT_extension).  */
732     sect_offset spec_offset;
733
734     /* Pointers to this DIE's parent, first child, and next sibling,
735        if any.  */
736     struct partial_die_info *die_parent, *die_child, *die_sibling;
737   };
738
739 /* This data structure holds the information of an abbrev.  */
740 struct abbrev_info
741   {
742     unsigned int number;        /* number identifying abbrev */
743     enum dwarf_tag tag;         /* dwarf tag */
744     unsigned short has_children;                /* boolean */
745     unsigned short num_attrs;   /* number of attributes */
746     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
747     struct abbrev_info *next;   /* next in chain */
748   };
749
750 struct attr_abbrev
751   {
752     ENUM_BITFIELD(dwarf_attribute) name : 16;
753     ENUM_BITFIELD(dwarf_form) form : 16;
754   };
755
756 /* Attributes have a name and a value.  */
757 struct attribute
758   {
759     ENUM_BITFIELD(dwarf_attribute) name : 16;
760     ENUM_BITFIELD(dwarf_form) form : 15;
761
762     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
763        field should be in u.str (existing only for DW_STRING) but it is kept
764        here for better struct attribute alignment.  */
765     unsigned int string_is_canonical : 1;
766
767     union
768       {
769         char *str;
770         struct dwarf_block *blk;
771         ULONGEST unsnd;
772         LONGEST snd;
773         CORE_ADDR addr;
774         struct signatured_type *signatured_type;
775       }
776     u;
777   };
778
779 /* This data structure holds a complete die structure.  */
780 struct die_info
781   {
782     /* DWARF-2 tag for this DIE.  */
783     ENUM_BITFIELD(dwarf_tag) tag : 16;
784
785     /* Number of attributes */
786     unsigned char num_attrs;
787
788     /* True if we're presently building the full type name for the
789        type derived from this DIE.  */
790     unsigned char building_fullname : 1;
791
792     /* Abbrev number */
793     unsigned int abbrev;
794
795     /* Offset in .debug_info or .debug_types section.  */
796     sect_offset offset;
797
798     /* The dies in a compilation unit form an n-ary tree.  PARENT
799        points to this die's parent; CHILD points to the first child of
800        this node; and all the children of a given node are chained
801        together via their SIBLING fields.  */
802     struct die_info *child;     /* Its first child, if any.  */
803     struct die_info *sibling;   /* Its next sibling, if any.  */
804     struct die_info *parent;    /* Its parent, if any.  */
805
806     /* An array of attributes, with NUM_ATTRS elements.  There may be
807        zero, but it's not common and zero-sized arrays are not
808        sufficiently portable C.  */
809     struct attribute attrs[1];
810   };
811
812 /* Get at parts of an attribute structure.  */
813
814 #define DW_STRING(attr)    ((attr)->u.str)
815 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
816 #define DW_UNSND(attr)     ((attr)->u.unsnd)
817 #define DW_BLOCK(attr)     ((attr)->u.blk)
818 #define DW_SND(attr)       ((attr)->u.snd)
819 #define DW_ADDR(attr)      ((attr)->u.addr)
820 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
821
822 /* Blocks are a bunch of untyped bytes.  */
823 struct dwarf_block
824   {
825     unsigned int size;
826
827     /* Valid only if SIZE is not zero.  */
828     gdb_byte *data;
829   };
830
831 #ifndef ATTR_ALLOC_CHUNK
832 #define ATTR_ALLOC_CHUNK 4
833 #endif
834
835 /* Allocate fields for structs, unions and enums in this size.  */
836 #ifndef DW_FIELD_ALLOC_CHUNK
837 #define DW_FIELD_ALLOC_CHUNK 4
838 #endif
839
840 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
841    but this would require a corresponding change in unpack_field_as_long
842    and friends.  */
843 static int bits_per_byte = 8;
844
845 /* The routines that read and process dies for a C struct or C++ class
846    pass lists of data member fields and lists of member function fields
847    in an instance of a field_info structure, as defined below.  */
848 struct field_info
849   {
850     /* List of data member and baseclasses fields.  */
851     struct nextfield
852       {
853         struct nextfield *next;
854         int accessibility;
855         int virtuality;
856         struct field field;
857       }
858      *fields, *baseclasses;
859
860     /* Number of fields (including baseclasses).  */
861     int nfields;
862
863     /* Number of baseclasses.  */
864     int nbaseclasses;
865
866     /* Set if the accesibility of one of the fields is not public.  */
867     int non_public_fields;
868
869     /* Member function fields array, entries are allocated in the order they
870        are encountered in the object file.  */
871     struct nextfnfield
872       {
873         struct nextfnfield *next;
874         struct fn_field fnfield;
875       }
876      *fnfields;
877
878     /* Member function fieldlist array, contains name of possibly overloaded
879        member function, number of overloaded member functions and a pointer
880        to the head of the member function field chain.  */
881     struct fnfieldlist
882       {
883         char *name;
884         int length;
885         struct nextfnfield *head;
886       }
887      *fnfieldlists;
888
889     /* Number of entries in the fnfieldlists array.  */
890     int nfnfields;
891
892     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
893        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
894     struct typedef_field_list
895       {
896         struct typedef_field field;
897         struct typedef_field_list *next;
898       }
899     *typedef_field_list;
900     unsigned typedef_field_list_count;
901   };
902
903 /* One item on the queue of compilation units to read in full symbols
904    for.  */
905 struct dwarf2_queue_item
906 {
907   struct dwarf2_per_cu_data *per_cu;
908   enum language pretend_language;
909   struct dwarf2_queue_item *next;
910 };
911
912 /* The current queue.  */
913 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
914
915 /* Loaded secondary compilation units are kept in memory until they
916    have not been referenced for the processing of this many
917    compilation units.  Set this to zero to disable caching.  Cache
918    sizes of up to at least twenty will improve startup time for
919    typical inter-CU-reference binaries, at an obvious memory cost.  */
920 static int dwarf2_max_cache_age = 5;
921 static void
922 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
923                            struct cmd_list_element *c, const char *value)
924 {
925   fprintf_filtered (file, _("The upper bound on the age of cached "
926                             "dwarf2 compilation units is %s.\n"),
927                     value);
928 }
929
930
931 /* Various complaints about symbol reading that don't abort the process.  */
932
933 static void
934 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
935 {
936   complaint (&symfile_complaints,
937              _("statement list doesn't fit in .debug_line section"));
938 }
939
940 static void
941 dwarf2_debug_line_missing_file_complaint (void)
942 {
943   complaint (&symfile_complaints,
944              _(".debug_line section has line data without a file"));
945 }
946
947 static void
948 dwarf2_debug_line_missing_end_sequence_complaint (void)
949 {
950   complaint (&symfile_complaints,
951              _(".debug_line section has line "
952                "program sequence without an end"));
953 }
954
955 static void
956 dwarf2_complex_location_expr_complaint (void)
957 {
958   complaint (&symfile_complaints, _("location expression too complex"));
959 }
960
961 static void
962 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
963                                               int arg3)
964 {
965   complaint (&symfile_complaints,
966              _("const value length mismatch for '%s', got %d, expected %d"),
967              arg1, arg2, arg3);
968 }
969
970 static void
971 dwarf2_macros_too_long_complaint (struct dwarf2_section_info *section)
972 {
973   complaint (&symfile_complaints,
974              _("macro info runs off end of `%s' section"),
975              section->asection->name);
976 }
977
978 static void
979 dwarf2_macro_malformed_definition_complaint (const char *arg1)
980 {
981   complaint (&symfile_complaints,
982              _("macro debug info contains a "
983                "malformed macro definition:\n`%s'"),
984              arg1);
985 }
986
987 static void
988 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
989 {
990   complaint (&symfile_complaints,
991              _("invalid attribute class or form for '%s' in '%s'"),
992              arg1, arg2);
993 }
994
995 /* local function prototypes */
996
997 static void dwarf2_locate_sections (bfd *, asection *, void *);
998
999 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1000                                            struct objfile *);
1001
1002 static void dwarf2_find_base_address (struct die_info *die,
1003                                       struct dwarf2_cu *cu);
1004
1005 static void dwarf2_build_psymtabs_hard (struct objfile *);
1006
1007 static void scan_partial_symbols (struct partial_die_info *,
1008                                   CORE_ADDR *, CORE_ADDR *,
1009                                   int, struct dwarf2_cu *);
1010
1011 static void add_partial_symbol (struct partial_die_info *,
1012                                 struct dwarf2_cu *);
1013
1014 static void add_partial_namespace (struct partial_die_info *pdi,
1015                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1016                                    int need_pc, struct dwarf2_cu *cu);
1017
1018 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1019                                 CORE_ADDR *highpc, int need_pc,
1020                                 struct dwarf2_cu *cu);
1021
1022 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1023                                      struct dwarf2_cu *cu);
1024
1025 static void add_partial_subprogram (struct partial_die_info *pdi,
1026                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1027                                     int need_pc, struct dwarf2_cu *cu);
1028
1029 static void dwarf2_psymtab_to_symtab (struct partial_symtab *);
1030
1031 static void psymtab_to_symtab_1 (struct partial_symtab *);
1032
1033 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1034                                  struct dwarf2_section_info *);
1035
1036 static void dwarf2_free_abbrev_table (void *);
1037
1038 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1039
1040 static struct abbrev_info *peek_die_abbrev (gdb_byte *, unsigned int *,
1041                                             struct dwarf2_cu *);
1042
1043 static struct abbrev_info *dwarf2_lookup_abbrev (unsigned int,
1044                                                  struct dwarf2_cu *);
1045
1046 static struct partial_die_info *load_partial_dies
1047   (const struct die_reader_specs *, gdb_byte *, int);
1048
1049 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1050                                    struct partial_die_info *,
1051                                    struct abbrev_info *,
1052                                    unsigned int,
1053                                    gdb_byte *);
1054
1055 static struct partial_die_info *find_partial_die (sect_offset,
1056                                                   struct dwarf2_cu *);
1057
1058 static void fixup_partial_die (struct partial_die_info *,
1059                                struct dwarf2_cu *);
1060
1061 static gdb_byte *read_attribute (const struct die_reader_specs *,
1062                                  struct attribute *, struct attr_abbrev *,
1063                                  gdb_byte *);
1064
1065 static unsigned int read_1_byte (bfd *, gdb_byte *);
1066
1067 static int read_1_signed_byte (bfd *, gdb_byte *);
1068
1069 static unsigned int read_2_bytes (bfd *, gdb_byte *);
1070
1071 static unsigned int read_4_bytes (bfd *, gdb_byte *);
1072
1073 static ULONGEST read_8_bytes (bfd *, gdb_byte *);
1074
1075 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1076                                unsigned int *);
1077
1078 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1079
1080 static LONGEST read_checked_initial_length_and_offset
1081   (bfd *, gdb_byte *, const struct comp_unit_head *,
1082    unsigned int *, unsigned int *);
1083
1084 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1085                             unsigned int *);
1086
1087 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1088
1089 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1090
1091 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1092
1093 static char *read_indirect_string (bfd *, gdb_byte *,
1094                                    const struct comp_unit_head *,
1095                                    unsigned int *);
1096
1097 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1098
1099 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1100
1101 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1102                                               unsigned int *);
1103
1104 static char *read_str_index (const struct die_reader_specs *reader,
1105                              struct dwarf2_cu *cu, ULONGEST str_index);
1106
1107 static gdb_byte *skip_leb128 (bfd *, gdb_byte *);
1108
1109 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1110
1111 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1112                                       struct dwarf2_cu *);
1113
1114 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1115                                                 unsigned int,
1116                                                 struct dwarf2_cu *);
1117
1118 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1119                                struct dwarf2_cu *cu);
1120
1121 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1122
1123 static struct die_info *die_specification (struct die_info *die,
1124                                            struct dwarf2_cu **);
1125
1126 static void free_line_header (struct line_header *lh);
1127
1128 static void add_file_name (struct line_header *, char *, unsigned int,
1129                            unsigned int, unsigned int);
1130
1131 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1132                                                      struct dwarf2_cu *cu);
1133
1134 static void dwarf_decode_lines (struct line_header *, const char *,
1135                                 struct dwarf2_cu *, struct partial_symtab *,
1136                                 int);
1137
1138 static void dwarf2_start_subfile (char *, const char *, const char *);
1139
1140 static struct symbol *new_symbol (struct die_info *, struct type *,
1141                                   struct dwarf2_cu *);
1142
1143 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1144                                        struct dwarf2_cu *, struct symbol *);
1145
1146 static void dwarf2_const_value (struct attribute *, struct symbol *,
1147                                 struct dwarf2_cu *);
1148
1149 static void dwarf2_const_value_attr (struct attribute *attr,
1150                                      struct type *type,
1151                                      const char *name,
1152                                      struct obstack *obstack,
1153                                      struct dwarf2_cu *cu, LONGEST *value,
1154                                      gdb_byte **bytes,
1155                                      struct dwarf2_locexpr_baton **baton);
1156
1157 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1158
1159 static int need_gnat_info (struct dwarf2_cu *);
1160
1161 static struct type *die_descriptive_type (struct die_info *,
1162                                           struct dwarf2_cu *);
1163
1164 static void set_descriptive_type (struct type *, struct die_info *,
1165                                   struct dwarf2_cu *);
1166
1167 static struct type *die_containing_type (struct die_info *,
1168                                          struct dwarf2_cu *);
1169
1170 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1171                                      struct dwarf2_cu *);
1172
1173 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1174
1175 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1176
1177 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1178
1179 static char *typename_concat (struct obstack *obs, const char *prefix,
1180                               const char *suffix, int physname,
1181                               struct dwarf2_cu *cu);
1182
1183 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1184
1185 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1186
1187 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1188
1189 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1190
1191 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1192
1193 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1194                                struct dwarf2_cu *, struct partial_symtab *);
1195
1196 static int dwarf2_get_pc_bounds (struct die_info *,
1197                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1198                                  struct partial_symtab *);
1199
1200 static void get_scope_pc_bounds (struct die_info *,
1201                                  CORE_ADDR *, CORE_ADDR *,
1202                                  struct dwarf2_cu *);
1203
1204 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1205                                         CORE_ADDR, struct dwarf2_cu *);
1206
1207 static void dwarf2_add_field (struct field_info *, struct die_info *,
1208                               struct dwarf2_cu *);
1209
1210 static void dwarf2_attach_fields_to_type (struct field_info *,
1211                                           struct type *, struct dwarf2_cu *);
1212
1213 static void dwarf2_add_member_fn (struct field_info *,
1214                                   struct die_info *, struct type *,
1215                                   struct dwarf2_cu *);
1216
1217 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1218                                              struct type *,
1219                                              struct dwarf2_cu *);
1220
1221 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1222
1223 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1224
1225 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1226
1227 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1228
1229 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1230
1231 static struct type *read_module_type (struct die_info *die,
1232                                       struct dwarf2_cu *cu);
1233
1234 static const char *namespace_name (struct die_info *die,
1235                                    int *is_anonymous, struct dwarf2_cu *);
1236
1237 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1238
1239 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1240
1241 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1242                                                        struct dwarf2_cu *);
1243
1244 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1245                                                gdb_byte *info_ptr,
1246                                                gdb_byte **new_info_ptr,
1247                                                struct die_info *parent);
1248
1249 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1250                                                gdb_byte *info_ptr,
1251                                                gdb_byte **new_info_ptr,
1252                                                struct die_info *parent);
1253
1254 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1255                                   struct die_info **, gdb_byte *, int *, int);
1256
1257 static gdb_byte *read_full_die (const struct die_reader_specs *,
1258                                 struct die_info **, gdb_byte *, int *);
1259
1260 static void process_die (struct die_info *, struct dwarf2_cu *);
1261
1262 static char *dwarf2_canonicalize_name (char *, struct dwarf2_cu *,
1263                                        struct obstack *);
1264
1265 static char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1266
1267 static const char *dwarf2_full_name (char *name,
1268                                      struct die_info *die,
1269                                      struct dwarf2_cu *cu);
1270
1271 static struct die_info *dwarf2_extension (struct die_info *die,
1272                                           struct dwarf2_cu **);
1273
1274 static const char *dwarf_tag_name (unsigned int);
1275
1276 static const char *dwarf_attr_name (unsigned int);
1277
1278 static const char *dwarf_form_name (unsigned int);
1279
1280 static char *dwarf_bool_name (unsigned int);
1281
1282 static const char *dwarf_type_encoding_name (unsigned int);
1283
1284 static struct die_info *sibling_die (struct die_info *);
1285
1286 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1287
1288 static void dump_die_for_error (struct die_info *);
1289
1290 static void dump_die_1 (struct ui_file *, int level, int max_level,
1291                         struct die_info *);
1292
1293 /*static*/ void dump_die (struct die_info *, int max_level);
1294
1295 static void store_in_ref_table (struct die_info *,
1296                                 struct dwarf2_cu *);
1297
1298 static int is_ref_attr (struct attribute *);
1299
1300 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1301
1302 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1303
1304 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1305                                                struct attribute *,
1306                                                struct dwarf2_cu **);
1307
1308 static struct die_info *follow_die_ref (struct die_info *,
1309                                         struct attribute *,
1310                                         struct dwarf2_cu **);
1311
1312 static struct die_info *follow_die_sig (struct die_info *,
1313                                         struct attribute *,
1314                                         struct dwarf2_cu **);
1315
1316 static struct signatured_type *lookup_signatured_type_at_offset
1317     (struct objfile *objfile,
1318      struct dwarf2_section_info *section, sect_offset offset);
1319
1320 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1321
1322 static void read_signatured_type (struct signatured_type *);
1323
1324 /* memory allocation interface */
1325
1326 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1327
1328 static struct abbrev_info *dwarf_alloc_abbrev (struct dwarf2_cu *);
1329
1330 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1331
1332 static void dwarf_decode_macros (struct line_header *, unsigned int,
1333                                  char *, bfd *, struct dwarf2_cu *,
1334                                  struct dwarf2_section_info *,
1335                                  int, const char *);
1336
1337 static int attr_form_is_block (struct attribute *);
1338
1339 static int attr_form_is_section_offset (struct attribute *);
1340
1341 static int attr_form_is_constant (struct attribute *);
1342
1343 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1344                                    struct dwarf2_loclist_baton *baton,
1345                                    struct attribute *attr);
1346
1347 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1348                                          struct symbol *sym,
1349                                          struct dwarf2_cu *cu);
1350
1351 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1352                                gdb_byte *info_ptr,
1353                                struct abbrev_info *abbrev);
1354
1355 static void free_stack_comp_unit (void *);
1356
1357 static hashval_t partial_die_hash (const void *item);
1358
1359 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1360
1361 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1362   (sect_offset offset, struct objfile *objfile);
1363
1364 static void init_one_comp_unit (struct dwarf2_cu *cu,
1365                                 struct dwarf2_per_cu_data *per_cu);
1366
1367 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1368                                    struct die_info *comp_unit_die,
1369                                    enum language pretend_language);
1370
1371 static void free_heap_comp_unit (void *);
1372
1373 static void free_cached_comp_units (void *);
1374
1375 static void age_cached_comp_units (void);
1376
1377 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1378
1379 static struct type *set_die_type (struct die_info *, struct type *,
1380                                   struct dwarf2_cu *);
1381
1382 static void create_all_comp_units (struct objfile *);
1383
1384 static int create_all_type_units (struct objfile *);
1385
1386 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1387                                  enum language);
1388
1389 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1390                                     enum language);
1391
1392 static void dwarf2_add_dependence (struct dwarf2_cu *,
1393                                    struct dwarf2_per_cu_data *);
1394
1395 static void dwarf2_mark (struct dwarf2_cu *);
1396
1397 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1398
1399 static struct type *get_die_type_at_offset (sect_offset,
1400                                             struct dwarf2_per_cu_data *per_cu);
1401
1402 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1403
1404 static void dwarf2_release_queue (void *dummy);
1405
1406 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1407                              enum language pretend_language);
1408
1409 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1410                                   struct dwarf2_per_cu_data *per_cu,
1411                                   enum language pretend_language);
1412
1413 static void process_queue (void);
1414
1415 static void find_file_and_directory (struct die_info *die,
1416                                      struct dwarf2_cu *cu,
1417                                      char **name, char **comp_dir);
1418
1419 static char *file_full_name (int file, struct line_header *lh,
1420                              const char *comp_dir);
1421
1422 static gdb_byte *read_and_check_comp_unit_head
1423   (struct comp_unit_head *header,
1424    struct dwarf2_section_info *section, gdb_byte *info_ptr,
1425    int is_debug_types_section);
1426
1427 static void init_cutu_and_read_dies
1428   (struct dwarf2_per_cu_data *this_cu, int use_existing_cu, int keep,
1429    die_reader_func_ftype *die_reader_func, void *data);
1430
1431 static void init_cutu_and_read_dies_simple
1432   (struct dwarf2_per_cu_data *this_cu,
1433    die_reader_func_ftype *die_reader_func, void *data);
1434
1435 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1436
1437 static void process_psymtab_comp_unit (struct dwarf2_per_cu_data *, int);
1438
1439 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1440
1441 static struct dwo_unit *lookup_dwo_comp_unit
1442   (struct dwarf2_per_cu_data *, char *, const char *, ULONGEST);
1443
1444 static struct dwo_unit *lookup_dwo_type_unit
1445   (struct signatured_type *, char *, const char *);
1446
1447 static void free_dwo_file_cleanup (void *);
1448
1449 static void munmap_section_buffer (struct dwarf2_section_info *);
1450
1451 static void process_cu_includes (void);
1452
1453 #if WORDS_BIGENDIAN
1454
1455 /* Convert VALUE between big- and little-endian.  */
1456 static offset_type
1457 byte_swap (offset_type value)
1458 {
1459   offset_type result;
1460
1461   result = (value & 0xff) << 24;
1462   result |= (value & 0xff00) << 8;
1463   result |= (value & 0xff0000) >> 8;
1464   result |= (value & 0xff000000) >> 24;
1465   return result;
1466 }
1467
1468 #define MAYBE_SWAP(V)  byte_swap (V)
1469
1470 #else
1471 #define MAYBE_SWAP(V) (V)
1472 #endif /* WORDS_BIGENDIAN */
1473
1474 /* The suffix for an index file.  */
1475 #define INDEX_SUFFIX ".gdb-index"
1476
1477 static const char *dwarf2_physname (char *name, struct die_info *die,
1478                                     struct dwarf2_cu *cu);
1479
1480 /* Try to locate the sections we need for DWARF 2 debugging
1481    information and return true if we have enough to do something.
1482    NAMES points to the dwarf2 section names, or is NULL if the standard
1483    ELF names are used.  */
1484
1485 int
1486 dwarf2_has_info (struct objfile *objfile,
1487                  const struct dwarf2_debug_sections *names)
1488 {
1489   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1490   if (!dwarf2_per_objfile)
1491     {
1492       /* Initialize per-objfile state.  */
1493       struct dwarf2_per_objfile *data
1494         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1495
1496       memset (data, 0, sizeof (*data));
1497       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1498       dwarf2_per_objfile = data;
1499
1500       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1501                              (void *) names);
1502       dwarf2_per_objfile->objfile = objfile;
1503     }
1504   return (dwarf2_per_objfile->info.asection != NULL
1505           && dwarf2_per_objfile->abbrev.asection != NULL);
1506 }
1507
1508 /* When loading sections, we look either for uncompressed section or for
1509    compressed section names.  */
1510
1511 static int
1512 section_is_p (const char *section_name,
1513               const struct dwarf2_section_names *names)
1514 {
1515   if (names->normal != NULL
1516       && strcmp (section_name, names->normal) == 0)
1517     return 1;
1518   if (names->compressed != NULL
1519       && strcmp (section_name, names->compressed) == 0)
1520     return 1;
1521   return 0;
1522 }
1523
1524 /* This function is mapped across the sections and remembers the
1525    offset and size of each of the debugging sections we are interested
1526    in.  */
1527
1528 static void
1529 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1530 {
1531   const struct dwarf2_debug_sections *names;
1532
1533   if (vnames == NULL)
1534     names = &dwarf2_elf_names;
1535   else
1536     names = (const struct dwarf2_debug_sections *) vnames;
1537
1538   if (section_is_p (sectp->name, &names->info))
1539     {
1540       dwarf2_per_objfile->info.asection = sectp;
1541       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1542     }
1543   else if (section_is_p (sectp->name, &names->abbrev))
1544     {
1545       dwarf2_per_objfile->abbrev.asection = sectp;
1546       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1547     }
1548   else if (section_is_p (sectp->name, &names->line))
1549     {
1550       dwarf2_per_objfile->line.asection = sectp;
1551       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1552     }
1553   else if (section_is_p (sectp->name, &names->loc))
1554     {
1555       dwarf2_per_objfile->loc.asection = sectp;
1556       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1557     }
1558   else if (section_is_p (sectp->name, &names->macinfo))
1559     {
1560       dwarf2_per_objfile->macinfo.asection = sectp;
1561       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1562     }
1563   else if (section_is_p (sectp->name, &names->macro))
1564     {
1565       dwarf2_per_objfile->macro.asection = sectp;
1566       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1567     }
1568   else if (section_is_p (sectp->name, &names->str))
1569     {
1570       dwarf2_per_objfile->str.asection = sectp;
1571       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1572     }
1573   else if (section_is_p (sectp->name, &names->addr))
1574     {
1575       dwarf2_per_objfile->addr.asection = sectp;
1576       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1577     }
1578   else if (section_is_p (sectp->name, &names->frame))
1579     {
1580       dwarf2_per_objfile->frame.asection = sectp;
1581       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1582     }
1583   else if (section_is_p (sectp->name, &names->eh_frame))
1584     {
1585       flagword aflag = bfd_get_section_flags (abfd, sectp);
1586
1587       if (aflag & SEC_HAS_CONTENTS)
1588         {
1589           dwarf2_per_objfile->eh_frame.asection = sectp;
1590           dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1591         }
1592     }
1593   else if (section_is_p (sectp->name, &names->ranges))
1594     {
1595       dwarf2_per_objfile->ranges.asection = sectp;
1596       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1597     }
1598   else if (section_is_p (sectp->name, &names->types))
1599     {
1600       struct dwarf2_section_info type_section;
1601
1602       memset (&type_section, 0, sizeof (type_section));
1603       type_section.asection = sectp;
1604       type_section.size = bfd_get_section_size (sectp);
1605
1606       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1607                      &type_section);
1608     }
1609   else if (section_is_p (sectp->name, &names->gdb_index))
1610     {
1611       dwarf2_per_objfile->gdb_index.asection = sectp;
1612       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1613     }
1614
1615   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1616       && bfd_section_vma (abfd, sectp) == 0)
1617     dwarf2_per_objfile->has_section_at_zero = 1;
1618 }
1619
1620 /* Decompress a section that was compressed using zlib.  Store the
1621    decompressed buffer, and its size, in OUTBUF and OUTSIZE.  */
1622
1623 static void
1624 zlib_decompress_section (struct objfile *objfile, asection *sectp,
1625                          gdb_byte **outbuf, bfd_size_type *outsize)
1626 {
1627   bfd *abfd = sectp->owner;
1628 #ifndef HAVE_ZLIB_H
1629   error (_("Support for zlib-compressed DWARF data (from '%s') "
1630            "is disabled in this copy of GDB"),
1631          bfd_get_filename (abfd));
1632 #else
1633   bfd_size_type compressed_size = bfd_get_section_size (sectp);
1634   gdb_byte *compressed_buffer = xmalloc (compressed_size);
1635   struct cleanup *cleanup = make_cleanup (xfree, compressed_buffer);
1636   bfd_size_type uncompressed_size;
1637   gdb_byte *uncompressed_buffer;
1638   z_stream strm;
1639   int rc;
1640   int header_size = 12;
1641
1642   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1643       || bfd_bread (compressed_buffer,
1644                     compressed_size, abfd) != compressed_size)
1645     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1646            bfd_get_filename (abfd));
1647
1648   /* Read the zlib header.  In this case, it should be "ZLIB" followed
1649      by the uncompressed section size, 8 bytes in big-endian order.  */
1650   if (compressed_size < header_size
1651       || strncmp (compressed_buffer, "ZLIB", 4) != 0)
1652     error (_("Dwarf Error: Corrupt DWARF ZLIB header from '%s'"),
1653            bfd_get_filename (abfd));
1654   uncompressed_size = compressed_buffer[4]; uncompressed_size <<= 8;
1655   uncompressed_size += compressed_buffer[5]; uncompressed_size <<= 8;
1656   uncompressed_size += compressed_buffer[6]; uncompressed_size <<= 8;
1657   uncompressed_size += compressed_buffer[7]; uncompressed_size <<= 8;
1658   uncompressed_size += compressed_buffer[8]; uncompressed_size <<= 8;
1659   uncompressed_size += compressed_buffer[9]; uncompressed_size <<= 8;
1660   uncompressed_size += compressed_buffer[10]; uncompressed_size <<= 8;
1661   uncompressed_size += compressed_buffer[11];
1662
1663   /* It is possible the section consists of several compressed
1664      buffers concatenated together, so we uncompress in a loop.  */
1665   strm.zalloc = NULL;
1666   strm.zfree = NULL;
1667   strm.opaque = NULL;
1668   strm.avail_in = compressed_size - header_size;
1669   strm.next_in = (Bytef*) compressed_buffer + header_size;
1670   strm.avail_out = uncompressed_size;
1671   uncompressed_buffer = obstack_alloc (&objfile->objfile_obstack,
1672                                        uncompressed_size);
1673   rc = inflateInit (&strm);
1674   while (strm.avail_in > 0)
1675     {
1676       if (rc != Z_OK)
1677         error (_("Dwarf Error: setting up DWARF uncompression in '%s': %d"),
1678                bfd_get_filename (abfd), rc);
1679       strm.next_out = ((Bytef*) uncompressed_buffer
1680                        + (uncompressed_size - strm.avail_out));
1681       rc = inflate (&strm, Z_FINISH);
1682       if (rc != Z_STREAM_END)
1683         error (_("Dwarf Error: zlib error uncompressing from '%s': %d"),
1684                bfd_get_filename (abfd), rc);
1685       rc = inflateReset (&strm);
1686     }
1687   rc = inflateEnd (&strm);
1688   if (rc != Z_OK
1689       || strm.avail_out != 0)
1690     error (_("Dwarf Error: concluding DWARF uncompression in '%s': %d"),
1691            bfd_get_filename (abfd), rc);
1692
1693   do_cleanups (cleanup);
1694   *outbuf = uncompressed_buffer;
1695   *outsize = uncompressed_size;
1696 #endif
1697 }
1698
1699 /* A helper function that decides whether a section is empty,
1700    or not present.  */
1701
1702 static int
1703 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1704 {
1705   return info->asection == NULL || info->size == 0;
1706 }
1707
1708 /* Read the contents of the section INFO.
1709    OBJFILE is the main object file, but not necessarily the file where
1710    the section comes from.  E.g., for DWO files INFO->asection->owner
1711    is the bfd of the DWO file.
1712    If the section is compressed, uncompress it before returning.  */
1713
1714 static void
1715 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1716 {
1717   asection *sectp = info->asection;
1718   bfd *abfd;
1719   gdb_byte *buf, *retbuf;
1720   unsigned char header[4];
1721
1722   if (info->readin)
1723     return;
1724   info->buffer = NULL;
1725   info->map_addr = NULL;
1726   info->readin = 1;
1727
1728   if (dwarf2_section_empty_p (info))
1729     return;
1730
1731   /* Note that ABFD may not be from OBJFILE, e.g. a DWO section.  */
1732   abfd = sectp->owner;
1733
1734   /* Check if the file has a 4-byte header indicating compression.  */
1735   if (info->size > sizeof (header)
1736       && bfd_seek (abfd, sectp->filepos, SEEK_SET) == 0
1737       && bfd_bread (header, sizeof (header), abfd) == sizeof (header))
1738     {
1739       /* Upon decompression, update the buffer and its size.  */
1740       if (strncmp (header, "ZLIB", sizeof (header)) == 0)
1741         {
1742           zlib_decompress_section (objfile, sectp, &info->buffer,
1743                                    &info->size);
1744           return;
1745         }
1746     }
1747
1748 #ifdef HAVE_MMAP
1749   if (pagesize == 0)
1750     pagesize = getpagesize ();
1751
1752   /* Only try to mmap sections which are large enough: we don't want to
1753      waste space due to fragmentation.  Also, only try mmap for sections
1754      without relocations.  */
1755
1756   if (info->size > 4 * pagesize && (sectp->flags & SEC_RELOC) == 0)
1757     {
1758       info->buffer = bfd_mmap (abfd, 0, info->size, PROT_READ,
1759                          MAP_PRIVATE, sectp->filepos,
1760                          &info->map_addr, &info->map_len);
1761
1762       if ((caddr_t)info->buffer != MAP_FAILED)
1763         {
1764 #if HAVE_POSIX_MADVISE
1765           posix_madvise (info->map_addr, info->map_len, POSIX_MADV_WILLNEED);
1766 #endif
1767           return;
1768         }
1769     }
1770 #endif
1771
1772   /* If we get here, we are a normal, not-compressed section.  */
1773   info->buffer = buf
1774     = obstack_alloc (&objfile->objfile_obstack, info->size);
1775
1776   /* When debugging .o files, we may need to apply relocations; see
1777      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1778      We never compress sections in .o files, so we only need to
1779      try this when the section is not compressed.  */
1780   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1781   if (retbuf != NULL)
1782     {
1783       info->buffer = retbuf;
1784       return;
1785     }
1786
1787   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1788       || bfd_bread (buf, info->size, abfd) != info->size)
1789     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1790            bfd_get_filename (abfd));
1791 }
1792
1793 /* A helper function that returns the size of a section in a safe way.
1794    If you are positive that the section has been read before using the
1795    size, then it is safe to refer to the dwarf2_section_info object's
1796    "size" field directly.  In other cases, you must call this
1797    function, because for compressed sections the size field is not set
1798    correctly until the section has been read.  */
1799
1800 static bfd_size_type
1801 dwarf2_section_size (struct objfile *objfile,
1802                      struct dwarf2_section_info *info)
1803 {
1804   if (!info->readin)
1805     dwarf2_read_section (objfile, info);
1806   return info->size;
1807 }
1808
1809 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1810    SECTION_NAME.  */
1811
1812 void
1813 dwarf2_get_section_info (struct objfile *objfile,
1814                          enum dwarf2_section_enum sect,
1815                          asection **sectp, gdb_byte **bufp,
1816                          bfd_size_type *sizep)
1817 {
1818   struct dwarf2_per_objfile *data
1819     = objfile_data (objfile, dwarf2_objfile_data_key);
1820   struct dwarf2_section_info *info;
1821
1822   /* We may see an objfile without any DWARF, in which case we just
1823      return nothing.  */
1824   if (data == NULL)
1825     {
1826       *sectp = NULL;
1827       *bufp = NULL;
1828       *sizep = 0;
1829       return;
1830     }
1831   switch (sect)
1832     {
1833     case DWARF2_DEBUG_FRAME:
1834       info = &data->frame;
1835       break;
1836     case DWARF2_EH_FRAME:
1837       info = &data->eh_frame;
1838       break;
1839     default:
1840       gdb_assert_not_reached ("unexpected section");
1841     }
1842
1843   dwarf2_read_section (objfile, info);
1844
1845   *sectp = info->asection;
1846   *bufp = info->buffer;
1847   *sizep = info->size;
1848 }
1849
1850 \f
1851 /* DWARF quick_symbols_functions support.  */
1852
1853 /* TUs can share .debug_line entries, and there can be a lot more TUs than
1854    unique line tables, so we maintain a separate table of all .debug_line
1855    derived entries to support the sharing.
1856    All the quick functions need is the list of file names.  We discard the
1857    line_header when we're done and don't need to record it here.  */
1858 struct quick_file_names
1859 {
1860   /* The offset in .debug_line of the line table.  We hash on this.  */
1861   unsigned int offset;
1862
1863   /* The number of entries in file_names, real_names.  */
1864   unsigned int num_file_names;
1865
1866   /* The file names from the line table, after being run through
1867      file_full_name.  */
1868   const char **file_names;
1869
1870   /* The file names from the line table after being run through
1871      gdb_realpath.  These are computed lazily.  */
1872   const char **real_names;
1873 };
1874
1875 /* When using the index (and thus not using psymtabs), each CU has an
1876    object of this type.  This is used to hold information needed by
1877    the various "quick" methods.  */
1878 struct dwarf2_per_cu_quick_data
1879 {
1880   /* The file table.  This can be NULL if there was no file table
1881      or it's currently not read in.
1882      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
1883   struct quick_file_names *file_names;
1884
1885   /* The corresponding symbol table.  This is NULL if symbols for this
1886      CU have not yet been read.  */
1887   struct symtab *symtab;
1888
1889   /* A temporary mark bit used when iterating over all CUs in
1890      expand_symtabs_matching.  */
1891   unsigned int mark : 1;
1892
1893   /* True if we've tried to read the file table and found there isn't one.
1894      There will be no point in trying to read it again next time.  */
1895   unsigned int no_file_data : 1;
1896 };
1897
1898 /* Hash function for a quick_file_names.  */
1899
1900 static hashval_t
1901 hash_file_name_entry (const void *e)
1902 {
1903   const struct quick_file_names *file_data = e;
1904
1905   return file_data->offset;
1906 }
1907
1908 /* Equality function for a quick_file_names.  */
1909
1910 static int
1911 eq_file_name_entry (const void *a, const void *b)
1912 {
1913   const struct quick_file_names *ea = a;
1914   const struct quick_file_names *eb = b;
1915
1916   return ea->offset == eb->offset;
1917 }
1918
1919 /* Delete function for a quick_file_names.  */
1920
1921 static void
1922 delete_file_name_entry (void *e)
1923 {
1924   struct quick_file_names *file_data = e;
1925   int i;
1926
1927   for (i = 0; i < file_data->num_file_names; ++i)
1928     {
1929       xfree ((void*) file_data->file_names[i]);
1930       if (file_data->real_names)
1931         xfree ((void*) file_data->real_names[i]);
1932     }
1933
1934   /* The space for the struct itself lives on objfile_obstack,
1935      so we don't free it here.  */
1936 }
1937
1938 /* Create a quick_file_names hash table.  */
1939
1940 static htab_t
1941 create_quick_file_names_table (unsigned int nr_initial_entries)
1942 {
1943   return htab_create_alloc (nr_initial_entries,
1944                             hash_file_name_entry, eq_file_name_entry,
1945                             delete_file_name_entry, xcalloc, xfree);
1946 }
1947
1948 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
1949    have to be created afterwards.  You should call age_cached_comp_units after
1950    processing PER_CU->CU.  dw2_setup must have been already called.  */
1951
1952 static void
1953 load_cu (struct dwarf2_per_cu_data *per_cu)
1954 {
1955   if (per_cu->is_debug_types)
1956     load_full_type_unit (per_cu);
1957   else
1958     load_full_comp_unit (per_cu, language_minimal);
1959
1960   gdb_assert (per_cu->cu != NULL);
1961
1962   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
1963 }
1964
1965 /* Read in the symbols for PER_CU.  */
1966
1967 static void
1968 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
1969 {
1970   struct cleanup *back_to;
1971
1972   back_to = make_cleanup (dwarf2_release_queue, NULL);
1973
1974   if (dwarf2_per_objfile->using_index
1975       ? per_cu->v.quick->symtab == NULL
1976       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
1977     {
1978       queue_comp_unit (per_cu, language_minimal);
1979       load_cu (per_cu);
1980     }
1981
1982   process_queue ();
1983
1984   /* Age the cache, releasing compilation units that have not
1985      been used recently.  */
1986   age_cached_comp_units ();
1987
1988   do_cleanups (back_to);
1989 }
1990
1991 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
1992    the objfile from which this CU came.  Returns the resulting symbol
1993    table.  */
1994
1995 static struct symtab *
1996 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
1997 {
1998   gdb_assert (dwarf2_per_objfile->using_index);
1999   if (!per_cu->v.quick->symtab)
2000     {
2001       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2002       increment_reading_symtab ();
2003       dw2_do_instantiate_symtab (per_cu);
2004       process_cu_includes ();
2005       do_cleanups (back_to);
2006     }
2007   return per_cu->v.quick->symtab;
2008 }
2009
2010 /* Return the CU given its index.  */
2011
2012 static struct dwarf2_per_cu_data *
2013 dw2_get_cu (int index)
2014 {
2015   if (index >= dwarf2_per_objfile->n_comp_units)
2016     {
2017       index -= dwarf2_per_objfile->n_comp_units;
2018       return dwarf2_per_objfile->all_type_units[index];
2019     }
2020   return dwarf2_per_objfile->all_comp_units[index];
2021 }
2022
2023 /* A helper function that knows how to read a 64-bit value in a way
2024    that doesn't make gdb die.  Returns 1 if the conversion went ok, 0
2025    otherwise.  */
2026
2027 static int
2028 extract_cu_value (const char *bytes, ULONGEST *result)
2029 {
2030   if (sizeof (ULONGEST) < 8)
2031     {
2032       int i;
2033
2034       /* Ignore the upper 4 bytes if they are all zero.  */
2035       for (i = 0; i < 4; ++i)
2036         if (bytes[i + 4] != 0)
2037           return 0;
2038
2039       *result = extract_unsigned_integer (bytes, 4, BFD_ENDIAN_LITTLE);
2040     }
2041   else
2042     *result = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2043   return 1;
2044 }
2045
2046 /* Read the CU list from the mapped index, and use it to create all
2047    the CU objects for this objfile.  Return 0 if something went wrong,
2048    1 if everything went ok.  */
2049
2050 static int
2051 create_cus_from_index (struct objfile *objfile, const gdb_byte *cu_list,
2052                        offset_type cu_list_elements)
2053 {
2054   offset_type i;
2055
2056   dwarf2_per_objfile->n_comp_units = cu_list_elements / 2;
2057   dwarf2_per_objfile->all_comp_units
2058     = obstack_alloc (&objfile->objfile_obstack,
2059                      dwarf2_per_objfile->n_comp_units
2060                      * sizeof (struct dwarf2_per_cu_data *));
2061
2062   for (i = 0; i < cu_list_elements; i += 2)
2063     {
2064       struct dwarf2_per_cu_data *the_cu;
2065       ULONGEST offset, length;
2066
2067       if (!extract_cu_value (cu_list, &offset)
2068           || !extract_cu_value (cu_list + 8, &length))
2069         return 0;
2070       cu_list += 2 * 8;
2071
2072       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2073                                struct dwarf2_per_cu_data);
2074       the_cu->offset.sect_off = offset;
2075       the_cu->length = length;
2076       the_cu->objfile = objfile;
2077       the_cu->info_or_types_section = &dwarf2_per_objfile->info;
2078       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2079                                         struct dwarf2_per_cu_quick_data);
2080       dwarf2_per_objfile->all_comp_units[i / 2] = the_cu;
2081     }
2082
2083   return 1;
2084 }
2085
2086 /* Create the signatured type hash table from the index.  */
2087
2088 static int
2089 create_signatured_type_table_from_index (struct objfile *objfile,
2090                                          struct dwarf2_section_info *section,
2091                                          const gdb_byte *bytes,
2092                                          offset_type elements)
2093 {
2094   offset_type i;
2095   htab_t sig_types_hash;
2096
2097   dwarf2_per_objfile->n_type_units = elements / 3;
2098   dwarf2_per_objfile->all_type_units
2099     = obstack_alloc (&objfile->objfile_obstack,
2100                      dwarf2_per_objfile->n_type_units
2101                      * sizeof (struct dwarf2_per_cu_data *));
2102
2103   sig_types_hash = allocate_signatured_type_table (objfile);
2104
2105   for (i = 0; i < elements; i += 3)
2106     {
2107       struct signatured_type *sig_type;
2108       ULONGEST offset, type_offset_in_tu, signature;
2109       void **slot;
2110
2111       if (!extract_cu_value (bytes, &offset)
2112           || !extract_cu_value (bytes + 8, &type_offset_in_tu))
2113         return 0;
2114       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2115       bytes += 3 * 8;
2116
2117       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2118                                  struct signatured_type);
2119       sig_type->signature = signature;
2120       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2121       sig_type->per_cu.is_debug_types = 1;
2122       sig_type->per_cu.info_or_types_section = section;
2123       sig_type->per_cu.offset.sect_off = offset;
2124       sig_type->per_cu.objfile = objfile;
2125       sig_type->per_cu.v.quick
2126         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2127                           struct dwarf2_per_cu_quick_data);
2128
2129       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2130       *slot = sig_type;
2131
2132       dwarf2_per_objfile->all_type_units[i / 3] = &sig_type->per_cu;
2133     }
2134
2135   dwarf2_per_objfile->signatured_types = sig_types_hash;
2136
2137   return 1;
2138 }
2139
2140 /* Read the address map data from the mapped index, and use it to
2141    populate the objfile's psymtabs_addrmap.  */
2142
2143 static void
2144 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2145 {
2146   const gdb_byte *iter, *end;
2147   struct obstack temp_obstack;
2148   struct addrmap *mutable_map;
2149   struct cleanup *cleanup;
2150   CORE_ADDR baseaddr;
2151
2152   obstack_init (&temp_obstack);
2153   cleanup = make_cleanup_obstack_free (&temp_obstack);
2154   mutable_map = addrmap_create_mutable (&temp_obstack);
2155
2156   iter = index->address_table;
2157   end = iter + index->address_table_size;
2158
2159   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2160
2161   while (iter < end)
2162     {
2163       ULONGEST hi, lo, cu_index;
2164       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2165       iter += 8;
2166       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2167       iter += 8;
2168       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2169       iter += 4;
2170       
2171       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2172                          dw2_get_cu (cu_index));
2173     }
2174
2175   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2176                                                     &objfile->objfile_obstack);
2177   do_cleanups (cleanup);
2178 }
2179
2180 /* The hash function for strings in the mapped index.  This is the same as
2181    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2182    implementation.  This is necessary because the hash function is tied to the
2183    format of the mapped index file.  The hash values do not have to match with
2184    SYMBOL_HASH_NEXT.
2185    
2186    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2187
2188 static hashval_t
2189 mapped_index_string_hash (int index_version, const void *p)
2190 {
2191   const unsigned char *str = (const unsigned char *) p;
2192   hashval_t r = 0;
2193   unsigned char c;
2194
2195   while ((c = *str++) != 0)
2196     {
2197       if (index_version >= 5)
2198         c = tolower (c);
2199       r = r * 67 + c - 113;
2200     }
2201
2202   return r;
2203 }
2204
2205 /* Find a slot in the mapped index INDEX for the object named NAME.
2206    If NAME is found, set *VEC_OUT to point to the CU vector in the
2207    constant pool and return 1.  If NAME cannot be found, return 0.  */
2208
2209 static int
2210 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2211                           offset_type **vec_out)
2212 {
2213   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2214   offset_type hash;
2215   offset_type slot, step;
2216   int (*cmp) (const char *, const char *);
2217
2218   if (current_language->la_language == language_cplus
2219       || current_language->la_language == language_java
2220       || current_language->la_language == language_fortran)
2221     {
2222       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2223          not contain any.  */
2224       const char *paren = strchr (name, '(');
2225
2226       if (paren)
2227         {
2228           char *dup;
2229
2230           dup = xmalloc (paren - name + 1);
2231           memcpy (dup, name, paren - name);
2232           dup[paren - name] = 0;
2233
2234           make_cleanup (xfree, dup);
2235           name = dup;
2236         }
2237     }
2238
2239   /* Index version 4 did not support case insensitive searches.  But the
2240      indices for case insensitive languages are built in lowercase, therefore
2241      simulate our NAME being searched is also lowercased.  */
2242   hash = mapped_index_string_hash ((index->version == 4
2243                                     && case_sensitivity == case_sensitive_off
2244                                     ? 5 : index->version),
2245                                    name);
2246
2247   slot = hash & (index->symbol_table_slots - 1);
2248   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2249   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2250
2251   for (;;)
2252     {
2253       /* Convert a slot number to an offset into the table.  */
2254       offset_type i = 2 * slot;
2255       const char *str;
2256       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2257         {
2258           do_cleanups (back_to);
2259           return 0;
2260         }
2261
2262       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2263       if (!cmp (name, str))
2264         {
2265           *vec_out = (offset_type *) (index->constant_pool
2266                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2267           do_cleanups (back_to);
2268           return 1;
2269         }
2270
2271       slot = (slot + step) & (index->symbol_table_slots - 1);
2272     }
2273 }
2274
2275 /* Read the index file.  If everything went ok, initialize the "quick"
2276    elements of all the CUs and return 1.  Otherwise, return 0.  */
2277
2278 static int
2279 dwarf2_read_index (struct objfile *objfile)
2280 {
2281   char *addr;
2282   struct mapped_index *map;
2283   offset_type *metadata;
2284   const gdb_byte *cu_list;
2285   const gdb_byte *types_list = NULL;
2286   offset_type version, cu_list_elements;
2287   offset_type types_list_elements = 0;
2288   int i;
2289
2290   if (dwarf2_section_empty_p (&dwarf2_per_objfile->gdb_index))
2291     return 0;
2292
2293   /* Older elfutils strip versions could keep the section in the main
2294      executable while splitting it for the separate debug info file.  */
2295   if ((bfd_get_file_flags (dwarf2_per_objfile->gdb_index.asection)
2296        & SEC_HAS_CONTENTS) == 0)
2297     return 0;
2298
2299   dwarf2_read_section (objfile, &dwarf2_per_objfile->gdb_index);
2300
2301   addr = dwarf2_per_objfile->gdb_index.buffer;
2302   /* Version check.  */
2303   version = MAYBE_SWAP (*(offset_type *) addr);
2304   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2305      causes the index to behave very poorly for certain requests.  Version 3
2306      contained incomplete addrmap.  So, it seems better to just ignore such
2307      indices.  */
2308   if (version < 4)
2309     {
2310       static int warning_printed = 0;
2311       if (!warning_printed)
2312         {
2313           warning (_("Skipping obsolete .gdb_index section in %s."),
2314                    objfile->name);
2315           warning_printed = 1;
2316         }
2317       return 0;
2318     }
2319   /* Index version 4 uses a different hash function than index version
2320      5 and later.
2321
2322      Versions earlier than 6 did not emit psymbols for inlined
2323      functions.  Using these files will cause GDB not to be able to
2324      set breakpoints on inlined functions by name, so we ignore these
2325      indices unless the --use-deprecated-index-sections command line
2326      option was supplied.  */
2327   if (version < 6 && !use_deprecated_index_sections)
2328     {
2329       static int warning_printed = 0;
2330       if (!warning_printed)
2331         {
2332           warning (_("Skipping deprecated .gdb_index section in %s, pass "
2333                      "--use-deprecated-index-sections to use them anyway"),
2334                    objfile->name);
2335           warning_printed = 1;
2336         }
2337       return 0;
2338     }
2339   /* Indexes with higher version than the one supported by GDB may be no
2340      longer backward compatible.  */
2341   if (version > 6)
2342     return 0;
2343
2344   map = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct mapped_index);
2345   map->version = version;
2346   map->total_size = dwarf2_per_objfile->gdb_index.size;
2347
2348   metadata = (offset_type *) (addr + sizeof (offset_type));
2349
2350   i = 0;
2351   cu_list = addr + MAYBE_SWAP (metadata[i]);
2352   cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2353                       / 8);
2354   ++i;
2355
2356   types_list = addr + MAYBE_SWAP (metadata[i]);
2357   types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2358                           - MAYBE_SWAP (metadata[i]))
2359                          / 8);
2360   ++i;
2361
2362   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2363   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2364                              - MAYBE_SWAP (metadata[i]));
2365   ++i;
2366
2367   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2368   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2369                               - MAYBE_SWAP (metadata[i]))
2370                              / (2 * sizeof (offset_type)));
2371   ++i;
2372
2373   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2374
2375   /* Don't use the index if it's empty.  */
2376   if (map->symbol_table_slots == 0)
2377     return 0;
2378
2379   if (!create_cus_from_index (objfile, cu_list, cu_list_elements))
2380     return 0;
2381
2382   if (types_list_elements)
2383     {
2384       struct dwarf2_section_info *section;
2385
2386       /* We can only handle a single .debug_types when we have an
2387          index.  */
2388       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2389         return 0;
2390
2391       section = VEC_index (dwarf2_section_info_def,
2392                            dwarf2_per_objfile->types, 0);
2393
2394       if (!create_signatured_type_table_from_index (objfile, section,
2395                                                     types_list,
2396                                                     types_list_elements))
2397         return 0;
2398     }
2399
2400   create_addrmap_from_index (objfile, map);
2401
2402   dwarf2_per_objfile->index_table = map;
2403   dwarf2_per_objfile->using_index = 1;
2404   dwarf2_per_objfile->quick_file_names_table =
2405     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2406
2407   return 1;
2408 }
2409
2410 /* A helper for the "quick" functions which sets the global
2411    dwarf2_per_objfile according to OBJFILE.  */
2412
2413 static void
2414 dw2_setup (struct objfile *objfile)
2415 {
2416   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2417   gdb_assert (dwarf2_per_objfile);
2418 }
2419
2420 /* die_reader_func for dw2_get_file_names.  */
2421
2422 static void
2423 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2424                            gdb_byte *info_ptr,
2425                            struct die_info *comp_unit_die,
2426                            int has_children,
2427                            void *data)
2428 {
2429   struct dwarf2_cu *cu = reader->cu;
2430   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2431   struct objfile *objfile = dwarf2_per_objfile->objfile;
2432   struct line_header *lh;
2433   struct attribute *attr;
2434   int i;
2435   char *name, *comp_dir;
2436   void **slot;
2437   struct quick_file_names *qfn;
2438   unsigned int line_offset;
2439
2440   lh = NULL;
2441   slot = NULL;
2442   line_offset = 0;
2443
2444   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2445   if (attr)
2446     {
2447       struct quick_file_names find_entry;
2448
2449       line_offset = DW_UNSND (attr);
2450
2451       /* We may have already read in this line header (TU line header sharing).
2452          If we have we're done.  */
2453       find_entry.offset = line_offset;
2454       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2455                              &find_entry, INSERT);
2456       if (*slot != NULL)
2457         {
2458           this_cu->v.quick->file_names = *slot;
2459           return;
2460         }
2461
2462       lh = dwarf_decode_line_header (line_offset, cu);
2463     }
2464   if (lh == NULL)
2465     {
2466       this_cu->v.quick->no_file_data = 1;
2467       return;
2468     }
2469
2470   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2471   qfn->offset = line_offset;
2472   gdb_assert (slot != NULL);
2473   *slot = qfn;
2474
2475   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2476
2477   qfn->num_file_names = lh->num_file_names;
2478   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2479                                    lh->num_file_names * sizeof (char *));
2480   for (i = 0; i < lh->num_file_names; ++i)
2481     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2482   qfn->real_names = NULL;
2483
2484   free_line_header (lh);
2485
2486   this_cu->v.quick->file_names = qfn;
2487 }
2488
2489 /* A helper for the "quick" functions which attempts to read the line
2490    table for THIS_CU.  */
2491
2492 static struct quick_file_names *
2493 dw2_get_file_names (struct objfile *objfile,
2494                     struct dwarf2_per_cu_data *this_cu)
2495 {
2496   if (this_cu->v.quick->file_names != NULL)
2497     return this_cu->v.quick->file_names;
2498   /* If we know there is no line data, no point in looking again.  */
2499   if (this_cu->v.quick->no_file_data)
2500     return NULL;
2501
2502   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2503      in the stub for CUs, there's is no need to lookup the DWO file.
2504      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2505      DWO file.  */
2506   if (this_cu->is_debug_types)
2507     init_cutu_and_read_dies (this_cu, 0, 0, dw2_get_file_names_reader, NULL);
2508   else
2509     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2510
2511   if (this_cu->v.quick->no_file_data)
2512     return NULL;
2513   return this_cu->v.quick->file_names;
2514 }
2515
2516 /* A helper for the "quick" functions which computes and caches the
2517    real path for a given file name from the line table.  */
2518
2519 static const char *
2520 dw2_get_real_path (struct objfile *objfile,
2521                    struct quick_file_names *qfn, int index)
2522 {
2523   if (qfn->real_names == NULL)
2524     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2525                                       qfn->num_file_names, sizeof (char *));
2526
2527   if (qfn->real_names[index] == NULL)
2528     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2529
2530   return qfn->real_names[index];
2531 }
2532
2533 static struct symtab *
2534 dw2_find_last_source_symtab (struct objfile *objfile)
2535 {
2536   int index;
2537
2538   dw2_setup (objfile);
2539   index = dwarf2_per_objfile->n_comp_units - 1;
2540   return dw2_instantiate_symtab (dw2_get_cu (index));
2541 }
2542
2543 /* Traversal function for dw2_forget_cached_source_info.  */
2544
2545 static int
2546 dw2_free_cached_file_names (void **slot, void *info)
2547 {
2548   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2549
2550   if (file_data->real_names)
2551     {
2552       int i;
2553
2554       for (i = 0; i < file_data->num_file_names; ++i)
2555         {
2556           xfree ((void*) file_data->real_names[i]);
2557           file_data->real_names[i] = NULL;
2558         }
2559     }
2560
2561   return 1;
2562 }
2563
2564 static void
2565 dw2_forget_cached_source_info (struct objfile *objfile)
2566 {
2567   dw2_setup (objfile);
2568
2569   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
2570                           dw2_free_cached_file_names, NULL);
2571 }
2572
2573 /* Helper function for dw2_map_symtabs_matching_filename that expands
2574    the symtabs and calls the iterator.  */
2575
2576 static int
2577 dw2_map_expand_apply (struct objfile *objfile,
2578                       struct dwarf2_per_cu_data *per_cu,
2579                       const char *name,
2580                       const char *full_path, const char *real_path,
2581                       int (*callback) (struct symtab *, void *),
2582                       void *data)
2583 {
2584   struct symtab *last_made = objfile->symtabs;
2585
2586   /* Don't visit already-expanded CUs.  */
2587   if (per_cu->v.quick->symtab)
2588     return 0;
2589
2590   /* This may expand more than one symtab, and we want to iterate over
2591      all of them.  */
2592   dw2_instantiate_symtab (per_cu);
2593
2594   return iterate_over_some_symtabs (name, full_path, real_path, callback, data,
2595                                     objfile->symtabs, last_made);
2596 }
2597
2598 /* Implementation of the map_symtabs_matching_filename method.  */
2599
2600 static int
2601 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
2602                                    const char *full_path, const char *real_path,
2603                                    int (*callback) (struct symtab *, void *),
2604                                    void *data)
2605 {
2606   int i;
2607   const char *name_basename = lbasename (name);
2608   int name_len = strlen (name);
2609   int is_abs = IS_ABSOLUTE_PATH (name);
2610
2611   dw2_setup (objfile);
2612
2613   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2614                    + dwarf2_per_objfile->n_type_units); ++i)
2615     {
2616       int j;
2617       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2618       struct quick_file_names *file_data;
2619
2620       /* We only need to look at symtabs not already expanded.  */
2621       if (per_cu->v.quick->symtab)
2622         continue;
2623
2624       file_data = dw2_get_file_names (objfile, per_cu);
2625       if (file_data == NULL)
2626         continue;
2627
2628       for (j = 0; j < file_data->num_file_names; ++j)
2629         {
2630           const char *this_name = file_data->file_names[j];
2631
2632           if (FILENAME_CMP (name, this_name) == 0
2633               || (!is_abs && compare_filenames_for_search (this_name,
2634                                                            name, name_len)))
2635             {
2636               if (dw2_map_expand_apply (objfile, per_cu,
2637                                         name, full_path, real_path,
2638                                         callback, data))
2639                 return 1;
2640             }
2641
2642           /* Before we invoke realpath, which can get expensive when many
2643              files are involved, do a quick comparison of the basenames.  */
2644           if (! basenames_may_differ
2645               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
2646             continue;
2647
2648           if (full_path != NULL)
2649             {
2650               const char *this_real_name = dw2_get_real_path (objfile,
2651                                                               file_data, j);
2652
2653               if (this_real_name != NULL
2654                   && (FILENAME_CMP (full_path, this_real_name) == 0
2655                       || (!is_abs
2656                           && compare_filenames_for_search (this_real_name,
2657                                                            name, name_len))))
2658                 {
2659                   if (dw2_map_expand_apply (objfile, per_cu,
2660                                             name, full_path, real_path,
2661                                             callback, data))
2662                     return 1;
2663                 }
2664             }
2665
2666           if (real_path != NULL)
2667             {
2668               const char *this_real_name = dw2_get_real_path (objfile,
2669                                                               file_data, j);
2670
2671               if (this_real_name != NULL
2672                   && (FILENAME_CMP (real_path, this_real_name) == 0
2673                       || (!is_abs
2674                           && compare_filenames_for_search (this_real_name,
2675                                                            name, name_len))))
2676                 {
2677                   if (dw2_map_expand_apply (objfile, per_cu,
2678                                             name, full_path, real_path,
2679                                             callback, data))
2680                     return 1;
2681                 }
2682             }
2683         }
2684     }
2685
2686   return 0;
2687 }
2688
2689 static struct symtab *
2690 dw2_lookup_symbol (struct objfile *objfile, int block_index,
2691                    const char *name, domain_enum domain)
2692 {
2693   /* We do all the work in the pre_expand_symtabs_matching hook
2694      instead.  */
2695   return NULL;
2696 }
2697
2698 /* A helper function that expands all symtabs that hold an object
2699    named NAME.  */
2700
2701 static void
2702 dw2_do_expand_symtabs_matching (struct objfile *objfile, const char *name)
2703 {
2704   dw2_setup (objfile);
2705
2706   /* index_table is NULL if OBJF_READNOW.  */
2707   if (dwarf2_per_objfile->index_table)
2708     {
2709       offset_type *vec;
2710
2711       if (find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
2712                                     name, &vec))
2713         {
2714           offset_type i, len = MAYBE_SWAP (*vec);
2715           for (i = 0; i < len; ++i)
2716             {
2717               offset_type cu_index = MAYBE_SWAP (vec[i + 1]);
2718               struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
2719
2720               dw2_instantiate_symtab (per_cu);
2721             }
2722         }
2723     }
2724 }
2725
2726 static void
2727 dw2_pre_expand_symtabs_matching (struct objfile *objfile,
2728                                  enum block_enum block_kind, const char *name,
2729                                  domain_enum domain)
2730 {
2731   dw2_do_expand_symtabs_matching (objfile, name);
2732 }
2733
2734 static void
2735 dw2_print_stats (struct objfile *objfile)
2736 {
2737   int i, count;
2738
2739   dw2_setup (objfile);
2740   count = 0;
2741   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2742                    + dwarf2_per_objfile->n_type_units); ++i)
2743     {
2744       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2745
2746       if (!per_cu->v.quick->symtab)
2747         ++count;
2748     }
2749   printf_filtered (_("  Number of unread CUs: %d\n"), count);
2750 }
2751
2752 static void
2753 dw2_dump (struct objfile *objfile)
2754 {
2755   /* Nothing worth printing.  */
2756 }
2757
2758 static void
2759 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
2760               struct section_offsets *delta)
2761 {
2762   /* There's nothing to relocate here.  */
2763 }
2764
2765 static void
2766 dw2_expand_symtabs_for_function (struct objfile *objfile,
2767                                  const char *func_name)
2768 {
2769   dw2_do_expand_symtabs_matching (objfile, func_name);
2770 }
2771
2772 static void
2773 dw2_expand_all_symtabs (struct objfile *objfile)
2774 {
2775   int i;
2776
2777   dw2_setup (objfile);
2778
2779   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2780                    + dwarf2_per_objfile->n_type_units); ++i)
2781     {
2782       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2783
2784       dw2_instantiate_symtab (per_cu);
2785     }
2786 }
2787
2788 static void
2789 dw2_expand_symtabs_with_filename (struct objfile *objfile,
2790                                   const char *filename)
2791 {
2792   int i;
2793
2794   dw2_setup (objfile);
2795
2796   /* We don't need to consider type units here.
2797      This is only called for examining code, e.g. expand_line_sal.
2798      There can be an order of magnitude (or more) more type units
2799      than comp units, and we avoid them if we can.  */
2800
2801   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
2802     {
2803       int j;
2804       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2805       struct quick_file_names *file_data;
2806
2807       /* We only need to look at symtabs not already expanded.  */
2808       if (per_cu->v.quick->symtab)
2809         continue;
2810
2811       file_data = dw2_get_file_names (objfile, per_cu);
2812       if (file_data == NULL)
2813         continue;
2814
2815       for (j = 0; j < file_data->num_file_names; ++j)
2816         {
2817           const char *this_name = file_data->file_names[j];
2818           if (FILENAME_CMP (this_name, filename) == 0)
2819             {
2820               dw2_instantiate_symtab (per_cu);
2821               break;
2822             }
2823         }
2824     }
2825 }
2826
2827 static const char *
2828 dw2_find_symbol_file (struct objfile *objfile, const char *name)
2829 {
2830   struct dwarf2_per_cu_data *per_cu;
2831   offset_type *vec;
2832   struct quick_file_names *file_data;
2833
2834   dw2_setup (objfile);
2835
2836   /* index_table is NULL if OBJF_READNOW.  */
2837   if (!dwarf2_per_objfile->index_table)
2838     {
2839       struct symtab *s;
2840
2841       ALL_OBJFILE_SYMTABS (objfile, s)
2842         if (s->primary)
2843           {
2844             struct blockvector *bv = BLOCKVECTOR (s);
2845             const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
2846             struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
2847
2848             if (sym)
2849               return sym->symtab->filename;
2850           }
2851       return NULL;
2852     }
2853
2854   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
2855                                  name, &vec))
2856     return NULL;
2857
2858   /* Note that this just looks at the very first one named NAME -- but
2859      actually we are looking for a function.  find_main_filename
2860      should be rewritten so that it doesn't require a custom hook.  It
2861      could just use the ordinary symbol tables.  */
2862   /* vec[0] is the length, which must always be >0.  */
2863   per_cu = dw2_get_cu (MAYBE_SWAP (vec[1]));
2864
2865   file_data = dw2_get_file_names (objfile, per_cu);
2866   if (file_data == NULL
2867       || file_data->num_file_names == 0)
2868     return NULL;
2869
2870   return file_data->file_names[file_data->num_file_names - 1];
2871 }
2872
2873 static void
2874 dw2_map_matching_symbols (const char * name, domain_enum namespace,
2875                           struct objfile *objfile, int global,
2876                           int (*callback) (struct block *,
2877                                            struct symbol *, void *),
2878                           void *data, symbol_compare_ftype *match,
2879                           symbol_compare_ftype *ordered_compare)
2880 {
2881   /* Currently unimplemented; used for Ada.  The function can be called if the
2882      current language is Ada for a non-Ada objfile using GNU index.  As Ada
2883      does not look for non-Ada symbols this function should just return.  */
2884 }
2885
2886 static void
2887 dw2_expand_symtabs_matching
2888   (struct objfile *objfile,
2889    int (*file_matcher) (const char *, void *),
2890    int (*name_matcher) (const char *, void *),
2891    enum search_domain kind,
2892    void *data)
2893 {
2894   int i;
2895   offset_type iter;
2896   struct mapped_index *index;
2897
2898   dw2_setup (objfile);
2899
2900   /* index_table is NULL if OBJF_READNOW.  */
2901   if (!dwarf2_per_objfile->index_table)
2902     return;
2903   index = dwarf2_per_objfile->index_table;
2904
2905   if (file_matcher != NULL)
2906     {
2907       struct cleanup *cleanup;
2908       htab_t visited_found, visited_not_found;
2909
2910       visited_found = htab_create_alloc (10,
2911                                          htab_hash_pointer, htab_eq_pointer,
2912                                          NULL, xcalloc, xfree);
2913       cleanup = make_cleanup_htab_delete (visited_found);
2914       visited_not_found = htab_create_alloc (10,
2915                                              htab_hash_pointer, htab_eq_pointer,
2916                                              NULL, xcalloc, xfree);
2917       make_cleanup_htab_delete (visited_not_found);
2918
2919       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2920                        + dwarf2_per_objfile->n_type_units); ++i)
2921         {
2922           int j;
2923           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2924           struct quick_file_names *file_data;
2925           void **slot;
2926
2927           per_cu->v.quick->mark = 0;
2928
2929           /* We only need to look at symtabs not already expanded.  */
2930           if (per_cu->v.quick->symtab)
2931             continue;
2932
2933           file_data = dw2_get_file_names (objfile, per_cu);
2934           if (file_data == NULL)
2935             continue;
2936
2937           if (htab_find (visited_not_found, file_data) != NULL)
2938             continue;
2939           else if (htab_find (visited_found, file_data) != NULL)
2940             {
2941               per_cu->v.quick->mark = 1;
2942               continue;
2943             }
2944
2945           for (j = 0; j < file_data->num_file_names; ++j)
2946             {
2947               if (file_matcher (file_data->file_names[j], data))
2948                 {
2949                   per_cu->v.quick->mark = 1;
2950                   break;
2951                 }
2952             }
2953
2954           slot = htab_find_slot (per_cu->v.quick->mark
2955                                  ? visited_found
2956                                  : visited_not_found,
2957                                  file_data, INSERT);
2958           *slot = file_data;
2959         }
2960
2961       do_cleanups (cleanup);
2962     }
2963
2964   for (iter = 0; iter < index->symbol_table_slots; ++iter)
2965     {
2966       offset_type idx = 2 * iter;
2967       const char *name;
2968       offset_type *vec, vec_len, vec_idx;
2969
2970       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
2971         continue;
2972
2973       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
2974
2975       if (! (*name_matcher) (name, data))
2976         continue;
2977
2978       /* The name was matched, now expand corresponding CUs that were
2979          marked.  */
2980       vec = (offset_type *) (index->constant_pool
2981                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
2982       vec_len = MAYBE_SWAP (vec[0]);
2983       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
2984         {
2985           struct dwarf2_per_cu_data *per_cu;
2986
2987           per_cu = dw2_get_cu (MAYBE_SWAP (vec[vec_idx + 1]));
2988           if (file_matcher == NULL || per_cu->v.quick->mark)
2989             dw2_instantiate_symtab (per_cu);
2990         }
2991     }
2992 }
2993
2994 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
2995    symtab.  */
2996
2997 static struct symtab *
2998 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
2999 {
3000   int i;
3001
3002   if (BLOCKVECTOR (symtab) != NULL
3003       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3004     return symtab;
3005
3006   if (symtab->includes == NULL)
3007     return NULL;
3008
3009   for (i = 0; symtab->includes[i]; ++i)
3010     {
3011       struct symtab *s = symtab->includes[i];
3012
3013       s = recursively_find_pc_sect_symtab (s, pc);
3014       if (s != NULL)
3015         return s;
3016     }
3017
3018   return NULL;
3019 }
3020
3021 static struct symtab *
3022 dw2_find_pc_sect_symtab (struct objfile *objfile,
3023                          struct minimal_symbol *msymbol,
3024                          CORE_ADDR pc,
3025                          struct obj_section *section,
3026                          int warn_if_readin)
3027 {
3028   struct dwarf2_per_cu_data *data;
3029   struct symtab *result;
3030
3031   dw2_setup (objfile);
3032
3033   if (!objfile->psymtabs_addrmap)
3034     return NULL;
3035
3036   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3037   if (!data)
3038     return NULL;
3039
3040   if (warn_if_readin && data->v.quick->symtab)
3041     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3042              paddress (get_objfile_arch (objfile), pc));
3043
3044   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3045   gdb_assert (result != NULL);
3046   return result;
3047 }
3048
3049 static void
3050 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3051                           void *data, int need_fullname)
3052 {
3053   int i;
3054   struct cleanup *cleanup;
3055   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3056                                       NULL, xcalloc, xfree);
3057
3058   cleanup = make_cleanup_htab_delete (visited);
3059   dw2_setup (objfile);
3060
3061   /* We can ignore file names coming from already-expanded CUs.  */
3062   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3063                    + dwarf2_per_objfile->n_type_units); ++i)
3064     {
3065       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3066
3067       if (per_cu->v.quick->symtab)
3068         {
3069           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3070                                         INSERT);
3071
3072           *slot = per_cu->v.quick->file_names;
3073         }
3074     }
3075
3076   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3077                    + dwarf2_per_objfile->n_type_units); ++i)
3078     {
3079       int j;
3080       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3081       struct quick_file_names *file_data;
3082       void **slot;
3083
3084       /* We only need to look at symtabs not already expanded.  */
3085       if (per_cu->v.quick->symtab)
3086         continue;
3087
3088       file_data = dw2_get_file_names (objfile, per_cu);
3089       if (file_data == NULL)
3090         continue;
3091
3092       slot = htab_find_slot (visited, file_data, INSERT);
3093       if (*slot)
3094         {
3095           /* Already visited.  */
3096           continue;
3097         }
3098       *slot = file_data;
3099
3100       for (j = 0; j < file_data->num_file_names; ++j)
3101         {
3102           const char *this_real_name;
3103
3104           if (need_fullname)
3105             this_real_name = dw2_get_real_path (objfile, file_data, j);
3106           else
3107             this_real_name = NULL;
3108           (*fun) (file_data->file_names[j], this_real_name, data);
3109         }
3110     }
3111
3112   do_cleanups (cleanup);
3113 }
3114
3115 static int
3116 dw2_has_symbols (struct objfile *objfile)
3117 {
3118   return 1;
3119 }
3120
3121 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3122 {
3123   dw2_has_symbols,
3124   dw2_find_last_source_symtab,
3125   dw2_forget_cached_source_info,
3126   dw2_map_symtabs_matching_filename,
3127   dw2_lookup_symbol,
3128   dw2_pre_expand_symtabs_matching,
3129   dw2_print_stats,
3130   dw2_dump,
3131   dw2_relocate,
3132   dw2_expand_symtabs_for_function,
3133   dw2_expand_all_symtabs,
3134   dw2_expand_symtabs_with_filename,
3135   dw2_find_symbol_file,
3136   dw2_map_matching_symbols,
3137   dw2_expand_symtabs_matching,
3138   dw2_find_pc_sect_symtab,
3139   dw2_map_symbol_filenames
3140 };
3141
3142 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3143    file will use psymtabs, or 1 if using the GNU index.  */
3144
3145 int
3146 dwarf2_initialize_objfile (struct objfile *objfile)
3147 {
3148   /* If we're about to read full symbols, don't bother with the
3149      indices.  In this case we also don't care if some other debug
3150      format is making psymtabs, because they are all about to be
3151      expanded anyway.  */
3152   if ((objfile->flags & OBJF_READNOW))
3153     {
3154       int i;
3155
3156       dwarf2_per_objfile->using_index = 1;
3157       create_all_comp_units (objfile);
3158       create_all_type_units (objfile);
3159       dwarf2_per_objfile->quick_file_names_table =
3160         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3161
3162       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3163                        + dwarf2_per_objfile->n_type_units); ++i)
3164         {
3165           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3166
3167           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3168                                             struct dwarf2_per_cu_quick_data);
3169         }
3170
3171       /* Return 1 so that gdb sees the "quick" functions.  However,
3172          these functions will be no-ops because we will have expanded
3173          all symtabs.  */
3174       return 1;
3175     }
3176
3177   if (dwarf2_read_index (objfile))
3178     return 1;
3179
3180   return 0;
3181 }
3182
3183 \f
3184
3185 /* Build a partial symbol table.  */
3186
3187 void
3188 dwarf2_build_psymtabs (struct objfile *objfile)
3189 {
3190   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3191     {
3192       init_psymbol_list (objfile, 1024);
3193     }
3194
3195   dwarf2_build_psymtabs_hard (objfile);
3196 }
3197
3198 /* Return TRUE if OFFSET is within CU_HEADER.  */
3199
3200 static inline int
3201 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3202 {
3203   sect_offset bottom = { cu_header->offset.sect_off };
3204   sect_offset top = { (cu_header->offset.sect_off + cu_header->length
3205                        + cu_header->initial_length_size) };
3206
3207   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3208 }
3209
3210 /* Read in the comp unit header information from the debug_info at info_ptr.
3211    NOTE: This leaves members offset, first_die_offset to be filled in
3212    by the caller.  */
3213
3214 static gdb_byte *
3215 read_comp_unit_head (struct comp_unit_head *cu_header,
3216                      gdb_byte *info_ptr, bfd *abfd)
3217 {
3218   int signed_addr;
3219   unsigned int bytes_read;
3220
3221   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3222   cu_header->initial_length_size = bytes_read;
3223   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3224   info_ptr += bytes_read;
3225   cu_header->version = read_2_bytes (abfd, info_ptr);
3226   info_ptr += 2;
3227   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3228                                              &bytes_read);
3229   info_ptr += bytes_read;
3230   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3231   info_ptr += 1;
3232   signed_addr = bfd_get_sign_extend_vma (abfd);
3233   if (signed_addr < 0)
3234     internal_error (__FILE__, __LINE__,
3235                     _("read_comp_unit_head: dwarf from non elf file"));
3236   cu_header->signed_addr_p = signed_addr;
3237
3238   return info_ptr;
3239 }
3240
3241 /* Subroutine of read_and_check_comp_unit_head and
3242    read_and_check_type_unit_head to simplify them.
3243    Perform various error checking on the header.  */
3244
3245 static void
3246 error_check_comp_unit_head (struct comp_unit_head *header,
3247                             struct dwarf2_section_info *section)
3248 {
3249   bfd *abfd = section->asection->owner;
3250   const char *filename = bfd_get_filename (abfd);
3251
3252   if (header->version != 2 && header->version != 3 && header->version != 4)
3253     error (_("Dwarf Error: wrong version in compilation unit header "
3254            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3255            filename);
3256
3257   if (header->abbrev_offset.sect_off
3258       >= dwarf2_section_size (dwarf2_per_objfile->objfile,
3259                               &dwarf2_per_objfile->abbrev))
3260     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3261            "(offset 0x%lx + 6) [in module %s]"),
3262            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3263            filename);
3264
3265   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3266      avoid potential 32-bit overflow.  */
3267   if (((unsigned long) header->offset.sect_off
3268        + header->length + header->initial_length_size)
3269       > section->size)
3270     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3271            "(offset 0x%lx + 0) [in module %s]"),
3272            (long) header->length, (long) header->offset.sect_off,
3273            filename);
3274 }
3275
3276 /* Read in a CU/TU header and perform some basic error checking.
3277    The contents of the header are stored in HEADER.
3278    The result is a pointer to the start of the first DIE.  */
3279
3280 static gdb_byte *
3281 read_and_check_comp_unit_head (struct comp_unit_head *header,
3282                                struct dwarf2_section_info *section,
3283                                gdb_byte *info_ptr,
3284                                int is_debug_types_section)
3285 {
3286   gdb_byte *beg_of_comp_unit = info_ptr;
3287   bfd *abfd = section->asection->owner;
3288
3289   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3290
3291   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3292
3293   /* If we're reading a type unit, skip over the signature and
3294      type_offset fields.  */
3295   if (is_debug_types_section)
3296     info_ptr += 8 /*signature*/ + header->offset_size;
3297
3298   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3299
3300   error_check_comp_unit_head (header, section);
3301
3302   return info_ptr;
3303 }
3304
3305 /* Read in the types comp unit header information from .debug_types entry at
3306    types_ptr.  The result is a pointer to one past the end of the header.  */
3307
3308 static gdb_byte *
3309 read_and_check_type_unit_head (struct comp_unit_head *header,
3310                                struct dwarf2_section_info *section,
3311                                gdb_byte *info_ptr,
3312                                ULONGEST *signature,
3313                                cu_offset *type_offset_in_tu)
3314 {
3315   gdb_byte *beg_of_comp_unit = info_ptr;
3316   bfd *abfd = section->asection->owner;
3317
3318   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3319
3320   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3321
3322   /* If we're reading a type unit, skip over the signature and
3323      type_offset fields.  */
3324   if (signature != NULL)
3325     *signature = read_8_bytes (abfd, info_ptr);
3326   info_ptr += 8;
3327   if (type_offset_in_tu != NULL)
3328     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
3329                                                header->offset_size);
3330   info_ptr += header->offset_size;
3331
3332   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3333
3334   error_check_comp_unit_head (header, section);
3335
3336   return info_ptr;
3337 }
3338
3339 /* Allocate a new partial symtab for file named NAME and mark this new
3340    partial symtab as being an include of PST.  */
3341
3342 static void
3343 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
3344                                struct objfile *objfile)
3345 {
3346   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
3347
3348   subpst->section_offsets = pst->section_offsets;
3349   subpst->textlow = 0;
3350   subpst->texthigh = 0;
3351
3352   subpst->dependencies = (struct partial_symtab **)
3353     obstack_alloc (&objfile->objfile_obstack,
3354                    sizeof (struct partial_symtab *));
3355   subpst->dependencies[0] = pst;
3356   subpst->number_of_dependencies = 1;
3357
3358   subpst->globals_offset = 0;
3359   subpst->n_global_syms = 0;
3360   subpst->statics_offset = 0;
3361   subpst->n_static_syms = 0;
3362   subpst->symtab = NULL;
3363   subpst->read_symtab = pst->read_symtab;
3364   subpst->readin = 0;
3365
3366   /* No private part is necessary for include psymtabs.  This property
3367      can be used to differentiate between such include psymtabs and
3368      the regular ones.  */
3369   subpst->read_symtab_private = NULL;
3370 }
3371
3372 /* Read the Line Number Program data and extract the list of files
3373    included by the source file represented by PST.  Build an include
3374    partial symtab for each of these included files.  */
3375
3376 static void
3377 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
3378                                struct die_info *die,
3379                                struct partial_symtab *pst)
3380 {
3381   struct line_header *lh = NULL;
3382   struct attribute *attr;
3383
3384   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
3385   if (attr)
3386     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
3387   if (lh == NULL)
3388     return;  /* No linetable, so no includes.  */
3389
3390   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
3391   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
3392
3393   free_line_header (lh);
3394 }
3395
3396 static hashval_t
3397 hash_signatured_type (const void *item)
3398 {
3399   const struct signatured_type *sig_type = item;
3400
3401   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
3402   return sig_type->signature;
3403 }
3404
3405 static int
3406 eq_signatured_type (const void *item_lhs, const void *item_rhs)
3407 {
3408   const struct signatured_type *lhs = item_lhs;
3409   const struct signatured_type *rhs = item_rhs;
3410
3411   return lhs->signature == rhs->signature;
3412 }
3413
3414 /* Allocate a hash table for signatured types.  */
3415
3416 static htab_t
3417 allocate_signatured_type_table (struct objfile *objfile)
3418 {
3419   return htab_create_alloc_ex (41,
3420                                hash_signatured_type,
3421                                eq_signatured_type,
3422                                NULL,
3423                                &objfile->objfile_obstack,
3424                                hashtab_obstack_allocate,
3425                                dummy_obstack_deallocate);
3426 }
3427
3428 /* A helper function to add a signatured type CU to a table.  */
3429
3430 static int
3431 add_signatured_type_cu_to_table (void **slot, void *datum)
3432 {
3433   struct signatured_type *sigt = *slot;
3434   struct dwarf2_per_cu_data ***datap = datum;
3435
3436   **datap = &sigt->per_cu;
3437   ++*datap;
3438
3439   return 1;
3440 }
3441
3442 /* Create the hash table of all entries in the .debug_types section.
3443    DWO_FILE is a pointer to the DWO file for .debug_types.dwo, NULL otherwise.
3444    The result is a pointer to the hash table or NULL if there are
3445    no types.  */
3446
3447 static htab_t
3448 create_debug_types_hash_table (struct dwo_file *dwo_file,
3449                                VEC (dwarf2_section_info_def) *types)
3450 {
3451   struct objfile *objfile = dwarf2_per_objfile->objfile;
3452   htab_t types_htab = NULL;
3453   int ix;
3454   struct dwarf2_section_info *section;
3455
3456   if (VEC_empty (dwarf2_section_info_def, types))
3457     return NULL;
3458
3459   for (ix = 0;
3460        VEC_iterate (dwarf2_section_info_def, types, ix, section);
3461        ++ix)
3462     {
3463       bfd *abfd;
3464       gdb_byte *info_ptr, *end_ptr;
3465
3466       dwarf2_read_section (objfile, section);
3467       info_ptr = section->buffer;
3468
3469       if (info_ptr == NULL)
3470         continue;
3471
3472       /* We can't set abfd until now because the section may be empty or
3473          not present, in which case section->asection will be NULL.  */
3474       abfd = section->asection->owner;
3475
3476       if (types_htab == NULL)
3477         {
3478           if (dwo_file)
3479             types_htab = allocate_dwo_unit_table (objfile);
3480           else
3481             types_htab = allocate_signatured_type_table (objfile);
3482         }
3483
3484       if (dwarf2_die_debug)
3485         fprintf_unfiltered (gdb_stdlog, "Reading signatured types for %s:\n",
3486                             bfd_get_filename (abfd));
3487
3488       /* We don't use init_cutu_and_read_dies_simple, or some such, here
3489          because we don't need to read any dies: the signature is in the
3490          header.  */
3491
3492       end_ptr = info_ptr + section->size;
3493       while (info_ptr < end_ptr)
3494         {
3495           sect_offset offset;
3496           cu_offset type_offset_in_tu;
3497           ULONGEST signature;
3498           struct signatured_type *sig_type;
3499           struct dwo_unit *dwo_tu;
3500           void **slot;
3501           gdb_byte *ptr = info_ptr;
3502           struct comp_unit_head header;
3503           unsigned int length;
3504
3505           offset.sect_off = ptr - section->buffer;
3506
3507           /* We need to read the type's signature in order to build the hash
3508              table, but we don't need anything else just yet.  */
3509
3510           ptr = read_and_check_type_unit_head (&header, section, ptr,
3511                                                &signature, &type_offset_in_tu);
3512
3513           length = header.initial_length_size + header.length;
3514
3515           /* Skip dummy type units.  */
3516           if (ptr >= info_ptr + length
3517               || peek_abbrev_code (abfd, ptr) == 0)
3518             {
3519               info_ptr += header.initial_length_size + header.length;
3520               continue;
3521             }
3522
3523           if (dwo_file)
3524             {
3525               sig_type = NULL;
3526               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3527                                        struct dwo_unit);
3528               dwo_tu->dwo_file = dwo_file;
3529               dwo_tu->signature = signature;
3530               dwo_tu->type_offset_in_tu = type_offset_in_tu;
3531               dwo_tu->info_or_types_section = section;
3532               dwo_tu->offset = offset;
3533               dwo_tu->length = length;
3534             }
3535           else
3536             {
3537               /* N.B.: type_offset is not usable if this type uses a DWO file.
3538                  The real type_offset is in the DWO file.  */
3539               dwo_tu = NULL;
3540               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3541                                          struct signatured_type);
3542               sig_type->signature = signature;
3543               sig_type->type_offset_in_tu = type_offset_in_tu;
3544               sig_type->per_cu.objfile = objfile;
3545               sig_type->per_cu.is_debug_types = 1;
3546               sig_type->per_cu.info_or_types_section = section;
3547               sig_type->per_cu.offset = offset;
3548               sig_type->per_cu.length = length;
3549             }
3550
3551           slot = htab_find_slot (types_htab,
3552                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
3553                                  INSERT);
3554           gdb_assert (slot != NULL);
3555           if (*slot != NULL)
3556             {
3557               sect_offset dup_offset;
3558
3559               if (dwo_file)
3560                 {
3561                   const struct dwo_unit *dup_tu = *slot;
3562
3563                   dup_offset = dup_tu->offset;
3564                 }
3565               else
3566                 {
3567                   const struct signatured_type *dup_tu = *slot;
3568
3569                   dup_offset = dup_tu->per_cu.offset;
3570                 }
3571
3572               complaint (&symfile_complaints,
3573                          _("debug type entry at offset 0x%x is duplicate to the "
3574                            "entry at offset 0x%x, signature 0x%s"),
3575                          offset.sect_off, dup_offset.sect_off,
3576                          phex (signature, sizeof (signature)));
3577             }
3578           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
3579
3580           if (dwarf2_die_debug)
3581             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
3582                                 offset.sect_off,
3583                                 phex (signature, sizeof (signature)));
3584
3585           info_ptr += length;
3586         }
3587     }
3588
3589   return types_htab;
3590 }
3591
3592 /* Create the hash table of all entries in the .debug_types section,
3593    and initialize all_type_units.
3594    The result is zero if there is an error (e.g. missing .debug_types section),
3595    otherwise non-zero.  */
3596
3597 static int
3598 create_all_type_units (struct objfile *objfile)
3599 {
3600   htab_t types_htab;
3601   struct dwarf2_per_cu_data **iter;
3602
3603   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
3604   if (types_htab == NULL)
3605     {
3606       dwarf2_per_objfile->signatured_types = NULL;
3607       return 0;
3608     }
3609
3610   dwarf2_per_objfile->signatured_types = types_htab;
3611
3612   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
3613   dwarf2_per_objfile->all_type_units
3614     = obstack_alloc (&objfile->objfile_obstack,
3615                      dwarf2_per_objfile->n_type_units
3616                      * sizeof (struct dwarf2_per_cu_data *));
3617   iter = &dwarf2_per_objfile->all_type_units[0];
3618   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
3619   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
3620               == dwarf2_per_objfile->n_type_units);
3621
3622   return 1;
3623 }
3624
3625 /* Lookup a signature based type for DW_FORM_ref_sig8.
3626    Returns NULL if signature SIG is not present in the table.  */
3627
3628 static struct signatured_type *
3629 lookup_signatured_type (ULONGEST sig)
3630 {
3631   struct signatured_type find_entry, *entry;
3632
3633   if (dwarf2_per_objfile->signatured_types == NULL)
3634     {
3635       complaint (&symfile_complaints,
3636                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
3637       return NULL;
3638     }
3639
3640   find_entry.signature = sig;
3641   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
3642   return entry;
3643 }
3644
3645 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
3646
3647 static void
3648 init_cu_die_reader (struct die_reader_specs *reader,
3649                     struct dwarf2_cu *cu,
3650                     struct dwarf2_section_info *section,
3651                     struct dwo_file *dwo_file)
3652 {
3653   gdb_assert (section->readin && section->buffer != NULL);
3654   reader->abfd = section->asection->owner;
3655   reader->cu = cu;
3656   reader->dwo_file = dwo_file;
3657   reader->die_section = section;
3658   reader->buffer = section->buffer;
3659 }
3660
3661 /* Find the base address of the compilation unit for range lists and
3662    location lists.  It will normally be specified by DW_AT_low_pc.
3663    In DWARF-3 draft 4, the base address could be overridden by
3664    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3665    compilation units with discontinuous ranges.  */
3666
3667 static void
3668 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3669 {
3670   struct attribute *attr;
3671
3672   cu->base_known = 0;
3673   cu->base_address = 0;
3674
3675   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3676   if (attr)
3677     {
3678       cu->base_address = DW_ADDR (attr);
3679       cu->base_known = 1;
3680     }
3681   else
3682     {
3683       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3684       if (attr)
3685         {
3686           cu->base_address = DW_ADDR (attr);
3687           cu->base_known = 1;
3688         }
3689     }
3690 }
3691
3692 /* Initialize a CU (or TU) and read its DIEs.
3693    If the CU defers to a DWO file, read the DWO file as well.
3694
3695    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
3696    Otherwise, a new CU is allocated with xmalloc.
3697
3698    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
3699    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
3700
3701    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
3702    linker) then DIE_READER_FUNC will not get called.  */
3703
3704 static void
3705 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
3706                          int use_existing_cu, int keep,
3707                          die_reader_func_ftype *die_reader_func,
3708                          void *data)
3709 {
3710   struct objfile *objfile = dwarf2_per_objfile->objfile;
3711   struct dwarf2_section_info *section = this_cu->info_or_types_section;
3712   bfd *abfd = section->asection->owner;
3713   struct dwarf2_cu *cu;
3714   gdb_byte *begin_info_ptr, *info_ptr;
3715   struct die_reader_specs reader;
3716   struct die_info *comp_unit_die;
3717   int has_children;
3718   struct attribute *attr;
3719   struct cleanup *cleanups, *free_cu_cleanup = NULL;
3720   struct signatured_type *sig_type = NULL;
3721
3722   if (use_existing_cu)
3723     gdb_assert (keep);
3724
3725   cleanups = make_cleanup (null_cleanup, NULL);
3726
3727   /* This is cheap if the section is already read in.  */
3728   dwarf2_read_section (objfile, section);
3729
3730   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
3731
3732   if (use_existing_cu && this_cu->cu != NULL)
3733     {
3734       cu = this_cu->cu;
3735       info_ptr += cu->header.first_die_offset.cu_off;
3736     }
3737   else
3738     {
3739       /* If !use_existing_cu, this_cu->cu must be NULL.  */
3740       gdb_assert (this_cu->cu == NULL);
3741
3742       cu = xmalloc (sizeof (*cu));
3743       init_one_comp_unit (cu, this_cu);
3744
3745       /* If an error occurs while loading, release our storage.  */
3746       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
3747
3748       if (this_cu->is_debug_types)
3749         {
3750           ULONGEST signature;
3751
3752           info_ptr = read_and_check_type_unit_head (&cu->header,
3753                                                     section, info_ptr,
3754                                                     &signature, NULL);
3755
3756           /* There's no way to get from PER_CU to its containing
3757              struct signatured_type.
3758              But we have the signature so we can use that.  */
3759           sig_type = lookup_signatured_type (signature);
3760           /* We've already scanned all the signatured types,
3761              this must succeed.  */
3762           gdb_assert (sig_type != NULL);
3763           gdb_assert (&sig_type->per_cu == this_cu);
3764           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
3765
3766           /* LENGTH has not been set yet for type units.  */
3767           this_cu->length = cu->header.length + cu->header.initial_length_size;
3768
3769           /* Establish the type offset that can be used to lookup the type.  */
3770           sig_type->type_offset_in_section.sect_off =
3771             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
3772         }
3773       else
3774         {
3775           info_ptr = read_and_check_comp_unit_head (&cu->header,
3776                                                     section, info_ptr, 0);
3777
3778           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
3779           gdb_assert (this_cu->length
3780                       == cu->header.length + cu->header.initial_length_size);
3781         }
3782     }
3783
3784   /* Skip dummy compilation units.  */
3785   if (info_ptr >= begin_info_ptr + this_cu->length
3786       || peek_abbrev_code (abfd, info_ptr) == 0)
3787     {
3788       do_cleanups (cleanups);
3789       return;
3790     }
3791
3792   /* Read the abbrevs for this compilation unit into a table.  */
3793   if (cu->dwarf2_abbrevs == NULL)
3794     {
3795       dwarf2_read_abbrevs (cu, &dwarf2_per_objfile->abbrev);
3796       make_cleanup (dwarf2_free_abbrev_table, cu);
3797     }
3798
3799   /* Read the top level CU/TU die.  */
3800   init_cu_die_reader (&reader, cu, section, NULL);
3801   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
3802
3803   /* If we have a DWO stub, process it and then read in the DWO file.
3804      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
3805      a DWO CU, that this test will fail.  */
3806   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
3807   if (attr)
3808     {
3809       char *dwo_name = DW_STRING (attr);
3810       const char *comp_dir;
3811       struct dwo_unit *dwo_unit;
3812       ULONGEST signature; /* Or dwo_id.  */
3813       struct attribute *stmt_list, *low_pc, *high_pc, *ranges;
3814       int i,num_extra_attrs;
3815
3816       if (has_children)
3817         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
3818                  " has children (offset 0x%x) [in module %s]"),
3819                this_cu->offset.sect_off, bfd_get_filename (abfd));
3820
3821       /* These attributes aren't processed until later:
3822          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
3823          However, the attribute is found in the stub which we won't have later.
3824          In order to not impose this complication on the rest of the code,
3825          we read them here and copy them to the DWO CU/TU die.  */
3826       stmt_list = low_pc = high_pc = ranges = NULL;
3827
3828       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
3829          DWO file.  */
3830       if (! this_cu->is_debug_types)
3831         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3832       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
3833       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
3834       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
3835
3836       /* There should be a DW_AT_addr_base attribute here (if needed).
3837          We need the value before we can process DW_FORM_GNU_addr_index.  */
3838       cu->addr_base = 0;
3839       cu->have_addr_base = 0;
3840       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
3841       if (attr)
3842         {
3843           cu->addr_base = DW_UNSND (attr);
3844           cu->have_addr_base = 1;
3845         }
3846
3847       if (this_cu->is_debug_types)
3848         {
3849           gdb_assert (sig_type != NULL);
3850           signature = sig_type->signature;
3851         }
3852       else
3853         {
3854           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
3855           if (! attr)
3856             error (_("Dwarf Error: missing dwo_id [in module %s]"),
3857                    dwo_name);
3858           signature = DW_UNSND (attr);
3859         }
3860
3861       /* We may need the comp_dir in order to find the DWO file.  */
3862       comp_dir = NULL;
3863       attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
3864       if (attr)
3865         comp_dir = DW_STRING (attr);
3866
3867       if (this_cu->is_debug_types)
3868         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
3869       else
3870         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
3871                                          signature);
3872
3873       if (dwo_unit == NULL)
3874         {
3875           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
3876                    " with ID %s [in module %s]"),
3877                  this_cu->offset.sect_off,
3878                  phex (signature, sizeof (signature)),
3879                  objfile->name);
3880         }
3881
3882       /* Set up for reading the DWO CU/TU.  */
3883       cu->dwo_unit = dwo_unit;
3884       section = dwo_unit->info_or_types_section;
3885       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
3886       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
3887
3888       if (this_cu->is_debug_types)
3889         {
3890           ULONGEST signature;
3891
3892           info_ptr = read_and_check_type_unit_head (&cu->header,
3893                                                     section, info_ptr,
3894                                                     &signature, NULL);
3895           gdb_assert (sig_type->signature == signature);
3896           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
3897           gdb_assert (dwo_unit->length
3898                       == cu->header.length + cu->header.initial_length_size);
3899
3900           /* Establish the type offset that can be used to lookup the type.
3901              For DWO files, we don't know it until now.  */
3902           sig_type->type_offset_in_section.sect_off =
3903             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
3904         }
3905       else
3906         {
3907           info_ptr = read_and_check_comp_unit_head (&cu->header,
3908                                                     section, info_ptr, 0);
3909           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
3910           gdb_assert (dwo_unit->length
3911                       == cu->header.length + cu->header.initial_length_size);
3912         }
3913
3914       /* Discard the original CU's abbrev table, and read the DWO's.  */
3915       dwarf2_free_abbrev_table (cu);
3916       dwarf2_read_abbrevs (cu, &dwo_unit->dwo_file->sections.abbrev);
3917
3918       /* Read in the die, but leave space to copy over the attributes
3919          from the stub.  This has the benefit of simplifying the rest of
3920          the code - all the real work is done here.  */
3921       num_extra_attrs = ((stmt_list != NULL)
3922                          + (low_pc != NULL)
3923                          + (high_pc != NULL)
3924                          + (ranges != NULL));
3925       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
3926                                   &has_children, num_extra_attrs);
3927
3928       /* Copy over the attributes from the stub to the DWO die.  */
3929       i = comp_unit_die->num_attrs;
3930       if (stmt_list != NULL)
3931         comp_unit_die->attrs[i++] = *stmt_list;
3932       if (low_pc != NULL)
3933         comp_unit_die->attrs[i++] = *low_pc;
3934       if (high_pc != NULL)
3935         comp_unit_die->attrs[i++] = *high_pc;
3936       if (ranges != NULL)
3937         comp_unit_die->attrs[i++] = *ranges;
3938       comp_unit_die->num_attrs += num_extra_attrs;
3939
3940       /* Skip dummy compilation units.  */
3941       if (info_ptr >= begin_info_ptr + dwo_unit->length
3942           || peek_abbrev_code (abfd, info_ptr) == 0)
3943         {
3944           do_cleanups (cleanups);
3945           return;
3946         }
3947     }
3948
3949   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
3950
3951   if (free_cu_cleanup != NULL)
3952     {
3953       if (keep)
3954         {
3955           /* We've successfully allocated this compilation unit.  Let our
3956              caller clean it up when finished with it.  */
3957           discard_cleanups (free_cu_cleanup);
3958
3959           /* We can only discard free_cu_cleanup and all subsequent cleanups.
3960              So we have to manually free the abbrev table.  */
3961           dwarf2_free_abbrev_table (cu);
3962
3963           /* Link this CU into read_in_chain.  */
3964           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
3965           dwarf2_per_objfile->read_in_chain = this_cu;
3966         }
3967       else
3968         do_cleanups (free_cu_cleanup);
3969     }
3970
3971   do_cleanups (cleanups);
3972 }
3973
3974 /* Read CU/TU THIS_CU in section SECTION,
3975    but do not follow DW_AT_GNU_dwo_name if present.
3976    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed to
3977    have already done the lookup to find the DWO file).
3978
3979    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
3980    THIS_CU->is_debug_types, but nothing else.
3981
3982    We fill in THIS_CU->length.
3983
3984    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
3985    linker) then DIE_READER_FUNC will not get called.
3986
3987    THIS_CU->cu is always freed when done.
3988    This is done in order to not leave THIS_CU->cu in a state where we have
3989    to care whether it refers to the "main" CU or the DWO CU.  */
3990
3991 static void
3992 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
3993                                    struct dwarf2_section_info *abbrev_section,
3994                                    struct dwo_file *dwo_file,
3995                                    die_reader_func_ftype *die_reader_func,
3996                                    void *data)
3997 {
3998   struct objfile *objfile = dwarf2_per_objfile->objfile;
3999   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4000   bfd *abfd = section->asection->owner;
4001   struct dwarf2_cu cu;
4002   gdb_byte *begin_info_ptr, *info_ptr;
4003   struct die_reader_specs reader;
4004   struct cleanup *cleanups;
4005   struct die_info *comp_unit_die;
4006   int has_children;
4007
4008   gdb_assert (this_cu->cu == NULL);
4009
4010   /* This is cheap if the section is already read in.  */
4011   dwarf2_read_section (objfile, section);
4012
4013   init_one_comp_unit (&cu, this_cu);
4014
4015   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4016
4017   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4018   info_ptr = read_and_check_comp_unit_head (&cu.header, section, info_ptr,
4019                                             this_cu->is_debug_types);
4020
4021   this_cu->length = cu.header.length + cu.header.initial_length_size;
4022
4023   /* Skip dummy compilation units.  */
4024   if (info_ptr >= begin_info_ptr + this_cu->length
4025       || peek_abbrev_code (abfd, info_ptr) == 0)
4026     {
4027       do_cleanups (cleanups);
4028       return;
4029     }
4030
4031   dwarf2_read_abbrevs (&cu, abbrev_section);
4032   make_cleanup (dwarf2_free_abbrev_table, &cu);
4033
4034   init_cu_die_reader (&reader, &cu, section, dwo_file);
4035   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4036
4037   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4038
4039   do_cleanups (cleanups);
4040 }
4041
4042 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4043    does not lookup the specified DWO file.
4044    This cannot be used to read DWO files.
4045
4046    THIS_CU->cu is always freed when done.
4047    This is done in order to not leave THIS_CU->cu in a state where we have
4048    to care whether it refers to the "main" CU or the DWO CU.
4049    We can revisit this if the data shows there's a performance issue.  */
4050
4051 static void
4052 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4053                                 die_reader_func_ftype *die_reader_func,
4054                                 void *data)
4055 {
4056   init_cutu_and_read_dies_no_follow (this_cu,
4057                                      &dwarf2_per_objfile->abbrev,
4058                                      NULL,
4059                                      die_reader_func, data);
4060 }
4061
4062 /* die_reader_func for process_psymtab_comp_unit.  */
4063
4064 static void
4065 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4066                                   gdb_byte *info_ptr,
4067                                   struct die_info *comp_unit_die,
4068                                   int has_children,
4069                                   void *data)
4070 {
4071   struct dwarf2_cu *cu = reader->cu;
4072   struct objfile *objfile = cu->objfile;
4073   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4074   struct attribute *attr;
4075   CORE_ADDR baseaddr;
4076   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4077   struct partial_symtab *pst;
4078   int has_pc_info;
4079   const char *filename;
4080   int *want_partial_unit_ptr = data;
4081
4082   if (comp_unit_die->tag == DW_TAG_partial_unit
4083       && (want_partial_unit_ptr == NULL
4084           || !*want_partial_unit_ptr))
4085     return;
4086
4087   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4088
4089   cu->list_in_scope = &file_symbols;
4090
4091   /* Allocate a new partial symbol table structure.  */
4092   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4093   if (attr == NULL || !DW_STRING (attr))
4094     filename = "";
4095   else
4096     filename = DW_STRING (attr);
4097   pst = start_psymtab_common (objfile, objfile->section_offsets,
4098                               filename,
4099                               /* TEXTLOW and TEXTHIGH are set below.  */
4100                               0,
4101                               objfile->global_psymbols.next,
4102                               objfile->static_psymbols.next);
4103   pst->psymtabs_addrmap_supported = 1;
4104
4105   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4106   if (attr != NULL)
4107     pst->dirname = DW_STRING (attr);
4108
4109   pst->read_symtab_private = per_cu;
4110
4111   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4112
4113   /* Store the function that reads in the rest of the symbol table.  */
4114   pst->read_symtab = dwarf2_psymtab_to_symtab;
4115
4116   per_cu->v.psymtab = pst;
4117
4118   dwarf2_find_base_address (comp_unit_die, cu);
4119
4120   /* Possibly set the default values of LOWPC and HIGHPC from
4121      `DW_AT_ranges'.  */
4122   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4123                                       &best_highpc, cu, pst);
4124   if (has_pc_info == 1 && best_lowpc < best_highpc)
4125     /* Store the contiguous range if it is not empty; it can be empty for
4126        CUs with no code.  */
4127     addrmap_set_empty (objfile->psymtabs_addrmap,
4128                        best_lowpc + baseaddr,
4129                        best_highpc + baseaddr - 1, pst);
4130
4131   /* Check if comp unit has_children.
4132      If so, read the rest of the partial symbols from this comp unit.
4133      If not, there's no more debug_info for this comp unit.  */
4134   if (has_children)
4135     {
4136       struct partial_die_info *first_die;
4137       CORE_ADDR lowpc, highpc;
4138
4139       lowpc = ((CORE_ADDR) -1);
4140       highpc = ((CORE_ADDR) 0);
4141
4142       first_die = load_partial_dies (reader, info_ptr, 1);
4143
4144       scan_partial_symbols (first_die, &lowpc, &highpc,
4145                             ! has_pc_info, cu);
4146
4147       /* If we didn't find a lowpc, set it to highpc to avoid
4148          complaints from `maint check'.  */
4149       if (lowpc == ((CORE_ADDR) -1))
4150         lowpc = highpc;
4151
4152       /* If the compilation unit didn't have an explicit address range,
4153          then use the information extracted from its child dies.  */
4154       if (! has_pc_info)
4155         {
4156           best_lowpc = lowpc;
4157           best_highpc = highpc;
4158         }
4159     }
4160   pst->textlow = best_lowpc + baseaddr;
4161   pst->texthigh = best_highpc + baseaddr;
4162
4163   pst->n_global_syms = objfile->global_psymbols.next -
4164     (objfile->global_psymbols.list + pst->globals_offset);
4165   pst->n_static_syms = objfile->static_psymbols.next -
4166     (objfile->static_psymbols.list + pst->statics_offset);
4167   sort_pst_symbols (pst);
4168
4169   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
4170     {
4171       int i;
4172       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4173       struct dwarf2_per_cu_data *iter;
4174
4175       /* Fill in 'dependencies' here; we fill in 'users' in a
4176          post-pass.  */
4177       pst->number_of_dependencies = len;
4178       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4179                                          len * sizeof (struct symtab *));
4180       for (i = 0;
4181            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
4182                         i, iter);
4183            ++i)
4184         pst->dependencies[i] = iter->v.psymtab;
4185
4186       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4187     }
4188
4189   if (per_cu->is_debug_types)
4190     {
4191       /* It's not clear we want to do anything with stmt lists here.
4192          Waiting to see what gcc ultimately does.  */
4193     }
4194   else
4195     {
4196       /* Get the list of files included in the current compilation unit,
4197          and build a psymtab for each of them.  */
4198       dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
4199     }
4200 }
4201
4202 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4203    Process compilation unit THIS_CU for a psymtab.  */
4204
4205 static void
4206 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
4207                            int want_partial_unit)
4208 {
4209   /* If this compilation unit was already read in, free the
4210      cached copy in order to read it in again.  This is
4211      necessary because we skipped some symbols when we first
4212      read in the compilation unit (see load_partial_dies).
4213      This problem could be avoided, but the benefit is unclear.  */
4214   if (this_cu->cu != NULL)
4215     free_one_cached_comp_unit (this_cu);
4216
4217   gdb_assert (! this_cu->is_debug_types);
4218   init_cutu_and_read_dies (this_cu, 0, 0, process_psymtab_comp_unit_reader,
4219                            &want_partial_unit);
4220
4221   /* Age out any secondary CUs.  */
4222   age_cached_comp_units ();
4223 }
4224
4225 /* Traversal function for htab_traverse_noresize.
4226    Process one .debug_types comp-unit.  */
4227
4228 static int
4229 process_psymtab_type_unit (void **slot, void *info)
4230 {
4231   struct signatured_type *sig_type = (struct signatured_type *) *slot;
4232   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
4233
4234   gdb_assert (per_cu->is_debug_types);
4235   gdb_assert (info == NULL);
4236
4237   /* If this compilation unit was already read in, free the
4238      cached copy in order to read it in again.  This is
4239      necessary because we skipped some symbols when we first
4240      read in the compilation unit (see load_partial_dies).
4241      This problem could be avoided, but the benefit is unclear.  */
4242   if (per_cu->cu != NULL)
4243     free_one_cached_comp_unit (per_cu);
4244
4245   init_cutu_and_read_dies (per_cu, 0, 0, process_psymtab_comp_unit_reader,
4246                            NULL);
4247
4248   /* Age out any secondary CUs.  */
4249   age_cached_comp_units ();
4250
4251   return 1;
4252 }
4253
4254 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4255    Build partial symbol tables for the .debug_types comp-units.  */
4256
4257 static void
4258 build_type_psymtabs (struct objfile *objfile)
4259 {
4260   if (! create_all_type_units (objfile))
4261     return;
4262
4263   htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
4264                           process_psymtab_type_unit, NULL);
4265 }
4266
4267 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
4268
4269 static void
4270 psymtabs_addrmap_cleanup (void *o)
4271 {
4272   struct objfile *objfile = o;
4273
4274   objfile->psymtabs_addrmap = NULL;
4275 }
4276
4277 /* Compute the 'user' field for each psymtab in OBJFILE.  */
4278
4279 static void
4280 set_partial_user (struct objfile *objfile)
4281 {
4282   int i;
4283
4284   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4285     {
4286       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4287       struct partial_symtab *pst = per_cu->v.psymtab;
4288       int j;
4289
4290       for (j = 0; j < pst->number_of_dependencies; ++j)
4291         {
4292           /* Set the 'user' field only if it is not already set.  */
4293           if (pst->dependencies[j]->user == NULL)
4294             pst->dependencies[j]->user = pst;
4295         }
4296     }
4297 }
4298
4299 /* Build the partial symbol table by doing a quick pass through the
4300    .debug_info and .debug_abbrev sections.  */
4301
4302 static void
4303 dwarf2_build_psymtabs_hard (struct objfile *objfile)
4304 {
4305   struct cleanup *back_to, *addrmap_cleanup;
4306   struct obstack temp_obstack;
4307   int i;
4308
4309   dwarf2_per_objfile->reading_partial_symbols = 1;
4310
4311   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
4312
4313   /* Any cached compilation units will be linked by the per-objfile
4314      read_in_chain.  Make sure to free them when we're done.  */
4315   back_to = make_cleanup (free_cached_comp_units, NULL);
4316
4317   build_type_psymtabs (objfile);
4318
4319   create_all_comp_units (objfile);
4320
4321   /* Create a temporary address map on a temporary obstack.  We later
4322      copy this to the final obstack.  */
4323   obstack_init (&temp_obstack);
4324   make_cleanup_obstack_free (&temp_obstack);
4325   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
4326   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
4327
4328   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4329     {
4330       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4331
4332       process_psymtab_comp_unit (per_cu, 0);
4333     }
4334
4335   set_partial_user (objfile);
4336
4337   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
4338                                                     &objfile->objfile_obstack);
4339   discard_cleanups (addrmap_cleanup);
4340
4341   do_cleanups (back_to);
4342 }
4343
4344 /* die_reader_func for load_partial_comp_unit.  */
4345
4346 static void
4347 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
4348                                gdb_byte *info_ptr,
4349                                struct die_info *comp_unit_die,
4350                                int has_children,
4351                                void *data)
4352 {
4353   struct dwarf2_cu *cu = reader->cu;
4354
4355   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4356
4357   /* Check if comp unit has_children.
4358      If so, read the rest of the partial symbols from this comp unit.
4359      If not, there's no more debug_info for this comp unit.  */
4360   if (has_children)
4361     load_partial_dies (reader, info_ptr, 0);
4362 }
4363
4364 /* Load the partial DIEs for a secondary CU into memory.
4365    This is also used when rereading a primary CU with load_all_dies.  */
4366
4367 static void
4368 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
4369 {
4370   init_cutu_and_read_dies (this_cu, 1, 1, load_partial_comp_unit_reader, NULL);
4371 }
4372
4373 /* Create a list of all compilation units in OBJFILE.
4374    This is only done for -readnow and building partial symtabs.  */
4375
4376 static void
4377 create_all_comp_units (struct objfile *objfile)
4378 {
4379   int n_allocated;
4380   int n_comp_units;
4381   struct dwarf2_per_cu_data **all_comp_units;
4382   gdb_byte *info_ptr;
4383
4384   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
4385   info_ptr = dwarf2_per_objfile->info.buffer;
4386
4387   n_comp_units = 0;
4388   n_allocated = 10;
4389   all_comp_units = xmalloc (n_allocated
4390                             * sizeof (struct dwarf2_per_cu_data *));
4391
4392   while (info_ptr < dwarf2_per_objfile->info.buffer
4393          + dwarf2_per_objfile->info.size)
4394     {
4395       unsigned int length, initial_length_size;
4396       struct dwarf2_per_cu_data *this_cu;
4397       sect_offset offset;
4398
4399       offset.sect_off = info_ptr - dwarf2_per_objfile->info.buffer;
4400
4401       /* Read just enough information to find out where the next
4402          compilation unit is.  */
4403       length = read_initial_length (objfile->obfd, info_ptr,
4404                                     &initial_length_size);
4405
4406       /* Save the compilation unit for later lookup.  */
4407       this_cu = obstack_alloc (&objfile->objfile_obstack,
4408                                sizeof (struct dwarf2_per_cu_data));
4409       memset (this_cu, 0, sizeof (*this_cu));
4410       this_cu->offset = offset;
4411       this_cu->length = length + initial_length_size;
4412       this_cu->objfile = objfile;
4413       this_cu->info_or_types_section = &dwarf2_per_objfile->info;
4414
4415       if (n_comp_units == n_allocated)
4416         {
4417           n_allocated *= 2;
4418           all_comp_units = xrealloc (all_comp_units,
4419                                      n_allocated
4420                                      * sizeof (struct dwarf2_per_cu_data *));
4421         }
4422       all_comp_units[n_comp_units++] = this_cu;
4423
4424       info_ptr = info_ptr + this_cu->length;
4425     }
4426
4427   dwarf2_per_objfile->all_comp_units
4428     = obstack_alloc (&objfile->objfile_obstack,
4429                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
4430   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
4431           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
4432   xfree (all_comp_units);
4433   dwarf2_per_objfile->n_comp_units = n_comp_units;
4434 }
4435
4436 /* Process all loaded DIEs for compilation unit CU, starting at
4437    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
4438    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
4439    DW_AT_ranges).  If NEED_PC is set, then this function will set
4440    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
4441    and record the covered ranges in the addrmap.  */
4442
4443 static void
4444 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
4445                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
4446 {
4447   struct partial_die_info *pdi;
4448
4449   /* Now, march along the PDI's, descending into ones which have
4450      interesting children but skipping the children of the other ones,
4451      until we reach the end of the compilation unit.  */
4452
4453   pdi = first_die;
4454
4455   while (pdi != NULL)
4456     {
4457       fixup_partial_die (pdi, cu);
4458
4459       /* Anonymous namespaces or modules have no name but have interesting
4460          children, so we need to look at them.  Ditto for anonymous
4461          enums.  */
4462
4463       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
4464           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
4465           || pdi->tag == DW_TAG_imported_unit)
4466         {
4467           switch (pdi->tag)
4468             {
4469             case DW_TAG_subprogram:
4470               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
4471               break;
4472             case DW_TAG_constant:
4473             case DW_TAG_variable:
4474             case DW_TAG_typedef:
4475             case DW_TAG_union_type:
4476               if (!pdi->is_declaration)
4477                 {
4478                   add_partial_symbol (pdi, cu);
4479                 }
4480               break;
4481             case DW_TAG_class_type:
4482             case DW_TAG_interface_type:
4483             case DW_TAG_structure_type:
4484               if (!pdi->is_declaration)
4485                 {
4486                   add_partial_symbol (pdi, cu);
4487                 }
4488               break;
4489             case DW_TAG_enumeration_type:
4490               if (!pdi->is_declaration)
4491                 add_partial_enumeration (pdi, cu);
4492               break;
4493             case DW_TAG_base_type:
4494             case DW_TAG_subrange_type:
4495               /* File scope base type definitions are added to the partial
4496                  symbol table.  */
4497               add_partial_symbol (pdi, cu);
4498               break;
4499             case DW_TAG_namespace:
4500               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
4501               break;
4502             case DW_TAG_module:
4503               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
4504               break;
4505             case DW_TAG_imported_unit:
4506               {
4507                 struct dwarf2_per_cu_data *per_cu;
4508
4509                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
4510                                                            cu->objfile);
4511
4512                 /* Go read the partial unit, if needed.  */
4513                 if (per_cu->v.psymtab == NULL)
4514                   process_psymtab_comp_unit (per_cu, 1);
4515
4516                 VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
4517                                per_cu);
4518               }
4519               break;
4520             default:
4521               break;
4522             }
4523         }
4524
4525       /* If the die has a sibling, skip to the sibling.  */
4526
4527       pdi = pdi->die_sibling;
4528     }
4529 }
4530
4531 /* Functions used to compute the fully scoped name of a partial DIE.
4532
4533    Normally, this is simple.  For C++, the parent DIE's fully scoped
4534    name is concatenated with "::" and the partial DIE's name.  For
4535    Java, the same thing occurs except that "." is used instead of "::".
4536    Enumerators are an exception; they use the scope of their parent
4537    enumeration type, i.e. the name of the enumeration type is not
4538    prepended to the enumerator.
4539
4540    There are two complexities.  One is DW_AT_specification; in this
4541    case "parent" means the parent of the target of the specification,
4542    instead of the direct parent of the DIE.  The other is compilers
4543    which do not emit DW_TAG_namespace; in this case we try to guess
4544    the fully qualified name of structure types from their members'
4545    linkage names.  This must be done using the DIE's children rather
4546    than the children of any DW_AT_specification target.  We only need
4547    to do this for structures at the top level, i.e. if the target of
4548    any DW_AT_specification (if any; otherwise the DIE itself) does not
4549    have a parent.  */
4550
4551 /* Compute the scope prefix associated with PDI's parent, in
4552    compilation unit CU.  The result will be allocated on CU's
4553    comp_unit_obstack, or a copy of the already allocated PDI->NAME
4554    field.  NULL is returned if no prefix is necessary.  */
4555 static char *
4556 partial_die_parent_scope (struct partial_die_info *pdi,
4557                           struct dwarf2_cu *cu)
4558 {
4559   char *grandparent_scope;
4560   struct partial_die_info *parent, *real_pdi;
4561
4562   /* We need to look at our parent DIE; if we have a DW_AT_specification,
4563      then this means the parent of the specification DIE.  */
4564
4565   real_pdi = pdi;
4566   while (real_pdi->has_specification)
4567     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
4568
4569   parent = real_pdi->die_parent;
4570   if (parent == NULL)
4571     return NULL;
4572
4573   if (parent->scope_set)
4574     return parent->scope;
4575
4576   fixup_partial_die (parent, cu);
4577
4578   grandparent_scope = partial_die_parent_scope (parent, cu);
4579
4580   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
4581      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
4582      Work around this problem here.  */
4583   if (cu->language == language_cplus
4584       && parent->tag == DW_TAG_namespace
4585       && strcmp (parent->name, "::") == 0
4586       && grandparent_scope == NULL)
4587     {
4588       parent->scope = NULL;
4589       parent->scope_set = 1;
4590       return NULL;
4591     }
4592
4593   if (pdi->tag == DW_TAG_enumerator)
4594     /* Enumerators should not get the name of the enumeration as a prefix.  */
4595     parent->scope = grandparent_scope;
4596   else if (parent->tag == DW_TAG_namespace
4597       || parent->tag == DW_TAG_module
4598       || parent->tag == DW_TAG_structure_type
4599       || parent->tag == DW_TAG_class_type
4600       || parent->tag == DW_TAG_interface_type
4601       || parent->tag == DW_TAG_union_type
4602       || parent->tag == DW_TAG_enumeration_type)
4603     {
4604       if (grandparent_scope == NULL)
4605         parent->scope = parent->name;
4606       else
4607         parent->scope = typename_concat (&cu->comp_unit_obstack,
4608                                          grandparent_scope,
4609                                          parent->name, 0, cu);
4610     }
4611   else
4612     {
4613       /* FIXME drow/2004-04-01: What should we be doing with
4614          function-local names?  For partial symbols, we should probably be
4615          ignoring them.  */
4616       complaint (&symfile_complaints,
4617                  _("unhandled containing DIE tag %d for DIE at %d"),
4618                  parent->tag, pdi->offset.sect_off);
4619       parent->scope = grandparent_scope;
4620     }
4621
4622   parent->scope_set = 1;
4623   return parent->scope;
4624 }
4625
4626 /* Return the fully scoped name associated with PDI, from compilation unit
4627    CU.  The result will be allocated with malloc.  */
4628
4629 static char *
4630 partial_die_full_name (struct partial_die_info *pdi,
4631                        struct dwarf2_cu *cu)
4632 {
4633   char *parent_scope;
4634
4635   /* If this is a template instantiation, we can not work out the
4636      template arguments from partial DIEs.  So, unfortunately, we have
4637      to go through the full DIEs.  At least any work we do building
4638      types here will be reused if full symbols are loaded later.  */
4639   if (pdi->has_template_arguments)
4640     {
4641       fixup_partial_die (pdi, cu);
4642
4643       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
4644         {
4645           struct die_info *die;
4646           struct attribute attr;
4647           struct dwarf2_cu *ref_cu = cu;
4648
4649           /* DW_FORM_ref_addr is using section offset.  */
4650           attr.name = 0;
4651           attr.form = DW_FORM_ref_addr;
4652           attr.u.unsnd = pdi->offset.sect_off;
4653           die = follow_die_ref (NULL, &attr, &ref_cu);
4654
4655           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
4656         }
4657     }
4658
4659   parent_scope = partial_die_parent_scope (pdi, cu);
4660   if (parent_scope == NULL)
4661     return NULL;
4662   else
4663     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
4664 }
4665
4666 static void
4667 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
4668 {
4669   struct objfile *objfile = cu->objfile;
4670   CORE_ADDR addr = 0;
4671   char *actual_name = NULL;
4672   CORE_ADDR baseaddr;
4673   int built_actual_name = 0;
4674
4675   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4676
4677   actual_name = partial_die_full_name (pdi, cu);
4678   if (actual_name)
4679     built_actual_name = 1;
4680
4681   if (actual_name == NULL)
4682     actual_name = pdi->name;
4683
4684   switch (pdi->tag)
4685     {
4686     case DW_TAG_subprogram:
4687       if (pdi->is_external || cu->language == language_ada)
4688         {
4689           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
4690              of the global scope.  But in Ada, we want to be able to access
4691              nested procedures globally.  So all Ada subprograms are stored
4692              in the global scope.  */
4693           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
4694              mst_text, objfile); */
4695           add_psymbol_to_list (actual_name, strlen (actual_name),
4696                                built_actual_name,
4697                                VAR_DOMAIN, LOC_BLOCK,
4698                                &objfile->global_psymbols,
4699                                0, pdi->lowpc + baseaddr,
4700                                cu->language, objfile);
4701         }
4702       else
4703         {
4704           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
4705              mst_file_text, objfile); */
4706           add_psymbol_to_list (actual_name, strlen (actual_name),
4707                                built_actual_name,
4708                                VAR_DOMAIN, LOC_BLOCK,
4709                                &objfile->static_psymbols,
4710                                0, pdi->lowpc + baseaddr,
4711                                cu->language, objfile);
4712         }
4713       break;
4714     case DW_TAG_constant:
4715       {
4716         struct psymbol_allocation_list *list;
4717
4718         if (pdi->is_external)
4719           list = &objfile->global_psymbols;
4720         else
4721           list = &objfile->static_psymbols;
4722         add_psymbol_to_list (actual_name, strlen (actual_name),
4723                              built_actual_name, VAR_DOMAIN, LOC_STATIC,
4724                              list, 0, 0, cu->language, objfile);
4725       }
4726       break;
4727     case DW_TAG_variable:
4728       if (pdi->d.locdesc)
4729         addr = decode_locdesc (pdi->d.locdesc, cu);
4730
4731       if (pdi->d.locdesc
4732           && addr == 0
4733           && !dwarf2_per_objfile->has_section_at_zero)
4734         {
4735           /* A global or static variable may also have been stripped
4736              out by the linker if unused, in which case its address
4737              will be nullified; do not add such variables into partial
4738              symbol table then.  */
4739         }
4740       else if (pdi->is_external)
4741         {
4742           /* Global Variable.
4743              Don't enter into the minimal symbol tables as there is
4744              a minimal symbol table entry from the ELF symbols already.
4745              Enter into partial symbol table if it has a location
4746              descriptor or a type.
4747              If the location descriptor is missing, new_symbol will create
4748              a LOC_UNRESOLVED symbol, the address of the variable will then
4749              be determined from the minimal symbol table whenever the variable
4750              is referenced.
4751              The address for the partial symbol table entry is not
4752              used by GDB, but it comes in handy for debugging partial symbol
4753              table building.  */
4754
4755           if (pdi->d.locdesc || pdi->has_type)
4756             add_psymbol_to_list (actual_name, strlen (actual_name),
4757                                  built_actual_name,
4758                                  VAR_DOMAIN, LOC_STATIC,
4759                                  &objfile->global_psymbols,
4760                                  0, addr + baseaddr,
4761                                  cu->language, objfile);
4762         }
4763       else
4764         {
4765           /* Static Variable.  Skip symbols without location descriptors.  */
4766           if (pdi->d.locdesc == NULL)
4767             {
4768               if (built_actual_name)
4769                 xfree (actual_name);
4770               return;
4771             }
4772           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
4773              mst_file_data, objfile); */
4774           add_psymbol_to_list (actual_name, strlen (actual_name),
4775                                built_actual_name,
4776                                VAR_DOMAIN, LOC_STATIC,
4777                                &objfile->static_psymbols,
4778                                0, addr + baseaddr,
4779                                cu->language, objfile);
4780         }
4781       break;
4782     case DW_TAG_typedef:
4783     case DW_TAG_base_type:
4784     case DW_TAG_subrange_type:
4785       add_psymbol_to_list (actual_name, strlen (actual_name),
4786                            built_actual_name,
4787                            VAR_DOMAIN, LOC_TYPEDEF,
4788                            &objfile->static_psymbols,
4789                            0, (CORE_ADDR) 0, cu->language, objfile);
4790       break;
4791     case DW_TAG_namespace:
4792       add_psymbol_to_list (actual_name, strlen (actual_name),
4793                            built_actual_name,
4794                            VAR_DOMAIN, LOC_TYPEDEF,
4795                            &objfile->global_psymbols,
4796                            0, (CORE_ADDR) 0, cu->language, objfile);
4797       break;
4798     case DW_TAG_class_type:
4799     case DW_TAG_interface_type:
4800     case DW_TAG_structure_type:
4801     case DW_TAG_union_type:
4802     case DW_TAG_enumeration_type:
4803       /* Skip external references.  The DWARF standard says in the section
4804          about "Structure, Union, and Class Type Entries": "An incomplete
4805          structure, union or class type is represented by a structure,
4806          union or class entry that does not have a byte size attribute
4807          and that has a DW_AT_declaration attribute."  */
4808       if (!pdi->has_byte_size && pdi->is_declaration)
4809         {
4810           if (built_actual_name)
4811             xfree (actual_name);
4812           return;
4813         }
4814
4815       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
4816          static vs. global.  */
4817       add_psymbol_to_list (actual_name, strlen (actual_name),
4818                            built_actual_name,
4819                            STRUCT_DOMAIN, LOC_TYPEDEF,
4820                            (cu->language == language_cplus
4821                             || cu->language == language_java)
4822                            ? &objfile->global_psymbols
4823                            : &objfile->static_psymbols,
4824                            0, (CORE_ADDR) 0, cu->language, objfile);
4825
4826       break;
4827     case DW_TAG_enumerator:
4828       add_psymbol_to_list (actual_name, strlen (actual_name),
4829                            built_actual_name,
4830                            VAR_DOMAIN, LOC_CONST,
4831                            (cu->language == language_cplus
4832                             || cu->language == language_java)
4833                            ? &objfile->global_psymbols
4834                            : &objfile->static_psymbols,
4835                            0, (CORE_ADDR) 0, cu->language, objfile);
4836       break;
4837     default:
4838       break;
4839     }
4840
4841   if (built_actual_name)
4842     xfree (actual_name);
4843 }
4844
4845 /* Read a partial die corresponding to a namespace; also, add a symbol
4846    corresponding to that namespace to the symbol table.  NAMESPACE is
4847    the name of the enclosing namespace.  */
4848
4849 static void
4850 add_partial_namespace (struct partial_die_info *pdi,
4851                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
4852                        int need_pc, struct dwarf2_cu *cu)
4853 {
4854   /* Add a symbol for the namespace.  */
4855
4856   add_partial_symbol (pdi, cu);
4857
4858   /* Now scan partial symbols in that namespace.  */
4859
4860   if (pdi->has_children)
4861     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
4862 }
4863
4864 /* Read a partial die corresponding to a Fortran module.  */
4865
4866 static void
4867 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
4868                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
4869 {
4870   /* Now scan partial symbols in that module.  */
4871
4872   if (pdi->has_children)
4873     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
4874 }
4875
4876 /* Read a partial die corresponding to a subprogram and create a partial
4877    symbol for that subprogram.  When the CU language allows it, this
4878    routine also defines a partial symbol for each nested subprogram
4879    that this subprogram contains.
4880
4881    DIE my also be a lexical block, in which case we simply search
4882    recursively for suprograms defined inside that lexical block.
4883    Again, this is only performed when the CU language allows this
4884    type of definitions.  */
4885
4886 static void
4887 add_partial_subprogram (struct partial_die_info *pdi,
4888                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
4889                         int need_pc, struct dwarf2_cu *cu)
4890 {
4891   if (pdi->tag == DW_TAG_subprogram)
4892     {
4893       if (pdi->has_pc_info)
4894         {
4895           if (pdi->lowpc < *lowpc)
4896             *lowpc = pdi->lowpc;
4897           if (pdi->highpc > *highpc)
4898             *highpc = pdi->highpc;
4899           if (need_pc)
4900             {
4901               CORE_ADDR baseaddr;
4902               struct objfile *objfile = cu->objfile;
4903
4904               baseaddr = ANOFFSET (objfile->section_offsets,
4905                                    SECT_OFF_TEXT (objfile));
4906               addrmap_set_empty (objfile->psymtabs_addrmap,
4907                                  pdi->lowpc + baseaddr,
4908                                  pdi->highpc - 1 + baseaddr,
4909                                  cu->per_cu->v.psymtab);
4910             }
4911         }
4912
4913       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
4914         {
4915           if (!pdi->is_declaration)
4916             /* Ignore subprogram DIEs that do not have a name, they are
4917                illegal.  Do not emit a complaint at this point, we will
4918                do so when we convert this psymtab into a symtab.  */
4919             if (pdi->name)
4920               add_partial_symbol (pdi, cu);
4921         }
4922     }
4923
4924   if (! pdi->has_children)
4925     return;
4926
4927   if (cu->language == language_ada)
4928     {
4929       pdi = pdi->die_child;
4930       while (pdi != NULL)
4931         {
4932           fixup_partial_die (pdi, cu);
4933           if (pdi->tag == DW_TAG_subprogram
4934               || pdi->tag == DW_TAG_lexical_block)
4935             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
4936           pdi = pdi->die_sibling;
4937         }
4938     }
4939 }
4940
4941 /* Read a partial die corresponding to an enumeration type.  */
4942
4943 static void
4944 add_partial_enumeration (struct partial_die_info *enum_pdi,
4945                          struct dwarf2_cu *cu)
4946 {
4947   struct partial_die_info *pdi;
4948
4949   if (enum_pdi->name != NULL)
4950     add_partial_symbol (enum_pdi, cu);
4951
4952   pdi = enum_pdi->die_child;
4953   while (pdi)
4954     {
4955       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
4956         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
4957       else
4958         add_partial_symbol (pdi, cu);
4959       pdi = pdi->die_sibling;
4960     }
4961 }
4962
4963 /* Return the initial uleb128 in the die at INFO_PTR.  */
4964
4965 static unsigned int
4966 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
4967 {
4968   unsigned int bytes_read;
4969
4970   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
4971 }
4972
4973 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
4974    Return the corresponding abbrev, or NULL if the number is zero (indicating
4975    an empty DIE).  In either case *BYTES_READ will be set to the length of
4976    the initial number.  */
4977
4978 static struct abbrev_info *
4979 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
4980                  struct dwarf2_cu *cu)
4981 {
4982   bfd *abfd = cu->objfile->obfd;
4983   unsigned int abbrev_number;
4984   struct abbrev_info *abbrev;
4985
4986   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
4987
4988   if (abbrev_number == 0)
4989     return NULL;
4990
4991   abbrev = dwarf2_lookup_abbrev (abbrev_number, cu);
4992   if (!abbrev)
4993     {
4994       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
4995              abbrev_number, bfd_get_filename (abfd));
4996     }
4997
4998   return abbrev;
4999 }
5000
5001 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5002    Returns a pointer to the end of a series of DIEs, terminated by an empty
5003    DIE.  Any children of the skipped DIEs will also be skipped.  */
5004
5005 static gdb_byte *
5006 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
5007 {
5008   struct dwarf2_cu *cu = reader->cu;
5009   struct abbrev_info *abbrev;
5010   unsigned int bytes_read;
5011
5012   while (1)
5013     {
5014       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
5015       if (abbrev == NULL)
5016         return info_ptr + bytes_read;
5017       else
5018         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
5019     }
5020 }
5021
5022 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
5023    INFO_PTR should point just after the initial uleb128 of a DIE, and the
5024    abbrev corresponding to that skipped uleb128 should be passed in
5025    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
5026    children.  */
5027
5028 static gdb_byte *
5029 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
5030               struct abbrev_info *abbrev)
5031 {
5032   unsigned int bytes_read;
5033   struct attribute attr;
5034   bfd *abfd = reader->abfd;
5035   struct dwarf2_cu *cu = reader->cu;
5036   gdb_byte *buffer = reader->buffer;
5037   unsigned int form, i;
5038
5039   for (i = 0; i < abbrev->num_attrs; i++)
5040     {
5041       /* The only abbrev we care about is DW_AT_sibling.  */
5042       if (abbrev->attrs[i].name == DW_AT_sibling)
5043         {
5044           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
5045           if (attr.form == DW_FORM_ref_addr)
5046             complaint (&symfile_complaints,
5047                        _("ignoring absolute DW_AT_sibling"));
5048           else
5049             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
5050         }
5051
5052       /* If it isn't DW_AT_sibling, skip this attribute.  */
5053       form = abbrev->attrs[i].form;
5054     skip_attribute:
5055       switch (form)
5056         {
5057         case DW_FORM_ref_addr:
5058           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
5059              and later it is offset sized.  */
5060           if (cu->header.version == 2)
5061             info_ptr += cu->header.addr_size;
5062           else
5063             info_ptr += cu->header.offset_size;
5064           break;
5065         case DW_FORM_addr:
5066           info_ptr += cu->header.addr_size;
5067           break;
5068         case DW_FORM_data1:
5069         case DW_FORM_ref1:
5070         case DW_FORM_flag:
5071           info_ptr += 1;
5072           break;
5073         case DW_FORM_flag_present:
5074           break;
5075         case DW_FORM_data2:
5076         case DW_FORM_ref2:
5077           info_ptr += 2;
5078           break;
5079         case DW_FORM_data4:
5080         case DW_FORM_ref4:
5081           info_ptr += 4;
5082           break;
5083         case DW_FORM_data8:
5084         case DW_FORM_ref8:
5085         case DW_FORM_ref_sig8:
5086           info_ptr += 8;
5087           break;
5088         case DW_FORM_string:
5089           read_direct_string (abfd, info_ptr, &bytes_read);
5090           info_ptr += bytes_read;
5091           break;
5092         case DW_FORM_sec_offset:
5093         case DW_FORM_strp:
5094           info_ptr += cu->header.offset_size;
5095           break;
5096         case DW_FORM_exprloc:
5097         case DW_FORM_block:
5098           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5099           info_ptr += bytes_read;
5100           break;
5101         case DW_FORM_block1:
5102           info_ptr += 1 + read_1_byte (abfd, info_ptr);
5103           break;
5104         case DW_FORM_block2:
5105           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
5106           break;
5107         case DW_FORM_block4:
5108           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
5109           break;
5110         case DW_FORM_sdata:
5111         case DW_FORM_udata:
5112         case DW_FORM_ref_udata:
5113         case DW_FORM_GNU_addr_index:
5114         case DW_FORM_GNU_str_index:
5115           info_ptr = skip_leb128 (abfd, info_ptr);
5116           break;
5117         case DW_FORM_indirect:
5118           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
5119           info_ptr += bytes_read;
5120           /* We need to continue parsing from here, so just go back to
5121              the top.  */
5122           goto skip_attribute;
5123
5124         default:
5125           error (_("Dwarf Error: Cannot handle %s "
5126                    "in DWARF reader [in module %s]"),
5127                  dwarf_form_name (form),
5128                  bfd_get_filename (abfd));
5129         }
5130     }
5131
5132   if (abbrev->has_children)
5133     return skip_children (reader, info_ptr);
5134   else
5135     return info_ptr;
5136 }
5137
5138 /* Locate ORIG_PDI's sibling.
5139    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
5140
5141 static gdb_byte *
5142 locate_pdi_sibling (const struct die_reader_specs *reader,
5143                     struct partial_die_info *orig_pdi,
5144                     gdb_byte *info_ptr)
5145 {
5146   /* Do we know the sibling already?  */
5147
5148   if (orig_pdi->sibling)
5149     return orig_pdi->sibling;
5150
5151   /* Are there any children to deal with?  */
5152
5153   if (!orig_pdi->has_children)
5154     return info_ptr;
5155
5156   /* Skip the children the long way.  */
5157
5158   return skip_children (reader, info_ptr);
5159 }
5160
5161 /* Expand this partial symbol table into a full symbol table.  */
5162
5163 static void
5164 dwarf2_psymtab_to_symtab (struct partial_symtab *pst)
5165 {
5166   if (pst != NULL)
5167     {
5168       if (pst->readin)
5169         {
5170           warning (_("bug: psymtab for %s is already read in."),
5171                    pst->filename);
5172         }
5173       else
5174         {
5175           if (info_verbose)
5176             {
5177               printf_filtered (_("Reading in symbols for %s..."),
5178                                pst->filename);
5179               gdb_flush (gdb_stdout);
5180             }
5181
5182           /* Restore our global data.  */
5183           dwarf2_per_objfile = objfile_data (pst->objfile,
5184                                              dwarf2_objfile_data_key);
5185
5186           /* If this psymtab is constructed from a debug-only objfile, the
5187              has_section_at_zero flag will not necessarily be correct.  We
5188              can get the correct value for this flag by looking at the data
5189              associated with the (presumably stripped) associated objfile.  */
5190           if (pst->objfile->separate_debug_objfile_backlink)
5191             {
5192               struct dwarf2_per_objfile *dpo_backlink
5193                 = objfile_data (pst->objfile->separate_debug_objfile_backlink,
5194                                 dwarf2_objfile_data_key);
5195
5196               dwarf2_per_objfile->has_section_at_zero
5197                 = dpo_backlink->has_section_at_zero;
5198             }
5199
5200           dwarf2_per_objfile->reading_partial_symbols = 0;
5201
5202           psymtab_to_symtab_1 (pst);
5203
5204           /* Finish up the debug error message.  */
5205           if (info_verbose)
5206             printf_filtered (_("done.\n"));
5207         }
5208     }
5209
5210   process_cu_includes ();
5211 }
5212 \f
5213 /* Reading in full CUs.  */
5214
5215 /* Add PER_CU to the queue.  */
5216
5217 static void
5218 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
5219                  enum language pretend_language)
5220 {
5221   struct dwarf2_queue_item *item;
5222
5223   per_cu->queued = 1;
5224   item = xmalloc (sizeof (*item));
5225   item->per_cu = per_cu;
5226   item->pretend_language = pretend_language;
5227   item->next = NULL;
5228
5229   if (dwarf2_queue == NULL)
5230     dwarf2_queue = item;
5231   else
5232     dwarf2_queue_tail->next = item;
5233
5234   dwarf2_queue_tail = item;
5235 }
5236
5237 /* Process the queue.  */
5238
5239 static void
5240 process_queue (void)
5241 {
5242   struct dwarf2_queue_item *item, *next_item;
5243
5244   /* The queue starts out with one item, but following a DIE reference
5245      may load a new CU, adding it to the end of the queue.  */
5246   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
5247     {
5248       if (dwarf2_per_objfile->using_index
5249           ? !item->per_cu->v.quick->symtab
5250           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
5251         process_full_comp_unit (item->per_cu, item->pretend_language);
5252
5253       item->per_cu->queued = 0;
5254       next_item = item->next;
5255       xfree (item);
5256     }
5257
5258   dwarf2_queue_tail = NULL;
5259 }
5260
5261 /* Free all allocated queue entries.  This function only releases anything if
5262    an error was thrown; if the queue was processed then it would have been
5263    freed as we went along.  */
5264
5265 static void
5266 dwarf2_release_queue (void *dummy)
5267 {
5268   struct dwarf2_queue_item *item, *last;
5269
5270   item = dwarf2_queue;
5271   while (item)
5272     {
5273       /* Anything still marked queued is likely to be in an
5274          inconsistent state, so discard it.  */
5275       if (item->per_cu->queued)
5276         {
5277           if (item->per_cu->cu != NULL)
5278             free_one_cached_comp_unit (item->per_cu);
5279           item->per_cu->queued = 0;
5280         }
5281
5282       last = item;
5283       item = item->next;
5284       xfree (last);
5285     }
5286
5287   dwarf2_queue = dwarf2_queue_tail = NULL;
5288 }
5289
5290 /* Read in full symbols for PST, and anything it depends on.  */
5291
5292 static void
5293 psymtab_to_symtab_1 (struct partial_symtab *pst)
5294 {
5295   struct dwarf2_per_cu_data *per_cu;
5296   int i;
5297
5298   if (pst->readin)
5299     return;
5300
5301   for (i = 0; i < pst->number_of_dependencies; i++)
5302     if (!pst->dependencies[i]->readin
5303         && pst->dependencies[i]->user == NULL)
5304       {
5305         /* Inform about additional files that need to be read in.  */
5306         if (info_verbose)
5307           {
5308             /* FIXME: i18n: Need to make this a single string.  */
5309             fputs_filtered (" ", gdb_stdout);
5310             wrap_here ("");
5311             fputs_filtered ("and ", gdb_stdout);
5312             wrap_here ("");
5313             printf_filtered ("%s...", pst->dependencies[i]->filename);
5314             wrap_here ("");     /* Flush output.  */
5315             gdb_flush (gdb_stdout);
5316           }
5317         psymtab_to_symtab_1 (pst->dependencies[i]);
5318       }
5319
5320   per_cu = pst->read_symtab_private;
5321
5322   if (per_cu == NULL)
5323     {
5324       /* It's an include file, no symbols to read for it.
5325          Everything is in the parent symtab.  */
5326       pst->readin = 1;
5327       return;
5328     }
5329
5330   dw2_do_instantiate_symtab (per_cu);
5331 }
5332
5333 /* Trivial hash function for die_info: the hash value of a DIE
5334    is its offset in .debug_info for this objfile.  */
5335
5336 static hashval_t
5337 die_hash (const void *item)
5338 {
5339   const struct die_info *die = item;
5340
5341   return die->offset.sect_off;
5342 }
5343
5344 /* Trivial comparison function for die_info structures: two DIEs
5345    are equal if they have the same offset.  */
5346
5347 static int
5348 die_eq (const void *item_lhs, const void *item_rhs)
5349 {
5350   const struct die_info *die_lhs = item_lhs;
5351   const struct die_info *die_rhs = item_rhs;
5352
5353   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
5354 }
5355
5356 /* die_reader_func for load_full_comp_unit.
5357    This is identical to read_signatured_type_reader,
5358    but is kept separate for now.  */
5359
5360 static void
5361 load_full_comp_unit_reader (const struct die_reader_specs *reader,
5362                             gdb_byte *info_ptr,
5363                             struct die_info *comp_unit_die,
5364                             int has_children,
5365                             void *data)
5366 {
5367   struct dwarf2_cu *cu = reader->cu;
5368   enum language *language_ptr = data;
5369
5370   gdb_assert (cu->die_hash == NULL);
5371   cu->die_hash =
5372     htab_create_alloc_ex (cu->header.length / 12,
5373                           die_hash,
5374                           die_eq,
5375                           NULL,
5376                           &cu->comp_unit_obstack,
5377                           hashtab_obstack_allocate,
5378                           dummy_obstack_deallocate);
5379
5380   if (has_children)
5381     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
5382                                                   &info_ptr, comp_unit_die);
5383   cu->dies = comp_unit_die;
5384   /* comp_unit_die is not stored in die_hash, no need.  */
5385
5386   /* We try not to read any attributes in this function, because not
5387      all CUs needed for references have been loaded yet, and symbol
5388      table processing isn't initialized.  But we have to set the CU language,
5389      or we won't be able to build types correctly.
5390      Similarly, if we do not read the producer, we can not apply
5391      producer-specific interpretation.  */
5392   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
5393 }
5394
5395 /* Load the DIEs associated with PER_CU into memory.  */
5396
5397 static void
5398 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
5399                      enum language pretend_language)
5400 {
5401   gdb_assert (! this_cu->is_debug_types);
5402
5403   init_cutu_and_read_dies (this_cu, 1, 1, load_full_comp_unit_reader,
5404                            &pretend_language);
5405 }
5406
5407 /* Add a DIE to the delayed physname list.  */
5408
5409 static void
5410 add_to_method_list (struct type *type, int fnfield_index, int index,
5411                     const char *name, struct die_info *die,
5412                     struct dwarf2_cu *cu)
5413 {
5414   struct delayed_method_info mi;
5415   mi.type = type;
5416   mi.fnfield_index = fnfield_index;
5417   mi.index = index;
5418   mi.name = name;
5419   mi.die = die;
5420   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
5421 }
5422
5423 /* A cleanup for freeing the delayed method list.  */
5424
5425 static void
5426 free_delayed_list (void *ptr)
5427 {
5428   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
5429   if (cu->method_list != NULL)
5430     {
5431       VEC_free (delayed_method_info, cu->method_list);
5432       cu->method_list = NULL;
5433     }
5434 }
5435
5436 /* Compute the physnames of any methods on the CU's method list.
5437
5438    The computation of method physnames is delayed in order to avoid the
5439    (bad) condition that one of the method's formal parameters is of an as yet
5440    incomplete type.  */
5441
5442 static void
5443 compute_delayed_physnames (struct dwarf2_cu *cu)
5444 {
5445   int i;
5446   struct delayed_method_info *mi;
5447   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
5448     {
5449       const char *physname;
5450       struct fn_fieldlist *fn_flp
5451         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
5452       physname = dwarf2_physname ((char *) mi->name, mi->die, cu);
5453       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
5454     }
5455 }
5456
5457 /* Go objects should be embedded in a DW_TAG_module DIE,
5458    and it's not clear if/how imported objects will appear.
5459    To keep Go support simple until that's worked out,
5460    go back through what we've read and create something usable.
5461    We could do this while processing each DIE, and feels kinda cleaner,
5462    but that way is more invasive.
5463    This is to, for example, allow the user to type "p var" or "b main"
5464    without having to specify the package name, and allow lookups
5465    of module.object to work in contexts that use the expression
5466    parser.  */
5467
5468 static void
5469 fixup_go_packaging (struct dwarf2_cu *cu)
5470 {
5471   char *package_name = NULL;
5472   struct pending *list;
5473   int i;
5474
5475   for (list = global_symbols; list != NULL; list = list->next)
5476     {
5477       for (i = 0; i < list->nsyms; ++i)
5478         {
5479           struct symbol *sym = list->symbol[i];
5480
5481           if (SYMBOL_LANGUAGE (sym) == language_go
5482               && SYMBOL_CLASS (sym) == LOC_BLOCK)
5483             {
5484               char *this_package_name = go_symbol_package_name (sym);
5485
5486               if (this_package_name == NULL)
5487                 continue;
5488               if (package_name == NULL)
5489                 package_name = this_package_name;
5490               else
5491                 {
5492                   if (strcmp (package_name, this_package_name) != 0)
5493                     complaint (&symfile_complaints,
5494                                _("Symtab %s has objects from two different Go packages: %s and %s"),
5495                                (sym->symtab && sym->symtab->filename
5496                                 ? sym->symtab->filename
5497                                 : cu->objfile->name),
5498                                this_package_name, package_name);
5499                   xfree (this_package_name);
5500                 }
5501             }
5502         }
5503     }
5504
5505   if (package_name != NULL)
5506     {
5507       struct objfile *objfile = cu->objfile;
5508       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
5509                                      package_name, objfile);
5510       struct symbol *sym;
5511
5512       TYPE_TAG_NAME (type) = TYPE_NAME (type);
5513
5514       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
5515       SYMBOL_SET_LANGUAGE (sym, language_go);
5516       SYMBOL_SET_NAMES (sym, package_name, strlen (package_name), 1, objfile);
5517       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
5518          e.g., "main" finds the "main" module and not C's main().  */
5519       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
5520       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
5521       SYMBOL_TYPE (sym) = type;
5522
5523       add_symbol_to_list (sym, &global_symbols);
5524
5525       xfree (package_name);
5526     }
5527 }
5528
5529 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
5530
5531 /* Return the symtab for PER_CU.  This works properly regardless of
5532    whether we're using the index or psymtabs.  */
5533
5534 static struct symtab *
5535 get_symtab (struct dwarf2_per_cu_data *per_cu)
5536 {
5537   return (dwarf2_per_objfile->using_index
5538           ? per_cu->v.quick->symtab
5539           : per_cu->v.psymtab->symtab);
5540 }
5541
5542 /* A helper function for computing the list of all symbol tables
5543    included by PER_CU.  */
5544
5545 static void
5546 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
5547                                 htab_t all_children,
5548                                 struct dwarf2_per_cu_data *per_cu)
5549 {
5550   void **slot;
5551   int ix;
5552   struct dwarf2_per_cu_data *iter;
5553
5554   slot = htab_find_slot (all_children, per_cu, INSERT);
5555   if (*slot != NULL)
5556     {
5557       /* This inclusion and its children have been processed.  */
5558       return;
5559     }
5560
5561   *slot = per_cu;
5562   /* Only add a CU if it has a symbol table.  */
5563   if (get_symtab (per_cu) != NULL)
5564     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
5565
5566   for (ix = 0;
5567        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
5568        ++ix)
5569     recursively_compute_inclusions (result, all_children, iter);
5570 }
5571
5572 /* Compute the symtab 'includes' fields for the symtab related to
5573    PER_CU.  */
5574
5575 static void
5576 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
5577 {
5578   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
5579     {
5580       int ix, len;
5581       struct dwarf2_per_cu_data *iter;
5582       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
5583       htab_t all_children;
5584       struct symtab *symtab = get_symtab (per_cu);
5585
5586       /* If we don't have a symtab, we can just skip this case.  */
5587       if (symtab == NULL)
5588         return;
5589
5590       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
5591                                         NULL, xcalloc, xfree);
5592
5593       for (ix = 0;
5594            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
5595                         ix, iter);
5596            ++ix)
5597         recursively_compute_inclusions (&result_children, all_children, iter);
5598
5599       /* Now we have a transitive closure of all the included CUs, so
5600          we can convert it to a list of symtabs.  */
5601       len = VEC_length (dwarf2_per_cu_ptr, result_children);
5602       symtab->includes
5603         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
5604                          (len + 1) * sizeof (struct symtab *));
5605       for (ix = 0;
5606            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
5607            ++ix)
5608         symtab->includes[ix] = get_symtab (iter);
5609       symtab->includes[len] = NULL;
5610
5611       VEC_free (dwarf2_per_cu_ptr, result_children);
5612       htab_delete (all_children);
5613     }
5614 }
5615
5616 /* Compute the 'includes' field for the symtabs of all the CUs we just
5617    read.  */
5618
5619 static void
5620 process_cu_includes (void)
5621 {
5622   int ix;
5623   struct dwarf2_per_cu_data *iter;
5624
5625   for (ix = 0;
5626        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
5627                     ix, iter);
5628        ++ix)
5629     compute_symtab_includes (iter);
5630
5631   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
5632 }
5633
5634 /* Generate full symbol information for PER_CU, whose DIEs have
5635    already been loaded into memory.  */
5636
5637 static void
5638 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
5639                         enum language pretend_language)
5640 {
5641   struct dwarf2_cu *cu = per_cu->cu;
5642   struct objfile *objfile = per_cu->objfile;
5643   CORE_ADDR lowpc, highpc;
5644   struct symtab *symtab;
5645   struct cleanup *back_to, *delayed_list_cleanup;
5646   CORE_ADDR baseaddr;
5647
5648   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5649
5650   buildsym_init ();
5651   back_to = make_cleanup (really_free_pendings, NULL);
5652   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
5653
5654   cu->list_in_scope = &file_symbols;
5655
5656   cu->language = pretend_language;
5657   cu->language_defn = language_def (cu->language);
5658
5659   /* Do line number decoding in read_file_scope () */
5660   process_die (cu->dies, cu);
5661
5662   /* For now fudge the Go package.  */
5663   if (cu->language == language_go)
5664     fixup_go_packaging (cu);
5665
5666   /* Now that we have processed all the DIEs in the CU, all the types 
5667      should be complete, and it should now be safe to compute all of the
5668      physnames.  */
5669   compute_delayed_physnames (cu);
5670   do_cleanups (delayed_list_cleanup);
5671
5672   /* Some compilers don't define a DW_AT_high_pc attribute for the
5673      compilation unit.  If the DW_AT_high_pc is missing, synthesize
5674      it, by scanning the DIE's below the compilation unit.  */
5675   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
5676
5677   symtab = end_symtab (highpc + baseaddr, objfile, SECT_OFF_TEXT (objfile));
5678
5679   if (symtab != NULL)
5680     {
5681       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
5682
5683       /* Set symtab language to language from DW_AT_language.  If the
5684          compilation is from a C file generated by language preprocessors, do
5685          not set the language if it was already deduced by start_subfile.  */
5686       if (!(cu->language == language_c && symtab->language != language_c))
5687         symtab->language = cu->language;
5688
5689       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
5690          produce DW_AT_location with location lists but it can be possibly
5691          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
5692          there were bugs in prologue debug info, fixed later in GCC-4.5
5693          by "unwind info for epilogues" patch (which is not directly related).
5694
5695          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
5696          needed, it would be wrong due to missing DW_AT_producer there.
5697
5698          Still one can confuse GDB by using non-standard GCC compilation
5699          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
5700          */ 
5701       if (cu->has_loclist && gcc_4_minor >= 5)
5702         symtab->locations_valid = 1;
5703
5704       if (gcc_4_minor >= 5)
5705         symtab->epilogue_unwind_valid = 1;
5706
5707       symtab->call_site_htab = cu->call_site_htab;
5708     }
5709
5710   if (dwarf2_per_objfile->using_index)
5711     per_cu->v.quick->symtab = symtab;
5712   else
5713     {
5714       struct partial_symtab *pst = per_cu->v.psymtab;
5715       pst->symtab = symtab;
5716       pst->readin = 1;
5717     }
5718
5719   /* Push it for inclusion processing later.  */
5720   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
5721
5722   do_cleanups (back_to);
5723 }
5724
5725 /* Process an imported unit DIE.  */
5726
5727 static void
5728 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
5729 {
5730   struct attribute *attr;
5731
5732   attr = dwarf2_attr (die, DW_AT_import, cu);
5733   if (attr != NULL)
5734     {
5735       struct dwarf2_per_cu_data *per_cu;
5736       struct symtab *imported_symtab;
5737       sect_offset offset;
5738
5739       offset = dwarf2_get_ref_die_offset (attr);
5740       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
5741
5742       /* Queue the unit, if needed.  */
5743       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
5744         load_full_comp_unit (per_cu, cu->language);
5745
5746       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5747                      per_cu);
5748     }
5749 }
5750
5751 /* Process a die and its children.  */
5752
5753 static void
5754 process_die (struct die_info *die, struct dwarf2_cu *cu)
5755 {
5756   switch (die->tag)
5757     {
5758     case DW_TAG_padding:
5759       break;
5760     case DW_TAG_compile_unit:
5761     case DW_TAG_partial_unit:
5762       read_file_scope (die, cu);
5763       break;
5764     case DW_TAG_type_unit:
5765       read_type_unit_scope (die, cu);
5766       break;
5767     case DW_TAG_subprogram:
5768     case DW_TAG_inlined_subroutine:
5769       read_func_scope (die, cu);
5770       break;
5771     case DW_TAG_lexical_block:
5772     case DW_TAG_try_block:
5773     case DW_TAG_catch_block:
5774       read_lexical_block_scope (die, cu);
5775       break;
5776     case DW_TAG_GNU_call_site:
5777       read_call_site_scope (die, cu);
5778       break;
5779     case DW_TAG_class_type:
5780     case DW_TAG_interface_type:
5781     case DW_TAG_structure_type:
5782     case DW_TAG_union_type:
5783       process_structure_scope (die, cu);
5784       break;
5785     case DW_TAG_enumeration_type:
5786       process_enumeration_scope (die, cu);
5787       break;
5788
5789     /* These dies have a type, but processing them does not create
5790        a symbol or recurse to process the children.  Therefore we can
5791        read them on-demand through read_type_die.  */
5792     case DW_TAG_subroutine_type:
5793     case DW_TAG_set_type:
5794     case DW_TAG_array_type:
5795     case DW_TAG_pointer_type:
5796     case DW_TAG_ptr_to_member_type:
5797     case DW_TAG_reference_type:
5798     case DW_TAG_string_type:
5799       break;
5800
5801     case DW_TAG_base_type:
5802     case DW_TAG_subrange_type:
5803     case DW_TAG_typedef:
5804       /* Add a typedef symbol for the type definition, if it has a
5805          DW_AT_name.  */
5806       new_symbol (die, read_type_die (die, cu), cu);
5807       break;
5808     case DW_TAG_common_block:
5809       read_common_block (die, cu);
5810       break;
5811     case DW_TAG_common_inclusion:
5812       break;
5813     case DW_TAG_namespace:
5814       processing_has_namespace_info = 1;
5815       read_namespace (die, cu);
5816       break;
5817     case DW_TAG_module:
5818       processing_has_namespace_info = 1;
5819       read_module (die, cu);
5820       break;
5821     case DW_TAG_imported_declaration:
5822     case DW_TAG_imported_module:
5823       processing_has_namespace_info = 1;
5824       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
5825                                  || cu->language != language_fortran))
5826         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
5827                    dwarf_tag_name (die->tag));
5828       read_import_statement (die, cu);
5829       break;
5830
5831     case DW_TAG_imported_unit:
5832       process_imported_unit_die (die, cu);
5833       break;
5834
5835     default:
5836       new_symbol (die, NULL, cu);
5837       break;
5838     }
5839 }
5840
5841 /* A helper function for dwarf2_compute_name which determines whether DIE
5842    needs to have the name of the scope prepended to the name listed in the
5843    die.  */
5844
5845 static int
5846 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
5847 {
5848   struct attribute *attr;
5849
5850   switch (die->tag)
5851     {
5852     case DW_TAG_namespace:
5853     case DW_TAG_typedef:
5854     case DW_TAG_class_type:
5855     case DW_TAG_interface_type:
5856     case DW_TAG_structure_type:
5857     case DW_TAG_union_type:
5858     case DW_TAG_enumeration_type:
5859     case DW_TAG_enumerator:
5860     case DW_TAG_subprogram:
5861     case DW_TAG_member:
5862       return 1;
5863
5864     case DW_TAG_variable:
5865     case DW_TAG_constant:
5866       /* We only need to prefix "globally" visible variables.  These include
5867          any variable marked with DW_AT_external or any variable that
5868          lives in a namespace.  [Variables in anonymous namespaces
5869          require prefixing, but they are not DW_AT_external.]  */
5870
5871       if (dwarf2_attr (die, DW_AT_specification, cu))
5872         {
5873           struct dwarf2_cu *spec_cu = cu;
5874
5875           return die_needs_namespace (die_specification (die, &spec_cu),
5876                                       spec_cu);
5877         }
5878
5879       attr = dwarf2_attr (die, DW_AT_external, cu);
5880       if (attr == NULL && die->parent->tag != DW_TAG_namespace
5881           && die->parent->tag != DW_TAG_module)
5882         return 0;
5883       /* A variable in a lexical block of some kind does not need a
5884          namespace, even though in C++ such variables may be external
5885          and have a mangled name.  */
5886       if (die->parent->tag ==  DW_TAG_lexical_block
5887           || die->parent->tag ==  DW_TAG_try_block
5888           || die->parent->tag ==  DW_TAG_catch_block
5889           || die->parent->tag == DW_TAG_subprogram)
5890         return 0;
5891       return 1;
5892
5893     default:
5894       return 0;
5895     }
5896 }
5897
5898 /* Retrieve the last character from a mem_file.  */
5899
5900 static void
5901 do_ui_file_peek_last (void *object, const char *buffer, long length)
5902 {
5903   char *last_char_p = (char *) object;
5904
5905   if (length > 0)
5906     *last_char_p = buffer[length - 1];
5907 }
5908
5909 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
5910    compute the physname for the object, which include a method's:
5911    - formal parameters (C++/Java),
5912    - receiver type (Go),
5913    - return type (Java).
5914
5915    The term "physname" is a bit confusing.
5916    For C++, for example, it is the demangled name.
5917    For Go, for example, it's the mangled name.
5918
5919    For Ada, return the DIE's linkage name rather than the fully qualified
5920    name.  PHYSNAME is ignored..
5921
5922    The result is allocated on the objfile_obstack and canonicalized.  */
5923
5924 static const char *
5925 dwarf2_compute_name (char *name, struct die_info *die, struct dwarf2_cu *cu,
5926                      int physname)
5927 {
5928   struct objfile *objfile = cu->objfile;
5929
5930   if (name == NULL)
5931     name = dwarf2_name (die, cu);
5932
5933   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
5934      compute it by typename_concat inside GDB.  */
5935   if (cu->language == language_ada
5936       || (cu->language == language_fortran && physname))
5937     {
5938       /* For Ada unit, we prefer the linkage name over the name, as
5939          the former contains the exported name, which the user expects
5940          to be able to reference.  Ideally, we want the user to be able
5941          to reference this entity using either natural or linkage name,
5942          but we haven't started looking at this enhancement yet.  */
5943       struct attribute *attr;
5944
5945       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
5946       if (attr == NULL)
5947         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
5948       if (attr && DW_STRING (attr))
5949         return DW_STRING (attr);
5950     }
5951
5952   /* These are the only languages we know how to qualify names in.  */
5953   if (name != NULL
5954       && (cu->language == language_cplus || cu->language == language_java
5955           || cu->language == language_fortran))
5956     {
5957       if (die_needs_namespace (die, cu))
5958         {
5959           long length;
5960           const char *prefix;
5961           struct ui_file *buf;
5962
5963           prefix = determine_prefix (die, cu);
5964           buf = mem_fileopen ();
5965           if (*prefix != '\0')
5966             {
5967               char *prefixed_name = typename_concat (NULL, prefix, name,
5968                                                      physname, cu);
5969
5970               fputs_unfiltered (prefixed_name, buf);
5971               xfree (prefixed_name);
5972             }
5973           else
5974             fputs_unfiltered (name, buf);
5975
5976           /* Template parameters may be specified in the DIE's DW_AT_name, or
5977              as children with DW_TAG_template_type_param or
5978              DW_TAG_value_type_param.  If the latter, add them to the name
5979              here.  If the name already has template parameters, then
5980              skip this step; some versions of GCC emit both, and
5981              it is more efficient to use the pre-computed name.
5982
5983              Something to keep in mind about this process: it is very
5984              unlikely, or in some cases downright impossible, to produce
5985              something that will match the mangled name of a function.
5986              If the definition of the function has the same debug info,
5987              we should be able to match up with it anyway.  But fallbacks
5988              using the minimal symbol, for instance to find a method
5989              implemented in a stripped copy of libstdc++, will not work.
5990              If we do not have debug info for the definition, we will have to
5991              match them up some other way.
5992
5993              When we do name matching there is a related problem with function
5994              templates; two instantiated function templates are allowed to
5995              differ only by their return types, which we do not add here.  */
5996
5997           if (cu->language == language_cplus && strchr (name, '<') == NULL)
5998             {
5999               struct attribute *attr;
6000               struct die_info *child;
6001               int first = 1;
6002
6003               die->building_fullname = 1;
6004
6005               for (child = die->child; child != NULL; child = child->sibling)
6006                 {
6007                   struct type *type;
6008                   LONGEST value;
6009                   gdb_byte *bytes;
6010                   struct dwarf2_locexpr_baton *baton;
6011                   struct value *v;
6012
6013                   if (child->tag != DW_TAG_template_type_param
6014                       && child->tag != DW_TAG_template_value_param)
6015                     continue;
6016
6017                   if (first)
6018                     {
6019                       fputs_unfiltered ("<", buf);
6020                       first = 0;
6021                     }
6022                   else
6023                     fputs_unfiltered (", ", buf);
6024
6025                   attr = dwarf2_attr (child, DW_AT_type, cu);
6026                   if (attr == NULL)
6027                     {
6028                       complaint (&symfile_complaints,
6029                                  _("template parameter missing DW_AT_type"));
6030                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
6031                       continue;
6032                     }
6033                   type = die_type (child, cu);
6034
6035                   if (child->tag == DW_TAG_template_type_param)
6036                     {
6037                       c_print_type (type, "", buf, -1, 0);
6038                       continue;
6039                     }
6040
6041                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
6042                   if (attr == NULL)
6043                     {
6044                       complaint (&symfile_complaints,
6045                                  _("template parameter missing "
6046                                    "DW_AT_const_value"));
6047                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
6048                       continue;
6049                     }
6050
6051                   dwarf2_const_value_attr (attr, type, name,
6052                                            &cu->comp_unit_obstack, cu,
6053                                            &value, &bytes, &baton);
6054
6055                   if (TYPE_NOSIGN (type))
6056                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
6057                        changed, this can use value_print instead.  */
6058                     c_printchar (value, type, buf);
6059                   else
6060                     {
6061                       struct value_print_options opts;
6062
6063                       if (baton != NULL)
6064                         v = dwarf2_evaluate_loc_desc (type, NULL,
6065                                                       baton->data,
6066                                                       baton->size,
6067                                                       baton->per_cu);
6068                       else if (bytes != NULL)
6069                         {
6070                           v = allocate_value (type);
6071                           memcpy (value_contents_writeable (v), bytes,
6072                                   TYPE_LENGTH (type));
6073                         }
6074                       else
6075                         v = value_from_longest (type, value);
6076
6077                       /* Specify decimal so that we do not depend on
6078                          the radix.  */
6079                       get_formatted_print_options (&opts, 'd');
6080                       opts.raw = 1;
6081                       value_print (v, buf, &opts);
6082                       release_value (v);
6083                       value_free (v);
6084                     }
6085                 }
6086
6087               die->building_fullname = 0;
6088
6089               if (!first)
6090                 {
6091                   /* Close the argument list, with a space if necessary
6092                      (nested templates).  */
6093                   char last_char = '\0';
6094                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
6095                   if (last_char == '>')
6096                     fputs_unfiltered (" >", buf);
6097                   else
6098                     fputs_unfiltered (">", buf);
6099                 }
6100             }
6101
6102           /* For Java and C++ methods, append formal parameter type
6103              information, if PHYSNAME.  */
6104
6105           if (physname && die->tag == DW_TAG_subprogram
6106               && (cu->language == language_cplus
6107                   || cu->language == language_java))
6108             {
6109               struct type *type = read_type_die (die, cu);
6110
6111               c_type_print_args (type, buf, 1, cu->language);
6112
6113               if (cu->language == language_java)
6114                 {
6115                   /* For java, we must append the return type to method
6116                      names.  */
6117                   if (die->tag == DW_TAG_subprogram)
6118                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
6119                                      0, 0);
6120                 }
6121               else if (cu->language == language_cplus)
6122                 {
6123                   /* Assume that an artificial first parameter is
6124                      "this", but do not crash if it is not.  RealView
6125                      marks unnamed (and thus unused) parameters as
6126                      artificial; there is no way to differentiate
6127                      the two cases.  */
6128                   if (TYPE_NFIELDS (type) > 0
6129                       && TYPE_FIELD_ARTIFICIAL (type, 0)
6130                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
6131                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
6132                                                                         0))))
6133                     fputs_unfiltered (" const", buf);
6134                 }
6135             }
6136
6137           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
6138                                        &length);
6139           ui_file_delete (buf);
6140
6141           if (cu->language == language_cplus)
6142             {
6143               char *cname
6144                 = dwarf2_canonicalize_name (name, cu,
6145                                             &objfile->objfile_obstack);
6146
6147               if (cname != NULL)
6148                 name = cname;
6149             }
6150         }
6151     }
6152
6153   return name;
6154 }
6155
6156 /* Return the fully qualified name of DIE, based on its DW_AT_name.
6157    If scope qualifiers are appropriate they will be added.  The result
6158    will be allocated on the objfile_obstack, or NULL if the DIE does
6159    not have a name.  NAME may either be from a previous call to
6160    dwarf2_name or NULL.
6161
6162    The output string will be canonicalized (if C++/Java).  */
6163
6164 static const char *
6165 dwarf2_full_name (char *name, struct die_info *die, struct dwarf2_cu *cu)
6166 {
6167   return dwarf2_compute_name (name, die, cu, 0);
6168 }
6169
6170 /* Construct a physname for the given DIE in CU.  NAME may either be
6171    from a previous call to dwarf2_name or NULL.  The result will be
6172    allocated on the objfile_objstack or NULL if the DIE does not have a
6173    name.
6174
6175    The output string will be canonicalized (if C++/Java).  */
6176
6177 static const char *
6178 dwarf2_physname (char *name, struct die_info *die, struct dwarf2_cu *cu)
6179 {
6180   struct objfile *objfile = cu->objfile;
6181   struct attribute *attr;
6182   const char *retval, *mangled = NULL, *canon = NULL;
6183   struct cleanup *back_to;
6184   int need_copy = 1;
6185
6186   /* In this case dwarf2_compute_name is just a shortcut not building anything
6187      on its own.  */
6188   if (!die_needs_namespace (die, cu))
6189     return dwarf2_compute_name (name, die, cu, 1);
6190
6191   back_to = make_cleanup (null_cleanup, NULL);
6192
6193   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
6194   if (!attr)
6195     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
6196
6197   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
6198      has computed.  */
6199   if (attr && DW_STRING (attr))
6200     {
6201       char *demangled;
6202
6203       mangled = DW_STRING (attr);
6204
6205       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
6206          type.  It is easier for GDB users to search for such functions as
6207          `name(params)' than `long name(params)'.  In such case the minimal
6208          symbol names do not match the full symbol names but for template
6209          functions there is never a need to look up their definition from their
6210          declaration so the only disadvantage remains the minimal symbol
6211          variant `long name(params)' does not have the proper inferior type.
6212          */
6213
6214       if (cu->language == language_go)
6215         {
6216           /* This is a lie, but we already lie to the caller new_symbol_full.
6217              new_symbol_full assumes we return the mangled name.
6218              This just undoes that lie until things are cleaned up.  */
6219           demangled = NULL;
6220         }
6221       else
6222         {
6223           demangled = cplus_demangle (mangled,
6224                                       (DMGL_PARAMS | DMGL_ANSI
6225                                        | (cu->language == language_java
6226                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
6227                                           : DMGL_RET_DROP)));
6228         }
6229       if (demangled)
6230         {
6231           make_cleanup (xfree, demangled);
6232           canon = demangled;
6233         }
6234       else
6235         {
6236           canon = mangled;
6237           need_copy = 0;
6238         }
6239     }
6240
6241   if (canon == NULL || check_physname)
6242     {
6243       const char *physname = dwarf2_compute_name (name, die, cu, 1);
6244
6245       if (canon != NULL && strcmp (physname, canon) != 0)
6246         {
6247           /* It may not mean a bug in GDB.  The compiler could also
6248              compute DW_AT_linkage_name incorrectly.  But in such case
6249              GDB would need to be bug-to-bug compatible.  */
6250
6251           complaint (&symfile_complaints,
6252                      _("Computed physname <%s> does not match demangled <%s> "
6253                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
6254                      physname, canon, mangled, die->offset.sect_off, objfile->name);
6255
6256           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
6257              is available here - over computed PHYSNAME.  It is safer
6258              against both buggy GDB and buggy compilers.  */
6259
6260           retval = canon;
6261         }
6262       else
6263         {
6264           retval = physname;
6265           need_copy = 0;
6266         }
6267     }
6268   else
6269     retval = canon;
6270
6271   if (need_copy)
6272     retval = obsavestring (retval, strlen (retval),
6273                            &objfile->objfile_obstack);
6274
6275   do_cleanups (back_to);
6276   return retval;
6277 }
6278
6279 /* Read the import statement specified by the given die and record it.  */
6280
6281 static void
6282 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
6283 {
6284   struct objfile *objfile = cu->objfile;
6285   struct attribute *import_attr;
6286   struct die_info *imported_die, *child_die;
6287   struct dwarf2_cu *imported_cu;
6288   const char *imported_name;
6289   const char *imported_name_prefix;
6290   const char *canonical_name;
6291   const char *import_alias;
6292   const char *imported_declaration = NULL;
6293   const char *import_prefix;
6294   VEC (const_char_ptr) *excludes = NULL;
6295   struct cleanup *cleanups;
6296
6297   char *temp;
6298
6299   import_attr = dwarf2_attr (die, DW_AT_import, cu);
6300   if (import_attr == NULL)
6301     {
6302       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
6303                  dwarf_tag_name (die->tag));
6304       return;
6305     }
6306
6307   imported_cu = cu;
6308   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
6309   imported_name = dwarf2_name (imported_die, imported_cu);
6310   if (imported_name == NULL)
6311     {
6312       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
6313
6314         The import in the following code:
6315         namespace A
6316           {
6317             typedef int B;
6318           }
6319
6320         int main ()
6321           {
6322             using A::B;
6323             B b;
6324             return b;
6325           }
6326
6327         ...
6328          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
6329             <52>   DW_AT_decl_file   : 1
6330             <53>   DW_AT_decl_line   : 6
6331             <54>   DW_AT_import      : <0x75>
6332          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
6333             <59>   DW_AT_name        : B
6334             <5b>   DW_AT_decl_file   : 1
6335             <5c>   DW_AT_decl_line   : 2
6336             <5d>   DW_AT_type        : <0x6e>
6337         ...
6338          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
6339             <76>   DW_AT_byte_size   : 4
6340             <77>   DW_AT_encoding    : 5        (signed)
6341
6342         imports the wrong die ( 0x75 instead of 0x58 ).
6343         This case will be ignored until the gcc bug is fixed.  */
6344       return;
6345     }
6346
6347   /* Figure out the local name after import.  */
6348   import_alias = dwarf2_name (die, cu);
6349
6350   /* Figure out where the statement is being imported to.  */
6351   import_prefix = determine_prefix (die, cu);
6352
6353   /* Figure out what the scope of the imported die is and prepend it
6354      to the name of the imported die.  */
6355   imported_name_prefix = determine_prefix (imported_die, imported_cu);
6356
6357   if (imported_die->tag != DW_TAG_namespace
6358       && imported_die->tag != DW_TAG_module)
6359     {
6360       imported_declaration = imported_name;
6361       canonical_name = imported_name_prefix;
6362     }
6363   else if (strlen (imported_name_prefix) > 0)
6364     {
6365       temp = alloca (strlen (imported_name_prefix)
6366                      + 2 + strlen (imported_name) + 1);
6367       strcpy (temp, imported_name_prefix);
6368       strcat (temp, "::");
6369       strcat (temp, imported_name);
6370       canonical_name = temp;
6371     }
6372   else
6373     canonical_name = imported_name;
6374
6375   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
6376
6377   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
6378     for (child_die = die->child; child_die && child_die->tag;
6379          child_die = sibling_die (child_die))
6380       {
6381         /* DWARF-4: A Fortran use statement with a “rename list” may be
6382            represented by an imported module entry with an import attribute
6383            referring to the module and owned entries corresponding to those
6384            entities that are renamed as part of being imported.  */
6385
6386         if (child_die->tag != DW_TAG_imported_declaration)
6387           {
6388             complaint (&symfile_complaints,
6389                        _("child DW_TAG_imported_declaration expected "
6390                          "- DIE at 0x%x [in module %s]"),
6391                        child_die->offset.sect_off, objfile->name);
6392             continue;
6393           }
6394
6395         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
6396         if (import_attr == NULL)
6397           {
6398             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
6399                        dwarf_tag_name (child_die->tag));
6400             continue;
6401           }
6402
6403         imported_cu = cu;
6404         imported_die = follow_die_ref_or_sig (child_die, import_attr,
6405                                               &imported_cu);
6406         imported_name = dwarf2_name (imported_die, imported_cu);
6407         if (imported_name == NULL)
6408           {
6409             complaint (&symfile_complaints,
6410                        _("child DW_TAG_imported_declaration has unknown "
6411                          "imported name - DIE at 0x%x [in module %s]"),
6412                        child_die->offset.sect_off, objfile->name);
6413             continue;
6414           }
6415
6416         VEC_safe_push (const_char_ptr, excludes, imported_name);
6417
6418         process_die (child_die, cu);
6419       }
6420
6421   cp_add_using_directive (import_prefix,
6422                           canonical_name,
6423                           import_alias,
6424                           imported_declaration,
6425                           excludes,
6426                           &objfile->objfile_obstack);
6427
6428   do_cleanups (cleanups);
6429 }
6430
6431 /* Cleanup function for read_file_scope.  */
6432
6433 static void
6434 free_cu_line_header (void *arg)
6435 {
6436   struct dwarf2_cu *cu = arg;
6437
6438   free_line_header (cu->line_header);
6439   cu->line_header = NULL;
6440 }
6441
6442 static void
6443 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
6444                          char **name, char **comp_dir)
6445 {
6446   struct attribute *attr;
6447
6448   *name = NULL;
6449   *comp_dir = NULL;
6450
6451   /* Find the filename.  Do not use dwarf2_name here, since the filename
6452      is not a source language identifier.  */
6453   attr = dwarf2_attr (die, DW_AT_name, cu);
6454   if (attr)
6455     {
6456       *name = DW_STRING (attr);
6457     }
6458
6459   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
6460   if (attr)
6461     *comp_dir = DW_STRING (attr);
6462   else if (*name != NULL && IS_ABSOLUTE_PATH (*name))
6463     {
6464       *comp_dir = ldirname (*name);
6465       if (*comp_dir != NULL)
6466         make_cleanup (xfree, *comp_dir);
6467     }
6468   if (*comp_dir != NULL)
6469     {
6470       /* Irix 6.2 native cc prepends <machine>.: to the compilation
6471          directory, get rid of it.  */
6472       char *cp = strchr (*comp_dir, ':');
6473
6474       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
6475         *comp_dir = cp + 1;
6476     }
6477
6478   if (*name == NULL)
6479     *name = "<unknown>";
6480 }
6481
6482 /* Handle DW_AT_stmt_list for a compilation unit or type unit.
6483    DIE is the DW_TAG_compile_unit or DW_TAG_type_unit die for CU.
6484    COMP_DIR is the compilation directory.
6485    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
6486
6487 static void
6488 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
6489                         const char *comp_dir, int want_line_info)
6490 {
6491   struct attribute *attr;
6492
6493   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6494   if (attr)
6495     {
6496       unsigned int line_offset = DW_UNSND (attr);
6497       struct line_header *line_header
6498         = dwarf_decode_line_header (line_offset, cu);
6499
6500       if (line_header)
6501         {
6502           cu->line_header = line_header;
6503           make_cleanup (free_cu_line_header, cu);
6504           dwarf_decode_lines (line_header, comp_dir, cu, NULL, want_line_info);
6505         }
6506     }
6507 }
6508
6509 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
6510
6511 static void
6512 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
6513 {
6514   struct objfile *objfile = dwarf2_per_objfile->objfile;
6515   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
6516   CORE_ADDR lowpc = ((CORE_ADDR) -1);
6517   CORE_ADDR highpc = ((CORE_ADDR) 0);
6518   struct attribute *attr;
6519   char *name = NULL;
6520   char *comp_dir = NULL;
6521   struct die_info *child_die;
6522   bfd *abfd = objfile->obfd;
6523   CORE_ADDR baseaddr;
6524
6525   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6526
6527   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
6528
6529   /* If we didn't find a lowpc, set it to highpc to avoid complaints
6530      from finish_block.  */
6531   if (lowpc == ((CORE_ADDR) -1))
6532     lowpc = highpc;
6533   lowpc += baseaddr;
6534   highpc += baseaddr;
6535
6536   find_file_and_directory (die, cu, &name, &comp_dir);
6537
6538   prepare_one_comp_unit (cu, die, cu->language);
6539
6540   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
6541      standardised yet.  As a workaround for the language detection we fall
6542      back to the DW_AT_producer string.  */
6543   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
6544     cu->language = language_opencl;
6545
6546   /* Similar hack for Go.  */
6547   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
6548     set_cu_language (DW_LANG_Go, cu);
6549
6550   /* We assume that we're processing GCC output.  */
6551   processing_gcc_compilation = 2;
6552
6553   processing_has_namespace_info = 0;
6554
6555   start_symtab (name, comp_dir, lowpc);
6556   record_debugformat ("DWARF 2");
6557   record_producer (cu->producer);
6558
6559   /* Decode line number information if present.  We do this before
6560      processing child DIEs, so that the line header table is available
6561      for DW_AT_decl_file.  */
6562   handle_DW_AT_stmt_list (die, cu, comp_dir, 1);
6563
6564   /* Process all dies in compilation unit.  */
6565   if (die->child != NULL)
6566     {
6567       child_die = die->child;
6568       while (child_die && child_die->tag)
6569         {
6570           process_die (child_die, cu);
6571           child_die = sibling_die (child_die);
6572         }
6573     }
6574
6575   /* Decode macro information, if present.  Dwarf 2 macro information
6576      refers to information in the line number info statement program
6577      header, so we can only read it if we've read the header
6578      successfully.  */
6579   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
6580   if (attr && cu->line_header)
6581     {
6582       if (dwarf2_attr (die, DW_AT_macro_info, cu))
6583         complaint (&symfile_complaints,
6584                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
6585
6586       dwarf_decode_macros (cu->line_header, DW_UNSND (attr),
6587                            comp_dir, abfd, cu,
6588                            &dwarf2_per_objfile->macro, 1,
6589                            ".debug_macro");
6590     }
6591   else
6592     {
6593       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
6594       if (attr && cu->line_header)
6595         {
6596           unsigned int macro_offset = DW_UNSND (attr);
6597
6598           dwarf_decode_macros (cu->line_header, macro_offset,
6599                                comp_dir, abfd, cu,
6600                                &dwarf2_per_objfile->macinfo, 0,
6601                                ".debug_macinfo");
6602         }
6603     }
6604
6605   do_cleanups (back_to);
6606 }
6607
6608 /* Process DW_TAG_type_unit.
6609    For TUs we want to skip the first top level sibling if it's not the
6610    actual type being defined by this TU.  In this case the first top
6611    level sibling is there to provide context only.  */
6612
6613 static void
6614 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
6615 {
6616   struct objfile *objfile = cu->objfile;
6617   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
6618   CORE_ADDR lowpc;
6619   struct attribute *attr;
6620   char *name = NULL;
6621   char *comp_dir = NULL;
6622   struct die_info *child_die;
6623   bfd *abfd = objfile->obfd;
6624
6625   /* start_symtab needs a low pc, but we don't really have one.
6626      Do what read_file_scope would do in the absence of such info.  */
6627   lowpc = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6628
6629   /* Find the filename.  Do not use dwarf2_name here, since the filename
6630      is not a source language identifier.  */
6631   attr = dwarf2_attr (die, DW_AT_name, cu);
6632   if (attr)
6633     name = DW_STRING (attr);
6634
6635   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
6636   if (attr)
6637     comp_dir = DW_STRING (attr);
6638   else if (name != NULL && IS_ABSOLUTE_PATH (name))
6639     {
6640       comp_dir = ldirname (name);
6641       if (comp_dir != NULL)
6642         make_cleanup (xfree, comp_dir);
6643     }
6644
6645   if (name == NULL)
6646     name = "<unknown>";
6647
6648   prepare_one_comp_unit (cu, die, language_minimal);
6649
6650   /* We assume that we're processing GCC output.  */
6651   processing_gcc_compilation = 2;
6652
6653   processing_has_namespace_info = 0;
6654
6655   start_symtab (name, comp_dir, lowpc);
6656   record_debugformat ("DWARF 2");
6657   record_producer (cu->producer);
6658
6659   /* Decode line number information if present.  We do this before
6660      processing child DIEs, so that the line header table is available
6661      for DW_AT_decl_file.
6662      We don't need the pc/line-number mapping for type units.  */
6663   handle_DW_AT_stmt_list (die, cu, comp_dir, 0);
6664
6665   /* Process the dies in the type unit.  */
6666   if (die->child == NULL)
6667     {
6668       dump_die_for_error (die);
6669       error (_("Dwarf Error: Missing children for type unit [in module %s]"),
6670              bfd_get_filename (abfd));
6671     }
6672
6673   child_die = die->child;
6674
6675   while (child_die && child_die->tag)
6676     {
6677       process_die (child_die, cu);
6678
6679       child_die = sibling_die (child_die);
6680     }
6681
6682   do_cleanups (back_to);
6683 }
6684 \f
6685 /* DWO files.  */
6686
6687 static hashval_t
6688 hash_dwo_file (const void *item)
6689 {
6690   const struct dwo_file *dwo_file = item;
6691
6692   return htab_hash_string (dwo_file->dwo_name);
6693 }
6694
6695 static int
6696 eq_dwo_file (const void *item_lhs, const void *item_rhs)
6697 {
6698   const struct dwo_file *lhs = item_lhs;
6699   const struct dwo_file *rhs = item_rhs;
6700
6701   return strcmp (lhs->dwo_name, rhs->dwo_name) == 0;
6702 }
6703
6704 /* Allocate a hash table for DWO files.  */
6705
6706 static htab_t
6707 allocate_dwo_file_hash_table (void)
6708 {
6709   struct objfile *objfile = dwarf2_per_objfile->objfile;
6710
6711   return htab_create_alloc_ex (41,
6712                                hash_dwo_file,
6713                                eq_dwo_file,
6714                                NULL,
6715                                &objfile->objfile_obstack,
6716                                hashtab_obstack_allocate,
6717                                dummy_obstack_deallocate);
6718 }
6719
6720 static hashval_t
6721 hash_dwo_unit (const void *item)
6722 {
6723   const struct dwo_unit *dwo_unit = item;
6724
6725   /* This drops the top 32 bits of the id, but is ok for a hash.  */
6726   return dwo_unit->signature;
6727 }
6728
6729 static int
6730 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
6731 {
6732   const struct dwo_unit *lhs = item_lhs;
6733   const struct dwo_unit *rhs = item_rhs;
6734
6735   /* The signature is assumed to be unique within the DWO file.
6736      So while object file CU dwo_id's always have the value zero,
6737      that's OK, assuming each object file DWO file has only one CU,
6738      and that's the rule for now.  */
6739   return lhs->signature == rhs->signature;
6740 }
6741
6742 /* Allocate a hash table for DWO CUs,TUs.
6743    There is one of these tables for each of CUs,TUs for each DWO file.  */
6744
6745 static htab_t
6746 allocate_dwo_unit_table (struct objfile *objfile)
6747 {
6748   /* Start out with a pretty small number.
6749      Generally DWO files contain only one CU and maybe some TUs.  */
6750   return htab_create_alloc_ex (3,
6751                                hash_dwo_unit,
6752                                eq_dwo_unit,
6753                                NULL,
6754                                &objfile->objfile_obstack,
6755                                hashtab_obstack_allocate,
6756                                dummy_obstack_deallocate);
6757 }
6758
6759 /* This function is mapped across the sections and remembers the offset and
6760    size of each of the DWO debugging sections we are interested in.  */
6761
6762 static void
6763 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_file_ptr)
6764 {
6765   struct dwo_file *dwo_file = dwo_file_ptr;
6766   const struct dwo_section_names *names = &dwo_section_names;
6767
6768   if (section_is_p (sectp->name, &names->abbrev_dwo))
6769     {
6770       dwo_file->sections.abbrev.asection = sectp;
6771       dwo_file->sections.abbrev.size = bfd_get_section_size (sectp);
6772     }
6773   else if (section_is_p (sectp->name, &names->info_dwo))
6774     {
6775       dwo_file->sections.info.asection = sectp;
6776       dwo_file->sections.info.size = bfd_get_section_size (sectp);
6777     }
6778   else if (section_is_p (sectp->name, &names->line_dwo))
6779     {
6780       dwo_file->sections.line.asection = sectp;
6781       dwo_file->sections.line.size = bfd_get_section_size (sectp);
6782     }
6783   else if (section_is_p (sectp->name, &names->loc_dwo))
6784     {
6785       dwo_file->sections.loc.asection = sectp;
6786       dwo_file->sections.loc.size = bfd_get_section_size (sectp);
6787     }
6788   else if (section_is_p (sectp->name, &names->str_dwo))
6789     {
6790       dwo_file->sections.str.asection = sectp;
6791       dwo_file->sections.str.size = bfd_get_section_size (sectp);
6792     }
6793   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
6794     {
6795       dwo_file->sections.str_offsets.asection = sectp;
6796       dwo_file->sections.str_offsets.size = bfd_get_section_size (sectp);
6797     }
6798   else if (section_is_p (sectp->name, &names->types_dwo))
6799     {
6800       struct dwarf2_section_info type_section;
6801
6802       memset (&type_section, 0, sizeof (type_section));
6803       type_section.asection = sectp;
6804       type_section.size = bfd_get_section_size (sectp);
6805       VEC_safe_push (dwarf2_section_info_def, dwo_file->sections.types,
6806                      &type_section);
6807     }
6808 }
6809
6810 /* Structure used to pass data to create_debug_info_hash_table_reader.  */
6811
6812 struct create_dwo_info_table_data
6813 {
6814   struct dwo_file *dwo_file;
6815   htab_t cu_htab;
6816 };
6817
6818 /* die_reader_func for create_debug_info_hash_table.  */
6819
6820 static void
6821 create_debug_info_hash_table_reader (const struct die_reader_specs *reader,
6822                                      gdb_byte *info_ptr,
6823                                      struct die_info *comp_unit_die,
6824                                      int has_children,
6825                                      void *datap)
6826 {
6827   struct dwarf2_cu *cu = reader->cu;
6828   struct objfile *objfile = dwarf2_per_objfile->objfile;
6829   sect_offset offset = cu->per_cu->offset;
6830   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
6831   struct create_dwo_info_table_data *data = datap;
6832   struct dwo_file *dwo_file = data->dwo_file;
6833   htab_t cu_htab = data->cu_htab;
6834   void **slot;
6835   struct attribute *attr;
6836   struct dwo_unit *dwo_unit;
6837
6838   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6839   if (attr == NULL)
6840     {
6841       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
6842                " its dwo_id [in module %s]"),
6843              offset.sect_off, dwo_file->dwo_name);
6844       return;
6845     }
6846
6847   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
6848   dwo_unit->dwo_file = dwo_file;
6849   dwo_unit->signature = DW_UNSND (attr);
6850   dwo_unit->info_or_types_section = section;
6851   dwo_unit->offset = offset;
6852   dwo_unit->length = cu->per_cu->length;
6853
6854   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
6855   gdb_assert (slot != NULL);
6856   if (*slot != NULL)
6857     {
6858       const struct dwo_unit *dup_dwo_unit = *slot;
6859
6860       complaint (&symfile_complaints,
6861                  _("debug entry at offset 0x%x is duplicate to the entry at"
6862                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
6863                  offset.sect_off, dup_dwo_unit->offset.sect_off,
6864                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
6865                  dwo_file->dwo_name);
6866     }
6867   else
6868     *slot = dwo_unit;
6869
6870   if (dwarf2_die_debug)
6871     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
6872                         offset.sect_off,
6873                         phex (dwo_unit->signature,
6874                               sizeof (dwo_unit->signature)));
6875 }
6876
6877 /* Create a hash table to map DWO IDs to their CU entry in .debug_info.dwo.  */
6878
6879 static htab_t
6880 create_debug_info_hash_table (struct dwo_file *dwo_file)
6881 {
6882   struct objfile *objfile = dwarf2_per_objfile->objfile;
6883   struct dwarf2_section_info *section = &dwo_file->sections.info;
6884   bfd *abfd;
6885   htab_t cu_htab;
6886   gdb_byte *info_ptr, *end_ptr;
6887   struct create_dwo_info_table_data create_dwo_info_table_data;
6888
6889   dwarf2_read_section (objfile, section);
6890   info_ptr = section->buffer;
6891
6892   if (info_ptr == NULL)
6893     return NULL;
6894
6895   /* We can't set abfd until now because the section may be empty or
6896      not present, in which case section->asection will be NULL.  */
6897   abfd = section->asection->owner;
6898
6899   if (dwarf2_die_debug)
6900     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
6901                         bfd_get_filename (abfd));
6902
6903   cu_htab = allocate_dwo_unit_table (objfile);
6904
6905   create_dwo_info_table_data.dwo_file = dwo_file;
6906   create_dwo_info_table_data.cu_htab = cu_htab;
6907
6908   end_ptr = info_ptr + section->size;
6909   while (info_ptr < end_ptr)
6910     {
6911       struct dwarf2_per_cu_data per_cu;
6912
6913       memset (&per_cu, 0, sizeof (per_cu));
6914       per_cu.objfile = objfile;
6915       per_cu.is_debug_types = 0;
6916       per_cu.offset.sect_off = info_ptr - section->buffer;
6917       per_cu.info_or_types_section = section;
6918
6919       init_cutu_and_read_dies_no_follow (&per_cu,
6920                                          &dwo_file->sections.abbrev,
6921                                          dwo_file,
6922                                          create_debug_info_hash_table_reader,
6923                                          &create_dwo_info_table_data);
6924
6925       info_ptr += per_cu.length;
6926     }
6927
6928   return cu_htab;
6929 }
6930
6931 /* Subroutine of open_dwo_file to simplify it.
6932    Open the file specified by FILE_NAME and hand it off to BFD for
6933    preliminary analysis.  Return a newly initialized bfd *, which
6934    includes a canonicalized copy of FILE_NAME.
6935    In case of trouble, return NULL.
6936    NOTE: This function is derived from symfile_bfd_open.  */
6937
6938 static bfd *
6939 try_open_dwo_file (const char *file_name)
6940 {
6941   bfd *sym_bfd;
6942   int desc;
6943   char *absolute_name;
6944
6945   desc = openp (debug_file_directory, OPF_TRY_CWD_FIRST, file_name,
6946                 O_RDONLY | O_BINARY, &absolute_name);
6947   if (desc < 0)
6948     return NULL;
6949
6950   sym_bfd = bfd_fopen (absolute_name, gnutarget, FOPEN_RB, desc);
6951   if (!sym_bfd)
6952     {
6953       close (desc);
6954       xfree (absolute_name);
6955       return NULL;
6956     }
6957   bfd_set_cacheable (sym_bfd, 1);
6958
6959   if (!bfd_check_format (sym_bfd, bfd_object))
6960     {
6961       bfd_close (sym_bfd); /* This also closes desc.  */
6962       xfree (absolute_name);
6963       return NULL;
6964     }
6965
6966   /* bfd_usrdata exists for applications and libbfd must not touch it.  */
6967   gdb_assert (bfd_usrdata (sym_bfd) == NULL);
6968
6969   return sym_bfd;
6970 }
6971
6972 /* Try to open DWO file DWO_NAME.
6973    COMP_DIR is the DW_AT_comp_dir attribute.
6974    The result is the bfd handle of the file.
6975    If there is a problem finding or opening the file, return NULL.
6976    Upon success, the canonicalized path of the file is stored in the bfd,
6977    same as symfile_bfd_open.  */
6978
6979 static bfd *
6980 open_dwo_file (const char *dwo_name, const char *comp_dir)
6981 {
6982   bfd *abfd;
6983
6984   if (IS_ABSOLUTE_PATH (dwo_name))
6985     return try_open_dwo_file (dwo_name);
6986
6987   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
6988
6989   if (comp_dir != NULL)
6990     {
6991       char *path_to_try = concat (comp_dir, SLASH_STRING, dwo_name, NULL);
6992
6993       /* NOTE: If comp_dir is a relative path, this will also try the
6994          search path, which seems useful.  */
6995       abfd = try_open_dwo_file (path_to_try);
6996       xfree (path_to_try);
6997       if (abfd != NULL)
6998         return abfd;
6999     }
7000
7001   /* That didn't work, try debug-file-directory, which, despite its name,
7002      is a list of paths.  */
7003
7004   if (*debug_file_directory == '\0')
7005     return NULL;
7006
7007   return try_open_dwo_file (dwo_name);
7008 }
7009
7010 /* Initialize the use of the DWO file specified by DWO_NAME.  */
7011
7012 static struct dwo_file *
7013 init_dwo_file (const char *dwo_name, const char *comp_dir)
7014 {
7015   struct objfile *objfile = dwarf2_per_objfile->objfile;
7016   struct dwo_file *dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7017                                               struct dwo_file);
7018   bfd *abfd;
7019   struct cleanup *cleanups;
7020
7021   if (dwarf2_die_debug)
7022     fprintf_unfiltered (gdb_stdlog, "Reading DWO file %s:\n", dwo_name);
7023
7024   abfd = open_dwo_file (dwo_name, comp_dir);
7025   if (abfd == NULL)
7026     return NULL;
7027   dwo_file->dwo_name = dwo_name;
7028   dwo_file->dwo_bfd = abfd;
7029
7030   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
7031
7032   bfd_map_over_sections (abfd, dwarf2_locate_dwo_sections, dwo_file);
7033
7034   dwo_file->cus = create_debug_info_hash_table (dwo_file);
7035
7036   dwo_file->tus = create_debug_types_hash_table (dwo_file,
7037                                                  dwo_file->sections.types);
7038
7039   discard_cleanups (cleanups);
7040
7041   return dwo_file;
7042 }
7043
7044 /* Lookup DWO file DWO_NAME.  */
7045
7046 static struct dwo_file *
7047 lookup_dwo_file (char *dwo_name, const char *comp_dir)
7048 {
7049   struct dwo_file *dwo_file;
7050   struct dwo_file find_entry;
7051   void **slot;
7052
7053   if (dwarf2_per_objfile->dwo_files == NULL)
7054     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
7055
7056   /* Have we already seen this DWO file?  */
7057   find_entry.dwo_name = dwo_name;
7058   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
7059
7060   /* If not, read it in and build a table of the DWOs it contains.  */
7061   if (*slot == NULL)
7062     *slot = init_dwo_file (dwo_name, comp_dir);
7063
7064   /* NOTE: This will be NULL if unable to open the file.  */
7065   dwo_file = *slot;
7066
7067   return dwo_file;
7068 }
7069
7070 /* Lookup the DWO CU referenced from THIS_CU in DWO file DWO_NAME.
7071    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
7072    SIGNATURE is the "dwo_id" of the CU (for consistency we use the same
7073    nomenclature as TUs).
7074    The result is the DWO CU or NULL if we didn't find it
7075    (dwo_id mismatch or couldn't find the DWO file).  */
7076
7077 static struct dwo_unit *
7078 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
7079                       char *dwo_name, const char *comp_dir,
7080                       ULONGEST signature)
7081 {
7082   struct objfile *objfile = dwarf2_per_objfile->objfile;
7083   struct dwo_file *dwo_file;
7084
7085   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
7086   if (dwo_file == NULL)
7087     return NULL;
7088
7089   /* Look up the DWO using its signature(dwo_id).  */
7090
7091   if (dwo_file->cus != NULL)
7092     {
7093       struct dwo_unit find_dwo_cu, *dwo_cu;
7094
7095       find_dwo_cu.signature = signature;
7096       dwo_cu = htab_find (dwo_file->cus, &find_dwo_cu);
7097
7098       if (dwo_cu != NULL)
7099         return dwo_cu;
7100     }
7101
7102   /* We didn't find it.  This must mean a dwo_id mismatch.  */
7103
7104   complaint (&symfile_complaints,
7105              _("Could not find DWO CU referenced by CU at offset 0x%x"
7106                " [in module %s]"),
7107              this_cu->offset.sect_off, objfile->name);
7108   return NULL;
7109 }
7110
7111 /* Lookup the DWO TU referenced from THIS_TU in DWO file DWO_NAME.
7112    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
7113    The result is the DWO CU or NULL if we didn't find it
7114    (dwo_id mismatch or couldn't find the DWO file).  */
7115
7116 static struct dwo_unit *
7117 lookup_dwo_type_unit (struct signatured_type *this_tu,
7118                       char *dwo_name, const char *comp_dir)
7119 {
7120   struct objfile *objfile = dwarf2_per_objfile->objfile;
7121   struct dwo_file *dwo_file;
7122
7123   dwo_file = lookup_dwo_file (dwo_name, comp_dir);
7124   if (dwo_file == NULL)
7125     return NULL;
7126
7127   /* Look up the DWO using its signature(dwo_id).  */
7128
7129   if (dwo_file->tus != NULL)
7130     {
7131       struct dwo_unit find_dwo_tu, *dwo_tu;
7132
7133       find_dwo_tu.signature = this_tu->signature;
7134       dwo_tu = htab_find (dwo_file->tus, &find_dwo_tu);
7135
7136       if (dwo_tu != NULL)
7137         return dwo_tu;
7138     }
7139
7140   /* We didn't find it.  This must mean a dwo_id mismatch.  */
7141
7142   complaint (&symfile_complaints,
7143              _("Could not find DWO TU referenced by TU at offset 0x%x"
7144                " [in module %s]"),
7145              this_tu->per_cu.offset.sect_off, objfile->name);
7146   return NULL;
7147 }
7148
7149 /* Free all resources associated with DWO_FILE.
7150    Close the DWO file and munmap the sections.
7151    All memory should be on the objfile obstack.  */
7152
7153 static void
7154 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
7155 {
7156   int ix;
7157   struct dwarf2_section_info *section;
7158
7159   gdb_assert (dwo_file->dwo_bfd != objfile->obfd);
7160   bfd_close (dwo_file->dwo_bfd);
7161
7162   munmap_section_buffer (&dwo_file->sections.abbrev);
7163   munmap_section_buffer (&dwo_file->sections.info);
7164   munmap_section_buffer (&dwo_file->sections.line);
7165   munmap_section_buffer (&dwo_file->sections.loc);
7166   munmap_section_buffer (&dwo_file->sections.str);
7167   munmap_section_buffer (&dwo_file->sections.str_offsets);
7168
7169   for (ix = 0;
7170        VEC_iterate (dwarf2_section_info_def, dwo_file->sections.types,
7171                     ix, section);
7172        ++ix)
7173     munmap_section_buffer (section);
7174
7175   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
7176 }
7177
7178 /* Wrapper for free_dwo_file for use in cleanups.  */
7179
7180 static void
7181 free_dwo_file_cleanup (void *arg)
7182 {
7183   struct dwo_file *dwo_file = (struct dwo_file *) arg;
7184   struct objfile *objfile = dwarf2_per_objfile->objfile;
7185
7186   free_dwo_file (dwo_file, objfile);
7187 }
7188
7189 /* Traversal function for free_dwo_files.  */
7190
7191 static int
7192 free_dwo_file_from_slot (void **slot, void *info)
7193 {
7194   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7195   struct objfile *objfile = (struct objfile *) info;
7196
7197   free_dwo_file (dwo_file, objfile);
7198
7199   return 1;
7200 }
7201
7202 /* Free all resources associated with DWO_FILES.  */
7203
7204 static void
7205 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
7206 {
7207   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
7208 }
7209 \f
7210 /* Read in various DIEs.  */
7211
7212 /* qsort helper for inherit_abstract_dies.  */
7213
7214 static int
7215 unsigned_int_compar (const void *ap, const void *bp)
7216 {
7217   unsigned int a = *(unsigned int *) ap;
7218   unsigned int b = *(unsigned int *) bp;
7219
7220   return (a > b) - (b > a);
7221 }
7222
7223 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
7224    Inherit only the children of the DW_AT_abstract_origin DIE not being
7225    already referenced by DW_AT_abstract_origin from the children of the
7226    current DIE.  */
7227
7228 static void
7229 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
7230 {
7231   struct die_info *child_die;
7232   unsigned die_children_count;
7233   /* CU offsets which were referenced by children of the current DIE.  */
7234   sect_offset *offsets;
7235   sect_offset *offsets_end, *offsetp;
7236   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
7237   struct die_info *origin_die;
7238   /* Iterator of the ORIGIN_DIE children.  */
7239   struct die_info *origin_child_die;
7240   struct cleanup *cleanups;
7241   struct attribute *attr;
7242   struct dwarf2_cu *origin_cu;
7243   struct pending **origin_previous_list_in_scope;
7244
7245   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
7246   if (!attr)
7247     return;
7248
7249   /* Note that following die references may follow to a die in a
7250      different cu.  */
7251
7252   origin_cu = cu;
7253   origin_die = follow_die_ref (die, attr, &origin_cu);
7254
7255   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
7256      symbols in.  */
7257   origin_previous_list_in_scope = origin_cu->list_in_scope;
7258   origin_cu->list_in_scope = cu->list_in_scope;
7259
7260   if (die->tag != origin_die->tag
7261       && !(die->tag == DW_TAG_inlined_subroutine
7262            && origin_die->tag == DW_TAG_subprogram))
7263     complaint (&symfile_complaints,
7264                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
7265                die->offset.sect_off, origin_die->offset.sect_off);
7266
7267   child_die = die->child;
7268   die_children_count = 0;
7269   while (child_die && child_die->tag)
7270     {
7271       child_die = sibling_die (child_die);
7272       die_children_count++;
7273     }
7274   offsets = xmalloc (sizeof (*offsets) * die_children_count);
7275   cleanups = make_cleanup (xfree, offsets);
7276
7277   offsets_end = offsets;
7278   child_die = die->child;
7279   while (child_die && child_die->tag)
7280     {
7281       /* For each CHILD_DIE, find the corresponding child of
7282          ORIGIN_DIE.  If there is more than one layer of
7283          DW_AT_abstract_origin, follow them all; there shouldn't be,
7284          but GCC versions at least through 4.4 generate this (GCC PR
7285          40573).  */
7286       struct die_info *child_origin_die = child_die;
7287       struct dwarf2_cu *child_origin_cu = cu;
7288
7289       while (1)
7290         {
7291           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
7292                               child_origin_cu);
7293           if (attr == NULL)
7294             break;
7295           child_origin_die = follow_die_ref (child_origin_die, attr,
7296                                              &child_origin_cu);
7297         }
7298
7299       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
7300          counterpart may exist.  */
7301       if (child_origin_die != child_die)
7302         {
7303           if (child_die->tag != child_origin_die->tag
7304               && !(child_die->tag == DW_TAG_inlined_subroutine
7305                    && child_origin_die->tag == DW_TAG_subprogram))
7306             complaint (&symfile_complaints,
7307                        _("Child DIE 0x%x and its abstract origin 0x%x have "
7308                          "different tags"), child_die->offset.sect_off,
7309                        child_origin_die->offset.sect_off);
7310           if (child_origin_die->parent != origin_die)
7311             complaint (&symfile_complaints,
7312                        _("Child DIE 0x%x and its abstract origin 0x%x have "
7313                          "different parents"), child_die->offset.sect_off,
7314                        child_origin_die->offset.sect_off);
7315           else
7316             *offsets_end++ = child_origin_die->offset;
7317         }
7318       child_die = sibling_die (child_die);
7319     }
7320   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
7321          unsigned_int_compar);
7322   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
7323     if (offsetp[-1].sect_off == offsetp->sect_off)
7324       complaint (&symfile_complaints,
7325                  _("Multiple children of DIE 0x%x refer "
7326                    "to DIE 0x%x as their abstract origin"),
7327                  die->offset.sect_off, offsetp->sect_off);
7328
7329   offsetp = offsets;
7330   origin_child_die = origin_die->child;
7331   while (origin_child_die && origin_child_die->tag)
7332     {
7333       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
7334       while (offsetp < offsets_end
7335              && offsetp->sect_off < origin_child_die->offset.sect_off)
7336         offsetp++;
7337       if (offsetp >= offsets_end
7338           || offsetp->sect_off > origin_child_die->offset.sect_off)
7339         {
7340           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
7341           process_die (origin_child_die, origin_cu);
7342         }
7343       origin_child_die = sibling_die (origin_child_die);
7344     }
7345   origin_cu->list_in_scope = origin_previous_list_in_scope;
7346
7347   do_cleanups (cleanups);
7348 }
7349
7350 static void
7351 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
7352 {
7353   struct objfile *objfile = cu->objfile;
7354   struct context_stack *new;
7355   CORE_ADDR lowpc;
7356   CORE_ADDR highpc;
7357   struct die_info *child_die;
7358   struct attribute *attr, *call_line, *call_file;
7359   char *name;
7360   CORE_ADDR baseaddr;
7361   struct block *block;
7362   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
7363   VEC (symbolp) *template_args = NULL;
7364   struct template_symbol *templ_func = NULL;
7365
7366   if (inlined_func)
7367     {
7368       /* If we do not have call site information, we can't show the
7369          caller of this inlined function.  That's too confusing, so
7370          only use the scope for local variables.  */
7371       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
7372       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
7373       if (call_line == NULL || call_file == NULL)
7374         {
7375           read_lexical_block_scope (die, cu);
7376           return;
7377         }
7378     }
7379
7380   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7381
7382   name = dwarf2_name (die, cu);
7383
7384   /* Ignore functions with missing or empty names.  These are actually
7385      illegal according to the DWARF standard.  */
7386   if (name == NULL)
7387     {
7388       complaint (&symfile_complaints,
7389                  _("missing name for subprogram DIE at %d"),
7390                  die->offset.sect_off);
7391       return;
7392     }
7393
7394   /* Ignore functions with missing or invalid low and high pc attributes.  */
7395   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
7396     {
7397       attr = dwarf2_attr (die, DW_AT_external, cu);
7398       if (!attr || !DW_UNSND (attr))
7399         complaint (&symfile_complaints,
7400                    _("cannot get low and high bounds "
7401                      "for subprogram DIE at %d"),
7402                    die->offset.sect_off);
7403       return;
7404     }
7405
7406   lowpc += baseaddr;
7407   highpc += baseaddr;
7408
7409   /* If we have any template arguments, then we must allocate a
7410      different sort of symbol.  */
7411   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
7412     {
7413       if (child_die->tag == DW_TAG_template_type_param
7414           || child_die->tag == DW_TAG_template_value_param)
7415         {
7416           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7417                                        struct template_symbol);
7418           templ_func->base.is_cplus_template_function = 1;
7419           break;
7420         }
7421     }
7422
7423   new = push_context (0, lowpc);
7424   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
7425                                (struct symbol *) templ_func);
7426
7427   /* If there is a location expression for DW_AT_frame_base, record
7428      it.  */
7429   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
7430   if (attr)
7431     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
7432        expression is being recorded directly in the function's symbol
7433        and not in a separate frame-base object.  I guess this hack is
7434        to avoid adding some sort of frame-base adjunct/annex to the
7435        function's symbol :-(.  The problem with doing this is that it
7436        results in a function symbol with a location expression that
7437        has nothing to do with the location of the function, ouch!  The
7438        relationship should be: a function's symbol has-a frame base; a
7439        frame-base has-a location expression.  */
7440     dwarf2_symbol_mark_computed (attr, new->name, cu);
7441
7442   cu->list_in_scope = &local_symbols;
7443
7444   if (die->child != NULL)
7445     {
7446       child_die = die->child;
7447       while (child_die && child_die->tag)
7448         {
7449           if (child_die->tag == DW_TAG_template_type_param
7450               || child_die->tag == DW_TAG_template_value_param)
7451             {
7452               struct symbol *arg = new_symbol (child_die, NULL, cu);
7453
7454               if (arg != NULL)
7455                 VEC_safe_push (symbolp, template_args, arg);
7456             }
7457           else
7458             process_die (child_die, cu);
7459           child_die = sibling_die (child_die);
7460         }
7461     }
7462
7463   inherit_abstract_dies (die, cu);
7464
7465   /* If we have a DW_AT_specification, we might need to import using
7466      directives from the context of the specification DIE.  See the
7467      comment in determine_prefix.  */
7468   if (cu->language == language_cplus
7469       && dwarf2_attr (die, DW_AT_specification, cu))
7470     {
7471       struct dwarf2_cu *spec_cu = cu;
7472       struct die_info *spec_die = die_specification (die, &spec_cu);
7473
7474       while (spec_die)
7475         {
7476           child_die = spec_die->child;
7477           while (child_die && child_die->tag)
7478             {
7479               if (child_die->tag == DW_TAG_imported_module)
7480                 process_die (child_die, spec_cu);
7481               child_die = sibling_die (child_die);
7482             }
7483
7484           /* In some cases, GCC generates specification DIEs that
7485              themselves contain DW_AT_specification attributes.  */
7486           spec_die = die_specification (spec_die, &spec_cu);
7487         }
7488     }
7489
7490   new = pop_context ();
7491   /* Make a block for the local symbols within.  */
7492   block = finish_block (new->name, &local_symbols, new->old_blocks,
7493                         lowpc, highpc, objfile);
7494
7495   /* For C++, set the block's scope.  */
7496   if (cu->language == language_cplus || cu->language == language_fortran)
7497     cp_set_block_scope (new->name, block, &objfile->objfile_obstack,
7498                         determine_prefix (die, cu),
7499                         processing_has_namespace_info);
7500
7501   /* If we have address ranges, record them.  */
7502   dwarf2_record_block_ranges (die, block, baseaddr, cu);
7503
7504   /* Attach template arguments to function.  */
7505   if (! VEC_empty (symbolp, template_args))
7506     {
7507       gdb_assert (templ_func != NULL);
7508
7509       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
7510       templ_func->template_arguments
7511         = obstack_alloc (&objfile->objfile_obstack,
7512                          (templ_func->n_template_arguments
7513                           * sizeof (struct symbol *)));
7514       memcpy (templ_func->template_arguments,
7515               VEC_address (symbolp, template_args),
7516               (templ_func->n_template_arguments * sizeof (struct symbol *)));
7517       VEC_free (symbolp, template_args);
7518     }
7519
7520   /* In C++, we can have functions nested inside functions (e.g., when
7521      a function declares a class that has methods).  This means that
7522      when we finish processing a function scope, we may need to go
7523      back to building a containing block's symbol lists.  */
7524   local_symbols = new->locals;
7525   param_symbols = new->params;
7526   using_directives = new->using_directives;
7527
7528   /* If we've finished processing a top-level function, subsequent
7529      symbols go in the file symbol list.  */
7530   if (outermost_context_p ())
7531     cu->list_in_scope = &file_symbols;
7532 }
7533
7534 /* Process all the DIES contained within a lexical block scope.  Start
7535    a new scope, process the dies, and then close the scope.  */
7536
7537 static void
7538 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
7539 {
7540   struct objfile *objfile = cu->objfile;
7541   struct context_stack *new;
7542   CORE_ADDR lowpc, highpc;
7543   struct die_info *child_die;
7544   CORE_ADDR baseaddr;
7545
7546   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7547
7548   /* Ignore blocks with missing or invalid low and high pc attributes.  */
7549   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
7550      as multiple lexical blocks?  Handling children in a sane way would
7551      be nasty.  Might be easier to properly extend generic blocks to
7552      describe ranges.  */
7553   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
7554     return;
7555   lowpc += baseaddr;
7556   highpc += baseaddr;
7557
7558   push_context (0, lowpc);
7559   if (die->child != NULL)
7560     {
7561       child_die = die->child;
7562       while (child_die && child_die->tag)
7563         {
7564           process_die (child_die, cu);
7565           child_die = sibling_die (child_die);
7566         }
7567     }
7568   new = pop_context ();
7569
7570   if (local_symbols != NULL || using_directives != NULL)
7571     {
7572       struct block *block
7573         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
7574                         highpc, objfile);
7575
7576       /* Note that recording ranges after traversing children, as we
7577          do here, means that recording a parent's ranges entails
7578          walking across all its children's ranges as they appear in
7579          the address map, which is quadratic behavior.
7580
7581          It would be nicer to record the parent's ranges before
7582          traversing its children, simply overriding whatever you find
7583          there.  But since we don't even decide whether to create a
7584          block until after we've traversed its children, that's hard
7585          to do.  */
7586       dwarf2_record_block_ranges (die, block, baseaddr, cu);
7587     }
7588   local_symbols = new->locals;
7589   using_directives = new->using_directives;
7590 }
7591
7592 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
7593
7594 static void
7595 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
7596 {
7597   struct objfile *objfile = cu->objfile;
7598   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7599   CORE_ADDR pc, baseaddr;
7600   struct attribute *attr;
7601   struct call_site *call_site, call_site_local;
7602   void **slot;
7603   int nparams;
7604   struct die_info *child_die;
7605
7606   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7607
7608   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
7609   if (!attr)
7610     {
7611       complaint (&symfile_complaints,
7612                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
7613                    "DIE 0x%x [in module %s]"),
7614                  die->offset.sect_off, objfile->name);
7615       return;
7616     }
7617   pc = DW_ADDR (attr) + baseaddr;
7618
7619   if (cu->call_site_htab == NULL)
7620     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
7621                                                NULL, &objfile->objfile_obstack,
7622                                                hashtab_obstack_allocate, NULL);
7623   call_site_local.pc = pc;
7624   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
7625   if (*slot != NULL)
7626     {
7627       complaint (&symfile_complaints,
7628                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
7629                    "DIE 0x%x [in module %s]"),
7630                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
7631       return;
7632     }
7633
7634   /* Count parameters at the caller.  */
7635
7636   nparams = 0;
7637   for (child_die = die->child; child_die && child_die->tag;
7638        child_die = sibling_die (child_die))
7639     {
7640       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
7641         {
7642           complaint (&symfile_complaints,
7643                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
7644                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7645                      child_die->tag, child_die->offset.sect_off, objfile->name);
7646           continue;
7647         }
7648
7649       nparams++;
7650     }
7651
7652   call_site = obstack_alloc (&objfile->objfile_obstack,
7653                              (sizeof (*call_site)
7654                               + (sizeof (*call_site->parameter)
7655                                  * (nparams - 1))));
7656   *slot = call_site;
7657   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
7658   call_site->pc = pc;
7659
7660   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
7661     {
7662       struct die_info *func_die;
7663
7664       /* Skip also over DW_TAG_inlined_subroutine.  */
7665       for (func_die = die->parent;
7666            func_die && func_die->tag != DW_TAG_subprogram
7667            && func_die->tag != DW_TAG_subroutine_type;
7668            func_die = func_die->parent);
7669
7670       /* DW_AT_GNU_all_call_sites is a superset
7671          of DW_AT_GNU_all_tail_call_sites.  */
7672       if (func_die
7673           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
7674           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
7675         {
7676           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
7677              not complete.  But keep CALL_SITE for look ups via call_site_htab,
7678              both the initial caller containing the real return address PC and
7679              the final callee containing the current PC of a chain of tail
7680              calls do not need to have the tail call list complete.  But any
7681              function candidate for a virtual tail call frame searched via
7682              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
7683              determined unambiguously.  */
7684         }
7685       else
7686         {
7687           struct type *func_type = NULL;
7688
7689           if (func_die)
7690             func_type = get_die_type (func_die, cu);
7691           if (func_type != NULL)
7692             {
7693               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
7694
7695               /* Enlist this call site to the function.  */
7696               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
7697               TYPE_TAIL_CALL_LIST (func_type) = call_site;
7698             }
7699           else
7700             complaint (&symfile_complaints,
7701                        _("Cannot find function owning DW_TAG_GNU_call_site "
7702                          "DIE 0x%x [in module %s]"),
7703                        die->offset.sect_off, objfile->name);
7704         }
7705     }
7706
7707   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
7708   if (attr == NULL)
7709     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
7710   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
7711   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
7712     /* Keep NULL DWARF_BLOCK.  */;
7713   else if (attr_form_is_block (attr))
7714     {
7715       struct dwarf2_locexpr_baton *dlbaton;
7716
7717       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
7718       dlbaton->data = DW_BLOCK (attr)->data;
7719       dlbaton->size = DW_BLOCK (attr)->size;
7720       dlbaton->per_cu = cu->per_cu;
7721
7722       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
7723     }
7724   else if (is_ref_attr (attr))
7725     {
7726       struct dwarf2_cu *target_cu = cu;
7727       struct die_info *target_die;
7728
7729       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
7730       gdb_assert (target_cu->objfile == objfile);
7731       if (die_is_declaration (target_die, target_cu))
7732         {
7733           const char *target_physname;
7734
7735           target_physname = dwarf2_physname (NULL, target_die, target_cu);
7736           if (target_physname == NULL)
7737             complaint (&symfile_complaints,
7738                        _("DW_AT_GNU_call_site_target target DIE has invalid "
7739                          "physname, for referencing DIE 0x%x [in module %s]"),
7740                        die->offset.sect_off, objfile->name);
7741           else
7742             SET_FIELD_PHYSNAME (call_site->target, (char *) target_physname);
7743         }
7744       else
7745         {
7746           CORE_ADDR lowpc;
7747
7748           /* DW_AT_entry_pc should be preferred.  */
7749           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
7750             complaint (&symfile_complaints,
7751                        _("DW_AT_GNU_call_site_target target DIE has invalid "
7752                          "low pc, for referencing DIE 0x%x [in module %s]"),
7753                        die->offset.sect_off, objfile->name);
7754           else
7755             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
7756         }
7757     }
7758   else
7759     complaint (&symfile_complaints,
7760                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
7761                  "block nor reference, for DIE 0x%x [in module %s]"),
7762                die->offset.sect_off, objfile->name);
7763
7764   call_site->per_cu = cu->per_cu;
7765
7766   for (child_die = die->child;
7767        child_die && child_die->tag;
7768        child_die = sibling_die (child_die))
7769     {
7770       struct call_site_parameter *parameter;
7771
7772       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
7773         {
7774           /* Already printed the complaint above.  */
7775           continue;
7776         }
7777
7778       gdb_assert (call_site->parameter_count < nparams);
7779       parameter = &call_site->parameter[call_site->parameter_count];
7780
7781       /* DW_AT_location specifies the register number.  Value of the data
7782          assumed for the register is contained in DW_AT_GNU_call_site_value.  */
7783
7784       attr = dwarf2_attr (child_die, DW_AT_location, cu);
7785       if (!attr || !attr_form_is_block (attr))
7786         {
7787           complaint (&symfile_complaints,
7788                      _("No DW_FORM_block* DW_AT_location for "
7789                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7790                      child_die->offset.sect_off, objfile->name);
7791           continue;
7792         }
7793       parameter->dwarf_reg = dwarf_block_to_dwarf_reg (DW_BLOCK (attr)->data,
7794                                  &DW_BLOCK (attr)->data[DW_BLOCK (attr)->size]);
7795       if (parameter->dwarf_reg == -1
7796           && !dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (attr)->data,
7797                                   &DW_BLOCK (attr)->data[DW_BLOCK (attr)->size],
7798                                         &parameter->fb_offset))
7799         {
7800           complaint (&symfile_complaints,
7801                      _("Only single DW_OP_reg or DW_OP_fbreg is supported "
7802                        "for DW_FORM_block* DW_AT_location for "
7803                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7804                      child_die->offset.sect_off, objfile->name);
7805           continue;
7806         }
7807
7808       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
7809       if (!attr_form_is_block (attr))
7810         {
7811           complaint (&symfile_complaints,
7812                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
7813                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7814                      child_die->offset.sect_off, objfile->name);
7815           continue;
7816         }
7817       parameter->value = DW_BLOCK (attr)->data;
7818       parameter->value_size = DW_BLOCK (attr)->size;
7819
7820       /* Parameters are not pre-cleared by memset above.  */
7821       parameter->data_value = NULL;
7822       parameter->data_value_size = 0;
7823       call_site->parameter_count++;
7824
7825       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
7826       if (attr)
7827         {
7828           if (!attr_form_is_block (attr))
7829             complaint (&symfile_complaints,
7830                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
7831                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
7832                        child_die->offset.sect_off, objfile->name);
7833           else
7834             {
7835               parameter->data_value = DW_BLOCK (attr)->data;
7836               parameter->data_value_size = DW_BLOCK (attr)->size;
7837             }
7838         }
7839     }
7840 }
7841
7842 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
7843    Return 1 if the attributes are present and valid, otherwise, return 0.
7844    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
7845
7846 static int
7847 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
7848                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
7849                     struct partial_symtab *ranges_pst)
7850 {
7851   struct objfile *objfile = cu->objfile;
7852   struct comp_unit_head *cu_header = &cu->header;
7853   bfd *obfd = objfile->obfd;
7854   unsigned int addr_size = cu_header->addr_size;
7855   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
7856   /* Base address selection entry.  */
7857   CORE_ADDR base;
7858   int found_base;
7859   unsigned int dummy;
7860   gdb_byte *buffer;
7861   CORE_ADDR marker;
7862   int low_set;
7863   CORE_ADDR low = 0;
7864   CORE_ADDR high = 0;
7865   CORE_ADDR baseaddr;
7866
7867   found_base = cu->base_known;
7868   base = cu->base_address;
7869
7870   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
7871   if (offset >= dwarf2_per_objfile->ranges.size)
7872     {
7873       complaint (&symfile_complaints,
7874                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
7875                  offset);
7876       return 0;
7877     }
7878   buffer = dwarf2_per_objfile->ranges.buffer + offset;
7879
7880   /* Read in the largest possible address.  */
7881   marker = read_address (obfd, buffer, cu, &dummy);
7882   if ((marker & mask) == mask)
7883     {
7884       /* If we found the largest possible address, then
7885          read the base address.  */
7886       base = read_address (obfd, buffer + addr_size, cu, &dummy);
7887       buffer += 2 * addr_size;
7888       offset += 2 * addr_size;
7889       found_base = 1;
7890     }
7891
7892   low_set = 0;
7893
7894   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7895
7896   while (1)
7897     {
7898       CORE_ADDR range_beginning, range_end;
7899
7900       range_beginning = read_address (obfd, buffer, cu, &dummy);
7901       buffer += addr_size;
7902       range_end = read_address (obfd, buffer, cu, &dummy);
7903       buffer += addr_size;
7904       offset += 2 * addr_size;
7905
7906       /* An end of list marker is a pair of zero addresses.  */
7907       if (range_beginning == 0 && range_end == 0)
7908         /* Found the end of list entry.  */
7909         break;
7910
7911       /* Each base address selection entry is a pair of 2 values.
7912          The first is the largest possible address, the second is
7913          the base address.  Check for a base address here.  */
7914       if ((range_beginning & mask) == mask)
7915         {
7916           /* If we found the largest possible address, then
7917              read the base address.  */
7918           base = read_address (obfd, buffer + addr_size, cu, &dummy);
7919           found_base = 1;
7920           continue;
7921         }
7922
7923       if (!found_base)
7924         {
7925           /* We have no valid base address for the ranges
7926              data.  */
7927           complaint (&symfile_complaints,
7928                      _("Invalid .debug_ranges data (no base address)"));
7929           return 0;
7930         }
7931
7932       if (range_beginning > range_end)
7933         {
7934           /* Inverted range entries are invalid.  */
7935           complaint (&symfile_complaints,
7936                      _("Invalid .debug_ranges data (inverted range)"));
7937           return 0;
7938         }
7939
7940       /* Empty range entries have no effect.  */
7941       if (range_beginning == range_end)
7942         continue;
7943
7944       range_beginning += base;
7945       range_end += base;
7946
7947       if (ranges_pst != NULL)
7948         addrmap_set_empty (objfile->psymtabs_addrmap,
7949                            range_beginning + baseaddr,
7950                            range_end - 1 + baseaddr,
7951                            ranges_pst);
7952
7953       /* FIXME: This is recording everything as a low-high
7954          segment of consecutive addresses.  We should have a
7955          data structure for discontiguous block ranges
7956          instead.  */
7957       if (! low_set)
7958         {
7959           low = range_beginning;
7960           high = range_end;
7961           low_set = 1;
7962         }
7963       else
7964         {
7965           if (range_beginning < low)
7966             low = range_beginning;
7967           if (range_end > high)
7968             high = range_end;
7969         }
7970     }
7971
7972   if (! low_set)
7973     /* If the first entry is an end-of-list marker, the range
7974        describes an empty scope, i.e. no instructions.  */
7975     return 0;
7976
7977   if (low_return)
7978     *low_return = low;
7979   if (high_return)
7980     *high_return = high;
7981   return 1;
7982 }
7983
7984 /* Get low and high pc attributes from a die.  Return 1 if the attributes
7985    are present and valid, otherwise, return 0.  Return -1 if the range is
7986    discontinuous, i.e. derived from DW_AT_ranges information.  */
7987
7988 static int
7989 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
7990                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
7991                       struct partial_symtab *pst)
7992 {
7993   struct attribute *attr;
7994   struct attribute *attr_high;
7995   CORE_ADDR low = 0;
7996   CORE_ADDR high = 0;
7997   int ret = 0;
7998
7999   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
8000   if (attr_high)
8001     {
8002       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
8003       if (attr)
8004         {
8005           low = DW_ADDR (attr);
8006           if (attr_high->form == DW_FORM_addr
8007               || attr_high->form == DW_FORM_GNU_addr_index)
8008             high = DW_ADDR (attr_high);
8009           else
8010             high = low + DW_UNSND (attr_high);
8011         }
8012       else
8013         /* Found high w/o low attribute.  */
8014         return 0;
8015
8016       /* Found consecutive range of addresses.  */
8017       ret = 1;
8018     }
8019   else
8020     {
8021       attr = dwarf2_attr (die, DW_AT_ranges, cu);
8022       if (attr != NULL)
8023         {
8024           /* Value of the DW_AT_ranges attribute is the offset in the
8025              .debug_ranges section.  */
8026           if (!dwarf2_ranges_read (DW_UNSND (attr), &low, &high, cu, pst))
8027             return 0;
8028           /* Found discontinuous range of addresses.  */
8029           ret = -1;
8030         }
8031     }
8032
8033   /* read_partial_die has also the strict LOW < HIGH requirement.  */
8034   if (high <= low)
8035     return 0;
8036
8037   /* When using the GNU linker, .gnu.linkonce. sections are used to
8038      eliminate duplicate copies of functions and vtables and such.
8039      The linker will arbitrarily choose one and discard the others.
8040      The AT_*_pc values for such functions refer to local labels in
8041      these sections.  If the section from that file was discarded, the
8042      labels are not in the output, so the relocs get a value of 0.
8043      If this is a discarded function, mark the pc bounds as invalid,
8044      so that GDB will ignore it.  */
8045   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
8046     return 0;
8047
8048   *lowpc = low;
8049   if (highpc)
8050     *highpc = high;
8051   return ret;
8052 }
8053
8054 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
8055    its low and high PC addresses.  Do nothing if these addresses could not
8056    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
8057    and HIGHPC to the high address if greater than HIGHPC.  */
8058
8059 static void
8060 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
8061                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
8062                                  struct dwarf2_cu *cu)
8063 {
8064   CORE_ADDR low, high;
8065   struct die_info *child = die->child;
8066
8067   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
8068     {
8069       *lowpc = min (*lowpc, low);
8070       *highpc = max (*highpc, high);
8071     }
8072
8073   /* If the language does not allow nested subprograms (either inside
8074      subprograms or lexical blocks), we're done.  */
8075   if (cu->language != language_ada)
8076     return;
8077
8078   /* Check all the children of the given DIE.  If it contains nested
8079      subprograms, then check their pc bounds.  Likewise, we need to
8080      check lexical blocks as well, as they may also contain subprogram
8081      definitions.  */
8082   while (child && child->tag)
8083     {
8084       if (child->tag == DW_TAG_subprogram
8085           || child->tag == DW_TAG_lexical_block)
8086         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
8087       child = sibling_die (child);
8088     }
8089 }
8090
8091 /* Get the low and high pc's represented by the scope DIE, and store
8092    them in *LOWPC and *HIGHPC.  If the correct values can't be
8093    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
8094
8095 static void
8096 get_scope_pc_bounds (struct die_info *die,
8097                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
8098                      struct dwarf2_cu *cu)
8099 {
8100   CORE_ADDR best_low = (CORE_ADDR) -1;
8101   CORE_ADDR best_high = (CORE_ADDR) 0;
8102   CORE_ADDR current_low, current_high;
8103
8104   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
8105     {
8106       best_low = current_low;
8107       best_high = current_high;
8108     }
8109   else
8110     {
8111       struct die_info *child = die->child;
8112
8113       while (child && child->tag)
8114         {
8115           switch (child->tag) {
8116           case DW_TAG_subprogram:
8117             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
8118             break;
8119           case DW_TAG_namespace:
8120           case DW_TAG_module:
8121             /* FIXME: carlton/2004-01-16: Should we do this for
8122                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
8123                that current GCC's always emit the DIEs corresponding
8124                to definitions of methods of classes as children of a
8125                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
8126                the DIEs giving the declarations, which could be
8127                anywhere).  But I don't see any reason why the
8128                standards says that they have to be there.  */
8129             get_scope_pc_bounds (child, &current_low, &current_high, cu);
8130
8131             if (current_low != ((CORE_ADDR) -1))
8132               {
8133                 best_low = min (best_low, current_low);
8134                 best_high = max (best_high, current_high);
8135               }
8136             break;
8137           default:
8138             /* Ignore.  */
8139             break;
8140           }
8141
8142           child = sibling_die (child);
8143         }
8144     }
8145
8146   *lowpc = best_low;
8147   *highpc = best_high;
8148 }
8149
8150 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
8151    in DIE.  */
8152
8153 static void
8154 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
8155                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
8156 {
8157   struct objfile *objfile = cu->objfile;
8158   struct attribute *attr;
8159   struct attribute *attr_high;
8160
8161   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
8162   if (attr_high)
8163     {
8164       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
8165       if (attr)
8166         {
8167           CORE_ADDR low = DW_ADDR (attr);
8168           CORE_ADDR high;
8169           if (attr_high->form == DW_FORM_addr
8170               || attr_high->form == DW_FORM_GNU_addr_index)
8171             high = DW_ADDR (attr_high);
8172           else
8173             high = low + DW_UNSND (attr_high);
8174
8175           record_block_range (block, baseaddr + low, baseaddr + high - 1);
8176         }
8177     }
8178
8179   attr = dwarf2_attr (die, DW_AT_ranges, cu);
8180   if (attr)
8181     {
8182       bfd *obfd = objfile->obfd;
8183
8184       /* The value of the DW_AT_ranges attribute is the offset of the
8185          address range list in the .debug_ranges section.  */
8186       unsigned long offset = DW_UNSND (attr);
8187       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
8188
8189       /* For some target architectures, but not others, the
8190          read_address function sign-extends the addresses it returns.
8191          To recognize base address selection entries, we need a
8192          mask.  */
8193       unsigned int addr_size = cu->header.addr_size;
8194       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
8195
8196       /* The base address, to which the next pair is relative.  Note
8197          that this 'base' is a DWARF concept: most entries in a range
8198          list are relative, to reduce the number of relocs against the
8199          debugging information.  This is separate from this function's
8200          'baseaddr' argument, which GDB uses to relocate debugging
8201          information from a shared library based on the address at
8202          which the library was loaded.  */
8203       CORE_ADDR base = cu->base_address;
8204       int base_known = cu->base_known;
8205
8206       gdb_assert (dwarf2_per_objfile->ranges.readin);
8207       if (offset >= dwarf2_per_objfile->ranges.size)
8208         {
8209           complaint (&symfile_complaints,
8210                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
8211                      offset);
8212           return;
8213         }
8214
8215       for (;;)
8216         {
8217           unsigned int bytes_read;
8218           CORE_ADDR start, end;
8219
8220           start = read_address (obfd, buffer, cu, &bytes_read);
8221           buffer += bytes_read;
8222           end = read_address (obfd, buffer, cu, &bytes_read);
8223           buffer += bytes_read;
8224
8225           /* Did we find the end of the range list?  */
8226           if (start == 0 && end == 0)
8227             break;
8228
8229           /* Did we find a base address selection entry?  */
8230           else if ((start & base_select_mask) == base_select_mask)
8231             {
8232               base = end;
8233               base_known = 1;
8234             }
8235
8236           /* We found an ordinary address range.  */
8237           else
8238             {
8239               if (!base_known)
8240                 {
8241                   complaint (&symfile_complaints,
8242                              _("Invalid .debug_ranges data "
8243                                "(no base address)"));
8244                   return;
8245                 }
8246
8247               if (start > end)
8248                 {
8249                   /* Inverted range entries are invalid.  */
8250                   complaint (&symfile_complaints,
8251                              _("Invalid .debug_ranges data "
8252                                "(inverted range)"));
8253                   return;
8254                 }
8255
8256               /* Empty range entries have no effect.  */
8257               if (start == end)
8258                 continue;
8259
8260               record_block_range (block,
8261                                   baseaddr + base + start,
8262                                   baseaddr + base + end - 1);
8263             }
8264         }
8265     }
8266 }
8267
8268 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
8269    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
8270    during 4.6.0 experimental.  */
8271
8272 static int
8273 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
8274 {
8275   const char *cs;
8276   int major, minor, release;
8277   int result = 0;
8278
8279   if (cu->producer == NULL)
8280     {
8281       /* For unknown compilers expect their behavior is DWARF version
8282          compliant.
8283
8284          GCC started to support .debug_types sections by -gdwarf-4 since
8285          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
8286          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
8287          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
8288          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
8289
8290       return 0;
8291     }
8292
8293   if (cu->checked_producer)
8294     return cu->producer_is_gxx_lt_4_6;
8295
8296   /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
8297
8298   if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) != 0)
8299     {
8300       /* For non-GCC compilers expect their behavior is DWARF version
8301          compliant.  */
8302     }
8303   else
8304     {
8305       cs = &cu->producer[strlen ("GNU ")];
8306       while (*cs && !isdigit (*cs))
8307         cs++;
8308       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
8309         {
8310           /* Not recognized as GCC.  */
8311         }
8312       else
8313         result = major < 4 || (major == 4 && minor < 6);
8314     }
8315
8316   cu->checked_producer = 1;
8317   cu->producer_is_gxx_lt_4_6 = result;
8318
8319   return result;
8320 }
8321
8322 /* Return the default accessibility type if it is not overriden by
8323    DW_AT_accessibility.  */
8324
8325 static enum dwarf_access_attribute
8326 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
8327 {
8328   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
8329     {
8330       /* The default DWARF 2 accessibility for members is public, the default
8331          accessibility for inheritance is private.  */
8332
8333       if (die->tag != DW_TAG_inheritance)
8334         return DW_ACCESS_public;
8335       else
8336         return DW_ACCESS_private;
8337     }
8338   else
8339     {
8340       /* DWARF 3+ defines the default accessibility a different way.  The same
8341          rules apply now for DW_TAG_inheritance as for the members and it only
8342          depends on the container kind.  */
8343
8344       if (die->parent->tag == DW_TAG_class_type)
8345         return DW_ACCESS_private;
8346       else
8347         return DW_ACCESS_public;
8348     }
8349 }
8350
8351 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
8352    offset.  If the attribute was not found return 0, otherwise return
8353    1.  If it was found but could not properly be handled, set *OFFSET
8354    to 0.  */
8355
8356 static int
8357 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
8358                              LONGEST *offset)
8359 {
8360   struct attribute *attr;
8361
8362   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
8363   if (attr != NULL)
8364     {
8365       *offset = 0;
8366
8367       /* Note that we do not check for a section offset first here.
8368          This is because DW_AT_data_member_location is new in DWARF 4,
8369          so if we see it, we can assume that a constant form is really
8370          a constant and not a section offset.  */
8371       if (attr_form_is_constant (attr))
8372         *offset = dwarf2_get_attr_constant_value (attr, 0);
8373       else if (attr_form_is_section_offset (attr))
8374         dwarf2_complex_location_expr_complaint ();
8375       else if (attr_form_is_block (attr))
8376         *offset = decode_locdesc (DW_BLOCK (attr), cu);
8377       else
8378         dwarf2_complex_location_expr_complaint ();
8379
8380       return 1;
8381     }
8382
8383   return 0;
8384 }
8385
8386 /* Add an aggregate field to the field list.  */
8387
8388 static void
8389 dwarf2_add_field (struct field_info *fip, struct die_info *die,
8390                   struct dwarf2_cu *cu)
8391 {
8392   struct objfile *objfile = cu->objfile;
8393   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8394   struct nextfield *new_field;
8395   struct attribute *attr;
8396   struct field *fp;
8397   char *fieldname = "";
8398
8399   /* Allocate a new field list entry and link it in.  */
8400   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
8401   make_cleanup (xfree, new_field);
8402   memset (new_field, 0, sizeof (struct nextfield));
8403
8404   if (die->tag == DW_TAG_inheritance)
8405     {
8406       new_field->next = fip->baseclasses;
8407       fip->baseclasses = new_field;
8408     }
8409   else
8410     {
8411       new_field->next = fip->fields;
8412       fip->fields = new_field;
8413     }
8414   fip->nfields++;
8415
8416   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
8417   if (attr)
8418     new_field->accessibility = DW_UNSND (attr);
8419   else
8420     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
8421   if (new_field->accessibility != DW_ACCESS_public)
8422     fip->non_public_fields = 1;
8423
8424   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
8425   if (attr)
8426     new_field->virtuality = DW_UNSND (attr);
8427   else
8428     new_field->virtuality = DW_VIRTUALITY_none;
8429
8430   fp = &new_field->field;
8431
8432   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
8433     {
8434       LONGEST offset;
8435
8436       /* Data member other than a C++ static data member.  */
8437
8438       /* Get type of field.  */
8439       fp->type = die_type (die, cu);
8440
8441       SET_FIELD_BITPOS (*fp, 0);
8442
8443       /* Get bit size of field (zero if none).  */
8444       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
8445       if (attr)
8446         {
8447           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
8448         }
8449       else
8450         {
8451           FIELD_BITSIZE (*fp) = 0;
8452         }
8453
8454       /* Get bit offset of field.  */
8455       if (handle_data_member_location (die, cu, &offset))
8456         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
8457       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
8458       if (attr)
8459         {
8460           if (gdbarch_bits_big_endian (gdbarch))
8461             {
8462               /* For big endian bits, the DW_AT_bit_offset gives the
8463                  additional bit offset from the MSB of the containing
8464                  anonymous object to the MSB of the field.  We don't
8465                  have to do anything special since we don't need to
8466                  know the size of the anonymous object.  */
8467               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
8468             }
8469           else
8470             {
8471               /* For little endian bits, compute the bit offset to the
8472                  MSB of the anonymous object, subtract off the number of
8473                  bits from the MSB of the field to the MSB of the
8474                  object, and then subtract off the number of bits of
8475                  the field itself.  The result is the bit offset of
8476                  the LSB of the field.  */
8477               int anonymous_size;
8478               int bit_offset = DW_UNSND (attr);
8479
8480               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
8481               if (attr)
8482                 {
8483                   /* The size of the anonymous object containing
8484                      the bit field is explicit, so use the
8485                      indicated size (in bytes).  */
8486                   anonymous_size = DW_UNSND (attr);
8487                 }
8488               else
8489                 {
8490                   /* The size of the anonymous object containing
8491                      the bit field must be inferred from the type
8492                      attribute of the data member containing the
8493                      bit field.  */
8494                   anonymous_size = TYPE_LENGTH (fp->type);
8495                 }
8496               SET_FIELD_BITPOS (*fp,
8497                                 (FIELD_BITPOS (*fp)
8498                                  + anonymous_size * bits_per_byte
8499                                  - bit_offset - FIELD_BITSIZE (*fp)));
8500             }
8501         }
8502
8503       /* Get name of field.  */
8504       fieldname = dwarf2_name (die, cu);
8505       if (fieldname == NULL)
8506         fieldname = "";
8507
8508       /* The name is already allocated along with this objfile, so we don't
8509          need to duplicate it for the type.  */
8510       fp->name = fieldname;
8511
8512       /* Change accessibility for artificial fields (e.g. virtual table
8513          pointer or virtual base class pointer) to private.  */
8514       if (dwarf2_attr (die, DW_AT_artificial, cu))
8515         {
8516           FIELD_ARTIFICIAL (*fp) = 1;
8517           new_field->accessibility = DW_ACCESS_private;
8518           fip->non_public_fields = 1;
8519         }
8520     }
8521   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
8522     {
8523       /* C++ static member.  */
8524
8525       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
8526          is a declaration, but all versions of G++ as of this writing
8527          (so through at least 3.2.1) incorrectly generate
8528          DW_TAG_variable tags.  */
8529
8530       const char *physname;
8531
8532       /* Get name of field.  */
8533       fieldname = dwarf2_name (die, cu);
8534       if (fieldname == NULL)
8535         return;
8536
8537       attr = dwarf2_attr (die, DW_AT_const_value, cu);
8538       if (attr
8539           /* Only create a symbol if this is an external value.
8540              new_symbol checks this and puts the value in the global symbol
8541              table, which we want.  If it is not external, new_symbol
8542              will try to put the value in cu->list_in_scope which is wrong.  */
8543           && dwarf2_flag_true_p (die, DW_AT_external, cu))
8544         {
8545           /* A static const member, not much different than an enum as far as
8546              we're concerned, except that we can support more types.  */
8547           new_symbol (die, NULL, cu);
8548         }
8549
8550       /* Get physical name.  */
8551       physname = dwarf2_physname (fieldname, die, cu);
8552
8553       /* The name is already allocated along with this objfile, so we don't
8554          need to duplicate it for the type.  */
8555       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
8556       FIELD_TYPE (*fp) = die_type (die, cu);
8557       FIELD_NAME (*fp) = fieldname;
8558     }
8559   else if (die->tag == DW_TAG_inheritance)
8560     {
8561       LONGEST offset;
8562
8563       /* C++ base class field.  */
8564       if (handle_data_member_location (die, cu, &offset))
8565         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
8566       FIELD_BITSIZE (*fp) = 0;
8567       FIELD_TYPE (*fp) = die_type (die, cu);
8568       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
8569       fip->nbaseclasses++;
8570     }
8571 }
8572
8573 /* Add a typedef defined in the scope of the FIP's class.  */
8574
8575 static void
8576 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
8577                     struct dwarf2_cu *cu)
8578 {
8579   struct objfile *objfile = cu->objfile;
8580   struct typedef_field_list *new_field;
8581   struct attribute *attr;
8582   struct typedef_field *fp;
8583   char *fieldname = "";
8584
8585   /* Allocate a new field list entry and link it in.  */
8586   new_field = xzalloc (sizeof (*new_field));
8587   make_cleanup (xfree, new_field);
8588
8589   gdb_assert (die->tag == DW_TAG_typedef);
8590
8591   fp = &new_field->field;
8592
8593   /* Get name of field.  */
8594   fp->name = dwarf2_name (die, cu);
8595   if (fp->name == NULL)
8596     return;
8597
8598   fp->type = read_type_die (die, cu);
8599
8600   new_field->next = fip->typedef_field_list;
8601   fip->typedef_field_list = new_field;
8602   fip->typedef_field_list_count++;
8603 }
8604
8605 /* Create the vector of fields, and attach it to the type.  */
8606
8607 static void
8608 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
8609                               struct dwarf2_cu *cu)
8610 {
8611   int nfields = fip->nfields;
8612
8613   /* Record the field count, allocate space for the array of fields,
8614      and create blank accessibility bitfields if necessary.  */
8615   TYPE_NFIELDS (type) = nfields;
8616   TYPE_FIELDS (type) = (struct field *)
8617     TYPE_ALLOC (type, sizeof (struct field) * nfields);
8618   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
8619
8620   if (fip->non_public_fields && cu->language != language_ada)
8621     {
8622       ALLOCATE_CPLUS_STRUCT_TYPE (type);
8623
8624       TYPE_FIELD_PRIVATE_BITS (type) =
8625         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
8626       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
8627
8628       TYPE_FIELD_PROTECTED_BITS (type) =
8629         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
8630       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
8631
8632       TYPE_FIELD_IGNORE_BITS (type) =
8633         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
8634       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
8635     }
8636
8637   /* If the type has baseclasses, allocate and clear a bit vector for
8638      TYPE_FIELD_VIRTUAL_BITS.  */
8639   if (fip->nbaseclasses && cu->language != language_ada)
8640     {
8641       int num_bytes = B_BYTES (fip->nbaseclasses);
8642       unsigned char *pointer;
8643
8644       ALLOCATE_CPLUS_STRUCT_TYPE (type);
8645       pointer = TYPE_ALLOC (type, num_bytes);
8646       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
8647       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
8648       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
8649     }
8650
8651   /* Copy the saved-up fields into the field vector.  Start from the head of
8652      the list, adding to the tail of the field array, so that they end up in
8653      the same order in the array in which they were added to the list.  */
8654   while (nfields-- > 0)
8655     {
8656       struct nextfield *fieldp;
8657
8658       if (fip->fields)
8659         {
8660           fieldp = fip->fields;
8661           fip->fields = fieldp->next;
8662         }
8663       else
8664         {
8665           fieldp = fip->baseclasses;
8666           fip->baseclasses = fieldp->next;
8667         }
8668
8669       TYPE_FIELD (type, nfields) = fieldp->field;
8670       switch (fieldp->accessibility)
8671         {
8672         case DW_ACCESS_private:
8673           if (cu->language != language_ada)
8674             SET_TYPE_FIELD_PRIVATE (type, nfields);
8675           break;
8676
8677         case DW_ACCESS_protected:
8678           if (cu->language != language_ada)
8679             SET_TYPE_FIELD_PROTECTED (type, nfields);
8680           break;
8681
8682         case DW_ACCESS_public:
8683           break;
8684
8685         default:
8686           /* Unknown accessibility.  Complain and treat it as public.  */
8687           {
8688             complaint (&symfile_complaints, _("unsupported accessibility %d"),
8689                        fieldp->accessibility);
8690           }
8691           break;
8692         }
8693       if (nfields < fip->nbaseclasses)
8694         {
8695           switch (fieldp->virtuality)
8696             {
8697             case DW_VIRTUALITY_virtual:
8698             case DW_VIRTUALITY_pure_virtual:
8699               if (cu->language == language_ada)
8700                 error (_("unexpected virtuality in component of Ada type"));
8701               SET_TYPE_FIELD_VIRTUAL (type, nfields);
8702               break;
8703             }
8704         }
8705     }
8706 }
8707
8708 /* Add a member function to the proper fieldlist.  */
8709
8710 static void
8711 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
8712                       struct type *type, struct dwarf2_cu *cu)
8713 {
8714   struct objfile *objfile = cu->objfile;
8715   struct attribute *attr;
8716   struct fnfieldlist *flp;
8717   int i;
8718   struct fn_field *fnp;
8719   char *fieldname;
8720   struct nextfnfield *new_fnfield;
8721   struct type *this_type;
8722   enum dwarf_access_attribute accessibility;
8723
8724   if (cu->language == language_ada)
8725     error (_("unexpected member function in Ada type"));
8726
8727   /* Get name of member function.  */
8728   fieldname = dwarf2_name (die, cu);
8729   if (fieldname == NULL)
8730     return;
8731
8732   /* Look up member function name in fieldlist.  */
8733   for (i = 0; i < fip->nfnfields; i++)
8734     {
8735       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
8736         break;
8737     }
8738
8739   /* Create new list element if necessary.  */
8740   if (i < fip->nfnfields)
8741     flp = &fip->fnfieldlists[i];
8742   else
8743     {
8744       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
8745         {
8746           fip->fnfieldlists = (struct fnfieldlist *)
8747             xrealloc (fip->fnfieldlists,
8748                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
8749                       * sizeof (struct fnfieldlist));
8750           if (fip->nfnfields == 0)
8751             make_cleanup (free_current_contents, &fip->fnfieldlists);
8752         }
8753       flp = &fip->fnfieldlists[fip->nfnfields];
8754       flp->name = fieldname;
8755       flp->length = 0;
8756       flp->head = NULL;
8757       i = fip->nfnfields++;
8758     }
8759
8760   /* Create a new member function field and chain it to the field list
8761      entry.  */
8762   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
8763   make_cleanup (xfree, new_fnfield);
8764   memset (new_fnfield, 0, sizeof (struct nextfnfield));
8765   new_fnfield->next = flp->head;
8766   flp->head = new_fnfield;
8767   flp->length++;
8768
8769   /* Fill in the member function field info.  */
8770   fnp = &new_fnfield->fnfield;
8771
8772   /* Delay processing of the physname until later.  */
8773   if (cu->language == language_cplus || cu->language == language_java)
8774     {
8775       add_to_method_list (type, i, flp->length - 1, fieldname,
8776                           die, cu);
8777     }
8778   else
8779     {
8780       const char *physname = dwarf2_physname (fieldname, die, cu);
8781       fnp->physname = physname ? physname : "";
8782     }
8783
8784   fnp->type = alloc_type (objfile);
8785   this_type = read_type_die (die, cu);
8786   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
8787     {
8788       int nparams = TYPE_NFIELDS (this_type);
8789
8790       /* TYPE is the domain of this method, and THIS_TYPE is the type
8791            of the method itself (TYPE_CODE_METHOD).  */
8792       smash_to_method_type (fnp->type, type,
8793                             TYPE_TARGET_TYPE (this_type),
8794                             TYPE_FIELDS (this_type),
8795                             TYPE_NFIELDS (this_type),
8796                             TYPE_VARARGS (this_type));
8797
8798       /* Handle static member functions.
8799          Dwarf2 has no clean way to discern C++ static and non-static
8800          member functions.  G++ helps GDB by marking the first
8801          parameter for non-static member functions (which is the this
8802          pointer) as artificial.  We obtain this information from
8803          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
8804       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
8805         fnp->voffset = VOFFSET_STATIC;
8806     }
8807   else
8808     complaint (&symfile_complaints, _("member function type missing for '%s'"),
8809                dwarf2_full_name (fieldname, die, cu));
8810
8811   /* Get fcontext from DW_AT_containing_type if present.  */
8812   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
8813     fnp->fcontext = die_containing_type (die, cu);
8814
8815   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
8816      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
8817
8818   /* Get accessibility.  */
8819   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
8820   if (attr)
8821     accessibility = DW_UNSND (attr);
8822   else
8823     accessibility = dwarf2_default_access_attribute (die, cu);
8824   switch (accessibility)
8825     {
8826     case DW_ACCESS_private:
8827       fnp->is_private = 1;
8828       break;
8829     case DW_ACCESS_protected:
8830       fnp->is_protected = 1;
8831       break;
8832     }
8833
8834   /* Check for artificial methods.  */
8835   attr = dwarf2_attr (die, DW_AT_artificial, cu);
8836   if (attr && DW_UNSND (attr) != 0)
8837     fnp->is_artificial = 1;
8838
8839   /* Get index in virtual function table if it is a virtual member
8840      function.  For older versions of GCC, this is an offset in the
8841      appropriate virtual table, as specified by DW_AT_containing_type.
8842      For everyone else, it is an expression to be evaluated relative
8843      to the object address.  */
8844
8845   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
8846   if (attr)
8847     {
8848       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
8849         {
8850           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
8851             {
8852               /* Old-style GCC.  */
8853               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
8854             }
8855           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
8856                    || (DW_BLOCK (attr)->size > 1
8857                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
8858                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
8859             {
8860               struct dwarf_block blk;
8861               int offset;
8862
8863               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
8864                         ? 1 : 2);
8865               blk.size = DW_BLOCK (attr)->size - offset;
8866               blk.data = DW_BLOCK (attr)->data + offset;
8867               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
8868               if ((fnp->voffset % cu->header.addr_size) != 0)
8869                 dwarf2_complex_location_expr_complaint ();
8870               else
8871                 fnp->voffset /= cu->header.addr_size;
8872               fnp->voffset += 2;
8873             }
8874           else
8875             dwarf2_complex_location_expr_complaint ();
8876
8877           if (!fnp->fcontext)
8878             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
8879         }
8880       else if (attr_form_is_section_offset (attr))
8881         {
8882           dwarf2_complex_location_expr_complaint ();
8883         }
8884       else
8885         {
8886           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
8887                                                  fieldname);
8888         }
8889     }
8890   else
8891     {
8892       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
8893       if (attr && DW_UNSND (attr))
8894         {
8895           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
8896           complaint (&symfile_complaints,
8897                      _("Member function \"%s\" (offset %d) is virtual "
8898                        "but the vtable offset is not specified"),
8899                      fieldname, die->offset.sect_off);
8900           ALLOCATE_CPLUS_STRUCT_TYPE (type);
8901           TYPE_CPLUS_DYNAMIC (type) = 1;
8902         }
8903     }
8904 }
8905
8906 /* Create the vector of member function fields, and attach it to the type.  */
8907
8908 static void
8909 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
8910                                  struct dwarf2_cu *cu)
8911 {
8912   struct fnfieldlist *flp;
8913   int i;
8914
8915   if (cu->language == language_ada)
8916     error (_("unexpected member functions in Ada type"));
8917
8918   ALLOCATE_CPLUS_STRUCT_TYPE (type);
8919   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
8920     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
8921
8922   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
8923     {
8924       struct nextfnfield *nfp = flp->head;
8925       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
8926       int k;
8927
8928       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
8929       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
8930       fn_flp->fn_fields = (struct fn_field *)
8931         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
8932       for (k = flp->length; (k--, nfp); nfp = nfp->next)
8933         fn_flp->fn_fields[k] = nfp->fnfield;
8934     }
8935
8936   TYPE_NFN_FIELDS (type) = fip->nfnfields;
8937 }
8938
8939 /* Returns non-zero if NAME is the name of a vtable member in CU's
8940    language, zero otherwise.  */
8941 static int
8942 is_vtable_name (const char *name, struct dwarf2_cu *cu)
8943 {
8944   static const char vptr[] = "_vptr";
8945   static const char vtable[] = "vtable";
8946
8947   /* Look for the C++ and Java forms of the vtable.  */
8948   if ((cu->language == language_java
8949        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
8950        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
8951        && is_cplus_marker (name[sizeof (vptr) - 1])))
8952     return 1;
8953
8954   return 0;
8955 }
8956
8957 /* GCC outputs unnamed structures that are really pointers to member
8958    functions, with the ABI-specified layout.  If TYPE describes
8959    such a structure, smash it into a member function type.
8960
8961    GCC shouldn't do this; it should just output pointer to member DIEs.
8962    This is GCC PR debug/28767.  */
8963
8964 static void
8965 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
8966 {
8967   struct type *pfn_type, *domain_type, *new_type;
8968
8969   /* Check for a structure with no name and two children.  */
8970   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
8971     return;
8972
8973   /* Check for __pfn and __delta members.  */
8974   if (TYPE_FIELD_NAME (type, 0) == NULL
8975       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
8976       || TYPE_FIELD_NAME (type, 1) == NULL
8977       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
8978     return;
8979
8980   /* Find the type of the method.  */
8981   pfn_type = TYPE_FIELD_TYPE (type, 0);
8982   if (pfn_type == NULL
8983       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
8984       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
8985     return;
8986
8987   /* Look for the "this" argument.  */
8988   pfn_type = TYPE_TARGET_TYPE (pfn_type);
8989   if (TYPE_NFIELDS (pfn_type) == 0
8990       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
8991       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
8992     return;
8993
8994   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
8995   new_type = alloc_type (objfile);
8996   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
8997                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
8998                         TYPE_VARARGS (pfn_type));
8999   smash_to_methodptr_type (type, new_type);
9000 }
9001
9002 /* Called when we find the DIE that starts a structure or union scope
9003    (definition) to create a type for the structure or union.  Fill in
9004    the type's name and general properties; the members will not be
9005    processed until process_structure_type.
9006
9007    NOTE: we need to call these functions regardless of whether or not the
9008    DIE has a DW_AT_name attribute, since it might be an anonymous
9009    structure or union.  This gets the type entered into our set of
9010    user defined types.
9011
9012    However, if the structure is incomplete (an opaque struct/union)
9013    then suppress creating a symbol table entry for it since gdb only
9014    wants to find the one with the complete definition.  Note that if
9015    it is complete, we just call new_symbol, which does it's own
9016    checking about whether the struct/union is anonymous or not (and
9017    suppresses creating a symbol table entry itself).  */
9018
9019 static struct type *
9020 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
9021 {
9022   struct objfile *objfile = cu->objfile;
9023   struct type *type;
9024   struct attribute *attr;
9025   char *name;
9026
9027   /* If the definition of this type lives in .debug_types, read that type.
9028      Don't follow DW_AT_specification though, that will take us back up
9029      the chain and we want to go down.  */
9030   attr = dwarf2_attr_no_follow (die, DW_AT_signature, cu);
9031   if (attr)
9032     {
9033       struct dwarf2_cu *type_cu = cu;
9034       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
9035
9036       /* We could just recurse on read_structure_type, but we need to call
9037          get_die_type to ensure only one type for this DIE is created.
9038          This is important, for example, because for c++ classes we need
9039          TYPE_NAME set which is only done by new_symbol.  Blech.  */
9040       type = read_type_die (type_die, type_cu);
9041
9042       /* TYPE_CU may not be the same as CU.
9043          Ensure TYPE is recorded in CU's type_hash table.  */
9044       return set_die_type (die, type, cu);
9045     }
9046
9047   type = alloc_type (objfile);
9048   INIT_CPLUS_SPECIFIC (type);
9049
9050   name = dwarf2_name (die, cu);
9051   if (name != NULL)
9052     {
9053       if (cu->language == language_cplus
9054           || cu->language == language_java)
9055         {
9056           char *full_name = (char *) dwarf2_full_name (name, die, cu);
9057
9058           /* dwarf2_full_name might have already finished building the DIE's
9059              type.  If so, there is no need to continue.  */
9060           if (get_die_type (die, cu) != NULL)
9061             return get_die_type (die, cu);
9062
9063           TYPE_TAG_NAME (type) = full_name;
9064           if (die->tag == DW_TAG_structure_type
9065               || die->tag == DW_TAG_class_type)
9066             TYPE_NAME (type) = TYPE_TAG_NAME (type);
9067         }
9068       else
9069         {
9070           /* The name is already allocated along with this objfile, so
9071              we don't need to duplicate it for the type.  */
9072           TYPE_TAG_NAME (type) = (char *) name;
9073           if (die->tag == DW_TAG_class_type)
9074             TYPE_NAME (type) = TYPE_TAG_NAME (type);
9075         }
9076     }
9077
9078   if (die->tag == DW_TAG_structure_type)
9079     {
9080       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9081     }
9082   else if (die->tag == DW_TAG_union_type)
9083     {
9084       TYPE_CODE (type) = TYPE_CODE_UNION;
9085     }
9086   else
9087     {
9088       TYPE_CODE (type) = TYPE_CODE_CLASS;
9089     }
9090
9091   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
9092     TYPE_DECLARED_CLASS (type) = 1;
9093
9094   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9095   if (attr)
9096     {
9097       TYPE_LENGTH (type) = DW_UNSND (attr);
9098     }
9099   else
9100     {
9101       TYPE_LENGTH (type) = 0;
9102     }
9103
9104   TYPE_STUB_SUPPORTED (type) = 1;
9105   if (die_is_declaration (die, cu))
9106     TYPE_STUB (type) = 1;
9107   else if (attr == NULL && die->child == NULL
9108            && producer_is_realview (cu->producer))
9109     /* RealView does not output the required DW_AT_declaration
9110        on incomplete types.  */
9111     TYPE_STUB (type) = 1;
9112
9113   /* We need to add the type field to the die immediately so we don't
9114      infinitely recurse when dealing with pointers to the structure
9115      type within the structure itself.  */
9116   set_die_type (die, type, cu);
9117
9118   /* set_die_type should be already done.  */
9119   set_descriptive_type (type, die, cu);
9120
9121   return type;
9122 }
9123
9124 /* Finish creating a structure or union type, including filling in
9125    its members and creating a symbol for it.  */
9126
9127 static void
9128 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
9129 {
9130   struct objfile *objfile = cu->objfile;
9131   struct die_info *child_die = die->child;
9132   struct type *type;
9133
9134   type = get_die_type (die, cu);
9135   if (type == NULL)
9136     type = read_structure_type (die, cu);
9137
9138   if (die->child != NULL && ! die_is_declaration (die, cu))
9139     {
9140       struct field_info fi;
9141       struct die_info *child_die;
9142       VEC (symbolp) *template_args = NULL;
9143       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
9144
9145       memset (&fi, 0, sizeof (struct field_info));
9146
9147       child_die = die->child;
9148
9149       while (child_die && child_die->tag)
9150         {
9151           if (child_die->tag == DW_TAG_member
9152               || child_die->tag == DW_TAG_variable)
9153             {
9154               /* NOTE: carlton/2002-11-05: A C++ static data member
9155                  should be a DW_TAG_member that is a declaration, but
9156                  all versions of G++ as of this writing (so through at
9157                  least 3.2.1) incorrectly generate DW_TAG_variable
9158                  tags for them instead.  */
9159               dwarf2_add_field (&fi, child_die, cu);
9160             }
9161           else if (child_die->tag == DW_TAG_subprogram)
9162             {
9163               /* C++ member function.  */
9164               dwarf2_add_member_fn (&fi, child_die, type, cu);
9165             }
9166           else if (child_die->tag == DW_TAG_inheritance)
9167             {
9168               /* C++ base class field.  */
9169               dwarf2_add_field (&fi, child_die, cu);
9170             }
9171           else if (child_die->tag == DW_TAG_typedef)
9172             dwarf2_add_typedef (&fi, child_die, cu);
9173           else if (child_die->tag == DW_TAG_template_type_param
9174                    || child_die->tag == DW_TAG_template_value_param)
9175             {
9176               struct symbol *arg = new_symbol (child_die, NULL, cu);
9177
9178               if (arg != NULL)
9179                 VEC_safe_push (symbolp, template_args, arg);
9180             }
9181
9182           child_die = sibling_die (child_die);
9183         }
9184
9185       /* Attach template arguments to type.  */
9186       if (! VEC_empty (symbolp, template_args))
9187         {
9188           ALLOCATE_CPLUS_STRUCT_TYPE (type);
9189           TYPE_N_TEMPLATE_ARGUMENTS (type)
9190             = VEC_length (symbolp, template_args);
9191           TYPE_TEMPLATE_ARGUMENTS (type)
9192             = obstack_alloc (&objfile->objfile_obstack,
9193                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
9194                               * sizeof (struct symbol *)));
9195           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
9196                   VEC_address (symbolp, template_args),
9197                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
9198                    * sizeof (struct symbol *)));
9199           VEC_free (symbolp, template_args);
9200         }
9201
9202       /* Attach fields and member functions to the type.  */
9203       if (fi.nfields)
9204         dwarf2_attach_fields_to_type (&fi, type, cu);
9205       if (fi.nfnfields)
9206         {
9207           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
9208
9209           /* Get the type which refers to the base class (possibly this
9210              class itself) which contains the vtable pointer for the current
9211              class from the DW_AT_containing_type attribute.  This use of
9212              DW_AT_containing_type is a GNU extension.  */
9213
9214           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
9215             {
9216               struct type *t = die_containing_type (die, cu);
9217
9218               TYPE_VPTR_BASETYPE (type) = t;
9219               if (type == t)
9220                 {
9221                   int i;
9222
9223                   /* Our own class provides vtbl ptr.  */
9224                   for (i = TYPE_NFIELDS (t) - 1;
9225                        i >= TYPE_N_BASECLASSES (t);
9226                        --i)
9227                     {
9228                       const char *fieldname = TYPE_FIELD_NAME (t, i);
9229
9230                       if (is_vtable_name (fieldname, cu))
9231                         {
9232                           TYPE_VPTR_FIELDNO (type) = i;
9233                           break;
9234                         }
9235                     }
9236
9237                   /* Complain if virtual function table field not found.  */
9238                   if (i < TYPE_N_BASECLASSES (t))
9239                     complaint (&symfile_complaints,
9240                                _("virtual function table pointer "
9241                                  "not found when defining class '%s'"),
9242                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
9243                                "");
9244                 }
9245               else
9246                 {
9247                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
9248                 }
9249             }
9250           else if (cu->producer
9251                    && strncmp (cu->producer,
9252                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
9253             {
9254               /* The IBM XLC compiler does not provide direct indication
9255                  of the containing type, but the vtable pointer is
9256                  always named __vfp.  */
9257
9258               int i;
9259
9260               for (i = TYPE_NFIELDS (type) - 1;
9261                    i >= TYPE_N_BASECLASSES (type);
9262                    --i)
9263                 {
9264                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
9265                     {
9266                       TYPE_VPTR_FIELDNO (type) = i;
9267                       TYPE_VPTR_BASETYPE (type) = type;
9268                       break;
9269                     }
9270                 }
9271             }
9272         }
9273
9274       /* Copy fi.typedef_field_list linked list elements content into the
9275          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
9276       if (fi.typedef_field_list)
9277         {
9278           int i = fi.typedef_field_list_count;
9279
9280           ALLOCATE_CPLUS_STRUCT_TYPE (type);
9281           TYPE_TYPEDEF_FIELD_ARRAY (type)
9282             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
9283           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
9284
9285           /* Reverse the list order to keep the debug info elements order.  */
9286           while (--i >= 0)
9287             {
9288               struct typedef_field *dest, *src;
9289
9290               dest = &TYPE_TYPEDEF_FIELD (type, i);
9291               src = &fi.typedef_field_list->field;
9292               fi.typedef_field_list = fi.typedef_field_list->next;
9293               *dest = *src;
9294             }
9295         }
9296
9297       do_cleanups (back_to);
9298
9299       if (HAVE_CPLUS_STRUCT (type))
9300         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
9301     }
9302
9303   quirk_gcc_member_function_pointer (type, objfile);
9304
9305   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
9306      snapshots) has been known to create a die giving a declaration
9307      for a class that has, as a child, a die giving a definition for a
9308      nested class.  So we have to process our children even if the
9309      current die is a declaration.  Normally, of course, a declaration
9310      won't have any children at all.  */
9311
9312   while (child_die != NULL && child_die->tag)
9313     {
9314       if (child_die->tag == DW_TAG_member
9315           || child_die->tag == DW_TAG_variable
9316           || child_die->tag == DW_TAG_inheritance
9317           || child_die->tag == DW_TAG_template_value_param
9318           || child_die->tag == DW_TAG_template_type_param)
9319         {
9320           /* Do nothing.  */
9321         }
9322       else
9323         process_die (child_die, cu);
9324
9325       child_die = sibling_die (child_die);
9326     }
9327
9328   /* Do not consider external references.  According to the DWARF standard,
9329      these DIEs are identified by the fact that they have no byte_size
9330      attribute, and a declaration attribute.  */
9331   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
9332       || !die_is_declaration (die, cu))
9333     new_symbol (die, type, cu);
9334 }
9335
9336 /* Given a DW_AT_enumeration_type die, set its type.  We do not
9337    complete the type's fields yet, or create any symbols.  */
9338
9339 static struct type *
9340 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
9341 {
9342   struct objfile *objfile = cu->objfile;
9343   struct type *type;
9344   struct attribute *attr;
9345   const char *name;
9346
9347   /* If the definition of this type lives in .debug_types, read that type.
9348      Don't follow DW_AT_specification though, that will take us back up
9349      the chain and we want to go down.  */
9350   attr = dwarf2_attr_no_follow (die, DW_AT_signature, cu);
9351   if (attr)
9352     {
9353       struct dwarf2_cu *type_cu = cu;
9354       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
9355
9356       type = read_type_die (type_die, type_cu);
9357
9358       /* TYPE_CU may not be the same as CU.
9359          Ensure TYPE is recorded in CU's type_hash table.  */
9360       return set_die_type (die, type, cu);
9361     }
9362
9363   type = alloc_type (objfile);
9364
9365   TYPE_CODE (type) = TYPE_CODE_ENUM;
9366   name = dwarf2_full_name (NULL, die, cu);
9367   if (name != NULL)
9368     TYPE_TAG_NAME (type) = (char *) name;
9369
9370   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9371   if (attr)
9372     {
9373       TYPE_LENGTH (type) = DW_UNSND (attr);
9374     }
9375   else
9376     {
9377       TYPE_LENGTH (type) = 0;
9378     }
9379
9380   /* The enumeration DIE can be incomplete.  In Ada, any type can be
9381      declared as private in the package spec, and then defined only
9382      inside the package body.  Such types are known as Taft Amendment
9383      Types.  When another package uses such a type, an incomplete DIE
9384      may be generated by the compiler.  */
9385   if (die_is_declaration (die, cu))
9386     TYPE_STUB (type) = 1;
9387
9388   return set_die_type (die, type, cu);
9389 }
9390
9391 /* Given a pointer to a die which begins an enumeration, process all
9392    the dies that define the members of the enumeration, and create the
9393    symbol for the enumeration type.
9394
9395    NOTE: We reverse the order of the element list.  */
9396
9397 static void
9398 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
9399 {
9400   struct type *this_type;
9401
9402   this_type = get_die_type (die, cu);
9403   if (this_type == NULL)
9404     this_type = read_enumeration_type (die, cu);
9405
9406   if (die->child != NULL)
9407     {
9408       struct die_info *child_die;
9409       struct symbol *sym;
9410       struct field *fields = NULL;
9411       int num_fields = 0;
9412       int unsigned_enum = 1;
9413       char *name;
9414       int flag_enum = 1;
9415       ULONGEST mask = 0;
9416
9417       child_die = die->child;
9418       while (child_die && child_die->tag)
9419         {
9420           if (child_die->tag != DW_TAG_enumerator)
9421             {
9422               process_die (child_die, cu);
9423             }
9424           else
9425             {
9426               name = dwarf2_name (child_die, cu);
9427               if (name)
9428                 {
9429                   sym = new_symbol (child_die, this_type, cu);
9430                   if (SYMBOL_VALUE (sym) < 0)
9431                     {
9432                       unsigned_enum = 0;
9433                       flag_enum = 0;
9434                     }
9435                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
9436                     flag_enum = 0;
9437                   else
9438                     mask |= SYMBOL_VALUE (sym);
9439
9440                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
9441                     {
9442                       fields = (struct field *)
9443                         xrealloc (fields,
9444                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
9445                                   * sizeof (struct field));
9446                     }
9447
9448                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
9449                   FIELD_TYPE (fields[num_fields]) = NULL;
9450                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
9451                   FIELD_BITSIZE (fields[num_fields]) = 0;
9452
9453                   num_fields++;
9454                 }
9455             }
9456
9457           child_die = sibling_die (child_die);
9458         }
9459
9460       if (num_fields)
9461         {
9462           TYPE_NFIELDS (this_type) = num_fields;
9463           TYPE_FIELDS (this_type) = (struct field *)
9464             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
9465           memcpy (TYPE_FIELDS (this_type), fields,
9466                   sizeof (struct field) * num_fields);
9467           xfree (fields);
9468         }
9469       if (unsigned_enum)
9470         TYPE_UNSIGNED (this_type) = 1;
9471       if (flag_enum)
9472         TYPE_FLAG_ENUM (this_type) = 1;
9473     }
9474
9475   /* If we are reading an enum from a .debug_types unit, and the enum
9476      is a declaration, and the enum is not the signatured type in the
9477      unit, then we do not want to add a symbol for it.  Adding a
9478      symbol would in some cases obscure the true definition of the
9479      enum, giving users an incomplete type when the definition is
9480      actually available.  Note that we do not want to do this for all
9481      enums which are just declarations, because C++0x allows forward
9482      enum declarations.  */
9483   if (cu->per_cu->is_debug_types
9484       && die_is_declaration (die, cu))
9485     {
9486       struct signatured_type *sig_type;
9487
9488       sig_type
9489         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
9490                                             cu->per_cu->info_or_types_section,
9491                                             cu->per_cu->offset);
9492       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
9493       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
9494         return;
9495     }
9496
9497   new_symbol (die, this_type, cu);
9498 }
9499
9500 /* Extract all information from a DW_TAG_array_type DIE and put it in
9501    the DIE's type field.  For now, this only handles one dimensional
9502    arrays.  */
9503
9504 static struct type *
9505 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
9506 {
9507   struct objfile *objfile = cu->objfile;
9508   struct die_info *child_die;
9509   struct type *type;
9510   struct type *element_type, *range_type, *index_type;
9511   struct type **range_types = NULL;
9512   struct attribute *attr;
9513   int ndim = 0;
9514   struct cleanup *back_to;
9515   char *name;
9516
9517   element_type = die_type (die, cu);
9518
9519   /* The die_type call above may have already set the type for this DIE.  */
9520   type = get_die_type (die, cu);
9521   if (type)
9522     return type;
9523
9524   /* Irix 6.2 native cc creates array types without children for
9525      arrays with unspecified length.  */
9526   if (die->child == NULL)
9527     {
9528       index_type = objfile_type (objfile)->builtin_int;
9529       range_type = create_range_type (NULL, index_type, 0, -1);
9530       type = create_array_type (NULL, element_type, range_type);
9531       return set_die_type (die, type, cu);
9532     }
9533
9534   back_to = make_cleanup (null_cleanup, NULL);
9535   child_die = die->child;
9536   while (child_die && child_die->tag)
9537     {
9538       if (child_die->tag == DW_TAG_subrange_type)
9539         {
9540           struct type *child_type = read_type_die (child_die, cu);
9541
9542           if (child_type != NULL)
9543             {
9544               /* The range type was succesfully read.  Save it for the
9545                  array type creation.  */
9546               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
9547                 {
9548                   range_types = (struct type **)
9549                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
9550                               * sizeof (struct type *));
9551                   if (ndim == 0)
9552                     make_cleanup (free_current_contents, &range_types);
9553                 }
9554               range_types[ndim++] = child_type;
9555             }
9556         }
9557       child_die = sibling_die (child_die);
9558     }
9559
9560   /* Dwarf2 dimensions are output from left to right, create the
9561      necessary array types in backwards order.  */
9562
9563   type = element_type;
9564
9565   if (read_array_order (die, cu) == DW_ORD_col_major)
9566     {
9567       int i = 0;
9568
9569       while (i < ndim)
9570         type = create_array_type (NULL, type, range_types[i++]);
9571     }
9572   else
9573     {
9574       while (ndim-- > 0)
9575         type = create_array_type (NULL, type, range_types[ndim]);
9576     }
9577
9578   /* Understand Dwarf2 support for vector types (like they occur on
9579      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
9580      array type.  This is not part of the Dwarf2/3 standard yet, but a
9581      custom vendor extension.  The main difference between a regular
9582      array and the vector variant is that vectors are passed by value
9583      to functions.  */
9584   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
9585   if (attr)
9586     make_vector_type (type);
9587
9588   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
9589      implementation may choose to implement triple vectors using this
9590      attribute.  */
9591   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9592   if (attr)
9593     {
9594       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
9595         TYPE_LENGTH (type) = DW_UNSND (attr);
9596       else
9597         complaint (&symfile_complaints,
9598                    _("DW_AT_byte_size for array type smaller "
9599                      "than the total size of elements"));
9600     }
9601
9602   name = dwarf2_name (die, cu);
9603   if (name)
9604     TYPE_NAME (type) = name;
9605
9606   /* Install the type in the die.  */
9607   set_die_type (die, type, cu);
9608
9609   /* set_die_type should be already done.  */
9610   set_descriptive_type (type, die, cu);
9611
9612   do_cleanups (back_to);
9613
9614   return type;
9615 }
9616
9617 static enum dwarf_array_dim_ordering
9618 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
9619 {
9620   struct attribute *attr;
9621
9622   attr = dwarf2_attr (die, DW_AT_ordering, cu);
9623
9624   if (attr) return DW_SND (attr);
9625
9626   /* GNU F77 is a special case, as at 08/2004 array type info is the
9627      opposite order to the dwarf2 specification, but data is still
9628      laid out as per normal fortran.
9629
9630      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
9631      version checking.  */
9632
9633   if (cu->language == language_fortran
9634       && cu->producer && strstr (cu->producer, "GNU F77"))
9635     {
9636       return DW_ORD_row_major;
9637     }
9638
9639   switch (cu->language_defn->la_array_ordering)
9640     {
9641     case array_column_major:
9642       return DW_ORD_col_major;
9643     case array_row_major:
9644     default:
9645       return DW_ORD_row_major;
9646     };
9647 }
9648
9649 /* Extract all information from a DW_TAG_set_type DIE and put it in
9650    the DIE's type field.  */
9651
9652 static struct type *
9653 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
9654 {
9655   struct type *domain_type, *set_type;
9656   struct attribute *attr;
9657
9658   domain_type = die_type (die, cu);
9659
9660   /* The die_type call above may have already set the type for this DIE.  */
9661   set_type = get_die_type (die, cu);
9662   if (set_type)
9663     return set_type;
9664
9665   set_type = create_set_type (NULL, domain_type);
9666
9667   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9668   if (attr)
9669     TYPE_LENGTH (set_type) = DW_UNSND (attr);
9670
9671   return set_die_type (die, set_type, cu);
9672 }
9673
9674 /* First cut: install each common block member as a global variable.  */
9675
9676 static void
9677 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
9678 {
9679   struct die_info *child_die;
9680   struct attribute *attr;
9681   struct symbol *sym;
9682   CORE_ADDR base = (CORE_ADDR) 0;
9683
9684   attr = dwarf2_attr (die, DW_AT_location, cu);
9685   if (attr)
9686     {
9687       /* Support the .debug_loc offsets.  */
9688       if (attr_form_is_block (attr))
9689         {
9690           base = decode_locdesc (DW_BLOCK (attr), cu);
9691         }
9692       else if (attr_form_is_section_offset (attr))
9693         {
9694           dwarf2_complex_location_expr_complaint ();
9695         }
9696       else
9697         {
9698           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
9699                                                  "common block member");
9700         }
9701     }
9702   if (die->child != NULL)
9703     {
9704       child_die = die->child;
9705       while (child_die && child_die->tag)
9706         {
9707           LONGEST offset;
9708
9709           sym = new_symbol (child_die, NULL, cu);
9710           if (sym != NULL
9711               && handle_data_member_location (child_die, cu, &offset))
9712             {
9713               SYMBOL_VALUE_ADDRESS (sym) = base + offset;
9714               add_symbol_to_list (sym, &global_symbols);
9715             }
9716           child_die = sibling_die (child_die);
9717         }
9718     }
9719 }
9720
9721 /* Create a type for a C++ namespace.  */
9722
9723 static struct type *
9724 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
9725 {
9726   struct objfile *objfile = cu->objfile;
9727   const char *previous_prefix, *name;
9728   int is_anonymous;
9729   struct type *type;
9730
9731   /* For extensions, reuse the type of the original namespace.  */
9732   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
9733     {
9734       struct die_info *ext_die;
9735       struct dwarf2_cu *ext_cu = cu;
9736
9737       ext_die = dwarf2_extension (die, &ext_cu);
9738       type = read_type_die (ext_die, ext_cu);
9739
9740       /* EXT_CU may not be the same as CU.
9741          Ensure TYPE is recorded in CU's type_hash table.  */
9742       return set_die_type (die, type, cu);
9743     }
9744
9745   name = namespace_name (die, &is_anonymous, cu);
9746
9747   /* Now build the name of the current namespace.  */
9748
9749   previous_prefix = determine_prefix (die, cu);
9750   if (previous_prefix[0] != '\0')
9751     name = typename_concat (&objfile->objfile_obstack,
9752                             previous_prefix, name, 0, cu);
9753
9754   /* Create the type.  */
9755   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
9756                     objfile);
9757   TYPE_NAME (type) = (char *) name;
9758   TYPE_TAG_NAME (type) = TYPE_NAME (type);
9759
9760   return set_die_type (die, type, cu);
9761 }
9762
9763 /* Read a C++ namespace.  */
9764
9765 static void
9766 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
9767 {
9768   struct objfile *objfile = cu->objfile;
9769   int is_anonymous;
9770
9771   /* Add a symbol associated to this if we haven't seen the namespace
9772      before.  Also, add a using directive if it's an anonymous
9773      namespace.  */
9774
9775   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
9776     {
9777       struct type *type;
9778
9779       type = read_type_die (die, cu);
9780       new_symbol (die, type, cu);
9781
9782       namespace_name (die, &is_anonymous, cu);
9783       if (is_anonymous)
9784         {
9785           const char *previous_prefix = determine_prefix (die, cu);
9786
9787           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
9788                                   NULL, NULL, &objfile->objfile_obstack);
9789         }
9790     }
9791
9792   if (die->child != NULL)
9793     {
9794       struct die_info *child_die = die->child;
9795
9796       while (child_die && child_die->tag)
9797         {
9798           process_die (child_die, cu);
9799           child_die = sibling_die (child_die);
9800         }
9801     }
9802 }
9803
9804 /* Read a Fortran module as type.  This DIE can be only a declaration used for
9805    imported module.  Still we need that type as local Fortran "use ... only"
9806    declaration imports depend on the created type in determine_prefix.  */
9807
9808 static struct type *
9809 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
9810 {
9811   struct objfile *objfile = cu->objfile;
9812   char *module_name;
9813   struct type *type;
9814
9815   module_name = dwarf2_name (die, cu);
9816   if (!module_name)
9817     complaint (&symfile_complaints,
9818                _("DW_TAG_module has no name, offset 0x%x"),
9819                die->offset.sect_off);
9820   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
9821
9822   /* determine_prefix uses TYPE_TAG_NAME.  */
9823   TYPE_TAG_NAME (type) = TYPE_NAME (type);
9824
9825   return set_die_type (die, type, cu);
9826 }
9827
9828 /* Read a Fortran module.  */
9829
9830 static void
9831 read_module (struct die_info *die, struct dwarf2_cu *cu)
9832 {
9833   struct die_info *child_die = die->child;
9834
9835   while (child_die && child_die->tag)
9836     {
9837       process_die (child_die, cu);
9838       child_die = sibling_die (child_die);
9839     }
9840 }
9841
9842 /* Return the name of the namespace represented by DIE.  Set
9843    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
9844    namespace.  */
9845
9846 static const char *
9847 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
9848 {
9849   struct die_info *current_die;
9850   const char *name = NULL;
9851
9852   /* Loop through the extensions until we find a name.  */
9853
9854   for (current_die = die;
9855        current_die != NULL;
9856        current_die = dwarf2_extension (die, &cu))
9857     {
9858       name = dwarf2_name (current_die, cu);
9859       if (name != NULL)
9860         break;
9861     }
9862
9863   /* Is it an anonymous namespace?  */
9864
9865   *is_anonymous = (name == NULL);
9866   if (*is_anonymous)
9867     name = CP_ANONYMOUS_NAMESPACE_STR;
9868
9869   return name;
9870 }
9871
9872 /* Extract all information from a DW_TAG_pointer_type DIE and add to
9873    the user defined type vector.  */
9874
9875 static struct type *
9876 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
9877 {
9878   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
9879   struct comp_unit_head *cu_header = &cu->header;
9880   struct type *type;
9881   struct attribute *attr_byte_size;
9882   struct attribute *attr_address_class;
9883   int byte_size, addr_class;
9884   struct type *target_type;
9885
9886   target_type = die_type (die, cu);
9887
9888   /* The die_type call above may have already set the type for this DIE.  */
9889   type = get_die_type (die, cu);
9890   if (type)
9891     return type;
9892
9893   type = lookup_pointer_type (target_type);
9894
9895   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
9896   if (attr_byte_size)
9897     byte_size = DW_UNSND (attr_byte_size);
9898   else
9899     byte_size = cu_header->addr_size;
9900
9901   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
9902   if (attr_address_class)
9903     addr_class = DW_UNSND (attr_address_class);
9904   else
9905     addr_class = DW_ADDR_none;
9906
9907   /* If the pointer size or address class is different than the
9908      default, create a type variant marked as such and set the
9909      length accordingly.  */
9910   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
9911     {
9912       if (gdbarch_address_class_type_flags_p (gdbarch))
9913         {
9914           int type_flags;
9915
9916           type_flags = gdbarch_address_class_type_flags
9917                          (gdbarch, byte_size, addr_class);
9918           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
9919                       == 0);
9920           type = make_type_with_address_space (type, type_flags);
9921         }
9922       else if (TYPE_LENGTH (type) != byte_size)
9923         {
9924           complaint (&symfile_complaints,
9925                      _("invalid pointer size %d"), byte_size);
9926         }
9927       else
9928         {
9929           /* Should we also complain about unhandled address classes?  */
9930         }
9931     }
9932
9933   TYPE_LENGTH (type) = byte_size;
9934   return set_die_type (die, type, cu);
9935 }
9936
9937 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
9938    the user defined type vector.  */
9939
9940 static struct type *
9941 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
9942 {
9943   struct type *type;
9944   struct type *to_type;
9945   struct type *domain;
9946
9947   to_type = die_type (die, cu);
9948   domain = die_containing_type (die, cu);
9949
9950   /* The calls above may have already set the type for this DIE.  */
9951   type = get_die_type (die, cu);
9952   if (type)
9953     return type;
9954
9955   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
9956     type = lookup_methodptr_type (to_type);
9957   else
9958     type = lookup_memberptr_type (to_type, domain);
9959
9960   return set_die_type (die, type, cu);
9961 }
9962
9963 /* Extract all information from a DW_TAG_reference_type DIE and add to
9964    the user defined type vector.  */
9965
9966 static struct type *
9967 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
9968 {
9969   struct comp_unit_head *cu_header = &cu->header;
9970   struct type *type, *target_type;
9971   struct attribute *attr;
9972
9973   target_type = die_type (die, cu);
9974
9975   /* The die_type call above may have already set the type for this DIE.  */
9976   type = get_die_type (die, cu);
9977   if (type)
9978     return type;
9979
9980   type = lookup_reference_type (target_type);
9981   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
9982   if (attr)
9983     {
9984       TYPE_LENGTH (type) = DW_UNSND (attr);
9985     }
9986   else
9987     {
9988       TYPE_LENGTH (type) = cu_header->addr_size;
9989     }
9990   return set_die_type (die, type, cu);
9991 }
9992
9993 static struct type *
9994 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
9995 {
9996   struct type *base_type, *cv_type;
9997
9998   base_type = die_type (die, cu);
9999
10000   /* The die_type call above may have already set the type for this DIE.  */
10001   cv_type = get_die_type (die, cu);
10002   if (cv_type)
10003     return cv_type;
10004
10005   /* In case the const qualifier is applied to an array type, the element type
10006      is so qualified, not the array type (section 6.7.3 of C99).  */
10007   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
10008     {
10009       struct type *el_type, *inner_array;
10010
10011       base_type = copy_type (base_type);
10012       inner_array = base_type;
10013
10014       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
10015         {
10016           TYPE_TARGET_TYPE (inner_array) =
10017             copy_type (TYPE_TARGET_TYPE (inner_array));
10018           inner_array = TYPE_TARGET_TYPE (inner_array);
10019         }
10020
10021       el_type = TYPE_TARGET_TYPE (inner_array);
10022       TYPE_TARGET_TYPE (inner_array) =
10023         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
10024
10025       return set_die_type (die, base_type, cu);
10026     }
10027
10028   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
10029   return set_die_type (die, cv_type, cu);
10030 }
10031
10032 static struct type *
10033 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
10034 {
10035   struct type *base_type, *cv_type;
10036
10037   base_type = die_type (die, cu);
10038
10039   /* The die_type call above may have already set the type for this DIE.  */
10040   cv_type = get_die_type (die, cu);
10041   if (cv_type)
10042     return cv_type;
10043
10044   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
10045   return set_die_type (die, cv_type, cu);
10046 }
10047
10048 /* Extract all information from a DW_TAG_string_type DIE and add to
10049    the user defined type vector.  It isn't really a user defined type,
10050    but it behaves like one, with other DIE's using an AT_user_def_type
10051    attribute to reference it.  */
10052
10053 static struct type *
10054 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
10055 {
10056   struct objfile *objfile = cu->objfile;
10057   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10058   struct type *type, *range_type, *index_type, *char_type;
10059   struct attribute *attr;
10060   unsigned int length;
10061
10062   attr = dwarf2_attr (die, DW_AT_string_length, cu);
10063   if (attr)
10064     {
10065       length = DW_UNSND (attr);
10066     }
10067   else
10068     {
10069       /* Check for the DW_AT_byte_size attribute.  */
10070       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10071       if (attr)
10072         {
10073           length = DW_UNSND (attr);
10074         }
10075       else
10076         {
10077           length = 1;
10078         }
10079     }
10080
10081   index_type = objfile_type (objfile)->builtin_int;
10082   range_type = create_range_type (NULL, index_type, 1, length);
10083   char_type = language_string_char_type (cu->language_defn, gdbarch);
10084   type = create_string_type (NULL, char_type, range_type);
10085
10086   return set_die_type (die, type, cu);
10087 }
10088
10089 /* Handle DIES due to C code like:
10090
10091    struct foo
10092    {
10093    int (*funcp)(int a, long l);
10094    int b;
10095    };
10096
10097    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
10098
10099 static struct type *
10100 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
10101 {
10102   struct objfile *objfile = cu->objfile;
10103   struct type *type;            /* Type that this function returns.  */
10104   struct type *ftype;           /* Function that returns above type.  */
10105   struct attribute *attr;
10106
10107   type = die_type (die, cu);
10108
10109   /* The die_type call above may have already set the type for this DIE.  */
10110   ftype = get_die_type (die, cu);
10111   if (ftype)
10112     return ftype;
10113
10114   ftype = lookup_function_type (type);
10115
10116   /* All functions in C++, Pascal and Java have prototypes.  */
10117   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
10118   if ((attr && (DW_UNSND (attr) != 0))
10119       || cu->language == language_cplus
10120       || cu->language == language_java
10121       || cu->language == language_pascal)
10122     TYPE_PROTOTYPED (ftype) = 1;
10123   else if (producer_is_realview (cu->producer))
10124     /* RealView does not emit DW_AT_prototyped.  We can not
10125        distinguish prototyped and unprototyped functions; default to
10126        prototyped, since that is more common in modern code (and
10127        RealView warns about unprototyped functions).  */
10128     TYPE_PROTOTYPED (ftype) = 1;
10129
10130   /* Store the calling convention in the type if it's available in
10131      the subroutine die.  Otherwise set the calling convention to
10132      the default value DW_CC_normal.  */
10133   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
10134   if (attr)
10135     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
10136   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
10137     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
10138   else
10139     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
10140
10141   /* We need to add the subroutine type to the die immediately so
10142      we don't infinitely recurse when dealing with parameters
10143      declared as the same subroutine type.  */
10144   set_die_type (die, ftype, cu);
10145
10146   if (die->child != NULL)
10147     {
10148       struct type *void_type = objfile_type (objfile)->builtin_void;
10149       struct die_info *child_die;
10150       int nparams, iparams;
10151
10152       /* Count the number of parameters.
10153          FIXME: GDB currently ignores vararg functions, but knows about
10154          vararg member functions.  */
10155       nparams = 0;
10156       child_die = die->child;
10157       while (child_die && child_die->tag)
10158         {
10159           if (child_die->tag == DW_TAG_formal_parameter)
10160             nparams++;
10161           else if (child_die->tag == DW_TAG_unspecified_parameters)
10162             TYPE_VARARGS (ftype) = 1;
10163           child_die = sibling_die (child_die);
10164         }
10165
10166       /* Allocate storage for parameters and fill them in.  */
10167       TYPE_NFIELDS (ftype) = nparams;
10168       TYPE_FIELDS (ftype) = (struct field *)
10169         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
10170
10171       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
10172          even if we error out during the parameters reading below.  */
10173       for (iparams = 0; iparams < nparams; iparams++)
10174         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
10175
10176       iparams = 0;
10177       child_die = die->child;
10178       while (child_die && child_die->tag)
10179         {
10180           if (child_die->tag == DW_TAG_formal_parameter)
10181             {
10182               struct type *arg_type;
10183
10184               /* DWARF version 2 has no clean way to discern C++
10185                  static and non-static member functions.  G++ helps
10186                  GDB by marking the first parameter for non-static
10187                  member functions (which is the this pointer) as
10188                  artificial.  We pass this information to
10189                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
10190
10191                  DWARF version 3 added DW_AT_object_pointer, which GCC
10192                  4.5 does not yet generate.  */
10193               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
10194               if (attr)
10195                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
10196               else
10197                 {
10198                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
10199
10200                   /* GCC/43521: In java, the formal parameter
10201                      "this" is sometimes not marked with DW_AT_artificial.  */
10202                   if (cu->language == language_java)
10203                     {
10204                       const char *name = dwarf2_name (child_die, cu);
10205
10206                       if (name && !strcmp (name, "this"))
10207                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
10208                     }
10209                 }
10210               arg_type = die_type (child_die, cu);
10211
10212               /* RealView does not mark THIS as const, which the testsuite
10213                  expects.  GCC marks THIS as const in method definitions,
10214                  but not in the class specifications (GCC PR 43053).  */
10215               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
10216                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
10217                 {
10218                   int is_this = 0;
10219                   struct dwarf2_cu *arg_cu = cu;
10220                   const char *name = dwarf2_name (child_die, cu);
10221
10222                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
10223                   if (attr)
10224                     {
10225                       /* If the compiler emits this, use it.  */
10226                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
10227                         is_this = 1;
10228                     }
10229                   else if (name && strcmp (name, "this") == 0)
10230                     /* Function definitions will have the argument names.  */
10231                     is_this = 1;
10232                   else if (name == NULL && iparams == 0)
10233                     /* Declarations may not have the names, so like
10234                        elsewhere in GDB, assume an artificial first
10235                        argument is "this".  */
10236                     is_this = 1;
10237
10238                   if (is_this)
10239                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
10240                                              arg_type, 0);
10241                 }
10242
10243               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
10244               iparams++;
10245             }
10246           child_die = sibling_die (child_die);
10247         }
10248     }
10249
10250   return ftype;
10251 }
10252
10253 static struct type *
10254 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
10255 {
10256   struct objfile *objfile = cu->objfile;
10257   const char *name = NULL;
10258   struct type *this_type, *target_type;
10259
10260   name = dwarf2_full_name (NULL, die, cu);
10261   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
10262                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
10263   TYPE_NAME (this_type) = (char *) name;
10264   set_die_type (die, this_type, cu);
10265   target_type = die_type (die, cu);
10266   if (target_type != this_type)
10267     TYPE_TARGET_TYPE (this_type) = target_type;
10268   else
10269     {
10270       /* Self-referential typedefs are, it seems, not allowed by the DWARF
10271          spec and cause infinite loops in GDB.  */
10272       complaint (&symfile_complaints,
10273                  _("Self-referential DW_TAG_typedef "
10274                    "- DIE at 0x%x [in module %s]"),
10275                  die->offset.sect_off, objfile->name);
10276       TYPE_TARGET_TYPE (this_type) = NULL;
10277     }
10278   return this_type;
10279 }
10280
10281 /* Find a representation of a given base type and install
10282    it in the TYPE field of the die.  */
10283
10284 static struct type *
10285 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
10286 {
10287   struct objfile *objfile = cu->objfile;
10288   struct type *type;
10289   struct attribute *attr;
10290   int encoding = 0, size = 0;
10291   char *name;
10292   enum type_code code = TYPE_CODE_INT;
10293   int type_flags = 0;
10294   struct type *target_type = NULL;
10295
10296   attr = dwarf2_attr (die, DW_AT_encoding, cu);
10297   if (attr)
10298     {
10299       encoding = DW_UNSND (attr);
10300     }
10301   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10302   if (attr)
10303     {
10304       size = DW_UNSND (attr);
10305     }
10306   name = dwarf2_name (die, cu);
10307   if (!name)
10308     {
10309       complaint (&symfile_complaints,
10310                  _("DW_AT_name missing from DW_TAG_base_type"));
10311     }
10312
10313   switch (encoding)
10314     {
10315       case DW_ATE_address:
10316         /* Turn DW_ATE_address into a void * pointer.  */
10317         code = TYPE_CODE_PTR;
10318         type_flags |= TYPE_FLAG_UNSIGNED;
10319         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
10320         break;
10321       case DW_ATE_boolean:
10322         code = TYPE_CODE_BOOL;
10323         type_flags |= TYPE_FLAG_UNSIGNED;
10324         break;
10325       case DW_ATE_complex_float:
10326         code = TYPE_CODE_COMPLEX;
10327         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
10328         break;
10329       case DW_ATE_decimal_float:
10330         code = TYPE_CODE_DECFLOAT;
10331         break;
10332       case DW_ATE_float:
10333         code = TYPE_CODE_FLT;
10334         break;
10335       case DW_ATE_signed:
10336         break;
10337       case DW_ATE_unsigned:
10338         type_flags |= TYPE_FLAG_UNSIGNED;
10339         if (cu->language == language_fortran
10340             && name
10341             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
10342           code = TYPE_CODE_CHAR;
10343         break;
10344       case DW_ATE_signed_char:
10345         if (cu->language == language_ada || cu->language == language_m2
10346             || cu->language == language_pascal
10347             || cu->language == language_fortran)
10348           code = TYPE_CODE_CHAR;
10349         break;
10350       case DW_ATE_unsigned_char:
10351         if (cu->language == language_ada || cu->language == language_m2
10352             || cu->language == language_pascal
10353             || cu->language == language_fortran)
10354           code = TYPE_CODE_CHAR;
10355         type_flags |= TYPE_FLAG_UNSIGNED;
10356         break;
10357       case DW_ATE_UTF:
10358         /* We just treat this as an integer and then recognize the
10359            type by name elsewhere.  */
10360         break;
10361
10362       default:
10363         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
10364                    dwarf_type_encoding_name (encoding));
10365         break;
10366     }
10367
10368   type = init_type (code, size, type_flags, NULL, objfile);
10369   TYPE_NAME (type) = name;
10370   TYPE_TARGET_TYPE (type) = target_type;
10371
10372   if (name && strcmp (name, "char") == 0)
10373     TYPE_NOSIGN (type) = 1;
10374
10375   return set_die_type (die, type, cu);
10376 }
10377
10378 /* Read the given DW_AT_subrange DIE.  */
10379
10380 static struct type *
10381 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
10382 {
10383   struct type *base_type;
10384   struct type *range_type;
10385   struct attribute *attr;
10386   LONGEST low, high;
10387   int low_default_is_valid;
10388   char *name;
10389   LONGEST negative_mask;
10390
10391   base_type = die_type (die, cu);
10392   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
10393   check_typedef (base_type);
10394
10395   /* The die_type call above may have already set the type for this DIE.  */
10396   range_type = get_die_type (die, cu);
10397   if (range_type)
10398     return range_type;
10399
10400   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
10401      omitting DW_AT_lower_bound.  */
10402   switch (cu->language)
10403     {
10404     case language_c:
10405     case language_cplus:
10406       low = 0;
10407       low_default_is_valid = 1;
10408       break;
10409     case language_fortran:
10410       low = 1;
10411       low_default_is_valid = 1;
10412       break;
10413     case language_d:
10414     case language_java:
10415     case language_objc:
10416       low = 0;
10417       low_default_is_valid = (cu->header.version >= 4);
10418       break;
10419     case language_ada:
10420     case language_m2:
10421     case language_pascal:
10422       low = 1;
10423       low_default_is_valid = (cu->header.version >= 4);
10424       break;
10425     default:
10426       low = 0;
10427       low_default_is_valid = 0;
10428       break;
10429     }
10430
10431   /* FIXME: For variable sized arrays either of these could be
10432      a variable rather than a constant value.  We'll allow it,
10433      but we don't know how to handle it.  */
10434   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
10435   if (attr)
10436     low = dwarf2_get_attr_constant_value (attr, low);
10437   else if (!low_default_is_valid)
10438     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
10439                                       "- DIE at 0x%x [in module %s]"),
10440                die->offset.sect_off, cu->objfile->name);
10441
10442   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
10443   if (attr)
10444     {
10445       if (attr_form_is_block (attr) || is_ref_attr (attr))
10446         {
10447           /* GCC encodes arrays with unspecified or dynamic length
10448              with a DW_FORM_block1 attribute or a reference attribute.
10449              FIXME: GDB does not yet know how to handle dynamic
10450              arrays properly, treat them as arrays with unspecified
10451              length for now.
10452
10453              FIXME: jimb/2003-09-22: GDB does not really know
10454              how to handle arrays of unspecified length
10455              either; we just represent them as zero-length
10456              arrays.  Choose an appropriate upper bound given
10457              the lower bound we've computed above.  */
10458           high = low - 1;
10459         }
10460       else
10461         high = dwarf2_get_attr_constant_value (attr, 1);
10462     }
10463   else
10464     {
10465       attr = dwarf2_attr (die, DW_AT_count, cu);
10466       if (attr)
10467         {
10468           int count = dwarf2_get_attr_constant_value (attr, 1);
10469           high = low + count - 1;
10470         }
10471       else
10472         {
10473           /* Unspecified array length.  */
10474           high = low - 1;
10475         }
10476     }
10477
10478   /* Dwarf-2 specifications explicitly allows to create subrange types
10479      without specifying a base type.
10480      In that case, the base type must be set to the type of
10481      the lower bound, upper bound or count, in that order, if any of these
10482      three attributes references an object that has a type.
10483      If no base type is found, the Dwarf-2 specifications say that
10484      a signed integer type of size equal to the size of an address should
10485      be used.
10486      For the following C code: `extern char gdb_int [];'
10487      GCC produces an empty range DIE.
10488      FIXME: muller/2010-05-28: Possible references to object for low bound,
10489      high bound or count are not yet handled by this code.  */
10490   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
10491     {
10492       struct objfile *objfile = cu->objfile;
10493       struct gdbarch *gdbarch = get_objfile_arch (objfile);
10494       int addr_size = gdbarch_addr_bit (gdbarch) /8;
10495       struct type *int_type = objfile_type (objfile)->builtin_int;
10496
10497       /* Test "int", "long int", and "long long int" objfile types,
10498          and select the first one having a size above or equal to the
10499          architecture address size.  */
10500       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
10501         base_type = int_type;
10502       else
10503         {
10504           int_type = objfile_type (objfile)->builtin_long;
10505           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
10506             base_type = int_type;
10507           else
10508             {
10509               int_type = objfile_type (objfile)->builtin_long_long;
10510               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
10511                 base_type = int_type;
10512             }
10513         }
10514     }
10515
10516   negative_mask =
10517     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
10518   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
10519     low |= negative_mask;
10520   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
10521     high |= negative_mask;
10522
10523   range_type = create_range_type (NULL, base_type, low, high);
10524
10525   /* Mark arrays with dynamic length at least as an array of unspecified
10526      length.  GDB could check the boundary but before it gets implemented at
10527      least allow accessing the array elements.  */
10528   if (attr && attr_form_is_block (attr))
10529     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
10530
10531   /* Ada expects an empty array on no boundary attributes.  */
10532   if (attr == NULL && cu->language != language_ada)
10533     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
10534
10535   name = dwarf2_name (die, cu);
10536   if (name)
10537     TYPE_NAME (range_type) = name;
10538
10539   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10540   if (attr)
10541     TYPE_LENGTH (range_type) = DW_UNSND (attr);
10542
10543   set_die_type (die, range_type, cu);
10544
10545   /* set_die_type should be already done.  */
10546   set_descriptive_type (range_type, die, cu);
10547
10548   return range_type;
10549 }
10550
10551 static struct type *
10552 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
10553 {
10554   struct type *type;
10555
10556   /* For now, we only support the C meaning of an unspecified type: void.  */
10557
10558   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
10559   TYPE_NAME (type) = dwarf2_name (die, cu);
10560
10561   return set_die_type (die, type, cu);
10562 }
10563
10564 /* Read a single die and all its descendents.  Set the die's sibling
10565    field to NULL; set other fields in the die correctly, and set all
10566    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
10567    location of the info_ptr after reading all of those dies.  PARENT
10568    is the parent of the die in question.  */
10569
10570 static struct die_info *
10571 read_die_and_children (const struct die_reader_specs *reader,
10572                        gdb_byte *info_ptr,
10573                        gdb_byte **new_info_ptr,
10574                        struct die_info *parent)
10575 {
10576   struct die_info *die;
10577   gdb_byte *cur_ptr;
10578   int has_children;
10579
10580   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
10581   if (die == NULL)
10582     {
10583       *new_info_ptr = cur_ptr;
10584       return NULL;
10585     }
10586   store_in_ref_table (die, reader->cu);
10587
10588   if (has_children)
10589     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
10590   else
10591     {
10592       die->child = NULL;
10593       *new_info_ptr = cur_ptr;
10594     }
10595
10596   die->sibling = NULL;
10597   die->parent = parent;
10598   return die;
10599 }
10600
10601 /* Read a die, all of its descendents, and all of its siblings; set
10602    all of the fields of all of the dies correctly.  Arguments are as
10603    in read_die_and_children.  */
10604
10605 static struct die_info *
10606 read_die_and_siblings (const struct die_reader_specs *reader,
10607                        gdb_byte *info_ptr,
10608                        gdb_byte **new_info_ptr,
10609                        struct die_info *parent)
10610 {
10611   struct die_info *first_die, *last_sibling;
10612   gdb_byte *cur_ptr;
10613
10614   cur_ptr = info_ptr;
10615   first_die = last_sibling = NULL;
10616
10617   while (1)
10618     {
10619       struct die_info *die
10620         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
10621
10622       if (die == NULL)
10623         {
10624           *new_info_ptr = cur_ptr;
10625           return first_die;
10626         }
10627
10628       if (!first_die)
10629         first_die = die;
10630       else
10631         last_sibling->sibling = die;
10632
10633       last_sibling = die;
10634     }
10635 }
10636
10637 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
10638    attributes.
10639    The caller is responsible for filling in the extra attributes
10640    and updating (*DIEP)->num_attrs.
10641    Set DIEP to point to a newly allocated die with its information,
10642    except for its child, sibling, and parent fields.
10643    Set HAS_CHILDREN to tell whether the die has children or not.  */
10644
10645 static gdb_byte *
10646 read_full_die_1 (const struct die_reader_specs *reader,
10647                  struct die_info **diep, gdb_byte *info_ptr,
10648                  int *has_children, int num_extra_attrs)
10649 {
10650   unsigned int abbrev_number, bytes_read, i;
10651   sect_offset offset;
10652   struct abbrev_info *abbrev;
10653   struct die_info *die;
10654   struct dwarf2_cu *cu = reader->cu;
10655   bfd *abfd = reader->abfd;
10656
10657   offset.sect_off = info_ptr - reader->buffer;
10658   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
10659   info_ptr += bytes_read;
10660   if (!abbrev_number)
10661     {
10662       *diep = NULL;
10663       *has_children = 0;
10664       return info_ptr;
10665     }
10666
10667   abbrev = dwarf2_lookup_abbrev (abbrev_number, cu);
10668   if (!abbrev)
10669     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
10670            abbrev_number,
10671            bfd_get_filename (abfd));
10672
10673   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
10674   die->offset = offset;
10675   die->tag = abbrev->tag;
10676   die->abbrev = abbrev_number;
10677
10678   /* Make the result usable.
10679      The caller needs to update num_attrs after adding the extra
10680      attributes.  */
10681   die->num_attrs = abbrev->num_attrs;
10682
10683   for (i = 0; i < abbrev->num_attrs; ++i)
10684     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
10685                                info_ptr);
10686
10687   *diep = die;
10688   *has_children = abbrev->has_children;
10689   return info_ptr;
10690 }
10691
10692 /* Read a die and all its attributes.
10693    Set DIEP to point to a newly allocated die with its information,
10694    except for its child, sibling, and parent fields.
10695    Set HAS_CHILDREN to tell whether the die has children or not.  */
10696
10697 static gdb_byte *
10698 read_full_die (const struct die_reader_specs *reader,
10699                struct die_info **diep, gdb_byte *info_ptr,
10700                int *has_children)
10701 {
10702   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
10703 }
10704
10705 /* In DWARF version 2, the description of the debugging information is
10706    stored in a separate .debug_abbrev section.  Before we read any
10707    dies from a section we read in all abbreviations and install them
10708    in a hash table.  This function also sets flags in CU describing
10709    the data found in the abbrev table.  */
10710
10711 static void
10712 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
10713                      struct dwarf2_section_info *abbrev_section)
10714
10715 {
10716   bfd *abfd = abbrev_section->asection->owner;
10717   struct comp_unit_head *cu_header = &cu->header;
10718   gdb_byte *abbrev_ptr;
10719   struct abbrev_info *cur_abbrev;
10720   unsigned int abbrev_number, bytes_read, abbrev_name;
10721   unsigned int abbrev_form, hash_number;
10722   struct attr_abbrev *cur_attrs;
10723   unsigned int allocated_attrs;
10724
10725   /* Initialize dwarf2 abbrevs.  */
10726   obstack_init (&cu->abbrev_obstack);
10727   cu->dwarf2_abbrevs = obstack_alloc (&cu->abbrev_obstack,
10728                                       (ABBREV_HASH_SIZE
10729                                        * sizeof (struct abbrev_info *)));
10730   memset (cu->dwarf2_abbrevs, 0,
10731           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
10732
10733   dwarf2_read_section (cu->objfile, abbrev_section);
10734   abbrev_ptr = abbrev_section->buffer + cu_header->abbrev_offset.sect_off;
10735   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10736   abbrev_ptr += bytes_read;
10737
10738   allocated_attrs = ATTR_ALLOC_CHUNK;
10739   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
10740
10741   /* Loop until we reach an abbrev number of 0.  */
10742   while (abbrev_number)
10743     {
10744       cur_abbrev = dwarf_alloc_abbrev (cu);
10745
10746       /* read in abbrev header */
10747       cur_abbrev->number = abbrev_number;
10748       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10749       abbrev_ptr += bytes_read;
10750       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
10751       abbrev_ptr += 1;
10752
10753       /* now read in declarations */
10754       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10755       abbrev_ptr += bytes_read;
10756       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10757       abbrev_ptr += bytes_read;
10758       while (abbrev_name)
10759         {
10760           if (cur_abbrev->num_attrs == allocated_attrs)
10761             {
10762               allocated_attrs += ATTR_ALLOC_CHUNK;
10763               cur_attrs
10764                 = xrealloc (cur_attrs, (allocated_attrs
10765                                         * sizeof (struct attr_abbrev)));
10766             }
10767
10768           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
10769           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
10770           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10771           abbrev_ptr += bytes_read;
10772           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10773           abbrev_ptr += bytes_read;
10774         }
10775
10776       cur_abbrev->attrs = obstack_alloc (&cu->abbrev_obstack,
10777                                          (cur_abbrev->num_attrs
10778                                           * sizeof (struct attr_abbrev)));
10779       memcpy (cur_abbrev->attrs, cur_attrs,
10780               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
10781
10782       hash_number = abbrev_number % ABBREV_HASH_SIZE;
10783       cur_abbrev->next = cu->dwarf2_abbrevs[hash_number];
10784       cu->dwarf2_abbrevs[hash_number] = cur_abbrev;
10785
10786       /* Get next abbreviation.
10787          Under Irix6 the abbreviations for a compilation unit are not
10788          always properly terminated with an abbrev number of 0.
10789          Exit loop if we encounter an abbreviation which we have
10790          already read (which means we are about to read the abbreviations
10791          for the next compile unit) or if the end of the abbreviation
10792          table is reached.  */
10793       if ((unsigned int) (abbrev_ptr - abbrev_section->buffer)
10794           >= abbrev_section->size)
10795         break;
10796       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
10797       abbrev_ptr += bytes_read;
10798       if (dwarf2_lookup_abbrev (abbrev_number, cu) != NULL)
10799         break;
10800     }
10801
10802   xfree (cur_attrs);
10803 }
10804
10805 /* Release the memory used by the abbrev table for a compilation unit.  */
10806
10807 static void
10808 dwarf2_free_abbrev_table (void *ptr_to_cu)
10809 {
10810   struct dwarf2_cu *cu = ptr_to_cu;
10811
10812   obstack_free (&cu->abbrev_obstack, NULL);
10813   cu->dwarf2_abbrevs = NULL;
10814 }
10815
10816 /* Lookup an abbrev_info structure in the abbrev hash table.  */
10817
10818 static struct abbrev_info *
10819 dwarf2_lookup_abbrev (unsigned int number, struct dwarf2_cu *cu)
10820 {
10821   unsigned int hash_number;
10822   struct abbrev_info *abbrev;
10823
10824   hash_number = number % ABBREV_HASH_SIZE;
10825   abbrev = cu->dwarf2_abbrevs[hash_number];
10826
10827   while (abbrev)
10828     {
10829       if (abbrev->number == number)
10830         return abbrev;
10831       else
10832         abbrev = abbrev->next;
10833     }
10834   return NULL;
10835 }
10836
10837 /* Returns nonzero if TAG represents a type that we might generate a partial
10838    symbol for.  */
10839
10840 static int
10841 is_type_tag_for_partial (int tag)
10842 {
10843   switch (tag)
10844     {
10845 #if 0
10846     /* Some types that would be reasonable to generate partial symbols for,
10847        that we don't at present.  */
10848     case DW_TAG_array_type:
10849     case DW_TAG_file_type:
10850     case DW_TAG_ptr_to_member_type:
10851     case DW_TAG_set_type:
10852     case DW_TAG_string_type:
10853     case DW_TAG_subroutine_type:
10854 #endif
10855     case DW_TAG_base_type:
10856     case DW_TAG_class_type:
10857     case DW_TAG_interface_type:
10858     case DW_TAG_enumeration_type:
10859     case DW_TAG_structure_type:
10860     case DW_TAG_subrange_type:
10861     case DW_TAG_typedef:
10862     case DW_TAG_union_type:
10863       return 1;
10864     default:
10865       return 0;
10866     }
10867 }
10868
10869 /* Load all DIEs that are interesting for partial symbols into memory.  */
10870
10871 static struct partial_die_info *
10872 load_partial_dies (const struct die_reader_specs *reader,
10873                    gdb_byte *info_ptr, int building_psymtab)
10874 {
10875   struct dwarf2_cu *cu = reader->cu;
10876   struct objfile *objfile = cu->objfile;
10877   struct partial_die_info *part_die;
10878   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
10879   struct abbrev_info *abbrev;
10880   unsigned int bytes_read;
10881   unsigned int load_all = 0;
10882   int nesting_level = 1;
10883
10884   parent_die = NULL;
10885   last_die = NULL;
10886
10887   gdb_assert (cu->per_cu != NULL);
10888   if (cu->per_cu->load_all_dies)
10889     load_all = 1;
10890
10891   cu->partial_dies
10892     = htab_create_alloc_ex (cu->header.length / 12,
10893                             partial_die_hash,
10894                             partial_die_eq,
10895                             NULL,
10896                             &cu->comp_unit_obstack,
10897                             hashtab_obstack_allocate,
10898                             dummy_obstack_deallocate);
10899
10900   part_die = obstack_alloc (&cu->comp_unit_obstack,
10901                             sizeof (struct partial_die_info));
10902
10903   while (1)
10904     {
10905       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
10906
10907       /* A NULL abbrev means the end of a series of children.  */
10908       if (abbrev == NULL)
10909         {
10910           if (--nesting_level == 0)
10911             {
10912               /* PART_DIE was probably the last thing allocated on the
10913                  comp_unit_obstack, so we could call obstack_free
10914                  here.  We don't do that because the waste is small,
10915                  and will be cleaned up when we're done with this
10916                  compilation unit.  This way, we're also more robust
10917                  against other users of the comp_unit_obstack.  */
10918               return first_die;
10919             }
10920           info_ptr += bytes_read;
10921           last_die = parent_die;
10922           parent_die = parent_die->die_parent;
10923           continue;
10924         }
10925
10926       /* Check for template arguments.  We never save these; if
10927          they're seen, we just mark the parent, and go on our way.  */
10928       if (parent_die != NULL
10929           && cu->language == language_cplus
10930           && (abbrev->tag == DW_TAG_template_type_param
10931               || abbrev->tag == DW_TAG_template_value_param))
10932         {
10933           parent_die->has_template_arguments = 1;
10934
10935           if (!load_all)
10936             {
10937               /* We don't need a partial DIE for the template argument.  */
10938               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
10939               continue;
10940             }
10941         }
10942
10943       /* We only recurse into c++ subprograms looking for template arguments.
10944          Skip their other children.  */
10945       if (!load_all
10946           && cu->language == language_cplus
10947           && parent_die != NULL
10948           && parent_die->tag == DW_TAG_subprogram)
10949         {
10950           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
10951           continue;
10952         }
10953
10954       /* Check whether this DIE is interesting enough to save.  Normally
10955          we would not be interested in members here, but there may be
10956          later variables referencing them via DW_AT_specification (for
10957          static members).  */
10958       if (!load_all
10959           && !is_type_tag_for_partial (abbrev->tag)
10960           && abbrev->tag != DW_TAG_constant
10961           && abbrev->tag != DW_TAG_enumerator
10962           && abbrev->tag != DW_TAG_subprogram
10963           && abbrev->tag != DW_TAG_lexical_block
10964           && abbrev->tag != DW_TAG_variable
10965           && abbrev->tag != DW_TAG_namespace
10966           && abbrev->tag != DW_TAG_module
10967           && abbrev->tag != DW_TAG_member
10968           && abbrev->tag != DW_TAG_imported_unit)
10969         {
10970           /* Otherwise we skip to the next sibling, if any.  */
10971           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
10972           continue;
10973         }
10974
10975       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
10976                                    info_ptr);
10977
10978       /* This two-pass algorithm for processing partial symbols has a
10979          high cost in cache pressure.  Thus, handle some simple cases
10980          here which cover the majority of C partial symbols.  DIEs
10981          which neither have specification tags in them, nor could have
10982          specification tags elsewhere pointing at them, can simply be
10983          processed and discarded.
10984
10985          This segment is also optional; scan_partial_symbols and
10986          add_partial_symbol will handle these DIEs if we chain
10987          them in normally.  When compilers which do not emit large
10988          quantities of duplicate debug information are more common,
10989          this code can probably be removed.  */
10990
10991       /* Any complete simple types at the top level (pretty much all
10992          of them, for a language without namespaces), can be processed
10993          directly.  */
10994       if (parent_die == NULL
10995           && part_die->has_specification == 0
10996           && part_die->is_declaration == 0
10997           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
10998               || part_die->tag == DW_TAG_base_type
10999               || part_die->tag == DW_TAG_subrange_type))
11000         {
11001           if (building_psymtab && part_die->name != NULL)
11002             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
11003                                  VAR_DOMAIN, LOC_TYPEDEF,
11004                                  &objfile->static_psymbols,
11005                                  0, (CORE_ADDR) 0, cu->language, objfile);
11006           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
11007           continue;
11008         }
11009
11010       /* The exception for DW_TAG_typedef with has_children above is
11011          a workaround of GCC PR debug/47510.  In the case of this complaint
11012          type_name_no_tag_or_error will error on such types later.
11013
11014          GDB skipped children of DW_TAG_typedef by the shortcut above and then
11015          it could not find the child DIEs referenced later, this is checked
11016          above.  In correct DWARF DW_TAG_typedef should have no children.  */
11017
11018       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
11019         complaint (&symfile_complaints,
11020                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
11021                      "- DIE at 0x%x [in module %s]"),
11022                    part_die->offset.sect_off, objfile->name);
11023
11024       /* If we're at the second level, and we're an enumerator, and
11025          our parent has no specification (meaning possibly lives in a
11026          namespace elsewhere), then we can add the partial symbol now
11027          instead of queueing it.  */
11028       if (part_die->tag == DW_TAG_enumerator
11029           && parent_die != NULL
11030           && parent_die->die_parent == NULL
11031           && parent_die->tag == DW_TAG_enumeration_type
11032           && parent_die->has_specification == 0)
11033         {
11034           if (part_die->name == NULL)
11035             complaint (&symfile_complaints,
11036                        _("malformed enumerator DIE ignored"));
11037           else if (building_psymtab)
11038             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
11039                                  VAR_DOMAIN, LOC_CONST,
11040                                  (cu->language == language_cplus
11041                                   || cu->language == language_java)
11042                                  ? &objfile->global_psymbols
11043                                  : &objfile->static_psymbols,
11044                                  0, (CORE_ADDR) 0, cu->language, objfile);
11045
11046           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
11047           continue;
11048         }
11049
11050       /* We'll save this DIE so link it in.  */
11051       part_die->die_parent = parent_die;
11052       part_die->die_sibling = NULL;
11053       part_die->die_child = NULL;
11054
11055       if (last_die && last_die == parent_die)
11056         last_die->die_child = part_die;
11057       else if (last_die)
11058         last_die->die_sibling = part_die;
11059
11060       last_die = part_die;
11061
11062       if (first_die == NULL)
11063         first_die = part_die;
11064
11065       /* Maybe add the DIE to the hash table.  Not all DIEs that we
11066          find interesting need to be in the hash table, because we
11067          also have the parent/sibling/child chains; only those that we
11068          might refer to by offset later during partial symbol reading.
11069
11070          For now this means things that might have be the target of a
11071          DW_AT_specification, DW_AT_abstract_origin, or
11072          DW_AT_extension.  DW_AT_extension will refer only to
11073          namespaces; DW_AT_abstract_origin refers to functions (and
11074          many things under the function DIE, but we do not recurse
11075          into function DIEs during partial symbol reading) and
11076          possibly variables as well; DW_AT_specification refers to
11077          declarations.  Declarations ought to have the DW_AT_declaration
11078          flag.  It happens that GCC forgets to put it in sometimes, but
11079          only for functions, not for types.
11080
11081          Adding more things than necessary to the hash table is harmless
11082          except for the performance cost.  Adding too few will result in
11083          wasted time in find_partial_die, when we reread the compilation
11084          unit with load_all_dies set.  */
11085
11086       if (load_all
11087           || abbrev->tag == DW_TAG_constant
11088           || abbrev->tag == DW_TAG_subprogram
11089           || abbrev->tag == DW_TAG_variable
11090           || abbrev->tag == DW_TAG_namespace
11091           || part_die->is_declaration)
11092         {
11093           void **slot;
11094
11095           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
11096                                            part_die->offset.sect_off, INSERT);
11097           *slot = part_die;
11098         }
11099
11100       part_die = obstack_alloc (&cu->comp_unit_obstack,
11101                                 sizeof (struct partial_die_info));
11102
11103       /* For some DIEs we want to follow their children (if any).  For C
11104          we have no reason to follow the children of structures; for other
11105          languages we have to, so that we can get at method physnames
11106          to infer fully qualified class names, for DW_AT_specification,
11107          and for C++ template arguments.  For C++, we also look one level
11108          inside functions to find template arguments (if the name of the
11109          function does not already contain the template arguments).
11110
11111          For Ada, we need to scan the children of subprograms and lexical
11112          blocks as well because Ada allows the definition of nested
11113          entities that could be interesting for the debugger, such as
11114          nested subprograms for instance.  */
11115       if (last_die->has_children
11116           && (load_all
11117               || last_die->tag == DW_TAG_namespace
11118               || last_die->tag == DW_TAG_module
11119               || last_die->tag == DW_TAG_enumeration_type
11120               || (cu->language == language_cplus
11121                   && last_die->tag == DW_TAG_subprogram
11122                   && (last_die->name == NULL
11123                       || strchr (last_die->name, '<') == NULL))
11124               || (cu->language != language_c
11125                   && (last_die->tag == DW_TAG_class_type
11126                       || last_die->tag == DW_TAG_interface_type
11127                       || last_die->tag == DW_TAG_structure_type
11128                       || last_die->tag == DW_TAG_union_type))
11129               || (cu->language == language_ada
11130                   && (last_die->tag == DW_TAG_subprogram
11131                       || last_die->tag == DW_TAG_lexical_block))))
11132         {
11133           nesting_level++;
11134           parent_die = last_die;
11135           continue;
11136         }
11137
11138       /* Otherwise we skip to the next sibling, if any.  */
11139       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
11140
11141       /* Back to the top, do it again.  */
11142     }
11143 }
11144
11145 /* Read a minimal amount of information into the minimal die structure.  */
11146
11147 static gdb_byte *
11148 read_partial_die (const struct die_reader_specs *reader,
11149                   struct partial_die_info *part_die,
11150                   struct abbrev_info *abbrev, unsigned int abbrev_len,
11151                   gdb_byte *info_ptr)
11152 {
11153   struct dwarf2_cu *cu = reader->cu;
11154   struct objfile *objfile = cu->objfile;
11155   gdb_byte *buffer = reader->buffer;
11156   unsigned int i;
11157   struct attribute attr;
11158   int has_low_pc_attr = 0;
11159   int has_high_pc_attr = 0;
11160   int high_pc_relative = 0;
11161
11162   memset (part_die, 0, sizeof (struct partial_die_info));
11163
11164   part_die->offset.sect_off = info_ptr - buffer;
11165
11166   info_ptr += abbrev_len;
11167
11168   if (abbrev == NULL)
11169     return info_ptr;
11170
11171   part_die->tag = abbrev->tag;
11172   part_die->has_children = abbrev->has_children;
11173
11174   for (i = 0; i < abbrev->num_attrs; ++i)
11175     {
11176       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
11177
11178       /* Store the data if it is of an attribute we want to keep in a
11179          partial symbol table.  */
11180       switch (attr.name)
11181         {
11182         case DW_AT_name:
11183           switch (part_die->tag)
11184             {
11185             case DW_TAG_compile_unit:
11186             case DW_TAG_partial_unit:
11187             case DW_TAG_type_unit:
11188               /* Compilation units have a DW_AT_name that is a filename, not
11189                  a source language identifier.  */
11190             case DW_TAG_enumeration_type:
11191             case DW_TAG_enumerator:
11192               /* These tags always have simple identifiers already; no need
11193                  to canonicalize them.  */
11194               part_die->name = DW_STRING (&attr);
11195               break;
11196             default:
11197               part_die->name
11198                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
11199                                             &objfile->objfile_obstack);
11200               break;
11201             }
11202           break;
11203         case DW_AT_linkage_name:
11204         case DW_AT_MIPS_linkage_name:
11205           /* Note that both forms of linkage name might appear.  We
11206              assume they will be the same, and we only store the last
11207              one we see.  */
11208           if (cu->language == language_ada)
11209             part_die->name = DW_STRING (&attr);
11210           part_die->linkage_name = DW_STRING (&attr);
11211           break;
11212         case DW_AT_low_pc:
11213           has_low_pc_attr = 1;
11214           part_die->lowpc = DW_ADDR (&attr);
11215           break;
11216         case DW_AT_high_pc:
11217           has_high_pc_attr = 1;
11218           if (attr.form == DW_FORM_addr
11219               || attr.form == DW_FORM_GNU_addr_index)
11220             part_die->highpc = DW_ADDR (&attr);
11221           else
11222             {
11223               high_pc_relative = 1;
11224               part_die->highpc = DW_UNSND (&attr);
11225             }
11226           break;
11227         case DW_AT_location:
11228           /* Support the .debug_loc offsets.  */
11229           if (attr_form_is_block (&attr))
11230             {
11231                part_die->d.locdesc = DW_BLOCK (&attr);
11232             }
11233           else if (attr_form_is_section_offset (&attr))
11234             {
11235               dwarf2_complex_location_expr_complaint ();
11236             }
11237           else
11238             {
11239               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
11240                                                      "partial symbol information");
11241             }
11242           break;
11243         case DW_AT_external:
11244           part_die->is_external = DW_UNSND (&attr);
11245           break;
11246         case DW_AT_declaration:
11247           part_die->is_declaration = DW_UNSND (&attr);
11248           break;
11249         case DW_AT_type:
11250           part_die->has_type = 1;
11251           break;
11252         case DW_AT_abstract_origin:
11253         case DW_AT_specification:
11254         case DW_AT_extension:
11255           part_die->has_specification = 1;
11256           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
11257           break;
11258         case DW_AT_sibling:
11259           /* Ignore absolute siblings, they might point outside of
11260              the current compile unit.  */
11261           if (attr.form == DW_FORM_ref_addr)
11262             complaint (&symfile_complaints,
11263                        _("ignoring absolute DW_AT_sibling"));
11264           else
11265             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
11266           break;
11267         case DW_AT_byte_size:
11268           part_die->has_byte_size = 1;
11269           break;
11270         case DW_AT_calling_convention:
11271           /* DWARF doesn't provide a way to identify a program's source-level
11272              entry point.  DW_AT_calling_convention attributes are only meant
11273              to describe functions' calling conventions.
11274
11275              However, because it's a necessary piece of information in
11276              Fortran, and because DW_CC_program is the only piece of debugging
11277              information whose definition refers to a 'main program' at all,
11278              several compilers have begun marking Fortran main programs with
11279              DW_CC_program --- even when those functions use the standard
11280              calling conventions.
11281
11282              So until DWARF specifies a way to provide this information and
11283              compilers pick up the new representation, we'll support this
11284              practice.  */
11285           if (DW_UNSND (&attr) == DW_CC_program
11286               && cu->language == language_fortran)
11287             {
11288               set_main_name (part_die->name);
11289
11290               /* As this DIE has a static linkage the name would be difficult
11291                  to look up later.  */
11292               language_of_main = language_fortran;
11293             }
11294           break;
11295         case DW_AT_inline:
11296           if (DW_UNSND (&attr) == DW_INL_inlined
11297               || DW_UNSND (&attr) == DW_INL_declared_inlined)
11298             part_die->may_be_inlined = 1;
11299           break;
11300
11301         case DW_AT_import:
11302           if (part_die->tag == DW_TAG_imported_unit)
11303             part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
11304           break;
11305
11306         default:
11307           break;
11308         }
11309     }
11310
11311   if (high_pc_relative)
11312     part_die->highpc += part_die->lowpc;
11313
11314   if (has_low_pc_attr && has_high_pc_attr)
11315     {
11316       /* When using the GNU linker, .gnu.linkonce. sections are used to
11317          eliminate duplicate copies of functions and vtables and such.
11318          The linker will arbitrarily choose one and discard the others.
11319          The AT_*_pc values for such functions refer to local labels in
11320          these sections.  If the section from that file was discarded, the
11321          labels are not in the output, so the relocs get a value of 0.
11322          If this is a discarded function, mark the pc bounds as invalid,
11323          so that GDB will ignore it.  */
11324       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
11325         {
11326           struct gdbarch *gdbarch = get_objfile_arch (objfile);
11327
11328           complaint (&symfile_complaints,
11329                      _("DW_AT_low_pc %s is zero "
11330                        "for DIE at 0x%x [in module %s]"),
11331                      paddress (gdbarch, part_die->lowpc),
11332                      part_die->offset.sect_off, objfile->name);
11333         }
11334       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
11335       else if (part_die->lowpc >= part_die->highpc)
11336         {
11337           struct gdbarch *gdbarch = get_objfile_arch (objfile);
11338
11339           complaint (&symfile_complaints,
11340                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
11341                        "for DIE at 0x%x [in module %s]"),
11342                      paddress (gdbarch, part_die->lowpc),
11343                      paddress (gdbarch, part_die->highpc),
11344                      part_die->offset.sect_off, objfile->name);
11345         }
11346       else
11347         part_die->has_pc_info = 1;
11348     }
11349
11350   return info_ptr;
11351 }
11352
11353 /* Find a cached partial DIE at OFFSET in CU.  */
11354
11355 static struct partial_die_info *
11356 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
11357 {
11358   struct partial_die_info *lookup_die = NULL;
11359   struct partial_die_info part_die;
11360
11361   part_die.offset = offset;
11362   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
11363                                     offset.sect_off);
11364
11365   return lookup_die;
11366 }
11367
11368 /* Find a partial DIE at OFFSET, which may or may not be in CU,
11369    except in the case of .debug_types DIEs which do not reference
11370    outside their CU (they do however referencing other types via
11371    DW_FORM_ref_sig8).  */
11372
11373 static struct partial_die_info *
11374 find_partial_die (sect_offset offset, struct dwarf2_cu *cu)
11375 {
11376   struct objfile *objfile = cu->objfile;
11377   struct dwarf2_per_cu_data *per_cu = NULL;
11378   struct partial_die_info *pd = NULL;
11379
11380   if (offset_in_cu_p (&cu->header, offset))
11381     {
11382       pd = find_partial_die_in_comp_unit (offset, cu);
11383       if (pd != NULL)
11384         return pd;
11385       /* We missed recording what we needed.
11386          Load all dies and try again.  */
11387       per_cu = cu->per_cu;
11388     }
11389   else
11390     {
11391       /* TUs don't reference other CUs/TUs (except via type signatures).  */
11392       if (cu->per_cu->is_debug_types)
11393         {
11394           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
11395                    " external reference to offset 0x%lx [in module %s].\n"),
11396                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
11397                  bfd_get_filename (objfile->obfd));
11398         }
11399       per_cu = dwarf2_find_containing_comp_unit (offset, objfile);
11400
11401       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
11402         load_partial_comp_unit (per_cu);
11403
11404       per_cu->cu->last_used = 0;
11405       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
11406     }
11407
11408   /* If we didn't find it, and not all dies have been loaded,
11409      load them all and try again.  */
11410
11411   if (pd == NULL && per_cu->load_all_dies == 0)
11412     {
11413       per_cu->load_all_dies = 1;
11414
11415       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
11416          THIS_CU->cu may already be in use.  So we can't just free it and
11417          replace its DIEs with the ones we read in.  Instead, we leave those
11418          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
11419          and clobber THIS_CU->cu->partial_dies with the hash table for the new
11420          set.  */
11421       load_partial_comp_unit (per_cu);
11422
11423       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
11424     }
11425
11426   if (pd == NULL)
11427     internal_error (__FILE__, __LINE__,
11428                     _("could not find partial DIE 0x%x "
11429                       "in cache [from module %s]\n"),
11430                     offset.sect_off, bfd_get_filename (objfile->obfd));
11431   return pd;
11432 }
11433
11434 /* See if we can figure out if the class lives in a namespace.  We do
11435    this by looking for a member function; its demangled name will
11436    contain namespace info, if there is any.  */
11437
11438 static void
11439 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
11440                                   struct dwarf2_cu *cu)
11441 {
11442   /* NOTE: carlton/2003-10-07: Getting the info this way changes
11443      what template types look like, because the demangler
11444      frequently doesn't give the same name as the debug info.  We
11445      could fix this by only using the demangled name to get the
11446      prefix (but see comment in read_structure_type).  */
11447
11448   struct partial_die_info *real_pdi;
11449   struct partial_die_info *child_pdi;
11450
11451   /* If this DIE (this DIE's specification, if any) has a parent, then
11452      we should not do this.  We'll prepend the parent's fully qualified
11453      name when we create the partial symbol.  */
11454
11455   real_pdi = struct_pdi;
11456   while (real_pdi->has_specification)
11457     real_pdi = find_partial_die (real_pdi->spec_offset, cu);
11458
11459   if (real_pdi->die_parent != NULL)
11460     return;
11461
11462   for (child_pdi = struct_pdi->die_child;
11463        child_pdi != NULL;
11464        child_pdi = child_pdi->die_sibling)
11465     {
11466       if (child_pdi->tag == DW_TAG_subprogram
11467           && child_pdi->linkage_name != NULL)
11468         {
11469           char *actual_class_name
11470             = language_class_name_from_physname (cu->language_defn,
11471                                                  child_pdi->linkage_name);
11472           if (actual_class_name != NULL)
11473             {
11474               struct_pdi->name
11475                 = obsavestring (actual_class_name,
11476                                 strlen (actual_class_name),
11477                                 &cu->objfile->objfile_obstack);
11478               xfree (actual_class_name);
11479             }
11480           break;
11481         }
11482     }
11483 }
11484
11485 /* Adjust PART_DIE before generating a symbol for it.  This function
11486    may set the is_external flag or change the DIE's name.  */
11487
11488 static void
11489 fixup_partial_die (struct partial_die_info *part_die,
11490                    struct dwarf2_cu *cu)
11491 {
11492   /* Once we've fixed up a die, there's no point in doing so again.
11493      This also avoids a memory leak if we were to call
11494      guess_partial_die_structure_name multiple times.  */
11495   if (part_die->fixup_called)
11496     return;
11497
11498   /* If we found a reference attribute and the DIE has no name, try
11499      to find a name in the referred to DIE.  */
11500
11501   if (part_die->name == NULL && part_die->has_specification)
11502     {
11503       struct partial_die_info *spec_die;
11504
11505       spec_die = find_partial_die (part_die->spec_offset, cu);
11506
11507       fixup_partial_die (spec_die, cu);
11508
11509       if (spec_die->name)
11510         {
11511           part_die->name = spec_die->name;
11512
11513           /* Copy DW_AT_external attribute if it is set.  */
11514           if (spec_die->is_external)
11515             part_die->is_external = spec_die->is_external;
11516         }
11517     }
11518
11519   /* Set default names for some unnamed DIEs.  */
11520
11521   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
11522     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
11523
11524   /* If there is no parent die to provide a namespace, and there are
11525      children, see if we can determine the namespace from their linkage
11526      name.  */
11527   if (cu->language == language_cplus
11528       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
11529       && part_die->die_parent == NULL
11530       && part_die->has_children
11531       && (part_die->tag == DW_TAG_class_type
11532           || part_die->tag == DW_TAG_structure_type
11533           || part_die->tag == DW_TAG_union_type))
11534     guess_partial_die_structure_name (part_die, cu);
11535
11536   /* GCC might emit a nameless struct or union that has a linkage
11537      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
11538   if (part_die->name == NULL
11539       && (part_die->tag == DW_TAG_class_type
11540           || part_die->tag == DW_TAG_interface_type
11541           || part_die->tag == DW_TAG_structure_type
11542           || part_die->tag == DW_TAG_union_type)
11543       && part_die->linkage_name != NULL)
11544     {
11545       char *demangled;
11546
11547       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
11548       if (demangled)
11549         {
11550           const char *base;
11551
11552           /* Strip any leading namespaces/classes, keep only the base name.
11553              DW_AT_name for named DIEs does not contain the prefixes.  */
11554           base = strrchr (demangled, ':');
11555           if (base && base > demangled && base[-1] == ':')
11556             base++;
11557           else
11558             base = demangled;
11559
11560           part_die->name = obsavestring (base, strlen (base),
11561                                          &cu->objfile->objfile_obstack);
11562           xfree (demangled);
11563         }
11564     }
11565
11566   part_die->fixup_called = 1;
11567 }
11568
11569 /* Read an attribute value described by an attribute form.  */
11570
11571 static gdb_byte *
11572 read_attribute_value (const struct die_reader_specs *reader,
11573                       struct attribute *attr, unsigned form,
11574                       gdb_byte *info_ptr)
11575 {
11576   struct dwarf2_cu *cu = reader->cu;
11577   bfd *abfd = reader->abfd;
11578   struct comp_unit_head *cu_header = &cu->header;
11579   unsigned int bytes_read;
11580   struct dwarf_block *blk;
11581
11582   attr->form = form;
11583   switch (form)
11584     {
11585     case DW_FORM_ref_addr:
11586       if (cu->header.version == 2)
11587         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
11588       else
11589         DW_UNSND (attr) = read_offset (abfd, info_ptr,
11590                                        &cu->header, &bytes_read);
11591       info_ptr += bytes_read;
11592       break;
11593     case DW_FORM_addr:
11594       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
11595       info_ptr += bytes_read;
11596       break;
11597     case DW_FORM_block2:
11598       blk = dwarf_alloc_block (cu);
11599       blk->size = read_2_bytes (abfd, info_ptr);
11600       info_ptr += 2;
11601       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11602       info_ptr += blk->size;
11603       DW_BLOCK (attr) = blk;
11604       break;
11605     case DW_FORM_block4:
11606       blk = dwarf_alloc_block (cu);
11607       blk->size = read_4_bytes (abfd, info_ptr);
11608       info_ptr += 4;
11609       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11610       info_ptr += blk->size;
11611       DW_BLOCK (attr) = blk;
11612       break;
11613     case DW_FORM_data2:
11614       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
11615       info_ptr += 2;
11616       break;
11617     case DW_FORM_data4:
11618       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
11619       info_ptr += 4;
11620       break;
11621     case DW_FORM_data8:
11622       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
11623       info_ptr += 8;
11624       break;
11625     case DW_FORM_sec_offset:
11626       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
11627       info_ptr += bytes_read;
11628       break;
11629     case DW_FORM_string:
11630       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
11631       DW_STRING_IS_CANONICAL (attr) = 0;
11632       info_ptr += bytes_read;
11633       break;
11634     case DW_FORM_strp:
11635       DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
11636                                                &bytes_read);
11637       DW_STRING_IS_CANONICAL (attr) = 0;
11638       info_ptr += bytes_read;
11639       break;
11640     case DW_FORM_exprloc:
11641     case DW_FORM_block:
11642       blk = dwarf_alloc_block (cu);
11643       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11644       info_ptr += bytes_read;
11645       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11646       info_ptr += blk->size;
11647       DW_BLOCK (attr) = blk;
11648       break;
11649     case DW_FORM_block1:
11650       blk = dwarf_alloc_block (cu);
11651       blk->size = read_1_byte (abfd, info_ptr);
11652       info_ptr += 1;
11653       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
11654       info_ptr += blk->size;
11655       DW_BLOCK (attr) = blk;
11656       break;
11657     case DW_FORM_data1:
11658       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
11659       info_ptr += 1;
11660       break;
11661     case DW_FORM_flag:
11662       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
11663       info_ptr += 1;
11664       break;
11665     case DW_FORM_flag_present:
11666       DW_UNSND (attr) = 1;
11667       break;
11668     case DW_FORM_sdata:
11669       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
11670       info_ptr += bytes_read;
11671       break;
11672     case DW_FORM_udata:
11673       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11674       info_ptr += bytes_read;
11675       break;
11676     case DW_FORM_ref1:
11677       DW_UNSND (attr) = (cu->header.offset.sect_off
11678                          + read_1_byte (abfd, info_ptr));
11679       info_ptr += 1;
11680       break;
11681     case DW_FORM_ref2:
11682       DW_UNSND (attr) = (cu->header.offset.sect_off
11683                          + read_2_bytes (abfd, info_ptr));
11684       info_ptr += 2;
11685       break;
11686     case DW_FORM_ref4:
11687       DW_UNSND (attr) = (cu->header.offset.sect_off
11688                          + read_4_bytes (abfd, info_ptr));
11689       info_ptr += 4;
11690       break;
11691     case DW_FORM_ref8:
11692       DW_UNSND (attr) = (cu->header.offset.sect_off
11693                          + read_8_bytes (abfd, info_ptr));
11694       info_ptr += 8;
11695       break;
11696     case DW_FORM_ref_sig8:
11697       /* Convert the signature to something we can record in DW_UNSND
11698          for later lookup.
11699          NOTE: This is NULL if the type wasn't found.  */
11700       DW_SIGNATURED_TYPE (attr) =
11701         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
11702       info_ptr += 8;
11703       break;
11704     case DW_FORM_ref_udata:
11705       DW_UNSND (attr) = (cu->header.offset.sect_off
11706                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
11707       info_ptr += bytes_read;
11708       break;
11709     case DW_FORM_indirect:
11710       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11711       info_ptr += bytes_read;
11712       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
11713       break;
11714     case DW_FORM_GNU_addr_index:
11715       if (reader->dwo_file == NULL)
11716         {
11717           /* For now flag a hard error.
11718              Later we can turn this into a complaint.  */
11719           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
11720                  dwarf_form_name (form),
11721                  bfd_get_filename (abfd));
11722         }
11723       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
11724       info_ptr += bytes_read;
11725       break;
11726     case DW_FORM_GNU_str_index:
11727       if (reader->dwo_file == NULL)
11728         {
11729           /* For now flag a hard error.
11730              Later we can turn this into a complaint if warranted.  */
11731           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
11732                  dwarf_form_name (form),
11733                  bfd_get_filename (abfd));
11734         }
11735       {
11736         ULONGEST str_index =
11737           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
11738
11739         DW_STRING (attr) = read_str_index (reader, cu, str_index);
11740         DW_STRING_IS_CANONICAL (attr) = 0;
11741         info_ptr += bytes_read;
11742       }
11743       break;
11744     default:
11745       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
11746              dwarf_form_name (form),
11747              bfd_get_filename (abfd));
11748     }
11749
11750   /* We have seen instances where the compiler tried to emit a byte
11751      size attribute of -1 which ended up being encoded as an unsigned
11752      0xffffffff.  Although 0xffffffff is technically a valid size value,
11753      an object of this size seems pretty unlikely so we can relatively
11754      safely treat these cases as if the size attribute was invalid and
11755      treat them as zero by default.  */
11756   if (attr->name == DW_AT_byte_size
11757       && form == DW_FORM_data4
11758       && DW_UNSND (attr) >= 0xffffffff)
11759     {
11760       complaint
11761         (&symfile_complaints,
11762          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
11763          hex_string (DW_UNSND (attr)));
11764       DW_UNSND (attr) = 0;
11765     }
11766
11767   return info_ptr;
11768 }
11769
11770 /* Read an attribute described by an abbreviated attribute.  */
11771
11772 static gdb_byte *
11773 read_attribute (const struct die_reader_specs *reader,
11774                 struct attribute *attr, struct attr_abbrev *abbrev,
11775                 gdb_byte *info_ptr)
11776 {
11777   attr->name = abbrev->name;
11778   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
11779 }
11780
11781 /* Read dwarf information from a buffer.  */
11782
11783 static unsigned int
11784 read_1_byte (bfd *abfd, gdb_byte *buf)
11785 {
11786   return bfd_get_8 (abfd, buf);
11787 }
11788
11789 static int
11790 read_1_signed_byte (bfd *abfd, gdb_byte *buf)
11791 {
11792   return bfd_get_signed_8 (abfd, buf);
11793 }
11794
11795 static unsigned int
11796 read_2_bytes (bfd *abfd, gdb_byte *buf)
11797 {
11798   return bfd_get_16 (abfd, buf);
11799 }
11800
11801 static int
11802 read_2_signed_bytes (bfd *abfd, gdb_byte *buf)
11803 {
11804   return bfd_get_signed_16 (abfd, buf);
11805 }
11806
11807 static unsigned int
11808 read_4_bytes (bfd *abfd, gdb_byte *buf)
11809 {
11810   return bfd_get_32 (abfd, buf);
11811 }
11812
11813 static int
11814 read_4_signed_bytes (bfd *abfd, gdb_byte *buf)
11815 {
11816   return bfd_get_signed_32 (abfd, buf);
11817 }
11818
11819 static ULONGEST
11820 read_8_bytes (bfd *abfd, gdb_byte *buf)
11821 {
11822   return bfd_get_64 (abfd, buf);
11823 }
11824
11825 static CORE_ADDR
11826 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
11827               unsigned int *bytes_read)
11828 {
11829   struct comp_unit_head *cu_header = &cu->header;
11830   CORE_ADDR retval = 0;
11831
11832   if (cu_header->signed_addr_p)
11833     {
11834       switch (cu_header->addr_size)
11835         {
11836         case 2:
11837           retval = bfd_get_signed_16 (abfd, buf);
11838           break;
11839         case 4:
11840           retval = bfd_get_signed_32 (abfd, buf);
11841           break;
11842         case 8:
11843           retval = bfd_get_signed_64 (abfd, buf);
11844           break;
11845         default:
11846           internal_error (__FILE__, __LINE__,
11847                           _("read_address: bad switch, signed [in module %s]"),
11848                           bfd_get_filename (abfd));
11849         }
11850     }
11851   else
11852     {
11853       switch (cu_header->addr_size)
11854         {
11855         case 2:
11856           retval = bfd_get_16 (abfd, buf);
11857           break;
11858         case 4:
11859           retval = bfd_get_32 (abfd, buf);
11860           break;
11861         case 8:
11862           retval = bfd_get_64 (abfd, buf);
11863           break;
11864         default:
11865           internal_error (__FILE__, __LINE__,
11866                           _("read_address: bad switch, "
11867                             "unsigned [in module %s]"),
11868                           bfd_get_filename (abfd));
11869         }
11870     }
11871
11872   *bytes_read = cu_header->addr_size;
11873   return retval;
11874 }
11875
11876 /* Read the initial length from a section.  The (draft) DWARF 3
11877    specification allows the initial length to take up either 4 bytes
11878    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
11879    bytes describe the length and all offsets will be 8 bytes in length
11880    instead of 4.
11881
11882    An older, non-standard 64-bit format is also handled by this
11883    function.  The older format in question stores the initial length
11884    as an 8-byte quantity without an escape value.  Lengths greater
11885    than 2^32 aren't very common which means that the initial 4 bytes
11886    is almost always zero.  Since a length value of zero doesn't make
11887    sense for the 32-bit format, this initial zero can be considered to
11888    be an escape value which indicates the presence of the older 64-bit
11889    format.  As written, the code can't detect (old format) lengths
11890    greater than 4GB.  If it becomes necessary to handle lengths
11891    somewhat larger than 4GB, we could allow other small values (such
11892    as the non-sensical values of 1, 2, and 3) to also be used as
11893    escape values indicating the presence of the old format.
11894
11895    The value returned via bytes_read should be used to increment the
11896    relevant pointer after calling read_initial_length().
11897
11898    [ Note:  read_initial_length() and read_offset() are based on the
11899      document entitled "DWARF Debugging Information Format", revision
11900      3, draft 8, dated November 19, 2001.  This document was obtained
11901      from:
11902
11903         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
11904
11905      This document is only a draft and is subject to change.  (So beware.)
11906
11907      Details regarding the older, non-standard 64-bit format were
11908      determined empirically by examining 64-bit ELF files produced by
11909      the SGI toolchain on an IRIX 6.5 machine.
11910
11911      - Kevin, July 16, 2002
11912    ] */
11913
11914 static LONGEST
11915 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
11916 {
11917   LONGEST length = bfd_get_32 (abfd, buf);
11918
11919   if (length == 0xffffffff)
11920     {
11921       length = bfd_get_64 (abfd, buf + 4);
11922       *bytes_read = 12;
11923     }
11924   else if (length == 0)
11925     {
11926       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
11927       length = bfd_get_64 (abfd, buf);
11928       *bytes_read = 8;
11929     }
11930   else
11931     {
11932       *bytes_read = 4;
11933     }
11934
11935   return length;
11936 }
11937
11938 /* Cover function for read_initial_length.
11939    Returns the length of the object at BUF, and stores the size of the
11940    initial length in *BYTES_READ and stores the size that offsets will be in
11941    *OFFSET_SIZE.
11942    If the initial length size is not equivalent to that specified in
11943    CU_HEADER then issue a complaint.
11944    This is useful when reading non-comp-unit headers.  */
11945
11946 static LONGEST
11947 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
11948                                         const struct comp_unit_head *cu_header,
11949                                         unsigned int *bytes_read,
11950                                         unsigned int *offset_size)
11951 {
11952   LONGEST length = read_initial_length (abfd, buf, bytes_read);
11953
11954   gdb_assert (cu_header->initial_length_size == 4
11955               || cu_header->initial_length_size == 8
11956               || cu_header->initial_length_size == 12);
11957
11958   if (cu_header->initial_length_size != *bytes_read)
11959     complaint (&symfile_complaints,
11960                _("intermixed 32-bit and 64-bit DWARF sections"));
11961
11962   *offset_size = (*bytes_read == 4) ? 4 : 8;
11963   return length;
11964 }
11965
11966 /* Read an offset from the data stream.  The size of the offset is
11967    given by cu_header->offset_size.  */
11968
11969 static LONGEST
11970 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
11971              unsigned int *bytes_read)
11972 {
11973   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
11974
11975   *bytes_read = cu_header->offset_size;
11976   return offset;
11977 }
11978
11979 /* Read an offset from the data stream.  */
11980
11981 static LONGEST
11982 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
11983 {
11984   LONGEST retval = 0;
11985
11986   switch (offset_size)
11987     {
11988     case 4:
11989       retval = bfd_get_32 (abfd, buf);
11990       break;
11991     case 8:
11992       retval = bfd_get_64 (abfd, buf);
11993       break;
11994     default:
11995       internal_error (__FILE__, __LINE__,
11996                       _("read_offset_1: bad switch [in module %s]"),
11997                       bfd_get_filename (abfd));
11998     }
11999
12000   return retval;
12001 }
12002
12003 static gdb_byte *
12004 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
12005 {
12006   /* If the size of a host char is 8 bits, we can return a pointer
12007      to the buffer, otherwise we have to copy the data to a buffer
12008      allocated on the temporary obstack.  */
12009   gdb_assert (HOST_CHAR_BIT == 8);
12010   return buf;
12011 }
12012
12013 static char *
12014 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
12015 {
12016   /* If the size of a host char is 8 bits, we can return a pointer
12017      to the string, otherwise we have to copy the string to a buffer
12018      allocated on the temporary obstack.  */
12019   gdb_assert (HOST_CHAR_BIT == 8);
12020   if (*buf == '\0')
12021     {
12022       *bytes_read_ptr = 1;
12023       return NULL;
12024     }
12025   *bytes_read_ptr = strlen ((char *) buf) + 1;
12026   return (char *) buf;
12027 }
12028
12029 static char *
12030 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
12031 {
12032   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
12033   if (dwarf2_per_objfile->str.buffer == NULL)
12034     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
12035            bfd_get_filename (abfd));
12036   if (str_offset >= dwarf2_per_objfile->str.size)
12037     error (_("DW_FORM_strp pointing outside of "
12038              ".debug_str section [in module %s]"),
12039            bfd_get_filename (abfd));
12040   gdb_assert (HOST_CHAR_BIT == 8);
12041   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
12042     return NULL;
12043   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
12044 }
12045
12046 static char *
12047 read_indirect_string (bfd *abfd, gdb_byte *buf,
12048                       const struct comp_unit_head *cu_header,
12049                       unsigned int *bytes_read_ptr)
12050 {
12051   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
12052
12053   return read_indirect_string_at_offset (abfd, str_offset);
12054 }
12055
12056 static ULONGEST
12057 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
12058 {
12059   ULONGEST result;
12060   unsigned int num_read;
12061   int i, shift;
12062   unsigned char byte;
12063
12064   result = 0;
12065   shift = 0;
12066   num_read = 0;
12067   i = 0;
12068   while (1)
12069     {
12070       byte = bfd_get_8 (abfd, buf);
12071       buf++;
12072       num_read++;
12073       result |= ((ULONGEST) (byte & 127) << shift);
12074       if ((byte & 128) == 0)
12075         {
12076           break;
12077         }
12078       shift += 7;
12079     }
12080   *bytes_read_ptr = num_read;
12081   return result;
12082 }
12083
12084 static LONGEST
12085 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
12086 {
12087   LONGEST result;
12088   int i, shift, num_read;
12089   unsigned char byte;
12090
12091   result = 0;
12092   shift = 0;
12093   num_read = 0;
12094   i = 0;
12095   while (1)
12096     {
12097       byte = bfd_get_8 (abfd, buf);
12098       buf++;
12099       num_read++;
12100       result |= ((LONGEST) (byte & 127) << shift);
12101       shift += 7;
12102       if ((byte & 128) == 0)
12103         {
12104           break;
12105         }
12106     }
12107   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
12108     result |= -(((LONGEST) 1) << shift);
12109   *bytes_read_ptr = num_read;
12110   return result;
12111 }
12112
12113 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
12114    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
12115    ADDR_SIZE is the size of addresses from the CU header.  */
12116
12117 static CORE_ADDR
12118 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
12119 {
12120   struct objfile *objfile = dwarf2_per_objfile->objfile;
12121   bfd *abfd = objfile->obfd;
12122   const gdb_byte *info_ptr;
12123
12124   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
12125   if (dwarf2_per_objfile->addr.buffer == NULL)
12126     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
12127            objfile->name);
12128   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
12129     error (_("DW_FORM_addr_index pointing outside of "
12130              ".debug_addr section [in module %s]"),
12131            objfile->name);
12132   info_ptr = (dwarf2_per_objfile->addr.buffer
12133               + addr_base + addr_index * addr_size);
12134   if (addr_size == 4)
12135     return bfd_get_32 (abfd, info_ptr);
12136   else
12137     return bfd_get_64 (abfd, info_ptr);
12138 }
12139
12140 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
12141
12142 static CORE_ADDR
12143 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
12144 {
12145   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
12146 }
12147
12148 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
12149
12150 static CORE_ADDR
12151 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
12152                              unsigned int *bytes_read)
12153 {
12154   bfd *abfd = cu->objfile->obfd;
12155   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
12156
12157   return read_addr_index (cu, addr_index);
12158 }
12159
12160 /* Data structure to pass results from dwarf2_read_addr_index_reader
12161    back to dwarf2_read_addr_index.  */
12162
12163 struct dwarf2_read_addr_index_data
12164 {
12165   ULONGEST addr_base;
12166   int addr_size;
12167 };
12168
12169 /* die_reader_func for dwarf2_read_addr_index.  */
12170
12171 static void
12172 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
12173                                gdb_byte *info_ptr,
12174                                struct die_info *comp_unit_die,
12175                                int has_children,
12176                                void *data)
12177 {
12178   struct dwarf2_cu *cu = reader->cu;
12179   struct dwarf2_read_addr_index_data *aidata =
12180     (struct dwarf2_read_addr_index_data *) data;
12181
12182   aidata->addr_base = cu->addr_base;
12183   aidata->addr_size = cu->header.addr_size;
12184 }
12185
12186 /* Given an index in .debug_addr, fetch the value.
12187    NOTE: This can be called during dwarf expression evaluation,
12188    long after the debug information has been read, and thus per_cu->cu
12189    may no longer exist.  */
12190
12191 CORE_ADDR
12192 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
12193                         unsigned int addr_index)
12194 {
12195   struct objfile *objfile = per_cu->objfile;
12196   struct dwarf2_cu *cu = per_cu->cu;
12197   ULONGEST addr_base;
12198   int addr_size;
12199
12200   /* This is intended to be called from outside this file.  */
12201   dw2_setup (objfile);
12202
12203   /* We need addr_base and addr_size.
12204      If we don't have PER_CU->cu, we have to get it.
12205      Nasty, but the alternative is storing the needed info in PER_CU,
12206      which at this point doesn't seem justified: it's not clear how frequently
12207      it would get used and it would increase the size of every PER_CU.
12208      Entry points like dwarf2_per_cu_addr_size do a similar thing
12209      so we're not in uncharted territory here.
12210      Alas we need to be a bit more complicated as addr_base is contained
12211      in the DIE.
12212
12213      We don't need to read the entire CU(/TU).
12214      We just need the header and top level die.
12215      IWBN to use the aging mechanism to let us lazily later discard the CU.
12216      See however init_cutu_and_read_dies_simple.  */
12217
12218   if (cu != NULL)
12219     {
12220       addr_base = cu->addr_base;
12221       addr_size = cu->header.addr_size;
12222     }
12223   else
12224     {
12225       struct dwarf2_read_addr_index_data aidata;
12226
12227       init_cutu_and_read_dies_simple (per_cu, dwarf2_read_addr_index_reader,
12228                                       &aidata);
12229       addr_base = aidata.addr_base;
12230       addr_size = aidata.addr_size;
12231     }
12232
12233   return read_addr_index_1 (addr_index, addr_base, addr_size);
12234 }
12235
12236 /* Given a DW_AT_str_index, fetch the string.  */
12237
12238 static char *
12239 read_str_index (const struct die_reader_specs *reader,
12240                 struct dwarf2_cu *cu, ULONGEST str_index)
12241 {
12242   struct objfile *objfile = dwarf2_per_objfile->objfile;
12243   const char *dwo_name = objfile->name;
12244   bfd *abfd = objfile->obfd;
12245   struct dwo_sections *sections = &reader->dwo_file->sections;
12246   gdb_byte *info_ptr;
12247   ULONGEST str_offset;
12248
12249   dwarf2_read_section (objfile, &sections->str);
12250   dwarf2_read_section (objfile, &sections->str_offsets);
12251   if (sections->str.buffer == NULL)
12252     error (_("DW_FORM_str_index used without .debug_str.dwo section"
12253              " in CU at offset 0x%lx [in module %s]"),
12254            (long) cu->header.offset.sect_off, dwo_name);
12255   if (sections->str_offsets.buffer == NULL)
12256     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
12257              " in CU at offset 0x%lx [in module %s]"),
12258            (long) cu->header.offset.sect_off, dwo_name);
12259   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
12260     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
12261              " section in CU at offset 0x%lx [in module %s]"),
12262            (long) cu->header.offset.sect_off, dwo_name);
12263   info_ptr = (sections->str_offsets.buffer
12264               + str_index * cu->header.offset_size);
12265   if (cu->header.offset_size == 4)
12266     str_offset = bfd_get_32 (abfd, info_ptr);
12267   else
12268     str_offset = bfd_get_64 (abfd, info_ptr);
12269   if (str_offset >= sections->str.size)
12270     error (_("Offset from DW_FORM_str_index pointing outside of"
12271              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
12272            (long) cu->header.offset.sect_off, dwo_name);
12273   return (char *) (sections->str.buffer + str_offset);
12274 }
12275
12276 /* Return a pointer to just past the end of an LEB128 number in BUF.  */
12277
12278 static gdb_byte *
12279 skip_leb128 (bfd *abfd, gdb_byte *buf)
12280 {
12281   int byte;
12282
12283   while (1)
12284     {
12285       byte = bfd_get_8 (abfd, buf);
12286       buf++;
12287       if ((byte & 128) == 0)
12288         return buf;
12289     }
12290 }
12291
12292 /* Return the length of an LEB128 number in BUF.  */
12293
12294 static int
12295 leb128_size (const gdb_byte *buf)
12296 {
12297   const gdb_byte *begin = buf;
12298   gdb_byte byte;
12299
12300   while (1)
12301     {
12302       byte = *buf++;
12303       if ((byte & 128) == 0)
12304         return buf - begin;
12305     }
12306 }
12307
12308 static void
12309 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
12310 {
12311   switch (lang)
12312     {
12313     case DW_LANG_C89:
12314     case DW_LANG_C99:
12315     case DW_LANG_C:
12316       cu->language = language_c;
12317       break;
12318     case DW_LANG_C_plus_plus:
12319       cu->language = language_cplus;
12320       break;
12321     case DW_LANG_D:
12322       cu->language = language_d;
12323       break;
12324     case DW_LANG_Fortran77:
12325     case DW_LANG_Fortran90:
12326     case DW_LANG_Fortran95:
12327       cu->language = language_fortran;
12328       break;
12329     case DW_LANG_Go:
12330       cu->language = language_go;
12331       break;
12332     case DW_LANG_Mips_Assembler:
12333       cu->language = language_asm;
12334       break;
12335     case DW_LANG_Java:
12336       cu->language = language_java;
12337       break;
12338     case DW_LANG_Ada83:
12339     case DW_LANG_Ada95:
12340       cu->language = language_ada;
12341       break;
12342     case DW_LANG_Modula2:
12343       cu->language = language_m2;
12344       break;
12345     case DW_LANG_Pascal83:
12346       cu->language = language_pascal;
12347       break;
12348     case DW_LANG_ObjC:
12349       cu->language = language_objc;
12350       break;
12351     case DW_LANG_Cobol74:
12352     case DW_LANG_Cobol85:
12353     default:
12354       cu->language = language_minimal;
12355       break;
12356     }
12357   cu->language_defn = language_def (cu->language);
12358 }
12359
12360 /* Return the named attribute or NULL if not there.  */
12361
12362 static struct attribute *
12363 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
12364 {
12365   for (;;)
12366     {
12367       unsigned int i;
12368       struct attribute *spec = NULL;
12369
12370       for (i = 0; i < die->num_attrs; ++i)
12371         {
12372           if (die->attrs[i].name == name)
12373             return &die->attrs[i];
12374           if (die->attrs[i].name == DW_AT_specification
12375               || die->attrs[i].name == DW_AT_abstract_origin)
12376             spec = &die->attrs[i];
12377         }
12378
12379       if (!spec)
12380         break;
12381
12382       die = follow_die_ref (die, spec, &cu);
12383     }
12384
12385   return NULL;
12386 }
12387
12388 /* Return the named attribute or NULL if not there,
12389    but do not follow DW_AT_specification, etc.
12390    This is for use in contexts where we're reading .debug_types dies.
12391    Following DW_AT_specification, DW_AT_abstract_origin will take us
12392    back up the chain, and we want to go down.  */
12393
12394 static struct attribute *
12395 dwarf2_attr_no_follow (struct die_info *die, unsigned int name,
12396                        struct dwarf2_cu *cu)
12397 {
12398   unsigned int i;
12399
12400   for (i = 0; i < die->num_attrs; ++i)
12401     if (die->attrs[i].name == name)
12402       return &die->attrs[i];
12403
12404   return NULL;
12405 }
12406
12407 /* Return non-zero iff the attribute NAME is defined for the given DIE,
12408    and holds a non-zero value.  This function should only be used for
12409    DW_FORM_flag or DW_FORM_flag_present attributes.  */
12410
12411 static int
12412 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
12413 {
12414   struct attribute *attr = dwarf2_attr (die, name, cu);
12415
12416   return (attr && DW_UNSND (attr));
12417 }
12418
12419 static int
12420 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
12421 {
12422   /* A DIE is a declaration if it has a DW_AT_declaration attribute
12423      which value is non-zero.  However, we have to be careful with
12424      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
12425      (via dwarf2_flag_true_p) follows this attribute.  So we may
12426      end up accidently finding a declaration attribute that belongs
12427      to a different DIE referenced by the specification attribute,
12428      even though the given DIE does not have a declaration attribute.  */
12429   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
12430           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
12431 }
12432
12433 /* Return the die giving the specification for DIE, if there is
12434    one.  *SPEC_CU is the CU containing DIE on input, and the CU
12435    containing the return value on output.  If there is no
12436    specification, but there is an abstract origin, that is
12437    returned.  */
12438
12439 static struct die_info *
12440 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
12441 {
12442   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
12443                                              *spec_cu);
12444
12445   if (spec_attr == NULL)
12446     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
12447
12448   if (spec_attr == NULL)
12449     return NULL;
12450   else
12451     return follow_die_ref (die, spec_attr, spec_cu);
12452 }
12453
12454 /* Free the line_header structure *LH, and any arrays and strings it
12455    refers to.
12456    NOTE: This is also used as a "cleanup" function.  */
12457
12458 static void
12459 free_line_header (struct line_header *lh)
12460 {
12461   if (lh->standard_opcode_lengths)
12462     xfree (lh->standard_opcode_lengths);
12463
12464   /* Remember that all the lh->file_names[i].name pointers are
12465      pointers into debug_line_buffer, and don't need to be freed.  */
12466   if (lh->file_names)
12467     xfree (lh->file_names);
12468
12469   /* Similarly for the include directory names.  */
12470   if (lh->include_dirs)
12471     xfree (lh->include_dirs);
12472
12473   xfree (lh);
12474 }
12475
12476 /* Add an entry to LH's include directory table.  */
12477
12478 static void
12479 add_include_dir (struct line_header *lh, char *include_dir)
12480 {
12481   /* Grow the array if necessary.  */
12482   if (lh->include_dirs_size == 0)
12483     {
12484       lh->include_dirs_size = 1; /* for testing */
12485       lh->include_dirs = xmalloc (lh->include_dirs_size
12486                                   * sizeof (*lh->include_dirs));
12487     }
12488   else if (lh->num_include_dirs >= lh->include_dirs_size)
12489     {
12490       lh->include_dirs_size *= 2;
12491       lh->include_dirs = xrealloc (lh->include_dirs,
12492                                    (lh->include_dirs_size
12493                                     * sizeof (*lh->include_dirs)));
12494     }
12495
12496   lh->include_dirs[lh->num_include_dirs++] = include_dir;
12497 }
12498
12499 /* Add an entry to LH's file name table.  */
12500
12501 static void
12502 add_file_name (struct line_header *lh,
12503                char *name,
12504                unsigned int dir_index,
12505                unsigned int mod_time,
12506                unsigned int length)
12507 {
12508   struct file_entry *fe;
12509
12510   /* Grow the array if necessary.  */
12511   if (lh->file_names_size == 0)
12512     {
12513       lh->file_names_size = 1; /* for testing */
12514       lh->file_names = xmalloc (lh->file_names_size
12515                                 * sizeof (*lh->file_names));
12516     }
12517   else if (lh->num_file_names >= lh->file_names_size)
12518     {
12519       lh->file_names_size *= 2;
12520       lh->file_names = xrealloc (lh->file_names,
12521                                  (lh->file_names_size
12522                                   * sizeof (*lh->file_names)));
12523     }
12524
12525   fe = &lh->file_names[lh->num_file_names++];
12526   fe->name = name;
12527   fe->dir_index = dir_index;
12528   fe->mod_time = mod_time;
12529   fe->length = length;
12530   fe->included_p = 0;
12531   fe->symtab = NULL;
12532 }
12533
12534 /* Read the statement program header starting at OFFSET in
12535    .debug_line, or .debug_line.dwo.  Return a pointer
12536    to a struct line_header, allocated using xmalloc.
12537
12538    NOTE: the strings in the include directory and file name tables of
12539    the returned object point into the dwarf line section buffer,
12540    and must not be freed.  */
12541
12542 static struct line_header *
12543 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
12544 {
12545   struct cleanup *back_to;
12546   struct line_header *lh;
12547   gdb_byte *line_ptr;
12548   unsigned int bytes_read, offset_size;
12549   int i;
12550   char *cur_dir, *cur_file;
12551   struct dwarf2_section_info *section;
12552   bfd *abfd;
12553
12554   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
12555      DWO file.  */
12556   if (cu->dwo_unit && cu->per_cu->is_debug_types)
12557     section = &cu->dwo_unit->dwo_file->sections.line;
12558   else
12559     section = &dwarf2_per_objfile->line;
12560
12561   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
12562   if (section->buffer == NULL)
12563     {
12564       if (cu->dwo_unit && cu->per_cu->is_debug_types)
12565         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
12566       else
12567         complaint (&symfile_complaints, _("missing .debug_line section"));
12568       return 0;
12569     }
12570
12571   /* We can't do this until we know the section is non-empty.
12572      Only then do we know we have such a section.  */
12573   abfd = section->asection->owner;
12574
12575   /* Make sure that at least there's room for the total_length field.
12576      That could be 12 bytes long, but we're just going to fudge that.  */
12577   if (offset + 4 >= section->size)
12578     {
12579       dwarf2_statement_list_fits_in_line_number_section_complaint ();
12580       return 0;
12581     }
12582
12583   lh = xmalloc (sizeof (*lh));
12584   memset (lh, 0, sizeof (*lh));
12585   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
12586                           (void *) lh);
12587
12588   line_ptr = section->buffer + offset;
12589
12590   /* Read in the header.  */
12591   lh->total_length =
12592     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
12593                                             &bytes_read, &offset_size);
12594   line_ptr += bytes_read;
12595   if (line_ptr + lh->total_length > (section->buffer + section->size))
12596     {
12597       dwarf2_statement_list_fits_in_line_number_section_complaint ();
12598       return 0;
12599     }
12600   lh->statement_program_end = line_ptr + lh->total_length;
12601   lh->version = read_2_bytes (abfd, line_ptr);
12602   line_ptr += 2;
12603   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
12604   line_ptr += offset_size;
12605   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
12606   line_ptr += 1;
12607   if (lh->version >= 4)
12608     {
12609       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
12610       line_ptr += 1;
12611     }
12612   else
12613     lh->maximum_ops_per_instruction = 1;
12614
12615   if (lh->maximum_ops_per_instruction == 0)
12616     {
12617       lh->maximum_ops_per_instruction = 1;
12618       complaint (&symfile_complaints,
12619                  _("invalid maximum_ops_per_instruction "
12620                    "in `.debug_line' section"));
12621     }
12622
12623   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
12624   line_ptr += 1;
12625   lh->line_base = read_1_signed_byte (abfd, line_ptr);
12626   line_ptr += 1;
12627   lh->line_range = read_1_byte (abfd, line_ptr);
12628   line_ptr += 1;
12629   lh->opcode_base = read_1_byte (abfd, line_ptr);
12630   line_ptr += 1;
12631   lh->standard_opcode_lengths
12632     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
12633
12634   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
12635   for (i = 1; i < lh->opcode_base; ++i)
12636     {
12637       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
12638       line_ptr += 1;
12639     }
12640
12641   /* Read directory table.  */
12642   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
12643     {
12644       line_ptr += bytes_read;
12645       add_include_dir (lh, cur_dir);
12646     }
12647   line_ptr += bytes_read;
12648
12649   /* Read file name table.  */
12650   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
12651     {
12652       unsigned int dir_index, mod_time, length;
12653
12654       line_ptr += bytes_read;
12655       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12656       line_ptr += bytes_read;
12657       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12658       line_ptr += bytes_read;
12659       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12660       line_ptr += bytes_read;
12661
12662       add_file_name (lh, cur_file, dir_index, mod_time, length);
12663     }
12664   line_ptr += bytes_read;
12665   lh->statement_program_start = line_ptr;
12666
12667   if (line_ptr > (section->buffer + section->size))
12668     complaint (&symfile_complaints,
12669                _("line number info header doesn't "
12670                  "fit in `.debug_line' section"));
12671
12672   discard_cleanups (back_to);
12673   return lh;
12674 }
12675
12676 /* Subroutine of dwarf_decode_lines to simplify it.
12677    Return the file name of the psymtab for included file FILE_INDEX
12678    in line header LH of PST.
12679    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
12680    If space for the result is malloc'd, it will be freed by a cleanup.
12681    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
12682
12683 static char *
12684 psymtab_include_file_name (const struct line_header *lh, int file_index,
12685                            const struct partial_symtab *pst,
12686                            const char *comp_dir)
12687 {
12688   const struct file_entry fe = lh->file_names [file_index];
12689   char *include_name = fe.name;
12690   char *include_name_to_compare = include_name;
12691   char *dir_name = NULL;
12692   const char *pst_filename;
12693   char *copied_name = NULL;
12694   int file_is_pst;
12695
12696   if (fe.dir_index)
12697     dir_name = lh->include_dirs[fe.dir_index - 1];
12698
12699   if (!IS_ABSOLUTE_PATH (include_name)
12700       && (dir_name != NULL || comp_dir != NULL))
12701     {
12702       /* Avoid creating a duplicate psymtab for PST.
12703          We do this by comparing INCLUDE_NAME and PST_FILENAME.
12704          Before we do the comparison, however, we need to account
12705          for DIR_NAME and COMP_DIR.
12706          First prepend dir_name (if non-NULL).  If we still don't
12707          have an absolute path prepend comp_dir (if non-NULL).
12708          However, the directory we record in the include-file's
12709          psymtab does not contain COMP_DIR (to match the
12710          corresponding symtab(s)).
12711
12712          Example:
12713
12714          bash$ cd /tmp
12715          bash$ gcc -g ./hello.c
12716          include_name = "hello.c"
12717          dir_name = "."
12718          DW_AT_comp_dir = comp_dir = "/tmp"
12719          DW_AT_name = "./hello.c"  */
12720
12721       if (dir_name != NULL)
12722         {
12723           include_name = concat (dir_name, SLASH_STRING,
12724                                  include_name, (char *)NULL);
12725           include_name_to_compare = include_name;
12726           make_cleanup (xfree, include_name);
12727         }
12728       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
12729         {
12730           include_name_to_compare = concat (comp_dir, SLASH_STRING,
12731                                             include_name, (char *)NULL);
12732         }
12733     }
12734
12735   pst_filename = pst->filename;
12736   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
12737     {
12738       copied_name = concat (pst->dirname, SLASH_STRING,
12739                             pst_filename, (char *)NULL);
12740       pst_filename = copied_name;
12741     }
12742
12743   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
12744
12745   if (include_name_to_compare != include_name)
12746     xfree (include_name_to_compare);
12747   if (copied_name != NULL)
12748     xfree (copied_name);
12749
12750   if (file_is_pst)
12751     return NULL;
12752   return include_name;
12753 }
12754
12755 /* Ignore this record_line request.  */
12756
12757 static void
12758 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
12759 {
12760   return;
12761 }
12762
12763 /* Subroutine of dwarf_decode_lines to simplify it.
12764    Process the line number information in LH.  */
12765
12766 static void
12767 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
12768                       struct dwarf2_cu *cu, struct partial_symtab *pst)
12769 {
12770   gdb_byte *line_ptr, *extended_end;
12771   gdb_byte *line_end;
12772   unsigned int bytes_read, extended_len;
12773   unsigned char op_code, extended_op, adj_opcode;
12774   CORE_ADDR baseaddr;
12775   struct objfile *objfile = cu->objfile;
12776   bfd *abfd = objfile->obfd;
12777   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12778   const int decode_for_pst_p = (pst != NULL);
12779   struct subfile *last_subfile = NULL;
12780   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
12781     = record_line;
12782
12783   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12784
12785   line_ptr = lh->statement_program_start;
12786   line_end = lh->statement_program_end;
12787
12788   /* Read the statement sequences until there's nothing left.  */
12789   while (line_ptr < line_end)
12790     {
12791       /* state machine registers  */
12792       CORE_ADDR address = 0;
12793       unsigned int file = 1;
12794       unsigned int line = 1;
12795       unsigned int column = 0;
12796       int is_stmt = lh->default_is_stmt;
12797       int basic_block = 0;
12798       int end_sequence = 0;
12799       CORE_ADDR addr;
12800       unsigned char op_index = 0;
12801
12802       if (!decode_for_pst_p && lh->num_file_names >= file)
12803         {
12804           /* Start a subfile for the current file of the state machine.  */
12805           /* lh->include_dirs and lh->file_names are 0-based, but the
12806              directory and file name numbers in the statement program
12807              are 1-based.  */
12808           struct file_entry *fe = &lh->file_names[file - 1];
12809           char *dir = NULL;
12810
12811           if (fe->dir_index)
12812             dir = lh->include_dirs[fe->dir_index - 1];
12813
12814           dwarf2_start_subfile (fe->name, dir, comp_dir);
12815         }
12816
12817       /* Decode the table.  */
12818       while (!end_sequence)
12819         {
12820           op_code = read_1_byte (abfd, line_ptr);
12821           line_ptr += 1;
12822           if (line_ptr > line_end)
12823             {
12824               dwarf2_debug_line_missing_end_sequence_complaint ();
12825               break;
12826             }
12827
12828           if (op_code >= lh->opcode_base)
12829             {
12830               /* Special operand.  */
12831               adj_opcode = op_code - lh->opcode_base;
12832               address += (((op_index + (adj_opcode / lh->line_range))
12833                            / lh->maximum_ops_per_instruction)
12834                           * lh->minimum_instruction_length);
12835               op_index = ((op_index + (adj_opcode / lh->line_range))
12836                           % lh->maximum_ops_per_instruction);
12837               line += lh->line_base + (adj_opcode % lh->line_range);
12838               if (lh->num_file_names < file || file == 0)
12839                 dwarf2_debug_line_missing_file_complaint ();
12840               /* For now we ignore lines not starting on an
12841                  instruction boundary.  */
12842               else if (op_index == 0)
12843                 {
12844                   lh->file_names[file - 1].included_p = 1;
12845                   if (!decode_for_pst_p && is_stmt)
12846                     {
12847                       if (last_subfile != current_subfile)
12848                         {
12849                           addr = gdbarch_addr_bits_remove (gdbarch, address);
12850                           if (last_subfile)
12851                             (*p_record_line) (last_subfile, 0, addr);
12852                           last_subfile = current_subfile;
12853                         }
12854                       /* Append row to matrix using current values.  */
12855                       addr = gdbarch_addr_bits_remove (gdbarch, address);
12856                       (*p_record_line) (current_subfile, line, addr);
12857                     }
12858                 }
12859               basic_block = 0;
12860             }
12861           else switch (op_code)
12862             {
12863             case DW_LNS_extended_op:
12864               extended_len = read_unsigned_leb128 (abfd, line_ptr,
12865                                                    &bytes_read);
12866               line_ptr += bytes_read;
12867               extended_end = line_ptr + extended_len;
12868               extended_op = read_1_byte (abfd, line_ptr);
12869               line_ptr += 1;
12870               switch (extended_op)
12871                 {
12872                 case DW_LNE_end_sequence:
12873                   p_record_line = record_line;
12874                   end_sequence = 1;
12875                   break;
12876                 case DW_LNE_set_address:
12877                   address = read_address (abfd, line_ptr, cu, &bytes_read);
12878
12879                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
12880                     {
12881                       /* This line table is for a function which has been
12882                          GCd by the linker.  Ignore it.  PR gdb/12528 */
12883
12884                       long line_offset
12885                         = line_ptr - dwarf2_per_objfile->line.buffer;
12886
12887                       complaint (&symfile_complaints,
12888                                  _(".debug_line address at offset 0x%lx is 0 "
12889                                    "[in module %s]"),
12890                                  line_offset, objfile->name);
12891                       p_record_line = noop_record_line;
12892                     }
12893
12894                   op_index = 0;
12895                   line_ptr += bytes_read;
12896                   address += baseaddr;
12897                   break;
12898                 case DW_LNE_define_file:
12899                   {
12900                     char *cur_file;
12901                     unsigned int dir_index, mod_time, length;
12902
12903                     cur_file = read_direct_string (abfd, line_ptr,
12904                                                    &bytes_read);
12905                     line_ptr += bytes_read;
12906                     dir_index =
12907                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12908                     line_ptr += bytes_read;
12909                     mod_time =
12910                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12911                     line_ptr += bytes_read;
12912                     length =
12913                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12914                     line_ptr += bytes_read;
12915                     add_file_name (lh, cur_file, dir_index, mod_time, length);
12916                   }
12917                   break;
12918                 case DW_LNE_set_discriminator:
12919                   /* The discriminator is not interesting to the debugger;
12920                      just ignore it.  */
12921                   line_ptr = extended_end;
12922                   break;
12923                 default:
12924                   complaint (&symfile_complaints,
12925                              _("mangled .debug_line section"));
12926                   return;
12927                 }
12928               /* Make sure that we parsed the extended op correctly.  If e.g.
12929                  we expected a different address size than the producer used,
12930                  we may have read the wrong number of bytes.  */
12931               if (line_ptr != extended_end)
12932                 {
12933                   complaint (&symfile_complaints,
12934                              _("mangled .debug_line section"));
12935                   return;
12936                 }
12937               break;
12938             case DW_LNS_copy:
12939               if (lh->num_file_names < file || file == 0)
12940                 dwarf2_debug_line_missing_file_complaint ();
12941               else
12942                 {
12943                   lh->file_names[file - 1].included_p = 1;
12944                   if (!decode_for_pst_p && is_stmt)
12945                     {
12946                       if (last_subfile != current_subfile)
12947                         {
12948                           addr = gdbarch_addr_bits_remove (gdbarch, address);
12949                           if (last_subfile)
12950                             (*p_record_line) (last_subfile, 0, addr);
12951                           last_subfile = current_subfile;
12952                         }
12953                       addr = gdbarch_addr_bits_remove (gdbarch, address);
12954                       (*p_record_line) (current_subfile, line, addr);
12955                     }
12956                 }
12957               basic_block = 0;
12958               break;
12959             case DW_LNS_advance_pc:
12960               {
12961                 CORE_ADDR adjust
12962                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12963
12964                 address += (((op_index + adjust)
12965                              / lh->maximum_ops_per_instruction)
12966                             * lh->minimum_instruction_length);
12967                 op_index = ((op_index + adjust)
12968                             % lh->maximum_ops_per_instruction);
12969                 line_ptr += bytes_read;
12970               }
12971               break;
12972             case DW_LNS_advance_line:
12973               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
12974               line_ptr += bytes_read;
12975               break;
12976             case DW_LNS_set_file:
12977               {
12978                 /* The arrays lh->include_dirs and lh->file_names are
12979                    0-based, but the directory and file name numbers in
12980                    the statement program are 1-based.  */
12981                 struct file_entry *fe;
12982                 char *dir = NULL;
12983
12984                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
12985                 line_ptr += bytes_read;
12986                 if (lh->num_file_names < file || file == 0)
12987                   dwarf2_debug_line_missing_file_complaint ();
12988                 else
12989                   {
12990                     fe = &lh->file_names[file - 1];
12991                     if (fe->dir_index)
12992                       dir = lh->include_dirs[fe->dir_index - 1];
12993                     if (!decode_for_pst_p)
12994                       {
12995                         last_subfile = current_subfile;
12996                         dwarf2_start_subfile (fe->name, dir, comp_dir);
12997                       }
12998                   }
12999               }
13000               break;
13001             case DW_LNS_set_column:
13002               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13003               line_ptr += bytes_read;
13004               break;
13005             case DW_LNS_negate_stmt:
13006               is_stmt = (!is_stmt);
13007               break;
13008             case DW_LNS_set_basic_block:
13009               basic_block = 1;
13010               break;
13011             /* Add to the address register of the state machine the
13012                address increment value corresponding to special opcode
13013                255.  I.e., this value is scaled by the minimum
13014                instruction length since special opcode 255 would have
13015                scaled the increment.  */
13016             case DW_LNS_const_add_pc:
13017               {
13018                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
13019
13020                 address += (((op_index + adjust)
13021                              / lh->maximum_ops_per_instruction)
13022                             * lh->minimum_instruction_length);
13023                 op_index = ((op_index + adjust)
13024                             % lh->maximum_ops_per_instruction);
13025               }
13026               break;
13027             case DW_LNS_fixed_advance_pc:
13028               address += read_2_bytes (abfd, line_ptr);
13029               op_index = 0;
13030               line_ptr += 2;
13031               break;
13032             default:
13033               {
13034                 /* Unknown standard opcode, ignore it.  */
13035                 int i;
13036
13037                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
13038                   {
13039                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
13040                     line_ptr += bytes_read;
13041                   }
13042               }
13043             }
13044         }
13045       if (lh->num_file_names < file || file == 0)
13046         dwarf2_debug_line_missing_file_complaint ();
13047       else
13048         {
13049           lh->file_names[file - 1].included_p = 1;
13050           if (!decode_for_pst_p)
13051             {
13052               addr = gdbarch_addr_bits_remove (gdbarch, address);
13053               (*p_record_line) (current_subfile, 0, addr);
13054             }
13055         }
13056     }
13057 }
13058
13059 /* Decode the Line Number Program (LNP) for the given line_header
13060    structure and CU.  The actual information extracted and the type
13061    of structures created from the LNP depends on the value of PST.
13062
13063    1. If PST is NULL, then this procedure uses the data from the program
13064       to create all necessary symbol tables, and their linetables.
13065
13066    2. If PST is not NULL, this procedure reads the program to determine
13067       the list of files included by the unit represented by PST, and
13068       builds all the associated partial symbol tables.
13069
13070    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
13071    It is used for relative paths in the line table.
13072    NOTE: When processing partial symtabs (pst != NULL),
13073    comp_dir == pst->dirname.
13074
13075    NOTE: It is important that psymtabs have the same file name (via strcmp)
13076    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
13077    symtab we don't use it in the name of the psymtabs we create.
13078    E.g. expand_line_sal requires this when finding psymtabs to expand.
13079    A good testcase for this is mb-inline.exp.  */
13080
13081 static void
13082 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
13083                     struct dwarf2_cu *cu, struct partial_symtab *pst,
13084                     int want_line_info)
13085 {
13086   struct objfile *objfile = cu->objfile;
13087   const int decode_for_pst_p = (pst != NULL);
13088   struct subfile *first_subfile = current_subfile;
13089
13090   if (want_line_info)
13091     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
13092
13093   if (decode_for_pst_p)
13094     {
13095       int file_index;
13096
13097       /* Now that we're done scanning the Line Header Program, we can
13098          create the psymtab of each included file.  */
13099       for (file_index = 0; file_index < lh->num_file_names; file_index++)
13100         if (lh->file_names[file_index].included_p == 1)
13101           {
13102             char *include_name =
13103               psymtab_include_file_name (lh, file_index, pst, comp_dir);
13104             if (include_name != NULL)
13105               dwarf2_create_include_psymtab (include_name, pst, objfile);
13106           }
13107     }
13108   else
13109     {
13110       /* Make sure a symtab is created for every file, even files
13111          which contain only variables (i.e. no code with associated
13112          line numbers).  */
13113       int i;
13114
13115       for (i = 0; i < lh->num_file_names; i++)
13116         {
13117           char *dir = NULL;
13118           struct file_entry *fe;
13119
13120           fe = &lh->file_names[i];
13121           if (fe->dir_index)
13122             dir = lh->include_dirs[fe->dir_index - 1];
13123           dwarf2_start_subfile (fe->name, dir, comp_dir);
13124
13125           /* Skip the main file; we don't need it, and it must be
13126              allocated last, so that it will show up before the
13127              non-primary symtabs in the objfile's symtab list.  */
13128           if (current_subfile == first_subfile)
13129             continue;
13130
13131           if (current_subfile->symtab == NULL)
13132             current_subfile->symtab = allocate_symtab (current_subfile->name,
13133                                                        objfile);
13134           fe->symtab = current_subfile->symtab;
13135         }
13136     }
13137 }
13138
13139 /* Start a subfile for DWARF.  FILENAME is the name of the file and
13140    DIRNAME the name of the source directory which contains FILENAME
13141    or NULL if not known.  COMP_DIR is the compilation directory for the
13142    linetable's compilation unit or NULL if not known.
13143    This routine tries to keep line numbers from identical absolute and
13144    relative file names in a common subfile.
13145
13146    Using the `list' example from the GDB testsuite, which resides in
13147    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
13148    of /srcdir/list0.c yields the following debugging information for list0.c:
13149
13150    DW_AT_name:          /srcdir/list0.c
13151    DW_AT_comp_dir:              /compdir
13152    files.files[0].name: list0.h
13153    files.files[0].dir:  /srcdir
13154    files.files[1].name: list0.c
13155    files.files[1].dir:  /srcdir
13156
13157    The line number information for list0.c has to end up in a single
13158    subfile, so that `break /srcdir/list0.c:1' works as expected.
13159    start_subfile will ensure that this happens provided that we pass the
13160    concatenation of files.files[1].dir and files.files[1].name as the
13161    subfile's name.  */
13162
13163 static void
13164 dwarf2_start_subfile (char *filename, const char *dirname,
13165                       const char *comp_dir)
13166 {
13167   char *fullname;
13168
13169   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
13170      `start_symtab' will always pass the contents of DW_AT_comp_dir as
13171      second argument to start_subfile.  To be consistent, we do the
13172      same here.  In order not to lose the line information directory,
13173      we concatenate it to the filename when it makes sense.
13174      Note that the Dwarf3 standard says (speaking of filenames in line
13175      information): ``The directory index is ignored for file names
13176      that represent full path names''.  Thus ignoring dirname in the
13177      `else' branch below isn't an issue.  */
13178
13179   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
13180     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
13181   else
13182     fullname = filename;
13183
13184   start_subfile (fullname, comp_dir);
13185
13186   if (fullname != filename)
13187     xfree (fullname);
13188 }
13189
13190 static void
13191 var_decode_location (struct attribute *attr, struct symbol *sym,
13192                      struct dwarf2_cu *cu)
13193 {
13194   struct objfile *objfile = cu->objfile;
13195   struct comp_unit_head *cu_header = &cu->header;
13196
13197   /* NOTE drow/2003-01-30: There used to be a comment and some special
13198      code here to turn a symbol with DW_AT_external and a
13199      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
13200      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
13201      with some versions of binutils) where shared libraries could have
13202      relocations against symbols in their debug information - the
13203      minimal symbol would have the right address, but the debug info
13204      would not.  It's no longer necessary, because we will explicitly
13205      apply relocations when we read in the debug information now.  */
13206
13207   /* A DW_AT_location attribute with no contents indicates that a
13208      variable has been optimized away.  */
13209   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
13210     {
13211       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
13212       return;
13213     }
13214
13215   /* Handle one degenerate form of location expression specially, to
13216      preserve GDB's previous behavior when section offsets are
13217      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
13218      then mark this symbol as LOC_STATIC.  */
13219
13220   if (attr_form_is_block (attr)
13221       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
13222            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
13223           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
13224               && (DW_BLOCK (attr)->size
13225                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
13226     {
13227       unsigned int dummy;
13228
13229       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
13230         SYMBOL_VALUE_ADDRESS (sym) =
13231           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
13232       else
13233         SYMBOL_VALUE_ADDRESS (sym) =
13234           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
13235       SYMBOL_CLASS (sym) = LOC_STATIC;
13236       fixup_symbol_section (sym, objfile);
13237       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
13238                                               SYMBOL_SECTION (sym));
13239       return;
13240     }
13241
13242   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
13243      expression evaluator, and use LOC_COMPUTED only when necessary
13244      (i.e. when the value of a register or memory location is
13245      referenced, or a thread-local block, etc.).  Then again, it might
13246      not be worthwhile.  I'm assuming that it isn't unless performance
13247      or memory numbers show me otherwise.  */
13248
13249   dwarf2_symbol_mark_computed (attr, sym, cu);
13250   SYMBOL_CLASS (sym) = LOC_COMPUTED;
13251
13252   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
13253     cu->has_loclist = 1;
13254 }
13255
13256 /* Given a pointer to a DWARF information entry, figure out if we need
13257    to make a symbol table entry for it, and if so, create a new entry
13258    and return a pointer to it.
13259    If TYPE is NULL, determine symbol type from the die, otherwise
13260    used the passed type.
13261    If SPACE is not NULL, use it to hold the new symbol.  If it is
13262    NULL, allocate a new symbol on the objfile's obstack.  */
13263
13264 static struct symbol *
13265 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
13266                  struct symbol *space)
13267 {
13268   struct objfile *objfile = cu->objfile;
13269   struct symbol *sym = NULL;
13270   char *name;
13271   struct attribute *attr = NULL;
13272   struct attribute *attr2 = NULL;
13273   CORE_ADDR baseaddr;
13274   struct pending **list_to_add = NULL;
13275
13276   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13277
13278   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13279
13280   name = dwarf2_name (die, cu);
13281   if (name)
13282     {
13283       const char *linkagename;
13284       int suppress_add = 0;
13285
13286       if (space)
13287         sym = space;
13288       else
13289         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
13290       OBJSTAT (objfile, n_syms++);
13291
13292       /* Cache this symbol's name and the name's demangled form (if any).  */
13293       SYMBOL_SET_LANGUAGE (sym, cu->language);
13294       linkagename = dwarf2_physname (name, die, cu);
13295       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
13296
13297       /* Fortran does not have mangling standard and the mangling does differ
13298          between gfortran, iFort etc.  */
13299       if (cu->language == language_fortran
13300           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
13301         symbol_set_demangled_name (&(sym->ginfo),
13302                                    (char *) dwarf2_full_name (name, die, cu),
13303                                    NULL);
13304
13305       /* Default assumptions.
13306          Use the passed type or decode it from the die.  */
13307       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
13308       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
13309       if (type != NULL)
13310         SYMBOL_TYPE (sym) = type;
13311       else
13312         SYMBOL_TYPE (sym) = die_type (die, cu);
13313       attr = dwarf2_attr (die,
13314                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
13315                           cu);
13316       if (attr)
13317         {
13318           SYMBOL_LINE (sym) = DW_UNSND (attr);
13319         }
13320
13321       attr = dwarf2_attr (die,
13322                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
13323                           cu);
13324       if (attr)
13325         {
13326           int file_index = DW_UNSND (attr);
13327
13328           if (cu->line_header == NULL
13329               || file_index > cu->line_header->num_file_names)
13330             complaint (&symfile_complaints,
13331                        _("file index out of range"));
13332           else if (file_index > 0)
13333             {
13334               struct file_entry *fe;
13335
13336               fe = &cu->line_header->file_names[file_index - 1];
13337               SYMBOL_SYMTAB (sym) = fe->symtab;
13338             }
13339         }
13340
13341       switch (die->tag)
13342         {
13343         case DW_TAG_label:
13344           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13345           if (attr)
13346             {
13347               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
13348             }
13349           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
13350           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
13351           SYMBOL_CLASS (sym) = LOC_LABEL;
13352           add_symbol_to_list (sym, cu->list_in_scope);
13353           break;
13354         case DW_TAG_subprogram:
13355           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
13356              finish_block.  */
13357           SYMBOL_CLASS (sym) = LOC_BLOCK;
13358           attr2 = dwarf2_attr (die, DW_AT_external, cu);
13359           if ((attr2 && (DW_UNSND (attr2) != 0))
13360               || cu->language == language_ada)
13361             {
13362               /* Subprograms marked external are stored as a global symbol.
13363                  Ada subprograms, whether marked external or not, are always
13364                  stored as a global symbol, because we want to be able to
13365                  access them globally.  For instance, we want to be able
13366                  to break on a nested subprogram without having to
13367                  specify the context.  */
13368               list_to_add = &global_symbols;
13369             }
13370           else
13371             {
13372               list_to_add = cu->list_in_scope;
13373             }
13374           break;
13375         case DW_TAG_inlined_subroutine:
13376           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
13377              finish_block.  */
13378           SYMBOL_CLASS (sym) = LOC_BLOCK;
13379           SYMBOL_INLINED (sym) = 1;
13380           list_to_add = cu->list_in_scope;
13381           break;
13382         case DW_TAG_template_value_param:
13383           suppress_add = 1;
13384           /* Fall through.  */
13385         case DW_TAG_constant:
13386         case DW_TAG_variable:
13387         case DW_TAG_member:
13388           /* Compilation with minimal debug info may result in
13389              variables with missing type entries.  Change the
13390              misleading `void' type to something sensible.  */
13391           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
13392             SYMBOL_TYPE (sym)
13393               = objfile_type (objfile)->nodebug_data_symbol;
13394
13395           attr = dwarf2_attr (die, DW_AT_const_value, cu);
13396           /* In the case of DW_TAG_member, we should only be called for
13397              static const members.  */
13398           if (die->tag == DW_TAG_member)
13399             {
13400               /* dwarf2_add_field uses die_is_declaration,
13401                  so we do the same.  */
13402               gdb_assert (die_is_declaration (die, cu));
13403               gdb_assert (attr);
13404             }
13405           if (attr)
13406             {
13407               dwarf2_const_value (attr, sym, cu);
13408               attr2 = dwarf2_attr (die, DW_AT_external, cu);
13409               if (!suppress_add)
13410                 {
13411                   if (attr2 && (DW_UNSND (attr2) != 0))
13412                     list_to_add = &global_symbols;
13413                   else
13414                     list_to_add = cu->list_in_scope;
13415                 }
13416               break;
13417             }
13418           attr = dwarf2_attr (die, DW_AT_location, cu);
13419           if (attr)
13420             {
13421               var_decode_location (attr, sym, cu);
13422               attr2 = dwarf2_attr (die, DW_AT_external, cu);
13423               if (SYMBOL_CLASS (sym) == LOC_STATIC
13424                   && SYMBOL_VALUE_ADDRESS (sym) == 0
13425                   && !dwarf2_per_objfile->has_section_at_zero)
13426                 {
13427                   /* When a static variable is eliminated by the linker,
13428                      the corresponding debug information is not stripped
13429                      out, but the variable address is set to null;
13430                      do not add such variables into symbol table.  */
13431                 }
13432               else if (attr2 && (DW_UNSND (attr2) != 0))
13433                 {
13434                   /* Workaround gfortran PR debug/40040 - it uses
13435                      DW_AT_location for variables in -fPIC libraries which may
13436                      get overriden by other libraries/executable and get
13437                      a different address.  Resolve it by the minimal symbol
13438                      which may come from inferior's executable using copy
13439                      relocation.  Make this workaround only for gfortran as for
13440                      other compilers GDB cannot guess the minimal symbol
13441                      Fortran mangling kind.  */
13442                   if (cu->language == language_fortran && die->parent
13443                       && die->parent->tag == DW_TAG_module
13444                       && cu->producer
13445                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
13446                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
13447
13448                   /* A variable with DW_AT_external is never static,
13449                      but it may be block-scoped.  */
13450                   list_to_add = (cu->list_in_scope == &file_symbols
13451                                  ? &global_symbols : cu->list_in_scope);
13452                 }
13453               else
13454                 list_to_add = cu->list_in_scope;
13455             }
13456           else
13457             {
13458               /* We do not know the address of this symbol.
13459                  If it is an external symbol and we have type information
13460                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
13461                  The address of the variable will then be determined from
13462                  the minimal symbol table whenever the variable is
13463                  referenced.  */
13464               attr2 = dwarf2_attr (die, DW_AT_external, cu);
13465               if (attr2 && (DW_UNSND (attr2) != 0)
13466                   && dwarf2_attr (die, DW_AT_type, cu) != NULL)
13467                 {
13468                   /* A variable with DW_AT_external is never static, but it
13469                      may be block-scoped.  */
13470                   list_to_add = (cu->list_in_scope == &file_symbols
13471                                  ? &global_symbols : cu->list_in_scope);
13472
13473                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
13474                 }
13475               else if (!die_is_declaration (die, cu))
13476                 {
13477                   /* Use the default LOC_OPTIMIZED_OUT class.  */
13478                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
13479                   if (!suppress_add)
13480                     list_to_add = cu->list_in_scope;
13481                 }
13482             }
13483           break;
13484         case DW_TAG_formal_parameter:
13485           /* If we are inside a function, mark this as an argument.  If
13486              not, we might be looking at an argument to an inlined function
13487              when we do not have enough information to show inlined frames;
13488              pretend it's a local variable in that case so that the user can
13489              still see it.  */
13490           if (context_stack_depth > 0
13491               && context_stack[context_stack_depth - 1].name != NULL)
13492             SYMBOL_IS_ARGUMENT (sym) = 1;
13493           attr = dwarf2_attr (die, DW_AT_location, cu);
13494           if (attr)
13495             {
13496               var_decode_location (attr, sym, cu);
13497             }
13498           attr = dwarf2_attr (die, DW_AT_const_value, cu);
13499           if (attr)
13500             {
13501               dwarf2_const_value (attr, sym, cu);
13502             }
13503
13504           list_to_add = cu->list_in_scope;
13505           break;
13506         case DW_TAG_unspecified_parameters:
13507           /* From varargs functions; gdb doesn't seem to have any
13508              interest in this information, so just ignore it for now.
13509              (FIXME?) */
13510           break;
13511         case DW_TAG_template_type_param:
13512           suppress_add = 1;
13513           /* Fall through.  */
13514         case DW_TAG_class_type:
13515         case DW_TAG_interface_type:
13516         case DW_TAG_structure_type:
13517         case DW_TAG_union_type:
13518         case DW_TAG_set_type:
13519         case DW_TAG_enumeration_type:
13520           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13521           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
13522
13523           {
13524             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
13525                really ever be static objects: otherwise, if you try
13526                to, say, break of a class's method and you're in a file
13527                which doesn't mention that class, it won't work unless
13528                the check for all static symbols in lookup_symbol_aux
13529                saves you.  See the OtherFileClass tests in
13530                gdb.c++/namespace.exp.  */
13531
13532             if (!suppress_add)
13533               {
13534                 list_to_add = (cu->list_in_scope == &file_symbols
13535                                && (cu->language == language_cplus
13536                                    || cu->language == language_java)
13537                                ? &global_symbols : cu->list_in_scope);
13538
13539                 /* The semantics of C++ state that "struct foo {
13540                    ... }" also defines a typedef for "foo".  A Java
13541                    class declaration also defines a typedef for the
13542                    class.  */
13543                 if (cu->language == language_cplus
13544                     || cu->language == language_java
13545                     || cu->language == language_ada)
13546                   {
13547                     /* The symbol's name is already allocated along
13548                        with this objfile, so we don't need to
13549                        duplicate it for the type.  */
13550                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
13551                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
13552                   }
13553               }
13554           }
13555           break;
13556         case DW_TAG_typedef:
13557           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13558           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
13559           list_to_add = cu->list_in_scope;
13560           break;
13561         case DW_TAG_base_type:
13562         case DW_TAG_subrange_type:
13563           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13564           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
13565           list_to_add = cu->list_in_scope;
13566           break;
13567         case DW_TAG_enumerator:
13568           attr = dwarf2_attr (die, DW_AT_const_value, cu);
13569           if (attr)
13570             {
13571               dwarf2_const_value (attr, sym, cu);
13572             }
13573           {
13574             /* NOTE: carlton/2003-11-10: See comment above in the
13575                DW_TAG_class_type, etc. block.  */
13576
13577             list_to_add = (cu->list_in_scope == &file_symbols
13578                            && (cu->language == language_cplus
13579                                || cu->language == language_java)
13580                            ? &global_symbols : cu->list_in_scope);
13581           }
13582           break;
13583         case DW_TAG_namespace:
13584           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
13585           list_to_add = &global_symbols;
13586           break;
13587         default:
13588           /* Not a tag we recognize.  Hopefully we aren't processing
13589              trash data, but since we must specifically ignore things
13590              we don't recognize, there is nothing else we should do at
13591              this point.  */
13592           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
13593                      dwarf_tag_name (die->tag));
13594           break;
13595         }
13596
13597       if (suppress_add)
13598         {
13599           sym->hash_next = objfile->template_symbols;
13600           objfile->template_symbols = sym;
13601           list_to_add = NULL;
13602         }
13603
13604       if (list_to_add != NULL)
13605         add_symbol_to_list (sym, list_to_add);
13606
13607       /* For the benefit of old versions of GCC, check for anonymous
13608          namespaces based on the demangled name.  */
13609       if (!processing_has_namespace_info
13610           && cu->language == language_cplus)
13611         cp_scan_for_anonymous_namespaces (sym, objfile);
13612     }
13613   return (sym);
13614 }
13615
13616 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
13617
13618 static struct symbol *
13619 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
13620 {
13621   return new_symbol_full (die, type, cu, NULL);
13622 }
13623
13624 /* Given an attr with a DW_FORM_dataN value in host byte order,
13625    zero-extend it as appropriate for the symbol's type.  The DWARF
13626    standard (v4) is not entirely clear about the meaning of using
13627    DW_FORM_dataN for a constant with a signed type, where the type is
13628    wider than the data.  The conclusion of a discussion on the DWARF
13629    list was that this is unspecified.  We choose to always zero-extend
13630    because that is the interpretation long in use by GCC.  */
13631
13632 static gdb_byte *
13633 dwarf2_const_value_data (struct attribute *attr, struct type *type,
13634                          const char *name, struct obstack *obstack,
13635                          struct dwarf2_cu *cu, LONGEST *value, int bits)
13636 {
13637   struct objfile *objfile = cu->objfile;
13638   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
13639                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
13640   LONGEST l = DW_UNSND (attr);
13641
13642   if (bits < sizeof (*value) * 8)
13643     {
13644       l &= ((LONGEST) 1 << bits) - 1;
13645       *value = l;
13646     }
13647   else if (bits == sizeof (*value) * 8)
13648     *value = l;
13649   else
13650     {
13651       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
13652       store_unsigned_integer (bytes, bits / 8, byte_order, l);
13653       return bytes;
13654     }
13655
13656   return NULL;
13657 }
13658
13659 /* Read a constant value from an attribute.  Either set *VALUE, or if
13660    the value does not fit in *VALUE, set *BYTES - either already
13661    allocated on the objfile obstack, or newly allocated on OBSTACK,
13662    or, set *BATON, if we translated the constant to a location
13663    expression.  */
13664
13665 static void
13666 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
13667                          const char *name, struct obstack *obstack,
13668                          struct dwarf2_cu *cu,
13669                          LONGEST *value, gdb_byte **bytes,
13670                          struct dwarf2_locexpr_baton **baton)
13671 {
13672   struct objfile *objfile = cu->objfile;
13673   struct comp_unit_head *cu_header = &cu->header;
13674   struct dwarf_block *blk;
13675   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
13676                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
13677
13678   *value = 0;
13679   *bytes = NULL;
13680   *baton = NULL;
13681
13682   switch (attr->form)
13683     {
13684     case DW_FORM_addr:
13685     case DW_FORM_GNU_addr_index:
13686       {
13687         gdb_byte *data;
13688
13689         if (TYPE_LENGTH (type) != cu_header->addr_size)
13690           dwarf2_const_value_length_mismatch_complaint (name,
13691                                                         cu_header->addr_size,
13692                                                         TYPE_LENGTH (type));
13693         /* Symbols of this form are reasonably rare, so we just
13694            piggyback on the existing location code rather than writing
13695            a new implementation of symbol_computed_ops.  */
13696         *baton = obstack_alloc (&objfile->objfile_obstack,
13697                                 sizeof (struct dwarf2_locexpr_baton));
13698         (*baton)->per_cu = cu->per_cu;
13699         gdb_assert ((*baton)->per_cu);
13700
13701         (*baton)->size = 2 + cu_header->addr_size;
13702         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
13703         (*baton)->data = data;
13704
13705         data[0] = DW_OP_addr;
13706         store_unsigned_integer (&data[1], cu_header->addr_size,
13707                                 byte_order, DW_ADDR (attr));
13708         data[cu_header->addr_size + 1] = DW_OP_stack_value;
13709       }
13710       break;
13711     case DW_FORM_string:
13712     case DW_FORM_strp:
13713     case DW_FORM_GNU_str_index:
13714       /* DW_STRING is already allocated on the objfile obstack, point
13715          directly to it.  */
13716       *bytes = (gdb_byte *) DW_STRING (attr);
13717       break;
13718     case DW_FORM_block1:
13719     case DW_FORM_block2:
13720     case DW_FORM_block4:
13721     case DW_FORM_block:
13722     case DW_FORM_exprloc:
13723       blk = DW_BLOCK (attr);
13724       if (TYPE_LENGTH (type) != blk->size)
13725         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
13726                                                       TYPE_LENGTH (type));
13727       *bytes = blk->data;
13728       break;
13729
13730       /* The DW_AT_const_value attributes are supposed to carry the
13731          symbol's value "represented as it would be on the target
13732          architecture."  By the time we get here, it's already been
13733          converted to host endianness, so we just need to sign- or
13734          zero-extend it as appropriate.  */
13735     case DW_FORM_data1:
13736       *bytes = dwarf2_const_value_data (attr, type, name,
13737                                         obstack, cu, value, 8);
13738       break;
13739     case DW_FORM_data2:
13740       *bytes = dwarf2_const_value_data (attr, type, name,
13741                                         obstack, cu, value, 16);
13742       break;
13743     case DW_FORM_data4:
13744       *bytes = dwarf2_const_value_data (attr, type, name,
13745                                         obstack, cu, value, 32);
13746       break;
13747     case DW_FORM_data8:
13748       *bytes = dwarf2_const_value_data (attr, type, name,
13749                                         obstack, cu, value, 64);
13750       break;
13751
13752     case DW_FORM_sdata:
13753       *value = DW_SND (attr);
13754       break;
13755
13756     case DW_FORM_udata:
13757       *value = DW_UNSND (attr);
13758       break;
13759
13760     default:
13761       complaint (&symfile_complaints,
13762                  _("unsupported const value attribute form: '%s'"),
13763                  dwarf_form_name (attr->form));
13764       *value = 0;
13765       break;
13766     }
13767 }
13768
13769
13770 /* Copy constant value from an attribute to a symbol.  */
13771
13772 static void
13773 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
13774                     struct dwarf2_cu *cu)
13775 {
13776   struct objfile *objfile = cu->objfile;
13777   struct comp_unit_head *cu_header = &cu->header;
13778   LONGEST value;
13779   gdb_byte *bytes;
13780   struct dwarf2_locexpr_baton *baton;
13781
13782   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
13783                            SYMBOL_PRINT_NAME (sym),
13784                            &objfile->objfile_obstack, cu,
13785                            &value, &bytes, &baton);
13786
13787   if (baton != NULL)
13788     {
13789       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
13790       SYMBOL_LOCATION_BATON (sym) = baton;
13791       SYMBOL_CLASS (sym) = LOC_COMPUTED;
13792     }
13793   else if (bytes != NULL)
13794      {
13795       SYMBOL_VALUE_BYTES (sym) = bytes;
13796       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
13797     }
13798   else
13799     {
13800       SYMBOL_VALUE (sym) = value;
13801       SYMBOL_CLASS (sym) = LOC_CONST;
13802     }
13803 }
13804
13805 /* Return the type of the die in question using its DW_AT_type attribute.  */
13806
13807 static struct type *
13808 die_type (struct die_info *die, struct dwarf2_cu *cu)
13809 {
13810   struct attribute *type_attr;
13811
13812   type_attr = dwarf2_attr (die, DW_AT_type, cu);
13813   if (!type_attr)
13814     {
13815       /* A missing DW_AT_type represents a void type.  */
13816       return objfile_type (cu->objfile)->builtin_void;
13817     }
13818
13819   return lookup_die_type (die, type_attr, cu);
13820 }
13821
13822 /* True iff CU's producer generates GNAT Ada auxiliary information
13823    that allows to find parallel types through that information instead
13824    of having to do expensive parallel lookups by type name.  */
13825
13826 static int
13827 need_gnat_info (struct dwarf2_cu *cu)
13828 {
13829   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
13830      of GNAT produces this auxiliary information, without any indication
13831      that it is produced.  Part of enhancing the FSF version of GNAT
13832      to produce that information will be to put in place an indicator
13833      that we can use in order to determine whether the descriptive type
13834      info is available or not.  One suggestion that has been made is
13835      to use a new attribute, attached to the CU die.  For now, assume
13836      that the descriptive type info is not available.  */
13837   return 0;
13838 }
13839
13840 /* Return the auxiliary type of the die in question using its
13841    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
13842    attribute is not present.  */
13843
13844 static struct type *
13845 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
13846 {
13847   struct attribute *type_attr;
13848
13849   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
13850   if (!type_attr)
13851     return NULL;
13852
13853   return lookup_die_type (die, type_attr, cu);
13854 }
13855
13856 /* If DIE has a descriptive_type attribute, then set the TYPE's
13857    descriptive type accordingly.  */
13858
13859 static void
13860 set_descriptive_type (struct type *type, struct die_info *die,
13861                       struct dwarf2_cu *cu)
13862 {
13863   struct type *descriptive_type = die_descriptive_type (die, cu);
13864
13865   if (descriptive_type)
13866     {
13867       ALLOCATE_GNAT_AUX_TYPE (type);
13868       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
13869     }
13870 }
13871
13872 /* Return the containing type of the die in question using its
13873    DW_AT_containing_type attribute.  */
13874
13875 static struct type *
13876 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13877 {
13878   struct attribute *type_attr;
13879
13880   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
13881   if (!type_attr)
13882     error (_("Dwarf Error: Problem turning containing type into gdb type "
13883              "[in module %s]"), cu->objfile->name);
13884
13885   return lookup_die_type (die, type_attr, cu);
13886 }
13887
13888 /* Look up the type of DIE in CU using its type attribute ATTR.
13889    If there is no type substitute an error marker.  */
13890
13891 static struct type *
13892 lookup_die_type (struct die_info *die, struct attribute *attr,
13893                  struct dwarf2_cu *cu)
13894 {
13895   struct objfile *objfile = cu->objfile;
13896   struct type *this_type;
13897
13898   /* First see if we have it cached.  */
13899
13900   if (is_ref_attr (attr))
13901     {
13902       sect_offset offset = dwarf2_get_ref_die_offset (attr);
13903
13904       this_type = get_die_type_at_offset (offset, cu->per_cu);
13905     }
13906   else if (attr->form == DW_FORM_ref_sig8)
13907     {
13908       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
13909
13910       /* sig_type will be NULL if the signatured type is missing from
13911          the debug info.  */
13912       if (sig_type == NULL)
13913         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
13914                  "at 0x%x [in module %s]"),
13915                die->offset.sect_off, objfile->name);
13916
13917       gdb_assert (sig_type->per_cu.is_debug_types);
13918       /* If we haven't filled in type_offset_in_section yet, then we
13919          haven't read the type in yet.  */
13920       this_type = NULL;
13921       if (sig_type->type_offset_in_section.sect_off != 0)
13922         {
13923           this_type =
13924             get_die_type_at_offset (sig_type->type_offset_in_section,
13925                                     &sig_type->per_cu);
13926         }
13927     }
13928   else
13929     {
13930       dump_die_for_error (die);
13931       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
13932              dwarf_attr_name (attr->name), objfile->name);
13933     }
13934
13935   /* If not cached we need to read it in.  */
13936
13937   if (this_type == NULL)
13938     {
13939       struct die_info *type_die;
13940       struct dwarf2_cu *type_cu = cu;
13941
13942       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
13943       /* If we found the type now, it's probably because the type came
13944          from an inter-CU reference and the type's CU got expanded before
13945          ours.  */
13946       this_type = get_die_type (type_die, type_cu);
13947       if (this_type == NULL)
13948         this_type = read_type_die_1 (type_die, type_cu);
13949     }
13950
13951   /* If we still don't have a type use an error marker.  */
13952
13953   if (this_type == NULL)
13954     {
13955       char *message, *saved;
13956
13957       /* read_type_die already issued a complaint.  */
13958       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
13959                             objfile->name,
13960                             cu->header.offset.sect_off,
13961                             die->offset.sect_off);
13962       saved = obstack_copy0 (&objfile->objfile_obstack,
13963                              message, strlen (message));
13964       xfree (message);
13965
13966       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
13967     }
13968
13969   return this_type;
13970 }
13971
13972 /* Return the type in DIE, CU.
13973    Returns NULL for invalid types.
13974
13975    This first does a lookup in the appropriate type_hash table,
13976    and only reads the die in if necessary.
13977
13978    NOTE: This can be called when reading in partial or full symbols.  */
13979
13980 static struct type *
13981 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
13982 {
13983   struct type *this_type;
13984
13985   this_type = get_die_type (die, cu);
13986   if (this_type)
13987     return this_type;
13988
13989   return read_type_die_1 (die, cu);
13990 }
13991
13992 /* Read the type in DIE, CU.
13993    Returns NULL for invalid types.  */
13994
13995 static struct type *
13996 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
13997 {
13998   struct type *this_type = NULL;
13999
14000   switch (die->tag)
14001     {
14002     case DW_TAG_class_type:
14003     case DW_TAG_interface_type:
14004     case DW_TAG_structure_type:
14005     case DW_TAG_union_type:
14006       this_type = read_structure_type (die, cu);
14007       break;
14008     case DW_TAG_enumeration_type:
14009       this_type = read_enumeration_type (die, cu);
14010       break;
14011     case DW_TAG_subprogram:
14012     case DW_TAG_subroutine_type:
14013     case DW_TAG_inlined_subroutine:
14014       this_type = read_subroutine_type (die, cu);
14015       break;
14016     case DW_TAG_array_type:
14017       this_type = read_array_type (die, cu);
14018       break;
14019     case DW_TAG_set_type:
14020       this_type = read_set_type (die, cu);
14021       break;
14022     case DW_TAG_pointer_type:
14023       this_type = read_tag_pointer_type (die, cu);
14024       break;
14025     case DW_TAG_ptr_to_member_type:
14026       this_type = read_tag_ptr_to_member_type (die, cu);
14027       break;
14028     case DW_TAG_reference_type:
14029       this_type = read_tag_reference_type (die, cu);
14030       break;
14031     case DW_TAG_const_type:
14032       this_type = read_tag_const_type (die, cu);
14033       break;
14034     case DW_TAG_volatile_type:
14035       this_type = read_tag_volatile_type (die, cu);
14036       break;
14037     case DW_TAG_string_type:
14038       this_type = read_tag_string_type (die, cu);
14039       break;
14040     case DW_TAG_typedef:
14041       this_type = read_typedef (die, cu);
14042       break;
14043     case DW_TAG_subrange_type:
14044       this_type = read_subrange_type (die, cu);
14045       break;
14046     case DW_TAG_base_type:
14047       this_type = read_base_type (die, cu);
14048       break;
14049     case DW_TAG_unspecified_type:
14050       this_type = read_unspecified_type (die, cu);
14051       break;
14052     case DW_TAG_namespace:
14053       this_type = read_namespace_type (die, cu);
14054       break;
14055     case DW_TAG_module:
14056       this_type = read_module_type (die, cu);
14057       break;
14058     default:
14059       complaint (&symfile_complaints,
14060                  _("unexpected tag in read_type_die: '%s'"),
14061                  dwarf_tag_name (die->tag));
14062       break;
14063     }
14064
14065   return this_type;
14066 }
14067
14068 /* See if we can figure out if the class lives in a namespace.  We do
14069    this by looking for a member function; its demangled name will
14070    contain namespace info, if there is any.
14071    Return the computed name or NULL.
14072    Space for the result is allocated on the objfile's obstack.
14073    This is the full-die version of guess_partial_die_structure_name.
14074    In this case we know DIE has no useful parent.  */
14075
14076 static char *
14077 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
14078 {
14079   struct die_info *spec_die;
14080   struct dwarf2_cu *spec_cu;
14081   struct die_info *child;
14082
14083   spec_cu = cu;
14084   spec_die = die_specification (die, &spec_cu);
14085   if (spec_die != NULL)
14086     {
14087       die = spec_die;
14088       cu = spec_cu;
14089     }
14090
14091   for (child = die->child;
14092        child != NULL;
14093        child = child->sibling)
14094     {
14095       if (child->tag == DW_TAG_subprogram)
14096         {
14097           struct attribute *attr;
14098
14099           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
14100           if (attr == NULL)
14101             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
14102           if (attr != NULL)
14103             {
14104               char *actual_name
14105                 = language_class_name_from_physname (cu->language_defn,
14106                                                      DW_STRING (attr));
14107               char *name = NULL;
14108
14109               if (actual_name != NULL)
14110                 {
14111                   char *die_name = dwarf2_name (die, cu);
14112
14113                   if (die_name != NULL
14114                       && strcmp (die_name, actual_name) != 0)
14115                     {
14116                       /* Strip off the class name from the full name.
14117                          We want the prefix.  */
14118                       int die_name_len = strlen (die_name);
14119                       int actual_name_len = strlen (actual_name);
14120
14121                       /* Test for '::' as a sanity check.  */
14122                       if (actual_name_len > die_name_len + 2
14123                           && actual_name[actual_name_len
14124                                          - die_name_len - 1] == ':')
14125                         name =
14126                           obsavestring (actual_name,
14127                                         actual_name_len - die_name_len - 2,
14128                                         &cu->objfile->objfile_obstack);
14129                     }
14130                 }
14131               xfree (actual_name);
14132               return name;
14133             }
14134         }
14135     }
14136
14137   return NULL;
14138 }
14139
14140 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
14141    prefix part in such case.  See
14142    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14143
14144 static char *
14145 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
14146 {
14147   struct attribute *attr;
14148   char *base;
14149
14150   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
14151       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
14152     return NULL;
14153
14154   attr = dwarf2_attr (die, DW_AT_name, cu);
14155   if (attr != NULL && DW_STRING (attr) != NULL)
14156     return NULL;
14157
14158   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
14159   if (attr == NULL)
14160     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
14161   if (attr == NULL || DW_STRING (attr) == NULL)
14162     return NULL;
14163
14164   /* dwarf2_name had to be already called.  */
14165   gdb_assert (DW_STRING_IS_CANONICAL (attr));
14166
14167   /* Strip the base name, keep any leading namespaces/classes.  */
14168   base = strrchr (DW_STRING (attr), ':');
14169   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
14170     return "";
14171
14172   return obsavestring (DW_STRING (attr), &base[-1] - DW_STRING (attr),
14173                        &cu->objfile->objfile_obstack);
14174 }
14175
14176 /* Return the name of the namespace/class that DIE is defined within,
14177    or "" if we can't tell.  The caller should not xfree the result.
14178
14179    For example, if we're within the method foo() in the following
14180    code:
14181
14182    namespace N {
14183      class C {
14184        void foo () {
14185        }
14186      };
14187    }
14188
14189    then determine_prefix on foo's die will return "N::C".  */
14190
14191 static const char *
14192 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
14193 {
14194   struct die_info *parent, *spec_die;
14195   struct dwarf2_cu *spec_cu;
14196   struct type *parent_type;
14197   char *retval;
14198
14199   if (cu->language != language_cplus && cu->language != language_java
14200       && cu->language != language_fortran)
14201     return "";
14202
14203   retval = anonymous_struct_prefix (die, cu);
14204   if (retval)
14205     return retval;
14206
14207   /* We have to be careful in the presence of DW_AT_specification.
14208      For example, with GCC 3.4, given the code
14209
14210      namespace N {
14211        void foo() {
14212          // Definition of N::foo.
14213        }
14214      }
14215
14216      then we'll have a tree of DIEs like this:
14217
14218      1: DW_TAG_compile_unit
14219        2: DW_TAG_namespace        // N
14220          3: DW_TAG_subprogram     // declaration of N::foo
14221        4: DW_TAG_subprogram       // definition of N::foo
14222             DW_AT_specification   // refers to die #3
14223
14224      Thus, when processing die #4, we have to pretend that we're in
14225      the context of its DW_AT_specification, namely the contex of die
14226      #3.  */
14227   spec_cu = cu;
14228   spec_die = die_specification (die, &spec_cu);
14229   if (spec_die == NULL)
14230     parent = die->parent;
14231   else
14232     {
14233       parent = spec_die->parent;
14234       cu = spec_cu;
14235     }
14236
14237   if (parent == NULL)
14238     return "";
14239   else if (parent->building_fullname)
14240     {
14241       const char *name;
14242       const char *parent_name;
14243
14244       /* It has been seen on RealView 2.2 built binaries,
14245          DW_TAG_template_type_param types actually _defined_ as
14246          children of the parent class:
14247
14248          enum E {};
14249          template class <class Enum> Class{};
14250          Class<enum E> class_e;
14251
14252          1: DW_TAG_class_type (Class)
14253            2: DW_TAG_enumeration_type (E)
14254              3: DW_TAG_enumerator (enum1:0)
14255              3: DW_TAG_enumerator (enum2:1)
14256              ...
14257            2: DW_TAG_template_type_param
14258               DW_AT_type  DW_FORM_ref_udata (E)
14259
14260          Besides being broken debug info, it can put GDB into an
14261          infinite loop.  Consider:
14262
14263          When we're building the full name for Class<E>, we'll start
14264          at Class, and go look over its template type parameters,
14265          finding E.  We'll then try to build the full name of E, and
14266          reach here.  We're now trying to build the full name of E,
14267          and look over the parent DIE for containing scope.  In the
14268          broken case, if we followed the parent DIE of E, we'd again
14269          find Class, and once again go look at its template type
14270          arguments, etc., etc.  Simply don't consider such parent die
14271          as source-level parent of this die (it can't be, the language
14272          doesn't allow it), and break the loop here.  */
14273       name = dwarf2_name (die, cu);
14274       parent_name = dwarf2_name (parent, cu);
14275       complaint (&symfile_complaints,
14276                  _("template param type '%s' defined within parent '%s'"),
14277                  name ? name : "<unknown>",
14278                  parent_name ? parent_name : "<unknown>");
14279       return "";
14280     }
14281   else
14282     switch (parent->tag)
14283       {
14284       case DW_TAG_namespace:
14285         parent_type = read_type_die (parent, cu);
14286         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
14287            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
14288            Work around this problem here.  */
14289         if (cu->language == language_cplus
14290             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
14291           return "";
14292         /* We give a name to even anonymous namespaces.  */
14293         return TYPE_TAG_NAME (parent_type);
14294       case DW_TAG_class_type:
14295       case DW_TAG_interface_type:
14296       case DW_TAG_structure_type:
14297       case DW_TAG_union_type:
14298       case DW_TAG_module:
14299         parent_type = read_type_die (parent, cu);
14300         if (TYPE_TAG_NAME (parent_type) != NULL)
14301           return TYPE_TAG_NAME (parent_type);
14302         else
14303           /* An anonymous structure is only allowed non-static data
14304              members; no typedefs, no member functions, et cetera.
14305              So it does not need a prefix.  */
14306           return "";
14307       case DW_TAG_compile_unit:
14308       case DW_TAG_partial_unit:
14309         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
14310         if (cu->language == language_cplus
14311             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14312             && die->child != NULL
14313             && (die->tag == DW_TAG_class_type
14314                 || die->tag == DW_TAG_structure_type
14315                 || die->tag == DW_TAG_union_type))
14316           {
14317             char *name = guess_full_die_structure_name (die, cu);
14318             if (name != NULL)
14319               return name;
14320           }
14321         return "";
14322       default:
14323         return determine_prefix (parent, cu);
14324       }
14325 }
14326
14327 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
14328    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
14329    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
14330    an obconcat, otherwise allocate storage for the result.  The CU argument is
14331    used to determine the language and hence, the appropriate separator.  */
14332
14333 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
14334
14335 static char *
14336 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
14337                  int physname, struct dwarf2_cu *cu)
14338 {
14339   const char *lead = "";
14340   const char *sep;
14341
14342   if (suffix == NULL || suffix[0] == '\0'
14343       || prefix == NULL || prefix[0] == '\0')
14344     sep = "";
14345   else if (cu->language == language_java)
14346     sep = ".";
14347   else if (cu->language == language_fortran && physname)
14348     {
14349       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
14350          DW_AT_MIPS_linkage_name is preferred and used instead.  */
14351
14352       lead = "__";
14353       sep = "_MOD_";
14354     }
14355   else
14356     sep = "::";
14357
14358   if (prefix == NULL)
14359     prefix = "";
14360   if (suffix == NULL)
14361     suffix = "";
14362
14363   if (obs == NULL)
14364     {
14365       char *retval
14366         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
14367
14368       strcpy (retval, lead);
14369       strcat (retval, prefix);
14370       strcat (retval, sep);
14371       strcat (retval, suffix);
14372       return retval;
14373     }
14374   else
14375     {
14376       /* We have an obstack.  */
14377       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
14378     }
14379 }
14380
14381 /* Return sibling of die, NULL if no sibling.  */
14382
14383 static struct die_info *
14384 sibling_die (struct die_info *die)
14385 {
14386   return die->sibling;
14387 }
14388
14389 /* Get name of a die, return NULL if not found.  */
14390
14391 static char *
14392 dwarf2_canonicalize_name (char *name, struct dwarf2_cu *cu,
14393                           struct obstack *obstack)
14394 {
14395   if (name && cu->language == language_cplus)
14396     {
14397       char *canon_name = cp_canonicalize_string (name);
14398
14399       if (canon_name != NULL)
14400         {
14401           if (strcmp (canon_name, name) != 0)
14402             name = obsavestring (canon_name, strlen (canon_name),
14403                                  obstack);
14404           xfree (canon_name);
14405         }
14406     }
14407
14408   return name;
14409 }
14410
14411 /* Get name of a die, return NULL if not found.  */
14412
14413 static char *
14414 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
14415 {
14416   struct attribute *attr;
14417
14418   attr = dwarf2_attr (die, DW_AT_name, cu);
14419   if ((!attr || !DW_STRING (attr))
14420       && die->tag != DW_TAG_class_type
14421       && die->tag != DW_TAG_interface_type
14422       && die->tag != DW_TAG_structure_type
14423       && die->tag != DW_TAG_union_type)
14424     return NULL;
14425
14426   switch (die->tag)
14427     {
14428     case DW_TAG_compile_unit:
14429     case DW_TAG_partial_unit:
14430       /* Compilation units have a DW_AT_name that is a filename, not
14431          a source language identifier.  */
14432     case DW_TAG_enumeration_type:
14433     case DW_TAG_enumerator:
14434       /* These tags always have simple identifiers already; no need
14435          to canonicalize them.  */
14436       return DW_STRING (attr);
14437
14438     case DW_TAG_subprogram:
14439       /* Java constructors will all be named "<init>", so return
14440          the class name when we see this special case.  */
14441       if (cu->language == language_java
14442           && DW_STRING (attr) != NULL
14443           && strcmp (DW_STRING (attr), "<init>") == 0)
14444         {
14445           struct dwarf2_cu *spec_cu = cu;
14446           struct die_info *spec_die;
14447
14448           /* GCJ will output '<init>' for Java constructor names.
14449              For this special case, return the name of the parent class.  */
14450
14451           /* GCJ may output suprogram DIEs with AT_specification set.
14452              If so, use the name of the specified DIE.  */
14453           spec_die = die_specification (die, &spec_cu);
14454           if (spec_die != NULL)
14455             return dwarf2_name (spec_die, spec_cu);
14456
14457           do
14458             {
14459               die = die->parent;
14460               if (die->tag == DW_TAG_class_type)
14461                 return dwarf2_name (die, cu);
14462             }
14463           while (die->tag != DW_TAG_compile_unit
14464                  && die->tag != DW_TAG_partial_unit);
14465         }
14466       break;
14467
14468     case DW_TAG_class_type:
14469     case DW_TAG_interface_type:
14470     case DW_TAG_structure_type:
14471     case DW_TAG_union_type:
14472       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
14473          structures or unions.  These were of the form "._%d" in GCC 4.1,
14474          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
14475          and GCC 4.4.  We work around this problem by ignoring these.  */
14476       if (attr && DW_STRING (attr)
14477           && (strncmp (DW_STRING (attr), "._", 2) == 0
14478               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
14479         return NULL;
14480
14481       /* GCC might emit a nameless typedef that has a linkage name.  See
14482          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14483       if (!attr || DW_STRING (attr) == NULL)
14484         {
14485           char *demangled = NULL;
14486
14487           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
14488           if (attr == NULL)
14489             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
14490
14491           if (attr == NULL || DW_STRING (attr) == NULL)
14492             return NULL;
14493
14494           /* Avoid demangling DW_STRING (attr) the second time on a second
14495              call for the same DIE.  */
14496           if (!DW_STRING_IS_CANONICAL (attr))
14497             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
14498
14499           if (demangled)
14500             {
14501               char *base;
14502
14503               /* FIXME: we already did this for the partial symbol... */
14504               DW_STRING (attr) = obsavestring (demangled, strlen (demangled),
14505                                                &cu->objfile->objfile_obstack);
14506               DW_STRING_IS_CANONICAL (attr) = 1;
14507               xfree (demangled);
14508
14509               /* Strip any leading namespaces/classes, keep only the base name.
14510                  DW_AT_name for named DIEs does not contain the prefixes.  */
14511               base = strrchr (DW_STRING (attr), ':');
14512               if (base && base > DW_STRING (attr) && base[-1] == ':')
14513                 return &base[1];
14514               else
14515                 return DW_STRING (attr);
14516             }
14517         }
14518       break;
14519
14520     default:
14521       break;
14522     }
14523
14524   if (!DW_STRING_IS_CANONICAL (attr))
14525     {
14526       DW_STRING (attr)
14527         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
14528                                     &cu->objfile->objfile_obstack);
14529       DW_STRING_IS_CANONICAL (attr) = 1;
14530     }
14531   return DW_STRING (attr);
14532 }
14533
14534 /* Return the die that this die in an extension of, or NULL if there
14535    is none.  *EXT_CU is the CU containing DIE on input, and the CU
14536    containing the return value on output.  */
14537
14538 static struct die_info *
14539 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
14540 {
14541   struct attribute *attr;
14542
14543   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
14544   if (attr == NULL)
14545     return NULL;
14546
14547   return follow_die_ref (die, attr, ext_cu);
14548 }
14549
14550 /* Convert a DIE tag into its string name.  */
14551
14552 static const char *
14553 dwarf_tag_name (unsigned tag)
14554 {
14555   const char *name = get_DW_TAG_name (tag);
14556
14557   if (name == NULL)
14558     return "DW_TAG_<unknown>";
14559
14560   return name;
14561 }
14562
14563 /* Convert a DWARF attribute code into its string name.  */
14564
14565 static const char *
14566 dwarf_attr_name (unsigned attr)
14567 {
14568   const char *name;
14569
14570 #ifdef MIPS /* collides with DW_AT_HP_block_index */
14571   if (attr == DW_AT_MIPS_fde)
14572     return "DW_AT_MIPS_fde";
14573 #else
14574   if (attr == DW_AT_HP_block_index)
14575     return "DW_AT_HP_block_index";
14576 #endif
14577
14578   name = get_DW_AT_name (attr);
14579
14580   if (name == NULL)
14581     return "DW_AT_<unknown>";
14582
14583   return name;
14584 }
14585
14586 /* Convert a DWARF value form code into its string name.  */
14587
14588 static const char *
14589 dwarf_form_name (unsigned form)
14590 {
14591   const char *name = get_DW_FORM_name (form);
14592
14593   if (name == NULL)
14594     return "DW_FORM_<unknown>";
14595
14596   return name;
14597 }
14598
14599 static char *
14600 dwarf_bool_name (unsigned mybool)
14601 {
14602   if (mybool)
14603     return "TRUE";
14604   else
14605     return "FALSE";
14606 }
14607
14608 /* Convert a DWARF type code into its string name.  */
14609
14610 static const char *
14611 dwarf_type_encoding_name (unsigned enc)
14612 {
14613   const char *name = get_DW_ATE_name (enc);
14614
14615   if (name == NULL)
14616     return "DW_ATE_<unknown>";
14617
14618   return name;
14619 }
14620
14621 static void
14622 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
14623 {
14624   unsigned int i;
14625
14626   print_spaces (indent, f);
14627   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
14628            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
14629
14630   if (die->parent != NULL)
14631     {
14632       print_spaces (indent, f);
14633       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
14634                           die->parent->offset.sect_off);
14635     }
14636
14637   print_spaces (indent, f);
14638   fprintf_unfiltered (f, "  has children: %s\n",
14639            dwarf_bool_name (die->child != NULL));
14640
14641   print_spaces (indent, f);
14642   fprintf_unfiltered (f, "  attributes:\n");
14643
14644   for (i = 0; i < die->num_attrs; ++i)
14645     {
14646       print_spaces (indent, f);
14647       fprintf_unfiltered (f, "    %s (%s) ",
14648                dwarf_attr_name (die->attrs[i].name),
14649                dwarf_form_name (die->attrs[i].form));
14650
14651       switch (die->attrs[i].form)
14652         {
14653         case DW_FORM_addr:
14654         case DW_FORM_GNU_addr_index:
14655           fprintf_unfiltered (f, "address: ");
14656           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
14657           break;
14658         case DW_FORM_block2:
14659         case DW_FORM_block4:
14660         case DW_FORM_block:
14661         case DW_FORM_block1:
14662           fprintf_unfiltered (f, "block: size %d",
14663                               DW_BLOCK (&die->attrs[i])->size);
14664           break;
14665         case DW_FORM_exprloc:
14666           fprintf_unfiltered (f, "expression: size %u",
14667                               DW_BLOCK (&die->attrs[i])->size);
14668           break;
14669         case DW_FORM_ref_addr:
14670           fprintf_unfiltered (f, "ref address: ");
14671           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
14672           break;
14673         case DW_FORM_ref1:
14674         case DW_FORM_ref2:
14675         case DW_FORM_ref4:
14676         case DW_FORM_ref8:
14677         case DW_FORM_ref_udata:
14678           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
14679                               (long) (DW_UNSND (&die->attrs[i])));
14680           break;
14681         case DW_FORM_data1:
14682         case DW_FORM_data2:
14683         case DW_FORM_data4:
14684         case DW_FORM_data8:
14685         case DW_FORM_udata:
14686         case DW_FORM_sdata:
14687           fprintf_unfiltered (f, "constant: %s",
14688                               pulongest (DW_UNSND (&die->attrs[i])));
14689           break;
14690         case DW_FORM_sec_offset:
14691           fprintf_unfiltered (f, "section offset: %s",
14692                               pulongest (DW_UNSND (&die->attrs[i])));
14693           break;
14694         case DW_FORM_ref_sig8:
14695           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
14696             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
14697                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
14698           else
14699             fprintf_unfiltered (f, "signatured type, offset: unknown");
14700           break;
14701         case DW_FORM_string:
14702         case DW_FORM_strp:
14703         case DW_FORM_GNU_str_index:
14704           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
14705                    DW_STRING (&die->attrs[i])
14706                    ? DW_STRING (&die->attrs[i]) : "",
14707                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
14708           break;
14709         case DW_FORM_flag:
14710           if (DW_UNSND (&die->attrs[i]))
14711             fprintf_unfiltered (f, "flag: TRUE");
14712           else
14713             fprintf_unfiltered (f, "flag: FALSE");
14714           break;
14715         case DW_FORM_flag_present:
14716           fprintf_unfiltered (f, "flag: TRUE");
14717           break;
14718         case DW_FORM_indirect:
14719           /* The reader will have reduced the indirect form to
14720              the "base form" so this form should not occur.  */
14721           fprintf_unfiltered (f, 
14722                               "unexpected attribute form: DW_FORM_indirect");
14723           break;
14724         default:
14725           fprintf_unfiltered (f, "unsupported attribute form: %d.",
14726                    die->attrs[i].form);
14727           break;
14728         }
14729       fprintf_unfiltered (f, "\n");
14730     }
14731 }
14732
14733 static void
14734 dump_die_for_error (struct die_info *die)
14735 {
14736   dump_die_shallow (gdb_stderr, 0, die);
14737 }
14738
14739 static void
14740 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
14741 {
14742   int indent = level * 4;
14743
14744   gdb_assert (die != NULL);
14745
14746   if (level >= max_level)
14747     return;
14748
14749   dump_die_shallow (f, indent, die);
14750
14751   if (die->child != NULL)
14752     {
14753       print_spaces (indent, f);
14754       fprintf_unfiltered (f, "  Children:");
14755       if (level + 1 < max_level)
14756         {
14757           fprintf_unfiltered (f, "\n");
14758           dump_die_1 (f, level + 1, max_level, die->child);
14759         }
14760       else
14761         {
14762           fprintf_unfiltered (f,
14763                               " [not printed, max nesting level reached]\n");
14764         }
14765     }
14766
14767   if (die->sibling != NULL && level > 0)
14768     {
14769       dump_die_1 (f, level, max_level, die->sibling);
14770     }
14771 }
14772
14773 /* This is called from the pdie macro in gdbinit.in.
14774    It's not static so gcc will keep a copy callable from gdb.  */
14775
14776 void
14777 dump_die (struct die_info *die, int max_level)
14778 {
14779   dump_die_1 (gdb_stdlog, 0, max_level, die);
14780 }
14781
14782 static void
14783 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
14784 {
14785   void **slot;
14786
14787   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
14788                                    INSERT);
14789
14790   *slot = die;
14791 }
14792
14793 /* DW_ADDR is always stored already as sect_offset; despite for the forms
14794    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
14795
14796 static int
14797 is_ref_attr (struct attribute *attr)
14798 {
14799   switch (attr->form)
14800     {
14801     case DW_FORM_ref_addr:
14802     case DW_FORM_ref1:
14803     case DW_FORM_ref2:
14804     case DW_FORM_ref4:
14805     case DW_FORM_ref8:
14806     case DW_FORM_ref_udata:
14807       return 1;
14808     default:
14809       return 0;
14810     }
14811 }
14812
14813 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
14814    required kind.  */
14815
14816 static sect_offset
14817 dwarf2_get_ref_die_offset (struct attribute *attr)
14818 {
14819   sect_offset retval = { DW_UNSND (attr) };
14820
14821   if (is_ref_attr (attr))
14822     return retval;
14823
14824   retval.sect_off = 0;
14825   complaint (&symfile_complaints,
14826              _("unsupported die ref attribute form: '%s'"),
14827              dwarf_form_name (attr->form));
14828   return retval;
14829 }
14830
14831 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
14832  * the value held by the attribute is not constant.  */
14833
14834 static LONGEST
14835 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
14836 {
14837   if (attr->form == DW_FORM_sdata)
14838     return DW_SND (attr);
14839   else if (attr->form == DW_FORM_udata
14840            || attr->form == DW_FORM_data1
14841            || attr->form == DW_FORM_data2
14842            || attr->form == DW_FORM_data4
14843            || attr->form == DW_FORM_data8)
14844     return DW_UNSND (attr);
14845   else
14846     {
14847       complaint (&symfile_complaints,
14848                  _("Attribute value is not a constant (%s)"),
14849                  dwarf_form_name (attr->form));
14850       return default_value;
14851     }
14852 }
14853
14854 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
14855    unit and add it to our queue.
14856    The result is non-zero if PER_CU was queued, otherwise the result is zero
14857    meaning either PER_CU is already queued or it is already loaded.  */
14858
14859 static int
14860 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
14861                        struct dwarf2_per_cu_data *per_cu,
14862                        enum language pretend_language)
14863 {
14864   /* We may arrive here during partial symbol reading, if we need full
14865      DIEs to process an unusual case (e.g. template arguments).  Do
14866      not queue PER_CU, just tell our caller to load its DIEs.  */
14867   if (dwarf2_per_objfile->reading_partial_symbols)
14868     {
14869       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
14870         return 1;
14871       return 0;
14872     }
14873
14874   /* Mark the dependence relation so that we don't flush PER_CU
14875      too early.  */
14876   dwarf2_add_dependence (this_cu, per_cu);
14877
14878   /* If it's already on the queue, we have nothing to do.  */
14879   if (per_cu->queued)
14880     return 0;
14881
14882   /* If the compilation unit is already loaded, just mark it as
14883      used.  */
14884   if (per_cu->cu != NULL)
14885     {
14886       per_cu->cu->last_used = 0;
14887       return 0;
14888     }
14889
14890   /* Add it to the queue.  */
14891   queue_comp_unit (per_cu, pretend_language);
14892
14893   return 1;
14894 }
14895
14896 /* Follow reference or signature attribute ATTR of SRC_DIE.
14897    On entry *REF_CU is the CU of SRC_DIE.
14898    On exit *REF_CU is the CU of the result.  */
14899
14900 static struct die_info *
14901 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
14902                        struct dwarf2_cu **ref_cu)
14903 {
14904   struct die_info *die;
14905
14906   if (is_ref_attr (attr))
14907     die = follow_die_ref (src_die, attr, ref_cu);
14908   else if (attr->form == DW_FORM_ref_sig8)
14909     die = follow_die_sig (src_die, attr, ref_cu);
14910   else
14911     {
14912       dump_die_for_error (src_die);
14913       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
14914              (*ref_cu)->objfile->name);
14915     }
14916
14917   return die;
14918 }
14919
14920 /* Follow reference OFFSET.
14921    On entry *REF_CU is the CU of the source die referencing OFFSET.
14922    On exit *REF_CU is the CU of the result.
14923    Returns NULL if OFFSET is invalid.  */
14924
14925 static struct die_info *
14926 follow_die_offset (sect_offset offset, struct dwarf2_cu **ref_cu)
14927 {
14928   struct die_info temp_die;
14929   struct dwarf2_cu *target_cu, *cu = *ref_cu;
14930
14931   gdb_assert (cu->per_cu != NULL);
14932
14933   target_cu = cu;
14934
14935   if (cu->per_cu->is_debug_types)
14936     {
14937       /* .debug_types CUs cannot reference anything outside their CU.
14938          If they need to, they have to reference a signatured type via
14939          DW_FORM_ref_sig8.  */
14940       if (! offset_in_cu_p (&cu->header, offset))
14941         return NULL;
14942     }
14943   else if (! offset_in_cu_p (&cu->header, offset))
14944     {
14945       struct dwarf2_per_cu_data *per_cu;
14946
14947       per_cu = dwarf2_find_containing_comp_unit (offset, cu->objfile);
14948
14949       /* If necessary, add it to the queue and load its DIEs.  */
14950       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
14951         load_full_comp_unit (per_cu, cu->language);
14952
14953       target_cu = per_cu->cu;
14954     }
14955   else if (cu->dies == NULL)
14956     {
14957       /* We're loading full DIEs during partial symbol reading.  */
14958       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
14959       load_full_comp_unit (cu->per_cu, language_minimal);
14960     }
14961
14962   *ref_cu = target_cu;
14963   temp_die.offset = offset;
14964   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
14965 }
14966
14967 /* Follow reference attribute ATTR of SRC_DIE.
14968    On entry *REF_CU is the CU of SRC_DIE.
14969    On exit *REF_CU is the CU of the result.  */
14970
14971 static struct die_info *
14972 follow_die_ref (struct die_info *src_die, struct attribute *attr,
14973                 struct dwarf2_cu **ref_cu)
14974 {
14975   sect_offset offset = dwarf2_get_ref_die_offset (attr);
14976   struct dwarf2_cu *cu = *ref_cu;
14977   struct die_info *die;
14978
14979   die = follow_die_offset (offset, ref_cu);
14980   if (!die)
14981     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
14982            "at 0x%x [in module %s]"),
14983            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
14984
14985   return die;
14986 }
14987
14988 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
14989    Returned value is intended for DW_OP_call*.  Returned
14990    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
14991
14992 struct dwarf2_locexpr_baton
14993 dwarf2_fetch_die_location_block (cu_offset offset_in_cu,
14994                                  struct dwarf2_per_cu_data *per_cu,
14995                                  CORE_ADDR (*get_frame_pc) (void *baton),
14996                                  void *baton)
14997 {
14998   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
14999   struct dwarf2_cu *cu;
15000   struct die_info *die;
15001   struct attribute *attr;
15002   struct dwarf2_locexpr_baton retval;
15003
15004   dw2_setup (per_cu->objfile);
15005
15006   if (per_cu->cu == NULL)
15007     load_cu (per_cu);
15008   cu = per_cu->cu;
15009
15010   die = follow_die_offset (offset, &cu);
15011   if (!die)
15012     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
15013            offset.sect_off, per_cu->objfile->name);
15014
15015   attr = dwarf2_attr (die, DW_AT_location, cu);
15016   if (!attr)
15017     {
15018       /* DWARF: "If there is no such attribute, then there is no effect.".
15019          DATA is ignored if SIZE is 0.  */
15020
15021       retval.data = NULL;
15022       retval.size = 0;
15023     }
15024   else if (attr_form_is_section_offset (attr))
15025     {
15026       struct dwarf2_loclist_baton loclist_baton;
15027       CORE_ADDR pc = (*get_frame_pc) (baton);
15028       size_t size;
15029
15030       fill_in_loclist_baton (cu, &loclist_baton, attr);
15031
15032       retval.data = dwarf2_find_location_expression (&loclist_baton,
15033                                                      &size, pc);
15034       retval.size = size;
15035     }
15036   else
15037     {
15038       if (!attr_form_is_block (attr))
15039         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
15040                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
15041                offset.sect_off, per_cu->objfile->name);
15042
15043       retval.data = DW_BLOCK (attr)->data;
15044       retval.size = DW_BLOCK (attr)->size;
15045     }
15046   retval.per_cu = cu->per_cu;
15047
15048   age_cached_comp_units ();
15049
15050   return retval;
15051 }
15052
15053 /* Return the type of the DIE at DIE_OFFSET in the CU named by
15054    PER_CU.  */
15055
15056 struct type *
15057 dwarf2_get_die_type (cu_offset die_offset,
15058                      struct dwarf2_per_cu_data *per_cu)
15059 {
15060   sect_offset die_offset_sect;
15061
15062   dw2_setup (per_cu->objfile);
15063
15064   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
15065   return get_die_type_at_offset (die_offset_sect, per_cu);
15066 }
15067
15068 /* Follow the signature attribute ATTR in SRC_DIE.
15069    On entry *REF_CU is the CU of SRC_DIE.
15070    On exit *REF_CU is the CU of the result.  */
15071
15072 static struct die_info *
15073 follow_die_sig (struct die_info *src_die, struct attribute *attr,
15074                 struct dwarf2_cu **ref_cu)
15075 {
15076   struct objfile *objfile = (*ref_cu)->objfile;
15077   struct die_info temp_die;
15078   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
15079   struct dwarf2_cu *sig_cu;
15080   struct die_info *die;
15081
15082   /* sig_type will be NULL if the signatured type is missing from
15083      the debug info.  */
15084   if (sig_type == NULL)
15085     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
15086              "at 0x%x [in module %s]"),
15087            src_die->offset.sect_off, objfile->name);
15088
15089   /* If necessary, add it to the queue and load its DIEs.  */
15090
15091   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
15092     read_signatured_type (sig_type);
15093
15094   gdb_assert (sig_type->per_cu.cu != NULL);
15095
15096   sig_cu = sig_type->per_cu.cu;
15097   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
15098   temp_die.offset = sig_type->type_offset_in_section;
15099   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
15100                              temp_die.offset.sect_off);
15101   if (die)
15102     {
15103       *ref_cu = sig_cu;
15104       return die;
15105     }
15106
15107   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
15108          "from DIE at 0x%x [in module %s]"),
15109          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
15110 }
15111
15112 /* Given an offset of a signatured type, return its signatured_type.  */
15113
15114 static struct signatured_type *
15115 lookup_signatured_type_at_offset (struct objfile *objfile,
15116                                   struct dwarf2_section_info *section,
15117                                   sect_offset offset)
15118 {
15119   gdb_byte *info_ptr = section->buffer + offset.sect_off;
15120   unsigned int length, initial_length_size;
15121   unsigned int sig_offset;
15122   struct signatured_type find_entry, *sig_type;
15123
15124   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
15125   sig_offset = (initial_length_size
15126                 + 2 /*version*/
15127                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
15128                 + 1 /*address_size*/);
15129   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
15130   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
15131
15132   /* This is only used to lookup previously recorded types.
15133      If we didn't find it, it's our bug.  */
15134   gdb_assert (sig_type != NULL);
15135   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
15136
15137   return sig_type;
15138 }
15139
15140 /* Load the DIEs associated with type unit PER_CU into memory.  */
15141
15142 static void
15143 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
15144 {
15145   struct objfile *objfile = per_cu->objfile;
15146   struct dwarf2_section_info *sect = per_cu->info_or_types_section;
15147   sect_offset offset = per_cu->offset;
15148   struct signatured_type *sig_type;
15149
15150   dwarf2_read_section (objfile, sect);
15151
15152   /* We have the section offset, but we need the signature to do the
15153      hash table lookup.  */
15154   /* FIXME: This is sorta unnecessary, read_signatured_type only uses
15155      the signature to assert we found the right one.
15156      Ok, but it's a lot of work.  We should simplify things so any needed
15157      assert doesn't require all this clumsiness.  */
15158   sig_type = lookup_signatured_type_at_offset (objfile, sect, offset);
15159
15160   gdb_assert (&sig_type->per_cu == per_cu);
15161   gdb_assert (sig_type->per_cu.cu == NULL);
15162
15163   read_signatured_type (sig_type);
15164
15165   gdb_assert (sig_type->per_cu.cu != NULL);
15166 }
15167
15168 /* die_reader_func for read_signatured_type.
15169    This is identical to load_full_comp_unit_reader,
15170    but is kept separate for now.  */
15171
15172 static void
15173 read_signatured_type_reader (const struct die_reader_specs *reader,
15174                              gdb_byte *info_ptr,
15175                              struct die_info *comp_unit_die,
15176                              int has_children,
15177                              void *data)
15178 {
15179   struct dwarf2_cu *cu = reader->cu;
15180
15181   gdb_assert (cu->die_hash == NULL);
15182   cu->die_hash =
15183     htab_create_alloc_ex (cu->header.length / 12,
15184                           die_hash,
15185                           die_eq,
15186                           NULL,
15187                           &cu->comp_unit_obstack,
15188                           hashtab_obstack_allocate,
15189                           dummy_obstack_deallocate);
15190
15191   if (has_children)
15192     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
15193                                                   &info_ptr, comp_unit_die);
15194   cu->dies = comp_unit_die;
15195   /* comp_unit_die is not stored in die_hash, no need.  */
15196
15197   /* We try not to read any attributes in this function, because not
15198      all CUs needed for references have been loaded yet, and symbol
15199      table processing isn't initialized.  But we have to set the CU language,
15200      or we won't be able to build types correctly.
15201      Similarly, if we do not read the producer, we can not apply
15202      producer-specific interpretation.  */
15203   prepare_one_comp_unit (cu, cu->dies, language_minimal);
15204 }
15205
15206 /* Read in a signatured type and build its CU and DIEs.
15207    If the type is a stub for the real type in a DWO file,
15208    read in the real type from the DWO file as well.  */
15209
15210 static void
15211 read_signatured_type (struct signatured_type *sig_type)
15212 {
15213   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
15214
15215   gdb_assert (per_cu->is_debug_types);
15216   gdb_assert (per_cu->cu == NULL);
15217
15218   init_cutu_and_read_dies (per_cu, 0, 1, read_signatured_type_reader, NULL);
15219 }
15220
15221 /* Decode simple location descriptions.
15222    Given a pointer to a dwarf block that defines a location, compute
15223    the location and return the value.
15224
15225    NOTE drow/2003-11-18: This function is called in two situations
15226    now: for the address of static or global variables (partial symbols
15227    only) and for offsets into structures which are expected to be
15228    (more or less) constant.  The partial symbol case should go away,
15229    and only the constant case should remain.  That will let this
15230    function complain more accurately.  A few special modes are allowed
15231    without complaint for global variables (for instance, global
15232    register values and thread-local values).
15233
15234    A location description containing no operations indicates that the
15235    object is optimized out.  The return value is 0 for that case.
15236    FIXME drow/2003-11-16: No callers check for this case any more; soon all
15237    callers will only want a very basic result and this can become a
15238    complaint.
15239
15240    Note that stack[0] is unused except as a default error return.  */
15241
15242 static CORE_ADDR
15243 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
15244 {
15245   struct objfile *objfile = cu->objfile;
15246   int i;
15247   int size = blk->size;
15248   gdb_byte *data = blk->data;
15249   CORE_ADDR stack[64];
15250   int stacki;
15251   unsigned int bytes_read, unsnd;
15252   gdb_byte op;
15253
15254   i = 0;
15255   stacki = 0;
15256   stack[stacki] = 0;
15257   stack[++stacki] = 0;
15258
15259   while (i < size)
15260     {
15261       op = data[i++];
15262       switch (op)
15263         {
15264         case DW_OP_lit0:
15265         case DW_OP_lit1:
15266         case DW_OP_lit2:
15267         case DW_OP_lit3:
15268         case DW_OP_lit4:
15269         case DW_OP_lit5:
15270         case DW_OP_lit6:
15271         case DW_OP_lit7:
15272         case DW_OP_lit8:
15273         case DW_OP_lit9:
15274         case DW_OP_lit10:
15275         case DW_OP_lit11:
15276         case DW_OP_lit12:
15277         case DW_OP_lit13:
15278         case DW_OP_lit14:
15279         case DW_OP_lit15:
15280         case DW_OP_lit16:
15281         case DW_OP_lit17:
15282         case DW_OP_lit18:
15283         case DW_OP_lit19:
15284         case DW_OP_lit20:
15285         case DW_OP_lit21:
15286         case DW_OP_lit22:
15287         case DW_OP_lit23:
15288         case DW_OP_lit24:
15289         case DW_OP_lit25:
15290         case DW_OP_lit26:
15291         case DW_OP_lit27:
15292         case DW_OP_lit28:
15293         case DW_OP_lit29:
15294         case DW_OP_lit30:
15295         case DW_OP_lit31:
15296           stack[++stacki] = op - DW_OP_lit0;
15297           break;
15298
15299         case DW_OP_reg0:
15300         case DW_OP_reg1:
15301         case DW_OP_reg2:
15302         case DW_OP_reg3:
15303         case DW_OP_reg4:
15304         case DW_OP_reg5:
15305         case DW_OP_reg6:
15306         case DW_OP_reg7:
15307         case DW_OP_reg8:
15308         case DW_OP_reg9:
15309         case DW_OP_reg10:
15310         case DW_OP_reg11:
15311         case DW_OP_reg12:
15312         case DW_OP_reg13:
15313         case DW_OP_reg14:
15314         case DW_OP_reg15:
15315         case DW_OP_reg16:
15316         case DW_OP_reg17:
15317         case DW_OP_reg18:
15318         case DW_OP_reg19:
15319         case DW_OP_reg20:
15320         case DW_OP_reg21:
15321         case DW_OP_reg22:
15322         case DW_OP_reg23:
15323         case DW_OP_reg24:
15324         case DW_OP_reg25:
15325         case DW_OP_reg26:
15326         case DW_OP_reg27:
15327         case DW_OP_reg28:
15328         case DW_OP_reg29:
15329         case DW_OP_reg30:
15330         case DW_OP_reg31:
15331           stack[++stacki] = op - DW_OP_reg0;
15332           if (i < size)
15333             dwarf2_complex_location_expr_complaint ();
15334           break;
15335
15336         case DW_OP_regx:
15337           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
15338           i += bytes_read;
15339           stack[++stacki] = unsnd;
15340           if (i < size)
15341             dwarf2_complex_location_expr_complaint ();
15342           break;
15343
15344         case DW_OP_addr:
15345           stack[++stacki] = read_address (objfile->obfd, &data[i],
15346                                           cu, &bytes_read);
15347           i += bytes_read;
15348           break;
15349
15350         case DW_OP_const1u:
15351           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
15352           i += 1;
15353           break;
15354
15355         case DW_OP_const1s:
15356           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
15357           i += 1;
15358           break;
15359
15360         case DW_OP_const2u:
15361           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
15362           i += 2;
15363           break;
15364
15365         case DW_OP_const2s:
15366           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
15367           i += 2;
15368           break;
15369
15370         case DW_OP_const4u:
15371           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
15372           i += 4;
15373           break;
15374
15375         case DW_OP_const4s:
15376           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
15377           i += 4;
15378           break;
15379
15380         case DW_OP_const8u:
15381           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
15382           i += 8;
15383           break;
15384
15385         case DW_OP_constu:
15386           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
15387                                                   &bytes_read);
15388           i += bytes_read;
15389           break;
15390
15391         case DW_OP_consts:
15392           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
15393           i += bytes_read;
15394           break;
15395
15396         case DW_OP_dup:
15397           stack[stacki + 1] = stack[stacki];
15398           stacki++;
15399           break;
15400
15401         case DW_OP_plus:
15402           stack[stacki - 1] += stack[stacki];
15403           stacki--;
15404           break;
15405
15406         case DW_OP_plus_uconst:
15407           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
15408                                                  &bytes_read);
15409           i += bytes_read;
15410           break;
15411
15412         case DW_OP_minus:
15413           stack[stacki - 1] -= stack[stacki];
15414           stacki--;
15415           break;
15416
15417         case DW_OP_deref:
15418           /* If we're not the last op, then we definitely can't encode
15419              this using GDB's address_class enum.  This is valid for partial
15420              global symbols, although the variable's address will be bogus
15421              in the psymtab.  */
15422           if (i < size)
15423             dwarf2_complex_location_expr_complaint ();
15424           break;
15425
15426         case DW_OP_GNU_push_tls_address:
15427           /* The top of the stack has the offset from the beginning
15428              of the thread control block at which the variable is located.  */
15429           /* Nothing should follow this operator, so the top of stack would
15430              be returned.  */
15431           /* This is valid for partial global symbols, but the variable's
15432              address will be bogus in the psymtab.  Make it always at least
15433              non-zero to not look as a variable garbage collected by linker
15434              which have DW_OP_addr 0.  */
15435           if (i < size)
15436             dwarf2_complex_location_expr_complaint ();
15437           stack[stacki]++;
15438           break;
15439
15440         case DW_OP_GNU_uninit:
15441           break;
15442
15443         case DW_OP_GNU_addr_index:
15444           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
15445                                                          &bytes_read);
15446           i += bytes_read;
15447           break;
15448
15449         default:
15450           {
15451             const char *name = get_DW_OP_name (op);
15452
15453             if (name)
15454               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
15455                          name);
15456             else
15457               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
15458                          op);
15459           }
15460
15461           return (stack[stacki]);
15462         }
15463
15464       /* Enforce maximum stack depth of SIZE-1 to avoid writing
15465          outside of the allocated space.  Also enforce minimum>0.  */
15466       if (stacki >= ARRAY_SIZE (stack) - 1)
15467         {
15468           complaint (&symfile_complaints,
15469                      _("location description stack overflow"));
15470           return 0;
15471         }
15472
15473       if (stacki <= 0)
15474         {
15475           complaint (&symfile_complaints,
15476                      _("location description stack underflow"));
15477           return 0;
15478         }
15479     }
15480   return (stack[stacki]);
15481 }
15482
15483 /* memory allocation interface */
15484
15485 static struct dwarf_block *
15486 dwarf_alloc_block (struct dwarf2_cu *cu)
15487 {
15488   struct dwarf_block *blk;
15489
15490   blk = (struct dwarf_block *)
15491     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
15492   return (blk);
15493 }
15494
15495 static struct abbrev_info *
15496 dwarf_alloc_abbrev (struct dwarf2_cu *cu)
15497 {
15498   struct abbrev_info *abbrev;
15499
15500   abbrev = (struct abbrev_info *)
15501     obstack_alloc (&cu->abbrev_obstack, sizeof (struct abbrev_info));
15502   memset (abbrev, 0, sizeof (struct abbrev_info));
15503   return (abbrev);
15504 }
15505
15506 static struct die_info *
15507 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
15508 {
15509   struct die_info *die;
15510   size_t size = sizeof (struct die_info);
15511
15512   if (num_attrs > 1)
15513     size += (num_attrs - 1) * sizeof (struct attribute);
15514
15515   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
15516   memset (die, 0, sizeof (struct die_info));
15517   return (die);
15518 }
15519
15520 \f
15521 /* Macro support.  */
15522
15523 /* Return the full name of file number I in *LH's file name table.
15524    Use COMP_DIR as the name of the current directory of the
15525    compilation.  The result is allocated using xmalloc; the caller is
15526    responsible for freeing it.  */
15527 static char *
15528 file_full_name (int file, struct line_header *lh, const char *comp_dir)
15529 {
15530   /* Is the file number a valid index into the line header's file name
15531      table?  Remember that file numbers start with one, not zero.  */
15532   if (1 <= file && file <= lh->num_file_names)
15533     {
15534       struct file_entry *fe = &lh->file_names[file - 1];
15535
15536       if (IS_ABSOLUTE_PATH (fe->name))
15537         return xstrdup (fe->name);
15538       else
15539         {
15540           const char *dir;
15541           int dir_len;
15542           char *full_name;
15543
15544           if (fe->dir_index)
15545             dir = lh->include_dirs[fe->dir_index - 1];
15546           else
15547             dir = comp_dir;
15548
15549           if (dir)
15550             {
15551               dir_len = strlen (dir);
15552               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
15553               strcpy (full_name, dir);
15554               full_name[dir_len] = '/';
15555               strcpy (full_name + dir_len + 1, fe->name);
15556               return full_name;
15557             }
15558           else
15559             return xstrdup (fe->name);
15560         }
15561     }
15562   else
15563     {
15564       /* The compiler produced a bogus file number.  We can at least
15565          record the macro definitions made in the file, even if we
15566          won't be able to find the file by name.  */
15567       char fake_name[80];
15568
15569       sprintf (fake_name, "<bad macro file number %d>", file);
15570
15571       complaint (&symfile_complaints,
15572                  _("bad file number in macro information (%d)"),
15573                  file);
15574
15575       return xstrdup (fake_name);
15576     }
15577 }
15578
15579
15580 static struct macro_source_file *
15581 macro_start_file (int file, int line,
15582                   struct macro_source_file *current_file,
15583                   const char *comp_dir,
15584                   struct line_header *lh, struct objfile *objfile)
15585 {
15586   /* The full name of this source file.  */
15587   char *full_name = file_full_name (file, lh, comp_dir);
15588
15589   /* We don't create a macro table for this compilation unit
15590      at all until we actually get a filename.  */
15591   if (! pending_macros)
15592     pending_macros = new_macro_table (&objfile->objfile_obstack,
15593                                       objfile->macro_cache);
15594
15595   if (! current_file)
15596     {
15597       /* If we have no current file, then this must be the start_file
15598          directive for the compilation unit's main source file.  */
15599       current_file = macro_set_main (pending_macros, full_name);
15600       macro_define_special (pending_macros);
15601     }
15602   else
15603     current_file = macro_include (current_file, line, full_name);
15604
15605   xfree (full_name);
15606
15607   return current_file;
15608 }
15609
15610
15611 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
15612    followed by a null byte.  */
15613 static char *
15614 copy_string (const char *buf, int len)
15615 {
15616   char *s = xmalloc (len + 1);
15617
15618   memcpy (s, buf, len);
15619   s[len] = '\0';
15620   return s;
15621 }
15622
15623
15624 static const char *
15625 consume_improper_spaces (const char *p, const char *body)
15626 {
15627   if (*p == ' ')
15628     {
15629       complaint (&symfile_complaints,
15630                  _("macro definition contains spaces "
15631                    "in formal argument list:\n`%s'"),
15632                  body);
15633
15634       while (*p == ' ')
15635         p++;
15636     }
15637
15638   return p;
15639 }
15640
15641
15642 static void
15643 parse_macro_definition (struct macro_source_file *file, int line,
15644                         const char *body)
15645 {
15646   const char *p;
15647
15648   /* The body string takes one of two forms.  For object-like macro
15649      definitions, it should be:
15650
15651         <macro name> " " <definition>
15652
15653      For function-like macro definitions, it should be:
15654
15655         <macro name> "() " <definition>
15656      or
15657         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
15658
15659      Spaces may appear only where explicitly indicated, and in the
15660      <definition>.
15661
15662      The Dwarf 2 spec says that an object-like macro's name is always
15663      followed by a space, but versions of GCC around March 2002 omit
15664      the space when the macro's definition is the empty string.
15665
15666      The Dwarf 2 spec says that there should be no spaces between the
15667      formal arguments in a function-like macro's formal argument list,
15668      but versions of GCC around March 2002 include spaces after the
15669      commas.  */
15670
15671
15672   /* Find the extent of the macro name.  The macro name is terminated
15673      by either a space or null character (for an object-like macro) or
15674      an opening paren (for a function-like macro).  */
15675   for (p = body; *p; p++)
15676     if (*p == ' ' || *p == '(')
15677       break;
15678
15679   if (*p == ' ' || *p == '\0')
15680     {
15681       /* It's an object-like macro.  */
15682       int name_len = p - body;
15683       char *name = copy_string (body, name_len);
15684       const char *replacement;
15685
15686       if (*p == ' ')
15687         replacement = body + name_len + 1;
15688       else
15689         {
15690           dwarf2_macro_malformed_definition_complaint (body);
15691           replacement = body + name_len;
15692         }
15693
15694       macro_define_object (file, line, name, replacement);
15695
15696       xfree (name);
15697     }
15698   else if (*p == '(')
15699     {
15700       /* It's a function-like macro.  */
15701       char *name = copy_string (body, p - body);
15702       int argc = 0;
15703       int argv_size = 1;
15704       char **argv = xmalloc (argv_size * sizeof (*argv));
15705
15706       p++;
15707
15708       p = consume_improper_spaces (p, body);
15709
15710       /* Parse the formal argument list.  */
15711       while (*p && *p != ')')
15712         {
15713           /* Find the extent of the current argument name.  */
15714           const char *arg_start = p;
15715
15716           while (*p && *p != ',' && *p != ')' && *p != ' ')
15717             p++;
15718
15719           if (! *p || p == arg_start)
15720             dwarf2_macro_malformed_definition_complaint (body);
15721           else
15722             {
15723               /* Make sure argv has room for the new argument.  */
15724               if (argc >= argv_size)
15725                 {
15726                   argv_size *= 2;
15727                   argv = xrealloc (argv, argv_size * sizeof (*argv));
15728                 }
15729
15730               argv[argc++] = copy_string (arg_start, p - arg_start);
15731             }
15732
15733           p = consume_improper_spaces (p, body);
15734
15735           /* Consume the comma, if present.  */
15736           if (*p == ',')
15737             {
15738               p++;
15739
15740               p = consume_improper_spaces (p, body);
15741             }
15742         }
15743
15744       if (*p == ')')
15745         {
15746           p++;
15747
15748           if (*p == ' ')
15749             /* Perfectly formed definition, no complaints.  */
15750             macro_define_function (file, line, name,
15751                                    argc, (const char **) argv,
15752                                    p + 1);
15753           else if (*p == '\0')
15754             {
15755               /* Complain, but do define it.  */
15756               dwarf2_macro_malformed_definition_complaint (body);
15757               macro_define_function (file, line, name,
15758                                      argc, (const char **) argv,
15759                                      p);
15760             }
15761           else
15762             /* Just complain.  */
15763             dwarf2_macro_malformed_definition_complaint (body);
15764         }
15765       else
15766         /* Just complain.  */
15767         dwarf2_macro_malformed_definition_complaint (body);
15768
15769       xfree (name);
15770       {
15771         int i;
15772
15773         for (i = 0; i < argc; i++)
15774           xfree (argv[i]);
15775       }
15776       xfree (argv);
15777     }
15778   else
15779     dwarf2_macro_malformed_definition_complaint (body);
15780 }
15781
15782 /* Skip some bytes from BYTES according to the form given in FORM.
15783    Returns the new pointer.  */
15784
15785 static gdb_byte *
15786 skip_form_bytes (bfd *abfd, gdb_byte *bytes,
15787                  enum dwarf_form form,
15788                  unsigned int offset_size,
15789                  struct dwarf2_section_info *section)
15790 {
15791   unsigned int bytes_read;
15792
15793   switch (form)
15794     {
15795     case DW_FORM_data1:
15796     case DW_FORM_flag:
15797       ++bytes;
15798       break;
15799
15800     case DW_FORM_data2:
15801       bytes += 2;
15802       break;
15803
15804     case DW_FORM_data4:
15805       bytes += 4;
15806       break;
15807
15808     case DW_FORM_data8:
15809       bytes += 8;
15810       break;
15811
15812     case DW_FORM_string:
15813       read_direct_string (abfd, bytes, &bytes_read);
15814       bytes += bytes_read;
15815       break;
15816
15817     case DW_FORM_sec_offset:
15818     case DW_FORM_strp:
15819       bytes += offset_size;
15820       break;
15821
15822     case DW_FORM_block:
15823       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
15824       bytes += bytes_read;
15825       break;
15826
15827     case DW_FORM_block1:
15828       bytes += 1 + read_1_byte (abfd, bytes);
15829       break;
15830     case DW_FORM_block2:
15831       bytes += 2 + read_2_bytes (abfd, bytes);
15832       break;
15833     case DW_FORM_block4:
15834       bytes += 4 + read_4_bytes (abfd, bytes);
15835       break;
15836
15837     case DW_FORM_sdata:
15838     case DW_FORM_udata:
15839     case DW_FORM_GNU_addr_index:
15840     case DW_FORM_GNU_str_index:
15841       bytes = skip_leb128 (abfd, bytes);
15842       break;
15843
15844     default:
15845       {
15846       complain:
15847         complaint (&symfile_complaints,
15848                    _("invalid form 0x%x in `%s'"),
15849                    form,
15850                    section->asection->name);
15851         return NULL;
15852       }
15853     }
15854
15855   return bytes;
15856 }
15857
15858 /* A helper for dwarf_decode_macros that handles skipping an unknown
15859    opcode.  Returns an updated pointer to the macro data buffer; or,
15860    on error, issues a complaint and returns NULL.  */
15861
15862 static gdb_byte *
15863 skip_unknown_opcode (unsigned int opcode,
15864                      gdb_byte **opcode_definitions,
15865                      gdb_byte *mac_ptr,
15866                      bfd *abfd,
15867                      unsigned int offset_size,
15868                      struct dwarf2_section_info *section)
15869 {
15870   unsigned int bytes_read, i;
15871   unsigned long arg;
15872   gdb_byte *defn;
15873
15874   if (opcode_definitions[opcode] == NULL)
15875     {
15876       complaint (&symfile_complaints,
15877                  _("unrecognized DW_MACFINO opcode 0x%x"),
15878                  opcode);
15879       return NULL;
15880     }
15881
15882   defn = opcode_definitions[opcode];
15883   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
15884   defn += bytes_read;
15885
15886   for (i = 0; i < arg; ++i)
15887     {
15888       mac_ptr = skip_form_bytes (abfd, mac_ptr, defn[i], offset_size, section);
15889       if (mac_ptr == NULL)
15890         {
15891           /* skip_form_bytes already issued the complaint.  */
15892           return NULL;
15893         }
15894     }
15895
15896   return mac_ptr;
15897 }
15898
15899 /* A helper function which parses the header of a macro section.
15900    If the macro section is the extended (for now called "GNU") type,
15901    then this updates *OFFSET_SIZE.  Returns a pointer to just after
15902    the header, or issues a complaint and returns NULL on error.  */
15903
15904 static gdb_byte *
15905 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
15906                           bfd *abfd,
15907                           gdb_byte *mac_ptr,
15908                           unsigned int *offset_size,
15909                           int section_is_gnu)
15910 {
15911   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
15912
15913   if (section_is_gnu)
15914     {
15915       unsigned int version, flags;
15916
15917       version = read_2_bytes (abfd, mac_ptr);
15918       if (version != 4)
15919         {
15920           complaint (&symfile_complaints,
15921                      _("unrecognized version `%d' in .debug_macro section"),
15922                      version);
15923           return NULL;
15924         }
15925       mac_ptr += 2;
15926
15927       flags = read_1_byte (abfd, mac_ptr);
15928       ++mac_ptr;
15929       *offset_size = (flags & 1) ? 8 : 4;
15930
15931       if ((flags & 2) != 0)
15932         /* We don't need the line table offset.  */
15933         mac_ptr += *offset_size;
15934
15935       /* Vendor opcode descriptions.  */
15936       if ((flags & 4) != 0)
15937         {
15938           unsigned int i, count;
15939
15940           count = read_1_byte (abfd, mac_ptr);
15941           ++mac_ptr;
15942           for (i = 0; i < count; ++i)
15943             {
15944               unsigned int opcode, bytes_read;
15945               unsigned long arg;
15946
15947               opcode = read_1_byte (abfd, mac_ptr);
15948               ++mac_ptr;
15949               opcode_definitions[opcode] = mac_ptr;
15950               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
15951               mac_ptr += bytes_read;
15952               mac_ptr += arg;
15953             }
15954         }
15955     }
15956
15957   return mac_ptr;
15958 }
15959
15960 /* A helper for dwarf_decode_macros that handles the GNU extensions,
15961    including DW_MACRO_GNU_transparent_include.  */
15962
15963 static void
15964 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
15965                           struct macro_source_file *current_file,
15966                           struct line_header *lh, char *comp_dir,
15967                           struct dwarf2_section_info *section,
15968                           int section_is_gnu,
15969                           unsigned int offset_size,
15970                           struct objfile *objfile,
15971                           htab_t include_hash)
15972 {
15973   enum dwarf_macro_record_type macinfo_type;
15974   int at_commandline;
15975   gdb_byte *opcode_definitions[256];
15976
15977   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
15978                                       &offset_size, section_is_gnu);
15979   if (mac_ptr == NULL)
15980     {
15981       /* We already issued a complaint.  */
15982       return;
15983     }
15984
15985   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
15986      GDB is still reading the definitions from command line.  First
15987      DW_MACINFO_start_file will need to be ignored as it was already executed
15988      to create CURRENT_FILE for the main source holding also the command line
15989      definitions.  On first met DW_MACINFO_start_file this flag is reset to
15990      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
15991
15992   at_commandline = 1;
15993
15994   do
15995     {
15996       /* Do we at least have room for a macinfo type byte?  */
15997       if (mac_ptr >= mac_end)
15998         {
15999           dwarf2_macros_too_long_complaint (section);
16000           break;
16001         }
16002
16003       macinfo_type = read_1_byte (abfd, mac_ptr);
16004       mac_ptr++;
16005
16006       /* Note that we rely on the fact that the corresponding GNU and
16007          DWARF constants are the same.  */
16008       switch (macinfo_type)
16009         {
16010           /* A zero macinfo type indicates the end of the macro
16011              information.  */
16012         case 0:
16013           break;
16014
16015         case DW_MACRO_GNU_define:
16016         case DW_MACRO_GNU_undef:
16017         case DW_MACRO_GNU_define_indirect:
16018         case DW_MACRO_GNU_undef_indirect:
16019           {
16020             unsigned int bytes_read;
16021             int line;
16022             char *body;
16023             int is_define;
16024
16025             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16026             mac_ptr += bytes_read;
16027
16028             if (macinfo_type == DW_MACRO_GNU_define
16029                 || macinfo_type == DW_MACRO_GNU_undef)
16030               {
16031                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
16032                 mac_ptr += bytes_read;
16033               }
16034             else
16035               {
16036                 LONGEST str_offset;
16037
16038                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
16039                 mac_ptr += offset_size;
16040
16041                 body = read_indirect_string_at_offset (abfd, str_offset);
16042               }
16043
16044             is_define = (macinfo_type == DW_MACRO_GNU_define
16045                          || macinfo_type == DW_MACRO_GNU_define_indirect);
16046             if (! current_file)
16047               {
16048                 /* DWARF violation as no main source is present.  */
16049                 complaint (&symfile_complaints,
16050                            _("debug info with no main source gives macro %s "
16051                              "on line %d: %s"),
16052                            is_define ? _("definition") : _("undefinition"),
16053                            line, body);
16054                 break;
16055               }
16056             if ((line == 0 && !at_commandline)
16057                 || (line != 0 && at_commandline))
16058               complaint (&symfile_complaints,
16059                          _("debug info gives %s macro %s with %s line %d: %s"),
16060                          at_commandline ? _("command-line") : _("in-file"),
16061                          is_define ? _("definition") : _("undefinition"),
16062                          line == 0 ? _("zero") : _("non-zero"), line, body);
16063
16064             if (is_define)
16065               parse_macro_definition (current_file, line, body);
16066             else
16067               {
16068                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
16069                             || macinfo_type == DW_MACRO_GNU_undef_indirect);
16070                 macro_undef (current_file, line, body);
16071               }
16072           }
16073           break;
16074
16075         case DW_MACRO_GNU_start_file:
16076           {
16077             unsigned int bytes_read;
16078             int line, file;
16079
16080             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16081             mac_ptr += bytes_read;
16082             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16083             mac_ptr += bytes_read;
16084
16085             if ((line == 0 && !at_commandline)
16086                 || (line != 0 && at_commandline))
16087               complaint (&symfile_complaints,
16088                          _("debug info gives source %d included "
16089                            "from %s at %s line %d"),
16090                          file, at_commandline ? _("command-line") : _("file"),
16091                          line == 0 ? _("zero") : _("non-zero"), line);
16092
16093             if (at_commandline)
16094               {
16095                 /* This DW_MACRO_GNU_start_file was executed in the
16096                    pass one.  */
16097                 at_commandline = 0;
16098               }
16099             else
16100               current_file = macro_start_file (file, line,
16101                                                current_file, comp_dir,
16102                                                lh, objfile);
16103           }
16104           break;
16105
16106         case DW_MACRO_GNU_end_file:
16107           if (! current_file)
16108             complaint (&symfile_complaints,
16109                        _("macro debug info has an unmatched "
16110                          "`close_file' directive"));
16111           else
16112             {
16113               current_file = current_file->included_by;
16114               if (! current_file)
16115                 {
16116                   enum dwarf_macro_record_type next_type;
16117
16118                   /* GCC circa March 2002 doesn't produce the zero
16119                      type byte marking the end of the compilation
16120                      unit.  Complain if it's not there, but exit no
16121                      matter what.  */
16122
16123                   /* Do we at least have room for a macinfo type byte?  */
16124                   if (mac_ptr >= mac_end)
16125                     {
16126                       dwarf2_macros_too_long_complaint (section);
16127                       return;
16128                     }
16129
16130                   /* We don't increment mac_ptr here, so this is just
16131                      a look-ahead.  */
16132                   next_type = read_1_byte (abfd, mac_ptr);
16133                   if (next_type != 0)
16134                     complaint (&symfile_complaints,
16135                                _("no terminating 0-type entry for "
16136                                  "macros in `.debug_macinfo' section"));
16137
16138                   return;
16139                 }
16140             }
16141           break;
16142
16143         case DW_MACRO_GNU_transparent_include:
16144           {
16145             LONGEST offset;
16146             void **slot;
16147
16148             offset = read_offset_1 (abfd, mac_ptr, offset_size);
16149             mac_ptr += offset_size;
16150
16151             slot = htab_find_slot (include_hash, mac_ptr, INSERT);
16152             if (*slot != NULL)
16153               {
16154                 /* This has actually happened; see
16155                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
16156                 complaint (&symfile_complaints,
16157                            _("recursive DW_MACRO_GNU_transparent_include in "
16158                              ".debug_macro section"));
16159               }
16160             else
16161               {
16162                 *slot = mac_ptr;
16163
16164                 dwarf_decode_macro_bytes (abfd,
16165                                           section->buffer + offset,
16166                                           mac_end, current_file,
16167                                           lh, comp_dir,
16168                                           section, section_is_gnu,
16169                                           offset_size, objfile, include_hash);
16170
16171                 htab_remove_elt (include_hash, mac_ptr);
16172               }
16173           }
16174           break;
16175
16176         case DW_MACINFO_vendor_ext:
16177           if (!section_is_gnu)
16178             {
16179               unsigned int bytes_read;
16180               int constant;
16181
16182               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16183               mac_ptr += bytes_read;
16184               read_direct_string (abfd, mac_ptr, &bytes_read);
16185               mac_ptr += bytes_read;
16186
16187               /* We don't recognize any vendor extensions.  */
16188               break;
16189             }
16190           /* FALLTHROUGH */
16191
16192         default:
16193           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
16194                                          mac_ptr, abfd, offset_size,
16195                                          section);
16196           if (mac_ptr == NULL)
16197             return;
16198           break;
16199         }
16200     } while (macinfo_type != 0);
16201 }
16202
16203 static void
16204 dwarf_decode_macros (struct line_header *lh, unsigned int offset,
16205                      char *comp_dir, bfd *abfd,
16206                      struct dwarf2_cu *cu,
16207                      struct dwarf2_section_info *section,
16208                      int section_is_gnu, const char *section_name)
16209 {
16210   struct objfile *objfile = dwarf2_per_objfile->objfile;
16211   gdb_byte *mac_ptr, *mac_end;
16212   struct macro_source_file *current_file = 0;
16213   enum dwarf_macro_record_type macinfo_type;
16214   unsigned int offset_size = cu->header.offset_size;
16215   gdb_byte *opcode_definitions[256];
16216   struct cleanup *cleanup;
16217   htab_t include_hash;
16218   void **slot;
16219
16220   dwarf2_read_section (objfile, section);
16221   if (section->buffer == NULL)
16222     {
16223       complaint (&symfile_complaints, _("missing %s section"), section_name);
16224       return;
16225     }
16226
16227   /* First pass: Find the name of the base filename.
16228      This filename is needed in order to process all macros whose definition
16229      (or undefinition) comes from the command line.  These macros are defined
16230      before the first DW_MACINFO_start_file entry, and yet still need to be
16231      associated to the base file.
16232
16233      To determine the base file name, we scan the macro definitions until we
16234      reach the first DW_MACINFO_start_file entry.  We then initialize
16235      CURRENT_FILE accordingly so that any macro definition found before the
16236      first DW_MACINFO_start_file can still be associated to the base file.  */
16237
16238   mac_ptr = section->buffer + offset;
16239   mac_end = section->buffer + section->size;
16240
16241   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
16242                                       &offset_size, section_is_gnu);
16243   if (mac_ptr == NULL)
16244     {
16245       /* We already issued a complaint.  */
16246       return;
16247     }
16248
16249   do
16250     {
16251       /* Do we at least have room for a macinfo type byte?  */
16252       if (mac_ptr >= mac_end)
16253         {
16254           /* Complaint is printed during the second pass as GDB will probably
16255              stop the first pass earlier upon finding
16256              DW_MACINFO_start_file.  */
16257           break;
16258         }
16259
16260       macinfo_type = read_1_byte (abfd, mac_ptr);
16261       mac_ptr++;
16262
16263       /* Note that we rely on the fact that the corresponding GNU and
16264          DWARF constants are the same.  */
16265       switch (macinfo_type)
16266         {
16267           /* A zero macinfo type indicates the end of the macro
16268              information.  */
16269         case 0:
16270           break;
16271
16272         case DW_MACRO_GNU_define:
16273         case DW_MACRO_GNU_undef:
16274           /* Only skip the data by MAC_PTR.  */
16275           {
16276             unsigned int bytes_read;
16277
16278             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16279             mac_ptr += bytes_read;
16280             read_direct_string (abfd, mac_ptr, &bytes_read);
16281             mac_ptr += bytes_read;
16282           }
16283           break;
16284
16285         case DW_MACRO_GNU_start_file:
16286           {
16287             unsigned int bytes_read;
16288             int line, file;
16289
16290             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16291             mac_ptr += bytes_read;
16292             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16293             mac_ptr += bytes_read;
16294
16295             current_file = macro_start_file (file, line, current_file,
16296                                              comp_dir, lh, objfile);
16297           }
16298           break;
16299
16300         case DW_MACRO_GNU_end_file:
16301           /* No data to skip by MAC_PTR.  */
16302           break;
16303
16304         case DW_MACRO_GNU_define_indirect:
16305         case DW_MACRO_GNU_undef_indirect:
16306           {
16307             unsigned int bytes_read;
16308
16309             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16310             mac_ptr += bytes_read;
16311             mac_ptr += offset_size;
16312           }
16313           break;
16314
16315         case DW_MACRO_GNU_transparent_include:
16316           /* Note that, according to the spec, a transparent include
16317              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
16318              skip this opcode.  */
16319           mac_ptr += offset_size;
16320           break;
16321
16322         case DW_MACINFO_vendor_ext:
16323           /* Only skip the data by MAC_PTR.  */
16324           if (!section_is_gnu)
16325             {
16326               unsigned int bytes_read;
16327
16328               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
16329               mac_ptr += bytes_read;
16330               read_direct_string (abfd, mac_ptr, &bytes_read);
16331               mac_ptr += bytes_read;
16332             }
16333           /* FALLTHROUGH */
16334
16335         default:
16336           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
16337                                          mac_ptr, abfd, offset_size,
16338                                          section);
16339           if (mac_ptr == NULL)
16340             return;
16341           break;
16342         }
16343     } while (macinfo_type != 0 && current_file == NULL);
16344
16345   /* Second pass: Process all entries.
16346
16347      Use the AT_COMMAND_LINE flag to determine whether we are still processing
16348      command-line macro definitions/undefinitions.  This flag is unset when we
16349      reach the first DW_MACINFO_start_file entry.  */
16350
16351   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
16352                                     NULL, xcalloc, xfree);
16353   cleanup = make_cleanup_htab_delete (include_hash);
16354   mac_ptr = section->buffer + offset;
16355   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
16356   *slot = mac_ptr;
16357   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
16358                             current_file, lh, comp_dir, section, section_is_gnu,
16359                             offset_size, objfile, include_hash);
16360   do_cleanups (cleanup);
16361 }
16362
16363 /* Check if the attribute's form is a DW_FORM_block*
16364    if so return true else false.  */
16365
16366 static int
16367 attr_form_is_block (struct attribute *attr)
16368 {
16369   return (attr == NULL ? 0 :
16370       attr->form == DW_FORM_block1
16371       || attr->form == DW_FORM_block2
16372       || attr->form == DW_FORM_block4
16373       || attr->form == DW_FORM_block
16374       || attr->form == DW_FORM_exprloc);
16375 }
16376
16377 /* Return non-zero if ATTR's value is a section offset --- classes
16378    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
16379    You may use DW_UNSND (attr) to retrieve such offsets.
16380
16381    Section 7.5.4, "Attribute Encodings", explains that no attribute
16382    may have a value that belongs to more than one of these classes; it
16383    would be ambiguous if we did, because we use the same forms for all
16384    of them.  */
16385
16386 static int
16387 attr_form_is_section_offset (struct attribute *attr)
16388 {
16389   return (attr->form == DW_FORM_data4
16390           || attr->form == DW_FORM_data8
16391           || attr->form == DW_FORM_sec_offset);
16392 }
16393
16394 /* Return non-zero if ATTR's value falls in the 'constant' class, or
16395    zero otherwise.  When this function returns true, you can apply
16396    dwarf2_get_attr_constant_value to it.
16397
16398    However, note that for some attributes you must check
16399    attr_form_is_section_offset before using this test.  DW_FORM_data4
16400    and DW_FORM_data8 are members of both the constant class, and of
16401    the classes that contain offsets into other debug sections
16402    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
16403    that, if an attribute's can be either a constant or one of the
16404    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
16405    taken as section offsets, not constants.  */
16406
16407 static int
16408 attr_form_is_constant (struct attribute *attr)
16409 {
16410   switch (attr->form)
16411     {
16412     case DW_FORM_sdata:
16413     case DW_FORM_udata:
16414     case DW_FORM_data1:
16415     case DW_FORM_data2:
16416     case DW_FORM_data4:
16417     case DW_FORM_data8:
16418       return 1;
16419     default:
16420       return 0;
16421     }
16422 }
16423
16424 /* Return the .debug_loc section to use for CU.
16425    For DWO files use .debug_loc.dwo.  */
16426
16427 static struct dwarf2_section_info *
16428 cu_debug_loc_section (struct dwarf2_cu *cu)
16429 {
16430   if (cu->dwo_unit)
16431     return &cu->dwo_unit->dwo_file->sections.loc;
16432   return &dwarf2_per_objfile->loc;
16433 }
16434
16435 /* A helper function that fills in a dwarf2_loclist_baton.  */
16436
16437 static void
16438 fill_in_loclist_baton (struct dwarf2_cu *cu,
16439                        struct dwarf2_loclist_baton *baton,
16440                        struct attribute *attr)
16441 {
16442   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
16443
16444   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
16445
16446   baton->per_cu = cu->per_cu;
16447   gdb_assert (baton->per_cu);
16448   /* We don't know how long the location list is, but make sure we
16449      don't run off the edge of the section.  */
16450   baton->size = section->size - DW_UNSND (attr);
16451   baton->data = section->buffer + DW_UNSND (attr);
16452   baton->base_address = cu->base_address;
16453 }
16454
16455 static void
16456 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
16457                              struct dwarf2_cu *cu)
16458 {
16459   struct objfile *objfile = dwarf2_per_objfile->objfile;
16460   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
16461
16462   if (attr_form_is_section_offset (attr)
16463       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
16464          the section.  If so, fall through to the complaint in the
16465          other branch.  */
16466       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
16467     {
16468       struct dwarf2_loclist_baton *baton;
16469
16470       baton = obstack_alloc (&objfile->objfile_obstack,
16471                              sizeof (struct dwarf2_loclist_baton));
16472
16473       fill_in_loclist_baton (cu, baton, attr);
16474
16475       if (cu->base_known == 0)
16476         complaint (&symfile_complaints,
16477                    _("Location list used without "
16478                      "specifying the CU base address."));
16479
16480       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
16481       SYMBOL_LOCATION_BATON (sym) = baton;
16482     }
16483   else
16484     {
16485       struct dwarf2_locexpr_baton *baton;
16486
16487       baton = obstack_alloc (&objfile->objfile_obstack,
16488                              sizeof (struct dwarf2_locexpr_baton));
16489       baton->per_cu = cu->per_cu;
16490       gdb_assert (baton->per_cu);
16491
16492       if (attr_form_is_block (attr))
16493         {
16494           /* Note that we're just copying the block's data pointer
16495              here, not the actual data.  We're still pointing into the
16496              info_buffer for SYM's objfile; right now we never release
16497              that buffer, but when we do clean up properly this may
16498              need to change.  */
16499           baton->size = DW_BLOCK (attr)->size;
16500           baton->data = DW_BLOCK (attr)->data;
16501         }
16502       else
16503         {
16504           dwarf2_invalid_attrib_class_complaint ("location description",
16505                                                  SYMBOL_NATURAL_NAME (sym));
16506           baton->size = 0;
16507         }
16508
16509       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
16510       SYMBOL_LOCATION_BATON (sym) = baton;
16511     }
16512 }
16513
16514 /* Return the OBJFILE associated with the compilation unit CU.  If CU
16515    came from a separate debuginfo file, then the master objfile is
16516    returned.  */
16517
16518 struct objfile *
16519 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
16520 {
16521   struct objfile *objfile = per_cu->objfile;
16522
16523   /* Return the master objfile, so that we can report and look up the
16524      correct file containing this variable.  */
16525   if (objfile->separate_debug_objfile_backlink)
16526     objfile = objfile->separate_debug_objfile_backlink;
16527
16528   return objfile;
16529 }
16530
16531 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
16532    (CU_HEADERP is unused in such case) or prepare a temporary copy at
16533    CU_HEADERP first.  */
16534
16535 static const struct comp_unit_head *
16536 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
16537                        struct dwarf2_per_cu_data *per_cu)
16538 {
16539   struct objfile *objfile;
16540   struct dwarf2_per_objfile *per_objfile;
16541   gdb_byte *info_ptr;
16542
16543   if (per_cu->cu)
16544     return &per_cu->cu->header;
16545
16546   objfile = per_cu->objfile;
16547   per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
16548   info_ptr = per_objfile->info.buffer + per_cu->offset.sect_off;
16549
16550   memset (cu_headerp, 0, sizeof (*cu_headerp));
16551   read_comp_unit_head (cu_headerp, info_ptr, objfile->obfd);
16552
16553   return cu_headerp;
16554 }
16555
16556 /* Return the address size given in the compilation unit header for CU.  */
16557
16558 int
16559 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
16560 {
16561   struct comp_unit_head cu_header_local;
16562   const struct comp_unit_head *cu_headerp;
16563
16564   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
16565
16566   return cu_headerp->addr_size;
16567 }
16568
16569 /* Return the offset size given in the compilation unit header for CU.  */
16570
16571 int
16572 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
16573 {
16574   struct comp_unit_head cu_header_local;
16575   const struct comp_unit_head *cu_headerp;
16576
16577   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
16578
16579   return cu_headerp->offset_size;
16580 }
16581
16582 /* See its dwarf2loc.h declaration.  */
16583
16584 int
16585 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
16586 {
16587   struct comp_unit_head cu_header_local;
16588   const struct comp_unit_head *cu_headerp;
16589
16590   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
16591
16592   if (cu_headerp->version == 2)
16593     return cu_headerp->addr_size;
16594   else
16595     return cu_headerp->offset_size;
16596 }
16597
16598 /* Return the text offset of the CU.  The returned offset comes from
16599    this CU's objfile.  If this objfile came from a separate debuginfo
16600    file, then the offset may be different from the corresponding
16601    offset in the parent objfile.  */
16602
16603 CORE_ADDR
16604 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
16605 {
16606   struct objfile *objfile = per_cu->objfile;
16607
16608   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16609 }
16610
16611 /* Locate the .debug_info compilation unit from CU's objfile which contains
16612    the DIE at OFFSET.  Raises an error on failure.  */
16613
16614 static struct dwarf2_per_cu_data *
16615 dwarf2_find_containing_comp_unit (sect_offset offset,
16616                                   struct objfile *objfile)
16617 {
16618   struct dwarf2_per_cu_data *this_cu;
16619   int low, high;
16620
16621   low = 0;
16622   high = dwarf2_per_objfile->n_comp_units - 1;
16623   while (high > low)
16624     {
16625       int mid = low + (high - low) / 2;
16626
16627       if (dwarf2_per_objfile->all_comp_units[mid]->offset.sect_off
16628           >= offset.sect_off)
16629         high = mid;
16630       else
16631         low = mid + 1;
16632     }
16633   gdb_assert (low == high);
16634   if (dwarf2_per_objfile->all_comp_units[low]->offset.sect_off
16635       > offset.sect_off)
16636     {
16637       if (low == 0)
16638         error (_("Dwarf Error: could not find partial DIE containing "
16639                "offset 0x%lx [in module %s]"),
16640                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
16641
16642       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
16643                   <= offset.sect_off);
16644       return dwarf2_per_objfile->all_comp_units[low-1];
16645     }
16646   else
16647     {
16648       this_cu = dwarf2_per_objfile->all_comp_units[low];
16649       if (low == dwarf2_per_objfile->n_comp_units - 1
16650           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
16651         error (_("invalid dwarf2 offset %u"), offset.sect_off);
16652       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
16653       return this_cu;
16654     }
16655 }
16656
16657 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
16658
16659 static void
16660 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
16661 {
16662   memset (cu, 0, sizeof (*cu));
16663   per_cu->cu = cu;
16664   cu->per_cu = per_cu;
16665   cu->objfile = per_cu->objfile;
16666   obstack_init (&cu->comp_unit_obstack);
16667 }
16668
16669 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
16670
16671 static void
16672 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
16673                        enum language pretend_language)
16674 {
16675   struct attribute *attr;
16676
16677   /* Set the language we're debugging.  */
16678   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
16679   if (attr)
16680     set_cu_language (DW_UNSND (attr), cu);
16681   else
16682     {
16683       cu->language = pretend_language;
16684       cu->language_defn = language_def (cu->language);
16685     }
16686
16687   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
16688   if (attr)
16689     cu->producer = DW_STRING (attr);
16690 }
16691
16692 /* Release one cached compilation unit, CU.  We unlink it from the tree
16693    of compilation units, but we don't remove it from the read_in_chain;
16694    the caller is responsible for that.
16695    NOTE: DATA is a void * because this function is also used as a
16696    cleanup routine.  */
16697
16698 static void
16699 free_heap_comp_unit (void *data)
16700 {
16701   struct dwarf2_cu *cu = data;
16702
16703   gdb_assert (cu->per_cu != NULL);
16704   cu->per_cu->cu = NULL;
16705   cu->per_cu = NULL;
16706
16707   obstack_free (&cu->comp_unit_obstack, NULL);
16708
16709   xfree (cu);
16710 }
16711
16712 /* This cleanup function is passed the address of a dwarf2_cu on the stack
16713    when we're finished with it.  We can't free the pointer itself, but be
16714    sure to unlink it from the cache.  Also release any associated storage.  */
16715
16716 static void
16717 free_stack_comp_unit (void *data)
16718 {
16719   struct dwarf2_cu *cu = data;
16720
16721   gdb_assert (cu->per_cu != NULL);
16722   cu->per_cu->cu = NULL;
16723   cu->per_cu = NULL;
16724
16725   obstack_free (&cu->comp_unit_obstack, NULL);
16726   cu->partial_dies = NULL;
16727 }
16728
16729 /* Free all cached compilation units.  */
16730
16731 static void
16732 free_cached_comp_units (void *data)
16733 {
16734   struct dwarf2_per_cu_data *per_cu, **last_chain;
16735
16736   per_cu = dwarf2_per_objfile->read_in_chain;
16737   last_chain = &dwarf2_per_objfile->read_in_chain;
16738   while (per_cu != NULL)
16739     {
16740       struct dwarf2_per_cu_data *next_cu;
16741
16742       next_cu = per_cu->cu->read_in_chain;
16743
16744       free_heap_comp_unit (per_cu->cu);
16745       *last_chain = next_cu;
16746
16747       per_cu = next_cu;
16748     }
16749 }
16750
16751 /* Increase the age counter on each cached compilation unit, and free
16752    any that are too old.  */
16753
16754 static void
16755 age_cached_comp_units (void)
16756 {
16757   struct dwarf2_per_cu_data *per_cu, **last_chain;
16758
16759   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
16760   per_cu = dwarf2_per_objfile->read_in_chain;
16761   while (per_cu != NULL)
16762     {
16763       per_cu->cu->last_used ++;
16764       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
16765         dwarf2_mark (per_cu->cu);
16766       per_cu = per_cu->cu->read_in_chain;
16767     }
16768
16769   per_cu = dwarf2_per_objfile->read_in_chain;
16770   last_chain = &dwarf2_per_objfile->read_in_chain;
16771   while (per_cu != NULL)
16772     {
16773       struct dwarf2_per_cu_data *next_cu;
16774
16775       next_cu = per_cu->cu->read_in_chain;
16776
16777       if (!per_cu->cu->mark)
16778         {
16779           free_heap_comp_unit (per_cu->cu);
16780           *last_chain = next_cu;
16781         }
16782       else
16783         last_chain = &per_cu->cu->read_in_chain;
16784
16785       per_cu = next_cu;
16786     }
16787 }
16788
16789 /* Remove a single compilation unit from the cache.  */
16790
16791 static void
16792 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
16793 {
16794   struct dwarf2_per_cu_data *per_cu, **last_chain;
16795
16796   per_cu = dwarf2_per_objfile->read_in_chain;
16797   last_chain = &dwarf2_per_objfile->read_in_chain;
16798   while (per_cu != NULL)
16799     {
16800       struct dwarf2_per_cu_data *next_cu;
16801
16802       next_cu = per_cu->cu->read_in_chain;
16803
16804       if (per_cu == target_per_cu)
16805         {
16806           free_heap_comp_unit (per_cu->cu);
16807           per_cu->cu = NULL;
16808           *last_chain = next_cu;
16809           break;
16810         }
16811       else
16812         last_chain = &per_cu->cu->read_in_chain;
16813
16814       per_cu = next_cu;
16815     }
16816 }
16817
16818 /* Release all extra memory associated with OBJFILE.  */
16819
16820 void
16821 dwarf2_free_objfile (struct objfile *objfile)
16822 {
16823   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
16824
16825   if (dwarf2_per_objfile == NULL)
16826     return;
16827
16828   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
16829   free_cached_comp_units (NULL);
16830
16831   if (dwarf2_per_objfile->quick_file_names_table)
16832     htab_delete (dwarf2_per_objfile->quick_file_names_table);
16833
16834   /* Everything else should be on the objfile obstack.  */
16835 }
16836
16837 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
16838    We store these in a hash table separate from the DIEs, and preserve them
16839    when the DIEs are flushed out of cache.
16840
16841    The CU "per_cu" pointer is needed because offset alone is not enough to
16842    uniquely identify the type.  A file may have multiple .debug_types sections,
16843    or the type may come from a DWO file.  We have to use something in
16844    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
16845    routine, get_die_type_at_offset, from outside this file, and thus won't
16846    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
16847    of the objfile.  */
16848
16849 struct dwarf2_per_cu_offset_and_type
16850 {
16851   const struct dwarf2_per_cu_data *per_cu;
16852   sect_offset offset;
16853   struct type *type;
16854 };
16855
16856 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
16857
16858 static hashval_t
16859 per_cu_offset_and_type_hash (const void *item)
16860 {
16861   const struct dwarf2_per_cu_offset_and_type *ofs = item;
16862
16863   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
16864 }
16865
16866 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
16867
16868 static int
16869 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
16870 {
16871   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
16872   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
16873
16874   return (ofs_lhs->per_cu == ofs_rhs->per_cu
16875           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
16876 }
16877
16878 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
16879    table if necessary.  For convenience, return TYPE.
16880
16881    The DIEs reading must have careful ordering to:
16882     * Not cause infite loops trying to read in DIEs as a prerequisite for
16883       reading current DIE.
16884     * Not trying to dereference contents of still incompletely read in types
16885       while reading in other DIEs.
16886     * Enable referencing still incompletely read in types just by a pointer to
16887       the type without accessing its fields.
16888
16889    Therefore caller should follow these rules:
16890      * Try to fetch any prerequisite types we may need to build this DIE type
16891        before building the type and calling set_die_type.
16892      * After building type call set_die_type for current DIE as soon as
16893        possible before fetching more types to complete the current type.
16894      * Make the type as complete as possible before fetching more types.  */
16895
16896 static struct type *
16897 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16898 {
16899   struct dwarf2_per_cu_offset_and_type **slot, ofs;
16900   struct objfile *objfile = cu->objfile;
16901
16902   /* For Ada types, make sure that the gnat-specific data is always
16903      initialized (if not already set).  There are a few types where
16904      we should not be doing so, because the type-specific area is
16905      already used to hold some other piece of info (eg: TYPE_CODE_FLT
16906      where the type-specific area is used to store the floatformat).
16907      But this is not a problem, because the gnat-specific information
16908      is actually not needed for these types.  */
16909   if (need_gnat_info (cu)
16910       && TYPE_CODE (type) != TYPE_CODE_FUNC
16911       && TYPE_CODE (type) != TYPE_CODE_FLT
16912       && !HAVE_GNAT_AUX_INFO (type))
16913     INIT_GNAT_SPECIFIC (type);
16914
16915   if (dwarf2_per_objfile->die_type_hash == NULL)
16916     {
16917       dwarf2_per_objfile->die_type_hash =
16918         htab_create_alloc_ex (127,
16919                               per_cu_offset_and_type_hash,
16920                               per_cu_offset_and_type_eq,
16921                               NULL,
16922                               &objfile->objfile_obstack,
16923                               hashtab_obstack_allocate,
16924                               dummy_obstack_deallocate);
16925     }
16926
16927   ofs.per_cu = cu->per_cu;
16928   ofs.offset = die->offset;
16929   ofs.type = type;
16930   slot = (struct dwarf2_per_cu_offset_and_type **)
16931     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
16932   if (*slot)
16933     complaint (&symfile_complaints,
16934                _("A problem internal to GDB: DIE 0x%x has type already set"),
16935                die->offset.sect_off);
16936   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
16937   **slot = ofs;
16938   return type;
16939 }
16940
16941 /* Look up the type for the die at OFFSET in the appropriate type_hash
16942    table, or return NULL if the die does not have a saved type.  */
16943
16944 static struct type *
16945 get_die_type_at_offset (sect_offset offset,
16946                         struct dwarf2_per_cu_data *per_cu)
16947 {
16948   struct dwarf2_per_cu_offset_and_type *slot, ofs;
16949
16950   if (dwarf2_per_objfile->die_type_hash == NULL)
16951     return NULL;
16952
16953   ofs.per_cu = per_cu;
16954   ofs.offset = offset;
16955   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
16956   if (slot)
16957     return slot->type;
16958   else
16959     return NULL;
16960 }
16961
16962 /* Look up the type for DIE in the appropriate type_hash table,
16963    or return NULL if DIE does not have a saved type.  */
16964
16965 static struct type *
16966 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
16967 {
16968   return get_die_type_at_offset (die->offset, cu->per_cu);
16969 }
16970
16971 /* Add a dependence relationship from CU to REF_PER_CU.  */
16972
16973 static void
16974 dwarf2_add_dependence (struct dwarf2_cu *cu,
16975                        struct dwarf2_per_cu_data *ref_per_cu)
16976 {
16977   void **slot;
16978
16979   if (cu->dependencies == NULL)
16980     cu->dependencies
16981       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
16982                               NULL, &cu->comp_unit_obstack,
16983                               hashtab_obstack_allocate,
16984                               dummy_obstack_deallocate);
16985
16986   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
16987   if (*slot == NULL)
16988     *slot = ref_per_cu;
16989 }
16990
16991 /* Subroutine of dwarf2_mark to pass to htab_traverse.
16992    Set the mark field in every compilation unit in the
16993    cache that we must keep because we are keeping CU.  */
16994
16995 static int
16996 dwarf2_mark_helper (void **slot, void *data)
16997 {
16998   struct dwarf2_per_cu_data *per_cu;
16999
17000   per_cu = (struct dwarf2_per_cu_data *) *slot;
17001
17002   /* cu->dependencies references may not yet have been ever read if QUIT aborts
17003      reading of the chain.  As such dependencies remain valid it is not much
17004      useful to track and undo them during QUIT cleanups.  */
17005   if (per_cu->cu == NULL)
17006     return 1;
17007
17008   if (per_cu->cu->mark)
17009     return 1;
17010   per_cu->cu->mark = 1;
17011
17012   if (per_cu->cu->dependencies != NULL)
17013     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
17014
17015   return 1;
17016 }
17017
17018 /* Set the mark field in CU and in every other compilation unit in the
17019    cache that we must keep because we are keeping CU.  */
17020
17021 static void
17022 dwarf2_mark (struct dwarf2_cu *cu)
17023 {
17024   if (cu->mark)
17025     return;
17026   cu->mark = 1;
17027   if (cu->dependencies != NULL)
17028     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
17029 }
17030
17031 static void
17032 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
17033 {
17034   while (per_cu)
17035     {
17036       per_cu->cu->mark = 0;
17037       per_cu = per_cu->cu->read_in_chain;
17038     }
17039 }
17040
17041 /* Trivial hash function for partial_die_info: the hash value of a DIE
17042    is its offset in .debug_info for this objfile.  */
17043
17044 static hashval_t
17045 partial_die_hash (const void *item)
17046 {
17047   const struct partial_die_info *part_die = item;
17048
17049   return part_die->offset.sect_off;
17050 }
17051
17052 /* Trivial comparison function for partial_die_info structures: two DIEs
17053    are equal if they have the same offset.  */
17054
17055 static int
17056 partial_die_eq (const void *item_lhs, const void *item_rhs)
17057 {
17058   const struct partial_die_info *part_die_lhs = item_lhs;
17059   const struct partial_die_info *part_die_rhs = item_rhs;
17060
17061   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
17062 }
17063
17064 static struct cmd_list_element *set_dwarf2_cmdlist;
17065 static struct cmd_list_element *show_dwarf2_cmdlist;
17066
17067 static void
17068 set_dwarf2_cmd (char *args, int from_tty)
17069 {
17070   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
17071 }
17072
17073 static void
17074 show_dwarf2_cmd (char *args, int from_tty)
17075 {
17076   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
17077 }
17078
17079 /* If section described by INFO was mmapped, munmap it now.  */
17080
17081 static void
17082 munmap_section_buffer (struct dwarf2_section_info *info)
17083 {
17084   if (info->map_addr != NULL)
17085     {
17086 #ifdef HAVE_MMAP
17087       int res;
17088
17089       res = munmap (info->map_addr, info->map_len);
17090       gdb_assert (res == 0);
17091 #else
17092       /* Without HAVE_MMAP, we should never be here to begin with.  */
17093       gdb_assert_not_reached ("no mmap support");
17094 #endif
17095     }
17096 }
17097
17098 /* munmap debug sections for OBJFILE, if necessary.  */
17099
17100 static void
17101 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
17102 {
17103   struct dwarf2_per_objfile *data = d;
17104   int ix;
17105   struct dwarf2_section_info *section;
17106
17107   /* This is sorted according to the order they're defined in to make it easier
17108      to keep in sync.  */
17109   munmap_section_buffer (&data->info);
17110   munmap_section_buffer (&data->abbrev);
17111   munmap_section_buffer (&data->line);
17112   munmap_section_buffer (&data->loc);
17113   munmap_section_buffer (&data->macinfo);
17114   munmap_section_buffer (&data->macro);
17115   munmap_section_buffer (&data->str);
17116   munmap_section_buffer (&data->ranges);
17117   munmap_section_buffer (&data->addr);
17118   munmap_section_buffer (&data->frame);
17119   munmap_section_buffer (&data->eh_frame);
17120   munmap_section_buffer (&data->gdb_index);
17121
17122   for (ix = 0;
17123        VEC_iterate (dwarf2_section_info_def, data->types, ix, section);
17124        ++ix)
17125     munmap_section_buffer (section);
17126
17127   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
17128     VEC_free (dwarf2_per_cu_ptr,
17129               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
17130
17131   VEC_free (dwarf2_section_info_def, data->types);
17132
17133   if (data->dwo_files)
17134     free_dwo_files (data->dwo_files, objfile);
17135 }
17136
17137 \f
17138 /* The "save gdb-index" command.  */
17139
17140 /* The contents of the hash table we create when building the string
17141    table.  */
17142 struct strtab_entry
17143 {
17144   offset_type offset;
17145   const char *str;
17146 };
17147
17148 /* Hash function for a strtab_entry.
17149
17150    Function is used only during write_hash_table so no index format backward
17151    compatibility is needed.  */
17152
17153 static hashval_t
17154 hash_strtab_entry (const void *e)
17155 {
17156   const struct strtab_entry *entry = e;
17157   return mapped_index_string_hash (INT_MAX, entry->str);
17158 }
17159
17160 /* Equality function for a strtab_entry.  */
17161
17162 static int
17163 eq_strtab_entry (const void *a, const void *b)
17164 {
17165   const struct strtab_entry *ea = a;
17166   const struct strtab_entry *eb = b;
17167   return !strcmp (ea->str, eb->str);
17168 }
17169
17170 /* Create a strtab_entry hash table.  */
17171
17172 static htab_t
17173 create_strtab (void)
17174 {
17175   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
17176                             xfree, xcalloc, xfree);
17177 }
17178
17179 /* Add a string to the constant pool.  Return the string's offset in
17180    host order.  */
17181
17182 static offset_type
17183 add_string (htab_t table, struct obstack *cpool, const char *str)
17184 {
17185   void **slot;
17186   struct strtab_entry entry;
17187   struct strtab_entry *result;
17188
17189   entry.str = str;
17190   slot = htab_find_slot (table, &entry, INSERT);
17191   if (*slot)
17192     result = *slot;
17193   else
17194     {
17195       result = XNEW (struct strtab_entry);
17196       result->offset = obstack_object_size (cpool);
17197       result->str = str;
17198       obstack_grow_str0 (cpool, str);
17199       *slot = result;
17200     }
17201   return result->offset;
17202 }
17203
17204 /* An entry in the symbol table.  */
17205 struct symtab_index_entry
17206 {
17207   /* The name of the symbol.  */
17208   const char *name;
17209   /* The offset of the name in the constant pool.  */
17210   offset_type index_offset;
17211   /* A sorted vector of the indices of all the CUs that hold an object
17212      of this name.  */
17213   VEC (offset_type) *cu_indices;
17214 };
17215
17216 /* The symbol table.  This is a power-of-2-sized hash table.  */
17217 struct mapped_symtab
17218 {
17219   offset_type n_elements;
17220   offset_type size;
17221   struct symtab_index_entry **data;
17222 };
17223
17224 /* Hash function for a symtab_index_entry.  */
17225
17226 static hashval_t
17227 hash_symtab_entry (const void *e)
17228 {
17229   const struct symtab_index_entry *entry = e;
17230   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
17231                          sizeof (offset_type) * VEC_length (offset_type,
17232                                                             entry->cu_indices),
17233                          0);
17234 }
17235
17236 /* Equality function for a symtab_index_entry.  */
17237
17238 static int
17239 eq_symtab_entry (const void *a, const void *b)
17240 {
17241   const struct symtab_index_entry *ea = a;
17242   const struct symtab_index_entry *eb = b;
17243   int len = VEC_length (offset_type, ea->cu_indices);
17244   if (len != VEC_length (offset_type, eb->cu_indices))
17245     return 0;
17246   return !memcmp (VEC_address (offset_type, ea->cu_indices),
17247                   VEC_address (offset_type, eb->cu_indices),
17248                   sizeof (offset_type) * len);
17249 }
17250
17251 /* Destroy a symtab_index_entry.  */
17252
17253 static void
17254 delete_symtab_entry (void *p)
17255 {
17256   struct symtab_index_entry *entry = p;
17257   VEC_free (offset_type, entry->cu_indices);
17258   xfree (entry);
17259 }
17260
17261 /* Create a hash table holding symtab_index_entry objects.  */
17262
17263 static htab_t
17264 create_symbol_hash_table (void)
17265 {
17266   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
17267                             delete_symtab_entry, xcalloc, xfree);
17268 }
17269
17270 /* Create a new mapped symtab object.  */
17271
17272 static struct mapped_symtab *
17273 create_mapped_symtab (void)
17274 {
17275   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
17276   symtab->n_elements = 0;
17277   symtab->size = 1024;
17278   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
17279   return symtab;
17280 }
17281
17282 /* Destroy a mapped_symtab.  */
17283
17284 static void
17285 cleanup_mapped_symtab (void *p)
17286 {
17287   struct mapped_symtab *symtab = p;
17288   /* The contents of the array are freed when the other hash table is
17289      destroyed.  */
17290   xfree (symtab->data);
17291   xfree (symtab);
17292 }
17293
17294 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
17295    the slot.
17296    
17297    Function is used only during write_hash_table so no index format backward
17298    compatibility is needed.  */
17299
17300 static struct symtab_index_entry **
17301 find_slot (struct mapped_symtab *symtab, const char *name)
17302 {
17303   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
17304
17305   index = hash & (symtab->size - 1);
17306   step = ((hash * 17) & (symtab->size - 1)) | 1;
17307
17308   for (;;)
17309     {
17310       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
17311         return &symtab->data[index];
17312       index = (index + step) & (symtab->size - 1);
17313     }
17314 }
17315
17316 /* Expand SYMTAB's hash table.  */
17317
17318 static void
17319 hash_expand (struct mapped_symtab *symtab)
17320 {
17321   offset_type old_size = symtab->size;
17322   offset_type i;
17323   struct symtab_index_entry **old_entries = symtab->data;
17324
17325   symtab->size *= 2;
17326   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
17327
17328   for (i = 0; i < old_size; ++i)
17329     {
17330       if (old_entries[i])
17331         {
17332           struct symtab_index_entry **slot = find_slot (symtab,
17333                                                         old_entries[i]->name);
17334           *slot = old_entries[i];
17335         }
17336     }
17337
17338   xfree (old_entries);
17339 }
17340
17341 /* Add an entry to SYMTAB.  NAME is the name of the symbol.  CU_INDEX
17342    is the index of the CU in which the symbol appears.  */
17343
17344 static void
17345 add_index_entry (struct mapped_symtab *symtab, const char *name,
17346                  offset_type cu_index)
17347 {
17348   struct symtab_index_entry **slot;
17349
17350   ++symtab->n_elements;
17351   if (4 * symtab->n_elements / 3 >= symtab->size)
17352     hash_expand (symtab);
17353
17354   slot = find_slot (symtab, name);
17355   if (!*slot)
17356     {
17357       *slot = XNEW (struct symtab_index_entry);
17358       (*slot)->name = name;
17359       (*slot)->cu_indices = NULL;
17360     }
17361   /* Don't push an index twice.  Due to how we add entries we only
17362      have to check the last one.  */ 
17363   if (VEC_empty (offset_type, (*slot)->cu_indices)
17364       || VEC_last (offset_type, (*slot)->cu_indices) != cu_index)
17365     VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index);
17366 }
17367
17368 /* Add a vector of indices to the constant pool.  */
17369
17370 static offset_type
17371 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
17372                       struct symtab_index_entry *entry)
17373 {
17374   void **slot;
17375
17376   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
17377   if (!*slot)
17378     {
17379       offset_type len = VEC_length (offset_type, entry->cu_indices);
17380       offset_type val = MAYBE_SWAP (len);
17381       offset_type iter;
17382       int i;
17383
17384       *slot = entry;
17385       entry->index_offset = obstack_object_size (cpool);
17386
17387       obstack_grow (cpool, &val, sizeof (val));
17388       for (i = 0;
17389            VEC_iterate (offset_type, entry->cu_indices, i, iter);
17390            ++i)
17391         {
17392           val = MAYBE_SWAP (iter);
17393           obstack_grow (cpool, &val, sizeof (val));
17394         }
17395     }
17396   else
17397     {
17398       struct symtab_index_entry *old_entry = *slot;
17399       entry->index_offset = old_entry->index_offset;
17400       entry = old_entry;
17401     }
17402   return entry->index_offset;
17403 }
17404
17405 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
17406    constant pool entries going into the obstack CPOOL.  */
17407
17408 static void
17409 write_hash_table (struct mapped_symtab *symtab,
17410                   struct obstack *output, struct obstack *cpool)
17411 {
17412   offset_type i;
17413   htab_t symbol_hash_table;
17414   htab_t str_table;
17415
17416   symbol_hash_table = create_symbol_hash_table ();
17417   str_table = create_strtab ();
17418
17419   /* We add all the index vectors to the constant pool first, to
17420      ensure alignment is ok.  */
17421   for (i = 0; i < symtab->size; ++i)
17422     {
17423       if (symtab->data[i])
17424         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
17425     }
17426
17427   /* Now write out the hash table.  */
17428   for (i = 0; i < symtab->size; ++i)
17429     {
17430       offset_type str_off, vec_off;
17431
17432       if (symtab->data[i])
17433         {
17434           str_off = add_string (str_table, cpool, symtab->data[i]->name);
17435           vec_off = symtab->data[i]->index_offset;
17436         }
17437       else
17438         {
17439           /* While 0 is a valid constant pool index, it is not valid
17440              to have 0 for both offsets.  */
17441           str_off = 0;
17442           vec_off = 0;
17443         }
17444
17445       str_off = MAYBE_SWAP (str_off);
17446       vec_off = MAYBE_SWAP (vec_off);
17447
17448       obstack_grow (output, &str_off, sizeof (str_off));
17449       obstack_grow (output, &vec_off, sizeof (vec_off));
17450     }
17451
17452   htab_delete (str_table);
17453   htab_delete (symbol_hash_table);
17454 }
17455
17456 /* Struct to map psymtab to CU index in the index file.  */
17457 struct psymtab_cu_index_map
17458 {
17459   struct partial_symtab *psymtab;
17460   unsigned int cu_index;
17461 };
17462
17463 static hashval_t
17464 hash_psymtab_cu_index (const void *item)
17465 {
17466   const struct psymtab_cu_index_map *map = item;
17467
17468   return htab_hash_pointer (map->psymtab);
17469 }
17470
17471 static int
17472 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
17473 {
17474   const struct psymtab_cu_index_map *lhs = item_lhs;
17475   const struct psymtab_cu_index_map *rhs = item_rhs;
17476
17477   return lhs->psymtab == rhs->psymtab;
17478 }
17479
17480 /* Helper struct for building the address table.  */
17481 struct addrmap_index_data
17482 {
17483   struct objfile *objfile;
17484   struct obstack *addr_obstack;
17485   htab_t cu_index_htab;
17486
17487   /* Non-zero if the previous_* fields are valid.
17488      We can't write an entry until we see the next entry (since it is only then
17489      that we know the end of the entry).  */
17490   int previous_valid;
17491   /* Index of the CU in the table of all CUs in the index file.  */
17492   unsigned int previous_cu_index;
17493   /* Start address of the CU.  */
17494   CORE_ADDR previous_cu_start;
17495 };
17496
17497 /* Write an address entry to OBSTACK.  */
17498
17499 static void
17500 add_address_entry (struct objfile *objfile, struct obstack *obstack,
17501                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
17502 {
17503   offset_type cu_index_to_write;
17504   char addr[8];
17505   CORE_ADDR baseaddr;
17506
17507   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17508
17509   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
17510   obstack_grow (obstack, addr, 8);
17511   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
17512   obstack_grow (obstack, addr, 8);
17513   cu_index_to_write = MAYBE_SWAP (cu_index);
17514   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
17515 }
17516
17517 /* Worker function for traversing an addrmap to build the address table.  */
17518
17519 static int
17520 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
17521 {
17522   struct addrmap_index_data *data = datap;
17523   struct partial_symtab *pst = obj;
17524
17525   if (data->previous_valid)
17526     add_address_entry (data->objfile, data->addr_obstack,
17527                        data->previous_cu_start, start_addr,
17528                        data->previous_cu_index);
17529
17530   data->previous_cu_start = start_addr;
17531   if (pst != NULL)
17532     {
17533       struct psymtab_cu_index_map find_map, *map;
17534       find_map.psymtab = pst;
17535       map = htab_find (data->cu_index_htab, &find_map);
17536       gdb_assert (map != NULL);
17537       data->previous_cu_index = map->cu_index;
17538       data->previous_valid = 1;
17539     }
17540   else
17541       data->previous_valid = 0;
17542
17543   return 0;
17544 }
17545
17546 /* Write OBJFILE's address map to OBSTACK.
17547    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
17548    in the index file.  */
17549
17550 static void
17551 write_address_map (struct objfile *objfile, struct obstack *obstack,
17552                    htab_t cu_index_htab)
17553 {
17554   struct addrmap_index_data addrmap_index_data;
17555
17556   /* When writing the address table, we have to cope with the fact that
17557      the addrmap iterator only provides the start of a region; we have to
17558      wait until the next invocation to get the start of the next region.  */
17559
17560   addrmap_index_data.objfile = objfile;
17561   addrmap_index_data.addr_obstack = obstack;
17562   addrmap_index_data.cu_index_htab = cu_index_htab;
17563   addrmap_index_data.previous_valid = 0;
17564
17565   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
17566                    &addrmap_index_data);
17567
17568   /* It's highly unlikely the last entry (end address = 0xff...ff)
17569      is valid, but we should still handle it.
17570      The end address is recorded as the start of the next region, but that
17571      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
17572      anyway.  */
17573   if (addrmap_index_data.previous_valid)
17574     add_address_entry (objfile, obstack,
17575                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
17576                        addrmap_index_data.previous_cu_index);
17577 }
17578
17579 /* Add a list of partial symbols to SYMTAB.  */
17580
17581 static void
17582 write_psymbols (struct mapped_symtab *symtab,
17583                 htab_t psyms_seen,
17584                 struct partial_symbol **psymp,
17585                 int count,
17586                 offset_type cu_index,
17587                 int is_static)
17588 {
17589   for (; count-- > 0; ++psymp)
17590     {
17591       void **slot, *lookup;
17592
17593       if (SYMBOL_LANGUAGE (*psymp) == language_ada)
17594         error (_("Ada is not currently supported by the index"));
17595
17596       /* We only want to add a given psymbol once.  However, we also
17597          want to account for whether it is global or static.  So, we
17598          may add it twice, using slightly different values.  */
17599       if (is_static)
17600         {
17601           uintptr_t val = 1 | (uintptr_t) *psymp;
17602
17603           lookup = (void *) val;
17604         }
17605       else
17606         lookup = *psymp;
17607
17608       /* Only add a given psymbol once.  */
17609       slot = htab_find_slot (psyms_seen, lookup, INSERT);
17610       if (!*slot)
17611         {
17612           *slot = lookup;
17613           add_index_entry (symtab, SYMBOL_SEARCH_NAME (*psymp), cu_index);
17614         }
17615     }
17616 }
17617
17618 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
17619    exception if there is an error.  */
17620
17621 static void
17622 write_obstack (FILE *file, struct obstack *obstack)
17623 {
17624   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
17625               file)
17626       != obstack_object_size (obstack))
17627     error (_("couldn't data write to file"));
17628 }
17629
17630 /* Unlink a file if the argument is not NULL.  */
17631
17632 static void
17633 unlink_if_set (void *p)
17634 {
17635   char **filename = p;
17636   if (*filename)
17637     unlink (*filename);
17638 }
17639
17640 /* A helper struct used when iterating over debug_types.  */
17641 struct signatured_type_index_data
17642 {
17643   struct objfile *objfile;
17644   struct mapped_symtab *symtab;
17645   struct obstack *types_list;
17646   htab_t psyms_seen;
17647   int cu_index;
17648 };
17649
17650 /* A helper function that writes a single signatured_type to an
17651    obstack.  */
17652
17653 static int
17654 write_one_signatured_type (void **slot, void *d)
17655 {
17656   struct signatured_type_index_data *info = d;
17657   struct signatured_type *entry = (struct signatured_type *) *slot;
17658   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
17659   struct partial_symtab *psymtab = per_cu->v.psymtab;
17660   gdb_byte val[8];
17661
17662   write_psymbols (info->symtab,
17663                   info->psyms_seen,
17664                   info->objfile->global_psymbols.list
17665                   + psymtab->globals_offset,
17666                   psymtab->n_global_syms, info->cu_index,
17667                   0);
17668   write_psymbols (info->symtab,
17669                   info->psyms_seen,
17670                   info->objfile->static_psymbols.list
17671                   + psymtab->statics_offset,
17672                   psymtab->n_static_syms, info->cu_index,
17673                   1);
17674
17675   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
17676                           entry->per_cu.offset.sect_off);
17677   obstack_grow (info->types_list, val, 8);
17678   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
17679                           entry->type_offset_in_tu.cu_off);
17680   obstack_grow (info->types_list, val, 8);
17681   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
17682   obstack_grow (info->types_list, val, 8);
17683
17684   ++info->cu_index;
17685
17686   return 1;
17687 }
17688
17689 /* Recurse into all "included" dependencies and write their symbols as
17690    if they appeared in this psymtab.  */
17691
17692 static void
17693 recursively_write_psymbols (struct objfile *objfile,
17694                             struct partial_symtab *psymtab,
17695                             struct mapped_symtab *symtab,
17696                             htab_t psyms_seen,
17697                             offset_type cu_index)
17698 {
17699   int i;
17700
17701   for (i = 0; i < psymtab->number_of_dependencies; ++i)
17702     if (psymtab->dependencies[i]->user != NULL)
17703       recursively_write_psymbols (objfile, psymtab->dependencies[i],
17704                                   symtab, psyms_seen, cu_index);
17705
17706   write_psymbols (symtab,
17707                   psyms_seen,
17708                   objfile->global_psymbols.list + psymtab->globals_offset,
17709                   psymtab->n_global_syms, cu_index,
17710                   0);
17711   write_psymbols (symtab,
17712                   psyms_seen,
17713                   objfile->static_psymbols.list + psymtab->statics_offset,
17714                   psymtab->n_static_syms, cu_index,
17715                   1);
17716 }
17717
17718 /* Create an index file for OBJFILE in the directory DIR.  */
17719
17720 static void
17721 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
17722 {
17723   struct cleanup *cleanup;
17724   char *filename, *cleanup_filename;
17725   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
17726   struct obstack cu_list, types_cu_list;
17727   int i;
17728   FILE *out_file;
17729   struct mapped_symtab *symtab;
17730   offset_type val, size_of_contents, total_len;
17731   struct stat st;
17732   htab_t psyms_seen;
17733   htab_t cu_index_htab;
17734   struct psymtab_cu_index_map *psymtab_cu_index_map;
17735
17736   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
17737     return;
17738
17739   if (dwarf2_per_objfile->using_index)
17740     error (_("Cannot use an index to create the index"));
17741
17742   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
17743     error (_("Cannot make an index when the file has multiple .debug_types sections"));
17744
17745   if (stat (objfile->name, &st) < 0)
17746     perror_with_name (objfile->name);
17747
17748   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
17749                      INDEX_SUFFIX, (char *) NULL);
17750   cleanup = make_cleanup (xfree, filename);
17751
17752   out_file = fopen (filename, "wb");
17753   if (!out_file)
17754     error (_("Can't open `%s' for writing"), filename);
17755
17756   cleanup_filename = filename;
17757   make_cleanup (unlink_if_set, &cleanup_filename);
17758
17759   symtab = create_mapped_symtab ();
17760   make_cleanup (cleanup_mapped_symtab, symtab);
17761
17762   obstack_init (&addr_obstack);
17763   make_cleanup_obstack_free (&addr_obstack);
17764
17765   obstack_init (&cu_list);
17766   make_cleanup_obstack_free (&cu_list);
17767
17768   obstack_init (&types_cu_list);
17769   make_cleanup_obstack_free (&types_cu_list);
17770
17771   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
17772                                   NULL, xcalloc, xfree);
17773   make_cleanup_htab_delete (psyms_seen);
17774
17775   /* While we're scanning CU's create a table that maps a psymtab pointer
17776      (which is what addrmap records) to its index (which is what is recorded
17777      in the index file).  This will later be needed to write the address
17778      table.  */
17779   cu_index_htab = htab_create_alloc (100,
17780                                      hash_psymtab_cu_index,
17781                                      eq_psymtab_cu_index,
17782                                      NULL, xcalloc, xfree);
17783   make_cleanup_htab_delete (cu_index_htab);
17784   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
17785     xmalloc (sizeof (struct psymtab_cu_index_map)
17786              * dwarf2_per_objfile->n_comp_units);
17787   make_cleanup (xfree, psymtab_cu_index_map);
17788
17789   /* The CU list is already sorted, so we don't need to do additional
17790      work here.  Also, the debug_types entries do not appear in
17791      all_comp_units, but only in their own hash table.  */
17792   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
17793     {
17794       struct dwarf2_per_cu_data *per_cu
17795         = dwarf2_per_objfile->all_comp_units[i];
17796       struct partial_symtab *psymtab = per_cu->v.psymtab;
17797       gdb_byte val[8];
17798       struct psymtab_cu_index_map *map;
17799       void **slot;
17800
17801       if (psymtab->user == NULL)
17802         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
17803
17804       map = &psymtab_cu_index_map[i];
17805       map->psymtab = psymtab;
17806       map->cu_index = i;
17807       slot = htab_find_slot (cu_index_htab, map, INSERT);
17808       gdb_assert (slot != NULL);
17809       gdb_assert (*slot == NULL);
17810       *slot = map;
17811
17812       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
17813                               per_cu->offset.sect_off);
17814       obstack_grow (&cu_list, val, 8);
17815       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
17816       obstack_grow (&cu_list, val, 8);
17817     }
17818
17819   /* Dump the address map.  */
17820   write_address_map (objfile, &addr_obstack, cu_index_htab);
17821
17822   /* Write out the .debug_type entries, if any.  */
17823   if (dwarf2_per_objfile->signatured_types)
17824     {
17825       struct signatured_type_index_data sig_data;
17826
17827       sig_data.objfile = objfile;
17828       sig_data.symtab = symtab;
17829       sig_data.types_list = &types_cu_list;
17830       sig_data.psyms_seen = psyms_seen;
17831       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
17832       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
17833                               write_one_signatured_type, &sig_data);
17834     }
17835
17836   obstack_init (&constant_pool);
17837   make_cleanup_obstack_free (&constant_pool);
17838   obstack_init (&symtab_obstack);
17839   make_cleanup_obstack_free (&symtab_obstack);
17840   write_hash_table (symtab, &symtab_obstack, &constant_pool);
17841
17842   obstack_init (&contents);
17843   make_cleanup_obstack_free (&contents);
17844   size_of_contents = 6 * sizeof (offset_type);
17845   total_len = size_of_contents;
17846
17847   /* The version number.  */
17848   val = MAYBE_SWAP (6);
17849   obstack_grow (&contents, &val, sizeof (val));
17850
17851   /* The offset of the CU list from the start of the file.  */
17852   val = MAYBE_SWAP (total_len);
17853   obstack_grow (&contents, &val, sizeof (val));
17854   total_len += obstack_object_size (&cu_list);
17855
17856   /* The offset of the types CU list from the start of the file.  */
17857   val = MAYBE_SWAP (total_len);
17858   obstack_grow (&contents, &val, sizeof (val));
17859   total_len += obstack_object_size (&types_cu_list);
17860
17861   /* The offset of the address table from the start of the file.  */
17862   val = MAYBE_SWAP (total_len);
17863   obstack_grow (&contents, &val, sizeof (val));
17864   total_len += obstack_object_size (&addr_obstack);
17865
17866   /* The offset of the symbol table from the start of the file.  */
17867   val = MAYBE_SWAP (total_len);
17868   obstack_grow (&contents, &val, sizeof (val));
17869   total_len += obstack_object_size (&symtab_obstack);
17870
17871   /* The offset of the constant pool from the start of the file.  */
17872   val = MAYBE_SWAP (total_len);
17873   obstack_grow (&contents, &val, sizeof (val));
17874   total_len += obstack_object_size (&constant_pool);
17875
17876   gdb_assert (obstack_object_size (&contents) == size_of_contents);
17877
17878   write_obstack (out_file, &contents);
17879   write_obstack (out_file, &cu_list);
17880   write_obstack (out_file, &types_cu_list);
17881   write_obstack (out_file, &addr_obstack);
17882   write_obstack (out_file, &symtab_obstack);
17883   write_obstack (out_file, &constant_pool);
17884
17885   fclose (out_file);
17886
17887   /* We want to keep the file, so we set cleanup_filename to NULL
17888      here.  See unlink_if_set.  */
17889   cleanup_filename = NULL;
17890
17891   do_cleanups (cleanup);
17892 }
17893
17894 /* Implementation of the `save gdb-index' command.
17895    
17896    Note that the file format used by this command is documented in the
17897    GDB manual.  Any changes here must be documented there.  */
17898
17899 static void
17900 save_gdb_index_command (char *arg, int from_tty)
17901 {
17902   struct objfile *objfile;
17903
17904   if (!arg || !*arg)
17905     error (_("usage: save gdb-index DIRECTORY"));
17906
17907   ALL_OBJFILES (objfile)
17908   {
17909     struct stat st;
17910
17911     /* If the objfile does not correspond to an actual file, skip it.  */
17912     if (stat (objfile->name, &st) < 0)
17913       continue;
17914
17915     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
17916     if (dwarf2_per_objfile)
17917       {
17918         volatile struct gdb_exception except;
17919
17920         TRY_CATCH (except, RETURN_MASK_ERROR)
17921           {
17922             write_psymtabs_to_index (objfile, arg);
17923           }
17924         if (except.reason < 0)
17925           exception_fprintf (gdb_stderr, except,
17926                              _("Error while writing index for `%s': "),
17927                              objfile->name);
17928       }
17929   }
17930 }
17931
17932 \f
17933
17934 int dwarf2_always_disassemble;
17935
17936 static void
17937 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
17938                                 struct cmd_list_element *c, const char *value)
17939 {
17940   fprintf_filtered (file,
17941                     _("Whether to always disassemble "
17942                       "DWARF expressions is %s.\n"),
17943                     value);
17944 }
17945
17946 static void
17947 show_check_physname (struct ui_file *file, int from_tty,
17948                      struct cmd_list_element *c, const char *value)
17949 {
17950   fprintf_filtered (file,
17951                     _("Whether to check \"physname\" is %s.\n"),
17952                     value);
17953 }
17954
17955 void _initialize_dwarf2_read (void);
17956
17957 void
17958 _initialize_dwarf2_read (void)
17959 {
17960   struct cmd_list_element *c;
17961
17962   dwarf2_objfile_data_key
17963     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
17964
17965   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
17966 Set DWARF 2 specific variables.\n\
17967 Configure DWARF 2 variables such as the cache size"),
17968                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
17969                   0/*allow-unknown*/, &maintenance_set_cmdlist);
17970
17971   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
17972 Show DWARF 2 specific variables\n\
17973 Show DWARF 2 variables such as the cache size"),
17974                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
17975                   0/*allow-unknown*/, &maintenance_show_cmdlist);
17976
17977   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
17978                             &dwarf2_max_cache_age, _("\
17979 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
17980 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
17981 A higher limit means that cached compilation units will be stored\n\
17982 in memory longer, and more total memory will be used.  Zero disables\n\
17983 caching, which can slow down startup."),
17984                             NULL,
17985                             show_dwarf2_max_cache_age,
17986                             &set_dwarf2_cmdlist,
17987                             &show_dwarf2_cmdlist);
17988
17989   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
17990                            &dwarf2_always_disassemble, _("\
17991 Set whether `info address' always disassembles DWARF expressions."), _("\
17992 Show whether `info address' always disassembles DWARF expressions."), _("\
17993 When enabled, DWARF expressions are always printed in an assembly-like\n\
17994 syntax.  When disabled, expressions will be printed in a more\n\
17995 conversational style, when possible."),
17996                            NULL,
17997                            show_dwarf2_always_disassemble,
17998                            &set_dwarf2_cmdlist,
17999                            &show_dwarf2_cmdlist);
18000
18001   add_setshow_zinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
18002 Set debugging of the dwarf2 DIE reader."), _("\
18003 Show debugging of the dwarf2 DIE reader."), _("\
18004 When enabled (non-zero), DIEs are dumped after they are read in.\n\
18005 The value is the maximum depth to print."),
18006                             NULL,
18007                             NULL,
18008                             &setdebuglist, &showdebuglist);
18009
18010   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
18011 Set cross-checking of \"physname\" code against demangler."), _("\
18012 Show cross-checking of \"physname\" code against demangler."), _("\
18013 When enabled, GDB's internal \"physname\" code is checked against\n\
18014 the demangler."),
18015                            NULL, show_check_physname,
18016                            &setdebuglist, &showdebuglist);
18017
18018   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
18019                _("\
18020 Save a gdb-index file.\n\
18021 Usage: save gdb-index DIRECTORY"),
18022                &save_cmdlist);
18023   set_cmd_completer (c, filename_completer);
18024 }