include/
[platform/upstream/binutils.git] / bfd / dwarf2.c
1 /* DWARF 2 support.
2    Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3    2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4
5    Adapted from gdb/dwarf2read.c by Gavin Koch of Cygnus Solutions
6    (gavin@cygnus.com).
7
8    From the dwarf2read.c header:
9    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
10    Inc.  with support from Florida State University (under contract
11    with the Ada Joint Program Office), and Silicon Graphics, Inc.
12    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
13    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
14    support in dwarfread.c
15
16    This file is part of BFD.
17
18    This program is free software; you can redistribute it and/or modify
19    it under the terms of the GNU General Public License as published by
20    the Free Software Foundation; either version 3 of the License, or (at
21    your option) any later version.
22
23    This program is distributed in the hope that it will be useful, but
24    WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
26    General Public License for more details.
27
28    You should have received a copy of the GNU General Public License
29    along with this program; if not, write to the Free Software
30    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
31    MA 02110-1301, USA.  */
32
33 #include "sysdep.h"
34 #include "bfd.h"
35 #include "libiberty.h"
36 #include "libbfd.h"
37 #include "elf-bfd.h"
38 #include "dwarf2.h"
39
40 /* The data in the .debug_line statement prologue looks like this.  */
41
42 struct line_head
43 {
44   bfd_vma total_length;
45   unsigned short version;
46   bfd_vma prologue_length;
47   unsigned char minimum_instruction_length;
48   unsigned char maximum_ops_per_insn;
49   unsigned char default_is_stmt;
50   int line_base;
51   unsigned char line_range;
52   unsigned char opcode_base;
53   unsigned char *standard_opcode_lengths;
54 };
55
56 /* Attributes have a name and a value.  */
57
58 struct attribute
59 {
60   enum dwarf_attribute name;
61   enum dwarf_form form;
62   union
63   {
64     char *str;
65     struct dwarf_block *blk;
66     bfd_uint64_t val;
67     bfd_int64_t sval;
68   }
69   u;
70 };
71
72 /* Blocks are a bunch of untyped bytes.  */
73 struct dwarf_block
74 {
75   unsigned int size;
76   bfd_byte *data;
77 };
78
79 struct adjusted_section
80 {
81   asection *section;
82   bfd_vma adj_vma;
83 };
84
85 struct dwarf2_debug
86 {
87   /* A list of all previously read comp_units.  */
88   struct comp_unit *all_comp_units;
89
90   /* Last comp unit in list above.  */
91   struct comp_unit *last_comp_unit;
92
93   /* The next unread compilation unit within the .debug_info section.
94      Zero indicates that the .debug_info section has not been loaded
95      into a buffer yet.  */
96   bfd_byte *info_ptr;
97
98   /* Pointer to the end of the .debug_info section memory buffer.  */
99   bfd_byte *info_ptr_end;
100
101   /* Pointer to the bfd, section and address of the beginning of the
102      section.  The bfd might be different than expected because of
103      gnu_debuglink sections.  */
104   bfd *bfd_ptr;
105   asection *sec;
106   bfd_byte *sec_info_ptr;
107
108   /* A pointer to the memory block allocated for info_ptr.  Neither
109      info_ptr nor sec_info_ptr are guaranteed to stay pointing to the
110      beginning of the malloc block.  This is used only to free the
111      memory later.  */
112   bfd_byte *info_ptr_memory;
113
114   /* Pointer to the symbol table.  */
115   asymbol **syms;
116
117   /* Pointer to the .debug_abbrev section loaded into memory.  */
118   bfd_byte *dwarf_abbrev_buffer;
119
120   /* Length of the loaded .debug_abbrev section.  */
121   bfd_size_type dwarf_abbrev_size;
122
123   /* Buffer for decode_line_info.  */
124   bfd_byte *dwarf_line_buffer;
125
126   /* Length of the loaded .debug_line section.  */
127   bfd_size_type dwarf_line_size;
128
129   /* Pointer to the .debug_str section loaded into memory.  */
130   bfd_byte *dwarf_str_buffer;
131
132   /* Length of the loaded .debug_str section.  */
133   bfd_size_type dwarf_str_size;
134
135   /* Pointer to the .debug_ranges section loaded into memory. */
136   bfd_byte *dwarf_ranges_buffer;
137
138   /* Length of the loaded .debug_ranges section. */
139   bfd_size_type dwarf_ranges_size;
140
141   /* If the most recent call to bfd_find_nearest_line was given an
142      address in an inlined function, preserve a pointer into the
143      calling chain for subsequent calls to bfd_find_inliner_info to
144      use. */
145   struct funcinfo *inliner_chain;
146
147   /* Number of sections whose VMA we must adjust.  */
148   unsigned int adjusted_section_count;
149
150   /* Array of sections with adjusted VMA.  */
151   struct adjusted_section *adjusted_sections;
152
153   /* Number of times find_line is called.  This is used in
154      the heuristic for enabling the info hash tables.  */
155   int info_hash_count;
156
157 #define STASH_INFO_HASH_TRIGGER    100
158
159   /* Hash table mapping symbol names to function infos.  */
160   struct info_hash_table *funcinfo_hash_table;
161
162   /* Hash table mapping symbol names to variable infos.  */
163   struct info_hash_table *varinfo_hash_table;
164
165   /* Head of comp_unit list in the last hash table update.  */
166   struct comp_unit *hash_units_head;
167
168   /* Status of info hash.  */
169   int info_hash_status;
170 #define STASH_INFO_HASH_OFF        0
171 #define STASH_INFO_HASH_ON         1
172 #define STASH_INFO_HASH_DISABLED   2
173 };
174
175 struct arange
176 {
177   struct arange *next;
178   bfd_vma low;
179   bfd_vma high;
180 };
181
182 /* A minimal decoding of DWARF2 compilation units.  We only decode
183    what's needed to get to the line number information.  */
184
185 struct comp_unit
186 {
187   /* Chain the previously read compilation units.  */
188   struct comp_unit *next_unit;
189
190   /* Likewise, chain the compilation unit read after this one.
191      The comp units are stored in reversed reading order.  */
192   struct comp_unit *prev_unit;
193
194   /* Keep the bfd convenient (for memory allocation).  */
195   bfd *abfd;
196
197   /* The lowest and highest addresses contained in this compilation
198      unit as specified in the compilation unit header.  */
199   struct arange arange;
200
201   /* The DW_AT_name attribute (for error messages).  */
202   char *name;
203
204   /* The abbrev hash table.  */
205   struct abbrev_info **abbrevs;
206
207   /* Note that an error was found by comp_unit_find_nearest_line.  */
208   int error;
209
210   /* The DW_AT_comp_dir attribute.  */
211   char *comp_dir;
212
213   /* TRUE if there is a line number table associated with this comp. unit.  */
214   int stmtlist;
215
216   /* Pointer to the current comp_unit so that we can find a given entry
217      by its reference.  */
218   bfd_byte *info_ptr_unit;
219
220   /* Pointer to the start of the debug section, for DW_FORM_ref_addr.  */
221   bfd_byte *sec_info_ptr;
222
223   /* The offset into .debug_line of the line number table.  */
224   unsigned long line_offset;
225
226   /* Pointer to the first child die for the comp unit.  */
227   bfd_byte *first_child_die_ptr;
228
229   /* The end of the comp unit.  */
230   bfd_byte *end_ptr;
231
232   /* The decoded line number, NULL if not yet decoded.  */
233   struct line_info_table *line_table;
234
235   /* A list of the functions found in this comp. unit.  */
236   struct funcinfo *function_table;
237
238   /* A list of the variables found in this comp. unit.  */
239   struct varinfo *variable_table;
240
241   /* Pointer to dwarf2_debug structure.  */
242   struct dwarf2_debug *stash;
243
244   /* DWARF format version for this unit - from unit header.  */
245   int version;
246
247   /* Address size for this unit - from unit header.  */
248   unsigned char addr_size;
249
250   /* Offset size for this unit - from unit header.  */
251   unsigned char offset_size;
252
253   /* Base address for this unit - from DW_AT_low_pc attribute of
254      DW_TAG_compile_unit DIE */
255   bfd_vma base_address;
256
257   /* TRUE if symbols are cached in hash table for faster lookup by name.  */
258   bfd_boolean cached;
259 };
260
261 /* This data structure holds the information of an abbrev.  */
262 struct abbrev_info
263 {
264   unsigned int number;          /* Number identifying abbrev.  */
265   enum dwarf_tag tag;           /* DWARF tag.  */
266   int has_children;             /* Boolean.  */
267   unsigned int num_attrs;       /* Number of attributes.  */
268   struct attr_abbrev *attrs;    /* An array of attribute descriptions.  */
269   struct abbrev_info *next;     /* Next in chain.  */
270 };
271
272 struct attr_abbrev
273 {
274   enum dwarf_attribute name;
275   enum dwarf_form form;
276 };
277
278 #ifndef ABBREV_HASH_SIZE
279 #define ABBREV_HASH_SIZE 121
280 #endif
281 #ifndef ATTR_ALLOC_CHUNK
282 #define ATTR_ALLOC_CHUNK 4
283 #endif
284
285 /* Variable and function hash tables.  This is used to speed up look-up
286    in lookup_symbol_in_var_table() and lookup_symbol_in_function_table().
287    In order to share code between variable and function infos, we use
288    a list of untyped pointer for all variable/function info associated with
289    a symbol.  We waste a bit of memory for list with one node but that
290    simplifies the code.  */
291
292 struct info_list_node
293 {
294   struct info_list_node *next;
295   void *info;
296 };
297
298 /* Info hash entry.  */
299 struct info_hash_entry
300 {
301   struct bfd_hash_entry root;
302   struct info_list_node *head;
303 };
304
305 struct info_hash_table
306 {
307   struct bfd_hash_table base;
308 };
309
310 /* Function to create a new entry in info hash table. */
311
312 static struct bfd_hash_entry *
313 info_hash_table_newfunc (struct bfd_hash_entry *entry,
314                          struct bfd_hash_table *table,
315                          const char *string)
316 {
317   struct info_hash_entry *ret = (struct info_hash_entry *) entry;
318
319   /* Allocate the structure if it has not already been allocated by a
320      derived class.  */
321   if (ret == NULL)
322     {
323       ret = (struct info_hash_entry *) bfd_hash_allocate (table,
324                                                           sizeof (* ret));
325       if (ret == NULL)
326         return NULL;
327     }
328
329   /* Call the allocation method of the base class.  */
330   ret = ((struct info_hash_entry *)
331          bfd_hash_newfunc ((struct bfd_hash_entry *) ret, table, string));
332
333   /* Initialize the local fields here.  */
334   if (ret)
335     ret->head = NULL;
336
337   return (struct bfd_hash_entry *) ret;
338 }
339
340 /* Function to create a new info hash table.  It returns a pointer to the
341    newly created table or NULL if there is any error.  We need abfd
342    solely for memory allocation.  */
343
344 static struct info_hash_table *
345 create_info_hash_table (bfd *abfd)
346 {
347   struct info_hash_table *hash_table;
348
349   hash_table = (struct info_hash_table *)
350       bfd_alloc (abfd, sizeof (struct info_hash_table));
351   if (!hash_table)
352     return hash_table;
353
354   if (!bfd_hash_table_init (&hash_table->base, info_hash_table_newfunc,
355                             sizeof (struct info_hash_entry)))
356     {
357       bfd_release (abfd, hash_table);
358       return NULL;
359     }
360
361   return hash_table;
362 }
363
364 /* Insert an info entry into an info hash table.  We do not check of
365    duplicate entries.  Also, the caller need to guarantee that the
366    right type of info in inserted as info is passed as a void* pointer.
367    This function returns true if there is no error.  */
368
369 static bfd_boolean
370 insert_info_hash_table (struct info_hash_table *hash_table,
371                         const char *key,
372                         void *info,
373                         bfd_boolean copy_p)
374 {
375   struct info_hash_entry *entry;
376   struct info_list_node *node;
377
378   entry = (struct info_hash_entry*) bfd_hash_lookup (&hash_table->base,
379                                                      key, TRUE, copy_p);
380   if (!entry)
381     return FALSE;
382
383   node = (struct info_list_node *) bfd_hash_allocate (&hash_table->base,
384                                                       sizeof (*node));
385   if (!node)
386     return FALSE;
387
388   node->info = info;
389   node->next = entry->head;
390   entry->head = node;
391
392   return TRUE;
393 }
394
395 /* Look up an info entry list from an info hash table.  Return NULL
396    if there is none. */
397
398 static struct info_list_node *
399 lookup_info_hash_table (struct info_hash_table *hash_table, const char *key)
400 {
401   struct info_hash_entry *entry;
402
403   entry = (struct info_hash_entry*) bfd_hash_lookup (&hash_table->base, key,
404                                                      FALSE, FALSE);
405   return entry ? entry->head : NULL;
406 }
407
408 /* Read a section into its appropriate place in the dwarf2_debug
409    struct (indicated by SECTION_BUFFER and SECTION_SIZE).  If SYMS is
410    not NULL, use bfd_simple_get_relocated_section_contents to read the
411    section contents, otherwise use bfd_get_section_contents.  Fail if
412    the located section does not contain at least OFFSET bytes.  */
413
414 static bfd_boolean
415 read_section (bfd *           abfd,
416               const char *    section_name,
417               const char *    compressed_section_name,
418               asymbol **      syms,
419               bfd_uint64_t    offset,
420               bfd_byte **     section_buffer,
421               bfd_size_type * section_size)
422 {
423   asection *msec;
424   bfd_boolean section_is_compressed = FALSE;
425
426   /* read_section is a noop if the section has already been read.  */
427   if (!*section_buffer)
428     {
429       msec = bfd_get_section_by_name (abfd, section_name);
430       if (! msec && compressed_section_name)
431         {
432           msec = bfd_get_section_by_name (abfd, compressed_section_name);
433           section_is_compressed = TRUE;
434         }
435       if (! msec)
436         {
437           (*_bfd_error_handler) (_("Dwarf Error: Can't find %s section."), section_name);
438           bfd_set_error (bfd_error_bad_value);
439           return FALSE;
440         }
441
442       *section_size = msec->rawsize ? msec->rawsize : msec->size;
443       if (syms)
444         {
445           *section_buffer
446               = bfd_simple_get_relocated_section_contents (abfd, msec, NULL, syms);
447           if (! *section_buffer)
448             return FALSE;
449         }
450       else
451         {
452           *section_buffer = (bfd_byte *) bfd_malloc (*section_size);
453           if (! *section_buffer)
454             return FALSE;
455           if (! bfd_get_section_contents (abfd, msec, *section_buffer,
456                                           0, *section_size))
457             return FALSE;
458         }
459
460       if (section_is_compressed)
461         {
462           if (! bfd_uncompress_section_contents (section_buffer, section_size))
463             {
464               (*_bfd_error_handler) (_("Dwarf Error: unable to decompress %s section."), compressed_section_name);
465               bfd_set_error (bfd_error_bad_value);
466               return FALSE;
467             }
468         }
469     }
470
471   /* It is possible to get a bad value for the offset into the section
472      that the client wants.  Validate it here to avoid trouble later.  */
473   if (offset != 0 && offset >= *section_size)
474     {
475       (*_bfd_error_handler) (_("Dwarf Error: Offset (%lu) greater than or equal to %s size (%lu)."),
476                              (long) offset, section_name, *section_size);
477       bfd_set_error (bfd_error_bad_value);
478       return FALSE;
479     }
480
481   return TRUE;
482 }
483
484 /* VERBATIM
485    The following function up to the END VERBATIM mark are
486    copied directly from dwarf2read.c.  */
487
488 /* Read dwarf information from a buffer.  */
489
490 static unsigned int
491 read_1_byte (bfd *abfd ATTRIBUTE_UNUSED, bfd_byte *buf)
492 {
493   return bfd_get_8 (abfd, buf);
494 }
495
496 static int
497 read_1_signed_byte (bfd *abfd ATTRIBUTE_UNUSED, bfd_byte *buf)
498 {
499   return bfd_get_signed_8 (abfd, buf);
500 }
501
502 static unsigned int
503 read_2_bytes (bfd *abfd, bfd_byte *buf)
504 {
505   return bfd_get_16 (abfd, buf);
506 }
507
508 static unsigned int
509 read_4_bytes (bfd *abfd, bfd_byte *buf)
510 {
511   return bfd_get_32 (abfd, buf);
512 }
513
514 static bfd_uint64_t
515 read_8_bytes (bfd *abfd, bfd_byte *buf)
516 {
517   return bfd_get_64 (abfd, buf);
518 }
519
520 static bfd_byte *
521 read_n_bytes (bfd *abfd ATTRIBUTE_UNUSED,
522               bfd_byte *buf,
523               unsigned int size ATTRIBUTE_UNUSED)
524 {
525   return buf;
526 }
527
528 static char *
529 read_string (bfd *abfd ATTRIBUTE_UNUSED,
530              bfd_byte *buf,
531              unsigned int *bytes_read_ptr)
532 {
533   /* Return a pointer to the embedded string.  */
534   char *str = (char *) buf;
535
536   if (*str == '\0')
537     {
538       *bytes_read_ptr = 1;
539       return NULL;
540     }
541
542   *bytes_read_ptr = strlen (str) + 1;
543   return str;
544 }
545
546 /* END VERBATIM */
547
548 static char *
549 read_indirect_string (struct comp_unit * unit,
550                       bfd_byte *         buf,
551                       unsigned int *     bytes_read_ptr)
552 {
553   bfd_uint64_t offset;
554   struct dwarf2_debug *stash = unit->stash;
555   char *str;
556
557   if (unit->offset_size == 4)
558     offset = read_4_bytes (unit->abfd, buf);
559   else
560     offset = read_8_bytes (unit->abfd, buf);
561
562   *bytes_read_ptr = unit->offset_size;
563
564   if (! read_section (unit->abfd, ".debug_str", ".zdebug_str",
565                       stash->syms, offset,
566                       &stash->dwarf_str_buffer, &stash->dwarf_str_size))
567     return NULL;
568
569   str = (char *) stash->dwarf_str_buffer + offset;
570   if (*str == '\0')
571     return NULL;
572   return str;
573 }
574
575 static bfd_uint64_t
576 read_address (struct comp_unit *unit, bfd_byte *buf)
577 {
578   int signed_vma = get_elf_backend_data (unit->abfd)->sign_extend_vma;
579
580   if (signed_vma)
581     {
582       switch (unit->addr_size)
583         {
584         case 8:
585           return bfd_get_signed_64 (unit->abfd, buf);
586         case 4:
587           return bfd_get_signed_32 (unit->abfd, buf);
588         case 2:
589           return bfd_get_signed_16 (unit->abfd, buf);
590         default:
591           abort ();
592         }
593     }
594   else
595     {
596       switch (unit->addr_size)
597         {
598         case 8:
599           return bfd_get_64 (unit->abfd, buf);
600         case 4:
601           return bfd_get_32 (unit->abfd, buf);
602         case 2:
603           return bfd_get_16 (unit->abfd, buf);
604         default:
605           abort ();
606         }
607     }
608 }
609
610 /* Lookup an abbrev_info structure in the abbrev hash table.  */
611
612 static struct abbrev_info *
613 lookup_abbrev (unsigned int number, struct abbrev_info **abbrevs)
614 {
615   unsigned int hash_number;
616   struct abbrev_info *abbrev;
617
618   hash_number = number % ABBREV_HASH_SIZE;
619   abbrev = abbrevs[hash_number];
620
621   while (abbrev)
622     {
623       if (abbrev->number == number)
624         return abbrev;
625       else
626         abbrev = abbrev->next;
627     }
628
629   return NULL;
630 }
631
632 /* In DWARF version 2, the description of the debugging information is
633    stored in a separate .debug_abbrev section.  Before we read any
634    dies from a section we read in all abbreviations and install them
635    in a hash table.  */
636
637 static struct abbrev_info**
638 read_abbrevs (bfd *abfd, bfd_uint64_t offset, struct dwarf2_debug *stash)
639 {
640   struct abbrev_info **abbrevs;
641   bfd_byte *abbrev_ptr;
642   struct abbrev_info *cur_abbrev;
643   unsigned int abbrev_number, bytes_read, abbrev_name;
644   unsigned int abbrev_form, hash_number;
645   bfd_size_type amt;
646
647   if (! read_section (abfd, ".debug_abbrev", ".zdebug_abbrev",
648                       stash->syms, offset,
649                       &stash->dwarf_abbrev_buffer, &stash->dwarf_abbrev_size))
650     return NULL;
651
652   amt = sizeof (struct abbrev_info*) * ABBREV_HASH_SIZE;
653   abbrevs = (struct abbrev_info **) bfd_zalloc (abfd, amt);
654   if (abbrevs == NULL)
655     return NULL;
656
657   abbrev_ptr = stash->dwarf_abbrev_buffer + offset;
658   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
659   abbrev_ptr += bytes_read;
660
661   /* Loop until we reach an abbrev number of 0.  */
662   while (abbrev_number)
663     {
664       amt = sizeof (struct abbrev_info);
665       cur_abbrev = (struct abbrev_info *) bfd_zalloc (abfd, amt);
666       if (cur_abbrev == NULL)
667         return NULL;
668
669       /* Read in abbrev header.  */
670       cur_abbrev->number = abbrev_number;
671       cur_abbrev->tag = (enum dwarf_tag)
672         read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
673       abbrev_ptr += bytes_read;
674       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
675       abbrev_ptr += 1;
676
677       /* Now read in declarations.  */
678       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
679       abbrev_ptr += bytes_read;
680       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
681       abbrev_ptr += bytes_read;
682
683       while (abbrev_name)
684         {
685           if ((cur_abbrev->num_attrs % ATTR_ALLOC_CHUNK) == 0)
686             {
687               struct attr_abbrev *tmp;
688
689               amt = cur_abbrev->num_attrs + ATTR_ALLOC_CHUNK;
690               amt *= sizeof (struct attr_abbrev);
691               tmp = (struct attr_abbrev *) bfd_realloc (cur_abbrev->attrs, amt);
692               if (tmp == NULL)
693                 {
694                   size_t i;
695
696                   for (i = 0; i < ABBREV_HASH_SIZE; i++)
697                     {
698                       struct abbrev_info *abbrev = abbrevs[i];
699
700                       while (abbrev)
701                         {
702                           free (abbrev->attrs);
703                           abbrev = abbrev->next;
704                         }
705                     }
706                   return NULL;
707                 }
708               cur_abbrev->attrs = tmp;
709             }
710
711           cur_abbrev->attrs[cur_abbrev->num_attrs].name
712             = (enum dwarf_attribute) abbrev_name;
713           cur_abbrev->attrs[cur_abbrev->num_attrs++].form
714             = (enum dwarf_form) abbrev_form;
715           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
716           abbrev_ptr += bytes_read;
717           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
718           abbrev_ptr += bytes_read;
719         }
720
721       hash_number = abbrev_number % ABBREV_HASH_SIZE;
722       cur_abbrev->next = abbrevs[hash_number];
723       abbrevs[hash_number] = cur_abbrev;
724
725       /* Get next abbreviation.
726          Under Irix6 the abbreviations for a compilation unit are not
727          always properly terminated with an abbrev number of 0.
728          Exit loop if we encounter an abbreviation which we have
729          already read (which means we are about to read the abbreviations
730          for the next compile unit) or if the end of the abbreviation
731          table is reached.  */
732       if ((unsigned int) (abbrev_ptr - stash->dwarf_abbrev_buffer)
733           >= stash->dwarf_abbrev_size)
734         break;
735       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
736       abbrev_ptr += bytes_read;
737       if (lookup_abbrev (abbrev_number,abbrevs) != NULL)
738         break;
739     }
740
741   return abbrevs;
742 }
743
744 /* Read an attribute value described by an attribute form.  */
745
746 static bfd_byte *
747 read_attribute_value (struct attribute *attr,
748                       unsigned form,
749                       struct comp_unit *unit,
750                       bfd_byte *info_ptr)
751 {
752   bfd *abfd = unit->abfd;
753   unsigned int bytes_read;
754   struct dwarf_block *blk;
755   bfd_size_type amt;
756
757   attr->form = (enum dwarf_form) form;
758
759   switch (form)
760     {
761     case DW_FORM_ref_addr:
762       /* DW_FORM_ref_addr is an address in DWARF2, and an offset in
763          DWARF3.  */
764       if (unit->version == 3 || unit->version == 4)
765         {
766           if (unit->offset_size == 4)
767             attr->u.val = read_4_bytes (unit->abfd, info_ptr);
768           else
769             attr->u.val = read_8_bytes (unit->abfd, info_ptr);
770           info_ptr += unit->offset_size;
771           break;
772         }
773       /* FALLTHROUGH */
774     case DW_FORM_addr:
775       attr->u.val = read_address (unit, info_ptr);
776       info_ptr += unit->addr_size;
777       break;
778     case DW_FORM_sec_offset:
779       if (unit->offset_size == 4)
780         attr->u.val = read_4_bytes (unit->abfd, info_ptr);
781       else
782         attr->u.val = read_8_bytes (unit->abfd, info_ptr);
783       info_ptr += unit->offset_size;
784       break;
785     case DW_FORM_block2:
786       amt = sizeof (struct dwarf_block);
787       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
788       if (blk == NULL)
789         return NULL;
790       blk->size = read_2_bytes (abfd, info_ptr);
791       info_ptr += 2;
792       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
793       info_ptr += blk->size;
794       attr->u.blk = blk;
795       break;
796     case DW_FORM_block4:
797       amt = sizeof (struct dwarf_block);
798       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
799       if (blk == NULL)
800         return NULL;
801       blk->size = read_4_bytes (abfd, info_ptr);
802       info_ptr += 4;
803       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
804       info_ptr += blk->size;
805       attr->u.blk = blk;
806       break;
807     case DW_FORM_data2:
808       attr->u.val = read_2_bytes (abfd, info_ptr);
809       info_ptr += 2;
810       break;
811     case DW_FORM_data4:
812       attr->u.val = read_4_bytes (abfd, info_ptr);
813       info_ptr += 4;
814       break;
815     case DW_FORM_data8:
816       attr->u.val = read_8_bytes (abfd, info_ptr);
817       info_ptr += 8;
818       break;
819     case DW_FORM_string:
820       attr->u.str = read_string (abfd, info_ptr, &bytes_read);
821       info_ptr += bytes_read;
822       break;
823     case DW_FORM_strp:
824       attr->u.str = read_indirect_string (unit, info_ptr, &bytes_read);
825       info_ptr += bytes_read;
826       break;
827     case DW_FORM_exprloc:
828     case DW_FORM_block:
829       amt = sizeof (struct dwarf_block);
830       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
831       if (blk == NULL)
832         return NULL;
833       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
834       info_ptr += bytes_read;
835       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
836       info_ptr += blk->size;
837       attr->u.blk = blk;
838       break;
839     case DW_FORM_block1:
840       amt = sizeof (struct dwarf_block);
841       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
842       if (blk == NULL)
843         return NULL;
844       blk->size = read_1_byte (abfd, info_ptr);
845       info_ptr += 1;
846       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
847       info_ptr += blk->size;
848       attr->u.blk = blk;
849       break;
850     case DW_FORM_data1:
851       attr->u.val = read_1_byte (abfd, info_ptr);
852       info_ptr += 1;
853       break;
854     case DW_FORM_flag:
855       attr->u.val = read_1_byte (abfd, info_ptr);
856       info_ptr += 1;
857       break;
858     case DW_FORM_flag_present:
859       attr->u.val = 1;
860       break;
861     case DW_FORM_sdata:
862       attr->u.sval = read_signed_leb128 (abfd, info_ptr, &bytes_read);
863       info_ptr += bytes_read;
864       break;
865     case DW_FORM_udata:
866       attr->u.val = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
867       info_ptr += bytes_read;
868       break;
869     case DW_FORM_ref1:
870       attr->u.val = read_1_byte (abfd, info_ptr);
871       info_ptr += 1;
872       break;
873     case DW_FORM_ref2:
874       attr->u.val = read_2_bytes (abfd, info_ptr);
875       info_ptr += 2;
876       break;
877     case DW_FORM_ref4:
878       attr->u.val = read_4_bytes (abfd, info_ptr);
879       info_ptr += 4;
880       break;
881     case DW_FORM_ref8:
882       attr->u.val = read_8_bytes (abfd, info_ptr);
883       info_ptr += 8;
884       break;
885     case DW_FORM_ref_sig8:
886       attr->u.val = read_8_bytes (abfd, info_ptr);
887       info_ptr += 8;
888       break;
889     case DW_FORM_ref_udata:
890       attr->u.val = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
891       info_ptr += bytes_read;
892       break;
893     case DW_FORM_indirect:
894       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
895       info_ptr += bytes_read;
896       info_ptr = read_attribute_value (attr, form, unit, info_ptr);
897       break;
898     default:
899       (*_bfd_error_handler) (_("Dwarf Error: Invalid or unhandled FORM value: %u."),
900                              form);
901       bfd_set_error (bfd_error_bad_value);
902       return NULL;
903     }
904   return info_ptr;
905 }
906
907 /* Read an attribute described by an abbreviated attribute.  */
908
909 static bfd_byte *
910 read_attribute (struct attribute *attr,
911                 struct attr_abbrev *abbrev,
912                 struct comp_unit *unit,
913                 bfd_byte *info_ptr)
914 {
915   attr->name = abbrev->name;
916   info_ptr = read_attribute_value (attr, abbrev->form, unit, info_ptr);
917   return info_ptr;
918 }
919
920 /* Source line information table routines.  */
921
922 #define FILE_ALLOC_CHUNK 5
923 #define DIR_ALLOC_CHUNK 5
924
925 struct line_info
926 {
927   struct line_info* prev_line;
928   bfd_vma address;
929   char *filename;
930   unsigned int line;
931   unsigned int column;
932   unsigned char op_index;
933   unsigned char end_sequence;           /* End of (sequential) code sequence.  */
934 };
935
936 struct fileinfo
937 {
938   char *name;
939   unsigned int dir;
940   unsigned int time;
941   unsigned int size;
942 };
943
944 struct line_sequence
945 {
946   bfd_vma               low_pc;
947   struct line_sequence* prev_sequence;
948   struct line_info*     last_line;  /* Largest VMA.  */
949 };
950
951 struct line_info_table
952 {
953   bfd*                  abfd;
954   unsigned int          num_files;
955   unsigned int          num_dirs;
956   unsigned int          num_sequences;
957   char *                comp_dir;
958   char **               dirs;
959   struct fileinfo*      files;
960   struct line_sequence* sequences;
961   struct line_info*     lcl_head;   /* Local head; used in 'add_line_info'.  */
962 };
963
964 /* Remember some information about each function.  If the function is
965    inlined (DW_TAG_inlined_subroutine) it may have two additional
966    attributes, DW_AT_call_file and DW_AT_call_line, which specify the
967    source code location where this function was inlined. */
968
969 struct funcinfo
970 {
971   struct funcinfo *prev_func;           /* Pointer to previous function in list of all functions */
972   struct funcinfo *caller_func;         /* Pointer to function one scope higher */
973   char *caller_file;                    /* Source location file name where caller_func inlines this func */
974   int caller_line;                      /* Source location line number where caller_func inlines this func */
975   char *file;                           /* Source location file name */
976   int line;                             /* Source location line number */
977   int tag;
978   char *name;
979   struct arange arange;
980   asection *sec;                        /* Where the symbol is defined */
981 };
982
983 struct varinfo
984 {
985   /* Pointer to previous variable in list of all variables */
986   struct varinfo *prev_var;
987   /* Source location file name */
988   char *file;
989   /* Source location line number */
990   int line;
991   int tag;
992   char *name;
993   bfd_vma addr;
994   /* Where the symbol is defined */
995   asection *sec;
996   /* Is this a stack variable? */
997   unsigned int stack: 1;
998 };
999
1000 /* Return TRUE if NEW_LINE should sort after LINE.  */
1001
1002 static inline bfd_boolean
1003 new_line_sorts_after (struct line_info *new_line, struct line_info *line)
1004 {
1005   return (new_line->address > line->address
1006           || (new_line->address == line->address
1007               && (new_line->op_index > line->op_index
1008                   || (new_line->op_index == line->op_index
1009                       && new_line->end_sequence < line->end_sequence))));
1010 }
1011
1012
1013 /* Adds a new entry to the line_info list in the line_info_table, ensuring
1014    that the list is sorted.  Note that the line_info list is sorted from
1015    highest to lowest VMA (with possible duplicates); that is,
1016    line_info->prev_line always accesses an equal or smaller VMA.  */
1017
1018 static bfd_boolean
1019 add_line_info (struct line_info_table *table,
1020                bfd_vma address,
1021                unsigned char op_index,
1022                char *filename,
1023                unsigned int line,
1024                unsigned int column,
1025                int end_sequence)
1026 {
1027   bfd_size_type amt = sizeof (struct line_info);
1028   struct line_sequence* seq = table->sequences;
1029   struct line_info* info = (struct line_info *) bfd_alloc (table->abfd, amt);
1030
1031   if (info == NULL)
1032     return FALSE;
1033
1034   /* Set member data of 'info'.  */
1035   info->address = address;
1036   info->op_index = op_index;
1037   info->line = line;
1038   info->column = column;
1039   info->end_sequence = end_sequence;
1040
1041   if (filename && filename[0])
1042     {
1043       info->filename = (char *) bfd_alloc (table->abfd, strlen (filename) + 1);
1044       if (info->filename == NULL)
1045         return FALSE;
1046       strcpy (info->filename, filename);
1047     }
1048   else
1049     info->filename = NULL;
1050
1051   /* Find the correct location for 'info'.  Normally we will receive
1052      new line_info data 1) in order and 2) with increasing VMAs.
1053      However some compilers break the rules (cf. decode_line_info) and
1054      so we include some heuristics for quickly finding the correct
1055      location for 'info'. In particular, these heuristics optimize for
1056      the common case in which the VMA sequence that we receive is a
1057      list of locally sorted VMAs such as
1058        p...z a...j  (where a < j < p < z)
1059
1060      Note: table->lcl_head is used to head an *actual* or *possible*
1061      sub-sequence within the list (such as a...j) that is not directly
1062      headed by table->last_line
1063
1064      Note: we may receive duplicate entries from 'decode_line_info'.  */
1065
1066   if (seq
1067       && seq->last_line->address == address
1068       && seq->last_line->op_index == op_index
1069       && seq->last_line->end_sequence == end_sequence)
1070     {
1071       /* We only keep the last entry with the same address and end
1072          sequence.  See PR ld/4986.  */
1073       if (table->lcl_head == seq->last_line)
1074         table->lcl_head = info;
1075       info->prev_line = seq->last_line->prev_line;
1076       seq->last_line = info;
1077     }
1078   else if (!seq || seq->last_line->end_sequence)
1079     {
1080       /* Start a new line sequence.  */
1081       amt = sizeof (struct line_sequence);
1082       seq = (struct line_sequence *) bfd_malloc (amt);
1083       if (seq == NULL)
1084         return FALSE;
1085       seq->low_pc = address;
1086       seq->prev_sequence = table->sequences;
1087       seq->last_line = info;
1088       table->lcl_head = info;
1089       table->sequences = seq;
1090       table->num_sequences++;
1091     }
1092   else if (new_line_sorts_after (info, seq->last_line))
1093     {
1094       /* Normal case: add 'info' to the beginning of the current sequence.  */
1095       info->prev_line = seq->last_line;
1096       seq->last_line = info;
1097
1098       /* lcl_head: initialize to head a *possible* sequence at the end.  */
1099       if (!table->lcl_head)
1100         table->lcl_head = info;
1101     }
1102   else if (!new_line_sorts_after (info, table->lcl_head)
1103            && (!table->lcl_head->prev_line
1104                || new_line_sorts_after (info, table->lcl_head->prev_line)))
1105     {
1106       /* Abnormal but easy: lcl_head is the head of 'info'.  */
1107       info->prev_line = table->lcl_head->prev_line;
1108       table->lcl_head->prev_line = info;
1109     }
1110   else
1111     {
1112       /* Abnormal and hard: Neither 'last_line' nor 'lcl_head'
1113          are valid heads for 'info'.  Reset 'lcl_head'.  */
1114       struct line_info* li2 = seq->last_line; /* Always non-NULL.  */
1115       struct line_info* li1 = li2->prev_line;
1116
1117       while (li1)
1118         {
1119           if (!new_line_sorts_after (info, li2)
1120               && new_line_sorts_after (info, li1))
1121             break;
1122
1123           li2 = li1; /* always non-NULL */
1124           li1 = li1->prev_line;
1125         }
1126       table->lcl_head = li2;
1127       info->prev_line = table->lcl_head->prev_line;
1128       table->lcl_head->prev_line = info;
1129       if (address < seq->low_pc)
1130         seq->low_pc = address;
1131     }
1132   return TRUE;
1133 }
1134
1135 /* Extract a fully qualified filename from a line info table.
1136    The returned string has been malloc'ed and it is the caller's
1137    responsibility to free it.  */
1138
1139 static char *
1140 concat_filename (struct line_info_table *table, unsigned int file)
1141 {
1142   char *filename;
1143
1144   if (file - 1 >= table->num_files)
1145     {
1146       /* FILE == 0 means unknown.  */
1147       if (file)
1148         (*_bfd_error_handler)
1149           (_("Dwarf Error: mangled line number section (bad file number)."));
1150       return strdup ("<unknown>");
1151     }
1152
1153   filename = table->files[file - 1].name;
1154
1155   if (!IS_ABSOLUTE_PATH (filename))
1156     {
1157       char *dir_name = NULL;
1158       char *subdir_name = NULL;
1159       char *name;
1160       size_t len;
1161
1162       if (table->files[file - 1].dir)
1163         subdir_name = table->dirs[table->files[file - 1].dir - 1];
1164
1165       if (!subdir_name || !IS_ABSOLUTE_PATH (subdir_name))
1166         dir_name = table->comp_dir;
1167
1168       if (!dir_name)
1169         {
1170           dir_name = subdir_name;
1171           subdir_name = NULL;
1172         }
1173
1174       if (!dir_name)
1175         return strdup (filename);
1176
1177       len = strlen (dir_name) + strlen (filename) + 2;
1178
1179       if (subdir_name)
1180         {
1181           len += strlen (subdir_name) + 1;
1182           name = (char *) bfd_malloc (len);
1183           if (name)
1184             sprintf (name, "%s/%s/%s", dir_name, subdir_name, filename);
1185         }
1186       else
1187         {
1188           name = (char *) bfd_malloc (len);
1189           if (name)
1190             sprintf (name, "%s/%s", dir_name, filename);
1191         }
1192
1193       return name;
1194     }
1195
1196   return strdup (filename);
1197 }
1198
1199 static bfd_boolean
1200 arange_add (bfd *abfd, struct arange *first_arange,
1201             bfd_vma low_pc, bfd_vma high_pc)
1202 {
1203   struct arange *arange;
1204
1205   /* If the first arange is empty, use it. */
1206   if (first_arange->high == 0)
1207     {
1208       first_arange->low = low_pc;
1209       first_arange->high = high_pc;
1210       return TRUE;
1211     }
1212
1213   /* Next see if we can cheaply extend an existing range.  */
1214   arange = first_arange;
1215   do
1216     {
1217       if (low_pc == arange->high)
1218         {
1219           arange->high = high_pc;
1220           return TRUE;
1221         }
1222       if (high_pc == arange->low)
1223         {
1224           arange->low = low_pc;
1225           return TRUE;
1226         }
1227       arange = arange->next;
1228     }
1229   while (arange);
1230
1231   /* Need to allocate a new arange and insert it into the arange list.
1232      Order isn't significant, so just insert after the first arange. */
1233   arange = (struct arange *) bfd_zalloc (abfd, sizeof (*arange));
1234   if (arange == NULL)
1235     return FALSE;
1236   arange->low = low_pc;
1237   arange->high = high_pc;
1238   arange->next = first_arange->next;
1239   first_arange->next = arange;
1240   return TRUE;
1241 }
1242
1243 /* Compare function for line sequences.  */
1244
1245 static int
1246 compare_sequences (const void* a, const void* b)
1247 {
1248   const struct line_sequence* seq1 = a;
1249   const struct line_sequence* seq2 = b;
1250
1251   /* Sort by low_pc as the primary key.  */
1252   if (seq1->low_pc < seq2->low_pc)
1253     return -1;
1254   if (seq1->low_pc > seq2->low_pc)
1255     return 1;
1256
1257   /* If low_pc values are equal, sort in reverse order of
1258      high_pc, so that the largest region comes first.  */
1259   if (seq1->last_line->address < seq2->last_line->address)
1260     return 1;
1261   if (seq1->last_line->address > seq2->last_line->address)
1262     return -1;
1263
1264   if (seq1->last_line->op_index < seq2->last_line->op_index)
1265     return 1;
1266   if (seq1->last_line->op_index > seq2->last_line->op_index)
1267     return -1;
1268
1269   return 0;
1270 }
1271
1272 /* Sort the line sequences for quick lookup.  */
1273
1274 static bfd_boolean
1275 sort_line_sequences (struct line_info_table* table)
1276 {
1277   bfd_size_type amt;
1278   struct line_sequence* sequences;
1279   struct line_sequence* seq;
1280   unsigned int n = 0;
1281   unsigned int num_sequences = table->num_sequences;
1282   bfd_vma last_high_pc;
1283
1284   if (num_sequences == 0)
1285     return TRUE;
1286
1287   /* Allocate space for an array of sequences.  */
1288   amt = sizeof (struct line_sequence) * num_sequences;
1289   sequences = (struct line_sequence *) bfd_alloc (table->abfd, amt);
1290   if (sequences == NULL)
1291     return FALSE;
1292
1293   /* Copy the linked list into the array, freeing the original nodes.  */
1294   seq = table->sequences;
1295   for (n = 0; n < num_sequences; n++)
1296     {
1297       struct line_sequence* last_seq = seq;
1298
1299       BFD_ASSERT (seq);
1300       sequences[n].low_pc = seq->low_pc;
1301       sequences[n].prev_sequence = NULL;
1302       sequences[n].last_line = seq->last_line;
1303       seq = seq->prev_sequence;
1304       free (last_seq);
1305     }
1306   BFD_ASSERT (seq == NULL);
1307
1308   qsort (sequences, n, sizeof (struct line_sequence), compare_sequences);
1309
1310   /* Make the list binary-searchable by trimming overlapping entries
1311      and removing nested entries.  */
1312   num_sequences = 1;
1313   last_high_pc = sequences[0].last_line->address;
1314   for (n = 1; n < table->num_sequences; n++)
1315     {
1316       if (sequences[n].low_pc < last_high_pc)
1317         {
1318           if (sequences[n].last_line->address <= last_high_pc)
1319             /* Skip nested entries.  */
1320             continue;
1321
1322           /* Trim overlapping entries.  */
1323           sequences[n].low_pc = last_high_pc;
1324         }
1325       last_high_pc = sequences[n].last_line->address;
1326       if (n > num_sequences)
1327         {
1328           /* Close up the gap.  */
1329           sequences[num_sequences].low_pc = sequences[n].low_pc;
1330           sequences[num_sequences].last_line = sequences[n].last_line;
1331         }
1332       num_sequences++;
1333     }
1334
1335   table->sequences = sequences;
1336   table->num_sequences = num_sequences;
1337   return TRUE;
1338 }
1339
1340 /* Decode the line number information for UNIT.  */
1341
1342 static struct line_info_table*
1343 decode_line_info (struct comp_unit *unit, struct dwarf2_debug *stash)
1344 {
1345   bfd *abfd = unit->abfd;
1346   struct line_info_table* table;
1347   bfd_byte *line_ptr;
1348   bfd_byte *line_end;
1349   struct line_head lh;
1350   unsigned int i, bytes_read, offset_size;
1351   char *cur_file, *cur_dir;
1352   unsigned char op_code, extended_op, adj_opcode;
1353   bfd_size_type amt;
1354
1355   if (! read_section (abfd, ".debug_line", ".zdebug_line",
1356                       stash->syms, unit->line_offset,
1357                       &stash->dwarf_line_buffer, &stash->dwarf_line_size))
1358     return NULL;
1359
1360   amt = sizeof (struct line_info_table);
1361   table = (struct line_info_table *) bfd_alloc (abfd, amt);
1362   if (table == NULL)
1363     return NULL;
1364   table->abfd = abfd;
1365   table->comp_dir = unit->comp_dir;
1366
1367   table->num_files = 0;
1368   table->files = NULL;
1369
1370   table->num_dirs = 0;
1371   table->dirs = NULL;
1372
1373   table->num_sequences = 0;
1374   table->sequences = NULL;
1375
1376   table->lcl_head = NULL;
1377
1378   line_ptr = stash->dwarf_line_buffer + unit->line_offset;
1379
1380   /* Read in the prologue.  */
1381   lh.total_length = read_4_bytes (abfd, line_ptr);
1382   line_ptr += 4;
1383   offset_size = 4;
1384   if (lh.total_length == 0xffffffff)
1385     {
1386       lh.total_length = read_8_bytes (abfd, line_ptr);
1387       line_ptr += 8;
1388       offset_size = 8;
1389     }
1390   else if (lh.total_length == 0 && unit->addr_size == 8)
1391     {
1392       /* Handle (non-standard) 64-bit DWARF2 formats.  */
1393       lh.total_length = read_4_bytes (abfd, line_ptr);
1394       line_ptr += 4;
1395       offset_size = 8;
1396     }
1397   line_end = line_ptr + lh.total_length;
1398   lh.version = read_2_bytes (abfd, line_ptr);
1399   if (lh.version < 2 || lh.version > 4)
1400     {
1401       (*_bfd_error_handler)
1402         (_("Dwarf Error: Unhandled .debug_line version %d."), lh.version);
1403       bfd_set_error (bfd_error_bad_value);
1404       return NULL;
1405     }
1406   line_ptr += 2;
1407   if (offset_size == 4)
1408     lh.prologue_length = read_4_bytes (abfd, line_ptr);
1409   else
1410     lh.prologue_length = read_8_bytes (abfd, line_ptr);
1411   line_ptr += offset_size;
1412   lh.minimum_instruction_length = read_1_byte (abfd, line_ptr);
1413   line_ptr += 1;
1414   if (lh.version >= 4)
1415     {
1416       lh.maximum_ops_per_insn = read_1_byte (abfd, line_ptr);
1417       line_ptr += 1;
1418     }
1419   else
1420     lh.maximum_ops_per_insn = 1;
1421   if (lh.maximum_ops_per_insn == 0)
1422     {
1423       (*_bfd_error_handler)
1424         (_("Dwarf Error: Invalid maximum operations per instruction."));
1425       bfd_set_error (bfd_error_bad_value);
1426       return NULL;
1427     }
1428   lh.default_is_stmt = read_1_byte (abfd, line_ptr);
1429   line_ptr += 1;
1430   lh.line_base = read_1_signed_byte (abfd, line_ptr);
1431   line_ptr += 1;
1432   lh.line_range = read_1_byte (abfd, line_ptr);
1433   line_ptr += 1;
1434   lh.opcode_base = read_1_byte (abfd, line_ptr);
1435   line_ptr += 1;
1436   amt = lh.opcode_base * sizeof (unsigned char);
1437   lh.standard_opcode_lengths = (unsigned char *) bfd_alloc (abfd, amt);
1438
1439   lh.standard_opcode_lengths[0] = 1;
1440
1441   for (i = 1; i < lh.opcode_base; ++i)
1442     {
1443       lh.standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
1444       line_ptr += 1;
1445     }
1446
1447   /* Read directory table.  */
1448   while ((cur_dir = read_string (abfd, line_ptr, &bytes_read)) != NULL)
1449     {
1450       line_ptr += bytes_read;
1451
1452       if ((table->num_dirs % DIR_ALLOC_CHUNK) == 0)
1453         {
1454           char **tmp;
1455
1456           amt = table->num_dirs + DIR_ALLOC_CHUNK;
1457           amt *= sizeof (char *);
1458
1459           tmp = (char **) bfd_realloc (table->dirs, amt);
1460           if (tmp == NULL)
1461             goto fail;
1462           table->dirs = tmp;
1463         }
1464
1465       table->dirs[table->num_dirs++] = cur_dir;
1466     }
1467
1468   line_ptr += bytes_read;
1469
1470   /* Read file name table.  */
1471   while ((cur_file = read_string (abfd, line_ptr, &bytes_read)) != NULL)
1472     {
1473       line_ptr += bytes_read;
1474
1475       if ((table->num_files % FILE_ALLOC_CHUNK) == 0)
1476         {
1477           struct fileinfo *tmp;
1478
1479           amt = table->num_files + FILE_ALLOC_CHUNK;
1480           amt *= sizeof (struct fileinfo);
1481
1482           tmp = (struct fileinfo *) bfd_realloc (table->files, amt);
1483           if (tmp == NULL)
1484             goto fail;
1485           table->files = tmp;
1486         }
1487
1488       table->files[table->num_files].name = cur_file;
1489       table->files[table->num_files].dir =
1490         read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1491       line_ptr += bytes_read;
1492       table->files[table->num_files].time =
1493         read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1494       line_ptr += bytes_read;
1495       table->files[table->num_files].size =
1496         read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1497       line_ptr += bytes_read;
1498       table->num_files++;
1499     }
1500
1501   line_ptr += bytes_read;
1502
1503   /* Read the statement sequences until there's nothing left.  */
1504   while (line_ptr < line_end)
1505     {
1506       /* State machine registers.  */
1507       bfd_vma address = 0;
1508       unsigned char op_index = 0;
1509       char * filename = table->num_files ? concat_filename (table, 1) : NULL;
1510       unsigned int line = 1;
1511       unsigned int column = 0;
1512       int is_stmt = lh.default_is_stmt;
1513       int end_sequence = 0;
1514       /* eraxxon@alumni.rice.edu: Against the DWARF2 specs, some
1515          compilers generate address sequences that are wildly out of
1516          order using DW_LNE_set_address (e.g. Intel C++ 6.0 compiler
1517          for ia64-Linux).  Thus, to determine the low and high
1518          address, we must compare on every DW_LNS_copy, etc.  */
1519       bfd_vma low_pc  = (bfd_vma) -1;
1520       bfd_vma high_pc = 0;
1521
1522       /* Decode the table.  */
1523       while (! end_sequence)
1524         {
1525           op_code = read_1_byte (abfd, line_ptr);
1526           line_ptr += 1;
1527
1528           if (op_code >= lh.opcode_base)
1529             {
1530               /* Special operand.  */
1531               adj_opcode = op_code - lh.opcode_base;
1532               if (lh.maximum_ops_per_insn == 1)
1533                 address += (adj_opcode / lh.line_range)
1534                            * lh.minimum_instruction_length;
1535               else
1536                 {
1537                   address += ((op_index + (adj_opcode / lh.line_range))
1538                               / lh.maximum_ops_per_insn)
1539                              * lh.minimum_instruction_length;
1540                   op_index = (op_index + (adj_opcode / lh.line_range))
1541                              % lh.maximum_ops_per_insn;
1542                 }
1543               line += lh.line_base + (adj_opcode % lh.line_range);
1544               /* Append row to matrix using current values.  */
1545               if (!add_line_info (table, address, op_index, filename,
1546                                   line, column, 0))
1547                 goto line_fail;
1548               if (address < low_pc)
1549                 low_pc = address;
1550               if (address > high_pc)
1551                 high_pc = address;
1552             }
1553           else switch (op_code)
1554             {
1555             case DW_LNS_extended_op:
1556               /* Ignore length.  */
1557               line_ptr += 1;
1558               extended_op = read_1_byte (abfd, line_ptr);
1559               line_ptr += 1;
1560
1561               switch (extended_op)
1562                 {
1563                 case DW_LNE_end_sequence:
1564                   end_sequence = 1;
1565                   if (!add_line_info (table, address, op_index, filename,
1566                                       line, column, end_sequence))
1567                     goto line_fail;
1568                   if (address < low_pc)
1569                     low_pc = address;
1570                   if (address > high_pc)
1571                     high_pc = address;
1572                   if (!arange_add (unit->abfd, &unit->arange, low_pc, high_pc))
1573                     goto line_fail;
1574                   break;
1575                 case DW_LNE_set_address:
1576                   address = read_address (unit, line_ptr);
1577                   op_index = 0;
1578                   line_ptr += unit->addr_size;
1579                   break;
1580                 case DW_LNE_define_file:
1581                   cur_file = read_string (abfd, line_ptr, &bytes_read);
1582                   line_ptr += bytes_read;
1583                   if ((table->num_files % FILE_ALLOC_CHUNK) == 0)
1584                     {
1585                       struct fileinfo *tmp;
1586
1587                       amt = table->num_files + FILE_ALLOC_CHUNK;
1588                       amt *= sizeof (struct fileinfo);
1589                       tmp = (struct fileinfo *) bfd_realloc (table->files, amt);
1590                       if (tmp == NULL)
1591                         goto line_fail;
1592                       table->files = tmp;
1593                     }
1594                   table->files[table->num_files].name = cur_file;
1595                   table->files[table->num_files].dir =
1596                     read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1597                   line_ptr += bytes_read;
1598                   table->files[table->num_files].time =
1599                     read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1600                   line_ptr += bytes_read;
1601                   table->files[table->num_files].size =
1602                     read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1603                   line_ptr += bytes_read;
1604                   table->num_files++;
1605                   break;
1606                 case DW_LNE_set_discriminator:
1607                   (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1608                   line_ptr += bytes_read;
1609                   break;
1610                 default:
1611                   (*_bfd_error_handler) (_("Dwarf Error: mangled line number section."));
1612                   bfd_set_error (bfd_error_bad_value);
1613                 line_fail:
1614                   if (filename != NULL)
1615                     free (filename);
1616                   goto fail;
1617                 }
1618               break;
1619             case DW_LNS_copy:
1620               if (!add_line_info (table, address, op_index,
1621                                   filename, line, column, 0))
1622                 goto line_fail;
1623               if (address < low_pc)
1624                 low_pc = address;
1625               if (address > high_pc)
1626                 high_pc = address;
1627               break;
1628             case DW_LNS_advance_pc:
1629               if (lh.maximum_ops_per_insn == 1)
1630                 address += lh.minimum_instruction_length
1631                            * read_unsigned_leb128 (abfd, line_ptr,
1632                                                    &bytes_read);
1633               else
1634                 {
1635                   bfd_vma adjust = read_unsigned_leb128 (abfd, line_ptr,
1636                                                          &bytes_read);
1637                   address = ((op_index + adjust) / lh.maximum_ops_per_insn)
1638                             * lh.minimum_instruction_length;
1639                   op_index = (op_index + adjust) % lh.maximum_ops_per_insn;
1640                 }
1641               line_ptr += bytes_read;
1642               break;
1643             case DW_LNS_advance_line:
1644               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
1645               line_ptr += bytes_read;
1646               break;
1647             case DW_LNS_set_file:
1648               {
1649                 unsigned int file;
1650
1651                 /* The file and directory tables are 0
1652                    based, the references are 1 based.  */
1653                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1654                 line_ptr += bytes_read;
1655                 if (filename)
1656                   free (filename);
1657                 filename = concat_filename (table, file);
1658                 break;
1659               }
1660             case DW_LNS_set_column:
1661               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1662               line_ptr += bytes_read;
1663               break;
1664             case DW_LNS_negate_stmt:
1665               is_stmt = (!is_stmt);
1666               break;
1667             case DW_LNS_set_basic_block:
1668               break;
1669             case DW_LNS_const_add_pc:
1670               if (lh.maximum_ops_per_insn == 1)
1671                 address += lh.minimum_instruction_length
1672                            * ((255 - lh.opcode_base) / lh.line_range);
1673               else
1674                 {
1675                   bfd_vma adjust = ((255 - lh.opcode_base) / lh.line_range);
1676                   address += lh.minimum_instruction_length
1677                              * ((op_index + adjust) / lh.maximum_ops_per_insn);
1678                   op_index = (op_index + adjust) % lh.maximum_ops_per_insn;
1679                 }
1680               break;
1681             case DW_LNS_fixed_advance_pc:
1682               address += read_2_bytes (abfd, line_ptr);
1683               op_index = 0;
1684               line_ptr += 2;
1685               break;
1686             default:
1687               /* Unknown standard opcode, ignore it.  */
1688               for (i = 0; i < lh.standard_opcode_lengths[op_code]; i++)
1689                 {
1690                   (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
1691                   line_ptr += bytes_read;
1692                 }
1693               break;
1694             }
1695         }
1696
1697       if (filename)
1698         free (filename);
1699     }
1700
1701   if (sort_line_sequences (table))
1702     return table;
1703
1704  fail:
1705   if (table->sequences != NULL)
1706     free (table->sequences);
1707   if (table->files != NULL)
1708     free (table->files);
1709   if (table->dirs != NULL)
1710     free (table->dirs);
1711   return NULL;
1712 }
1713
1714 /* If ADDR is within TABLE set the output parameters and return TRUE,
1715    otherwise return FALSE.  The output parameters, FILENAME_PTR and
1716    LINENUMBER_PTR, are pointers to the objects to be filled in.  */
1717
1718 static bfd_boolean
1719 lookup_address_in_line_info_table (struct line_info_table *table,
1720                                    bfd_vma addr,
1721                                    const char **filename_ptr,
1722                                    unsigned int *linenumber_ptr)
1723 {
1724   struct line_sequence *seq = NULL;
1725   struct line_info *each_line;
1726   int low, high, mid;
1727
1728   /* Binary search the array of sequences.  */
1729   low = 0;
1730   high = table->num_sequences;
1731   while (low < high)
1732     {
1733       mid = (low + high) / 2;
1734       seq = &table->sequences[mid];
1735       if (addr < seq->low_pc)
1736         high = mid;
1737       else if (addr >= seq->last_line->address)
1738         low = mid + 1;
1739       else
1740         break;
1741     }
1742
1743   if (seq && addr >= seq->low_pc && addr < seq->last_line->address)
1744     {
1745       /* Note: seq->last_line should be a descendingly sorted list.  */
1746       for (each_line = seq->last_line;
1747            each_line;
1748            each_line = each_line->prev_line)
1749         if (addr >= each_line->address)
1750           break;
1751
1752       if (each_line
1753           && !(each_line->end_sequence || each_line == seq->last_line))
1754         {
1755           *filename_ptr = each_line->filename;
1756           *linenumber_ptr = each_line->line;
1757           return TRUE;
1758         }
1759     }
1760
1761   *filename_ptr = NULL;
1762   return FALSE;
1763 }
1764
1765 /* Read in the .debug_ranges section for future reference.  */
1766
1767 static bfd_boolean
1768 read_debug_ranges (struct comp_unit *unit)
1769 {
1770   struct dwarf2_debug *stash = unit->stash;
1771   return read_section (unit->abfd, ".debug_ranges", ".zdebug_ranges",
1772                        stash->syms, 0,
1773                        &stash->dwarf_ranges_buffer, &stash->dwarf_ranges_size);
1774 }
1775
1776 /* Function table functions.  */
1777
1778 /* If ADDR is within TABLE, set FUNCTIONNAME_PTR, and return TRUE.
1779    Note that we need to find the function that has the smallest
1780    range that contains ADDR, to handle inlined functions without
1781    depending upon them being ordered in TABLE by increasing range. */
1782
1783 static bfd_boolean
1784 lookup_address_in_function_table (struct comp_unit *unit,
1785                                   bfd_vma addr,
1786                                   struct funcinfo **function_ptr,
1787                                   const char **functionname_ptr)
1788 {
1789   struct funcinfo* each_func;
1790   struct funcinfo* best_fit = NULL;
1791   struct arange *arange;
1792
1793   for (each_func = unit->function_table;
1794        each_func;
1795        each_func = each_func->prev_func)
1796     {
1797       for (arange = &each_func->arange;
1798            arange;
1799            arange = arange->next)
1800         {
1801           if (addr >= arange->low && addr < arange->high)
1802             {
1803               if (!best_fit ||
1804                   ((arange->high - arange->low) < (best_fit->arange.high - best_fit->arange.low)))
1805                 best_fit = each_func;
1806             }
1807         }
1808     }
1809
1810   if (best_fit)
1811     {
1812       *functionname_ptr = best_fit->name;
1813       *function_ptr = best_fit;
1814       return TRUE;
1815     }
1816   else
1817     {
1818       return FALSE;
1819     }
1820 }
1821
1822 /* If SYM at ADDR is within function table of UNIT, set FILENAME_PTR
1823    and LINENUMBER_PTR, and return TRUE.  */
1824
1825 static bfd_boolean
1826 lookup_symbol_in_function_table (struct comp_unit *unit,
1827                                  asymbol *sym,
1828                                  bfd_vma addr,
1829                                  const char **filename_ptr,
1830                                  unsigned int *linenumber_ptr)
1831 {
1832   struct funcinfo* each_func;
1833   struct funcinfo* best_fit = NULL;
1834   struct arange *arange;
1835   const char *name = bfd_asymbol_name (sym);
1836   asection *sec = bfd_get_section (sym);
1837
1838   for (each_func = unit->function_table;
1839        each_func;
1840        each_func = each_func->prev_func)
1841     {
1842       for (arange = &each_func->arange;
1843            arange;
1844            arange = arange->next)
1845         {
1846           if ((!each_func->sec || each_func->sec == sec)
1847               && addr >= arange->low
1848               && addr < arange->high
1849               && each_func->name
1850               && strcmp (name, each_func->name) == 0
1851               && (!best_fit
1852                   || ((arange->high - arange->low)
1853                       < (best_fit->arange.high - best_fit->arange.low))))
1854             best_fit = each_func;
1855         }
1856     }
1857
1858   if (best_fit)
1859     {
1860       best_fit->sec = sec;
1861       *filename_ptr = best_fit->file;
1862       *linenumber_ptr = best_fit->line;
1863       return TRUE;
1864     }
1865   else
1866     return FALSE;
1867 }
1868
1869 /* Variable table functions.  */
1870
1871 /* If SYM is within variable table of UNIT, set FILENAME_PTR and
1872    LINENUMBER_PTR, and return TRUE.  */
1873
1874 static bfd_boolean
1875 lookup_symbol_in_variable_table (struct comp_unit *unit,
1876                                  asymbol *sym,
1877                                  bfd_vma addr,
1878                                  const char **filename_ptr,
1879                                  unsigned int *linenumber_ptr)
1880 {
1881   const char *name = bfd_asymbol_name (sym);
1882   asection *sec = bfd_get_section (sym);
1883   struct varinfo* each;
1884
1885   for (each = unit->variable_table; each; each = each->prev_var)
1886     if (each->stack == 0
1887         && each->file != NULL
1888         && each->name != NULL
1889         && each->addr == addr
1890         && (!each->sec || each->sec == sec)
1891         && strcmp (name, each->name) == 0)
1892       break;
1893
1894   if (each)
1895     {
1896       each->sec = sec;
1897       *filename_ptr = each->file;
1898       *linenumber_ptr = each->line;
1899       return TRUE;
1900     }
1901   else
1902     return FALSE;
1903 }
1904
1905 static char *
1906 find_abstract_instance_name (struct comp_unit *unit,
1907                              struct attribute *attr_ptr)
1908 {
1909   bfd *abfd = unit->abfd;
1910   bfd_byte *info_ptr;
1911   unsigned int abbrev_number, bytes_read, i;
1912   struct abbrev_info *abbrev;
1913   bfd_uint64_t die_ref = attr_ptr->u.val;
1914   struct attribute attr;
1915   char *name = 0;
1916
1917   /* DW_FORM_ref_addr can reference an entry in a different CU. It
1918      is an offset from the .debug_info section, not the current CU.  */
1919   if (attr_ptr->form == DW_FORM_ref_addr)
1920     {
1921       /* We only support DW_FORM_ref_addr within the same file, so
1922          any relocations should be resolved already.  */
1923       if (!die_ref)
1924         abort ();
1925
1926       info_ptr = unit->sec_info_ptr + die_ref;
1927     }
1928   else 
1929     info_ptr = unit->info_ptr_unit + die_ref;
1930   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
1931   info_ptr += bytes_read;
1932
1933   if (abbrev_number)
1934     {
1935       abbrev = lookup_abbrev (abbrev_number, unit->abbrevs);
1936       if (! abbrev)
1937         {
1938           (*_bfd_error_handler) (_("Dwarf Error: Could not find abbrev number %u."),
1939                                  abbrev_number);
1940           bfd_set_error (bfd_error_bad_value);
1941         }
1942       else
1943         {
1944           for (i = 0; i < abbrev->num_attrs; ++i)
1945             {
1946               info_ptr = read_attribute (&attr, &abbrev->attrs[i], unit,
1947                                          info_ptr);
1948               if (info_ptr == NULL)
1949                 break;
1950               switch (attr.name)
1951                 {
1952                 case DW_AT_name:
1953                   /* Prefer DW_AT_MIPS_linkage_name over DW_AT_name.  */
1954                   if (name == NULL)
1955                     name = attr.u.str;
1956                   break;
1957                 case DW_AT_specification:
1958                   name = find_abstract_instance_name (unit, &attr);
1959                   break;
1960                 case DW_AT_MIPS_linkage_name:
1961                   name = attr.u.str;
1962                   break;
1963                 default:
1964                   break;
1965                 }
1966             }
1967         }
1968     }
1969   return name;
1970 }
1971
1972 static bfd_boolean
1973 read_rangelist (struct comp_unit *unit, struct arange *arange,
1974                 bfd_uint64_t offset)
1975 {
1976   bfd_byte *ranges_ptr;
1977   bfd_vma base_address = unit->base_address;
1978
1979   if (! unit->stash->dwarf_ranges_buffer)
1980     {
1981       if (! read_debug_ranges (unit))
1982         return FALSE;
1983     }
1984   ranges_ptr = unit->stash->dwarf_ranges_buffer + offset;
1985
1986   for (;;)
1987     {
1988       bfd_vma low_pc;
1989       bfd_vma high_pc;
1990
1991       low_pc = read_address (unit, ranges_ptr);
1992       ranges_ptr += unit->addr_size;
1993       high_pc = read_address (unit, ranges_ptr);
1994       ranges_ptr += unit->addr_size;
1995
1996       if (low_pc == 0 && high_pc == 0)
1997         break;
1998       if (low_pc == -1UL && high_pc != -1UL)
1999         base_address = high_pc;
2000       else
2001         {
2002           if (!arange_add (unit->abfd, arange,
2003                            base_address + low_pc, base_address + high_pc))
2004             return FALSE;
2005         }
2006     }
2007   return TRUE;
2008 }
2009
2010 /* DWARF2 Compilation unit functions.  */
2011
2012 /* Scan over each die in a comp. unit looking for functions to add
2013    to the function table and variables to the variable table.  */
2014
2015 static bfd_boolean
2016 scan_unit_for_symbols (struct comp_unit *unit)
2017 {
2018   bfd *abfd = unit->abfd;
2019   bfd_byte *info_ptr = unit->first_child_die_ptr;
2020   int nesting_level = 1;
2021   struct funcinfo **nested_funcs;
2022   int nested_funcs_size;
2023
2024   /* Maintain a stack of in-scope functions and inlined functions, which we
2025      can use to set the caller_func field.  */
2026   nested_funcs_size = 32;
2027   nested_funcs = (struct funcinfo **)
2028       bfd_malloc (nested_funcs_size * sizeof (struct funcinfo *));
2029   if (nested_funcs == NULL)
2030     return FALSE;
2031   nested_funcs[nesting_level] = 0;
2032
2033   while (nesting_level)
2034     {
2035       unsigned int abbrev_number, bytes_read, i;
2036       struct abbrev_info *abbrev;
2037       struct attribute attr;
2038       struct funcinfo *func;
2039       struct varinfo *var;
2040       bfd_vma low_pc = 0;
2041       bfd_vma high_pc = 0;
2042
2043       abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
2044       info_ptr += bytes_read;
2045
2046       if (! abbrev_number)
2047         {
2048           nesting_level--;
2049           continue;
2050         }
2051
2052       abbrev = lookup_abbrev (abbrev_number,unit->abbrevs);
2053       if (! abbrev)
2054         {
2055           (*_bfd_error_handler)
2056             (_("Dwarf Error: Could not find abbrev number %u."),
2057              abbrev_number);
2058           bfd_set_error (bfd_error_bad_value);
2059           goto fail;
2060         }
2061
2062       var = NULL;
2063       if (abbrev->tag == DW_TAG_subprogram
2064           || abbrev->tag == DW_TAG_entry_point
2065           || abbrev->tag == DW_TAG_inlined_subroutine)
2066         {
2067           bfd_size_type amt = sizeof (struct funcinfo);
2068           func = (struct funcinfo *) bfd_zalloc (abfd, amt);
2069           if (func == NULL)
2070             goto fail;
2071           func->tag = abbrev->tag;
2072           func->prev_func = unit->function_table;
2073           unit->function_table = func;
2074           BFD_ASSERT (!unit->cached);
2075
2076           if (func->tag == DW_TAG_inlined_subroutine)
2077             for (i = nesting_level - 1; i >= 1; i--)
2078               if (nested_funcs[i])
2079                 {
2080                   func->caller_func = nested_funcs[i];
2081                   break;
2082                 }
2083           nested_funcs[nesting_level] = func;
2084         }
2085       else
2086         {
2087           func = NULL;
2088           if (abbrev->tag == DW_TAG_variable)
2089             {
2090               bfd_size_type amt = sizeof (struct varinfo);
2091               var = (struct varinfo *) bfd_zalloc (abfd, amt);
2092               if (var == NULL)
2093                 goto fail;
2094               var->tag = abbrev->tag;
2095               var->stack = 1;
2096               var->prev_var = unit->variable_table;
2097               unit->variable_table = var;
2098               BFD_ASSERT (!unit->cached);
2099             }
2100
2101           /* No inline function in scope at this nesting level.  */
2102           nested_funcs[nesting_level] = 0;
2103         }
2104
2105       for (i = 0; i < abbrev->num_attrs; ++i)
2106         {
2107           info_ptr = read_attribute (&attr, &abbrev->attrs[i], unit, info_ptr);
2108           if (info_ptr == NULL)
2109             return FALSE;
2110
2111           if (func)
2112             {
2113               switch (attr.name)
2114                 {
2115                 case DW_AT_call_file:
2116                   func->caller_file = concat_filename (unit->line_table,
2117                                                        attr.u.val);
2118                   break;
2119
2120                 case DW_AT_call_line:
2121                   func->caller_line = attr.u.val;
2122                   break;
2123
2124                 case DW_AT_abstract_origin:
2125                   func->name = find_abstract_instance_name (unit, &attr);
2126                   break;
2127
2128                 case DW_AT_name:
2129                   /* Prefer DW_AT_MIPS_linkage_name over DW_AT_name.  */
2130                   if (func->name == NULL)
2131                     func->name = attr.u.str;
2132                   break;
2133
2134                 case DW_AT_MIPS_linkage_name:
2135                   func->name = attr.u.str;
2136                   break;
2137
2138                 case DW_AT_low_pc:
2139                   low_pc = attr.u.val;
2140                   break;
2141
2142                 case DW_AT_high_pc:
2143                   high_pc = attr.u.val;
2144                   break;
2145
2146                 case DW_AT_ranges:
2147                   if (!read_rangelist (unit, &func->arange, attr.u.val))
2148                     goto fail;
2149                   break;
2150
2151                 case DW_AT_decl_file:
2152                   func->file = concat_filename (unit->line_table,
2153                                                 attr.u.val);
2154                   break;
2155
2156                 case DW_AT_decl_line:
2157                   func->line = attr.u.val;
2158                   break;
2159
2160                 default:
2161                   break;
2162                 }
2163             }
2164           else if (var)
2165             {
2166               switch (attr.name)
2167                 {
2168                 case DW_AT_name:
2169                   var->name = attr.u.str;
2170                   break;
2171
2172                 case DW_AT_decl_file:
2173                   var->file = concat_filename (unit->line_table,
2174                                                attr.u.val);
2175                   break;
2176
2177                 case DW_AT_decl_line:
2178                   var->line = attr.u.val;
2179                   break;
2180
2181                 case DW_AT_external:
2182                   if (attr.u.val != 0)
2183                     var->stack = 0;
2184                   break;
2185
2186                 case DW_AT_location:
2187                   switch (attr.form)
2188                     {
2189                     case DW_FORM_block:
2190                     case DW_FORM_block1:
2191                     case DW_FORM_block2:
2192                     case DW_FORM_block4:
2193                     case DW_FORM_exprloc:
2194                       if (*attr.u.blk->data == DW_OP_addr)
2195                         {
2196                           var->stack = 0;
2197
2198                           /* Verify that DW_OP_addr is the only opcode in the
2199                              location, in which case the block size will be 1
2200                              plus the address size.  */
2201                           /* ??? For TLS variables, gcc can emit
2202                              DW_OP_addr <addr> DW_OP_GNU_push_tls_address
2203                              which we don't handle here yet.  */
2204                           if (attr.u.blk->size == unit->addr_size + 1U)
2205                             var->addr = bfd_get (unit->addr_size * 8,
2206                                                  unit->abfd,
2207                                                  attr.u.blk->data + 1);
2208                         }
2209                       break;
2210
2211                     default:
2212                       break;
2213                     }
2214                   break;
2215
2216                 default:
2217                   break;
2218                 }
2219             }
2220         }
2221
2222       if (func && high_pc != 0)
2223         {
2224           if (!arange_add (unit->abfd, &func->arange, low_pc, high_pc))
2225             goto fail;
2226         }
2227
2228       if (abbrev->has_children)
2229         {
2230           nesting_level++;
2231
2232           if (nesting_level >= nested_funcs_size)
2233             {
2234               struct funcinfo **tmp;
2235
2236               nested_funcs_size *= 2;
2237               tmp = (struct funcinfo **)
2238                  bfd_realloc (nested_funcs,
2239                               (nested_funcs_size * sizeof (struct funcinfo *)));
2240               if (tmp == NULL)
2241                 goto fail;
2242               nested_funcs = tmp;
2243             }
2244           nested_funcs[nesting_level] = 0;
2245         }
2246     }
2247
2248   free (nested_funcs);
2249   return TRUE;
2250
2251  fail:
2252   free (nested_funcs);
2253   return FALSE;
2254 }
2255
2256 /* Parse a DWARF2 compilation unit starting at INFO_PTR.  This
2257    includes the compilation unit header that proceeds the DIE's, but
2258    does not include the length field that precedes each compilation
2259    unit header.  END_PTR points one past the end of this comp unit.
2260    OFFSET_SIZE is the size of DWARF2 offsets (either 4 or 8 bytes).
2261
2262    This routine does not read the whole compilation unit; only enough
2263    to get to the line number information for the compilation unit.  */
2264
2265 static struct comp_unit *
2266 parse_comp_unit (struct dwarf2_debug *stash,
2267                  bfd_vma unit_length,
2268                  bfd_byte *info_ptr_unit,
2269                  unsigned int offset_size)
2270 {
2271   struct comp_unit* unit;
2272   unsigned int version;
2273   bfd_uint64_t abbrev_offset = 0;
2274   unsigned int addr_size;
2275   struct abbrev_info** abbrevs;
2276   unsigned int abbrev_number, bytes_read, i;
2277   struct abbrev_info *abbrev;
2278   struct attribute attr;
2279   bfd_byte *info_ptr = stash->info_ptr;
2280   bfd_byte *end_ptr = info_ptr + unit_length;
2281   bfd_size_type amt;
2282   bfd_vma low_pc = 0;
2283   bfd_vma high_pc = 0;
2284   bfd *abfd = stash->bfd_ptr;
2285
2286   version = read_2_bytes (abfd, info_ptr);
2287   info_ptr += 2;
2288   BFD_ASSERT (offset_size == 4 || offset_size == 8);
2289   if (offset_size == 4)
2290     abbrev_offset = read_4_bytes (abfd, info_ptr);
2291   else
2292     abbrev_offset = read_8_bytes (abfd, info_ptr);
2293   info_ptr += offset_size;
2294   addr_size = read_1_byte (abfd, info_ptr);
2295   info_ptr += 1;
2296
2297   if (version != 2 && version != 3 && version != 4)
2298     {
2299       (*_bfd_error_handler) (_("Dwarf Error: found dwarf version '%u', this reader only handles version 2, 3 and 4 information."), version);
2300       bfd_set_error (bfd_error_bad_value);
2301       return 0;
2302     }
2303
2304   if (addr_size > sizeof (bfd_vma))
2305     {
2306       (*_bfd_error_handler) (_("Dwarf Error: found address size '%u', this reader can not handle sizes greater than '%u'."),
2307                          addr_size,
2308                          (unsigned int) sizeof (bfd_vma));
2309       bfd_set_error (bfd_error_bad_value);
2310       return 0;
2311     }
2312
2313   if (addr_size != 2 && addr_size != 4 && addr_size != 8)
2314     {
2315       (*_bfd_error_handler) ("Dwarf Error: found address size '%u', this reader can only handle address sizes '2', '4' and '8'.", addr_size);
2316       bfd_set_error (bfd_error_bad_value);
2317       return 0;
2318     }
2319
2320   /* Read the abbrevs for this compilation unit into a table.  */
2321   abbrevs = read_abbrevs (abfd, abbrev_offset, stash);
2322   if (! abbrevs)
2323       return 0;
2324
2325   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
2326   info_ptr += bytes_read;
2327   if (! abbrev_number)
2328     {
2329       (*_bfd_error_handler) (_("Dwarf Error: Bad abbrev number: %u."),
2330                          abbrev_number);
2331       bfd_set_error (bfd_error_bad_value);
2332       return 0;
2333     }
2334
2335   abbrev = lookup_abbrev (abbrev_number, abbrevs);
2336   if (! abbrev)
2337     {
2338       (*_bfd_error_handler) (_("Dwarf Error: Could not find abbrev number %u."),
2339                          abbrev_number);
2340       bfd_set_error (bfd_error_bad_value);
2341       return 0;
2342     }
2343
2344   amt = sizeof (struct comp_unit);
2345   unit = (struct comp_unit *) bfd_zalloc (abfd, amt);
2346   if (unit == NULL)
2347     return NULL;
2348   unit->abfd = abfd;
2349   unit->version = version;
2350   unit->addr_size = addr_size;
2351   unit->offset_size = offset_size;
2352   unit->abbrevs = abbrevs;
2353   unit->end_ptr = end_ptr;
2354   unit->stash = stash;
2355   unit->info_ptr_unit = info_ptr_unit;
2356   unit->sec_info_ptr = stash->sec_info_ptr;
2357
2358   for (i = 0; i < abbrev->num_attrs; ++i)
2359     {
2360       info_ptr = read_attribute (&attr, &abbrev->attrs[i], unit, info_ptr);
2361       if (info_ptr == NULL)
2362         return NULL;
2363
2364       /* Store the data if it is of an attribute we want to keep in a
2365          partial symbol table.  */
2366       switch (attr.name)
2367         {
2368         case DW_AT_stmt_list:
2369           unit->stmtlist = 1;
2370           unit->line_offset = attr.u.val;
2371           break;
2372
2373         case DW_AT_name:
2374           unit->name = attr.u.str;
2375           break;
2376
2377         case DW_AT_low_pc:
2378           low_pc = attr.u.val;
2379           /* If the compilation unit DIE has a DW_AT_low_pc attribute,
2380              this is the base address to use when reading location
2381              lists or range lists. */
2382           unit->base_address = low_pc;
2383           break;
2384
2385         case DW_AT_high_pc:
2386           high_pc = attr.u.val;
2387           break;
2388
2389         case DW_AT_ranges:
2390           if (!read_rangelist (unit, &unit->arange, attr.u.val))
2391             return NULL;
2392           break;
2393
2394         case DW_AT_comp_dir:
2395           {
2396             char *comp_dir = attr.u.str;
2397             if (comp_dir)
2398               {
2399                 /* Irix 6.2 native cc prepends <machine>.: to the compilation
2400                    directory, get rid of it.  */
2401                 char *cp = strchr (comp_dir, ':');
2402
2403                 if (cp && cp != comp_dir && cp[-1] == '.' && cp[1] == '/')
2404                   comp_dir = cp + 1;
2405               }
2406             unit->comp_dir = comp_dir;
2407             break;
2408           }
2409
2410         default:
2411           break;
2412         }
2413     }
2414   if (high_pc != 0)
2415     {
2416       if (!arange_add (unit->abfd, &unit->arange, low_pc, high_pc))
2417         return NULL;
2418     }
2419
2420   unit->first_child_die_ptr = info_ptr;
2421   return unit;
2422 }
2423
2424 /* Return TRUE if UNIT may contain the address given by ADDR.  When
2425    there are functions written entirely with inline asm statements, the
2426    range info in the compilation unit header may not be correct.  We
2427    need to consult the line info table to see if a compilation unit
2428    really contains the given address.  */
2429
2430 static bfd_boolean
2431 comp_unit_contains_address (struct comp_unit *unit, bfd_vma addr)
2432 {
2433   struct arange *arange;
2434
2435   if (unit->error)
2436     return FALSE;
2437
2438   arange = &unit->arange;
2439   do
2440     {
2441       if (addr >= arange->low && addr < arange->high)
2442         return TRUE;
2443       arange = arange->next;
2444     }
2445   while (arange);
2446
2447   return FALSE;
2448 }
2449
2450 /* If UNIT contains ADDR, set the output parameters to the values for
2451    the line containing ADDR.  The output parameters, FILENAME_PTR,
2452    FUNCTIONNAME_PTR, and LINENUMBER_PTR, are pointers to the objects
2453    to be filled in.
2454
2455    Return TRUE if UNIT contains ADDR, and no errors were encountered;
2456    FALSE otherwise.  */
2457
2458 static bfd_boolean
2459 comp_unit_find_nearest_line (struct comp_unit *unit,
2460                              bfd_vma addr,
2461                              const char **filename_ptr,
2462                              const char **functionname_ptr,
2463                              unsigned int *linenumber_ptr,
2464                              struct dwarf2_debug *stash)
2465 {
2466   bfd_boolean line_p;
2467   bfd_boolean func_p;
2468   struct funcinfo *function;
2469
2470   if (unit->error)
2471     return FALSE;
2472
2473   if (! unit->line_table)
2474     {
2475       if (! unit->stmtlist)
2476         {
2477           unit->error = 1;
2478           return FALSE;
2479         }
2480
2481       unit->line_table = decode_line_info (unit, stash);
2482
2483       if (! unit->line_table)
2484         {
2485           unit->error = 1;
2486           return FALSE;
2487         }
2488
2489       if (unit->first_child_die_ptr < unit->end_ptr
2490           && ! scan_unit_for_symbols (unit))
2491         {
2492           unit->error = 1;
2493           return FALSE;
2494         }
2495     }
2496
2497   function = NULL;
2498   func_p = lookup_address_in_function_table (unit, addr,
2499                                              &function, functionname_ptr);
2500   if (func_p && (function->tag == DW_TAG_inlined_subroutine))
2501     stash->inliner_chain = function;
2502   line_p = lookup_address_in_line_info_table (unit->line_table, addr,
2503                                               filename_ptr,
2504                                               linenumber_ptr);
2505   return line_p || func_p;
2506 }
2507
2508 /* Check to see if line info is already decoded in a comp_unit.
2509    If not, decode it.  Returns TRUE if no errors were encountered;
2510    FALSE otherwise.  */
2511
2512 static bfd_boolean
2513 comp_unit_maybe_decode_line_info (struct comp_unit *unit,
2514                                   struct dwarf2_debug *stash)
2515 {
2516   if (unit->error)
2517     return FALSE;
2518
2519   if (! unit->line_table)
2520     {
2521       if (! unit->stmtlist)
2522         {
2523           unit->error = 1;
2524           return FALSE;
2525         }
2526
2527       unit->line_table = decode_line_info (unit, stash);
2528
2529       if (! unit->line_table)
2530         {
2531           unit->error = 1;
2532           return FALSE;
2533         }
2534
2535       if (unit->first_child_die_ptr < unit->end_ptr
2536           && ! scan_unit_for_symbols (unit))
2537         {
2538           unit->error = 1;
2539           return FALSE;
2540         }
2541     }
2542
2543   return TRUE;
2544 }
2545
2546 /* If UNIT contains SYM at ADDR, set the output parameters to the
2547    values for the line containing SYM.  The output parameters,
2548    FILENAME_PTR, and LINENUMBER_PTR, are pointers to the objects to be
2549    filled in.
2550
2551    Return TRUE if UNIT contains SYM, and no errors were encountered;
2552    FALSE otherwise.  */
2553
2554 static bfd_boolean
2555 comp_unit_find_line (struct comp_unit *unit,
2556                      asymbol *sym,
2557                      bfd_vma addr,
2558                      const char **filename_ptr,
2559                      unsigned int *linenumber_ptr,
2560                      struct dwarf2_debug *stash)
2561 {
2562   if (!comp_unit_maybe_decode_line_info (unit, stash))
2563     return FALSE;
2564
2565   if (sym->flags & BSF_FUNCTION)
2566     return lookup_symbol_in_function_table (unit, sym, addr,
2567                                             filename_ptr,
2568                                             linenumber_ptr);
2569
2570   return lookup_symbol_in_variable_table (unit, sym, addr,
2571                                           filename_ptr,
2572                                           linenumber_ptr);
2573 }
2574
2575 static struct funcinfo *
2576 reverse_funcinfo_list (struct funcinfo *head)
2577 {
2578   struct funcinfo *rhead;
2579   struct funcinfo *temp;
2580
2581   for (rhead = NULL; head; head = temp)
2582     {
2583       temp = head->prev_func;
2584       head->prev_func = rhead;
2585       rhead = head;
2586     }
2587   return rhead;
2588 }
2589
2590 static struct varinfo *
2591 reverse_varinfo_list (struct varinfo *head)
2592 {
2593   struct varinfo *rhead;
2594   struct varinfo *temp;
2595
2596   for (rhead = NULL; head; head = temp)
2597     {
2598       temp = head->prev_var;
2599       head->prev_var = rhead;
2600       rhead = head;
2601     }
2602   return rhead;
2603 }
2604
2605 /* Extract all interesting funcinfos and varinfos of a compilation
2606    unit into hash tables for faster lookup.  Returns TRUE if no
2607    errors were enountered; FALSE otherwise.  */
2608
2609 static bfd_boolean
2610 comp_unit_hash_info (struct dwarf2_debug *stash,
2611                      struct comp_unit *unit,
2612                      struct info_hash_table *funcinfo_hash_table,
2613                      struct info_hash_table *varinfo_hash_table)
2614 {
2615   struct funcinfo* each_func;
2616   struct varinfo* each_var;
2617   bfd_boolean okay = TRUE;
2618
2619   BFD_ASSERT (stash->info_hash_status != STASH_INFO_HASH_DISABLED);
2620
2621   if (!comp_unit_maybe_decode_line_info (unit, stash))
2622     return FALSE;
2623
2624   BFD_ASSERT (!unit->cached);
2625
2626   /* To preserve the original search order, we went to visit the function
2627      infos in the reversed order of the list.  However, making the list
2628      bi-directional use quite a bit of extra memory.  So we reverse
2629      the list first, traverse the list in the now reversed order and
2630      finally reverse the list again to get back the original order.  */
2631   unit->function_table = reverse_funcinfo_list (unit->function_table);
2632   for (each_func = unit->function_table;
2633        each_func && okay;
2634        each_func = each_func->prev_func)
2635     {
2636       /* Skip nameless functions. */
2637       if (each_func->name)
2638         /* There is no need to copy name string into hash table as
2639            name string is either in the dwarf string buffer or
2640            info in the stash.  */
2641         okay = insert_info_hash_table (funcinfo_hash_table, each_func->name,
2642                                        (void*) each_func, FALSE);
2643     }
2644   unit->function_table = reverse_funcinfo_list (unit->function_table);
2645   if (!okay)
2646     return FALSE;
2647
2648   /* We do the same for variable infos.  */
2649   unit->variable_table = reverse_varinfo_list (unit->variable_table);
2650   for (each_var = unit->variable_table;
2651        each_var && okay;
2652        each_var = each_var->prev_var)
2653     {
2654       /* Skip stack vars and vars with no files or names.  */
2655       if (each_var->stack == 0
2656           && each_var->file != NULL
2657           && each_var->name != NULL)
2658         /* There is no need to copy name string into hash table as
2659            name string is either in the dwarf string buffer or
2660            info in the stash.  */
2661         okay = insert_info_hash_table (varinfo_hash_table, each_var->name,
2662                                        (void*) each_var, FALSE);
2663     }
2664
2665   unit->variable_table = reverse_varinfo_list (unit->variable_table);
2666   unit->cached = TRUE;
2667   return okay;
2668 }
2669
2670 /* Locate a section in a BFD containing debugging info.  The search starts
2671    from the section after AFTER_SEC, or from the first section in the BFD if
2672    AFTER_SEC is NULL.  The search works by examining the names of the
2673    sections.  There are two permissiable names.  The first is .debug_info.
2674    This is the standard DWARF2 name.  The second is a prefix .gnu.linkonce.wi.
2675    This is a variation on the .debug_info section which has a checksum
2676    describing the contents appended onto the name.  This allows the linker to
2677    identify and discard duplicate debugging sections for different
2678    compilation units.  */
2679 #define DWARF2_DEBUG_INFO ".debug_info"
2680 #define DWARF2_COMPRESSED_DEBUG_INFO ".zdebug_info"
2681 #define GNU_LINKONCE_INFO ".gnu.linkonce.wi."
2682
2683 static asection *
2684 find_debug_info (bfd *abfd, asection *after_sec)
2685 {
2686   asection * msec;
2687
2688   msec = after_sec != NULL ? after_sec->next : abfd->sections;
2689
2690   while (msec)
2691     {
2692       if (strcmp (msec->name, DWARF2_DEBUG_INFO) == 0)
2693         return msec;
2694
2695       if (strcmp (msec->name, DWARF2_COMPRESSED_DEBUG_INFO) == 0)
2696         return msec;
2697
2698       if (CONST_STRNEQ (msec->name, GNU_LINKONCE_INFO))
2699         return msec;
2700
2701       msec = msec->next;
2702     }
2703
2704   return NULL;
2705 }
2706
2707 /* Unset vmas for adjusted sections in STASH.  */
2708
2709 static void
2710 unset_sections (struct dwarf2_debug *stash)
2711 {
2712   unsigned int i;
2713   struct adjusted_section *p;
2714
2715   i = stash->adjusted_section_count;
2716   p = stash->adjusted_sections;
2717   for (; i > 0; i--, p++)
2718     p->section->vma = 0;
2719 }
2720
2721 /* Set unique VMAs for loadable and DWARF sections in ABFD and save
2722    VMAs in STASH for unset_sections.  */
2723
2724 static bfd_boolean
2725 place_sections (bfd *abfd, struct dwarf2_debug *stash)
2726 {
2727   struct adjusted_section *p;
2728   unsigned int i;
2729
2730   if (stash->adjusted_section_count != 0)
2731     {
2732       i = stash->adjusted_section_count;
2733       p = stash->adjusted_sections;
2734       for (; i > 0; i--, p++)
2735         p->section->vma = p->adj_vma;
2736     }
2737   else
2738     {
2739       asection *sect;
2740       bfd_vma last_vma = 0, last_dwarf = 0;
2741       bfd_size_type amt;
2742
2743       i = 0;
2744       for (sect = abfd->sections; sect != NULL; sect = sect->next)
2745         {
2746           bfd_size_type sz;
2747           int is_debug_info;
2748
2749           if (sect->vma != 0)
2750             continue;
2751
2752           /* We need to adjust the VMAs of any .debug_info sections.
2753              Skip compressed ones, since no relocations could target
2754              them - they should not appear in object files anyway.  */
2755           if (strcmp (sect->name, DWARF2_DEBUG_INFO) == 0)
2756             is_debug_info = 1;
2757           else if (CONST_STRNEQ (sect->name, GNU_LINKONCE_INFO))
2758             is_debug_info = 1;
2759           else
2760             is_debug_info = 0;
2761
2762           if (!is_debug_info && (sect->flags & SEC_LOAD) == 0)
2763             continue;
2764
2765           sz = sect->rawsize ? sect->rawsize : sect->size;
2766           if (sz == 0)
2767             continue;
2768
2769           i++;
2770         }
2771
2772       amt = i * sizeof (struct adjusted_section);
2773       p = (struct adjusted_section *) bfd_zalloc (abfd, amt);
2774       if (! p)
2775         return FALSE;
2776
2777       stash->adjusted_sections = p;
2778       stash->adjusted_section_count = i;
2779
2780       for (sect = abfd->sections; sect != NULL; sect = sect->next)
2781         {
2782           bfd_size_type sz;
2783           int is_debug_info;
2784
2785           if (sect->vma != 0)
2786             continue;
2787
2788           /* We need to adjust the VMAs of any .debug_info sections.
2789              Skip compressed ones, since no relocations could target
2790              them - they should not appear in object files anyway.  */
2791           if (strcmp (sect->name, DWARF2_DEBUG_INFO) == 0)
2792             is_debug_info = 1;
2793           else if (CONST_STRNEQ (sect->name, GNU_LINKONCE_INFO))
2794             is_debug_info = 1;
2795           else
2796             is_debug_info = 0;
2797
2798           if (!is_debug_info && (sect->flags & SEC_LOAD) == 0)
2799             continue;
2800
2801           sz = sect->rawsize ? sect->rawsize : sect->size;
2802           if (sz == 0)
2803             continue;
2804
2805           p->section = sect;
2806           if (is_debug_info)
2807             {
2808               BFD_ASSERT (sect->alignment_power == 0);
2809               sect->vma = last_dwarf;
2810               last_dwarf += sz;
2811             }
2812           else if (last_vma != 0)
2813             {
2814               /* Align the new address to the current section
2815                  alignment.  */
2816               last_vma = ((last_vma
2817                            + ~((bfd_vma) -1 << sect->alignment_power))
2818                           & ((bfd_vma) -1 << sect->alignment_power));
2819               sect->vma = last_vma;
2820               last_vma += sect->vma + sz;
2821             }
2822           else
2823             last_vma += sect->vma + sz;
2824
2825           p->adj_vma = sect->vma;
2826
2827           p++;
2828         }
2829     }
2830
2831   return TRUE;
2832 }
2833
2834 /* Look up a funcinfo by name using the given info hash table.  If found,
2835    also update the locations pointed to by filename_ptr and linenumber_ptr.
2836
2837    This function returns TRUE if a funcinfo that matches the given symbol
2838    and address is found with any error; otherwise it returns FALSE.  */
2839
2840 static bfd_boolean
2841 info_hash_lookup_funcinfo (struct info_hash_table *hash_table,
2842                            asymbol *sym,
2843                            bfd_vma addr,
2844                            const char **filename_ptr,
2845                            unsigned int *linenumber_ptr)
2846 {
2847   struct funcinfo* each_func;
2848   struct funcinfo* best_fit = NULL;
2849   struct info_list_node *node;
2850   struct arange *arange;
2851   const char *name = bfd_asymbol_name (sym);
2852   asection *sec = bfd_get_section (sym);
2853
2854   for (node = lookup_info_hash_table (hash_table, name);
2855        node;
2856        node = node->next)
2857     {
2858       each_func = (struct funcinfo *) node->info;
2859       for (arange = &each_func->arange;
2860            arange;
2861            arange = arange->next)
2862         {
2863           if ((!each_func->sec || each_func->sec == sec)
2864               && addr >= arange->low
2865               && addr < arange->high
2866               && (!best_fit
2867                   || ((arange->high - arange->low)
2868                       < (best_fit->arange.high - best_fit->arange.low))))
2869             best_fit = each_func;
2870         }
2871     }
2872
2873   if (best_fit)
2874     {
2875       best_fit->sec = sec;
2876       *filename_ptr = best_fit->file;
2877       *linenumber_ptr = best_fit->line;
2878       return TRUE;
2879     }
2880
2881   return FALSE;
2882 }
2883
2884 /* Look up a varinfo by name using the given info hash table.  If found,
2885    also update the locations pointed to by filename_ptr and linenumber_ptr.
2886
2887    This function returns TRUE if a varinfo that matches the given symbol
2888    and address is found with any error; otherwise it returns FALSE.  */
2889
2890 static bfd_boolean
2891 info_hash_lookup_varinfo (struct info_hash_table *hash_table,
2892                           asymbol *sym,
2893                           bfd_vma addr,
2894                           const char **filename_ptr,
2895                           unsigned int *linenumber_ptr)
2896 {
2897   const char *name = bfd_asymbol_name (sym);
2898   asection *sec = bfd_get_section (sym);
2899   struct varinfo* each;
2900   struct info_list_node *node;
2901
2902   for (node = lookup_info_hash_table (hash_table, name);
2903        node;
2904        node = node->next)
2905     {
2906       each = (struct varinfo *) node->info;
2907       if (each->addr == addr
2908           && (!each->sec || each->sec == sec))
2909         {
2910           each->sec = sec;
2911           *filename_ptr = each->file;
2912           *linenumber_ptr = each->line;
2913           return TRUE;
2914         }
2915     }
2916
2917   return FALSE;
2918 }
2919
2920 /* Update the funcinfo and varinfo info hash tables if they are
2921    not up to date.  Returns TRUE if there is no error; otherwise
2922    returns FALSE and disable the info hash tables.  */
2923
2924 static bfd_boolean
2925 stash_maybe_update_info_hash_tables (struct dwarf2_debug *stash)
2926 {
2927   struct comp_unit *each;
2928
2929   /* Exit if hash tables are up-to-date.  */
2930   if (stash->all_comp_units == stash->hash_units_head)
2931     return TRUE;
2932
2933   if (stash->hash_units_head)
2934     each = stash->hash_units_head->prev_unit;
2935   else
2936     each = stash->last_comp_unit;
2937
2938   while (each)
2939     {
2940       if (!comp_unit_hash_info (stash, each, stash->funcinfo_hash_table,
2941                                 stash->varinfo_hash_table))
2942         {
2943           stash->info_hash_status = STASH_INFO_HASH_DISABLED;
2944           return FALSE;
2945         }
2946       each = each->prev_unit;
2947     }
2948
2949   stash->hash_units_head = stash->all_comp_units;
2950   return TRUE;
2951 }
2952
2953 /* Check consistency of info hash tables.  This is for debugging only. */
2954
2955 static void ATTRIBUTE_UNUSED
2956 stash_verify_info_hash_table (struct dwarf2_debug *stash)
2957 {
2958   struct comp_unit *each_unit;
2959   struct funcinfo *each_func;
2960   struct varinfo *each_var;
2961   struct info_list_node *node;
2962   bfd_boolean found;
2963
2964   for (each_unit = stash->all_comp_units;
2965        each_unit;
2966        each_unit = each_unit->next_unit)
2967     {
2968       for (each_func = each_unit->function_table;
2969            each_func;
2970            each_func = each_func->prev_func)
2971         {
2972           if (!each_func->name)
2973             continue;
2974           node = lookup_info_hash_table (stash->funcinfo_hash_table,
2975                                          each_func->name);
2976           BFD_ASSERT (node);
2977           found = FALSE;
2978           while (node && !found)
2979             {
2980               found = node->info == each_func;
2981               node = node->next;
2982             }
2983           BFD_ASSERT (found);
2984         }
2985
2986       for (each_var = each_unit->variable_table;
2987            each_var;
2988            each_var = each_var->prev_var)
2989         {
2990           if (!each_var->name || !each_var->file || each_var->stack)
2991             continue;
2992           node = lookup_info_hash_table (stash->varinfo_hash_table,
2993                                          each_var->name);
2994           BFD_ASSERT (node);
2995           found = FALSE;
2996           while (node && !found)
2997             {
2998               found = node->info == each_var;
2999               node = node->next;
3000             }
3001           BFD_ASSERT (found);
3002         }
3003     }
3004 }
3005
3006 /* Check to see if we want to enable the info hash tables, which consume
3007    quite a bit of memory.  Currently we only check the number times
3008    bfd_dwarf2_find_line is called.  In the future, we may also want to
3009    take the number of symbols into account.  */
3010
3011 static void
3012 stash_maybe_enable_info_hash_tables (bfd *abfd, struct dwarf2_debug *stash)
3013 {
3014   BFD_ASSERT (stash->info_hash_status == STASH_INFO_HASH_OFF);
3015
3016   if (stash->info_hash_count++ < STASH_INFO_HASH_TRIGGER)
3017     return;
3018
3019   /* FIXME: Maybe we should check the reduce_memory_overheads
3020      and optimize fields in the bfd_link_info structure ?  */
3021
3022   /* Create hash tables.  */
3023   stash->funcinfo_hash_table = create_info_hash_table (abfd);
3024   stash->varinfo_hash_table = create_info_hash_table (abfd);
3025   if (!stash->funcinfo_hash_table || !stash->varinfo_hash_table)
3026     {
3027       /* Turn off info hashes if any allocation above fails.  */
3028       stash->info_hash_status = STASH_INFO_HASH_DISABLED;
3029       return;
3030     }
3031   /* We need a forced update so that the info hash tables will
3032      be created even though there is no compilation unit.  That
3033      happens if STASH_INFO_HASH_TRIGGER is 0.  */
3034   stash_maybe_update_info_hash_tables (stash);
3035   stash->info_hash_status = STASH_INFO_HASH_ON;
3036 }
3037
3038 /* Find the file and line associated with a symbol and address using the
3039    info hash tables of a stash. If there is a match, the function returns
3040    TRUE and update the locations pointed to by filename_ptr and linenumber_ptr;
3041    otherwise it returns FALSE.  */
3042
3043 static bfd_boolean
3044 stash_find_line_fast (struct dwarf2_debug *stash,
3045                       asymbol *sym,
3046                       bfd_vma addr,
3047                       const char **filename_ptr,
3048                       unsigned int *linenumber_ptr)
3049 {
3050   BFD_ASSERT (stash->info_hash_status == STASH_INFO_HASH_ON);
3051
3052   if (sym->flags & BSF_FUNCTION)
3053     return info_hash_lookup_funcinfo (stash->funcinfo_hash_table, sym, addr,
3054                                       filename_ptr, linenumber_ptr);
3055   return info_hash_lookup_varinfo (stash->varinfo_hash_table, sym, addr,
3056                                    filename_ptr, linenumber_ptr);
3057 }
3058
3059 /* Find the source code location of SYMBOL.  If SYMBOL is NULL
3060    then find the nearest source code location corresponding to
3061    the address SECTION + OFFSET.
3062    Returns TRUE if the line is found without error and fills in
3063    FILENAME_PTR and LINENUMBER_PTR.  In the case where SYMBOL was
3064    NULL the FUNCTIONNAME_PTR is also filled in.
3065    SYMBOLS contains the symbol table for ABFD.
3066    ADDR_SIZE is the number of bytes in the initial .debug_info length
3067    field and in the abbreviation offset, or zero to indicate that the
3068    default value should be used.  */
3069
3070 static bfd_boolean
3071 find_line (bfd *abfd,
3072            asection *section,
3073            bfd_vma offset,
3074            asymbol *symbol,
3075            asymbol **symbols,
3076            const char **filename_ptr,
3077            const char **functionname_ptr,
3078            unsigned int *linenumber_ptr,
3079            unsigned int addr_size,
3080            void **pinfo)
3081 {
3082   /* Read each compilation unit from the section .debug_info, and check
3083      to see if it contains the address we are searching for.  If yes,
3084      lookup the address, and return the line number info.  If no, go
3085      on to the next compilation unit.
3086
3087      We keep a list of all the previously read compilation units, and
3088      a pointer to the next un-read compilation unit.  Check the
3089      previously read units before reading more.  */
3090   struct dwarf2_debug *stash;
3091   /* What address are we looking for?  */
3092   bfd_vma addr;
3093   struct comp_unit* each;
3094   bfd_vma found = FALSE;
3095   bfd_boolean do_line;
3096
3097   stash = (struct dwarf2_debug *) *pinfo;
3098
3099   if (! stash)
3100     {
3101       bfd_size_type amt = sizeof (struct dwarf2_debug);
3102
3103       stash = (struct dwarf2_debug *) bfd_zalloc (abfd, amt);
3104       if (! stash)
3105         return FALSE;
3106     }
3107
3108   /* In a relocatable file, 2 functions may have the same address.
3109      We change the section vma so that they won't overlap.  */
3110   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
3111     {
3112       if (! place_sections (abfd, stash))
3113         return FALSE;
3114     }
3115
3116   do_line = (section == NULL
3117              && offset == 0
3118              && functionname_ptr == NULL
3119              && symbol != NULL);
3120   if (do_line)
3121     {
3122       addr = symbol->value;
3123       section = bfd_get_section (symbol);
3124     }
3125   else if (section != NULL
3126            && functionname_ptr != NULL
3127            && symbol == NULL)
3128     addr = offset;
3129   else
3130     abort ();
3131
3132   if (section->output_section)
3133     addr += section->output_section->vma + section->output_offset;
3134   else
3135     addr += section->vma;
3136   *filename_ptr = NULL;
3137   if (! do_line)
3138     *functionname_ptr = NULL;
3139   *linenumber_ptr = 0;
3140
3141   if (! *pinfo)
3142     {
3143       bfd *debug_bfd;
3144       bfd_size_type total_size;
3145       asection *msec;
3146
3147       *pinfo = stash;
3148
3149       msec = find_debug_info (abfd, NULL);
3150       if (msec == NULL)
3151         {
3152           char * debug_filename = bfd_follow_gnu_debuglink (abfd, DEBUGDIR);
3153
3154           if (debug_filename == NULL)
3155             /* No dwarf2 info, and no gnu_debuglink to follow.
3156                Note that at this point the stash has been allocated, but
3157                contains zeros.  This lets future calls to this function
3158                fail more quickly.  */
3159             goto done;
3160
3161           if ((debug_bfd = bfd_openr (debug_filename, NULL)) == NULL
3162               || ! bfd_check_format (debug_bfd, bfd_object)
3163               || (msec = find_debug_info (debug_bfd, NULL)) == NULL)
3164             {
3165               if (debug_bfd)
3166                 bfd_close (debug_bfd);
3167               /* FIXME: Should we report our failure to follow the debuglink ?  */
3168               free (debug_filename);
3169               goto done;
3170             }
3171         }
3172       else
3173         debug_bfd = abfd;
3174
3175       /* There can be more than one DWARF2 info section in a BFD these
3176          days.  First handle the easy case when there's only one.  If
3177          there's more than one, try case two: none of the sections is
3178          compressed.  In that case, read them all in and produce one
3179          large stash.  We do this in two passes - in the first pass we
3180          just accumulate the section sizes, and in the second pass we
3181          read in the section's contents.  (The allows us to avoid
3182          reallocing the data as we add sections to the stash.)  If
3183          some or all sections are compressed, then do things the slow
3184          way, with a bunch of reallocs.  */
3185
3186       if (! find_debug_info (debug_bfd, msec))
3187         {
3188           /* Case 1: only one info section.  */
3189           total_size = msec->size;
3190           if (! read_section (debug_bfd, ".debug_info", ".zdebug_info",
3191                               symbols, 0,
3192                               &stash->info_ptr_memory, &total_size))
3193             goto done;
3194         }
3195       else
3196         {
3197           int all_uncompressed = 1;
3198           for (total_size = 0; msec; msec = find_debug_info (debug_bfd, msec))
3199             {
3200               total_size += msec->size;
3201               if (strcmp (msec->name, DWARF2_COMPRESSED_DEBUG_INFO) == 0)
3202                 all_uncompressed = 0;
3203             }
3204           if (all_uncompressed)
3205             {
3206               /* Case 2: multiple sections, but none is compressed.  */
3207               stash->info_ptr_memory = (bfd_byte *) bfd_malloc (total_size);
3208               if (stash->info_ptr_memory == NULL)
3209                 goto done;
3210
3211               total_size = 0;
3212               for (msec = find_debug_info (debug_bfd, NULL);
3213                    msec;
3214                    msec = find_debug_info (debug_bfd, msec))
3215                 {
3216                   bfd_size_type size;
3217
3218                   size = msec->size;
3219                   if (size == 0)
3220                     continue;
3221
3222                   if (!(bfd_simple_get_relocated_section_contents
3223                         (debug_bfd, msec, stash->info_ptr_memory + total_size,
3224                          symbols)))
3225                     goto done;
3226
3227                   total_size += size;
3228                 }
3229             }
3230           else
3231             {
3232               /* Case 3: multiple sections, some or all compressed.  */
3233               stash->info_ptr_memory = NULL;
3234               total_size = 0;
3235               for (msec = find_debug_info (debug_bfd, NULL);
3236                    msec;
3237                    msec = find_debug_info (debug_bfd, msec))
3238                 {
3239                   bfd_size_type size = msec->size;
3240                   bfd_byte *buffer, *tmp;
3241
3242                   if (size == 0)
3243                     continue;
3244
3245                   buffer = (bfd_simple_get_relocated_section_contents
3246                             (debug_bfd, msec, NULL, symbols));
3247                   if (! buffer)
3248                     goto done;
3249
3250                   if (strcmp (msec->name, DWARF2_COMPRESSED_DEBUG_INFO) == 0)
3251                     {
3252                       if (! bfd_uncompress_section_contents (&buffer, &size))
3253                         {
3254                           free (buffer);
3255                           goto done;
3256                         }
3257                     }
3258                   tmp = (bfd_byte *) bfd_realloc (stash->info_ptr_memory,
3259                                                   total_size + size);
3260                   if (tmp == NULL)
3261                     {
3262                       free (buffer);
3263                       goto done;
3264                     }
3265                   stash->info_ptr_memory = tmp;
3266                   memcpy (stash->info_ptr_memory + total_size, buffer, size);
3267                   free (buffer);
3268                   total_size += size;
3269                 }
3270             }
3271         }
3272
3273       stash->info_ptr = stash->info_ptr_memory;
3274       stash->info_ptr_end = stash->info_ptr + total_size;
3275       stash->sec = find_debug_info (debug_bfd, NULL);
3276       stash->sec_info_ptr = stash->info_ptr;
3277       stash->syms = symbols;
3278       stash->bfd_ptr = debug_bfd;
3279     }
3280
3281   /* A null info_ptr indicates that there is no dwarf2 info
3282      (or that an error occured while setting up the stash).  */
3283   if (! stash->info_ptr)
3284     goto done;
3285
3286   stash->inliner_chain = NULL;
3287
3288   /* Check the previously read comp. units first.  */
3289   if (do_line)
3290     {
3291       /* The info hash tables use quite a bit of memory.  We may not want to
3292          always use them.  We use some heuristics to decide if and when to
3293          turn it on.  */
3294       if (stash->info_hash_status == STASH_INFO_HASH_OFF)
3295         stash_maybe_enable_info_hash_tables (abfd, stash);
3296
3297       /* Keep info hash table up to date if they are available.  Note that we
3298          may disable the hash tables if there is any error duing update. */
3299       if (stash->info_hash_status == STASH_INFO_HASH_ON)
3300         stash_maybe_update_info_hash_tables (stash);
3301
3302       if (stash->info_hash_status == STASH_INFO_HASH_ON)
3303         {
3304           found = stash_find_line_fast (stash, symbol, addr, filename_ptr,
3305                                         linenumber_ptr);
3306           if (found)
3307             goto done;
3308         }
3309       else
3310         {
3311           /* Check the previously read comp. units first.  */
3312           for (each = stash->all_comp_units; each; each = each->next_unit)
3313             if ((symbol->flags & BSF_FUNCTION) == 0
3314                 || comp_unit_contains_address (each, addr))
3315               {
3316                 found = comp_unit_find_line (each, symbol, addr, filename_ptr,
3317                                              linenumber_ptr, stash);
3318                 if (found)
3319                   goto done;
3320               }
3321         }
3322     }
3323   else
3324     {
3325       for (each = stash->all_comp_units; each; each = each->next_unit)
3326         {
3327           found = (comp_unit_contains_address (each, addr)
3328                    && comp_unit_find_nearest_line (each, addr,
3329                                                    filename_ptr,
3330                                                    functionname_ptr,
3331                                                    linenumber_ptr,
3332                                                    stash));
3333           if (found)
3334             goto done;
3335         }
3336     }
3337
3338   /* The DWARF2 spec says that the initial length field, and the
3339      offset of the abbreviation table, should both be 4-byte values.
3340      However, some compilers do things differently.  */
3341   if (addr_size == 0)
3342     addr_size = 4;
3343   BFD_ASSERT (addr_size == 4 || addr_size == 8);
3344
3345   /* Read each remaining comp. units checking each as they are read.  */
3346   while (stash->info_ptr < stash->info_ptr_end)
3347     {
3348       bfd_vma length;
3349       unsigned int offset_size = addr_size;
3350       bfd_byte *info_ptr_unit = stash->info_ptr;
3351
3352       length = read_4_bytes (stash->bfd_ptr, stash->info_ptr);
3353       /* A 0xffffff length is the DWARF3 way of indicating
3354          we use 64-bit offsets, instead of 32-bit offsets.  */
3355       if (length == 0xffffffff)
3356         {
3357           offset_size = 8;
3358           length = read_8_bytes (stash->bfd_ptr, stash->info_ptr + 4);
3359           stash->info_ptr += 12;
3360         }
3361       /* A zero length is the IRIX way of indicating 64-bit offsets,
3362          mostly because the 64-bit length will generally fit in 32
3363          bits, and the endianness helps.  */
3364       else if (length == 0)
3365         {
3366           offset_size = 8;
3367           length = read_4_bytes (stash->bfd_ptr, stash->info_ptr + 4);
3368           stash->info_ptr += 8;
3369         }
3370       /* In the absence of the hints above, we assume 32-bit DWARF2
3371          offsets even for targets with 64-bit addresses, because:
3372            a) most of the time these targets will not have generated
3373               more than 2Gb of debug info and so will not need 64-bit
3374               offsets,
3375          and
3376            b) if they do use 64-bit offsets but they are not using
3377               the size hints that are tested for above then they are
3378               not conforming to the DWARF3 standard anyway.  */
3379       else if (addr_size == 8)
3380         {
3381           offset_size = 4;
3382           stash->info_ptr += 4;
3383         }
3384       else
3385         stash->info_ptr += 4;
3386
3387       if (length > 0)
3388         {
3389           each = parse_comp_unit (stash, length, info_ptr_unit,
3390                                   offset_size);
3391           if (!each)
3392             /* The dwarf information is damaged, don't trust it any
3393                more.  */
3394             break;
3395           stash->info_ptr += length;
3396
3397           if (stash->all_comp_units)
3398             stash->all_comp_units->prev_unit = each;
3399           else
3400             stash->last_comp_unit = each;
3401           
3402           each->next_unit = stash->all_comp_units;
3403           stash->all_comp_units = each;
3404           
3405           /* DW_AT_low_pc and DW_AT_high_pc are optional for
3406              compilation units.  If we don't have them (i.e.,
3407              unit->high == 0), we need to consult the line info table
3408              to see if a compilation unit contains the given
3409              address.  */
3410           if (do_line)
3411             found = (((symbol->flags & BSF_FUNCTION) == 0
3412                       || each->arange.high == 0
3413                       || comp_unit_contains_address (each, addr))
3414                      && comp_unit_find_line (each, symbol, addr,
3415                                              filename_ptr,
3416                                              linenumber_ptr,
3417                                              stash));
3418           else
3419             found = ((each->arange.high == 0
3420                       || comp_unit_contains_address (each, addr))
3421                      && comp_unit_find_nearest_line (each, addr,
3422                                                      filename_ptr,
3423                                                      functionname_ptr,
3424                                                      linenumber_ptr,
3425                                                      stash));
3426
3427           if ((bfd_vma) (stash->info_ptr - stash->sec_info_ptr)
3428               == stash->sec->size)
3429             {
3430               stash->sec = find_debug_info (stash->bfd_ptr, stash->sec);
3431               stash->sec_info_ptr = stash->info_ptr;
3432             }
3433
3434           if (found)
3435             goto done;
3436         }
3437     }
3438
3439 done:
3440   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
3441     unset_sections (stash);
3442
3443   return found;
3444 }
3445
3446 /* The DWARF2 version of find_nearest_line.
3447    Return TRUE if the line is found without error.  */
3448
3449 bfd_boolean
3450 _bfd_dwarf2_find_nearest_line (bfd *abfd,
3451                                asection *section,
3452                                asymbol **symbols,
3453                                bfd_vma offset,
3454                                const char **filename_ptr,
3455                                const char **functionname_ptr,
3456                                unsigned int *linenumber_ptr,
3457                                unsigned int addr_size,
3458                                void **pinfo)
3459 {
3460   return find_line (abfd, section, offset, NULL, symbols, filename_ptr,
3461                     functionname_ptr, linenumber_ptr, addr_size,
3462                     pinfo);
3463 }
3464
3465 /* The DWARF2 version of find_line.
3466    Return TRUE if the line is found without error.  */
3467
3468 bfd_boolean
3469 _bfd_dwarf2_find_line (bfd *abfd,
3470                        asymbol **symbols,
3471                        asymbol *symbol,
3472                        const char **filename_ptr,
3473                        unsigned int *linenumber_ptr,
3474                        unsigned int addr_size,
3475                        void **pinfo)
3476 {
3477   return find_line (abfd, NULL, 0, symbol, symbols, filename_ptr,
3478                     NULL, linenumber_ptr, addr_size,
3479                     pinfo);
3480 }
3481
3482 bfd_boolean
3483 _bfd_dwarf2_find_inliner_info (bfd *abfd ATTRIBUTE_UNUSED,
3484                                const char **filename_ptr,
3485                                const char **functionname_ptr,
3486                                unsigned int *linenumber_ptr,
3487                                void **pinfo)
3488 {
3489   struct dwarf2_debug *stash;
3490
3491   stash = (struct dwarf2_debug *) *pinfo;
3492   if (stash)
3493     {
3494       struct funcinfo *func = stash->inliner_chain;
3495
3496       if (func && func->caller_func)
3497         {
3498           *filename_ptr = func->caller_file;
3499           *functionname_ptr = func->caller_func->name;
3500           *linenumber_ptr = func->caller_line;
3501           stash->inliner_chain = func->caller_func;
3502           return TRUE;
3503         }
3504     }
3505
3506   return FALSE;
3507 }
3508
3509 void
3510 _bfd_dwarf2_cleanup_debug_info (bfd *abfd)
3511 {
3512   struct comp_unit *each;
3513   struct dwarf2_debug *stash;
3514
3515   if (abfd == NULL || elf_tdata (abfd) == NULL)
3516     return;
3517
3518   stash = (struct dwarf2_debug *) elf_tdata (abfd)->dwarf2_find_line_info;
3519
3520   if (stash == NULL)
3521     return;
3522
3523   for (each = stash->all_comp_units; each; each = each->next_unit)
3524     {
3525       struct abbrev_info **abbrevs = each->abbrevs;
3526       struct funcinfo *function_table = each->function_table;
3527       struct varinfo *variable_table = each->variable_table;
3528       size_t i;
3529
3530       for (i = 0; i < ABBREV_HASH_SIZE; i++)
3531         {
3532           struct abbrev_info *abbrev = abbrevs[i];
3533
3534           while (abbrev)
3535             {
3536               free (abbrev->attrs);
3537               abbrev = abbrev->next;
3538             }
3539         }
3540
3541       if (each->line_table)
3542         {
3543           free (each->line_table->dirs);
3544           free (each->line_table->files);
3545         }
3546
3547       while (function_table)
3548         {
3549           if (function_table->file)
3550             {
3551               free (function_table->file);
3552               function_table->file = NULL;
3553             }
3554
3555           if (function_table->caller_file)
3556             {
3557               free (function_table->caller_file);
3558               function_table->caller_file = NULL;
3559             }
3560           function_table = function_table->prev_func;
3561         }
3562
3563       while (variable_table)
3564         {
3565           if (variable_table->file)
3566             {
3567               free (variable_table->file);
3568               variable_table->file = NULL;
3569             }
3570
3571           variable_table = variable_table->prev_var;
3572         }
3573     }
3574
3575   if (stash->dwarf_abbrev_buffer)
3576     free (stash->dwarf_abbrev_buffer);
3577   if (stash->dwarf_line_buffer)
3578     free (stash->dwarf_line_buffer);
3579   if (stash->dwarf_str_buffer)
3580     free (stash->dwarf_str_buffer);
3581   if (stash->dwarf_ranges_buffer)
3582     free (stash->dwarf_ranges_buffer);
3583   if (stash->info_ptr_memory)
3584     free (stash->info_ptr_memory);
3585 }