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