PR22209, invalid memory read in find_abstract_instance_name
[external/binutils.git] / bfd / dwarf2.c
1 /* DWARF 2 support.
2    Copyright (C) 1994-2017 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 original bfd for which debug was loaded.  This is what
104      we use to compare and so check that the cached debug data is still
105      valid - it saves having to possibly dereference the gnu_debuglink each
106      time.  */
107   bfd *orig_bfd;
108
109   /* Pointer to the bfd, section and address of the beginning of the
110      section.  The bfd might be different than expected because of
111      gnu_debuglink sections.  */
112   bfd *bfd_ptr;
113   asection *sec;
114   bfd_byte *sec_info_ptr;
115
116   /* Support for alternate debug info sections created by the DWZ utility:
117      This includes a pointer to an alternate bfd which contains *extra*,
118      possibly duplicate debug sections, and pointers to the loaded
119      .debug_str and .debug_info sections from this bfd.  */
120   bfd *          alt_bfd_ptr;
121   bfd_byte *     alt_dwarf_str_buffer;
122   bfd_size_type  alt_dwarf_str_size;
123   bfd_byte *     alt_dwarf_info_buffer;
124   bfd_size_type  alt_dwarf_info_size;
125
126   /* A pointer to the memory block allocated for info_ptr.  Neither
127      info_ptr nor sec_info_ptr are guaranteed to stay pointing to the
128      beginning of the malloc block.  */
129   bfd_byte *info_ptr_memory;
130
131   /* Pointer to the symbol table.  */
132   asymbol **syms;
133
134   /* Pointer to the .debug_abbrev section loaded into memory.  */
135   bfd_byte *dwarf_abbrev_buffer;
136
137   /* Length of the loaded .debug_abbrev section.  */
138   bfd_size_type dwarf_abbrev_size;
139
140   /* Buffer for decode_line_info.  */
141   bfd_byte *dwarf_line_buffer;
142
143   /* Length of the loaded .debug_line section.  */
144   bfd_size_type dwarf_line_size;
145
146   /* Pointer to the .debug_str section loaded into memory.  */
147   bfd_byte *dwarf_str_buffer;
148
149   /* Length of the loaded .debug_str section.  */
150   bfd_size_type dwarf_str_size;
151
152   /* Pointer to the .debug_line_str section loaded into memory.  */
153   bfd_byte *dwarf_line_str_buffer;
154
155   /* Length of the loaded .debug_line_str section.  */
156   bfd_size_type dwarf_line_str_size;
157
158   /* Pointer to the .debug_ranges section loaded into memory.  */
159   bfd_byte *dwarf_ranges_buffer;
160
161   /* Length of the loaded .debug_ranges section.  */
162   bfd_size_type dwarf_ranges_size;
163
164   /* If the most recent call to bfd_find_nearest_line was given an
165      address in an inlined function, preserve a pointer into the
166      calling chain for subsequent calls to bfd_find_inliner_info to
167      use.  */
168   struct funcinfo *inliner_chain;
169
170   /* Section VMAs at the time the stash was built.  */
171   bfd_vma *sec_vma;
172
173   /* Number of sections whose VMA we must adjust.  */
174   int adjusted_section_count;
175
176   /* Array of sections with adjusted VMA.  */
177   struct adjusted_section *adjusted_sections;
178
179   /* Number of times find_line is called.  This is used in
180      the heuristic for enabling the info hash tables.  */
181   int info_hash_count;
182
183 #define STASH_INFO_HASH_TRIGGER    100
184
185   /* Hash table mapping symbol names to function infos.  */
186   struct info_hash_table *funcinfo_hash_table;
187
188   /* Hash table mapping symbol names to variable infos.  */
189   struct info_hash_table *varinfo_hash_table;
190
191   /* Head of comp_unit list in the last hash table update.  */
192   struct comp_unit *hash_units_head;
193
194   /* Status of info hash.  */
195   int info_hash_status;
196 #define STASH_INFO_HASH_OFF        0
197 #define STASH_INFO_HASH_ON         1
198 #define STASH_INFO_HASH_DISABLED   2
199
200   /* True if we opened bfd_ptr.  */
201   bfd_boolean close_on_cleanup;
202 };
203
204 struct arange
205 {
206   struct arange *next;
207   bfd_vma low;
208   bfd_vma high;
209 };
210
211 /* A minimal decoding of DWARF2 compilation units.  We only decode
212    what's needed to get to the line number information.  */
213
214 struct comp_unit
215 {
216   /* Chain the previously read compilation units.  */
217   struct comp_unit *next_unit;
218
219   /* Likewise, chain the compilation unit read after this one.
220      The comp units are stored in reversed reading order.  */
221   struct comp_unit *prev_unit;
222
223   /* Keep the bfd convenient (for memory allocation).  */
224   bfd *abfd;
225
226   /* The lowest and highest addresses contained in this compilation
227      unit as specified in the compilation unit header.  */
228   struct arange arange;
229
230   /* The DW_AT_name attribute (for error messages).  */
231   char *name;
232
233   /* The abbrev hash table.  */
234   struct abbrev_info **abbrevs;
235
236   /* DW_AT_language.  */
237   int lang;
238
239   /* Note that an error was found by comp_unit_find_nearest_line.  */
240   int error;
241
242   /* The DW_AT_comp_dir attribute.  */
243   char *comp_dir;
244
245   /* TRUE if there is a line number table associated with this comp. unit.  */
246   int stmtlist;
247
248   /* Pointer to the current comp_unit so that we can find a given entry
249      by its reference.  */
250   bfd_byte *info_ptr_unit;
251
252   /* The offset into .debug_line of the line number table.  */
253   unsigned long line_offset;
254
255   /* Pointer to the first child die for the comp unit.  */
256   bfd_byte *first_child_die_ptr;
257
258   /* The end of the comp unit.  */
259   bfd_byte *end_ptr;
260
261   /* The decoded line number, NULL if not yet decoded.  */
262   struct line_info_table *line_table;
263
264   /* A list of the functions found in this comp. unit.  */
265   struct funcinfo *function_table;
266
267   /* A table of function information references searchable by address.  */
268   struct lookup_funcinfo *lookup_funcinfo_table;
269
270   /* Number of functions in the function_table and sorted_function_table.  */
271   bfd_size_type number_of_functions;
272
273   /* A list of the variables found in this comp. unit.  */
274   struct varinfo *variable_table;
275
276   /* Pointer to dwarf2_debug structure.  */
277   struct dwarf2_debug *stash;
278
279   /* DWARF format version for this unit - from unit header.  */
280   int version;
281
282   /* Address size for this unit - from unit header.  */
283   unsigned char addr_size;
284
285   /* Offset size for this unit - from unit header.  */
286   unsigned char offset_size;
287
288   /* Base address for this unit - from DW_AT_low_pc attribute of
289      DW_TAG_compile_unit DIE */
290   bfd_vma base_address;
291
292   /* TRUE if symbols are cached in hash table for faster lookup by name.  */
293   bfd_boolean cached;
294 };
295
296 /* This data structure holds the information of an abbrev.  */
297 struct abbrev_info
298 {
299   unsigned int number;          /* Number identifying abbrev.  */
300   enum dwarf_tag tag;           /* DWARF tag.  */
301   int has_children;             /* Boolean.  */
302   unsigned int num_attrs;       /* Number of attributes.  */
303   struct attr_abbrev *attrs;    /* An array of attribute descriptions.  */
304   struct abbrev_info *next;     /* Next in chain.  */
305 };
306
307 struct attr_abbrev
308 {
309   enum dwarf_attribute name;
310   enum dwarf_form form;
311   bfd_vma implicit_const;
312 };
313
314 /* Map of uncompressed DWARF debug section name to compressed one.  It
315    is terminated by NULL uncompressed_name.  */
316
317 const struct dwarf_debug_section dwarf_debug_sections[] =
318 {
319   { ".debug_abbrev",            ".zdebug_abbrev" },
320   { ".debug_aranges",           ".zdebug_aranges" },
321   { ".debug_frame",             ".zdebug_frame" },
322   { ".debug_info",              ".zdebug_info" },
323   { ".debug_info",              ".zdebug_info" },
324   { ".debug_line",              ".zdebug_line" },
325   { ".debug_loc",               ".zdebug_loc" },
326   { ".debug_macinfo",           ".zdebug_macinfo" },
327   { ".debug_macro",             ".zdebug_macro" },
328   { ".debug_pubnames",          ".zdebug_pubnames" },
329   { ".debug_pubtypes",          ".zdebug_pubtypes" },
330   { ".debug_ranges",            ".zdebug_ranges" },
331   { ".debug_static_func",       ".zdebug_static_func" },
332   { ".debug_static_vars",       ".zdebug_static_vars" },
333   { ".debug_str",               ".zdebug_str", },
334   { ".debug_str",               ".zdebug_str", },
335   { ".debug_line_str",          ".zdebug_line_str", },
336   { ".debug_types",             ".zdebug_types" },
337   /* GNU DWARF 1 extensions */
338   { ".debug_sfnames",           ".zdebug_sfnames" },
339   { ".debug_srcinfo",           ".zebug_srcinfo" },
340   /* SGI/MIPS DWARF 2 extensions */
341   { ".debug_funcnames",         ".zdebug_funcnames" },
342   { ".debug_typenames",         ".zdebug_typenames" },
343   { ".debug_varnames",          ".zdebug_varnames" },
344   { ".debug_weaknames",         ".zdebug_weaknames" },
345   { NULL,                       NULL },
346 };
347
348 /* NB/ Numbers in this enum must match up with indicies
349    into the dwarf_debug_sections[] array above.  */
350 enum dwarf_debug_section_enum
351 {
352   debug_abbrev = 0,
353   debug_aranges,
354   debug_frame,
355   debug_info,
356   debug_info_alt,
357   debug_line,
358   debug_loc,
359   debug_macinfo,
360   debug_macro,
361   debug_pubnames,
362   debug_pubtypes,
363   debug_ranges,
364   debug_static_func,
365   debug_static_vars,
366   debug_str,
367   debug_str_alt,
368   debug_line_str,
369   debug_types,
370   debug_sfnames,
371   debug_srcinfo,
372   debug_funcnames,
373   debug_typenames,
374   debug_varnames,
375   debug_weaknames,
376   debug_max
377 };
378
379 /* A static assertion.  */
380 extern int dwarf_debug_section_assert[ARRAY_SIZE (dwarf_debug_sections)
381                                       == debug_max + 1 ? 1 : -1];
382
383 #ifndef ABBREV_HASH_SIZE
384 #define ABBREV_HASH_SIZE 121
385 #endif
386 #ifndef ATTR_ALLOC_CHUNK
387 #define ATTR_ALLOC_CHUNK 4
388 #endif
389
390 /* Variable and function hash tables.  This is used to speed up look-up
391    in lookup_symbol_in_var_table() and lookup_symbol_in_function_table().
392    In order to share code between variable and function infos, we use
393    a list of untyped pointer for all variable/function info associated with
394    a symbol.  We waste a bit of memory for list with one node but that
395    simplifies the code.  */
396
397 struct info_list_node
398 {
399   struct info_list_node *next;
400   void *info;
401 };
402
403 /* Info hash entry.  */
404 struct info_hash_entry
405 {
406   struct bfd_hash_entry root;
407   struct info_list_node *head;
408 };
409
410 struct info_hash_table
411 {
412   struct bfd_hash_table base;
413 };
414
415 /* Function to create a new entry in info hash table.  */
416
417 static struct bfd_hash_entry *
418 info_hash_table_newfunc (struct bfd_hash_entry *entry,
419                          struct bfd_hash_table *table,
420                          const char *string)
421 {
422   struct info_hash_entry *ret = (struct info_hash_entry *) entry;
423
424   /* Allocate the structure if it has not already been allocated by a
425      derived class.  */
426   if (ret == NULL)
427     {
428       ret = (struct info_hash_entry *) bfd_hash_allocate (table,
429                                                           sizeof (* ret));
430       if (ret == NULL)
431         return NULL;
432     }
433
434   /* Call the allocation method of the base class.  */
435   ret = ((struct info_hash_entry *)
436          bfd_hash_newfunc ((struct bfd_hash_entry *) ret, table, string));
437
438   /* Initialize the local fields here.  */
439   if (ret)
440     ret->head = NULL;
441
442   return (struct bfd_hash_entry *) ret;
443 }
444
445 /* Function to create a new info hash table.  It returns a pointer to the
446    newly created table or NULL if there is any error.  We need abfd
447    solely for memory allocation.  */
448
449 static struct info_hash_table *
450 create_info_hash_table (bfd *abfd)
451 {
452   struct info_hash_table *hash_table;
453
454   hash_table = ((struct info_hash_table *)
455                 bfd_alloc (abfd, sizeof (struct info_hash_table)));
456   if (!hash_table)
457     return hash_table;
458
459   if (!bfd_hash_table_init (&hash_table->base, info_hash_table_newfunc,
460                             sizeof (struct info_hash_entry)))
461     {
462       bfd_release (abfd, hash_table);
463       return NULL;
464     }
465
466   return hash_table;
467 }
468
469 /* Insert an info entry into an info hash table.  We do not check of
470    duplicate entries.  Also, the caller need to guarantee that the
471    right type of info in inserted as info is passed as a void* pointer.
472    This function returns true if there is no error.  */
473
474 static bfd_boolean
475 insert_info_hash_table (struct info_hash_table *hash_table,
476                         const char *key,
477                         void *info,
478                         bfd_boolean copy_p)
479 {
480   struct info_hash_entry *entry;
481   struct info_list_node *node;
482
483   entry = (struct info_hash_entry*) bfd_hash_lookup (&hash_table->base,
484                                                      key, TRUE, copy_p);
485   if (!entry)
486     return FALSE;
487
488   node = (struct info_list_node *) bfd_hash_allocate (&hash_table->base,
489                                                       sizeof (*node));
490   if (!node)
491     return FALSE;
492
493   node->info = info;
494   node->next = entry->head;
495   entry->head = node;
496
497   return TRUE;
498 }
499
500 /* Look up an info entry list from an info hash table.  Return NULL
501    if there is none.  */
502
503 static struct info_list_node *
504 lookup_info_hash_table (struct info_hash_table *hash_table, const char *key)
505 {
506   struct info_hash_entry *entry;
507
508   entry = (struct info_hash_entry*) bfd_hash_lookup (&hash_table->base, key,
509                                                      FALSE, FALSE);
510   return entry ? entry->head : NULL;
511 }
512
513 /* Read a section into its appropriate place in the dwarf2_debug
514    struct (indicated by SECTION_BUFFER and SECTION_SIZE).  If SYMS is
515    not NULL, use bfd_simple_get_relocated_section_contents to read the
516    section contents, otherwise use bfd_get_section_contents.  Fail if
517    the located section does not contain at least OFFSET bytes.  */
518
519 static bfd_boolean
520 read_section (bfd *           abfd,
521               const struct dwarf_debug_section *sec,
522               asymbol **      syms,
523               bfd_uint64_t    offset,
524               bfd_byte **     section_buffer,
525               bfd_size_type * section_size)
526 {
527   asection *msec;
528   const char *section_name = sec->uncompressed_name;
529
530   /* The section may have already been read.  */
531   if (*section_buffer == NULL)
532     {
533       msec = bfd_get_section_by_name (abfd, section_name);
534       if (! msec)
535         {
536           section_name = sec->compressed_name;
537           if (section_name != NULL)
538             msec = bfd_get_section_by_name (abfd, section_name);
539         }
540       if (! msec)
541         {
542           _bfd_error_handler (_("Dwarf Error: Can't find %s section."),
543                               sec->uncompressed_name);
544           bfd_set_error (bfd_error_bad_value);
545           return FALSE;
546         }
547
548       *section_size = msec->rawsize ? msec->rawsize : msec->size;
549       if (syms)
550         {
551           *section_buffer
552             = bfd_simple_get_relocated_section_contents (abfd, msec, NULL, syms);
553           if (! *section_buffer)
554             return FALSE;
555         }
556       else
557         {
558           *section_buffer = (bfd_byte *) bfd_malloc (*section_size);
559           if (! *section_buffer)
560             return FALSE;
561           if (! bfd_get_section_contents (abfd, msec, *section_buffer,
562                                           0, *section_size))
563             return FALSE;
564         }
565
566       /* Paranoia - if we are reading in a string section, make sure that it
567          is NUL terminated.  This is to prevent string functions from running
568          off the end of the buffer.  Note - knowing the size of the buffer is
569          not enough as some functions, eg strchr, do not have a range limited
570          equivalent.
571
572          FIXME: We ought to use a flag in the dwarf_debug_sections[] table to
573          determine the nature of a debug section, rather than checking the
574          section name as we do here.  */
575       if (*section_size > 0
576           && (*section_buffer)[*section_size - 1] != 0
577           && (strstr (section_name, "_str") || strstr (section_name, "names")))
578         {
579           bfd_byte * new_buffer = malloc (*section_size + 1);
580
581           _bfd_error_handler (_("warning: dwarf string section '%s' is not NUL terminated"),
582                               section_name);
583           memcpy (new_buffer, *section_buffer, *section_size);
584           new_buffer[*section_size] = 0;
585           free (*section_buffer);
586           *section_buffer = new_buffer;
587         }
588     }
589
590   /* It is possible to get a bad value for the offset into the section
591      that the client wants.  Validate it here to avoid trouble later.  */
592   if (offset != 0 && offset >= *section_size)
593     {
594       /* xgettext: c-format */
595       _bfd_error_handler (_("Dwarf Error: Offset (%llu)"
596                             " greater than or equal to %s size (%Lu)."),
597                           (long long) offset, section_name, *section_size);
598       bfd_set_error (bfd_error_bad_value);
599       return FALSE;
600     }
601
602   return TRUE;
603 }
604
605 /* Read dwarf information from a buffer.  */
606
607 static unsigned int
608 read_1_byte (bfd *abfd ATTRIBUTE_UNUSED, bfd_byte *buf, bfd_byte *end)
609 {
610   if (buf + 1 > end)
611     return 0;
612   return bfd_get_8 (abfd, buf);
613 }
614
615 static int
616 read_1_signed_byte (bfd *abfd ATTRIBUTE_UNUSED, bfd_byte *buf, bfd_byte *end)
617 {
618   if (buf + 1 > end)
619     return 0;
620   return bfd_get_signed_8 (abfd, buf);
621 }
622
623 static unsigned int
624 read_2_bytes (bfd *abfd, bfd_byte *buf, bfd_byte *end)
625 {
626   if (buf + 2 > end)
627     return 0;
628   return bfd_get_16 (abfd, buf);
629 }
630
631 static unsigned int
632 read_4_bytes (bfd *abfd, bfd_byte *buf, bfd_byte *end)
633 {
634   if (buf + 4 > end)
635     return 0;
636   return bfd_get_32 (abfd, buf);
637 }
638
639 static bfd_uint64_t
640 read_8_bytes (bfd *abfd, bfd_byte *buf, bfd_byte *end)
641 {
642   if (buf + 8 > end)
643     return 0;
644   return bfd_get_64 (abfd, buf);
645 }
646
647 static bfd_byte *
648 read_n_bytes (bfd *abfd ATTRIBUTE_UNUSED,
649               bfd_byte *buf,
650               bfd_byte *end,
651               unsigned int size ATTRIBUTE_UNUSED)
652 {
653   if (buf + size > end)
654     return NULL;
655   return buf;
656 }
657
658 /* Scans a NUL terminated string starting at BUF, returning a pointer to it.
659    Returns the number of characters in the string, *including* the NUL byte,
660    in BYTES_READ_PTR.  This value is set even if the function fails.  Bytes
661    at or beyond BUF_END will not be read.  Returns NULL if there was a
662    problem, or if the string is empty.  */
663
664 static char *
665 read_string (bfd *          abfd ATTRIBUTE_UNUSED,
666              bfd_byte *     buf,
667              bfd_byte *     buf_end,
668              unsigned int * bytes_read_ptr)
669 {
670   bfd_byte *str = buf;
671
672   if (buf >= buf_end)
673     {
674       * bytes_read_ptr = 0;
675       return NULL;
676     }
677
678   if (*str == '\0')
679     {
680       * bytes_read_ptr = 1;
681       return NULL;
682     }
683
684   while (buf < buf_end)
685     if (* buf ++ == 0)
686       {
687         * bytes_read_ptr = buf - str;
688         return (char *) str;
689       }
690
691   * bytes_read_ptr = buf - str;
692   return NULL;
693 }
694
695 /* Reads an offset from BUF and then locates the string at this offset
696    inside the debug string section.  Returns a pointer to the string.
697    Returns the number of bytes read from BUF, *not* the length of the string,
698    in BYTES_READ_PTR.  This value is set even if the function fails.  Bytes
699    at or beyond BUF_END will not be read from BUF.  Returns NULL if there was
700    a problem, or if the string is empty.  Does not check for NUL termination
701    of the string.  */
702
703 static char *
704 read_indirect_string (struct comp_unit * unit,
705                       bfd_byte *         buf,
706                       bfd_byte *         buf_end,
707                       unsigned int *     bytes_read_ptr)
708 {
709   bfd_uint64_t offset;
710   struct dwarf2_debug *stash = unit->stash;
711   char *str;
712
713   if (buf + unit->offset_size > buf_end)
714     {
715       * bytes_read_ptr = 0;
716       return NULL;
717     }
718
719   if (unit->offset_size == 4)
720     offset = read_4_bytes (unit->abfd, buf, buf_end);
721   else
722     offset = read_8_bytes (unit->abfd, buf, buf_end);
723
724   *bytes_read_ptr = unit->offset_size;
725
726   if (! read_section (unit->abfd, &stash->debug_sections[debug_str],
727                       stash->syms, offset,
728                       &stash->dwarf_str_buffer, &stash->dwarf_str_size))
729     return NULL;
730
731   if (offset >= stash->dwarf_str_size)
732     return NULL;
733   str = (char *) stash->dwarf_str_buffer + offset;
734   if (*str == '\0')
735     return NULL;
736   return str;
737 }
738
739 /* Like read_indirect_string but from .debug_line_str section.  */
740
741 static char *
742 read_indirect_line_string (struct comp_unit * unit,
743                            bfd_byte *         buf,
744                            bfd_byte *         buf_end,
745                            unsigned int *     bytes_read_ptr)
746 {
747   bfd_uint64_t offset;
748   struct dwarf2_debug *stash = unit->stash;
749   char *str;
750
751   if (buf + unit->offset_size > buf_end)
752     {
753       * bytes_read_ptr = 0;
754       return NULL;
755     }
756
757   if (unit->offset_size == 4)
758     offset = read_4_bytes (unit->abfd, buf, buf_end);
759   else
760     offset = read_8_bytes (unit->abfd, buf, buf_end);
761
762   *bytes_read_ptr = unit->offset_size;
763
764   if (! read_section (unit->abfd, &stash->debug_sections[debug_line_str],
765                       stash->syms, offset,
766                       &stash->dwarf_line_str_buffer,
767                       &stash->dwarf_line_str_size))
768     return NULL;
769
770   if (offset >= stash->dwarf_line_str_size)
771     return NULL;
772   str = (char *) stash->dwarf_line_str_buffer + offset;
773   if (*str == '\0')
774     return NULL;
775   return str;
776 }
777
778 /* Like read_indirect_string but uses a .debug_str located in
779    an alternate file pointed to by the .gnu_debugaltlink section.
780    Used to impement DW_FORM_GNU_strp_alt.  */
781
782 static char *
783 read_alt_indirect_string (struct comp_unit * unit,
784                           bfd_byte *         buf,
785                           bfd_byte *         buf_end,
786                           unsigned int *     bytes_read_ptr)
787 {
788   bfd_uint64_t offset;
789   struct dwarf2_debug *stash = unit->stash;
790   char *str;
791
792   if (buf + unit->offset_size > buf_end)
793     {
794       * bytes_read_ptr = 0;
795       return NULL;
796     }
797
798   if (unit->offset_size == 4)
799     offset = read_4_bytes (unit->abfd, buf, buf_end);
800   else
801     offset = read_8_bytes (unit->abfd, buf, buf_end);
802
803   *bytes_read_ptr = unit->offset_size;
804
805   if (stash->alt_bfd_ptr == NULL)
806     {
807       bfd *  debug_bfd;
808       char * debug_filename = bfd_follow_gnu_debugaltlink (unit->abfd, DEBUGDIR);
809
810       if (debug_filename == NULL)
811         return NULL;
812
813       if ((debug_bfd = bfd_openr (debug_filename, NULL)) == NULL
814           || ! bfd_check_format (debug_bfd, bfd_object))
815         {
816           if (debug_bfd)
817             bfd_close (debug_bfd);
818
819           /* FIXME: Should we report our failure to follow the debuglink ?  */
820           free (debug_filename);
821           return NULL;
822         }
823       stash->alt_bfd_ptr = debug_bfd;
824     }
825
826   if (! read_section (unit->stash->alt_bfd_ptr,
827                       stash->debug_sections + debug_str_alt,
828                       NULL, /* FIXME: Do we need to load alternate symbols ?  */
829                       offset,
830                       &stash->alt_dwarf_str_buffer,
831                       &stash->alt_dwarf_str_size))
832     return NULL;
833
834   if (offset >= stash->alt_dwarf_str_size)
835     return NULL;
836   str = (char *) stash->alt_dwarf_str_buffer + offset;
837   if (*str == '\0')
838     return NULL;
839
840   return str;
841 }
842
843 /* Resolve an alternate reference from UNIT at OFFSET.
844    Returns a pointer into the loaded alternate CU upon success
845    or NULL upon failure.  */
846
847 static bfd_byte *
848 read_alt_indirect_ref (struct comp_unit * unit,
849                        bfd_uint64_t       offset)
850 {
851   struct dwarf2_debug *stash = unit->stash;
852
853   if (stash->alt_bfd_ptr == NULL)
854     {
855       bfd *  debug_bfd;
856       char * debug_filename = bfd_follow_gnu_debugaltlink (unit->abfd, DEBUGDIR);
857
858       if (debug_filename == NULL)
859         return FALSE;
860
861       if ((debug_bfd = bfd_openr (debug_filename, NULL)) == NULL
862           || ! bfd_check_format (debug_bfd, bfd_object))
863         {
864           if (debug_bfd)
865             bfd_close (debug_bfd);
866
867           /* FIXME: Should we report our failure to follow the debuglink ?  */
868           free (debug_filename);
869           return NULL;
870         }
871       stash->alt_bfd_ptr = debug_bfd;
872     }
873
874   if (! read_section (unit->stash->alt_bfd_ptr,
875                       stash->debug_sections + debug_info_alt,
876                       NULL, /* FIXME: Do we need to load alternate symbols ?  */
877                       offset,
878                       &stash->alt_dwarf_info_buffer,
879                       &stash->alt_dwarf_info_size))
880     return NULL;
881
882   if (offset >= stash->alt_dwarf_info_size)
883     return NULL;
884   return stash->alt_dwarf_info_buffer + offset;
885 }
886
887 static bfd_uint64_t
888 read_address (struct comp_unit *unit, bfd_byte *buf, bfd_byte * buf_end)
889 {
890   int signed_vma = 0;
891
892   if (bfd_get_flavour (unit->abfd) == bfd_target_elf_flavour)
893     signed_vma = get_elf_backend_data (unit->abfd)->sign_extend_vma;
894
895   if (buf + unit->addr_size > buf_end)
896     return 0;
897
898   if (signed_vma)
899     {
900       switch (unit->addr_size)
901         {
902         case 8:
903           return bfd_get_signed_64 (unit->abfd, buf);
904         case 4:
905           return bfd_get_signed_32 (unit->abfd, buf);
906         case 2:
907           return bfd_get_signed_16 (unit->abfd, buf);
908         default:
909           abort ();
910         }
911     }
912   else
913     {
914       switch (unit->addr_size)
915         {
916         case 8:
917           return bfd_get_64 (unit->abfd, buf);
918         case 4:
919           return bfd_get_32 (unit->abfd, buf);
920         case 2:
921           return bfd_get_16 (unit->abfd, buf);
922         default:
923           abort ();
924         }
925     }
926 }
927
928 /* Lookup an abbrev_info structure in the abbrev hash table.  */
929
930 static struct abbrev_info *
931 lookup_abbrev (unsigned int number, struct abbrev_info **abbrevs)
932 {
933   unsigned int hash_number;
934   struct abbrev_info *abbrev;
935
936   hash_number = number % ABBREV_HASH_SIZE;
937   abbrev = abbrevs[hash_number];
938
939   while (abbrev)
940     {
941       if (abbrev->number == number)
942         return abbrev;
943       else
944         abbrev = abbrev->next;
945     }
946
947   return NULL;
948 }
949
950 /* In DWARF version 2, the description of the debugging information is
951    stored in a separate .debug_abbrev section.  Before we read any
952    dies from a section we read in all abbreviations and install them
953    in a hash table.  */
954
955 static struct abbrev_info**
956 read_abbrevs (bfd *abfd, bfd_uint64_t offset, struct dwarf2_debug *stash)
957 {
958   struct abbrev_info **abbrevs;
959   bfd_byte *abbrev_ptr;
960   bfd_byte *abbrev_end;
961   struct abbrev_info *cur_abbrev;
962   unsigned int abbrev_number, bytes_read, abbrev_name;
963   unsigned int abbrev_form, hash_number;
964   bfd_size_type amt;
965
966   if (! read_section (abfd, &stash->debug_sections[debug_abbrev],
967                       stash->syms, offset,
968                       &stash->dwarf_abbrev_buffer, &stash->dwarf_abbrev_size))
969     return NULL;
970
971   if (offset >= stash->dwarf_abbrev_size)
972     return NULL;
973
974   amt = sizeof (struct abbrev_info*) * ABBREV_HASH_SIZE;
975   abbrevs = (struct abbrev_info **) bfd_zalloc (abfd, amt);
976   if (abbrevs == NULL)
977     return NULL;
978
979   abbrev_ptr = stash->dwarf_abbrev_buffer + offset;
980   abbrev_end = stash->dwarf_abbrev_buffer + stash->dwarf_abbrev_size;
981   abbrev_number = _bfd_safe_read_leb128 (abfd, abbrev_ptr, &bytes_read,
982                                          FALSE, abbrev_end);
983   abbrev_ptr += bytes_read;
984
985   /* Loop until we reach an abbrev number of 0.  */
986   while (abbrev_number)
987     {
988       amt = sizeof (struct abbrev_info);
989       cur_abbrev = (struct abbrev_info *) bfd_zalloc (abfd, amt);
990       if (cur_abbrev == NULL)
991         return NULL;
992
993       /* Read in abbrev header.  */
994       cur_abbrev->number = abbrev_number;
995       cur_abbrev->tag = (enum dwarf_tag)
996         _bfd_safe_read_leb128 (abfd, abbrev_ptr, &bytes_read,
997                                FALSE, abbrev_end);
998       abbrev_ptr += bytes_read;
999       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr, abbrev_end);
1000       abbrev_ptr += 1;
1001
1002       /* Now read in declarations.  */
1003       for (;;)
1004         {
1005           /* Initialize it just to avoid a GCC false warning.  */
1006           bfd_vma implicit_const = -1;
1007
1008           abbrev_name = _bfd_safe_read_leb128 (abfd, abbrev_ptr, &bytes_read,
1009                                                FALSE, abbrev_end);
1010           abbrev_ptr += bytes_read;
1011           abbrev_form = _bfd_safe_read_leb128 (abfd, abbrev_ptr, &bytes_read,
1012                                                FALSE, abbrev_end);
1013           abbrev_ptr += bytes_read;
1014           if (abbrev_form == DW_FORM_implicit_const)
1015             {
1016               implicit_const = _bfd_safe_read_leb128 (abfd, abbrev_ptr,
1017                                                       &bytes_read, TRUE,
1018                                                       abbrev_end);
1019               abbrev_ptr += bytes_read;
1020             }
1021
1022           if (abbrev_name == 0)
1023             break;
1024
1025           if ((cur_abbrev->num_attrs % ATTR_ALLOC_CHUNK) == 0)
1026             {
1027               struct attr_abbrev *tmp;
1028
1029               amt = cur_abbrev->num_attrs + ATTR_ALLOC_CHUNK;
1030               amt *= sizeof (struct attr_abbrev);
1031               tmp = (struct attr_abbrev *) bfd_realloc (cur_abbrev->attrs, amt);
1032               if (tmp == NULL)
1033                 {
1034                   size_t i;
1035
1036                   for (i = 0; i < ABBREV_HASH_SIZE; i++)
1037                     {
1038                       struct abbrev_info *abbrev = abbrevs[i];
1039
1040                       while (abbrev)
1041                         {
1042                           free (abbrev->attrs);
1043                           abbrev = abbrev->next;
1044                         }
1045                     }
1046                   return NULL;
1047                 }
1048               cur_abbrev->attrs = tmp;
1049             }
1050
1051           cur_abbrev->attrs[cur_abbrev->num_attrs].name
1052             = (enum dwarf_attribute) abbrev_name;
1053           cur_abbrev->attrs[cur_abbrev->num_attrs].form
1054             = (enum dwarf_form) abbrev_form;
1055           cur_abbrev->attrs[cur_abbrev->num_attrs].implicit_const
1056             = implicit_const;
1057           ++cur_abbrev->num_attrs;
1058         }
1059
1060       hash_number = abbrev_number % ABBREV_HASH_SIZE;
1061       cur_abbrev->next = abbrevs[hash_number];
1062       abbrevs[hash_number] = cur_abbrev;
1063
1064       /* Get next abbreviation.
1065          Under Irix6 the abbreviations for a compilation unit are not
1066          always properly terminated with an abbrev number of 0.
1067          Exit loop if we encounter an abbreviation which we have
1068          already read (which means we are about to read the abbreviations
1069          for the next compile unit) or if the end of the abbreviation
1070          table is reached.  */
1071       if ((unsigned int) (abbrev_ptr - stash->dwarf_abbrev_buffer)
1072           >= stash->dwarf_abbrev_size)
1073         break;
1074       abbrev_number = _bfd_safe_read_leb128 (abfd, abbrev_ptr,
1075                                              &bytes_read, FALSE, abbrev_end);
1076       abbrev_ptr += bytes_read;
1077       if (lookup_abbrev (abbrev_number, abbrevs) != NULL)
1078         break;
1079     }
1080
1081   return abbrevs;
1082 }
1083
1084 /* Returns true if the form is one which has a string value.  */
1085
1086 static inline bfd_boolean
1087 is_str_attr (enum dwarf_form form)
1088 {
1089   return (form == DW_FORM_string || form == DW_FORM_strp
1090           || form == DW_FORM_line_strp || form == DW_FORM_GNU_strp_alt);
1091 }
1092
1093 /* Read and fill in the value of attribute ATTR as described by FORM.
1094    Read data starting from INFO_PTR, but never at or beyond INFO_PTR_END.
1095    Returns an updated INFO_PTR taking into account the amount of data read.  */
1096
1097 static bfd_byte *
1098 read_attribute_value (struct attribute *  attr,
1099                       unsigned            form,
1100                       bfd_vma             implicit_const,
1101                       struct comp_unit *  unit,
1102                       bfd_byte *          info_ptr,
1103                       bfd_byte *          info_ptr_end)
1104 {
1105   bfd *abfd = unit->abfd;
1106   unsigned int bytes_read;
1107   struct dwarf_block *blk;
1108   bfd_size_type amt;
1109
1110   if (info_ptr >= info_ptr_end && form != DW_FORM_flag_present)
1111     {
1112       _bfd_error_handler (_("Dwarf Error: Info pointer extends beyond end of attributes"));
1113       bfd_set_error (bfd_error_bad_value);
1114       return info_ptr;
1115     }
1116
1117   attr->form = (enum dwarf_form) form;
1118
1119   switch (form)
1120     {
1121     case DW_FORM_ref_addr:
1122       /* DW_FORM_ref_addr is an address in DWARF2, and an offset in
1123          DWARF3.  */
1124       if (unit->version == 3 || unit->version == 4)
1125         {
1126           if (unit->offset_size == 4)
1127             attr->u.val = read_4_bytes (unit->abfd, info_ptr, info_ptr_end);
1128           else
1129             attr->u.val = read_8_bytes (unit->abfd, info_ptr, info_ptr_end);
1130           info_ptr += unit->offset_size;
1131           break;
1132         }
1133       /* FALLTHROUGH */
1134     case DW_FORM_addr:
1135       attr->u.val = read_address (unit, info_ptr, info_ptr_end);
1136       info_ptr += unit->addr_size;
1137       break;
1138     case DW_FORM_GNU_ref_alt:
1139     case DW_FORM_sec_offset:
1140       if (unit->offset_size == 4)
1141         attr->u.val = read_4_bytes (unit->abfd, info_ptr, info_ptr_end);
1142       else
1143         attr->u.val = read_8_bytes (unit->abfd, info_ptr, info_ptr_end);
1144       info_ptr += unit->offset_size;
1145       break;
1146     case DW_FORM_block2:
1147       amt = sizeof (struct dwarf_block);
1148       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
1149       if (blk == NULL)
1150         return NULL;
1151       blk->size = read_2_bytes (abfd, info_ptr, info_ptr_end);
1152       info_ptr += 2;
1153       blk->data = read_n_bytes (abfd, info_ptr, info_ptr_end, blk->size);
1154       info_ptr += blk->size;
1155       attr->u.blk = blk;
1156       break;
1157     case DW_FORM_block4:
1158       amt = sizeof (struct dwarf_block);
1159       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
1160       if (blk == NULL)
1161         return NULL;
1162       blk->size = read_4_bytes (abfd, info_ptr, info_ptr_end);
1163       info_ptr += 4;
1164       blk->data = read_n_bytes (abfd, info_ptr, info_ptr_end, blk->size);
1165       info_ptr += blk->size;
1166       attr->u.blk = blk;
1167       break;
1168     case DW_FORM_data2:
1169       attr->u.val = read_2_bytes (abfd, info_ptr, info_ptr_end);
1170       info_ptr += 2;
1171       break;
1172     case DW_FORM_data4:
1173       attr->u.val = read_4_bytes (abfd, info_ptr, info_ptr_end);
1174       info_ptr += 4;
1175       break;
1176     case DW_FORM_data8:
1177       attr->u.val = read_8_bytes (abfd, info_ptr, info_ptr_end);
1178       info_ptr += 8;
1179       break;
1180     case DW_FORM_string:
1181       attr->u.str = read_string (abfd, info_ptr, info_ptr_end, &bytes_read);
1182       info_ptr += bytes_read;
1183       break;
1184     case DW_FORM_strp:
1185       attr->u.str = read_indirect_string (unit, info_ptr, info_ptr_end, &bytes_read);
1186       info_ptr += bytes_read;
1187       break;
1188     case DW_FORM_line_strp:
1189       attr->u.str = read_indirect_line_string (unit, info_ptr, info_ptr_end, &bytes_read);
1190       info_ptr += bytes_read;
1191       break;
1192     case DW_FORM_GNU_strp_alt:
1193       attr->u.str = read_alt_indirect_string (unit, info_ptr, info_ptr_end, &bytes_read);
1194       info_ptr += bytes_read;
1195       break;
1196     case DW_FORM_exprloc:
1197     case DW_FORM_block:
1198       amt = sizeof (struct dwarf_block);
1199       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
1200       if (blk == NULL)
1201         return NULL;
1202       blk->size = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
1203                                          FALSE, info_ptr_end);
1204       info_ptr += bytes_read;
1205       blk->data = read_n_bytes (abfd, info_ptr, info_ptr_end, blk->size);
1206       info_ptr += blk->size;
1207       attr->u.blk = blk;
1208       break;
1209     case DW_FORM_block1:
1210       amt = sizeof (struct dwarf_block);
1211       blk = (struct dwarf_block *) bfd_alloc (abfd, amt);
1212       if (blk == NULL)
1213         return NULL;
1214       blk->size = read_1_byte (abfd, info_ptr, info_ptr_end);
1215       info_ptr += 1;
1216       blk->data = read_n_bytes (abfd, info_ptr, info_ptr_end, blk->size);
1217       info_ptr += blk->size;
1218       attr->u.blk = blk;
1219       break;
1220     case DW_FORM_data1:
1221       attr->u.val = read_1_byte (abfd, info_ptr, info_ptr_end);
1222       info_ptr += 1;
1223       break;
1224     case DW_FORM_flag:
1225       attr->u.val = read_1_byte (abfd, info_ptr, info_ptr_end);
1226       info_ptr += 1;
1227       break;
1228     case DW_FORM_flag_present:
1229       attr->u.val = 1;
1230       break;
1231     case DW_FORM_sdata:
1232       attr->u.sval = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
1233                                             TRUE, info_ptr_end);
1234       info_ptr += bytes_read;
1235       break;
1236     case DW_FORM_udata:
1237       attr->u.val = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
1238                                            FALSE, info_ptr_end);
1239       info_ptr += bytes_read;
1240       break;
1241     case DW_FORM_ref1:
1242       attr->u.val = read_1_byte (abfd, info_ptr, info_ptr_end);
1243       info_ptr += 1;
1244       break;
1245     case DW_FORM_ref2:
1246       attr->u.val = read_2_bytes (abfd, info_ptr, info_ptr_end);
1247       info_ptr += 2;
1248       break;
1249     case DW_FORM_ref4:
1250       attr->u.val = read_4_bytes (abfd, info_ptr, info_ptr_end);
1251       info_ptr += 4;
1252       break;
1253     case DW_FORM_ref8:
1254       attr->u.val = read_8_bytes (abfd, info_ptr, info_ptr_end);
1255       info_ptr += 8;
1256       break;
1257     case DW_FORM_ref_sig8:
1258       attr->u.val = read_8_bytes (abfd, info_ptr, info_ptr_end);
1259       info_ptr += 8;
1260       break;
1261     case DW_FORM_ref_udata:
1262       attr->u.val = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
1263                                            FALSE, info_ptr_end);
1264       info_ptr += bytes_read;
1265       break;
1266     case DW_FORM_indirect:
1267       form = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
1268                                     FALSE, info_ptr_end);
1269       info_ptr += bytes_read;
1270       if (form == DW_FORM_implicit_const)
1271         {
1272           implicit_const = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
1273                                                   TRUE, info_ptr_end);
1274           info_ptr += bytes_read;
1275         }
1276       info_ptr = read_attribute_value (attr, form, implicit_const, unit,
1277                                        info_ptr, info_ptr_end);
1278       break;
1279     case DW_FORM_implicit_const:
1280       attr->form = DW_FORM_sdata;
1281       attr->u.sval = implicit_const;
1282       break;
1283     default:
1284       _bfd_error_handler (_("Dwarf Error: Invalid or unhandled FORM value: %#x."),
1285                           form);
1286       bfd_set_error (bfd_error_bad_value);
1287       return NULL;
1288     }
1289   return info_ptr;
1290 }
1291
1292 /* Read an attribute described by an abbreviated attribute.  */
1293
1294 static bfd_byte *
1295 read_attribute (struct attribute *    attr,
1296                 struct attr_abbrev *  abbrev,
1297                 struct comp_unit *    unit,
1298                 bfd_byte *            info_ptr,
1299                 bfd_byte *            info_ptr_end)
1300 {
1301   attr->name = abbrev->name;
1302   info_ptr = read_attribute_value (attr, abbrev->form, abbrev->implicit_const,
1303                                    unit, info_ptr, info_ptr_end);
1304   return info_ptr;
1305 }
1306
1307 /* Return whether DW_AT_name will return the same as DW_AT_linkage_name
1308    for a function.  */
1309
1310 static bfd_boolean
1311 non_mangled (int lang)
1312 {
1313   switch (lang)
1314     {
1315     default:
1316       return FALSE;
1317
1318     case DW_LANG_C89:
1319     case DW_LANG_C:
1320     case DW_LANG_Ada83:
1321     case DW_LANG_Cobol74:
1322     case DW_LANG_Cobol85:
1323     case DW_LANG_Fortran77:
1324     case DW_LANG_Pascal83:
1325     case DW_LANG_C99:
1326     case DW_LANG_Ada95:
1327     case DW_LANG_PLI:
1328     case DW_LANG_UPC:
1329     case DW_LANG_C11:
1330       return TRUE;
1331     }
1332 }
1333
1334 /* Source line information table routines.  */
1335
1336 #define FILE_ALLOC_CHUNK 5
1337 #define DIR_ALLOC_CHUNK 5
1338
1339 struct line_info
1340 {
1341   struct line_info *    prev_line;
1342   bfd_vma               address;
1343   char *                filename;
1344   unsigned int          line;
1345   unsigned int          column;
1346   unsigned int          discriminator;
1347   unsigned char         op_index;
1348   unsigned char         end_sequence;           /* End of (sequential) code sequence.  */
1349 };
1350
1351 struct fileinfo
1352 {
1353   char *                name;
1354   unsigned int          dir;
1355   unsigned int          time;
1356   unsigned int          size;
1357 };
1358
1359 struct line_sequence
1360 {
1361   bfd_vma               low_pc;
1362   struct line_sequence* prev_sequence;
1363   struct line_info*     last_line;  /* Largest VMA.  */
1364   struct line_info**    line_info_lookup;
1365   bfd_size_type         num_lines;
1366 };
1367
1368 struct line_info_table
1369 {
1370   bfd *                 abfd;
1371   unsigned int          num_files;
1372   unsigned int          num_dirs;
1373   unsigned int          num_sequences;
1374   char *                comp_dir;
1375   char **               dirs;
1376   struct fileinfo*      files;
1377   struct line_sequence* sequences;
1378   struct line_info*     lcl_head;   /* Local head; used in 'add_line_info'.  */
1379 };
1380
1381 /* Remember some information about each function.  If the function is
1382    inlined (DW_TAG_inlined_subroutine) it may have two additional
1383    attributes, DW_AT_call_file and DW_AT_call_line, which specify the
1384    source code location where this function was inlined.  */
1385
1386 struct funcinfo
1387 {
1388   /* Pointer to previous function in list of all functions.  */
1389   struct funcinfo *     prev_func;
1390   /* Pointer to function one scope higher.  */
1391   struct funcinfo *     caller_func;
1392   /* Source location file name where caller_func inlines this func.  */
1393   char *                caller_file;
1394   /* Source location file name.  */
1395   char *                file;
1396   /* Source location line number where caller_func inlines this func.  */
1397   int                   caller_line;
1398   /* Source location line number.  */
1399   int                   line;
1400   int                   tag;
1401   bfd_boolean           is_linkage;
1402   const char *          name;
1403   struct arange         arange;
1404   /* Where the symbol is defined.  */
1405   asection *            sec;
1406 };
1407
1408 struct lookup_funcinfo
1409 {
1410   /* Function information corresponding to this lookup table entry.  */
1411   struct funcinfo *     funcinfo;
1412
1413   /* The lowest address for this specific function.  */
1414   bfd_vma               low_addr;
1415
1416   /* The highest address of this function before the lookup table is sorted.
1417      The highest address of all prior functions after the lookup table is
1418      sorted, which is used for binary search.  */
1419   bfd_vma               high_addr;
1420 };
1421
1422 struct varinfo
1423 {
1424   /* Pointer to previous variable in list of all variables */
1425   struct varinfo *prev_var;
1426   /* Source location file name */
1427   char *file;
1428   /* Source location line number */
1429   int line;
1430   int tag;
1431   char *name;
1432   bfd_vma addr;
1433   /* Where the symbol is defined */
1434   asection *sec;
1435   /* Is this a stack variable? */
1436   unsigned int stack: 1;
1437 };
1438
1439 /* Return TRUE if NEW_LINE should sort after LINE.  */
1440
1441 static inline bfd_boolean
1442 new_line_sorts_after (struct line_info *new_line, struct line_info *line)
1443 {
1444   return (new_line->address > line->address
1445           || (new_line->address == line->address
1446               && (new_line->op_index > line->op_index
1447                   || (new_line->op_index == line->op_index
1448                       && new_line->end_sequence < line->end_sequence))));
1449 }
1450
1451
1452 /* Adds a new entry to the line_info list in the line_info_table, ensuring
1453    that the list is sorted.  Note that the line_info list is sorted from
1454    highest to lowest VMA (with possible duplicates); that is,
1455    line_info->prev_line always accesses an equal or smaller VMA.  */
1456
1457 static bfd_boolean
1458 add_line_info (struct line_info_table *table,
1459                bfd_vma address,
1460                unsigned char op_index,
1461                char *filename,
1462                unsigned int line,
1463                unsigned int column,
1464                unsigned int discriminator,
1465                int end_sequence)
1466 {
1467   bfd_size_type amt = sizeof (struct line_info);
1468   struct line_sequence* seq = table->sequences;
1469   struct line_info* info = (struct line_info *) bfd_alloc (table->abfd, amt);
1470
1471   if (info == NULL)
1472     return FALSE;
1473
1474   /* Set member data of 'info'.  */
1475   info->prev_line = NULL;
1476   info->address = address;
1477   info->op_index = op_index;
1478   info->line = line;
1479   info->column = column;
1480   info->discriminator = discriminator;
1481   info->end_sequence = end_sequence;
1482
1483   if (filename && filename[0])
1484     {
1485       info->filename = (char *) bfd_alloc (table->abfd, strlen (filename) + 1);
1486       if (info->filename == NULL)
1487         return FALSE;
1488       strcpy (info->filename, filename);
1489     }
1490   else
1491     info->filename = NULL;
1492
1493   /* Find the correct location for 'info'.  Normally we will receive
1494      new line_info data 1) in order and 2) with increasing VMAs.
1495      However some compilers break the rules (cf. decode_line_info) and
1496      so we include some heuristics for quickly finding the correct
1497      location for 'info'. In particular, these heuristics optimize for
1498      the common case in which the VMA sequence that we receive is a
1499      list of locally sorted VMAs such as
1500        p...z a...j  (where a < j < p < z)
1501
1502      Note: table->lcl_head is used to head an *actual* or *possible*
1503      sub-sequence within the list (such as a...j) that is not directly
1504      headed by table->last_line
1505
1506      Note: we may receive duplicate entries from 'decode_line_info'.  */
1507
1508   if (seq
1509       && seq->last_line->address == address
1510       && seq->last_line->op_index == op_index
1511       && seq->last_line->end_sequence == end_sequence)
1512     {
1513       /* We only keep the last entry with the same address and end
1514          sequence.  See PR ld/4986.  */
1515       if (table->lcl_head == seq->last_line)
1516         table->lcl_head = info;
1517       info->prev_line = seq->last_line->prev_line;
1518       seq->last_line = info;
1519     }
1520   else if (!seq || seq->last_line->end_sequence)
1521     {
1522       /* Start a new line sequence.  */
1523       amt = sizeof (struct line_sequence);
1524       seq = (struct line_sequence *) bfd_malloc (amt);
1525       if (seq == NULL)
1526         return FALSE;
1527       seq->low_pc = address;
1528       seq->prev_sequence = table->sequences;
1529       seq->last_line = info;
1530       table->lcl_head = info;
1531       table->sequences = seq;
1532       table->num_sequences++;
1533     }
1534   else if (new_line_sorts_after (info, seq->last_line))
1535     {
1536       /* Normal case: add 'info' to the beginning of the current sequence.  */
1537       info->prev_line = seq->last_line;
1538       seq->last_line = info;
1539
1540       /* lcl_head: initialize to head a *possible* sequence at the end.  */
1541       if (!table->lcl_head)
1542         table->lcl_head = info;
1543     }
1544   else if (!new_line_sorts_after (info, table->lcl_head)
1545            && (!table->lcl_head->prev_line
1546                || new_line_sorts_after (info, table->lcl_head->prev_line)))
1547     {
1548       /* Abnormal but easy: lcl_head is the head of 'info'.  */
1549       info->prev_line = table->lcl_head->prev_line;
1550       table->lcl_head->prev_line = info;
1551     }
1552   else
1553     {
1554       /* Abnormal and hard: Neither 'last_line' nor 'lcl_head'
1555          are valid heads for 'info'.  Reset 'lcl_head'.  */
1556       struct line_info* li2 = seq->last_line; /* Always non-NULL.  */
1557       struct line_info* li1 = li2->prev_line;
1558
1559       while (li1)
1560         {
1561           if (!new_line_sorts_after (info, li2)
1562               && new_line_sorts_after (info, li1))
1563             break;
1564
1565           li2 = li1; /* always non-NULL */
1566           li1 = li1->prev_line;
1567         }
1568       table->lcl_head = li2;
1569       info->prev_line = table->lcl_head->prev_line;
1570       table->lcl_head->prev_line = info;
1571       if (address < seq->low_pc)
1572         seq->low_pc = address;
1573     }
1574   return TRUE;
1575 }
1576
1577 /* Extract a fully qualified filename from a line info table.
1578    The returned string has been malloc'ed and it is the caller's
1579    responsibility to free it.  */
1580
1581 static char *
1582 concat_filename (struct line_info_table *table, unsigned int file)
1583 {
1584   char *filename;
1585
1586   if (file - 1 >= table->num_files)
1587     {
1588       /* FILE == 0 means unknown.  */
1589       if (file)
1590         _bfd_error_handler
1591           (_("Dwarf Error: mangled line number section (bad file number)."));
1592       return strdup ("<unknown>");
1593     }
1594
1595   filename = table->files[file - 1].name;
1596   if (filename == NULL)
1597     return strdup ("<unknown>");
1598
1599   if (!IS_ABSOLUTE_PATH (filename))
1600     {
1601       char *dir_name = NULL;
1602       char *subdir_name = NULL;
1603       char *name;
1604       size_t len;
1605
1606       if (table->files[file - 1].dir
1607           /* PR 17512: file: 0317e960.  */
1608           && table->files[file - 1].dir <= table->num_dirs
1609           /* PR 17512: file: 7f3d2e4b.  */
1610           && table->dirs != NULL)
1611         subdir_name = table->dirs[table->files[file - 1].dir - 1];
1612
1613       if (!subdir_name || !IS_ABSOLUTE_PATH (subdir_name))
1614         dir_name = table->comp_dir;
1615
1616       if (!dir_name)
1617         {
1618           dir_name = subdir_name;
1619           subdir_name = NULL;
1620         }
1621
1622       if (!dir_name)
1623         return strdup (filename);
1624
1625       len = strlen (dir_name) + strlen (filename) + 2;
1626
1627       if (subdir_name)
1628         {
1629           len += strlen (subdir_name) + 1;
1630           name = (char *) bfd_malloc (len);
1631           if (name)
1632             sprintf (name, "%s/%s/%s", dir_name, subdir_name, filename);
1633         }
1634       else
1635         {
1636           name = (char *) bfd_malloc (len);
1637           if (name)
1638             sprintf (name, "%s/%s", dir_name, filename);
1639         }
1640
1641       return name;
1642     }
1643
1644   return strdup (filename);
1645 }
1646
1647 static bfd_boolean
1648 arange_add (const struct comp_unit *unit, struct arange *first_arange,
1649             bfd_vma low_pc, bfd_vma high_pc)
1650 {
1651   struct arange *arange;
1652
1653   /* Ignore empty ranges.  */
1654   if (low_pc == high_pc)
1655     return TRUE;
1656
1657   /* If the first arange is empty, use it.  */
1658   if (first_arange->high == 0)
1659     {
1660       first_arange->low = low_pc;
1661       first_arange->high = high_pc;
1662       return TRUE;
1663     }
1664
1665   /* Next see if we can cheaply extend an existing range.  */
1666   arange = first_arange;
1667   do
1668     {
1669       if (low_pc == arange->high)
1670         {
1671           arange->high = high_pc;
1672           return TRUE;
1673         }
1674       if (high_pc == arange->low)
1675         {
1676           arange->low = low_pc;
1677           return TRUE;
1678         }
1679       arange = arange->next;
1680     }
1681   while (arange);
1682
1683   /* Need to allocate a new arange and insert it into the arange list.
1684      Order isn't significant, so just insert after the first arange.  */
1685   arange = (struct arange *) bfd_alloc (unit->abfd, sizeof (*arange));
1686   if (arange == NULL)
1687     return FALSE;
1688   arange->low = low_pc;
1689   arange->high = high_pc;
1690   arange->next = first_arange->next;
1691   first_arange->next = arange;
1692   return TRUE;
1693 }
1694
1695 /* Compare function for line sequences.  */
1696
1697 static int
1698 compare_sequences (const void* a, const void* b)
1699 {
1700   const struct line_sequence* seq1 = a;
1701   const struct line_sequence* seq2 = b;
1702
1703   /* Sort by low_pc as the primary key.  */
1704   if (seq1->low_pc < seq2->low_pc)
1705     return -1;
1706   if (seq1->low_pc > seq2->low_pc)
1707     return 1;
1708
1709   /* If low_pc values are equal, sort in reverse order of
1710      high_pc, so that the largest region comes first.  */
1711   if (seq1->last_line->address < seq2->last_line->address)
1712     return 1;
1713   if (seq1->last_line->address > seq2->last_line->address)
1714     return -1;
1715
1716   if (seq1->last_line->op_index < seq2->last_line->op_index)
1717     return 1;
1718   if (seq1->last_line->op_index > seq2->last_line->op_index)
1719     return -1;
1720
1721   return 0;
1722 }
1723
1724 /* Construct the line information table for quick lookup.  */
1725
1726 static bfd_boolean
1727 build_line_info_table (struct line_info_table *  table,
1728                        struct line_sequence *    seq)
1729 {
1730   bfd_size_type      amt;
1731   struct line_info** line_info_lookup;
1732   struct line_info*  each_line;
1733   unsigned int       num_lines;
1734   unsigned int       line_index;
1735
1736   if (seq->line_info_lookup != NULL)
1737     return TRUE;
1738
1739   /* Count the number of line information entries.  We could do this while
1740      scanning the debug information, but some entries may be added via
1741      lcl_head without having a sequence handy to increment the number of
1742      lines.  */
1743   num_lines = 0;
1744   for (each_line = seq->last_line; each_line; each_line = each_line->prev_line)
1745     num_lines++;
1746
1747   if (num_lines == 0)
1748     return TRUE;
1749
1750   /* Allocate space for the line information lookup table.  */
1751   amt = sizeof (struct line_info*) * num_lines;
1752   line_info_lookup = (struct line_info**) bfd_alloc (table->abfd, amt);
1753   if (line_info_lookup == NULL)
1754     return FALSE;
1755
1756   /* Create the line information lookup table.  */
1757   line_index = num_lines;
1758   for (each_line = seq->last_line; each_line; each_line = each_line->prev_line)
1759     line_info_lookup[--line_index] = each_line;
1760
1761   BFD_ASSERT (line_index == 0);
1762
1763   seq->num_lines = num_lines;
1764   seq->line_info_lookup = line_info_lookup;
1765
1766   return TRUE;
1767 }
1768
1769 /* Sort the line sequences for quick lookup.  */
1770
1771 static bfd_boolean
1772 sort_line_sequences (struct line_info_table* table)
1773 {
1774   bfd_size_type          amt;
1775   struct line_sequence*  sequences;
1776   struct line_sequence*  seq;
1777   unsigned int           n = 0;
1778   unsigned int           num_sequences = table->num_sequences;
1779   bfd_vma                last_high_pc;
1780
1781   if (num_sequences == 0)
1782     return TRUE;
1783
1784   /* Allocate space for an array of sequences.  */
1785   amt = sizeof (struct line_sequence) * num_sequences;
1786   sequences = (struct line_sequence *) bfd_alloc (table->abfd, amt);
1787   if (sequences == NULL)
1788     return FALSE;
1789
1790   /* Copy the linked list into the array, freeing the original nodes.  */
1791   seq = table->sequences;
1792   for (n = 0; n < num_sequences; n++)
1793     {
1794       struct line_sequence* last_seq = seq;
1795
1796       BFD_ASSERT (seq);
1797       sequences[n].low_pc = seq->low_pc;
1798       sequences[n].prev_sequence = NULL;
1799       sequences[n].last_line = seq->last_line;
1800       sequences[n].line_info_lookup = NULL;
1801       sequences[n].num_lines = 0;
1802       seq = seq->prev_sequence;
1803       free (last_seq);
1804     }
1805   BFD_ASSERT (seq == NULL);
1806
1807   qsort (sequences, n, sizeof (struct line_sequence), compare_sequences);
1808
1809   /* Make the list binary-searchable by trimming overlapping entries
1810      and removing nested entries.  */
1811   num_sequences = 1;
1812   last_high_pc = sequences[0].last_line->address;
1813   for (n = 1; n < table->num_sequences; n++)
1814     {
1815       if (sequences[n].low_pc < last_high_pc)
1816         {
1817           if (sequences[n].last_line->address <= last_high_pc)
1818             /* Skip nested entries.  */
1819             continue;
1820
1821           /* Trim overlapping entries.  */
1822           sequences[n].low_pc = last_high_pc;
1823         }
1824       last_high_pc = sequences[n].last_line->address;
1825       if (n > num_sequences)
1826         {
1827           /* Close up the gap.  */
1828           sequences[num_sequences].low_pc = sequences[n].low_pc;
1829           sequences[num_sequences].last_line = sequences[n].last_line;
1830         }
1831       num_sequences++;
1832     }
1833
1834   table->sequences = sequences;
1835   table->num_sequences = num_sequences;
1836   return TRUE;
1837 }
1838
1839 /* Add directory to TABLE.  CUR_DIR memory ownership is taken by TABLE.  */
1840
1841 static bfd_boolean
1842 line_info_add_include_dir (struct line_info_table *table, char *cur_dir)
1843 {
1844   if ((table->num_dirs % DIR_ALLOC_CHUNK) == 0)
1845     {
1846       char **tmp;
1847       bfd_size_type amt;
1848
1849       amt = table->num_dirs + DIR_ALLOC_CHUNK;
1850       amt *= sizeof (char *);
1851
1852       tmp = (char **) bfd_realloc (table->dirs, amt);
1853       if (tmp == NULL)
1854         return FALSE;
1855       table->dirs = tmp;
1856     }
1857
1858   table->dirs[table->num_dirs++] = cur_dir;
1859   return TRUE;
1860 }
1861
1862 static bfd_boolean
1863 line_info_add_include_dir_stub (struct line_info_table *table, char *cur_dir,
1864                                 unsigned int dir ATTRIBUTE_UNUSED,
1865                                 unsigned int xtime ATTRIBUTE_UNUSED,
1866                                 unsigned int size ATTRIBUTE_UNUSED)
1867 {
1868   return line_info_add_include_dir (table, cur_dir);
1869 }
1870
1871 /* Add file to TABLE.  CUR_FILE memory ownership is taken by TABLE.  */
1872
1873 static bfd_boolean
1874 line_info_add_file_name (struct line_info_table *table, char *cur_file,
1875                          unsigned int dir, unsigned int xtime,
1876                          unsigned int size)
1877 {
1878   if ((table->num_files % FILE_ALLOC_CHUNK) == 0)
1879     {
1880       struct fileinfo *tmp;
1881       bfd_size_type amt;
1882
1883       amt = table->num_files + FILE_ALLOC_CHUNK;
1884       amt *= sizeof (struct fileinfo);
1885
1886       tmp = (struct fileinfo *) bfd_realloc (table->files, amt);
1887       if (tmp == NULL)
1888         return FALSE;
1889       table->files = tmp;
1890     }
1891
1892   table->files[table->num_files].name = cur_file;
1893   table->files[table->num_files].dir = dir;
1894   table->files[table->num_files].time = xtime;
1895   table->files[table->num_files].size = size;
1896   table->num_files++;
1897   return TRUE;
1898 }
1899
1900 /* Read directory or file name entry format, starting with byte of
1901    format count entries, ULEB128 pairs of entry formats, ULEB128 of
1902    entries count and the entries themselves in the described entry
1903    format.  */
1904
1905 static bfd_boolean
1906 read_formatted_entries (struct comp_unit *unit, bfd_byte **bufp,
1907                         bfd_byte *buf_end, struct line_info_table *table,
1908                         bfd_boolean (*callback) (struct line_info_table *table,
1909                                                  char *cur_file,
1910                                                  unsigned int dir,
1911                                                  unsigned int time,
1912                                                  unsigned int size))
1913 {
1914   bfd *abfd = unit->abfd;
1915   bfd_byte format_count, formati;
1916   bfd_vma data_count, datai;
1917   bfd_byte *buf = *bufp;
1918   bfd_byte *format_header_data;
1919   unsigned int bytes_read;
1920
1921   format_count = read_1_byte (abfd, buf, buf_end);
1922   buf += 1;
1923   format_header_data = buf;
1924   for (formati = 0; formati < format_count; formati++)
1925     {
1926       _bfd_safe_read_leb128 (abfd, buf, &bytes_read, FALSE, buf_end);
1927       buf += bytes_read;
1928       _bfd_safe_read_leb128 (abfd, buf, &bytes_read, FALSE, buf_end);
1929       buf += bytes_read;
1930     }
1931
1932   data_count = _bfd_safe_read_leb128 (abfd, buf, &bytes_read, FALSE, buf_end);
1933   buf += bytes_read;
1934   if (format_count == 0 && data_count != 0)
1935     {
1936       _bfd_error_handler (_("Dwarf Error: Zero format count."));
1937       bfd_set_error (bfd_error_bad_value);
1938       return FALSE;
1939     }
1940
1941   for (datai = 0; datai < data_count; datai++)
1942     {
1943       bfd_byte *format = format_header_data;
1944       struct fileinfo fe;
1945
1946       memset (&fe, 0, sizeof fe);
1947       for (formati = 0; formati < format_count; formati++)
1948         {
1949           bfd_vma content_type, form;
1950           char *string_trash;
1951           char **stringp = &string_trash;
1952           unsigned int uint_trash, *uintp = &uint_trash;
1953
1954           content_type = _bfd_safe_read_leb128 (abfd, format, &bytes_read,
1955                                                 FALSE, buf_end);
1956           format += bytes_read;
1957           switch (content_type)
1958             {
1959             case DW_LNCT_path:
1960               stringp = &fe.name;
1961               break;
1962             case DW_LNCT_directory_index:
1963               uintp = &fe.dir;
1964               break;
1965             case DW_LNCT_timestamp:
1966               uintp = &fe.time;
1967               break;
1968             case DW_LNCT_size:
1969               uintp = &fe.size;
1970               break;
1971             case DW_LNCT_MD5:
1972               break;
1973             default:
1974               _bfd_error_handler
1975                 (_("Dwarf Error: Unknown format content type %Lu."),
1976                  content_type);
1977               bfd_set_error (bfd_error_bad_value);
1978               return FALSE;
1979             }
1980
1981           form = _bfd_safe_read_leb128 (abfd, format, &bytes_read, FALSE,
1982                                         buf_end);
1983           format += bytes_read;
1984           switch (form)
1985             {
1986             case DW_FORM_string:
1987               *stringp = read_string (abfd, buf, buf_end, &bytes_read);
1988               buf += bytes_read;
1989               break;
1990
1991             case DW_FORM_line_strp:
1992               *stringp = read_indirect_line_string (unit, buf, buf_end, &bytes_read);
1993               buf += bytes_read;
1994               break;
1995
1996             case DW_FORM_data1:
1997               *uintp = read_1_byte (abfd, buf, buf_end);
1998               buf += 1;
1999               break;
2000
2001             case DW_FORM_data2:
2002               *uintp = read_2_bytes (abfd, buf, buf_end);
2003               buf += 2;
2004               break;
2005
2006             case DW_FORM_data4:
2007               *uintp = read_4_bytes (abfd, buf, buf_end);
2008               buf += 4;
2009               break;
2010
2011             case DW_FORM_data8:
2012               *uintp = read_8_bytes (abfd, buf, buf_end);
2013               buf += 8;
2014               break;
2015
2016             case DW_FORM_udata:
2017               *uintp = _bfd_safe_read_leb128 (abfd, buf, &bytes_read, FALSE,
2018                                               buf_end);
2019               buf += bytes_read;
2020               break;
2021
2022             case DW_FORM_block:
2023               /* It is valid only for DW_LNCT_timestamp which is ignored by
2024                  current GDB.  */
2025               break;
2026             }
2027         }
2028
2029       if (!callback (table, fe.name, fe.dir, fe.time, fe.size))
2030         return FALSE;
2031     }
2032
2033   *bufp = buf;
2034   return TRUE;
2035 }
2036
2037 /* Decode the line number information for UNIT.  */
2038
2039 static struct line_info_table*
2040 decode_line_info (struct comp_unit *unit, struct dwarf2_debug *stash)
2041 {
2042   bfd *abfd = unit->abfd;
2043   struct line_info_table* table;
2044   bfd_byte *line_ptr;
2045   bfd_byte *line_end;
2046   struct line_head lh;
2047   unsigned int i, bytes_read, offset_size;
2048   char *cur_file, *cur_dir;
2049   unsigned char op_code, extended_op, adj_opcode;
2050   unsigned int exop_len;
2051   bfd_size_type amt;
2052
2053   if (! read_section (abfd, &stash->debug_sections[debug_line],
2054                       stash->syms, unit->line_offset,
2055                       &stash->dwarf_line_buffer, &stash->dwarf_line_size))
2056     return NULL;
2057
2058   amt = sizeof (struct line_info_table);
2059   table = (struct line_info_table *) bfd_alloc (abfd, amt);
2060   if (table == NULL)
2061     return NULL;
2062   table->abfd = abfd;
2063   table->comp_dir = unit->comp_dir;
2064
2065   table->num_files = 0;
2066   table->files = NULL;
2067
2068   table->num_dirs = 0;
2069   table->dirs = NULL;
2070
2071   table->num_sequences = 0;
2072   table->sequences = NULL;
2073
2074   table->lcl_head = NULL;
2075
2076   if (stash->dwarf_line_size < 16)
2077     {
2078       _bfd_error_handler
2079         (_("Dwarf Error: Line info section is too small (%Ld)"),
2080          stash->dwarf_line_size);
2081       bfd_set_error (bfd_error_bad_value);
2082       return NULL;
2083     }
2084   line_ptr = stash->dwarf_line_buffer + unit->line_offset;
2085   line_end = stash->dwarf_line_buffer + stash->dwarf_line_size;
2086
2087   /* Read in the prologue.  */
2088   lh.total_length = read_4_bytes (abfd, line_ptr, line_end);
2089   line_ptr += 4;
2090   offset_size = 4;
2091   if (lh.total_length == 0xffffffff)
2092     {
2093       lh.total_length = read_8_bytes (abfd, line_ptr, line_end);
2094       line_ptr += 8;
2095       offset_size = 8;
2096     }
2097   else if (lh.total_length == 0 && unit->addr_size == 8)
2098     {
2099       /* Handle (non-standard) 64-bit DWARF2 formats.  */
2100       lh.total_length = read_4_bytes (abfd, line_ptr, line_end);
2101       line_ptr += 4;
2102       offset_size = 8;
2103     }
2104
2105   if (lh.total_length > (size_t) (line_end - line_ptr))
2106     {
2107       _bfd_error_handler
2108         /* xgettext: c-format */
2109         (_("Dwarf Error: Line info data is bigger (%#Lx)"
2110            " than the space remaining in the section (%#lx)"),
2111          lh.total_length, (unsigned long) (line_end - line_ptr));
2112       bfd_set_error (bfd_error_bad_value);
2113       return NULL;
2114     }
2115
2116   line_end = line_ptr + lh.total_length;
2117
2118   lh.version = read_2_bytes (abfd, line_ptr, line_end);
2119   if (lh.version < 2 || lh.version > 5)
2120     {
2121       _bfd_error_handler
2122         (_("Dwarf Error: Unhandled .debug_line version %d."), lh.version);
2123       bfd_set_error (bfd_error_bad_value);
2124       return NULL;
2125     }
2126   line_ptr += 2;
2127
2128   if (line_ptr + offset_size + (lh.version >= 5 ? 8 : (lh.version >= 4 ? 6 : 5))
2129       >= line_end)
2130     {
2131       _bfd_error_handler
2132         (_("Dwarf Error: Ran out of room reading prologue"));
2133       bfd_set_error (bfd_error_bad_value);
2134       return NULL;
2135     }
2136
2137   if (lh.version >= 5)
2138     {
2139       unsigned int segment_selector_size;
2140
2141       /* Skip address size.  */
2142       read_1_byte (abfd, line_ptr, line_end);
2143       line_ptr += 1;
2144
2145       segment_selector_size = read_1_byte (abfd, line_ptr, line_end);
2146       line_ptr += 1;
2147       if (segment_selector_size != 0)
2148         {
2149           _bfd_error_handler
2150             (_("Dwarf Error: Line info unsupported segment selector size %u."),
2151              segment_selector_size);
2152           bfd_set_error (bfd_error_bad_value);
2153           return NULL;
2154         }
2155     }
2156
2157   if (offset_size == 4)
2158     lh.prologue_length = read_4_bytes (abfd, line_ptr, line_end);
2159   else
2160     lh.prologue_length = read_8_bytes (abfd, line_ptr, line_end);
2161   line_ptr += offset_size;
2162
2163   lh.minimum_instruction_length = read_1_byte (abfd, line_ptr, line_end);
2164   line_ptr += 1;
2165
2166   if (lh.version >= 4)
2167     {
2168       lh.maximum_ops_per_insn = read_1_byte (abfd, line_ptr, line_end);
2169       line_ptr += 1;
2170     }
2171   else
2172     lh.maximum_ops_per_insn = 1;
2173
2174   if (lh.maximum_ops_per_insn == 0)
2175     {
2176       _bfd_error_handler
2177         (_("Dwarf Error: Invalid maximum operations per instruction."));
2178       bfd_set_error (bfd_error_bad_value);
2179       return NULL;
2180     }
2181
2182   lh.default_is_stmt = read_1_byte (abfd, line_ptr, line_end);
2183   line_ptr += 1;
2184
2185   lh.line_base = read_1_signed_byte (abfd, line_ptr, line_end);
2186   line_ptr += 1;
2187
2188   lh.line_range = read_1_byte (abfd, line_ptr, line_end);
2189   line_ptr += 1;
2190
2191   lh.opcode_base = read_1_byte (abfd, line_ptr, line_end);
2192   line_ptr += 1;
2193
2194   if (line_ptr + (lh.opcode_base - 1) >= line_end)
2195     {
2196       _bfd_error_handler (_("Dwarf Error: Ran out of room reading opcodes"));
2197       bfd_set_error (bfd_error_bad_value);
2198       return NULL;
2199     }
2200
2201   amt = lh.opcode_base * sizeof (unsigned char);
2202   lh.standard_opcode_lengths = (unsigned char *) bfd_alloc (abfd, amt);
2203
2204   lh.standard_opcode_lengths[0] = 1;
2205
2206   for (i = 1; i < lh.opcode_base; ++i)
2207     {
2208       lh.standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr, line_end);
2209       line_ptr += 1;
2210     }
2211
2212   if (lh.version >= 5)
2213     {
2214       /* Read directory table.  */
2215       if (!read_formatted_entries (unit, &line_ptr, line_end, table,
2216                                    line_info_add_include_dir_stub))
2217         goto fail;
2218
2219       /* Read file name table.  */
2220       if (!read_formatted_entries (unit, &line_ptr, line_end, table,
2221                                    line_info_add_file_name))
2222         goto fail;
2223     }
2224   else
2225     {
2226       /* Read directory table.  */
2227       while ((cur_dir = read_string (abfd, line_ptr, line_end, &bytes_read)) != NULL)
2228         {
2229           line_ptr += bytes_read;
2230
2231           if (!line_info_add_include_dir (table, cur_dir))
2232             goto fail;
2233         }
2234
2235       line_ptr += bytes_read;
2236
2237       /* Read file name table.  */
2238       while ((cur_file = read_string (abfd, line_ptr, line_end, &bytes_read)) != NULL)
2239         {
2240           unsigned int dir, xtime, size;
2241
2242           line_ptr += bytes_read;
2243
2244           dir = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read, FALSE, line_end);
2245           line_ptr += bytes_read;
2246           xtime = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read, FALSE, line_end);
2247           line_ptr += bytes_read;
2248           size = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read, FALSE, line_end);
2249           line_ptr += bytes_read;
2250
2251           if (!line_info_add_file_name (table, cur_file, dir, xtime, size))
2252             goto fail;
2253         }
2254
2255       line_ptr += bytes_read;
2256     }
2257
2258   /* Read the statement sequences until there's nothing left.  */
2259   while (line_ptr < line_end)
2260     {
2261       /* State machine registers.  */
2262       bfd_vma address = 0;
2263       unsigned char op_index = 0;
2264       char * filename = table->num_files ? concat_filename (table, 1) : NULL;
2265       unsigned int line = 1;
2266       unsigned int column = 0;
2267       unsigned int discriminator = 0;
2268       int is_stmt = lh.default_is_stmt;
2269       int end_sequence = 0;
2270       unsigned int dir, xtime, size;
2271       /* eraxxon@alumni.rice.edu: Against the DWARF2 specs, some
2272          compilers generate address sequences that are wildly out of
2273          order using DW_LNE_set_address (e.g. Intel C++ 6.0 compiler
2274          for ia64-Linux).  Thus, to determine the low and high
2275          address, we must compare on every DW_LNS_copy, etc.  */
2276       bfd_vma low_pc  = (bfd_vma) -1;
2277       bfd_vma high_pc = 0;
2278
2279       /* Decode the table.  */
2280       while (!end_sequence && line_ptr < line_end)
2281         {
2282           op_code = read_1_byte (abfd, line_ptr, line_end);
2283           line_ptr += 1;
2284
2285           if (op_code >= lh.opcode_base)
2286             {
2287               /* Special operand.  */
2288               adj_opcode = op_code - lh.opcode_base;
2289               if (lh.line_range == 0)
2290                 goto line_fail;
2291               if (lh.maximum_ops_per_insn == 1)
2292                 address += (adj_opcode / lh.line_range
2293                             * lh.minimum_instruction_length);
2294               else
2295                 {
2296                   address += ((op_index + adj_opcode / lh.line_range)
2297                               / lh.maximum_ops_per_insn
2298                               * lh.minimum_instruction_length);
2299                   op_index = ((op_index + adj_opcode / lh.line_range)
2300                               % lh.maximum_ops_per_insn);
2301                 }
2302               line += lh.line_base + (adj_opcode % lh.line_range);
2303               /* Append row to matrix using current values.  */
2304               if (!add_line_info (table, address, op_index, filename,
2305                                   line, column, discriminator, 0))
2306                 goto line_fail;
2307               discriminator = 0;
2308               if (address < low_pc)
2309                 low_pc = address;
2310               if (address > high_pc)
2311                 high_pc = address;
2312             }
2313           else switch (op_code)
2314             {
2315             case DW_LNS_extended_op:
2316               exop_len = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2317                                                 FALSE, line_end);
2318               line_ptr += bytes_read;
2319               extended_op = read_1_byte (abfd, line_ptr, line_end);
2320               line_ptr += 1;
2321
2322               switch (extended_op)
2323                 {
2324                 case DW_LNE_end_sequence:
2325                   end_sequence = 1;
2326                   if (!add_line_info (table, address, op_index, filename, line,
2327                                       column, discriminator, end_sequence))
2328                     goto line_fail;
2329                   discriminator = 0;
2330                   if (address < low_pc)
2331                     low_pc = address;
2332                   if (address > high_pc)
2333                     high_pc = address;
2334                   if (!arange_add (unit, &unit->arange, low_pc, high_pc))
2335                     goto line_fail;
2336                   break;
2337                 case DW_LNE_set_address:
2338                   address = read_address (unit, line_ptr, line_end);
2339                   op_index = 0;
2340                   line_ptr += unit->addr_size;
2341                   break;
2342                 case DW_LNE_define_file:
2343                   cur_file = read_string (abfd, line_ptr, line_end, &bytes_read);
2344                   line_ptr += bytes_read;
2345                   dir = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2346                                                FALSE, line_end);
2347                   line_ptr += bytes_read;
2348                   xtime = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2349                                                  FALSE, line_end);
2350                   line_ptr += bytes_read;
2351                   size = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2352                                                 FALSE, line_end);
2353                   line_ptr += bytes_read;
2354                   if (!line_info_add_file_name (table, cur_file, dir,
2355                                                 xtime, size))
2356                     goto line_fail;
2357                   break;
2358                 case DW_LNE_set_discriminator:
2359                   discriminator =
2360                     _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2361                                            FALSE, line_end);
2362                   line_ptr += bytes_read;
2363                   break;
2364                 case DW_LNE_HP_source_file_correlation:
2365                   line_ptr += exop_len - 1;
2366                   break;
2367                 default:
2368                   _bfd_error_handler
2369                     (_("Dwarf Error: mangled line number section."));
2370                   bfd_set_error (bfd_error_bad_value);
2371                 line_fail:
2372                   if (filename != NULL)
2373                     free (filename);
2374                   goto fail;
2375                 }
2376               break;
2377             case DW_LNS_copy:
2378               if (!add_line_info (table, address, op_index,
2379                                   filename, line, column, discriminator, 0))
2380                 goto line_fail;
2381               discriminator = 0;
2382               if (address < low_pc)
2383                 low_pc = address;
2384               if (address > high_pc)
2385                 high_pc = address;
2386               break;
2387             case DW_LNS_advance_pc:
2388               if (lh.maximum_ops_per_insn == 1)
2389                 address += (lh.minimum_instruction_length
2390                             * _bfd_safe_read_leb128 (abfd, line_ptr,
2391                                                      &bytes_read,
2392                                                      FALSE, line_end));
2393               else
2394                 {
2395                   bfd_vma adjust = _bfd_safe_read_leb128 (abfd, line_ptr,
2396                                                           &bytes_read,
2397                                                           FALSE, line_end);
2398                   address = ((op_index + adjust) / lh.maximum_ops_per_insn
2399                              * lh.minimum_instruction_length);
2400                   op_index = (op_index + adjust) % lh.maximum_ops_per_insn;
2401                 }
2402               line_ptr += bytes_read;
2403               break;
2404             case DW_LNS_advance_line:
2405               line += _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2406                                              TRUE, line_end);
2407               line_ptr += bytes_read;
2408               break;
2409             case DW_LNS_set_file:
2410               {
2411                 unsigned int file;
2412
2413                 /* The file and directory tables are 0
2414                    based, the references are 1 based.  */
2415                 file = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2416                                               FALSE, line_end);
2417                 line_ptr += bytes_read;
2418                 if (filename)
2419                   free (filename);
2420                 filename = concat_filename (table, file);
2421                 break;
2422               }
2423             case DW_LNS_set_column:
2424               column = _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2425                                               FALSE, line_end);
2426               line_ptr += bytes_read;
2427               break;
2428             case DW_LNS_negate_stmt:
2429               is_stmt = (!is_stmt);
2430               break;
2431             case DW_LNS_set_basic_block:
2432               break;
2433             case DW_LNS_const_add_pc:
2434               if (lh.line_range == 0)
2435                 goto line_fail;
2436               if (lh.maximum_ops_per_insn == 1)
2437                 address += (lh.minimum_instruction_length
2438                             * ((255 - lh.opcode_base) / lh.line_range));
2439               else
2440                 {
2441                   bfd_vma adjust = ((255 - lh.opcode_base) / lh.line_range);
2442                   address += (lh.minimum_instruction_length
2443                               * ((op_index + adjust)
2444                                  / lh.maximum_ops_per_insn));
2445                   op_index = (op_index + adjust) % lh.maximum_ops_per_insn;
2446                 }
2447               break;
2448             case DW_LNS_fixed_advance_pc:
2449               address += read_2_bytes (abfd, line_ptr, line_end);
2450               op_index = 0;
2451               line_ptr += 2;
2452               break;
2453             default:
2454               /* Unknown standard opcode, ignore it.  */
2455               for (i = 0; i < lh.standard_opcode_lengths[op_code]; i++)
2456                 {
2457                   (void) _bfd_safe_read_leb128 (abfd, line_ptr, &bytes_read,
2458                                                 FALSE, line_end);
2459                   line_ptr += bytes_read;
2460                 }
2461               break;
2462             }
2463         }
2464
2465       if (filename)
2466         free (filename);
2467     }
2468
2469   if (sort_line_sequences (table))
2470     return table;
2471
2472  fail:
2473   while (table->sequences != NULL)
2474     {
2475       struct line_sequence* seq = table->sequences;
2476       table->sequences = table->sequences->prev_sequence;
2477       free (seq);
2478     }
2479   if (table->files != NULL)
2480     free (table->files);
2481   if (table->dirs != NULL)
2482     free (table->dirs);
2483   return NULL;
2484 }
2485
2486 /* If ADDR is within TABLE set the output parameters and return the
2487    range of addresses covered by the entry used to fill them out.
2488    Otherwise set * FILENAME_PTR to NULL and return 0.
2489    The parameters FILENAME_PTR, LINENUMBER_PTR and DISCRIMINATOR_PTR
2490    are pointers to the objects to be filled in.  */
2491
2492 static bfd_vma
2493 lookup_address_in_line_info_table (struct line_info_table *table,
2494                                    bfd_vma addr,
2495                                    const char **filename_ptr,
2496                                    unsigned int *linenumber_ptr,
2497                                    unsigned int *discriminator_ptr)
2498 {
2499   struct line_sequence *seq = NULL;
2500   struct line_info *info;
2501   int low, high, mid;
2502
2503   /* Binary search the array of sequences.  */
2504   low = 0;
2505   high = table->num_sequences;
2506   while (low < high)
2507     {
2508       mid = (low + high) / 2;
2509       seq = &table->sequences[mid];
2510       if (addr < seq->low_pc)
2511         high = mid;
2512       else if (addr >= seq->last_line->address)
2513         low = mid + 1;
2514       else
2515         break;
2516     }
2517
2518   /* Check for a valid sequence.  */
2519   if (!seq || addr < seq->low_pc || addr >= seq->last_line->address)
2520     goto fail;
2521
2522   if (!build_line_info_table (table, seq))
2523     goto fail;
2524
2525   /* Binary search the array of line information.  */
2526   low = 0;
2527   high = seq->num_lines;
2528   info = NULL;
2529   while (low < high)
2530     {
2531       mid = (low + high) / 2;
2532       info = seq->line_info_lookup[mid];
2533       if (addr < info->address)
2534         high = mid;
2535       else if (addr >= seq->line_info_lookup[mid + 1]->address)
2536         low = mid + 1;
2537       else
2538         break;
2539     }
2540
2541   /* Check for a valid line information entry.  */
2542   if (info
2543       && addr >= info->address
2544       && addr < seq->line_info_lookup[mid + 1]->address
2545       && !(info->end_sequence || info == seq->last_line))
2546     {
2547       *filename_ptr = info->filename;
2548       *linenumber_ptr = info->line;
2549       if (discriminator_ptr)
2550         *discriminator_ptr = info->discriminator;
2551       return seq->last_line->address - seq->low_pc;
2552     }
2553
2554 fail:
2555   *filename_ptr = NULL;
2556   return 0;
2557 }
2558
2559 /* Read in the .debug_ranges section for future reference.  */
2560
2561 static bfd_boolean
2562 read_debug_ranges (struct comp_unit * unit)
2563 {
2564   struct dwarf2_debug * stash = unit->stash;
2565
2566   return read_section (unit->abfd, &stash->debug_sections[debug_ranges],
2567                        stash->syms, 0,
2568                        &stash->dwarf_ranges_buffer,
2569                        &stash->dwarf_ranges_size);
2570 }
2571
2572 /* Function table functions.  */
2573
2574 static int
2575 compare_lookup_funcinfos (const void * a, const void * b)
2576 {
2577   const struct lookup_funcinfo * lookup1 = a;
2578   const struct lookup_funcinfo * lookup2 = b;
2579
2580   if (lookup1->low_addr < lookup2->low_addr)
2581     return -1;
2582   if (lookup1->low_addr > lookup2->low_addr)
2583     return 1;
2584   if (lookup1->high_addr < lookup2->high_addr)
2585     return -1;
2586   if (lookup1->high_addr > lookup2->high_addr)
2587     return 1;
2588
2589   return 0;
2590 }
2591
2592 static bfd_boolean
2593 build_lookup_funcinfo_table (struct comp_unit * unit)
2594 {
2595   struct lookup_funcinfo *lookup_funcinfo_table = unit->lookup_funcinfo_table;
2596   unsigned int number_of_functions = unit->number_of_functions;
2597   struct funcinfo *each;
2598   struct lookup_funcinfo *entry;
2599   size_t func_index;
2600   struct arange *range;
2601   bfd_vma low_addr, high_addr;
2602
2603   if (lookup_funcinfo_table || number_of_functions == 0)
2604     return TRUE;
2605
2606   /* Create the function info lookup table.  */
2607   lookup_funcinfo_table = (struct lookup_funcinfo *)
2608     bfd_malloc (number_of_functions * sizeof (struct lookup_funcinfo));
2609   if (lookup_funcinfo_table == NULL)
2610     return FALSE;
2611
2612   /* Populate the function info lookup table.  */
2613   func_index = number_of_functions;
2614   for (each = unit->function_table; each; each = each->prev_func)
2615     {
2616       entry = &lookup_funcinfo_table[--func_index];
2617       entry->funcinfo = each;
2618
2619       /* Calculate the lowest and highest address for this function entry.  */
2620       low_addr  = entry->funcinfo->arange.low;
2621       high_addr = entry->funcinfo->arange.high;
2622
2623       for (range = entry->funcinfo->arange.next; range; range = range->next)
2624         {
2625           if (range->low < low_addr)
2626             low_addr = range->low;
2627           if (range->high > high_addr)
2628             high_addr = range->high;
2629         }
2630
2631       entry->low_addr = low_addr;
2632       entry->high_addr = high_addr;
2633     }
2634
2635   BFD_ASSERT (func_index == 0);
2636
2637   /* Sort the function by address.  */
2638   qsort (lookup_funcinfo_table,
2639          number_of_functions,
2640          sizeof (struct lookup_funcinfo),
2641          compare_lookup_funcinfos);
2642
2643   /* Calculate the high watermark for each function in the lookup table.  */
2644   high_addr = lookup_funcinfo_table[0].high_addr;
2645   for (func_index = 1; func_index < number_of_functions; func_index++)
2646     {
2647       entry = &lookup_funcinfo_table[func_index];
2648       if (entry->high_addr > high_addr)
2649         high_addr = entry->high_addr;
2650       else
2651         entry->high_addr = high_addr;
2652     }
2653
2654   unit->lookup_funcinfo_table = lookup_funcinfo_table;
2655   return TRUE;
2656 }
2657
2658 /* If ADDR is within UNIT's function tables, set FUNCTION_PTR, and return
2659    TRUE.  Note that we need to find the function that has the smallest range
2660    that contains ADDR, to handle inlined functions without depending upon
2661    them being ordered in TABLE by increasing range.  */
2662
2663 static bfd_boolean
2664 lookup_address_in_function_table (struct comp_unit *unit,
2665                                   bfd_vma addr,
2666                                   struct funcinfo **function_ptr)
2667 {
2668   unsigned int number_of_functions = unit->number_of_functions;
2669   struct lookup_funcinfo* lookup_funcinfo = NULL;
2670   struct funcinfo* funcinfo = NULL;
2671   struct funcinfo* best_fit = NULL;
2672   bfd_vma best_fit_len = 0;
2673   bfd_size_type low, high, mid, first;
2674   struct arange *arange;
2675
2676   if (number_of_functions == 0)
2677     return FALSE;
2678
2679   if (!build_lookup_funcinfo_table (unit))
2680     return FALSE;
2681
2682   if (unit->lookup_funcinfo_table[number_of_functions - 1].high_addr < addr)
2683     return FALSE;
2684   
2685   /* Find the first function in the lookup table which may contain the
2686      specified address.  */
2687   low = 0;
2688   high = number_of_functions;
2689   first = high;
2690   while (low < high)
2691     {
2692       mid = (low + high) / 2;
2693       lookup_funcinfo = &unit->lookup_funcinfo_table[mid];
2694       if (addr < lookup_funcinfo->low_addr)
2695         high = mid;
2696       else if (addr >= lookup_funcinfo->high_addr)
2697         low = mid + 1;
2698       else
2699         high = first = mid;
2700     }
2701
2702   /* Find the 'best' match for the address.  The prior algorithm defined the
2703      best match as the function with the smallest address range containing
2704      the specified address.  This definition should probably be changed to the
2705      innermost inline routine containing the address, but right now we want
2706      to get the same results we did before.  */
2707   while (first < number_of_functions)
2708     {
2709       if (addr < unit->lookup_funcinfo_table[first].low_addr)
2710         break;
2711       funcinfo = unit->lookup_funcinfo_table[first].funcinfo;
2712
2713       for (arange = &funcinfo->arange; arange; arange = arange->next)
2714         {
2715           if (addr < arange->low || addr >= arange->high)
2716             continue;
2717
2718           if (!best_fit
2719               || arange->high - arange->low < best_fit_len
2720               /* The following comparison is designed to return the same
2721                  match as the previous algorithm for routines which have the
2722                  same best fit length.  */
2723               || (arange->high - arange->low == best_fit_len
2724                   && funcinfo > best_fit))
2725             {
2726               best_fit = funcinfo;
2727               best_fit_len = arange->high - arange->low;
2728             }
2729         }
2730
2731       first++;
2732     }
2733
2734   if (!best_fit)
2735     return FALSE;
2736
2737   *function_ptr = best_fit;
2738   return TRUE;
2739 }
2740
2741 /* If SYM at ADDR is within function table of UNIT, set FILENAME_PTR
2742    and LINENUMBER_PTR, and return TRUE.  */
2743
2744 static bfd_boolean
2745 lookup_symbol_in_function_table (struct comp_unit *unit,
2746                                  asymbol *sym,
2747                                  bfd_vma addr,
2748                                  const char **filename_ptr,
2749                                  unsigned int *linenumber_ptr)
2750 {
2751   struct funcinfo* each_func;
2752   struct funcinfo* best_fit = NULL;
2753   bfd_vma best_fit_len = 0;
2754   struct arange *arange;
2755   const char *name = bfd_asymbol_name (sym);
2756   asection *sec = bfd_get_section (sym);
2757
2758   for (each_func = unit->function_table;
2759        each_func;
2760        each_func = each_func->prev_func)
2761     {
2762       for (arange = &each_func->arange;
2763            arange;
2764            arange = arange->next)
2765         {
2766           if ((!each_func->sec || each_func->sec == sec)
2767               && addr >= arange->low
2768               && addr < arange->high
2769               && each_func->name
2770               && strcmp (name, each_func->name) == 0
2771               && (!best_fit
2772                   || arange->high - arange->low < best_fit_len))
2773             {
2774               best_fit = each_func;
2775               best_fit_len = arange->high - arange->low;
2776             }
2777         }
2778     }
2779
2780   if (best_fit)
2781     {
2782       best_fit->sec = sec;
2783       *filename_ptr = best_fit->file;
2784       *linenumber_ptr = best_fit->line;
2785       return TRUE;
2786     }
2787   else
2788     return FALSE;
2789 }
2790
2791 /* Variable table functions.  */
2792
2793 /* If SYM is within variable table of UNIT, set FILENAME_PTR and
2794    LINENUMBER_PTR, and return TRUE.  */
2795
2796 static bfd_boolean
2797 lookup_symbol_in_variable_table (struct comp_unit *unit,
2798                                  asymbol *sym,
2799                                  bfd_vma addr,
2800                                  const char **filename_ptr,
2801                                  unsigned int *linenumber_ptr)
2802 {
2803   const char *name = bfd_asymbol_name (sym);
2804   asection *sec = bfd_get_section (sym);
2805   struct varinfo* each;
2806
2807   for (each = unit->variable_table; each; each = each->prev_var)
2808     if (each->stack == 0
2809         && each->file != NULL
2810         && each->name != NULL
2811         && each->addr == addr
2812         && (!each->sec || each->sec == sec)
2813         && strcmp (name, each->name) == 0)
2814       break;
2815
2816   if (each)
2817     {
2818       each->sec = sec;
2819       *filename_ptr = each->file;
2820       *linenumber_ptr = each->line;
2821       return TRUE;
2822     }
2823
2824   return FALSE;
2825 }
2826
2827 static bfd_boolean
2828 find_abstract_instance_name (struct comp_unit *unit,
2829                              bfd_byte *orig_info_ptr,
2830                              struct attribute *attr_ptr,
2831                              const char **pname,
2832                              bfd_boolean *is_linkage)
2833 {
2834   bfd *abfd = unit->abfd;
2835   bfd_byte *info_ptr;
2836   bfd_byte *info_ptr_end;
2837   unsigned int abbrev_number, bytes_read, i;
2838   struct abbrev_info *abbrev;
2839   bfd_uint64_t die_ref = attr_ptr->u.val;
2840   struct attribute attr;
2841   const char *name = NULL;
2842
2843   /* DW_FORM_ref_addr can reference an entry in a different CU. It
2844      is an offset from the .debug_info section, not the current CU.  */
2845   if (attr_ptr->form == DW_FORM_ref_addr)
2846     {
2847       /* We only support DW_FORM_ref_addr within the same file, so
2848          any relocations should be resolved already.  Check this by
2849          testing for a zero die_ref;  There can't be a valid reference
2850          to the header of a .debug_info section.
2851          DW_FORM_ref_addr is an offset relative to .debug_info.
2852          Normally when using the GNU linker this is accomplished by
2853          emitting a symbolic reference to a label, because .debug_info
2854          sections are linked at zero.  When there are multiple section
2855          groups containing .debug_info, as there might be in a
2856          relocatable object file, it would be reasonable to assume that
2857          a symbolic reference to a label in any .debug_info section
2858          might be used.  Since we lay out multiple .debug_info
2859          sections at non-zero VMAs (see place_sections), and read
2860          them contiguously into stash->info_ptr_memory, that means
2861          the reference is relative to stash->info_ptr_memory.  */
2862       size_t total;
2863
2864       info_ptr = unit->stash->info_ptr_memory;
2865       info_ptr_end = unit->stash->info_ptr_end;
2866       total = info_ptr_end - info_ptr;
2867       if (!die_ref || die_ref >= total)
2868         {
2869           _bfd_error_handler
2870             (_("Dwarf Error: Invalid abstract instance DIE ref."));
2871           bfd_set_error (bfd_error_bad_value);
2872           return FALSE;
2873         }
2874       info_ptr += die_ref;
2875
2876       /* Now find the CU containing this pointer.  */
2877       if (info_ptr >= unit->info_ptr_unit && info_ptr < unit->end_ptr)
2878         info_ptr_end = unit->end_ptr;
2879       else
2880         {
2881           /* Check other CUs to see if they contain the abbrev.  */
2882           struct comp_unit * u;
2883
2884           for (u = unit->prev_unit; u != NULL; u = u->prev_unit)
2885             if (info_ptr >= u->info_ptr_unit && info_ptr < u->end_ptr)
2886               break;
2887
2888           if (u == NULL)
2889             for (u = unit->next_unit; u != NULL; u = u->next_unit)
2890               if (info_ptr >= u->info_ptr_unit && info_ptr < u->end_ptr)
2891                 break;
2892
2893           if (u)
2894             {
2895               unit = u;
2896               info_ptr_end = unit->end_ptr;
2897             }
2898           /* else FIXME: What do we do now ?  */
2899         }
2900     }
2901   else if (attr_ptr->form == DW_FORM_GNU_ref_alt)
2902     {
2903       info_ptr = read_alt_indirect_ref (unit, die_ref);
2904       if (info_ptr == NULL)
2905         {
2906           _bfd_error_handler
2907             (_("Dwarf Error: Unable to read alt ref %llu."),
2908              (long long) die_ref);
2909           bfd_set_error (bfd_error_bad_value);
2910           return FALSE;
2911         }
2912       info_ptr_end = (unit->stash->alt_dwarf_info_buffer
2913                       + unit->stash->alt_dwarf_info_size);
2914
2915       /* FIXME: Do we need to locate the correct CU, in a similar
2916          fashion to the code in the DW_FORM_ref_addr case above ?  */
2917     }
2918   else
2919     {
2920       /* DW_FORM_ref1, DW_FORM_ref2, DW_FORM_ref4, DW_FORM_ref8 or
2921          DW_FORM_ref_udata.  These are all references relative to the
2922          start of the current CU.  */
2923       size_t total;
2924
2925       info_ptr = unit->info_ptr_unit;
2926       info_ptr_end = unit->end_ptr;
2927       total = info_ptr_end - info_ptr;
2928       if (!die_ref || die_ref >= total)
2929         {
2930           _bfd_error_handler
2931             (_("Dwarf Error: Invalid abstract instance DIE ref."));
2932           bfd_set_error (bfd_error_bad_value);
2933           return FALSE;
2934         }
2935       info_ptr += die_ref;
2936     }
2937
2938   abbrev_number = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
2939                                          FALSE, info_ptr_end);
2940   info_ptr += bytes_read;
2941
2942   if (abbrev_number)
2943     {
2944       abbrev = lookup_abbrev (abbrev_number, unit->abbrevs);
2945       if (! abbrev)
2946         {
2947           _bfd_error_handler
2948             (_("Dwarf Error: Could not find abbrev number %u."), abbrev_number);
2949           bfd_set_error (bfd_error_bad_value);
2950           return FALSE;
2951         }
2952       else
2953         {
2954           for (i = 0; i < abbrev->num_attrs; ++i)
2955             {
2956               info_ptr = read_attribute (&attr, &abbrev->attrs[i], unit,
2957                                          info_ptr, info_ptr_end);
2958               if (info_ptr == NULL)
2959                 break;
2960               /* It doesn't ever make sense for DW_AT_specification to
2961                  refer to the same DIE.  Stop simple recursion.  */
2962               if (info_ptr == orig_info_ptr)
2963                 {
2964                   _bfd_error_handler
2965                     (_("Dwarf Error: Abstract instance recursion detected."));
2966                   bfd_set_error (bfd_error_bad_value);
2967                   return FALSE;
2968                 }
2969               switch (attr.name)
2970                 {
2971                 case DW_AT_name:
2972                   /* Prefer DW_AT_MIPS_linkage_name or DW_AT_linkage_name
2973                      over DW_AT_name.  */
2974                   if (name == NULL && is_str_attr (attr.form))
2975                     {
2976                       name = attr.u.str;
2977                       if (non_mangled (unit->lang))
2978                         *is_linkage = TRUE;
2979                     }
2980                   break;
2981                 case DW_AT_specification:
2982                   if (!find_abstract_instance_name (unit, info_ptr, &attr,
2983                                                     pname, is_linkage))
2984                     return FALSE;
2985                   break;
2986                 case DW_AT_linkage_name:
2987                 case DW_AT_MIPS_linkage_name:
2988                   /* PR 16949:  Corrupt debug info can place
2989                      non-string forms into these attributes.  */
2990                   if (is_str_attr (attr.form))
2991                     {
2992                       name = attr.u.str;
2993                       *is_linkage = TRUE;
2994                     }
2995                   break;
2996                 default:
2997                   break;
2998                 }
2999             }
3000         }
3001     }
3002   *pname = name;
3003   return TRUE;
3004 }
3005
3006 static bfd_boolean
3007 read_rangelist (struct comp_unit *unit, struct arange *arange,
3008                 bfd_uint64_t offset)
3009 {
3010   bfd_byte *ranges_ptr;
3011   bfd_byte *ranges_end;
3012   bfd_vma base_address = unit->base_address;
3013
3014   if (! unit->stash->dwarf_ranges_buffer)
3015     {
3016       if (! read_debug_ranges (unit))
3017         return FALSE;
3018     }
3019
3020   ranges_ptr = unit->stash->dwarf_ranges_buffer + offset;
3021   if (ranges_ptr < unit->stash->dwarf_ranges_buffer)
3022     return FALSE;
3023   ranges_end = unit->stash->dwarf_ranges_buffer + unit->stash->dwarf_ranges_size;
3024
3025   for (;;)
3026     {
3027       bfd_vma low_pc;
3028       bfd_vma high_pc;
3029
3030       /* PR 17512: file: 62cada7d.  */
3031       if (ranges_ptr + 2 * unit->addr_size > ranges_end)
3032         return FALSE;
3033
3034       low_pc = read_address (unit, ranges_ptr, ranges_end);
3035       ranges_ptr += unit->addr_size;
3036       high_pc = read_address (unit, ranges_ptr, ranges_end);
3037       ranges_ptr += unit->addr_size;
3038
3039       if (low_pc == 0 && high_pc == 0)
3040         break;
3041       if (low_pc == -1UL && high_pc != -1UL)
3042         base_address = high_pc;
3043       else
3044         {
3045           if (!arange_add (unit, arange,
3046                            base_address + low_pc, base_address + high_pc))
3047             return FALSE;
3048         }
3049     }
3050   return TRUE;
3051 }
3052
3053 /* DWARF2 Compilation unit functions.  */
3054
3055 /* Scan over each die in a comp. unit looking for functions to add
3056    to the function table and variables to the variable table.  */
3057
3058 static bfd_boolean
3059 scan_unit_for_symbols (struct comp_unit *unit)
3060 {
3061   bfd *abfd = unit->abfd;
3062   bfd_byte *info_ptr = unit->first_child_die_ptr;
3063   bfd_byte *info_ptr_end = unit->stash->info_ptr_end;
3064   int nesting_level = 0;
3065   struct nest_funcinfo {
3066     struct funcinfo *func;
3067   } *nested_funcs;
3068   int nested_funcs_size;
3069
3070   /* Maintain a stack of in-scope functions and inlined functions, which we
3071      can use to set the caller_func field.  */
3072   nested_funcs_size = 32;
3073   nested_funcs = (struct nest_funcinfo *)
3074     bfd_malloc (nested_funcs_size * sizeof (*nested_funcs));
3075   if (nested_funcs == NULL)
3076     return FALSE;
3077   nested_funcs[nesting_level].func = 0;
3078
3079   while (nesting_level >= 0)
3080     {
3081       unsigned int abbrev_number, bytes_read, i;
3082       struct abbrev_info *abbrev;
3083       struct attribute attr;
3084       struct funcinfo *func;
3085       struct varinfo *var;
3086       bfd_vma low_pc = 0;
3087       bfd_vma high_pc = 0;
3088       bfd_boolean high_pc_relative = FALSE;
3089
3090       /* PR 17512: file: 9f405d9d.  */
3091       if (info_ptr >= info_ptr_end)
3092         goto fail;
3093
3094       abbrev_number = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
3095                                              FALSE, info_ptr_end);
3096       info_ptr += bytes_read;
3097
3098       if (! abbrev_number)
3099         {
3100           nesting_level--;
3101           continue;
3102         }
3103
3104       abbrev = lookup_abbrev (abbrev_number, unit->abbrevs);
3105       if (! abbrev)
3106         {
3107           static unsigned int previous_failed_abbrev = -1U;
3108
3109           /* Avoid multiple reports of the same missing abbrev.  */
3110           if (abbrev_number != previous_failed_abbrev)
3111             {
3112               _bfd_error_handler
3113                 (_("Dwarf Error: Could not find abbrev number %u."),
3114                  abbrev_number);
3115               previous_failed_abbrev = abbrev_number;
3116             }
3117           bfd_set_error (bfd_error_bad_value);
3118           goto fail;
3119         }
3120
3121       var = NULL;
3122       if (abbrev->tag == DW_TAG_subprogram
3123           || abbrev->tag == DW_TAG_entry_point
3124           || abbrev->tag == DW_TAG_inlined_subroutine)
3125         {
3126           bfd_size_type amt = sizeof (struct funcinfo);
3127           func = (struct funcinfo *) bfd_zalloc (abfd, amt);
3128           if (func == NULL)
3129             goto fail;
3130           func->tag = abbrev->tag;
3131           func->prev_func = unit->function_table;
3132           unit->function_table = func;
3133           unit->number_of_functions++;
3134           BFD_ASSERT (!unit->cached);
3135
3136           if (func->tag == DW_TAG_inlined_subroutine)
3137             for (i = nesting_level; i-- != 0; )
3138               if (nested_funcs[i].func)
3139                 {
3140                   func->caller_func = nested_funcs[i].func;
3141                   break;
3142                 }
3143           nested_funcs[nesting_level].func = func;
3144         }
3145       else
3146         {
3147           func = NULL;
3148           if (abbrev->tag == DW_TAG_variable)
3149             {
3150               bfd_size_type amt = sizeof (struct varinfo);
3151               var = (struct varinfo *) bfd_zalloc (abfd, amt);
3152               if (var == NULL)
3153                 goto fail;
3154               var->tag = abbrev->tag;
3155               var->stack = 1;
3156               var->prev_var = unit->variable_table;
3157               unit->variable_table = var;
3158               /* PR 18205: Missing debug information can cause this
3159                  var to be attached to an already cached unit.  */
3160             }
3161
3162           /* No inline function in scope at this nesting level.  */
3163           nested_funcs[nesting_level].func = 0;
3164         }
3165
3166       for (i = 0; i < abbrev->num_attrs; ++i)
3167         {
3168           info_ptr = read_attribute (&attr, &abbrev->attrs[i],
3169                                      unit, info_ptr, info_ptr_end);
3170           if (info_ptr == NULL)
3171             goto fail;
3172
3173           if (func)
3174             {
3175               switch (attr.name)
3176                 {
3177                 case DW_AT_call_file:
3178                   func->caller_file = concat_filename (unit->line_table,
3179                                                        attr.u.val);
3180                   break;
3181
3182                 case DW_AT_call_line:
3183                   func->caller_line = attr.u.val;
3184                   break;
3185
3186                 case DW_AT_abstract_origin:
3187                 case DW_AT_specification:
3188                   if (!find_abstract_instance_name (unit, info_ptr, &attr,
3189                                                     &func->name,
3190                                                     &func->is_linkage))
3191                     goto fail;
3192                   break;
3193
3194                 case DW_AT_name:
3195                   /* Prefer DW_AT_MIPS_linkage_name or DW_AT_linkage_name
3196                      over DW_AT_name.  */
3197                   if (func->name == NULL && is_str_attr (attr.form))
3198                     {
3199                       func->name = attr.u.str;
3200                       if (non_mangled (unit->lang))
3201                         func->is_linkage = TRUE;
3202                     }
3203                   break;
3204
3205                 case DW_AT_linkage_name:
3206                 case DW_AT_MIPS_linkage_name:
3207                   /* PR 16949:  Corrupt debug info can place
3208                      non-string forms into these attributes.  */
3209                   if (is_str_attr (attr.form))
3210                     {
3211                       func->name = attr.u.str;
3212                       func->is_linkage = TRUE;
3213                     }
3214                   break;
3215
3216                 case DW_AT_low_pc:
3217                   low_pc = attr.u.val;
3218                   break;
3219
3220                 case DW_AT_high_pc:
3221                   high_pc = attr.u.val;
3222                   high_pc_relative = attr.form != DW_FORM_addr;
3223                   break;
3224
3225                 case DW_AT_ranges:
3226                   if (!read_rangelist (unit, &func->arange, attr.u.val))
3227                     goto fail;
3228                   break;
3229
3230                 case DW_AT_decl_file:
3231                   func->file = concat_filename (unit->line_table,
3232                                                 attr.u.val);
3233                   break;
3234
3235                 case DW_AT_decl_line:
3236                   func->line = attr.u.val;
3237                   break;
3238
3239                 default:
3240                   break;
3241                 }
3242             }
3243           else if (var)
3244             {
3245               switch (attr.name)
3246                 {
3247                 case DW_AT_name:
3248                   if (is_str_attr (attr.form))
3249                     var->name = attr.u.str;
3250                   break;
3251
3252                 case DW_AT_decl_file:
3253                   var->file = concat_filename (unit->line_table,
3254                                                attr.u.val);
3255                   break;
3256
3257                 case DW_AT_decl_line:
3258                   var->line = attr.u.val;
3259                   break;
3260
3261                 case DW_AT_external:
3262                   if (attr.u.val != 0)
3263                     var->stack = 0;
3264                   break;
3265
3266                 case DW_AT_location:
3267                   switch (attr.form)
3268                     {
3269                     case DW_FORM_block:
3270                     case DW_FORM_block1:
3271                     case DW_FORM_block2:
3272                     case DW_FORM_block4:
3273                     case DW_FORM_exprloc:
3274                       if (attr.u.blk->data != NULL
3275                           && *attr.u.blk->data == DW_OP_addr)
3276                         {
3277                           var->stack = 0;
3278
3279                           /* Verify that DW_OP_addr is the only opcode in the
3280                              location, in which case the block size will be 1
3281                              plus the address size.  */
3282                           /* ??? For TLS variables, gcc can emit
3283                              DW_OP_addr <addr> DW_OP_GNU_push_tls_address
3284                              which we don't handle here yet.  */
3285                           if (attr.u.blk->size == unit->addr_size + 1U)
3286                             var->addr = bfd_get (unit->addr_size * 8,
3287                                                  unit->abfd,
3288                                                  attr.u.blk->data + 1);
3289                         }
3290                       break;
3291
3292                     default:
3293                       break;
3294                     }
3295                   break;
3296
3297                 default:
3298                   break;
3299                 }
3300             }
3301         }
3302
3303       if (high_pc_relative)
3304         high_pc += low_pc;
3305
3306       if (func && high_pc != 0)
3307         {
3308           if (!arange_add (unit, &func->arange, low_pc, high_pc))
3309             goto fail;
3310         }
3311
3312       if (abbrev->has_children)
3313         {
3314           nesting_level++;
3315
3316           if (nesting_level >= nested_funcs_size)
3317             {
3318               struct nest_funcinfo *tmp;
3319
3320               nested_funcs_size *= 2;
3321               tmp = (struct nest_funcinfo *)
3322                 bfd_realloc (nested_funcs,
3323                              nested_funcs_size * sizeof (*nested_funcs));
3324               if (tmp == NULL)
3325                 goto fail;
3326               nested_funcs = tmp;
3327             }
3328           nested_funcs[nesting_level].func = 0;
3329         }
3330     }
3331
3332   free (nested_funcs);
3333   return TRUE;
3334
3335  fail:
3336   free (nested_funcs);
3337   return FALSE;
3338 }
3339
3340 /* Parse a DWARF2 compilation unit starting at INFO_PTR.  This
3341    includes the compilation unit header that proceeds the DIE's, but
3342    does not include the length field that precedes each compilation
3343    unit header.  END_PTR points one past the end of this comp unit.
3344    OFFSET_SIZE is the size of DWARF2 offsets (either 4 or 8 bytes).
3345
3346    This routine does not read the whole compilation unit; only enough
3347    to get to the line number information for the compilation unit.  */
3348
3349 static struct comp_unit *
3350 parse_comp_unit (struct dwarf2_debug *stash,
3351                  bfd_vma unit_length,
3352                  bfd_byte *info_ptr_unit,
3353                  unsigned int offset_size)
3354 {
3355   struct comp_unit* unit;
3356   unsigned int version;
3357   bfd_uint64_t abbrev_offset = 0;
3358   /* Initialize it just to avoid a GCC false warning.  */
3359   unsigned int addr_size = -1;
3360   struct abbrev_info** abbrevs;
3361   unsigned int abbrev_number, bytes_read, i;
3362   struct abbrev_info *abbrev;
3363   struct attribute attr;
3364   bfd_byte *info_ptr = stash->info_ptr;
3365   bfd_byte *end_ptr = info_ptr + unit_length;
3366   bfd_size_type amt;
3367   bfd_vma low_pc = 0;
3368   bfd_vma high_pc = 0;
3369   bfd *abfd = stash->bfd_ptr;
3370   bfd_boolean high_pc_relative = FALSE;
3371   enum dwarf_unit_type unit_type;
3372
3373   version = read_2_bytes (abfd, info_ptr, end_ptr);
3374   info_ptr += 2;
3375   if (version < 2 || version > 5)
3376     {
3377       /* PR 19872: A version number of 0 probably means that there is padding
3378          at the end of the .debug_info section.  Gold puts it there when
3379          performing an incremental link, for example.  So do not generate
3380          an error, just return a NULL.  */
3381       if (version)
3382         {
3383           _bfd_error_handler
3384             (_("Dwarf Error: found dwarf version '%u', this reader"
3385                " only handles version 2, 3, 4 and 5 information."), version);
3386           bfd_set_error (bfd_error_bad_value);
3387         }
3388       return NULL;
3389     }
3390
3391   if (version < 5)
3392     unit_type = DW_UT_compile;
3393   else
3394     {
3395       unit_type = read_1_byte (abfd, info_ptr, end_ptr);
3396       info_ptr += 1;
3397
3398       addr_size = read_1_byte (abfd, info_ptr, end_ptr);
3399       info_ptr += 1;
3400     }
3401
3402   BFD_ASSERT (offset_size == 4 || offset_size == 8);
3403   if (offset_size == 4)
3404     abbrev_offset = read_4_bytes (abfd, info_ptr, end_ptr);
3405   else
3406     abbrev_offset = read_8_bytes (abfd, info_ptr, end_ptr);
3407   info_ptr += offset_size;
3408
3409   if (version < 5)
3410     {
3411       addr_size = read_1_byte (abfd, info_ptr, end_ptr);
3412       info_ptr += 1;
3413     }
3414
3415   if (unit_type == DW_UT_type)
3416     {
3417       /* Skip type signature.  */
3418       info_ptr += 8;
3419
3420       /* Skip type offset.  */
3421       info_ptr += offset_size;
3422     }
3423
3424   if (addr_size > sizeof (bfd_vma))
3425     {
3426       _bfd_error_handler
3427         /* xgettext: c-format */
3428         (_("Dwarf Error: found address size '%u', this reader"
3429            " can not handle sizes greater than '%u'."),
3430          addr_size,
3431          (unsigned int) sizeof (bfd_vma));
3432       bfd_set_error (bfd_error_bad_value);
3433       return NULL;
3434     }
3435
3436   if (addr_size != 2 && addr_size != 4 && addr_size != 8)
3437     {
3438       _bfd_error_handler
3439         ("Dwarf Error: found address size '%u', this reader"
3440          " can only handle address sizes '2', '4' and '8'.", addr_size);
3441       bfd_set_error (bfd_error_bad_value);
3442       return NULL;
3443     }
3444
3445   /* Read the abbrevs for this compilation unit into a table.  */
3446   abbrevs = read_abbrevs (abfd, abbrev_offset, stash);
3447   if (! abbrevs)
3448     return NULL;
3449
3450   abbrev_number = _bfd_safe_read_leb128 (abfd, info_ptr, &bytes_read,
3451                                          FALSE, end_ptr);
3452   info_ptr += bytes_read;
3453   if (! abbrev_number)
3454     {
3455       /* PR 19872: An abbrev number of 0 probably means that there is padding
3456          at the end of the .debug_abbrev section.  Gold puts it there when
3457          performing an incremental link, for example.  So do not generate
3458          an error, just return a NULL.  */
3459       return NULL;
3460     }
3461
3462   abbrev = lookup_abbrev (abbrev_number, abbrevs);
3463   if (! abbrev)
3464     {
3465       _bfd_error_handler (_("Dwarf Error: Could not find abbrev number %u."),
3466                           abbrev_number);
3467       bfd_set_error (bfd_error_bad_value);
3468       return NULL;
3469     }
3470
3471   amt = sizeof (struct comp_unit);
3472   unit = (struct comp_unit *) bfd_zalloc (abfd, amt);
3473   if (unit == NULL)
3474     return NULL;
3475   unit->abfd = abfd;
3476   unit->version = version;
3477   unit->addr_size = addr_size;
3478   unit->offset_size = offset_size;
3479   unit->abbrevs = abbrevs;
3480   unit->end_ptr = end_ptr;
3481   unit->stash = stash;
3482   unit->info_ptr_unit = info_ptr_unit;
3483
3484   for (i = 0; i < abbrev->num_attrs; ++i)
3485     {
3486       info_ptr = read_attribute (&attr, &abbrev->attrs[i], unit, info_ptr, end_ptr);
3487       if (info_ptr == NULL)
3488         return NULL;
3489
3490       /* Store the data if it is of an attribute we want to keep in a
3491          partial symbol table.  */
3492       switch (attr.name)
3493         {
3494         case DW_AT_stmt_list:
3495           unit->stmtlist = 1;
3496           unit->line_offset = attr.u.val;
3497           break;
3498
3499         case DW_AT_name:
3500           if (is_str_attr (attr.form))
3501             unit->name = attr.u.str;
3502           break;
3503
3504         case DW_AT_low_pc:
3505           low_pc = attr.u.val;
3506           /* If the compilation unit DIE has a DW_AT_low_pc attribute,
3507              this is the base address to use when reading location
3508              lists or range lists.  */
3509           if (abbrev->tag == DW_TAG_compile_unit)
3510             unit->base_address = low_pc;
3511           break;
3512
3513         case DW_AT_high_pc:
3514           high_pc = attr.u.val;
3515           high_pc_relative = attr.form != DW_FORM_addr;
3516           break;
3517
3518         case DW_AT_ranges:
3519           if (!read_rangelist (unit, &unit->arange, attr.u.val))
3520             return NULL;
3521           break;
3522
3523         case DW_AT_comp_dir:
3524           {
3525             char *comp_dir = attr.u.str;
3526
3527             /* PR 17512: file: 1fe726be.  */
3528             if (! is_str_attr (attr.form))
3529               {
3530                 _bfd_error_handler
3531                   (_("Dwarf Error: DW_AT_comp_dir attribute encountered with a non-string form."));
3532                 comp_dir = NULL;
3533               }
3534
3535             if (comp_dir)
3536               {
3537                 /* Irix 6.2 native cc prepends <machine>.: to the compilation
3538                    directory, get rid of it.  */
3539                 char *cp = strchr (comp_dir, ':');
3540
3541                 if (cp && cp != comp_dir && cp[-1] == '.' && cp[1] == '/')
3542                   comp_dir = cp + 1;
3543               }
3544             unit->comp_dir = comp_dir;
3545             break;
3546           }
3547
3548         case DW_AT_language:
3549           unit->lang = attr.u.val;
3550           break;
3551
3552         default:
3553           break;
3554         }
3555     }
3556   if (high_pc_relative)
3557     high_pc += low_pc;
3558   if (high_pc != 0)
3559     {
3560       if (!arange_add (unit, &unit->arange, low_pc, high_pc))
3561         return NULL;
3562     }
3563
3564   unit->first_child_die_ptr = info_ptr;
3565   return unit;
3566 }
3567
3568 /* Return TRUE if UNIT may contain the address given by ADDR.  When
3569    there are functions written entirely with inline asm statements, the
3570    range info in the compilation unit header may not be correct.  We
3571    need to consult the line info table to see if a compilation unit
3572    really contains the given address.  */
3573
3574 static bfd_boolean
3575 comp_unit_contains_address (struct comp_unit *unit, bfd_vma addr)
3576 {
3577   struct arange *arange;
3578
3579   if (unit->error)
3580     return FALSE;
3581
3582   arange = &unit->arange;
3583   do
3584     {
3585       if (addr >= arange->low && addr < arange->high)
3586         return TRUE;
3587       arange = arange->next;
3588     }
3589   while (arange);
3590
3591   return FALSE;
3592 }
3593
3594 /* If UNIT contains ADDR, set the output parameters to the values for
3595    the line containing ADDR.  The output parameters, FILENAME_PTR,
3596    FUNCTION_PTR, and LINENUMBER_PTR, are pointers to the objects
3597    to be filled in.
3598
3599    Returns the range of addresses covered by the entry that was used
3600    to fill in *LINENUMBER_PTR or 0 if it was not filled in.  */
3601
3602 static bfd_vma
3603 comp_unit_find_nearest_line (struct comp_unit *unit,
3604                              bfd_vma addr,
3605                              const char **filename_ptr,
3606                              struct funcinfo **function_ptr,
3607                              unsigned int *linenumber_ptr,
3608                              unsigned int *discriminator_ptr,
3609                              struct dwarf2_debug *stash)
3610 {
3611   bfd_boolean func_p;
3612
3613   if (unit->error)
3614     return FALSE;
3615
3616   if (! unit->line_table)
3617     {
3618       if (! unit->stmtlist)
3619         {
3620           unit->error = 1;
3621           return FALSE;
3622         }
3623
3624       unit->line_table = decode_line_info (unit, stash);
3625
3626       if (! unit->line_table)
3627         {
3628           unit->error = 1;
3629           return FALSE;
3630         }
3631
3632       if (unit->first_child_die_ptr < unit->end_ptr
3633           && ! scan_unit_for_symbols (unit))
3634         {
3635           unit->error = 1;
3636           return FALSE;
3637         }
3638     }
3639
3640   *function_ptr = NULL;
3641   func_p = lookup_address_in_function_table (unit, addr, function_ptr);
3642   if (func_p && (*function_ptr)->tag == DW_TAG_inlined_subroutine)
3643     stash->inliner_chain = *function_ptr;
3644
3645   return lookup_address_in_line_info_table (unit->line_table, addr,
3646                                             filename_ptr,
3647                                             linenumber_ptr,
3648                                             discriminator_ptr);
3649 }
3650
3651 /* Check to see if line info is already decoded in a comp_unit.
3652    If not, decode it.  Returns TRUE if no errors were encountered;
3653    FALSE otherwise.  */
3654
3655 static bfd_boolean
3656 comp_unit_maybe_decode_line_info (struct comp_unit *unit,
3657                                   struct dwarf2_debug *stash)
3658 {
3659   if (unit->error)
3660     return FALSE;
3661
3662   if (! unit->line_table)
3663     {
3664       if (! unit->stmtlist)
3665         {
3666           unit->error = 1;
3667           return FALSE;
3668         }
3669
3670       unit->line_table = decode_line_info (unit, stash);
3671
3672       if (! unit->line_table)
3673         {
3674           unit->error = 1;
3675           return FALSE;
3676         }
3677
3678       if (unit->first_child_die_ptr < unit->end_ptr
3679           && ! scan_unit_for_symbols (unit))
3680         {
3681           unit->error = 1;
3682           return FALSE;
3683         }
3684     }
3685
3686   return TRUE;
3687 }
3688
3689 /* If UNIT contains SYM at ADDR, set the output parameters to the
3690    values for the line containing SYM.  The output parameters,
3691    FILENAME_PTR, and LINENUMBER_PTR, are pointers to the objects to be
3692    filled in.
3693
3694    Return TRUE if UNIT contains SYM, and no errors were encountered;
3695    FALSE otherwise.  */
3696
3697 static bfd_boolean
3698 comp_unit_find_line (struct comp_unit *unit,
3699                      asymbol *sym,
3700                      bfd_vma addr,
3701                      const char **filename_ptr,
3702                      unsigned int *linenumber_ptr,
3703                      struct dwarf2_debug *stash)
3704 {
3705   if (!comp_unit_maybe_decode_line_info (unit, stash))
3706     return FALSE;
3707
3708   if (sym->flags & BSF_FUNCTION)
3709     return lookup_symbol_in_function_table (unit, sym, addr,
3710                                             filename_ptr,
3711                                             linenumber_ptr);
3712
3713   return lookup_symbol_in_variable_table (unit, sym, addr,
3714                                           filename_ptr,
3715                                           linenumber_ptr);
3716 }
3717
3718 static struct funcinfo *
3719 reverse_funcinfo_list (struct funcinfo *head)
3720 {
3721   struct funcinfo *rhead;
3722   struct funcinfo *temp;
3723
3724   for (rhead = NULL; head; head = temp)
3725     {
3726       temp = head->prev_func;
3727       head->prev_func = rhead;
3728       rhead = head;
3729     }
3730   return rhead;
3731 }
3732
3733 static struct varinfo *
3734 reverse_varinfo_list (struct varinfo *head)
3735 {
3736   struct varinfo *rhead;
3737   struct varinfo *temp;
3738
3739   for (rhead = NULL; head; head = temp)
3740     {
3741       temp = head->prev_var;
3742       head->prev_var = rhead;
3743       rhead = head;
3744     }
3745   return rhead;
3746 }
3747
3748 /* Extract all interesting funcinfos and varinfos of a compilation
3749    unit into hash tables for faster lookup.  Returns TRUE if no
3750    errors were enountered; FALSE otherwise.  */
3751
3752 static bfd_boolean
3753 comp_unit_hash_info (struct dwarf2_debug *stash,
3754                      struct comp_unit *unit,
3755                      struct info_hash_table *funcinfo_hash_table,
3756                      struct info_hash_table *varinfo_hash_table)
3757 {
3758   struct funcinfo* each_func;
3759   struct varinfo* each_var;
3760   bfd_boolean okay = TRUE;
3761
3762   BFD_ASSERT (stash->info_hash_status != STASH_INFO_HASH_DISABLED);
3763
3764   if (!comp_unit_maybe_decode_line_info (unit, stash))
3765     return FALSE;
3766
3767   BFD_ASSERT (!unit->cached);
3768
3769   /* To preserve the original search order, we went to visit the function
3770      infos in the reversed order of the list.  However, making the list
3771      bi-directional use quite a bit of extra memory.  So we reverse
3772      the list first, traverse the list in the now reversed order and
3773      finally reverse the list again to get back the original order.  */
3774   unit->function_table = reverse_funcinfo_list (unit->function_table);
3775   for (each_func = unit->function_table;
3776        each_func && okay;
3777        each_func = each_func->prev_func)
3778     {
3779       /* Skip nameless functions.  */
3780       if (each_func->name)
3781         /* There is no need to copy name string into hash table as
3782            name string is either in the dwarf string buffer or
3783            info in the stash.  */
3784         okay = insert_info_hash_table (funcinfo_hash_table, each_func->name,
3785                                        (void*) each_func, FALSE);
3786     }
3787   unit->function_table = reverse_funcinfo_list (unit->function_table);
3788   if (!okay)
3789     return FALSE;
3790
3791   /* We do the same for variable infos.  */
3792   unit->variable_table = reverse_varinfo_list (unit->variable_table);
3793   for (each_var = unit->variable_table;
3794        each_var && okay;
3795        each_var = each_var->prev_var)
3796     {
3797       /* Skip stack vars and vars with no files or names.  */
3798       if (each_var->stack == 0
3799           && each_var->file != NULL
3800           && each_var->name != NULL)
3801         /* There is no need to copy name string into hash table as
3802            name string is either in the dwarf string buffer or
3803            info in the stash.  */
3804         okay = insert_info_hash_table (varinfo_hash_table, each_var->name,
3805                                        (void*) each_var, FALSE);
3806     }
3807
3808   unit->variable_table = reverse_varinfo_list (unit->variable_table);
3809   unit->cached = TRUE;
3810   return okay;
3811 }
3812
3813 /* Locate a section in a BFD containing debugging info.  The search starts
3814    from the section after AFTER_SEC, or from the first section in the BFD if
3815    AFTER_SEC is NULL.  The search works by examining the names of the
3816    sections.  There are three permissiable names.  The first two are given
3817    by DEBUG_SECTIONS[debug_info] (whose standard DWARF2 names are .debug_info
3818    and .zdebug_info).  The third is a prefix .gnu.linkonce.wi.
3819    This is a variation on the .debug_info section which has a checksum
3820    describing the contents appended onto the name.  This allows the linker to
3821    identify and discard duplicate debugging sections for different
3822    compilation units.  */
3823 #define GNU_LINKONCE_INFO ".gnu.linkonce.wi."
3824
3825 static asection *
3826 find_debug_info (bfd *abfd, const struct dwarf_debug_section *debug_sections,
3827                  asection *after_sec)
3828 {
3829   asection *msec;
3830   const char *look;
3831
3832   if (after_sec == NULL)
3833     {
3834       look = debug_sections[debug_info].uncompressed_name;
3835       msec = bfd_get_section_by_name (abfd, look);
3836       if (msec != NULL)
3837         return msec;
3838
3839       look = debug_sections[debug_info].compressed_name;
3840       if (look != NULL)
3841         {
3842           msec = bfd_get_section_by_name (abfd, look);
3843           if (msec != NULL)
3844             return msec;
3845         }
3846
3847       for (msec = abfd->sections; msec != NULL; msec = msec->next)
3848         if (CONST_STRNEQ (msec->name, GNU_LINKONCE_INFO))
3849           return msec;
3850
3851       return NULL;
3852     }
3853
3854   for (msec = after_sec->next; msec != NULL; msec = msec->next)
3855     {
3856       look = debug_sections[debug_info].uncompressed_name;
3857       if (strcmp (msec->name, look) == 0)
3858         return msec;
3859
3860       look = debug_sections[debug_info].compressed_name;
3861       if (look != NULL && strcmp (msec->name, look) == 0)
3862         return msec;
3863
3864       if (CONST_STRNEQ (msec->name, GNU_LINKONCE_INFO))
3865         return msec;
3866     }
3867
3868   return NULL;
3869 }
3870
3871 /* Transfer VMAs from object file to separate debug file.  */
3872
3873 static void
3874 set_debug_vma (bfd *orig_bfd, bfd *debug_bfd)
3875 {
3876   asection *s, *d;
3877
3878   for (s = orig_bfd->sections, d = debug_bfd->sections;
3879        s != NULL && d != NULL;
3880        s = s->next, d = d->next)
3881     {
3882       if ((d->flags & SEC_DEBUGGING) != 0)
3883         break;
3884       /* ??? Assumes 1-1 correspondence between sections in the
3885          two files.  */
3886       if (strcmp (s->name, d->name) == 0)
3887         {
3888           d->output_section = s->output_section;
3889           d->output_offset = s->output_offset;
3890           d->vma = s->vma;
3891         }
3892     }
3893 }
3894
3895 /* Unset vmas for adjusted sections in STASH.  */
3896
3897 static void
3898 unset_sections (struct dwarf2_debug *stash)
3899 {
3900   int i;
3901   struct adjusted_section *p;
3902
3903   i = stash->adjusted_section_count;
3904   p = stash->adjusted_sections;
3905   for (; i > 0; i--, p++)
3906     p->section->vma = 0;
3907 }
3908
3909 /* Set VMAs for allocated and .debug_info sections in ORIG_BFD, a
3910    relocatable object file.  VMAs are normally all zero in relocatable
3911    object files, so if we want to distinguish locations in sections by
3912    address we need to set VMAs so the sections do not overlap.  We
3913    also set VMA on .debug_info so that when we have multiple
3914    .debug_info sections (or the linkonce variant) they also do not
3915    overlap.  The multiple .debug_info sections make up a single
3916    logical section.  ??? We should probably do the same for other
3917    debug sections.  */
3918
3919 static bfd_boolean
3920 place_sections (bfd *orig_bfd, struct dwarf2_debug *stash)
3921 {
3922   bfd *abfd;
3923   struct adjusted_section *p;
3924   int i;
3925   const char *debug_info_name;
3926
3927   if (stash->adjusted_section_count != 0)
3928     {
3929       i = stash->adjusted_section_count;
3930       p = stash->adjusted_sections;
3931       for (; i > 0; i--, p++)
3932         p->section->vma = p->adj_vma;
3933       return TRUE;
3934     }
3935
3936   debug_info_name = stash->debug_sections[debug_info].uncompressed_name;
3937   i = 0;
3938   abfd = orig_bfd;
3939   while (1)
3940     {
3941       asection *sect;
3942
3943       for (sect = abfd->sections; sect != NULL; sect = sect->next)
3944         {
3945           int is_debug_info;
3946
3947           if ((sect->output_section != NULL
3948                && sect->output_section != sect
3949                && (sect->flags & SEC_DEBUGGING) == 0)
3950               || sect->vma != 0)
3951             continue;
3952
3953           is_debug_info = (strcmp (sect->name, debug_info_name) == 0
3954                            || CONST_STRNEQ (sect->name, GNU_LINKONCE_INFO));
3955
3956           if (!((sect->flags & SEC_ALLOC) != 0 && abfd == orig_bfd)
3957               && !is_debug_info)
3958             continue;
3959
3960           i++;
3961         }
3962       if (abfd == stash->bfd_ptr)
3963         break;
3964       abfd = stash->bfd_ptr;
3965     }
3966
3967   if (i <= 1)
3968     stash->adjusted_section_count = -1;
3969   else
3970     {
3971       bfd_vma last_vma = 0, last_dwarf = 0;
3972       bfd_size_type amt = i * sizeof (struct adjusted_section);
3973
3974       p = (struct adjusted_section *) bfd_malloc (amt);
3975       if (p == NULL)
3976         return FALSE;
3977
3978       stash->adjusted_sections = p;
3979       stash->adjusted_section_count = i;
3980
3981       abfd = orig_bfd;
3982       while (1)
3983         {
3984           asection *sect;
3985
3986           for (sect = abfd->sections; sect != NULL; sect = sect->next)
3987             {
3988               bfd_size_type sz;
3989               int is_debug_info;
3990
3991               if ((sect->output_section != NULL
3992                    && sect->output_section != sect
3993                    && (sect->flags & SEC_DEBUGGING) == 0)
3994                   || sect->vma != 0)
3995                 continue;
3996
3997               is_debug_info = (strcmp (sect->name, debug_info_name) == 0
3998                                || CONST_STRNEQ (sect->name, GNU_LINKONCE_INFO));
3999
4000               if (!((sect->flags & SEC_ALLOC) != 0 && abfd == orig_bfd)
4001                   && !is_debug_info)
4002                 continue;
4003
4004               sz = sect->rawsize ? sect->rawsize : sect->size;
4005
4006               if (is_debug_info)
4007                 {
4008                   BFD_ASSERT (sect->alignment_power == 0);
4009                   sect->vma = last_dwarf;
4010                   last_dwarf += sz;
4011                 }
4012               else
4013                 {
4014                   /* Align the new address to the current section
4015                      alignment.  */
4016                   last_vma = ((last_vma
4017                                + ~(-((bfd_vma) 1 << sect->alignment_power)))
4018                               & (-((bfd_vma) 1 << sect->alignment_power)));
4019                   sect->vma = last_vma;
4020                   last_vma += sz;
4021                 }
4022
4023               p->section = sect;
4024               p->adj_vma = sect->vma;
4025               p++;
4026             }
4027           if (abfd == stash->bfd_ptr)
4028             break;
4029           abfd = stash->bfd_ptr;
4030         }
4031     }
4032
4033   if (orig_bfd != stash->bfd_ptr)
4034     set_debug_vma (orig_bfd, stash->bfd_ptr);
4035
4036   return TRUE;
4037 }
4038
4039 /* Look up a funcinfo by name using the given info hash table.  If found,
4040    also update the locations pointed to by filename_ptr and linenumber_ptr.
4041
4042    This function returns TRUE if a funcinfo that matches the given symbol
4043    and address is found with any error; otherwise it returns FALSE.  */
4044
4045 static bfd_boolean
4046 info_hash_lookup_funcinfo (struct info_hash_table *hash_table,
4047                            asymbol *sym,
4048                            bfd_vma addr,
4049                            const char **filename_ptr,
4050                            unsigned int *linenumber_ptr)
4051 {
4052   struct funcinfo* each_func;
4053   struct funcinfo* best_fit = NULL;
4054   bfd_vma best_fit_len = 0;
4055   struct info_list_node *node;
4056   struct arange *arange;
4057   const char *name = bfd_asymbol_name (sym);
4058   asection *sec = bfd_get_section (sym);
4059
4060   for (node = lookup_info_hash_table (hash_table, name);
4061        node;
4062        node = node->next)
4063     {
4064       each_func = (struct funcinfo *) node->info;
4065       for (arange = &each_func->arange;
4066            arange;
4067            arange = arange->next)
4068         {
4069           if ((!each_func->sec || each_func->sec == sec)
4070               && addr >= arange->low
4071               && addr < arange->high
4072               && (!best_fit
4073                   || arange->high - arange->low < best_fit_len))
4074             {
4075               best_fit = each_func;
4076               best_fit_len = arange->high - arange->low;
4077             }
4078         }
4079     }
4080
4081   if (best_fit)
4082     {
4083       best_fit->sec = sec;
4084       *filename_ptr = best_fit->file;
4085       *linenumber_ptr = best_fit->line;
4086       return TRUE;
4087     }
4088
4089   return FALSE;
4090 }
4091
4092 /* Look up a varinfo by name using the given info hash table.  If found,
4093    also update the locations pointed to by filename_ptr and linenumber_ptr.
4094
4095    This function returns TRUE if a varinfo that matches the given symbol
4096    and address is found with any error; otherwise it returns FALSE.  */
4097
4098 static bfd_boolean
4099 info_hash_lookup_varinfo (struct info_hash_table *hash_table,
4100                           asymbol *sym,
4101                           bfd_vma addr,
4102                           const char **filename_ptr,
4103                           unsigned int *linenumber_ptr)
4104 {
4105   const char *name = bfd_asymbol_name (sym);
4106   asection *sec = bfd_get_section (sym);
4107   struct varinfo* each;
4108   struct info_list_node *node;
4109
4110   for (node = lookup_info_hash_table (hash_table, name);
4111        node;
4112        node = node->next)
4113     {
4114       each = (struct varinfo *) node->info;
4115       if (each->addr == addr
4116           && (!each->sec || each->sec == sec))
4117         {
4118           each->sec = sec;
4119           *filename_ptr = each->file;
4120           *linenumber_ptr = each->line;
4121           return TRUE;
4122         }
4123     }
4124
4125   return FALSE;
4126 }
4127
4128 /* Update the funcinfo and varinfo info hash tables if they are
4129    not up to date.  Returns TRUE if there is no error; otherwise
4130    returns FALSE and disable the info hash tables.  */
4131
4132 static bfd_boolean
4133 stash_maybe_update_info_hash_tables (struct dwarf2_debug *stash)
4134 {
4135   struct comp_unit *each;
4136
4137   /* Exit if hash tables are up-to-date.  */
4138   if (stash->all_comp_units == stash->hash_units_head)
4139     return TRUE;
4140
4141   if (stash->hash_units_head)
4142     each = stash->hash_units_head->prev_unit;
4143   else
4144     each = stash->last_comp_unit;
4145
4146   while (each)
4147     {
4148       if (!comp_unit_hash_info (stash, each, stash->funcinfo_hash_table,
4149                                 stash->varinfo_hash_table))
4150         {
4151           stash->info_hash_status = STASH_INFO_HASH_DISABLED;
4152           return FALSE;
4153         }
4154       each = each->prev_unit;
4155     }
4156
4157   stash->hash_units_head = stash->all_comp_units;
4158   return TRUE;
4159 }
4160
4161 /* Check consistency of info hash tables.  This is for debugging only.  */
4162
4163 static void ATTRIBUTE_UNUSED
4164 stash_verify_info_hash_table (struct dwarf2_debug *stash)
4165 {
4166   struct comp_unit *each_unit;
4167   struct funcinfo *each_func;
4168   struct varinfo *each_var;
4169   struct info_list_node *node;
4170   bfd_boolean found;
4171
4172   for (each_unit = stash->all_comp_units;
4173        each_unit;
4174        each_unit = each_unit->next_unit)
4175     {
4176       for (each_func = each_unit->function_table;
4177            each_func;
4178            each_func = each_func->prev_func)
4179         {
4180           if (!each_func->name)
4181             continue;
4182           node = lookup_info_hash_table (stash->funcinfo_hash_table,
4183                                          each_func->name);
4184           BFD_ASSERT (node);
4185           found = FALSE;
4186           while (node && !found)
4187             {
4188               found = node->info == each_func;
4189               node = node->next;
4190             }
4191           BFD_ASSERT (found);
4192         }
4193
4194       for (each_var = each_unit->variable_table;
4195            each_var;
4196            each_var = each_var->prev_var)
4197         {
4198           if (!each_var->name || !each_var->file || each_var->stack)
4199             continue;
4200           node = lookup_info_hash_table (stash->varinfo_hash_table,
4201                                          each_var->name);
4202           BFD_ASSERT (node);
4203           found = FALSE;
4204           while (node && !found)
4205             {
4206               found = node->info == each_var;
4207               node = node->next;
4208             }
4209           BFD_ASSERT (found);
4210         }
4211     }
4212 }
4213
4214 /* Check to see if we want to enable the info hash tables, which consume
4215    quite a bit of memory.  Currently we only check the number times
4216    bfd_dwarf2_find_line is called.  In the future, we may also want to
4217    take the number of symbols into account.  */
4218
4219 static void
4220 stash_maybe_enable_info_hash_tables (bfd *abfd, struct dwarf2_debug *stash)
4221 {
4222   BFD_ASSERT (stash->info_hash_status == STASH_INFO_HASH_OFF);
4223
4224   if (stash->info_hash_count++ < STASH_INFO_HASH_TRIGGER)
4225     return;
4226
4227   /* FIXME: Maybe we should check the reduce_memory_overheads
4228      and optimize fields in the bfd_link_info structure ?  */
4229
4230   /* Create hash tables.  */
4231   stash->funcinfo_hash_table = create_info_hash_table (abfd);
4232   stash->varinfo_hash_table = create_info_hash_table (abfd);
4233   if (!stash->funcinfo_hash_table || !stash->varinfo_hash_table)
4234     {
4235       /* Turn off info hashes if any allocation above fails.  */
4236       stash->info_hash_status = STASH_INFO_HASH_DISABLED;
4237       return;
4238     }
4239   /* We need a forced update so that the info hash tables will
4240      be created even though there is no compilation unit.  That
4241      happens if STASH_INFO_HASH_TRIGGER is 0.  */
4242   stash_maybe_update_info_hash_tables (stash);
4243   stash->info_hash_status = STASH_INFO_HASH_ON;
4244 }
4245
4246 /* Find the file and line associated with a symbol and address using the
4247    info hash tables of a stash. If there is a match, the function returns
4248    TRUE and update the locations pointed to by filename_ptr and linenumber_ptr;
4249    otherwise it returns FALSE.  */
4250
4251 static bfd_boolean
4252 stash_find_line_fast (struct dwarf2_debug *stash,
4253                       asymbol *sym,
4254                       bfd_vma addr,
4255                       const char **filename_ptr,
4256                       unsigned int *linenumber_ptr)
4257 {
4258   BFD_ASSERT (stash->info_hash_status == STASH_INFO_HASH_ON);
4259
4260   if (sym->flags & BSF_FUNCTION)
4261     return info_hash_lookup_funcinfo (stash->funcinfo_hash_table, sym, addr,
4262                                       filename_ptr, linenumber_ptr);
4263   return info_hash_lookup_varinfo (stash->varinfo_hash_table, sym, addr,
4264                                    filename_ptr, linenumber_ptr);
4265 }
4266
4267 /* Save current section VMAs.  */
4268
4269 static bfd_boolean
4270 save_section_vma (const bfd *abfd, struct dwarf2_debug *stash)
4271 {
4272   asection *s;
4273   unsigned int i;
4274
4275   if (abfd->section_count == 0)
4276     return TRUE;
4277   stash->sec_vma = bfd_malloc (sizeof (*stash->sec_vma) * abfd->section_count);
4278   if (stash->sec_vma == NULL)
4279     return FALSE;
4280   for (i = 0, s = abfd->sections; i < abfd->section_count; i++, s = s->next)
4281     {
4282       if (s->output_section != NULL)
4283         stash->sec_vma[i] = s->output_section->vma + s->output_offset;
4284       else
4285         stash->sec_vma[i] = s->vma;
4286     }
4287   return TRUE;
4288 }
4289
4290 /* Compare current section VMAs against those at the time the stash
4291    was created.  If find_nearest_line is used in linker warnings or
4292    errors early in the link process, the debug info stash will be
4293    invalid for later calls.  This is because we relocate debug info
4294    sections, so the stashed section contents depend on symbol values,
4295    which in turn depend on section VMAs.  */
4296
4297 static bfd_boolean
4298 section_vma_same (const bfd *abfd, const struct dwarf2_debug *stash)
4299 {
4300   asection *s;
4301   unsigned int i;
4302
4303   for (i = 0, s = abfd->sections; i < abfd->section_count; i++, s = s->next)
4304     {
4305       bfd_vma vma;
4306
4307       if (s->output_section != NULL)
4308         vma = s->output_section->vma + s->output_offset;
4309       else
4310         vma = s->vma;
4311       if (vma != stash->sec_vma[i])
4312         return FALSE;
4313     }
4314   return TRUE;
4315 }
4316
4317 /* Read debug information from DEBUG_BFD when DEBUG_BFD is specified.
4318    If DEBUG_BFD is not specified, we read debug information from ABFD
4319    or its gnu_debuglink. The results will be stored in PINFO.
4320    The function returns TRUE iff debug information is ready.  */
4321
4322 bfd_boolean
4323 _bfd_dwarf2_slurp_debug_info (bfd *abfd, bfd *debug_bfd,
4324                               const struct dwarf_debug_section *debug_sections,
4325                               asymbol **symbols,
4326                               void **pinfo,
4327                               bfd_boolean do_place)
4328 {
4329   bfd_size_type amt = sizeof (struct dwarf2_debug);
4330   bfd_size_type total_size;
4331   asection *msec;
4332   struct dwarf2_debug *stash = (struct dwarf2_debug *) *pinfo;
4333
4334   if (stash != NULL)
4335     {
4336       if (stash->orig_bfd == abfd
4337           && section_vma_same (abfd, stash))
4338         {
4339           /* Check that we did previously find some debug information
4340              before attempting to make use of it.  */
4341           if (stash->bfd_ptr != NULL)
4342             {
4343               if (do_place && !place_sections (abfd, stash))
4344                 return FALSE;
4345               return TRUE;
4346             }
4347
4348           return FALSE;
4349         }
4350       _bfd_dwarf2_cleanup_debug_info (abfd, pinfo);
4351       memset (stash, 0, amt);
4352     }
4353   else
4354     {
4355       stash = (struct dwarf2_debug *) bfd_zalloc (abfd, amt);
4356       if (! stash)
4357         return FALSE;
4358     }
4359   stash->orig_bfd = abfd;
4360   stash->debug_sections = debug_sections;
4361   stash->syms = symbols;
4362   if (!save_section_vma (abfd, stash))
4363     return FALSE;
4364
4365   *pinfo = stash;
4366
4367   if (debug_bfd == NULL)
4368     debug_bfd = abfd;
4369
4370   msec = find_debug_info (debug_bfd, debug_sections, NULL);
4371   if (msec == NULL && abfd == debug_bfd)
4372     {
4373       char * debug_filename;
4374
4375       debug_filename = bfd_follow_build_id_debuglink (abfd, DEBUGDIR);
4376       if (debug_filename == NULL)
4377         debug_filename = bfd_follow_gnu_debuglink (abfd, DEBUGDIR);
4378
4379       if (debug_filename == NULL)
4380         /* No dwarf2 info, and no gnu_debuglink to follow.
4381            Note that at this point the stash has been allocated, but
4382            contains zeros.  This lets future calls to this function
4383            fail more quickly.  */
4384         return FALSE;
4385
4386       /* Set BFD_DECOMPRESS to decompress debug sections.  */
4387       if ((debug_bfd = bfd_openr (debug_filename, NULL)) == NULL
4388           || !(debug_bfd->flags |= BFD_DECOMPRESS,
4389                bfd_check_format (debug_bfd, bfd_object))
4390           || (msec = find_debug_info (debug_bfd,
4391                                       debug_sections, NULL)) == NULL
4392           || !bfd_generic_link_read_symbols (debug_bfd))
4393         {
4394           if (debug_bfd)
4395             bfd_close (debug_bfd);
4396           /* FIXME: Should we report our failure to follow the debuglink ?  */
4397           free (debug_filename);
4398           return FALSE;
4399         }
4400
4401       symbols = bfd_get_outsymbols (debug_bfd);
4402       stash->syms = symbols;
4403       stash->close_on_cleanup = TRUE;
4404     }
4405   stash->bfd_ptr = debug_bfd;
4406
4407   if (do_place
4408       && !place_sections (abfd, stash))
4409     return FALSE;
4410
4411   /* There can be more than one DWARF2 info section in a BFD these
4412      days.  First handle the easy case when there's only one.  If
4413      there's more than one, try case two: none of the sections is
4414      compressed.  In that case, read them all in and produce one
4415      large stash.  We do this in two passes - in the first pass we
4416      just accumulate the section sizes, and in the second pass we
4417      read in the section's contents.  (The allows us to avoid
4418      reallocing the data as we add sections to the stash.)  If
4419      some or all sections are compressed, then do things the slow
4420      way, with a bunch of reallocs.  */
4421
4422   if (! find_debug_info (debug_bfd, debug_sections, msec))
4423     {
4424       /* Case 1: only one info section.  */
4425       total_size = msec->size;
4426       if (! read_section (debug_bfd, &stash->debug_sections[debug_info],
4427                           symbols, 0,
4428                           &stash->info_ptr_memory, &total_size))
4429         return FALSE;
4430     }
4431   else
4432     {
4433       /* Case 2: multiple sections.  */
4434       for (total_size = 0;
4435            msec;
4436            msec = find_debug_info (debug_bfd, debug_sections, msec))
4437         total_size += msec->size;
4438
4439       stash->info_ptr_memory = (bfd_byte *) bfd_malloc (total_size);
4440       if (stash->info_ptr_memory == NULL)
4441         return FALSE;
4442
4443       total_size = 0;
4444       for (msec = find_debug_info (debug_bfd, debug_sections, NULL);
4445            msec;
4446            msec = find_debug_info (debug_bfd, debug_sections, msec))
4447         {
4448           bfd_size_type size;
4449
4450           size = msec->size;
4451           if (size == 0)
4452             continue;
4453
4454           if (!(bfd_simple_get_relocated_section_contents
4455                 (debug_bfd, msec, stash->info_ptr_memory + total_size,
4456                  symbols)))
4457             return FALSE;
4458
4459           total_size += size;
4460         }
4461     }
4462
4463   stash->info_ptr = stash->info_ptr_memory;
4464   stash->info_ptr_end = stash->info_ptr + total_size;
4465   stash->sec = find_debug_info (debug_bfd, debug_sections, NULL);
4466   stash->sec_info_ptr = stash->info_ptr;
4467   return TRUE;
4468 }
4469
4470 /* Scan the debug information in PINFO looking for a DW_TAG_subprogram
4471    abbrev with a DW_AT_low_pc attached to it.  Then lookup that same
4472    symbol in SYMBOLS and return the difference between the low_pc and
4473    the symbol's address.  Returns 0 if no suitable symbol could be found.  */
4474
4475 bfd_signed_vma
4476 _bfd_dwarf2_find_symbol_bias (asymbol ** symbols, void ** pinfo)
4477 {
4478   struct dwarf2_debug *stash;
4479   struct comp_unit * unit;
4480
4481   stash = (struct dwarf2_debug *) *pinfo;
4482
4483   if (stash == NULL)
4484     return 0;
4485
4486   for (unit = stash->all_comp_units; unit; unit = unit->next_unit)
4487     {
4488       struct funcinfo * func;
4489
4490       if (unit->function_table == NULL)
4491         {
4492           if (unit->line_table == NULL)
4493             unit->line_table = decode_line_info (unit, stash);
4494           if (unit->line_table != NULL)
4495             scan_unit_for_symbols (unit);
4496         }
4497
4498       for (func = unit->function_table; func != NULL; func = func->prev_func)
4499         if (func->name && func->arange.low)
4500           {
4501             asymbol ** psym;
4502
4503             /* FIXME: Do we need to scan the aranges looking for the lowest pc value ?  */
4504
4505             for (psym = symbols; * psym != NULL; psym++)
4506               {
4507                 asymbol * sym = * psym;
4508
4509                 if (sym->flags & BSF_FUNCTION
4510                     && sym->section != NULL
4511                     && strcmp (sym->name, func->name) == 0)
4512                   return ((bfd_signed_vma) func->arange.low) -
4513                     ((bfd_signed_vma) (sym->value + sym->section->vma));
4514               }
4515           }
4516     }
4517
4518   return 0;
4519 }
4520
4521 /* Find the source code location of SYMBOL.  If SYMBOL is NULL
4522    then find the nearest source code location corresponding to
4523    the address SECTION + OFFSET.
4524    Returns TRUE if the line is found without error and fills in
4525    FILENAME_PTR and LINENUMBER_PTR.  In the case where SYMBOL was
4526    NULL the FUNCTIONNAME_PTR is also filled in.
4527    SYMBOLS contains the symbol table for ABFD.
4528    DEBUG_SECTIONS contains the name of the dwarf debug sections.
4529    ADDR_SIZE is the number of bytes in the initial .debug_info length
4530    field and in the abbreviation offset, or zero to indicate that the
4531    default value should be used.  */
4532
4533 bfd_boolean
4534 _bfd_dwarf2_find_nearest_line (bfd *abfd,
4535                                asymbol **symbols,
4536                                asymbol *symbol,
4537                                asection *section,
4538                                bfd_vma offset,
4539                                const char **filename_ptr,
4540                                const char **functionname_ptr,
4541                                unsigned int *linenumber_ptr,
4542                                unsigned int *discriminator_ptr,
4543                                const struct dwarf_debug_section *debug_sections,
4544                                unsigned int addr_size,
4545                                void **pinfo)
4546 {
4547   /* Read each compilation unit from the section .debug_info, and check
4548      to see if it contains the address we are searching for.  If yes,
4549      lookup the address, and return the line number info.  If no, go
4550      on to the next compilation unit.
4551
4552      We keep a list of all the previously read compilation units, and
4553      a pointer to the next un-read compilation unit.  Check the
4554      previously read units before reading more.  */
4555   struct dwarf2_debug *stash;
4556   /* What address are we looking for?  */
4557   bfd_vma addr;
4558   struct comp_unit* each;
4559   struct funcinfo *function = NULL;
4560   bfd_boolean found = FALSE;
4561   bfd_boolean do_line;
4562
4563   *filename_ptr = NULL;
4564   if (functionname_ptr != NULL)
4565     *functionname_ptr = NULL;
4566   *linenumber_ptr = 0;
4567   if (discriminator_ptr)
4568     *discriminator_ptr = 0;
4569
4570   if (! _bfd_dwarf2_slurp_debug_info (abfd, NULL, debug_sections,
4571                                       symbols, pinfo,
4572                                       (abfd->flags & (EXEC_P | DYNAMIC)) == 0))
4573     return FALSE;
4574
4575   stash = (struct dwarf2_debug *) *pinfo;
4576
4577   do_line = symbol != NULL;
4578   if (do_line)
4579     {
4580       BFD_ASSERT (section == NULL && offset == 0 && functionname_ptr == NULL);
4581       section = bfd_get_section (symbol);
4582       addr = symbol->value;
4583     }
4584   else
4585     {
4586       BFD_ASSERT (section != NULL && functionname_ptr != NULL);
4587       addr = offset;
4588
4589       /* If we have no SYMBOL but the section we're looking at is not a
4590          code section, then take a look through the list of symbols to see
4591          if we have a symbol at the address we're looking for.  If we do
4592          then use this to look up line information.  This will allow us to
4593          give file and line results for data symbols.  We exclude code
4594          symbols here, if we look up a function symbol and then look up the
4595          line information we'll actually return the line number for the
4596          opening '{' rather than the function definition line.  This is
4597          because looking up by symbol uses the line table, in which the
4598          first line for a function is usually the opening '{', while
4599          looking up the function by section + offset uses the
4600          DW_AT_decl_line from the function DW_TAG_subprogram for the line,
4601          which will be the line of the function name.  */
4602       if (symbols != NULL && (section->flags & SEC_CODE) == 0)
4603         {
4604           asymbol **tmp;
4605
4606           for (tmp = symbols; (*tmp) != NULL; ++tmp)
4607             if ((*tmp)->the_bfd == abfd
4608                 && (*tmp)->section == section
4609                 && (*tmp)->value == offset
4610                 && ((*tmp)->flags & BSF_SECTION_SYM) == 0)
4611               {
4612                 symbol = *tmp;
4613                 do_line = TRUE;
4614                 /* For local symbols, keep going in the hope we find a
4615                    global.  */
4616                 if ((symbol->flags & BSF_GLOBAL) != 0)
4617                   break;
4618               }
4619         }
4620     }
4621
4622   if (section->output_section)
4623     addr += section->output_section->vma + section->output_offset;
4624   else
4625     addr += section->vma;
4626
4627   /* A null info_ptr indicates that there is no dwarf2 info
4628      (or that an error occured while setting up the stash).  */
4629   if (! stash->info_ptr)
4630     return FALSE;
4631
4632   stash->inliner_chain = NULL;
4633
4634   /* Check the previously read comp. units first.  */
4635   if (do_line)
4636     {
4637       /* The info hash tables use quite a bit of memory.  We may not want to
4638          always use them.  We use some heuristics to decide if and when to
4639          turn it on.  */
4640       if (stash->info_hash_status == STASH_INFO_HASH_OFF)
4641         stash_maybe_enable_info_hash_tables (abfd, stash);
4642
4643       /* Keep info hash table up to date if they are available.  Note that we
4644          may disable the hash tables if there is any error duing update.  */
4645       if (stash->info_hash_status == STASH_INFO_HASH_ON)
4646         stash_maybe_update_info_hash_tables (stash);
4647
4648       if (stash->info_hash_status == STASH_INFO_HASH_ON)
4649         {
4650           found = stash_find_line_fast (stash, symbol, addr, filename_ptr,
4651                                         linenumber_ptr);
4652           if (found)
4653             goto done;
4654         }
4655       else
4656         {
4657           /* Check the previously read comp. units first.  */
4658           for (each = stash->all_comp_units; each; each = each->next_unit)
4659             if ((symbol->flags & BSF_FUNCTION) == 0
4660                 || each->arange.high == 0
4661                 || comp_unit_contains_address (each, addr))
4662               {
4663                 found = comp_unit_find_line (each, symbol, addr, filename_ptr,
4664                                              linenumber_ptr, stash);
4665                 if (found)
4666                   goto done;
4667               }
4668         }
4669     }
4670   else
4671     {
4672       bfd_vma min_range = (bfd_vma) -1;
4673       const char * local_filename = NULL;
4674       struct funcinfo *local_function = NULL;
4675       unsigned int local_linenumber = 0;
4676       unsigned int local_discriminator = 0;
4677
4678       for (each = stash->all_comp_units; each; each = each->next_unit)
4679         {
4680           bfd_vma range = (bfd_vma) -1;
4681
4682           found = ((each->arange.high == 0
4683                     || comp_unit_contains_address (each, addr))
4684                    && (range = comp_unit_find_nearest_line (each, addr,
4685                                                             & local_filename,
4686                                                             & local_function,
4687                                                             & local_linenumber,
4688                                                             & local_discriminator,
4689                                                             stash)) != 0);
4690           if (found)
4691             {
4692               /* PRs 15935 15994: Bogus debug information may have provided us
4693                  with an erroneous match.  We attempt to counter this by
4694                  selecting the match that has the smallest address range
4695                  associated with it.  (We are assuming that corrupt debug info
4696                  will tend to result in extra large address ranges rather than
4697                  extra small ranges).
4698
4699                  This does mean that we scan through all of the CUs associated
4700                  with the bfd each time this function is called.  But this does
4701                  have the benefit of producing consistent results every time the
4702                  function is called.  */
4703               if (range <= min_range)
4704                 {
4705                   if (filename_ptr && local_filename)
4706                     * filename_ptr = local_filename;
4707                   if (local_function)
4708                     function = local_function;
4709                   if (discriminator_ptr && local_discriminator)
4710                     * discriminator_ptr = local_discriminator;
4711                   if (local_linenumber)
4712                     * linenumber_ptr = local_linenumber;
4713                   min_range = range;
4714                 }
4715             }
4716         }
4717
4718       if (* linenumber_ptr)
4719         {
4720           found = TRUE;
4721           goto done;
4722         }
4723     }
4724
4725   /* The DWARF2 spec says that the initial length field, and the
4726      offset of the abbreviation table, should both be 4-byte values.
4727      However, some compilers do things differently.  */
4728   if (addr_size == 0)
4729     addr_size = 4;
4730   BFD_ASSERT (addr_size == 4 || addr_size == 8);
4731
4732   /* Read each remaining comp. units checking each as they are read.  */
4733   while (stash->info_ptr < stash->info_ptr_end)
4734     {
4735       bfd_vma length;
4736       unsigned int offset_size = addr_size;
4737       bfd_byte *info_ptr_unit = stash->info_ptr;
4738
4739       length = read_4_bytes (stash->bfd_ptr, stash->info_ptr, stash->info_ptr_end);
4740       /* A 0xffffff length is the DWARF3 way of indicating
4741          we use 64-bit offsets, instead of 32-bit offsets.  */
4742       if (length == 0xffffffff)
4743         {
4744           offset_size = 8;
4745           length = read_8_bytes (stash->bfd_ptr, stash->info_ptr + 4, stash->info_ptr_end);
4746           stash->info_ptr += 12;
4747         }
4748       /* A zero length is the IRIX way of indicating 64-bit offsets,
4749          mostly because the 64-bit length will generally fit in 32
4750          bits, and the endianness helps.  */
4751       else if (length == 0)
4752         {
4753           offset_size = 8;
4754           length = read_4_bytes (stash->bfd_ptr, stash->info_ptr + 4, stash->info_ptr_end);
4755           stash->info_ptr += 8;
4756         }
4757       /* In the absence of the hints above, we assume 32-bit DWARF2
4758          offsets even for targets with 64-bit addresses, because:
4759            a) most of the time these targets will not have generated
4760               more than 2Gb of debug info and so will not need 64-bit
4761               offsets,
4762          and
4763            b) if they do use 64-bit offsets but they are not using
4764               the size hints that are tested for above then they are
4765               not conforming to the DWARF3 standard anyway.  */
4766       else if (addr_size == 8)
4767         {
4768           offset_size = 4;
4769           stash->info_ptr += 4;
4770         }
4771       else
4772         stash->info_ptr += 4;
4773
4774       if (length > 0)
4775         {
4776           bfd_byte * new_ptr;
4777
4778           /* PR 21151  */
4779           if (stash->info_ptr + length > stash->info_ptr_end)
4780             return FALSE;
4781
4782           each = parse_comp_unit (stash, length, info_ptr_unit,
4783                                   offset_size);
4784           if (!each)
4785             /* The dwarf information is damaged, don't trust it any
4786                more.  */
4787             break;
4788
4789           new_ptr = stash->info_ptr + length;
4790           /* PR 17512: file: 1500698c.  */
4791           if (new_ptr < stash->info_ptr)
4792             {
4793               /* A corrupt length value - do not trust the info any more.  */
4794               found = FALSE;
4795               break;
4796             }
4797           else
4798             stash->info_ptr = new_ptr;
4799
4800           if (stash->all_comp_units)
4801             stash->all_comp_units->prev_unit = each;
4802           else
4803             stash->last_comp_unit = each;
4804
4805           each->next_unit = stash->all_comp_units;
4806           stash->all_comp_units = each;
4807
4808           /* DW_AT_low_pc and DW_AT_high_pc are optional for
4809              compilation units.  If we don't have them (i.e.,
4810              unit->high == 0), we need to consult the line info table
4811              to see if a compilation unit contains the given
4812              address.  */
4813           if (do_line)
4814             found = (((symbol->flags & BSF_FUNCTION) == 0
4815                       || each->arange.high == 0
4816                       || comp_unit_contains_address (each, addr))
4817                      && comp_unit_find_line (each, symbol, addr,
4818                                              filename_ptr,
4819                                              linenumber_ptr,
4820                                              stash));
4821           else
4822             found = ((each->arange.high == 0
4823                       || comp_unit_contains_address (each, addr))
4824                      && comp_unit_find_nearest_line (each, addr,
4825                                                      filename_ptr,
4826                                                      &function,
4827                                                      linenumber_ptr,
4828                                                      discriminator_ptr,
4829                                                      stash) != 0);
4830
4831           if ((bfd_vma) (stash->info_ptr - stash->sec_info_ptr)
4832               == stash->sec->size)
4833             {
4834               stash->sec = find_debug_info (stash->bfd_ptr, debug_sections,
4835                                             stash->sec);
4836               stash->sec_info_ptr = stash->info_ptr;
4837             }
4838
4839           if (found)
4840             goto done;
4841         }
4842     }
4843
4844  done:
4845   if (function)
4846     {
4847       if (!function->is_linkage)
4848         {
4849           asymbol *fun;
4850           bfd_vma sec_vma;
4851
4852           fun = _bfd_elf_find_function (abfd, symbols, section, offset,
4853                                         *filename_ptr ? NULL : filename_ptr,
4854                                         functionname_ptr);
4855           sec_vma = section->vma;
4856           if (section->output_section != NULL)
4857             sec_vma = section->output_section->vma + section->output_offset;
4858           if (fun != NULL
4859               && fun->value + sec_vma == function->arange.low)
4860             function->name = *functionname_ptr;
4861           /* Even if we didn't find a linkage name, say that we have
4862              to stop a repeated search of symbols.  */
4863           function->is_linkage = TRUE;
4864         }
4865       *functionname_ptr = function->name;
4866     }
4867   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
4868     unset_sections (stash);
4869
4870   return found;
4871 }
4872
4873 bfd_boolean
4874 _bfd_dwarf2_find_inliner_info (bfd *abfd ATTRIBUTE_UNUSED,
4875                                const char **filename_ptr,
4876                                const char **functionname_ptr,
4877                                unsigned int *linenumber_ptr,
4878                                void **pinfo)
4879 {
4880   struct dwarf2_debug *stash;
4881
4882   stash = (struct dwarf2_debug *) *pinfo;
4883   if (stash)
4884     {
4885       struct funcinfo *func = stash->inliner_chain;
4886
4887       if (func && func->caller_func)
4888         {
4889           *filename_ptr = func->caller_file;
4890           *functionname_ptr = func->caller_func->name;
4891           *linenumber_ptr = func->caller_line;
4892           stash->inliner_chain = func->caller_func;
4893           return TRUE;
4894         }
4895     }
4896
4897   return FALSE;
4898 }
4899
4900 void
4901 _bfd_dwarf2_cleanup_debug_info (bfd *abfd, void **pinfo)
4902 {
4903   struct dwarf2_debug *stash = (struct dwarf2_debug *) *pinfo;
4904   struct comp_unit *each;
4905
4906   if (abfd == NULL || stash == NULL)
4907     return;
4908
4909   for (each = stash->all_comp_units; each; each = each->next_unit)
4910     {
4911       struct abbrev_info **abbrevs = each->abbrevs;
4912       struct funcinfo *function_table = each->function_table;
4913       struct varinfo *variable_table = each->variable_table;
4914       size_t i;
4915
4916       for (i = 0; i < ABBREV_HASH_SIZE; i++)
4917         {
4918           struct abbrev_info *abbrev = abbrevs[i];
4919
4920           while (abbrev)
4921             {
4922               free (abbrev->attrs);
4923               abbrev = abbrev->next;
4924             }
4925         }
4926
4927       if (each->line_table)
4928         {
4929           free (each->line_table->dirs);
4930           free (each->line_table->files);
4931         }
4932
4933       while (function_table)
4934         {
4935           if (function_table->file)
4936             {
4937               free (function_table->file);
4938               function_table->file = NULL;
4939             }
4940
4941           if (function_table->caller_file)
4942             {
4943               free (function_table->caller_file);
4944               function_table->caller_file = NULL;
4945             }
4946           function_table = function_table->prev_func;
4947         }
4948
4949       if (each->lookup_funcinfo_table)
4950         {
4951           free (each->lookup_funcinfo_table);
4952           each->lookup_funcinfo_table = NULL;
4953         }
4954
4955       while (variable_table)
4956         {
4957           if (variable_table->file)
4958             {
4959               free (variable_table->file);
4960               variable_table->file = NULL;
4961             }
4962
4963           variable_table = variable_table->prev_var;
4964         }
4965     }
4966
4967   if (stash->dwarf_abbrev_buffer)
4968     free (stash->dwarf_abbrev_buffer);
4969   if (stash->dwarf_line_buffer)
4970     free (stash->dwarf_line_buffer);
4971   if (stash->dwarf_str_buffer)
4972     free (stash->dwarf_str_buffer);
4973   if (stash->dwarf_line_str_buffer)
4974     free (stash->dwarf_line_str_buffer);
4975   if (stash->dwarf_ranges_buffer)
4976     free (stash->dwarf_ranges_buffer);
4977   if (stash->info_ptr_memory)
4978     free (stash->info_ptr_memory);
4979   if (stash->close_on_cleanup)
4980     bfd_close (stash->bfd_ptr);
4981   if (stash->alt_dwarf_str_buffer)
4982     free (stash->alt_dwarf_str_buffer);
4983   if (stash->alt_dwarf_info_buffer)
4984     free (stash->alt_dwarf_info_buffer);
4985   if (stash->sec_vma)
4986     free (stash->sec_vma);
4987   if (stash->adjusted_sections)
4988     free (stash->adjusted_sections);
4989   if (stash->alt_bfd_ptr)
4990     bfd_close (stash->alt_bfd_ptr);
4991 }
4992
4993 /* Find the function to a particular section and offset,
4994    for error reporting.  */
4995
4996 asymbol *
4997 _bfd_elf_find_function (bfd *abfd,
4998                         asymbol **symbols,
4999                         asection *section,
5000                         bfd_vma offset,
5001                         const char **filename_ptr,
5002                         const char **functionname_ptr)
5003 {
5004   struct elf_find_function_cache
5005   {
5006     asection *last_section;
5007     asymbol *func;
5008     const char *filename;
5009     bfd_size_type func_size;
5010   } *cache;
5011
5012   if (symbols == NULL)
5013     return NULL;
5014
5015   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
5016     return NULL;
5017
5018   cache = elf_tdata (abfd)->elf_find_function_cache;
5019   if (cache == NULL)
5020     {
5021       cache = bfd_zalloc (abfd, sizeof (*cache));
5022       elf_tdata (abfd)->elf_find_function_cache = cache;
5023       if (cache == NULL)
5024         return NULL;
5025     }
5026   if (cache->last_section != section
5027       || cache->func == NULL
5028       || offset < cache->func->value
5029       || offset >= cache->func->value + cache->func_size)
5030     {
5031       asymbol *file;
5032       bfd_vma low_func;
5033       asymbol **p;
5034       /* ??? Given multiple file symbols, it is impossible to reliably
5035          choose the right file name for global symbols.  File symbols are
5036          local symbols, and thus all file symbols must sort before any
5037          global symbols.  The ELF spec may be interpreted to say that a
5038          file symbol must sort before other local symbols, but currently
5039          ld -r doesn't do this.  So, for ld -r output, it is possible to
5040          make a better choice of file name for local symbols by ignoring
5041          file symbols appearing after a given local symbol.  */
5042       enum { nothing_seen, symbol_seen, file_after_symbol_seen } state;
5043       const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5044
5045       file = NULL;
5046       low_func = 0;
5047       state = nothing_seen;
5048       cache->filename = NULL;
5049       cache->func = NULL;
5050       cache->func_size = 0;
5051       cache->last_section = section;
5052
5053       for (p = symbols; *p != NULL; p++)
5054         {
5055           asymbol *sym = *p;
5056           bfd_vma code_off;
5057           bfd_size_type size;
5058
5059           if ((sym->flags & BSF_FILE) != 0)
5060             {
5061               file = sym;
5062               if (state == symbol_seen)
5063                 state = file_after_symbol_seen;
5064               continue;
5065             }
5066
5067           size = bed->maybe_function_sym (sym, section, &code_off);
5068           if (size != 0
5069               && code_off <= offset
5070               && (code_off > low_func
5071                   || (code_off == low_func
5072                       && size > cache->func_size)))
5073             {
5074               cache->func = sym;
5075               cache->func_size = size;
5076               cache->filename = NULL;
5077               low_func = code_off;
5078               if (file != NULL
5079                   && ((sym->flags & BSF_LOCAL) != 0
5080                       || state != file_after_symbol_seen))
5081                 cache->filename = bfd_asymbol_name (file);
5082             }
5083           if (state == nothing_seen)
5084             state = symbol_seen;
5085         }
5086     }
5087
5088   if (cache->func == NULL)
5089     return NULL;
5090
5091   if (filename_ptr)
5092     *filename_ptr = cache->filename;
5093   if (functionname_ptr)
5094     *functionname_ptr = bfd_asymbol_name (cache->func);
5095
5096   return cache->func;
5097 }