Can now dynamically link hello, world.
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 #include "gold.h"
4
5 #include <cstring>
6 #include <algorithm>
7 #include <iostream>
8 #include <utility>
9
10 #include "output.h"
11 #include "symtab.h"
12 #include "dynobj.h"
13 #include "layout.h"
14
15 namespace gold
16 {
17
18 // Layout_task_runner methods.
19
20 // Lay out the sections.  This is called after all the input objects
21 // have been read.
22
23 void
24 Layout_task_runner::run(Workqueue* workqueue)
25 {
26   off_t file_size = this->layout_->finalize(this->input_objects_,
27                                             this->symtab_);
28
29   // Now we know the final size of the output file and we know where
30   // each piece of information goes.
31   Output_file* of = new Output_file(this->options_);
32   of->open(file_size);
33
34   // Queue up the final set of tasks.
35   gold::queue_final_tasks(this->options_, this->input_objects_,
36                           this->symtab_, this->layout_, workqueue, of);
37 }
38
39 // Layout methods.
40
41 Layout::Layout(const General_options& options)
42   : options_(options), namepool_(), sympool_(), dynpool_(), signatures_(),
43     section_name_map_(), segment_list_(), section_list_(),
44     unattached_section_list_(), special_output_list_(),
45     tls_segment_(NULL), symtab_section_(NULL), dynsym_section_(NULL),
46     dynamic_section_(NULL), dynamic_data_(NULL)
47 {
48   // Make space for more than enough segments for a typical file.
49   // This is just for efficiency--it's OK if we wind up needing more.
50   this->segment_list_.reserve(12);
51
52   // We expect three unattached Output_data objects: the file header,
53   // the segment headers, and the section headers.
54   this->special_output_list_.reserve(3);
55 }
56
57 // Hash a key we use to look up an output section mapping.
58
59 size_t
60 Layout::Hash_key::operator()(const Layout::Key& k) const
61 {
62  return k.first + k.second.first + k.second.second;
63 }
64
65 // Whether to include this section in the link.
66
67 template<int size, bool big_endian>
68 bool
69 Layout::include_section(Object*, const char*,
70                         const elfcpp::Shdr<size, big_endian>& shdr)
71 {
72   // Some section types are never linked.  Some are only linked when
73   // doing a relocateable link.
74   switch (shdr.get_sh_type())
75     {
76     case elfcpp::SHT_NULL:
77     case elfcpp::SHT_SYMTAB:
78     case elfcpp::SHT_DYNSYM:
79     case elfcpp::SHT_STRTAB:
80     case elfcpp::SHT_HASH:
81     case elfcpp::SHT_DYNAMIC:
82     case elfcpp::SHT_SYMTAB_SHNDX:
83       return false;
84
85     case elfcpp::SHT_RELA:
86     case elfcpp::SHT_REL:
87     case elfcpp::SHT_GROUP:
88       return this->options_.is_relocatable();
89
90     default:
91       // FIXME: Handle stripping debug sections here.
92       return true;
93     }
94 }
95
96 // Return an output section named NAME, or NULL if there is none.
97
98 Output_section*
99 Layout::find_output_section(const char* name) const
100 {
101   for (Section_name_map::const_iterator p = this->section_name_map_.begin();
102        p != this->section_name_map_.end();
103        ++p)
104     if (strcmp(p->second->name(), name) == 0)
105       return p->second;
106   return NULL;
107 }
108
109 // Return an output segment of type TYPE, with segment flags SET set
110 // and segment flags CLEAR clear.  Return NULL if there is none.
111
112 Output_segment*
113 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
114                             elfcpp::Elf_Word clear) const
115 {
116   for (Segment_list::const_iterator p = this->segment_list_.begin();
117        p != this->segment_list_.end();
118        ++p)
119     if (static_cast<elfcpp::PT>((*p)->type()) == type
120         && ((*p)->flags() & set) == set
121         && ((*p)->flags() & clear) == 0)
122       return *p;
123   return NULL;
124 }
125
126 // Return the output section to use for section NAME with type TYPE
127 // and section flags FLAGS.
128
129 Output_section*
130 Layout::get_output_section(const char* name, Stringpool::Key name_key,
131                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
132 {
133   // We should ignore some flags.
134   flags &= ~ (elfcpp::SHF_INFO_LINK
135               | elfcpp::SHF_LINK_ORDER
136               | elfcpp::SHF_GROUP);
137
138   const Key key(name_key, std::make_pair(type, flags));
139   const std::pair<Key, Output_section*> v(key, NULL);
140   std::pair<Section_name_map::iterator, bool> ins(
141     this->section_name_map_.insert(v));
142
143   if (!ins.second)
144     return ins.first->second;
145   else
146     {
147       // This is the first time we've seen this name/type/flags
148       // combination.
149       Output_section* os = this->make_output_section(name, type, flags);
150       ins.first->second = os;
151       return os;
152     }
153 }
154
155 // Return the output section to use for input section SHNDX, with name
156 // NAME, with header HEADER, from object OBJECT.  Set *OFF to the
157 // offset of this input section without the output section.
158
159 template<int size, bool big_endian>
160 Output_section*
161 Layout::layout(Relobj* object, unsigned int shndx, const char* name,
162                const elfcpp::Shdr<size, big_endian>& shdr, off_t* off)
163 {
164   if (!this->include_section(object, name, shdr))
165     return NULL;
166
167   // If we are not doing a relocateable link, choose the name to use
168   // for the output section.
169   size_t len = strlen(name);
170   if (!this->options_.is_relocatable())
171     name = Layout::output_section_name(name, &len);
172
173   // FIXME: Handle SHF_OS_NONCONFORMING here.
174
175   // Canonicalize the section name.
176   Stringpool::Key name_key;
177   name = this->namepool_.add(name, len, &name_key);
178
179   // Find the output section.  The output section is selected based on
180   // the section name, type, and flags.
181   Output_section* os = this->get_output_section(name, name_key,
182                                                 shdr.get_sh_type(),
183                                                 shdr.get_sh_flags());
184
185   // FIXME: Handle SHF_LINK_ORDER somewhere.
186
187   *off = os->add_input_section(object, shndx, name, shdr);
188
189   return os;
190 }
191
192 // Add POSD to an output section using NAME, TYPE, and FLAGS.
193
194 void
195 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
196                                 elfcpp::Elf_Xword flags,
197                                 Output_section_data* posd)
198 {
199   // Canonicalize the name.
200   Stringpool::Key name_key;
201   name = this->namepool_.add(name, &name_key);
202
203   Output_section* os = this->get_output_section(name, name_key, type, flags);
204   os->add_output_section_data(posd);
205 }
206
207 // Map section flags to segment flags.
208
209 elfcpp::Elf_Word
210 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
211 {
212   elfcpp::Elf_Word ret = elfcpp::PF_R;
213   if ((flags & elfcpp::SHF_WRITE) != 0)
214     ret |= elfcpp::PF_W;
215   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
216     ret |= elfcpp::PF_X;
217   return ret;
218 }
219
220 // Make a new Output_section, and attach it to segments as
221 // appropriate.
222
223 Output_section*
224 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
225                             elfcpp::Elf_Xword flags)
226 {
227   Output_section* os = new Output_section(name, type, flags, true);
228   this->section_list_.push_back(os);
229
230   if ((flags & elfcpp::SHF_ALLOC) == 0)
231     this->unattached_section_list_.push_back(os);
232   else
233     {
234       // This output section goes into a PT_LOAD segment.
235
236       elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
237
238       // The only thing we really care about for PT_LOAD segments is
239       // whether or not they are writable, so that is how we search
240       // for them.  People who need segments sorted on some other
241       // basis will have to wait until we implement a mechanism for
242       // them to describe the segments they want.
243
244       Segment_list::const_iterator p;
245       for (p = this->segment_list_.begin();
246            p != this->segment_list_.end();
247            ++p)
248         {
249           if ((*p)->type() == elfcpp::PT_LOAD
250               && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
251             {
252               (*p)->add_output_section(os, seg_flags);
253               break;
254             }
255         }
256
257       if (p == this->segment_list_.end())
258         {
259           Output_segment* oseg = new Output_segment(elfcpp::PT_LOAD,
260                                                     seg_flags);
261           this->segment_list_.push_back(oseg);
262           oseg->add_output_section(os, seg_flags);
263         }
264
265       // If we see a loadable SHT_NOTE section, we create a PT_NOTE
266       // segment.
267       if (type == elfcpp::SHT_NOTE)
268         {
269           // See if we already have an equivalent PT_NOTE segment.
270           for (p = this->segment_list_.begin();
271                p != segment_list_.end();
272                ++p)
273             {
274               if ((*p)->type() == elfcpp::PT_NOTE
275                   && (((*p)->flags() & elfcpp::PF_W)
276                       == (seg_flags & elfcpp::PF_W)))
277                 {
278                   (*p)->add_output_section(os, seg_flags);
279                   break;
280                 }
281             }
282
283           if (p == this->segment_list_.end())
284             {
285               Output_segment* oseg = new Output_segment(elfcpp::PT_NOTE,
286                                                         seg_flags);
287               this->segment_list_.push_back(oseg);
288               oseg->add_output_section(os, seg_flags);
289             }
290         }
291
292       // If we see a loadable SHF_TLS section, we create a PT_TLS
293       // segment.  There can only be one such segment.
294       if ((flags & elfcpp::SHF_TLS) != 0)
295         {
296           if (this->tls_segment_ == NULL)
297             {
298               this->tls_segment_ = new Output_segment(elfcpp::PT_TLS,
299                                                       seg_flags);
300               this->segment_list_.push_back(this->tls_segment_);
301             }
302           this->tls_segment_->add_output_section(os, seg_flags);
303         }
304     }
305
306   return os;
307 }
308
309 // Create the dynamic sections which are needed before we read the
310 // relocs.
311
312 void
313 Layout::create_initial_dynamic_sections(const Input_objects* input_objects,
314                                         Symbol_table* symtab)
315 {
316   if (!input_objects->any_dynamic())
317     return;
318
319   const char* dynamic_name = this->namepool_.add(".dynamic", NULL);
320   this->dynamic_section_ = this->make_output_section(dynamic_name,
321                                                      elfcpp::SHT_DYNAMIC,
322                                                      (elfcpp::SHF_ALLOC
323                                                       | elfcpp::SHF_WRITE));
324
325   symtab->define_in_output_data(input_objects->target(), "_DYNAMIC",
326                                 this->dynamic_section_, 0, 0,
327                                 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
328                                 elfcpp::STV_HIDDEN, 0, false, false);
329
330   this->dynamic_data_ =  new Output_data_dynamic(input_objects->target(),
331                                                  &this->dynpool_);
332
333   this->dynamic_section_->add_output_section_data(this->dynamic_data_);
334 }
335
336 // Find the first read-only PT_LOAD segment, creating one if
337 // necessary.
338
339 Output_segment*
340 Layout::find_first_load_seg()
341 {
342   for (Segment_list::const_iterator p = this->segment_list_.begin();
343        p != this->segment_list_.end();
344        ++p)
345     {
346       if ((*p)->type() == elfcpp::PT_LOAD
347           && ((*p)->flags() & elfcpp::PF_R) != 0
348           && ((*p)->flags() & elfcpp::PF_W) == 0)
349         return *p;
350     }
351
352   Output_segment* load_seg = new Output_segment(elfcpp::PT_LOAD, elfcpp::PF_R);
353   this->segment_list_.push_back(load_seg);
354   return load_seg;
355 }
356
357 // Finalize the layout.  When this is called, we have created all the
358 // output sections and all the output segments which are based on
359 // input sections.  We have several things to do, and we have to do
360 // them in the right order, so that we get the right results correctly
361 // and efficiently.
362
363 // 1) Finalize the list of output segments and create the segment
364 // table header.
365
366 // 2) Finalize the dynamic symbol table and associated sections.
367
368 // 3) Determine the final file offset of all the output segments.
369
370 // 4) Determine the final file offset of all the SHF_ALLOC output
371 // sections.
372
373 // 5) Create the symbol table sections and the section name table
374 // section.
375
376 // 6) Finalize the symbol table: set symbol values to their final
377 // value and make a final determination of which symbols are going
378 // into the output symbol table.
379
380 // 7) Create the section table header.
381
382 // 8) Determine the final file offset of all the output sections which
383 // are not SHF_ALLOC, including the section table header.
384
385 // 9) Finalize the ELF file header.
386
387 // This function returns the size of the output file.
388
389 off_t
390 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab)
391 {
392   Target* const target = input_objects->target();
393   const int size = target->get_size();
394
395   target->finalize_sections(&this->options_, this);
396
397   Output_segment* phdr_seg = NULL;
398   if (input_objects->any_dynamic())
399     {
400       // There was a dynamic object in the link.  We need to create
401       // some information for the dynamic linker.
402
403       // Create the PT_PHDR segment which will hold the program
404       // headers.
405       phdr_seg = new Output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
406       this->segment_list_.push_back(phdr_seg);
407
408       // Create the dynamic symbol table, including the hash table,
409       // the dynamic relocations, and the version sections.
410       this->create_dynamic_symtab(target, symtab);
411
412       // Create the .interp section to hold the name of the
413       // interpreter, and put it in a PT_INTERP segment.
414       this->create_interp(target);
415
416       // Finish the .dynamic section to hold the dynamic data, and put
417       // it in a PT_DYNAMIC segment.
418       this->finish_dynamic_section(input_objects, symtab);
419     }
420
421   // FIXME: Handle PT_GNU_STACK.
422
423   Output_segment* load_seg = this->find_first_load_seg();
424
425   // Lay out the segment headers.
426   bool big_endian = target->is_big_endian();
427   Output_segment_headers* segment_headers;
428   segment_headers = new Output_segment_headers(size, big_endian,
429                                                this->segment_list_);
430   load_seg->add_initial_output_data(segment_headers);
431   this->special_output_list_.push_back(segment_headers);
432   if (phdr_seg != NULL)
433     phdr_seg->add_initial_output_data(segment_headers);
434
435   // Lay out the file header.
436   Output_file_header* file_header;
437   file_header = new Output_file_header(size,
438                                        big_endian,
439                                        this->options_,
440                                        target,
441                                        symtab,
442                                        segment_headers);
443   load_seg->add_initial_output_data(file_header);
444   this->special_output_list_.push_back(file_header);
445
446   // We set the output section indexes in set_segment_offsets and
447   // set_section_offsets.
448   unsigned int shndx = 1;
449
450   // Set the file offsets of all the segments, and all the sections
451   // they contain.
452   off_t off = this->set_segment_offsets(target, load_seg, &shndx);
453
454   // Create the symbol table sections.
455   // FIXME: We don't need to do this if we are stripping symbols.
456   this->create_symtab_sections(size, input_objects, symtab, &off);
457
458   // Create the .shstrtab section.
459   Output_section* shstrtab_section = this->create_shstrtab();
460
461   // Set the file offsets of all the sections not associated with
462   // segments.
463   off = this->set_section_offsets(off, &shndx);
464
465   // Create the section table header.
466   Output_section_headers* oshdrs = this->create_shdrs(size, big_endian, &off);
467
468   file_header->set_section_info(oshdrs, shstrtab_section);
469
470   // Now we know exactly where everything goes in the output file.
471   Output_data::layout_complete();
472
473   return off;
474 }
475
476 // Return whether SEG1 should be before SEG2 in the output file.  This
477 // is based entirely on the segment type and flags.  When this is
478 // called the segment addresses has normally not yet been set.
479
480 bool
481 Layout::segment_precedes(const Output_segment* seg1,
482                          const Output_segment* seg2)
483 {
484   elfcpp::Elf_Word type1 = seg1->type();
485   elfcpp::Elf_Word type2 = seg2->type();
486
487   // The single PT_PHDR segment is required to precede any loadable
488   // segment.  We simply make it always first.
489   if (type1 == elfcpp::PT_PHDR)
490     {
491       gold_assert(type2 != elfcpp::PT_PHDR);
492       return true;
493     }
494   if (type2 == elfcpp::PT_PHDR)
495     return false;
496
497   // The single PT_INTERP segment is required to precede any loadable
498   // segment.  We simply make it always second.
499   if (type1 == elfcpp::PT_INTERP)
500     {
501       gold_assert(type2 != elfcpp::PT_INTERP);
502       return true;
503     }
504   if (type2 == elfcpp::PT_INTERP)
505     return false;
506
507   // We then put PT_LOAD segments before any other segments.
508   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
509     return true;
510   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
511     return false;
512
513   // We put the PT_TLS segment last, because that is where the dynamic
514   // linker expects to find it (this is just for efficiency; other
515   // positions would also work correctly).
516   if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
517     return false;
518   if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
519     return true;
520
521   const elfcpp::Elf_Word flags1 = seg1->flags();
522   const elfcpp::Elf_Word flags2 = seg2->flags();
523
524   // The order of non-PT_LOAD segments is unimportant.  We simply sort
525   // by the numeric segment type and flags values.  There should not
526   // be more than one segment with the same type and flags.
527   if (type1 != elfcpp::PT_LOAD)
528     {
529       if (type1 != type2)
530         return type1 < type2;
531       gold_assert(flags1 != flags2);
532       return flags1 < flags2;
533     }
534
535   // We sort PT_LOAD segments based on the flags.  Readonly segments
536   // come before writable segments.  Then executable segments come
537   // before non-executable segments.  Then the unlikely case of a
538   // non-readable segment comes before the normal case of a readable
539   // segment.  If there are multiple segments with the same type and
540   // flags, we require that the address be set, and we sort by
541   // virtual address and then physical address.
542   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
543     return (flags1 & elfcpp::PF_W) == 0;
544   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
545     return (flags1 & elfcpp::PF_X) != 0;
546   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
547     return (flags1 & elfcpp::PF_R) == 0;
548
549   uint64_t vaddr1 = seg1->vaddr();
550   uint64_t vaddr2 = seg2->vaddr();
551   if (vaddr1 != vaddr2)
552     return vaddr1 < vaddr2;
553
554   uint64_t paddr1 = seg1->paddr();
555   uint64_t paddr2 = seg2->paddr();
556   gold_assert(paddr1 != paddr2);
557   return paddr1 < paddr2;
558 }
559
560 // Set the file offsets of all the segments, and all the sections they
561 // contain.  They have all been created.  LOAD_SEG must be be laid out
562 // first.  Return the offset of the data to follow.
563
564 off_t
565 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
566                             unsigned int *pshndx)
567 {
568   // Sort them into the final order.
569   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
570             Layout::Compare_segments());
571
572   // Find the PT_LOAD segments, and set their addresses and offsets
573   // and their section's addresses and offsets.
574   uint64_t addr = target->text_segment_address();
575   off_t off = 0;
576   bool was_readonly = false;
577   for (Segment_list::iterator p = this->segment_list_.begin();
578        p != this->segment_list_.end();
579        ++p)
580     {
581       if ((*p)->type() == elfcpp::PT_LOAD)
582         {
583           if (load_seg != NULL && load_seg != *p)
584             gold_unreachable();
585           load_seg = NULL;
586
587           // If the last segment was readonly, and this one is not,
588           // then skip the address forward one page, maintaining the
589           // same position within the page.  This lets us store both
590           // segments overlapping on a single page in the file, but
591           // the loader will put them on different pages in memory.
592
593           uint64_t orig_addr = addr;
594           uint64_t orig_off = off;
595
596           uint64_t aligned_addr = addr;
597           uint64_t abi_pagesize = target->abi_pagesize();
598           if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
599             {
600               uint64_t align = (*p)->addralign();
601
602               addr = align_address(addr, align);
603               aligned_addr = addr;
604               if ((addr & (abi_pagesize - 1)) != 0)
605                 addr = addr + abi_pagesize;
606             }
607
608           unsigned int shndx_hold = *pshndx;
609           off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
610           uint64_t new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
611
612           // Now that we know the size of this segment, we may be able
613           // to save a page in memory, at the cost of wasting some
614           // file space, by instead aligning to the start of a new
615           // page.  Here we use the real machine page size rather than
616           // the ABI mandated page size.
617
618           if (aligned_addr != addr)
619             {
620               uint64_t common_pagesize = target->common_pagesize();
621               uint64_t first_off = (common_pagesize
622                                     - (aligned_addr
623                                        & (common_pagesize - 1)));
624               uint64_t last_off = new_addr & (common_pagesize - 1);
625               if (first_off > 0
626                   && last_off > 0
627                   && ((aligned_addr & ~ (common_pagesize - 1))
628                       != (new_addr & ~ (common_pagesize - 1)))
629                   && first_off + last_off <= common_pagesize)
630                 {
631                   *pshndx = shndx_hold;
632                   addr = align_address(aligned_addr, common_pagesize);
633                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
634                   new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
635                 }
636             }
637
638           addr = new_addr;
639
640           if (((*p)->flags() & elfcpp::PF_W) == 0)
641             was_readonly = true;
642         }
643     }
644
645   // Handle the non-PT_LOAD segments, setting their offsets from their
646   // section's offsets.
647   for (Segment_list::iterator p = this->segment_list_.begin();
648        p != this->segment_list_.end();
649        ++p)
650     {
651       if ((*p)->type() != elfcpp::PT_LOAD)
652         (*p)->set_offset();
653     }
654
655   return off;
656 }
657
658 // Set the file offset of all the sections not associated with a
659 // segment.
660
661 off_t
662 Layout::set_section_offsets(off_t off, unsigned int* pshndx)
663 {
664   for (Section_list::iterator p = this->unattached_section_list_.begin();
665        p != this->unattached_section_list_.end();
666        ++p)
667     {
668       (*p)->set_out_shndx(*pshndx);
669       ++*pshndx;
670       if ((*p)->offset() != -1)
671         continue;
672       off = align_address(off, (*p)->addralign());
673       (*p)->set_address(0, off);
674       off += (*p)->data_size();
675     }
676   return off;
677 }
678
679 // Create the symbol table sections.
680
681 void
682 Layout::create_symtab_sections(int size, const Input_objects* input_objects,
683                                Symbol_table* symtab,
684                                off_t* poff)
685 {
686   int symsize;
687   unsigned int align;
688   if (size == 32)
689     {
690       symsize = elfcpp::Elf_sizes<32>::sym_size;
691       align = 4;
692     }
693   else if (size == 64)
694     {
695       symsize = elfcpp::Elf_sizes<64>::sym_size;
696       align = 8;
697     }
698   else
699     gold_unreachable();
700
701   off_t off = *poff;
702   off = align_address(off, align);
703   off_t startoff = off;
704
705   // Save space for the dummy symbol at the start of the section.  We
706   // never bother to write this out--it will just be left as zero.
707   off += symsize;
708   unsigned int local_symbol_index = 1;
709
710   // Add STT_SECTION symbols for each Output section which needs one.
711   for (Section_list::iterator p = this->section_list_.begin();
712        p != this->section_list_.end();
713        ++p)
714     {
715       if (!(*p)->needs_symtab_index())
716         (*p)->set_symtab_index(-1U);
717       else
718         {
719           (*p)->set_symtab_index(local_symbol_index);
720           ++local_symbol_index;
721           off += symsize;
722         }
723     }
724
725   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
726        p != input_objects->relobj_end();
727        ++p)
728     {
729       Task_lock_obj<Object> tlo(**p);
730       unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
731                                                         off,
732                                                         &this->sympool_);
733       off += (index - local_symbol_index) * symsize;
734       local_symbol_index = index;
735     }
736
737   unsigned int local_symcount = local_symbol_index;
738   gold_assert(local_symcount * symsize == off - startoff);
739
740   off_t dynoff;
741   size_t dyn_global_index;
742   size_t dyncount;
743   if (this->dynsym_section_ == NULL)
744     {
745       dynoff = 0;
746       dyn_global_index = 0;
747       dyncount = 0;
748     }
749   else
750     {
751       dyn_global_index = this->dynsym_section_->info();
752       off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
753       dynoff = this->dynsym_section_->offset() + locsize;
754       dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
755       gold_assert(dyncount * symsize
756                   == this->dynsym_section_->data_size() - locsize);
757     }
758
759   off = symtab->finalize(local_symcount, off, dynoff, dyn_global_index,
760                          dyncount, &this->sympool_);
761
762   this->sympool_.set_string_offsets();
763
764   const char* symtab_name = this->namepool_.add(".symtab", NULL);
765   Output_section* osymtab = this->make_output_section(symtab_name,
766                                                       elfcpp::SHT_SYMTAB,
767                                                       0);
768   this->symtab_section_ = osymtab;
769
770   Output_section_data* pos = new Output_data_space(off - startoff,
771                                                    align);
772   osymtab->add_output_section_data(pos);
773
774   const char* strtab_name = this->namepool_.add(".strtab", NULL);
775   Output_section* ostrtab = this->make_output_section(strtab_name,
776                                                       elfcpp::SHT_STRTAB,
777                                                       0);
778
779   Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
780   ostrtab->add_output_section_data(pstr);
781
782   osymtab->set_address(0, startoff);
783   osymtab->set_link_section(ostrtab);
784   osymtab->set_info(local_symcount);
785   osymtab->set_entsize(symsize);
786
787   *poff = off;
788 }
789
790 // Create the .shstrtab section, which holds the names of the
791 // sections.  At the time this is called, we have created all the
792 // output sections except .shstrtab itself.
793
794 Output_section*
795 Layout::create_shstrtab()
796 {
797   // FIXME: We don't need to create a .shstrtab section if we are
798   // stripping everything.
799
800   const char* name = this->namepool_.add(".shstrtab", NULL);
801
802   this->namepool_.set_string_offsets();
803
804   Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
805
806   Output_section_data* posd = new Output_data_strtab(&this->namepool_);
807   os->add_output_section_data(posd);
808
809   return os;
810 }
811
812 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
813 // offset.
814
815 Output_section_headers*
816 Layout::create_shdrs(int size, bool big_endian, off_t* poff)
817 {
818   Output_section_headers* oshdrs;
819   oshdrs = new Output_section_headers(size, big_endian, this,
820                                       &this->segment_list_,
821                                       &this->unattached_section_list_,
822                                       &this->namepool_);
823   off_t off = align_address(*poff, oshdrs->addralign());
824   oshdrs->set_address(0, off);
825   off += oshdrs->data_size();
826   *poff = off;
827   this->special_output_list_.push_back(oshdrs);
828   return oshdrs;
829 }
830
831 // Create the dynamic symbol table.
832
833 void
834 Layout::create_dynamic_symtab(const Target* target, Symbol_table* symtab)
835 {
836   // Count all the symbols in the dynamic symbol table, and set the
837   // dynamic symbol indexes.
838
839   // Skip symbol 0, which is always all zeroes.
840   unsigned int index = 1;
841
842   // Add STT_SECTION symbols for each Output section which needs one.
843   for (Section_list::iterator p = this->section_list_.begin();
844        p != this->section_list_.end();
845        ++p)
846     {
847       if (!(*p)->needs_dynsym_index())
848         (*p)->set_dynsym_index(-1U);
849       else
850         {
851           (*p)->set_dynsym_index(index);
852           ++index;
853         }
854     }
855
856   // FIXME: Some targets apparently require local symbols in the
857   // dynamic symbol table.  Here is where we will have to count them,
858   // and set the dynamic symbol indexes, and add the names to
859   // this->dynpool_.
860
861   unsigned int local_symcount = index;
862
863   std::vector<Symbol*> dynamic_symbols;
864
865   // FIXME: We have to tell set_dynsym_indexes whether the
866   // -E/--export-dynamic option was used.
867   index = symtab->set_dynsym_indexes(index, &dynamic_symbols,
868                                      &this->dynpool_);
869
870   int symsize;
871   unsigned int align;
872   const int size = target->get_size();
873   if (size == 32)
874     {
875       symsize = elfcpp::Elf_sizes<32>::sym_size;
876       align = 4;
877     }
878   else if (size == 64)
879     {
880       symsize = elfcpp::Elf_sizes<64>::sym_size;
881       align = 8;
882     }
883   else
884     gold_unreachable();
885
886   const char* dynsym_name = this->namepool_.add(".dynsym", NULL);
887   Output_section* dynsym = this->make_output_section(dynsym_name,
888                                                      elfcpp::SHT_DYNSYM,
889                                                      elfcpp::SHF_ALLOC);
890
891   Output_section_data* odata = new Output_data_space(index * symsize,
892                                                      align);
893   dynsym->add_output_section_data(odata);
894
895   dynsym->set_info(local_symcount);
896   dynsym->set_entsize(symsize);
897   dynsym->set_addralign(align);
898
899   this->dynsym_section_ = dynsym;
900
901   Output_data_dynamic* const odyn = this->dynamic_data_;
902   odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
903   odyn->add_constant(elfcpp::DT_SYMENT, symsize);
904
905   const char* dynstr_name = this->namepool_.add(".dynstr", NULL);
906   Output_section* dynstr = this->make_output_section(dynstr_name,
907                                                      elfcpp::SHT_STRTAB,
908                                                      elfcpp::SHF_ALLOC);
909
910   Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
911   dynstr->add_output_section_data(strdata);
912
913   dynsym->set_link_section(dynstr);
914   this->dynamic_section_->set_link_section(dynstr);
915
916   odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
917   odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
918
919   // FIXME: We need an option to create a GNU hash table.
920
921   unsigned char* phash;
922   unsigned int hashlen;
923   Dynobj::create_elf_hash_table(target, dynamic_symbols, local_symcount,
924                                 &phash, &hashlen);
925
926   const char* hash_name = this->namepool_.add(".hash", NULL);
927   Output_section* hashsec = this->make_output_section(hash_name,
928                                                       elfcpp::SHT_HASH,
929                                                       elfcpp::SHF_ALLOC);
930
931   Output_section_data* hashdata = new Output_data_const_buffer(phash,
932                                                                hashlen,
933                                                                align);
934   hashsec->add_output_section_data(hashdata);
935
936   hashsec->set_link_section(dynsym);
937   hashsec->set_entsize(4);
938
939   odyn->add_section_address(elfcpp::DT_HASH, hashsec);
940 }
941
942 // Create the .interp section and PT_INTERP segment.
943
944 void
945 Layout::create_interp(const Target* target)
946 {
947   const char* interp = this->options_.dynamic_linker();
948   if (interp == NULL)
949     {
950       interp = target->dynamic_linker();
951       gold_assert(interp != NULL);
952     }
953
954   size_t len = strlen(interp) + 1;
955
956   Output_section_data* odata = new Output_data_const(interp, len, 1);
957
958   const char* interp_name = this->namepool_.add(".interp", NULL);
959   Output_section* osec = this->make_output_section(interp_name,
960                                                    elfcpp::SHT_PROGBITS,
961                                                    elfcpp::SHF_ALLOC);
962   osec->add_output_section_data(odata);
963
964   Output_segment* oseg = new Output_segment(elfcpp::PT_INTERP, elfcpp::PF_R);
965   this->segment_list_.push_back(oseg);
966   oseg->add_initial_output_section(osec, elfcpp::PF_R);
967 }
968
969 // Finish the .dynamic section and PT_DYNAMIC segment.
970
971 void
972 Layout::finish_dynamic_section(const Input_objects* input_objects,
973                                const Symbol_table* symtab)
974 {
975   Output_segment* oseg = new Output_segment(elfcpp::PT_DYNAMIC,
976                                             elfcpp::PF_R | elfcpp::PF_W);
977   this->segment_list_.push_back(oseg);
978   oseg->add_initial_output_section(this->dynamic_section_,
979                                    elfcpp::PF_R | elfcpp::PF_W);
980
981   Output_data_dynamic* const odyn = this->dynamic_data_;
982
983   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
984        p != input_objects->dynobj_end();
985        ++p)
986     {
987       // FIXME: Handle --as-needed.
988       odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
989     }
990
991   // FIXME: Support --init and --fini.
992   Symbol* sym = symtab->lookup("_init");
993   if (sym != NULL && sym->is_defined() && !sym->is_defined_in_dynobj())
994     odyn->add_symbol(elfcpp::DT_INIT, sym);
995
996   sym = symtab->lookup("_fini");
997   if (sym != NULL && sym->is_defined() && !sym->is_defined_in_dynobj())
998     odyn->add_symbol(elfcpp::DT_FINI, sym);
999
1000   // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
1001 }
1002
1003 // The mapping of .gnu.linkonce section names to real section names.
1004
1005 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
1006 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
1007 {
1008   MAPPING_INIT("d.rel.ro", ".data.rel.ro"),     // Must be before "d".
1009   MAPPING_INIT("t", ".text"),
1010   MAPPING_INIT("r", ".rodata"),
1011   MAPPING_INIT("d", ".data"),
1012   MAPPING_INIT("b", ".bss"),
1013   MAPPING_INIT("s", ".sdata"),
1014   MAPPING_INIT("sb", ".sbss"),
1015   MAPPING_INIT("s2", ".sdata2"),
1016   MAPPING_INIT("sb2", ".sbss2"),
1017   MAPPING_INIT("wi", ".debug_info"),
1018   MAPPING_INIT("td", ".tdata"),
1019   MAPPING_INIT("tb", ".tbss"),
1020   MAPPING_INIT("lr", ".lrodata"),
1021   MAPPING_INIT("l", ".ldata"),
1022   MAPPING_INIT("lb", ".lbss"),
1023 };
1024 #undef MAPPING_INIT
1025
1026 const int Layout::linkonce_mapping_count =
1027   sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
1028
1029 // Return the name of the output section to use for a .gnu.linkonce
1030 // section.  This is based on the default ELF linker script of the old
1031 // GNU linker.  For example, we map a name like ".gnu.linkonce.t.foo"
1032 // to ".text".  Set *PLEN to the length of the name.  *PLEN is
1033 // initialized to the length of NAME.
1034
1035 const char*
1036 Layout::linkonce_output_name(const char* name, size_t *plen)
1037 {
1038   const char* s = name + sizeof(".gnu.linkonce") - 1;
1039   if (*s != '.')
1040     return name;
1041   ++s;
1042   const Linkonce_mapping* plm = linkonce_mapping;
1043   for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
1044     {
1045       if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
1046         {
1047           *plen = plm->tolen;
1048           return plm->to;
1049         }
1050     }
1051   return name;
1052 }
1053
1054 // Choose the output section name to use given an input section name.
1055 // Set *PLEN to the length of the name.  *PLEN is initialized to the
1056 // length of NAME.
1057
1058 const char*
1059 Layout::output_section_name(const char* name, size_t* plen)
1060 {
1061   if (Layout::is_linkonce(name))
1062     {
1063       // .gnu.linkonce sections are laid out as though they were named
1064       // for the sections are placed into.
1065       return Layout::linkonce_output_name(name, plen);
1066     }
1067
1068   // If the section name has no '.', or only an initial '.', we use
1069   // the name unchanged (i.e., ".text" is unchanged).
1070
1071   // Otherwise, if the section name does not include ".rel", we drop
1072   // the last '.'  and everything that follows (i.e., ".text.XXX"
1073   // becomes ".text").
1074
1075   // Otherwise, if the section name has zero or one '.' after the
1076   // ".rel", we use the name unchanged (i.e., ".rel.text" is
1077   // unchanged).
1078
1079   // Otherwise, we drop the last '.' and everything that follows
1080   // (i.e., ".rel.text.XXX" becomes ".rel.text").
1081
1082   const char* s = name;
1083   if (*s == '.')
1084     ++s;
1085   const char* sdot = strchr(s, '.');
1086   if (sdot == NULL)
1087     return name;
1088
1089   const char* srel = strstr(s, ".rel");
1090   if (srel == NULL)
1091     {
1092       *plen = sdot - name;
1093       return name;
1094     }
1095
1096   sdot = strchr(srel + 1, '.');
1097   if (sdot == NULL)
1098     return name;
1099   sdot = strchr(sdot + 1, '.');
1100   if (sdot == NULL)
1101     return name;
1102
1103   *plen = sdot - name;
1104   return name;
1105 }
1106
1107 // Record the signature of a comdat section, and return whether to
1108 // include it in the link.  If GROUP is true, this is a regular
1109 // section group.  If GROUP is false, this is a group signature
1110 // derived from the name of a linkonce section.  We want linkonce
1111 // signatures and group signatures to block each other, but we don't
1112 // want a linkonce signature to block another linkonce signature.
1113
1114 bool
1115 Layout::add_comdat(const char* signature, bool group)
1116 {
1117   std::string sig(signature);
1118   std::pair<Signatures::iterator, bool> ins(
1119     this->signatures_.insert(std::make_pair(sig, group)));
1120
1121   if (ins.second)
1122     {
1123       // This is the first time we've seen this signature.
1124       return true;
1125     }
1126
1127   if (ins.first->second)
1128     {
1129       // We've already seen a real section group with this signature.
1130       return false;
1131     }
1132   else if (group)
1133     {
1134       // This is a real section group, and we've already seen a
1135       // linkonce section with tihs signature.  Record that we've seen
1136       // a section group, and don't include this section group.
1137       ins.first->second = true;
1138       return false;
1139     }
1140   else
1141     {
1142       // We've already seen a linkonce section and this is a linkonce
1143       // section.  These don't block each other--this may be the same
1144       // symbol name with different section types.
1145       return true;
1146     }
1147 }
1148
1149 // Write out data not associated with a section or the symbol table.
1150
1151 void
1152 Layout::write_data(const Symbol_table* symtab, const Target* target,
1153                    Output_file* of) const
1154 {
1155   const Output_section* symtab_section = this->symtab_section_;
1156   for (Section_list::const_iterator p = this->section_list_.begin();
1157        p != this->section_list_.end();
1158        ++p)
1159     {
1160       if ((*p)->needs_symtab_index())
1161         {
1162           gold_assert(symtab_section != NULL);
1163           unsigned int index = (*p)->symtab_index();
1164           gold_assert(index > 0 && index != -1U);
1165           off_t off = (symtab_section->offset()
1166                        + index * symtab_section->entsize());
1167           symtab->write_section_symbol(target, *p, of, off);
1168         }
1169     }
1170
1171   const Output_section* dynsym_section = this->dynsym_section_;
1172   for (Section_list::const_iterator p = this->section_list_.begin();
1173        p != this->section_list_.end();
1174        ++p)
1175     {
1176       if ((*p)->needs_dynsym_index())
1177         {
1178           gold_assert(dynsym_section != NULL);
1179           unsigned int index = (*p)->dynsym_index();
1180           gold_assert(index > 0 && index != -1U);
1181           off_t off = (dynsym_section->offset()
1182                        + index * dynsym_section->entsize());
1183           symtab->write_section_symbol(target, *p, of, off);
1184         }
1185     }
1186
1187   // Write out the Output_sections.  Most won't have anything to
1188   // write, since most of the data will come from input sections which
1189   // are handled elsewhere.  But some Output_sections do have
1190   // Output_data.
1191   for (Section_list::const_iterator p = this->section_list_.begin();
1192        p != this->section_list_.end();
1193        ++p)
1194     (*p)->write(of);
1195
1196   // Write out the Output_data which are not in an Output_section.
1197   for (Data_list::const_iterator p = this->special_output_list_.begin();
1198        p != this->special_output_list_.end();
1199        ++p)
1200     (*p)->write(of);
1201 }
1202
1203 // Write_data_task methods.
1204
1205 // We can always run this task.
1206
1207 Task::Is_runnable_type
1208 Write_data_task::is_runnable(Workqueue*)
1209 {
1210   return IS_RUNNABLE;
1211 }
1212
1213 // We need to unlock FINAL_BLOCKER when finished.
1214
1215 Task_locker*
1216 Write_data_task::locks(Workqueue* workqueue)
1217 {
1218   return new Task_locker_block(*this->final_blocker_, workqueue);
1219 }
1220
1221 // Run the task--write out the data.
1222
1223 void
1224 Write_data_task::run(Workqueue*)
1225 {
1226   this->layout_->write_data(this->symtab_, this->target_, this->of_);
1227 }
1228
1229 // Write_symbols_task methods.
1230
1231 // We can always run this task.
1232
1233 Task::Is_runnable_type
1234 Write_symbols_task::is_runnable(Workqueue*)
1235 {
1236   return IS_RUNNABLE;
1237 }
1238
1239 // We need to unlock FINAL_BLOCKER when finished.
1240
1241 Task_locker*
1242 Write_symbols_task::locks(Workqueue* workqueue)
1243 {
1244   return new Task_locker_block(*this->final_blocker_, workqueue);
1245 }
1246
1247 // Run the task--write out the symbols.
1248
1249 void
1250 Write_symbols_task::run(Workqueue*)
1251 {
1252   this->symtab_->write_globals(this->target_, this->sympool_, this->dynpool_,
1253                                this->of_);
1254 }
1255
1256 // Close_task_runner methods.
1257
1258 // Run the task--close the file.
1259
1260 void
1261 Close_task_runner::run(Workqueue*)
1262 {
1263   this->of_->close();
1264 }
1265
1266 // Instantiate the templates we need.  We could use the configure
1267 // script to restrict this to only the ones for implemented targets.
1268
1269 template
1270 Output_section*
1271 Layout::layout<32, false>(Relobj* object, unsigned int shndx, const char* name,
1272                           const elfcpp::Shdr<32, false>& shdr, off_t*);
1273
1274 template
1275 Output_section*
1276 Layout::layout<32, true>(Relobj* object, unsigned int shndx, const char* name,
1277                          const elfcpp::Shdr<32, true>& shdr, off_t*);
1278
1279 template
1280 Output_section*
1281 Layout::layout<64, false>(Relobj* object, unsigned int shndx, const char* name,
1282                           const elfcpp::Shdr<64, false>& shdr, off_t*);
1283
1284 template
1285 Output_section*
1286 Layout::layout<64, true>(Relobj* object, unsigned int shndx, const char* name,
1287                          const elfcpp::Shdr<64, true>& shdr, off_t*);
1288
1289
1290 } // End namespace gold.