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