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