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