Implement SIZEOF_HEADERS, section constraints, other minor linker
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright 2006, 2007, 2008 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 "options.h"
32 #include "script.h"
33 #include "script-sections.h"
34 #include "output.h"
35 #include "symtab.h"
36 #include "dynobj.h"
37 #include "ehframe.h"
38 #include "compressed_output.h"
39 #include "layout.h"
40
41 namespace gold
42 {
43
44 // Layout_task_runner methods.
45
46 // Lay out the sections.  This is called after all the input objects
47 // have been read.
48
49 void
50 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
51 {
52   off_t file_size = this->layout_->finalize(this->input_objects_,
53                                             this->symtab_,
54                                             task);
55
56   // Now we know the final size of the output file and we know where
57   // each piece of information goes.
58   Output_file* of = new Output_file(parameters->output_file_name());
59   of->open(file_size);
60
61   // Queue up the final set of tasks.
62   gold::queue_final_tasks(this->options_, this->input_objects_,
63                           this->symtab_, this->layout_, workqueue, of);
64 }
65
66 // Layout methods.
67
68 Layout::Layout(const General_options& options, Script_options* script_options)
69   : options_(options), script_options_(script_options), namepool_(),
70     sympool_(), dynpool_(), signatures_(),
71     section_name_map_(), segment_list_(), section_list_(),
72     unattached_section_list_(), special_output_list_(),
73     section_headers_(NULL), tls_segment_(NULL), symtab_section_(NULL),
74     dynsym_section_(NULL), dynamic_section_(NULL), dynamic_data_(NULL),
75     eh_frame_section_(NULL), output_file_size_(-1),
76     input_requires_executable_stack_(false),
77     input_with_gnu_stack_note_(false),
78     input_without_gnu_stack_note_(false),
79     has_static_tls_(false),
80     any_postprocessing_sections_(false)
81 {
82   // Make space for more than enough segments for a typical file.
83   // This is just for efficiency--it's OK if we wind up needing more.
84   this->segment_list_.reserve(12);
85
86   // We expect two unattached Output_data objects: the file header and
87   // the segment headers.
88   this->special_output_list_.reserve(2);
89 }
90
91 // Hash a key we use to look up an output section mapping.
92
93 size_t
94 Layout::Hash_key::operator()(const Layout::Key& k) const
95 {
96  return k.first + k.second.first + k.second.second;
97 }
98
99 // Return whether PREFIX is a prefix of STR.
100
101 static inline bool
102 is_prefix_of(const char* prefix, const char* str)
103 {
104   return strncmp(prefix, str, strlen(prefix)) == 0;
105 }
106
107 // Returns whether the given section is in the list of
108 // debug-sections-used-by-some-version-of-gdb.  Currently,
109 // we've checked versions of gdb up to and including 6.7.1.
110
111 static const char* gdb_sections[] =
112 { ".debug_abbrev",
113   // ".debug_aranges",   // not used by gdb as of 6.7.1
114   ".debug_frame",
115   ".debug_info",
116   ".debug_line",
117   ".debug_loc",
118   ".debug_macinfo",
119   // ".debug_pubnames",  // not used by gdb as of 6.7.1
120   ".debug_ranges",
121   ".debug_str",
122 };
123
124 static inline bool
125 is_gdb_debug_section(const char* str)
126 {
127   // We can do this faster: binary search or a hashtable.  But why bother?
128   for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
129     if (strcmp(str, gdb_sections[i]) == 0)
130       return true;
131   return false;
132 }
133
134 // Whether to include this section in the link.
135
136 template<int size, bool big_endian>
137 bool
138 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
139                         const elfcpp::Shdr<size, big_endian>& shdr)
140 {
141   // Some section types are never linked.  Some are only linked when
142   // doing a relocateable link.
143   switch (shdr.get_sh_type())
144     {
145     case elfcpp::SHT_NULL:
146     case elfcpp::SHT_SYMTAB:
147     case elfcpp::SHT_DYNSYM:
148     case elfcpp::SHT_STRTAB:
149     case elfcpp::SHT_HASH:
150     case elfcpp::SHT_DYNAMIC:
151     case elfcpp::SHT_SYMTAB_SHNDX:
152       return false;
153
154     case elfcpp::SHT_RELA:
155     case elfcpp::SHT_REL:
156     case elfcpp::SHT_GROUP:
157       return parameters->output_is_object();
158
159     case elfcpp::SHT_PROGBITS:
160       if (parameters->strip_debug()
161           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
162         {
163           // Debugging sections can only be recognized by name.
164           if (is_prefix_of(".debug", name)
165               || is_prefix_of(".gnu.linkonce.wi.", name)
166               || is_prefix_of(".line", name)
167               || is_prefix_of(".stab", name))
168             return false;
169         }
170       if (parameters->strip_debug_gdb()
171           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
172         {
173           // Debugging sections can only be recognized by name.
174           if (is_prefix_of(".debug", name)
175               && !is_gdb_debug_section(name))
176             return false;
177         }
178       return true;
179
180     default:
181       return true;
182     }
183 }
184
185 // Return an output section named NAME, or NULL if there is none.
186
187 Output_section*
188 Layout::find_output_section(const char* name) const
189 {
190   for (Section_list::const_iterator p = this->section_list_.begin();
191        p != this->section_list_.end();
192        ++p)
193     if (strcmp((*p)->name(), name) == 0)
194       return *p;
195   return NULL;
196 }
197
198 // Return an output segment of type TYPE, with segment flags SET set
199 // and segment flags CLEAR clear.  Return NULL if there is none.
200
201 Output_segment*
202 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
203                             elfcpp::Elf_Word clear) const
204 {
205   for (Segment_list::const_iterator p = this->segment_list_.begin();
206        p != this->segment_list_.end();
207        ++p)
208     if (static_cast<elfcpp::PT>((*p)->type()) == type
209         && ((*p)->flags() & set) == set
210         && ((*p)->flags() & clear) == 0)
211       return *p;
212   return NULL;
213 }
214
215 // Return the output section to use for section NAME with type TYPE
216 // and section flags FLAGS.  NAME must be canonicalized in the string
217 // pool, and NAME_KEY is the key.
218
219 Output_section*
220 Layout::get_output_section(const char* name, Stringpool::Key name_key,
221                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
222 {
223   const Key key(name_key, std::make_pair(type, flags));
224   const std::pair<Key, Output_section*> v(key, NULL);
225   std::pair<Section_name_map::iterator, bool> ins(
226     this->section_name_map_.insert(v));
227
228   if (!ins.second)
229     return ins.first->second;
230   else
231     {
232       // This is the first time we've seen this name/type/flags
233       // combination.
234       Output_section* os = this->make_output_section(name, type, flags);
235       ins.first->second = os;
236       return os;
237     }
238 }
239
240 // Pick the output section to use for section NAME, in input file
241 // RELOBJ, with type TYPE and flags FLAGS.  RELOBJ may be NULL for a
242 // linker created section.  ADJUST_NAME is true if we should apply the
243 // standard name mappings in Layout::output_section_name.  This will
244 // return NULL if the input section should be discarded.
245
246 Output_section*
247 Layout::choose_output_section(const Relobj* relobj, const char* name,
248                               elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
249                               bool adjust_name)
250 {
251   // We should ignore some flags.  FIXME: This will need some
252   // adjustment for ld -r.
253   flags &= ~ (elfcpp::SHF_INFO_LINK
254               | elfcpp::SHF_LINK_ORDER
255               | elfcpp::SHF_GROUP
256               | elfcpp::SHF_MERGE
257               | elfcpp::SHF_STRINGS);
258
259   if (this->script_options_->saw_sections_clause())
260     {
261       // We are using a SECTIONS clause, so the output section is
262       // chosen based only on the name.
263
264       Script_sections* ss = this->script_options_->script_sections();
265       const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
266       Output_section** output_section_slot;
267       name = ss->output_section_name(file_name, name, &output_section_slot);
268       if (name == NULL)
269         {
270           // The SECTIONS clause says to discard this input section.
271           return NULL;
272         }
273
274       // If this is an orphan section--one not mentioned in the linker
275       // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
276       // default processing below.
277
278       if (output_section_slot != NULL)
279         {
280           if (*output_section_slot != NULL)
281             return *output_section_slot;
282
283           // We don't put sections found in the linker script into
284           // SECTION_NAME_MAP_.  That keeps us from getting confused
285           // if an orphan section is mapped to a section with the same
286           // name as one in the linker script.
287
288           name = this->namepool_.add(name, false, NULL);
289
290           Output_section* os = this->make_output_section(name, type, flags);
291           os->set_found_in_sections_clause();
292           *output_section_slot = os;
293           return os;
294         }
295     }
296
297   // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
298
299   // Turn NAME from the name of the input section into the name of the
300   // output section.
301
302   size_t len = strlen(name);
303   if (adjust_name && !parameters->output_is_object())
304     name = Layout::output_section_name(name, &len);
305
306   Stringpool::Key name_key;
307   name = this->namepool_.add_with_length(name, len, true, &name_key);
308
309   // Find or make the output section.  The output section is selected
310   // based on the section name, type, and flags.
311   return this->get_output_section(name, name_key, type, flags);
312 }
313
314 // Return the output section to use for input section SHNDX, with name
315 // NAME, with header HEADER, from object OBJECT.  RELOC_SHNDX is the
316 // index of a relocation section which applies to this section, or 0
317 // if none, or -1U if more than one.  RELOC_TYPE is the type of the
318 // relocation section if there is one.  Set *OFF to the offset of this
319 // input section without the output section.  Return NULL if the
320 // section should be discarded.  Set *OFF to -1 if the section
321 // contents should not be written directly to the output file, but
322 // will instead receive special handling.
323
324 template<int size, bool big_endian>
325 Output_section*
326 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
327                const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
328                unsigned int reloc_shndx, unsigned int, off_t* off)
329 {
330   if (!this->include_section(object, name, shdr))
331     return NULL;
332
333   Output_section* os = this->choose_output_section(object,
334                                                    name,
335                                                    shdr.get_sh_type(),
336                                                    shdr.get_sh_flags(),
337                                                    true);
338   if (os == NULL)
339     return NULL;
340
341   // FIXME: Handle SHF_LINK_ORDER somewhere.
342
343   *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
344                                this->script_options_->saw_sections_clause());
345
346   return os;
347 }
348
349 // Special GNU handling of sections name .eh_frame.  They will
350 // normally hold exception frame data as defined by the C++ ABI
351 // (http://codesourcery.com/cxx-abi/).
352
353 template<int size, bool big_endian>
354 Output_section*
355 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
356                         const unsigned char* symbols,
357                         off_t symbols_size,
358                         const unsigned char* symbol_names,
359                         off_t symbol_names_size,
360                         unsigned int shndx,
361                         const elfcpp::Shdr<size, big_endian>& shdr,
362                         unsigned int reloc_shndx, unsigned int reloc_type,
363                         off_t* off)
364 {
365   gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
366   gold_assert(shdr.get_sh_flags() == elfcpp::SHF_ALLOC);
367
368   const char* const name = ".eh_frame";
369   Output_section* os = this->choose_output_section(object,
370                                                    name,
371                                                    elfcpp::SHT_PROGBITS,
372                                                    elfcpp::SHF_ALLOC,
373                                                    false);
374   if (os == NULL)
375     return NULL;
376
377   if (this->eh_frame_section_ == NULL)
378     {
379       this->eh_frame_section_ = os;
380       this->eh_frame_data_ = new Eh_frame();
381       os->add_output_section_data(this->eh_frame_data_);
382
383       if (this->options_.create_eh_frame_hdr())
384         {
385           Output_section* hdr_os =
386             this->choose_output_section(NULL,
387                                         ".eh_frame_hdr",
388                                         elfcpp::SHT_PROGBITS,
389                                         elfcpp::SHF_ALLOC,
390                                         false);
391
392           if (hdr_os != NULL)
393             {
394               Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
395                                                         this->eh_frame_data_);
396               hdr_os->add_output_section_data(hdr_posd);
397
398               hdr_os->set_after_input_sections();
399
400               Output_segment* hdr_oseg;
401               hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
402                                                    elfcpp::PF_R);
403               hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
404
405               this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
406             }
407         }
408     }
409
410   gold_assert(this->eh_frame_section_ == os);
411
412   if (this->eh_frame_data_->add_ehframe_input_section(object,
413                                                       symbols,
414                                                       symbols_size,
415                                                       symbol_names,
416                                                       symbol_names_size,
417                                                       shndx,
418                                                       reloc_shndx,
419                                                       reloc_type))
420     *off = -1;
421   else
422     {
423       // We couldn't handle this .eh_frame section for some reason.
424       // Add it as a normal section.
425       bool saw_sections_clause = this->script_options_->saw_sections_clause();
426       *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
427                                    saw_sections_clause);
428     }
429
430   return os;
431 }
432
433 // Add POSD to an output section using NAME, TYPE, and FLAGS.
434
435 void
436 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
437                                 elfcpp::Elf_Xword flags,
438                                 Output_section_data* posd)
439 {
440   Output_section* os = this->choose_output_section(NULL, name, type, flags,
441                                                    false);
442   if (os != NULL)
443     os->add_output_section_data(posd);
444 }
445
446 // Map section flags to segment flags.
447
448 elfcpp::Elf_Word
449 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
450 {
451   elfcpp::Elf_Word ret = elfcpp::PF_R;
452   if ((flags & elfcpp::SHF_WRITE) != 0)
453     ret |= elfcpp::PF_W;
454   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
455     ret |= elfcpp::PF_X;
456   return ret;
457 }
458
459 // Sometimes we compress sections.  This is typically done for
460 // sections that are not part of normal program execution (such as
461 // .debug_* sections), and where the readers of these sections know
462 // how to deal with compressed sections.  (To make it easier for them,
463 // we will rename the ouput section in such cases from .foo to
464 // .foo.zlib.nnnn, where nnnn is the uncompressed size.)  This routine
465 // doesn't say for certain whether we'll compress -- it depends on
466 // commandline options as well -- just whether this section is a
467 // candidate for compression.
468
469 static bool
470 is_compressible_debug_section(const char* secname)
471 {
472   return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
473 }
474
475 // Make a new Output_section, and attach it to segments as
476 // appropriate.
477
478 Output_section*
479 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
480                             elfcpp::Elf_Xword flags)
481 {
482   Output_section* os;
483   if ((flags & elfcpp::SHF_ALLOC) == 0
484       && this->options_.compress_debug_sections()
485       && is_compressible_debug_section(name))
486     os = new Output_compressed_section(&this->options_, name, type, flags);
487   else
488     os = new Output_section(name, type, flags);
489
490   this->section_list_.push_back(os);
491
492   if ((flags & elfcpp::SHF_ALLOC) == 0)
493     this->unattached_section_list_.push_back(os);
494   else
495     {
496       // If we have a SECTIONS clause, we can't handle the attachment
497       // to segments until after we've seen all the sections.
498       if (this->script_options_->saw_sections_clause())
499         return os;
500
501       // This output section goes into a PT_LOAD segment.
502
503       elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
504
505       // The only thing we really care about for PT_LOAD segments is
506       // whether or not they are writable, so that is how we search
507       // for them.  People who need segments sorted on some other
508       // basis will have to wait until we implement a mechanism for
509       // them to describe the segments they want.
510
511       Segment_list::const_iterator p;
512       for (p = this->segment_list_.begin();
513            p != this->segment_list_.end();
514            ++p)
515         {
516           if ((*p)->type() == elfcpp::PT_LOAD
517               && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
518             {
519               (*p)->add_output_section(os, seg_flags);
520               break;
521             }
522         }
523
524       if (p == this->segment_list_.end())
525         {
526           Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
527                                                            seg_flags);
528           oseg->add_output_section(os, seg_flags);
529         }
530
531       // If we see a loadable SHT_NOTE section, we create a PT_NOTE
532       // segment.
533       if (type == elfcpp::SHT_NOTE)
534         {
535           // See if we already have an equivalent PT_NOTE segment.
536           for (p = this->segment_list_.begin();
537                p != segment_list_.end();
538                ++p)
539             {
540               if ((*p)->type() == elfcpp::PT_NOTE
541                   && (((*p)->flags() & elfcpp::PF_W)
542                       == (seg_flags & elfcpp::PF_W)))
543                 {
544                   (*p)->add_output_section(os, seg_flags);
545                   break;
546                 }
547             }
548
549           if (p == this->segment_list_.end())
550             {
551               Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
552                                                                seg_flags);
553               oseg->add_output_section(os, seg_flags);
554             }
555         }
556
557       // If we see a loadable SHF_TLS section, we create a PT_TLS
558       // segment.  There can only be one such segment.
559       if ((flags & elfcpp::SHF_TLS) != 0)
560         {
561           if (this->tls_segment_ == NULL)
562             this->tls_segment_ = this->make_output_segment(elfcpp::PT_TLS,
563                                                            seg_flags);
564           this->tls_segment_->add_output_section(os, seg_flags);
565         }
566     }
567
568   return os;
569 }
570
571 // Return the number of segments we expect to see.
572
573 size_t
574 Layout::expected_segment_count() const
575 {
576   size_t ret = this->segment_list_.size();
577
578   // If we didn't see a SECTIONS clause in a linker script, we should
579   // already have the complete list of segments.  Otherwise we ask the
580   // SECTIONS clause how many segments it expects, and add in the ones
581   // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
582
583   if (!this->script_options_->saw_sections_clause())
584     return ret;
585   else
586     {
587       const Script_sections* ss = this->script_options_->script_sections();
588       return ret + ss->expected_segment_count(this);
589     }
590 }
591
592 // Handle the .note.GNU-stack section at layout time.  SEEN_GNU_STACK
593 // is whether we saw a .note.GNU-stack section in the object file.
594 // GNU_STACK_FLAGS is the section flags.  The flags give the
595 // protection required for stack memory.  We record this in an
596 // executable as a PT_GNU_STACK segment.  If an object file does not
597 // have a .note.GNU-stack segment, we must assume that it is an old
598 // object.  On some targets that will force an executable stack.
599
600 void
601 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
602 {
603   if (!seen_gnu_stack)
604     this->input_without_gnu_stack_note_ = true;
605   else
606     {
607       this->input_with_gnu_stack_note_ = true;
608       if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
609         this->input_requires_executable_stack_ = true;
610     }
611 }
612
613 // Create the dynamic sections which are needed before we read the
614 // relocs.
615
616 void
617 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
618 {
619   if (parameters->doing_static_link())
620     return;
621
622   this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
623                                                        elfcpp::SHT_DYNAMIC,
624                                                        (elfcpp::SHF_ALLOC
625                                                         | elfcpp::SHF_WRITE),
626                                                        false);
627
628   symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
629                                 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
630                                 elfcpp::STV_HIDDEN, 0, false, false);
631
632   this->dynamic_data_ =  new Output_data_dynamic(&this->dynpool_);
633
634   this->dynamic_section_->add_output_section_data(this->dynamic_data_);
635 }
636
637 // For each output section whose name can be represented as C symbol,
638 // define __start and __stop symbols for the section.  This is a GNU
639 // extension.
640
641 void
642 Layout::define_section_symbols(Symbol_table* symtab)
643 {
644   for (Section_list::const_iterator p = this->section_list_.begin();
645        p != this->section_list_.end();
646        ++p)
647     {
648       const char* const name = (*p)->name();
649       if (name[strspn(name,
650                       ("0123456789"
651                        "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
652                        "abcdefghijklmnopqrstuvwxyz"
653                        "_"))]
654           == '\0')
655         {
656           const std::string name_string(name);
657           const std::string start_name("__start_" + name_string);
658           const std::string stop_name("__stop_" + name_string);
659
660           symtab->define_in_output_data(start_name.c_str(),
661                                         NULL, // version
662                                         *p,
663                                         0, // value
664                                         0, // symsize
665                                         elfcpp::STT_NOTYPE,
666                                         elfcpp::STB_GLOBAL,
667                                         elfcpp::STV_DEFAULT,
668                                         0, // nonvis
669                                         false, // offset_is_from_end
670                                         true); // only_if_ref
671
672           symtab->define_in_output_data(stop_name.c_str(),
673                                         NULL, // version
674                                         *p,
675                                         0, // value
676                                         0, // symsize
677                                         elfcpp::STT_NOTYPE,
678                                         elfcpp::STB_GLOBAL,
679                                         elfcpp::STV_DEFAULT,
680                                         0, // nonvis
681                                         true, // offset_is_from_end
682                                         true); // only_if_ref
683         }
684     }
685 }
686
687 // Find the first read-only PT_LOAD segment, creating one if
688 // necessary.
689
690 Output_segment*
691 Layout::find_first_load_seg()
692 {
693   for (Segment_list::const_iterator p = this->segment_list_.begin();
694        p != this->segment_list_.end();
695        ++p)
696     {
697       if ((*p)->type() == elfcpp::PT_LOAD
698           && ((*p)->flags() & elfcpp::PF_R) != 0
699           && ((*p)->flags() & elfcpp::PF_W) == 0)
700         return *p;
701     }
702
703   Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
704                                                        elfcpp::PF_R);
705   return load_seg;
706 }
707
708 // Finalize the layout.  When this is called, we have created all the
709 // output sections and all the output segments which are based on
710 // input sections.  We have several things to do, and we have to do
711 // them in the right order, so that we get the right results correctly
712 // and efficiently.
713
714 // 1) Finalize the list of output segments and create the segment
715 // table header.
716
717 // 2) Finalize the dynamic symbol table and associated sections.
718
719 // 3) Determine the final file offset of all the output segments.
720
721 // 4) Determine the final file offset of all the SHF_ALLOC output
722 // sections.
723
724 // 5) Create the symbol table sections and the section name table
725 // section.
726
727 // 6) Finalize the symbol table: set symbol values to their final
728 // value and make a final determination of which symbols are going
729 // into the output symbol table.
730
731 // 7) Create the section table header.
732
733 // 8) Determine the final file offset of all the output sections which
734 // are not SHF_ALLOC, including the section table header.
735
736 // 9) Finalize the ELF file header.
737
738 // This function returns the size of the output file.
739
740 off_t
741 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
742                  const Task* task)
743 {
744   Target* const target = input_objects->target();
745
746   target->finalize_sections(this);
747
748   this->count_local_symbols(task, input_objects);
749
750   this->create_gold_note();
751   this->create_executable_stack_info(target);
752
753   Output_segment* phdr_seg = NULL;
754   if (!parameters->output_is_object() && !parameters->doing_static_link())
755     {
756       // There was a dynamic object in the link.  We need to create
757       // some information for the dynamic linker.
758
759       // Create the PT_PHDR segment which will hold the program
760       // headers.
761       phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
762
763       // Create the dynamic symbol table, including the hash table.
764       Output_section* dynstr;
765       std::vector<Symbol*> dynamic_symbols;
766       unsigned int local_dynamic_count;
767       Versions versions(this->options_, &this->dynpool_);
768       this->create_dynamic_symtab(input_objects, symtab, &dynstr,
769                                   &local_dynamic_count, &dynamic_symbols,
770                                   &versions);
771
772       // Create the .interp section to hold the name of the
773       // interpreter, and put it in a PT_INTERP segment.
774       if (!parameters->output_is_shared())
775         this->create_interp(target);
776
777       // Finish the .dynamic section to hold the dynamic data, and put
778       // it in a PT_DYNAMIC segment.
779       this->finish_dynamic_section(input_objects, symtab);
780
781       // We should have added everything we need to the dynamic string
782       // table.
783       this->dynpool_.set_string_offsets();
784
785       // Create the version sections.  We can't do this until the
786       // dynamic string table is complete.
787       this->create_version_sections(&versions, symtab, local_dynamic_count,
788                                     dynamic_symbols, dynstr);
789     }
790
791   // If there is a SECTIONS clause, put all the input sections into
792   // the required order.
793   Output_segment* load_seg;
794   if (this->script_options_->saw_sections_clause())
795     load_seg = this->set_section_addresses_from_script(symtab);
796   else
797     load_seg = this->find_first_load_seg();
798
799   gold_assert(phdr_seg == NULL || load_seg != NULL);
800
801   // Lay out the segment headers.
802   Output_segment_headers* segment_headers;
803   segment_headers = new Output_segment_headers(this->segment_list_);
804   if (load_seg != NULL)
805     load_seg->add_initial_output_data(segment_headers);
806   if (phdr_seg != NULL)
807     phdr_seg->add_initial_output_data(segment_headers);
808
809   // Lay out the file header.
810   Output_file_header* file_header;
811   file_header = new Output_file_header(target, symtab, segment_headers,
812                                        this->script_options_->entry());
813   if (load_seg != NULL)
814     load_seg->add_initial_output_data(file_header);
815
816   this->special_output_list_.push_back(file_header);
817   this->special_output_list_.push_back(segment_headers);
818
819   // We set the output section indexes in set_segment_offsets and
820   // set_section_indexes.
821   unsigned int shndx = 1;
822
823   // Set the file offsets of all the segments, and all the sections
824   // they contain.
825   off_t off = this->set_segment_offsets(target, load_seg, &shndx);
826
827   // Set the file offsets of all the non-data sections we've seen so
828   // far which don't have to wait for the input sections.  We need
829   // this in order to finalize local symbols in non-allocated
830   // sections.
831   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
832
833   // Create the symbol table sections.
834   this->create_symtab_sections(input_objects, symtab, &off);
835   if (!parameters->doing_static_link())
836     this->assign_local_dynsym_offsets(input_objects);
837
838   // Process any symbol assignments from a linker script.  This must
839   // be called after the symbol table has been finalized.
840   this->script_options_->finalize_symbols(symtab, this);
841
842   // Create the .shstrtab section.
843   Output_section* shstrtab_section = this->create_shstrtab();
844
845   // Set the file offsets of the rest of the non-data sections which
846   // don't have to wait for the input sections.
847   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
848
849   // Now that all sections have been created, set the section indexes.
850   shndx = this->set_section_indexes(shndx);
851
852   // Create the section table header.
853   this->create_shdrs(&off);
854
855   // If there are no sections which require postprocessing, we can
856   // handle the section names now, and avoid a resize later.
857   if (!this->any_postprocessing_sections_)
858     off = this->set_section_offsets(off,
859                                     STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
860
861   file_header->set_section_info(this->section_headers_, shstrtab_section);
862
863   // Now we know exactly where everything goes in the output file
864   // (except for non-allocated sections which require postprocessing).
865   Output_data::layout_complete();
866
867   this->output_file_size_ = off;
868
869   return off;
870 }
871
872 // Create a .note section for an executable or shared library.  This
873 // records the version of gold used to create the binary.
874
875 void
876 Layout::create_gold_note()
877 {
878   if (parameters->output_is_object())
879     return;
880
881   // Authorities all agree that the values in a .note field should
882   // be aligned on 4-byte boundaries for 32-bit binaries.  However,
883   // they differ on what the alignment is for 64-bit binaries.
884   // The GABI says unambiguously they take 8-byte alignment:
885   //    http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
886   // Other documentation says alignment should always be 4 bytes:
887   //    http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
888   // GNU ld and GNU readelf both support the latter (at least as of
889   // version 2.16.91), and glibc always generates the latter for
890   // .note.ABI-tag (as of version 1.6), so that's the one we go with
891   // here.
892 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION   // This is not defined by default.
893   const int size = parameters->get_size();
894 #else
895   const int size = 32;
896 #endif
897
898   // The contents of the .note section.
899   const char* name = "GNU";
900   std::string desc(std::string("gold ") + gold::get_version_string());
901   size_t namesz = strlen(name) + 1;
902   size_t aligned_namesz = align_address(namesz, size / 8);
903   size_t descsz = desc.length() + 1;
904   size_t aligned_descsz = align_address(descsz, size / 8);
905   const int note_type = 4;
906
907   size_t notesz = 3 * (size / 8) + aligned_namesz + aligned_descsz;
908
909   unsigned char buffer[128];
910   gold_assert(sizeof buffer >= notesz);
911   memset(buffer, 0, notesz);
912
913   bool is_big_endian = parameters->is_big_endian();
914
915   if (size == 32)
916     {
917       if (!is_big_endian)
918         {
919           elfcpp::Swap<32, false>::writeval(buffer, namesz);
920           elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
921           elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
922         }
923       else
924         {
925           elfcpp::Swap<32, true>::writeval(buffer, namesz);
926           elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
927           elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
928         }
929     }
930   else if (size == 64)
931     {
932       if (!is_big_endian)
933         {
934           elfcpp::Swap<64, false>::writeval(buffer, namesz);
935           elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
936           elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
937         }
938       else
939         {
940           elfcpp::Swap<64, true>::writeval(buffer, namesz);
941           elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
942           elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
943         }
944     }
945   else
946     gold_unreachable();
947
948   memcpy(buffer + 3 * (size / 8), name, namesz);
949   memcpy(buffer + 3 * (size / 8) + aligned_namesz, desc.data(), descsz);
950
951   const char* note_name = this->namepool_.add(".note", false, NULL);
952   Output_section* os = this->make_output_section(note_name,
953                                                  elfcpp::SHT_NOTE,
954                                                  0);
955   Output_section_data* posd = new Output_data_const(buffer, notesz,
956                                                     size / 8);
957   os->add_output_section_data(posd);
958 }
959
960 // Record whether the stack should be executable.  This can be set
961 // from the command line using the -z execstack or -z noexecstack
962 // options.  Otherwise, if any input file has a .note.GNU-stack
963 // section with the SHF_EXECINSTR flag set, the stack should be
964 // executable.  Otherwise, if at least one input file a
965 // .note.GNU-stack section, and some input file has no .note.GNU-stack
966 // section, we use the target default for whether the stack should be
967 // executable.  Otherwise, we don't generate a stack note.  When
968 // generating a object file, we create a .note.GNU-stack section with
969 // the appropriate marking.  When generating an executable or shared
970 // library, we create a PT_GNU_STACK segment.
971
972 void
973 Layout::create_executable_stack_info(const Target* target)
974 {
975   bool is_stack_executable;
976   if (this->options_.is_execstack_set())
977     is_stack_executable = this->options_.is_stack_executable();
978   else if (!this->input_with_gnu_stack_note_)
979     return;
980   else
981     {
982       if (this->input_requires_executable_stack_)
983         is_stack_executable = true;
984       else if (this->input_without_gnu_stack_note_)
985         is_stack_executable = target->is_default_stack_executable();
986       else
987         is_stack_executable = false;
988     }
989
990   if (parameters->output_is_object())
991     {
992       const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
993       elfcpp::Elf_Xword flags = 0;
994       if (is_stack_executable)
995         flags |= elfcpp::SHF_EXECINSTR;
996       this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
997     }
998   else
999     {
1000       int flags = elfcpp::PF_R | elfcpp::PF_W;
1001       if (is_stack_executable)
1002         flags |= elfcpp::PF_X;
1003       this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1004     }
1005 }
1006
1007 // Return whether SEG1 should be before SEG2 in the output file.  This
1008 // is based entirely on the segment type and flags.  When this is
1009 // called the segment addresses has normally not yet been set.
1010
1011 bool
1012 Layout::segment_precedes(const Output_segment* seg1,
1013                          const Output_segment* seg2)
1014 {
1015   elfcpp::Elf_Word type1 = seg1->type();
1016   elfcpp::Elf_Word type2 = seg2->type();
1017
1018   // The single PT_PHDR segment is required to precede any loadable
1019   // segment.  We simply make it always first.
1020   if (type1 == elfcpp::PT_PHDR)
1021     {
1022       gold_assert(type2 != elfcpp::PT_PHDR);
1023       return true;
1024     }
1025   if (type2 == elfcpp::PT_PHDR)
1026     return false;
1027
1028   // The single PT_INTERP segment is required to precede any loadable
1029   // segment.  We simply make it always second.
1030   if (type1 == elfcpp::PT_INTERP)
1031     {
1032       gold_assert(type2 != elfcpp::PT_INTERP);
1033       return true;
1034     }
1035   if (type2 == elfcpp::PT_INTERP)
1036     return false;
1037
1038   // We then put PT_LOAD segments before any other segments.
1039   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1040     return true;
1041   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1042     return false;
1043
1044   // We put the PT_TLS segment last, because that is where the dynamic
1045   // linker expects to find it (this is just for efficiency; other
1046   // positions would also work correctly).
1047   if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
1048     return false;
1049   if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
1050     return true;
1051
1052   const elfcpp::Elf_Word flags1 = seg1->flags();
1053   const elfcpp::Elf_Word flags2 = seg2->flags();
1054
1055   // The order of non-PT_LOAD segments is unimportant.  We simply sort
1056   // by the numeric segment type and flags values.  There should not
1057   // be more than one segment with the same type and flags.
1058   if (type1 != elfcpp::PT_LOAD)
1059     {
1060       if (type1 != type2)
1061         return type1 < type2;
1062       gold_assert(flags1 != flags2);
1063       return flags1 < flags2;
1064     }
1065
1066   // If the addresses are set already, sort by load address.
1067   if (seg1->are_addresses_set())
1068     {
1069       if (!seg2->are_addresses_set())
1070         return true;
1071
1072       unsigned int section_count1 = seg1->output_section_count();
1073       unsigned int section_count2 = seg2->output_section_count();
1074       if (section_count1 == 0 && section_count2 > 0)
1075         return true;
1076       if (section_count1 > 0 && section_count2 == 0)
1077         return false;
1078
1079       uint64_t paddr1 = seg1->first_section_load_address();
1080       uint64_t paddr2 = seg2->first_section_load_address();
1081       if (paddr1 != paddr2)
1082         return paddr1 < paddr2;
1083     }
1084   else if (seg2->are_addresses_set())
1085     return false;
1086
1087   // We sort PT_LOAD segments based on the flags.  Readonly segments
1088   // come before writable segments.  Then executable segments come
1089   // before non-executable segments.  Then the unlikely case of a
1090   // non-readable segment comes before the normal case of a readable
1091   // segment.  If there are multiple segments with the same type and
1092   // flags, we require that the address be set, and we sort by
1093   // virtual address and then physical address.
1094   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1095     return (flags1 & elfcpp::PF_W) == 0;
1096   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1097     return (flags1 & elfcpp::PF_X) != 0;
1098   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1099     return (flags1 & elfcpp::PF_R) == 0;
1100
1101   // We shouldn't get here--we shouldn't create segments which we
1102   // can't distinguish.
1103   gold_unreachable();
1104 }
1105
1106 // Set the file offsets of all the segments, and all the sections they
1107 // contain.  They have all been created.  LOAD_SEG must be be laid out
1108 // first.  Return the offset of the data to follow.
1109
1110 off_t
1111 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1112                             unsigned int *pshndx)
1113 {
1114   // Sort them into the final order.
1115   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1116             Layout::Compare_segments());
1117
1118   // Find the PT_LOAD segments, and set their addresses and offsets
1119   // and their section's addresses and offsets.
1120   uint64_t addr;
1121   if (this->options_.user_set_text_segment_address())
1122     addr = options_.text_segment_address();
1123   else if (parameters->output_is_shared())
1124     addr = 0;
1125   else
1126     addr = target->default_text_segment_address();
1127   off_t off = 0;
1128
1129   // If LOAD_SEG is NULL, then the file header and segment headers
1130   // will not be loadable.  But they still need to be at offset 0 in
1131   // the file.  Set their offsets now.
1132   if (load_seg == NULL)
1133     {
1134       for (Data_list::iterator p = this->special_output_list_.begin();
1135            p != this->special_output_list_.end();
1136            ++p)
1137         {
1138           off = align_address(off, (*p)->addralign());
1139           (*p)->set_address_and_file_offset(0, off);
1140           off += (*p)->data_size();
1141         }
1142     }
1143
1144   bool was_readonly = false;
1145   for (Segment_list::iterator p = this->segment_list_.begin();
1146        p != this->segment_list_.end();
1147        ++p)
1148     {
1149       if ((*p)->type() == elfcpp::PT_LOAD)
1150         {
1151           if (load_seg != NULL && load_seg != *p)
1152             gold_unreachable();
1153           load_seg = NULL;
1154
1155           uint64_t orig_addr = addr;
1156           uint64_t orig_off = off;
1157
1158           uint64_t aligned_addr = 0;
1159           uint64_t abi_pagesize = target->abi_pagesize();
1160
1161           // FIXME: This should depend on the -n and -N options.
1162           (*p)->set_minimum_p_align(target->common_pagesize());
1163
1164           bool are_addresses_set = (*p)->are_addresses_set();
1165           if (are_addresses_set)
1166             {
1167               // When it comes to setting file offsets, we care about
1168               // the physical address.
1169               addr = (*p)->paddr();
1170
1171               // Adjust the file offset to the same address modulo the
1172               // page size.
1173               uint64_t unsigned_off = off;
1174               uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1175                                       | (addr & (abi_pagesize - 1)));
1176               if (aligned_off < unsigned_off)
1177                 aligned_off += abi_pagesize;
1178               off = aligned_off;
1179             }
1180           else
1181             {
1182               // If the last segment was readonly, and this one is
1183               // not, then skip the address forward one page,
1184               // maintaining the same position within the page.  This
1185               // lets us store both segments overlapping on a single
1186               // page in the file, but the loader will put them on
1187               // different pages in memory.
1188
1189               addr = align_address(addr, (*p)->maximum_alignment());
1190               aligned_addr = addr;
1191
1192               if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1193                 {
1194                   if ((addr & (abi_pagesize - 1)) != 0)
1195                     addr = addr + abi_pagesize;
1196                 }
1197
1198               off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1199             }
1200
1201           unsigned int shndx_hold = *pshndx;
1202           uint64_t new_addr = (*p)->set_section_addresses(false, addr, &off,
1203                                                           pshndx);
1204
1205           // Now that we know the size of this segment, we may be able
1206           // to save a page in memory, at the cost of wasting some
1207           // file space, by instead aligning to the start of a new
1208           // page.  Here we use the real machine page size rather than
1209           // the ABI mandated page size.
1210
1211           if (!are_addresses_set && aligned_addr != addr)
1212             {
1213               uint64_t common_pagesize = target->common_pagesize();
1214               uint64_t first_off = (common_pagesize
1215                                     - (aligned_addr
1216                                        & (common_pagesize - 1)));
1217               uint64_t last_off = new_addr & (common_pagesize - 1);
1218               if (first_off > 0
1219                   && last_off > 0
1220                   && ((aligned_addr & ~ (common_pagesize - 1))
1221                       != (new_addr & ~ (common_pagesize - 1)))
1222                   && first_off + last_off <= common_pagesize)
1223                 {
1224                   *pshndx = shndx_hold;
1225                   addr = align_address(aligned_addr, common_pagesize);
1226                   addr = align_address(addr, (*p)->maximum_alignment());
1227                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1228                   new_addr = (*p)->set_section_addresses(true, addr, &off,
1229                                                          pshndx);
1230                 }
1231             }
1232
1233           addr = new_addr;
1234
1235           if (((*p)->flags() & elfcpp::PF_W) == 0)
1236             was_readonly = true;
1237         }
1238     }
1239
1240   // Handle the non-PT_LOAD segments, setting their offsets from their
1241   // section's offsets.
1242   for (Segment_list::iterator p = this->segment_list_.begin();
1243        p != this->segment_list_.end();
1244        ++p)
1245     {
1246       if ((*p)->type() != elfcpp::PT_LOAD)
1247         (*p)->set_offset();
1248     }
1249
1250   // Set the TLS offsets for each section in the PT_TLS segment.
1251   if (this->tls_segment_ != NULL)
1252     this->tls_segment_->set_tls_offsets();
1253
1254   return off;
1255 }
1256
1257 // Set the file offset of all the sections not associated with a
1258 // segment.
1259
1260 off_t
1261 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1262 {
1263   for (Section_list::iterator p = this->unattached_section_list_.begin();
1264        p != this->unattached_section_list_.end();
1265        ++p)
1266     {
1267       // The symtab section is handled in create_symtab_sections.
1268       if (*p == this->symtab_section_)
1269         continue;
1270
1271       // If we've already set the data size, don't set it again.
1272       if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1273         continue;
1274
1275       if (pass == BEFORE_INPUT_SECTIONS_PASS
1276           && (*p)->requires_postprocessing())
1277         {
1278           (*p)->create_postprocessing_buffer();
1279           this->any_postprocessing_sections_ = true;
1280         }
1281
1282       if (pass == BEFORE_INPUT_SECTIONS_PASS
1283           && (*p)->after_input_sections())
1284         continue;
1285       else if (pass == POSTPROCESSING_SECTIONS_PASS
1286                && (!(*p)->after_input_sections()
1287                    || (*p)->type() == elfcpp::SHT_STRTAB))
1288         continue;
1289       else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1290                && (!(*p)->after_input_sections()
1291                    || (*p)->type() != elfcpp::SHT_STRTAB))
1292         continue;
1293
1294       off = align_address(off, (*p)->addralign());
1295       (*p)->set_file_offset(off);
1296       (*p)->finalize_data_size();
1297       off += (*p)->data_size();
1298
1299       // At this point the name must be set.
1300       if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1301         this->namepool_.add((*p)->name(), false, NULL);
1302     }
1303   return off;
1304 }
1305
1306 // Set the section indexes of all the sections not associated with a
1307 // segment.
1308
1309 unsigned int
1310 Layout::set_section_indexes(unsigned int shndx)
1311 {
1312   for (Section_list::iterator p = this->unattached_section_list_.begin();
1313        p != this->unattached_section_list_.end();
1314        ++p)
1315     {
1316       (*p)->set_out_shndx(shndx);
1317       ++shndx;
1318     }
1319   return shndx;
1320 }
1321
1322 // Set the section addresses according to the linker script.  This is
1323 // only called when we see a SECTIONS clause.  This returns the
1324 // program segment which should hold the file header and segment
1325 // headers, if any.  It will return NULL if they should not be in a
1326 // segment.
1327
1328 Output_segment*
1329 Layout::set_section_addresses_from_script(Symbol_table* symtab)
1330 {
1331   Script_sections* ss = this->script_options_->script_sections();
1332   gold_assert(ss->saw_sections_clause());
1333
1334   // Place each orphaned output section in the script.
1335   for (Section_list::iterator p = this->section_list_.begin();
1336        p != this->section_list_.end();
1337        ++p)
1338     {
1339       if (!(*p)->found_in_sections_clause())
1340         ss->place_orphan(*p);
1341     }
1342
1343   return this->script_options_->set_section_addresses(symtab, this);
1344 }
1345
1346 // Count the local symbols in the regular symbol table and the dynamic
1347 // symbol table, and build the respective string pools.
1348
1349 void
1350 Layout::count_local_symbols(const Task* task,
1351                             const Input_objects* input_objects)
1352 {
1353   // First, figure out an upper bound on the number of symbols we'll
1354   // be inserting into each pool.  This helps us create the pools with
1355   // the right size, to avoid unnecessary hashtable resizing.
1356   unsigned int symbol_count = 0;
1357   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1358        p != input_objects->relobj_end();
1359        ++p)
1360     symbol_count += (*p)->local_symbol_count();
1361
1362   // Go from "upper bound" to "estimate."  We overcount for two
1363   // reasons: we double-count symbols that occur in more than one
1364   // object file, and we count symbols that are dropped from the
1365   // output.  Add it all together and assume we overcount by 100%.
1366   symbol_count /= 2;
1367
1368   // We assume all symbols will go into both the sympool and dynpool.
1369   this->sympool_.reserve(symbol_count);
1370   this->dynpool_.reserve(symbol_count);
1371
1372   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1373        p != input_objects->relobj_end();
1374        ++p)
1375     {
1376       Task_lock_obj<Object> tlo(task, *p);
1377       (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
1378     }
1379 }
1380
1381 // Create the symbol table sections.  Here we also set the final
1382 // values of the symbols.  At this point all the loadable sections are
1383 // fully laid out.
1384
1385 void
1386 Layout::create_symtab_sections(const Input_objects* input_objects,
1387                                Symbol_table* symtab,
1388                                off_t* poff)
1389 {
1390   int symsize;
1391   unsigned int align;
1392   if (parameters->get_size() == 32)
1393     {
1394       symsize = elfcpp::Elf_sizes<32>::sym_size;
1395       align = 4;
1396     }
1397   else if (parameters->get_size() == 64)
1398     {
1399       symsize = elfcpp::Elf_sizes<64>::sym_size;
1400       align = 8;
1401     }
1402   else
1403     gold_unreachable();
1404
1405   off_t off = *poff;
1406   off = align_address(off, align);
1407   off_t startoff = off;
1408
1409   // Save space for the dummy symbol at the start of the section.  We
1410   // never bother to write this out--it will just be left as zero.
1411   off += symsize;
1412   unsigned int local_symbol_index = 1;
1413
1414   // Add STT_SECTION symbols for each Output section which needs one.
1415   for (Section_list::iterator p = this->section_list_.begin();
1416        p != this->section_list_.end();
1417        ++p)
1418     {
1419       if (!(*p)->needs_symtab_index())
1420         (*p)->set_symtab_index(-1U);
1421       else
1422         {
1423           (*p)->set_symtab_index(local_symbol_index);
1424           ++local_symbol_index;
1425           off += symsize;
1426         }
1427     }
1428
1429   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1430        p != input_objects->relobj_end();
1431        ++p)
1432     {
1433       unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
1434                                                         off);
1435       off += (index - local_symbol_index) * symsize;
1436       local_symbol_index = index;
1437     }
1438
1439   unsigned int local_symcount = local_symbol_index;
1440   gold_assert(local_symcount * symsize == off - startoff);
1441
1442   off_t dynoff;
1443   size_t dyn_global_index;
1444   size_t dyncount;
1445   if (this->dynsym_section_ == NULL)
1446     {
1447       dynoff = 0;
1448       dyn_global_index = 0;
1449       dyncount = 0;
1450     }
1451   else
1452     {
1453       dyn_global_index = this->dynsym_section_->info();
1454       off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
1455       dynoff = this->dynsym_section_->offset() + locsize;
1456       dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
1457       gold_assert(static_cast<off_t>(dyncount * symsize)
1458                   == this->dynsym_section_->data_size() - locsize);
1459     }
1460
1461   off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
1462                          &this->sympool_, &local_symcount);
1463
1464   if (!parameters->strip_all())
1465     {
1466       this->sympool_.set_string_offsets();
1467
1468       const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
1469       Output_section* osymtab = this->make_output_section(symtab_name,
1470                                                           elfcpp::SHT_SYMTAB,
1471                                                           0);
1472       this->symtab_section_ = osymtab;
1473
1474       Output_section_data* pos = new Output_data_fixed_space(off - startoff,
1475                                                              align);
1476       osymtab->add_output_section_data(pos);
1477
1478       const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
1479       Output_section* ostrtab = this->make_output_section(strtab_name,
1480                                                           elfcpp::SHT_STRTAB,
1481                                                           0);
1482
1483       Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
1484       ostrtab->add_output_section_data(pstr);
1485
1486       osymtab->set_file_offset(startoff);
1487       osymtab->finalize_data_size();
1488       osymtab->set_link_section(ostrtab);
1489       osymtab->set_info(local_symcount);
1490       osymtab->set_entsize(symsize);
1491
1492       *poff = off;
1493     }
1494 }
1495
1496 // Create the .shstrtab section, which holds the names of the
1497 // sections.  At the time this is called, we have created all the
1498 // output sections except .shstrtab itself.
1499
1500 Output_section*
1501 Layout::create_shstrtab()
1502 {
1503   // FIXME: We don't need to create a .shstrtab section if we are
1504   // stripping everything.
1505
1506   const char* name = this->namepool_.add(".shstrtab", false, NULL);
1507
1508   Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
1509
1510   // We can't write out this section until we've set all the section
1511   // names, and we don't set the names of compressed output sections
1512   // until relocations are complete.
1513   os->set_after_input_sections();
1514
1515   Output_section_data* posd = new Output_data_strtab(&this->namepool_);
1516   os->add_output_section_data(posd);
1517
1518   return os;
1519 }
1520
1521 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
1522 // offset.
1523
1524 void
1525 Layout::create_shdrs(off_t* poff)
1526 {
1527   Output_section_headers* oshdrs;
1528   oshdrs = new Output_section_headers(this,
1529                                       &this->segment_list_,
1530                                       &this->unattached_section_list_,
1531                                       &this->namepool_);
1532   off_t off = align_address(*poff, oshdrs->addralign());
1533   oshdrs->set_address_and_file_offset(0, off);
1534   off += oshdrs->data_size();
1535   *poff = off;
1536   this->section_headers_ = oshdrs;
1537 }
1538
1539 // Create the dynamic symbol table.
1540
1541 void
1542 Layout::create_dynamic_symtab(const Input_objects* input_objects,
1543                               Symbol_table* symtab,
1544                               Output_section **pdynstr,
1545                               unsigned int* plocal_dynamic_count,
1546                               std::vector<Symbol*>* pdynamic_symbols,
1547                               Versions* pversions)
1548 {
1549   // Count all the symbols in the dynamic symbol table, and set the
1550   // dynamic symbol indexes.
1551
1552   // Skip symbol 0, which is always all zeroes.
1553   unsigned int index = 1;
1554
1555   // Add STT_SECTION symbols for each Output section which needs one.
1556   for (Section_list::iterator p = this->section_list_.begin();
1557        p != this->section_list_.end();
1558        ++p)
1559     {
1560       if (!(*p)->needs_dynsym_index())
1561         (*p)->set_dynsym_index(-1U);
1562       else
1563         {
1564           (*p)->set_dynsym_index(index);
1565           ++index;
1566         }
1567     }
1568
1569   // Count the local symbols that need to go in the dynamic symbol table,
1570   // and set the dynamic symbol indexes.
1571   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1572        p != input_objects->relobj_end();
1573        ++p)
1574     {
1575       unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
1576       index = new_index;
1577     }
1578
1579   unsigned int local_symcount = index;
1580   *plocal_dynamic_count = local_symcount;
1581
1582   // FIXME: We have to tell set_dynsym_indexes whether the
1583   // -E/--export-dynamic option was used.
1584   index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
1585                                      &this->dynpool_, pversions);
1586
1587   int symsize;
1588   unsigned int align;
1589   const int size = parameters->get_size();
1590   if (size == 32)
1591     {
1592       symsize = elfcpp::Elf_sizes<32>::sym_size;
1593       align = 4;
1594     }
1595   else if (size == 64)
1596     {
1597       symsize = elfcpp::Elf_sizes<64>::sym_size;
1598       align = 8;
1599     }
1600   else
1601     gold_unreachable();
1602
1603   // Create the dynamic symbol table section.
1604
1605   Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
1606                                                        elfcpp::SHT_DYNSYM,
1607                                                        elfcpp::SHF_ALLOC,
1608                                                        false);
1609
1610   Output_section_data* odata = new Output_data_fixed_space(index * symsize,
1611                                                            align);
1612   dynsym->add_output_section_data(odata);
1613
1614   dynsym->set_info(local_symcount);
1615   dynsym->set_entsize(symsize);
1616   dynsym->set_addralign(align);
1617
1618   this->dynsym_section_ = dynsym;
1619
1620   Output_data_dynamic* const odyn = this->dynamic_data_;
1621   odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
1622   odyn->add_constant(elfcpp::DT_SYMENT, symsize);
1623
1624   // Create the dynamic string table section.
1625
1626   Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
1627                                                        elfcpp::SHT_STRTAB,
1628                                                        elfcpp::SHF_ALLOC,
1629                                                        false);
1630
1631   Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
1632   dynstr->add_output_section_data(strdata);
1633
1634   dynsym->set_link_section(dynstr);
1635   this->dynamic_section_->set_link_section(dynstr);
1636
1637   odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
1638   odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
1639
1640   *pdynstr = dynstr;
1641
1642   // Create the hash tables.
1643
1644   // FIXME: We need an option to create a GNU hash table.
1645
1646   unsigned char* phash;
1647   unsigned int hashlen;
1648   Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
1649                                 &phash, &hashlen);
1650
1651   Output_section* hashsec = this->choose_output_section(NULL, ".hash",
1652                                                         elfcpp::SHT_HASH,
1653                                                         elfcpp::SHF_ALLOC,
1654                                                         false);
1655
1656   Output_section_data* hashdata = new Output_data_const_buffer(phash,
1657                                                                hashlen,
1658                                                                align);
1659   hashsec->add_output_section_data(hashdata);
1660
1661   hashsec->set_link_section(dynsym);
1662   hashsec->set_entsize(4);
1663
1664   odyn->add_section_address(elfcpp::DT_HASH, hashsec);
1665 }
1666
1667 // Assign offsets to each local portion of the dynamic symbol table.
1668
1669 void
1670 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
1671 {
1672   Output_section* dynsym = this->dynsym_section_;
1673   gold_assert(dynsym != NULL);
1674
1675   off_t off = dynsym->offset();
1676
1677   // Skip the dummy symbol at the start of the section.
1678   off += dynsym->entsize();
1679
1680   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1681        p != input_objects->relobj_end();
1682        ++p)
1683     {
1684       unsigned int count = (*p)->set_local_dynsym_offset(off);
1685       off += count * dynsym->entsize();
1686     }
1687 }
1688
1689 // Create the version sections.
1690
1691 void
1692 Layout::create_version_sections(const Versions* versions,
1693                                 const Symbol_table* symtab,
1694                                 unsigned int local_symcount,
1695                                 const std::vector<Symbol*>& dynamic_symbols,
1696                                 const Output_section* dynstr)
1697 {
1698   if (!versions->any_defs() && !versions->any_needs())
1699     return;
1700
1701   if (parameters->get_size() == 32)
1702     {
1703       if (parameters->is_big_endian())
1704         {
1705 #ifdef HAVE_TARGET_32_BIG
1706           this->sized_create_version_sections
1707               SELECT_SIZE_ENDIAN_NAME(32, true)(
1708                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1709                   SELECT_SIZE_ENDIAN(32, true));
1710 #else
1711           gold_unreachable();
1712 #endif
1713         }
1714       else
1715         {
1716 #ifdef HAVE_TARGET_32_LITTLE
1717           this->sized_create_version_sections
1718               SELECT_SIZE_ENDIAN_NAME(32, false)(
1719                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1720                   SELECT_SIZE_ENDIAN(32, false));
1721 #else
1722           gold_unreachable();
1723 #endif
1724         }
1725     }
1726   else if (parameters->get_size() == 64)
1727     {
1728       if (parameters->is_big_endian())
1729         {
1730 #ifdef HAVE_TARGET_64_BIG
1731           this->sized_create_version_sections
1732               SELECT_SIZE_ENDIAN_NAME(64, true)(
1733                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1734                   SELECT_SIZE_ENDIAN(64, true));
1735 #else
1736           gold_unreachable();
1737 #endif
1738         }
1739       else
1740         {
1741 #ifdef HAVE_TARGET_64_LITTLE
1742           this->sized_create_version_sections
1743               SELECT_SIZE_ENDIAN_NAME(64, false)(
1744                   versions, symtab, local_symcount, dynamic_symbols, dynstr
1745                   SELECT_SIZE_ENDIAN(64, false));
1746 #else
1747           gold_unreachable();
1748 #endif
1749         }
1750     }
1751   else
1752     gold_unreachable();
1753 }
1754
1755 // Create the version sections, sized version.
1756
1757 template<int size, bool big_endian>
1758 void
1759 Layout::sized_create_version_sections(
1760     const Versions* versions,
1761     const Symbol_table* symtab,
1762     unsigned int local_symcount,
1763     const std::vector<Symbol*>& dynamic_symbols,
1764     const Output_section* dynstr
1765     ACCEPT_SIZE_ENDIAN)
1766 {
1767   Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
1768                                                      elfcpp::SHT_GNU_versym,
1769                                                      elfcpp::SHF_ALLOC,
1770                                                      false);
1771
1772   unsigned char* vbuf;
1773   unsigned int vsize;
1774   versions->symbol_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1775       symtab, &this->dynpool_, local_symcount, dynamic_symbols, &vbuf, &vsize
1776       SELECT_SIZE_ENDIAN(size, big_endian));
1777
1778   Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2);
1779
1780   vsec->add_output_section_data(vdata);
1781   vsec->set_entsize(2);
1782   vsec->set_link_section(this->dynsym_section_);
1783
1784   Output_data_dynamic* const odyn = this->dynamic_data_;
1785   odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
1786
1787   if (versions->any_defs())
1788     {
1789       Output_section* vdsec;
1790       vdsec= this->choose_output_section(NULL, ".gnu.version_d",
1791                                          elfcpp::SHT_GNU_verdef,
1792                                          elfcpp::SHF_ALLOC,
1793                                          false);
1794
1795       unsigned char* vdbuf;
1796       unsigned int vdsize;
1797       unsigned int vdentries;
1798       versions->def_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1799           &this->dynpool_, &vdbuf, &vdsize, &vdentries
1800           SELECT_SIZE_ENDIAN(size, big_endian));
1801
1802       Output_section_data* vddata = new Output_data_const_buffer(vdbuf,
1803                                                                  vdsize,
1804                                                                  4);
1805
1806       vdsec->add_output_section_data(vddata);
1807       vdsec->set_link_section(dynstr);
1808       vdsec->set_info(vdentries);
1809
1810       odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
1811       odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
1812     }
1813
1814   if (versions->any_needs())
1815     {
1816       Output_section* vnsec;
1817       vnsec = this->choose_output_section(NULL, ".gnu.version_r",
1818                                           elfcpp::SHT_GNU_verneed,
1819                                           elfcpp::SHF_ALLOC,
1820                                           false);
1821
1822       unsigned char* vnbuf;
1823       unsigned int vnsize;
1824       unsigned int vnentries;
1825       versions->need_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)
1826         (&this->dynpool_, &vnbuf, &vnsize, &vnentries
1827          SELECT_SIZE_ENDIAN(size, big_endian));
1828
1829       Output_section_data* vndata = new Output_data_const_buffer(vnbuf,
1830                                                                  vnsize,
1831                                                                  4);
1832
1833       vnsec->add_output_section_data(vndata);
1834       vnsec->set_link_section(dynstr);
1835       vnsec->set_info(vnentries);
1836
1837       odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
1838       odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
1839     }
1840 }
1841
1842 // Create the .interp section and PT_INTERP segment.
1843
1844 void
1845 Layout::create_interp(const Target* target)
1846 {
1847   const char* interp = this->options_.dynamic_linker();
1848   if (interp == NULL)
1849     {
1850       interp = target->dynamic_linker();
1851       gold_assert(interp != NULL);
1852     }
1853
1854   size_t len = strlen(interp) + 1;
1855
1856   Output_section_data* odata = new Output_data_const(interp, len, 1);
1857
1858   Output_section* osec = this->choose_output_section(NULL, ".interp",
1859                                                      elfcpp::SHT_PROGBITS,
1860                                                      elfcpp::SHF_ALLOC,
1861                                                      false);
1862   osec->add_output_section_data(odata);
1863
1864   Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
1865                                                    elfcpp::PF_R);
1866   oseg->add_initial_output_section(osec, elfcpp::PF_R);
1867 }
1868
1869 // Finish the .dynamic section and PT_DYNAMIC segment.
1870
1871 void
1872 Layout::finish_dynamic_section(const Input_objects* input_objects,
1873                                const Symbol_table* symtab)
1874 {
1875   Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
1876                                                    (elfcpp::PF_R
1877                                                     | elfcpp::PF_W));
1878   oseg->add_initial_output_section(this->dynamic_section_,
1879                                    elfcpp::PF_R | elfcpp::PF_W);
1880
1881   Output_data_dynamic* const odyn = this->dynamic_data_;
1882
1883   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
1884        p != input_objects->dynobj_end();
1885        ++p)
1886     {
1887       // FIXME: Handle --as-needed.
1888       odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
1889     }
1890
1891   if (parameters->output_is_shared())
1892     {
1893       const char* soname = this->options_.soname();
1894       if (soname != NULL)
1895         odyn->add_string(elfcpp::DT_SONAME, soname);
1896     }
1897
1898   // FIXME: Support --init and --fini.
1899   Symbol* sym = symtab->lookup("_init");
1900   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1901     odyn->add_symbol(elfcpp::DT_INIT, sym);
1902
1903   sym = symtab->lookup("_fini");
1904   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1905     odyn->add_symbol(elfcpp::DT_FINI, sym);
1906
1907   // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
1908
1909   // Add a DT_RPATH entry if needed.
1910   const General_options::Dir_list& rpath(this->options_.rpath());
1911   if (!rpath.empty())
1912     {
1913       std::string rpath_val;
1914       for (General_options::Dir_list::const_iterator p = rpath.begin();
1915            p != rpath.end();
1916            ++p)
1917         {
1918           if (rpath_val.empty())
1919             rpath_val = p->name();
1920           else
1921             {
1922               // Eliminate duplicates.
1923               General_options::Dir_list::const_iterator q;
1924               for (q = rpath.begin(); q != p; ++q)
1925                 if (q->name() == p->name())
1926                   break;
1927               if (q == p)
1928                 {
1929                   rpath_val += ':';
1930                   rpath_val += p->name();
1931                 }
1932             }
1933         }
1934
1935       odyn->add_string(elfcpp::DT_RPATH, rpath_val);
1936     }
1937
1938   // Look for text segments that have dynamic relocations.
1939   bool have_textrel = false;
1940   for (Segment_list::const_iterator p = this->segment_list_.begin();
1941        p != this->segment_list_.end();
1942        ++p)
1943     {
1944       if (((*p)->flags() & elfcpp::PF_W) == 0
1945           && (*p)->dynamic_reloc_count() > 0)
1946         {
1947           have_textrel = true;
1948           break;
1949         }
1950     }
1951
1952   // Add a DT_FLAGS entry. We add it even if no flags are set so that
1953   // post-link tools can easily modify these flags if desired.
1954   unsigned int flags = 0;
1955   if (have_textrel)
1956     {
1957       // Add a DT_TEXTREL for compatibility with older loaders.
1958       odyn->add_constant(elfcpp::DT_TEXTREL, 0);
1959       flags |= elfcpp::DF_TEXTREL;
1960     }
1961   if (parameters->output_is_shared() && this->has_static_tls())
1962     flags |= elfcpp::DF_STATIC_TLS;
1963   odyn->add_constant(elfcpp::DT_FLAGS, flags);
1964 }
1965
1966 // The mapping of .gnu.linkonce section names to real section names.
1967
1968 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
1969 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
1970 {
1971   MAPPING_INIT("d.rel.ro", ".data.rel.ro"),     // Must be before "d".
1972   MAPPING_INIT("t", ".text"),
1973   MAPPING_INIT("r", ".rodata"),
1974   MAPPING_INIT("d", ".data"),
1975   MAPPING_INIT("b", ".bss"),
1976   MAPPING_INIT("s", ".sdata"),
1977   MAPPING_INIT("sb", ".sbss"),
1978   MAPPING_INIT("s2", ".sdata2"),
1979   MAPPING_INIT("sb2", ".sbss2"),
1980   MAPPING_INIT("wi", ".debug_info"),
1981   MAPPING_INIT("td", ".tdata"),
1982   MAPPING_INIT("tb", ".tbss"),
1983   MAPPING_INIT("lr", ".lrodata"),
1984   MAPPING_INIT("l", ".ldata"),
1985   MAPPING_INIT("lb", ".lbss"),
1986 };
1987 #undef MAPPING_INIT
1988
1989 const int Layout::linkonce_mapping_count =
1990   sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
1991
1992 // Return the name of the output section to use for a .gnu.linkonce
1993 // section.  This is based on the default ELF linker script of the old
1994 // GNU linker.  For example, we map a name like ".gnu.linkonce.t.foo"
1995 // to ".text".  Set *PLEN to the length of the name.  *PLEN is
1996 // initialized to the length of NAME.
1997
1998 const char*
1999 Layout::linkonce_output_name(const char* name, size_t *plen)
2000 {
2001   const char* s = name + sizeof(".gnu.linkonce") - 1;
2002   if (*s != '.')
2003     return name;
2004   ++s;
2005   const Linkonce_mapping* plm = linkonce_mapping;
2006   for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2007     {
2008       if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2009         {
2010           *plen = plm->tolen;
2011           return plm->to;
2012         }
2013     }
2014   return name;
2015 }
2016
2017 // Choose the output section name to use given an input section name.
2018 // Set *PLEN to the length of the name.  *PLEN is initialized to the
2019 // length of NAME.
2020
2021 const char*
2022 Layout::output_section_name(const char* name, size_t* plen)
2023 {
2024   if (Layout::is_linkonce(name))
2025     {
2026       // .gnu.linkonce sections are laid out as though they were named
2027       // for the sections are placed into.
2028       return Layout::linkonce_output_name(name, plen);
2029     }
2030
2031   // gcc 4.3 generates the following sorts of section names when it
2032   // needs a section name specific to a function:
2033   //   .text.FN
2034   //   .rodata.FN
2035   //   .sdata2.FN
2036   //   .data.FN
2037   //   .data.rel.FN
2038   //   .data.rel.local.FN
2039   //   .data.rel.ro.FN
2040   //   .data.rel.ro.local.FN
2041   //   .sdata.FN
2042   //   .bss.FN
2043   //   .sbss.FN
2044   //   .tdata.FN
2045   //   .tbss.FN
2046
2047   // The GNU linker maps all of those to the part before the .FN,
2048   // except that .data.rel.local.FN is mapped to .data, and
2049   // .data.rel.ro.local.FN is mapped to .data.rel.ro.  The sections
2050   // beginning with .data.rel.ro.local are grouped together.
2051
2052   // For an anonymous namespace, the string FN can contain a '.'.
2053
2054   // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2055   // GNU linker maps to .rodata.
2056
2057   // The .data.rel.ro sections enable a security feature triggered by
2058   // the -z relro option.  Section which need to be relocated at
2059   // program startup time but which may be readonly after startup are
2060   // grouped into .data.rel.ro.  They are then put into a PT_GNU_RELRO
2061   // segment.  The dynamic linker will make that segment writable,
2062   // perform relocations, and then make it read-only.  FIXME: We do
2063   // not yet implement this optimization.
2064
2065   // It is hard to handle this in a principled way.
2066
2067   // These are the rules we follow:
2068
2069   // If the section name has no initial '.', or no dot other than an
2070   // initial '.', we use the name unchanged (i.e., "mysection" and
2071   // ".text" are unchanged).
2072
2073   // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2074
2075   // Otherwise, we drop the second '.' and everything that comes after
2076   // it (i.e., ".text.XXX" becomes ".text").
2077
2078   const char* s = name;
2079   if (*s != '.')
2080     return name;
2081   ++s;
2082   const char* sdot = strchr(s, '.');
2083   if (sdot == NULL)
2084     return name;
2085
2086   const char* const data_rel_ro = ".data.rel.ro";
2087   if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2088     {
2089       *plen = strlen(data_rel_ro);
2090       return data_rel_ro;
2091     }
2092
2093   *plen = sdot - name;
2094   return name;
2095 }
2096
2097 // Record the signature of a comdat section, and return whether to
2098 // include it in the link.  If GROUP is true, this is a regular
2099 // section group.  If GROUP is false, this is a group signature
2100 // derived from the name of a linkonce section.  We want linkonce
2101 // signatures and group signatures to block each other, but we don't
2102 // want a linkonce signature to block another linkonce signature.
2103
2104 bool
2105 Layout::add_comdat(const char* signature, bool group)
2106 {
2107   std::string sig(signature);
2108   std::pair<Signatures::iterator, bool> ins(
2109     this->signatures_.insert(std::make_pair(sig, group)));
2110
2111   if (ins.second)
2112     {
2113       // This is the first time we've seen this signature.
2114       return true;
2115     }
2116
2117   if (ins.first->second)
2118     {
2119       // We've already seen a real section group with this signature.
2120       return false;
2121     }
2122   else if (group)
2123     {
2124       // This is a real section group, and we've already seen a
2125       // linkonce section with this signature.  Record that we've seen
2126       // a section group, and don't include this section group.
2127       ins.first->second = true;
2128       return false;
2129     }
2130   else
2131     {
2132       // We've already seen a linkonce section and this is a linkonce
2133       // section.  These don't block each other--this may be the same
2134       // symbol name with different section types.
2135       return true;
2136     }
2137 }
2138
2139 // Store the allocated sections into the section list.
2140
2141 void
2142 Layout::get_allocated_sections(Section_list* section_list) const
2143 {
2144   for (Section_list::const_iterator p = this->section_list_.begin();
2145        p != this->section_list_.end();
2146        ++p)
2147     if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2148       section_list->push_back(*p);
2149 }
2150
2151 // Create an output segment.
2152
2153 Output_segment*
2154 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2155 {
2156   Output_segment* oseg = new Output_segment(type, flags);
2157   this->segment_list_.push_back(oseg);
2158   return oseg;
2159 }
2160
2161 // Write out the Output_sections.  Most won't have anything to write,
2162 // since most of the data will come from input sections which are
2163 // handled elsewhere.  But some Output_sections do have Output_data.
2164
2165 void
2166 Layout::write_output_sections(Output_file* of) const
2167 {
2168   for (Section_list::const_iterator p = this->section_list_.begin();
2169        p != this->section_list_.end();
2170        ++p)
2171     {
2172       if (!(*p)->after_input_sections())
2173         (*p)->write(of);
2174     }
2175 }
2176
2177 // Write out data not associated with a section or the symbol table.
2178
2179 void
2180 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
2181 {
2182   if (!parameters->strip_all())
2183     {
2184       const Output_section* symtab_section = this->symtab_section_;
2185       for (Section_list::const_iterator p = this->section_list_.begin();
2186            p != this->section_list_.end();
2187            ++p)
2188         {
2189           if ((*p)->needs_symtab_index())
2190             {
2191               gold_assert(symtab_section != NULL);
2192               unsigned int index = (*p)->symtab_index();
2193               gold_assert(index > 0 && index != -1U);
2194               off_t off = (symtab_section->offset()
2195                            + index * symtab_section->entsize());
2196               symtab->write_section_symbol(*p, of, off);
2197             }
2198         }
2199     }
2200
2201   const Output_section* dynsym_section = this->dynsym_section_;
2202   for (Section_list::const_iterator p = this->section_list_.begin();
2203        p != this->section_list_.end();
2204        ++p)
2205     {
2206       if ((*p)->needs_dynsym_index())
2207         {
2208           gold_assert(dynsym_section != NULL);
2209           unsigned int index = (*p)->dynsym_index();
2210           gold_assert(index > 0 && index != -1U);
2211           off_t off = (dynsym_section->offset()
2212                        + index * dynsym_section->entsize());
2213           symtab->write_section_symbol(*p, of, off);
2214         }
2215     }
2216
2217   // Write out the Output_data which are not in an Output_section.
2218   for (Data_list::const_iterator p = this->special_output_list_.begin();
2219        p != this->special_output_list_.end();
2220        ++p)
2221     (*p)->write(of);
2222 }
2223
2224 // Write out the Output_sections which can only be written after the
2225 // input sections are complete.
2226
2227 void
2228 Layout::write_sections_after_input_sections(Output_file* of)
2229 {
2230   // Determine the final section offsets, and thus the final output
2231   // file size.  Note we finalize the .shstrab last, to allow the
2232   // after_input_section sections to modify their section-names before
2233   // writing.
2234   if (this->any_postprocessing_sections_)
2235     {
2236       off_t off = this->output_file_size_;
2237       off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
2238       
2239       // Now that we've finalized the names, we can finalize the shstrab.
2240       off =
2241         this->set_section_offsets(off,
2242                                   STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2243
2244       if (off > this->output_file_size_)
2245         {
2246           of->resize(off);
2247           this->output_file_size_ = off;
2248         }
2249     }
2250
2251   for (Section_list::const_iterator p = this->section_list_.begin();
2252        p != this->section_list_.end();
2253        ++p)
2254     {
2255       if ((*p)->after_input_sections())
2256         (*p)->write(of);
2257     }
2258
2259   this->section_headers_->write(of);
2260 }
2261
2262 // Print statistical information to stderr.  This is used for --stats.
2263
2264 void
2265 Layout::print_stats() const
2266 {
2267   this->namepool_.print_stats("section name pool");
2268   this->sympool_.print_stats("output symbol name pool");
2269   this->dynpool_.print_stats("dynamic name pool");
2270
2271   for (Section_list::const_iterator p = this->section_list_.begin();
2272        p != this->section_list_.end();
2273        ++p)
2274     (*p)->print_merge_stats();
2275 }
2276
2277 // Write_sections_task methods.
2278
2279 // We can always run this task.
2280
2281 Task_token*
2282 Write_sections_task::is_runnable()
2283 {
2284   return NULL;
2285 }
2286
2287 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
2288 // when finished.
2289
2290 void
2291 Write_sections_task::locks(Task_locker* tl)
2292 {
2293   tl->add(this, this->output_sections_blocker_);
2294   tl->add(this, this->final_blocker_);
2295 }
2296
2297 // Run the task--write out the data.
2298
2299 void
2300 Write_sections_task::run(Workqueue*)
2301 {
2302   this->layout_->write_output_sections(this->of_);
2303 }
2304
2305 // Write_data_task methods.
2306
2307 // We can always run this task.
2308
2309 Task_token*
2310 Write_data_task::is_runnable()
2311 {
2312   return NULL;
2313 }
2314
2315 // We need to unlock FINAL_BLOCKER when finished.
2316
2317 void
2318 Write_data_task::locks(Task_locker* tl)
2319 {
2320   tl->add(this, this->final_blocker_);
2321 }
2322
2323 // Run the task--write out the data.
2324
2325 void
2326 Write_data_task::run(Workqueue*)
2327 {
2328   this->layout_->write_data(this->symtab_, this->of_);
2329 }
2330
2331 // Write_symbols_task methods.
2332
2333 // We can always run this task.
2334
2335 Task_token*
2336 Write_symbols_task::is_runnable()
2337 {
2338   return NULL;
2339 }
2340
2341 // We need to unlock FINAL_BLOCKER when finished.
2342
2343 void
2344 Write_symbols_task::locks(Task_locker* tl)
2345 {
2346   tl->add(this, this->final_blocker_);
2347 }
2348
2349 // Run the task--write out the symbols.
2350
2351 void
2352 Write_symbols_task::run(Workqueue*)
2353 {
2354   this->symtab_->write_globals(this->input_objects_, this->sympool_,
2355                                this->dynpool_, this->of_);
2356 }
2357
2358 // Write_after_input_sections_task methods.
2359
2360 // We can only run this task after the input sections have completed.
2361
2362 Task_token*
2363 Write_after_input_sections_task::is_runnable()
2364 {
2365   if (this->input_sections_blocker_->is_blocked())
2366     return this->input_sections_blocker_;
2367   return NULL;
2368 }
2369
2370 // We need to unlock FINAL_BLOCKER when finished.
2371
2372 void
2373 Write_after_input_sections_task::locks(Task_locker* tl)
2374 {
2375   tl->add(this, this->final_blocker_);
2376 }
2377
2378 // Run the task.
2379
2380 void
2381 Write_after_input_sections_task::run(Workqueue*)
2382 {
2383   this->layout_->write_sections_after_input_sections(this->of_);
2384 }
2385
2386 // Close_task_runner methods.
2387
2388 // Run the task--close the file.
2389
2390 void
2391 Close_task_runner::run(Workqueue*, const Task*)
2392 {
2393   this->of_->close();
2394 }
2395
2396 // Instantiate the templates we need.  We could use the configure
2397 // script to restrict this to only the ones for implemented targets.
2398
2399 #ifdef HAVE_TARGET_32_LITTLE
2400 template
2401 Output_section*
2402 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
2403                           const char* name,
2404                           const elfcpp::Shdr<32, false>& shdr,
2405                           unsigned int, unsigned int, off_t*);
2406 #endif
2407
2408 #ifdef HAVE_TARGET_32_BIG
2409 template
2410 Output_section*
2411 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
2412                          const char* name,
2413                          const elfcpp::Shdr<32, true>& shdr,
2414                          unsigned int, unsigned int, off_t*);
2415 #endif
2416
2417 #ifdef HAVE_TARGET_64_LITTLE
2418 template
2419 Output_section*
2420 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
2421                           const char* name,
2422                           const elfcpp::Shdr<64, false>& shdr,
2423                           unsigned int, unsigned int, off_t*);
2424 #endif
2425
2426 #ifdef HAVE_TARGET_64_BIG
2427 template
2428 Output_section*
2429 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
2430                          const char* name,
2431                          const elfcpp::Shdr<64, true>& shdr,
2432                          unsigned int, unsigned int, off_t*);
2433 #endif
2434
2435 #ifdef HAVE_TARGET_32_LITTLE
2436 template
2437 Output_section*
2438 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
2439                                    const unsigned char* symbols,
2440                                    off_t symbols_size,
2441                                    const unsigned char* symbol_names,
2442                                    off_t symbol_names_size,
2443                                    unsigned int shndx,
2444                                    const elfcpp::Shdr<32, false>& shdr,
2445                                    unsigned int reloc_shndx,
2446                                    unsigned int reloc_type,
2447                                    off_t* off);
2448 #endif
2449
2450 #ifdef HAVE_TARGET_32_BIG
2451 template
2452 Output_section*
2453 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
2454                                    const unsigned char* symbols,
2455                                    off_t symbols_size,
2456                                   const unsigned char* symbol_names,
2457                                   off_t symbol_names_size,
2458                                   unsigned int shndx,
2459                                   const elfcpp::Shdr<32, true>& shdr,
2460                                   unsigned int reloc_shndx,
2461                                   unsigned int reloc_type,
2462                                   off_t* off);
2463 #endif
2464
2465 #ifdef HAVE_TARGET_64_LITTLE
2466 template
2467 Output_section*
2468 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
2469                                    const unsigned char* symbols,
2470                                    off_t symbols_size,
2471                                    const unsigned char* symbol_names,
2472                                    off_t symbol_names_size,
2473                                    unsigned int shndx,
2474                                    const elfcpp::Shdr<64, false>& shdr,
2475                                    unsigned int reloc_shndx,
2476                                    unsigned int reloc_type,
2477                                    off_t* off);
2478 #endif
2479
2480 #ifdef HAVE_TARGET_64_BIG
2481 template
2482 Output_section*
2483 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
2484                                    const unsigned char* symbols,
2485                                    off_t symbols_size,
2486                                   const unsigned char* symbol_names,
2487                                   off_t symbol_names_size,
2488                                   unsigned int shndx,
2489                                   const elfcpp::Shdr<64, true>& shdr,
2490                                   unsigned int reloc_shndx,
2491                                   unsigned int reloc_type,
2492                                   off_t* off);
2493 #endif
2494
2495 } // End namespace gold.