From Cary Coutant: More support for -shared, including fixes to GOT
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright 2006, 2007 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cstring>
26 #include <algorithm>
27 #include <iostream>
28 #include <utility>
29
30 #include "parameters.h"
31 #include "output.h"
32 #include "symtab.h"
33 #include "dynobj.h"
34 #include "ehframe.h"
35 #include "layout.h"
36
37 namespace gold
38 {
39
40 // Layout_task_runner methods.
41
42 // Lay out the sections.  This is called after all the input objects
43 // have been read.
44
45 void
46 Layout_task_runner::run(Workqueue* workqueue)
47 {
48   off_t file_size = this->layout_->finalize(this->input_objects_,
49                                             this->symtab_);
50
51   // Now we know the final size of the output file and we know where
52   // each piece of information goes.
53   Output_file* of = new Output_file(this->options_,
54                                     this->input_objects_->target());
55   of->open(file_size);
56
57   // Queue up the final set of tasks.
58   gold::queue_final_tasks(this->options_, this->input_objects_,
59                           this->symtab_, this->layout_, workqueue, of);
60 }
61
62 // Layout methods.
63
64 Layout::Layout(const General_options& options)
65   : options_(options), namepool_(), sympool_(), dynpool_(), signatures_(),
66     section_name_map_(), segment_list_(), section_list_(),
67     unattached_section_list_(), special_output_list_(),
68     tls_segment_(NULL), symtab_section_(NULL),
69     dynsym_section_(NULL), dynamic_section_(NULL), dynamic_data_(NULL),
70     eh_frame_section_(NULL), output_file_size_(-1),
71     input_requires_executable_stack_(false),
72     input_with_gnu_stack_note_(false),
73     input_without_gnu_stack_note_(false)
74 {
75   // Make space for more than enough segments for a typical file.
76   // This is just for efficiency--it's OK if we wind up needing more.
77   this->segment_list_.reserve(12);
78
79   // We expect three unattached Output_data objects: the file header,
80   // the segment headers, and the section headers.
81   this->special_output_list_.reserve(3);
82 }
83
84 // Hash a key we use to look up an output section mapping.
85
86 size_t
87 Layout::Hash_key::operator()(const Layout::Key& k) const
88 {
89  return k.first + k.second.first + k.second.second;
90 }
91
92 // Return whether PREFIX is a prefix of STR.
93
94 static inline bool
95 is_prefix_of(const char* prefix, const char* str)
96 {
97   return strncmp(prefix, str, strlen(prefix)) == 0;
98 }
99
100 // Whether to include this section in the link.
101
102 template<int size, bool big_endian>
103 bool
104 Layout::include_section(Object*, const char* name,
105                         const elfcpp::Shdr<size, big_endian>& shdr)
106 {
107   // Some section types are never linked.  Some are only linked when
108   // doing a relocateable link.
109   switch (shdr.get_sh_type())
110     {
111     case elfcpp::SHT_NULL:
112     case elfcpp::SHT_SYMTAB:
113     case elfcpp::SHT_DYNSYM:
114     case elfcpp::SHT_STRTAB:
115     case elfcpp::SHT_HASH:
116     case elfcpp::SHT_DYNAMIC:
117     case elfcpp::SHT_SYMTAB_SHNDX:
118       return false;
119
120     case elfcpp::SHT_RELA:
121     case elfcpp::SHT_REL:
122     case elfcpp::SHT_GROUP:
123       return parameters->output_is_object();
124
125     case elfcpp::SHT_PROGBITS:
126       if (parameters->strip_debug()
127           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
128         {
129           // Debugging sections can only be recognized by name.
130           if (is_prefix_of(".debug", name)
131               || is_prefix_of(".gnu.linkonce.wi.", name)
132               || is_prefix_of(".line", name)
133               || is_prefix_of(".stab", name))
134             return false;
135         }
136       return true;
137
138     default:
139       return true;
140     }
141 }
142
143 // Return an output section named NAME, or NULL if there is none.
144
145 Output_section*
146 Layout::find_output_section(const char* name) const
147 {
148   for (Section_name_map::const_iterator p = this->section_name_map_.begin();
149        p != this->section_name_map_.end();
150        ++p)
151     if (strcmp(p->second->name(), name) == 0)
152       return p->second;
153   return NULL;
154 }
155
156 // Return an output segment of type TYPE, with segment flags SET set
157 // and segment flags CLEAR clear.  Return NULL if there is none.
158
159 Output_segment*
160 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
161                             elfcpp::Elf_Word clear) const
162 {
163   for (Segment_list::const_iterator p = this->segment_list_.begin();
164        p != this->segment_list_.end();
165        ++p)
166     if (static_cast<elfcpp::PT>((*p)->type()) == type
167         && ((*p)->flags() & set) == set
168         && ((*p)->flags() & clear) == 0)
169       return *p;
170   return NULL;
171 }
172
173 // Return the output section to use for section NAME with type TYPE
174 // and section flags FLAGS.
175
176 Output_section*
177 Layout::get_output_section(const char* name, Stringpool::Key name_key,
178                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
179 {
180   // We should ignore some flags.
181   flags &= ~ (elfcpp::SHF_INFO_LINK
182               | elfcpp::SHF_LINK_ORDER
183               | elfcpp::SHF_GROUP
184               | elfcpp::SHF_MERGE
185               | elfcpp::SHF_STRINGS);
186
187   const Key key(name_key, std::make_pair(type, flags));
188   const std::pair<Key, Output_section*> v(key, NULL);
189   std::pair<Section_name_map::iterator, bool> ins(
190     this->section_name_map_.insert(v));
191
192   if (!ins.second)
193     return ins.first->second;
194   else
195     {
196       // This is the first time we've seen this name/type/flags
197       // combination.
198       Output_section* os = this->make_output_section(name, type, flags);
199       ins.first->second = os;
200       return os;
201     }
202 }
203
204 // Return the output section to use for input section SHNDX, with name
205 // NAME, with header HEADER, from object OBJECT.  Set *OFF to the
206 // offset of this input section without the output section.
207
208 template<int size, bool big_endian>
209 Output_section*
210 Layout::layout(Relobj* object, unsigned int shndx, const char* name,
211                const elfcpp::Shdr<size, big_endian>& shdr, off_t* off)
212 {
213   if (!this->include_section(object, name, shdr))
214     return NULL;
215
216   // If we are not doing a relocateable link, choose the name to use
217   // for the output section.
218   size_t len = strlen(name);
219   if (!parameters->output_is_object())
220     name = Layout::output_section_name(name, &len);
221
222   // FIXME: Handle SHF_OS_NONCONFORMING here.
223
224   // Canonicalize the section name.
225   Stringpool::Key name_key;
226   name = this->namepool_.add_prefix(name, len, &name_key);
227
228   // Find the output section.  The output section is selected based on
229   // the section name, type, and flags.
230   Output_section* os = this->get_output_section(name, name_key,
231                                                 shdr.get_sh_type(),
232                                                 shdr.get_sh_flags());
233
234   // Special GNU handling of sections named .eh_frame.
235   if (!parameters->output_is_object()
236       && strcmp(name, ".eh_frame") == 0
237       && shdr.get_sh_size() > 0
238       && shdr.get_sh_type() == elfcpp::SHT_PROGBITS
239       && shdr.get_sh_flags() == elfcpp::SHF_ALLOC)
240     {
241       this->layout_eh_frame(object, shndx, name, shdr, os, off);
242       return os;
243     }
244
245   // FIXME: Handle SHF_LINK_ORDER somewhere.
246
247   *off = os->add_input_section(object, shndx, name, shdr);
248
249   return os;
250 }
251
252 // Special GNU handling of sections named .eh_frame.  They will
253 // normally hold exception frame data.
254
255 template<int size, bool big_endian>
256 void
257 Layout::layout_eh_frame(Relobj* object,
258                         unsigned int shndx,
259                         const char* name,
260                         const elfcpp::Shdr<size, big_endian>& shdr,
261                         Output_section* os, off_t* off)
262 {
263   if (this->eh_frame_section_ == NULL)
264     {
265       this->eh_frame_section_ = os;
266
267       if (this->options_.create_eh_frame_hdr())
268         {
269           Stringpool::Key hdr_name_key;
270           const char* hdr_name = this->namepool_.add(".eh_frame_hdr",
271                                                      false,
272                                                      &hdr_name_key);
273           Output_section* hdr_os =
274             this->get_output_section(hdr_name, hdr_name_key,
275                                      elfcpp::SHT_PROGBITS,
276                                      elfcpp::SHF_ALLOC);
277
278           Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os);
279           hdr_os->add_output_section_data(hdr_posd);
280
281           Output_segment* hdr_oseg =
282             new Output_segment(elfcpp::PT_GNU_EH_FRAME, elfcpp::PF_R);
283           this->segment_list_.push_back(hdr_oseg);
284           hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
285         }
286     }
287
288   gold_assert(this->eh_frame_section_ == os);
289
290   *off = os->add_input_section(object, shndx, name, shdr);
291 }
292
293 // Add POSD to an output section using NAME, TYPE, and FLAGS.
294
295 void
296 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
297                                 elfcpp::Elf_Xword flags,
298                                 Output_section_data* posd)
299 {
300   // Canonicalize the name.
301   Stringpool::Key name_key;
302   name = this->namepool_.add(name, true, &name_key);
303
304   Output_section* os = this->get_output_section(name, name_key, type, flags);
305   os->add_output_section_data(posd);
306 }
307
308 // Map section flags to segment flags.
309
310 elfcpp::Elf_Word
311 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
312 {
313   elfcpp::Elf_Word ret = elfcpp::PF_R;
314   if ((flags & elfcpp::SHF_WRITE) != 0)
315     ret |= elfcpp::PF_W;
316   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
317     ret |= elfcpp::PF_X;
318   return ret;
319 }
320
321 // Make a new Output_section, and attach it to segments as
322 // appropriate.
323
324 Output_section*
325 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
326                             elfcpp::Elf_Xword flags)
327 {
328   Output_section* os = new Output_section(name, type, flags);
329   this->section_list_.push_back(os);
330
331   if ((flags & elfcpp::SHF_ALLOC) == 0)
332     this->unattached_section_list_.push_back(os);
333   else
334     {
335       // This output section goes into a PT_LOAD segment.
336
337       elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
338
339       // The only thing we really care about for PT_LOAD segments is
340       // whether or not they are writable, so that is how we search
341       // for them.  People who need segments sorted on some other
342       // basis will have to wait until we implement a mechanism for
343       // them to describe the segments they want.
344
345       Segment_list::const_iterator p;
346       for (p = this->segment_list_.begin();
347            p != this->segment_list_.end();
348            ++p)
349         {
350           if ((*p)->type() == elfcpp::PT_LOAD
351               && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
352             {
353               (*p)->add_output_section(os, seg_flags);
354               break;
355             }
356         }
357
358       if (p == this->segment_list_.end())
359         {
360           Output_segment* oseg = new Output_segment(elfcpp::PT_LOAD,
361                                                     seg_flags);
362           this->segment_list_.push_back(oseg);
363           oseg->add_output_section(os, seg_flags);
364         }
365
366       // If we see a loadable SHT_NOTE section, we create a PT_NOTE
367       // segment.
368       if (type == elfcpp::SHT_NOTE)
369         {
370           // See if we already have an equivalent PT_NOTE segment.
371           for (p = this->segment_list_.begin();
372                p != segment_list_.end();
373                ++p)
374             {
375               if ((*p)->type() == elfcpp::PT_NOTE
376                   && (((*p)->flags() & elfcpp::PF_W)
377                       == (seg_flags & elfcpp::PF_W)))
378                 {
379                   (*p)->add_output_section(os, seg_flags);
380                   break;
381                 }
382             }
383
384           if (p == this->segment_list_.end())
385             {
386               Output_segment* oseg = new Output_segment(elfcpp::PT_NOTE,
387                                                         seg_flags);
388               this->segment_list_.push_back(oseg);
389               oseg->add_output_section(os, seg_flags);
390             }
391         }
392
393       // If we see a loadable SHF_TLS section, we create a PT_TLS
394       // segment.  There can only be one such segment.
395       if ((flags & elfcpp::SHF_TLS) != 0)
396         {
397           if (this->tls_segment_ == NULL)
398             {
399               this->tls_segment_ = new Output_segment(elfcpp::PT_TLS,
400                                                       seg_flags);
401               this->segment_list_.push_back(this->tls_segment_);
402             }
403           this->tls_segment_->add_output_section(os, seg_flags);
404         }
405     }
406
407   return os;
408 }
409
410 // Handle the .note.GNU-stack section at layout time.  SEEN_GNU_STACK
411 // is whether we saw a .note.GNU-stack section in the object file.
412 // GNU_STACK_FLAGS is the section flags.  The flags give the
413 // protection required for stack memory.  We record this in an
414 // executable as a PT_GNU_STACK segment.  If an object file does not
415 // have a .note.GNU-stack segment, we must assume that it is an old
416 // object.  On some targets that will force an executable stack.
417
418 void
419 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
420 {
421   if (!seen_gnu_stack)
422     this->input_without_gnu_stack_note_ = true;
423   else
424     {
425       this->input_with_gnu_stack_note_ = true;
426       if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
427         this->input_requires_executable_stack_ = true;
428     }
429 }
430
431 // Create the dynamic sections which are needed before we read the
432 // relocs.
433
434 void
435 Layout::create_initial_dynamic_sections(const Input_objects* input_objects,
436                                         Symbol_table* symtab)
437 {
438   if (parameters->doing_static_link())
439     return;
440
441   const char* dynamic_name = this->namepool_.add(".dynamic", false, NULL);
442   this->dynamic_section_ = this->make_output_section(dynamic_name,
443                                                      elfcpp::SHT_DYNAMIC,
444                                                      (elfcpp::SHF_ALLOC
445                                                       | elfcpp::SHF_WRITE));
446
447   symtab->define_in_output_data(input_objects->target(), "_DYNAMIC", NULL,
448                                 this->dynamic_section_, 0, 0,
449                                 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
450                                 elfcpp::STV_HIDDEN, 0, false, false);
451
452   this->dynamic_data_ =  new Output_data_dynamic(&this->dynpool_);
453
454   this->dynamic_section_->add_output_section_data(this->dynamic_data_);
455 }
456
457 // For each output section whose name can be represented as C symbol,
458 // define __start and __stop symbols for the section.  This is a GNU
459 // extension.
460
461 void
462 Layout::define_section_symbols(Symbol_table* symtab, const Target* target)
463 {
464   for (Section_list::const_iterator p = this->section_list_.begin();
465        p != this->section_list_.end();
466        ++p)
467     {
468       const char* const name = (*p)->name();
469       if (name[strspn(name,
470                       ("0123456789"
471                        "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
472                        "abcdefghijklmnopqrstuvwxyz"
473                        "_"))]
474           == '\0')
475         {
476           const std::string name_string(name);
477           const std::string start_name("__start_" + name_string);
478           const std::string stop_name("__stop_" + name_string);
479
480           symtab->define_in_output_data(target,
481                                         start_name.c_str(),
482                                         NULL, // version
483                                         *p,
484                                         0, // value
485                                         0, // symsize
486                                         elfcpp::STT_NOTYPE,
487                                         elfcpp::STB_GLOBAL,
488                                         elfcpp::STV_DEFAULT,
489                                         0, // nonvis
490                                         false, // offset_is_from_end
491                                         false); // only_if_ref
492
493           symtab->define_in_output_data(target,
494                                         stop_name.c_str(),
495                                         NULL, // version
496                                         *p,
497                                         0, // value
498                                         0, // symsize
499                                         elfcpp::STT_NOTYPE,
500                                         elfcpp::STB_GLOBAL,
501                                         elfcpp::STV_DEFAULT,
502                                         0, // nonvis
503                                         true, // offset_is_from_end
504                                         false); // only_if_ref
505         }
506     }
507 }
508
509 // Find the first read-only PT_LOAD segment, creating one if
510 // necessary.
511
512 Output_segment*
513 Layout::find_first_load_seg()
514 {
515   for (Segment_list::const_iterator p = this->segment_list_.begin();
516        p != this->segment_list_.end();
517        ++p)
518     {
519       if ((*p)->type() == elfcpp::PT_LOAD
520           && ((*p)->flags() & elfcpp::PF_R) != 0
521           && ((*p)->flags() & elfcpp::PF_W) == 0)
522         return *p;
523     }
524
525   Output_segment* load_seg = new Output_segment(elfcpp::PT_LOAD, elfcpp::PF_R);
526   this->segment_list_.push_back(load_seg);
527   return load_seg;
528 }
529
530 // Finalize the layout.  When this is called, we have created all the
531 // output sections and all the output segments which are based on
532 // input sections.  We have several things to do, and we have to do
533 // them in the right order, so that we get the right results correctly
534 // and efficiently.
535
536 // 1) Finalize the list of output segments and create the segment
537 // table header.
538
539 // 2) Finalize the dynamic symbol table and associated sections.
540
541 // 3) Determine the final file offset of all the output segments.
542
543 // 4) Determine the final file offset of all the SHF_ALLOC output
544 // sections.
545
546 // 5) Create the symbol table sections and the section name table
547 // section.
548
549 // 6) Finalize the symbol table: set symbol values to their final
550 // value and make a final determination of which symbols are going
551 // into the output symbol table.
552
553 // 7) Create the section table header.
554
555 // 8) Determine the final file offset of all the output sections which
556 // are not SHF_ALLOC, including the section table header.
557
558 // 9) Finalize the ELF file header.
559
560 // This function returns the size of the output file.
561
562 off_t
563 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab)
564 {
565   Target* const target = input_objects->target();
566
567   target->finalize_sections(this);
568
569   this->create_gold_note();
570   this->create_executable_stack_info(target);
571
572   Output_segment* phdr_seg = NULL;
573   if (!parameters->doing_static_link())
574     {
575       // There was a dynamic object in the link.  We need to create
576       // some information for the dynamic linker.
577
578       // Create the PT_PHDR segment which will hold the program
579       // headers.
580       phdr_seg = new Output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
581       this->segment_list_.push_back(phdr_seg);
582
583       // Create the dynamic symbol table, including the hash table.
584       Output_section* dynstr;
585       std::vector<Symbol*> dynamic_symbols;
586       unsigned int local_dynamic_count;
587       Versions versions;
588       this->create_dynamic_symtab(target, symtab, &dynstr,
589                                   &local_dynamic_count, &dynamic_symbols,
590                                   &versions);
591
592       // Create the .interp section to hold the name of the
593       // interpreter, and put it in a PT_INTERP segment.
594       if (!parameters->output_is_shared())
595         this->create_interp(target);
596
597       // Finish the .dynamic section to hold the dynamic data, and put
598       // it in a PT_DYNAMIC segment.
599       this->finish_dynamic_section(input_objects, symtab);
600
601       // We should have added everything we need to the dynamic string
602       // table.
603       this->dynpool_.set_string_offsets();
604
605       // Create the version sections.  We can't do this until the
606       // dynamic string table is complete.
607       this->create_version_sections(&versions, symtab, local_dynamic_count,
608                                     dynamic_symbols, dynstr);
609     }
610
611   // FIXME: Handle PT_GNU_STACK.
612
613   Output_segment* load_seg = this->find_first_load_seg();
614
615   // Lay out the segment headers.
616   Output_segment_headers* segment_headers;
617   segment_headers = new Output_segment_headers(this->segment_list_);
618   load_seg->add_initial_output_data(segment_headers);
619   this->special_output_list_.push_back(segment_headers);
620   if (phdr_seg != NULL)
621     phdr_seg->add_initial_output_data(segment_headers);
622
623   // Lay out the file header.
624   Output_file_header* file_header;
625   file_header = new Output_file_header(target, symtab, segment_headers);
626   load_seg->add_initial_output_data(file_header);
627   this->special_output_list_.push_back(file_header);
628
629   // We set the output section indexes in set_segment_offsets and
630   // set_section_offsets.
631   unsigned int shndx = 1;
632
633   // Set the file offsets of all the segments, and all the sections
634   // they contain.
635   off_t off = this->set_segment_offsets(target, load_seg, &shndx);
636
637   // Set the file offsets of all the data sections not associated with
638   // segments. This makes sure that debug sections have their offsets
639   // before symbols are finalized.
640   off = this->set_section_offsets(off, &shndx, true);
641
642   // Create the symbol table sections.
643   this->create_symtab_sections(input_objects, symtab, &off);
644
645   // Create the .shstrtab section.
646   Output_section* shstrtab_section = this->create_shstrtab();
647
648   // Set the file offsets of all the non-data sections not associated with
649   // segments.
650   off = this->set_section_offsets(off, &shndx, false);
651
652   // Create the section table header.
653   Output_section_headers* oshdrs = this->create_shdrs(&off);
654
655   file_header->set_section_info(oshdrs, shstrtab_section);
656
657   // Now we know exactly where everything goes in the output file.
658   Output_data::layout_complete();
659
660   this->output_file_size_ = off;
661
662   return off;
663 }
664
665 // Create a .note section for an executable or shared library.  This
666 // records the version of gold used to create the binary.
667
668 void
669 Layout::create_gold_note()
670 {
671   if (parameters->output_is_object())
672     return;
673
674   // Authorities all agree that the values in a .note field should
675   // be aligned on 4-byte boundaries for 32-bit binaries.  However,
676   // they differ on what the alignment is for 64-bit binaries.
677   // The GABI says unambiguously they take 8-byte alignment:
678   //    http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
679   // Other documentation says alignment should always be 4 bytes:
680   //    http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
681   // GNU ld and GNU readelf both support the latter (at least as of
682   // version 2.16.91), and glibc always generates the latter for
683   // .note.ABI-tag (as of version 1.6), so that's the one we go with
684   // here.
685 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION   // This is not defined by default.
686   const int size = parameters->get_size();
687 #else
688   const int size = 32;
689 #endif
690
691   // The contents of the .note section.
692   const char* name = "GNU";
693   std::string desc(std::string("gold ") + gold::get_version_string());
694   size_t namesz = strlen(name) + 1;
695   size_t aligned_namesz = align_address(namesz, size / 8);
696   size_t descsz = desc.length() + 1;
697   size_t aligned_descsz = align_address(descsz, size / 8);
698   const int note_type = 4;
699
700   size_t notesz = 3 * (size / 8) + aligned_namesz + aligned_descsz;
701
702   unsigned char buffer[128];
703   gold_assert(sizeof buffer >= notesz);
704   memset(buffer, 0, notesz);
705
706   bool is_big_endian = parameters->is_big_endian();
707
708   if (size == 32)
709     {
710       if (!is_big_endian)
711         {
712           elfcpp::Swap<32, false>::writeval(buffer, namesz);
713           elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
714           elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
715         }
716       else
717         {
718           elfcpp::Swap<32, true>::writeval(buffer, namesz);
719           elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
720           elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
721         }
722     }
723   else if (size == 64)
724     {
725       if (!is_big_endian)
726         {
727           elfcpp::Swap<64, false>::writeval(buffer, namesz);
728           elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
729           elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
730         }
731       else
732         {
733           elfcpp::Swap<64, true>::writeval(buffer, namesz);
734           elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
735           elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
736         }
737     }
738   else
739     gold_unreachable();
740
741   memcpy(buffer + 3 * (size / 8), name, namesz);
742   memcpy(buffer + 3 * (size / 8) + aligned_namesz, desc.data(), descsz);
743
744   const char* note_name = this->namepool_.add(".note", false, NULL);
745   Output_section* os = this->make_output_section(note_name,
746                                                  elfcpp::SHT_NOTE,
747                                                  0);
748   Output_section_data* posd = new Output_data_const(buffer, notesz,
749                                                     size / 8);
750   os->add_output_section_data(posd);
751 }
752
753 // Record whether the stack should be executable.  This can be set
754 // from the command line using the -z execstack or -z noexecstack
755 // options.  Otherwise, if any input file has a .note.GNU-stack
756 // section with the SHF_EXECINSTR flag set, the stack should be
757 // executable.  Otherwise, if at least one input file a
758 // .note.GNU-stack section, and some input file has no .note.GNU-stack
759 // section, we use the target default for whether the stack should be
760 // executable.  Otherwise, we don't generate a stack note.  When
761 // generating a object file, we create a .note.GNU-stack section with
762 // the appropriate marking.  When generating an executable or shared
763 // library, we create a PT_GNU_STACK segment.
764
765 void
766 Layout::create_executable_stack_info(const Target* target)
767 {
768   bool is_stack_executable;
769   if (this->options_.is_execstack_set())
770     is_stack_executable = this->options_.is_stack_executable();
771   else if (!this->input_with_gnu_stack_note_)
772     return;
773   else
774     {
775       if (this->input_requires_executable_stack_)
776         is_stack_executable = true;
777       else if (this->input_without_gnu_stack_note_)
778         is_stack_executable = target->is_default_stack_executable();
779       else
780         is_stack_executable = false;
781     }
782
783   if (parameters->output_is_object())
784     {
785       const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
786       elfcpp::Elf_Xword flags = 0;
787       if (is_stack_executable)
788         flags |= elfcpp::SHF_EXECINSTR;
789       this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
790     }
791   else
792     {
793       int flags = elfcpp::PF_R | elfcpp::PF_W;
794       if (is_stack_executable)
795         flags |= elfcpp::PF_X;
796       Output_segment* oseg = new Output_segment(elfcpp::PT_GNU_STACK, flags);
797       this->segment_list_.push_back(oseg);
798     }
799 }
800
801 // Return whether SEG1 should be before SEG2 in the output file.  This
802 // is based entirely on the segment type and flags.  When this is
803 // called the segment addresses has normally not yet been set.
804
805 bool
806 Layout::segment_precedes(const Output_segment* seg1,
807                          const Output_segment* seg2)
808 {
809   elfcpp::Elf_Word type1 = seg1->type();
810   elfcpp::Elf_Word type2 = seg2->type();
811
812   // The single PT_PHDR segment is required to precede any loadable
813   // segment.  We simply make it always first.
814   if (type1 == elfcpp::PT_PHDR)
815     {
816       gold_assert(type2 != elfcpp::PT_PHDR);
817       return true;
818     }
819   if (type2 == elfcpp::PT_PHDR)
820     return false;
821
822   // The single PT_INTERP segment is required to precede any loadable
823   // segment.  We simply make it always second.
824   if (type1 == elfcpp::PT_INTERP)
825     {
826       gold_assert(type2 != elfcpp::PT_INTERP);
827       return true;
828     }
829   if (type2 == elfcpp::PT_INTERP)
830     return false;
831
832   // We then put PT_LOAD segments before any other segments.
833   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
834     return true;
835   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
836     return false;
837
838   // We put the PT_TLS segment last, because that is where the dynamic
839   // linker expects to find it (this is just for efficiency; other
840   // positions would also work correctly).
841   if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
842     return false;
843   if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
844     return true;
845
846   const elfcpp::Elf_Word flags1 = seg1->flags();
847   const elfcpp::Elf_Word flags2 = seg2->flags();
848
849   // The order of non-PT_LOAD segments is unimportant.  We simply sort
850   // by the numeric segment type and flags values.  There should not
851   // be more than one segment with the same type and flags.
852   if (type1 != elfcpp::PT_LOAD)
853     {
854       if (type1 != type2)
855         return type1 < type2;
856       gold_assert(flags1 != flags2);
857       return flags1 < flags2;
858     }
859
860   // We sort PT_LOAD segments based on the flags.  Readonly segments
861   // come before writable segments.  Then executable segments come
862   // before non-executable segments.  Then the unlikely case of a
863   // non-readable segment comes before the normal case of a readable
864   // segment.  If there are multiple segments with the same type and
865   // flags, we require that the address be set, and we sort by
866   // virtual address and then physical address.
867   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
868     return (flags1 & elfcpp::PF_W) == 0;
869   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
870     return (flags1 & elfcpp::PF_X) != 0;
871   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
872     return (flags1 & elfcpp::PF_R) == 0;
873
874   uint64_t vaddr1 = seg1->vaddr();
875   uint64_t vaddr2 = seg2->vaddr();
876   if (vaddr1 != vaddr2)
877     return vaddr1 < vaddr2;
878
879   uint64_t paddr1 = seg1->paddr();
880   uint64_t paddr2 = seg2->paddr();
881   gold_assert(paddr1 != paddr2);
882   return paddr1 < paddr2;
883 }
884
885 // Set the file offsets of all the segments, and all the sections they
886 // contain.  They have all been created.  LOAD_SEG must be be laid out
887 // first.  Return the offset of the data to follow.
888
889 off_t
890 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
891                             unsigned int *pshndx)
892 {
893   // Sort them into the final order.
894   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
895             Layout::Compare_segments());
896
897   // Find the PT_LOAD segments, and set their addresses and offsets
898   // and their section's addresses and offsets.
899   uint64_t addr;
900   if (options_.user_set_text_segment_address())
901     addr = options_.text_segment_address();
902   else
903     addr = target->default_text_segment_address();
904   off_t off = 0;
905   bool was_readonly = false;
906   for (Segment_list::iterator p = this->segment_list_.begin();
907        p != this->segment_list_.end();
908        ++p)
909     {
910       if ((*p)->type() == elfcpp::PT_LOAD)
911         {
912           if (load_seg != NULL && load_seg != *p)
913             gold_unreachable();
914           load_seg = NULL;
915
916           // If the last segment was readonly, and this one is not,
917           // then skip the address forward one page, maintaining the
918           // same position within the page.  This lets us store both
919           // segments overlapping on a single page in the file, but
920           // the loader will put them on different pages in memory.
921
922           uint64_t orig_addr = addr;
923           uint64_t orig_off = off;
924
925           uint64_t aligned_addr = addr;
926           uint64_t abi_pagesize = target->abi_pagesize();
927
928           // FIXME: This should depend on the -n and -N options.
929           (*p)->set_minimum_addralign(target->common_pagesize());
930
931           if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
932             {
933               uint64_t align = (*p)->addralign();
934
935               addr = align_address(addr, align);
936               aligned_addr = addr;
937               if ((addr & (abi_pagesize - 1)) != 0)
938                 addr = addr + abi_pagesize;
939             }
940
941           unsigned int shndx_hold = *pshndx;
942           off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
943           uint64_t new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
944
945           // Now that we know the size of this segment, we may be able
946           // to save a page in memory, at the cost of wasting some
947           // file space, by instead aligning to the start of a new
948           // page.  Here we use the real machine page size rather than
949           // the ABI mandated page size.
950
951           if (aligned_addr != addr)
952             {
953               uint64_t common_pagesize = target->common_pagesize();
954               uint64_t first_off = (common_pagesize
955                                     - (aligned_addr
956                                        & (common_pagesize - 1)));
957               uint64_t last_off = new_addr & (common_pagesize - 1);
958               if (first_off > 0
959                   && last_off > 0
960                   && ((aligned_addr & ~ (common_pagesize - 1))
961                       != (new_addr & ~ (common_pagesize - 1)))
962                   && first_off + last_off <= common_pagesize)
963                 {
964                   *pshndx = shndx_hold;
965                   addr = align_address(aligned_addr, common_pagesize);
966                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
967                   new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
968                 }
969             }
970
971           addr = new_addr;
972
973           if (((*p)->flags() & elfcpp::PF_W) == 0)
974             was_readonly = true;
975         }
976     }
977
978   // Handle the non-PT_LOAD segments, setting their offsets from their
979   // section's offsets.
980   for (Segment_list::iterator p = this->segment_list_.begin();
981        p != this->segment_list_.end();
982        ++p)
983     {
984       if ((*p)->type() != elfcpp::PT_LOAD)
985         (*p)->set_offset();
986     }
987
988   return off;
989 }
990
991 // Set the file offset of all the sections not associated with a
992 // segment.
993
994 off_t
995 Layout::set_section_offsets(off_t off,
996                             unsigned int* pshndx,
997                             bool do_bits_sections)
998 {
999   for (Section_list::iterator p = this->unattached_section_list_.begin();
1000        p != this->unattached_section_list_.end();
1001        ++p)
1002     {
1003       bool is_bits_section = ((*p)->type() == elfcpp::SHT_PROGBITS
1004                               || (*p)->type() == elfcpp::SHT_NOBITS);
1005       if (is_bits_section != do_bits_sections)
1006         continue;
1007       (*p)->set_out_shndx(*pshndx);
1008       ++*pshndx;
1009       if ((*p)->offset() != -1)
1010         continue;
1011       off = align_address(off, (*p)->addralign());
1012       (*p)->set_address(0, off);
1013       off += (*p)->data_size();
1014     }
1015   return off;
1016 }
1017
1018 // Create the symbol table sections.  Here we also set the final
1019 // values of the symbols.  At this point all the loadable sections are
1020 // fully laid out.
1021
1022 void
1023 Layout::create_symtab_sections(const Input_objects* input_objects,
1024                                Symbol_table* symtab,
1025                                off_t* poff)
1026 {
1027   int symsize;
1028   unsigned int align;
1029   if (parameters->get_size() == 32)
1030     {
1031       symsize = elfcpp::Elf_sizes<32>::sym_size;
1032       align = 4;
1033     }
1034   else if (parameters->get_size() == 64)
1035     {
1036       symsize = elfcpp::Elf_sizes<64>::sym_size;
1037       align = 8;
1038     }
1039   else
1040     gold_unreachable();
1041
1042   off_t off = *poff;
1043   off = align_address(off, align);
1044   off_t startoff = off;
1045
1046   // Save space for the dummy symbol at the start of the section.  We
1047   // never bother to write this out--it will just be left as zero.
1048   off += symsize;
1049   unsigned int local_symbol_index = 1;
1050
1051   // Add STT_SECTION symbols for each Output section which needs one.
1052   for (Section_list::iterator p = this->section_list_.begin();
1053        p != this->section_list_.end();
1054        ++p)
1055     {
1056       if (!(*p)->needs_symtab_index())
1057         (*p)->set_symtab_index(-1U);
1058       else
1059         {
1060           (*p)->set_symtab_index(local_symbol_index);
1061           ++local_symbol_index;
1062           off += symsize;
1063         }
1064     }
1065
1066   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1067        p != input_objects->relobj_end();
1068        ++p)
1069     {
1070       Task_lock_obj<Object> tlo(**p);
1071       unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
1072                                                         off,
1073                                                         &this->sympool_);
1074       off += (index - local_symbol_index) * symsize;
1075       local_symbol_index = index;
1076     }
1077
1078   unsigned int local_symcount = local_symbol_index;
1079   gold_assert(local_symcount * symsize == off - startoff);
1080
1081   off_t dynoff;
1082   size_t dyn_global_index;
1083   size_t dyncount;
1084   if (this->dynsym_section_ == NULL)
1085     {
1086       dynoff = 0;
1087       dyn_global_index = 0;
1088       dyncount = 0;
1089     }
1090   else
1091     {
1092       dyn_global_index = this->dynsym_section_->info();
1093       off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
1094       dynoff = this->dynsym_section_->offset() + locsize;
1095       dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
1096       gold_assert(static_cast<off_t>(dyncount * symsize)
1097                   == this->dynsym_section_->data_size() - locsize);
1098     }
1099
1100   off = symtab->finalize(local_symcount, off, dynoff, dyn_global_index,
1101                          dyncount, &this->sympool_);
1102
1103   if (!parameters->strip_all())
1104     {
1105       this->sympool_.set_string_offsets();
1106
1107       const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
1108       Output_section* osymtab = this->make_output_section(symtab_name,
1109                                                           elfcpp::SHT_SYMTAB,
1110                                                           0);
1111       this->symtab_section_ = osymtab;
1112
1113       Output_section_data* pos = new Output_data_space(off - startoff,
1114                                                        align);
1115       osymtab->add_output_section_data(pos);
1116
1117       const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
1118       Output_section* ostrtab = this->make_output_section(strtab_name,
1119                                                           elfcpp::SHT_STRTAB,
1120                                                           0);
1121
1122       Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
1123       ostrtab->add_output_section_data(pstr);
1124
1125       osymtab->set_address(0, startoff);
1126       osymtab->set_link_section(ostrtab);
1127       osymtab->set_info(local_symcount);
1128       osymtab->set_entsize(symsize);
1129
1130       *poff = off;
1131     }
1132 }
1133
1134 // Create the .shstrtab section, which holds the names of the
1135 // sections.  At the time this is called, we have created all the
1136 // output sections except .shstrtab itself.
1137
1138 Output_section*
1139 Layout::create_shstrtab()
1140 {
1141   // FIXME: We don't need to create a .shstrtab section if we are
1142   // stripping everything.
1143
1144   const char* name = this->namepool_.add(".shstrtab", false, NULL);
1145
1146   this->namepool_.set_string_offsets();
1147
1148   Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
1149
1150   Output_section_data* posd = new Output_data_strtab(&this->namepool_);
1151   os->add_output_section_data(posd);
1152
1153   return os;
1154 }
1155
1156 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
1157 // offset.
1158
1159 Output_section_headers*
1160 Layout::create_shdrs(off_t* poff)
1161 {
1162   Output_section_headers* oshdrs;
1163   oshdrs = new Output_section_headers(this,
1164                                       &this->segment_list_,
1165                                       &this->unattached_section_list_,
1166                                       &this->namepool_);
1167   off_t off = align_address(*poff, oshdrs->addralign());
1168   oshdrs->set_address(0, off);
1169   off += oshdrs->data_size();
1170   *poff = off;
1171   this->special_output_list_.push_back(oshdrs);
1172   return oshdrs;
1173 }
1174
1175 // Create the dynamic symbol table.
1176
1177 void
1178 Layout::create_dynamic_symtab(const Target* target, Symbol_table* symtab,
1179                               Output_section **pdynstr,
1180                               unsigned int* plocal_dynamic_count,
1181                               std::vector<Symbol*>* pdynamic_symbols,
1182                               Versions* pversions)
1183 {
1184   // Count all the symbols in the dynamic symbol table, and set the
1185   // dynamic symbol indexes.
1186
1187   // Skip symbol 0, which is always all zeroes.
1188   unsigned int index = 1;
1189
1190   // Add STT_SECTION symbols for each Output section which needs one.
1191   for (Section_list::iterator p = this->section_list_.begin();
1192        p != this->section_list_.end();
1193        ++p)
1194     {
1195       if (!(*p)->needs_dynsym_index())
1196         (*p)->set_dynsym_index(-1U);
1197       else
1198         {
1199           (*p)->set_dynsym_index(index);
1200           ++index;
1201         }
1202     }
1203
1204   // FIXME: Some targets apparently require local symbols in the
1205   // dynamic symbol table.  Here is where we will have to count them,
1206   // and set the dynamic symbol indexes, and add the names to
1207   // this->dynpool_.
1208
1209   unsigned int local_symcount = index;
1210   *plocal_dynamic_count = local_symcount;
1211
1212   // FIXME: We have to tell set_dynsym_indexes whether the
1213   // -E/--export-dynamic option was used.
1214   index = symtab->set_dynsym_indexes(target, index, pdynamic_symbols,
1215                                      &this->dynpool_, pversions);
1216
1217   int symsize;
1218   unsigned int align;
1219   const int size = parameters->get_size();
1220   if (size == 32)
1221     {
1222       symsize = elfcpp::Elf_sizes<32>::sym_size;
1223       align = 4;
1224     }
1225   else if (size == 64)
1226     {
1227       symsize = elfcpp::Elf_sizes<64>::sym_size;
1228       align = 8;
1229     }
1230   else
1231     gold_unreachable();
1232
1233   // Create the dynamic symbol table section.
1234
1235   const char* dynsym_name = this->namepool_.add(".dynsym", false, NULL);
1236   Output_section* dynsym = this->make_output_section(dynsym_name,
1237                                                      elfcpp::SHT_DYNSYM,
1238                                                      elfcpp::SHF_ALLOC);
1239
1240   Output_section_data* odata = new Output_data_space(index * symsize,
1241                                                      align);
1242   dynsym->add_output_section_data(odata);
1243
1244   dynsym->set_info(local_symcount);
1245   dynsym->set_entsize(symsize);
1246   dynsym->set_addralign(align);
1247
1248   this->dynsym_section_ = dynsym;
1249
1250   Output_data_dynamic* const odyn = this->dynamic_data_;
1251   odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
1252   odyn->add_constant(elfcpp::DT_SYMENT, symsize);
1253
1254   // Create the dynamic string table section.
1255
1256   const char* dynstr_name = this->namepool_.add(".dynstr", false, NULL);
1257   Output_section* dynstr = this->make_output_section(dynstr_name,
1258                                                      elfcpp::SHT_STRTAB,
1259                                                      elfcpp::SHF_ALLOC);
1260
1261   Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
1262   dynstr->add_output_section_data(strdata);
1263
1264   dynsym->set_link_section(dynstr);
1265   this->dynamic_section_->set_link_section(dynstr);
1266
1267   odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
1268   odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
1269
1270   *pdynstr = dynstr;
1271
1272   // Create the hash tables.
1273
1274   // FIXME: We need an option to create a GNU hash table.
1275
1276   unsigned char* phash;
1277   unsigned int hashlen;
1278   Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
1279                                 &phash, &hashlen);
1280
1281   const char* hash_name = this->namepool_.add(".hash", false, NULL);
1282   Output_section* hashsec = this->make_output_section(hash_name,
1283                                                       elfcpp::SHT_HASH,
1284                                                       elfcpp::SHF_ALLOC);
1285
1286   Output_section_data* hashdata = new Output_data_const_buffer(phash,
1287                                                                hashlen,
1288                                                                align);
1289   hashsec->add_output_section_data(hashdata);
1290
1291   hashsec->set_link_section(dynsym);
1292   hashsec->set_entsize(4);
1293
1294   odyn->add_section_address(elfcpp::DT_HASH, hashsec);
1295 }
1296
1297 // Create the version sections.
1298
1299 void
1300 Layout::create_version_sections(const Versions* versions,
1301                                 const Symbol_table* symtab,
1302                                 unsigned int local_symcount,
1303                                 const std::vector<Symbol*>& dynamic_symbols,
1304                                 const Output_section* dynstr)
1305 {
1306   if (!versions->any_defs() && !versions->any_needs())
1307     return;
1308
1309   if (parameters->get_size() == 32)
1310     {
1311       if (parameters->is_big_endian())
1312         {
1313 #ifdef HAVE_TARGET_32_BIG
1314           this->sized_create_version_sections
1315               SELECT_SIZE_ENDIAN_NAME(32, true)(
1316                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1317                   SELECT_SIZE_ENDIAN(32, true));
1318 #else
1319           gold_unreachable();
1320 #endif
1321         }
1322       else
1323         {
1324 #ifdef HAVE_TARGET_32_LITTLE
1325           this->sized_create_version_sections
1326               SELECT_SIZE_ENDIAN_NAME(32, false)(
1327                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1328                   SELECT_SIZE_ENDIAN(32, false));
1329 #else
1330           gold_unreachable();
1331 #endif
1332         }
1333     }
1334   else if (parameters->get_size() == 64)
1335     {
1336       if (parameters->is_big_endian())
1337         {
1338 #ifdef HAVE_TARGET_64_BIG
1339           this->sized_create_version_sections
1340               SELECT_SIZE_ENDIAN_NAME(64, true)(
1341                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1342                   SELECT_SIZE_ENDIAN(64, true));
1343 #else
1344           gold_unreachable();
1345 #endif
1346         }
1347       else
1348         {
1349 #ifdef HAVE_TARGET_64_LITTLE
1350           this->sized_create_version_sections
1351               SELECT_SIZE_ENDIAN_NAME(64, false)(
1352                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1353                   SELECT_SIZE_ENDIAN(64, false));
1354 #else
1355           gold_unreachable();
1356 #endif
1357         }
1358     }
1359   else
1360     gold_unreachable();
1361 }
1362
1363 // Create the version sections, sized version.
1364
1365 template<int size, bool big_endian>
1366 void
1367 Layout::sized_create_version_sections(
1368     const Versions* versions,
1369     const Symbol_table* symtab,
1370     unsigned int local_symcount,
1371     const std::vector<Symbol*>& dynamic_symbols,
1372     const Output_section* dynstr
1373     ACCEPT_SIZE_ENDIAN)
1374 {
1375   const char* vname = this->namepool_.add(".gnu.version", false, NULL);
1376   Output_section* vsec = this->make_output_section(vname,
1377                                                    elfcpp::SHT_GNU_versym,
1378                                                    elfcpp::SHF_ALLOC);
1379
1380   unsigned char* vbuf;
1381   unsigned int vsize;
1382   versions->symbol_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1383       symtab, &this->dynpool_, local_symcount, dynamic_symbols, &vbuf, &vsize
1384       SELECT_SIZE_ENDIAN(size, big_endian));
1385
1386   Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2);
1387
1388   vsec->add_output_section_data(vdata);
1389   vsec->set_entsize(2);
1390   vsec->set_link_section(this->dynsym_section_);
1391
1392   Output_data_dynamic* const odyn = this->dynamic_data_;
1393   odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
1394
1395   if (versions->any_defs())
1396     {
1397       const char* vdname = this->namepool_.add(".gnu.version_d", false, NULL);
1398       Output_section *vdsec;
1399       vdsec = this->make_output_section(vdname, elfcpp::SHT_GNU_verdef,
1400                                         elfcpp::SHF_ALLOC);
1401
1402       unsigned char* vdbuf;
1403       unsigned int vdsize;
1404       unsigned int vdentries;
1405       versions->def_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1406           &this->dynpool_, &vdbuf, &vdsize, &vdentries
1407           SELECT_SIZE_ENDIAN(size, big_endian));
1408
1409       Output_section_data* vddata = new Output_data_const_buffer(vdbuf,
1410                                                                  vdsize,
1411                                                                  4);
1412
1413       vdsec->add_output_section_data(vddata);
1414       vdsec->set_link_section(dynstr);
1415       vdsec->set_info(vdentries);
1416
1417       odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
1418       odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
1419     }
1420
1421   if (versions->any_needs())
1422     {
1423       const char* vnname = this->namepool_.add(".gnu.version_r", false, NULL);
1424       Output_section* vnsec;
1425       vnsec = this->make_output_section(vnname, elfcpp::SHT_GNU_verneed,
1426                                         elfcpp::SHF_ALLOC);
1427
1428       unsigned char* vnbuf;
1429       unsigned int vnsize;
1430       unsigned int vnentries;
1431       versions->need_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)
1432         (&this->dynpool_, &vnbuf, &vnsize, &vnentries
1433          SELECT_SIZE_ENDIAN(size, big_endian));
1434
1435       Output_section_data* vndata = new Output_data_const_buffer(vnbuf,
1436                                                                  vnsize,
1437                                                                  4);
1438
1439       vnsec->add_output_section_data(vndata);
1440       vnsec->set_link_section(dynstr);
1441       vnsec->set_info(vnentries);
1442
1443       odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
1444       odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
1445     }
1446 }
1447
1448 // Create the .interp section and PT_INTERP segment.
1449
1450 void
1451 Layout::create_interp(const Target* target)
1452 {
1453   const char* interp = this->options_.dynamic_linker();
1454   if (interp == NULL)
1455     {
1456       interp = target->dynamic_linker();
1457       gold_assert(interp != NULL);
1458     }
1459
1460   size_t len = strlen(interp) + 1;
1461
1462   Output_section_data* odata = new Output_data_const(interp, len, 1);
1463
1464   const char* interp_name = this->namepool_.add(".interp", false, NULL);
1465   Output_section* osec = this->make_output_section(interp_name,
1466                                                    elfcpp::SHT_PROGBITS,
1467                                                    elfcpp::SHF_ALLOC);
1468   osec->add_output_section_data(odata);
1469
1470   Output_segment* oseg = new Output_segment(elfcpp::PT_INTERP, elfcpp::PF_R);
1471   this->segment_list_.push_back(oseg);
1472   oseg->add_initial_output_section(osec, elfcpp::PF_R);
1473 }
1474
1475 // Finish the .dynamic section and PT_DYNAMIC segment.
1476
1477 void
1478 Layout::finish_dynamic_section(const Input_objects* input_objects,
1479                                const Symbol_table* symtab)
1480 {
1481   Output_segment* oseg = new Output_segment(elfcpp::PT_DYNAMIC,
1482                                             elfcpp::PF_R | elfcpp::PF_W);
1483   this->segment_list_.push_back(oseg);
1484   oseg->add_initial_output_section(this->dynamic_section_,
1485                                    elfcpp::PF_R | elfcpp::PF_W);
1486
1487   Output_data_dynamic* const odyn = this->dynamic_data_;
1488
1489   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
1490        p != input_objects->dynobj_end();
1491        ++p)
1492     {
1493       // FIXME: Handle --as-needed.
1494       odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
1495     }
1496
1497   // FIXME: Support --init and --fini.
1498   Symbol* sym = symtab->lookup("_init");
1499   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1500     odyn->add_symbol(elfcpp::DT_INIT, sym);
1501
1502   sym = symtab->lookup("_fini");
1503   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1504     odyn->add_symbol(elfcpp::DT_FINI, sym);
1505
1506   // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
1507
1508   // Add a DT_RPATH entry if needed.
1509   const General_options::Dir_list& rpath(this->options_.rpath());
1510   if (!rpath.empty())
1511     {
1512       std::string rpath_val;
1513       for (General_options::Dir_list::const_iterator p = rpath.begin();
1514            p != rpath.end();
1515            ++p)
1516         {
1517           if (rpath_val.empty())
1518             rpath_val = p->name();
1519           else
1520             {
1521               // Eliminate duplicates.
1522               General_options::Dir_list::const_iterator q;
1523               for (q = rpath.begin(); q != p; ++q)
1524                 if (q->name() == p->name())
1525                   break;
1526               if (q == p)
1527                 {
1528                   rpath_val += ':';
1529                   rpath_val += p->name();
1530                 }
1531             }
1532         }
1533
1534       odyn->add_string(elfcpp::DT_RPATH, rpath_val);
1535     }
1536 }
1537
1538 // The mapping of .gnu.linkonce section names to real section names.
1539
1540 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
1541 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
1542 {
1543   MAPPING_INIT("d.rel.ro", ".data.rel.ro"),     // Must be before "d".
1544   MAPPING_INIT("t", ".text"),
1545   MAPPING_INIT("r", ".rodata"),
1546   MAPPING_INIT("d", ".data"),
1547   MAPPING_INIT("b", ".bss"),
1548   MAPPING_INIT("s", ".sdata"),
1549   MAPPING_INIT("sb", ".sbss"),
1550   MAPPING_INIT("s2", ".sdata2"),
1551   MAPPING_INIT("sb2", ".sbss2"),
1552   MAPPING_INIT("wi", ".debug_info"),
1553   MAPPING_INIT("td", ".tdata"),
1554   MAPPING_INIT("tb", ".tbss"),
1555   MAPPING_INIT("lr", ".lrodata"),
1556   MAPPING_INIT("l", ".ldata"),
1557   MAPPING_INIT("lb", ".lbss"),
1558 };
1559 #undef MAPPING_INIT
1560
1561 const int Layout::linkonce_mapping_count =
1562   sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
1563
1564 // Return the name of the output section to use for a .gnu.linkonce
1565 // section.  This is based on the default ELF linker script of the old
1566 // GNU linker.  For example, we map a name like ".gnu.linkonce.t.foo"
1567 // to ".text".  Set *PLEN to the length of the name.  *PLEN is
1568 // initialized to the length of NAME.
1569
1570 const char*
1571 Layout::linkonce_output_name(const char* name, size_t *plen)
1572 {
1573   const char* s = name + sizeof(".gnu.linkonce") - 1;
1574   if (*s != '.')
1575     return name;
1576   ++s;
1577   const Linkonce_mapping* plm = linkonce_mapping;
1578   for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
1579     {
1580       if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
1581         {
1582           *plen = plm->tolen;
1583           return plm->to;
1584         }
1585     }
1586   return name;
1587 }
1588
1589 // Choose the output section name to use given an input section name.
1590 // Set *PLEN to the length of the name.  *PLEN is initialized to the
1591 // length of NAME.
1592
1593 const char*
1594 Layout::output_section_name(const char* name, size_t* plen)
1595 {
1596   if (Layout::is_linkonce(name))
1597     {
1598       // .gnu.linkonce sections are laid out as though they were named
1599       // for the sections are placed into.
1600       return Layout::linkonce_output_name(name, plen);
1601     }
1602
1603   // gcc 4.3 generates the following sorts of section names when it
1604   // needs a section name specific to a function:
1605   //   .text.FN
1606   //   .rodata.FN
1607   //   .sdata2.FN
1608   //   .data.FN
1609   //   .data.rel.FN
1610   //   .data.rel.local.FN
1611   //   .data.rel.ro.FN
1612   //   .data.rel.ro.local.FN
1613   //   .sdata.FN
1614   //   .bss.FN
1615   //   .sbss.FN
1616   //   .tdata.FN
1617   //   .tbss.FN
1618
1619   // The GNU linker maps all of those to the part before the .FN,
1620   // except that .data.rel.local.FN is mapped to .data, and
1621   // .data.rel.ro.local.FN is mapped to .data.rel.ro.  The sections
1622   // beginning with .data.rel.ro.local are grouped together.
1623
1624   // For an anonymous namespace, the string FN can contain a '.'.
1625
1626   // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
1627   // GNU linker maps to .rodata.
1628
1629   // The .data.rel.ro sections enable a security feature triggered by
1630   // the -z relro option.  Section which need to be relocated at
1631   // program startup time but which may be readonly after startup are
1632   // grouped into .data.rel.ro.  They are then put into a PT_GNU_RELRO
1633   // segment.  The dynamic linker will make that segment writable,
1634   // perform relocations, and then make it read-only.  FIXME: We do
1635   // not yet implement this optimization.
1636
1637   // It is hard to handle this in a principled way.
1638
1639   // These are the rules we follow:
1640
1641   // If the section name has no initial '.', or no dot other than an
1642   // initial '.', we use the name unchanged (i.e., "mysection" and
1643   // ".text" are unchanged).
1644
1645   // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
1646
1647   // Otherwise, we drop the second '.' and everything that comes after
1648   // it (i.e., ".text.XXX" becomes ".text").
1649
1650   const char* s = name;
1651   if (*s != '.')
1652     return name;
1653   ++s;
1654   const char* sdot = strchr(s, '.');
1655   if (sdot == NULL)
1656     return name;
1657
1658   const char* const data_rel_ro = ".data.rel.ro";
1659   if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
1660     {
1661       *plen = strlen(data_rel_ro);
1662       return data_rel_ro;
1663     }
1664
1665   *plen = sdot - name;
1666   return name;
1667 }
1668
1669 // Record the signature of a comdat section, and return whether to
1670 // include it in the link.  If GROUP is true, this is a regular
1671 // section group.  If GROUP is false, this is a group signature
1672 // derived from the name of a linkonce section.  We want linkonce
1673 // signatures and group signatures to block each other, but we don't
1674 // want a linkonce signature to block another linkonce signature.
1675
1676 bool
1677 Layout::add_comdat(const char* signature, bool group)
1678 {
1679   std::string sig(signature);
1680   std::pair<Signatures::iterator, bool> ins(
1681     this->signatures_.insert(std::make_pair(sig, group)));
1682
1683   if (ins.second)
1684     {
1685       // This is the first time we've seen this signature.
1686       return true;
1687     }
1688
1689   if (ins.first->second)
1690     {
1691       // We've already seen a real section group with this signature.
1692       return false;
1693     }
1694   else if (group)
1695     {
1696       // This is a real section group, and we've already seen a
1697       // linkonce section with this signature.  Record that we've seen
1698       // a section group, and don't include this section group.
1699       ins.first->second = true;
1700       return false;
1701     }
1702   else
1703     {
1704       // We've already seen a linkonce section and this is a linkonce
1705       // section.  These don't block each other--this may be the same
1706       // symbol name with different section types.
1707       return true;
1708     }
1709 }
1710
1711 // Write out data not associated with a section or the symbol table.
1712
1713 void
1714 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
1715 {
1716   if (!parameters->strip_all())
1717     {
1718       const Output_section* symtab_section = this->symtab_section_;
1719       for (Section_list::const_iterator p = this->section_list_.begin();
1720            p != this->section_list_.end();
1721            ++p)
1722         {
1723           if ((*p)->needs_symtab_index())
1724             {
1725               gold_assert(symtab_section != NULL);
1726               unsigned int index = (*p)->symtab_index();
1727               gold_assert(index > 0 && index != -1U);
1728               off_t off = (symtab_section->offset()
1729                            + index * symtab_section->entsize());
1730               symtab->write_section_symbol(*p, of, off);
1731             }
1732         }
1733     }
1734
1735   const Output_section* dynsym_section = this->dynsym_section_;
1736   for (Section_list::const_iterator p = this->section_list_.begin();
1737        p != this->section_list_.end();
1738        ++p)
1739     {
1740       if ((*p)->needs_dynsym_index())
1741         {
1742           gold_assert(dynsym_section != NULL);
1743           unsigned int index = (*p)->dynsym_index();
1744           gold_assert(index > 0 && index != -1U);
1745           off_t off = (dynsym_section->offset()
1746                        + index * dynsym_section->entsize());
1747           symtab->write_section_symbol(*p, of, off);
1748         }
1749     }
1750
1751   // Write out the Output_sections.  Most won't have anything to
1752   // write, since most of the data will come from input sections which
1753   // are handled elsewhere.  But some Output_sections do have
1754   // Output_data.
1755   for (Section_list::const_iterator p = this->section_list_.begin();
1756        p != this->section_list_.end();
1757        ++p)
1758     (*p)->write(of);
1759
1760   // Write out the Output_data which are not in an Output_section.
1761   for (Data_list::const_iterator p = this->special_output_list_.begin();
1762        p != this->special_output_list_.end();
1763        ++p)
1764     (*p)->write(of);
1765 }
1766
1767 // Write_data_task methods.
1768
1769 // We can always run this task.
1770
1771 Task::Is_runnable_type
1772 Write_data_task::is_runnable(Workqueue*)
1773 {
1774   return IS_RUNNABLE;
1775 }
1776
1777 // We need to unlock FINAL_BLOCKER when finished.
1778
1779 Task_locker*
1780 Write_data_task::locks(Workqueue* workqueue)
1781 {
1782   return new Task_locker_block(*this->final_blocker_, workqueue);
1783 }
1784
1785 // Run the task--write out the data.
1786
1787 void
1788 Write_data_task::run(Workqueue*)
1789 {
1790   this->layout_->write_data(this->symtab_, this->of_);
1791 }
1792
1793 // Write_symbols_task methods.
1794
1795 // We can always run this task.
1796
1797 Task::Is_runnable_type
1798 Write_symbols_task::is_runnable(Workqueue*)
1799 {
1800   return IS_RUNNABLE;
1801 }
1802
1803 // We need to unlock FINAL_BLOCKER when finished.
1804
1805 Task_locker*
1806 Write_symbols_task::locks(Workqueue* workqueue)
1807 {
1808   return new Task_locker_block(*this->final_blocker_, workqueue);
1809 }
1810
1811 // Run the task--write out the symbols.
1812
1813 void
1814 Write_symbols_task::run(Workqueue*)
1815 {
1816   this->symtab_->write_globals(this->target_, this->sympool_, this->dynpool_,
1817                                this->of_);
1818 }
1819
1820 // Close_task_runner methods.
1821
1822 // Run the task--close the file.
1823
1824 void
1825 Close_task_runner::run(Workqueue*)
1826 {
1827   this->of_->close();
1828 }
1829
1830 // Instantiate the templates we need.  We could use the configure
1831 // script to restrict this to only the ones for implemented targets.
1832
1833 #ifdef HAVE_TARGET_32_LITTLE
1834 template
1835 Output_section*
1836 Layout::layout<32, false>(Relobj* object, unsigned int shndx, const char* name,
1837                           const elfcpp::Shdr<32, false>& shdr, off_t*);
1838 #endif
1839
1840 #ifdef HAVE_TARGET_32_BIG
1841 template
1842 Output_section*
1843 Layout::layout<32, true>(Relobj* object, unsigned int shndx, const char* name,
1844                          const elfcpp::Shdr<32, true>& shdr, off_t*);
1845 #endif
1846
1847 #ifdef HAVE_TARGET_64_LITTLE
1848 template
1849 Output_section*
1850 Layout::layout<64, false>(Relobj* object, unsigned int shndx, const char* name,
1851                           const elfcpp::Shdr<64, false>& shdr, off_t*);
1852 #endif
1853
1854 #ifdef HAVE_TARGET_64_BIG
1855 template
1856 Output_section*
1857 Layout::layout<64, true>(Relobj* object, unsigned int shndx, const char* name,
1858                          const elfcpp::Shdr<64, true>& shdr, off_t*);
1859 #endif
1860
1861
1862 } // End namespace gold.