* target.h (Target::plt_fde_location, do_plt_fde_location): Declare.
[external/binutils.git] / gold / ehframe.cc
1 // ehframe.cc -- handle exception frame sections for gold
2
3 // Copyright 2006, 2007, 2008, 2010, 2011, 2012 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 <cstring>
26 #include <algorithm>
27
28 #include "elfcpp.h"
29 #include "dwarf.h"
30 #include "symtab.h"
31 #include "reloc.h"
32 #include "ehframe.h"
33
34 namespace gold
35 {
36
37 // This file handles generation of the exception frame header that
38 // gcc's runtime support libraries use to find unwind information at
39 // runtime.  This file also handles discarding duplicate exception
40 // frame information.
41
42 // The exception frame header starts with four bytes:
43
44 // 0: The version number, currently 1.
45
46 // 1: The encoding of the pointer to the exception frames.  This can
47 //    be any DWARF unwind encoding (DW_EH_PE_*).  It is normally a 4
48 //    byte PC relative offset (DW_EH_PE_pcrel | DW_EH_PE_sdata4).
49
50 // 2: The encoding of the count of the number of FDE pointers in the
51 //    lookup table.  This can be any DWARF unwind encoding, and in
52 //    particular can be DW_EH_PE_omit if the count is omitted.  It is
53 //    normally a 4 byte unsigned count (DW_EH_PE_udata4).
54
55 // 3: The encoding of the lookup table entries.  Currently gcc's
56 //    libraries will only support DW_EH_PE_datarel | DW_EH_PE_sdata4,
57 //    which means that the values are 4 byte offsets from the start of
58 //    the table.
59
60 // The exception frame header is followed by a pointer to the contents
61 // of the exception frame section (.eh_frame).  This pointer is
62 // encoded as specified in the byte at offset 1 of the header (i.e.,
63 // it is normally a 4 byte PC relative offset).
64
65 // If there is a lookup table, this is followed by the count of the
66 // number of FDE pointers, encoded as specified in the byte at offset
67 // 2 of the header (i.e., normally a 4 byte unsigned integer).
68
69 // This is followed by the table, which should start at an 4-byte
70 // aligned address in memory.  Each entry in the table is 8 bytes.
71 // Each entry represents an FDE.  The first four bytes of each entry
72 // are an offset to the starting PC for the FDE.  The last four bytes
73 // of each entry are an offset to the FDE data.  The offsets are from
74 // the start of the exception frame header information.  The entries
75 // are in sorted order by starting PC.
76
77 const int eh_frame_hdr_size = 4;
78
79 // Construct the exception frame header.
80
81 Eh_frame_hdr::Eh_frame_hdr(Output_section* eh_frame_section,
82                            const Eh_frame* eh_frame_data)
83   : Output_section_data(4),
84     eh_frame_section_(eh_frame_section),
85     eh_frame_data_(eh_frame_data),
86     fde_offsets_(),
87     any_unrecognized_eh_frame_sections_(false)
88 {
89 }
90
91 // Set the size of the exception frame header.
92
93 void
94 Eh_frame_hdr::set_final_data_size()
95 {
96   unsigned int data_size = eh_frame_hdr_size + 4;
97   if (!this->any_unrecognized_eh_frame_sections_)
98     {
99       unsigned int fde_count = this->eh_frame_data_->fde_count();
100       if (fde_count != 0)
101         data_size += 4 + 8 * fde_count;
102       this->fde_offsets_.reserve(fde_count);
103     }
104   this->set_data_size(data_size);
105 }
106
107 // Write the data to the file.
108
109 void
110 Eh_frame_hdr::do_write(Output_file* of)
111 {
112   switch (parameters->size_and_endianness())
113     {
114 #ifdef HAVE_TARGET_32_LITTLE
115     case Parameters::TARGET_32_LITTLE:
116       this->do_sized_write<32, false>(of);
117       break;
118 #endif
119 #ifdef HAVE_TARGET_32_BIG
120     case Parameters::TARGET_32_BIG:
121       this->do_sized_write<32, true>(of);
122       break;
123 #endif
124 #ifdef HAVE_TARGET_64_LITTLE
125     case Parameters::TARGET_64_LITTLE:
126       this->do_sized_write<64, false>(of);
127       break;
128 #endif
129 #ifdef HAVE_TARGET_64_BIG
130     case Parameters::TARGET_64_BIG:
131       this->do_sized_write<64, true>(of);
132       break;
133 #endif
134     default:
135       gold_unreachable();
136     }
137 }
138
139 // Write the data to the file with the right endianness.
140
141 template<int size, bool big_endian>
142 void
143 Eh_frame_hdr::do_sized_write(Output_file* of)
144 {
145   const off_t off = this->offset();
146   const off_t oview_size = this->data_size();
147   unsigned char* const oview = of->get_output_view(off, oview_size);
148
149   // Version number.
150   oview[0] = 1;
151
152   // Write out a 4 byte PC relative offset to the address of the
153   // .eh_frame section.
154   oview[1] = elfcpp::DW_EH_PE_pcrel | elfcpp::DW_EH_PE_sdata4;
155   uint64_t eh_frame_address = this->eh_frame_section_->address();
156   uint64_t eh_frame_hdr_address = this->address();
157   uint64_t eh_frame_offset = (eh_frame_address -
158                               (eh_frame_hdr_address + 4));
159   elfcpp::Swap<32, big_endian>::writeval(oview + 4, eh_frame_offset);
160
161   if (this->any_unrecognized_eh_frame_sections_
162       || this->fde_offsets_.empty())
163     {
164       // There are no FDEs, or we didn't recognize the format of the
165       // some of the .eh_frame sections, so we can't write out the
166       // sorted table.
167       oview[2] = elfcpp::DW_EH_PE_omit;
168       oview[3] = elfcpp::DW_EH_PE_omit;
169
170       gold_assert(oview_size == 8);
171     }
172   else
173     {
174       oview[2] = elfcpp::DW_EH_PE_udata4;
175       oview[3] = elfcpp::DW_EH_PE_datarel | elfcpp::DW_EH_PE_sdata4;
176
177       elfcpp::Swap<32, big_endian>::writeval(oview + 8,
178                                              this->fde_offsets_.size());
179
180       // We have the offsets of the FDEs in the .eh_frame section.  We
181       // couldn't easily get the PC values before, as they depend on
182       // relocations which are, of course, target specific.  This code
183       // is run after all those relocations have been applied to the
184       // output file.  Here we read the output file again to find the
185       // PC values.  Then we sort the list and write it out.
186
187       Fde_addresses<size> fde_addresses(this->fde_offsets_.size());
188       this->get_fde_addresses<size, big_endian>(of, &this->fde_offsets_,
189                                                 &fde_addresses);
190
191       std::sort(fde_addresses.begin(), fde_addresses.end(),
192                 Fde_address_compare<size>());
193
194       typename elfcpp::Elf_types<size>::Elf_Addr output_address;
195       output_address = this->address();
196
197       unsigned char* pfde = oview + 12;
198       for (typename Fde_addresses<size>::iterator p = fde_addresses.begin();
199            p != fde_addresses.end();
200            ++p)
201         {
202           elfcpp::Swap<32, big_endian>::writeval(pfde,
203                                                  p->first - output_address);
204           elfcpp::Swap<32, big_endian>::writeval(pfde + 4,
205                                                  p->second - output_address);
206           pfde += 8;
207         }
208
209       gold_assert(pfde - oview == oview_size);
210     }
211
212   of->write_output_view(off, oview_size, oview);
213 }
214
215 // Given the offset FDE_OFFSET of an FDE in the .eh_frame section, and
216 // the contents of the .eh_frame section EH_FRAME_CONTENTS, where the
217 // FDE's encoding is FDE_ENCODING, return the output address of the
218 // FDE's PC.
219
220 template<int size, bool big_endian>
221 typename elfcpp::Elf_types<size>::Elf_Addr
222 Eh_frame_hdr::get_fde_pc(
223     typename elfcpp::Elf_types<size>::Elf_Addr eh_frame_address,
224     const unsigned char* eh_frame_contents,
225     section_offset_type fde_offset,
226     unsigned char fde_encoding)
227 {
228   // The FDE starts with a 4 byte length and a 4 byte offset to the
229   // CIE.  The PC follows.
230   const unsigned char* p = eh_frame_contents + fde_offset + 8;
231
232   typename elfcpp::Elf_types<size>::Elf_Addr pc;
233   bool is_signed = (fde_encoding & elfcpp::DW_EH_PE_signed) != 0;
234   int pc_size = fde_encoding & 7;
235   if (pc_size == elfcpp::DW_EH_PE_absptr)
236     {
237       if (size == 32)
238         pc_size = elfcpp::DW_EH_PE_udata4;
239       else if (size == 64)
240         pc_size = elfcpp::DW_EH_PE_udata8;
241       else
242         gold_unreachable();
243     }
244
245   switch (pc_size)
246     {
247     case elfcpp::DW_EH_PE_udata2:
248       pc = elfcpp::Swap<16, big_endian>::readval(p);
249       if (is_signed)
250         pc = (pc ^ 0x8000) - 0x8000;
251       break;
252
253     case elfcpp::DW_EH_PE_udata4:
254       pc = elfcpp::Swap<32, big_endian>::readval(p);
255       if (size > 32 && is_signed)
256         pc = (pc ^ 0x80000000) - 0x80000000;
257       break;
258
259     case elfcpp::DW_EH_PE_udata8:
260       gold_assert(size == 64);
261       pc = elfcpp::Swap_unaligned<64, big_endian>::readval(p);
262       break;
263
264     default:
265       // All other cases were rejected in Eh_frame::read_cie.
266       gold_unreachable();
267     }
268
269   switch (fde_encoding & 0x70)
270     {
271     case 0:
272       break;
273
274     case elfcpp::DW_EH_PE_pcrel:
275       pc += eh_frame_address + fde_offset + 8;
276       break;
277
278     case elfcpp::DW_EH_PE_datarel:
279       pc += parameters->target().ehframe_datarel_base();
280       break;
281
282     default:
283       // If other cases arise, then we have to handle them, or we have
284       // to reject them by returning false in Eh_frame::read_cie.
285       gold_unreachable();
286     }
287
288   gold_assert((fde_encoding & elfcpp::DW_EH_PE_indirect) == 0);
289
290   return pc;
291 }
292
293 // Given an array of FDE offsets in the .eh_frame section, return an
294 // array of offsets from the exception frame header to the FDE's
295 // output PC and to the output address of the FDE itself.  We get the
296 // FDE's PC by actually looking in the .eh_frame section we just wrote
297 // to the output file.
298
299 template<int size, bool big_endian>
300 void
301 Eh_frame_hdr::get_fde_addresses(Output_file* of,
302                                 const Fde_offsets* fde_offsets,
303                                 Fde_addresses<size>* fde_addresses)
304 {
305   typename elfcpp::Elf_types<size>::Elf_Addr eh_frame_address;
306   eh_frame_address = this->eh_frame_section_->address();
307   off_t eh_frame_offset = this->eh_frame_section_->offset();
308   off_t eh_frame_size = this->eh_frame_section_->data_size();
309   const unsigned char* eh_frame_contents = of->get_input_view(eh_frame_offset,
310                                                               eh_frame_size);
311
312   for (Fde_offsets::const_iterator p = fde_offsets->begin();
313        p != fde_offsets->end();
314        ++p)
315     {
316       typename elfcpp::Elf_types<size>::Elf_Addr fde_pc;
317       fde_pc = this->get_fde_pc<size, big_endian>(eh_frame_address,
318                                                   eh_frame_contents,
319                                                   p->first, p->second);
320       fde_addresses->push_back(fde_pc, eh_frame_address + p->first);
321     }
322
323   of->free_input_view(eh_frame_offset, eh_frame_size, eh_frame_contents);
324 }
325
326 // Class Fde.
327
328 // Write the FDE to OVIEW starting at OFFSET.  CIE_OFFSET is the
329 // offset of the CIE in OVIEW.  FDE_ENCODING is the encoding, from the
330 // CIE.  ADDRALIGN is the required alignment.  ADDRESS is the virtual
331 // address of OVIEW.  Record the FDE pc for EH_FRAME_HDR.  Return the
332 // new offset.
333
334 template<int size, bool big_endian>
335 section_offset_type
336 Fde::write(unsigned char* oview, section_offset_type offset,
337            uint64_t address, unsigned int addralign,
338            section_offset_type cie_offset, unsigned char fde_encoding,
339            Eh_frame_hdr* eh_frame_hdr)
340 {
341   gold_assert((offset & (addralign - 1)) == 0);
342
343   size_t length = this->contents_.length();
344
345   // We add 8 when getting the aligned length to account for the
346   // length word and the CIE offset.
347   size_t aligned_full_length = align_address(length + 8, addralign);
348
349   // Write the length of the FDE as a 32-bit word.  The length word
350   // does not include the four bytes of the length word itself, but it
351   // does include the offset to the CIE.
352   elfcpp::Swap<32, big_endian>::writeval(oview + offset,
353                                          aligned_full_length - 4);
354
355   // Write the offset to the CIE as a 32-bit word.  This is the
356   // difference between the address of the offset word itself and the
357   // CIE address.
358   elfcpp::Swap<32, big_endian>::writeval(oview + offset + 4,
359                                          offset + 4 - cie_offset);
360
361   // Copy the rest of the FDE.  Note that this is run before
362   // relocation processing is done on this section, so the relocations
363   // will later be applied to the FDE data.
364   memcpy(oview + offset + 8, this->contents_.data(), length);
365
366   // If this FDE is associated with a PLT, fill in the PLT's address
367   // and size.
368   if (this->object_ == NULL)
369     {
370       gold_assert(memcmp(oview + offset + 8, "\0\0\0\0\0\0\0\0", 8) == 0);
371       uint64_t paddress;
372       off_t psize;
373       parameters->target().plt_fde_location(this->u_.from_linker.plt,
374                                             oview + offset + 8,
375                                             &paddress, &psize);
376       uint64_t poffset = paddress - (address + offset + 8);
377       int32_t spoffset = static_cast<int32_t>(poffset);
378       uint32_t upsize = static_cast<uint32_t>(psize);
379       if (static_cast<uint64_t>(static_cast<int64_t>(spoffset)) != poffset
380           || static_cast<off_t>(upsize) != psize)
381         gold_warning(_("overflow in PLT unwind data; "
382                        "unwinding through PLT may fail"));
383       elfcpp::Swap<32, big_endian>::writeval(oview + offset + 8, spoffset);
384       elfcpp::Swap<32, big_endian>::writeval(oview + offset + 12, upsize);
385     }
386
387   if (aligned_full_length > length + 8)
388     memset(oview + offset + length + 8, 0, aligned_full_length - (length + 8));
389
390   // Tell the exception frame header about this FDE.
391   if (eh_frame_hdr != NULL)
392     eh_frame_hdr->record_fde(offset, fde_encoding);
393
394   return offset + aligned_full_length;
395 }
396
397 // Class Cie.
398
399 // Destructor.
400
401 Cie::~Cie()
402 {
403   for (std::vector<Fde*>::iterator p = this->fdes_.begin();
404        p != this->fdes_.end();
405        ++p)
406     delete *p;
407 }
408
409 // Set the output offset of a CIE.  Return the new output offset.
410
411 section_offset_type
412 Cie::set_output_offset(section_offset_type output_offset,
413                        unsigned int addralign,
414                        Merge_map* merge_map)
415 {
416   size_t length = this->contents_.length();
417
418   // Add 4 for length and 4 for zero CIE identifier tag.
419   length += 8;
420
421   if (this->object_ != NULL)
422     {
423       // Add a mapping so that relocations are applied correctly.
424       merge_map->add_mapping(this->object_, this->shndx_, this->input_offset_,
425                              length, output_offset);
426     }
427
428   length = align_address(length, addralign);
429
430   for (std::vector<Fde*>::const_iterator p = this->fdes_.begin();
431        p != this->fdes_.end();
432        ++p)
433     {
434       (*p)->add_mapping(output_offset + length, merge_map);
435
436       size_t fde_length = (*p)->length();
437       fde_length = align_address(fde_length, addralign);
438       length += fde_length;
439     }
440
441   return output_offset + length;
442 }
443
444 // A FDE plus some info from a CIE to allow later writing of the FDE.
445
446 struct Post_fde
447 {
448   Post_fde(Fde* f, section_offset_type cie_off, unsigned char encoding)
449     : fde(f), cie_offset(cie_off), fde_encoding(encoding)
450   { }
451
452   Fde* fde;
453   section_offset_type cie_offset;
454   unsigned char fde_encoding;
455 };
456
457 // Write the CIE to OVIEW starting at OFFSET.  Round up the bytes to
458 // ADDRALIGN.  ADDRESS is the virtual address of OVIEW.
459 // EH_FRAME_HDR is the exception frame header for FDE recording.
460 // POST_FDES stashes FDEs created after mappings were done, for later
461 // writing.  Return the new offset.
462
463 template<int size, bool big_endian>
464 section_offset_type
465 Cie::write(unsigned char* oview, section_offset_type offset,
466            uint64_t address, unsigned int addralign,
467            Eh_frame_hdr* eh_frame_hdr, Post_fdes* post_fdes)
468 {
469   gold_assert((offset & (addralign - 1)) == 0);
470
471   section_offset_type cie_offset = offset;
472
473   size_t length = this->contents_.length();
474
475   // We add 8 when getting the aligned length to account for the
476   // length word and the CIE tag.
477   size_t aligned_full_length = align_address(length + 8, addralign);
478
479   // Write the length of the CIE as a 32-bit word.  The length word
480   // does not include the four bytes of the length word itself.
481   elfcpp::Swap<32, big_endian>::writeval(oview + offset,
482                                          aligned_full_length - 4);
483
484   // Write the tag which marks this as a CIE: a 32-bit zero.
485   elfcpp::Swap<32, big_endian>::writeval(oview + offset + 4, 0);
486
487   // Write out the CIE data.
488   memcpy(oview + offset + 8, this->contents_.data(), length);
489
490   if (aligned_full_length > length + 8)
491     memset(oview + offset + length + 8, 0, aligned_full_length - (length + 8));
492
493   offset += aligned_full_length;
494
495   // Write out the associated FDEs.
496   unsigned char fde_encoding = this->fde_encoding_;
497   for (std::vector<Fde*>::const_iterator p = this->fdes_.begin();
498        p != this->fdes_.end();
499        ++p)
500     {
501       if ((*p)->post_map())
502         post_fdes->push_back(new Post_fde(*p, cie_offset, fde_encoding));
503       else
504         offset = (*p)->write<size, big_endian>(oview, offset, address,
505                                                addralign, cie_offset,
506                                                fde_encoding, eh_frame_hdr);
507     }
508
509   return offset;
510 }
511
512 // We track all the CIEs we see, and merge them when possible.  This
513 // works because each FDE holds an offset to the relevant CIE: we
514 // rewrite the FDEs to point to the merged CIE.  This is worthwhile
515 // because in a typical C++ program many FDEs in many different object
516 // files will use the same CIE.
517
518 // An equality operator for Cie.
519
520 bool
521 operator==(const Cie& cie1, const Cie& cie2)
522 {
523   return (cie1.personality_name_ == cie2.personality_name_
524           && cie1.contents_ == cie2.contents_);
525 }
526
527 // A less-than operator for Cie.
528
529 bool
530 operator<(const Cie& cie1, const Cie& cie2)
531 {
532   if (cie1.personality_name_ != cie2.personality_name_)
533     return cie1.personality_name_ < cie2.personality_name_;
534   return cie1.contents_ < cie2.contents_;
535 }
536
537 // Class Eh_frame.
538
539 Eh_frame::Eh_frame()
540   : Output_section_data(Output_data::default_alignment()),
541     eh_frame_hdr_(NULL),
542     cie_offsets_(),
543     unmergeable_cie_offsets_(),
544     merge_map_(),
545     mappings_are_done_(false),
546     final_data_size_(0)
547 {
548 }
549
550 // Skip an LEB128, updating *PP to point to the next character.
551 // Return false if we ran off the end of the string.
552
553 bool
554 Eh_frame::skip_leb128(const unsigned char** pp, const unsigned char* pend)
555 {
556   const unsigned char* p;
557   for (p = *pp; p < pend; ++p)
558     {
559       if ((*p & 0x80) == 0)
560         {
561           *pp = p + 1;
562           return true;
563         }
564     }
565   return false;
566 }
567
568 // Add input section SHNDX in OBJECT to an exception frame section.
569 // SYMBOLS is the contents of the symbol table section (size
570 // SYMBOLS_SIZE), SYMBOL_NAMES is the symbol names section (size
571 // SYMBOL_NAMES_SIZE).  RELOC_SHNDX is the index of a relocation
572 // section applying to SHNDX, or 0 if none, or -1U if more than one.
573 // RELOC_TYPE is the type of the reloc section if there is one, either
574 // SHT_REL or SHT_RELA.  We try to parse the input exception frame
575 // data into our data structures.  If we can't do it, we return false
576 // to mean that the section should be handled as a normal input
577 // section.
578
579 template<int size, bool big_endian>
580 bool
581 Eh_frame::add_ehframe_input_section(
582     Sized_relobj_file<size, big_endian>* object,
583     const unsigned char* symbols,
584     section_size_type symbols_size,
585     const unsigned char* symbol_names,
586     section_size_type symbol_names_size,
587     unsigned int shndx,
588     unsigned int reloc_shndx,
589     unsigned int reloc_type)
590 {
591   // Get the section contents.
592   section_size_type contents_len;
593   const unsigned char* pcontents = object->section_contents(shndx,
594                                                             &contents_len,
595                                                             false);
596   if (contents_len == 0)
597     return false;
598
599   // If this is the marker section for the end of the data, then
600   // return false to force it to be handled as an ordinary input
601   // section.  If we don't do this, we won't correctly handle the case
602   // of unrecognized .eh_frame sections.
603   if (contents_len == 4
604       && elfcpp::Swap<32, big_endian>::readval(pcontents) == 0)
605     return false;
606
607   New_cies new_cies;
608   if (!this->do_add_ehframe_input_section(object, symbols, symbols_size,
609                                           symbol_names, symbol_names_size,
610                                           shndx, reloc_shndx,
611                                           reloc_type, pcontents,
612                                           contents_len, &new_cies))
613     {
614       if (this->eh_frame_hdr_ != NULL)
615         this->eh_frame_hdr_->found_unrecognized_eh_frame_section();
616
617       for (New_cies::iterator p = new_cies.begin();
618            p != new_cies.end();
619            ++p)
620         delete p->first;
621
622       return false;
623     }
624
625   // Now that we know we are using this section, record any new CIEs
626   // that we found.
627   for (New_cies::const_iterator p = new_cies.begin();
628        p != new_cies.end();
629        ++p)
630     {
631       if (p->second)
632         this->cie_offsets_.insert(p->first);
633       else
634         this->unmergeable_cie_offsets_.push_back(p->first);
635     }
636
637   return true;
638 }
639
640 // The bulk of the implementation of add_ehframe_input_section.
641
642 template<int size, bool big_endian>
643 bool
644 Eh_frame::do_add_ehframe_input_section(
645     Sized_relobj_file<size, big_endian>* object,
646     const unsigned char* symbols,
647     section_size_type symbols_size,
648     const unsigned char* symbol_names,
649     section_size_type symbol_names_size,
650     unsigned int shndx,
651     unsigned int reloc_shndx,
652     unsigned int reloc_type,
653     const unsigned char* pcontents,
654     section_size_type contents_len,
655     New_cies* new_cies)
656 {
657   Track_relocs<size, big_endian> relocs;
658
659   const unsigned char* p = pcontents;
660   const unsigned char* pend = p + contents_len;
661
662   // Get the contents of the reloc section if any.
663   if (!relocs.initialize(object, reloc_shndx, reloc_type))
664     return false;
665
666   // Keep track of which CIEs are at which offsets.
667   Offsets_to_cie cies;
668
669   while (p < pend)
670     {
671       if (pend - p < 4)
672         return false;
673
674       // There shouldn't be any relocations here.
675       if (relocs.advance(p + 4 - pcontents) > 0)
676         return false;
677
678       unsigned int len = elfcpp::Swap<32, big_endian>::readval(p);
679       p += 4;
680       if (len == 0)
681         {
682           // We should only find a zero-length entry at the end of the
683           // section.
684           if (p < pend)
685             return false;
686           break;
687         }
688       // We don't support a 64-bit .eh_frame.
689       if (len == 0xffffffff)
690         return false;
691       if (static_cast<unsigned int>(pend - p) < len)
692         return false;
693
694       const unsigned char* const pentend = p + len;
695
696       if (pend - p < 4)
697         return false;
698       if (relocs.advance(p + 4 - pcontents) > 0)
699         return false;
700
701       unsigned int id = elfcpp::Swap<32, big_endian>::readval(p);
702       p += 4;
703
704       if (id == 0)
705         {
706           // CIE.
707           if (!this->read_cie(object, shndx, symbols, symbols_size,
708                               symbol_names, symbol_names_size,
709                               pcontents, p, pentend, &relocs, &cies,
710                               new_cies))
711             return false;
712         }
713       else
714         {
715           // FDE.
716           if (!this->read_fde(object, shndx, symbols, symbols_size,
717                               pcontents, id, p, pentend, &relocs, &cies))
718             return false;
719         }
720
721       p = pentend;
722     }
723
724   return true;
725 }
726
727 // Read a CIE.  Return false if we can't parse the information.
728
729 template<int size, bool big_endian>
730 bool
731 Eh_frame::read_cie(Sized_relobj_file<size, big_endian>* object,
732                    unsigned int shndx,
733                    const unsigned char* symbols,
734                    section_size_type symbols_size,
735                    const unsigned char* symbol_names,
736                    section_size_type symbol_names_size,
737                    const unsigned char* pcontents,
738                    const unsigned char* pcie,
739                    const unsigned char* pcieend,
740                    Track_relocs<size, big_endian>* relocs,
741                    Offsets_to_cie* cies,
742                    New_cies* new_cies)
743 {
744   bool mergeable = true;
745
746   // We need to find the personality routine if there is one, since we
747   // can only merge CIEs which use the same routine.  We also need to
748   // find the FDE encoding if there is one, so that we can read the PC
749   // from the FDE.
750
751   const unsigned char* p = pcie;
752
753   if (pcieend - p < 1)
754     return false;
755   unsigned char version = *p++;
756   if (version != 1 && version != 3)
757     return false;
758
759   const unsigned char* paug = p;
760   const void* paugendv = memchr(p, '\0', pcieend - p);
761   const unsigned char* paugend = static_cast<const unsigned char*>(paugendv);
762   if (paugend == NULL)
763     return false;
764   p = paugend + 1;
765
766   if (paug[0] == 'e' && paug[1] == 'h')
767     {
768       // This is a CIE from gcc before version 3.0.  We can't merge
769       // these.  We can still read the FDEs.
770       mergeable = false;
771       paug += 2;
772       if (*paug != '\0')
773         return false;
774       if (pcieend - p < size / 8)
775         return false;
776       p += size / 8;
777     }
778
779   // Skip the code alignment.
780   if (!skip_leb128(&p, pcieend))
781     return false;
782
783   // Skip the data alignment.
784   if (!skip_leb128(&p, pcieend))
785     return false;
786
787   // Skip the return column.
788   if (version == 1)
789     {
790       if (pcieend - p < 1)
791         return false;
792       ++p;
793     }
794   else
795     {
796       if (!skip_leb128(&p, pcieend))
797         return false;
798     }
799
800   if (*paug == 'z')
801     {
802       ++paug;
803       // Skip the augmentation size.
804       if (!skip_leb128(&p, pcieend))
805         return false;
806     }
807
808   unsigned char fde_encoding = elfcpp::DW_EH_PE_absptr;
809   int per_offset = -1;
810   while (*paug != '\0')
811     {
812       switch (*paug)
813         {
814         case 'L': // LSDA encoding.
815           if (pcieend - p < 1)
816             return false;
817           ++p;
818           break;
819
820         case 'R': // FDE encoding.
821           if (pcieend - p < 1)
822             return false;
823           fde_encoding = *p;
824           switch (fde_encoding & 7)
825             {
826             case elfcpp::DW_EH_PE_absptr:
827             case elfcpp::DW_EH_PE_udata2:
828             case elfcpp::DW_EH_PE_udata4:
829             case elfcpp::DW_EH_PE_udata8:
830               break;
831             default:
832               // We don't expect to see any other cases here, and
833               // we're not prepared to handle them.
834               return false;
835             }
836           ++p;
837           break;
838
839         case 'S':
840           break;
841
842         case 'P':
843           // Personality encoding.
844           {
845             if (pcieend - p < 1)
846               return false;
847             unsigned char per_encoding = *p;
848             ++p;
849
850             if ((per_encoding & 0x60) == 0x60)
851               return false;
852             unsigned int per_width;
853             switch (per_encoding & 7)
854               {
855               case elfcpp::DW_EH_PE_udata2:
856                 per_width = 2;
857                 break;
858               case elfcpp::DW_EH_PE_udata4:
859                 per_width = 4;
860                 break;
861               case elfcpp::DW_EH_PE_udata8:
862                 per_width = 8;
863                 break;
864               case elfcpp::DW_EH_PE_absptr:
865                 per_width = size / 8;
866                 break;
867               default:
868                 return false;
869               }
870
871             if ((per_encoding & 0xf0) == elfcpp::DW_EH_PE_aligned)
872               {
873                 unsigned int len = p - pcie;
874                 len += per_width - 1;
875                 len &= ~ (per_width - 1);
876                 if (static_cast<unsigned int>(pcieend - p) < len)
877                   return false;
878                 p += len;
879               }
880
881             per_offset = p - pcontents;
882
883             if (static_cast<unsigned int>(pcieend - p) < per_width)
884               return false;
885             p += per_width;
886           }
887           break;
888
889         default:
890           return false;
891         }
892
893       ++paug;
894     }
895
896   const char* personality_name = "";
897   if (per_offset != -1)
898     {
899       if (relocs->advance(per_offset) > 0)
900         return false;
901       if (relocs->next_offset() != per_offset)
902         return false;
903
904       unsigned int personality_symndx = relocs->next_symndx();
905       if (personality_symndx == -1U)
906         return false;
907
908       if (personality_symndx < object->local_symbol_count())
909         {
910           // We can only merge this CIE if the personality routine is
911           // a global symbol.  We can still read the FDEs.
912           mergeable = false;
913         }
914       else
915         {
916           const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
917           if (personality_symndx >= symbols_size / sym_size)
918             return false;
919           elfcpp::Sym<size, big_endian> sym(symbols
920                                             + (personality_symndx * sym_size));
921           unsigned int name_offset = sym.get_st_name();
922           if (name_offset >= symbol_names_size)
923             return false;
924           personality_name = (reinterpret_cast<const char*>(symbol_names)
925                               + name_offset);
926         }
927
928       int r = relocs->advance(per_offset + 1);
929       gold_assert(r == 1);
930     }
931
932   if (relocs->advance(pcieend - pcontents) > 0)
933     return false;
934
935   Cie cie(object, shndx, (pcie - 8) - pcontents, fde_encoding, 
936           personality_name, pcie, pcieend - pcie);
937   Cie* cie_pointer = NULL;
938   if (mergeable)
939     {
940       Cie_offsets::iterator find_cie = this->cie_offsets_.find(&cie);
941       if (find_cie != this->cie_offsets_.end())
942         cie_pointer = *find_cie;
943       else
944         {
945           // See if we already saw this CIE in this object file.
946           for (New_cies::const_iterator pc = new_cies->begin();
947                pc != new_cies->end();
948                ++pc)
949             {
950               if (*(pc->first) == cie)
951                 {
952                   cie_pointer = pc->first;
953                   break;
954                 }
955             }
956         }
957     }
958
959   if (cie_pointer == NULL)
960     {
961       cie_pointer = new Cie(cie);
962       new_cies->push_back(std::make_pair(cie_pointer, mergeable));
963     }
964   else
965     {
966       // We are deleting this CIE.  Record that in our mapping from
967       // input sections to the output section.  At this point we don't
968       // know for sure that we are doing a special mapping for this
969       // input section, but that's OK--if we don't do a special
970       // mapping, nobody will ever ask for the mapping we add here.
971       this->merge_map_.add_mapping(object, shndx, (pcie - 8) - pcontents,
972                                    pcieend - (pcie - 8), -1);
973     }
974
975   // Record this CIE plus the offset in the input section.
976   cies->insert(std::make_pair(pcie - pcontents, cie_pointer));
977
978   return true;
979 }
980
981 // Read an FDE.  Return false if we can't parse the information.
982
983 template<int size, bool big_endian>
984 bool
985 Eh_frame::read_fde(Sized_relobj_file<size, big_endian>* object,
986                    unsigned int shndx,
987                    const unsigned char* symbols,
988                    section_size_type symbols_size,
989                    const unsigned char* pcontents,
990                    unsigned int offset,
991                    const unsigned char* pfde,
992                    const unsigned char* pfdeend,
993                    Track_relocs<size, big_endian>* relocs,
994                    Offsets_to_cie* cies)
995 {
996   // OFFSET is the distance between the 4 bytes before PFDE to the
997   // start of the CIE.  The offset we recorded for the CIE is 8 bytes
998   // after the start of the CIE--after the length and the zero tag.
999   unsigned int cie_offset = (pfde - 4 - pcontents) - offset + 8;
1000   Offsets_to_cie::const_iterator pcie = cies->find(cie_offset);
1001   if (pcie == cies->end())
1002     return false;
1003   Cie* cie = pcie->second;
1004
1005   // The FDE should start with a reloc to the start of the code which
1006   // it describes.
1007   if (relocs->advance(pfde - pcontents) > 0)
1008     return false;
1009
1010   if (relocs->next_offset() != pfde - pcontents)
1011     return false;
1012
1013   unsigned int symndx = relocs->next_symndx();
1014   if (symndx == -1U)
1015     return false;
1016
1017   // There can be another reloc in the FDE, if the CIE specifies an
1018   // LSDA (language specific data area).  We currently don't care.  We
1019   // will care later if we want to optimize the LSDA from an absolute
1020   // pointer to a PC relative offset when generating a shared library.
1021   relocs->advance(pfdeend - pcontents);
1022
1023   unsigned int fde_shndx;
1024   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1025   if (symndx >= symbols_size / sym_size)
1026     return false;
1027   elfcpp::Sym<size, big_endian> sym(symbols + symndx * sym_size);
1028   bool is_ordinary;
1029   fde_shndx = object->adjust_sym_shndx(symndx, sym.get_st_shndx(),
1030                                        &is_ordinary);
1031
1032   if (is_ordinary
1033       && fde_shndx != elfcpp::SHN_UNDEF
1034       && fde_shndx < object->shnum()
1035       && !object->is_section_included(fde_shndx))
1036     {
1037       // This FDE applies to a section which we are discarding.  We
1038       // can discard this FDE.
1039       this->merge_map_.add_mapping(object, shndx, (pfde - 8) - pcontents,
1040                                    pfdeend - (pfde - 8), -1);
1041       return true;
1042     }
1043
1044   cie->add_fde(new Fde(object, shndx, (pfde - 8) - pcontents,
1045                        pfde, pfdeend - pfde));
1046
1047   return true;
1048 }
1049
1050 // Add unwind information for a PLT.
1051
1052 void
1053 Eh_frame::add_ehframe_for_plt(Output_data* plt, const unsigned char* cie_data,
1054                               size_t cie_length, const unsigned char* fde_data,
1055                               size_t fde_length)
1056 {
1057   Cie cie(NULL, 0, 0, elfcpp::DW_EH_PE_pcrel | elfcpp::DW_EH_PE_sdata4, "",
1058           cie_data, cie_length);
1059   Cie_offsets::iterator find_cie = this->cie_offsets_.find(&cie);
1060   Cie* pcie;
1061   if (find_cie != this->cie_offsets_.end())
1062     pcie = *find_cie;
1063   else
1064     {
1065       gold_assert(!this->mappings_are_done_);
1066       pcie = new Cie(cie);
1067       this->cie_offsets_.insert(pcie);
1068     }
1069
1070   Fde* fde = new Fde(plt, fde_data, fde_length, this->mappings_are_done_);
1071   pcie->add_fde(fde);
1072
1073   if (this->mappings_are_done_)
1074     this->final_data_size_ += align_address(fde_length + 8, this->addralign());
1075 }
1076
1077 // Return the number of FDEs.
1078
1079 unsigned int
1080 Eh_frame::fde_count() const
1081 {
1082   unsigned int ret = 0;
1083   for (Unmergeable_cie_offsets::const_iterator p =
1084          this->unmergeable_cie_offsets_.begin();
1085        p != this->unmergeable_cie_offsets_.end();
1086        ++p)
1087     ret += (*p)->fde_count();
1088   for (Cie_offsets::const_iterator p = this->cie_offsets_.begin();
1089        p != this->cie_offsets_.end();
1090        ++p)
1091     ret += (*p)->fde_count();
1092   return ret;
1093 }
1094
1095 // Set the final data size.
1096
1097 void
1098 Eh_frame::set_final_data_size()
1099 {
1100   // We can be called more than once if Layout::set_segment_offsets
1101   // finds a better mapping.  We don't want to add all the mappings
1102   // again.
1103   if (this->mappings_are_done_)
1104     {
1105       this->set_data_size(this->final_data_size_);
1106       return;
1107     }
1108
1109   section_offset_type output_offset = 0;
1110
1111   for (Unmergeable_cie_offsets::iterator p =
1112          this->unmergeable_cie_offsets_.begin();
1113        p != this->unmergeable_cie_offsets_.end();
1114        ++p)
1115     output_offset = (*p)->set_output_offset(output_offset,
1116                                             this->addralign(),
1117                                             &this->merge_map_);
1118
1119   for (Cie_offsets::iterator p = this->cie_offsets_.begin();
1120        p != this->cie_offsets_.end();
1121        ++p)
1122     output_offset = (*p)->set_output_offset(output_offset,
1123                                             this->addralign(),
1124                                             &this->merge_map_);
1125
1126   this->mappings_are_done_ = true;
1127   this->final_data_size_ = output_offset;
1128
1129   gold_assert((output_offset & (this->addralign() - 1)) == 0);
1130   this->set_data_size(output_offset);
1131 }
1132
1133 // Return an output offset for an input offset.
1134
1135 bool
1136 Eh_frame::do_output_offset(const Relobj* object, unsigned int shndx,
1137                            section_offset_type offset,
1138                            section_offset_type* poutput) const
1139 {
1140   return this->merge_map_.get_output_offset(object, shndx, offset, poutput);
1141 }
1142
1143 // Return whether this is the merge section for an input section.
1144
1145 bool
1146 Eh_frame::do_is_merge_section_for(const Relobj* object,
1147                                   unsigned int shndx) const
1148 {
1149   return this->merge_map_.is_merge_section_for(object, shndx);
1150 }
1151
1152 // Write the data to the output file.
1153
1154 void
1155 Eh_frame::do_write(Output_file* of)
1156 {
1157   const off_t offset = this->offset();
1158   const off_t oview_size = this->data_size();
1159   unsigned char* const oview = of->get_output_view(offset, oview_size);
1160
1161   switch (parameters->size_and_endianness())
1162     {
1163 #ifdef HAVE_TARGET_32_LITTLE
1164     case Parameters::TARGET_32_LITTLE:
1165       this->do_sized_write<32, false>(oview);
1166       break;
1167 #endif
1168 #ifdef HAVE_TARGET_32_BIG
1169     case Parameters::TARGET_32_BIG:
1170       this->do_sized_write<32, true>(oview);
1171       break;
1172 #endif
1173 #ifdef HAVE_TARGET_64_LITTLE
1174     case Parameters::TARGET_64_LITTLE:
1175       this->do_sized_write<64, false>(oview);
1176       break;
1177 #endif
1178 #ifdef HAVE_TARGET_64_BIG
1179     case Parameters::TARGET_64_BIG:
1180       this->do_sized_write<64, true>(oview);
1181       break;
1182 #endif
1183     default:
1184       gold_unreachable();
1185     }
1186
1187   of->write_output_view(offset, oview_size, oview);
1188 }
1189
1190 // Write the data to the output file--template version.
1191
1192 template<int size, bool big_endian>
1193 void
1194 Eh_frame::do_sized_write(unsigned char* oview)
1195 {
1196   uint64_t address = this->address();
1197   unsigned int addralign = this->addralign();
1198   section_offset_type o = 0;
1199   Post_fdes post_fdes;
1200   for (Unmergeable_cie_offsets::iterator p =
1201          this->unmergeable_cie_offsets_.begin();
1202        p != this->unmergeable_cie_offsets_.end();
1203        ++p)
1204     o = (*p)->write<size, big_endian>(oview, o, address, addralign,
1205                                       this->eh_frame_hdr_, &post_fdes);
1206   for (Cie_offsets::iterator p = this->cie_offsets_.begin();
1207        p != this->cie_offsets_.end();
1208        ++p)
1209     o = (*p)->write<size, big_endian>(oview, o, address, addralign,
1210                                       this->eh_frame_hdr_, &post_fdes);
1211   for (Post_fdes::iterator p = post_fdes.begin();
1212        p != post_fdes.end();
1213        ++p)
1214     {
1215       o = (*p)->fde->write<size, big_endian>(oview, o, address, addralign,
1216                                              (*p)->cie_offset,
1217                                              (*p)->fde_encoding,
1218                                              this->eh_frame_hdr_);
1219       delete *p;
1220     }
1221 }
1222
1223 #ifdef HAVE_TARGET_32_LITTLE
1224 template
1225 bool
1226 Eh_frame::add_ehframe_input_section<32, false>(
1227     Sized_relobj_file<32, false>* object,
1228     const unsigned char* symbols,
1229     section_size_type symbols_size,
1230     const unsigned char* symbol_names,
1231     section_size_type symbol_names_size,
1232     unsigned int shndx,
1233     unsigned int reloc_shndx,
1234     unsigned int reloc_type);
1235 #endif
1236
1237 #ifdef HAVE_TARGET_32_BIG
1238 template
1239 bool
1240 Eh_frame::add_ehframe_input_section<32, true>(
1241     Sized_relobj_file<32, true>* object,
1242     const unsigned char* symbols,
1243     section_size_type symbols_size,
1244     const unsigned char* symbol_names,
1245     section_size_type symbol_names_size,
1246     unsigned int shndx,
1247     unsigned int reloc_shndx,
1248     unsigned int reloc_type);
1249 #endif
1250
1251 #ifdef HAVE_TARGET_64_LITTLE
1252 template
1253 bool
1254 Eh_frame::add_ehframe_input_section<64, false>(
1255     Sized_relobj_file<64, false>* object,
1256     const unsigned char* symbols,
1257     section_size_type symbols_size,
1258     const unsigned char* symbol_names,
1259     section_size_type symbol_names_size,
1260     unsigned int shndx,
1261     unsigned int reloc_shndx,
1262     unsigned int reloc_type);
1263 #endif
1264
1265 #ifdef HAVE_TARGET_64_BIG
1266 template
1267 bool
1268 Eh_frame::add_ehframe_input_section<64, true>(
1269     Sized_relobj_file<64, true>* object,
1270     const unsigned char* symbols,
1271     section_size_type symbols_size,
1272     const unsigned char* symbol_names,
1273     section_size_type symbol_names_size,
1274     unsigned int shndx,
1275     unsigned int reloc_shndx,
1276     unsigned int reloc_type);
1277 #endif
1278
1279 } // End namespace gold.