OSDN Git Service

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