* dwarf_reader.h (class Sized_dwarf_line_info): Add
[external/binutils.git] / gold / dwarf_reader.cc
1 // dwarf_reader.cc -- parse dwarf2/3 debug information
2
3 // Copyright 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <algorithm>
26 #include <vector>
27
28 #include "elfcpp_swap.h"
29 #include "dwarf.h"
30 #include "object.h"
31 #include "parameters.h"
32 #include "reloc.h"
33 #include "dwarf_reader.h"
34 #include "int_encoding.h"
35 #include "compressed_output.h"
36
37 namespace gold {
38
39 struct LineStateMachine
40 {
41   int file_num;
42   uint64_t address;
43   int line_num;
44   int column_num;
45   unsigned int shndx;    // the section address refers to
46   bool is_stmt;          // stmt means statement.
47   bool basic_block;
48   bool end_sequence;
49 };
50
51 static void
52 ResetLineStateMachine(struct LineStateMachine* lsm, bool default_is_stmt)
53 {
54   lsm->file_num = 1;
55   lsm->address = 0;
56   lsm->line_num = 1;
57   lsm->column_num = 0;
58   lsm->shndx = -1U;
59   lsm->is_stmt = default_is_stmt;
60   lsm->basic_block = false;
61   lsm->end_sequence = false;
62 }
63
64 template<int size, bool big_endian>
65 Sized_dwarf_line_info<size, big_endian>::Sized_dwarf_line_info(Object* object,
66                                                                unsigned int read_shndx)
67   : data_valid_(false), buffer_(NULL), symtab_buffer_(NULL),
68     directories_(), files_(), current_header_index_(-1)
69 {
70   unsigned int debug_shndx;
71   for (debug_shndx = 1; debug_shndx < object->shnum(); ++debug_shndx)
72     {
73       // FIXME: do this more efficiently: section_name() isn't super-fast
74       std::string name = object->section_name(debug_shndx);
75       if (name == ".debug_line" || name == ".zdebug_line")
76         {
77           section_size_type buffer_size;
78           this->buffer_ = object->section_contents(debug_shndx, &buffer_size,
79                                                    false);
80           this->buffer_end_ = this->buffer_ + buffer_size;
81           break;
82         }
83     }
84   if (this->buffer_ == NULL)
85     return;
86
87   section_size_type uncompressed_size = 0;
88   unsigned char* uncompressed_data = NULL;
89   if (object->section_is_compressed(debug_shndx, &uncompressed_size))
90     {
91       uncompressed_data = new unsigned char[uncompressed_size];
92       if (!decompress_input_section(this->buffer_,
93                                     this->buffer_end_ - this->buffer_,
94                                     uncompressed_data,
95                                     uncompressed_size))
96         object->error(_("could not decompress section %s"),
97                       object->section_name(debug_shndx).c_str());
98       this->buffer_ = uncompressed_data;
99       this->buffer_end_ = this->buffer_ + uncompressed_size;
100     }
101
102   // Find the relocation section for ".debug_line".
103   // We expect these for relobjs (.o's) but not dynobjs (.so's).
104   bool got_relocs = false;
105   for (unsigned int reloc_shndx = 0;
106        reloc_shndx < object->shnum();
107        ++reloc_shndx)
108     {
109       unsigned int reloc_sh_type = object->section_type(reloc_shndx);
110       if ((reloc_sh_type == elfcpp::SHT_REL
111            || reloc_sh_type == elfcpp::SHT_RELA)
112           && object->section_info(reloc_shndx) == debug_shndx)
113         {
114           got_relocs = this->track_relocs_.initialize(object, reloc_shndx,
115                                                       reloc_sh_type);
116           this->track_relocs_type_ = reloc_sh_type;
117           break;
118         }
119     }
120
121   // Finally, we need the symtab section to interpret the relocs.
122   if (got_relocs)
123     {
124       unsigned int symtab_shndx;
125       for (symtab_shndx = 0; symtab_shndx < object->shnum(); ++symtab_shndx)
126         if (object->section_type(symtab_shndx) == elfcpp::SHT_SYMTAB)
127           {
128             this->symtab_buffer_ = object->section_contents(
129                 symtab_shndx, &this->symtab_buffer_size_, false);
130             break;
131           }
132       if (this->symtab_buffer_ == NULL)
133         return;
134     }
135
136   // Now that we have successfully read all the data, parse the debug
137   // info.
138   this->data_valid_ = true;
139   this->read_line_mappings(object, read_shndx);
140 }
141
142 // Read the DWARF header.
143
144 template<int size, bool big_endian>
145 const unsigned char*
146 Sized_dwarf_line_info<size, big_endian>::read_header_prolog(
147     const unsigned char* lineptr)
148 {
149   uint32_t initial_length = elfcpp::Swap_unaligned<32, big_endian>::readval(lineptr);
150   lineptr += 4;
151
152   // In DWARF2/3, if the initial length is all 1 bits, then the offset
153   // size is 8 and we need to read the next 8 bytes for the real length.
154   if (initial_length == 0xffffffff)
155     {
156       header_.offset_size = 8;
157       initial_length = elfcpp::Swap_unaligned<64, big_endian>::readval(lineptr);
158       lineptr += 8;
159     }
160   else
161     header_.offset_size = 4;
162
163   header_.total_length = initial_length;
164
165   gold_assert(lineptr + header_.total_length <= buffer_end_);
166
167   header_.version = elfcpp::Swap_unaligned<16, big_endian>::readval(lineptr);
168   lineptr += 2;
169
170   if (header_.offset_size == 4)
171     header_.prologue_length = elfcpp::Swap_unaligned<32, big_endian>::readval(lineptr);
172   else
173     header_.prologue_length = elfcpp::Swap_unaligned<64, big_endian>::readval(lineptr);
174   lineptr += header_.offset_size;
175
176   header_.min_insn_length = *lineptr;
177   lineptr += 1;
178
179   header_.default_is_stmt = *lineptr;
180   lineptr += 1;
181
182   header_.line_base = *reinterpret_cast<const signed char*>(lineptr);
183   lineptr += 1;
184
185   header_.line_range = *lineptr;
186   lineptr += 1;
187
188   header_.opcode_base = *lineptr;
189   lineptr += 1;
190
191   header_.std_opcode_lengths.reserve(header_.opcode_base + 1);
192   header_.std_opcode_lengths[0] = 0;
193   for (int i = 1; i < header_.opcode_base; i++)
194     {
195       header_.std_opcode_lengths[i] = *lineptr;
196       lineptr += 1;
197     }
198
199   return lineptr;
200 }
201
202 // The header for a debug_line section is mildly complicated, because
203 // the line info is very tightly encoded.
204
205 template<int size, bool big_endian>
206 const unsigned char*
207 Sized_dwarf_line_info<size, big_endian>::read_header_tables(
208     const unsigned char* lineptr)
209 {
210   ++this->current_header_index_;
211
212   // Create a new directories_ entry and a new files_ entry for our new
213   // header.  We initialize each with a single empty element, because
214   // dwarf indexes directory and filenames starting at 1.
215   gold_assert(static_cast<int>(this->directories_.size())
216               == this->current_header_index_);
217   gold_assert(static_cast<int>(this->files_.size())
218               == this->current_header_index_);
219   this->directories_.push_back(std::vector<std::string>(1));
220   this->files_.push_back(std::vector<std::pair<int, std::string> >(1));
221
222   // It is legal for the directory entry table to be empty.
223   if (*lineptr)
224     {
225       int dirindex = 1;
226       while (*lineptr)
227         {
228           const char* dirname = reinterpret_cast<const char*>(lineptr);
229           gold_assert(dirindex
230                       == static_cast<int>(this->directories_.back().size()));
231           this->directories_.back().push_back(dirname);
232           lineptr += this->directories_.back().back().size() + 1;
233           dirindex++;
234         }
235     }
236   lineptr++;
237
238   // It is also legal for the file entry table to be empty.
239   if (*lineptr)
240     {
241       int fileindex = 1;
242       size_t len;
243       while (*lineptr)
244         {
245           const char* filename = reinterpret_cast<const char*>(lineptr);
246           lineptr += strlen(filename) + 1;
247
248           uint64_t dirindex = read_unsigned_LEB_128(lineptr, &len);
249           lineptr += len;
250
251           if (dirindex >= this->directories_.back().size())
252             dirindex = 0;
253           int dirindexi = static_cast<int>(dirindex);
254
255           read_unsigned_LEB_128(lineptr, &len);   // mod_time
256           lineptr += len;
257
258           read_unsigned_LEB_128(lineptr, &len);   // filelength
259           lineptr += len;
260
261           gold_assert(fileindex
262                       == static_cast<int>(this->files_.back().size()));
263           this->files_.back().push_back(std::make_pair(dirindexi, filename));
264           fileindex++;
265         }
266     }
267   lineptr++;
268
269   return lineptr;
270 }
271
272 // Process a single opcode in the .debug.line structure.
273
274 // Templating on size and big_endian would yield more efficient (and
275 // simpler) code, but would bloat the binary.  Speed isn't important
276 // here.
277
278 template<int size, bool big_endian>
279 bool
280 Sized_dwarf_line_info<size, big_endian>::process_one_opcode(
281     const unsigned char* start, struct LineStateMachine* lsm, size_t* len)
282 {
283   size_t oplen = 0;
284   size_t templen;
285   unsigned char opcode = *start;
286   oplen++;
287   start++;
288
289   // If the opcode is great than the opcode_base, it is a special
290   // opcode. Most line programs consist mainly of special opcodes.
291   if (opcode >= header_.opcode_base)
292     {
293       opcode -= header_.opcode_base;
294       const int advance_address = ((opcode / header_.line_range)
295                                    * header_.min_insn_length);
296       lsm->address += advance_address;
297
298       const int advance_line = ((opcode % header_.line_range)
299                                 + header_.line_base);
300       lsm->line_num += advance_line;
301       lsm->basic_block = true;
302       *len = oplen;
303       return true;
304     }
305
306   // Otherwise, we have the regular opcodes
307   switch (opcode)
308     {
309     case elfcpp::DW_LNS_copy:
310       lsm->basic_block = false;
311       *len = oplen;
312       return true;
313
314     case elfcpp::DW_LNS_advance_pc:
315       {
316         const uint64_t advance_address
317             = read_unsigned_LEB_128(start, &templen);
318         oplen += templen;
319         lsm->address += header_.min_insn_length * advance_address;
320       }
321       break;
322
323     case elfcpp::DW_LNS_advance_line:
324       {
325         const uint64_t advance_line = read_signed_LEB_128(start, &templen);
326         oplen += templen;
327         lsm->line_num += advance_line;
328       }
329       break;
330
331     case elfcpp::DW_LNS_set_file:
332       {
333         const uint64_t fileno = read_unsigned_LEB_128(start, &templen);
334         oplen += templen;
335         lsm->file_num = fileno;
336       }
337       break;
338
339     case elfcpp::DW_LNS_set_column:
340       {
341         const uint64_t colno = read_unsigned_LEB_128(start, &templen);
342         oplen += templen;
343         lsm->column_num = colno;
344       }
345       break;
346
347     case elfcpp::DW_LNS_negate_stmt:
348       lsm->is_stmt = !lsm->is_stmt;
349       break;
350
351     case elfcpp::DW_LNS_set_basic_block:
352       lsm->basic_block = true;
353       break;
354
355     case elfcpp::DW_LNS_fixed_advance_pc:
356       {
357         int advance_address;
358         advance_address = elfcpp::Swap_unaligned<16, big_endian>::readval(start);
359         oplen += 2;
360         lsm->address += advance_address;
361       }
362       break;
363
364     case elfcpp::DW_LNS_const_add_pc:
365       {
366         const int advance_address = (header_.min_insn_length
367                                      * ((255 - header_.opcode_base)
368                                         / header_.line_range));
369         lsm->address += advance_address;
370       }
371       break;
372
373     case elfcpp::DW_LNS_extended_op:
374       {
375         const uint64_t extended_op_len
376             = read_unsigned_LEB_128(start, &templen);
377         start += templen;
378         oplen += templen + extended_op_len;
379
380         const unsigned char extended_op = *start;
381         start++;
382
383         switch (extended_op)
384           {
385           case elfcpp::DW_LNE_end_sequence:
386             // This means that the current byte is the one immediately
387             // after a set of instructions.  Record the current line
388             // for up to one less than the current address.
389             lsm->line_num = -1;
390             lsm->end_sequence = true;
391             *len = oplen;
392             return true;
393
394           case elfcpp::DW_LNE_set_address:
395             {
396               lsm->address =
397                 elfcpp::Swap_unaligned<size, big_endian>::readval(start);
398               typename Reloc_map::const_iterator it
399                   = this->reloc_map_.find(start - this->buffer_);
400               if (it != reloc_map_.end())
401                 {
402                   // If this is a SHT_RELA section, then ignore the
403                   // section contents.  This assumes that this is a
404                   // straight reloc which just uses the reloc addend.
405                   // The reloc addend has already been included in the
406                   // symbol value.
407                   if (this->track_relocs_type_ == elfcpp::SHT_RELA)
408                     lsm->address = 0;
409                   // Add in the symbol value.
410                   lsm->address += it->second.second;
411                   lsm->shndx = it->second.first;
412                 }
413               else
414                 {
415                   // If we're a normal .o file, with relocs, every
416                   // set_address should have an associated relocation.
417                   if (this->input_is_relobj())
418                     this->data_valid_ = false;
419                 }
420               break;
421             }
422           case elfcpp::DW_LNE_define_file:
423             {
424               const char* filename  = reinterpret_cast<const char*>(start);
425               templen = strlen(filename) + 1;
426               start += templen;
427
428               uint64_t dirindex = read_unsigned_LEB_128(start, &templen);
429               oplen += templen;
430
431               if (dirindex >= this->directories_.back().size())
432                 dirindex = 0;
433               int dirindexi = static_cast<int>(dirindex);
434
435               read_unsigned_LEB_128(start, &templen);   // mod_time
436               oplen += templen;
437
438               read_unsigned_LEB_128(start, &templen);   // filelength
439               oplen += templen;
440
441               this->files_.back().push_back(std::make_pair(dirindexi,
442                                                            filename));
443             }
444             break;
445           }
446       }
447       break;
448
449     default:
450       {
451         // Ignore unknown opcode  silently
452         for (int i = 0; i < header_.std_opcode_lengths[opcode]; i++)
453           {
454             size_t templen;
455             read_unsigned_LEB_128(start, &templen);
456             start += templen;
457             oplen += templen;
458           }
459       }
460       break;
461   }
462   *len = oplen;
463   return false;
464 }
465
466 // Read the debug information at LINEPTR and store it in the line
467 // number map.
468
469 template<int size, bool big_endian>
470 unsigned const char*
471 Sized_dwarf_line_info<size, big_endian>::read_lines(unsigned const char* lineptr,
472                                                     unsigned int shndx)
473 {
474   struct LineStateMachine lsm;
475
476   // LENGTHSTART is the place the length field is based on.  It is the
477   // point in the header after the initial length field.
478   const unsigned char* lengthstart = buffer_;
479
480   // In 64 bit dwarf, the initial length is 12 bytes, because of the
481   // 0xffffffff at the start.
482   if (header_.offset_size == 8)
483     lengthstart += 12;
484   else
485     lengthstart += 4;
486
487   while (lineptr < lengthstart + header_.total_length)
488     {
489       ResetLineStateMachine(&lsm, header_.default_is_stmt);
490       while (!lsm.end_sequence)
491         {
492           size_t oplength;
493           bool add_line = this->process_one_opcode(lineptr, &lsm, &oplength);
494           if (add_line
495               && (shndx == -1U || lsm.shndx == -1U || shndx == lsm.shndx))
496             {
497               Offset_to_lineno_entry entry
498                   = { lsm.address, this->current_header_index_,
499                       lsm.file_num, lsm.line_num };
500               line_number_map_[lsm.shndx].push_back(entry);
501             }
502           lineptr += oplength;
503         }
504     }
505
506   return lengthstart + header_.total_length;
507 }
508
509 // Looks in the symtab to see what section a symbol is in.
510
511 template<int size, bool big_endian>
512 unsigned int
513 Sized_dwarf_line_info<size, big_endian>::symbol_section(
514     Object* object,
515     unsigned int sym,
516     typename elfcpp::Elf_types<size>::Elf_Addr* value,
517     bool* is_ordinary)
518 {
519   const int symsize = elfcpp::Elf_sizes<size>::sym_size;
520   gold_assert(sym * symsize < this->symtab_buffer_size_);
521   elfcpp::Sym<size, big_endian> elfsym(this->symtab_buffer_ + sym * symsize);
522   *value = elfsym.get_st_value();
523   return object->adjust_sym_shndx(sym, elfsym.get_st_shndx(), is_ordinary);
524 }
525
526 // Read the relocations into a Reloc_map.
527
528 template<int size, bool big_endian>
529 void
530 Sized_dwarf_line_info<size, big_endian>::read_relocs(Object* object)
531 {
532   if (this->symtab_buffer_ == NULL)
533     return;
534
535   typename elfcpp::Elf_types<size>::Elf_Addr value;
536   off_t reloc_offset;
537   while ((reloc_offset = this->track_relocs_.next_offset()) != -1)
538     {
539       const unsigned int sym = this->track_relocs_.next_symndx();
540
541       bool is_ordinary;
542       const unsigned int shndx = this->symbol_section(object, sym, &value,
543                                                       &is_ordinary);
544
545       // There is no reason to record non-ordinary section indexes, or
546       // SHN_UNDEF, because they will never match the real section.
547       if (is_ordinary && shndx != elfcpp::SHN_UNDEF)
548         {
549           value += this->track_relocs_.next_addend();
550           this->reloc_map_[reloc_offset] = std::make_pair(shndx, value);
551         }
552
553       this->track_relocs_.advance(reloc_offset + 1);
554     }
555 }
556
557 // Read the line number info.
558
559 template<int size, bool big_endian>
560 void
561 Sized_dwarf_line_info<size, big_endian>::read_line_mappings(Object* object,
562                                                             unsigned int shndx)
563 {
564   gold_assert(this->data_valid_ == true);
565
566   this->read_relocs(object);
567   while (this->buffer_ < this->buffer_end_)
568     {
569       const unsigned char* lineptr = this->buffer_;
570       lineptr = this->read_header_prolog(lineptr);
571       lineptr = this->read_header_tables(lineptr);
572       lineptr = this->read_lines(lineptr, shndx);
573       this->buffer_ = lineptr;
574     }
575
576   // Sort the lines numbers, so addr2line can use binary search.
577   for (typename Lineno_map::iterator it = line_number_map_.begin();
578        it != line_number_map_.end();
579        ++it)
580     // Each vector needs to be sorted by offset.
581     std::sort(it->second.begin(), it->second.end());
582 }
583
584 // Some processing depends on whether the input is a .o file or not.
585 // For instance, .o files have relocs, and have .debug_lines
586 // information on a per section basis.  .so files, on the other hand,
587 // lack relocs, and offsets are unique, so we can ignore the section
588 // information.
589
590 template<int size, bool big_endian>
591 bool
592 Sized_dwarf_line_info<size, big_endian>::input_is_relobj()
593 {
594   // Only .o files have relocs and the symtab buffer that goes with them.
595   return this->symtab_buffer_ != NULL;
596 }
597
598 // Given an Offset_to_lineno_entry vector, and an offset, figure out
599 // if the offset points into a function according to the vector (see
600 // comments below for the algorithm).  If it does, return an iterator
601 // into the vector that points to the line-number that contains that
602 // offset.  If not, it returns vector::end().
603
604 static std::vector<Offset_to_lineno_entry>::const_iterator
605 offset_to_iterator(const std::vector<Offset_to_lineno_entry>* offsets,
606                    off_t offset)
607 {
608   const Offset_to_lineno_entry lookup_key = { offset, 0, 0, 0 };
609
610   // lower_bound() returns the smallest offset which is >= lookup_key.
611   // If no offset in offsets is >= lookup_key, returns end().
612   std::vector<Offset_to_lineno_entry>::const_iterator it
613       = std::lower_bound(offsets->begin(), offsets->end(), lookup_key);
614
615   // This code is easiest to understand with a concrete example.
616   // Here's a possible offsets array:
617   // {{offset = 3211, header_num = 0, file_num = 1, line_num = 16},  // 0
618   //  {offset = 3224, header_num = 0, file_num = 1, line_num = 20},  // 1
619   //  {offset = 3226, header_num = 0, file_num = 1, line_num = 22},  // 2
620   //  {offset = 3231, header_num = 0, file_num = 1, line_num = 25},  // 3
621   //  {offset = 3232, header_num = 0, file_num = 1, line_num = -1},  // 4
622   //  {offset = 3232, header_num = 0, file_num = 1, line_num = 65},  // 5
623   //  {offset = 3235, header_num = 0, file_num = 1, line_num = 66},  // 6
624   //  {offset = 3236, header_num = 0, file_num = 1, line_num = -1},  // 7
625   //  {offset = 5764, header_num = 0, file_num = 1, line_num = 47},  // 8
626   //  {offset = 5765, header_num = 0, file_num = 1, line_num = 48},  // 9
627   //  {offset = 5767, header_num = 0, file_num = 1, line_num = 49},  // 10
628   //  {offset = 5768, header_num = 0, file_num = 1, line_num = 50},  // 11
629   //  {offset = 5773, header_num = 0, file_num = 1, line_num = -1},  // 12
630   //  {offset = 5787, header_num = 1, file_num = 1, line_num = 19},  // 13
631   //  {offset = 5790, header_num = 1, file_num = 1, line_num = 20},  // 14
632   //  {offset = 5793, header_num = 1, file_num = 1, line_num = 67},  // 15
633   //  {offset = 5793, header_num = 1, file_num = 1, line_num = -1},  // 16
634   //  {offset = 5795, header_num = 1, file_num = 1, line_num = 68},  // 17
635   //  {offset = 5798, header_num = 1, file_num = 1, line_num = -1},  // 18
636   // The entries with line_num == -1 mark the end of a function: the
637   // associated offset is one past the last instruction in the
638   // function.  This can correspond to the beginning of the next
639   // function (as is true for offset 3232); alternately, there can be
640   // a gap between the end of one function and the start of the next
641   // (as is true for some others, most obviously from 3236->5764).
642   //
643   // Case 1: lookup_key has offset == 10.  lower_bound returns
644   //         offsets[0].  Since it's not an exact match and we're
645   //         at the beginning of offsets, we return end() (invalid).
646   // Case 2: lookup_key has offset 10000.  lower_bound returns
647   //         offset[19] (end()).  We return end() (invalid).
648   // Case 3: lookup_key has offset == 3211.  lower_bound matches
649   //         offsets[0] exactly, and that's the entry we return.
650   // Case 4: lookup_key has offset == 3232.  lower_bound returns
651   //         offsets[4].  That's an exact match, but indicates
652   //         end-of-function.  We check if offsets[5] is also an
653   //         exact match but not end-of-function.  It is, so we
654   //         return offsets[5].
655   // Case 5: lookup_key has offset == 3214.  lower_bound returns
656   //         offsets[1].  Since it's not an exact match, we back
657   //         up to the offset that's < lookup_key, offsets[0].
658   //         We note offsets[0] is a valid entry (not end-of-function),
659   //         so that's the entry we return.
660   // Case 6: lookup_key has offset == 4000.  lower_bound returns
661   //         offsets[8].  Since it's not an exact match, we back
662   //         up to offsets[7].  Since offsets[7] indicates
663   //         end-of-function, we know lookup_key is between
664   //         functions, so we return end() (not a valid offset).
665   // Case 7: lookup_key has offset == 5794.  lower_bound returns
666   //         offsets[17].  Since it's not an exact match, we back
667   //         up to offsets[15].  Note we back up to the *first*
668   //         entry with offset 5793, not just offsets[17-1].
669   //         We note offsets[15] is a valid entry, so we return it.
670   //         If offsets[15] had had line_num == -1, we would have
671   //         checked offsets[16].  The reason for this is that
672   //         15 and 16 can be in an arbitrary order, since we sort
673   //         only by offset.  (Note it doesn't help to use line_number
674   //         as a secondary sort key, since sometimes we want the -1
675   //         to be first and sometimes we want it to be last.)
676
677   // This deals with cases (1) and (2).
678   if ((it == offsets->begin() && offset < it->offset)
679       || it == offsets->end())
680     return offsets->end();
681
682   // This deals with cases (3) and (4).
683   if (offset == it->offset)
684     {
685       while (it != offsets->end()
686              && it->offset == offset
687              && it->line_num == -1)
688         ++it;
689       if (it == offsets->end() || it->offset != offset)
690         return offsets->end();
691       else
692         return it;
693     }
694
695   // This handles the first part of case (7) -- we back up to the
696   // *first* entry that has the offset that's behind us.
697   gold_assert(it != offsets->begin());
698   std::vector<Offset_to_lineno_entry>::const_iterator range_end = it;
699   --it;
700   const off_t range_value = it->offset;
701   while (it != offsets->begin() && (it-1)->offset == range_value)
702     --it;
703
704   // This handles cases (5), (6), and (7): if any entry in the
705   // equal_range [it, range_end) has a line_num != -1, it's a valid
706   // match.  If not, we're not in a function.
707   for (; it != range_end; ++it)
708     if (it->line_num != -1)
709       return it;
710   return offsets->end();
711 }
712
713 // Return a string for a file name and line number.
714
715 template<int size, bool big_endian>
716 std::string
717 Sized_dwarf_line_info<size, big_endian>::do_addr2line(unsigned int shndx,
718                                                       off_t offset)
719 {
720   if (this->data_valid_ == false)
721     return "";
722
723   const std::vector<Offset_to_lineno_entry>* offsets;
724   // If we do not have reloc information, then our input is a .so or
725   // some similar data structure where all the information is held in
726   // the offset.  In that case, we ignore the input shndx.
727   if (this->input_is_relobj())
728     offsets = &this->line_number_map_[shndx];
729   else
730     offsets = &this->line_number_map_[-1U];
731   if (offsets->empty())
732     return "";
733
734   typename std::vector<Offset_to_lineno_entry>::const_iterator it
735       = offset_to_iterator(offsets, offset);
736   if (it == offsets->end())
737     return "";
738
739   // Convert the file_num + line_num into a string.
740   std::string ret;
741
742   gold_assert(it->header_num < static_cast<int>(this->files_.size()));
743   gold_assert(it->file_num
744               < static_cast<int>(this->files_[it->header_num].size()));
745   const std::pair<int, std::string>& filename_pair
746       = this->files_[it->header_num][it->file_num];
747   const std::string& filename = filename_pair.second;
748
749   gold_assert(it->header_num < static_cast<int>(this->directories_.size()));
750   gold_assert(filename_pair.first
751               < static_cast<int>(this->directories_[it->header_num].size()));
752   const std::string& dirname
753       = this->directories_[it->header_num][filename_pair.first];
754
755   if (!dirname.empty())
756     {
757       ret += dirname;
758       ret += "/";
759     }
760   ret += filename;
761   if (ret.empty())
762     ret = "(unknown)";
763
764   char buffer[64];   // enough to hold a line number
765   snprintf(buffer, sizeof(buffer), "%d", it->line_num);
766   ret += ":";
767   ret += buffer;
768
769   return ret;
770 }
771
772 // Dwarf_line_info routines.
773
774 static unsigned int next_generation_count = 0;
775
776 struct Addr2line_cache_entry
777 {
778   Object* object;
779   unsigned int shndx;
780   Dwarf_line_info* dwarf_line_info;
781   unsigned int generation_count;
782   unsigned int access_count;
783
784   Addr2line_cache_entry(Object* o, unsigned int s, Dwarf_line_info* d)
785       : object(o), shndx(s), dwarf_line_info(d),
786         generation_count(next_generation_count), access_count(0)
787   {
788     if (next_generation_count < (1U << 31))
789       ++next_generation_count;
790   }
791 };
792 // We expect this cache to be small, so don't bother with a hashtable
793 // or priority queue or anything: just use a simple vector.
794 static std::vector<Addr2line_cache_entry> addr2line_cache;
795
796 std::string
797 Dwarf_line_info::one_addr2line(Object* object,
798                                unsigned int shndx, off_t offset,
799                                size_t cache_size)
800 {
801   Dwarf_line_info* lineinfo = NULL;
802   std::vector<Addr2line_cache_entry>::iterator it;
803
804   // First, check the cache.  If we hit, update the counts.
805   for (it = addr2line_cache.begin(); it != addr2line_cache.end(); ++it)
806     {
807       if (it->object == object && it->shndx == shndx)
808         {
809           lineinfo = it->dwarf_line_info;
810           it->generation_count = next_generation_count;
811           // We cap generation_count at 2^31 -1 to avoid overflow.
812           if (next_generation_count < (1U << 31))
813             ++next_generation_count;
814           // We cap access_count at 31 so 2^access_count doesn't overflow
815           if (it->access_count < 31)
816             ++it->access_count;
817           break;
818         }
819     }
820
821   // If we don't hit the cache, create a new object and insert into the
822   // cache.
823   if (lineinfo == NULL)
824   {
825     switch (parameters->size_and_endianness())
826       {
827 #ifdef HAVE_TARGET_32_LITTLE
828         case Parameters::TARGET_32_LITTLE:
829           lineinfo = new Sized_dwarf_line_info<32, false>(object, shndx); break;
830 #endif
831 #ifdef HAVE_TARGET_32_BIG
832         case Parameters::TARGET_32_BIG:
833           lineinfo = new Sized_dwarf_line_info<32, true>(object, shndx); break;
834 #endif
835 #ifdef HAVE_TARGET_64_LITTLE
836         case Parameters::TARGET_64_LITTLE:
837           lineinfo = new Sized_dwarf_line_info<64, false>(object, shndx); break;
838 #endif
839 #ifdef HAVE_TARGET_64_BIG
840         case Parameters::TARGET_64_BIG:
841           lineinfo = new Sized_dwarf_line_info<64, true>(object, shndx); break;
842 #endif
843         default:
844           gold_unreachable();
845       }
846     addr2line_cache.push_back(Addr2line_cache_entry(object, shndx, lineinfo));
847   }
848
849   // Now that we have our object, figure out the answer
850   std::string retval = lineinfo->addr2line(shndx, offset);
851
852   // Finally, if our cache has grown too big, delete old objects.  We
853   // assume the common (probably only) case is deleting only one object.
854   // We use a pretty simple scheme to evict: function of LRU and MFU.
855   while (addr2line_cache.size() > cache_size)
856     {
857       unsigned int lowest_score = ~0U;
858       std::vector<Addr2line_cache_entry>::iterator lowest
859           = addr2line_cache.end();
860       for (it = addr2line_cache.begin(); it != addr2line_cache.end(); ++it)
861         {
862           const unsigned int score = (it->generation_count
863                                       + (1U << it->access_count));
864           if (score < lowest_score)
865             {
866               lowest_score = score;
867               lowest = it;
868             }
869         }
870       if (lowest != addr2line_cache.end())
871         {
872           delete lowest->dwarf_line_info;
873           addr2line_cache.erase(lowest);
874         }
875     }
876
877   return retval;
878 }
879
880 void
881 Dwarf_line_info::clear_addr2line_cache()
882 {
883   for (std::vector<Addr2line_cache_entry>::iterator it = addr2line_cache.begin();
884        it != addr2line_cache.end();
885        ++it)
886     delete it->dwarf_line_info;
887   addr2line_cache.clear();
888 }
889
890 #ifdef HAVE_TARGET_32_LITTLE
891 template
892 class Sized_dwarf_line_info<32, false>;
893 #endif
894
895 #ifdef HAVE_TARGET_32_BIG
896 template
897 class Sized_dwarf_line_info<32, true>;
898 #endif
899
900 #ifdef HAVE_TARGET_64_LITTLE
901 template
902 class Sized_dwarf_line_info<64, false>;
903 #endif
904
905 #ifdef HAVE_TARGET_64_BIG
906 template
907 class Sized_dwarf_line_info<64, true>;
908 #endif
909
910 } // End namespace gold.