PR gold/13249
[platform/upstream/binutils.git] / gold / output.cc
1 // output.cc -- manage the output file for gold
2
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011 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 <cstdlib>
26 #include <cstring>
27 #include <cerrno>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <sys/stat.h>
31 #include <algorithm>
32
33 #ifdef HAVE_SYS_MMAN_H
34 #include <sys/mman.h>
35 #endif
36
37 #include "libiberty.h"
38
39 #include "dwarf.h"
40 #include "parameters.h"
41 #include "object.h"
42 #include "symtab.h"
43 #include "reloc.h"
44 #include "merge.h"
45 #include "descriptors.h"
46 #include "layout.h"
47 #include "output.h"
48
49 // For systems without mmap support.
50 #ifndef HAVE_MMAP
51 # define mmap gold_mmap
52 # define munmap gold_munmap
53 # define mremap gold_mremap
54 # ifndef MAP_FAILED
55 #  define MAP_FAILED (reinterpret_cast<void*>(-1))
56 # endif
57 # ifndef PROT_READ
58 #  define PROT_READ 0
59 # endif
60 # ifndef PROT_WRITE
61 #  define PROT_WRITE 0
62 # endif
63 # ifndef MAP_PRIVATE
64 #  define MAP_PRIVATE 0
65 # endif
66 # ifndef MAP_ANONYMOUS
67 #  define MAP_ANONYMOUS 0
68 # endif
69 # ifndef MAP_SHARED
70 #  define MAP_SHARED 0
71 # endif
72
73 # ifndef ENOSYS
74 #  define ENOSYS EINVAL
75 # endif
76
77 static void *
78 gold_mmap(void *, size_t, int, int, int, off_t)
79 {
80   errno = ENOSYS;
81   return MAP_FAILED;
82 }
83
84 static int
85 gold_munmap(void *, size_t)
86 {
87   errno = ENOSYS;
88   return -1;
89 }
90
91 static void *
92 gold_mremap(void *, size_t, size_t, int)
93 {
94   errno = ENOSYS;
95   return MAP_FAILED;
96 }
97
98 #endif
99
100 #if defined(HAVE_MMAP) && !defined(HAVE_MREMAP)
101 # define mremap gold_mremap
102 extern "C" void *gold_mremap(void *, size_t, size_t, int);
103 #endif
104
105 // Some BSD systems still use MAP_ANON instead of MAP_ANONYMOUS
106 #ifndef MAP_ANONYMOUS
107 # define MAP_ANONYMOUS  MAP_ANON
108 #endif
109
110 #ifndef MREMAP_MAYMOVE
111 # define MREMAP_MAYMOVE 1
112 #endif
113
114 #ifndef HAVE_POSIX_FALLOCATE
115 // A dummy, non general, version of posix_fallocate.  Here we just set
116 // the file size and hope that there is enough disk space.  FIXME: We
117 // could allocate disk space by walking block by block and writing a
118 // zero byte into each block.
119 static int
120 posix_fallocate(int o, off_t offset, off_t len)
121 {
122   return ftruncate(o, offset + len);
123 }
124 #endif // !defined(HAVE_POSIX_FALLOCATE)
125
126 // Mingw does not have S_ISLNK.
127 #ifndef S_ISLNK
128 # define S_ISLNK(mode) 0
129 #endif
130
131 namespace gold
132 {
133
134 // Output_data variables.
135
136 bool Output_data::allocated_sizes_are_fixed;
137
138 // Output_data methods.
139
140 Output_data::~Output_data()
141 {
142 }
143
144 // Return the default alignment for the target size.
145
146 uint64_t
147 Output_data::default_alignment()
148 {
149   return Output_data::default_alignment_for_size(
150       parameters->target().get_size());
151 }
152
153 // Return the default alignment for a size--32 or 64.
154
155 uint64_t
156 Output_data::default_alignment_for_size(int size)
157 {
158   if (size == 32)
159     return 4;
160   else if (size == 64)
161     return 8;
162   else
163     gold_unreachable();
164 }
165
166 // Output_section_header methods.  This currently assumes that the
167 // segment and section lists are complete at construction time.
168
169 Output_section_headers::Output_section_headers(
170     const Layout* layout,
171     const Layout::Segment_list* segment_list,
172     const Layout::Section_list* section_list,
173     const Layout::Section_list* unattached_section_list,
174     const Stringpool* secnamepool,
175     const Output_section* shstrtab_section)
176   : layout_(layout),
177     segment_list_(segment_list),
178     section_list_(section_list),
179     unattached_section_list_(unattached_section_list),
180     secnamepool_(secnamepool),
181     shstrtab_section_(shstrtab_section)
182 {
183 }
184
185 // Compute the current data size.
186
187 off_t
188 Output_section_headers::do_size() const
189 {
190   // Count all the sections.  Start with 1 for the null section.
191   off_t count = 1;
192   if (!parameters->options().relocatable())
193     {
194       for (Layout::Segment_list::const_iterator p =
195              this->segment_list_->begin();
196            p != this->segment_list_->end();
197            ++p)
198         if ((*p)->type() == elfcpp::PT_LOAD)
199           count += (*p)->output_section_count();
200     }
201   else
202     {
203       for (Layout::Section_list::const_iterator p =
204              this->section_list_->begin();
205            p != this->section_list_->end();
206            ++p)
207         if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
208           ++count;
209     }
210   count += this->unattached_section_list_->size();
211
212   const int size = parameters->target().get_size();
213   int shdr_size;
214   if (size == 32)
215     shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
216   else if (size == 64)
217     shdr_size = elfcpp::Elf_sizes<64>::shdr_size;
218   else
219     gold_unreachable();
220
221   return count * shdr_size;
222 }
223
224 // Write out the section headers.
225
226 void
227 Output_section_headers::do_write(Output_file* of)
228 {
229   switch (parameters->size_and_endianness())
230     {
231 #ifdef HAVE_TARGET_32_LITTLE
232     case Parameters::TARGET_32_LITTLE:
233       this->do_sized_write<32, false>(of);
234       break;
235 #endif
236 #ifdef HAVE_TARGET_32_BIG
237     case Parameters::TARGET_32_BIG:
238       this->do_sized_write<32, true>(of);
239       break;
240 #endif
241 #ifdef HAVE_TARGET_64_LITTLE
242     case Parameters::TARGET_64_LITTLE:
243       this->do_sized_write<64, false>(of);
244       break;
245 #endif
246 #ifdef HAVE_TARGET_64_BIG
247     case Parameters::TARGET_64_BIG:
248       this->do_sized_write<64, true>(of);
249       break;
250 #endif
251     default:
252       gold_unreachable();
253     }
254 }
255
256 template<int size, bool big_endian>
257 void
258 Output_section_headers::do_sized_write(Output_file* of)
259 {
260   off_t all_shdrs_size = this->data_size();
261   unsigned char* view = of->get_output_view(this->offset(), all_shdrs_size);
262
263   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
264   unsigned char* v = view;
265
266   {
267     typename elfcpp::Shdr_write<size, big_endian> oshdr(v);
268     oshdr.put_sh_name(0);
269     oshdr.put_sh_type(elfcpp::SHT_NULL);
270     oshdr.put_sh_flags(0);
271     oshdr.put_sh_addr(0);
272     oshdr.put_sh_offset(0);
273
274     size_t section_count = (this->data_size()
275                             / elfcpp::Elf_sizes<size>::shdr_size);
276     if (section_count < elfcpp::SHN_LORESERVE)
277       oshdr.put_sh_size(0);
278     else
279       oshdr.put_sh_size(section_count);
280
281     unsigned int shstrndx = this->shstrtab_section_->out_shndx();
282     if (shstrndx < elfcpp::SHN_LORESERVE)
283       oshdr.put_sh_link(0);
284     else
285       oshdr.put_sh_link(shstrndx);
286
287     size_t segment_count = this->segment_list_->size();
288     oshdr.put_sh_info(segment_count >= elfcpp::PN_XNUM ? segment_count : 0);
289
290     oshdr.put_sh_addralign(0);
291     oshdr.put_sh_entsize(0);
292   }
293
294   v += shdr_size;
295
296   unsigned int shndx = 1;
297   if (!parameters->options().relocatable())
298     {
299       for (Layout::Segment_list::const_iterator p =
300              this->segment_list_->begin();
301            p != this->segment_list_->end();
302            ++p)
303         v = (*p)->write_section_headers<size, big_endian>(this->layout_,
304                                                           this->secnamepool_,
305                                                           v,
306                                                           &shndx);
307     }
308   else
309     {
310       for (Layout::Section_list::const_iterator p =
311              this->section_list_->begin();
312            p != this->section_list_->end();
313            ++p)
314         {
315           // We do unallocated sections below, except that group
316           // sections have to come first.
317           if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
318               && (*p)->type() != elfcpp::SHT_GROUP)
319             continue;
320           gold_assert(shndx == (*p)->out_shndx());
321           elfcpp::Shdr_write<size, big_endian> oshdr(v);
322           (*p)->write_header(this->layout_, this->secnamepool_, &oshdr);
323           v += shdr_size;
324           ++shndx;
325         }
326     }
327
328   for (Layout::Section_list::const_iterator p =
329          this->unattached_section_list_->begin();
330        p != this->unattached_section_list_->end();
331        ++p)
332     {
333       // For a relocatable link, we did unallocated group sections
334       // above, since they have to come first.
335       if ((*p)->type() == elfcpp::SHT_GROUP
336           && parameters->options().relocatable())
337         continue;
338       gold_assert(shndx == (*p)->out_shndx());
339       elfcpp::Shdr_write<size, big_endian> oshdr(v);
340       (*p)->write_header(this->layout_, this->secnamepool_, &oshdr);
341       v += shdr_size;
342       ++shndx;
343     }
344
345   of->write_output_view(this->offset(), all_shdrs_size, view);
346 }
347
348 // Output_segment_header methods.
349
350 Output_segment_headers::Output_segment_headers(
351     const Layout::Segment_list& segment_list)
352   : segment_list_(segment_list)
353 {
354   this->set_current_data_size_for_child(this->do_size());
355 }
356
357 void
358 Output_segment_headers::do_write(Output_file* of)
359 {
360   switch (parameters->size_and_endianness())
361     {
362 #ifdef HAVE_TARGET_32_LITTLE
363     case Parameters::TARGET_32_LITTLE:
364       this->do_sized_write<32, false>(of);
365       break;
366 #endif
367 #ifdef HAVE_TARGET_32_BIG
368     case Parameters::TARGET_32_BIG:
369       this->do_sized_write<32, true>(of);
370       break;
371 #endif
372 #ifdef HAVE_TARGET_64_LITTLE
373     case Parameters::TARGET_64_LITTLE:
374       this->do_sized_write<64, false>(of);
375       break;
376 #endif
377 #ifdef HAVE_TARGET_64_BIG
378     case Parameters::TARGET_64_BIG:
379       this->do_sized_write<64, true>(of);
380       break;
381 #endif
382     default:
383       gold_unreachable();
384     }
385 }
386
387 template<int size, bool big_endian>
388 void
389 Output_segment_headers::do_sized_write(Output_file* of)
390 {
391   const int phdr_size = elfcpp::Elf_sizes<size>::phdr_size;
392   off_t all_phdrs_size = this->segment_list_.size() * phdr_size;
393   gold_assert(all_phdrs_size == this->data_size());
394   unsigned char* view = of->get_output_view(this->offset(),
395                                             all_phdrs_size);
396   unsigned char* v = view;
397   for (Layout::Segment_list::const_iterator p = this->segment_list_.begin();
398        p != this->segment_list_.end();
399        ++p)
400     {
401       elfcpp::Phdr_write<size, big_endian> ophdr(v);
402       (*p)->write_header(&ophdr);
403       v += phdr_size;
404     }
405
406   gold_assert(v - view == all_phdrs_size);
407
408   of->write_output_view(this->offset(), all_phdrs_size, view);
409 }
410
411 off_t
412 Output_segment_headers::do_size() const
413 {
414   const int size = parameters->target().get_size();
415   int phdr_size;
416   if (size == 32)
417     phdr_size = elfcpp::Elf_sizes<32>::phdr_size;
418   else if (size == 64)
419     phdr_size = elfcpp::Elf_sizes<64>::phdr_size;
420   else
421     gold_unreachable();
422
423   return this->segment_list_.size() * phdr_size;
424 }
425
426 // Output_file_header methods.
427
428 Output_file_header::Output_file_header(const Target* target,
429                                        const Symbol_table* symtab,
430                                        const Output_segment_headers* osh)
431   : target_(target),
432     symtab_(symtab),
433     segment_header_(osh),
434     section_header_(NULL),
435     shstrtab_(NULL)
436 {
437   this->set_data_size(this->do_size());
438 }
439
440 // Set the section table information for a file header.
441
442 void
443 Output_file_header::set_section_info(const Output_section_headers* shdrs,
444                                      const Output_section* shstrtab)
445 {
446   this->section_header_ = shdrs;
447   this->shstrtab_ = shstrtab;
448 }
449
450 // Write out the file header.
451
452 void
453 Output_file_header::do_write(Output_file* of)
454 {
455   gold_assert(this->offset() == 0);
456
457   switch (parameters->size_and_endianness())
458     {
459 #ifdef HAVE_TARGET_32_LITTLE
460     case Parameters::TARGET_32_LITTLE:
461       this->do_sized_write<32, false>(of);
462       break;
463 #endif
464 #ifdef HAVE_TARGET_32_BIG
465     case Parameters::TARGET_32_BIG:
466       this->do_sized_write<32, true>(of);
467       break;
468 #endif
469 #ifdef HAVE_TARGET_64_LITTLE
470     case Parameters::TARGET_64_LITTLE:
471       this->do_sized_write<64, false>(of);
472       break;
473 #endif
474 #ifdef HAVE_TARGET_64_BIG
475     case Parameters::TARGET_64_BIG:
476       this->do_sized_write<64, true>(of);
477       break;
478 #endif
479     default:
480       gold_unreachable();
481     }
482 }
483
484 // Write out the file header with appropriate size and endianness.
485
486 template<int size, bool big_endian>
487 void
488 Output_file_header::do_sized_write(Output_file* of)
489 {
490   gold_assert(this->offset() == 0);
491
492   int ehdr_size = elfcpp::Elf_sizes<size>::ehdr_size;
493   unsigned char* view = of->get_output_view(0, ehdr_size);
494   elfcpp::Ehdr_write<size, big_endian> oehdr(view);
495
496   unsigned char e_ident[elfcpp::EI_NIDENT];
497   memset(e_ident, 0, elfcpp::EI_NIDENT);
498   e_ident[elfcpp::EI_MAG0] = elfcpp::ELFMAG0;
499   e_ident[elfcpp::EI_MAG1] = elfcpp::ELFMAG1;
500   e_ident[elfcpp::EI_MAG2] = elfcpp::ELFMAG2;
501   e_ident[elfcpp::EI_MAG3] = elfcpp::ELFMAG3;
502   if (size == 32)
503     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS32;
504   else if (size == 64)
505     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS64;
506   else
507     gold_unreachable();
508   e_ident[elfcpp::EI_DATA] = (big_endian
509                               ? elfcpp::ELFDATA2MSB
510                               : elfcpp::ELFDATA2LSB);
511   e_ident[elfcpp::EI_VERSION] = elfcpp::EV_CURRENT;
512   oehdr.put_e_ident(e_ident);
513
514   elfcpp::ET e_type;
515   if (parameters->options().relocatable())
516     e_type = elfcpp::ET_REL;
517   else if (parameters->options().output_is_position_independent())
518     e_type = elfcpp::ET_DYN;
519   else
520     e_type = elfcpp::ET_EXEC;
521   oehdr.put_e_type(e_type);
522
523   oehdr.put_e_machine(this->target_->machine_code());
524   oehdr.put_e_version(elfcpp::EV_CURRENT);
525
526   oehdr.put_e_entry(this->entry<size>());
527
528   if (this->segment_header_ == NULL)
529     oehdr.put_e_phoff(0);
530   else
531     oehdr.put_e_phoff(this->segment_header_->offset());
532
533   oehdr.put_e_shoff(this->section_header_->offset());
534   oehdr.put_e_flags(this->target_->processor_specific_flags());
535   oehdr.put_e_ehsize(elfcpp::Elf_sizes<size>::ehdr_size);
536
537   if (this->segment_header_ == NULL)
538     {
539       oehdr.put_e_phentsize(0);
540       oehdr.put_e_phnum(0);
541     }
542   else
543     {
544       oehdr.put_e_phentsize(elfcpp::Elf_sizes<size>::phdr_size);
545       size_t phnum = (this->segment_header_->data_size()
546                       / elfcpp::Elf_sizes<size>::phdr_size);
547       if (phnum > elfcpp::PN_XNUM)
548         phnum = elfcpp::PN_XNUM;
549       oehdr.put_e_phnum(phnum);
550     }
551
552   oehdr.put_e_shentsize(elfcpp::Elf_sizes<size>::shdr_size);
553   size_t section_count = (this->section_header_->data_size()
554                           / elfcpp::Elf_sizes<size>::shdr_size);
555
556   if (section_count < elfcpp::SHN_LORESERVE)
557     oehdr.put_e_shnum(this->section_header_->data_size()
558                       / elfcpp::Elf_sizes<size>::shdr_size);
559   else
560     oehdr.put_e_shnum(0);
561
562   unsigned int shstrndx = this->shstrtab_->out_shndx();
563   if (shstrndx < elfcpp::SHN_LORESERVE)
564     oehdr.put_e_shstrndx(this->shstrtab_->out_shndx());
565   else
566     oehdr.put_e_shstrndx(elfcpp::SHN_XINDEX);
567
568   // Let the target adjust the ELF header, e.g., to set EI_OSABI in
569   // the e_ident field.
570   parameters->target().adjust_elf_header(view, ehdr_size);
571
572   of->write_output_view(0, ehdr_size, view);
573 }
574
575 // Return the value to use for the entry address.
576
577 template<int size>
578 typename elfcpp::Elf_types<size>::Elf_Addr
579 Output_file_header::entry()
580 {
581   const bool should_issue_warning = (parameters->options().entry() != NULL
582                                      && !parameters->options().relocatable()
583                                      && !parameters->options().shared());
584   const char* entry = parameters->entry();
585   Symbol* sym = this->symtab_->lookup(entry);
586
587   typename Sized_symbol<size>::Value_type v;
588   if (sym != NULL)
589     {
590       Sized_symbol<size>* ssym;
591       ssym = this->symtab_->get_sized_symbol<size>(sym);
592       if (!ssym->is_defined() && should_issue_warning)
593         gold_warning("entry symbol '%s' exists but is not defined", entry);
594       v = ssym->value();
595     }
596   else
597     {
598       // We couldn't find the entry symbol.  See if we can parse it as
599       // a number.  This supports, e.g., -e 0x1000.
600       char* endptr;
601       v = strtoull(entry, &endptr, 0);
602       if (*endptr != '\0')
603         {
604           if (should_issue_warning)
605             gold_warning("cannot find entry symbol '%s'", entry);
606           v = 0;
607         }
608     }
609
610   return v;
611 }
612
613 // Compute the current data size.
614
615 off_t
616 Output_file_header::do_size() const
617 {
618   const int size = parameters->target().get_size();
619   if (size == 32)
620     return elfcpp::Elf_sizes<32>::ehdr_size;
621   else if (size == 64)
622     return elfcpp::Elf_sizes<64>::ehdr_size;
623   else
624     gold_unreachable();
625 }
626
627 // Output_data_const methods.
628
629 void
630 Output_data_const::do_write(Output_file* of)
631 {
632   of->write(this->offset(), this->data_.data(), this->data_.size());
633 }
634
635 // Output_data_const_buffer methods.
636
637 void
638 Output_data_const_buffer::do_write(Output_file* of)
639 {
640   of->write(this->offset(), this->p_, this->data_size());
641 }
642
643 // Output_section_data methods.
644
645 // Record the output section, and set the entry size and such.
646
647 void
648 Output_section_data::set_output_section(Output_section* os)
649 {
650   gold_assert(this->output_section_ == NULL);
651   this->output_section_ = os;
652   this->do_adjust_output_section(os);
653 }
654
655 // Return the section index of the output section.
656
657 unsigned int
658 Output_section_data::do_out_shndx() const
659 {
660   gold_assert(this->output_section_ != NULL);
661   return this->output_section_->out_shndx();
662 }
663
664 // Set the alignment, which means we may need to update the alignment
665 // of the output section.
666
667 void
668 Output_section_data::set_addralign(uint64_t addralign)
669 {
670   this->addralign_ = addralign;
671   if (this->output_section_ != NULL
672       && this->output_section_->addralign() < addralign)
673     this->output_section_->set_addralign(addralign);
674 }
675
676 // Output_data_strtab methods.
677
678 // Set the final data size.
679
680 void
681 Output_data_strtab::set_final_data_size()
682 {
683   this->strtab_->set_string_offsets();
684   this->set_data_size(this->strtab_->get_strtab_size());
685 }
686
687 // Write out a string table.
688
689 void
690 Output_data_strtab::do_write(Output_file* of)
691 {
692   this->strtab_->write(of, this->offset());
693 }
694
695 // Output_reloc methods.
696
697 // A reloc against a global symbol.
698
699 template<bool dynamic, int size, bool big_endian>
700 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
701     Symbol* gsym,
702     unsigned int type,
703     Output_data* od,
704     Address address,
705     bool is_relative,
706     bool is_symbolless)
707   : address_(address), local_sym_index_(GSYM_CODE), type_(type),
708     is_relative_(is_relative), is_symbolless_(is_symbolless),
709     is_section_symbol_(false), use_plt_offset_(false), shndx_(INVALID_CODE)
710 {
711   // this->type_ is a bitfield; make sure TYPE fits.
712   gold_assert(this->type_ == type);
713   this->u1_.gsym = gsym;
714   this->u2_.od = od;
715   if (dynamic)
716     this->set_needs_dynsym_index();
717 }
718
719 template<bool dynamic, int size, bool big_endian>
720 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
721     Symbol* gsym,
722     unsigned int type,
723     Sized_relobj<size, big_endian>* relobj,
724     unsigned int shndx,
725     Address address,
726     bool is_relative,
727     bool is_symbolless)
728   : address_(address), local_sym_index_(GSYM_CODE), type_(type),
729     is_relative_(is_relative), is_symbolless_(is_symbolless),
730     is_section_symbol_(false), use_plt_offset_(false), shndx_(shndx)
731 {
732   gold_assert(shndx != INVALID_CODE);
733   // this->type_ is a bitfield; make sure TYPE fits.
734   gold_assert(this->type_ == type);
735   this->u1_.gsym = gsym;
736   this->u2_.relobj = relobj;
737   if (dynamic)
738     this->set_needs_dynsym_index();
739 }
740
741 // A reloc against a local symbol.
742
743 template<bool dynamic, int size, bool big_endian>
744 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
745     Sized_relobj<size, big_endian>* relobj,
746     unsigned int local_sym_index,
747     unsigned int type,
748     Output_data* od,
749     Address address,
750     bool is_relative,
751     bool is_symbolless,
752     bool is_section_symbol,
753     bool use_plt_offset)
754   : address_(address), local_sym_index_(local_sym_index), type_(type),
755     is_relative_(is_relative), is_symbolless_(is_symbolless),
756     is_section_symbol_(is_section_symbol), use_plt_offset_(use_plt_offset),
757     shndx_(INVALID_CODE)
758 {
759   gold_assert(local_sym_index != GSYM_CODE
760               && local_sym_index != INVALID_CODE);
761   // this->type_ is a bitfield; make sure TYPE fits.
762   gold_assert(this->type_ == type);
763   this->u1_.relobj = relobj;
764   this->u2_.od = od;
765   if (dynamic)
766     this->set_needs_dynsym_index();
767 }
768
769 template<bool dynamic, int size, bool big_endian>
770 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
771     Sized_relobj<size, big_endian>* relobj,
772     unsigned int local_sym_index,
773     unsigned int type,
774     unsigned int shndx,
775     Address address,
776     bool is_relative,
777     bool is_symbolless,
778     bool is_section_symbol,
779     bool use_plt_offset)
780   : address_(address), local_sym_index_(local_sym_index), type_(type),
781     is_relative_(is_relative), is_symbolless_(is_symbolless),
782     is_section_symbol_(is_section_symbol), use_plt_offset_(use_plt_offset),
783     shndx_(shndx)
784 {
785   gold_assert(local_sym_index != GSYM_CODE
786               && local_sym_index != INVALID_CODE);
787   gold_assert(shndx != INVALID_CODE);
788   // this->type_ is a bitfield; make sure TYPE fits.
789   gold_assert(this->type_ == type);
790   this->u1_.relobj = relobj;
791   this->u2_.relobj = relobj;
792   if (dynamic)
793     this->set_needs_dynsym_index();
794 }
795
796 // A reloc against the STT_SECTION symbol of an output section.
797
798 template<bool dynamic, int size, bool big_endian>
799 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
800     Output_section* os,
801     unsigned int type,
802     Output_data* od,
803     Address address)
804   : address_(address), local_sym_index_(SECTION_CODE), type_(type),
805     is_relative_(false), is_symbolless_(false),
806     is_section_symbol_(true), use_plt_offset_(false), shndx_(INVALID_CODE)
807 {
808   // this->type_ is a bitfield; make sure TYPE fits.
809   gold_assert(this->type_ == type);
810   this->u1_.os = os;
811   this->u2_.od = od;
812   if (dynamic)
813     this->set_needs_dynsym_index();
814   else
815     os->set_needs_symtab_index();
816 }
817
818 template<bool dynamic, int size, bool big_endian>
819 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
820     Output_section* os,
821     unsigned int type,
822     Sized_relobj<size, big_endian>* relobj,
823     unsigned int shndx,
824     Address address)
825   : address_(address), local_sym_index_(SECTION_CODE), type_(type),
826     is_relative_(false), is_symbolless_(false),
827     is_section_symbol_(true), use_plt_offset_(false), shndx_(shndx)
828 {
829   gold_assert(shndx != INVALID_CODE);
830   // this->type_ is a bitfield; make sure TYPE fits.
831   gold_assert(this->type_ == type);
832   this->u1_.os = os;
833   this->u2_.relobj = relobj;
834   if (dynamic)
835     this->set_needs_dynsym_index();
836   else
837     os->set_needs_symtab_index();
838 }
839
840 // An absolute relocation.
841
842 template<bool dynamic, int size, bool big_endian>
843 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
844     unsigned int type,
845     Output_data* od,
846     Address address)
847   : address_(address), local_sym_index_(0), type_(type),
848     is_relative_(false), is_symbolless_(false),
849     is_section_symbol_(false), use_plt_offset_(false), shndx_(INVALID_CODE)
850 {
851   // this->type_ is a bitfield; make sure TYPE fits.
852   gold_assert(this->type_ == type);
853   this->u1_.relobj = NULL;
854   this->u2_.od = od;
855 }
856
857 template<bool dynamic, int size, bool big_endian>
858 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
859     unsigned int type,
860     Sized_relobj<size, big_endian>* relobj,
861     unsigned int shndx,
862     Address address)
863   : address_(address), local_sym_index_(0), type_(type),
864     is_relative_(false), is_symbolless_(false),
865     is_section_symbol_(false), use_plt_offset_(false), shndx_(shndx)
866 {
867   gold_assert(shndx != INVALID_CODE);
868   // this->type_ is a bitfield; make sure TYPE fits.
869   gold_assert(this->type_ == type);
870   this->u1_.relobj = NULL;
871   this->u2_.relobj = relobj;
872 }
873
874 // A target specific relocation.
875
876 template<bool dynamic, int size, bool big_endian>
877 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
878     unsigned int type,
879     void* arg,
880     Output_data* od,
881     Address address)
882   : address_(address), local_sym_index_(TARGET_CODE), type_(type),
883     is_relative_(false), is_symbolless_(false),
884     is_section_symbol_(false), use_plt_offset_(false), shndx_(INVALID_CODE)
885 {
886   // this->type_ is a bitfield; make sure TYPE fits.
887   gold_assert(this->type_ == type);
888   this->u1_.arg = arg;
889   this->u2_.od = od;
890 }
891
892 template<bool dynamic, int size, bool big_endian>
893 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
894     unsigned int type,
895     void* arg,
896     Sized_relobj<size, big_endian>* relobj,
897     unsigned int shndx,
898     Address address)
899   : address_(address), local_sym_index_(TARGET_CODE), type_(type),
900     is_relative_(false), is_symbolless_(false),
901     is_section_symbol_(false), use_plt_offset_(false), shndx_(shndx)
902 {
903   gold_assert(shndx != INVALID_CODE);
904   // this->type_ is a bitfield; make sure TYPE fits.
905   gold_assert(this->type_ == type);
906   this->u1_.arg = arg;
907   this->u2_.relobj = relobj;
908 }
909
910 // Record that we need a dynamic symbol index for this relocation.
911
912 template<bool dynamic, int size, bool big_endian>
913 void
914 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::
915 set_needs_dynsym_index()
916 {
917   if (this->is_symbolless_)
918     return;
919   switch (this->local_sym_index_)
920     {
921     case INVALID_CODE:
922       gold_unreachable();
923
924     case GSYM_CODE:
925       this->u1_.gsym->set_needs_dynsym_entry();
926       break;
927
928     case SECTION_CODE:
929       this->u1_.os->set_needs_dynsym_index();
930       break;
931
932     case TARGET_CODE:
933       // The target must take care of this if necessary.
934       break;
935
936     case 0:
937       break;
938
939     default:
940       {
941         const unsigned int lsi = this->local_sym_index_;
942         Sized_relobj_file<size, big_endian>* relobj =
943             this->u1_.relobj->sized_relobj();
944         gold_assert(relobj != NULL);
945         if (!this->is_section_symbol_)
946           relobj->set_needs_output_dynsym_entry(lsi);
947         else
948           relobj->output_section(lsi)->set_needs_dynsym_index();
949       }
950       break;
951     }
952 }
953
954 // Get the symbol index of a relocation.
955
956 template<bool dynamic, int size, bool big_endian>
957 unsigned int
958 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::get_symbol_index()
959   const
960 {
961   unsigned int index;
962   if (this->is_symbolless_)
963     return 0;
964   switch (this->local_sym_index_)
965     {
966     case INVALID_CODE:
967       gold_unreachable();
968
969     case GSYM_CODE:
970       if (this->u1_.gsym == NULL)
971         index = 0;
972       else if (dynamic)
973         index = this->u1_.gsym->dynsym_index();
974       else
975         index = this->u1_.gsym->symtab_index();
976       break;
977
978     case SECTION_CODE:
979       if (dynamic)
980         index = this->u1_.os->dynsym_index();
981       else
982         index = this->u1_.os->symtab_index();
983       break;
984
985     case TARGET_CODE:
986       index = parameters->target().reloc_symbol_index(this->u1_.arg,
987                                                       this->type_);
988       break;
989
990     case 0:
991       // Relocations without symbols use a symbol index of 0.
992       index = 0;
993       break;
994
995     default:
996       {
997         const unsigned int lsi = this->local_sym_index_;
998         Sized_relobj_file<size, big_endian>* relobj =
999             this->u1_.relobj->sized_relobj();
1000         gold_assert(relobj != NULL);
1001         if (!this->is_section_symbol_)
1002           {
1003             if (dynamic)
1004               index = relobj->dynsym_index(lsi);
1005             else
1006               index = relobj->symtab_index(lsi);
1007           }
1008         else
1009           {
1010             Output_section* os = relobj->output_section(lsi);
1011             gold_assert(os != NULL);
1012             if (dynamic)
1013               index = os->dynsym_index();
1014             else
1015               index = os->symtab_index();
1016           }
1017       }
1018       break;
1019     }
1020   gold_assert(index != -1U);
1021   return index;
1022 }
1023
1024 // For a local section symbol, get the address of the offset ADDEND
1025 // within the input section.
1026
1027 template<bool dynamic, int size, bool big_endian>
1028 typename elfcpp::Elf_types<size>::Elf_Addr
1029 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::
1030   local_section_offset(Addend addend) const
1031 {
1032   gold_assert(this->local_sym_index_ != GSYM_CODE
1033               && this->local_sym_index_ != SECTION_CODE
1034               && this->local_sym_index_ != TARGET_CODE
1035               && this->local_sym_index_ != INVALID_CODE
1036               && this->local_sym_index_ != 0
1037               && this->is_section_symbol_);
1038   const unsigned int lsi = this->local_sym_index_;
1039   Output_section* os = this->u1_.relobj->output_section(lsi);
1040   gold_assert(os != NULL);
1041   Address offset = this->u1_.relobj->get_output_section_offset(lsi);
1042   if (offset != invalid_address)
1043     return offset + addend;
1044   // This is a merge section.
1045   Sized_relobj_file<size, big_endian>* relobj =
1046       this->u1_.relobj->sized_relobj();
1047   gold_assert(relobj != NULL);
1048   offset = os->output_address(relobj, lsi, addend);
1049   gold_assert(offset != invalid_address);
1050   return offset;
1051 }
1052
1053 // Get the output address of a relocation.
1054
1055 template<bool dynamic, int size, bool big_endian>
1056 typename elfcpp::Elf_types<size>::Elf_Addr
1057 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::get_address() const
1058 {
1059   Address address = this->address_;
1060   if (this->shndx_ != INVALID_CODE)
1061     {
1062       Output_section* os = this->u2_.relobj->output_section(this->shndx_);
1063       gold_assert(os != NULL);
1064       Address off = this->u2_.relobj->get_output_section_offset(this->shndx_);
1065       if (off != invalid_address)
1066         address += os->address() + off;
1067       else
1068         {
1069           Sized_relobj_file<size, big_endian>* relobj =
1070               this->u2_.relobj->sized_relobj();
1071           gold_assert(relobj != NULL);
1072           address = os->output_address(relobj, this->shndx_, address);
1073           gold_assert(address != invalid_address);
1074         }
1075     }
1076   else if (this->u2_.od != NULL)
1077     address += this->u2_.od->address();
1078   return address;
1079 }
1080
1081 // Write out the offset and info fields of a Rel or Rela relocation
1082 // entry.
1083
1084 template<bool dynamic, int size, bool big_endian>
1085 template<typename Write_rel>
1086 void
1087 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::write_rel(
1088     Write_rel* wr) const
1089 {
1090   wr->put_r_offset(this->get_address());
1091   unsigned int sym_index = this->get_symbol_index();
1092   wr->put_r_info(elfcpp::elf_r_info<size>(sym_index, this->type_));
1093 }
1094
1095 // Write out a Rel relocation.
1096
1097 template<bool dynamic, int size, bool big_endian>
1098 void
1099 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::write(
1100     unsigned char* pov) const
1101 {
1102   elfcpp::Rel_write<size, big_endian> orel(pov);
1103   this->write_rel(&orel);
1104 }
1105
1106 // Get the value of the symbol referred to by a Rel relocation.
1107
1108 template<bool dynamic, int size, bool big_endian>
1109 typename elfcpp::Elf_types<size>::Elf_Addr
1110 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::symbol_value(
1111     Addend addend) const
1112 {
1113   if (this->local_sym_index_ == GSYM_CODE)
1114     {
1115       const Sized_symbol<size>* sym;
1116       sym = static_cast<const Sized_symbol<size>*>(this->u1_.gsym);
1117       return sym->value() + addend;
1118     }
1119   gold_assert(this->local_sym_index_ != SECTION_CODE
1120               && this->local_sym_index_ != TARGET_CODE
1121               && this->local_sym_index_ != INVALID_CODE
1122               && this->local_sym_index_ != 0
1123               && !this->is_section_symbol_);
1124   const unsigned int lsi = this->local_sym_index_;
1125   Sized_relobj_file<size, big_endian>* relobj =
1126       this->u1_.relobj->sized_relobj();
1127   gold_assert(relobj != NULL);
1128   if (this->use_plt_offset_)
1129     {
1130       uint64_t plt_address =
1131           parameters->target().plt_address_for_local(relobj, lsi);
1132       return plt_address + relobj->local_plt_offset(lsi);
1133     }
1134   const Symbol_value<size>* symval = relobj->local_symbol(lsi);
1135   return symval->value(relobj, addend);
1136 }
1137
1138 // Reloc comparison.  This function sorts the dynamic relocs for the
1139 // benefit of the dynamic linker.  First we sort all relative relocs
1140 // to the front.  Among relative relocs, we sort by output address.
1141 // Among non-relative relocs, we sort by symbol index, then by output
1142 // address.
1143
1144 template<bool dynamic, int size, bool big_endian>
1145 int
1146 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::
1147   compare(const Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>& r2)
1148     const
1149 {
1150   if (this->is_relative_)
1151     {
1152       if (!r2.is_relative_)
1153         return -1;
1154       // Otherwise sort by reloc address below.
1155     }
1156   else if (r2.is_relative_)
1157     return 1;
1158   else
1159     {
1160       unsigned int sym1 = this->get_symbol_index();
1161       unsigned int sym2 = r2.get_symbol_index();
1162       if (sym1 < sym2)
1163         return -1;
1164       else if (sym1 > sym2)
1165         return 1;
1166       // Otherwise sort by reloc address.
1167     }
1168
1169   section_offset_type addr1 = this->get_address();
1170   section_offset_type addr2 = r2.get_address();
1171   if (addr1 < addr2)
1172     return -1;
1173   else if (addr1 > addr2)
1174     return 1;
1175
1176   // Final tie breaker, in order to generate the same output on any
1177   // host: reloc type.
1178   unsigned int type1 = this->type_;
1179   unsigned int type2 = r2.type_;
1180   if (type1 < type2)
1181     return -1;
1182   else if (type1 > type2)
1183     return 1;
1184
1185   // These relocs appear to be exactly the same.
1186   return 0;
1187 }
1188
1189 // Write out a Rela relocation.
1190
1191 template<bool dynamic, int size, bool big_endian>
1192 void
1193 Output_reloc<elfcpp::SHT_RELA, dynamic, size, big_endian>::write(
1194     unsigned char* pov) const
1195 {
1196   elfcpp::Rela_write<size, big_endian> orel(pov);
1197   this->rel_.write_rel(&orel);
1198   Addend addend = this->addend_;
1199   if (this->rel_.is_target_specific())
1200     addend = parameters->target().reloc_addend(this->rel_.target_arg(),
1201                                                this->rel_.type(), addend);
1202   else if (this->rel_.is_symbolless())
1203     addend = this->rel_.symbol_value(addend);
1204   else if (this->rel_.is_local_section_symbol())
1205     addend = this->rel_.local_section_offset(addend);
1206   orel.put_r_addend(addend);
1207 }
1208
1209 // Output_data_reloc_base methods.
1210
1211 // Adjust the output section.
1212
1213 template<int sh_type, bool dynamic, int size, bool big_endian>
1214 void
1215 Output_data_reloc_base<sh_type, dynamic, size, big_endian>
1216     ::do_adjust_output_section(Output_section* os)
1217 {
1218   if (sh_type == elfcpp::SHT_REL)
1219     os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
1220   else if (sh_type == elfcpp::SHT_RELA)
1221     os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
1222   else
1223     gold_unreachable();
1224
1225   // A STT_GNU_IFUNC symbol may require a IRELATIVE reloc when doing a
1226   // static link.  The backends will generate a dynamic reloc section
1227   // to hold this.  In that case we don't want to link to the dynsym
1228   // section, because there isn't one.
1229   if (!dynamic)
1230     os->set_should_link_to_symtab();
1231   else if (parameters->doing_static_link())
1232     ;
1233   else
1234     os->set_should_link_to_dynsym();
1235 }
1236
1237 // Write out relocation data.
1238
1239 template<int sh_type, bool dynamic, int size, bool big_endian>
1240 void
1241 Output_data_reloc_base<sh_type, dynamic, size, big_endian>::do_write(
1242     Output_file* of)
1243 {
1244   const off_t off = this->offset();
1245   const off_t oview_size = this->data_size();
1246   unsigned char* const oview = of->get_output_view(off, oview_size);
1247
1248   if (this->sort_relocs())
1249     {
1250       gold_assert(dynamic);
1251       std::sort(this->relocs_.begin(), this->relocs_.end(),
1252                 Sort_relocs_comparison());
1253     }
1254
1255   unsigned char* pov = oview;
1256   for (typename Relocs::const_iterator p = this->relocs_.begin();
1257        p != this->relocs_.end();
1258        ++p)
1259     {
1260       p->write(pov);
1261       pov += reloc_size;
1262     }
1263
1264   gold_assert(pov - oview == oview_size);
1265
1266   of->write_output_view(off, oview_size, oview);
1267
1268   // We no longer need the relocation entries.
1269   this->relocs_.clear();
1270 }
1271
1272 // Class Output_relocatable_relocs.
1273
1274 template<int sh_type, int size, bool big_endian>
1275 void
1276 Output_relocatable_relocs<sh_type, size, big_endian>::set_final_data_size()
1277 {
1278   this->set_data_size(this->rr_->output_reloc_count()
1279                       * Reloc_types<sh_type, size, big_endian>::reloc_size);
1280 }
1281
1282 // class Output_data_group.
1283
1284 template<int size, bool big_endian>
1285 Output_data_group<size, big_endian>::Output_data_group(
1286     Sized_relobj_file<size, big_endian>* relobj,
1287     section_size_type entry_count,
1288     elfcpp::Elf_Word flags,
1289     std::vector<unsigned int>* input_shndxes)
1290   : Output_section_data(entry_count * 4, 4, false),
1291     relobj_(relobj),
1292     flags_(flags)
1293 {
1294   this->input_shndxes_.swap(*input_shndxes);
1295 }
1296
1297 // Write out the section group, which means translating the section
1298 // indexes to apply to the output file.
1299
1300 template<int size, bool big_endian>
1301 void
1302 Output_data_group<size, big_endian>::do_write(Output_file* of)
1303 {
1304   const off_t off = this->offset();
1305   const section_size_type oview_size =
1306     convert_to_section_size_type(this->data_size());
1307   unsigned char* const oview = of->get_output_view(off, oview_size);
1308
1309   elfcpp::Elf_Word* contents = reinterpret_cast<elfcpp::Elf_Word*>(oview);
1310   elfcpp::Swap<32, big_endian>::writeval(contents, this->flags_);
1311   ++contents;
1312
1313   for (std::vector<unsigned int>::const_iterator p =
1314          this->input_shndxes_.begin();
1315        p != this->input_shndxes_.end();
1316        ++p, ++contents)
1317     {
1318       Output_section* os = this->relobj_->output_section(*p);
1319
1320       unsigned int output_shndx;
1321       if (os != NULL)
1322         output_shndx = os->out_shndx();
1323       else
1324         {
1325           this->relobj_->error(_("section group retained but "
1326                                  "group element discarded"));
1327           output_shndx = 0;
1328         }
1329
1330       elfcpp::Swap<32, big_endian>::writeval(contents, output_shndx);
1331     }
1332
1333   size_t wrote = reinterpret_cast<unsigned char*>(contents) - oview;
1334   gold_assert(wrote == oview_size);
1335
1336   of->write_output_view(off, oview_size, oview);
1337
1338   // We no longer need this information.
1339   this->input_shndxes_.clear();
1340 }
1341
1342 // Output_data_got::Got_entry methods.
1343
1344 // Write out the entry.
1345
1346 template<int size, bool big_endian>
1347 void
1348 Output_data_got<size, big_endian>::Got_entry::write(unsigned char* pov) const
1349 {
1350   Valtype val = 0;
1351
1352   switch (this->local_sym_index_)
1353     {
1354     case GSYM_CODE:
1355       {
1356         // If the symbol is resolved locally, we need to write out the
1357         // link-time value, which will be relocated dynamically by a
1358         // RELATIVE relocation.
1359         Symbol* gsym = this->u_.gsym;
1360         if (this->use_plt_offset_ && gsym->has_plt_offset())
1361           val = (parameters->target().plt_address_for_global(gsym)
1362                  + gsym->plt_offset());
1363         else
1364           {
1365             Sized_symbol<size>* sgsym;
1366             // This cast is a bit ugly.  We don't want to put a
1367             // virtual method in Symbol, because we want Symbol to be
1368             // as small as possible.
1369             sgsym = static_cast<Sized_symbol<size>*>(gsym);
1370             val = sgsym->value();
1371           }
1372       }
1373       break;
1374
1375     case CONSTANT_CODE:
1376       val = this->u_.constant;
1377       break;
1378
1379     case RESERVED_CODE:
1380       // If we're doing an incremental update, don't touch this GOT entry.
1381       if (parameters->incremental_update())
1382         return;
1383       val = this->u_.constant;
1384       break;
1385
1386     default:
1387       {
1388         const Sized_relobj_file<size, big_endian>* object = this->u_.object;
1389         const unsigned int lsi = this->local_sym_index_;
1390         const Symbol_value<size>* symval = object->local_symbol(lsi);
1391         if (!this->use_plt_offset_)
1392           val = symval->value(this->u_.object, 0);
1393         else
1394           {
1395             uint64_t plt_address =
1396               parameters->target().plt_address_for_local(object, lsi);
1397             val = plt_address + object->local_plt_offset(lsi);
1398           }
1399       }
1400       break;
1401     }
1402
1403   elfcpp::Swap<size, big_endian>::writeval(pov, val);
1404 }
1405
1406 // Output_data_got methods.
1407
1408 // Add an entry for a global symbol to the GOT.  This returns true if
1409 // this is a new GOT entry, false if the symbol already had a GOT
1410 // entry.
1411
1412 template<int size, bool big_endian>
1413 bool
1414 Output_data_got<size, big_endian>::add_global(
1415     Symbol* gsym,
1416     unsigned int got_type)
1417 {
1418   if (gsym->has_got_offset(got_type))
1419     return false;
1420
1421   unsigned int got_offset = this->add_got_entry(Got_entry(gsym, false));
1422   gsym->set_got_offset(got_type, got_offset);
1423   return true;
1424 }
1425
1426 // Like add_global, but use the PLT offset.
1427
1428 template<int size, bool big_endian>
1429 bool
1430 Output_data_got<size, big_endian>::add_global_plt(Symbol* gsym,
1431                                                   unsigned int got_type)
1432 {
1433   if (gsym->has_got_offset(got_type))
1434     return false;
1435
1436   unsigned int got_offset = this->add_got_entry(Got_entry(gsym, true));
1437   gsym->set_got_offset(got_type, got_offset);
1438   return true;
1439 }
1440
1441 // Add an entry for a global symbol to the GOT, and add a dynamic
1442 // relocation of type R_TYPE for the GOT entry.
1443
1444 template<int size, bool big_endian>
1445 void
1446 Output_data_got<size, big_endian>::add_global_with_rel(
1447     Symbol* gsym,
1448     unsigned int got_type,
1449     Rel_dyn* rel_dyn,
1450     unsigned int r_type)
1451 {
1452   if (gsym->has_got_offset(got_type))
1453     return;
1454
1455   unsigned int got_offset = this->add_got_entry(Got_entry());
1456   gsym->set_got_offset(got_type, got_offset);
1457   rel_dyn->add_global(gsym, r_type, this, got_offset);
1458 }
1459
1460 template<int size, bool big_endian>
1461 void
1462 Output_data_got<size, big_endian>::add_global_with_rela(
1463     Symbol* gsym,
1464     unsigned int got_type,
1465     Rela_dyn* rela_dyn,
1466     unsigned int r_type)
1467 {
1468   if (gsym->has_got_offset(got_type))
1469     return;
1470
1471   unsigned int got_offset = this->add_got_entry(Got_entry());
1472   gsym->set_got_offset(got_type, got_offset);
1473   rela_dyn->add_global(gsym, r_type, this, got_offset, 0);
1474 }
1475
1476 // Add a pair of entries for a global symbol to the GOT, and add
1477 // dynamic relocations of type R_TYPE_1 and R_TYPE_2, respectively.
1478 // If R_TYPE_2 == 0, add the second entry with no relocation.
1479 template<int size, bool big_endian>
1480 void
1481 Output_data_got<size, big_endian>::add_global_pair_with_rel(
1482     Symbol* gsym,
1483     unsigned int got_type,
1484     Rel_dyn* rel_dyn,
1485     unsigned int r_type_1,
1486     unsigned int r_type_2)
1487 {
1488   if (gsym->has_got_offset(got_type))
1489     return;
1490
1491   unsigned int got_offset = this->add_got_entry_pair(Got_entry(), Got_entry());
1492   gsym->set_got_offset(got_type, got_offset);
1493   rel_dyn->add_global(gsym, r_type_1, this, got_offset);
1494
1495   if (r_type_2 != 0)
1496     rel_dyn->add_global(gsym, r_type_2, this, got_offset + size / 8);
1497 }
1498
1499 template<int size, bool big_endian>
1500 void
1501 Output_data_got<size, big_endian>::add_global_pair_with_rela(
1502     Symbol* gsym,
1503     unsigned int got_type,
1504     Rela_dyn* rela_dyn,
1505     unsigned int r_type_1,
1506     unsigned int r_type_2)
1507 {
1508   if (gsym->has_got_offset(got_type))
1509     return;
1510
1511   unsigned int got_offset = this->add_got_entry_pair(Got_entry(), Got_entry());
1512   gsym->set_got_offset(got_type, got_offset);
1513   rela_dyn->add_global(gsym, r_type_1, this, got_offset, 0);
1514
1515   if (r_type_2 != 0)
1516     rela_dyn->add_global(gsym, r_type_2, this, got_offset + size / 8, 0);
1517 }
1518
1519 // Add an entry for a local symbol to the GOT.  This returns true if
1520 // this is a new GOT entry, false if the symbol already has a GOT
1521 // entry.
1522
1523 template<int size, bool big_endian>
1524 bool
1525 Output_data_got<size, big_endian>::add_local(
1526     Sized_relobj_file<size, big_endian>* object,
1527     unsigned int symndx,
1528     unsigned int got_type)
1529 {
1530   if (object->local_has_got_offset(symndx, got_type))
1531     return false;
1532
1533   unsigned int got_offset = this->add_got_entry(Got_entry(object, symndx,
1534                                                           false));
1535   object->set_local_got_offset(symndx, got_type, got_offset);
1536   return true;
1537 }
1538
1539 // Like add_local, but use the PLT offset.
1540
1541 template<int size, bool big_endian>
1542 bool
1543 Output_data_got<size, big_endian>::add_local_plt(
1544     Sized_relobj_file<size, big_endian>* object,
1545     unsigned int symndx,
1546     unsigned int got_type)
1547 {
1548   if (object->local_has_got_offset(symndx, got_type))
1549     return false;
1550
1551   unsigned int got_offset = this->add_got_entry(Got_entry(object, symndx,
1552                                                           true));
1553   object->set_local_got_offset(symndx, got_type, got_offset);
1554   return true;
1555 }
1556
1557 // Add an entry for a local symbol to the GOT, and add a dynamic
1558 // relocation of type R_TYPE for the GOT entry.
1559
1560 template<int size, bool big_endian>
1561 void
1562 Output_data_got<size, big_endian>::add_local_with_rel(
1563     Sized_relobj_file<size, big_endian>* object,
1564     unsigned int symndx,
1565     unsigned int got_type,
1566     Rel_dyn* rel_dyn,
1567     unsigned int r_type)
1568 {
1569   if (object->local_has_got_offset(symndx, got_type))
1570     return;
1571
1572   unsigned int got_offset = this->add_got_entry(Got_entry());
1573   object->set_local_got_offset(symndx, got_type, got_offset);
1574   rel_dyn->add_local(object, symndx, r_type, this, got_offset);
1575 }
1576
1577 template<int size, bool big_endian>
1578 void
1579 Output_data_got<size, big_endian>::add_local_with_rela(
1580     Sized_relobj_file<size, big_endian>* object,
1581     unsigned int symndx,
1582     unsigned int got_type,
1583     Rela_dyn* rela_dyn,
1584     unsigned int r_type)
1585 {
1586   if (object->local_has_got_offset(symndx, got_type))
1587     return;
1588
1589   unsigned int got_offset = this->add_got_entry(Got_entry());
1590   object->set_local_got_offset(symndx, got_type, got_offset);
1591   rela_dyn->add_local(object, symndx, r_type, this, got_offset, 0);
1592 }
1593
1594 // Add a pair of entries for a local symbol to the GOT, and add
1595 // dynamic relocations of type R_TYPE_1 and R_TYPE_2, respectively.
1596 // If R_TYPE_2 == 0, add the second entry with no relocation.
1597 template<int size, bool big_endian>
1598 void
1599 Output_data_got<size, big_endian>::add_local_pair_with_rel(
1600     Sized_relobj_file<size, big_endian>* object,
1601     unsigned int symndx,
1602     unsigned int shndx,
1603     unsigned int got_type,
1604     Rel_dyn* rel_dyn,
1605     unsigned int r_type_1,
1606     unsigned int r_type_2)
1607 {
1608   if (object->local_has_got_offset(symndx, got_type))
1609     return;
1610
1611   unsigned int got_offset =
1612       this->add_got_entry_pair(Got_entry(),
1613                                Got_entry(object, symndx, false));
1614   object->set_local_got_offset(symndx, got_type, got_offset);
1615   Output_section* os = object->output_section(shndx);
1616   rel_dyn->add_output_section(os, r_type_1, this, got_offset);
1617
1618   if (r_type_2 != 0)
1619     rel_dyn->add_output_section(os, r_type_2, this, got_offset + size / 8);
1620 }
1621
1622 template<int size, bool big_endian>
1623 void
1624 Output_data_got<size, big_endian>::add_local_pair_with_rela(
1625     Sized_relobj_file<size, big_endian>* object,
1626     unsigned int symndx,
1627     unsigned int shndx,
1628     unsigned int got_type,
1629     Rela_dyn* rela_dyn,
1630     unsigned int r_type_1,
1631     unsigned int r_type_2)
1632 {
1633   if (object->local_has_got_offset(symndx, got_type))
1634     return;
1635
1636   unsigned int got_offset =
1637       this->add_got_entry_pair(Got_entry(),
1638                                Got_entry(object, symndx, false));
1639   object->set_local_got_offset(symndx, got_type, got_offset);
1640   Output_section* os = object->output_section(shndx);
1641   rela_dyn->add_output_section(os, r_type_1, this, got_offset, 0);
1642
1643   if (r_type_2 != 0)
1644     rela_dyn->add_output_section(os, r_type_2, this, got_offset + size / 8, 0);
1645 }
1646
1647 // Reserve a slot in the GOT for a local symbol or the second slot of a pair.
1648
1649 template<int size, bool big_endian>
1650 void
1651 Output_data_got<size, big_endian>::reserve_local(
1652     unsigned int i,
1653     Sized_relobj<size, big_endian>* object,
1654     unsigned int sym_index,
1655     unsigned int got_type)
1656 {
1657   this->reserve_slot(i);
1658   object->set_local_got_offset(sym_index, got_type, this->got_offset(i));
1659 }
1660
1661 // Reserve a slot in the GOT for a global symbol.
1662
1663 template<int size, bool big_endian>
1664 void
1665 Output_data_got<size, big_endian>::reserve_global(
1666     unsigned int i,
1667     Symbol* gsym,
1668     unsigned int got_type)
1669 {
1670   this->reserve_slot(i);
1671   gsym->set_got_offset(got_type, this->got_offset(i));
1672 }
1673
1674 // Write out the GOT.
1675
1676 template<int size, bool big_endian>
1677 void
1678 Output_data_got<size, big_endian>::do_write(Output_file* of)
1679 {
1680   const int add = size / 8;
1681
1682   const off_t off = this->offset();
1683   const off_t oview_size = this->data_size();
1684   unsigned char* const oview = of->get_output_view(off, oview_size);
1685
1686   unsigned char* pov = oview;
1687   for (typename Got_entries::const_iterator p = this->entries_.begin();
1688        p != this->entries_.end();
1689        ++p)
1690     {
1691       p->write(pov);
1692       pov += add;
1693     }
1694
1695   gold_assert(pov - oview == oview_size);
1696
1697   of->write_output_view(off, oview_size, oview);
1698
1699   // We no longer need the GOT entries.
1700   this->entries_.clear();
1701 }
1702
1703 // Create a new GOT entry and return its offset.
1704
1705 template<int size, bool big_endian>
1706 unsigned int
1707 Output_data_got<size, big_endian>::add_got_entry(Got_entry got_entry)
1708 {
1709   if (!this->is_data_size_valid())
1710     {
1711       this->entries_.push_back(got_entry);
1712       this->set_got_size();
1713       return this->last_got_offset();
1714     }
1715   else
1716     {
1717       // For an incremental update, find an available slot.
1718       off_t got_offset = this->free_list_.allocate(size / 8, size / 8, 0);
1719       if (got_offset == -1)
1720         gold_fallback(_("out of patch space (GOT);"
1721                         " relink with --incremental-full"));
1722       unsigned int got_index = got_offset / (size / 8);
1723       gold_assert(got_index < this->entries_.size());
1724       this->entries_[got_index] = got_entry;
1725       return static_cast<unsigned int>(got_offset);
1726     }
1727 }
1728
1729 // Create a pair of new GOT entries and return the offset of the first.
1730
1731 template<int size, bool big_endian>
1732 unsigned int
1733 Output_data_got<size, big_endian>::add_got_entry_pair(Got_entry got_entry_1,
1734                                                       Got_entry got_entry_2)
1735 {
1736   if (!this->is_data_size_valid())
1737     {
1738       unsigned int got_offset;
1739       this->entries_.push_back(got_entry_1);
1740       got_offset = this->last_got_offset();
1741       this->entries_.push_back(got_entry_2);
1742       this->set_got_size();
1743       return got_offset;
1744     }
1745   else
1746     {
1747       // For an incremental update, find an available pair of slots.
1748       off_t got_offset = this->free_list_.allocate(2 * size / 8, size / 8, 0);
1749       if (got_offset == -1)
1750         gold_fallback(_("out of patch space (GOT);"
1751                         " relink with --incremental-full"));
1752       unsigned int got_index = got_offset / (size / 8);
1753       gold_assert(got_index < this->entries_.size());
1754       this->entries_[got_index] = got_entry_1;
1755       this->entries_[got_index + 1] = got_entry_2;
1756       return static_cast<unsigned int>(got_offset);
1757     }
1758 }
1759
1760 // Output_data_dynamic::Dynamic_entry methods.
1761
1762 // Write out the entry.
1763
1764 template<int size, bool big_endian>
1765 void
1766 Output_data_dynamic::Dynamic_entry::write(
1767     unsigned char* pov,
1768     const Stringpool* pool) const
1769 {
1770   typename elfcpp::Elf_types<size>::Elf_WXword val;
1771   switch (this->offset_)
1772     {
1773     case DYNAMIC_NUMBER:
1774       val = this->u_.val;
1775       break;
1776
1777     case DYNAMIC_SECTION_SIZE:
1778       val = this->u_.od->data_size();
1779       if (this->od2 != NULL)
1780         val += this->od2->data_size();
1781       break;
1782
1783     case DYNAMIC_SYMBOL:
1784       {
1785         const Sized_symbol<size>* s =
1786           static_cast<const Sized_symbol<size>*>(this->u_.sym);
1787         val = s->value();
1788       }
1789       break;
1790
1791     case DYNAMIC_STRING:
1792       val = pool->get_offset(this->u_.str);
1793       break;
1794
1795     default:
1796       val = this->u_.od->address() + this->offset_;
1797       break;
1798     }
1799
1800   elfcpp::Dyn_write<size, big_endian> dw(pov);
1801   dw.put_d_tag(this->tag_);
1802   dw.put_d_val(val);
1803 }
1804
1805 // Output_data_dynamic methods.
1806
1807 // Adjust the output section to set the entry size.
1808
1809 void
1810 Output_data_dynamic::do_adjust_output_section(Output_section* os)
1811 {
1812   if (parameters->target().get_size() == 32)
1813     os->set_entsize(elfcpp::Elf_sizes<32>::dyn_size);
1814   else if (parameters->target().get_size() == 64)
1815     os->set_entsize(elfcpp::Elf_sizes<64>::dyn_size);
1816   else
1817     gold_unreachable();
1818 }
1819
1820 // Set the final data size.
1821
1822 void
1823 Output_data_dynamic::set_final_data_size()
1824 {
1825   // Add the terminating entry if it hasn't been added.
1826   // Because of relaxation, we can run this multiple times.
1827   if (this->entries_.empty() || this->entries_.back().tag() != elfcpp::DT_NULL)
1828     {
1829       int extra = parameters->options().spare_dynamic_tags();
1830       for (int i = 0; i < extra; ++i)
1831         this->add_constant(elfcpp::DT_NULL, 0);
1832       this->add_constant(elfcpp::DT_NULL, 0);
1833     }
1834
1835   int dyn_size;
1836   if (parameters->target().get_size() == 32)
1837     dyn_size = elfcpp::Elf_sizes<32>::dyn_size;
1838   else if (parameters->target().get_size() == 64)
1839     dyn_size = elfcpp::Elf_sizes<64>::dyn_size;
1840   else
1841     gold_unreachable();
1842   this->set_data_size(this->entries_.size() * dyn_size);
1843 }
1844
1845 // Write out the dynamic entries.
1846
1847 void
1848 Output_data_dynamic::do_write(Output_file* of)
1849 {
1850   switch (parameters->size_and_endianness())
1851     {
1852 #ifdef HAVE_TARGET_32_LITTLE
1853     case Parameters::TARGET_32_LITTLE:
1854       this->sized_write<32, false>(of);
1855       break;
1856 #endif
1857 #ifdef HAVE_TARGET_32_BIG
1858     case Parameters::TARGET_32_BIG:
1859       this->sized_write<32, true>(of);
1860       break;
1861 #endif
1862 #ifdef HAVE_TARGET_64_LITTLE
1863     case Parameters::TARGET_64_LITTLE:
1864       this->sized_write<64, false>(of);
1865       break;
1866 #endif
1867 #ifdef HAVE_TARGET_64_BIG
1868     case Parameters::TARGET_64_BIG:
1869       this->sized_write<64, true>(of);
1870       break;
1871 #endif
1872     default:
1873       gold_unreachable();
1874     }
1875 }
1876
1877 template<int size, bool big_endian>
1878 void
1879 Output_data_dynamic::sized_write(Output_file* of)
1880 {
1881   const int dyn_size = elfcpp::Elf_sizes<size>::dyn_size;
1882
1883   const off_t offset = this->offset();
1884   const off_t oview_size = this->data_size();
1885   unsigned char* const oview = of->get_output_view(offset, oview_size);
1886
1887   unsigned char* pov = oview;
1888   for (typename Dynamic_entries::const_iterator p = this->entries_.begin();
1889        p != this->entries_.end();
1890        ++p)
1891     {
1892       p->write<size, big_endian>(pov, this->pool_);
1893       pov += dyn_size;
1894     }
1895
1896   gold_assert(pov - oview == oview_size);
1897
1898   of->write_output_view(offset, oview_size, oview);
1899
1900   // We no longer need the dynamic entries.
1901   this->entries_.clear();
1902 }
1903
1904 // Class Output_symtab_xindex.
1905
1906 void
1907 Output_symtab_xindex::do_write(Output_file* of)
1908 {
1909   const off_t offset = this->offset();
1910   const off_t oview_size = this->data_size();
1911   unsigned char* const oview = of->get_output_view(offset, oview_size);
1912
1913   memset(oview, 0, oview_size);
1914
1915   if (parameters->target().is_big_endian())
1916     this->endian_do_write<true>(oview);
1917   else
1918     this->endian_do_write<false>(oview);
1919
1920   of->write_output_view(offset, oview_size, oview);
1921
1922   // We no longer need the data.
1923   this->entries_.clear();
1924 }
1925
1926 template<bool big_endian>
1927 void
1928 Output_symtab_xindex::endian_do_write(unsigned char* const oview)
1929 {
1930   for (Xindex_entries::const_iterator p = this->entries_.begin();
1931        p != this->entries_.end();
1932        ++p)
1933     {
1934       unsigned int symndx = p->first;
1935       gold_assert(symndx * 4 < this->data_size());
1936       elfcpp::Swap<32, big_endian>::writeval(oview + symndx * 4, p->second);
1937     }
1938 }
1939
1940 // Output_fill_debug_info methods.
1941
1942 // Return the minimum size needed for a dummy compilation unit header.
1943
1944 size_t
1945 Output_fill_debug_info::do_minimum_hole_size() const
1946 {
1947   // Compile unit header fields: unit_length, version, debug_abbrev_offset,
1948   // address_size.
1949   const size_t len = 4 + 2 + 4 + 1;
1950   // For type units, add type_signature, type_offset.
1951   if (this->is_debug_types_)
1952     return len + 8 + 4;
1953   return len;
1954 }
1955
1956 // Write a dummy compilation unit header to fill a hole in the
1957 // .debug_info or .debug_types section.
1958
1959 void
1960 Output_fill_debug_info::do_write(Output_file* of, off_t off, size_t len) const
1961 {
1962   gold_debug(DEBUG_INCREMENTAL, "fill_debug_info(%08lx, %08lx)",
1963              static_cast<long>(off), static_cast<long>(len));
1964
1965   gold_assert(len >= this->do_minimum_hole_size());
1966
1967   unsigned char* const oview = of->get_output_view(off, len);
1968   unsigned char* pov = oview;
1969
1970   // Write header fields: unit_length, version, debug_abbrev_offset,
1971   // address_size.
1972   if (this->is_big_endian())
1973     {
1974       elfcpp::Swap_unaligned<32, true>::writeval(pov, len - 4);
1975       elfcpp::Swap_unaligned<16, true>::writeval(pov + 4, this->version);
1976       elfcpp::Swap_unaligned<32, true>::writeval(pov + 6, 0);
1977     }
1978   else
1979     {
1980       elfcpp::Swap_unaligned<32, false>::writeval(pov, len - 4);
1981       elfcpp::Swap_unaligned<16, false>::writeval(pov + 4, this->version);
1982       elfcpp::Swap_unaligned<32, false>::writeval(pov + 6, 0);
1983     }
1984   pov += 4 + 2 + 4;
1985   *pov++ = 4;
1986
1987   // For type units, the additional header fields -- type_signature,
1988   // type_offset -- can be filled with zeroes.
1989
1990   // Fill the remainder of the free space with zeroes.  The first
1991   // zero should tell the consumer there are no DIEs to read in this
1992   // compilation unit.
1993   if (pov < oview + len)
1994     memset(pov, 0, oview + len - pov);
1995
1996   of->write_output_view(off, len, oview);
1997 }
1998
1999 // Output_fill_debug_line methods.
2000
2001 // Return the minimum size needed for a dummy line number program header.
2002
2003 size_t
2004 Output_fill_debug_line::do_minimum_hole_size() const
2005 {
2006   // Line number program header fields: unit_length, version, header_length,
2007   // minimum_instruction_length, default_is_stmt, line_base, line_range,
2008   // opcode_base, standard_opcode_lengths[], include_directories, filenames.
2009   const size_t len = 4 + 2 + 4 + this->header_length;
2010   return len;
2011 }
2012
2013 // Write a dummy line number program header to fill a hole in the
2014 // .debug_line section.
2015
2016 void
2017 Output_fill_debug_line::do_write(Output_file* of, off_t off, size_t len) const
2018 {
2019   gold_debug(DEBUG_INCREMENTAL, "fill_debug_line(%08lx, %08lx)",
2020              static_cast<long>(off), static_cast<long>(len));
2021
2022   gold_assert(len >= this->do_minimum_hole_size());
2023
2024   unsigned char* const oview = of->get_output_view(off, len);
2025   unsigned char* pov = oview;
2026
2027   // Write header fields: unit_length, version, header_length,
2028   // minimum_instruction_length, default_is_stmt, line_base, line_range,
2029   // opcode_base, standard_opcode_lengths[], include_directories, filenames.
2030   // We set the header_length field to cover the entire hole, so the
2031   // line number program is empty.
2032   if (this->is_big_endian())
2033     {
2034       elfcpp::Swap_unaligned<32, true>::writeval(pov, len - 4);
2035       elfcpp::Swap_unaligned<16, true>::writeval(pov + 4, this->version);
2036       elfcpp::Swap_unaligned<32, true>::writeval(pov + 6, len - (4 + 2 + 4));
2037     }
2038   else
2039     {
2040       elfcpp::Swap_unaligned<32, false>::writeval(pov, len - 4);
2041       elfcpp::Swap_unaligned<16, false>::writeval(pov + 4, this->version);
2042       elfcpp::Swap_unaligned<32, false>::writeval(pov + 6, len - (4 + 2 + 4));
2043     }
2044   pov += 4 + 2 + 4;
2045   *pov++ = 1;   // minimum_instruction_length
2046   *pov++ = 0;   // default_is_stmt
2047   *pov++ = 0;   // line_base
2048   *pov++ = 5;   // line_range
2049   *pov++ = 13;  // opcode_base
2050   *pov++ = 0;   // standard_opcode_lengths[1]
2051   *pov++ = 1;   // standard_opcode_lengths[2]
2052   *pov++ = 1;   // standard_opcode_lengths[3]
2053   *pov++ = 1;   // standard_opcode_lengths[4]
2054   *pov++ = 1;   // standard_opcode_lengths[5]
2055   *pov++ = 0;   // standard_opcode_lengths[6]
2056   *pov++ = 0;   // standard_opcode_lengths[7]
2057   *pov++ = 0;   // standard_opcode_lengths[8]
2058   *pov++ = 1;   // standard_opcode_lengths[9]
2059   *pov++ = 0;   // standard_opcode_lengths[10]
2060   *pov++ = 0;   // standard_opcode_lengths[11]
2061   *pov++ = 1;   // standard_opcode_lengths[12]
2062   *pov++ = 0;   // include_directories (empty)
2063   *pov++ = 0;   // filenames (empty)
2064
2065   // Some consumers don't check the header_length field, and simply
2066   // start reading the line number program immediately following the
2067   // header.  For those consumers, we fill the remainder of the free
2068   // space with DW_LNS_set_basic_block opcodes.  These are effectively
2069   // no-ops: the resulting line table program will not create any rows.
2070   if (pov < oview + len)
2071     memset(pov, elfcpp::DW_LNS_set_basic_block, oview + len - pov);
2072
2073   of->write_output_view(off, len, oview);
2074 }
2075
2076 // Output_section::Input_section methods.
2077
2078 // Return the current data size.  For an input section we store the size here.
2079 // For an Output_section_data, we have to ask it for the size.
2080
2081 off_t
2082 Output_section::Input_section::current_data_size() const
2083 {
2084   if (this->is_input_section())
2085     return this->u1_.data_size;
2086   else
2087     {
2088       this->u2_.posd->pre_finalize_data_size();
2089       return this->u2_.posd->current_data_size();
2090     }
2091 }
2092
2093 // Return the data size.  For an input section we store the size here.
2094 // For an Output_section_data, we have to ask it for the size.
2095
2096 off_t
2097 Output_section::Input_section::data_size() const
2098 {
2099   if (this->is_input_section())
2100     return this->u1_.data_size;
2101   else
2102     return this->u2_.posd->data_size();
2103 }
2104
2105 // Return the object for an input section.
2106
2107 Relobj*
2108 Output_section::Input_section::relobj() const
2109 {
2110   if (this->is_input_section())
2111     return this->u2_.object;
2112   else if (this->is_merge_section())
2113     {
2114       gold_assert(this->u2_.pomb->first_relobj() != NULL);
2115       return this->u2_.pomb->first_relobj();
2116     }
2117   else if (this->is_relaxed_input_section())
2118     return this->u2_.poris->relobj();
2119   else
2120     gold_unreachable();
2121 }
2122
2123 // Return the input section index for an input section.
2124
2125 unsigned int
2126 Output_section::Input_section::shndx() const
2127 {
2128   if (this->is_input_section())
2129     return this->shndx_;
2130   else if (this->is_merge_section())
2131     {
2132       gold_assert(this->u2_.pomb->first_relobj() != NULL);
2133       return this->u2_.pomb->first_shndx();
2134     }
2135   else if (this->is_relaxed_input_section())
2136     return this->u2_.poris->shndx();
2137   else
2138     gold_unreachable();
2139 }
2140
2141 // Set the address and file offset.
2142
2143 void
2144 Output_section::Input_section::set_address_and_file_offset(
2145     uint64_t address,
2146     off_t file_offset,
2147     off_t section_file_offset)
2148 {
2149   if (this->is_input_section())
2150     this->u2_.object->set_section_offset(this->shndx_,
2151                                          file_offset - section_file_offset);
2152   else
2153     this->u2_.posd->set_address_and_file_offset(address, file_offset);
2154 }
2155
2156 // Reset the address and file offset.
2157
2158 void
2159 Output_section::Input_section::reset_address_and_file_offset()
2160 {
2161   if (!this->is_input_section())
2162     this->u2_.posd->reset_address_and_file_offset();
2163 }
2164
2165 // Finalize the data size.
2166
2167 void
2168 Output_section::Input_section::finalize_data_size()
2169 {
2170   if (!this->is_input_section())
2171     this->u2_.posd->finalize_data_size();
2172 }
2173
2174 // Try to turn an input offset into an output offset.  We want to
2175 // return the output offset relative to the start of this
2176 // Input_section in the output section.
2177
2178 inline bool
2179 Output_section::Input_section::output_offset(
2180     const Relobj* object,
2181     unsigned int shndx,
2182     section_offset_type offset,
2183     section_offset_type* poutput) const
2184 {
2185   if (!this->is_input_section())
2186     return this->u2_.posd->output_offset(object, shndx, offset, poutput);
2187   else
2188     {
2189       if (this->shndx_ != shndx || this->u2_.object != object)
2190         return false;
2191       *poutput = offset;
2192       return true;
2193     }
2194 }
2195
2196 // Return whether this is the merge section for the input section
2197 // SHNDX in OBJECT.
2198
2199 inline bool
2200 Output_section::Input_section::is_merge_section_for(const Relobj* object,
2201                                                     unsigned int shndx) const
2202 {
2203   if (this->is_input_section())
2204     return false;
2205   return this->u2_.posd->is_merge_section_for(object, shndx);
2206 }
2207
2208 // Write out the data.  We don't have to do anything for an input
2209 // section--they are handled via Object::relocate--but this is where
2210 // we write out the data for an Output_section_data.
2211
2212 void
2213 Output_section::Input_section::write(Output_file* of)
2214 {
2215   if (!this->is_input_section())
2216     this->u2_.posd->write(of);
2217 }
2218
2219 // Write the data to a buffer.  As for write(), we don't have to do
2220 // anything for an input section.
2221
2222 void
2223 Output_section::Input_section::write_to_buffer(unsigned char* buffer)
2224 {
2225   if (!this->is_input_section())
2226     this->u2_.posd->write_to_buffer(buffer);
2227 }
2228
2229 // Print to a map file.
2230
2231 void
2232 Output_section::Input_section::print_to_mapfile(Mapfile* mapfile) const
2233 {
2234   switch (this->shndx_)
2235     {
2236     case OUTPUT_SECTION_CODE:
2237     case MERGE_DATA_SECTION_CODE:
2238     case MERGE_STRING_SECTION_CODE:
2239       this->u2_.posd->print_to_mapfile(mapfile);
2240       break;
2241
2242     case RELAXED_INPUT_SECTION_CODE:
2243       {
2244         Output_relaxed_input_section* relaxed_section =
2245           this->relaxed_input_section();
2246         mapfile->print_input_section(relaxed_section->relobj(),
2247                                      relaxed_section->shndx());
2248       }
2249       break;
2250     default:
2251       mapfile->print_input_section(this->u2_.object, this->shndx_);
2252       break;
2253     }
2254 }
2255
2256 // Output_section methods.
2257
2258 // Construct an Output_section.  NAME will point into a Stringpool.
2259
2260 Output_section::Output_section(const char* name, elfcpp::Elf_Word type,
2261                                elfcpp::Elf_Xword flags)
2262   : name_(name),
2263     addralign_(0),
2264     entsize_(0),
2265     load_address_(0),
2266     link_section_(NULL),
2267     link_(0),
2268     info_section_(NULL),
2269     info_symndx_(NULL),
2270     info_(0),
2271     type_(type),
2272     flags_(flags),
2273     order_(ORDER_INVALID),
2274     out_shndx_(-1U),
2275     symtab_index_(0),
2276     dynsym_index_(0),
2277     input_sections_(),
2278     first_input_offset_(0),
2279     fills_(),
2280     postprocessing_buffer_(NULL),
2281     needs_symtab_index_(false),
2282     needs_dynsym_index_(false),
2283     should_link_to_symtab_(false),
2284     should_link_to_dynsym_(false),
2285     after_input_sections_(false),
2286     requires_postprocessing_(false),
2287     found_in_sections_clause_(false),
2288     has_load_address_(false),
2289     info_uses_section_index_(false),
2290     input_section_order_specified_(false),
2291     may_sort_attached_input_sections_(false),
2292     must_sort_attached_input_sections_(false),
2293     attached_input_sections_are_sorted_(false),
2294     is_relro_(false),
2295     is_small_section_(false),
2296     is_large_section_(false),
2297     generate_code_fills_at_write_(false),
2298     is_entsize_zero_(false),
2299     section_offsets_need_adjustment_(false),
2300     is_noload_(false),
2301     always_keeps_input_sections_(false),
2302     has_fixed_layout_(false),
2303     is_patch_space_allowed_(false),
2304     tls_offset_(0),
2305     checkpoint_(NULL),
2306     lookup_maps_(new Output_section_lookup_maps),
2307     free_list_(),
2308     free_space_fill_(NULL),
2309     patch_space_(0)
2310 {
2311   // An unallocated section has no address.  Forcing this means that
2312   // we don't need special treatment for symbols defined in debug
2313   // sections.
2314   if ((flags & elfcpp::SHF_ALLOC) == 0)
2315     this->set_address(0);
2316 }
2317
2318 Output_section::~Output_section()
2319 {
2320   delete this->checkpoint_;
2321 }
2322
2323 // Set the entry size.
2324
2325 void
2326 Output_section::set_entsize(uint64_t v)
2327 {
2328   if (this->is_entsize_zero_)
2329     ;
2330   else if (this->entsize_ == 0)
2331     this->entsize_ = v;
2332   else if (this->entsize_ != v)
2333     {
2334       this->entsize_ = 0;
2335       this->is_entsize_zero_ = 1;
2336     }
2337 }
2338
2339 // Add the input section SHNDX, with header SHDR, named SECNAME, in
2340 // OBJECT, to the Output_section.  RELOC_SHNDX is the index of a
2341 // relocation section which applies to this section, or 0 if none, or
2342 // -1U if more than one.  Return the offset of the input section
2343 // within the output section.  Return -1 if the input section will
2344 // receive special handling.  In the normal case we don't always keep
2345 // track of input sections for an Output_section.  Instead, each
2346 // Object keeps track of the Output_section for each of its input
2347 // sections.  However, if HAVE_SECTIONS_SCRIPT is true, we do keep
2348 // track of input sections here; this is used when SECTIONS appears in
2349 // a linker script.
2350
2351 template<int size, bool big_endian>
2352 off_t
2353 Output_section::add_input_section(Layout* layout,
2354                                   Sized_relobj_file<size, big_endian>* object,
2355                                   unsigned int shndx,
2356                                   const char* secname,
2357                                   const elfcpp::Shdr<size, big_endian>& shdr,
2358                                   unsigned int reloc_shndx,
2359                                   bool have_sections_script)
2360 {
2361   elfcpp::Elf_Xword addralign = shdr.get_sh_addralign();
2362   if ((addralign & (addralign - 1)) != 0)
2363     {
2364       object->error(_("invalid alignment %lu for section \"%s\""),
2365                     static_cast<unsigned long>(addralign), secname);
2366       addralign = 1;
2367     }
2368
2369   if (addralign > this->addralign_)
2370     this->addralign_ = addralign;
2371
2372   typename elfcpp::Elf_types<size>::Elf_WXword sh_flags = shdr.get_sh_flags();
2373   uint64_t entsize = shdr.get_sh_entsize();
2374
2375   // .debug_str is a mergeable string section, but is not always so
2376   // marked by compilers.  Mark manually here so we can optimize.
2377   if (strcmp(secname, ".debug_str") == 0)
2378     {
2379       sh_flags |= (elfcpp::SHF_MERGE | elfcpp::SHF_STRINGS);
2380       entsize = 1;
2381     }
2382
2383   this->update_flags_for_input_section(sh_flags);
2384   this->set_entsize(entsize);
2385
2386   // If this is a SHF_MERGE section, we pass all the input sections to
2387   // a Output_data_merge.  We don't try to handle relocations for such
2388   // a section.  We don't try to handle empty merge sections--they
2389   // mess up the mappings, and are useless anyhow.
2390   // FIXME: Need to handle merge sections during incremental update.
2391   if ((sh_flags & elfcpp::SHF_MERGE) != 0
2392       && reloc_shndx == 0
2393       && shdr.get_sh_size() > 0
2394       && !parameters->incremental())
2395     {
2396       // Keep information about merged input sections for rebuilding fast
2397       // lookup maps if we have sections-script or we do relaxation.
2398       bool keeps_input_sections = (this->always_keeps_input_sections_
2399                                    || have_sections_script
2400                                    || parameters->target().may_relax());
2401
2402       if (this->add_merge_input_section(object, shndx, sh_flags, entsize,
2403                                         addralign, keeps_input_sections))
2404         {
2405           // Tell the relocation routines that they need to call the
2406           // output_offset method to determine the final address.
2407           return -1;
2408         }
2409     }
2410
2411   section_size_type input_section_size = shdr.get_sh_size();
2412   section_size_type uncompressed_size;
2413   if (object->section_is_compressed(shndx, &uncompressed_size))
2414     input_section_size = uncompressed_size;
2415
2416   off_t offset_in_section;
2417   off_t aligned_offset_in_section;
2418   if (this->has_fixed_layout())
2419     {
2420       // For incremental updates, find a chunk of unused space in the section.
2421       offset_in_section = this->free_list_.allocate(input_section_size,
2422                                                     addralign, 0);
2423       if (offset_in_section == -1)
2424         gold_fallback(_("out of patch space in section %s; "
2425                         "relink with --incremental-full"),
2426                       this->name());
2427       aligned_offset_in_section = offset_in_section;
2428     }
2429   else
2430     {
2431       offset_in_section = this->current_data_size_for_child();
2432       aligned_offset_in_section = align_address(offset_in_section,
2433                                                 addralign);
2434       this->set_current_data_size_for_child(aligned_offset_in_section
2435                                             + input_section_size);
2436     }
2437
2438   // Determine if we want to delay code-fill generation until the output
2439   // section is written.  When the target is relaxing, we want to delay fill
2440   // generating to avoid adjusting them during relaxation.  Also, if we are
2441   // sorting input sections we must delay fill generation.
2442   if (!this->generate_code_fills_at_write_
2443       && !have_sections_script
2444       && (sh_flags & elfcpp::SHF_EXECINSTR) != 0
2445       && parameters->target().has_code_fill()
2446       && (parameters->target().may_relax()
2447           || layout->is_section_ordering_specified()))
2448     {
2449       gold_assert(this->fills_.empty());
2450       this->generate_code_fills_at_write_ = true;
2451     }
2452
2453   if (aligned_offset_in_section > offset_in_section
2454       && !this->generate_code_fills_at_write_
2455       && !have_sections_script
2456       && (sh_flags & elfcpp::SHF_EXECINSTR) != 0
2457       && parameters->target().has_code_fill())
2458     {
2459       // We need to add some fill data.  Using fill_list_ when
2460       // possible is an optimization, since we will often have fill
2461       // sections without input sections.
2462       off_t fill_len = aligned_offset_in_section - offset_in_section;
2463       if (this->input_sections_.empty())
2464         this->fills_.push_back(Fill(offset_in_section, fill_len));
2465       else
2466         {
2467           std::string fill_data(parameters->target().code_fill(fill_len));
2468           Output_data_const* odc = new Output_data_const(fill_data, 1);
2469           this->input_sections_.push_back(Input_section(odc));
2470         }
2471     }
2472
2473   // We need to keep track of this section if we are already keeping
2474   // track of sections, or if we are relaxing.  Also, if this is a
2475   // section which requires sorting, or which may require sorting in
2476   // the future, we keep track of the sections.  If the
2477   // --section-ordering-file option is used to specify the order of
2478   // sections, we need to keep track of sections.
2479   if (this->always_keeps_input_sections_
2480       || have_sections_script
2481       || !this->input_sections_.empty()
2482       || this->may_sort_attached_input_sections()
2483       || this->must_sort_attached_input_sections()
2484       || parameters->options().user_set_Map()
2485       || parameters->target().may_relax()
2486       || layout->is_section_ordering_specified())
2487     {
2488       Input_section isecn(object, shndx, input_section_size, addralign);
2489       /* If section ordering is requested by specifying a ordering file,
2490          using --section-ordering-file, match the section name with
2491          a pattern.  */
2492       if (parameters->options().section_ordering_file())
2493         {
2494           unsigned int section_order_index =
2495             layout->find_section_order_index(std::string(secname));
2496           if (section_order_index != 0)
2497             {
2498               isecn.set_section_order_index(section_order_index);
2499               this->set_input_section_order_specified();
2500             }
2501         }
2502       if (this->has_fixed_layout())
2503         {
2504           // For incremental updates, finalize the address and offset now.
2505           uint64_t addr = this->address();
2506           isecn.set_address_and_file_offset(addr + aligned_offset_in_section,
2507                                             aligned_offset_in_section,
2508                                             this->offset());
2509         }
2510       this->input_sections_.push_back(isecn);
2511     }
2512
2513   return aligned_offset_in_section;
2514 }
2515
2516 // Add arbitrary data to an output section.
2517
2518 void
2519 Output_section::add_output_section_data(Output_section_data* posd)
2520 {
2521   Input_section inp(posd);
2522   this->add_output_section_data(&inp);
2523
2524   if (posd->is_data_size_valid())
2525     {
2526       off_t offset_in_section;
2527       if (this->has_fixed_layout())
2528         {
2529           // For incremental updates, find a chunk of unused space.
2530           offset_in_section = this->free_list_.allocate(posd->data_size(),
2531                                                         posd->addralign(), 0);
2532           if (offset_in_section == -1)
2533             gold_fallback(_("out of patch space in section %s; "
2534                             "relink with --incremental-full"),
2535                           this->name());
2536           // Finalize the address and offset now.
2537           uint64_t addr = this->address();
2538           off_t offset = this->offset();
2539           posd->set_address_and_file_offset(addr + offset_in_section,
2540                                             offset + offset_in_section);
2541         }
2542       else
2543         {
2544           offset_in_section = this->current_data_size_for_child();
2545           off_t aligned_offset_in_section = align_address(offset_in_section,
2546                                                           posd->addralign());
2547           this->set_current_data_size_for_child(aligned_offset_in_section
2548                                                 + posd->data_size());
2549         }
2550     }
2551   else if (this->has_fixed_layout())
2552     {
2553       // For incremental updates, arrange for the data to have a fixed layout.
2554       // This will mean that additions to the data must be allocated from
2555       // free space within the containing output section.
2556       uint64_t addr = this->address();
2557       posd->set_address(addr);
2558       posd->set_file_offset(0);
2559       // FIXME: This should eventually be unreachable.
2560       // gold_unreachable();
2561     }
2562 }
2563
2564 // Add a relaxed input section.
2565
2566 void
2567 Output_section::add_relaxed_input_section(Layout* layout,
2568                                           Output_relaxed_input_section* poris,
2569                                           const std::string& name)
2570 {
2571   Input_section inp(poris);
2572
2573   // If the --section-ordering-file option is used to specify the order of
2574   // sections, we need to keep track of sections.
2575   if (layout->is_section_ordering_specified())
2576     {
2577       unsigned int section_order_index =
2578         layout->find_section_order_index(name);
2579       if (section_order_index != 0)
2580         {
2581           inp.set_section_order_index(section_order_index);
2582           this->set_input_section_order_specified();
2583         }
2584     }
2585
2586   this->add_output_section_data(&inp);
2587   if (this->lookup_maps_->is_valid())
2588     this->lookup_maps_->add_relaxed_input_section(poris->relobj(),
2589                                                   poris->shndx(), poris);
2590
2591   // For a relaxed section, we use the current data size.  Linker scripts
2592   // get all the input sections, including relaxed one from an output
2593   // section and add them back to them same output section to compute the
2594   // output section size.  If we do not account for sizes of relaxed input
2595   // sections,  an output section would be incorrectly sized.
2596   off_t offset_in_section = this->current_data_size_for_child();
2597   off_t aligned_offset_in_section = align_address(offset_in_section,
2598                                                   poris->addralign());
2599   this->set_current_data_size_for_child(aligned_offset_in_section
2600                                         + poris->current_data_size());
2601 }
2602
2603 // Add arbitrary data to an output section by Input_section.
2604
2605 void
2606 Output_section::add_output_section_data(Input_section* inp)
2607 {
2608   if (this->input_sections_.empty())
2609     this->first_input_offset_ = this->current_data_size_for_child();
2610
2611   this->input_sections_.push_back(*inp);
2612
2613   uint64_t addralign = inp->addralign();
2614   if (addralign > this->addralign_)
2615     this->addralign_ = addralign;
2616
2617   inp->set_output_section(this);
2618 }
2619
2620 // Add a merge section to an output section.
2621
2622 void
2623 Output_section::add_output_merge_section(Output_section_data* posd,
2624                                          bool is_string, uint64_t entsize)
2625 {
2626   Input_section inp(posd, is_string, entsize);
2627   this->add_output_section_data(&inp);
2628 }
2629
2630 // Add an input section to a SHF_MERGE section.
2631
2632 bool
2633 Output_section::add_merge_input_section(Relobj* object, unsigned int shndx,
2634                                         uint64_t flags, uint64_t entsize,
2635                                         uint64_t addralign,
2636                                         bool keeps_input_sections)
2637 {
2638   bool is_string = (flags & elfcpp::SHF_STRINGS) != 0;
2639
2640   // We only merge strings if the alignment is not more than the
2641   // character size.  This could be handled, but it's unusual.
2642   if (is_string && addralign > entsize)
2643     return false;
2644
2645   // We cannot restore merged input section states.
2646   gold_assert(this->checkpoint_ == NULL);
2647
2648   // Look up merge sections by required properties.
2649   // Currently, we only invalidate the lookup maps in script processing
2650   // and relaxation.  We should not have done either when we reach here.
2651   // So we assume that the lookup maps are valid to simply code.
2652   gold_assert(this->lookup_maps_->is_valid());
2653   Merge_section_properties msp(is_string, entsize, addralign);
2654   Output_merge_base* pomb = this->lookup_maps_->find_merge_section(msp);
2655   bool is_new = false;
2656   if (pomb != NULL)
2657     {
2658       gold_assert(pomb->is_string() == is_string
2659                   && pomb->entsize() == entsize
2660                   && pomb->addralign() == addralign);
2661     }
2662   else
2663     {
2664       // Create a new Output_merge_data or Output_merge_string_data.
2665       if (!is_string)
2666         pomb = new Output_merge_data(entsize, addralign);
2667       else
2668         {
2669           switch (entsize)
2670             {
2671             case 1:
2672               pomb = new Output_merge_string<char>(addralign);
2673               break;
2674             case 2:
2675               pomb = new Output_merge_string<uint16_t>(addralign);
2676               break;
2677             case 4:
2678               pomb = new Output_merge_string<uint32_t>(addralign);
2679               break;
2680             default:
2681               return false;
2682             }
2683         }
2684       // If we need to do script processing or relaxation, we need to keep
2685       // the original input sections to rebuild the fast lookup maps.
2686       if (keeps_input_sections)
2687         pomb->set_keeps_input_sections();
2688       is_new = true;
2689     }
2690
2691   if (pomb->add_input_section(object, shndx))
2692     {
2693       // Add new merge section to this output section and link merge
2694       // section properties to new merge section in map.
2695       if (is_new)
2696         {
2697           this->add_output_merge_section(pomb, is_string, entsize);
2698           this->lookup_maps_->add_merge_section(msp, pomb);
2699         }
2700
2701       // Add input section to new merge section and link input section to new
2702       // merge section in map.
2703       this->lookup_maps_->add_merge_input_section(object, shndx, pomb);
2704       return true;
2705     }
2706   else
2707     {
2708       // If add_input_section failed, delete new merge section to avoid
2709       // exporting empty merge sections in Output_section::get_input_section.
2710       if (is_new)
2711         delete pomb;
2712       return false;
2713     }
2714 }
2715
2716 // Build a relaxation map to speed up relaxation of existing input sections.
2717 // Look up to the first LIMIT elements in INPUT_SECTIONS.
2718
2719 void
2720 Output_section::build_relaxation_map(
2721   const Input_section_list& input_sections,
2722   size_t limit,
2723   Relaxation_map* relaxation_map) const
2724 {
2725   for (size_t i = 0; i < limit; ++i)
2726     {
2727       const Input_section& is(input_sections[i]);
2728       if (is.is_input_section() || is.is_relaxed_input_section())
2729         {
2730           Section_id sid(is.relobj(), is.shndx());
2731           (*relaxation_map)[sid] = i;
2732         }
2733     }
2734 }
2735
2736 // Convert regular input sections in INPUT_SECTIONS into relaxed input
2737 // sections in RELAXED_SECTIONS.  MAP is a prebuilt map from section id
2738 // indices of INPUT_SECTIONS.
2739
2740 void
2741 Output_section::convert_input_sections_in_list_to_relaxed_sections(
2742   const std::vector<Output_relaxed_input_section*>& relaxed_sections,
2743   const Relaxation_map& map,
2744   Input_section_list* input_sections)
2745 {
2746   for (size_t i = 0; i < relaxed_sections.size(); ++i)
2747     {
2748       Output_relaxed_input_section* poris = relaxed_sections[i];
2749       Section_id sid(poris->relobj(), poris->shndx());
2750       Relaxation_map::const_iterator p = map.find(sid);
2751       gold_assert(p != map.end());
2752       gold_assert((*input_sections)[p->second].is_input_section());
2753
2754       // Remember section order index of original input section
2755       // if it is set.  Copy it to the relaxed input section.
2756       unsigned int soi =
2757         (*input_sections)[p->second].section_order_index();
2758       (*input_sections)[p->second] = Input_section(poris);
2759       (*input_sections)[p->second].set_section_order_index(soi);
2760     }
2761 }
2762   
2763 // Convert regular input sections into relaxed input sections. RELAXED_SECTIONS
2764 // is a vector of pointers to Output_relaxed_input_section or its derived
2765 // classes.  The relaxed sections must correspond to existing input sections.
2766
2767 void
2768 Output_section::convert_input_sections_to_relaxed_sections(
2769   const std::vector<Output_relaxed_input_section*>& relaxed_sections)
2770 {
2771   gold_assert(parameters->target().may_relax());
2772
2773   // We want to make sure that restore_states does not undo the effect of
2774   // this.  If there is no checkpoint active, just search the current
2775   // input section list and replace the sections there.  If there is
2776   // a checkpoint, also replace the sections there.
2777   
2778   // By default, we look at the whole list.
2779   size_t limit = this->input_sections_.size();
2780
2781   if (this->checkpoint_ != NULL)
2782     {
2783       // Replace input sections with relaxed input section in the saved
2784       // copy of the input section list.
2785       if (this->checkpoint_->input_sections_saved())
2786         {
2787           Relaxation_map map;
2788           this->build_relaxation_map(
2789                     *(this->checkpoint_->input_sections()),
2790                     this->checkpoint_->input_sections()->size(),
2791                     &map);
2792           this->convert_input_sections_in_list_to_relaxed_sections(
2793                     relaxed_sections,
2794                     map,
2795                     this->checkpoint_->input_sections());
2796         }
2797       else
2798         {
2799           // We have not copied the input section list yet.  Instead, just
2800           // look at the portion that would be saved.
2801           limit = this->checkpoint_->input_sections_size();
2802         }
2803     }
2804
2805   // Convert input sections in input_section_list.
2806   Relaxation_map map;
2807   this->build_relaxation_map(this->input_sections_, limit, &map);
2808   this->convert_input_sections_in_list_to_relaxed_sections(
2809             relaxed_sections,
2810             map,
2811             &this->input_sections_);
2812
2813   // Update fast look-up map.
2814   if (this->lookup_maps_->is_valid())
2815     for (size_t i = 0; i < relaxed_sections.size(); ++i)
2816       {
2817         Output_relaxed_input_section* poris = relaxed_sections[i];
2818         this->lookup_maps_->add_relaxed_input_section(poris->relobj(),
2819                                                       poris->shndx(), poris);
2820       }
2821 }
2822
2823 // Update the output section flags based on input section flags.
2824
2825 void
2826 Output_section::update_flags_for_input_section(elfcpp::Elf_Xword flags)
2827 {
2828   // If we created the section with SHF_ALLOC clear, we set the
2829   // address.  If we are now setting the SHF_ALLOC flag, we need to
2830   // undo that.
2831   if ((this->flags_ & elfcpp::SHF_ALLOC) == 0
2832       && (flags & elfcpp::SHF_ALLOC) != 0)
2833     this->mark_address_invalid();
2834
2835   this->flags_ |= (flags
2836                    & (elfcpp::SHF_WRITE
2837                       | elfcpp::SHF_ALLOC
2838                       | elfcpp::SHF_EXECINSTR));
2839
2840   if ((flags & elfcpp::SHF_MERGE) == 0)
2841     this->flags_ &=~ elfcpp::SHF_MERGE;
2842   else
2843     {
2844       if (this->current_data_size_for_child() == 0)
2845         this->flags_ |= elfcpp::SHF_MERGE;
2846     }
2847
2848   if ((flags & elfcpp::SHF_STRINGS) == 0)
2849     this->flags_ &=~ elfcpp::SHF_STRINGS;
2850   else
2851     {
2852       if (this->current_data_size_for_child() == 0)
2853         this->flags_ |= elfcpp::SHF_STRINGS;
2854     }
2855 }
2856
2857 // Find the merge section into which an input section with index SHNDX in
2858 // OBJECT has been added.  Return NULL if none found.
2859
2860 Output_section_data*
2861 Output_section::find_merge_section(const Relobj* object,
2862                                    unsigned int shndx) const
2863 {
2864   if (!this->lookup_maps_->is_valid())
2865     this->build_lookup_maps();
2866   return this->lookup_maps_->find_merge_section(object, shndx);
2867 }
2868
2869 // Build the lookup maps for merge and relaxed sections.  This is needs
2870 // to be declared as a const methods so that it is callable with a const
2871 // Output_section pointer.  The method only updates states of the maps.
2872
2873 void
2874 Output_section::build_lookup_maps() const
2875 {
2876   this->lookup_maps_->clear();
2877   for (Input_section_list::const_iterator p = this->input_sections_.begin();
2878        p != this->input_sections_.end();
2879        ++p)
2880     {
2881       if (p->is_merge_section())
2882         {
2883           Output_merge_base* pomb = p->output_merge_base();
2884           Merge_section_properties msp(pomb->is_string(), pomb->entsize(),
2885                                        pomb->addralign());
2886           this->lookup_maps_->add_merge_section(msp, pomb);
2887           for (Output_merge_base::Input_sections::const_iterator is =
2888                  pomb->input_sections_begin();
2889                is != pomb->input_sections_end();
2890                ++is) 
2891             {
2892               const Const_section_id& csid = *is;
2893             this->lookup_maps_->add_merge_input_section(csid.first,
2894                                                         csid.second, pomb);
2895             }
2896             
2897         }
2898       else if (p->is_relaxed_input_section())
2899         {
2900           Output_relaxed_input_section* poris = p->relaxed_input_section();
2901           this->lookup_maps_->add_relaxed_input_section(poris->relobj(),
2902                                                         poris->shndx(), poris);
2903         }
2904     }
2905 }
2906
2907 // Find an relaxed input section corresponding to an input section
2908 // in OBJECT with index SHNDX.
2909
2910 const Output_relaxed_input_section*
2911 Output_section::find_relaxed_input_section(const Relobj* object,
2912                                            unsigned int shndx) const
2913 {
2914   if (!this->lookup_maps_->is_valid())
2915     this->build_lookup_maps();
2916   return this->lookup_maps_->find_relaxed_input_section(object, shndx);
2917 }
2918
2919 // Given an address OFFSET relative to the start of input section
2920 // SHNDX in OBJECT, return whether this address is being included in
2921 // the final link.  This should only be called if SHNDX in OBJECT has
2922 // a special mapping.
2923
2924 bool
2925 Output_section::is_input_address_mapped(const Relobj* object,
2926                                         unsigned int shndx,
2927                                         off_t offset) const
2928 {
2929   // Look at the Output_section_data_maps first.
2930   const Output_section_data* posd = this->find_merge_section(object, shndx);
2931   if (posd == NULL)
2932     posd = this->find_relaxed_input_section(object, shndx);
2933
2934   if (posd != NULL)
2935     {
2936       section_offset_type output_offset;
2937       bool found = posd->output_offset(object, shndx, offset, &output_offset);
2938       gold_assert(found);   
2939       return output_offset != -1;
2940     }
2941
2942   // Fall back to the slow look-up.
2943   for (Input_section_list::const_iterator p = this->input_sections_.begin();
2944        p != this->input_sections_.end();
2945        ++p)
2946     {
2947       section_offset_type output_offset;
2948       if (p->output_offset(object, shndx, offset, &output_offset))
2949         return output_offset != -1;
2950     }
2951
2952   // By default we assume that the address is mapped.  This should
2953   // only be called after we have passed all sections to Layout.  At
2954   // that point we should know what we are discarding.
2955   return true;
2956 }
2957
2958 // Given an address OFFSET relative to the start of input section
2959 // SHNDX in object OBJECT, return the output offset relative to the
2960 // start of the input section in the output section.  This should only
2961 // be called if SHNDX in OBJECT has a special mapping.
2962
2963 section_offset_type
2964 Output_section::output_offset(const Relobj* object, unsigned int shndx,
2965                               section_offset_type offset) const
2966 {
2967   // This can only be called meaningfully when we know the data size
2968   // of this.
2969   gold_assert(this->is_data_size_valid());
2970
2971   // Look at the Output_section_data_maps first.
2972   const Output_section_data* posd = this->find_merge_section(object, shndx);
2973   if (posd == NULL) 
2974     posd = this->find_relaxed_input_section(object, shndx);
2975   if (posd != NULL)
2976     {
2977       section_offset_type output_offset;
2978       bool found = posd->output_offset(object, shndx, offset, &output_offset);
2979       gold_assert(found);   
2980       return output_offset;
2981     }
2982
2983   // Fall back to the slow look-up.
2984   for (Input_section_list::const_iterator p = this->input_sections_.begin();
2985        p != this->input_sections_.end();
2986        ++p)
2987     {
2988       section_offset_type output_offset;
2989       if (p->output_offset(object, shndx, offset, &output_offset))
2990         return output_offset;
2991     }
2992   gold_unreachable();
2993 }
2994
2995 // Return the output virtual address of OFFSET relative to the start
2996 // of input section SHNDX in object OBJECT.
2997
2998 uint64_t
2999 Output_section::output_address(const Relobj* object, unsigned int shndx,
3000                                off_t offset) const
3001 {
3002   uint64_t addr = this->address() + this->first_input_offset_;
3003
3004   // Look at the Output_section_data_maps first.
3005   const Output_section_data* posd = this->find_merge_section(object, shndx);
3006   if (posd == NULL) 
3007     posd = this->find_relaxed_input_section(object, shndx);
3008   if (posd != NULL && posd->is_address_valid())
3009     {
3010       section_offset_type output_offset;
3011       bool found = posd->output_offset(object, shndx, offset, &output_offset);
3012       gold_assert(found);
3013       return posd->address() + output_offset;
3014     }
3015
3016   // Fall back to the slow look-up.
3017   for (Input_section_list::const_iterator p = this->input_sections_.begin();
3018        p != this->input_sections_.end();
3019        ++p)
3020     {
3021       addr = align_address(addr, p->addralign());
3022       section_offset_type output_offset;
3023       if (p->output_offset(object, shndx, offset, &output_offset))
3024         {
3025           if (output_offset == -1)
3026             return -1ULL;
3027           return addr + output_offset;
3028         }
3029       addr += p->data_size();
3030     }
3031
3032   // If we get here, it means that we don't know the mapping for this
3033   // input section.  This might happen in principle if
3034   // add_input_section were called before add_output_section_data.
3035   // But it should never actually happen.
3036
3037   gold_unreachable();
3038 }
3039
3040 // Find the output address of the start of the merged section for
3041 // input section SHNDX in object OBJECT.
3042
3043 bool
3044 Output_section::find_starting_output_address(const Relobj* object,
3045                                              unsigned int shndx,
3046                                              uint64_t* paddr) const
3047 {
3048   // FIXME: This becomes a bottle-neck if we have many relaxed sections.
3049   // Looking up the merge section map does not always work as we sometimes
3050   // find a merge section without its address set.
3051   uint64_t addr = this->address() + this->first_input_offset_;
3052   for (Input_section_list::const_iterator p = this->input_sections_.begin();
3053        p != this->input_sections_.end();
3054        ++p)
3055     {
3056       addr = align_address(addr, p->addralign());
3057
3058       // It would be nice if we could use the existing output_offset
3059       // method to get the output offset of input offset 0.
3060       // Unfortunately we don't know for sure that input offset 0 is
3061       // mapped at all.
3062       if (p->is_merge_section_for(object, shndx))
3063         {
3064           *paddr = addr;
3065           return true;
3066         }
3067
3068       addr += p->data_size();
3069     }
3070
3071   // We couldn't find a merge output section for this input section.
3072   return false;
3073 }
3074
3075 // Update the data size of an Output_section.
3076
3077 void
3078 Output_section::update_data_size()
3079 {
3080   if (this->input_sections_.empty())
3081       return;
3082
3083   if (this->must_sort_attached_input_sections()
3084       || this->input_section_order_specified())
3085     this->sort_attached_input_sections();
3086
3087   off_t off = this->first_input_offset_;
3088   for (Input_section_list::iterator p = this->input_sections_.begin();
3089        p != this->input_sections_.end();
3090        ++p)
3091     {
3092       off = align_address(off, p->addralign());
3093       off += p->current_data_size();
3094     }
3095
3096   this->set_current_data_size_for_child(off);
3097 }
3098
3099 // Set the data size of an Output_section.  This is where we handle
3100 // setting the addresses of any Output_section_data objects.
3101
3102 void
3103 Output_section::set_final_data_size()
3104 {
3105   off_t data_size;
3106
3107   if (this->input_sections_.empty())
3108     data_size = this->current_data_size_for_child();
3109   else
3110     {
3111       if (this->must_sort_attached_input_sections()
3112           || this->input_section_order_specified())
3113         this->sort_attached_input_sections();
3114
3115       uint64_t address = this->address();
3116       off_t startoff = this->offset();
3117       off_t off = startoff + this->first_input_offset_;
3118       for (Input_section_list::iterator p = this->input_sections_.begin();
3119            p != this->input_sections_.end();
3120            ++p)
3121         {
3122           off = align_address(off, p->addralign());
3123           p->set_address_and_file_offset(address + (off - startoff), off,
3124                                          startoff);
3125           off += p->data_size();
3126         }
3127       data_size = off - startoff;
3128     }
3129
3130   // For full incremental links, we want to allocate some patch space
3131   // in most sections for subsequent incremental updates.
3132   if (this->is_patch_space_allowed_ && parameters->incremental_full())
3133     {
3134       double pct = parameters->options().incremental_patch();
3135       size_t extra = static_cast<size_t>(data_size * pct);
3136       if (this->free_space_fill_ != NULL
3137           && this->free_space_fill_->minimum_hole_size() > extra)
3138         extra = this->free_space_fill_->minimum_hole_size();
3139       off_t new_size = align_address(data_size + extra, this->addralign());
3140       this->patch_space_ = new_size - data_size;
3141       gold_debug(DEBUG_INCREMENTAL,
3142                  "set_final_data_size: %08lx + %08lx: section %s",
3143                  static_cast<long>(data_size),
3144                  static_cast<long>(this->patch_space_),
3145                  this->name());
3146       data_size = new_size;
3147     }
3148
3149   this->set_data_size(data_size);
3150 }
3151
3152 // Reset the address and file offset.
3153
3154 void
3155 Output_section::do_reset_address_and_file_offset()
3156 {
3157   // An unallocated section has no address.  Forcing this means that
3158   // we don't need special treatment for symbols defined in debug
3159   // sections.  We do the same in the constructor.  This does not
3160   // apply to NOLOAD sections though.
3161   if (((this->flags_ & elfcpp::SHF_ALLOC) == 0) && !this->is_noload_)
3162      this->set_address(0);
3163
3164   for (Input_section_list::iterator p = this->input_sections_.begin();
3165        p != this->input_sections_.end();
3166        ++p)
3167     p->reset_address_and_file_offset();
3168
3169   // Remove any patch space that was added in set_final_data_size.
3170   if (this->patch_space_ > 0)
3171     {
3172       this->set_current_data_size_for_child(this->current_data_size_for_child()
3173                                             - this->patch_space_);
3174       this->patch_space_ = 0;
3175     }
3176 }
3177
3178 // Return true if address and file offset have the values after reset.
3179
3180 bool
3181 Output_section::do_address_and_file_offset_have_reset_values() const
3182 {
3183   if (this->is_offset_valid())
3184     return false;
3185
3186   // An unallocated section has address 0 after its construction or a reset.
3187   if ((this->flags_ & elfcpp::SHF_ALLOC) == 0)
3188     return this->is_address_valid() && this->address() == 0;
3189   else
3190     return !this->is_address_valid();
3191 }
3192
3193 // Set the TLS offset.  Called only for SHT_TLS sections.
3194
3195 void
3196 Output_section::do_set_tls_offset(uint64_t tls_base)
3197 {
3198   this->tls_offset_ = this->address() - tls_base;
3199 }
3200
3201 // In a few cases we need to sort the input sections attached to an
3202 // output section.  This is used to implement the type of constructor
3203 // priority ordering implemented by the GNU linker, in which the
3204 // priority becomes part of the section name and the sections are
3205 // sorted by name.  We only do this for an output section if we see an
3206 // attached input section matching ".ctors.*", ".dtors.*",
3207 // ".init_array.*" or ".fini_array.*".
3208
3209 class Output_section::Input_section_sort_entry
3210 {
3211  public:
3212   Input_section_sort_entry()
3213     : input_section_(), index_(-1U), section_has_name_(false),
3214       section_name_()
3215   { }
3216
3217   Input_section_sort_entry(const Input_section& input_section,
3218                            unsigned int index,
3219                            bool must_sort_attached_input_sections)
3220     : input_section_(input_section), index_(index),
3221       section_has_name_(input_section.is_input_section()
3222                         || input_section.is_relaxed_input_section())
3223   {
3224     if (this->section_has_name_
3225         && must_sort_attached_input_sections)
3226       {
3227         // This is only called single-threaded from Layout::finalize,
3228         // so it is OK to lock.  Unfortunately we have no way to pass
3229         // in a Task token.
3230         const Task* dummy_task = reinterpret_cast<const Task*>(-1);
3231         Object* obj = (input_section.is_input_section()
3232                        ? input_section.relobj()
3233                        : input_section.relaxed_input_section()->relobj());
3234         Task_lock_obj<Object> tl(dummy_task, obj);
3235
3236         // This is a slow operation, which should be cached in
3237         // Layout::layout if this becomes a speed problem.
3238         this->section_name_ = obj->section_name(input_section.shndx());
3239       }
3240   }
3241
3242   // Return the Input_section.
3243   const Input_section&
3244   input_section() const
3245   {
3246     gold_assert(this->index_ != -1U);
3247     return this->input_section_;
3248   }
3249
3250   // The index of this entry in the original list.  This is used to
3251   // make the sort stable.
3252   unsigned int
3253   index() const
3254   {
3255     gold_assert(this->index_ != -1U);
3256     return this->index_;
3257   }
3258
3259   // Whether there is a section name.
3260   bool
3261   section_has_name() const
3262   { return this->section_has_name_; }
3263
3264   // The section name.
3265   const std::string&
3266   section_name() const
3267   {
3268     gold_assert(this->section_has_name_);
3269     return this->section_name_;
3270   }
3271
3272   // Return true if the section name has a priority.  This is assumed
3273   // to be true if it has a dot after the initial dot.
3274   bool
3275   has_priority() const
3276   {
3277     gold_assert(this->section_has_name_);
3278     return this->section_name_.find('.', 1) != std::string::npos;
3279   }
3280
3281   // Return the priority.  Believe it or not, gcc encodes the priority
3282   // differently for .ctors/.dtors and .init_array/.fini_array
3283   // sections.
3284   unsigned int
3285   get_priority() const
3286   {
3287     gold_assert(this->section_has_name_);
3288     bool is_ctors;
3289     if (is_prefix_of(".ctors.", this->section_name_.c_str())
3290         || is_prefix_of(".dtors.", this->section_name_.c_str()))
3291       is_ctors = true;
3292     else if (is_prefix_of(".init_array.", this->section_name_.c_str())
3293              || is_prefix_of(".fini_array.", this->section_name_.c_str()))
3294       is_ctors = false;
3295     else
3296       return 0;
3297     char* end;
3298     unsigned long prio = strtoul((this->section_name_.c_str()
3299                                   + (is_ctors ? 7 : 12)),
3300                                  &end, 10);
3301     if (*end != '\0')
3302       return 0;
3303     else if (is_ctors)
3304       return 65535 - prio;
3305     else
3306       return prio;
3307   }
3308
3309   // Return true if this an input file whose base name matches
3310   // FILE_NAME.  The base name must have an extension of ".o", and
3311   // must be exactly FILE_NAME.o or FILE_NAME, one character, ".o".
3312   // This is to match crtbegin.o as well as crtbeginS.o without
3313   // getting confused by other possibilities.  Overall matching the
3314   // file name this way is a dreadful hack, but the GNU linker does it
3315   // in order to better support gcc, and we need to be compatible.
3316   bool
3317   match_file_name(const char* file_name) const
3318   { return Layout::match_file_name(this->input_section_.relobj(), file_name); }
3319
3320   // Returns 1 if THIS should appear before S in section order, -1 if S
3321   // appears before THIS and 0 if they are not comparable.
3322   int
3323   compare_section_ordering(const Input_section_sort_entry& s) const
3324   {
3325     unsigned int this_secn_index = this->input_section_.section_order_index();
3326     unsigned int s_secn_index = s.input_section().section_order_index();
3327     if (this_secn_index > 0 && s_secn_index > 0)
3328       {
3329         if (this_secn_index < s_secn_index)
3330           return 1;
3331         else if (this_secn_index > s_secn_index)
3332           return -1;
3333       }
3334     return 0;
3335   }
3336
3337  private:
3338   // The Input_section we are sorting.
3339   Input_section input_section_;
3340   // The index of this Input_section in the original list.
3341   unsigned int index_;
3342   // Whether this Input_section has a section name--it won't if this
3343   // is some random Output_section_data.
3344   bool section_has_name_;
3345   // The section name if there is one.
3346   std::string section_name_;
3347 };
3348
3349 // Return true if S1 should come before S2 in the output section.
3350
3351 bool
3352 Output_section::Input_section_sort_compare::operator()(
3353     const Output_section::Input_section_sort_entry& s1,
3354     const Output_section::Input_section_sort_entry& s2) const
3355 {
3356   // crtbegin.o must come first.
3357   bool s1_begin = s1.match_file_name("crtbegin");
3358   bool s2_begin = s2.match_file_name("crtbegin");
3359   if (s1_begin || s2_begin)
3360     {
3361       if (!s1_begin)
3362         return false;
3363       if (!s2_begin)
3364         return true;
3365       return s1.index() < s2.index();
3366     }
3367
3368   // crtend.o must come last.
3369   bool s1_end = s1.match_file_name("crtend");
3370   bool s2_end = s2.match_file_name("crtend");
3371   if (s1_end || s2_end)
3372     {
3373       if (!s1_end)
3374         return true;
3375       if (!s2_end)
3376         return false;
3377       return s1.index() < s2.index();
3378     }
3379
3380   // We sort all the sections with no names to the end.
3381   if (!s1.section_has_name() || !s2.section_has_name())
3382     {
3383       if (s1.section_has_name())
3384         return true;
3385       if (s2.section_has_name())
3386         return false;
3387       return s1.index() < s2.index();
3388     }
3389
3390   // A section with a priority follows a section without a priority.
3391   bool s1_has_priority = s1.has_priority();
3392   bool s2_has_priority = s2.has_priority();
3393   if (s1_has_priority && !s2_has_priority)
3394     return false;
3395   if (!s1_has_priority && s2_has_priority)
3396     return true;
3397
3398   // Check if a section order exists for these sections through a section
3399   // ordering file.  If sequence_num is 0, an order does not exist.
3400   int sequence_num = s1.compare_section_ordering(s2);
3401   if (sequence_num != 0)
3402     return sequence_num == 1;
3403
3404   // Otherwise we sort by name.
3405   int compare = s1.section_name().compare(s2.section_name());
3406   if (compare != 0)
3407     return compare < 0;
3408
3409   // Otherwise we keep the input order.
3410   return s1.index() < s2.index();
3411 }
3412
3413 // Return true if S1 should come before S2 in an .init_array or .fini_array
3414 // output section.
3415
3416 bool
3417 Output_section::Input_section_sort_init_fini_compare::operator()(
3418     const Output_section::Input_section_sort_entry& s1,
3419     const Output_section::Input_section_sort_entry& s2) const
3420 {
3421   // We sort all the sections with no names to the end.
3422   if (!s1.section_has_name() || !s2.section_has_name())
3423     {
3424       if (s1.section_has_name())
3425         return true;
3426       if (s2.section_has_name())
3427         return false;
3428       return s1.index() < s2.index();
3429     }
3430
3431   // A section without a priority follows a section with a priority.
3432   // This is the reverse of .ctors and .dtors sections.
3433   bool s1_has_priority = s1.has_priority();
3434   bool s2_has_priority = s2.has_priority();
3435   if (s1_has_priority && !s2_has_priority)
3436     return true;
3437   if (!s1_has_priority && s2_has_priority)
3438     return false;
3439
3440   // .ctors and .dtors sections without priority come after
3441   // .init_array and .fini_array sections without priority.
3442   if (!s1_has_priority
3443       && (s1.section_name() == ".ctors" || s1.section_name() == ".dtors")
3444       && s1.section_name() != s2.section_name())
3445     return false;
3446   if (!s2_has_priority
3447       && (s2.section_name() == ".ctors" || s2.section_name() == ".dtors")
3448       && s2.section_name() != s1.section_name())
3449     return true;
3450
3451   // Sort by priority if we can.
3452   if (s1_has_priority)
3453     {
3454       unsigned int s1_prio = s1.get_priority();
3455       unsigned int s2_prio = s2.get_priority();
3456       if (s1_prio < s2_prio)
3457         return true;
3458       else if (s1_prio > s2_prio)
3459         return false;
3460     }
3461
3462   // Check if a section order exists for these sections through a section
3463   // ordering file.  If sequence_num is 0, an order does not exist.
3464   int sequence_num = s1.compare_section_ordering(s2);
3465   if (sequence_num != 0)
3466     return sequence_num == 1;
3467
3468   // Otherwise we sort by name.
3469   int compare = s1.section_name().compare(s2.section_name());
3470   if (compare != 0)
3471     return compare < 0;
3472
3473   // Otherwise we keep the input order.
3474   return s1.index() < s2.index();
3475 }
3476
3477 // Return true if S1 should come before S2.  Sections that do not match
3478 // any pattern in the section ordering file are placed ahead of the sections
3479 // that match some pattern.
3480
3481 bool
3482 Output_section::Input_section_sort_section_order_index_compare::operator()(
3483     const Output_section::Input_section_sort_entry& s1,
3484     const Output_section::Input_section_sort_entry& s2) const
3485 {
3486   unsigned int s1_secn_index = s1.input_section().section_order_index();
3487   unsigned int s2_secn_index = s2.input_section().section_order_index();
3488
3489   // Keep input order if section ordering cannot determine order.
3490   if (s1_secn_index == s2_secn_index)
3491     return s1.index() < s2.index();
3492   
3493   return s1_secn_index < s2_secn_index;
3494 }
3495
3496 // This updates the section order index of input sections according to the
3497 // the order specified in the mapping from Section id to order index.
3498
3499 void
3500 Output_section::update_section_layout(
3501   const Section_layout_order* order_map)
3502 {
3503   for (Input_section_list::iterator p = this->input_sections_.begin();
3504        p != this->input_sections_.end();
3505        ++p)
3506     {
3507       if (p->is_input_section()
3508           || p->is_relaxed_input_section())
3509         {
3510           Object* obj = (p->is_input_section()
3511                          ? p->relobj()
3512                          : p->relaxed_input_section()->relobj());
3513           unsigned int shndx = p->shndx();
3514           Section_layout_order::const_iterator it
3515             = order_map->find(Section_id(obj, shndx));
3516           if (it == order_map->end())
3517             continue;
3518           unsigned int section_order_index = it->second;
3519           if (section_order_index != 0)
3520             {
3521               p->set_section_order_index(section_order_index);
3522               this->set_input_section_order_specified();
3523             }
3524         }
3525     }
3526 }
3527
3528 // Sort the input sections attached to an output section.
3529
3530 void
3531 Output_section::sort_attached_input_sections()
3532 {
3533   if (this->attached_input_sections_are_sorted_)
3534     return;
3535
3536   if (this->checkpoint_ != NULL
3537       && !this->checkpoint_->input_sections_saved())
3538     this->checkpoint_->save_input_sections();
3539
3540   // The only thing we know about an input section is the object and
3541   // the section index.  We need the section name.  Recomputing this
3542   // is slow but this is an unusual case.  If this becomes a speed
3543   // problem we can cache the names as required in Layout::layout.
3544
3545   // We start by building a larger vector holding a copy of each
3546   // Input_section, plus its current index in the list and its name.
3547   std::vector<Input_section_sort_entry> sort_list;
3548
3549   unsigned int i = 0;
3550   for (Input_section_list::iterator p = this->input_sections_.begin();
3551        p != this->input_sections_.end();
3552        ++p, ++i)
3553       sort_list.push_back(Input_section_sort_entry(*p, i,
3554                             this->must_sort_attached_input_sections()));
3555
3556   // Sort the input sections.
3557   if (this->must_sort_attached_input_sections())
3558     {
3559       if (this->type() == elfcpp::SHT_PREINIT_ARRAY
3560           || this->type() == elfcpp::SHT_INIT_ARRAY
3561           || this->type() == elfcpp::SHT_FINI_ARRAY)
3562         std::sort(sort_list.begin(), sort_list.end(),
3563                   Input_section_sort_init_fini_compare());
3564       else
3565         std::sort(sort_list.begin(), sort_list.end(),
3566                   Input_section_sort_compare());
3567     }
3568   else
3569     {
3570       gold_assert(this->input_section_order_specified());
3571       std::sort(sort_list.begin(), sort_list.end(),
3572                 Input_section_sort_section_order_index_compare());
3573     }
3574
3575   // Copy the sorted input sections back to our list.
3576   this->input_sections_.clear();
3577   for (std::vector<Input_section_sort_entry>::iterator p = sort_list.begin();
3578        p != sort_list.end();
3579        ++p)
3580     this->input_sections_.push_back(p->input_section());
3581   sort_list.clear();
3582
3583   // Remember that we sorted the input sections, since we might get
3584   // called again.
3585   this->attached_input_sections_are_sorted_ = true;
3586 }
3587
3588 // Write the section header to *OSHDR.
3589
3590 template<int size, bool big_endian>
3591 void
3592 Output_section::write_header(const Layout* layout,
3593                              const Stringpool* secnamepool,
3594                              elfcpp::Shdr_write<size, big_endian>* oshdr) const
3595 {
3596   oshdr->put_sh_name(secnamepool->get_offset(this->name_));
3597   oshdr->put_sh_type(this->type_);
3598
3599   elfcpp::Elf_Xword flags = this->flags_;
3600   if (this->info_section_ != NULL && this->info_uses_section_index_)
3601     flags |= elfcpp::SHF_INFO_LINK;
3602   oshdr->put_sh_flags(flags);
3603
3604   oshdr->put_sh_addr(this->address());
3605   oshdr->put_sh_offset(this->offset());
3606   oshdr->put_sh_size(this->data_size());
3607   if (this->link_section_ != NULL)
3608     oshdr->put_sh_link(this->link_section_->out_shndx());
3609   else if (this->should_link_to_symtab_)
3610     oshdr->put_sh_link(layout->symtab_section_shndx());
3611   else if (this->should_link_to_dynsym_)
3612     oshdr->put_sh_link(layout->dynsym_section()->out_shndx());
3613   else
3614     oshdr->put_sh_link(this->link_);
3615
3616   elfcpp::Elf_Word info;
3617   if (this->info_section_ != NULL)
3618     {
3619       if (this->info_uses_section_index_)
3620         info = this->info_section_->out_shndx();
3621       else
3622         info = this->info_section_->symtab_index();
3623     }
3624   else if (this->info_symndx_ != NULL)
3625     info = this->info_symndx_->symtab_index();
3626   else
3627     info = this->info_;
3628   oshdr->put_sh_info(info);
3629
3630   oshdr->put_sh_addralign(this->addralign_);
3631   oshdr->put_sh_entsize(this->entsize_);
3632 }
3633
3634 // Write out the data.  For input sections the data is written out by
3635 // Object::relocate, but we have to handle Output_section_data objects
3636 // here.
3637
3638 void
3639 Output_section::do_write(Output_file* of)
3640 {
3641   gold_assert(!this->requires_postprocessing());
3642
3643   // If the target performs relaxation, we delay filler generation until now.
3644   gold_assert(!this->generate_code_fills_at_write_ || this->fills_.empty());
3645
3646   off_t output_section_file_offset = this->offset();
3647   for (Fill_list::iterator p = this->fills_.begin();
3648        p != this->fills_.end();
3649        ++p)
3650     {
3651       std::string fill_data(parameters->target().code_fill(p->length()));
3652       of->write(output_section_file_offset + p->section_offset(),
3653                 fill_data.data(), fill_data.size());
3654     }
3655
3656   off_t off = this->offset() + this->first_input_offset_;
3657   for (Input_section_list::iterator p = this->input_sections_.begin();
3658        p != this->input_sections_.end();
3659        ++p)
3660     {
3661       off_t aligned_off = align_address(off, p->addralign());
3662       if (this->generate_code_fills_at_write_ && (off != aligned_off))
3663         {
3664           size_t fill_len = aligned_off - off;
3665           std::string fill_data(parameters->target().code_fill(fill_len));
3666           of->write(off, fill_data.data(), fill_data.size());
3667         }
3668
3669       p->write(of);
3670       off = aligned_off + p->data_size();
3671     }
3672
3673   // For incremental links, fill in unused chunks in debug sections
3674   // with dummy compilation unit headers.
3675   if (this->free_space_fill_ != NULL)
3676     {
3677       for (Free_list::Const_iterator p = this->free_list_.begin();
3678            p != this->free_list_.end();
3679            ++p)
3680         {
3681           off_t off = p->start_;
3682           size_t len = p->end_ - off;
3683           this->free_space_fill_->write(of, this->offset() + off, len);
3684         }
3685       if (this->patch_space_ > 0)
3686         {
3687           off_t off = this->current_data_size_for_child() - this->patch_space_;
3688           this->free_space_fill_->write(of, this->offset() + off,
3689                                         this->patch_space_);
3690         }
3691     }
3692 }
3693
3694 // If a section requires postprocessing, create the buffer to use.
3695
3696 void
3697 Output_section::create_postprocessing_buffer()
3698 {
3699   gold_assert(this->requires_postprocessing());
3700
3701   if (this->postprocessing_buffer_ != NULL)
3702     return;
3703
3704   if (!this->input_sections_.empty())
3705     {
3706       off_t off = this->first_input_offset_;
3707       for (Input_section_list::iterator p = this->input_sections_.begin();
3708            p != this->input_sections_.end();
3709            ++p)
3710         {
3711           off = align_address(off, p->addralign());
3712           p->finalize_data_size();
3713           off += p->data_size();
3714         }
3715       this->set_current_data_size_for_child(off);
3716     }
3717
3718   off_t buffer_size = this->current_data_size_for_child();
3719   this->postprocessing_buffer_ = new unsigned char[buffer_size];
3720 }
3721
3722 // Write all the data of an Output_section into the postprocessing
3723 // buffer.  This is used for sections which require postprocessing,
3724 // such as compression.  Input sections are handled by
3725 // Object::Relocate.
3726
3727 void
3728 Output_section::write_to_postprocessing_buffer()
3729 {
3730   gold_assert(this->requires_postprocessing());
3731
3732   // If the target performs relaxation, we delay filler generation until now.
3733   gold_assert(!this->generate_code_fills_at_write_ || this->fills_.empty());
3734
3735   unsigned char* buffer = this->postprocessing_buffer();
3736   for (Fill_list::iterator p = this->fills_.begin();
3737        p != this->fills_.end();
3738        ++p)
3739     {
3740       std::string fill_data(parameters->target().code_fill(p->length()));
3741       memcpy(buffer + p->section_offset(), fill_data.data(),
3742              fill_data.size());
3743     }
3744
3745   off_t off = this->first_input_offset_;
3746   for (Input_section_list::iterator p = this->input_sections_.begin();
3747        p != this->input_sections_.end();
3748        ++p)
3749     {
3750       off_t aligned_off = align_address(off, p->addralign());
3751       if (this->generate_code_fills_at_write_ && (off != aligned_off))
3752         {
3753           size_t fill_len = aligned_off - off;
3754           std::string fill_data(parameters->target().code_fill(fill_len));
3755           memcpy(buffer + off, fill_data.data(), fill_data.size());
3756         }
3757
3758       p->write_to_buffer(buffer + aligned_off);
3759       off = aligned_off + p->data_size();
3760     }
3761 }
3762
3763 // Get the input sections for linker script processing.  We leave
3764 // behind the Output_section_data entries.  Note that this may be
3765 // slightly incorrect for merge sections.  We will leave them behind,
3766 // but it is possible that the script says that they should follow
3767 // some other input sections, as in:
3768 //    .rodata { *(.rodata) *(.rodata.cst*) }
3769 // For that matter, we don't handle this correctly:
3770 //    .rodata { foo.o(.rodata.cst*) *(.rodata.cst*) }
3771 // With luck this will never matter.
3772
3773 uint64_t
3774 Output_section::get_input_sections(
3775     uint64_t address,
3776     const std::string& fill,
3777     std::list<Input_section>* input_sections)
3778 {
3779   if (this->checkpoint_ != NULL
3780       && !this->checkpoint_->input_sections_saved())
3781     this->checkpoint_->save_input_sections();
3782
3783   // Invalidate fast look-up maps.
3784   this->lookup_maps_->invalidate();
3785
3786   uint64_t orig_address = address;
3787
3788   address = align_address(address, this->addralign());
3789
3790   Input_section_list remaining;
3791   for (Input_section_list::iterator p = this->input_sections_.begin();
3792        p != this->input_sections_.end();
3793        ++p)
3794     {
3795       if (p->is_input_section()
3796           || p->is_relaxed_input_section()
3797           || p->is_merge_section())
3798         input_sections->push_back(*p);
3799       else
3800         {
3801           uint64_t aligned_address = align_address(address, p->addralign());
3802           if (aligned_address != address && !fill.empty())
3803             {
3804               section_size_type length =
3805                 convert_to_section_size_type(aligned_address - address);
3806               std::string this_fill;
3807               this_fill.reserve(length);
3808               while (this_fill.length() + fill.length() <= length)
3809                 this_fill += fill;
3810               if (this_fill.length() < length)
3811                 this_fill.append(fill, 0, length - this_fill.length());
3812
3813               Output_section_data* posd = new Output_data_const(this_fill, 0);
3814               remaining.push_back(Input_section(posd));
3815             }
3816           address = aligned_address;
3817
3818           remaining.push_back(*p);
3819
3820           p->finalize_data_size();
3821           address += p->data_size();
3822         }
3823     }
3824
3825   this->input_sections_.swap(remaining);
3826   this->first_input_offset_ = 0;
3827
3828   uint64_t data_size = address - orig_address;
3829   this->set_current_data_size_for_child(data_size);
3830   return data_size;
3831 }
3832
3833 // Add a script input section.  SIS is an Output_section::Input_section,
3834 // which can be either a plain input section or a special input section like
3835 // a relaxed input section.  For a special input section, its size must be
3836 // finalized.
3837
3838 void
3839 Output_section::add_script_input_section(const Input_section& sis)
3840 {
3841   uint64_t data_size = sis.data_size();
3842   uint64_t addralign = sis.addralign();
3843   if (addralign > this->addralign_)
3844     this->addralign_ = addralign;
3845
3846   off_t offset_in_section = this->current_data_size_for_child();
3847   off_t aligned_offset_in_section = align_address(offset_in_section,
3848                                                   addralign);
3849
3850   this->set_current_data_size_for_child(aligned_offset_in_section
3851                                         + data_size);
3852
3853   this->input_sections_.push_back(sis);
3854
3855   // Update fast lookup maps if necessary. 
3856   if (this->lookup_maps_->is_valid())
3857     {
3858       if (sis.is_merge_section())
3859         {
3860           Output_merge_base* pomb = sis.output_merge_base();
3861           Merge_section_properties msp(pomb->is_string(), pomb->entsize(),
3862                                        pomb->addralign());
3863           this->lookup_maps_->add_merge_section(msp, pomb);
3864           for (Output_merge_base::Input_sections::const_iterator p =
3865                  pomb->input_sections_begin();
3866                p != pomb->input_sections_end();
3867                ++p)
3868             this->lookup_maps_->add_merge_input_section(p->first, p->second,
3869                                                         pomb);
3870         }
3871       else if (sis.is_relaxed_input_section())
3872         {
3873           Output_relaxed_input_section* poris = sis.relaxed_input_section();
3874           this->lookup_maps_->add_relaxed_input_section(poris->relobj(),
3875                                                         poris->shndx(), poris);
3876         }
3877     }
3878 }
3879
3880 // Save states for relaxation.
3881
3882 void
3883 Output_section::save_states()
3884 {
3885   gold_assert(this->checkpoint_ == NULL);
3886   Checkpoint_output_section* checkpoint =
3887     new Checkpoint_output_section(this->addralign_, this->flags_,
3888                                   this->input_sections_,
3889                                   this->first_input_offset_,
3890                                   this->attached_input_sections_are_sorted_);
3891   this->checkpoint_ = checkpoint;
3892   gold_assert(this->fills_.empty());
3893 }
3894
3895 void
3896 Output_section::discard_states()
3897 {
3898   gold_assert(this->checkpoint_ != NULL);
3899   delete this->checkpoint_;
3900   this->checkpoint_ = NULL;
3901   gold_assert(this->fills_.empty());
3902
3903   // Simply invalidate the fast lookup maps since we do not keep
3904   // track of them.
3905   this->lookup_maps_->invalidate();
3906 }
3907
3908 void
3909 Output_section::restore_states()
3910 {
3911   gold_assert(this->checkpoint_ != NULL);
3912   Checkpoint_output_section* checkpoint = this->checkpoint_;
3913
3914   this->addralign_ = checkpoint->addralign();
3915   this->flags_ = checkpoint->flags();
3916   this->first_input_offset_ = checkpoint->first_input_offset();
3917
3918   if (!checkpoint->input_sections_saved())
3919     {
3920       // If we have not copied the input sections, just resize it.
3921       size_t old_size = checkpoint->input_sections_size();
3922       gold_assert(this->input_sections_.size() >= old_size);
3923       this->input_sections_.resize(old_size);
3924     }
3925   else
3926     {
3927       // We need to copy the whole list.  This is not efficient for
3928       // extremely large output with hundreads of thousands of input
3929       // objects.  We may need to re-think how we should pass sections
3930       // to scripts.
3931       this->input_sections_ = *checkpoint->input_sections();
3932     }
3933
3934   this->attached_input_sections_are_sorted_ =
3935     checkpoint->attached_input_sections_are_sorted();
3936
3937   // Simply invalidate the fast lookup maps since we do not keep
3938   // track of them.
3939   this->lookup_maps_->invalidate();
3940 }
3941
3942 // Update the section offsets of input sections in this.  This is required if
3943 // relaxation causes some input sections to change sizes.
3944
3945 void
3946 Output_section::adjust_section_offsets()
3947 {
3948   if (!this->section_offsets_need_adjustment_)
3949     return;
3950
3951   off_t off = 0;
3952   for (Input_section_list::iterator p = this->input_sections_.begin();
3953        p != this->input_sections_.end();
3954        ++p)
3955     {
3956       off = align_address(off, p->addralign());
3957       if (p->is_input_section())
3958         p->relobj()->set_section_offset(p->shndx(), off);
3959       off += p->data_size();
3960     }
3961
3962   this->section_offsets_need_adjustment_ = false;
3963 }
3964
3965 // Print to the map file.
3966
3967 void
3968 Output_section::do_print_to_mapfile(Mapfile* mapfile) const
3969 {
3970   mapfile->print_output_section(this);
3971
3972   for (Input_section_list::const_iterator p = this->input_sections_.begin();
3973        p != this->input_sections_.end();
3974        ++p)
3975     p->print_to_mapfile(mapfile);
3976 }
3977
3978 // Print stats for merge sections to stderr.
3979
3980 void
3981 Output_section::print_merge_stats()
3982 {
3983   Input_section_list::iterator p;
3984   for (p = this->input_sections_.begin();
3985        p != this->input_sections_.end();
3986        ++p)
3987     p->print_merge_stats(this->name_);
3988 }
3989
3990 // Set a fixed layout for the section.  Used for incremental update links.
3991
3992 void
3993 Output_section::set_fixed_layout(uint64_t sh_addr, off_t sh_offset,
3994                                  off_t sh_size, uint64_t sh_addralign)
3995 {
3996   this->addralign_ = sh_addralign;
3997   this->set_current_data_size(sh_size);
3998   if ((this->flags_ & elfcpp::SHF_ALLOC) != 0)
3999     this->set_address(sh_addr);
4000   this->set_file_offset(sh_offset);
4001   this->finalize_data_size();
4002   this->free_list_.init(sh_size, false);
4003   this->has_fixed_layout_ = true;
4004 }
4005
4006 // Reserve space within the fixed layout for the section.  Used for
4007 // incremental update links.
4008
4009 void
4010 Output_section::reserve(uint64_t sh_offset, uint64_t sh_size)
4011 {
4012   this->free_list_.remove(sh_offset, sh_offset + sh_size);
4013 }
4014
4015 // Allocate space from the free list for the section.  Used for
4016 // incremental update links.
4017
4018 off_t
4019 Output_section::allocate(off_t len, uint64_t addralign)
4020 {
4021   return this->free_list_.allocate(len, addralign, 0);
4022 }
4023
4024 // Output segment methods.
4025
4026 Output_segment::Output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
4027   : vaddr_(0),
4028     paddr_(0),
4029     memsz_(0),
4030     max_align_(0),
4031     min_p_align_(0),
4032     offset_(0),
4033     filesz_(0),
4034     type_(type),
4035     flags_(flags),
4036     is_max_align_known_(false),
4037     are_addresses_set_(false),
4038     is_large_data_segment_(false)
4039 {
4040   // The ELF ABI specifies that a PT_TLS segment always has PF_R as
4041   // the flags.
4042   if (type == elfcpp::PT_TLS)
4043     this->flags_ = elfcpp::PF_R;
4044 }
4045
4046 // Add an Output_section to a PT_LOAD Output_segment.
4047
4048 void
4049 Output_segment::add_output_section_to_load(Layout* layout,
4050                                            Output_section* os,
4051                                            elfcpp::Elf_Word seg_flags)
4052 {
4053   gold_assert(this->type() == elfcpp::PT_LOAD);
4054   gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
4055   gold_assert(!this->is_max_align_known_);
4056   gold_assert(os->is_large_data_section() == this->is_large_data_segment());
4057
4058   this->update_flags_for_output_section(seg_flags);
4059
4060   // We don't want to change the ordering if we have a linker script
4061   // with a SECTIONS clause.
4062   Output_section_order order = os->order();
4063   if (layout->script_options()->saw_sections_clause())
4064     order = static_cast<Output_section_order>(0);
4065   else
4066     gold_assert(order != ORDER_INVALID);
4067
4068   this->output_lists_[order].push_back(os);
4069 }
4070
4071 // Add an Output_section to a non-PT_LOAD Output_segment.
4072
4073 void
4074 Output_segment::add_output_section_to_nonload(Output_section* os,
4075                                               elfcpp::Elf_Word seg_flags)
4076 {
4077   gold_assert(this->type() != elfcpp::PT_LOAD);
4078   gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
4079   gold_assert(!this->is_max_align_known_);
4080
4081   this->update_flags_for_output_section(seg_flags);
4082
4083   this->output_lists_[0].push_back(os);
4084 }
4085
4086 // Remove an Output_section from this segment.  It is an error if it
4087 // is not present.
4088
4089 void
4090 Output_segment::remove_output_section(Output_section* os)
4091 {
4092   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4093     {
4094       Output_data_list* pdl = &this->output_lists_[i];
4095       for (Output_data_list::iterator p = pdl->begin(); p != pdl->end(); ++p)
4096         {
4097           if (*p == os)
4098             {
4099               pdl->erase(p);
4100               return;
4101             }
4102         }
4103     }
4104   gold_unreachable();
4105 }
4106
4107 // Add an Output_data (which need not be an Output_section) to the
4108 // start of a segment.
4109
4110 void
4111 Output_segment::add_initial_output_data(Output_data* od)
4112 {
4113   gold_assert(!this->is_max_align_known_);
4114   Output_data_list::iterator p = this->output_lists_[0].begin();
4115   this->output_lists_[0].insert(p, od);
4116 }
4117
4118 // Return true if this segment has any sections which hold actual
4119 // data, rather than being a BSS section.
4120
4121 bool
4122 Output_segment::has_any_data_sections() const
4123 {
4124   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4125     {
4126       const Output_data_list* pdl = &this->output_lists_[i];
4127       for (Output_data_list::const_iterator p = pdl->begin();
4128            p != pdl->end();
4129            ++p)
4130         {
4131           if (!(*p)->is_section())
4132             return true;
4133           if ((*p)->output_section()->type() != elfcpp::SHT_NOBITS)
4134             return true;
4135         }
4136     }
4137   return false;
4138 }
4139
4140 // Return whether the first data section (not counting TLS sections)
4141 // is a relro section.
4142
4143 bool
4144 Output_segment::is_first_section_relro() const
4145 {
4146   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4147     {
4148       if (i == static_cast<int>(ORDER_TLS_DATA)
4149           || i == static_cast<int>(ORDER_TLS_BSS))
4150         continue;
4151       const Output_data_list* pdl = &this->output_lists_[i];
4152       if (!pdl->empty())
4153         {
4154           Output_data* p = pdl->front();
4155           return p->is_section() && p->output_section()->is_relro();
4156         }
4157     }
4158   return false;
4159 }
4160
4161 // Return the maximum alignment of the Output_data in Output_segment.
4162
4163 uint64_t
4164 Output_segment::maximum_alignment()
4165 {
4166   if (!this->is_max_align_known_)
4167     {
4168       for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4169         {       
4170           const Output_data_list* pdl = &this->output_lists_[i];
4171           uint64_t addralign = Output_segment::maximum_alignment_list(pdl);
4172           if (addralign > this->max_align_)
4173             this->max_align_ = addralign;
4174         }
4175       this->is_max_align_known_ = true;
4176     }
4177
4178   return this->max_align_;
4179 }
4180
4181 // Return the maximum alignment of a list of Output_data.
4182
4183 uint64_t
4184 Output_segment::maximum_alignment_list(const Output_data_list* pdl)
4185 {
4186   uint64_t ret = 0;
4187   for (Output_data_list::const_iterator p = pdl->begin();
4188        p != pdl->end();
4189        ++p)
4190     {
4191       uint64_t addralign = (*p)->addralign();
4192       if (addralign > ret)
4193         ret = addralign;
4194     }
4195   return ret;
4196 }
4197
4198 // Return whether this segment has any dynamic relocs.
4199
4200 bool
4201 Output_segment::has_dynamic_reloc() const
4202 {
4203   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4204     if (this->has_dynamic_reloc_list(&this->output_lists_[i]))
4205       return true;
4206   return false;
4207 }
4208
4209 // Return whether this Output_data_list has any dynamic relocs.
4210
4211 bool
4212 Output_segment::has_dynamic_reloc_list(const Output_data_list* pdl) const
4213 {
4214   for (Output_data_list::const_iterator p = pdl->begin();
4215        p != pdl->end();
4216        ++p)
4217     if ((*p)->has_dynamic_reloc())
4218       return true;
4219   return false;
4220 }
4221
4222 // Set the section addresses for an Output_segment.  If RESET is true,
4223 // reset the addresses first.  ADDR is the address and *POFF is the
4224 // file offset.  Set the section indexes starting with *PSHNDX.
4225 // INCREASE_RELRO is the size of the portion of the first non-relro
4226 // section that should be included in the PT_GNU_RELRO segment.
4227 // If this segment has relro sections, and has been aligned for
4228 // that purpose, set *HAS_RELRO to TRUE.  Return the address of
4229 // the immediately following segment.  Update *HAS_RELRO, *POFF,
4230 // and *PSHNDX.
4231
4232 uint64_t
4233 Output_segment::set_section_addresses(Layout* layout, bool reset,
4234                                       uint64_t addr,
4235                                       unsigned int* increase_relro,
4236                                       bool* has_relro,
4237                                       off_t* poff,
4238                                       unsigned int* pshndx)
4239 {
4240   gold_assert(this->type_ == elfcpp::PT_LOAD);
4241
4242   uint64_t last_relro_pad = 0;
4243   off_t orig_off = *poff;
4244
4245   bool in_tls = false;
4246
4247   // If we have relro sections, we need to pad forward now so that the
4248   // relro sections plus INCREASE_RELRO end on a common page boundary.
4249   if (parameters->options().relro()
4250       && this->is_first_section_relro()
4251       && (!this->are_addresses_set_ || reset))
4252     {
4253       uint64_t relro_size = 0;
4254       off_t off = *poff;
4255       uint64_t max_align = 0;
4256       for (int i = 0; i <= static_cast<int>(ORDER_RELRO_LAST); ++i)
4257         {
4258           Output_data_list* pdl = &this->output_lists_[i];
4259           Output_data_list::iterator p;
4260           for (p = pdl->begin(); p != pdl->end(); ++p)
4261             {
4262               if (!(*p)->is_section())
4263                 break;
4264               uint64_t align = (*p)->addralign();
4265               if (align > max_align)
4266                 max_align = align;
4267               if ((*p)->is_section_flag_set(elfcpp::SHF_TLS))
4268                 in_tls = true;
4269               else if (in_tls)
4270                 {
4271                   // Align the first non-TLS section to the alignment
4272                   // of the TLS segment.
4273                   align = max_align;
4274                   in_tls = false;
4275                 }
4276               relro_size = align_address(relro_size, align);
4277               // Ignore the size of the .tbss section.
4278               if ((*p)->is_section_flag_set(elfcpp::SHF_TLS)
4279                   && (*p)->is_section_type(elfcpp::SHT_NOBITS))
4280                 continue;
4281               if ((*p)->is_address_valid())
4282                 relro_size += (*p)->data_size();
4283               else
4284                 {
4285                   // FIXME: This could be faster.
4286                   (*p)->set_address_and_file_offset(addr + relro_size,
4287                                                     off + relro_size);
4288                   relro_size += (*p)->data_size();
4289                   (*p)->reset_address_and_file_offset();
4290                 }
4291             }
4292           if (p != pdl->end())
4293             break;
4294         }
4295       relro_size += *increase_relro;
4296       // Pad the total relro size to a multiple of the maximum
4297       // section alignment seen.
4298       uint64_t aligned_size = align_address(relro_size, max_align);
4299       // Note the amount of padding added after the last relro section.
4300       last_relro_pad = aligned_size - relro_size;
4301       *has_relro = true;
4302
4303       uint64_t page_align = parameters->target().common_pagesize();
4304
4305       // Align to offset N such that (N + RELRO_SIZE) % PAGE_ALIGN == 0.
4306       uint64_t desired_align = page_align - (aligned_size % page_align);
4307       if (desired_align < *poff % page_align)
4308         *poff += page_align - *poff % page_align;
4309       *poff += desired_align - *poff % page_align;
4310       addr += *poff - orig_off;
4311       orig_off = *poff;
4312     }
4313
4314   if (!reset && this->are_addresses_set_)
4315     {
4316       gold_assert(this->paddr_ == addr);
4317       addr = this->vaddr_;
4318     }
4319   else
4320     {
4321       this->vaddr_ = addr;
4322       this->paddr_ = addr;
4323       this->are_addresses_set_ = true;
4324     }
4325
4326   in_tls = false;
4327
4328   this->offset_ = orig_off;
4329
4330   off_t off = 0;
4331   uint64_t ret;
4332   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4333     {
4334       if (i == static_cast<int>(ORDER_RELRO_LAST))
4335         {
4336           *poff += last_relro_pad;
4337           addr += last_relro_pad;
4338           if (this->output_lists_[i].empty())
4339             {
4340               // If there is nothing in the ORDER_RELRO_LAST list,
4341               // the padding will occur at the end of the relro
4342               // segment, and we need to add it to *INCREASE_RELRO.
4343               *increase_relro += last_relro_pad;
4344             }
4345         }
4346       addr = this->set_section_list_addresses(layout, reset,
4347                                               &this->output_lists_[i],
4348                                               addr, poff, pshndx, &in_tls);
4349       if (i < static_cast<int>(ORDER_SMALL_BSS))
4350         {
4351           this->filesz_ = *poff - orig_off;
4352           off = *poff;
4353         }
4354
4355       ret = addr;
4356     }
4357
4358   // If the last section was a TLS section, align upward to the
4359   // alignment of the TLS segment, so that the overall size of the TLS
4360   // segment is aligned.
4361   if (in_tls)
4362     {
4363       uint64_t segment_align = layout->tls_segment()->maximum_alignment();
4364       *poff = align_address(*poff, segment_align);
4365     }
4366
4367   this->memsz_ = *poff - orig_off;
4368
4369   // Ignore the file offset adjustments made by the BSS Output_data
4370   // objects.
4371   *poff = off;
4372
4373   return ret;
4374 }
4375
4376 // Set the addresses and file offsets in a list of Output_data
4377 // structures.
4378
4379 uint64_t
4380 Output_segment::set_section_list_addresses(Layout* layout, bool reset,
4381                                            Output_data_list* pdl,
4382                                            uint64_t addr, off_t* poff,
4383                                            unsigned int* pshndx,
4384                                            bool* in_tls)
4385 {
4386   off_t startoff = *poff;
4387   // For incremental updates, we may allocate non-fixed sections from
4388   // free space in the file.  This keeps track of the high-water mark.
4389   off_t maxoff = startoff;
4390
4391   off_t off = startoff;
4392   for (Output_data_list::iterator p = pdl->begin();
4393        p != pdl->end();
4394        ++p)
4395     {
4396       if (reset)
4397         (*p)->reset_address_and_file_offset();
4398
4399       // When doing an incremental update or when using a linker script,
4400       // the section will most likely already have an address.
4401       if (!(*p)->is_address_valid())
4402         {
4403           uint64_t align = (*p)->addralign();
4404
4405           if ((*p)->is_section_flag_set(elfcpp::SHF_TLS))
4406             {
4407               // Give the first TLS section the alignment of the
4408               // entire TLS segment.  Otherwise the TLS segment as a
4409               // whole may be misaligned.
4410               if (!*in_tls)
4411                 {
4412                   Output_segment* tls_segment = layout->tls_segment();
4413                   gold_assert(tls_segment != NULL);
4414                   uint64_t segment_align = tls_segment->maximum_alignment();
4415                   gold_assert(segment_align >= align);
4416                   align = segment_align;
4417
4418                   *in_tls = true;
4419                 }
4420             }
4421           else
4422             {
4423               // If this is the first section after the TLS segment,
4424               // align it to at least the alignment of the TLS
4425               // segment, so that the size of the overall TLS segment
4426               // is aligned.
4427               if (*in_tls)
4428                 {
4429                   uint64_t segment_align =
4430                       layout->tls_segment()->maximum_alignment();
4431                   if (segment_align > align)
4432                     align = segment_align;
4433
4434                   *in_tls = false;
4435                 }
4436             }
4437
4438           if (!parameters->incremental_update())
4439             {
4440               off = align_address(off, align);
4441               (*p)->set_address_and_file_offset(addr + (off - startoff), off);
4442             }
4443           else
4444             {
4445               // Incremental update: allocate file space from free list.
4446               (*p)->pre_finalize_data_size();
4447               off_t current_size = (*p)->current_data_size();
4448               off = layout->allocate(current_size, align, startoff);
4449               if (off == -1)
4450                 {
4451                   gold_assert((*p)->output_section() != NULL);
4452                   gold_fallback(_("out of patch space for section %s; "
4453                                   "relink with --incremental-full"),
4454                                 (*p)->output_section()->name());
4455                 }
4456               (*p)->set_address_and_file_offset(addr + (off - startoff), off);
4457               if ((*p)->data_size() > current_size)
4458                 {
4459                   gold_assert((*p)->output_section() != NULL);
4460                   gold_fallback(_("%s: section changed size; "
4461                                   "relink with --incremental-full"),
4462                                 (*p)->output_section()->name());
4463                 }
4464             }
4465         }
4466       else if (parameters->incremental_update())
4467         {
4468           // For incremental updates, use the fixed offset for the
4469           // high-water mark computation.
4470           off = (*p)->offset();
4471         }
4472       else
4473         {
4474           // The script may have inserted a skip forward, but it
4475           // better not have moved backward.
4476           if ((*p)->address() >= addr + (off - startoff))
4477             off += (*p)->address() - (addr + (off - startoff));
4478           else
4479             {
4480               if (!layout->script_options()->saw_sections_clause())
4481                 gold_unreachable();
4482               else
4483                 {
4484                   Output_section* os = (*p)->output_section();
4485
4486                   // Cast to unsigned long long to avoid format warnings.
4487                   unsigned long long previous_dot =
4488                     static_cast<unsigned long long>(addr + (off - startoff));
4489                   unsigned long long dot =
4490                     static_cast<unsigned long long>((*p)->address());
4491
4492                   if (os == NULL)
4493                     gold_error(_("dot moves backward in linker script "
4494                                  "from 0x%llx to 0x%llx"), previous_dot, dot);
4495                   else
4496                     gold_error(_("address of section '%s' moves backward "
4497                                  "from 0x%llx to 0x%llx"),
4498                                os->name(), previous_dot, dot);
4499                 }
4500             }
4501           (*p)->set_file_offset(off);
4502           (*p)->finalize_data_size();
4503         }
4504
4505       if (parameters->incremental_update())
4506         gold_debug(DEBUG_INCREMENTAL,
4507                    "set_section_list_addresses: %08lx %08lx %s",
4508                    static_cast<long>(off),
4509                    static_cast<long>((*p)->data_size()),
4510                    ((*p)->output_section() != NULL
4511                     ? (*p)->output_section()->name() : "(special)"));
4512
4513       // We want to ignore the size of a SHF_TLS SHT_NOBITS
4514       // section.  Such a section does not affect the size of a
4515       // PT_LOAD segment.
4516       if (!(*p)->is_section_flag_set(elfcpp::SHF_TLS)
4517           || !(*p)->is_section_type(elfcpp::SHT_NOBITS))
4518         off += (*p)->data_size();
4519
4520       if (off > maxoff)
4521         maxoff = off;
4522
4523       if ((*p)->is_section())
4524         {
4525           (*p)->set_out_shndx(*pshndx);
4526           ++*pshndx;
4527         }
4528     }
4529
4530   *poff = maxoff;
4531   return addr + (maxoff - startoff);
4532 }
4533
4534 // For a non-PT_LOAD segment, set the offset from the sections, if
4535 // any.  Add INCREASE to the file size and the memory size.
4536
4537 void
4538 Output_segment::set_offset(unsigned int increase)
4539 {
4540   gold_assert(this->type_ != elfcpp::PT_LOAD);
4541
4542   gold_assert(!this->are_addresses_set_);
4543
4544   // A non-load section only uses output_lists_[0].
4545
4546   Output_data_list* pdl = &this->output_lists_[0];
4547
4548   if (pdl->empty())
4549     {
4550       gold_assert(increase == 0);
4551       this->vaddr_ = 0;
4552       this->paddr_ = 0;
4553       this->are_addresses_set_ = true;
4554       this->memsz_ = 0;
4555       this->min_p_align_ = 0;
4556       this->offset_ = 0;
4557       this->filesz_ = 0;
4558       return;
4559     }
4560
4561   // Find the first and last section by address.
4562   const Output_data* first = NULL;
4563   const Output_data* last_data = NULL;
4564   const Output_data* last_bss = NULL;
4565   for (Output_data_list::const_iterator p = pdl->begin();
4566        p != pdl->end();
4567        ++p)
4568     {
4569       if (first == NULL
4570           || (*p)->address() < first->address()
4571           || ((*p)->address() == first->address()
4572               && (*p)->data_size() < first->data_size()))
4573         first = *p;
4574       const Output_data** plast;
4575       if ((*p)->is_section()
4576           && (*p)->output_section()->type() == elfcpp::SHT_NOBITS)
4577         plast = &last_bss;
4578       else
4579         plast = &last_data;
4580       if (*plast == NULL
4581           || (*p)->address() > (*plast)->address()
4582           || ((*p)->address() == (*plast)->address()
4583               && (*p)->data_size() > (*plast)->data_size()))
4584         *plast = *p;
4585     }
4586
4587   this->vaddr_ = first->address();
4588   this->paddr_ = (first->has_load_address()
4589                   ? first->load_address()
4590                   : this->vaddr_);
4591   this->are_addresses_set_ = true;
4592   this->offset_ = first->offset();
4593
4594   if (last_data == NULL)
4595     this->filesz_ = 0;
4596   else
4597     this->filesz_ = (last_data->address()
4598                      + last_data->data_size()
4599                      - this->vaddr_);
4600
4601   const Output_data* last = last_bss != NULL ? last_bss : last_data;
4602   this->memsz_ = (last->address()
4603                   + last->data_size()
4604                   - this->vaddr_);
4605
4606   this->filesz_ += increase;
4607   this->memsz_ += increase;
4608
4609   // If this is a RELRO segment, verify that the segment ends at a
4610   // page boundary.
4611   if (this->type_ == elfcpp::PT_GNU_RELRO)
4612     {
4613       uint64_t page_align = parameters->target().common_pagesize();
4614       uint64_t segment_end = this->vaddr_ + this->memsz_;
4615       if (parameters->incremental_update())
4616         {
4617           // The INCREASE_RELRO calculation is bypassed for an incremental
4618           // update, so we need to adjust the segment size manually here.
4619           segment_end = align_address(segment_end, page_align);
4620           this->memsz_ = segment_end - this->vaddr_;
4621         }
4622       else
4623         gold_assert(segment_end == align_address(segment_end, page_align));
4624     }
4625
4626   // If this is a TLS segment, align the memory size.  The code in
4627   // set_section_list ensures that the section after the TLS segment
4628   // is aligned to give us room.
4629   if (this->type_ == elfcpp::PT_TLS)
4630     {
4631       uint64_t segment_align = this->maximum_alignment();
4632       gold_assert(this->vaddr_ == align_address(this->vaddr_, segment_align));
4633       this->memsz_ = align_address(this->memsz_, segment_align);
4634     }
4635 }
4636
4637 // Set the TLS offsets of the sections in the PT_TLS segment.
4638
4639 void
4640 Output_segment::set_tls_offsets()
4641 {
4642   gold_assert(this->type_ == elfcpp::PT_TLS);
4643
4644   for (Output_data_list::iterator p = this->output_lists_[0].begin();
4645        p != this->output_lists_[0].end();
4646        ++p)
4647     (*p)->set_tls_offset(this->vaddr_);
4648 }
4649
4650 // Return the load address of the first section.
4651
4652 uint64_t
4653 Output_segment::first_section_load_address() const
4654 {
4655   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4656     {
4657       const Output_data_list* pdl = &this->output_lists_[i];
4658       for (Output_data_list::const_iterator p = pdl->begin();
4659            p != pdl->end();
4660            ++p)
4661         {
4662           if ((*p)->is_section())
4663             return ((*p)->has_load_address()
4664                     ? (*p)->load_address()
4665                     : (*p)->address());
4666         }
4667     }
4668   gold_unreachable();
4669 }
4670
4671 // Return the number of Output_sections in an Output_segment.
4672
4673 unsigned int
4674 Output_segment::output_section_count() const
4675 {
4676   unsigned int ret = 0;
4677   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4678     ret += this->output_section_count_list(&this->output_lists_[i]);
4679   return ret;
4680 }
4681
4682 // Return the number of Output_sections in an Output_data_list.
4683
4684 unsigned int
4685 Output_segment::output_section_count_list(const Output_data_list* pdl) const
4686 {
4687   unsigned int count = 0;
4688   for (Output_data_list::const_iterator p = pdl->begin();
4689        p != pdl->end();
4690        ++p)
4691     {
4692       if ((*p)->is_section())
4693         ++count;
4694     }
4695   return count;
4696 }
4697
4698 // Return the section attached to the list segment with the lowest
4699 // load address.  This is used when handling a PHDRS clause in a
4700 // linker script.
4701
4702 Output_section*
4703 Output_segment::section_with_lowest_load_address() const
4704 {
4705   Output_section* found = NULL;
4706   uint64_t found_lma = 0;
4707   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4708     this->lowest_load_address_in_list(&this->output_lists_[i], &found,
4709                                       &found_lma);
4710   return found;
4711 }
4712
4713 // Look through a list for a section with a lower load address.
4714
4715 void
4716 Output_segment::lowest_load_address_in_list(const Output_data_list* pdl,
4717                                             Output_section** found,
4718                                             uint64_t* found_lma) const
4719 {
4720   for (Output_data_list::const_iterator p = pdl->begin();
4721        p != pdl->end();
4722        ++p)
4723     {
4724       if (!(*p)->is_section())
4725         continue;
4726       Output_section* os = static_cast<Output_section*>(*p);
4727       uint64_t lma = (os->has_load_address()
4728                       ? os->load_address()
4729                       : os->address());
4730       if (*found == NULL || lma < *found_lma)
4731         {
4732           *found = os;
4733           *found_lma = lma;
4734         }
4735     }
4736 }
4737
4738 // Write the segment data into *OPHDR.
4739
4740 template<int size, bool big_endian>
4741 void
4742 Output_segment::write_header(elfcpp::Phdr_write<size, big_endian>* ophdr)
4743 {
4744   ophdr->put_p_type(this->type_);
4745   ophdr->put_p_offset(this->offset_);
4746   ophdr->put_p_vaddr(this->vaddr_);
4747   ophdr->put_p_paddr(this->paddr_);
4748   ophdr->put_p_filesz(this->filesz_);
4749   ophdr->put_p_memsz(this->memsz_);
4750   ophdr->put_p_flags(this->flags_);
4751   ophdr->put_p_align(std::max(this->min_p_align_, this->maximum_alignment()));
4752 }
4753
4754 // Write the section headers into V.
4755
4756 template<int size, bool big_endian>
4757 unsigned char*
4758 Output_segment::write_section_headers(const Layout* layout,
4759                                       const Stringpool* secnamepool,
4760                                       unsigned char* v,
4761                                       unsigned int* pshndx) const
4762 {
4763   // Every section that is attached to a segment must be attached to a
4764   // PT_LOAD segment, so we only write out section headers for PT_LOAD
4765   // segments.
4766   if (this->type_ != elfcpp::PT_LOAD)
4767     return v;
4768
4769   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4770     {
4771       const Output_data_list* pdl = &this->output_lists_[i];
4772       v = this->write_section_headers_list<size, big_endian>(layout,
4773                                                              secnamepool,
4774                                                              pdl,
4775                                                              v, pshndx);
4776     }
4777
4778   return v;
4779 }
4780
4781 template<int size, bool big_endian>
4782 unsigned char*
4783 Output_segment::write_section_headers_list(const Layout* layout,
4784                                            const Stringpool* secnamepool,
4785                                            const Output_data_list* pdl,
4786                                            unsigned char* v,
4787                                            unsigned int* pshndx) const
4788 {
4789   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
4790   for (Output_data_list::const_iterator p = pdl->begin();
4791        p != pdl->end();
4792        ++p)
4793     {
4794       if ((*p)->is_section())
4795         {
4796           const Output_section* ps = static_cast<const Output_section*>(*p);
4797           gold_assert(*pshndx == ps->out_shndx());
4798           elfcpp::Shdr_write<size, big_endian> oshdr(v);
4799           ps->write_header(layout, secnamepool, &oshdr);
4800           v += shdr_size;
4801           ++*pshndx;
4802         }
4803     }
4804   return v;
4805 }
4806
4807 // Print the output sections to the map file.
4808
4809 void
4810 Output_segment::print_sections_to_mapfile(Mapfile* mapfile) const
4811 {
4812   if (this->type() != elfcpp::PT_LOAD)
4813     return;
4814   for (int i = 0; i < static_cast<int>(ORDER_MAX); ++i)
4815     this->print_section_list_to_mapfile(mapfile, &this->output_lists_[i]);
4816 }
4817
4818 // Print an output section list to the map file.
4819
4820 void
4821 Output_segment::print_section_list_to_mapfile(Mapfile* mapfile,
4822                                               const Output_data_list* pdl) const
4823 {
4824   for (Output_data_list::const_iterator p = pdl->begin();
4825        p != pdl->end();
4826        ++p)
4827     (*p)->print_to_mapfile(mapfile);
4828 }
4829
4830 // Output_file methods.
4831
4832 Output_file::Output_file(const char* name)
4833   : name_(name),
4834     o_(-1),
4835     file_size_(0),
4836     base_(NULL),
4837     map_is_anonymous_(false),
4838     map_is_allocated_(false),
4839     is_temporary_(false)
4840 {
4841 }
4842
4843 // Try to open an existing file.  Returns false if the file doesn't
4844 // exist, has a size of 0 or can't be mmapped.  If BASE_NAME is not
4845 // NULL, open that file as the base for incremental linking, and
4846 // copy its contents to the new output file.  This routine can
4847 // be called for incremental updates, in which case WRITABLE should
4848 // be true, or by the incremental-dump utility, in which case
4849 // WRITABLE should be false.
4850
4851 bool
4852 Output_file::open_base_file(const char* base_name, bool writable)
4853 {
4854   // The name "-" means "stdout".
4855   if (strcmp(this->name_, "-") == 0)
4856     return false;
4857
4858   bool use_base_file = base_name != NULL;
4859   if (!use_base_file)
4860     base_name = this->name_;
4861   else if (strcmp(base_name, this->name_) == 0)
4862     gold_fatal(_("%s: incremental base and output file name are the same"),
4863                base_name);
4864
4865   // Don't bother opening files with a size of zero.
4866   struct stat s;
4867   if (::stat(base_name, &s) != 0)
4868     {
4869       gold_info(_("%s: stat: %s"), base_name, strerror(errno));
4870       return false;
4871     }
4872   if (s.st_size == 0)
4873     {
4874       gold_info(_("%s: incremental base file is empty"), base_name);
4875       return false;
4876     }
4877
4878   // If we're using a base file, we want to open it read-only.
4879   if (use_base_file)
4880     writable = false;
4881
4882   int oflags = writable ? O_RDWR : O_RDONLY;
4883   int o = open_descriptor(-1, base_name, oflags, 0);
4884   if (o < 0)
4885     {
4886       gold_info(_("%s: open: %s"), base_name, strerror(errno));
4887       return false;
4888     }
4889
4890   // If the base file and the output file are different, open a
4891   // new output file and read the contents from the base file into
4892   // the newly-mapped region.
4893   if (use_base_file)
4894     {
4895       this->open(s.st_size);
4896       ssize_t len = ::read(o, this->base_, s.st_size);
4897       if (len < 0)
4898         {
4899           gold_info(_("%s: read failed: %s"), base_name, strerror(errno));
4900           return false;
4901         }
4902       if (len < s.st_size)
4903         {
4904           gold_info(_("%s: file too short"), base_name);
4905           return false;
4906         }
4907       ::close(o);
4908       return true;
4909     }
4910
4911   this->o_ = o;
4912   this->file_size_ = s.st_size;
4913
4914   if (!this->map_no_anonymous(writable))
4915     {
4916       release_descriptor(o, true);
4917       this->o_ = -1;
4918       this->file_size_ = 0;
4919       return false;
4920     }
4921
4922   return true;
4923 }
4924
4925 // Open the output file.
4926
4927 void
4928 Output_file::open(off_t file_size)
4929 {
4930   this->file_size_ = file_size;
4931
4932   // Unlink the file first; otherwise the open() may fail if the file
4933   // is busy (e.g. it's an executable that's currently being executed).
4934   //
4935   // However, the linker may be part of a system where a zero-length
4936   // file is created for it to write to, with tight permissions (gcc
4937   // 2.95 did something like this).  Unlinking the file would work
4938   // around those permission controls, so we only unlink if the file
4939   // has a non-zero size.  We also unlink only regular files to avoid
4940   // trouble with directories/etc.
4941   //
4942   // If we fail, continue; this command is merely a best-effort attempt
4943   // to improve the odds for open().
4944
4945   // We let the name "-" mean "stdout"
4946   if (!this->is_temporary_)
4947     {
4948       if (strcmp(this->name_, "-") == 0)
4949         this->o_ = STDOUT_FILENO;
4950       else
4951         {
4952           struct stat s;
4953           if (::stat(this->name_, &s) == 0
4954               && (S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
4955             {
4956               if (s.st_size != 0)
4957                 ::unlink(this->name_);
4958               else if (!parameters->options().relocatable())
4959                 {
4960                   // If we don't unlink the existing file, add execute
4961                   // permission where read permissions already exist
4962                   // and where the umask permits.
4963                   int mask = ::umask(0);
4964                   ::umask(mask);
4965                   s.st_mode |= (s.st_mode & 0444) >> 2;
4966                   ::chmod(this->name_, s.st_mode & ~mask);
4967                 }
4968             }
4969
4970           int mode = parameters->options().relocatable() ? 0666 : 0777;
4971           int o = open_descriptor(-1, this->name_, O_RDWR | O_CREAT | O_TRUNC,
4972                                   mode);
4973           if (o < 0)
4974             gold_fatal(_("%s: open: %s"), this->name_, strerror(errno));
4975           this->o_ = o;
4976         }
4977     }
4978
4979   this->map();
4980 }
4981
4982 // Resize the output file.
4983
4984 void
4985 Output_file::resize(off_t file_size)
4986 {
4987   // If the mmap is mapping an anonymous memory buffer, this is easy:
4988   // just mremap to the new size.  If it's mapping to a file, we want
4989   // to unmap to flush to the file, then remap after growing the file.
4990   if (this->map_is_anonymous_)
4991     {
4992       void* base;
4993       if (!this->map_is_allocated_)
4994         {
4995           base = ::mremap(this->base_, this->file_size_, file_size,
4996                           MREMAP_MAYMOVE);
4997           if (base == MAP_FAILED)
4998             gold_fatal(_("%s: mremap: %s"), this->name_, strerror(errno));
4999         }
5000       else
5001         {
5002           base = realloc(this->base_, file_size);
5003           if (base == NULL)
5004             gold_nomem();
5005           if (file_size > this->file_size_)
5006             memset(static_cast<char*>(base) + this->file_size_, 0,
5007                    file_size - this->file_size_);
5008         }
5009       this->base_ = static_cast<unsigned char*>(base);
5010       this->file_size_ = file_size;
5011     }
5012   else
5013     {
5014       this->unmap();
5015       this->file_size_ = file_size;
5016       if (!this->map_no_anonymous(true))
5017         gold_fatal(_("%s: mmap: %s"), this->name_, strerror(errno));
5018     }
5019 }
5020
5021 // Map an anonymous block of memory which will later be written to the
5022 // file.  Return whether the map succeeded.
5023
5024 bool
5025 Output_file::map_anonymous()
5026 {
5027   void* base = ::mmap(NULL, this->file_size_, PROT_READ | PROT_WRITE,
5028                       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
5029   if (base == MAP_FAILED)
5030     {
5031       base = malloc(this->file_size_);
5032       if (base == NULL)
5033         return false;
5034       memset(base, 0, this->file_size_);
5035       this->map_is_allocated_ = true;
5036     }
5037   this->base_ = static_cast<unsigned char*>(base);
5038   this->map_is_anonymous_ = true;
5039   return true;
5040 }
5041
5042 // Map the file into memory.  Return whether the mapping succeeded.
5043 // If WRITABLE is true, map with write access.
5044
5045 bool
5046 Output_file::map_no_anonymous(bool writable)
5047 {
5048   const int o = this->o_;
5049
5050   // If the output file is not a regular file, don't try to mmap it;
5051   // instead, we'll mmap a block of memory (an anonymous buffer), and
5052   // then later write the buffer to the file.
5053   void* base;
5054   struct stat statbuf;
5055   if (o == STDOUT_FILENO || o == STDERR_FILENO
5056       || ::fstat(o, &statbuf) != 0
5057       || !S_ISREG(statbuf.st_mode)
5058       || this->is_temporary_)
5059     return false;
5060
5061   // Ensure that we have disk space available for the file.  If we
5062   // don't do this, it is possible that we will call munmap, close,
5063   // and exit with dirty buffers still in the cache with no assigned
5064   // disk blocks.  If the disk is out of space at that point, the
5065   // output file will wind up incomplete, but we will have already
5066   // exited.  The alternative to fallocate would be to use fdatasync,
5067   // but that would be a more significant performance hit.
5068   if (writable && ::posix_fallocate(o, 0, this->file_size_) < 0)
5069     gold_fatal(_("%s: %s"), this->name_, strerror(errno));
5070
5071   // Map the file into memory.
5072   int prot = PROT_READ;
5073   if (writable)
5074     prot |= PROT_WRITE;
5075   base = ::mmap(NULL, this->file_size_, prot, MAP_SHARED, o, 0);
5076
5077   // The mmap call might fail because of file system issues: the file
5078   // system might not support mmap at all, or it might not support
5079   // mmap with PROT_WRITE.
5080   if (base == MAP_FAILED)
5081     return false;
5082
5083   this->map_is_anonymous_ = false;
5084   this->base_ = static_cast<unsigned char*>(base);
5085   return true;
5086 }
5087
5088 // Map the file into memory.
5089
5090 void
5091 Output_file::map()
5092 {
5093   if (this->map_no_anonymous(true))
5094     return;
5095
5096   // The mmap call might fail because of file system issues: the file
5097   // system might not support mmap at all, or it might not support
5098   // mmap with PROT_WRITE.  I'm not sure which errno values we will
5099   // see in all cases, so if the mmap fails for any reason and we
5100   // don't care about file contents, try for an anonymous map.
5101   if (this->map_anonymous())
5102     return;
5103
5104   gold_fatal(_("%s: mmap: failed to allocate %lu bytes for output file: %s"),
5105              this->name_, static_cast<unsigned long>(this->file_size_),
5106              strerror(errno));
5107 }
5108
5109 // Unmap the file from memory.
5110
5111 void
5112 Output_file::unmap()
5113 {
5114   if (this->map_is_anonymous_)
5115     {
5116       // We've already written out the data, so there is no reason to
5117       // waste time unmapping or freeing the memory.
5118     }
5119   else
5120     {
5121       if (::munmap(this->base_, this->file_size_) < 0)
5122         gold_error(_("%s: munmap: %s"), this->name_, strerror(errno));
5123     }
5124   this->base_ = NULL;
5125 }
5126
5127 // Close the output file.
5128
5129 void
5130 Output_file::close()
5131 {
5132   // If the map isn't file-backed, we need to write it now.
5133   if (this->map_is_anonymous_ && !this->is_temporary_)
5134     {
5135       size_t bytes_to_write = this->file_size_;
5136       size_t offset = 0;
5137       while (bytes_to_write > 0)
5138         {
5139           ssize_t bytes_written = ::write(this->o_, this->base_ + offset,
5140                                           bytes_to_write);
5141           if (bytes_written == 0)
5142             gold_error(_("%s: write: unexpected 0 return-value"), this->name_);
5143           else if (bytes_written < 0)
5144             gold_error(_("%s: write: %s"), this->name_, strerror(errno));
5145           else
5146             {
5147               bytes_to_write -= bytes_written;
5148               offset += bytes_written;
5149             }
5150         }
5151     }
5152   this->unmap();
5153
5154   // We don't close stdout or stderr
5155   if (this->o_ != STDOUT_FILENO
5156       && this->o_ != STDERR_FILENO
5157       && !this->is_temporary_)
5158     if (::close(this->o_) < 0)
5159       gold_error(_("%s: close: %s"), this->name_, strerror(errno));
5160   this->o_ = -1;
5161 }
5162
5163 // Instantiate the templates we need.  We could use the configure
5164 // script to restrict this to only the ones for implemented targets.
5165
5166 #ifdef HAVE_TARGET_32_LITTLE
5167 template
5168 off_t
5169 Output_section::add_input_section<32, false>(
5170     Layout* layout,
5171     Sized_relobj_file<32, false>* object,
5172     unsigned int shndx,
5173     const char* secname,
5174     const elfcpp::Shdr<32, false>& shdr,
5175     unsigned int reloc_shndx,
5176     bool have_sections_script);
5177 #endif
5178
5179 #ifdef HAVE_TARGET_32_BIG
5180 template
5181 off_t
5182 Output_section::add_input_section<32, true>(
5183     Layout* layout,
5184     Sized_relobj_file<32, true>* object,
5185     unsigned int shndx,
5186     const char* secname,
5187     const elfcpp::Shdr<32, true>& shdr,
5188     unsigned int reloc_shndx,
5189     bool have_sections_script);
5190 #endif
5191
5192 #ifdef HAVE_TARGET_64_LITTLE
5193 template
5194 off_t
5195 Output_section::add_input_section<64, false>(
5196     Layout* layout,
5197     Sized_relobj_file<64, false>* object,
5198     unsigned int shndx,
5199     const char* secname,
5200     const elfcpp::Shdr<64, false>& shdr,
5201     unsigned int reloc_shndx,
5202     bool have_sections_script);
5203 #endif
5204
5205 #ifdef HAVE_TARGET_64_BIG
5206 template
5207 off_t
5208 Output_section::add_input_section<64, true>(
5209     Layout* layout,
5210     Sized_relobj_file<64, true>* object,
5211     unsigned int shndx,
5212     const char* secname,
5213     const elfcpp::Shdr<64, true>& shdr,
5214     unsigned int reloc_shndx,
5215     bool have_sections_script);
5216 #endif
5217
5218 #ifdef HAVE_TARGET_32_LITTLE
5219 template
5220 class Output_reloc<elfcpp::SHT_REL, false, 32, false>;
5221 #endif
5222
5223 #ifdef HAVE_TARGET_32_BIG
5224 template
5225 class Output_reloc<elfcpp::SHT_REL, false, 32, true>;
5226 #endif
5227
5228 #ifdef HAVE_TARGET_64_LITTLE
5229 template
5230 class Output_reloc<elfcpp::SHT_REL, false, 64, false>;
5231 #endif
5232
5233 #ifdef HAVE_TARGET_64_BIG
5234 template
5235 class Output_reloc<elfcpp::SHT_REL, false, 64, true>;
5236 #endif
5237
5238 #ifdef HAVE_TARGET_32_LITTLE
5239 template
5240 class Output_reloc<elfcpp::SHT_REL, true, 32, false>;
5241 #endif
5242
5243 #ifdef HAVE_TARGET_32_BIG
5244 template
5245 class Output_reloc<elfcpp::SHT_REL, true, 32, true>;
5246 #endif
5247
5248 #ifdef HAVE_TARGET_64_LITTLE
5249 template
5250 class Output_reloc<elfcpp::SHT_REL, true, 64, false>;
5251 #endif
5252
5253 #ifdef HAVE_TARGET_64_BIG
5254 template
5255 class Output_reloc<elfcpp::SHT_REL, true, 64, true>;
5256 #endif
5257
5258 #ifdef HAVE_TARGET_32_LITTLE
5259 template
5260 class Output_reloc<elfcpp::SHT_RELA, false, 32, false>;
5261 #endif
5262
5263 #ifdef HAVE_TARGET_32_BIG
5264 template
5265 class Output_reloc<elfcpp::SHT_RELA, false, 32, true>;
5266 #endif
5267
5268 #ifdef HAVE_TARGET_64_LITTLE
5269 template
5270 class Output_reloc<elfcpp::SHT_RELA, false, 64, false>;
5271 #endif
5272
5273 #ifdef HAVE_TARGET_64_BIG
5274 template
5275 class Output_reloc<elfcpp::SHT_RELA, false, 64, true>;
5276 #endif
5277
5278 #ifdef HAVE_TARGET_32_LITTLE
5279 template
5280 class Output_reloc<elfcpp::SHT_RELA, true, 32, false>;
5281 #endif
5282
5283 #ifdef HAVE_TARGET_32_BIG
5284 template
5285 class Output_reloc<elfcpp::SHT_RELA, true, 32, true>;
5286 #endif
5287
5288 #ifdef HAVE_TARGET_64_LITTLE
5289 template
5290 class Output_reloc<elfcpp::SHT_RELA, true, 64, false>;
5291 #endif
5292
5293 #ifdef HAVE_TARGET_64_BIG
5294 template
5295 class Output_reloc<elfcpp::SHT_RELA, true, 64, true>;
5296 #endif
5297
5298 #ifdef HAVE_TARGET_32_LITTLE
5299 template
5300 class Output_data_reloc<elfcpp::SHT_REL, false, 32, false>;
5301 #endif
5302
5303 #ifdef HAVE_TARGET_32_BIG
5304 template
5305 class Output_data_reloc<elfcpp::SHT_REL, false, 32, true>;
5306 #endif
5307
5308 #ifdef HAVE_TARGET_64_LITTLE
5309 template
5310 class Output_data_reloc<elfcpp::SHT_REL, false, 64, false>;
5311 #endif
5312
5313 #ifdef HAVE_TARGET_64_BIG
5314 template
5315 class Output_data_reloc<elfcpp::SHT_REL, false, 64, true>;
5316 #endif
5317
5318 #ifdef HAVE_TARGET_32_LITTLE
5319 template
5320 class Output_data_reloc<elfcpp::SHT_REL, true, 32, false>;
5321 #endif
5322
5323 #ifdef HAVE_TARGET_32_BIG
5324 template
5325 class Output_data_reloc<elfcpp::SHT_REL, true, 32, true>;
5326 #endif
5327
5328 #ifdef HAVE_TARGET_64_LITTLE
5329 template
5330 class Output_data_reloc<elfcpp::SHT_REL, true, 64, false>;
5331 #endif
5332
5333 #ifdef HAVE_TARGET_64_BIG
5334 template
5335 class Output_data_reloc<elfcpp::SHT_REL, true, 64, true>;
5336 #endif
5337
5338 #ifdef HAVE_TARGET_32_LITTLE
5339 template
5340 class Output_data_reloc<elfcpp::SHT_RELA, false, 32, false>;
5341 #endif
5342
5343 #ifdef HAVE_TARGET_32_BIG
5344 template
5345 class Output_data_reloc<elfcpp::SHT_RELA, false, 32, true>;
5346 #endif
5347
5348 #ifdef HAVE_TARGET_64_LITTLE
5349 template
5350 class Output_data_reloc<elfcpp::SHT_RELA, false, 64, false>;
5351 #endif
5352
5353 #ifdef HAVE_TARGET_64_BIG
5354 template
5355 class Output_data_reloc<elfcpp::SHT_RELA, false, 64, true>;
5356 #endif
5357
5358 #ifdef HAVE_TARGET_32_LITTLE
5359 template
5360 class Output_data_reloc<elfcpp::SHT_RELA, true, 32, false>;
5361 #endif
5362
5363 #ifdef HAVE_TARGET_32_BIG
5364 template
5365 class Output_data_reloc<elfcpp::SHT_RELA, true, 32, true>;
5366 #endif
5367
5368 #ifdef HAVE_TARGET_64_LITTLE
5369 template
5370 class Output_data_reloc<elfcpp::SHT_RELA, true, 64, false>;
5371 #endif
5372
5373 #ifdef HAVE_TARGET_64_BIG
5374 template
5375 class Output_data_reloc<elfcpp::SHT_RELA, true, 64, true>;
5376 #endif
5377
5378 #ifdef HAVE_TARGET_32_LITTLE
5379 template
5380 class Output_relocatable_relocs<elfcpp::SHT_REL, 32, false>;
5381 #endif
5382
5383 #ifdef HAVE_TARGET_32_BIG
5384 template
5385 class Output_relocatable_relocs<elfcpp::SHT_REL, 32, true>;
5386 #endif
5387
5388 #ifdef HAVE_TARGET_64_LITTLE
5389 template
5390 class Output_relocatable_relocs<elfcpp::SHT_REL, 64, false>;
5391 #endif
5392
5393 #ifdef HAVE_TARGET_64_BIG
5394 template
5395 class Output_relocatable_relocs<elfcpp::SHT_REL, 64, true>;
5396 #endif
5397
5398 #ifdef HAVE_TARGET_32_LITTLE
5399 template
5400 class Output_relocatable_relocs<elfcpp::SHT_RELA, 32, false>;
5401 #endif
5402
5403 #ifdef HAVE_TARGET_32_BIG
5404 template
5405 class Output_relocatable_relocs<elfcpp::SHT_RELA, 32, true>;
5406 #endif
5407
5408 #ifdef HAVE_TARGET_64_LITTLE
5409 template
5410 class Output_relocatable_relocs<elfcpp::SHT_RELA, 64, false>;
5411 #endif
5412
5413 #ifdef HAVE_TARGET_64_BIG
5414 template
5415 class Output_relocatable_relocs<elfcpp::SHT_RELA, 64, true>;
5416 #endif
5417
5418 #ifdef HAVE_TARGET_32_LITTLE
5419 template
5420 class Output_data_group<32, false>;
5421 #endif
5422
5423 #ifdef HAVE_TARGET_32_BIG
5424 template
5425 class Output_data_group<32, true>;
5426 #endif
5427
5428 #ifdef HAVE_TARGET_64_LITTLE
5429 template
5430 class Output_data_group<64, false>;
5431 #endif
5432
5433 #ifdef HAVE_TARGET_64_BIG
5434 template
5435 class Output_data_group<64, true>;
5436 #endif
5437
5438 #ifdef HAVE_TARGET_32_LITTLE
5439 template
5440 class Output_data_got<32, false>;
5441 #endif
5442
5443 #ifdef HAVE_TARGET_32_BIG
5444 template
5445 class Output_data_got<32, true>;
5446 #endif
5447
5448 #ifdef HAVE_TARGET_64_LITTLE
5449 template
5450 class Output_data_got<64, false>;
5451 #endif
5452
5453 #ifdef HAVE_TARGET_64_BIG
5454 template
5455 class Output_data_got<64, true>;
5456 #endif
5457
5458 } // End namespace gold.