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