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