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