Rework stringpool and hash tables so that we always generate the same
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 #include "gold.h"
4
5 #include <cassert>
6 #include <cstring>
7 #include <algorithm>
8 #include <iostream>
9 #include <utility>
10
11 #include "output.h"
12 #include "symtab.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_(), signatures_(),
43     section_name_map_(), segment_list_(), section_list_(),
44     special_output_list_(), tls_segment_(NULL)
45 {
46   // Make space for more than enough segments for a typical file.
47   // This is just for efficiency--it's OK if we wind up needing more.
48   segment_list_.reserve(12);
49 }
50
51 // Hash a key we use to look up an output section mapping.
52
53 size_t
54 Layout::Hash_key::operator()(const Layout::Key& k) const
55 {
56  return k.first + k.second.first + k.second.second;
57 }
58
59 // Whether to include this section in the link.
60
61 template<int size, bool big_endian>
62 bool
63 Layout::include_section(Object*, const char*,
64                         const elfcpp::Shdr<size, big_endian>& shdr)
65 {
66   // Some section types are never linked.  Some are only linked when
67   // doing a relocateable link.
68   switch (shdr.get_sh_type())
69     {
70     case elfcpp::SHT_NULL:
71     case elfcpp::SHT_SYMTAB:
72     case elfcpp::SHT_DYNSYM:
73     case elfcpp::SHT_STRTAB:
74     case elfcpp::SHT_HASH:
75     case elfcpp::SHT_DYNAMIC:
76     case elfcpp::SHT_SYMTAB_SHNDX:
77       return false;
78
79     case elfcpp::SHT_RELA:
80     case elfcpp::SHT_REL:
81     case elfcpp::SHT_GROUP:
82       return this->options_.is_relocatable();
83
84     default:
85       // FIXME: Handle stripping debug sections here.
86       return true;
87     }
88 }
89
90 // Return an output section named NAME, or NULL if there is none.
91
92 Output_section*
93 Layout::find_output_section(const char* name) const
94 {
95   for (Section_name_map::const_iterator p = this->section_name_map_.begin();
96        p != this->section_name_map_.end();
97        ++p)
98     if (strcmp(p->second->name(), name) == 0)
99       return p->second;
100   return NULL;
101 }
102
103 // Return an output segment of type TYPE, with segment flags SET set
104 // and segment flags CLEAR clear.  Return NULL if there is none.
105
106 Output_segment*
107 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
108                             elfcpp::Elf_Word clear) const
109 {
110   for (Segment_list::const_iterator p = this->segment_list_.begin();
111        p != this->segment_list_.end();
112        ++p)
113     if (static_cast<elfcpp::PT>((*p)->type()) == type
114         && ((*p)->flags() & set) == set
115         && ((*p)->flags() & clear) == 0)
116       return *p;
117   return NULL;
118 }
119
120 // Return the output section to use for section NAME with type TYPE
121 // and section flags FLAGS.
122
123 Output_section*
124 Layout::get_output_section(const char* name, Stringpool::Key name_key,
125                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
126 {
127   // We should ignore some flags.
128   flags &= ~ (elfcpp::SHF_INFO_LINK
129               | elfcpp::SHF_LINK_ORDER
130               | elfcpp::SHF_GROUP);
131
132   const Key key(name_key, std::make_pair(type, flags));
133   const std::pair<Key, Output_section*> v(key, NULL);
134   std::pair<Section_name_map::iterator, bool> ins(
135     this->section_name_map_.insert(v));
136
137   if (!ins.second)
138     return ins.first->second;
139   else
140     {
141       // This is the first time we've seen this name/type/flags
142       // combination.
143       Output_section* os = this->make_output_section(name, type, flags);
144       ins.first->second = os;
145       return os;
146     }
147 }
148
149 // Return the output section to use for input section SHNDX, with name
150 // NAME, with header HEADER, from object OBJECT.  Set *OFF to the
151 // offset of this input section without the output section.
152
153 template<int size, bool big_endian>
154 Output_section*
155 Layout::layout(Relobj* object, unsigned int shndx, const char* name,
156                const elfcpp::Shdr<size, big_endian>& shdr, off_t* off)
157 {
158   if (!this->include_section(object, name, shdr))
159     return NULL;
160
161   // If we are not doing a relocateable link, choose the name to use
162   // for the output section.
163   size_t len = strlen(name);
164   if (!this->options_.is_relocatable())
165     name = Layout::output_section_name(name, &len);
166
167   // FIXME: Handle SHF_OS_NONCONFORMING here.
168
169   // Canonicalize the section name.
170   Stringpool::Key name_key;
171   name = this->namepool_.add(name, len, &name_key);
172
173   // Find the output section.  The output section is selected based on
174   // the section name, type, and flags.
175   Output_section* os = this->get_output_section(name, name_key,
176                                                 shdr.get_sh_type(),
177                                                 shdr.get_sh_flags());
178
179   // FIXME: Handle SHF_LINK_ORDER somewhere.
180
181   *off = os->add_input_section(object, shndx, name, shdr);
182
183   return os;
184 }
185
186 // Add POSD to an output section using NAME, TYPE, and FLAGS.
187
188 void
189 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
190                                 elfcpp::Elf_Xword flags,
191                                 Output_section_data* posd)
192 {
193   // Canonicalize the name.
194   Stringpool::Key name_key;
195   name = this->namepool_.add(name, &name_key);
196
197   Output_section* os = this->get_output_section(name, name_key, type, flags);
198   os->add_output_section_data(posd);
199 }
200
201 // Map section flags to segment flags.
202
203 elfcpp::Elf_Word
204 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
205 {
206   elfcpp::Elf_Word ret = elfcpp::PF_R;
207   if ((flags & elfcpp::SHF_WRITE) != 0)
208     ret |= elfcpp::PF_W;
209   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
210     ret |= elfcpp::PF_X;
211   return ret;
212 }
213
214 // Make a new Output_section, and attach it to segments as
215 // appropriate.
216
217 Output_section*
218 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
219                             elfcpp::Elf_Xword flags)
220 {
221   Output_section* os = new Output_section(name, type, flags, true);
222
223   if ((flags & elfcpp::SHF_ALLOC) == 0)
224     this->section_list_.push_back(os);
225   else
226     {
227       // This output section goes into a PT_LOAD segment.
228
229       elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
230
231       // The only thing we really care about for PT_LOAD segments is
232       // whether or not they are writable, so that is how we search
233       // for them.  People who need segments sorted on some other
234       // basis will have to wait until we implement a mechanism for
235       // them to describe the segments they want.
236
237       Segment_list::const_iterator p;
238       for (p = this->segment_list_.begin();
239            p != this->segment_list_.end();
240            ++p)
241         {
242           if ((*p)->type() == elfcpp::PT_LOAD
243               && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
244             {
245               (*p)->add_output_section(os, seg_flags);
246               break;
247             }
248         }
249
250       if (p == this->segment_list_.end())
251         {
252           Output_segment* oseg = new Output_segment(elfcpp::PT_LOAD,
253                                                     seg_flags);
254           this->segment_list_.push_back(oseg);
255           oseg->add_output_section(os, seg_flags);
256         }
257
258       // If we see a loadable SHT_NOTE section, we create a PT_NOTE
259       // segment.
260       if (type == elfcpp::SHT_NOTE)
261         {
262           // See if we already have an equivalent PT_NOTE segment.
263           for (p = this->segment_list_.begin();
264                p != segment_list_.end();
265                ++p)
266             {
267               if ((*p)->type() == elfcpp::PT_NOTE
268                   && (((*p)->flags() & elfcpp::PF_W)
269                       == (seg_flags & elfcpp::PF_W)))
270                 {
271                   (*p)->add_output_section(os, seg_flags);
272                   break;
273                 }
274             }
275
276           if (p == this->segment_list_.end())
277             {
278               Output_segment* oseg = new Output_segment(elfcpp::PT_NOTE,
279                                                         seg_flags);
280               this->segment_list_.push_back(oseg);
281               oseg->add_output_section(os, seg_flags);
282             }
283         }
284
285       // If we see a loadable SHF_TLS section, we create a PT_TLS
286       // segment.  There can only be one such segment.
287       if ((flags & elfcpp::SHF_TLS) != 0)
288         {
289           if (this->tls_segment_ == NULL)
290             {
291               this->tls_segment_ = new Output_segment(elfcpp::PT_TLS,
292                                                       seg_flags);
293               this->segment_list_.push_back(this->tls_segment_);
294             }
295           this->tls_segment_->add_output_section(os, seg_flags);
296         }
297     }
298
299   return os;
300 }
301
302 // Find the first read-only PT_LOAD segment, creating one if
303 // necessary.
304
305 Output_segment*
306 Layout::find_first_load_seg()
307 {
308   for (Segment_list::const_iterator p = this->segment_list_.begin();
309        p != this->segment_list_.end();
310        ++p)
311     {
312       if ((*p)->type() == elfcpp::PT_LOAD
313           && ((*p)->flags() & elfcpp::PF_R) != 0
314           && ((*p)->flags() & elfcpp::PF_W) == 0)
315         return *p;
316     }
317
318   Output_segment* load_seg = new Output_segment(elfcpp::PT_LOAD, elfcpp::PF_R);
319   this->segment_list_.push_back(load_seg);
320   return load_seg;
321 }
322
323 // Finalize the layout.  When this is called, we have created all the
324 // output sections and all the output segments which are based on
325 // input sections.  We have several things to do, and we have to do
326 // them in the right order, so that we get the right results correctly
327 // and efficiently.
328
329 // 1) Finalize the list of output segments and create the segment
330 // table header.
331
332 // 2) Finalize the dynamic symbol table and associated sections.
333
334 // 3) Determine the final file offset of all the output segments.
335
336 // 4) Determine the final file offset of all the SHF_ALLOC output
337 // sections.
338
339 // 5) Create the symbol table sections and the section name table
340 // section.
341
342 // 6) Finalize the symbol table: set symbol values to their final
343 // value and make a final determination of which symbols are going
344 // into the output symbol table.
345
346 // 7) Create the section table header.
347
348 // 8) Determine the final file offset of all the output sections which
349 // are not SHF_ALLOC, including the section table header.
350
351 // 9) Finalize the ELF file header.
352
353 // This function returns the size of the output file.
354
355 off_t
356 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab)
357 {
358   if (input_objects->any_dynamic())
359     {
360       // If there are any dynamic objects in the link, then we need
361       // some additional segments: PT_PHDRS, PT_INTERP, and
362       // PT_DYNAMIC.  We also need to finalize the dynamic symbol
363       // table and create the dynamic hash table.
364       abort();
365     }
366
367   // FIXME: Handle PT_GNU_STACK.
368
369   Output_segment* load_seg = this->find_first_load_seg();
370
371   // Lay out the segment headers.
372   int size = input_objects->target()->get_size();
373   bool big_endian = input_objects->target()->is_big_endian();
374   Output_segment_headers* segment_headers;
375   segment_headers = new Output_segment_headers(size, big_endian,
376                                                this->segment_list_);
377   load_seg->add_initial_output_data(segment_headers);
378   this->special_output_list_.push_back(segment_headers);
379   // FIXME: Attach them to PT_PHDRS if necessary.
380
381   // Lay out the file header.
382   Output_file_header* file_header;
383   file_header = new Output_file_header(size,
384                                        big_endian,
385                                        this->options_,
386                                        input_objects->target(),
387                                        symtab,
388                                        segment_headers);
389   load_seg->add_initial_output_data(file_header);
390   this->special_output_list_.push_back(file_header);
391
392   // We set the output section indexes in set_segment_offsets and
393   // set_section_offsets.
394   unsigned int shndx = 1;
395
396   // Set the file offsets of all the segments, and all the sections
397   // they contain.
398   off_t off = this->set_segment_offsets(input_objects->target(), load_seg,
399                                         &shndx);
400
401   // Create the symbol table sections.
402   // FIXME: We don't need to do this if we are stripping symbols.
403   Output_section* osymtab;
404   Output_section* ostrtab;
405   this->create_symtab_sections(size, input_objects, symtab, &off,
406                                &osymtab, &ostrtab);
407
408   // Create the .shstrtab section.
409   Output_section* shstrtab_section = this->create_shstrtab();
410
411   // Set the file offsets of all the sections not associated with
412   // segments.
413   off = this->set_section_offsets(off, &shndx);
414
415   // Now the section index of OSTRTAB is set.
416   osymtab->set_link(ostrtab->out_shndx());
417
418   // Create the section table header.
419   Output_section_headers* oshdrs = this->create_shdrs(size, big_endian, &off);
420
421   file_header->set_section_info(oshdrs, shstrtab_section);
422
423   // Now we know exactly where everything goes in the output file.
424
425   return off;
426 }
427
428 // Return whether SEG1 should be before SEG2 in the output file.  This
429 // is based entirely on the segment type and flags.  When this is
430 // called the segment addresses has normally not yet been set.
431
432 bool
433 Layout::segment_precedes(const Output_segment* seg1,
434                          const Output_segment* seg2)
435 {
436   elfcpp::Elf_Word type1 = seg1->type();
437   elfcpp::Elf_Word type2 = seg2->type();
438
439   // The single PT_PHDR segment is required to precede any loadable
440   // segment.  We simply make it always first.
441   if (type1 == elfcpp::PT_PHDR)
442     {
443       assert(type2 != elfcpp::PT_PHDR);
444       return true;
445     }
446   if (type2 == elfcpp::PT_PHDR)
447     return false;
448
449   // The single PT_INTERP segment is required to precede any loadable
450   // segment.  We simply make it always second.
451   if (type1 == elfcpp::PT_INTERP)
452     {
453       assert(type2 != elfcpp::PT_INTERP);
454       return true;
455     }
456   if (type2 == elfcpp::PT_INTERP)
457     return false;
458
459   // We then put PT_LOAD segments before any other segments.
460   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
461     return true;
462   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
463     return false;
464
465   // We put the PT_TLS segment last, because that is where the dynamic
466   // linker expects to find it (this is just for efficiency; other
467   // positions would also work correctly).
468   if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
469     return false;
470   if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
471     return true;
472
473   const elfcpp::Elf_Word flags1 = seg1->flags();
474   const elfcpp::Elf_Word flags2 = seg2->flags();
475
476   // The order of non-PT_LOAD segments is unimportant.  We simply sort
477   // by the numeric segment type and flags values.  There should not
478   // be more than one segment with the same type and flags.
479   if (type1 != elfcpp::PT_LOAD)
480     {
481       if (type1 != type2)
482         return type1 < type2;
483       assert(flags1 != flags2);
484       return flags1 < flags2;
485     }
486
487   // We sort PT_LOAD segments based on the flags.  Readonly segments
488   // come before writable segments.  Then executable segments come
489   // before non-executable segments.  Then the unlikely case of a
490   // non-readable segment comes before the normal case of a readable
491   // segment.  If there are multiple segments with the same type and
492   // flags, we require that the address be set, and we sort by
493   // virtual address and then physical address.
494   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
495     return (flags1 & elfcpp::PF_W) == 0;
496   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
497     return (flags1 & elfcpp::PF_X) != 0;
498   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
499     return (flags1 & elfcpp::PF_R) == 0;
500
501   uint64_t vaddr1 = seg1->vaddr();
502   uint64_t vaddr2 = seg2->vaddr();
503   if (vaddr1 != vaddr2)
504     return vaddr1 < vaddr2;
505
506   uint64_t paddr1 = seg1->paddr();
507   uint64_t paddr2 = seg2->paddr();
508   assert(paddr1 != paddr2);
509   return paddr1 < paddr2;
510 }
511
512 // Set the file offsets of all the segments, and all the sections they
513 // contain.  They have all been created.  LOAD_SEG must be be laid out
514 // first.  Return the offset of the data to follow.
515
516 off_t
517 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
518                             unsigned int *pshndx)
519 {
520   // Sort them into the final order.
521   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
522             Layout::Compare_segments());
523
524   // Find the PT_LOAD segments, and set their addresses and offsets
525   // and their section's addresses and offsets.
526   uint64_t addr = target->text_segment_address();
527   off_t off = 0;
528   bool was_readonly = false;
529   for (Segment_list::iterator p = this->segment_list_.begin();
530        p != this->segment_list_.end();
531        ++p)
532     {
533       if ((*p)->type() == elfcpp::PT_LOAD)
534         {
535           if (load_seg != NULL && load_seg != *p)
536             abort();
537           load_seg = NULL;
538
539           // If the last segment was readonly, and this one is not,
540           // then skip the address forward one page, maintaining the
541           // same position within the page.  This lets us store both
542           // segments overlapping on a single page in the file, but
543           // the loader will put them on different pages in memory.
544
545           uint64_t orig_addr = addr;
546           uint64_t orig_off = off;
547
548           uint64_t aligned_addr = addr;
549           uint64_t abi_pagesize = target->abi_pagesize();
550           if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
551             {
552               uint64_t align = (*p)->addralign();
553
554               addr = align_address(addr, align);
555               aligned_addr = addr;
556               if ((addr & (abi_pagesize - 1)) != 0)
557                 addr = addr + abi_pagesize;
558             }
559
560           unsigned int shndx_hold = *pshndx;
561           off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
562           uint64_t new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
563
564           // Now that we know the size of this segment, we may be able
565           // to save a page in memory, at the cost of wasting some
566           // file space, by instead aligning to the start of a new
567           // page.  Here we use the real machine page size rather than
568           // the ABI mandated page size.
569
570           if (aligned_addr != addr)
571             {
572               uint64_t common_pagesize = target->common_pagesize();
573               uint64_t first_off = (common_pagesize
574                                     - (aligned_addr
575                                        & (common_pagesize - 1)));
576               uint64_t last_off = new_addr & (common_pagesize - 1);
577               if (first_off > 0
578                   && last_off > 0
579                   && ((aligned_addr & ~ (common_pagesize - 1))
580                       != (new_addr & ~ (common_pagesize - 1)))
581                   && first_off + last_off <= common_pagesize)
582                 {
583                   *pshndx = shndx_hold;
584                   addr = align_address(aligned_addr, common_pagesize);
585                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
586                   new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
587                 }
588             }
589
590           addr = new_addr;
591
592           if (((*p)->flags() & elfcpp::PF_W) == 0)
593             was_readonly = true;
594         }
595     }
596
597   // Handle the non-PT_LOAD segments, setting their offsets from their
598   // section's offsets.
599   for (Segment_list::iterator p = this->segment_list_.begin();
600        p != this->segment_list_.end();
601        ++p)
602     {
603       if ((*p)->type() != elfcpp::PT_LOAD)
604         (*p)->set_offset();
605     }
606
607   return off;
608 }
609
610 // Set the file offset of all the sections not associated with a
611 // segment.
612
613 off_t
614 Layout::set_section_offsets(off_t off, unsigned int* pshndx)
615 {
616   for (Layout::Section_list::iterator p = this->section_list_.begin();
617        p != this->section_list_.end();
618        ++p)
619     {
620       (*p)->set_out_shndx(*pshndx);
621       ++*pshndx;
622       if ((*p)->offset() != -1)
623         continue;
624       off = align_address(off, (*p)->addralign());
625       (*p)->set_address(0, off);
626       off += (*p)->data_size();
627     }
628   return off;
629 }
630
631 // Create the symbol table sections.
632
633 void
634 Layout::create_symtab_sections(int size, const Input_objects* input_objects,
635                                Symbol_table* symtab,
636                                off_t* poff,
637                                Output_section** posymtab,
638                                Output_section** postrtab)
639 {
640   int symsize;
641   unsigned int align;
642   if (size == 32)
643     {
644       symsize = elfcpp::Elf_sizes<32>::sym_size;
645       align = 4;
646     }
647   else if (size == 64)
648     {
649       symsize = elfcpp::Elf_sizes<64>::sym_size;
650       align = 8;
651     }
652   else
653     abort();
654
655   off_t off = *poff;
656   off = align_address(off, align);
657   off_t startoff = off;
658
659   // Save space for the dummy symbol at the start of the section.  We
660   // never bother to write this out--it will just be left as zero.
661   off += symsize;
662
663   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
664        p != input_objects->relobj_end();
665        ++p)
666     {
667       Task_lock_obj<Object> tlo(**p);
668       off = (*p)->finalize_local_symbols(off, &this->sympool_);
669     }
670
671   unsigned int local_symcount = (off - startoff) / symsize;
672   assert(local_symcount * symsize == off - startoff);
673
674   off = symtab->finalize(off, &this->sympool_);
675
676   this->sympool_.set_string_offsets();
677
678   const char* symtab_name = this->namepool_.add(".symtab", NULL);
679   Output_section* osymtab = new Output_section_symtab(symtab_name,
680                                                       off - startoff);
681   this->section_list_.push_back(osymtab);
682
683   const char* strtab_name = this->namepool_.add(".strtab", NULL);
684   Output_section *ostrtab = new Output_section_strtab(strtab_name,
685                                                       &this->sympool_);
686   this->section_list_.push_back(ostrtab);
687   this->special_output_list_.push_back(ostrtab);
688
689   osymtab->set_address(0, startoff);
690   osymtab->set_info(local_symcount);
691   osymtab->set_entsize(symsize);
692   osymtab->set_addralign(align);
693
694   *poff = off;
695   *posymtab = osymtab;
696   *postrtab = ostrtab;
697 }
698
699 // Create the .shstrtab section, which holds the names of the
700 // sections.  At the time this is called, we have created all the
701 // output sections except .shstrtab itself.
702
703 Output_section*
704 Layout::create_shstrtab()
705 {
706   // FIXME: We don't need to create a .shstrtab section if we are
707   // stripping everything.
708
709   const char* name = this->namepool_.add(".shstrtab", NULL);
710
711   this->namepool_.set_string_offsets();
712
713   Output_section* os = new Output_section_strtab(name, &this->namepool_);
714
715   this->section_list_.push_back(os);
716   this->special_output_list_.push_back(os);
717
718   return os;
719 }
720
721 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
722 // offset.
723
724 Output_section_headers*
725 Layout::create_shdrs(int size, bool big_endian, off_t* poff)
726 {
727   Output_section_headers* oshdrs;
728   oshdrs = new Output_section_headers(size, big_endian, this->segment_list_,
729                                       this->section_list_,
730                                       &this->namepool_);
731   off_t off = align_address(*poff, oshdrs->addralign());
732   oshdrs->set_address(0, off);
733   off += oshdrs->data_size();
734   *poff = off;
735   this->special_output_list_.push_back(oshdrs);
736   return oshdrs;
737 }
738
739 // The mapping of .gnu.linkonce section names to real section names.
740
741 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
742 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
743 {
744   MAPPING_INIT("d.rel.ro", ".data.rel.ro"),     // Must be before "d".
745   MAPPING_INIT("t", ".text"),
746   MAPPING_INIT("r", ".rodata"),
747   MAPPING_INIT("d", ".data"),
748   MAPPING_INIT("b", ".bss"),
749   MAPPING_INIT("s", ".sdata"),
750   MAPPING_INIT("sb", ".sbss"),
751   MAPPING_INIT("s2", ".sdata2"),
752   MAPPING_INIT("sb2", ".sbss2"),
753   MAPPING_INIT("wi", ".debug_info"),
754   MAPPING_INIT("td", ".tdata"),
755   MAPPING_INIT("tb", ".tbss"),
756   MAPPING_INIT("lr", ".lrodata"),
757   MAPPING_INIT("l", ".ldata"),
758   MAPPING_INIT("lb", ".lbss"),
759 };
760 #undef MAPPING_INIT
761
762 const int Layout::linkonce_mapping_count =
763   sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
764
765 // Return the name of the output section to use for a .gnu.linkonce
766 // section.  This is based on the default ELF linker script of the old
767 // GNU linker.  For example, we map a name like ".gnu.linkonce.t.foo"
768 // to ".text".  Set *PLEN to the length of the name.  *PLEN is
769 // initialized to the length of NAME.
770
771 const char*
772 Layout::linkonce_output_name(const char* name, size_t *plen)
773 {
774   const char* s = name + sizeof(".gnu.linkonce") - 1;
775   if (*s != '.')
776     return name;
777   ++s;
778   const Linkonce_mapping* plm = linkonce_mapping;
779   for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
780     {
781       if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
782         {
783           *plen = plm->tolen;
784           return plm->to;
785         }
786     }
787   return name;
788 }
789
790 // Choose the output section name to use given an input section name.
791 // Set *PLEN to the length of the name.  *PLEN is initialized to the
792 // length of NAME.
793
794 const char*
795 Layout::output_section_name(const char* name, size_t* plen)
796 {
797   if (Layout::is_linkonce(name))
798     {
799       // .gnu.linkonce sections are laid out as though they were named
800       // for the sections are placed into.
801       return Layout::linkonce_output_name(name, plen);
802     }
803
804   // If the section name has no '.', or only an initial '.', we use
805   // the name unchanged (i.e., ".text" is unchanged).
806
807   // Otherwise, if the section name does not include ".rel", we drop
808   // the last '.'  and everything that follows (i.e., ".text.XXX"
809   // becomes ".text").
810
811   // Otherwise, if the section name has zero or one '.' after the
812   // ".rel", we use the name unchanged (i.e., ".rel.text" is
813   // unchanged).
814
815   // Otherwise, we drop the last '.' and everything that follows
816   // (i.e., ".rel.text.XXX" becomes ".rel.text").
817
818   const char* s = name;
819   if (*s == '.')
820     ++s;
821   const char* sdot = strchr(s, '.');
822   if (sdot == NULL)
823     return name;
824
825   const char* srel = strstr(s, ".rel");
826   if (srel == NULL)
827     {
828       *plen = sdot - name;
829       return name;
830     }
831
832   sdot = strchr(srel + 1, '.');
833   if (sdot == NULL)
834     return name;
835   sdot = strchr(sdot + 1, '.');
836   if (sdot == NULL)
837     return name;
838
839   *plen = sdot - name;
840   return name;
841 }
842
843 // Record the signature of a comdat section, and return whether to
844 // include it in the link.  If GROUP is true, this is a regular
845 // section group.  If GROUP is false, this is a group signature
846 // derived from the name of a linkonce section.  We want linkonce
847 // signatures and group signatures to block each other, but we don't
848 // want a linkonce signature to block another linkonce signature.
849
850 bool
851 Layout::add_comdat(const char* signature, bool group)
852 {
853   std::string sig(signature);
854   std::pair<Signatures::iterator, bool> ins(
855     this->signatures_.insert(std::make_pair(sig, group)));
856
857   if (ins.second)
858     {
859       // This is the first time we've seen this signature.
860       return true;
861     }
862
863   if (ins.first->second)
864     {
865       // We've already seen a real section group with this signature.
866       return false;
867     }
868   else if (group)
869     {
870       // This is a real section group, and we've already seen a
871       // linkonce section with tihs signature.  Record that we've seen
872       // a section group, and don't include this section group.
873       ins.first->second = true;
874       return false;
875     }
876   else
877     {
878       // We've already seen a linkonce section and this is a linkonce
879       // section.  These don't block each other--this may be the same
880       // symbol name with different section types.
881       return true;
882     }
883 }
884
885 // Write out data not associated with a section or the symbol table.
886
887 void
888 Layout::write_data(Output_file* of) const
889 {
890   for (Data_list::const_iterator p = this->special_output_list_.begin();
891        p != this->special_output_list_.end();
892        ++p)
893     (*p)->write(of);
894 }
895
896 // Write_data_task methods.
897
898 // We can always run this task.
899
900 Task::Is_runnable_type
901 Write_data_task::is_runnable(Workqueue*)
902 {
903   return IS_RUNNABLE;
904 }
905
906 // We need to unlock FINAL_BLOCKER when finished.
907
908 Task_locker*
909 Write_data_task::locks(Workqueue* workqueue)
910 {
911   return new Task_locker_block(*this->final_blocker_, workqueue);
912 }
913
914 // Run the task--write out the data.
915
916 void
917 Write_data_task::run(Workqueue*)
918 {
919   this->layout_->write_data(this->of_);
920 }
921
922 // Write_symbols_task methods.
923
924 // We can always run this task.
925
926 Task::Is_runnable_type
927 Write_symbols_task::is_runnable(Workqueue*)
928 {
929   return IS_RUNNABLE;
930 }
931
932 // We need to unlock FINAL_BLOCKER when finished.
933
934 Task_locker*
935 Write_symbols_task::locks(Workqueue* workqueue)
936 {
937   return new Task_locker_block(*this->final_blocker_, workqueue);
938 }
939
940 // Run the task--write out the symbols.
941
942 void
943 Write_symbols_task::run(Workqueue*)
944 {
945   this->symtab_->write_globals(this->target_, this->sympool_, this->of_);
946 }
947
948 // Close_task_runner methods.
949
950 // Run the task--close the file.
951
952 void
953 Close_task_runner::run(Workqueue*)
954 {
955   this->of_->close();
956 }
957
958 // Instantiate the templates we need.  We could use the configure
959 // script to restrict this to only the ones for implemented targets.
960
961 template
962 Output_section*
963 Layout::layout<32, false>(Relobj* object, unsigned int shndx, const char* name,
964                           const elfcpp::Shdr<32, false>& shdr, off_t*);
965
966 template
967 Output_section*
968 Layout::layout<32, true>(Relobj* object, unsigned int shndx, const char* name,
969                          const elfcpp::Shdr<32, true>& shdr, off_t*);
970
971 template
972 Output_section*
973 Layout::layout<64, false>(Relobj* object, unsigned int shndx, const char* name,
974                           const elfcpp::Shdr<64, false>& shdr, off_t*);
975
976 template
977 Output_section*
978 Layout::layout<64, true>(Relobj* object, unsigned int shndx, const char* name,
979                          const elfcpp::Shdr<64, true>& shdr, off_t*);
980
981
982 } // End namespace gold.