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