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