Snapshot. Includes first cut at output relocation sections.
[platform/upstream/binutils.git] / gold / output.cc
1 // output.cc -- manage the output file for gold
2
3 #include "gold.h"
4
5 #include <cstdlib>
6 #include <cerrno>
7 #include <fcntl.h>
8 #include <unistd.h>
9 #include <sys/mman.h>
10 #include <algorithm>
11
12 #include "object.h"
13 #include "symtab.h"
14 #include "reloc.h"
15 #include "output.h"
16
17 namespace gold
18 {
19
20 // Output_data methods.
21
22 Output_data::~Output_data()
23 {
24 }
25
26 // Set the address and offset.
27
28 void
29 Output_data::set_address(uint64_t addr, off_t off)
30 {
31   this->address_ = addr;
32   this->offset_ = off;
33
34   // Let the child class know.
35   this->do_set_address(addr, off);
36 }
37
38 // Return the default alignment for a size--32 or 64.
39
40 uint64_t
41 Output_data::default_alignment(int size)
42 {
43   if (size == 32)
44     return 4;
45   else if (size == 64)
46     return 8;
47   else
48     abort();
49 }
50
51 // Output_section_header methods.  This currently assumes that the
52 // segment and section lists are complete at construction time.
53
54 Output_section_headers::Output_section_headers(
55     int size,
56     bool big_endian,
57     const Layout::Segment_list& segment_list,
58     const Layout::Section_list& section_list,
59     const Stringpool* secnamepool)
60   : size_(size),
61     big_endian_(big_endian),
62     segment_list_(segment_list),
63     section_list_(section_list),
64     secnamepool_(secnamepool)
65 {
66   // Count all the sections.  Start with 1 for the null section.
67   off_t count = 1;
68   for (Layout::Segment_list::const_iterator p = segment_list.begin();
69        p != segment_list.end();
70        ++p)
71     if ((*p)->type() == elfcpp::PT_LOAD)
72       count += (*p)->output_section_count();
73   count += section_list.size();
74
75   int shdr_size;
76   if (size == 32)
77     shdr_size = elfcpp::Elf_sizes<32>::shdr_size;
78   else if (size == 64)
79     shdr_size = elfcpp::Elf_sizes<64>::shdr_size;
80   else
81     abort();
82
83   this->set_data_size(count * shdr_size);
84 }
85
86 // Write out the section headers.
87
88 void
89 Output_section_headers::do_write(Output_file* of)
90 {
91   if (this->size_ == 32)
92     {
93       if (this->big_endian_)
94         this->do_sized_write<32, true>(of);
95       else
96         this->do_sized_write<32, false>(of);
97     }
98   else if (this->size_ == 64)
99     {
100       if (this->big_endian_)
101         this->do_sized_write<64, true>(of);
102       else
103         this->do_sized_write<64, false>(of);
104     }
105   else
106     abort();
107 }
108
109 template<int size, bool big_endian>
110 void
111 Output_section_headers::do_sized_write(Output_file* of)
112 {
113   off_t all_shdrs_size = this->data_size();
114   unsigned char* view = of->get_output_view(this->offset(), all_shdrs_size);
115
116   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
117   unsigned char* v = view;
118
119   {
120     typename elfcpp::Shdr_write<size, big_endian> oshdr(v);
121     oshdr.put_sh_name(0);
122     oshdr.put_sh_type(elfcpp::SHT_NULL);
123     oshdr.put_sh_flags(0);
124     oshdr.put_sh_addr(0);
125     oshdr.put_sh_offset(0);
126     oshdr.put_sh_size(0);
127     oshdr.put_sh_link(0);
128     oshdr.put_sh_info(0);
129     oshdr.put_sh_addralign(0);
130     oshdr.put_sh_entsize(0);
131   }
132
133   v += shdr_size;
134
135   unsigned shndx = 1;
136   for (Layout::Segment_list::const_iterator p = this->segment_list_.begin();
137        p != this->segment_list_.end();
138        ++p)
139     v = (*p)->write_section_headers SELECT_SIZE_ENDIAN_NAME(size, big_endian) (
140             this->secnamepool_, v, &shndx
141             SELECT_SIZE_ENDIAN(size, big_endian));
142   for (Layout::Section_list::const_iterator p = this->section_list_.begin();
143        p != this->section_list_.end();
144        ++p)
145     {
146       assert(shndx == (*p)->out_shndx());
147       elfcpp::Shdr_write<size, big_endian> oshdr(v);
148       (*p)->write_header(this->secnamepool_, &oshdr);
149       v += shdr_size;
150       ++shndx;
151     }
152
153   of->write_output_view(this->offset(), all_shdrs_size, view);
154 }
155
156 // Output_segment_header methods.
157
158 Output_segment_headers::Output_segment_headers(
159     int size,
160     bool big_endian,
161     const Layout::Segment_list& segment_list)
162   : size_(size), big_endian_(big_endian), segment_list_(segment_list)
163 {
164   int phdr_size;
165   if (size == 32)
166     phdr_size = elfcpp::Elf_sizes<32>::phdr_size;
167   else if (size == 64)
168     phdr_size = elfcpp::Elf_sizes<64>::phdr_size;
169   else
170     abort();
171
172   this->set_data_size(segment_list.size() * phdr_size);
173 }
174
175 void
176 Output_segment_headers::do_write(Output_file* of)
177 {
178   if (this->size_ == 32)
179     {
180       if (this->big_endian_)
181         this->do_sized_write<32, true>(of);
182       else
183         this->do_sized_write<32, false>(of);
184     }
185   else if (this->size_ == 64)
186     {
187       if (this->big_endian_)
188         this->do_sized_write<64, true>(of);
189       else
190         this->do_sized_write<64, false>(of);
191     }
192   else
193     abort();
194 }
195
196 template<int size, bool big_endian>
197 void
198 Output_segment_headers::do_sized_write(Output_file* of)
199 {
200   const int phdr_size = elfcpp::Elf_sizes<size>::phdr_size;
201   off_t all_phdrs_size = this->segment_list_.size() * phdr_size;
202   unsigned char* view = of->get_output_view(this->offset(),
203                                             all_phdrs_size);
204   unsigned char* v = view;
205   for (Layout::Segment_list::const_iterator p = this->segment_list_.begin();
206        p != this->segment_list_.end();
207        ++p)
208     {
209       elfcpp::Phdr_write<size, big_endian> ophdr(v);
210       (*p)->write_header(&ophdr);
211       v += phdr_size;
212     }
213
214   of->write_output_view(this->offset(), all_phdrs_size, view);
215 }
216
217 // Output_file_header methods.
218
219 Output_file_header::Output_file_header(int size,
220                                        bool big_endian,
221                                        const General_options& options,
222                                        const Target* target,
223                                        const Symbol_table* symtab,
224                                        const Output_segment_headers* osh)
225   : size_(size),
226     big_endian_(big_endian),
227     options_(options),
228     target_(target),
229     symtab_(symtab),
230     segment_header_(osh),
231     section_header_(NULL),
232     shstrtab_(NULL)
233 {
234   int ehdr_size;
235   if (size == 32)
236     ehdr_size = elfcpp::Elf_sizes<32>::ehdr_size;
237   else if (size == 64)
238     ehdr_size = elfcpp::Elf_sizes<64>::ehdr_size;
239   else
240     abort();
241
242   this->set_data_size(ehdr_size);
243 }
244
245 // Set the section table information for a file header.
246
247 void
248 Output_file_header::set_section_info(const Output_section_headers* shdrs,
249                                      const Output_section* shstrtab)
250 {
251   this->section_header_ = shdrs;
252   this->shstrtab_ = shstrtab;
253 }
254
255 // Write out the file header.
256
257 void
258 Output_file_header::do_write(Output_file* of)
259 {
260   if (this->size_ == 32)
261     {
262       if (this->big_endian_)
263         this->do_sized_write<32, true>(of);
264       else
265         this->do_sized_write<32, false>(of);
266     }
267   else if (this->size_ == 64)
268     {
269       if (this->big_endian_)
270         this->do_sized_write<64, true>(of);
271       else
272         this->do_sized_write<64, false>(of);
273     }
274   else
275     abort();
276 }
277
278 // Write out the file header with appropriate size and endianess.
279
280 template<int size, bool big_endian>
281 void
282 Output_file_header::do_sized_write(Output_file* of)
283 {
284   assert(this->offset() == 0);
285
286   int ehdr_size = elfcpp::Elf_sizes<size>::ehdr_size;
287   unsigned char* view = of->get_output_view(0, ehdr_size);
288   elfcpp::Ehdr_write<size, big_endian> oehdr(view);
289
290   unsigned char e_ident[elfcpp::EI_NIDENT];
291   memset(e_ident, 0, elfcpp::EI_NIDENT);
292   e_ident[elfcpp::EI_MAG0] = elfcpp::ELFMAG0;
293   e_ident[elfcpp::EI_MAG1] = elfcpp::ELFMAG1;
294   e_ident[elfcpp::EI_MAG2] = elfcpp::ELFMAG2;
295   e_ident[elfcpp::EI_MAG3] = elfcpp::ELFMAG3;
296   if (size == 32)
297     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS32;
298   else if (size == 64)
299     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS64;
300   else
301     abort();
302   e_ident[elfcpp::EI_DATA] = (big_endian
303                               ? elfcpp::ELFDATA2MSB
304                               : elfcpp::ELFDATA2LSB);
305   e_ident[elfcpp::EI_VERSION] = elfcpp::EV_CURRENT;
306   // FIXME: Some targets may need to set EI_OSABI and EI_ABIVERSION.
307   oehdr.put_e_ident(e_ident);
308
309   elfcpp::ET e_type;
310   // FIXME: ET_DYN.
311   if (this->options_.is_relocatable())
312     e_type = elfcpp::ET_REL;
313   else
314     e_type = elfcpp::ET_EXEC;
315   oehdr.put_e_type(e_type);
316
317   oehdr.put_e_machine(this->target_->machine_code());
318   oehdr.put_e_version(elfcpp::EV_CURRENT);
319
320   // FIXME: Need to support -e, and target specific entry symbol.
321   Symbol* sym = this->symtab_->lookup("_start");
322   typename Sized_symbol<size>::Value_type v;
323   if (sym == NULL)
324     v = 0;
325   else
326     {
327       Sized_symbol<size>* ssym;
328       ssym = this->symtab_->get_sized_symbol SELECT_SIZE_NAME(size) (
329         sym SELECT_SIZE(size));
330       v = ssym->value();
331     }
332   oehdr.put_e_entry(v);
333
334   oehdr.put_e_phoff(this->segment_header_->offset());
335   oehdr.put_e_shoff(this->section_header_->offset());
336
337   // FIXME: The target needs to set the flags.
338   oehdr.put_e_flags(0);
339
340   oehdr.put_e_ehsize(elfcpp::Elf_sizes<size>::ehdr_size);
341   oehdr.put_e_phentsize(elfcpp::Elf_sizes<size>::phdr_size);
342   oehdr.put_e_phnum(this->segment_header_->data_size()
343                      / elfcpp::Elf_sizes<size>::phdr_size);
344   oehdr.put_e_shentsize(elfcpp::Elf_sizes<size>::shdr_size);
345   oehdr.put_e_shnum(this->section_header_->data_size()
346                      / elfcpp::Elf_sizes<size>::shdr_size);
347   oehdr.put_e_shstrndx(this->shstrtab_->out_shndx());
348
349   of->write_output_view(0, ehdr_size, view);
350 }
351
352 // Output_data_const methods.
353
354 void
355 Output_data_const::do_write(Output_file* output)
356 {
357   output->write(this->offset(), data_.data(), data_.size());
358 }
359
360 // Output_section_data methods.
361
362 unsigned int
363 Output_section_data::do_out_shndx() const
364 {
365   assert(this->output_section_ != NULL);
366   return this->output_section_->out_shndx();
367 }
368
369 // Output_reloc methods.
370
371 // Get the symbol index of a relocation.
372
373 template<bool dynamic, int size, bool big_endian>
374 unsigned int
375 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::get_symbol_index()
376   const
377 {
378   unsigned int index;
379   switch (this->local_sym_index_)
380     {
381     case INVALID_CODE:
382       abort();
383
384     case GSYM_CODE:
385       if (this->u_.gsym == NULL)
386         index = 0;
387       else if (dynamic)
388         index = this->u_.gsym->dynsym_index();
389       else
390         index = this->u_.gsym->symtab_index();
391       break;
392
393     case SECTION_CODE:
394       if (dynamic)
395         index = this->u_.os->dynsym_index();
396       else
397         index = this->u_.os->symtab_index();
398       break;
399
400     default:
401       if (dynamic)
402         {
403           // FIXME: It seems that some targets may need to generate
404           // dynamic relocations against local symbols for some
405           // reasons.  This will have to be addressed at some point.
406           abort();
407         }
408       else
409         index = this->u_.object->symtab_index(this->local_sym_index_);
410       break;
411     }
412   assert(index != -1U);
413   return index;
414 }
415
416 // Write out the offset and info fields of a Rel or Rela relocation
417 // entry.
418
419 template<bool dynamic, int size, bool big_endian>
420 template<typename Write_rel>
421 void
422 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::write_rel(
423     Write_rel* wr) const
424 {
425   wr->put_r_offset(this->address_);
426   wr->put_r_info(elfcpp::elf_r_info<size>(this->get_symbol_index(),
427                                           this->type_));
428 }
429
430 // Write out a Rel relocation.
431
432 template<bool dynamic, int size, bool big_endian>
433 void
434 Output_reloc<elfcpp::SHT_REL, dynamic, size, big_endian>::write(
435     unsigned char* pov) const
436 {
437   elfcpp::Rel_write<size, big_endian> orel(pov);
438   this->write_rel(&orel);
439 }
440
441 // Write out a Rela relocation.
442
443 template<bool dynamic, int size, bool big_endian>
444 void
445 Output_reloc<elfcpp::SHT_RELA, dynamic, size, big_endian>::write(
446     unsigned char* pov) const
447 {
448   elfcpp::Rela_write<size, big_endian> orel(pov);
449   this->rel_.write_rel(&orel);
450   orel.put_r_addend(this->addend_);
451 }
452
453 // Output_data_reloc_base methods.
454
455 // Write out relocation data.
456
457 template<int sh_type, bool dynamic, int size, bool big_endian>
458 void
459 Output_data_reloc_base<sh_type, dynamic, size, big_endian>::do_write(
460     Output_file* of)
461 {
462   const off_t off = this->offset();
463   const off_t oview_size = this->data_size();
464   unsigned char* const oview = of->get_output_view(off, oview_size);
465
466   unsigned char* pov = oview;
467   for (typename Relocs::const_iterator p = this->relocs_.begin();
468        p != this->relocs_.end();
469        ++p)
470     {
471       p->write(pov);
472       pov += reloc_size;
473     }
474
475   assert(pov - oview == oview_size);
476
477   of->write_output_view(off, oview_size, oview);
478
479   // We no longer need the relocation entries.
480   this->relocs_.clear();
481 }
482
483 // Output_data_got::Got_entry methods.
484
485 // Write out the entry.
486
487 template<int size, bool big_endian>
488 void
489 Output_data_got<size, big_endian>::Got_entry::write(unsigned char* pov)
490     const
491 {
492   Valtype val = 0;
493
494   switch (this->local_sym_index_)
495     {
496     case GSYM_CODE:
497       {
498         Symbol* gsym = this->u_.gsym;
499
500         // If the symbol is resolved locally, we need to write out its
501         // value.  Otherwise we just write zero.  The target code is
502         // responsible for creating a relocation entry to fill in the
503         // value at runtime.
504         if (gsym->is_resolved_locally())
505           {
506             Sized_symbol<size>* sgsym;
507             // This cast is a bit ugly.  We don't want to put a
508             // virtual method in Symbol, because we want Symbol to be
509             // as small as possible.
510             sgsym = static_cast<Sized_symbol<size>*>(gsym);
511             val = sgsym->value();
512           }
513       }
514       break;
515
516     case CONSTANT_CODE:
517       val = this->u_.constant;
518       break;
519
520     default:
521       abort();
522     }
523
524   Valtype* povv = reinterpret_cast<Valtype*>(pov);
525   elfcpp::Swap<size, big_endian>::writeval(povv, val);
526 }
527
528 // Output_data_got methods.
529
530 // Add an entry for a global symbol to the GOT.  This returns true if
531 // this is a new GOT entry, false if the symbol already had a GOT
532 // entry.
533
534 template<int size, bool big_endian>
535 bool
536 Output_data_got<size, big_endian>::add_global(Symbol* gsym)
537 {
538   if (gsym->has_got_offset())
539     return false;
540
541   this->entries_.push_back(Got_entry(gsym));
542   this->set_got_size();
543   gsym->set_got_offset(this->last_got_offset());
544   return true;
545 }
546
547 // Write out the GOT.
548
549 template<int size, bool big_endian>
550 void
551 Output_data_got<size, big_endian>::do_write(Output_file* of)
552 {
553   const int add = size / 8;
554
555   const off_t off = this->offset();
556   const off_t oview_size = this->data_size();
557   unsigned char* const oview = of->get_output_view(off, oview_size);
558
559   unsigned char* pov = oview;
560   for (typename Got_entries::const_iterator p = this->entries_.begin();
561        p != this->entries_.end();
562        ++p)
563     {
564       p->write(pov);
565       pov += add;
566     }
567
568   assert(pov - oview == oview_size);
569
570   of->write_output_view(off, oview_size, oview);
571
572   // We no longer need the GOT entries.
573   this->entries_.clear();
574 }
575
576 // Output_section::Input_section methods.
577
578 // Return the data size.  For an input section we store the size here.
579 // For an Output_section_data, we have to ask it for the size.
580
581 off_t
582 Output_section::Input_section::data_size() const
583 {
584   if (this->is_input_section())
585     return this->data_size_;
586   else
587     return this->u_.posd->data_size();
588 }
589
590 // Set the address and file offset.
591
592 void
593 Output_section::Input_section::set_address(uint64_t addr, off_t off,
594                                            off_t secoff)
595 {
596   if (this->is_input_section())
597     this->u_.object->set_section_offset(this->shndx_, off - secoff);
598   else
599     this->u_.posd->set_address(addr, off);
600 }
601
602 // Write out the data.  We don't have to do anything for an input
603 // section--they are handled via Object::relocate--but this is where
604 // we write out the data for an Output_section_data.
605
606 void
607 Output_section::Input_section::write(Output_file* of)
608 {
609   if (!this->is_input_section())
610     this->u_.posd->write(of);
611 }
612
613 // Output_section methods.
614
615 // Construct an Output_section.  NAME will point into a Stringpool.
616
617 Output_section::Output_section(const char* name, elfcpp::Elf_Word type,
618                                elfcpp::Elf_Xword flags, bool may_add_data)
619   : name_(name),
620     addralign_(0),
621     entsize_(0),
622     link_(0),
623     info_(0),
624     type_(type),
625     flags_(flags),
626     out_shndx_(0),
627     symtab_index_(0),
628     dynsym_index_(0),
629     input_sections_(),
630     first_input_offset_(0),
631     may_add_data_(may_add_data)
632 {
633 }
634
635 Output_section::~Output_section()
636 {
637 }
638
639 // Add the input section SHNDX, with header SHDR, named SECNAME, in
640 // OBJECT, to the Output_section.  Return the offset of the input
641 // section within the output section.  We don't always keep track of
642 // input sections for an Output_section.  Instead, each Object keeps
643 // track of the Output_section for each of its input sections.
644
645 template<int size, bool big_endian>
646 off_t
647 Output_section::add_input_section(Relobj* object, unsigned int shndx,
648                                   const char* secname,
649                                   const elfcpp::Shdr<size, big_endian>& shdr)
650 {
651   assert(this->may_add_data_);
652
653   elfcpp::Elf_Xword addralign = shdr.get_sh_addralign();
654   if ((addralign & (addralign - 1)) != 0)
655     {
656       fprintf(stderr, _("%s: %s: invalid alignment %lu for section \"%s\"\n"),
657               program_name, object->name().c_str(),
658               static_cast<unsigned long>(addralign), secname);
659       gold_exit(false);
660     }
661
662   if (addralign > this->addralign_)
663     this->addralign_ = addralign;
664
665   off_t ssize = this->data_size();
666   ssize = align_address(ssize, addralign);
667   this->set_data_size(ssize + shdr.get_sh_size());
668
669   // We need to keep track of this section if we are already keeping
670   // track of sections, or if we are relaxing.  FIXME: Add test for
671   // relaxing.
672   if (! this->input_sections_.empty())
673     this->input_sections_.push_back(Input_section(object, shndx,
674                                                   shdr.get_sh_size(),
675                                                   addralign));
676
677   return ssize;
678 }
679
680 // Add arbitrary data to an output section.
681
682 void
683 Output_section::add_output_section_data(Output_section_data* posd)
684 {
685   assert(this->may_add_data_);
686
687   if (this->input_sections_.empty())
688     this->first_input_offset_ = this->data_size();
689
690   this->input_sections_.push_back(Input_section(posd));
691
692   uint64_t addralign = posd->addralign();
693   if (addralign > this->addralign_)
694     this->addralign_ = addralign;
695
696   posd->set_output_section(this);
697 }
698
699 // Set the address of an Output_section.  This is where we handle
700 // setting the addresses of any Output_section_data objects.
701
702 void
703 Output_section::do_set_address(uint64_t address, off_t startoff)
704 {
705   if (this->input_sections_.empty())
706     return;
707
708   off_t off = startoff + this->first_input_offset_;
709   for (Input_section_list::iterator p = this->input_sections_.begin();
710        p != this->input_sections_.end();
711        ++p)
712     {
713       off = align_address(off, p->addralign());
714       p->set_address(address + (off - startoff), off, startoff);
715       off += p->data_size();
716     }
717
718   this->set_data_size(off - startoff);
719 }
720
721 // Write the section header to *OSHDR.
722
723 template<int size, bool big_endian>
724 void
725 Output_section::write_header(const Stringpool* secnamepool,
726                              elfcpp::Shdr_write<size, big_endian>* oshdr) const
727 {
728   oshdr->put_sh_name(secnamepool->get_offset(this->name_));
729   oshdr->put_sh_type(this->type_);
730   oshdr->put_sh_flags(this->flags_);
731   oshdr->put_sh_addr(this->address());
732   oshdr->put_sh_offset(this->offset());
733   oshdr->put_sh_size(this->data_size());
734   oshdr->put_sh_link(this->link_);
735   oshdr->put_sh_info(this->info_);
736   oshdr->put_sh_addralign(this->addralign_);
737   oshdr->put_sh_entsize(this->entsize_);
738 }
739
740 // Write out the data.  For input sections the data is written out by
741 // Object::relocate, but we have to handle Output_section_data objects
742 // here.
743
744 void
745 Output_section::do_write(Output_file* of)
746 {
747   for (Input_section_list::iterator p = this->input_sections_.begin();
748        p != this->input_sections_.end();
749        ++p)
750     p->write(of);
751 }
752
753 // Output_section_strtab methods.
754
755 Output_section_strtab::Output_section_strtab(const char* name,
756                                              Stringpool* contents)
757   : Output_section(name, elfcpp::SHT_STRTAB, 0, false),
758     contents_(contents)
759 {
760   this->set_data_size(contents->get_strtab_size());
761 }
762
763 void
764 Output_section_strtab::do_write(Output_file* of)
765 {
766   this->contents_->write(of, this->offset());
767 }
768
769 // Output segment methods.
770
771 Output_segment::Output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
772   : output_data_(),
773     output_bss_(),
774     vaddr_(0),
775     paddr_(0),
776     memsz_(0),
777     align_(0),
778     offset_(0),
779     filesz_(0),
780     type_(type),
781     flags_(flags),
782     is_align_known_(false)
783 {
784 }
785
786 // Add an Output_section to an Output_segment.
787
788 void
789 Output_segment::add_output_section(Output_section* os,
790                                    elfcpp::Elf_Word seg_flags,
791                                    bool front)
792 {
793   assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
794   assert(!this->is_align_known_);
795
796   // Update the segment flags.
797   this->flags_ |= seg_flags;
798
799   Output_segment::Output_data_list* pdl;
800   if (os->type() == elfcpp::SHT_NOBITS)
801     pdl = &this->output_bss_;
802   else
803     pdl = &this->output_data_;
804
805   // So that PT_NOTE segments will work correctly, we need to ensure
806   // that all SHT_NOTE sections are adjacent.  This will normally
807   // happen automatically, because all the SHT_NOTE input sections
808   // will wind up in the same output section.  However, it is possible
809   // for multiple SHT_NOTE input sections to have different section
810   // flags, and thus be in different output sections, but for the
811   // different section flags to map into the same segment flags and
812   // thus the same output segment.
813
814   // Note that while there may be many input sections in an output
815   // section, there are normally only a few output sections in an
816   // output segment.  This loop is expected to be fast.
817
818   if (os->type() == elfcpp::SHT_NOTE && !pdl->empty())
819     {
820       Layout::Data_list::iterator p = pdl->end();
821       do
822         {
823           --p;
824           if ((*p)->is_section_type(elfcpp::SHT_NOTE))
825             {
826               // We don't worry about the FRONT parameter.
827               ++p;
828               pdl->insert(p, os);
829               return;
830             }
831         }
832       while (p != pdl->begin());
833     }
834
835   // Similarly, so that PT_TLS segments will work, we need to group
836   // SHF_TLS sections.  An SHF_TLS/SHT_NOBITS section is a special
837   // case: we group the SHF_TLS/SHT_NOBITS sections right after the
838   // SHF_TLS/SHT_PROGBITS sections.  This lets us set up PT_TLS
839   // correctly.
840   if ((os->flags() & elfcpp::SHF_TLS) != 0 && !this->output_data_.empty())
841     {
842       pdl = &this->output_data_;
843       bool nobits = os->type() == elfcpp::SHT_NOBITS;
844       bool sawtls = false;
845       Layout::Data_list::iterator p = pdl->end();
846       do
847         {
848           --p;
849           bool insert;
850           if ((*p)->is_section_flag_set(elfcpp::SHF_TLS))
851             {
852               sawtls = true;
853               // Put a NOBITS section after the first TLS section.
854               // But a PROGBITS section after the first TLS/PROGBITS
855               // section.
856               insert = nobits || !(*p)->is_section_type(elfcpp::SHT_NOBITS);
857             }
858           else
859             {
860               // If we've gone past the TLS sections, but we've seen a
861               // TLS section, then we need to insert this section now.
862               insert = sawtls;
863             }
864
865           if (insert)
866             {
867               // We don't worry about the FRONT parameter.
868               ++p;
869               pdl->insert(p, os);
870               return;
871             }
872         }
873       while (p != pdl->begin());
874
875       // There are no TLS sections yet; put this one at the requested
876       // location in the section list.
877     }
878
879   if (front)
880     pdl->push_front(os);
881   else
882     pdl->push_back(os);
883 }
884
885 // Add an Output_data (which is not an Output_section) to the start of
886 // a segment.
887
888 void
889 Output_segment::add_initial_output_data(Output_data* od)
890 {
891   assert(!this->is_align_known_);
892   this->output_data_.push_front(od);
893 }
894
895 // Return the maximum alignment of the Output_data in Output_segment.
896 // Once we compute this, we prohibit new sections from being added.
897
898 uint64_t
899 Output_segment::addralign()
900 {
901   if (!this->is_align_known_)
902     {
903       uint64_t addralign;
904
905       addralign = Output_segment::maximum_alignment(&this->output_data_);
906       if (addralign > this->align_)
907         this->align_ = addralign;
908
909       addralign = Output_segment::maximum_alignment(&this->output_bss_);
910       if (addralign > this->align_)
911         this->align_ = addralign;
912
913       this->is_align_known_ = true;
914     }
915
916   return this->align_;
917 }
918
919 // Return the maximum alignment of a list of Output_data.
920
921 uint64_t
922 Output_segment::maximum_alignment(const Output_data_list* pdl)
923 {
924   uint64_t ret = 0;
925   for (Output_data_list::const_iterator p = pdl->begin();
926        p != pdl->end();
927        ++p)
928     {
929       uint64_t addralign = (*p)->addralign();
930       if (addralign > ret)
931         ret = addralign;
932     }
933   return ret;
934 }
935
936 // Set the section addresses for an Output_segment.  ADDR is the
937 // address and *POFF is the file offset.  Set the section indexes
938 // starting with *PSHNDX.  Return the address of the immediately
939 // following segment.  Update *POFF and *PSHNDX.
940
941 uint64_t
942 Output_segment::set_section_addresses(uint64_t addr, off_t* poff,
943                                       unsigned int* pshndx)
944 {
945   assert(this->type_ == elfcpp::PT_LOAD);
946
947   this->vaddr_ = addr;
948   this->paddr_ = addr;
949
950   off_t orig_off = *poff;
951   this->offset_ = orig_off;
952
953   *poff = align_address(*poff, this->addralign());
954
955   addr = this->set_section_list_addresses(&this->output_data_, addr, poff,
956                                           pshndx);
957   this->filesz_ = *poff - orig_off;
958
959   off_t off = *poff;
960
961   uint64_t ret = this->set_section_list_addresses(&this->output_bss_, addr,
962                                                   poff, pshndx);
963   this->memsz_ = *poff - orig_off;
964
965   // Ignore the file offset adjustments made by the BSS Output_data
966   // objects.
967   *poff = off;
968
969   return ret;
970 }
971
972 // Set the addresses in a list of Output_data structures.
973
974 uint64_t
975 Output_segment::set_section_list_addresses(Output_data_list* pdl,
976                                            uint64_t addr, off_t* poff,
977                                            unsigned int* pshndx)
978 {
979   off_t startoff = *poff;
980
981   off_t off = startoff;
982   for (Output_data_list::iterator p = pdl->begin();
983        p != pdl->end();
984        ++p)
985     {
986       off = align_address(off, (*p)->addralign());
987       (*p)->set_address(addr + (off - startoff), off);
988
989       // Unless this is a PT_TLS segment, we want to ignore the size
990       // of a SHF_TLS/SHT_NOBITS section.  Such a section does not
991       // affect the size of a PT_LOAD segment.
992       if (this->type_ == elfcpp::PT_TLS
993           || !(*p)->is_section_flag_set(elfcpp::SHF_TLS)
994           || !(*p)->is_section_type(elfcpp::SHT_NOBITS))
995         off += (*p)->data_size();
996
997       if ((*p)->is_section())
998         {
999           (*p)->set_out_shndx(*pshndx);
1000           ++*pshndx;
1001         }
1002     }
1003
1004   *poff = off;
1005   return addr + (off - startoff);
1006 }
1007
1008 // For a non-PT_LOAD segment, set the offset from the sections, if
1009 // any.
1010
1011 void
1012 Output_segment::set_offset()
1013 {
1014   assert(this->type_ != elfcpp::PT_LOAD);
1015
1016   if (this->output_data_.empty() && this->output_bss_.empty())
1017     {
1018       this->vaddr_ = 0;
1019       this->paddr_ = 0;
1020       this->memsz_ = 0;
1021       this->align_ = 0;
1022       this->offset_ = 0;
1023       this->filesz_ = 0;
1024       return;
1025     }
1026
1027   const Output_data* first;
1028   if (this->output_data_.empty())
1029     first = this->output_bss_.front();
1030   else
1031     first = this->output_data_.front();
1032   this->vaddr_ = first->address();
1033   this->paddr_ = this->vaddr_;
1034   this->offset_ = first->offset();
1035
1036   if (this->output_data_.empty())
1037     this->filesz_ = 0;
1038   else
1039     {
1040       const Output_data* last_data = this->output_data_.back();
1041       this->filesz_ = (last_data->address()
1042                        + last_data->data_size()
1043                        - this->vaddr_);
1044     }
1045
1046   const Output_data* last;
1047   if (this->output_bss_.empty())
1048     last = this->output_data_.back();
1049   else
1050     last = this->output_bss_.back();
1051   this->memsz_ = (last->address()
1052                   + last->data_size()
1053                   - this->vaddr_);
1054 }
1055
1056 // Return the number of Output_sections in an Output_segment.
1057
1058 unsigned int
1059 Output_segment::output_section_count() const
1060 {
1061   return (this->output_section_count_list(&this->output_data_)
1062           + this->output_section_count_list(&this->output_bss_));
1063 }
1064
1065 // Return the number of Output_sections in an Output_data_list.
1066
1067 unsigned int
1068 Output_segment::output_section_count_list(const Output_data_list* pdl) const
1069 {
1070   unsigned int count = 0;
1071   for (Output_data_list::const_iterator p = pdl->begin();
1072        p != pdl->end();
1073        ++p)
1074     {
1075       if ((*p)->is_section())
1076         ++count;
1077     }
1078   return count;
1079 }
1080
1081 // Write the segment data into *OPHDR.
1082
1083 template<int size, bool big_endian>
1084 void
1085 Output_segment::write_header(elfcpp::Phdr_write<size, big_endian>* ophdr)
1086 {
1087   ophdr->put_p_type(this->type_);
1088   ophdr->put_p_offset(this->offset_);
1089   ophdr->put_p_vaddr(this->vaddr_);
1090   ophdr->put_p_paddr(this->paddr_);
1091   ophdr->put_p_filesz(this->filesz_);
1092   ophdr->put_p_memsz(this->memsz_);
1093   ophdr->put_p_flags(this->flags_);
1094   ophdr->put_p_align(this->addralign());
1095 }
1096
1097 // Write the section headers into V.
1098
1099 template<int size, bool big_endian>
1100 unsigned char*
1101 Output_segment::write_section_headers(const Stringpool* secnamepool,
1102                                       unsigned char* v,
1103                                       unsigned int *pshndx
1104                                       ACCEPT_SIZE_ENDIAN) const
1105 {
1106   // Every section that is attached to a segment must be attached to a
1107   // PT_LOAD segment, so we only write out section headers for PT_LOAD
1108   // segments.
1109   if (this->type_ != elfcpp::PT_LOAD)
1110     return v;
1111
1112   v = this->write_section_headers_list
1113       SELECT_SIZE_ENDIAN_NAME(size, big_endian) (
1114           secnamepool, &this->output_data_, v, pshndx
1115           SELECT_SIZE_ENDIAN(size, big_endian));
1116   v = this->write_section_headers_list
1117       SELECT_SIZE_ENDIAN_NAME(size, big_endian) (
1118           secnamepool, &this->output_bss_, v, pshndx
1119           SELECT_SIZE_ENDIAN(size, big_endian));
1120   return v;
1121 }
1122
1123 template<int size, bool big_endian>
1124 unsigned char*
1125 Output_segment::write_section_headers_list(const Stringpool* secnamepool,
1126                                            const Output_data_list* pdl,
1127                                            unsigned char* v,
1128                                            unsigned int* pshndx
1129                                            ACCEPT_SIZE_ENDIAN) const
1130 {
1131   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
1132   for (Output_data_list::const_iterator p = pdl->begin();
1133        p != pdl->end();
1134        ++p)
1135     {
1136       if ((*p)->is_section())
1137         {
1138           const Output_section* ps = static_cast<const Output_section*>(*p);
1139           assert(*pshndx == ps->out_shndx());
1140           elfcpp::Shdr_write<size, big_endian> oshdr(v);
1141           ps->write_header(secnamepool, &oshdr);
1142           v += shdr_size;
1143           ++*pshndx;
1144         }
1145     }
1146   return v;
1147 }
1148
1149 // Output_file methods.
1150
1151 Output_file::Output_file(const General_options& options)
1152   : options_(options),
1153     name_(options.output_file_name()),
1154     o_(-1),
1155     file_size_(0),
1156     base_(NULL)
1157 {
1158 }
1159
1160 // Open the output file.
1161
1162 void
1163 Output_file::open(off_t file_size)
1164 {
1165   this->file_size_ = file_size;
1166
1167   int mode = this->options_.is_relocatable() ? 0666 : 0777;
1168   int o = ::open(this->name_, O_RDWR | O_CREAT | O_TRUNC, mode);
1169   if (o < 0)
1170     {
1171       fprintf(stderr, _("%s: %s: open: %s\n"),
1172               program_name, this->name_, strerror(errno));
1173       gold_exit(false);
1174     }
1175   this->o_ = o;
1176
1177   // Write out one byte to make the file the right size.
1178   if (::lseek(o, file_size - 1, SEEK_SET) < 0)
1179     {
1180       fprintf(stderr, _("%s: %s: lseek: %s\n"),
1181               program_name, this->name_, strerror(errno));
1182       gold_exit(false);
1183     }
1184   char b = 0;
1185   if (::write(o, &b, 1) != 1)
1186     {
1187       fprintf(stderr, _("%s: %s: write: %s\n"),
1188               program_name, this->name_, strerror(errno));
1189       gold_exit(false);
1190     }
1191
1192   // Map the file into memory.
1193   void* base = ::mmap(NULL, file_size, PROT_READ | PROT_WRITE,
1194                       MAP_SHARED, o, 0);
1195   if (base == MAP_FAILED)
1196     {
1197       fprintf(stderr, _("%s: %s: mmap: %s\n"),
1198               program_name, this->name_, strerror(errno));
1199       gold_exit(false);
1200     }
1201   this->base_ = static_cast<unsigned char*>(base);
1202 }
1203
1204 // Close the output file.
1205
1206 void
1207 Output_file::close()
1208 {
1209   if (::munmap(this->base_, this->file_size_) < 0)
1210     {
1211       fprintf(stderr, _("%s: %s: munmap: %s\n"),
1212               program_name, this->name_, strerror(errno));
1213       gold_exit(false);
1214     }
1215   this->base_ = NULL;
1216
1217   if (::close(this->o_) < 0)
1218     {
1219       fprintf(stderr, _("%s: %s: close: %s\n"),
1220               program_name, this->name_, strerror(errno));
1221       gold_exit(false);
1222     }
1223   this->o_ = -1;
1224 }
1225
1226 // Instantiate the templates we need.  We could use the configure
1227 // script to restrict this to only the ones for implemented targets.
1228
1229 template
1230 off_t
1231 Output_section::add_input_section<32, false>(
1232     Relobj* object,
1233     unsigned int shndx,
1234     const char* secname,
1235     const elfcpp::Shdr<32, false>& shdr);
1236
1237 template
1238 off_t
1239 Output_section::add_input_section<32, true>(
1240     Relobj* object,
1241     unsigned int shndx,
1242     const char* secname,
1243     const elfcpp::Shdr<32, true>& shdr);
1244
1245 template
1246 off_t
1247 Output_section::add_input_section<64, false>(
1248     Relobj* object,
1249     unsigned int shndx,
1250     const char* secname,
1251     const elfcpp::Shdr<64, false>& shdr);
1252
1253 template
1254 off_t
1255 Output_section::add_input_section<64, true>(
1256     Relobj* object,
1257     unsigned int shndx,
1258     const char* secname,
1259     const elfcpp::Shdr<64, true>& shdr);
1260
1261 template
1262 class Output_data_reloc<elfcpp::SHT_REL, false, 32, false>;
1263
1264 template
1265 class Output_data_reloc<elfcpp::SHT_REL, false, 32, true>;
1266
1267 template
1268 class Output_data_reloc<elfcpp::SHT_REL, false, 64, false>;
1269
1270 template
1271 class Output_data_reloc<elfcpp::SHT_REL, false, 64, true>;
1272
1273 template
1274 class Output_data_reloc<elfcpp::SHT_REL, true, 32, false>;
1275
1276 template
1277 class Output_data_reloc<elfcpp::SHT_REL, true, 32, true>;
1278
1279 template
1280 class Output_data_reloc<elfcpp::SHT_REL, true, 64, false>;
1281
1282 template
1283 class Output_data_reloc<elfcpp::SHT_REL, true, 64, true>;
1284
1285 template
1286 class Output_data_reloc<elfcpp::SHT_RELA, false, 32, false>;
1287
1288 template
1289 class Output_data_reloc<elfcpp::SHT_RELA, false, 32, true>;
1290
1291 template
1292 class Output_data_reloc<elfcpp::SHT_RELA, false, 64, false>;
1293
1294 template
1295 class Output_data_reloc<elfcpp::SHT_RELA, false, 64, true>;
1296
1297 template
1298 class Output_data_reloc<elfcpp::SHT_RELA, true, 32, false>;
1299
1300 template
1301 class Output_data_reloc<elfcpp::SHT_RELA, true, 32, true>;
1302
1303 template
1304 class Output_data_reloc<elfcpp::SHT_RELA, true, 64, false>;
1305
1306 template
1307 class Output_data_reloc<elfcpp::SHT_RELA, true, 64, true>;
1308
1309 template
1310 class Output_data_got<32, false>;
1311
1312 template
1313 class Output_data_got<32, true>;
1314
1315 template
1316 class Output_data_got<64, false>;
1317
1318 template
1319 class Output_data_got<64, true>;
1320
1321 } // End namespace gold.