* layout.cc (Layout::Layout): Initialize sections_are_attached_.
[external/binutils.git] / gold / output.cc
1 // output.cc -- manage the output file for gold
2
3 // Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <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"   // for unlink_if_ordinary()
34
35 #include "parameters.h"
36 #include "object.h"
37 #include "symtab.h"
38 #include "reloc.h"
39 #include "merge.h"
40 #include "output.h"
41
42 // Some BSD systems still use MAP_ANON instead of MAP_ANONYMOUS
43 #ifndef MAP_ANONYMOUS
44 # define MAP_ANONYMOUS  MAP_ANON
45 #endif
46
47 namespace gold
48 {
49
50 // Output_data variables.
51
52 bool Output_data::allocated_sizes_are_fixed;
53
54 // Output_data methods.
55
56 Output_data::~Output_data()
57 {
58 }
59
60 // Return the default alignment for the target size.
61
62 uint64_t
63 Output_data::default_alignment()
64 {
65   return Output_data::default_alignment_for_size(
66       parameters->target().get_size());
67 }
68
69 // Return the default alignment for a size--32 or 64.
70
71 uint64_t
72 Output_data::default_alignment_for_size(int size)
73 {
74   if (size == 32)
75     return 4;
76   else if (size == 64)
77     return 8;
78   else
79     gold_unreachable();
80 }
81
82 // Output_section_header methods.  This currently assumes that the
83 // segment and section lists are complete at construction time.
84
85 Output_section_headers::Output_section_headers(
86     const Layout* layout,
87     const Layout::Segment_list* segment_list,
88     const Layout::Section_list* section_list,
89     const Layout::Section_list* unattached_section_list,
90     const Stringpool* secnamepool)
91   : layout_(layout),
92     segment_list_(segment_list),
93     section_list_(section_list),
94     unattached_section_list_(unattached_section_list),
95     secnamepool_(secnamepool)
96 {
97   // Count all the sections.  Start with 1 for the null section.
98   off_t count = 1;
99   if (!parameters->options().relocatable())
100     {
101       for (Layout::Segment_list::const_iterator p = segment_list->begin();
102            p != segment_list->end();
103            ++p)
104         if ((*p)->type() == elfcpp::PT_LOAD)
105           count += (*p)->output_section_count();
106     }
107   else
108     {
109       for (Layout::Section_list::const_iterator p = section_list->begin();
110            p != section_list->end();
111            ++p)
112         if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
113           ++count;
114     }
115   count += unattached_section_list->size();
116
117   const int size = parameters->target().get_size();
118   int shdr_size;
119   if (size == 32)
120     shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
121   else if (size == 64)
122     shdr_size = elfcpp::Elf_sizes<64>::shdr_size;
123   else
124     gold_unreachable();
125
126   this->set_data_size(count * shdr_size);
127 }
128
129 // Write out the section headers.
130
131 void
132 Output_section_headers::do_write(Output_file* of)
133 {
134   switch (parameters->size_and_endianness())
135     {
136 #ifdef HAVE_TARGET_32_LITTLE
137     case Parameters::TARGET_32_LITTLE:
138       this->do_sized_write<32, false>(of);
139       break;
140 #endif
141 #ifdef HAVE_TARGET_32_BIG
142     case Parameters::TARGET_32_BIG:
143       this->do_sized_write<32, true>(of);
144       break;
145 #endif
146 #ifdef HAVE_TARGET_64_LITTLE
147     case Parameters::TARGET_64_LITTLE:
148       this->do_sized_write<64, false>(of);
149       break;
150 #endif
151 #ifdef HAVE_TARGET_64_BIG
152     case Parameters::TARGET_64_BIG:
153       this->do_sized_write<64, true>(of);
154       break;
155 #endif
156     default:
157       gold_unreachable();
158     }
159 }
160
161 template<int size, bool big_endian>
162 void
163 Output_section_headers::do_sized_write(Output_file* of)
164 {
165   off_t all_shdrs_size = this->data_size();
166   unsigned char* view = of->get_output_view(this->offset(), all_shdrs_size);
167
168   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
169   unsigned char* v = view;
170
171   {
172     typename elfcpp::Shdr_write<size, big_endian> oshdr(v);
173     oshdr.put_sh_name(0);
174     oshdr.put_sh_type(elfcpp::SHT_NULL);
175     oshdr.put_sh_flags(0);
176     oshdr.put_sh_addr(0);
177     oshdr.put_sh_offset(0);
178     oshdr.put_sh_size(0);
179     oshdr.put_sh_link(0);
180     oshdr.put_sh_info(0);
181     oshdr.put_sh_addralign(0);
182     oshdr.put_sh_entsize(0);
183   }
184
185   v += shdr_size;
186
187   unsigned int shndx = 1;
188   if (!parameters->options().relocatable())
189     {
190       for (Layout::Segment_list::const_iterator p =
191              this->segment_list_->begin();
192            p != this->segment_list_->end();
193            ++p)
194         v = (*p)->write_section_headers<size, big_endian>(this->layout_,
195                                                           this->secnamepool_,
196                                                           v,
197                                                           &shndx);
198     }
199   else
200     {
201       for (Layout::Section_list::const_iterator p =
202              this->section_list_->begin();
203            p != this->section_list_->end();
204            ++p)
205         {
206           // We do unallocated sections below, except that group
207           // sections have to come first.
208           if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
209               && (*p)->type() != elfcpp::SHT_GROUP)
210             continue;
211           gold_assert(shndx == (*p)->out_shndx());
212           elfcpp::Shdr_write<size, big_endian> oshdr(v);
213           (*p)->write_header(this->layout_, this->secnamepool_, &oshdr);
214           v += shdr_size;
215           ++shndx;
216         }
217     }
218
219   for (Layout::Section_list::const_iterator p =
220          this->unattached_section_list_->begin();
221        p != this->unattached_section_list_->end();
222        ++p)
223     {
224       // For a relocatable link, we did unallocated group sections
225       // above, since they have to come first.
226       if ((*p)->type() == elfcpp::SHT_GROUP
227           && parameters->options().relocatable())
228         continue;
229       gold_assert(shndx == (*p)->out_shndx());
230       elfcpp::Shdr_write<size, big_endian> oshdr(v);
231       (*p)->write_header(this->layout_, this->secnamepool_, &oshdr);
232       v += shdr_size;
233       ++shndx;
234     }
235
236   of->write_output_view(this->offset(), all_shdrs_size, view);
237 }
238
239 // Output_segment_header methods.
240
241 Output_segment_headers::Output_segment_headers(
242     const Layout::Segment_list& segment_list)
243   : segment_list_(segment_list)
244 {
245   const int size = parameters->target().get_size();
246   int phdr_size;
247   if (size == 32)
248     phdr_size = elfcpp::Elf_sizes<32>::phdr_size;
249   else if (size == 64)
250     phdr_size = elfcpp::Elf_sizes<64>::phdr_size;
251   else
252     gold_unreachable();
253
254   this->set_data_size(segment_list.size() * phdr_size);
255 }
256
257 void
258 Output_segment_headers::do_write(Output_file* of)
259 {
260   switch (parameters->size_and_endianness())
261     {
262 #ifdef HAVE_TARGET_32_LITTLE
263     case Parameters::TARGET_32_LITTLE:
264       this->do_sized_write<32, false>(of);
265       break;
266 #endif
267 #ifdef HAVE_TARGET_32_BIG
268     case Parameters::TARGET_32_BIG:
269       this->do_sized_write<32, true>(of);
270       break;
271 #endif
272 #ifdef HAVE_TARGET_64_LITTLE
273     case Parameters::TARGET_64_LITTLE:
274       this->do_sized_write<64, false>(of);
275       break;
276 #endif
277 #ifdef HAVE_TARGET_64_BIG
278     case Parameters::TARGET_64_BIG:
279       this->do_sized_write<64, true>(of);
280       break;
281 #endif
282     default:
283       gold_unreachable();
284     }
285 }
286
287 template<int size, bool big_endian>
288 void
289 Output_segment_headers::do_sized_write(Output_file* of)
290 {
291   const int phdr_size = elfcpp::Elf_sizes<size>::phdr_size;
292   off_t all_phdrs_size = this->segment_list_.size() * phdr_size;
293   gold_assert(all_phdrs_size == this->data_size());
294   unsigned char* view = of->get_output_view(this->offset(),
295                                             all_phdrs_size);
296   unsigned char* v = view;
297   for (Layout::Segment_list::const_iterator p = this->segment_list_.begin();
298        p != this->segment_list_.end();
299        ++p)
300     {
301       elfcpp::Phdr_write<size, big_endian> ophdr(v);
302       (*p)->write_header(&ophdr);
303       v += phdr_size;
304     }
305
306   gold_assert(v - view == all_phdrs_size);
307
308   of->write_output_view(this->offset(), all_phdrs_size, view);
309 }
310
311 // Output_file_header methods.
312
313 Output_file_header::Output_file_header(const Target* target,
314                                        const Symbol_table* symtab,
315                                        const Output_segment_headers* osh,
316                                        const char* entry)
317   : target_(target),
318     symtab_(symtab),
319     segment_header_(osh),
320     section_header_(NULL),
321     shstrtab_(NULL),
322     entry_(entry)
323 {
324   const int size = parameters->target().get_size();
325   int ehdr_size;
326   if (size == 32)
327     ehdr_size = elfcpp::Elf_sizes<32>::ehdr_size;
328   else if (size == 64)
329     ehdr_size = elfcpp::Elf_sizes<64>::ehdr_size;
330   else
331     gold_unreachable();
332
333   this->set_data_size(ehdr_size);
334 }
335
336 // Set the section table information for a file header.
337
338 void
339 Output_file_header::set_section_info(const Output_section_headers* shdrs,
340                                      const Output_section* shstrtab)
341 {
342   this->section_header_ = shdrs;
343   this->shstrtab_ = shstrtab;
344 }
345
346 // Write out the file header.
347
348 void
349 Output_file_header::do_write(Output_file* of)
350 {
351   gold_assert(this->offset() == 0);
352
353   switch (parameters->size_and_endianness())
354     {
355 #ifdef HAVE_TARGET_32_LITTLE
356     case Parameters::TARGET_32_LITTLE:
357       this->do_sized_write<32, false>(of);
358       break;
359 #endif
360 #ifdef HAVE_TARGET_32_BIG
361     case Parameters::TARGET_32_BIG:
362       this->do_sized_write<32, true>(of);
363       break;
364 #endif
365 #ifdef HAVE_TARGET_64_LITTLE
366     case Parameters::TARGET_64_LITTLE:
367       this->do_sized_write<64, false>(of);
368       break;
369 #endif
370 #ifdef HAVE_TARGET_64_BIG
371     case Parameters::TARGET_64_BIG:
372       this->do_sized_write<64, true>(of);
373       break;
374 #endif
375     default:
376       gold_unreachable();
377     }
378 }
379
380 // Write out the file header with appropriate size and endianess.
381
382 template<int size, bool big_endian>
383 void
384 Output_file_header::do_sized_write(Output_file* of)
385 {
386   gold_assert(this->offset() == 0);
387
388   int ehdr_size = elfcpp::Elf_sizes<size>::ehdr_size;
389   unsigned char* view = of->get_output_view(0, ehdr_size);
390   elfcpp::Ehdr_write<size, big_endian> oehdr(view);
391
392   unsigned char e_ident[elfcpp::EI_NIDENT];
393   memset(e_ident, 0, elfcpp::EI_NIDENT);
394   e_ident[elfcpp::EI_MAG0] = elfcpp::ELFMAG0;
395   e_ident[elfcpp::EI_MAG1] = elfcpp::ELFMAG1;
396   e_ident[elfcpp::EI_MAG2] = elfcpp::ELFMAG2;
397   e_ident[elfcpp::EI_MAG3] = elfcpp::ELFMAG3;
398   if (size == 32)
399     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS32;
400   else if (size == 64)
401     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS64;
402   else
403     gold_unreachable();
404   e_ident[elfcpp::EI_DATA] = (big_endian
405                               ? elfcpp::ELFDATA2MSB
406                               : elfcpp::ELFDATA2LSB);
407   e_ident[elfcpp::EI_VERSION] = elfcpp::EV_CURRENT;
408   // FIXME: Some targets may need to set EI_OSABI and EI_ABIVERSION.
409   oehdr.put_e_ident(e_ident);
410
411   elfcpp::ET e_type;
412   if (parameters->options().relocatable())
413     e_type = elfcpp::ET_REL;
414   else if (parameters->options().shared())
415     e_type = elfcpp::ET_DYN;
416   else
417     e_type = elfcpp::ET_EXEC;
418   oehdr.put_e_type(e_type);
419
420   oehdr.put_e_machine(this->target_->machine_code());
421   oehdr.put_e_version(elfcpp::EV_CURRENT);
422
423   oehdr.put_e_entry(this->entry<size>());
424
425   if (this->segment_header_ == NULL)
426     oehdr.put_e_phoff(0);
427   else
428     oehdr.put_e_phoff(this->segment_header_->offset());
429
430   oehdr.put_e_shoff(this->section_header_->offset());
431
432   // FIXME: The target needs to set the flags.
433   oehdr.put_e_flags(0);
434
435   oehdr.put_e_ehsize(elfcpp::Elf_sizes<size>::ehdr_size);
436
437   if (this->segment_header_ == NULL)
438     {
439       oehdr.put_e_phentsize(0);
440       oehdr.put_e_phnum(0);
441     }
442   else
443     {
444       oehdr.put_e_phentsize(elfcpp::Elf_sizes<size>::phdr_size);
445       oehdr.put_e_phnum(this->segment_header_->data_size()
446                         / elfcpp::Elf_sizes<size>::phdr_size);
447     }
448
449   oehdr.put_e_shentsize(elfcpp::Elf_sizes<size>::shdr_size);
450   oehdr.put_e_shnum(this->section_header_->data_size()
451                      / elfcpp::Elf_sizes<size>::shdr_size);
452   oehdr.put_e_shstrndx(this->shstrtab_->out_shndx());
453
454   of->write_output_view(0, ehdr_size, view);
455 }
456
457 // Return the value to use for the entry address.  THIS->ENTRY_ is the
458 // symbol specified on the command line, if any.
459
460 template<int size>
461 typename elfcpp::Elf_types<size>::Elf_Addr
462 Output_file_header::entry()
463 {
464   const bool should_issue_warning = (this->entry_ != NULL
465                                      && !parameters->options().relocatable()
466                                      && !parameters->options().shared());
467
468   // FIXME: Need to support target specific entry symbol.
469   const char* entry = this->entry_;
470   if (entry == NULL)
471     entry = "_start";
472
473   Symbol* sym = this->symtab_->lookup(entry);
474
475   typename Sized_symbol<size>::Value_type v;
476   if (sym != NULL)
477     {
478       Sized_symbol<size>* ssym;
479       ssym = this->symtab_->get_sized_symbol<size>(sym);
480       if (!ssym->is_defined() && should_issue_warning)
481         gold_warning("entry symbol '%s' exists but is not defined", entry);
482       v = ssym->value();
483     }
484   else
485     {
486       // We couldn't find the entry symbol.  See if we can parse it as
487       // a number.  This supports, e.g., -e 0x1000.
488       char* endptr;
489       v = strtoull(entry, &endptr, 0);
490       if (*endptr != '\0')
491         {
492           if (should_issue_warning)
493             gold_warning("cannot find entry symbol '%s'", entry);
494           v = 0;
495         }
496     }
497
498   return v;
499 }
500
501 // Output_data_const methods.
502
503 void
504 Output_data_const::do_write(Output_file* of)
505 {
506   of->write(this->offset(), this->data_.data(), this->data_.size());
507 }
508
509 // Output_data_const_buffer methods.
510
511 void
512 Output_data_const_buffer::do_write(Output_file* of)
513 {
514   of->write(this->offset(), this->p_, this->data_size());
515 }
516
517 // Output_section_data methods.
518
519 // Record the output section, and set the entry size and such.
520
521 void
522 Output_section_data::set_output_section(Output_section* os)
523 {
524   gold_assert(this->output_section_ == NULL);
525   this->output_section_ = os;
526   this->do_adjust_output_section(os);
527 }
528
529 // Return the section index of the output section.
530
531 unsigned int
532 Output_section_data::do_out_shndx() const
533 {
534   gold_assert(this->output_section_ != NULL);
535   return this->output_section_->out_shndx();
536 }
537
538 // Set the alignment, which means we may need to update the alignment
539 // of the output section.
540
541 void
542 Output_section_data::set_addralign(uint64_t addralign)
543 {
544   this->addralign_ = addralign;
545   if (this->output_section_ != NULL
546       && this->output_section_->addralign() < addralign)
547     this->output_section_->set_addralign(addralign);
548 }
549
550 // Output_data_strtab methods.
551
552 // Set the final data size.
553
554 void
555 Output_data_strtab::set_final_data_size()
556 {
557   this->strtab_->set_string_offsets();
558   this->set_data_size(this->strtab_->get_strtab_size());
559 }
560
561 // Write out a string table.
562
563 void
564 Output_data_strtab::do_write(Output_file* of)
565 {
566   this->strtab_->write(of, this->offset());
567 }
568
569 // Output_reloc methods.
570
571 // A reloc against a global symbol.
572
573 template<bool dynamic, int size, bool big_endian>
574 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
575     Symbol* gsym,
576     unsigned int type,
577     Output_data* od,
578     Address address,
579     bool is_relative)
580   : address_(address), local_sym_index_(GSYM_CODE), type_(type),
581     is_relative_(is_relative), is_section_symbol_(false), shndx_(INVALID_CODE)
582 {
583   // this->type_ is a bitfield; make sure TYPE fits.
584   gold_assert(this->type_ == type);
585   this->u1_.gsym = gsym;
586   this->u2_.od = od;
587   if (dynamic)
588     this->set_needs_dynsym_index();
589 }
590
591 template<bool dynamic, int size, bool big_endian>
592 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
593     Symbol* gsym,
594     unsigned int type,
595     Relobj* relobj,
596     unsigned int shndx,
597     Address address,
598     bool is_relative)
599   : address_(address), local_sym_index_(GSYM_CODE), type_(type),
600     is_relative_(is_relative), is_section_symbol_(false), shndx_(shndx)
601 {
602   gold_assert(shndx != INVALID_CODE);
603   // this->type_ is a bitfield; make sure TYPE fits.
604   gold_assert(this->type_ == type);
605   this->u1_.gsym = gsym;
606   this->u2_.relobj = relobj;
607   if (dynamic)
608     this->set_needs_dynsym_index();
609 }
610
611 // A reloc against a local symbol.
612
613 template<bool dynamic, int size, bool big_endian>
614 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
615     Sized_relobj<size, big_endian>* relobj,
616     unsigned int local_sym_index,
617     unsigned int type,
618     Output_data* od,
619     Address address,
620     bool is_relative,
621     bool is_section_symbol)
622   : address_(address), local_sym_index_(local_sym_index), type_(type),
623     is_relative_(is_relative), is_section_symbol_(is_section_symbol),
624     shndx_(INVALID_CODE)
625 {
626   gold_assert(local_sym_index != GSYM_CODE
627               && local_sym_index != INVALID_CODE);
628   // this->type_ is a bitfield; make sure TYPE fits.
629   gold_assert(this->type_ == type);
630   this->u1_.relobj = relobj;
631   this->u2_.od = od;
632   if (dynamic)
633     this->set_needs_dynsym_index();
634 }
635
636 template<bool dynamic, int size, bool big_endian>
637 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
638     Sized_relobj<size, big_endian>* relobj,
639     unsigned int local_sym_index,
640     unsigned int type,
641     unsigned int shndx,
642     Address address,
643     bool is_relative,
644     bool is_section_symbol)
645   : address_(address), local_sym_index_(local_sym_index), type_(type),
646     is_relative_(is_relative), is_section_symbol_(is_section_symbol),
647     shndx_(shndx)
648 {
649   gold_assert(local_sym_index != GSYM_CODE
650               && local_sym_index != INVALID_CODE);
651   gold_assert(shndx != INVALID_CODE);
652   // this->type_ is a bitfield; make sure TYPE fits.
653   gold_assert(this->type_ == type);
654   this->u1_.relobj = relobj;
655   this->u2_.relobj = relobj;
656   if (dynamic)
657     this->set_needs_dynsym_index();
658 }
659
660 // A reloc against the STT_SECTION symbol of an output section.
661
662 template<bool dynamic, int size, bool big_endian>
663 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
664     Output_section* os,
665     unsigned int type,
666     Output_data* od,
667     Address address)
668   : address_(address), local_sym_index_(SECTION_CODE), type_(type),
669     is_relative_(false), is_section_symbol_(true), shndx_(INVALID_CODE)
670 {
671   // this->type_ is a bitfield; make sure TYPE fits.
672   gold_assert(this->type_ == type);
673   this->u1_.os = os;
674   this->u2_.od = od;
675   if (dynamic)
676     this->set_needs_dynsym_index();
677   else
678     os->set_needs_symtab_index();
679 }
680
681 template<bool dynamic, int size, bool big_endian>
682 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::Output_reloc(
683     Output_section* os,
684     unsigned int type,
685     Relobj* relobj,
686     unsigned int shndx,
687     Address address)
688   : address_(address), local_sym_index_(SECTION_CODE), type_(type),
689     is_relative_(false), is_section_symbol_(true), shndx_(shndx)
690 {
691   gold_assert(shndx != INVALID_CODE);
692   // this->type_ is a bitfield; make sure TYPE fits.
693   gold_assert(this->type_ == type);
694   this->u1_.os = os;
695   this->u2_.relobj = relobj;
696   if (dynamic)
697     this->set_needs_dynsym_index();
698   else
699     os->set_needs_symtab_index();
700 }
701
702 // Record that we need a dynamic symbol index for this relocation.
703
704 template<bool dynamic, int size, bool big_endian>
705 void
706 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::
707 set_needs_dynsym_index()
708 {
709   if (this->is_relative_)
710     return;
711   switch (this->local_sym_index_)
712     {
713     case INVALID_CODE:
714       gold_unreachable();
715
716     case GSYM_CODE:
717       this->u1_.gsym->set_needs_dynsym_entry();
718       break;
719
720     case SECTION_CODE:
721       this->u1_.os->set_needs_dynsym_index();
722       break;
723
724     case 0:
725       break;
726
727     default:
728       {
729         const unsigned int lsi = this->local_sym_index_;
730         if (!this->is_section_symbol_)
731           this->u1_.relobj->set_needs_output_dynsym_entry(lsi);
732         else
733           {
734             section_offset_type dummy;
735             Output_section* os = this->u1_.relobj->output_section(lsi, &dummy);
736             gold_assert(os != NULL);
737             os->set_needs_dynsym_index();
738           }
739       }
740       break;
741     }
742 }
743
744 // Get the symbol index of a relocation.
745
746 template<bool dynamic, int size, bool big_endian>
747 unsigned int
748 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::get_symbol_index()
749   const
750 {
751   unsigned int index;
752   switch (this->local_sym_index_)
753     {
754     case INVALID_CODE:
755       gold_unreachable();
756
757     case GSYM_CODE:
758       if (this->u1_.gsym == NULL)
759         index = 0;
760       else if (dynamic)
761         index = this->u1_.gsym->dynsym_index();
762       else
763         index = this->u1_.gsym->symtab_index();
764       break;
765
766     case SECTION_CODE:
767       if (dynamic)
768         index = this->u1_.os->dynsym_index();
769       else
770         index = this->u1_.os->symtab_index();
771       break;
772
773     case 0:
774       // Relocations without symbols use a symbol index of 0.
775       index = 0;
776       break;
777
778     default:
779       {
780         const unsigned int lsi = this->local_sym_index_;
781         if (!this->is_section_symbol_)
782           {
783             if (dynamic)
784               index = this->u1_.relobj->dynsym_index(lsi);
785             else
786               index = this->u1_.relobj->symtab_index(lsi);
787           }
788         else
789           {
790             section_offset_type dummy;
791             Output_section* os = this->u1_.relobj->output_section(lsi, &dummy);
792             gold_assert(os != NULL);
793             if (dynamic)
794               index = os->dynsym_index();
795             else
796               index = os->symtab_index();
797           }
798       }
799       break;
800     }
801   gold_assert(index != -1U);
802   return index;
803 }
804
805 // For a local section symbol, get the address of the offset ADDEND
806 // within the input section.
807
808 template<bool dynamic, int size, bool big_endian>
809 section_offset_type
810 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::
811   local_section_offset(Addend addend) const
812 {
813   gold_assert(this->local_sym_index_ != GSYM_CODE
814               && this->local_sym_index_ != SECTION_CODE
815               && this->local_sym_index_ != INVALID_CODE
816               && this->is_section_symbol_);
817   const unsigned int lsi = this->local_sym_index_;
818   section_offset_type offset;
819   Output_section* os = this->u1_.relobj->output_section(lsi, &offset);
820   gold_assert(os != NULL);
821   if (offset != -1)
822     return offset + addend;
823   // This is a merge section.
824   offset = os->output_address(this->u1_.relobj, lsi, addend);
825   gold_assert(offset != -1);
826   return offset;
827 }
828
829 // Write out the offset and info fields of a Rel or Rela relocation
830 // entry.
831
832 template<bool dynamic, int size, bool big_endian>
833 template<typename Write_rel>
834 void
835 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::write_rel(
836     Write_rel* wr) const
837 {
838   Address address = this->address_;
839   if (this->shndx_ != INVALID_CODE)
840     {
841       section_offset_type off;
842       Output_section* os = this->u2_.relobj->output_section(this->shndx_,
843                                                             &off);
844       gold_assert(os != NULL);
845       if (off != -1)
846         address += os->address() + off;
847       else
848         {
849           address = os->output_address(this->u2_.relobj, this->shndx_,
850                                        address);
851           gold_assert(address != -1U);
852         }
853     }
854   else if (this->u2_.od != NULL)
855     address += this->u2_.od->address();
856   wr->put_r_offset(address);
857   unsigned int sym_index = this->is_relative_ ? 0 : this->get_symbol_index();
858   wr->put_r_info(elfcpp::elf_r_info<size>(sym_index, this->type_));
859 }
860
861 // Write out a Rel relocation.
862
863 template<bool dynamic, int size, bool big_endian>
864 void
865 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::write(
866     unsigned char* pov) const
867 {
868   elfcpp::Rel_write<size, big_endian> orel(pov);
869   this->write_rel(&orel);
870 }
871
872 // Get the value of the symbol referred to by a Rel relocation.
873
874 template<bool dynamic, int size, bool big_endian>
875 typename elfcpp::Elf_types<size>::Elf_Addr
876 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::symbol_value(
877     Addend addend) const
878 {
879   if (this->local_sym_index_ == GSYM_CODE)
880     {
881       const Sized_symbol<size>* sym;
882       sym = static_cast<const Sized_symbol<size>*>(this->u1_.gsym);
883       return sym->value() + addend;
884     }
885   gold_assert(this->local_sym_index_ != SECTION_CODE
886               && this->local_sym_index_ != INVALID_CODE
887               && !this->is_section_symbol_);
888   const unsigned int lsi = this->local_sym_index_;
889   const Symbol_value<size>* symval = this->u1_.relobj->local_symbol(lsi);
890   return symval->value(this->u1_.relobj, addend);
891 }
892
893 // Write out a Rela relocation.
894
895 template<bool dynamic, int size, bool big_endian>
896 void
897 Output_reloc<elfcpp::SHT_RELA, dynamic, size, big_endian>::write(
898     unsigned char* pov) const
899 {
900   elfcpp::Rela_write<size, big_endian> orel(pov);
901   this->rel_.write_rel(&orel);
902   Addend addend = this->addend_;
903   if (this->rel_.is_relative())
904     addend = this->rel_.symbol_value(addend);
905   else if (this->rel_.is_local_section_symbol())
906     addend = this->rel_.local_section_offset(addend);
907   orel.put_r_addend(addend);
908 }
909
910 // Output_data_reloc_base methods.
911
912 // Adjust the output section.
913
914 template<int sh_type, bool dynamic, int size, bool big_endian>
915 void
916 Output_data_reloc_base<sh_type, dynamic, size, big_endian>
917     ::do_adjust_output_section(Output_section* os)
918 {
919   if (sh_type == elfcpp::SHT_REL)
920     os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
921   else if (sh_type == elfcpp::SHT_RELA)
922     os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
923   else
924     gold_unreachable();
925   if (dynamic)
926     os->set_should_link_to_dynsym();
927   else
928     os->set_should_link_to_symtab();
929 }
930
931 // Write out relocation data.
932
933 template<int sh_type, bool dynamic, int size, bool big_endian>
934 void
935 Output_data_reloc_base<sh_type, dynamic, size, big_endian>::do_write(
936     Output_file* of)
937 {
938   const off_t off = this->offset();
939   const off_t oview_size = this->data_size();
940   unsigned char* const oview = of->get_output_view(off, oview_size);
941
942   unsigned char* pov = oview;
943   for (typename Relocs::const_iterator p = this->relocs_.begin();
944        p != this->relocs_.end();
945        ++p)
946     {
947       p->write(pov);
948       pov += reloc_size;
949     }
950
951   gold_assert(pov - oview == oview_size);
952
953   of->write_output_view(off, oview_size, oview);
954
955   // We no longer need the relocation entries.
956   this->relocs_.clear();
957 }
958
959 // Class Output_relocatable_relocs.
960
961 template<int sh_type, int size, bool big_endian>
962 void
963 Output_relocatable_relocs<sh_type, size, big_endian>::set_final_data_size()
964 {
965   this->set_data_size(this->rr_->output_reloc_count()
966                       * Reloc_types<sh_type, size, big_endian>::reloc_size);
967 }
968
969 // class Output_data_group.
970
971 template<int size, bool big_endian>
972 Output_data_group<size, big_endian>::Output_data_group(
973     Sized_relobj<size, big_endian>* relobj,
974     section_size_type entry_count,
975     const elfcpp::Elf_Word* contents)
976   : Output_section_data(entry_count * 4, 4),
977     relobj_(relobj)
978 {
979   this->flags_ = elfcpp::Swap<32, big_endian>::readval(contents);
980   for (section_size_type i = 1; i < entry_count; ++i)
981     {
982       unsigned int shndx = elfcpp::Swap<32, big_endian>::readval(contents + i);
983       this->input_sections_.push_back(shndx);
984     }
985 }
986
987 // Write out the section group, which means translating the section
988 // indexes to apply to the output file.
989
990 template<int size, bool big_endian>
991 void
992 Output_data_group<size, big_endian>::do_write(Output_file* of)
993 {
994   const off_t off = this->offset();
995   const section_size_type oview_size =
996     convert_to_section_size_type(this->data_size());
997   unsigned char* const oview = of->get_output_view(off, oview_size);
998
999   elfcpp::Elf_Word* contents = reinterpret_cast<elfcpp::Elf_Word*>(oview);
1000   elfcpp::Swap<32, big_endian>::writeval(contents, this->flags_);
1001   ++contents;
1002
1003   for (std::vector<unsigned int>::const_iterator p =
1004          this->input_sections_.begin();
1005        p != this->input_sections_.end();
1006        ++p, ++contents)
1007     {
1008       section_offset_type dummy;
1009       Output_section* os = this->relobj_->output_section(*p, &dummy);
1010
1011       unsigned int output_shndx;
1012       if (os != NULL)
1013         output_shndx = os->out_shndx();
1014       else
1015         {
1016           this->relobj_->error(_("section group retained but "
1017                                  "group element discarded"));
1018           output_shndx = 0;
1019         }
1020
1021       elfcpp::Swap<32, big_endian>::writeval(contents, output_shndx);
1022     }
1023
1024   size_t wrote = reinterpret_cast<unsigned char*>(contents) - oview;
1025   gold_assert(wrote == oview_size);
1026
1027   of->write_output_view(off, oview_size, oview);
1028
1029   // We no longer need this information.
1030   this->input_sections_.clear();
1031 }
1032
1033 // Output_data_got::Got_entry methods.
1034
1035 // Write out the entry.
1036
1037 template<int size, bool big_endian>
1038 void
1039 Output_data_got<size, big_endian>::Got_entry::write(unsigned char* pov) const
1040 {
1041   Valtype val = 0;
1042
1043   switch (this->local_sym_index_)
1044     {
1045     case GSYM_CODE:
1046       {
1047         // If the symbol is resolved locally, we need to write out the
1048         // link-time value, which will be relocated dynamically by a
1049         // RELATIVE relocation.
1050         Symbol* gsym = this->u_.gsym;
1051         Sized_symbol<size>* sgsym;
1052         // This cast is a bit ugly.  We don't want to put a
1053         // virtual method in Symbol, because we want Symbol to be
1054         // as small as possible.
1055         sgsym = static_cast<Sized_symbol<size>*>(gsym);
1056         val = sgsym->value();
1057       }
1058       break;
1059
1060     case CONSTANT_CODE:
1061       val = this->u_.constant;
1062       break;
1063
1064     default:
1065       {
1066         const unsigned int lsi = this->local_sym_index_;
1067         const Symbol_value<size>* symval = this->u_.object->local_symbol(lsi);
1068         val = symval->value(this->u_.object, 0);
1069       }
1070       break;
1071     }
1072
1073   elfcpp::Swap<size, big_endian>::writeval(pov, val);
1074 }
1075
1076 // Output_data_got methods.
1077
1078 // Add an entry for a global symbol to the GOT.  This returns true if
1079 // this is a new GOT entry, false if the symbol already had a GOT
1080 // entry.
1081
1082 template<int size, bool big_endian>
1083 bool
1084 Output_data_got<size, big_endian>::add_global(
1085     Symbol* gsym,
1086     unsigned int got_type)
1087 {
1088   if (gsym->has_got_offset(got_type))
1089     return false;
1090
1091   this->entries_.push_back(Got_entry(gsym));
1092   this->set_got_size();
1093   gsym->set_got_offset(got_type, this->last_got_offset());
1094   return true;
1095 }
1096
1097 // Add an entry for a global symbol to the GOT, and add a dynamic
1098 // relocation of type R_TYPE for the GOT entry.
1099 template<int size, bool big_endian>
1100 void
1101 Output_data_got<size, big_endian>::add_global_with_rel(
1102     Symbol* gsym,
1103     unsigned int got_type,
1104     Rel_dyn* rel_dyn,
1105     unsigned int r_type)
1106 {
1107   if (gsym->has_got_offset(got_type))
1108     return;
1109
1110   this->entries_.push_back(Got_entry());
1111   this->set_got_size();
1112   unsigned int got_offset = this->last_got_offset();
1113   gsym->set_got_offset(got_type, got_offset);
1114   rel_dyn->add_global(gsym, r_type, this, got_offset);
1115 }
1116
1117 template<int size, bool big_endian>
1118 void
1119 Output_data_got<size, big_endian>::add_global_with_rela(
1120     Symbol* gsym,
1121     unsigned int got_type,
1122     Rela_dyn* rela_dyn,
1123     unsigned int r_type)
1124 {
1125   if (gsym->has_got_offset(got_type))
1126     return;
1127
1128   this->entries_.push_back(Got_entry());
1129   this->set_got_size();
1130   unsigned int got_offset = this->last_got_offset();
1131   gsym->set_got_offset(got_type, got_offset);
1132   rela_dyn->add_global(gsym, r_type, this, got_offset, 0);
1133 }
1134
1135 // Add a pair of entries for a global symbol to the GOT, and add
1136 // dynamic relocations of type R_TYPE_1 and R_TYPE_2, respectively.
1137 // If R_TYPE_2 == 0, add the second entry with no relocation.
1138 template<int size, bool big_endian>
1139 void
1140 Output_data_got<size, big_endian>::add_global_pair_with_rel(
1141     Symbol* gsym,
1142     unsigned int got_type,
1143     Rel_dyn* rel_dyn,
1144     unsigned int r_type_1,
1145     unsigned int r_type_2)
1146 {
1147   if (gsym->has_got_offset(got_type))
1148     return;
1149
1150   this->entries_.push_back(Got_entry());
1151   unsigned int got_offset = this->last_got_offset();
1152   gsym->set_got_offset(got_type, got_offset);
1153   rel_dyn->add_global(gsym, r_type_1, this, got_offset);
1154
1155   this->entries_.push_back(Got_entry());
1156   if (r_type_2 != 0)
1157     {
1158       got_offset = this->last_got_offset();
1159       rel_dyn->add_global(gsym, r_type_2, this, got_offset);
1160     }
1161
1162   this->set_got_size();
1163 }
1164
1165 template<int size, bool big_endian>
1166 void
1167 Output_data_got<size, big_endian>::add_global_pair_with_rela(
1168     Symbol* gsym,
1169     unsigned int got_type,
1170     Rela_dyn* rela_dyn,
1171     unsigned int r_type_1,
1172     unsigned int r_type_2)
1173 {
1174   if (gsym->has_got_offset(got_type))
1175     return;
1176
1177   this->entries_.push_back(Got_entry());
1178   unsigned int got_offset = this->last_got_offset();
1179   gsym->set_got_offset(got_type, got_offset);
1180   rela_dyn->add_global(gsym, r_type_1, this, got_offset, 0);
1181
1182   this->entries_.push_back(Got_entry());
1183   if (r_type_2 != 0)
1184     {
1185       got_offset = this->last_got_offset();
1186       rela_dyn->add_global(gsym, r_type_2, this, got_offset, 0);
1187     }
1188
1189   this->set_got_size();
1190 }
1191
1192 // Add an entry for a local symbol to the GOT.  This returns true if
1193 // this is a new GOT entry, false if the symbol already has a GOT
1194 // entry.
1195
1196 template<int size, bool big_endian>
1197 bool
1198 Output_data_got<size, big_endian>::add_local(
1199     Sized_relobj<size, big_endian>* object,
1200     unsigned int symndx,
1201     unsigned int got_type)
1202 {
1203   if (object->local_has_got_offset(symndx, got_type))
1204     return false;
1205
1206   this->entries_.push_back(Got_entry(object, symndx));
1207   this->set_got_size();
1208   object->set_local_got_offset(symndx, got_type, this->last_got_offset());
1209   return true;
1210 }
1211
1212 // Add an entry for a local symbol to the GOT, and add a dynamic
1213 // relocation of type R_TYPE for the GOT entry.
1214 template<int size, bool big_endian>
1215 void
1216 Output_data_got<size, big_endian>::add_local_with_rel(
1217     Sized_relobj<size, big_endian>* object,
1218     unsigned int symndx,
1219     unsigned int got_type,
1220     Rel_dyn* rel_dyn,
1221     unsigned int r_type)
1222 {
1223   if (object->local_has_got_offset(symndx, got_type))
1224     return;
1225
1226   this->entries_.push_back(Got_entry());
1227   this->set_got_size();
1228   unsigned int got_offset = this->last_got_offset();
1229   object->set_local_got_offset(symndx, got_type, got_offset);
1230   rel_dyn->add_local(object, symndx, r_type, this, got_offset);
1231 }
1232
1233 template<int size, bool big_endian>
1234 void
1235 Output_data_got<size, big_endian>::add_local_with_rela(
1236     Sized_relobj<size, big_endian>* object,
1237     unsigned int symndx,
1238     unsigned int got_type,
1239     Rela_dyn* rela_dyn,
1240     unsigned int r_type)
1241 {
1242   if (object->local_has_got_offset(symndx, got_type))
1243     return;
1244
1245   this->entries_.push_back(Got_entry());
1246   this->set_got_size();
1247   unsigned int got_offset = this->last_got_offset();
1248   object->set_local_got_offset(symndx, got_type, got_offset);
1249   rela_dyn->add_local(object, symndx, r_type, this, got_offset, 0);
1250 }
1251
1252 // Add a pair of entries for a local symbol to the GOT, and add
1253 // dynamic relocations of type R_TYPE_1 and R_TYPE_2, respectively.
1254 // If R_TYPE_2 == 0, add the second entry with no relocation.
1255 template<int size, bool big_endian>
1256 void
1257 Output_data_got<size, big_endian>::add_local_pair_with_rel(
1258     Sized_relobj<size, big_endian>* object,
1259     unsigned int symndx,
1260     unsigned int shndx,
1261     unsigned int got_type,
1262     Rel_dyn* rel_dyn,
1263     unsigned int r_type_1,
1264     unsigned int r_type_2)
1265 {
1266   if (object->local_has_got_offset(symndx, got_type))
1267     return;
1268
1269   this->entries_.push_back(Got_entry());
1270   unsigned int got_offset = this->last_got_offset();
1271   object->set_local_got_offset(symndx, got_type, got_offset);
1272   section_offset_type off;
1273   Output_section* os = object->output_section(shndx, &off);
1274   rel_dyn->add_output_section(os, r_type_1, this, got_offset);
1275
1276   this->entries_.push_back(Got_entry(object, symndx));
1277   if (r_type_2 != 0)
1278     {
1279       got_offset = this->last_got_offset();
1280       rel_dyn->add_output_section(os, r_type_2, this, got_offset);
1281     }
1282
1283   this->set_got_size();
1284 }
1285
1286 template<int size, bool big_endian>
1287 void
1288 Output_data_got<size, big_endian>::add_local_pair_with_rela(
1289     Sized_relobj<size, big_endian>* object,
1290     unsigned int symndx,
1291     unsigned int shndx,
1292     unsigned int got_type,
1293     Rela_dyn* rela_dyn,
1294     unsigned int r_type_1,
1295     unsigned int r_type_2)
1296 {
1297   if (object->local_has_got_offset(symndx, got_type))
1298     return;
1299
1300   this->entries_.push_back(Got_entry());
1301   unsigned int got_offset = this->last_got_offset();
1302   object->set_local_got_offset(symndx, got_type, got_offset);
1303   section_offset_type off;
1304   Output_section* os = object->output_section(shndx, &off);
1305   rela_dyn->add_output_section(os, r_type_1, this, got_offset, 0);
1306
1307   this->entries_.push_back(Got_entry(object, symndx));
1308   if (r_type_2 != 0)
1309     {
1310       got_offset = this->last_got_offset();
1311       rela_dyn->add_output_section(os, r_type_2, this, got_offset, 0);
1312     }
1313
1314   this->set_got_size();
1315 }
1316
1317 // Write out the GOT.
1318
1319 template<int size, bool big_endian>
1320 void
1321 Output_data_got<size, big_endian>::do_write(Output_file* of)
1322 {
1323   const int add = size / 8;
1324
1325   const off_t off = this->offset();
1326   const off_t oview_size = this->data_size();
1327   unsigned char* const oview = of->get_output_view(off, oview_size);
1328
1329   unsigned char* pov = oview;
1330   for (typename Got_entries::const_iterator p = this->entries_.begin();
1331        p != this->entries_.end();
1332        ++p)
1333     {
1334       p->write(pov);
1335       pov += add;
1336     }
1337
1338   gold_assert(pov - oview == oview_size);
1339
1340   of->write_output_view(off, oview_size, oview);
1341
1342   // We no longer need the GOT entries.
1343   this->entries_.clear();
1344 }
1345
1346 // Output_data_dynamic::Dynamic_entry methods.
1347
1348 // Write out the entry.
1349
1350 template<int size, bool big_endian>
1351 void
1352 Output_data_dynamic::Dynamic_entry::write(
1353     unsigned char* pov,
1354     const Stringpool* pool) const
1355 {
1356   typename elfcpp::Elf_types<size>::Elf_WXword val;
1357   switch (this->offset_)
1358     {
1359     case DYNAMIC_NUMBER:
1360       val = this->u_.val;
1361       break;
1362
1363     case DYNAMIC_SECTION_SIZE:
1364       val = this->u_.od->data_size();
1365       break;
1366
1367     case DYNAMIC_SYMBOL:
1368       {
1369         const Sized_symbol<size>* s =
1370           static_cast<const Sized_symbol<size>*>(this->u_.sym);
1371         val = s->value();
1372       }
1373       break;
1374
1375     case DYNAMIC_STRING:
1376       val = pool->get_offset(this->u_.str);
1377       break;
1378
1379     default:
1380       val = this->u_.od->address() + this->offset_;
1381       break;
1382     }
1383
1384   elfcpp::Dyn_write<size, big_endian> dw(pov);
1385   dw.put_d_tag(this->tag_);
1386   dw.put_d_val(val);
1387 }
1388
1389 // Output_data_dynamic methods.
1390
1391 // Adjust the output section to set the entry size.
1392
1393 void
1394 Output_data_dynamic::do_adjust_output_section(Output_section* os)
1395 {
1396   if (parameters->target().get_size() == 32)
1397     os->set_entsize(elfcpp::Elf_sizes<32>::dyn_size);
1398   else if (parameters->target().get_size() == 64)
1399     os->set_entsize(elfcpp::Elf_sizes<64>::dyn_size);
1400   else
1401     gold_unreachable();
1402 }
1403
1404 // Set the final data size.
1405
1406 void
1407 Output_data_dynamic::set_final_data_size()
1408 {
1409   // Add the terminating entry.
1410   this->add_constant(elfcpp::DT_NULL, 0);
1411
1412   int dyn_size;
1413   if (parameters->target().get_size() == 32)
1414     dyn_size = elfcpp::Elf_sizes<32>::dyn_size;
1415   else if (parameters->target().get_size() == 64)
1416     dyn_size = elfcpp::Elf_sizes<64>::dyn_size;
1417   else
1418     gold_unreachable();
1419   this->set_data_size(this->entries_.size() * dyn_size);
1420 }
1421
1422 // Write out the dynamic entries.
1423
1424 void
1425 Output_data_dynamic::do_write(Output_file* of)
1426 {
1427   switch (parameters->size_and_endianness())
1428     {
1429 #ifdef HAVE_TARGET_32_LITTLE
1430     case Parameters::TARGET_32_LITTLE:
1431       this->sized_write<32, false>(of);
1432       break;
1433 #endif
1434 #ifdef HAVE_TARGET_32_BIG
1435     case Parameters::TARGET_32_BIG:
1436       this->sized_write<32, true>(of);
1437       break;
1438 #endif
1439 #ifdef HAVE_TARGET_64_LITTLE
1440     case Parameters::TARGET_64_LITTLE:
1441       this->sized_write<64, false>(of);
1442       break;
1443 #endif
1444 #ifdef HAVE_TARGET_64_BIG
1445     case Parameters::TARGET_64_BIG:
1446       this->sized_write<64, true>(of);
1447       break;
1448 #endif
1449     default:
1450       gold_unreachable();
1451     }
1452 }
1453
1454 template<int size, bool big_endian>
1455 void
1456 Output_data_dynamic::sized_write(Output_file* of)
1457 {
1458   const int dyn_size = elfcpp::Elf_sizes<size>::dyn_size;
1459
1460   const off_t offset = this->offset();
1461   const off_t oview_size = this->data_size();
1462   unsigned char* const oview = of->get_output_view(offset, oview_size);
1463
1464   unsigned char* pov = oview;
1465   for (typename Dynamic_entries::const_iterator p = this->entries_.begin();
1466        p != this->entries_.end();
1467        ++p)
1468     {
1469       p->write<size, big_endian>(pov, this->pool_);
1470       pov += dyn_size;
1471     }
1472
1473   gold_assert(pov - oview == oview_size);
1474
1475   of->write_output_view(offset, oview_size, oview);
1476
1477   // We no longer need the dynamic entries.
1478   this->entries_.clear();
1479 }
1480
1481 // Output_section::Input_section methods.
1482
1483 // Return the data size.  For an input section we store the size here.
1484 // For an Output_section_data, we have to ask it for the size.
1485
1486 off_t
1487 Output_section::Input_section::data_size() const
1488 {
1489   if (this->is_input_section())
1490     return this->u1_.data_size;
1491   else
1492     return this->u2_.posd->data_size();
1493 }
1494
1495 // Set the address and file offset.
1496
1497 void
1498 Output_section::Input_section::set_address_and_file_offset(
1499     uint64_t address,
1500     off_t file_offset,
1501     off_t section_file_offset)
1502 {
1503   if (this->is_input_section())
1504     this->u2_.object->set_section_offset(this->shndx_,
1505                                          file_offset - section_file_offset);
1506   else
1507     this->u2_.posd->set_address_and_file_offset(address, file_offset);
1508 }
1509
1510 // Reset the address and file offset.
1511
1512 void
1513 Output_section::Input_section::reset_address_and_file_offset()
1514 {
1515   if (!this->is_input_section())
1516     this->u2_.posd->reset_address_and_file_offset();
1517 }
1518
1519 // Finalize the data size.
1520
1521 void
1522 Output_section::Input_section::finalize_data_size()
1523 {
1524   if (!this->is_input_section())
1525     this->u2_.posd->finalize_data_size();
1526 }
1527
1528 // Try to turn an input offset into an output offset.  We want to
1529 // return the output offset relative to the start of this
1530 // Input_section in the output section.
1531
1532 inline bool
1533 Output_section::Input_section::output_offset(
1534     const Relobj* object,
1535     unsigned int shndx,
1536     section_offset_type offset,
1537     section_offset_type *poutput) const
1538 {
1539   if (!this->is_input_section())
1540     return this->u2_.posd->output_offset(object, shndx, offset, poutput);
1541   else
1542     {
1543       if (this->shndx_ != shndx || this->u2_.object != object)
1544         return false;
1545       *poutput = offset;
1546       return true;
1547     }
1548 }
1549
1550 // Return whether this is the merge section for the input section
1551 // SHNDX in OBJECT.
1552
1553 inline bool
1554 Output_section::Input_section::is_merge_section_for(const Relobj* object,
1555                                                     unsigned int shndx) const
1556 {
1557   if (this->is_input_section())
1558     return false;
1559   return this->u2_.posd->is_merge_section_for(object, shndx);
1560 }
1561
1562 // Write out the data.  We don't have to do anything for an input
1563 // section--they are handled via Object::relocate--but this is where
1564 // we write out the data for an Output_section_data.
1565
1566 void
1567 Output_section::Input_section::write(Output_file* of)
1568 {
1569   if (!this->is_input_section())
1570     this->u2_.posd->write(of);
1571 }
1572
1573 // Write the data to a buffer.  As for write(), we don't have to do
1574 // anything for an input section.
1575
1576 void
1577 Output_section::Input_section::write_to_buffer(unsigned char* buffer)
1578 {
1579   if (!this->is_input_section())
1580     this->u2_.posd->write_to_buffer(buffer);
1581 }
1582
1583 // Output_section methods.
1584
1585 // Construct an Output_section.  NAME will point into a Stringpool.
1586
1587 Output_section::Output_section(const char* name, elfcpp::Elf_Word type,
1588                                elfcpp::Elf_Xword flags)
1589   : name_(name),
1590     addralign_(0),
1591     entsize_(0),
1592     load_address_(0),
1593     link_section_(NULL),
1594     link_(0),
1595     info_section_(NULL),
1596     info_symndx_(NULL),
1597     info_(0),
1598     type_(type),
1599     flags_(flags),
1600     out_shndx_(-1U),
1601     symtab_index_(0),
1602     dynsym_index_(0),
1603     input_sections_(),
1604     first_input_offset_(0),
1605     fills_(),
1606     postprocessing_buffer_(NULL),
1607     needs_symtab_index_(false),
1608     needs_dynsym_index_(false),
1609     should_link_to_symtab_(false),
1610     should_link_to_dynsym_(false),
1611     after_input_sections_(false),
1612     requires_postprocessing_(false),
1613     found_in_sections_clause_(false),
1614     has_load_address_(false),
1615     info_uses_section_index_(false),
1616     may_sort_attached_input_sections_(false),
1617     must_sort_attached_input_sections_(false),
1618     attached_input_sections_are_sorted_(false),
1619     tls_offset_(0)
1620 {
1621   // An unallocated section has no address.  Forcing this means that
1622   // we don't need special treatment for symbols defined in debug
1623   // sections.
1624   if ((flags & elfcpp::SHF_ALLOC) == 0)
1625     this->set_address(0);
1626 }
1627
1628 Output_section::~Output_section()
1629 {
1630 }
1631
1632 // Set the entry size.
1633
1634 void
1635 Output_section::set_entsize(uint64_t v)
1636 {
1637   if (this->entsize_ == 0)
1638     this->entsize_ = v;
1639   else
1640     gold_assert(this->entsize_ == v);
1641 }
1642
1643 // Add the input section SHNDX, with header SHDR, named SECNAME, in
1644 // OBJECT, to the Output_section.  RELOC_SHNDX is the index of a
1645 // relocation section which applies to this section, or 0 if none, or
1646 // -1U if more than one.  Return the offset of the input section
1647 // within the output section.  Return -1 if the input section will
1648 // receive special handling.  In the normal case we don't always keep
1649 // track of input sections for an Output_section.  Instead, each
1650 // Object keeps track of the Output_section for each of its input
1651 // sections.  However, if HAVE_SECTIONS_SCRIPT is true, we do keep
1652 // track of input sections here; this is used when SECTIONS appears in
1653 // a linker script.
1654
1655 template<int size, bool big_endian>
1656 off_t
1657 Output_section::add_input_section(Sized_relobj<size, big_endian>* object,
1658                                   unsigned int shndx,
1659                                   const char* secname,
1660                                   const elfcpp::Shdr<size, big_endian>& shdr,
1661                                   unsigned int reloc_shndx,
1662                                   bool have_sections_script)
1663 {
1664   elfcpp::Elf_Xword addralign = shdr.get_sh_addralign();
1665   if ((addralign & (addralign - 1)) != 0)
1666     {
1667       object->error(_("invalid alignment %lu for section \"%s\""),
1668                     static_cast<unsigned long>(addralign), secname);
1669       addralign = 1;
1670     }
1671
1672   if (addralign > this->addralign_)
1673     this->addralign_ = addralign;
1674
1675   typename elfcpp::Elf_types<size>::Elf_WXword sh_flags = shdr.get_sh_flags();
1676   this->update_flags_for_input_section(sh_flags);
1677
1678   uint64_t entsize = shdr.get_sh_entsize();
1679
1680   // .debug_str is a mergeable string section, but is not always so
1681   // marked by compilers.  Mark manually here so we can optimize.
1682   if (strcmp(secname, ".debug_str") == 0)
1683     {
1684       sh_flags |= (elfcpp::SHF_MERGE | elfcpp::SHF_STRINGS);
1685       entsize = 1;
1686     }
1687
1688   // If this is a SHF_MERGE section, we pass all the input sections to
1689   // a Output_data_merge.  We don't try to handle relocations for such
1690   // a section.
1691   if ((sh_flags & elfcpp::SHF_MERGE) != 0
1692       && reloc_shndx == 0)
1693     {
1694       if (this->add_merge_input_section(object, shndx, sh_flags,
1695                                         entsize, addralign))
1696         {
1697           // Tell the relocation routines that they need to call the
1698           // output_offset method to determine the final address.
1699           return -1;
1700         }
1701     }
1702
1703   off_t offset_in_section = this->current_data_size_for_child();
1704   off_t aligned_offset_in_section = align_address(offset_in_section,
1705                                                   addralign);
1706
1707   if (aligned_offset_in_section > offset_in_section
1708       && !have_sections_script
1709       && (sh_flags & elfcpp::SHF_EXECINSTR) != 0
1710       && object->target()->has_code_fill())
1711     {
1712       // We need to add some fill data.  Using fill_list_ when
1713       // possible is an optimization, since we will often have fill
1714       // sections without input sections.
1715       off_t fill_len = aligned_offset_in_section - offset_in_section;
1716       if (this->input_sections_.empty())
1717         this->fills_.push_back(Fill(offset_in_section, fill_len));
1718       else
1719         {
1720           // FIXME: When relaxing, the size needs to adjust to
1721           // maintain a constant alignment.
1722           std::string fill_data(object->target()->code_fill(fill_len));
1723           Output_data_const* odc = new Output_data_const(fill_data, 1);
1724           this->input_sections_.push_back(Input_section(odc));
1725         }
1726     }
1727
1728   this->set_current_data_size_for_child(aligned_offset_in_section
1729                                         + shdr.get_sh_size());
1730
1731   // We need to keep track of this section if we are already keeping
1732   // track of sections, or if we are relaxing.  Also, if this is a
1733   // section which requires sorting, or which may require sorting in
1734   // the future, we keep track of the sections.  FIXME: Add test for
1735   // relaxing.
1736   if (have_sections_script
1737       || !this->input_sections_.empty()
1738       || this->may_sort_attached_input_sections()
1739       || this->must_sort_attached_input_sections())
1740     this->input_sections_.push_back(Input_section(object, shndx,
1741                                                   shdr.get_sh_size(),
1742                                                   addralign));
1743
1744   return aligned_offset_in_section;
1745 }
1746
1747 // Add arbitrary data to an output section.
1748
1749 void
1750 Output_section::add_output_section_data(Output_section_data* posd)
1751 {
1752   Input_section inp(posd);
1753   this->add_output_section_data(&inp);
1754
1755   if (posd->is_data_size_valid())
1756     {
1757       off_t offset_in_section = this->current_data_size_for_child();
1758       off_t aligned_offset_in_section = align_address(offset_in_section,
1759                                                       posd->addralign());
1760       this->set_current_data_size_for_child(aligned_offset_in_section
1761                                             + posd->data_size());
1762     }
1763 }
1764
1765 // Add arbitrary data to an output section by Input_section.
1766
1767 void
1768 Output_section::add_output_section_data(Input_section* inp)
1769 {
1770   if (this->input_sections_.empty())
1771     this->first_input_offset_ = this->current_data_size_for_child();
1772
1773   this->input_sections_.push_back(*inp);
1774
1775   uint64_t addralign = inp->addralign();
1776   if (addralign > this->addralign_)
1777     this->addralign_ = addralign;
1778
1779   inp->set_output_section(this);
1780 }
1781
1782 // Add a merge section to an output section.
1783
1784 void
1785 Output_section::add_output_merge_section(Output_section_data* posd,
1786                                          bool is_string, uint64_t entsize)
1787 {
1788   Input_section inp(posd, is_string, entsize);
1789   this->add_output_section_data(&inp);
1790 }
1791
1792 // Add an input section to a SHF_MERGE section.
1793
1794 bool
1795 Output_section::add_merge_input_section(Relobj* object, unsigned int shndx,
1796                                         uint64_t flags, uint64_t entsize,
1797                                         uint64_t addralign)
1798 {
1799   bool is_string = (flags & elfcpp::SHF_STRINGS) != 0;
1800
1801   // We only merge strings if the alignment is not more than the
1802   // character size.  This could be handled, but it's unusual.
1803   if (is_string && addralign > entsize)
1804     return false;
1805
1806   Input_section_list::iterator p;
1807   for (p = this->input_sections_.begin();
1808        p != this->input_sections_.end();
1809        ++p)
1810     if (p->is_merge_section(is_string, entsize, addralign))
1811       {
1812         p->add_input_section(object, shndx);
1813         return true;
1814       }
1815
1816   // We handle the actual constant merging in Output_merge_data or
1817   // Output_merge_string_data.
1818   Output_section_data* posd;
1819   if (!is_string)
1820     posd = new Output_merge_data(entsize, addralign);
1821   else
1822     {
1823       switch (entsize)
1824         {
1825         case 1:
1826           posd = new Output_merge_string<char>(addralign);
1827           break;
1828         case 2:
1829           posd = new Output_merge_string<uint16_t>(addralign);
1830           break;
1831         case 4:
1832           posd = new Output_merge_string<uint32_t>(addralign);
1833           break;
1834         default:
1835           return false;
1836         }
1837     }
1838
1839   this->add_output_merge_section(posd, is_string, entsize);
1840   posd->add_input_section(object, shndx);
1841
1842   return true;
1843 }
1844
1845 // Given an address OFFSET relative to the start of input section
1846 // SHNDX in OBJECT, return whether this address is being included in
1847 // the final link.  This should only be called if SHNDX in OBJECT has
1848 // a special mapping.
1849
1850 bool
1851 Output_section::is_input_address_mapped(const Relobj* object,
1852                                         unsigned int shndx,
1853                                         off_t offset) const
1854 {
1855   gold_assert(object->is_section_specially_mapped(shndx));
1856
1857   for (Input_section_list::const_iterator p = this->input_sections_.begin();
1858        p != this->input_sections_.end();
1859        ++p)
1860     {
1861       section_offset_type output_offset;
1862       if (p->output_offset(object, shndx, offset, &output_offset))
1863         return output_offset != -1;
1864     }
1865
1866   // By default we assume that the address is mapped.  This should
1867   // only be called after we have passed all sections to Layout.  At
1868   // that point we should know what we are discarding.
1869   return true;
1870 }
1871
1872 // Given an address OFFSET relative to the start of input section
1873 // SHNDX in object OBJECT, return the output offset relative to the
1874 // start of the input section in the output section.  This should only
1875 // be called if SHNDX in OBJECT has a special mapping.
1876
1877 section_offset_type
1878 Output_section::output_offset(const Relobj* object, unsigned int shndx,
1879                               section_offset_type offset) const
1880 {
1881   gold_assert(object->is_section_specially_mapped(shndx));
1882   // This can only be called meaningfully when layout is complete.
1883   gold_assert(Output_data::is_layout_complete());
1884
1885   for (Input_section_list::const_iterator p = this->input_sections_.begin();
1886        p != this->input_sections_.end();
1887        ++p)
1888     {
1889       section_offset_type output_offset;
1890       if (p->output_offset(object, shndx, offset, &output_offset))
1891         return output_offset;
1892     }
1893   gold_unreachable();
1894 }
1895
1896 // Return the output virtual address of OFFSET relative to the start
1897 // of input section SHNDX in object OBJECT.
1898
1899 uint64_t
1900 Output_section::output_address(const Relobj* object, unsigned int shndx,
1901                                off_t offset) const
1902 {
1903   gold_assert(object->is_section_specially_mapped(shndx));
1904
1905   uint64_t addr = this->address() + this->first_input_offset_;
1906   for (Input_section_list::const_iterator p = this->input_sections_.begin();
1907        p != this->input_sections_.end();
1908        ++p)
1909     {
1910       addr = align_address(addr, p->addralign());
1911       section_offset_type output_offset;
1912       if (p->output_offset(object, shndx, offset, &output_offset))
1913         {
1914           if (output_offset == -1)
1915             return -1U;
1916           return addr + output_offset;
1917         }
1918       addr += p->data_size();
1919     }
1920
1921   // If we get here, it means that we don't know the mapping for this
1922   // input section.  This might happen in principle if
1923   // add_input_section were called before add_output_section_data.
1924   // But it should never actually happen.
1925
1926   gold_unreachable();
1927 }
1928
1929 // Return the output address of the start of the merged section for
1930 // input section SHNDX in object OBJECT.
1931
1932 uint64_t
1933 Output_section::starting_output_address(const Relobj* object,
1934                                         unsigned int shndx) const
1935 {
1936   gold_assert(object->is_section_specially_mapped(shndx));
1937
1938   uint64_t addr = this->address() + this->first_input_offset_;
1939   for (Input_section_list::const_iterator p = this->input_sections_.begin();
1940        p != this->input_sections_.end();
1941        ++p)
1942     {
1943       addr = align_address(addr, p->addralign());
1944
1945       // It would be nice if we could use the existing output_offset
1946       // method to get the output offset of input offset 0.
1947       // Unfortunately we don't know for sure that input offset 0 is
1948       // mapped at all.
1949       if (p->is_merge_section_for(object, shndx))
1950         return addr;
1951
1952       addr += p->data_size();
1953     }
1954   gold_unreachable();
1955 }
1956
1957 // Set the data size of an Output_section.  This is where we handle
1958 // setting the addresses of any Output_section_data objects.
1959
1960 void
1961 Output_section::set_final_data_size()
1962 {
1963   if (this->input_sections_.empty())
1964     {
1965       this->set_data_size(this->current_data_size_for_child());
1966       return;
1967     }
1968
1969   if (this->must_sort_attached_input_sections())
1970     this->sort_attached_input_sections();
1971
1972   uint64_t address = this->address();
1973   off_t startoff = this->offset();
1974   off_t off = startoff + this->first_input_offset_;
1975   for (Input_section_list::iterator p = this->input_sections_.begin();
1976        p != this->input_sections_.end();
1977        ++p)
1978     {
1979       off = align_address(off, p->addralign());
1980       p->set_address_and_file_offset(address + (off - startoff), off,
1981                                      startoff);
1982       off += p->data_size();
1983     }
1984
1985   this->set_data_size(off - startoff);
1986 }
1987
1988 // Reset the address and file offset.
1989
1990 void
1991 Output_section::do_reset_address_and_file_offset()
1992 {
1993   for (Input_section_list::iterator p = this->input_sections_.begin();
1994        p != this->input_sections_.end();
1995        ++p)
1996     p->reset_address_and_file_offset();
1997 }
1998
1999 // Set the TLS offset.  Called only for SHT_TLS sections.
2000
2001 void
2002 Output_section::do_set_tls_offset(uint64_t tls_base)
2003 {
2004   this->tls_offset_ = this->address() - tls_base;
2005 }
2006
2007 // In a few cases we need to sort the input sections attached to an
2008 // output section.  This is used to implement the type of constructor
2009 // priority ordering implemented by the GNU linker, in which the
2010 // priority becomes part of the section name and the sections are
2011 // sorted by name.  We only do this for an output section if we see an
2012 // attached input section matching ".ctor.*", ".dtor.*",
2013 // ".init_array.*" or ".fini_array.*".
2014
2015 class Output_section::Input_section_sort_entry
2016 {
2017  public:
2018   Input_section_sort_entry()
2019     : input_section_(), index_(-1U), section_has_name_(false),
2020       section_name_()
2021   { }
2022
2023   Input_section_sort_entry(const Input_section& input_section,
2024                            unsigned int index)
2025     : input_section_(input_section), index_(index),
2026       section_has_name_(input_section.is_input_section())
2027   {
2028     if (this->section_has_name_)
2029       {
2030         // This is only called single-threaded from Layout::finalize,
2031         // so it is OK to lock.  Unfortunately we have no way to pass
2032         // in a Task token.
2033         const Task* dummy_task = reinterpret_cast<const Task*>(-1);
2034         Object* obj = input_section.relobj();
2035         Task_lock_obj<Object> tl(dummy_task, obj);
2036
2037         // This is a slow operation, which should be cached in
2038         // Layout::layout if this becomes a speed problem.
2039         this->section_name_ = obj->section_name(input_section.shndx());
2040       }
2041   }
2042
2043   // Return the Input_section.
2044   const Input_section&
2045   input_section() const
2046   {
2047     gold_assert(this->index_ != -1U);
2048     return this->input_section_;
2049   }
2050
2051   // The index of this entry in the original list.  This is used to
2052   // make the sort stable.
2053   unsigned int
2054   index() const
2055   {
2056     gold_assert(this->index_ != -1U);
2057     return this->index_;
2058   }
2059
2060   // Whether there is a section name.
2061   bool
2062   section_has_name() const
2063   { return this->section_has_name_; }
2064
2065   // The section name.
2066   const std::string&
2067   section_name() const
2068   {
2069     gold_assert(this->section_has_name_);
2070     return this->section_name_;
2071   }
2072
2073   // Return true if the section name has a priority.  This is assumed
2074   // to be true if it has a dot after the initial dot.
2075   bool
2076   has_priority() const
2077   {
2078     gold_assert(this->section_has_name_);
2079     return this->section_name_.find('.', 1);
2080   }
2081
2082   // Return true if this an input file whose base name matches
2083   // FILE_NAME.  The base name must have an extension of ".o", and
2084   // must be exactly FILE_NAME.o or FILE_NAME, one character, ".o".
2085   // This is to match crtbegin.o as well as crtbeginS.o without
2086   // getting confused by other possibilities.  Overall matching the
2087   // file name this way is a dreadful hack, but the GNU linker does it
2088   // in order to better support gcc, and we need to be compatible.
2089   bool
2090   match_file_name(const char* match_file_name) const
2091   {
2092     const std::string& file_name(this->input_section_.relobj()->name());
2093     const char* base_name = lbasename(file_name.c_str());
2094     size_t match_len = strlen(match_file_name);
2095     if (strncmp(base_name, match_file_name, match_len) != 0)
2096       return false;
2097     size_t base_len = strlen(base_name);
2098     if (base_len != match_len + 2 && base_len != match_len + 3)
2099       return false;
2100     return memcmp(base_name + base_len - 2, ".o", 2) == 0;
2101   }
2102
2103  private:
2104   // The Input_section we are sorting.
2105   Input_section input_section_;
2106   // The index of this Input_section in the original list.
2107   unsigned int index_;
2108   // Whether this Input_section has a section name--it won't if this
2109   // is some random Output_section_data.
2110   bool section_has_name_;
2111   // The section name if there is one.
2112   std::string section_name_;
2113 };
2114
2115 // Return true if S1 should come before S2 in the output section.
2116
2117 bool
2118 Output_section::Input_section_sort_compare::operator()(
2119     const Output_section::Input_section_sort_entry& s1,
2120     const Output_section::Input_section_sort_entry& s2) const
2121 {
2122   // crtbegin.o must come first.
2123   bool s1_begin = s1.match_file_name("crtbegin");
2124   bool s2_begin = s2.match_file_name("crtbegin");
2125   if (s1_begin || s2_begin)
2126     {
2127       if (!s1_begin)
2128         return false;
2129       if (!s2_begin)
2130         return true;
2131       return s1.index() < s2.index();
2132     }
2133
2134   // crtend.o must come last.
2135   bool s1_end = s1.match_file_name("crtend");
2136   bool s2_end = s2.match_file_name("crtend");
2137   if (s1_end || s2_end)
2138     {
2139       if (!s1_end)
2140         return true;
2141       if (!s2_end)
2142         return false;
2143       return s1.index() < s2.index();
2144     }
2145
2146   // We sort all the sections with no names to the end.
2147   if (!s1.section_has_name() || !s2.section_has_name())
2148     {
2149       if (s1.section_has_name())
2150         return true;
2151       if (s2.section_has_name())
2152         return false;
2153       return s1.index() < s2.index();
2154     }
2155
2156   // A section with a priority follows a section without a priority.
2157   // The GNU linker does this for all but .init_array sections; until
2158   // further notice we'll assume that that is an mistake.
2159   bool s1_has_priority = s1.has_priority();
2160   bool s2_has_priority = s2.has_priority();
2161   if (s1_has_priority && !s2_has_priority)
2162     return false;
2163   if (!s1_has_priority && s2_has_priority)
2164     return true;
2165
2166   // Otherwise we sort by name.
2167   int compare = s1.section_name().compare(s2.section_name());
2168   if (compare != 0)
2169     return compare < 0;
2170
2171   // Otherwise we keep the input order.
2172   return s1.index() < s2.index();
2173 }
2174
2175 // Sort the input sections attached to an output section.
2176
2177 void
2178 Output_section::sort_attached_input_sections()
2179 {
2180   if (this->attached_input_sections_are_sorted_)
2181     return;
2182
2183   // The only thing we know about an input section is the object and
2184   // the section index.  We need the section name.  Recomputing this
2185   // is slow but this is an unusual case.  If this becomes a speed
2186   // problem we can cache the names as required in Layout::layout.
2187
2188   // We start by building a larger vector holding a copy of each
2189   // Input_section, plus its current index in the list and its name.
2190   std::vector<Input_section_sort_entry> sort_list;
2191
2192   unsigned int i = 0;
2193   for (Input_section_list::iterator p = this->input_sections_.begin();
2194        p != this->input_sections_.end();
2195        ++p, ++i)
2196     sort_list.push_back(Input_section_sort_entry(*p, i));
2197
2198   // Sort the input sections.
2199   std::sort(sort_list.begin(), sort_list.end(), Input_section_sort_compare());
2200
2201   // Copy the sorted input sections back to our list.
2202   this->input_sections_.clear();
2203   for (std::vector<Input_section_sort_entry>::iterator p = sort_list.begin();
2204        p != sort_list.end();
2205        ++p)
2206     this->input_sections_.push_back(p->input_section());
2207
2208   // Remember that we sorted the input sections, since we might get
2209   // called again.
2210   this->attached_input_sections_are_sorted_ = true;
2211 }
2212
2213 // Write the section header to *OSHDR.
2214
2215 template<int size, bool big_endian>
2216 void
2217 Output_section::write_header(const Layout* layout,
2218                              const Stringpool* secnamepool,
2219                              elfcpp::Shdr_write<size, big_endian>* oshdr) const
2220 {
2221   oshdr->put_sh_name(secnamepool->get_offset(this->name_));
2222   oshdr->put_sh_type(this->type_);
2223
2224   elfcpp::Elf_Xword flags = this->flags_;
2225   if (this->info_section_ != NULL && this->info_uses_section_index_)
2226     flags |= elfcpp::SHF_INFO_LINK;
2227   oshdr->put_sh_flags(flags);
2228
2229   oshdr->put_sh_addr(this->address());
2230   oshdr->put_sh_offset(this->offset());
2231   oshdr->put_sh_size(this->data_size());
2232   if (this->link_section_ != NULL)
2233     oshdr->put_sh_link(this->link_section_->out_shndx());
2234   else if (this->should_link_to_symtab_)
2235     oshdr->put_sh_link(layout->symtab_section()->out_shndx());
2236   else if (this->should_link_to_dynsym_)
2237     oshdr->put_sh_link(layout->dynsym_section()->out_shndx());
2238   else
2239     oshdr->put_sh_link(this->link_);
2240
2241   elfcpp::Elf_Word info;
2242   if (this->info_section_ != NULL)
2243     {
2244       if (this->info_uses_section_index_)
2245         info = this->info_section_->out_shndx();
2246       else
2247         info = this->info_section_->symtab_index();
2248     }
2249   else if (this->info_symndx_ != NULL)
2250     info = this->info_symndx_->symtab_index();
2251   else
2252     info = this->info_;
2253   oshdr->put_sh_info(info);
2254
2255   oshdr->put_sh_addralign(this->addralign_);
2256   oshdr->put_sh_entsize(this->entsize_);
2257 }
2258
2259 // Write out the data.  For input sections the data is written out by
2260 // Object::relocate, but we have to handle Output_section_data objects
2261 // here.
2262
2263 void
2264 Output_section::do_write(Output_file* of)
2265 {
2266   gold_assert(!this->requires_postprocessing());
2267
2268   off_t output_section_file_offset = this->offset();
2269   for (Fill_list::iterator p = this->fills_.begin();
2270        p != this->fills_.end();
2271        ++p)
2272     {
2273       std::string fill_data(parameters->target().code_fill(p->length()));
2274       of->write(output_section_file_offset + p->section_offset(),
2275                 fill_data.data(), fill_data.size());
2276     }
2277
2278   for (Input_section_list::iterator p = this->input_sections_.begin();
2279        p != this->input_sections_.end();
2280        ++p)
2281     p->write(of);
2282 }
2283
2284 // If a section requires postprocessing, create the buffer to use.
2285
2286 void
2287 Output_section::create_postprocessing_buffer()
2288 {
2289   gold_assert(this->requires_postprocessing());
2290
2291   if (this->postprocessing_buffer_ != NULL)
2292     return;
2293
2294   if (!this->input_sections_.empty())
2295     {
2296       off_t off = this->first_input_offset_;
2297       for (Input_section_list::iterator p = this->input_sections_.begin();
2298            p != this->input_sections_.end();
2299            ++p)
2300         {
2301           off = align_address(off, p->addralign());
2302           p->finalize_data_size();
2303           off += p->data_size();
2304         }
2305       this->set_current_data_size_for_child(off);
2306     }
2307
2308   off_t buffer_size = this->current_data_size_for_child();
2309   this->postprocessing_buffer_ = new unsigned char[buffer_size];
2310 }
2311
2312 // Write all the data of an Output_section into the postprocessing
2313 // buffer.  This is used for sections which require postprocessing,
2314 // such as compression.  Input sections are handled by
2315 // Object::Relocate.
2316
2317 void
2318 Output_section::write_to_postprocessing_buffer()
2319 {
2320   gold_assert(this->requires_postprocessing());
2321
2322   unsigned char* buffer = this->postprocessing_buffer();
2323   for (Fill_list::iterator p = this->fills_.begin();
2324        p != this->fills_.end();
2325        ++p)
2326     {
2327       std::string fill_data(parameters->target().code_fill(p->length()));
2328       memcpy(buffer + p->section_offset(), fill_data.data(),
2329              fill_data.size());
2330     }
2331
2332   off_t off = this->first_input_offset_;
2333   for (Input_section_list::iterator p = this->input_sections_.begin();
2334        p != this->input_sections_.end();
2335        ++p)
2336     {
2337       off = align_address(off, p->addralign());
2338       p->write_to_buffer(buffer + off);
2339       off += p->data_size();
2340     }
2341 }
2342
2343 // Get the input sections for linker script processing.  We leave
2344 // behind the Output_section_data entries.  Note that this may be
2345 // slightly incorrect for merge sections.  We will leave them behind,
2346 // but it is possible that the script says that they should follow
2347 // some other input sections, as in:
2348 //    .rodata { *(.rodata) *(.rodata.cst*) }
2349 // For that matter, we don't handle this correctly:
2350 //    .rodata { foo.o(.rodata.cst*) *(.rodata.cst*) }
2351 // With luck this will never matter.
2352
2353 uint64_t
2354 Output_section::get_input_sections(
2355     uint64_t address,
2356     const std::string& fill,
2357     std::list<std::pair<Relobj*, unsigned int> >* input_sections)
2358 {
2359   uint64_t orig_address = address;
2360
2361   address = align_address(address, this->addralign());
2362
2363   Input_section_list remaining;
2364   for (Input_section_list::iterator p = this->input_sections_.begin();
2365        p != this->input_sections_.end();
2366        ++p)
2367     {
2368       if (p->is_input_section())
2369         input_sections->push_back(std::make_pair(p->relobj(), p->shndx()));
2370       else
2371         {
2372           uint64_t aligned_address = align_address(address, p->addralign());
2373           if (aligned_address != address && !fill.empty())
2374             {
2375               section_size_type length =
2376                 convert_to_section_size_type(aligned_address - address);
2377               std::string this_fill;
2378               this_fill.reserve(length);
2379               while (this_fill.length() + fill.length() <= length)
2380                 this_fill += fill;
2381               if (this_fill.length() < length)
2382                 this_fill.append(fill, 0, length - this_fill.length());
2383
2384               Output_section_data* posd = new Output_data_const(this_fill, 0);
2385               remaining.push_back(Input_section(posd));
2386             }
2387           address = aligned_address;
2388
2389           remaining.push_back(*p);
2390
2391           p->finalize_data_size();
2392           address += p->data_size();
2393         }
2394     }
2395
2396   this->input_sections_.swap(remaining);
2397   this->first_input_offset_ = 0;
2398
2399   uint64_t data_size = address - orig_address;
2400   this->set_current_data_size_for_child(data_size);
2401   return data_size;
2402 }
2403
2404 // Add an input section from a script.
2405
2406 void
2407 Output_section::add_input_section_for_script(Relobj* object,
2408                                              unsigned int shndx,
2409                                              off_t data_size,
2410                                              uint64_t addralign)
2411 {
2412   if (addralign > this->addralign_)
2413     this->addralign_ = addralign;
2414
2415   off_t offset_in_section = this->current_data_size_for_child();
2416   off_t aligned_offset_in_section = align_address(offset_in_section,
2417                                                   addralign);
2418
2419   this->set_current_data_size_for_child(aligned_offset_in_section
2420                                         + data_size);
2421
2422   this->input_sections_.push_back(Input_section(object, shndx,
2423                                                 data_size, addralign));
2424 }
2425
2426 // Print stats for merge sections to stderr.
2427
2428 void
2429 Output_section::print_merge_stats()
2430 {
2431   Input_section_list::iterator p;
2432   for (p = this->input_sections_.begin();
2433        p != this->input_sections_.end();
2434        ++p)
2435     p->print_merge_stats(this->name_);
2436 }
2437
2438 // Output segment methods.
2439
2440 Output_segment::Output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2441   : output_data_(),
2442     output_bss_(),
2443     vaddr_(0),
2444     paddr_(0),
2445     memsz_(0),
2446     max_align_(0),
2447     min_p_align_(0),
2448     offset_(0),
2449     filesz_(0),
2450     type_(type),
2451     flags_(flags),
2452     is_max_align_known_(false),
2453     are_addresses_set_(false)
2454 {
2455 }
2456
2457 // Add an Output_section to an Output_segment.
2458
2459 void
2460 Output_segment::add_output_section(Output_section* os,
2461                                    elfcpp::Elf_Word seg_flags,
2462                                    bool front)
2463 {
2464   gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
2465   gold_assert(!this->is_max_align_known_);
2466
2467   // Update the segment flags.
2468   this->flags_ |= seg_flags;
2469
2470   Output_segment::Output_data_list* pdl;
2471   if (os->type() == elfcpp::SHT_NOBITS)
2472     pdl = &this->output_bss_;
2473   else
2474     pdl = &this->output_data_;
2475
2476   // So that PT_NOTE segments will work correctly, we need to ensure
2477   // that all SHT_NOTE sections are adjacent.  This will normally
2478   // happen automatically, because all the SHT_NOTE input sections
2479   // will wind up in the same output section.  However, it is possible
2480   // for multiple SHT_NOTE input sections to have different section
2481   // flags, and thus be in different output sections, but for the
2482   // different section flags to map into the same segment flags and
2483   // thus the same output segment.
2484
2485   // Note that while there may be many input sections in an output
2486   // section, there are normally only a few output sections in an
2487   // output segment.  This loop is expected to be fast.
2488
2489   if (os->type() == elfcpp::SHT_NOTE && !pdl->empty())
2490     {
2491       Output_segment::Output_data_list::iterator p = pdl->end();
2492       do
2493         {
2494           --p;
2495           if ((*p)->is_section_type(elfcpp::SHT_NOTE))
2496             {
2497               // We don't worry about the FRONT parameter.
2498               ++p;
2499               pdl->insert(p, os);
2500               return;
2501             }
2502         }
2503       while (p != pdl->begin());
2504     }
2505
2506   // Similarly, so that PT_TLS segments will work, we need to group
2507   // SHF_TLS sections.  An SHF_TLS/SHT_NOBITS section is a special
2508   // case: we group the SHF_TLS/SHT_NOBITS sections right after the
2509   // SHF_TLS/SHT_PROGBITS sections.  This lets us set up PT_TLS
2510   // correctly.  SHF_TLS sections get added to both a PT_LOAD segment
2511   // and the PT_TLS segment -- we do this grouping only for the
2512   // PT_LOAD segment.
2513   if (this->type_ != elfcpp::PT_TLS
2514       && (os->flags() & elfcpp::SHF_TLS) != 0
2515       && !this->output_data_.empty())
2516     {
2517       pdl = &this->output_data_;
2518       bool nobits = os->type() == elfcpp::SHT_NOBITS;
2519       bool sawtls = false;
2520       Output_segment::Output_data_list::iterator p = pdl->end();
2521       do
2522         {
2523           --p;
2524           bool insert;
2525           if ((*p)->is_section_flag_set(elfcpp::SHF_TLS))
2526             {
2527               sawtls = true;
2528               // Put a NOBITS section after the first TLS section.
2529               // But a PROGBITS section after the first TLS/PROGBITS
2530               // section.
2531               insert = nobits || !(*p)->is_section_type(elfcpp::SHT_NOBITS);
2532             }
2533           else
2534             {
2535               // If we've gone past the TLS sections, but we've seen a
2536               // TLS section, then we need to insert this section now.
2537               insert = sawtls;
2538             }
2539
2540           if (insert)
2541             {
2542               // We don't worry about the FRONT parameter.
2543               ++p;
2544               pdl->insert(p, os);
2545               return;
2546             }
2547         }
2548       while (p != pdl->begin());
2549
2550       // There are no TLS sections yet; put this one at the requested
2551       // location in the section list.
2552     }
2553
2554   if (front)
2555     pdl->push_front(os);
2556   else
2557     pdl->push_back(os);
2558 }
2559
2560 // Remove an Output_section from this segment.  It is an error if it
2561 // is not present.
2562
2563 void
2564 Output_segment::remove_output_section(Output_section* os)
2565 {
2566   // We only need this for SHT_PROGBITS.
2567   gold_assert(os->type() == elfcpp::SHT_PROGBITS);
2568   for (Output_data_list::iterator p = this->output_data_.begin();
2569        p != this->output_data_.end();
2570        ++p)
2571    {
2572      if (*p == os)
2573        {
2574          this->output_data_.erase(p);
2575          return;
2576        }
2577    }
2578   gold_unreachable();
2579 }
2580
2581 // Add an Output_data (which is not an Output_section) to the start of
2582 // a segment.
2583
2584 void
2585 Output_segment::add_initial_output_data(Output_data* od)
2586 {
2587   gold_assert(!this->is_max_align_known_);
2588   this->output_data_.push_front(od);
2589 }
2590
2591 // Return the maximum alignment of the Output_data in Output_segment.
2592
2593 uint64_t
2594 Output_segment::maximum_alignment()
2595 {
2596   if (!this->is_max_align_known_)
2597     {
2598       uint64_t addralign;
2599
2600       addralign = Output_segment::maximum_alignment_list(&this->output_data_);
2601       if (addralign > this->max_align_)
2602         this->max_align_ = addralign;
2603
2604       addralign = Output_segment::maximum_alignment_list(&this->output_bss_);
2605       if (addralign > this->max_align_)
2606         this->max_align_ = addralign;
2607
2608       this->is_max_align_known_ = true;
2609     }
2610
2611   return this->max_align_;
2612 }
2613
2614 // Return the maximum alignment of a list of Output_data.
2615
2616 uint64_t
2617 Output_segment::maximum_alignment_list(const Output_data_list* pdl)
2618 {
2619   uint64_t ret = 0;
2620   for (Output_data_list::const_iterator p = pdl->begin();
2621        p != pdl->end();
2622        ++p)
2623     {
2624       uint64_t addralign = (*p)->addralign();
2625       if (addralign > ret)
2626         ret = addralign;
2627     }
2628   return ret;
2629 }
2630
2631 // Return the number of dynamic relocs applied to this segment.
2632
2633 unsigned int
2634 Output_segment::dynamic_reloc_count() const
2635 {
2636   return (this->dynamic_reloc_count_list(&this->output_data_)
2637           + this->dynamic_reloc_count_list(&this->output_bss_));
2638 }
2639
2640 // Return the number of dynamic relocs applied to an Output_data_list.
2641
2642 unsigned int
2643 Output_segment::dynamic_reloc_count_list(const Output_data_list* pdl) const
2644 {
2645   unsigned int count = 0;
2646   for (Output_data_list::const_iterator p = pdl->begin();
2647        p != pdl->end();
2648        ++p)
2649     count += (*p)->dynamic_reloc_count();
2650   return count;
2651 }
2652
2653 // Set the section addresses for an Output_segment.  If RESET is true,
2654 // reset the addresses first.  ADDR is the address and *POFF is the
2655 // file offset.  Set the section indexes starting with *PSHNDX.
2656 // Return the address of the immediately following segment.  Update
2657 // *POFF and *PSHNDX.
2658
2659 uint64_t
2660 Output_segment::set_section_addresses(const Layout* layout, bool reset,
2661                                       uint64_t addr, off_t* poff,
2662                                       unsigned int* pshndx)
2663 {
2664   gold_assert(this->type_ == elfcpp::PT_LOAD);
2665
2666   if (!reset && this->are_addresses_set_)
2667     {
2668       gold_assert(this->paddr_ == addr);
2669       addr = this->vaddr_;
2670     }
2671   else
2672     {
2673       this->vaddr_ = addr;
2674       this->paddr_ = addr;
2675       this->are_addresses_set_ = true;
2676     }
2677
2678   bool in_tls = false;
2679
2680   off_t orig_off = *poff;
2681   this->offset_ = orig_off;
2682
2683   addr = this->set_section_list_addresses(layout, reset, &this->output_data_,
2684                                           addr, poff, pshndx, &in_tls);
2685   this->filesz_ = *poff - orig_off;
2686
2687   off_t off = *poff;
2688
2689   uint64_t ret = this->set_section_list_addresses(layout, reset,
2690                                                   &this->output_bss_,
2691                                                   addr, poff, pshndx,
2692                                                   &in_tls);
2693
2694   // If the last section was a TLS section, align upward to the
2695   // alignment of the TLS segment, so that the overall size of the TLS
2696   // segment is aligned.
2697   if (in_tls)
2698     {
2699       uint64_t segment_align = layout->tls_segment()->maximum_alignment();
2700       *poff = align_address(*poff, segment_align);
2701     }
2702
2703   this->memsz_ = *poff - orig_off;
2704
2705   // Ignore the file offset adjustments made by the BSS Output_data
2706   // objects.
2707   *poff = off;
2708
2709   return ret;
2710 }
2711
2712 // Set the addresses and file offsets in a list of Output_data
2713 // structures.
2714
2715 uint64_t
2716 Output_segment::set_section_list_addresses(const Layout* layout, bool reset,
2717                                            Output_data_list* pdl,
2718                                            uint64_t addr, off_t* poff,
2719                                            unsigned int* pshndx,
2720                                            bool* in_tls)
2721 {
2722   off_t startoff = *poff;
2723
2724   off_t off = startoff;
2725   for (Output_data_list::iterator p = pdl->begin();
2726        p != pdl->end();
2727        ++p)
2728     {
2729       if (reset)
2730         (*p)->reset_address_and_file_offset();
2731
2732       // When using a linker script the section will most likely
2733       // already have an address.
2734       if (!(*p)->is_address_valid())
2735         {
2736           uint64_t align = (*p)->addralign();
2737
2738           if ((*p)->is_section_flag_set(elfcpp::SHF_TLS))
2739             {
2740               // Give the first TLS section the alignment of the
2741               // entire TLS segment.  Otherwise the TLS segment as a
2742               // whole may be misaligned.
2743               if (!*in_tls)
2744                 {
2745                   Output_segment* tls_segment = layout->tls_segment();
2746                   gold_assert(tls_segment != NULL);
2747                   uint64_t segment_align = tls_segment->maximum_alignment();
2748                   gold_assert(segment_align >= align);
2749                   align = segment_align;
2750
2751                   *in_tls = true;
2752                 }
2753             }
2754           else
2755             {
2756               // If this is the first section after the TLS segment,
2757               // align it to at least the alignment of the TLS
2758               // segment, so that the size of the overall TLS segment
2759               // is aligned.
2760               if (*in_tls)
2761                 {
2762                   uint64_t segment_align =
2763                       layout->tls_segment()->maximum_alignment();
2764                   if (segment_align > align)
2765                     align = segment_align;
2766
2767                   *in_tls = false;
2768                 }
2769             }
2770
2771           off = align_address(off, align);
2772           (*p)->set_address_and_file_offset(addr + (off - startoff), off);
2773         }
2774       else
2775         {
2776           // The script may have inserted a skip forward, but it
2777           // better not have moved backward.
2778           gold_assert((*p)->address() >= addr + (off - startoff));
2779           off += (*p)->address() - (addr + (off - startoff));
2780           (*p)->set_file_offset(off);
2781           (*p)->finalize_data_size();
2782         }
2783
2784       // We want to ignore the size of a SHF_TLS or SHT_NOBITS
2785       // section.  Such a section does not affect the size of a
2786       // PT_LOAD segment.
2787       if (!(*p)->is_section_flag_set(elfcpp::SHF_TLS)
2788           || !(*p)->is_section_type(elfcpp::SHT_NOBITS))
2789         off += (*p)->data_size();
2790
2791       if ((*p)->is_section())
2792         {
2793           (*p)->set_out_shndx(*pshndx);
2794           ++*pshndx;
2795         }
2796     }
2797
2798   *poff = off;
2799   return addr + (off - startoff);
2800 }
2801
2802 // For a non-PT_LOAD segment, set the offset from the sections, if
2803 // any.
2804
2805 void
2806 Output_segment::set_offset()
2807 {
2808   gold_assert(this->type_ != elfcpp::PT_LOAD);
2809
2810   gold_assert(!this->are_addresses_set_);
2811
2812   if (this->output_data_.empty() && this->output_bss_.empty())
2813     {
2814       this->vaddr_ = 0;
2815       this->paddr_ = 0;
2816       this->are_addresses_set_ = true;
2817       this->memsz_ = 0;
2818       this->min_p_align_ = 0;
2819       this->offset_ = 0;
2820       this->filesz_ = 0;
2821       return;
2822     }
2823
2824   const Output_data* first;
2825   if (this->output_data_.empty())
2826     first = this->output_bss_.front();
2827   else
2828     first = this->output_data_.front();
2829   this->vaddr_ = first->address();
2830   this->paddr_ = (first->has_load_address()
2831                   ? first->load_address()
2832                   : this->vaddr_);
2833   this->are_addresses_set_ = true;
2834   this->offset_ = first->offset();
2835
2836   if (this->output_data_.empty())
2837     this->filesz_ = 0;
2838   else
2839     {
2840       const Output_data* last_data = this->output_data_.back();
2841       this->filesz_ = (last_data->address()
2842                        + last_data->data_size()
2843                        - this->vaddr_);
2844     }
2845
2846   const Output_data* last;
2847   if (this->output_bss_.empty())
2848     last = this->output_data_.back();
2849   else
2850     last = this->output_bss_.back();
2851   this->memsz_ = (last->address()
2852                   + last->data_size()
2853                   - this->vaddr_);
2854
2855   // If this is a TLS segment, align the memory size.  The code in
2856   // set_section_list ensures that the section after the TLS segment
2857   // is aligned to give us room.
2858   if (this->type_ == elfcpp::PT_TLS)
2859     {
2860       uint64_t segment_align = this->maximum_alignment();
2861       gold_assert(this->vaddr_ == align_address(this->vaddr_, segment_align));
2862       this->memsz_ = align_address(this->memsz_, segment_align);
2863     }
2864 }
2865
2866 // Set the TLS offsets of the sections in the PT_TLS segment.
2867
2868 void
2869 Output_segment::set_tls_offsets()
2870 {
2871   gold_assert(this->type_ == elfcpp::PT_TLS);
2872
2873   for (Output_data_list::iterator p = this->output_data_.begin();
2874        p != this->output_data_.end();
2875        ++p)
2876     (*p)->set_tls_offset(this->vaddr_);
2877
2878   for (Output_data_list::iterator p = this->output_bss_.begin();
2879        p != this->output_bss_.end();
2880        ++p)
2881     (*p)->set_tls_offset(this->vaddr_);
2882 }
2883
2884 // Return the address of the first section.
2885
2886 uint64_t
2887 Output_segment::first_section_load_address() const
2888 {
2889   for (Output_data_list::const_iterator p = this->output_data_.begin();
2890        p != this->output_data_.end();
2891        ++p)
2892     if ((*p)->is_section())
2893       return (*p)->has_load_address() ? (*p)->load_address() : (*p)->address();
2894
2895   for (Output_data_list::const_iterator p = this->output_bss_.begin();
2896        p != this->output_bss_.end();
2897        ++p)
2898     if ((*p)->is_section())
2899       return (*p)->has_load_address() ? (*p)->load_address() : (*p)->address();
2900
2901   gold_unreachable();
2902 }
2903
2904 // Return the number of Output_sections in an Output_segment.
2905
2906 unsigned int
2907 Output_segment::output_section_count() const
2908 {
2909   return (this->output_section_count_list(&this->output_data_)
2910           + this->output_section_count_list(&this->output_bss_));
2911 }
2912
2913 // Return the number of Output_sections in an Output_data_list.
2914
2915 unsigned int
2916 Output_segment::output_section_count_list(const Output_data_list* pdl) const
2917 {
2918   unsigned int count = 0;
2919   for (Output_data_list::const_iterator p = pdl->begin();
2920        p != pdl->end();
2921        ++p)
2922     {
2923       if ((*p)->is_section())
2924         ++count;
2925     }
2926   return count;
2927 }
2928
2929 // Return the section attached to the list segment with the lowest
2930 // load address.  This is used when handling a PHDRS clause in a
2931 // linker script.
2932
2933 Output_section*
2934 Output_segment::section_with_lowest_load_address() const
2935 {
2936   Output_section* found = NULL;
2937   uint64_t found_lma = 0;
2938   this->lowest_load_address_in_list(&this->output_data_, &found, &found_lma);
2939
2940   Output_section* found_data = found;
2941   this->lowest_load_address_in_list(&this->output_bss_, &found, &found_lma);
2942   if (found != found_data && found_data != NULL)
2943     {
2944       gold_error(_("nobits section %s may not precede progbits section %s "
2945                    "in same segment"),
2946                  found->name(), found_data->name());
2947       return NULL;
2948     }
2949
2950   return found;
2951 }
2952
2953 // Look through a list for a section with a lower load address.
2954
2955 void
2956 Output_segment::lowest_load_address_in_list(const Output_data_list* pdl,
2957                                             Output_section** found,
2958                                             uint64_t* found_lma) const
2959 {
2960   for (Output_data_list::const_iterator p = pdl->begin();
2961        p != pdl->end();
2962        ++p)
2963     {
2964       if (!(*p)->is_section())
2965         continue;
2966       Output_section* os = static_cast<Output_section*>(*p);
2967       uint64_t lma = (os->has_load_address()
2968                       ? os->load_address()
2969                       : os->address());
2970       if (*found == NULL || lma < *found_lma)
2971         {
2972           *found = os;
2973           *found_lma = lma;
2974         }
2975     }
2976 }
2977
2978 // Write the segment data into *OPHDR.
2979
2980 template<int size, bool big_endian>
2981 void
2982 Output_segment::write_header(elfcpp::Phdr_write<size, big_endian>* ophdr)
2983 {
2984   ophdr->put_p_type(this->type_);
2985   ophdr->put_p_offset(this->offset_);
2986   ophdr->put_p_vaddr(this->vaddr_);
2987   ophdr->put_p_paddr(this->paddr_);
2988   ophdr->put_p_filesz(this->filesz_);
2989   ophdr->put_p_memsz(this->memsz_);
2990   ophdr->put_p_flags(this->flags_);
2991   ophdr->put_p_align(std::max(this->min_p_align_, this->maximum_alignment()));
2992 }
2993
2994 // Write the section headers into V.
2995
2996 template<int size, bool big_endian>
2997 unsigned char*
2998 Output_segment::write_section_headers(const Layout* layout,
2999                                       const Stringpool* secnamepool,
3000                                       unsigned char* v,
3001                                       unsigned int *pshndx) const
3002 {
3003   // Every section that is attached to a segment must be attached to a
3004   // PT_LOAD segment, so we only write out section headers for PT_LOAD
3005   // segments.
3006   if (this->type_ != elfcpp::PT_LOAD)
3007     return v;
3008
3009   v = this->write_section_headers_list<size, big_endian>(layout, secnamepool,
3010                                                          &this->output_data_,
3011                                                          v, pshndx);
3012   v = this->write_section_headers_list<size, big_endian>(layout, secnamepool,
3013                                                          &this->output_bss_,
3014                                                          v, pshndx);
3015   return v;
3016 }
3017
3018 template<int size, bool big_endian>
3019 unsigned char*
3020 Output_segment::write_section_headers_list(const Layout* layout,
3021                                            const Stringpool* secnamepool,
3022                                            const Output_data_list* pdl,
3023                                            unsigned char* v,
3024                                            unsigned int* pshndx) const
3025 {
3026   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
3027   for (Output_data_list::const_iterator p = pdl->begin();
3028        p != pdl->end();
3029        ++p)
3030     {
3031       if ((*p)->is_section())
3032         {
3033           const Output_section* ps = static_cast<const Output_section*>(*p);
3034           gold_assert(*pshndx == ps->out_shndx());
3035           elfcpp::Shdr_write<size, big_endian> oshdr(v);
3036           ps->write_header(layout, secnamepool, &oshdr);
3037           v += shdr_size;
3038           ++*pshndx;
3039         }
3040     }
3041   return v;
3042 }
3043
3044 // Output_file methods.
3045
3046 Output_file::Output_file(const char* name)
3047   : name_(name),
3048     o_(-1),
3049     file_size_(0),
3050     base_(NULL),
3051     map_is_anonymous_(false),
3052     is_temporary_(false)
3053 {
3054 }
3055
3056 // Open the output file.
3057
3058 void
3059 Output_file::open(off_t file_size)
3060 {
3061   this->file_size_ = file_size;
3062
3063   // Unlink the file first; otherwise the open() may fail if the file
3064   // is busy (e.g. it's an executable that's currently being executed).
3065   //
3066   // However, the linker may be part of a system where a zero-length
3067   // file is created for it to write to, with tight permissions (gcc
3068   // 2.95 did something like this).  Unlinking the file would work
3069   // around those permission controls, so we only unlink if the file
3070   // has a non-zero size.  We also unlink only regular files to avoid
3071   // trouble with directories/etc.
3072   //
3073   // If we fail, continue; this command is merely a best-effort attempt
3074   // to improve the odds for open().
3075
3076   // We let the name "-" mean "stdout"
3077   if (!this->is_temporary_)
3078     {
3079       if (strcmp(this->name_, "-") == 0)
3080         this->o_ = STDOUT_FILENO;
3081       else
3082         {
3083           struct stat s;
3084           if (::stat(this->name_, &s) == 0 && s.st_size != 0)
3085             unlink_if_ordinary(this->name_);
3086
3087           int mode = parameters->options().relocatable() ? 0666 : 0777;
3088           int o = ::open(this->name_, O_RDWR | O_CREAT | O_TRUNC, mode);
3089           if (o < 0)
3090             gold_fatal(_("%s: open: %s"), this->name_, strerror(errno));
3091           this->o_ = o;
3092         }
3093     }
3094
3095   this->map();
3096 }
3097
3098 // Resize the output file.
3099
3100 void
3101 Output_file::resize(off_t file_size)
3102 {
3103   // If the mmap is mapping an anonymous memory buffer, this is easy:
3104   // just mremap to the new size.  If it's mapping to a file, we want
3105   // to unmap to flush to the file, then remap after growing the file.
3106   if (this->map_is_anonymous_)
3107     {
3108       void* base = ::mremap(this->base_, this->file_size_, file_size,
3109                             MREMAP_MAYMOVE);
3110       if (base == MAP_FAILED)
3111         gold_fatal(_("%s: mremap: %s"), this->name_, strerror(errno));
3112       this->base_ = static_cast<unsigned char*>(base);
3113       this->file_size_ = file_size;
3114     }
3115   else
3116     {
3117       this->unmap();
3118       this->file_size_ = file_size;
3119       this->map();
3120     }
3121 }
3122
3123 // Map the file into memory.
3124
3125 void
3126 Output_file::map()
3127 {
3128   const int o = this->o_;
3129
3130   // If the output file is not a regular file, don't try to mmap it;
3131   // instead, we'll mmap a block of memory (an anonymous buffer), and
3132   // then later write the buffer to the file.
3133   void* base;
3134   struct stat statbuf;
3135   if (o == STDOUT_FILENO || o == STDERR_FILENO
3136       || ::fstat(o, &statbuf) != 0
3137       || !S_ISREG(statbuf.st_mode)
3138       || this->is_temporary_)
3139     {
3140       this->map_is_anonymous_ = true;
3141       base = ::mmap(NULL, this->file_size_, PROT_READ | PROT_WRITE,
3142                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
3143     }
3144   else
3145     {
3146       // Write out one byte to make the file the right size.
3147       if (::lseek(o, this->file_size_ - 1, SEEK_SET) < 0)
3148         gold_fatal(_("%s: lseek: %s"), this->name_, strerror(errno));
3149       char b = 0;
3150       if (::write(o, &b, 1) != 1)
3151         gold_fatal(_("%s: write: %s"), this->name_, strerror(errno));
3152
3153       // Map the file into memory.
3154       this->map_is_anonymous_ = false;
3155       base = ::mmap(NULL, this->file_size_, PROT_READ | PROT_WRITE,
3156                     MAP_SHARED, o, 0);
3157     }
3158   if (base == MAP_FAILED)
3159     gold_fatal(_("%s: mmap: %s"), this->name_, strerror(errno));
3160   this->base_ = static_cast<unsigned char*>(base);
3161 }
3162
3163 // Unmap the file from memory.
3164
3165 void
3166 Output_file::unmap()
3167 {
3168   if (::munmap(this->base_, this->file_size_) < 0)
3169     gold_error(_("%s: munmap: %s"), this->name_, strerror(errno));
3170   this->base_ = NULL;
3171 }
3172
3173 // Close the output file.
3174
3175 void
3176 Output_file::close()
3177 {
3178   // If the map isn't file-backed, we need to write it now.
3179   if (this->map_is_anonymous_ && !this->is_temporary_)
3180     {
3181       size_t bytes_to_write = this->file_size_;
3182       while (bytes_to_write > 0)
3183         {
3184           ssize_t bytes_written = ::write(this->o_, this->base_, bytes_to_write);
3185           if (bytes_written == 0)
3186             gold_error(_("%s: write: unexpected 0 return-value"), this->name_);
3187           else if (bytes_written < 0)
3188             gold_error(_("%s: write: %s"), this->name_, strerror(errno));
3189           else
3190             bytes_to_write -= bytes_written;
3191         }
3192     }
3193   this->unmap();
3194
3195   // We don't close stdout or stderr
3196   if (this->o_ != STDOUT_FILENO
3197       && this->o_ != STDERR_FILENO
3198       && !this->is_temporary_)
3199     if (::close(this->o_) < 0)
3200       gold_error(_("%s: close: %s"), this->name_, strerror(errno));
3201   this->o_ = -1;
3202 }
3203
3204 // Instantiate the templates we need.  We could use the configure
3205 // script to restrict this to only the ones for implemented targets.
3206
3207 #ifdef HAVE_TARGET_32_LITTLE
3208 template
3209 off_t
3210 Output_section::add_input_section<32, false>(
3211     Sized_relobj<32, false>* object,
3212     unsigned int shndx,
3213     const char* secname,
3214     const elfcpp::Shdr<32, false>& shdr,
3215     unsigned int reloc_shndx,
3216     bool have_sections_script);
3217 #endif
3218
3219 #ifdef HAVE_TARGET_32_BIG
3220 template
3221 off_t
3222 Output_section::add_input_section<32, true>(
3223     Sized_relobj<32, true>* object,
3224     unsigned int shndx,
3225     const char* secname,
3226     const elfcpp::Shdr<32, true>& shdr,
3227     unsigned int reloc_shndx,
3228     bool have_sections_script);
3229 #endif
3230
3231 #ifdef HAVE_TARGET_64_LITTLE
3232 template
3233 off_t
3234 Output_section::add_input_section<64, false>(
3235     Sized_relobj<64, false>* object,
3236     unsigned int shndx,
3237     const char* secname,
3238     const elfcpp::Shdr<64, false>& shdr,
3239     unsigned int reloc_shndx,
3240     bool have_sections_script);
3241 #endif
3242
3243 #ifdef HAVE_TARGET_64_BIG
3244 template
3245 off_t
3246 Output_section::add_input_section<64, true>(
3247     Sized_relobj<64, true>* object,
3248     unsigned int shndx,
3249     const char* secname,
3250     const elfcpp::Shdr<64, true>& shdr,
3251     unsigned int reloc_shndx,
3252     bool have_sections_script);
3253 #endif
3254
3255 #ifdef HAVE_TARGET_32_LITTLE
3256 template
3257 class Output_data_reloc<elfcpp::SHT_REL, false, 32, false>;
3258 #endif
3259
3260 #ifdef HAVE_TARGET_32_BIG
3261 template
3262 class Output_data_reloc<elfcpp::SHT_REL, false, 32, true>;
3263 #endif
3264
3265 #ifdef HAVE_TARGET_64_LITTLE
3266 template
3267 class Output_data_reloc<elfcpp::SHT_REL, false, 64, false>;
3268 #endif
3269
3270 #ifdef HAVE_TARGET_64_BIG
3271 template
3272 class Output_data_reloc<elfcpp::SHT_REL, false, 64, true>;
3273 #endif
3274
3275 #ifdef HAVE_TARGET_32_LITTLE
3276 template
3277 class Output_data_reloc<elfcpp::SHT_REL, true, 32, false>;
3278 #endif
3279
3280 #ifdef HAVE_TARGET_32_BIG
3281 template
3282 class Output_data_reloc<elfcpp::SHT_REL, true, 32, true>;
3283 #endif
3284
3285 #ifdef HAVE_TARGET_64_LITTLE
3286 template
3287 class Output_data_reloc<elfcpp::SHT_REL, true, 64, false>;
3288 #endif
3289
3290 #ifdef HAVE_TARGET_64_BIG
3291 template
3292 class Output_data_reloc<elfcpp::SHT_REL, true, 64, true>;
3293 #endif
3294
3295 #ifdef HAVE_TARGET_32_LITTLE
3296 template
3297 class Output_data_reloc<elfcpp::SHT_RELA, false, 32, false>;
3298 #endif
3299
3300 #ifdef HAVE_TARGET_32_BIG
3301 template
3302 class Output_data_reloc<elfcpp::SHT_RELA, false, 32, true>;
3303 #endif
3304
3305 #ifdef HAVE_TARGET_64_LITTLE
3306 template
3307 class Output_data_reloc<elfcpp::SHT_RELA, false, 64, false>;
3308 #endif
3309
3310 #ifdef HAVE_TARGET_64_BIG
3311 template
3312 class Output_data_reloc<elfcpp::SHT_RELA, false, 64, true>;
3313 #endif
3314
3315 #ifdef HAVE_TARGET_32_LITTLE
3316 template
3317 class Output_data_reloc<elfcpp::SHT_RELA, true, 32, false>;
3318 #endif
3319
3320 #ifdef HAVE_TARGET_32_BIG
3321 template
3322 class Output_data_reloc<elfcpp::SHT_RELA, true, 32, true>;
3323 #endif
3324
3325 #ifdef HAVE_TARGET_64_LITTLE
3326 template
3327 class Output_data_reloc<elfcpp::SHT_RELA, true, 64, false>;
3328 #endif
3329
3330 #ifdef HAVE_TARGET_64_BIG
3331 template
3332 class Output_data_reloc<elfcpp::SHT_RELA, true, 64, true>;
3333 #endif
3334
3335 #ifdef HAVE_TARGET_32_LITTLE
3336 template
3337 class Output_relocatable_relocs<elfcpp::SHT_REL, 32, false>;
3338 #endif
3339
3340 #ifdef HAVE_TARGET_32_BIG
3341 template
3342 class Output_relocatable_relocs<elfcpp::SHT_REL, 32, true>;
3343 #endif
3344
3345 #ifdef HAVE_TARGET_64_LITTLE
3346 template
3347 class Output_relocatable_relocs<elfcpp::SHT_REL, 64, false>;
3348 #endif
3349
3350 #ifdef HAVE_TARGET_64_BIG
3351 template
3352 class Output_relocatable_relocs<elfcpp::SHT_REL, 64, true>;
3353 #endif
3354
3355 #ifdef HAVE_TARGET_32_LITTLE
3356 template
3357 class Output_relocatable_relocs<elfcpp::SHT_RELA, 32, false>;
3358 #endif
3359
3360 #ifdef HAVE_TARGET_32_BIG
3361 template
3362 class Output_relocatable_relocs<elfcpp::SHT_RELA, 32, true>;
3363 #endif
3364
3365 #ifdef HAVE_TARGET_64_LITTLE
3366 template
3367 class Output_relocatable_relocs<elfcpp::SHT_RELA, 64, false>;
3368 #endif
3369
3370 #ifdef HAVE_TARGET_64_BIG
3371 template
3372 class Output_relocatable_relocs<elfcpp::SHT_RELA, 64, true>;
3373 #endif
3374
3375 #ifdef HAVE_TARGET_32_LITTLE
3376 template
3377 class Output_data_group<32, false>;
3378 #endif
3379
3380 #ifdef HAVE_TARGET_32_BIG
3381 template
3382 class Output_data_group<32, true>;
3383 #endif
3384
3385 #ifdef HAVE_TARGET_64_LITTLE
3386 template
3387 class Output_data_group<64, false>;
3388 #endif
3389
3390 #ifdef HAVE_TARGET_64_BIG
3391 template
3392 class Output_data_group<64, true>;
3393 #endif
3394
3395 #ifdef HAVE_TARGET_32_LITTLE
3396 template
3397 class Output_data_got<32, false>;
3398 #endif
3399
3400 #ifdef HAVE_TARGET_32_BIG
3401 template
3402 class Output_data_got<32, true>;
3403 #endif
3404
3405 #ifdef HAVE_TARGET_64_LITTLE
3406 template
3407 class Output_data_got<64, false>;
3408 #endif
3409
3410 #ifdef HAVE_TARGET_64_BIG
3411 template
3412 class Output_data_got<64, true>;
3413 #endif
3414
3415 } // End namespace gold.