2013-04-26 Geoff Pike <gpike@chromium.org>
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2012
4 // Free Software Foundation, Inc.
5 // Written by Ian Lance Taylor <iant@google.com>.
6
7 // This file is part of gold.
8
9 // This program is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation; either version 3 of the License, or
12 // (at your option) any later version.
13
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
22 // MA 02110-1301, USA.
23
24 #include "gold.h"
25
26 #include <cerrno>
27 #include <cstring>
28 #include <algorithm>
29 #include <iostream>
30 #include <fstream>
31 #include <utility>
32 #include <fcntl.h>
33 #include <fnmatch.h>
34 #include <unistd.h>
35 #include "libiberty.h"
36 #include "md5.h"
37 #include "sha1.h"
38
39 #include "parameters.h"
40 #include "options.h"
41 #include "mapfile.h"
42 #include "script.h"
43 #include "script-sections.h"
44 #include "output.h"
45 #include "symtab.h"
46 #include "dynobj.h"
47 #include "ehframe.h"
48 #include "gdb-index.h"
49 #include "compressed_output.h"
50 #include "reduced_debug_output.h"
51 #include "object.h"
52 #include "reloc.h"
53 #include "descriptors.h"
54 #include "plugin.h"
55 #include "incremental.h"
56 #include "layout.h"
57
58 namespace gold
59 {
60
61 // Class Free_list.
62
63 // The total number of free lists used.
64 unsigned int Free_list::num_lists = 0;
65 // The total number of free list nodes used.
66 unsigned int Free_list::num_nodes = 0;
67 // The total number of calls to Free_list::remove.
68 unsigned int Free_list::num_removes = 0;
69 // The total number of nodes visited during calls to Free_list::remove.
70 unsigned int Free_list::num_remove_visits = 0;
71 // The total number of calls to Free_list::allocate.
72 unsigned int Free_list::num_allocates = 0;
73 // The total number of nodes visited during calls to Free_list::allocate.
74 unsigned int Free_list::num_allocate_visits = 0;
75
76 // Initialize the free list.  Creates a single free list node that
77 // describes the entire region of length LEN.  If EXTEND is true,
78 // allocate() is allowed to extend the region beyond its initial
79 // length.
80
81 void
82 Free_list::init(off_t len, bool extend)
83 {
84   this->list_.push_front(Free_list_node(0, len));
85   this->last_remove_ = this->list_.begin();
86   this->extend_ = extend;
87   this->length_ = len;
88   ++Free_list::num_lists;
89   ++Free_list::num_nodes;
90 }
91
92 // Remove a chunk from the free list.  Because we start with a single
93 // node that covers the entire section, and remove chunks from it one
94 // at a time, we do not need to coalesce chunks or handle cases that
95 // span more than one free node.  We expect to remove chunks from the
96 // free list in order, and we expect to have only a few chunks of free
97 // space left (corresponding to files that have changed since the last
98 // incremental link), so a simple linear list should provide sufficient
99 // performance.
100
101 void
102 Free_list::remove(off_t start, off_t end)
103 {
104   if (start == end)
105     return;
106   gold_assert(start < end);
107
108   ++Free_list::num_removes;
109
110   Iterator p = this->last_remove_;
111   if (p->start_ > start)
112     p = this->list_.begin();
113
114   for (; p != this->list_.end(); ++p)
115     {
116       ++Free_list::num_remove_visits;
117       // Find a node that wholly contains the indicated region.
118       if (p->start_ <= start && p->end_ >= end)
119         {
120           // Case 1: the indicated region spans the whole node.
121           // Add some fuzz to avoid creating tiny free chunks.
122           if (p->start_ + 3 >= start && p->end_ <= end + 3)
123             p = this->list_.erase(p);
124           // Case 2: remove a chunk from the start of the node.
125           else if (p->start_ + 3 >= start)
126             p->start_ = end;
127           // Case 3: remove a chunk from the end of the node.
128           else if (p->end_ <= end + 3)
129             p->end_ = start;
130           // Case 4: remove a chunk from the middle, and split
131           // the node into two.
132           else
133             {
134               Free_list_node newnode(p->start_, start);
135               p->start_ = end;
136               this->list_.insert(p, newnode);
137               ++Free_list::num_nodes;
138             }
139           this->last_remove_ = p;
140           return;
141         }
142     }
143
144   // Did not find a node containing the given chunk.  This could happen
145   // because a small chunk was already removed due to the fuzz.
146   gold_debug(DEBUG_INCREMENTAL,
147              "Free_list::remove(%d,%d) not found",
148              static_cast<int>(start), static_cast<int>(end));
149 }
150
151 // Allocate a chunk of size LEN from the free list.  Returns -1ULL
152 // if a sufficiently large chunk of free space is not found.
153 // We use a simple first-fit algorithm.
154
155 off_t
156 Free_list::allocate(off_t len, uint64_t align, off_t minoff)
157 {
158   gold_debug(DEBUG_INCREMENTAL,
159              "Free_list::allocate(%08lx, %d, %08lx)",
160              static_cast<long>(len), static_cast<int>(align),
161              static_cast<long>(minoff));
162   if (len == 0)
163     return align_address(minoff, align);
164
165   ++Free_list::num_allocates;
166
167   // We usually want to drop free chunks smaller than 4 bytes.
168   // If we need to guarantee a minimum hole size, though, we need
169   // to keep track of all free chunks.
170   const int fuzz = this->min_hole_ > 0 ? 0 : 3;
171
172   for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
173     {
174       ++Free_list::num_allocate_visits;
175       off_t start = p->start_ > minoff ? p->start_ : minoff;
176       start = align_address(start, align);
177       off_t end = start + len;
178       if (end > p->end_ && p->end_ == this->length_ && this->extend_)
179         {
180           this->length_ = end;
181           p->end_ = end;
182         }
183       if (end == p->end_ || (end <= p->end_ - this->min_hole_))
184         {
185           if (p->start_ + fuzz >= start && p->end_ <= end + fuzz)
186             this->list_.erase(p);
187           else if (p->start_ + fuzz >= start)
188             p->start_ = end;
189           else if (p->end_ <= end + fuzz)
190             p->end_ = start;
191           else
192             {
193               Free_list_node newnode(p->start_, start);
194               p->start_ = end;
195               this->list_.insert(p, newnode);
196               ++Free_list::num_nodes;
197             }
198           return start;
199         }
200     }
201   if (this->extend_)
202     {
203       off_t start = align_address(this->length_, align);
204       this->length_ = start + len;
205       return start;
206     }
207   return -1;
208 }
209
210 // Dump the free list (for debugging).
211 void
212 Free_list::dump()
213 {
214   gold_info("Free list:\n     start      end   length\n");
215   for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
216     gold_info("  %08lx %08lx %08lx", static_cast<long>(p->start_),
217               static_cast<long>(p->end_),
218               static_cast<long>(p->end_ - p->start_));
219 }
220
221 // Print the statistics for the free lists.
222 void
223 Free_list::print_stats()
224 {
225   fprintf(stderr, _("%s: total free lists: %u\n"),
226           program_name, Free_list::num_lists);
227   fprintf(stderr, _("%s: total free list nodes: %u\n"),
228           program_name, Free_list::num_nodes);
229   fprintf(stderr, _("%s: calls to Free_list::remove: %u\n"),
230           program_name, Free_list::num_removes);
231   fprintf(stderr, _("%s: nodes visited: %u\n"),
232           program_name, Free_list::num_remove_visits);
233   fprintf(stderr, _("%s: calls to Free_list::allocate: %u\n"),
234           program_name, Free_list::num_allocates);
235   fprintf(stderr, _("%s: nodes visited: %u\n"),
236           program_name, Free_list::num_allocate_visits);
237 }
238
239 // A Hash_task computes the MD5 checksum of an array of char.
240 // It has a blocker on either side (i.e., the task cannot run until
241 // the first is unblocked, and it unblocks the second after running).
242
243 class Hash_task : public Task
244 {
245  public:
246   Hash_task(const unsigned char* src,
247             size_t size,
248             unsigned char* dst,
249             Task_token* build_id_blocker,
250             Task_token* final_blocker)
251     : src_(src), size_(size), dst_(dst), build_id_blocker_(build_id_blocker),
252       final_blocker_(final_blocker)
253   { }
254
255   void
256   run(Workqueue*)
257   { md5_buffer(reinterpret_cast<const char*>(src_), size_, dst_); }
258
259   Task_token*
260   is_runnable();
261
262   // Unblock FINAL_BLOCKER_ when done.
263   void
264   locks(Task_locker* tl)
265   { tl->add(this, this->final_blocker_); }
266
267   std::string
268   get_name() const
269   { return "Hash_task"; }
270
271  private:
272   const unsigned char* const src_;
273   const size_t size_;
274   unsigned char* const dst_;
275   Task_token* const build_id_blocker_;
276   Task_token* const final_blocker_;
277 };
278
279 Task_token*
280 Hash_task::is_runnable()
281 {
282   if (this->build_id_blocker_->is_blocked())
283     return this->build_id_blocker_;
284   return NULL;
285 }
286
287 // Layout::Relaxation_debug_check methods.
288
289 // Check that sections and special data are in reset states.
290 // We do not save states for Output_sections and special Output_data.
291 // So we check that they have not assigned any addresses or offsets.
292 // clean_up_after_relaxation simply resets their addresses and offsets.
293 void
294 Layout::Relaxation_debug_check::check_output_data_for_reset_values(
295     const Layout::Section_list& sections,
296     const Layout::Data_list& special_outputs)
297 {
298   for(Layout::Section_list::const_iterator p = sections.begin();
299       p != sections.end();
300       ++p)
301     gold_assert((*p)->address_and_file_offset_have_reset_values());
302
303   for(Layout::Data_list::const_iterator p = special_outputs.begin();
304       p != special_outputs.end();
305       ++p)
306     gold_assert((*p)->address_and_file_offset_have_reset_values());
307 }
308
309 // Save information of SECTIONS for checking later.
310
311 void
312 Layout::Relaxation_debug_check::read_sections(
313     const Layout::Section_list& sections)
314 {
315   for(Layout::Section_list::const_iterator p = sections.begin();
316       p != sections.end();
317       ++p)
318     {
319       Output_section* os = *p;
320       Section_info info;
321       info.output_section = os;
322       info.address = os->is_address_valid() ? os->address() : 0;
323       info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
324       info.offset = os->is_offset_valid()? os->offset() : -1 ;
325       this->section_infos_.push_back(info);
326     }
327 }
328
329 // Verify SECTIONS using previously recorded information.
330
331 void
332 Layout::Relaxation_debug_check::verify_sections(
333     const Layout::Section_list& sections)
334 {
335   size_t i = 0;
336   for(Layout::Section_list::const_iterator p = sections.begin();
337       p != sections.end();
338       ++p, ++i)
339     {
340       Output_section* os = *p;
341       uint64_t address = os->is_address_valid() ? os->address() : 0;
342       off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
343       off_t offset = os->is_offset_valid()? os->offset() : -1 ;
344
345       if (i >= this->section_infos_.size())
346         {
347           gold_fatal("Section_info of %s missing.\n", os->name());
348         }
349       const Section_info& info = this->section_infos_[i];
350       if (os != info.output_section)
351         gold_fatal("Section order changed.  Expecting %s but see %s\n",
352                    info.output_section->name(), os->name());
353       if (address != info.address
354           || data_size != info.data_size
355           || offset != info.offset)
356         gold_fatal("Section %s changed.\n", os->name());
357     }
358 }
359
360 // Layout_task_runner methods.
361
362 // Lay out the sections.  This is called after all the input objects
363 // have been read.
364
365 void
366 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
367 {
368   // See if any of the input definitions violate the One Definition Rule.
369   // TODO: if this is too slow, do this as a task, rather than inline.
370   this->symtab_->detect_odr_violations(task, this->options_.output_file_name());
371
372   Layout* layout = this->layout_;
373   off_t file_size = layout->finalize(this->input_objects_,
374                                      this->symtab_,
375                                      this->target_,
376                                      task);
377
378   // Now we know the final size of the output file and we know where
379   // each piece of information goes.
380
381   if (this->mapfile_ != NULL)
382     {
383       this->mapfile_->print_discarded_sections(this->input_objects_);
384       layout->print_to_mapfile(this->mapfile_);
385     }
386
387   Output_file* of;
388   if (layout->incremental_base() == NULL)
389     {
390       of = new Output_file(parameters->options().output_file_name());
391       if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
392         of->set_is_temporary();
393       of->open(file_size);
394     }
395   else
396     {
397       of = layout->incremental_base()->output_file();
398
399       // Apply the incremental relocations for symbols whose values
400       // have changed.  We do this before we resize the file and start
401       // writing anything else to it, so that we can read the old
402       // incremental information from the file before (possibly)
403       // overwriting it.
404       if (parameters->incremental_update())
405         layout->incremental_base()->apply_incremental_relocs(this->symtab_,
406                                                              this->layout_,
407                                                              of);
408
409       of->resize(file_size);
410     }
411
412   // Queue up the final set of tasks.
413   gold::queue_final_tasks(this->options_, this->input_objects_,
414                           this->symtab_, layout, workqueue, of);
415 }
416
417 // Layout methods.
418
419 Layout::Layout(int number_of_input_files, Script_options* script_options)
420   : number_of_input_files_(number_of_input_files),
421     script_options_(script_options),
422     namepool_(),
423     sympool_(),
424     dynpool_(),
425     signatures_(),
426     section_name_map_(),
427     segment_list_(),
428     section_list_(),
429     unattached_section_list_(),
430     special_output_list_(),
431     section_headers_(NULL),
432     tls_segment_(NULL),
433     relro_segment_(NULL),
434     interp_segment_(NULL),
435     increase_relro_(0),
436     symtab_section_(NULL),
437     symtab_xindex_(NULL),
438     dynsym_section_(NULL),
439     dynsym_xindex_(NULL),
440     dynamic_section_(NULL),
441     dynamic_symbol_(NULL),
442     dynamic_data_(NULL),
443     eh_frame_section_(NULL),
444     eh_frame_data_(NULL),
445     added_eh_frame_data_(false),
446     eh_frame_hdr_section_(NULL),
447     gdb_index_data_(NULL),
448     build_id_note_(NULL),
449     array_of_hashes_(NULL),
450     size_of_array_of_hashes_(0),
451     input_view_(NULL),
452     debug_abbrev_(NULL),
453     debug_info_(NULL),
454     group_signatures_(),
455     output_file_size_(-1),
456     have_added_input_section_(false),
457     sections_are_attached_(false),
458     input_requires_executable_stack_(false),
459     input_with_gnu_stack_note_(false),
460     input_without_gnu_stack_note_(false),
461     has_static_tls_(false),
462     any_postprocessing_sections_(false),
463     resized_signatures_(false),
464     have_stabstr_section_(false),
465     section_ordering_specified_(false),
466     unique_segment_for_sections_specified_(false),
467     incremental_inputs_(NULL),
468     record_output_section_data_from_script_(false),
469     script_output_section_data_list_(),
470     segment_states_(NULL),
471     relaxation_debug_check_(NULL),
472     section_order_map_(),
473     section_segment_map_(),
474     input_section_position_(),
475     input_section_glob_(),
476     incremental_base_(NULL),
477     free_list_()
478 {
479   // Make space for more than enough segments for a typical file.
480   // This is just for efficiency--it's OK if we wind up needing more.
481   this->segment_list_.reserve(12);
482
483   // We expect two unattached Output_data objects: the file header and
484   // the segment headers.
485   this->special_output_list_.reserve(2);
486
487   // Initialize structure needed for an incremental build.
488   if (parameters->incremental())
489     this->incremental_inputs_ = new Incremental_inputs;
490
491   // The section name pool is worth optimizing in all cases, because
492   // it is small, but there are often overlaps due to .rel sections.
493   this->namepool_.set_optimize();
494 }
495
496 // For incremental links, record the base file to be modified.
497
498 void
499 Layout::set_incremental_base(Incremental_binary* base)
500 {
501   this->incremental_base_ = base;
502   this->free_list_.init(base->output_file()->filesize(), true);
503 }
504
505 // Hash a key we use to look up an output section mapping.
506
507 size_t
508 Layout::Hash_key::operator()(const Layout::Key& k) const
509 {
510  return k.first + k.second.first + k.second.second;
511 }
512
513 // These are the debug sections that are actually used by gdb.
514 // Currently, we've checked versions of gdb up to and including 7.4.
515 // We only check the part of the name that follows ".debug_" or
516 // ".zdebug_".
517
518 static const char* gdb_sections[] =
519 {
520   "abbrev",
521   "addr",         // Fission extension
522   // "aranges",   // not used by gdb as of 7.4
523   "frame",
524   "info",
525   "types",
526   "line",
527   "loc",
528   "macinfo",
529   "macro",
530   // "pubnames",  // not used by gdb as of 7.4
531   // "pubtypes",  // not used by gdb as of 7.4
532   "ranges",
533   "str",
534 };
535
536 // This is the minimum set of sections needed for line numbers.
537
538 static const char* lines_only_debug_sections[] =
539 {
540   "abbrev",
541   // "addr",      // Fission extension
542   // "aranges",   // not used by gdb as of 7.4
543   // "frame",
544   "info",
545   // "types",
546   "line",
547   // "loc",
548   // "macinfo",
549   // "macro",
550   // "pubnames",  // not used by gdb as of 7.4
551   // "pubtypes",  // not used by gdb as of 7.4
552   // "ranges",
553   "str",
554 };
555
556 // These sections are the DWARF fast-lookup tables, and are not needed
557 // when building a .gdb_index section.
558
559 static const char* gdb_fast_lookup_sections[] =
560 {
561   "aranges",
562   "pubnames",
563   "pubtypes",
564 };
565
566 // Returns whether the given debug section is in the list of
567 // debug-sections-used-by-some-version-of-gdb.  SUFFIX is the
568 // portion of the name following ".debug_" or ".zdebug_".
569
570 static inline bool
571 is_gdb_debug_section(const char* suffix)
572 {
573   // We can do this faster: binary search or a hashtable.  But why bother?
574   for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
575     if (strcmp(suffix, gdb_sections[i]) == 0)
576       return true;
577   return false;
578 }
579
580 // Returns whether the given section is needed for lines-only debugging.
581
582 static inline bool
583 is_lines_only_debug_section(const char* suffix)
584 {
585   // We can do this faster: binary search or a hashtable.  But why bother?
586   for (size_t i = 0;
587        i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
588        ++i)
589     if (strcmp(suffix, lines_only_debug_sections[i]) == 0)
590       return true;
591   return false;
592 }
593
594 // Returns whether the given section is a fast-lookup section that
595 // will not be needed when building a .gdb_index section.
596
597 static inline bool
598 is_gdb_fast_lookup_section(const char* suffix)
599 {
600   // We can do this faster: binary search or a hashtable.  But why bother?
601   for (size_t i = 0;
602        i < sizeof(gdb_fast_lookup_sections)/sizeof(*gdb_fast_lookup_sections);
603        ++i)
604     if (strcmp(suffix, gdb_fast_lookup_sections[i]) == 0)
605       return true;
606   return false;
607 }
608
609 // Sometimes we compress sections.  This is typically done for
610 // sections that are not part of normal program execution (such as
611 // .debug_* sections), and where the readers of these sections know
612 // how to deal with compressed sections.  This routine doesn't say for
613 // certain whether we'll compress -- it depends on commandline options
614 // as well -- just whether this section is a candidate for compression.
615 // (The Output_compressed_section class decides whether to compress
616 // a given section, and picks the name of the compressed section.)
617
618 static bool
619 is_compressible_debug_section(const char* secname)
620 {
621   return (is_prefix_of(".debug", secname));
622 }
623
624 // We may see compressed debug sections in input files.  Return TRUE
625 // if this is the name of a compressed debug section.
626
627 bool
628 is_compressed_debug_section(const char* secname)
629 {
630   return (is_prefix_of(".zdebug", secname));
631 }
632
633 // Whether to include this section in the link.
634
635 template<int size, bool big_endian>
636 bool
637 Layout::include_section(Sized_relobj_file<size, big_endian>*, const char* name,
638                         const elfcpp::Shdr<size, big_endian>& shdr)
639 {
640   if (!parameters->options().relocatable()
641       && (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE))
642     return false;
643
644   switch (shdr.get_sh_type())
645     {
646     case elfcpp::SHT_NULL:
647     case elfcpp::SHT_SYMTAB:
648     case elfcpp::SHT_DYNSYM:
649     case elfcpp::SHT_HASH:
650     case elfcpp::SHT_DYNAMIC:
651     case elfcpp::SHT_SYMTAB_SHNDX:
652       return false;
653
654     case elfcpp::SHT_STRTAB:
655       // Discard the sections which have special meanings in the ELF
656       // ABI.  Keep others (e.g., .stabstr).  We could also do this by
657       // checking the sh_link fields of the appropriate sections.
658       return (strcmp(name, ".dynstr") != 0
659               && strcmp(name, ".strtab") != 0
660               && strcmp(name, ".shstrtab") != 0);
661
662     case elfcpp::SHT_RELA:
663     case elfcpp::SHT_REL:
664     case elfcpp::SHT_GROUP:
665       // If we are emitting relocations these should be handled
666       // elsewhere.
667       gold_assert(!parameters->options().relocatable());
668       return false;
669
670     case elfcpp::SHT_PROGBITS:
671       if (parameters->options().strip_debug()
672           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
673         {
674           if (is_debug_info_section(name))
675             return false;
676         }
677       if (parameters->options().strip_debug_non_line()
678           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
679         {
680           // Debugging sections can only be recognized by name.
681           if (is_prefix_of(".debug_", name)
682               && !is_lines_only_debug_section(name + 7))
683             return false;
684           if (is_prefix_of(".zdebug_", name)
685               && !is_lines_only_debug_section(name + 8))
686             return false;
687         }
688       if (parameters->options().strip_debug_gdb()
689           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
690         {
691           // Debugging sections can only be recognized by name.
692           if (is_prefix_of(".debug_", name)
693               && !is_gdb_debug_section(name + 7))
694             return false;
695           if (is_prefix_of(".zdebug_", name)
696               && !is_gdb_debug_section(name + 8))
697             return false;
698         }
699       if (parameters->options().gdb_index()
700           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
701         {
702           // When building .gdb_index, we can strip .debug_pubnames,
703           // .debug_pubtypes, and .debug_aranges sections.
704           if (is_prefix_of(".debug_", name)
705               && is_gdb_fast_lookup_section(name + 7))
706             return false;
707           if (is_prefix_of(".zdebug_", name)
708               && is_gdb_fast_lookup_section(name + 8))
709             return false;
710         }
711       if (parameters->options().strip_lto_sections()
712           && !parameters->options().relocatable()
713           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
714         {
715           // Ignore LTO sections containing intermediate code.
716           if (is_prefix_of(".gnu.lto_", name))
717             return false;
718         }
719       // The GNU linker strips .gnu_debuglink sections, so we do too.
720       // This is a feature used to keep debugging information in
721       // separate files.
722       if (strcmp(name, ".gnu_debuglink") == 0)
723         return false;
724       return true;
725
726     default:
727       return true;
728     }
729 }
730
731 // Return an output section named NAME, or NULL if there is none.
732
733 Output_section*
734 Layout::find_output_section(const char* name) const
735 {
736   for (Section_list::const_iterator p = this->section_list_.begin();
737        p != this->section_list_.end();
738        ++p)
739     if (strcmp((*p)->name(), name) == 0)
740       return *p;
741   return NULL;
742 }
743
744 // Return an output segment of type TYPE, with segment flags SET set
745 // and segment flags CLEAR clear.  Return NULL if there is none.
746
747 Output_segment*
748 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
749                             elfcpp::Elf_Word clear) const
750 {
751   for (Segment_list::const_iterator p = this->segment_list_.begin();
752        p != this->segment_list_.end();
753        ++p)
754     if (static_cast<elfcpp::PT>((*p)->type()) == type
755         && ((*p)->flags() & set) == set
756         && ((*p)->flags() & clear) == 0)
757       return *p;
758   return NULL;
759 }
760
761 // When we put a .ctors or .dtors section with more than one word into
762 // a .init_array or .fini_array section, we need to reverse the words
763 // in the .ctors/.dtors section.  This is because .init_array executes
764 // constructors front to back, where .ctors executes them back to
765 // front, and vice-versa for .fini_array/.dtors.  Although we do want
766 // to remap .ctors/.dtors into .init_array/.fini_array because it can
767 // be more efficient, we don't want to change the order in which
768 // constructors/destructors are run.  This set just keeps track of
769 // these sections which need to be reversed.  It is only changed by
770 // Layout::layout.  It should be a private member of Layout, but that
771 // would require layout.h to #include object.h to get the definition
772 // of Section_id.
773 static Unordered_set<Section_id, Section_id_hash> ctors_sections_in_init_array;
774
775 // Return whether OBJECT/SHNDX is a .ctors/.dtors section mapped to a
776 // .init_array/.fini_array section.
777
778 bool
779 Layout::is_ctors_in_init_array(Relobj* relobj, unsigned int shndx) const
780 {
781   return (ctors_sections_in_init_array.find(Section_id(relobj, shndx))
782           != ctors_sections_in_init_array.end());
783 }
784
785 // Return the output section to use for section NAME with type TYPE
786 // and section flags FLAGS.  NAME must be canonicalized in the string
787 // pool, and NAME_KEY is the key.  ORDER is where this should appear
788 // in the output sections.  IS_RELRO is true for a relro section.
789
790 Output_section*
791 Layout::get_output_section(const char* name, Stringpool::Key name_key,
792                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
793                            Output_section_order order, bool is_relro)
794 {
795   elfcpp::Elf_Word lookup_type = type;
796
797   // For lookup purposes, treat INIT_ARRAY, FINI_ARRAY, and
798   // PREINIT_ARRAY like PROGBITS.  This ensures that we combine
799   // .init_array, .fini_array, and .preinit_array sections by name
800   // whatever their type in the input file.  We do this because the
801   // types are not always right in the input files.
802   if (lookup_type == elfcpp::SHT_INIT_ARRAY
803       || lookup_type == elfcpp::SHT_FINI_ARRAY
804       || lookup_type == elfcpp::SHT_PREINIT_ARRAY)
805     lookup_type = elfcpp::SHT_PROGBITS;
806
807   elfcpp::Elf_Xword lookup_flags = flags;
808
809   // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
810   // read-write with read-only sections.  Some other ELF linkers do
811   // not do this.  FIXME: Perhaps there should be an option
812   // controlling this.
813   lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
814
815   const Key key(name_key, std::make_pair(lookup_type, lookup_flags));
816   const std::pair<Key, Output_section*> v(key, NULL);
817   std::pair<Section_name_map::iterator, bool> ins(
818     this->section_name_map_.insert(v));
819
820   if (!ins.second)
821     return ins.first->second;
822   else
823     {
824       // This is the first time we've seen this name/type/flags
825       // combination.  For compatibility with the GNU linker, we
826       // combine sections with contents and zero flags with sections
827       // with non-zero flags.  This is a workaround for cases where
828       // assembler code forgets to set section flags.  FIXME: Perhaps
829       // there should be an option to control this.
830       Output_section* os = NULL;
831
832       if (lookup_type == elfcpp::SHT_PROGBITS)
833         {
834           if (flags == 0)
835             {
836               Output_section* same_name = this->find_output_section(name);
837               if (same_name != NULL
838                   && (same_name->type() == elfcpp::SHT_PROGBITS
839                       || same_name->type() == elfcpp::SHT_INIT_ARRAY
840                       || same_name->type() == elfcpp::SHT_FINI_ARRAY
841                       || same_name->type() == elfcpp::SHT_PREINIT_ARRAY)
842                   && (same_name->flags() & elfcpp::SHF_TLS) == 0)
843                 os = same_name;
844             }
845           else if ((flags & elfcpp::SHF_TLS) == 0)
846             {
847               elfcpp::Elf_Xword zero_flags = 0;
848               const Key zero_key(name_key, std::make_pair(lookup_type,
849                                                           zero_flags));
850               Section_name_map::iterator p =
851                   this->section_name_map_.find(zero_key);
852               if (p != this->section_name_map_.end())
853                 os = p->second;
854             }
855         }
856
857       if (os == NULL)
858         os = this->make_output_section(name, type, flags, order, is_relro);
859
860       ins.first->second = os;
861       return os;
862     }
863 }
864
865 // Returns TRUE iff NAME (an input section from RELOBJ) will
866 // be mapped to an output section that should be KEPT.
867
868 bool
869 Layout::keep_input_section(const Relobj* relobj, const char* name)
870 {
871   if (! this->script_options_->saw_sections_clause())
872     return false;
873
874   Script_sections* ss = this->script_options_->script_sections();
875   const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
876   Output_section** output_section_slot;
877   Script_sections::Section_type script_section_type;
878   bool keep;
879
880   name = ss->output_section_name(file_name, name, &output_section_slot,
881                                  &script_section_type, &keep);
882   return name != NULL && keep;
883 }
884
885 // Clear the input section flags that should not be copied to the
886 // output section.
887
888 elfcpp::Elf_Xword
889 Layout::get_output_section_flags(elfcpp::Elf_Xword input_section_flags)
890 {
891   // Some flags in the input section should not be automatically
892   // copied to the output section.
893   input_section_flags &= ~ (elfcpp::SHF_INFO_LINK
894                             | elfcpp::SHF_GROUP
895                             | elfcpp::SHF_MERGE
896                             | elfcpp::SHF_STRINGS);
897
898   // We only clear the SHF_LINK_ORDER flag in for
899   // a non-relocatable link.
900   if (!parameters->options().relocatable())
901     input_section_flags &= ~elfcpp::SHF_LINK_ORDER;
902
903   return input_section_flags;
904 }
905
906 // Pick the output section to use for section NAME, in input file
907 // RELOBJ, with type TYPE and flags FLAGS.  RELOBJ may be NULL for a
908 // linker created section.  IS_INPUT_SECTION is true if we are
909 // choosing an output section for an input section found in a input
910 // file.  ORDER is where this section should appear in the output
911 // sections.  IS_RELRO is true for a relro section.  This will return
912 // NULL if the input section should be discarded.
913
914 Output_section*
915 Layout::choose_output_section(const Relobj* relobj, const char* name,
916                               elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
917                               bool is_input_section, Output_section_order order,
918                               bool is_relro)
919 {
920   // We should not see any input sections after we have attached
921   // sections to segments.
922   gold_assert(!is_input_section || !this->sections_are_attached_);
923
924   flags = this->get_output_section_flags(flags);
925
926   if (this->script_options_->saw_sections_clause())
927     {
928       // We are using a SECTIONS clause, so the output section is
929       // chosen based only on the name.
930
931       Script_sections* ss = this->script_options_->script_sections();
932       const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
933       Output_section** output_section_slot;
934       Script_sections::Section_type script_section_type;
935       const char* orig_name = name;
936       bool keep;
937       name = ss->output_section_name(file_name, name, &output_section_slot,
938                                      &script_section_type, &keep);
939
940       if (name == NULL)
941         {
942           gold_debug(DEBUG_SCRIPT, _("Unable to create output section '%s' "
943                                      "because it is not allowed by the "
944                                      "SECTIONS clause of the linker script"),
945                      orig_name);
946           // The SECTIONS clause says to discard this input section.
947           return NULL;
948         }
949
950       // We can only handle script section types ST_NONE and ST_NOLOAD.
951       switch (script_section_type)
952         {
953         case Script_sections::ST_NONE:
954           break;
955         case Script_sections::ST_NOLOAD:
956           flags &= elfcpp::SHF_ALLOC;
957           break;
958         default:
959           gold_unreachable();
960         }
961
962       // If this is an orphan section--one not mentioned in the linker
963       // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
964       // default processing below.
965
966       if (output_section_slot != NULL)
967         {
968           if (*output_section_slot != NULL)
969             {
970               (*output_section_slot)->update_flags_for_input_section(flags);
971               return *output_section_slot;
972             }
973
974           // We don't put sections found in the linker script into
975           // SECTION_NAME_MAP_.  That keeps us from getting confused
976           // if an orphan section is mapped to a section with the same
977           // name as one in the linker script.
978
979           name = this->namepool_.add(name, false, NULL);
980
981           Output_section* os = this->make_output_section(name, type, flags,
982                                                          order, is_relro);
983
984           os->set_found_in_sections_clause();
985
986           // Special handling for NOLOAD sections.
987           if (script_section_type == Script_sections::ST_NOLOAD)
988             {
989               os->set_is_noload();
990
991               // The constructor of Output_section sets addresses of non-ALLOC
992               // sections to 0 by default.  We don't want that for NOLOAD
993               // sections even if they have no SHF_ALLOC flag.
994               if ((os->flags() & elfcpp::SHF_ALLOC) == 0
995                   && os->is_address_valid())
996                 {
997                   gold_assert(os->address() == 0
998                               && !os->is_offset_valid()
999                               && !os->is_data_size_valid());
1000                   os->reset_address_and_file_offset();
1001                 }
1002             }
1003
1004           *output_section_slot = os;
1005           return os;
1006         }
1007     }
1008
1009   // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
1010
1011   size_t len = strlen(name);
1012   char* uncompressed_name = NULL;
1013
1014   // Compressed debug sections should be mapped to the corresponding
1015   // uncompressed section.
1016   if (is_compressed_debug_section(name))
1017     {
1018       uncompressed_name = new char[len];
1019       uncompressed_name[0] = '.';
1020       gold_assert(name[0] == '.' && name[1] == 'z');
1021       strncpy(&uncompressed_name[1], &name[2], len - 2);
1022       uncompressed_name[len - 1] = '\0';
1023       len -= 1;
1024       name = uncompressed_name;
1025     }
1026
1027   // Turn NAME from the name of the input section into the name of the
1028   // output section.
1029   if (is_input_section
1030       && !this->script_options_->saw_sections_clause()
1031       && !parameters->options().relocatable())
1032     {
1033       const char *orig_name = name;
1034       name = parameters->target().output_section_name(relobj, name, &len);
1035       if (name == NULL)
1036         name = Layout::output_section_name(relobj, orig_name, &len);
1037     }
1038
1039   Stringpool::Key name_key;
1040   name = this->namepool_.add_with_length(name, len, true, &name_key);
1041
1042   if (uncompressed_name != NULL)
1043     delete[] uncompressed_name;
1044
1045   // Find or make the output section.  The output section is selected
1046   // based on the section name, type, and flags.
1047   return this->get_output_section(name, name_key, type, flags, order, is_relro);
1048 }
1049
1050 // For incremental links, record the initial fixed layout of a section
1051 // from the base file, and return a pointer to the Output_section.
1052
1053 template<int size, bool big_endian>
1054 Output_section*
1055 Layout::init_fixed_output_section(const char* name,
1056                                   elfcpp::Shdr<size, big_endian>& shdr)
1057 {
1058   unsigned int sh_type = shdr.get_sh_type();
1059
1060   // We preserve the layout of PROGBITS, NOBITS, INIT_ARRAY, FINI_ARRAY,
1061   // PRE_INIT_ARRAY, and NOTE sections.
1062   // All others will be created from scratch and reallocated.
1063   if (!can_incremental_update(sh_type))
1064     return NULL;
1065
1066   // If we're generating a .gdb_index section, we need to regenerate
1067   // it from scratch.
1068   if (parameters->options().gdb_index()
1069       && sh_type == elfcpp::SHT_PROGBITS
1070       && strcmp(name, ".gdb_index") == 0)
1071     return NULL;
1072
1073   typename elfcpp::Elf_types<size>::Elf_Addr sh_addr = shdr.get_sh_addr();
1074   typename elfcpp::Elf_types<size>::Elf_Off sh_offset = shdr.get_sh_offset();
1075   typename elfcpp::Elf_types<size>::Elf_WXword sh_size = shdr.get_sh_size();
1076   typename elfcpp::Elf_types<size>::Elf_WXword sh_flags = shdr.get_sh_flags();
1077   typename elfcpp::Elf_types<size>::Elf_WXword sh_addralign =
1078       shdr.get_sh_addralign();
1079
1080   // Make the output section.
1081   Stringpool::Key name_key;
1082   name = this->namepool_.add(name, true, &name_key);
1083   Output_section* os = this->get_output_section(name, name_key, sh_type,
1084                                                 sh_flags, ORDER_INVALID, false);
1085   os->set_fixed_layout(sh_addr, sh_offset, sh_size, sh_addralign);
1086   if (sh_type != elfcpp::SHT_NOBITS)
1087     this->free_list_.remove(sh_offset, sh_offset + sh_size);
1088   return os;
1089 }
1090
1091 // Return the index by which an input section should be ordered.  This
1092 // is used to sort some .text sections, for compatibility with GNU ld.
1093
1094 int
1095 Layout::special_ordering_of_input_section(const char* name)
1096 {
1097   // The GNU linker has some special handling for some sections that
1098   // wind up in the .text section.  Sections that start with these
1099   // prefixes must appear first, and must appear in the order listed
1100   // here.
1101   static const char* const text_section_sort[] = 
1102   {
1103     ".text.unlikely",
1104     ".text.exit",
1105     ".text.startup",
1106     ".text.hot"
1107   };
1108
1109   for (size_t i = 0;
1110        i < sizeof(text_section_sort) / sizeof(text_section_sort[0]);
1111        i++)
1112     if (is_prefix_of(text_section_sort[i], name))
1113       return i;
1114
1115   return -1;
1116 }
1117
1118 // Return the output section to use for input section SHNDX, with name
1119 // NAME, with header HEADER, from object OBJECT.  RELOC_SHNDX is the
1120 // index of a relocation section which applies to this section, or 0
1121 // if none, or -1U if more than one.  RELOC_TYPE is the type of the
1122 // relocation section if there is one.  Set *OFF to the offset of this
1123 // input section without the output section.  Return NULL if the
1124 // section should be discarded.  Set *OFF to -1 if the section
1125 // contents should not be written directly to the output file, but
1126 // will instead receive special handling.
1127
1128 template<int size, bool big_endian>
1129 Output_section*
1130 Layout::layout(Sized_relobj_file<size, big_endian>* object, unsigned int shndx,
1131                const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
1132                unsigned int reloc_shndx, unsigned int, off_t* off)
1133 {
1134   *off = 0;
1135
1136   if (!this->include_section(object, name, shdr))
1137     return NULL;
1138
1139   elfcpp::Elf_Word sh_type = shdr.get_sh_type();
1140
1141   // In a relocatable link a grouped section must not be combined with
1142   // any other sections.
1143   Output_section* os;
1144   if (parameters->options().relocatable()
1145       && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
1146     {
1147       name = this->namepool_.add(name, true, NULL);
1148       os = this->make_output_section(name, sh_type, shdr.get_sh_flags(),
1149                                      ORDER_INVALID, false);
1150     }
1151   else
1152     {
1153       // Plugins can choose to place one or more subsets of sections in
1154       // unique segments and this is done by mapping these section subsets
1155       // to unique output sections.  Check if this section needs to be
1156       // remapped to a unique output section.
1157       Section_segment_map::iterator it
1158           = this->section_segment_map_.find(Const_section_id(object, shndx));
1159       if (it == this->section_segment_map_.end())
1160         {
1161           os = this->choose_output_section(object, name, sh_type,
1162                                            shdr.get_sh_flags(), true,
1163                                            ORDER_INVALID, false);
1164         }
1165       else
1166         {
1167           // We know the name of the output section, directly call
1168           // get_output_section here by-passing choose_output_section.
1169           elfcpp::Elf_Xword flags
1170             = this->get_output_section_flags(shdr.get_sh_flags());
1171
1172           const char* os_name = it->second->name;
1173           Stringpool::Key name_key;
1174           os_name = this->namepool_.add(os_name, true, &name_key);
1175           os = this->get_output_section(os_name, name_key, sh_type, flags,
1176                                         ORDER_INVALID, false);
1177           if (!os->is_unique_segment())
1178             {
1179               os->set_is_unique_segment();
1180               os->set_extra_segment_flags(it->second->flags);
1181               os->set_segment_alignment(it->second->align);
1182             }
1183         }
1184       if (os == NULL)
1185         return NULL;
1186     }
1187
1188   // By default the GNU linker sorts input sections whose names match
1189   // .ctors.*, .dtors.*, .init_array.*, or .fini_array.*.  The
1190   // sections are sorted by name.  This is used to implement
1191   // constructor priority ordering.  We are compatible.  When we put
1192   // .ctor sections in .init_array and .dtor sections in .fini_array,
1193   // we must also sort plain .ctor and .dtor sections.
1194   if (!this->script_options_->saw_sections_clause()
1195       && !parameters->options().relocatable()
1196       && (is_prefix_of(".ctors.", name)
1197           || is_prefix_of(".dtors.", name)
1198           || is_prefix_of(".init_array.", name)
1199           || is_prefix_of(".fini_array.", name)
1200           || (parameters->options().ctors_in_init_array()
1201               && (strcmp(name, ".ctors") == 0
1202                   || strcmp(name, ".dtors") == 0))))
1203     os->set_must_sort_attached_input_sections();
1204
1205   // By default the GNU linker sorts some special text sections ahead
1206   // of others.  We are compatible.
1207   if (parameters->options().text_reorder()
1208       && !this->script_options_->saw_sections_clause()
1209       && !this->is_section_ordering_specified()
1210       && !parameters->options().relocatable()
1211       && Layout::special_ordering_of_input_section(name) >= 0)
1212     os->set_must_sort_attached_input_sections();
1213
1214   // If this is a .ctors or .ctors.* section being mapped to a
1215   // .init_array section, or a .dtors or .dtors.* section being mapped
1216   // to a .fini_array section, we will need to reverse the words if
1217   // there is more than one.  Record this section for later.  See
1218   // ctors_sections_in_init_array above.
1219   if (!this->script_options_->saw_sections_clause()
1220       && !parameters->options().relocatable()
1221       && shdr.get_sh_size() > size / 8
1222       && (((strcmp(name, ".ctors") == 0
1223             || is_prefix_of(".ctors.", name))
1224            && strcmp(os->name(), ".init_array") == 0)
1225           || ((strcmp(name, ".dtors") == 0
1226                || is_prefix_of(".dtors.", name))
1227               && strcmp(os->name(), ".fini_array") == 0)))
1228     ctors_sections_in_init_array.insert(Section_id(object, shndx));
1229
1230   // FIXME: Handle SHF_LINK_ORDER somewhere.
1231
1232   elfcpp::Elf_Xword orig_flags = os->flags();
1233
1234   *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
1235                                this->script_options_->saw_sections_clause());
1236
1237   // If the flags changed, we may have to change the order.
1238   if ((orig_flags & elfcpp::SHF_ALLOC) != 0)
1239     {
1240       orig_flags &= (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
1241       elfcpp::Elf_Xword new_flags =
1242         os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
1243       if (orig_flags != new_flags)
1244         os->set_order(this->default_section_order(os, false));
1245     }
1246
1247   this->have_added_input_section_ = true;
1248
1249   return os;
1250 }
1251
1252 // Maps section SECN to SEGMENT s.
1253 void
1254 Layout::insert_section_segment_map(Const_section_id secn,
1255                                    Unique_segment_info *s)
1256 {
1257   gold_assert(this->unique_segment_for_sections_specified_); 
1258   this->section_segment_map_[secn] = s;
1259 }
1260
1261 // Handle a relocation section when doing a relocatable link.
1262
1263 template<int size, bool big_endian>
1264 Output_section*
1265 Layout::layout_reloc(Sized_relobj_file<size, big_endian>* object,
1266                      unsigned int,
1267                      const elfcpp::Shdr<size, big_endian>& shdr,
1268                      Output_section* data_section,
1269                      Relocatable_relocs* rr)
1270 {
1271   gold_assert(parameters->options().relocatable()
1272               || parameters->options().emit_relocs());
1273
1274   int sh_type = shdr.get_sh_type();
1275
1276   std::string name;
1277   if (sh_type == elfcpp::SHT_REL)
1278     name = ".rel";
1279   else if (sh_type == elfcpp::SHT_RELA)
1280     name = ".rela";
1281   else
1282     gold_unreachable();
1283   name += data_section->name();
1284
1285   // In a relocatable link relocs for a grouped section must not be
1286   // combined with other reloc sections.
1287   Output_section* os;
1288   if (!parameters->options().relocatable()
1289       || (data_section->flags() & elfcpp::SHF_GROUP) == 0)
1290     os = this->choose_output_section(object, name.c_str(), sh_type,
1291                                      shdr.get_sh_flags(), false,
1292                                      ORDER_INVALID, false);
1293   else
1294     {
1295       const char* n = this->namepool_.add(name.c_str(), true, NULL);
1296       os = this->make_output_section(n, sh_type, shdr.get_sh_flags(),
1297                                      ORDER_INVALID, false);
1298     }
1299
1300   os->set_should_link_to_symtab();
1301   os->set_info_section(data_section);
1302
1303   Output_section_data* posd;
1304   if (sh_type == elfcpp::SHT_REL)
1305     {
1306       os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
1307       posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
1308                                            size,
1309                                            big_endian>(rr);
1310     }
1311   else if (sh_type == elfcpp::SHT_RELA)
1312     {
1313       os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
1314       posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
1315                                            size,
1316                                            big_endian>(rr);
1317     }
1318   else
1319     gold_unreachable();
1320
1321   os->add_output_section_data(posd);
1322   rr->set_output_data(posd);
1323
1324   return os;
1325 }
1326
1327 // Handle a group section when doing a relocatable link.
1328
1329 template<int size, bool big_endian>
1330 void
1331 Layout::layout_group(Symbol_table* symtab,
1332                      Sized_relobj_file<size, big_endian>* object,
1333                      unsigned int,
1334                      const char* group_section_name,
1335                      const char* signature,
1336                      const elfcpp::Shdr<size, big_endian>& shdr,
1337                      elfcpp::Elf_Word flags,
1338                      std::vector<unsigned int>* shndxes)
1339 {
1340   gold_assert(parameters->options().relocatable());
1341   gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
1342   group_section_name = this->namepool_.add(group_section_name, true, NULL);
1343   Output_section* os = this->make_output_section(group_section_name,
1344                                                  elfcpp::SHT_GROUP,
1345                                                  shdr.get_sh_flags(),
1346                                                  ORDER_INVALID, false);
1347
1348   // We need to find a symbol with the signature in the symbol table.
1349   // If we don't find one now, we need to look again later.
1350   Symbol* sym = symtab->lookup(signature, NULL);
1351   if (sym != NULL)
1352     os->set_info_symndx(sym);
1353   else
1354     {
1355       // Reserve some space to minimize reallocations.
1356       if (this->group_signatures_.empty())
1357         this->group_signatures_.reserve(this->number_of_input_files_ * 16);
1358
1359       // We will wind up using a symbol whose name is the signature.
1360       // So just put the signature in the symbol name pool to save it.
1361       signature = symtab->canonicalize_name(signature);
1362       this->group_signatures_.push_back(Group_signature(os, signature));
1363     }
1364
1365   os->set_should_link_to_symtab();
1366   os->set_entsize(4);
1367
1368   section_size_type entry_count =
1369     convert_to_section_size_type(shdr.get_sh_size() / 4);
1370   Output_section_data* posd =
1371     new Output_data_group<size, big_endian>(object, entry_count, flags,
1372                                             shndxes);
1373   os->add_output_section_data(posd);
1374 }
1375
1376 // Special GNU handling of sections name .eh_frame.  They will
1377 // normally hold exception frame data as defined by the C++ ABI
1378 // (http://codesourcery.com/cxx-abi/).
1379
1380 template<int size, bool big_endian>
1381 Output_section*
1382 Layout::layout_eh_frame(Sized_relobj_file<size, big_endian>* object,
1383                         const unsigned char* symbols,
1384                         off_t symbols_size,
1385                         const unsigned char* symbol_names,
1386                         off_t symbol_names_size,
1387                         unsigned int shndx,
1388                         const elfcpp::Shdr<size, big_endian>& shdr,
1389                         unsigned int reloc_shndx, unsigned int reloc_type,
1390                         off_t* off)
1391 {
1392   gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS
1393               || shdr.get_sh_type() == elfcpp::SHT_X86_64_UNWIND);
1394   gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
1395
1396   Output_section* os = this->make_eh_frame_section(object);
1397   if (os == NULL)
1398     return NULL;
1399
1400   gold_assert(this->eh_frame_section_ == os);
1401
1402   elfcpp::Elf_Xword orig_flags = os->flags();
1403
1404   if (!parameters->incremental()
1405       && this->eh_frame_data_->add_ehframe_input_section(object,
1406                                                          symbols,
1407                                                          symbols_size,
1408                                                          symbol_names,
1409                                                          symbol_names_size,
1410                                                          shndx,
1411                                                          reloc_shndx,
1412                                                          reloc_type))
1413     {
1414       os->update_flags_for_input_section(shdr.get_sh_flags());
1415
1416       // A writable .eh_frame section is a RELRO section.
1417       if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
1418           != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
1419         {
1420           os->set_is_relro();
1421           os->set_order(ORDER_RELRO);
1422         }
1423
1424       // We found a .eh_frame section we are going to optimize, so now
1425       // we can add the set of optimized sections to the output
1426       // section.  We need to postpone adding this until we've found a
1427       // section we can optimize so that the .eh_frame section in
1428       // crtbegin.o winds up at the start of the output section.
1429       if (!this->added_eh_frame_data_)
1430         {
1431           os->add_output_section_data(this->eh_frame_data_);
1432           this->added_eh_frame_data_ = true;
1433         }
1434       *off = -1;
1435     }
1436   else
1437     {
1438       // We couldn't handle this .eh_frame section for some reason.
1439       // Add it as a normal section.
1440       bool saw_sections_clause = this->script_options_->saw_sections_clause();
1441       *off = os->add_input_section(this, object, shndx, ".eh_frame", shdr,
1442                                    reloc_shndx, saw_sections_clause);
1443       this->have_added_input_section_ = true;
1444
1445       if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
1446           != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
1447         os->set_order(this->default_section_order(os, false));
1448     }
1449
1450   return os;
1451 }
1452
1453 // Create and return the magic .eh_frame section.  Create
1454 // .eh_frame_hdr also if appropriate.  OBJECT is the object with the
1455 // input .eh_frame section; it may be NULL.
1456
1457 Output_section*
1458 Layout::make_eh_frame_section(const Relobj* object)
1459 {
1460   // FIXME: On x86_64, this could use SHT_X86_64_UNWIND rather than
1461   // SHT_PROGBITS.
1462   Output_section* os = this->choose_output_section(object, ".eh_frame",
1463                                                    elfcpp::SHT_PROGBITS,
1464                                                    elfcpp::SHF_ALLOC, false,
1465                                                    ORDER_EHFRAME, false);
1466   if (os == NULL)
1467     return NULL;
1468
1469   if (this->eh_frame_section_ == NULL)
1470     {
1471       this->eh_frame_section_ = os;
1472       this->eh_frame_data_ = new Eh_frame();
1473
1474       // For incremental linking, we do not optimize .eh_frame sections
1475       // or create a .eh_frame_hdr section.
1476       if (parameters->options().eh_frame_hdr() && !parameters->incremental())
1477         {
1478           Output_section* hdr_os =
1479             this->choose_output_section(NULL, ".eh_frame_hdr",
1480                                         elfcpp::SHT_PROGBITS,
1481                                         elfcpp::SHF_ALLOC, false,
1482                                         ORDER_EHFRAME, false);
1483
1484           if (hdr_os != NULL)
1485             {
1486               Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
1487                                                         this->eh_frame_data_);
1488               hdr_os->add_output_section_data(hdr_posd);
1489
1490               hdr_os->set_after_input_sections();
1491
1492               if (!this->script_options_->saw_phdrs_clause())
1493                 {
1494                   Output_segment* hdr_oseg;
1495                   hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
1496                                                        elfcpp::PF_R);
1497                   hdr_oseg->add_output_section_to_nonload(hdr_os,
1498                                                           elfcpp::PF_R);
1499                 }
1500
1501               this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
1502             }
1503         }
1504     }
1505
1506   return os;
1507 }
1508
1509 // Add an exception frame for a PLT.  This is called from target code.
1510
1511 void
1512 Layout::add_eh_frame_for_plt(Output_data* plt, const unsigned char* cie_data,
1513                              size_t cie_length, const unsigned char* fde_data,
1514                              size_t fde_length)
1515 {
1516   if (parameters->incremental())
1517     {
1518       // FIXME: Maybe this could work some day....
1519       return;
1520     }
1521   Output_section* os = this->make_eh_frame_section(NULL);
1522   if (os == NULL)
1523     return;
1524   this->eh_frame_data_->add_ehframe_for_plt(plt, cie_data, cie_length,
1525                                             fde_data, fde_length);
1526   if (!this->added_eh_frame_data_)
1527     {
1528       os->add_output_section_data(this->eh_frame_data_);
1529       this->added_eh_frame_data_ = true;
1530     }
1531 }
1532
1533 // Scan a .debug_info or .debug_types section, and add summary
1534 // information to the .gdb_index section.
1535
1536 template<int size, bool big_endian>
1537 void
1538 Layout::add_to_gdb_index(bool is_type_unit,
1539                          Sized_relobj<size, big_endian>* object,
1540                          const unsigned char* symbols,
1541                          off_t symbols_size,
1542                          unsigned int shndx,
1543                          unsigned int reloc_shndx,
1544                          unsigned int reloc_type)
1545 {
1546   if (this->gdb_index_data_ == NULL)
1547     {
1548       Output_section* os = this->choose_output_section(NULL, ".gdb_index",
1549                                                        elfcpp::SHT_PROGBITS, 0,
1550                                                        false, ORDER_INVALID,
1551                                                        false);
1552       if (os == NULL)
1553         return;
1554
1555       this->gdb_index_data_ = new Gdb_index(os);
1556       os->add_output_section_data(this->gdb_index_data_);
1557       os->set_after_input_sections();
1558     }
1559
1560   this->gdb_index_data_->scan_debug_info(is_type_unit, object, symbols,
1561                                          symbols_size, shndx, reloc_shndx,
1562                                          reloc_type);
1563 }
1564
1565 // Add POSD to an output section using NAME, TYPE, and FLAGS.  Return
1566 // the output section.
1567
1568 Output_section*
1569 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
1570                                 elfcpp::Elf_Xword flags,
1571                                 Output_section_data* posd,
1572                                 Output_section_order order, bool is_relro)
1573 {
1574   Output_section* os = this->choose_output_section(NULL, name, type, flags,
1575                                                    false, order, is_relro);
1576   if (os != NULL)
1577     os->add_output_section_data(posd);
1578   return os;
1579 }
1580
1581 // Map section flags to segment flags.
1582
1583 elfcpp::Elf_Word
1584 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
1585 {
1586   elfcpp::Elf_Word ret = elfcpp::PF_R;
1587   if ((flags & elfcpp::SHF_WRITE) != 0)
1588     ret |= elfcpp::PF_W;
1589   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
1590     ret |= elfcpp::PF_X;
1591   return ret;
1592 }
1593
1594 // Make a new Output_section, and attach it to segments as
1595 // appropriate.  ORDER is the order in which this section should
1596 // appear in the output segment.  IS_RELRO is true if this is a relro
1597 // (read-only after relocations) section.
1598
1599 Output_section*
1600 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
1601                             elfcpp::Elf_Xword flags,
1602                             Output_section_order order, bool is_relro)
1603 {
1604   Output_section* os;
1605   if ((flags & elfcpp::SHF_ALLOC) == 0
1606       && strcmp(parameters->options().compress_debug_sections(), "none") != 0
1607       && is_compressible_debug_section(name))
1608     os = new Output_compressed_section(&parameters->options(), name, type,
1609                                        flags);
1610   else if ((flags & elfcpp::SHF_ALLOC) == 0
1611            && parameters->options().strip_debug_non_line()
1612            && strcmp(".debug_abbrev", name) == 0)
1613     {
1614       os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
1615           name, type, flags);
1616       if (this->debug_info_)
1617         this->debug_info_->set_abbreviations(this->debug_abbrev_);
1618     }
1619   else if ((flags & elfcpp::SHF_ALLOC) == 0
1620            && parameters->options().strip_debug_non_line()
1621            && strcmp(".debug_info", name) == 0)
1622     {
1623       os = this->debug_info_ = new Output_reduced_debug_info_section(
1624           name, type, flags);
1625       if (this->debug_abbrev_)
1626         this->debug_info_->set_abbreviations(this->debug_abbrev_);
1627     }
1628   else
1629     {
1630       // Sometimes .init_array*, .preinit_array* and .fini_array* do
1631       // not have correct section types.  Force them here.
1632       if (type == elfcpp::SHT_PROGBITS)
1633         {
1634           if (is_prefix_of(".init_array", name))
1635             type = elfcpp::SHT_INIT_ARRAY;
1636           else if (is_prefix_of(".preinit_array", name))
1637             type = elfcpp::SHT_PREINIT_ARRAY;
1638           else if (is_prefix_of(".fini_array", name))
1639             type = elfcpp::SHT_FINI_ARRAY;
1640         }
1641
1642       // FIXME: const_cast is ugly.
1643       Target* target = const_cast<Target*>(&parameters->target());
1644       os = target->make_output_section(name, type, flags);
1645     }
1646
1647   // With -z relro, we have to recognize the special sections by name.
1648   // There is no other way.
1649   bool is_relro_local = false;
1650   if (!this->script_options_->saw_sections_clause()
1651       && parameters->options().relro()
1652       && (flags & elfcpp::SHF_ALLOC) != 0
1653       && (flags & elfcpp::SHF_WRITE) != 0)
1654     {
1655       if (type == elfcpp::SHT_PROGBITS)
1656         {
1657           if ((flags & elfcpp::SHF_TLS) != 0)
1658             is_relro = true;
1659           else if (strcmp(name, ".data.rel.ro") == 0)
1660             is_relro = true;
1661           else if (strcmp(name, ".data.rel.ro.local") == 0)
1662             {
1663               is_relro = true;
1664               is_relro_local = true;
1665             }
1666           else if (strcmp(name, ".ctors") == 0
1667                    || strcmp(name, ".dtors") == 0
1668                    || strcmp(name, ".jcr") == 0)
1669             is_relro = true;
1670         }
1671       else if (type == elfcpp::SHT_INIT_ARRAY
1672                || type == elfcpp::SHT_FINI_ARRAY
1673                || type == elfcpp::SHT_PREINIT_ARRAY)
1674         is_relro = true;
1675     }
1676
1677   if (is_relro)
1678     os->set_is_relro();
1679
1680   if (order == ORDER_INVALID && (flags & elfcpp::SHF_ALLOC) != 0)
1681     order = this->default_section_order(os, is_relro_local);
1682
1683   os->set_order(order);
1684
1685   parameters->target().new_output_section(os);
1686
1687   this->section_list_.push_back(os);
1688
1689   // The GNU linker by default sorts some sections by priority, so we
1690   // do the same.  We need to know that this might happen before we
1691   // attach any input sections.
1692   if (!this->script_options_->saw_sections_clause()
1693       && !parameters->options().relocatable()
1694       && (strcmp(name, ".init_array") == 0
1695           || strcmp(name, ".fini_array") == 0
1696           || (!parameters->options().ctors_in_init_array()
1697               && (strcmp(name, ".ctors") == 0
1698                   || strcmp(name, ".dtors") == 0))))
1699     os->set_may_sort_attached_input_sections();
1700
1701   // The GNU linker by default sorts .text.{unlikely,exit,startup,hot}
1702   // sections before other .text sections.  We are compatible.  We
1703   // need to know that this might happen before we attach any input
1704   // sections.
1705   if (parameters->options().text_reorder()
1706       && !this->script_options_->saw_sections_clause()
1707       && !this->is_section_ordering_specified()
1708       && !parameters->options().relocatable()
1709       && strcmp(name, ".text") == 0)
1710     os->set_may_sort_attached_input_sections();
1711
1712   // Check for .stab*str sections, as .stab* sections need to link to
1713   // them.
1714   if (type == elfcpp::SHT_STRTAB
1715       && !this->have_stabstr_section_
1716       && strncmp(name, ".stab", 5) == 0
1717       && strcmp(name + strlen(name) - 3, "str") == 0)
1718     this->have_stabstr_section_ = true;
1719
1720   // During a full incremental link, we add patch space to most
1721   // PROGBITS and NOBITS sections.  Flag those that may be
1722   // arbitrarily padded.
1723   if ((type == elfcpp::SHT_PROGBITS || type == elfcpp::SHT_NOBITS)
1724       && order != ORDER_INTERP
1725       && order != ORDER_INIT
1726       && order != ORDER_PLT
1727       && order != ORDER_FINI
1728       && order != ORDER_RELRO_LAST
1729       && order != ORDER_NON_RELRO_FIRST
1730       && strcmp(name, ".eh_frame") != 0
1731       && strcmp(name, ".ctors") != 0
1732       && strcmp(name, ".dtors") != 0
1733       && strcmp(name, ".jcr") != 0)
1734     {
1735       os->set_is_patch_space_allowed();
1736
1737       // Certain sections require "holes" to be filled with
1738       // specific fill patterns.  These fill patterns may have
1739       // a minimum size, so we must prevent allocations from the
1740       // free list that leave a hole smaller than the minimum.
1741       if (strcmp(name, ".debug_info") == 0)
1742         os->set_free_space_fill(new Output_fill_debug_info(false));
1743       else if (strcmp(name, ".debug_types") == 0)
1744         os->set_free_space_fill(new Output_fill_debug_info(true));
1745       else if (strcmp(name, ".debug_line") == 0)
1746         os->set_free_space_fill(new Output_fill_debug_line());
1747     }
1748
1749   // If we have already attached the sections to segments, then we
1750   // need to attach this one now.  This happens for sections created
1751   // directly by the linker.
1752   if (this->sections_are_attached_)
1753     this->attach_section_to_segment(&parameters->target(), os);
1754
1755   return os;
1756 }
1757
1758 // Return the default order in which a section should be placed in an
1759 // output segment.  This function captures a lot of the ideas in
1760 // ld/scripttempl/elf.sc in the GNU linker.  Note that the order of a
1761 // linker created section is normally set when the section is created;
1762 // this function is used for input sections.
1763
1764 Output_section_order
1765 Layout::default_section_order(Output_section* os, bool is_relro_local)
1766 {
1767   gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
1768   bool is_write = (os->flags() & elfcpp::SHF_WRITE) != 0;
1769   bool is_execinstr = (os->flags() & elfcpp::SHF_EXECINSTR) != 0;
1770   bool is_bss = false;
1771
1772   switch (os->type())
1773     {
1774     default:
1775     case elfcpp::SHT_PROGBITS:
1776       break;
1777     case elfcpp::SHT_NOBITS:
1778       is_bss = true;
1779       break;
1780     case elfcpp::SHT_RELA:
1781     case elfcpp::SHT_REL:
1782       if (!is_write)
1783         return ORDER_DYNAMIC_RELOCS;
1784       break;
1785     case elfcpp::SHT_HASH:
1786     case elfcpp::SHT_DYNAMIC:
1787     case elfcpp::SHT_SHLIB:
1788     case elfcpp::SHT_DYNSYM:
1789     case elfcpp::SHT_GNU_HASH:
1790     case elfcpp::SHT_GNU_verdef:
1791     case elfcpp::SHT_GNU_verneed:
1792     case elfcpp::SHT_GNU_versym:
1793       if (!is_write)
1794         return ORDER_DYNAMIC_LINKER;
1795       break;
1796     case elfcpp::SHT_NOTE:
1797       return is_write ? ORDER_RW_NOTE : ORDER_RO_NOTE;
1798     }
1799
1800   if ((os->flags() & elfcpp::SHF_TLS) != 0)
1801     return is_bss ? ORDER_TLS_BSS : ORDER_TLS_DATA;
1802
1803   if (!is_bss && !is_write)
1804     {
1805       if (is_execinstr)
1806         {
1807           if (strcmp(os->name(), ".init") == 0)
1808             return ORDER_INIT;
1809           else if (strcmp(os->name(), ".fini") == 0)
1810             return ORDER_FINI;
1811         }
1812       return is_execinstr ? ORDER_TEXT : ORDER_READONLY;
1813     }
1814
1815   if (os->is_relro())
1816     return is_relro_local ? ORDER_RELRO_LOCAL : ORDER_RELRO;
1817
1818   if (os->is_small_section())
1819     return is_bss ? ORDER_SMALL_BSS : ORDER_SMALL_DATA;
1820   if (os->is_large_section())
1821     return is_bss ? ORDER_LARGE_BSS : ORDER_LARGE_DATA;
1822
1823   return is_bss ? ORDER_BSS : ORDER_DATA;
1824 }
1825
1826 // Attach output sections to segments.  This is called after we have
1827 // seen all the input sections.
1828
1829 void
1830 Layout::attach_sections_to_segments(const Target* target)
1831 {
1832   for (Section_list::iterator p = this->section_list_.begin();
1833        p != this->section_list_.end();
1834        ++p)
1835     this->attach_section_to_segment(target, *p);
1836
1837   this->sections_are_attached_ = true;
1838 }
1839
1840 // Attach an output section to a segment.
1841
1842 void
1843 Layout::attach_section_to_segment(const Target* target, Output_section* os)
1844 {
1845   if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1846     this->unattached_section_list_.push_back(os);
1847   else
1848     this->attach_allocated_section_to_segment(target, os);
1849 }
1850
1851 // Attach an allocated output section to a segment.
1852
1853 void
1854 Layout::attach_allocated_section_to_segment(const Target* target,
1855                                             Output_section* os)
1856 {
1857   elfcpp::Elf_Xword flags = os->flags();
1858   gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
1859
1860   if (parameters->options().relocatable())
1861     return;
1862
1863   // If we have a SECTIONS clause, we can't handle the attachment to
1864   // segments until after we've seen all the sections.
1865   if (this->script_options_->saw_sections_clause())
1866     return;
1867
1868   gold_assert(!this->script_options_->saw_phdrs_clause());
1869
1870   // This output section goes into a PT_LOAD segment.
1871
1872   elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
1873
1874   // If this output section's segment has extra flags that need to be set,
1875   // coming from a linker plugin, do that.
1876   seg_flags |= os->extra_segment_flags();
1877
1878   // Check for --section-start.
1879   uint64_t addr;
1880   bool is_address_set = parameters->options().section_start(os->name(), &addr);
1881
1882   // In general the only thing we really care about for PT_LOAD
1883   // segments is whether or not they are writable or executable,
1884   // so that is how we search for them.
1885   // Large data sections also go into their own PT_LOAD segment.
1886   // People who need segments sorted on some other basis will
1887   // have to use a linker script.
1888
1889   Segment_list::const_iterator p;
1890   if (!os->is_unique_segment())
1891     {
1892       for (p = this->segment_list_.begin();
1893            p != this->segment_list_.end();
1894            ++p)
1895         {
1896           if ((*p)->type() != elfcpp::PT_LOAD)                        
1897             continue;                        
1898           if ((*p)->is_unique_segment())                        
1899             continue;                        
1900           if (!parameters->options().omagic()                        
1901               && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))                        
1902             continue;                        
1903           if ((target->isolate_execinstr() || parameters->options().rosegment())                        
1904               && ((*p)->flags() & elfcpp::PF_X) != (seg_flags & elfcpp::PF_X))                        
1905             continue;                        
1906           // If -Tbss was specified, we need to separate the data and BSS                        
1907           // segments.                        
1908           if (parameters->options().user_set_Tbss())                        
1909             {                        
1910               if ((os->type() == elfcpp::SHT_NOBITS)                        
1911                   == (*p)->has_any_data_sections())                        
1912                 continue;                        
1913             }                        
1914           if (os->is_large_data_section() && !(*p)->is_large_data_segment())                        
1915             continue;                        
1916                             
1917           if (is_address_set)                        
1918             {                        
1919               if ((*p)->are_addresses_set())                        
1920                 continue;                        
1921                             
1922               (*p)->add_initial_output_data(os);                        
1923               (*p)->update_flags_for_output_section(seg_flags);                        
1924               (*p)->set_addresses(addr, addr);                        
1925               break;                        
1926             }                        
1927                             
1928           (*p)->add_output_section_to_load(this, os, seg_flags);                        
1929           break;                        
1930         }                        
1931     }
1932
1933   if (p == this->segment_list_.end()
1934       || os->is_unique_segment())
1935     {
1936       Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1937                                                        seg_flags);
1938       if (os->is_large_data_section())
1939         oseg->set_is_large_data_segment();
1940       oseg->add_output_section_to_load(this, os, seg_flags);
1941       if (is_address_set)
1942         oseg->set_addresses(addr, addr);
1943       // Check if segment should be marked unique.  For segments marked
1944       // unique by linker plugins, set the new alignment if specified.
1945       if (os->is_unique_segment())
1946         {
1947           oseg->set_is_unique_segment();
1948           if (os->segment_alignment() != 0)
1949             oseg->set_minimum_p_align(os->segment_alignment());
1950         }
1951     }
1952
1953   // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1954   // segment.
1955   if (os->type() == elfcpp::SHT_NOTE)
1956     {
1957       // See if we already have an equivalent PT_NOTE segment.
1958       for (p = this->segment_list_.begin();
1959            p != segment_list_.end();
1960            ++p)
1961         {
1962           if ((*p)->type() == elfcpp::PT_NOTE
1963               && (((*p)->flags() & elfcpp::PF_W)
1964                   == (seg_flags & elfcpp::PF_W)))
1965             {
1966               (*p)->add_output_section_to_nonload(os, seg_flags);
1967               break;
1968             }
1969         }
1970
1971       if (p == this->segment_list_.end())
1972         {
1973           Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1974                                                            seg_flags);
1975           oseg->add_output_section_to_nonload(os, seg_flags);
1976         }
1977     }
1978
1979   // If we see a loadable SHF_TLS section, we create a PT_TLS
1980   // segment.  There can only be one such segment.
1981   if ((flags & elfcpp::SHF_TLS) != 0)
1982     {
1983       if (this->tls_segment_ == NULL)
1984         this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1985       this->tls_segment_->add_output_section_to_nonload(os, seg_flags);
1986     }
1987
1988   // If -z relro is in effect, and we see a relro section, we create a
1989   // PT_GNU_RELRO segment.  There can only be one such segment.
1990   if (os->is_relro() && parameters->options().relro())
1991     {
1992       gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1993       if (this->relro_segment_ == NULL)
1994         this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1995       this->relro_segment_->add_output_section_to_nonload(os, seg_flags);
1996     }
1997
1998   // If we see a section named .interp, put it into a PT_INTERP
1999   // segment.  This seems broken to me, but this is what GNU ld does,
2000   // and glibc expects it.
2001   if (strcmp(os->name(), ".interp") == 0
2002       && !this->script_options_->saw_phdrs_clause())
2003     {
2004       if (this->interp_segment_ == NULL)
2005         this->make_output_segment(elfcpp::PT_INTERP, seg_flags);
2006       else
2007         gold_warning(_("multiple '.interp' sections in input files "
2008                        "may cause confusing PT_INTERP segment"));
2009       this->interp_segment_->add_output_section_to_nonload(os, seg_flags);
2010     }
2011 }
2012
2013 // Make an output section for a script.
2014
2015 Output_section*
2016 Layout::make_output_section_for_script(
2017     const char* name,
2018     Script_sections::Section_type section_type)
2019 {
2020   name = this->namepool_.add(name, false, NULL);
2021   elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
2022   if (section_type == Script_sections::ST_NOLOAD)
2023     sh_flags = 0;
2024   Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
2025                                                  sh_flags, ORDER_INVALID,
2026                                                  false);
2027   os->set_found_in_sections_clause();
2028   if (section_type == Script_sections::ST_NOLOAD)
2029     os->set_is_noload();
2030   return os;
2031 }
2032
2033 // Return the number of segments we expect to see.
2034
2035 size_t
2036 Layout::expected_segment_count() const
2037 {
2038   size_t ret = this->segment_list_.size();
2039
2040   // If we didn't see a SECTIONS clause in a linker script, we should
2041   // already have the complete list of segments.  Otherwise we ask the
2042   // SECTIONS clause how many segments it expects, and add in the ones
2043   // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
2044
2045   if (!this->script_options_->saw_sections_clause())
2046     return ret;
2047   else
2048     {
2049       const Script_sections* ss = this->script_options_->script_sections();
2050       return ret + ss->expected_segment_count(this);
2051     }
2052 }
2053
2054 // Handle the .note.GNU-stack section at layout time.  SEEN_GNU_STACK
2055 // is whether we saw a .note.GNU-stack section in the object file.
2056 // GNU_STACK_FLAGS is the section flags.  The flags give the
2057 // protection required for stack memory.  We record this in an
2058 // executable as a PT_GNU_STACK segment.  If an object file does not
2059 // have a .note.GNU-stack segment, we must assume that it is an old
2060 // object.  On some targets that will force an executable stack.
2061
2062 void
2063 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags,
2064                          const Object* obj)
2065 {
2066   if (!seen_gnu_stack)
2067     {
2068       this->input_without_gnu_stack_note_ = true;
2069       if (parameters->options().warn_execstack()
2070           && parameters->target().is_default_stack_executable())
2071         gold_warning(_("%s: missing .note.GNU-stack section"
2072                        " implies executable stack"),
2073                      obj->name().c_str());
2074     }
2075   else
2076     {
2077       this->input_with_gnu_stack_note_ = true;
2078       if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
2079         {
2080           this->input_requires_executable_stack_ = true;
2081           if (parameters->options().warn_execstack()
2082               || parameters->options().is_stack_executable())
2083             gold_warning(_("%s: requires executable stack"),
2084                          obj->name().c_str());
2085         }
2086     }
2087 }
2088
2089 // Create automatic note sections.
2090
2091 void
2092 Layout::create_notes()
2093 {
2094   this->create_gold_note();
2095   this->create_executable_stack_info();
2096   this->create_build_id();
2097 }
2098
2099 // Create the dynamic sections which are needed before we read the
2100 // relocs.
2101
2102 void
2103 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
2104 {
2105   if (parameters->doing_static_link())
2106     return;
2107
2108   this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
2109                                                        elfcpp::SHT_DYNAMIC,
2110                                                        (elfcpp::SHF_ALLOC
2111                                                         | elfcpp::SHF_WRITE),
2112                                                        false, ORDER_RELRO,
2113                                                        true);
2114
2115   // A linker script may discard .dynamic, so check for NULL.
2116   if (this->dynamic_section_ != NULL)
2117     {
2118       this->dynamic_symbol_ =
2119         symtab->define_in_output_data("_DYNAMIC", NULL,
2120                                       Symbol_table::PREDEFINED,
2121                                       this->dynamic_section_, 0, 0,
2122                                       elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
2123                                       elfcpp::STV_HIDDEN, 0, false, false);
2124
2125       this->dynamic_data_ =  new Output_data_dynamic(&this->dynpool_);
2126
2127       this->dynamic_section_->add_output_section_data(this->dynamic_data_);
2128     }
2129 }
2130
2131 // For each output section whose name can be represented as C symbol,
2132 // define __start and __stop symbols for the section.  This is a GNU
2133 // extension.
2134
2135 void
2136 Layout::define_section_symbols(Symbol_table* symtab)
2137 {
2138   for (Section_list::const_iterator p = this->section_list_.begin();
2139        p != this->section_list_.end();
2140        ++p)
2141     {
2142       const char* const name = (*p)->name();
2143       if (is_cident(name))
2144         {
2145           const std::string name_string(name);
2146           const std::string start_name(cident_section_start_prefix
2147                                        + name_string);
2148           const std::string stop_name(cident_section_stop_prefix
2149                                       + name_string);
2150
2151           symtab->define_in_output_data(start_name.c_str(),
2152                                         NULL, // version
2153                                         Symbol_table::PREDEFINED,
2154                                         *p,
2155                                         0, // value
2156                                         0, // symsize
2157                                         elfcpp::STT_NOTYPE,
2158                                         elfcpp::STB_GLOBAL,
2159                                         elfcpp::STV_DEFAULT,
2160                                         0, // nonvis
2161                                         false, // offset_is_from_end
2162                                         true); // only_if_ref
2163
2164           symtab->define_in_output_data(stop_name.c_str(),
2165                                         NULL, // version
2166                                         Symbol_table::PREDEFINED,
2167                                         *p,
2168                                         0, // value
2169                                         0, // symsize
2170                                         elfcpp::STT_NOTYPE,
2171                                         elfcpp::STB_GLOBAL,
2172                                         elfcpp::STV_DEFAULT,
2173                                         0, // nonvis
2174                                         true, // offset_is_from_end
2175                                         true); // only_if_ref
2176         }
2177     }
2178 }
2179
2180 // Define symbols for group signatures.
2181
2182 void
2183 Layout::define_group_signatures(Symbol_table* symtab)
2184 {
2185   for (Group_signatures::iterator p = this->group_signatures_.begin();
2186        p != this->group_signatures_.end();
2187        ++p)
2188     {
2189       Symbol* sym = symtab->lookup(p->signature, NULL);
2190       if (sym != NULL)
2191         p->section->set_info_symndx(sym);
2192       else
2193         {
2194           // Force the name of the group section to the group
2195           // signature, and use the group's section symbol as the
2196           // signature symbol.
2197           if (strcmp(p->section->name(), p->signature) != 0)
2198             {
2199               const char* name = this->namepool_.add(p->signature,
2200                                                      true, NULL);
2201               p->section->set_name(name);
2202             }
2203           p->section->set_needs_symtab_index();
2204           p->section->set_info_section_symndx(p->section);
2205         }
2206     }
2207
2208   this->group_signatures_.clear();
2209 }
2210
2211 // Find the first read-only PT_LOAD segment, creating one if
2212 // necessary.
2213
2214 Output_segment*
2215 Layout::find_first_load_seg(const Target* target)
2216 {
2217   Output_segment* best = NULL;
2218   for (Segment_list::const_iterator p = this->segment_list_.begin();
2219        p != this->segment_list_.end();
2220        ++p)
2221     {
2222       if ((*p)->type() == elfcpp::PT_LOAD
2223           && ((*p)->flags() & elfcpp::PF_R) != 0
2224           && (parameters->options().omagic()
2225               || ((*p)->flags() & elfcpp::PF_W) == 0)
2226           && (!target->isolate_execinstr()
2227               || ((*p)->flags() & elfcpp::PF_X) == 0))
2228         {
2229           if (best == NULL || this->segment_precedes(*p, best))
2230             best = *p;
2231         }
2232     }
2233   if (best != NULL)
2234     return best;
2235
2236   gold_assert(!this->script_options_->saw_phdrs_clause());
2237
2238   Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
2239                                                        elfcpp::PF_R);
2240   return load_seg;
2241 }
2242
2243 // Save states of all current output segments.  Store saved states
2244 // in SEGMENT_STATES.
2245
2246 void
2247 Layout::save_segments(Segment_states* segment_states)
2248 {
2249   for (Segment_list::const_iterator p = this->segment_list_.begin();
2250        p != this->segment_list_.end();
2251        ++p)
2252     {
2253       Output_segment* segment = *p;
2254       // Shallow copy.
2255       Output_segment* copy = new Output_segment(*segment);
2256       (*segment_states)[segment] = copy;
2257     }
2258 }
2259
2260 // Restore states of output segments and delete any segment not found in
2261 // SEGMENT_STATES.
2262
2263 void
2264 Layout::restore_segments(const Segment_states* segment_states)
2265 {
2266   // Go through the segment list and remove any segment added in the
2267   // relaxation loop.
2268   this->tls_segment_ = NULL;
2269   this->relro_segment_ = NULL;
2270   Segment_list::iterator list_iter = this->segment_list_.begin();
2271   while (list_iter != this->segment_list_.end())
2272     {
2273       Output_segment* segment = *list_iter;
2274       Segment_states::const_iterator states_iter =
2275           segment_states->find(segment);
2276       if (states_iter != segment_states->end())
2277         {
2278           const Output_segment* copy = states_iter->second;
2279           // Shallow copy to restore states.
2280           *segment = *copy;
2281
2282           // Also fix up TLS and RELRO segment pointers as appropriate.
2283           if (segment->type() == elfcpp::PT_TLS)
2284             this->tls_segment_ = segment;
2285           else if (segment->type() == elfcpp::PT_GNU_RELRO)
2286             this->relro_segment_ = segment;
2287
2288           ++list_iter;
2289         }
2290       else
2291         {
2292           list_iter = this->segment_list_.erase(list_iter);
2293           // This is a segment created during section layout.  It should be
2294           // safe to remove it since we should have removed all pointers to it.
2295           delete segment;
2296         }
2297     }
2298 }
2299
2300 // Clean up after relaxation so that sections can be laid out again.
2301
2302 void
2303 Layout::clean_up_after_relaxation()
2304 {
2305   // Restore the segments to point state just prior to the relaxation loop.
2306   Script_sections* script_section = this->script_options_->script_sections();
2307   script_section->release_segments();
2308   this->restore_segments(this->segment_states_);
2309
2310   // Reset section addresses and file offsets
2311   for (Section_list::iterator p = this->section_list_.begin();
2312        p != this->section_list_.end();
2313        ++p)
2314     {
2315       (*p)->restore_states();
2316
2317       // If an input section changes size because of relaxation,
2318       // we need to adjust the section offsets of all input sections.
2319       // after such a section.
2320       if ((*p)->section_offsets_need_adjustment())
2321         (*p)->adjust_section_offsets();
2322
2323       (*p)->reset_address_and_file_offset();
2324     }
2325
2326   // Reset special output object address and file offsets.
2327   for (Data_list::iterator p = this->special_output_list_.begin();
2328        p != this->special_output_list_.end();
2329        ++p)
2330     (*p)->reset_address_and_file_offset();
2331
2332   // A linker script may have created some output section data objects.
2333   // They are useless now.
2334   for (Output_section_data_list::const_iterator p =
2335          this->script_output_section_data_list_.begin();
2336        p != this->script_output_section_data_list_.end();
2337        ++p)
2338     delete *p;
2339   this->script_output_section_data_list_.clear();
2340 }
2341
2342 // Prepare for relaxation.
2343
2344 void
2345 Layout::prepare_for_relaxation()
2346 {
2347   // Create an relaxation debug check if in debugging mode.
2348   if (is_debugging_enabled(DEBUG_RELAXATION))
2349     this->relaxation_debug_check_ = new Relaxation_debug_check();
2350
2351   // Save segment states.
2352   this->segment_states_ = new Segment_states();
2353   this->save_segments(this->segment_states_);
2354
2355   for(Section_list::const_iterator p = this->section_list_.begin();
2356       p != this->section_list_.end();
2357       ++p)
2358     (*p)->save_states();
2359
2360   if (is_debugging_enabled(DEBUG_RELAXATION))
2361     this->relaxation_debug_check_->check_output_data_for_reset_values(
2362         this->section_list_, this->special_output_list_);
2363
2364   // Also enable recording of output section data from scripts.
2365   this->record_output_section_data_from_script_ = true;
2366 }
2367
2368 // Relaxation loop body:  If target has no relaxation, this runs only once
2369 // Otherwise, the target relaxation hook is called at the end of
2370 // each iteration.  If the hook returns true, it means re-layout of
2371 // section is required.
2372 //
2373 // The number of segments created by a linking script without a PHDRS
2374 // clause may be affected by section sizes and alignments.  There is
2375 // a remote chance that relaxation causes different number of PT_LOAD
2376 // segments are created and sections are attached to different segments.
2377 // Therefore, we always throw away all segments created during section
2378 // layout.  In order to be able to restart the section layout, we keep
2379 // a copy of the segment list right before the relaxation loop and use
2380 // that to restore the segments.
2381 //
2382 // PASS is the current relaxation pass number.
2383 // SYMTAB is a symbol table.
2384 // PLOAD_SEG is the address of a pointer for the load segment.
2385 // PHDR_SEG is a pointer to the PHDR segment.
2386 // SEGMENT_HEADERS points to the output segment header.
2387 // FILE_HEADER points to the output file header.
2388 // PSHNDX is the address to store the output section index.
2389
2390 off_t inline
2391 Layout::relaxation_loop_body(
2392     int pass,
2393     Target* target,
2394     Symbol_table* symtab,
2395     Output_segment** pload_seg,
2396     Output_segment* phdr_seg,
2397     Output_segment_headers* segment_headers,
2398     Output_file_header* file_header,
2399     unsigned int* pshndx)
2400 {
2401   // If this is not the first iteration, we need to clean up after
2402   // relaxation so that we can lay out the sections again.
2403   if (pass != 0)
2404     this->clean_up_after_relaxation();
2405
2406   // If there is a SECTIONS clause, put all the input sections into
2407   // the required order.
2408   Output_segment* load_seg;
2409   if (this->script_options_->saw_sections_clause())
2410     load_seg = this->set_section_addresses_from_script(symtab);
2411   else if (parameters->options().relocatable())
2412     load_seg = NULL;
2413   else
2414     load_seg = this->find_first_load_seg(target);
2415
2416   if (parameters->options().oformat_enum()
2417       != General_options::OBJECT_FORMAT_ELF)
2418     load_seg = NULL;
2419
2420   // If the user set the address of the text segment, that may not be
2421   // compatible with putting the segment headers and file headers into
2422   // that segment.
2423   if (parameters->options().user_set_Ttext()
2424       && parameters->options().Ttext() % target->abi_pagesize() != 0)
2425     {
2426       load_seg = NULL;
2427       phdr_seg = NULL;
2428     }
2429
2430   gold_assert(phdr_seg == NULL
2431               || load_seg != NULL
2432               || this->script_options_->saw_sections_clause());
2433
2434   // If the address of the load segment we found has been set by
2435   // --section-start rather than by a script, then adjust the VMA and
2436   // LMA downward if possible to include the file and section headers.
2437   uint64_t header_gap = 0;
2438   if (load_seg != NULL
2439       && load_seg->are_addresses_set()
2440       && !this->script_options_->saw_sections_clause()
2441       && !parameters->options().relocatable())
2442     {
2443       file_header->finalize_data_size();
2444       segment_headers->finalize_data_size();
2445       size_t sizeof_headers = (file_header->data_size()
2446                                + segment_headers->data_size());
2447       const uint64_t abi_pagesize = target->abi_pagesize();
2448       uint64_t hdr_paddr = load_seg->paddr() - sizeof_headers;
2449       hdr_paddr &= ~(abi_pagesize - 1);
2450       uint64_t subtract = load_seg->paddr() - hdr_paddr;
2451       if (load_seg->paddr() < subtract || load_seg->vaddr() < subtract)
2452         load_seg = NULL;
2453       else
2454         {
2455           load_seg->set_addresses(load_seg->vaddr() - subtract,
2456                                   load_seg->paddr() - subtract);
2457           header_gap = subtract - sizeof_headers;
2458         }
2459     }
2460
2461   // Lay out the segment headers.
2462   if (!parameters->options().relocatable())
2463     {
2464       gold_assert(segment_headers != NULL);
2465       if (header_gap != 0 && load_seg != NULL)
2466         {
2467           Output_data_zero_fill* z = new Output_data_zero_fill(header_gap, 1);
2468           load_seg->add_initial_output_data(z);
2469         }
2470       if (load_seg != NULL)
2471         load_seg->add_initial_output_data(segment_headers);
2472       if (phdr_seg != NULL)
2473         phdr_seg->add_initial_output_data(segment_headers);
2474     }
2475
2476   // Lay out the file header.
2477   if (load_seg != NULL)
2478     load_seg->add_initial_output_data(file_header);
2479
2480   if (this->script_options_->saw_phdrs_clause()
2481       && !parameters->options().relocatable())
2482     {
2483       // Support use of FILEHDRS and PHDRS attachments in a PHDRS
2484       // clause in a linker script.
2485       Script_sections* ss = this->script_options_->script_sections();
2486       ss->put_headers_in_phdrs(file_header, segment_headers);
2487     }
2488
2489   // We set the output section indexes in set_segment_offsets and
2490   // set_section_indexes.
2491   *pshndx = 1;
2492
2493   // Set the file offsets of all the segments, and all the sections
2494   // they contain.
2495   off_t off;
2496   if (!parameters->options().relocatable())
2497     off = this->set_segment_offsets(target, load_seg, pshndx);
2498   else
2499     off = this->set_relocatable_section_offsets(file_header, pshndx);
2500
2501    // Verify that the dummy relaxation does not change anything.
2502   if (is_debugging_enabled(DEBUG_RELAXATION))
2503     {
2504       if (pass == 0)
2505         this->relaxation_debug_check_->read_sections(this->section_list_);
2506       else
2507         this->relaxation_debug_check_->verify_sections(this->section_list_);
2508     }
2509
2510   *pload_seg = load_seg;
2511   return off;
2512 }
2513
2514 // Search the list of patterns and find the postion of the given section
2515 // name in the output section.  If the section name matches a glob
2516 // pattern and a non-glob name, then the non-glob position takes
2517 // precedence.  Return 0 if no match is found.
2518
2519 unsigned int
2520 Layout::find_section_order_index(const std::string& section_name)
2521 {
2522   Unordered_map<std::string, unsigned int>::iterator map_it;
2523   map_it = this->input_section_position_.find(section_name);
2524   if (map_it != this->input_section_position_.end())
2525     return map_it->second;
2526
2527   // Absolute match failed.  Linear search the glob patterns.
2528   std::vector<std::string>::iterator it;
2529   for (it = this->input_section_glob_.begin();
2530        it != this->input_section_glob_.end();
2531        ++it)
2532     {
2533        if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
2534          {
2535            map_it = this->input_section_position_.find(*it);
2536            gold_assert(map_it != this->input_section_position_.end());
2537            return map_it->second;
2538          }
2539     }
2540   return 0;
2541 }
2542
2543 // Read the sequence of input sections from the file specified with
2544 // option --section-ordering-file.
2545
2546 void
2547 Layout::read_layout_from_file()
2548 {
2549   const char* filename = parameters->options().section_ordering_file();
2550   std::ifstream in;
2551   std::string line;
2552
2553   in.open(filename);
2554   if (!in)
2555     gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
2556                filename, strerror(errno));
2557
2558   std::getline(in, line);   // this chops off the trailing \n, if any
2559   unsigned int position = 1;
2560   this->set_section_ordering_specified();
2561
2562   while (in)
2563     {
2564       if (!line.empty() && line[line.length() - 1] == '\r')   // Windows
2565         line.resize(line.length() - 1);
2566       // Ignore comments, beginning with '#'
2567       if (line[0] == '#')
2568         {
2569           std::getline(in, line);
2570           continue;
2571         }
2572       this->input_section_position_[line] = position;
2573       // Store all glob patterns in a vector.
2574       if (is_wildcard_string(line.c_str()))
2575         this->input_section_glob_.push_back(line);
2576       position++;
2577       std::getline(in, line);
2578     }
2579 }
2580
2581 // Finalize the layout.  When this is called, we have created all the
2582 // output sections and all the output segments which are based on
2583 // input sections.  We have several things to do, and we have to do
2584 // them in the right order, so that we get the right results correctly
2585 // and efficiently.
2586
2587 // 1) Finalize the list of output segments and create the segment
2588 // table header.
2589
2590 // 2) Finalize the dynamic symbol table and associated sections.
2591
2592 // 3) Determine the final file offset of all the output segments.
2593
2594 // 4) Determine the final file offset of all the SHF_ALLOC output
2595 // sections.
2596
2597 // 5) Create the symbol table sections and the section name table
2598 // section.
2599
2600 // 6) Finalize the symbol table: set symbol values to their final
2601 // value and make a final determination of which symbols are going
2602 // into the output symbol table.
2603
2604 // 7) Create the section table header.
2605
2606 // 8) Determine the final file offset of all the output sections which
2607 // are not SHF_ALLOC, including the section table header.
2608
2609 // 9) Finalize the ELF file header.
2610
2611 // This function returns the size of the output file.
2612
2613 off_t
2614 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
2615                  Target* target, const Task* task)
2616 {
2617   target->finalize_sections(this, input_objects, symtab);
2618
2619   this->count_local_symbols(task, input_objects);
2620
2621   this->link_stabs_sections();
2622
2623   Output_segment* phdr_seg = NULL;
2624   if (!parameters->options().relocatable() && !parameters->doing_static_link())
2625     {
2626       // There was a dynamic object in the link.  We need to create
2627       // some information for the dynamic linker.
2628
2629       // Create the PT_PHDR segment which will hold the program
2630       // headers.
2631       if (!this->script_options_->saw_phdrs_clause())
2632         phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
2633
2634       // Create the dynamic symbol table, including the hash table.
2635       Output_section* dynstr;
2636       std::vector<Symbol*> dynamic_symbols;
2637       unsigned int local_dynamic_count;
2638       Versions versions(*this->script_options()->version_script_info(),
2639                         &this->dynpool_);
2640       this->create_dynamic_symtab(input_objects, symtab, &dynstr,
2641                                   &local_dynamic_count, &dynamic_symbols,
2642                                   &versions);
2643
2644       // Create the .interp section to hold the name of the
2645       // interpreter, and put it in a PT_INTERP segment.  Don't do it
2646       // if we saw a .interp section in an input file.
2647       if ((!parameters->options().shared()
2648            || parameters->options().dynamic_linker() != NULL)
2649           && this->interp_segment_ == NULL)
2650         this->create_interp(target);
2651
2652       // Finish the .dynamic section to hold the dynamic data, and put
2653       // it in a PT_DYNAMIC segment.
2654       this->finish_dynamic_section(input_objects, symtab);
2655
2656       // We should have added everything we need to the dynamic string
2657       // table.
2658       this->dynpool_.set_string_offsets();
2659
2660       // Create the version sections.  We can't do this until the
2661       // dynamic string table is complete.
2662       this->create_version_sections(&versions, symtab, local_dynamic_count,
2663                                     dynamic_symbols, dynstr);
2664
2665       // Set the size of the _DYNAMIC symbol.  We can't do this until
2666       // after we call create_version_sections.
2667       this->set_dynamic_symbol_size(symtab);
2668     }
2669
2670   // Create segment headers.
2671   Output_segment_headers* segment_headers =
2672     (parameters->options().relocatable()
2673      ? NULL
2674      : new Output_segment_headers(this->segment_list_));
2675
2676   // Lay out the file header.
2677   Output_file_header* file_header = new Output_file_header(target, symtab,
2678                                                            segment_headers);
2679
2680   this->special_output_list_.push_back(file_header);
2681   if (segment_headers != NULL)
2682     this->special_output_list_.push_back(segment_headers);
2683
2684   // Find approriate places for orphan output sections if we are using
2685   // a linker script.
2686   if (this->script_options_->saw_sections_clause())
2687     this->place_orphan_sections_in_script();
2688
2689   Output_segment* load_seg;
2690   off_t off;
2691   unsigned int shndx;
2692   int pass = 0;
2693
2694   // Take a snapshot of the section layout as needed.
2695   if (target->may_relax())
2696     this->prepare_for_relaxation();
2697
2698   // Run the relaxation loop to lay out sections.
2699   do
2700     {
2701       off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
2702                                        phdr_seg, segment_headers, file_header,
2703                                        &shndx);
2704       pass++;
2705     }
2706   while (target->may_relax()
2707          && target->relax(pass, input_objects, symtab, this, task));
2708
2709   // If there is a load segment that contains the file and program headers,
2710   // provide a symbol __ehdr_start pointing there.
2711   // A program can use this to examine itself robustly.
2712   if (load_seg != NULL)
2713     symtab->define_in_output_segment("__ehdr_start", NULL,
2714                                      Symbol_table::PREDEFINED, load_seg, 0, 0,
2715                                      elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
2716                                      elfcpp::STV_DEFAULT, 0,
2717                                      Symbol::SEGMENT_START, true);
2718
2719   // Set the file offsets of all the non-data sections we've seen so
2720   // far which don't have to wait for the input sections.  We need
2721   // this in order to finalize local symbols in non-allocated
2722   // sections.
2723   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
2724
2725   // Set the section indexes of all unallocated sections seen so far,
2726   // in case any of them are somehow referenced by a symbol.
2727   shndx = this->set_section_indexes(shndx);
2728
2729   // Create the symbol table sections.
2730   this->create_symtab_sections(input_objects, symtab, shndx, &off);
2731   if (!parameters->doing_static_link())
2732     this->assign_local_dynsym_offsets(input_objects);
2733
2734   // Process any symbol assignments from a linker script.  This must
2735   // be called after the symbol table has been finalized.
2736   this->script_options_->finalize_symbols(symtab, this);
2737
2738   // Create the incremental inputs sections.
2739   if (this->incremental_inputs_)
2740     {
2741       this->incremental_inputs_->finalize();
2742       this->create_incremental_info_sections(symtab);
2743     }
2744
2745   // Create the .shstrtab section.
2746   Output_section* shstrtab_section = this->create_shstrtab();
2747
2748   // Set the file offsets of the rest of the non-data sections which
2749   // don't have to wait for the input sections.
2750   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
2751
2752   // Now that all sections have been created, set the section indexes
2753   // for any sections which haven't been done yet.
2754   shndx = this->set_section_indexes(shndx);
2755
2756   // Create the section table header.
2757   this->create_shdrs(shstrtab_section, &off);
2758
2759   // If there are no sections which require postprocessing, we can
2760   // handle the section names now, and avoid a resize later.
2761   if (!this->any_postprocessing_sections_)
2762     {
2763       off = this->set_section_offsets(off,
2764                                       POSTPROCESSING_SECTIONS_PASS);
2765       off =
2766           this->set_section_offsets(off,
2767                                     STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2768     }
2769
2770   file_header->set_section_info(this->section_headers_, shstrtab_section);
2771
2772   // Now we know exactly where everything goes in the output file
2773   // (except for non-allocated sections which require postprocessing).
2774   Output_data::layout_complete();
2775
2776   this->output_file_size_ = off;
2777
2778   return off;
2779 }
2780
2781 // Create a note header following the format defined in the ELF ABI.
2782 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
2783 // of the section to create, DESCSZ is the size of the descriptor.
2784 // ALLOCATE is true if the section should be allocated in memory.
2785 // This returns the new note section.  It sets *TRAILING_PADDING to
2786 // the number of trailing zero bytes required.
2787
2788 Output_section*
2789 Layout::create_note(const char* name, int note_type,
2790                     const char* section_name, size_t descsz,
2791                     bool allocate, size_t* trailing_padding)
2792 {
2793   // Authorities all agree that the values in a .note field should
2794   // be aligned on 4-byte boundaries for 32-bit binaries.  However,
2795   // they differ on what the alignment is for 64-bit binaries.
2796   // The GABI says unambiguously they take 8-byte alignment:
2797   //    http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
2798   // Other documentation says alignment should always be 4 bytes:
2799   //    http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
2800   // GNU ld and GNU readelf both support the latter (at least as of
2801   // version 2.16.91), and glibc always generates the latter for
2802   // .note.ABI-tag (as of version 1.6), so that's the one we go with
2803   // here.
2804 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION   // This is not defined by default.
2805   const int size = parameters->target().get_size();
2806 #else
2807   const int size = 32;
2808 #endif
2809
2810   // The contents of the .note section.
2811   size_t namesz = strlen(name) + 1;
2812   size_t aligned_namesz = align_address(namesz, size / 8);
2813   size_t aligned_descsz = align_address(descsz, size / 8);
2814
2815   size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
2816
2817   unsigned char* buffer = new unsigned char[notehdrsz];
2818   memset(buffer, 0, notehdrsz);
2819
2820   bool is_big_endian = parameters->target().is_big_endian();
2821
2822   if (size == 32)
2823     {
2824       if (!is_big_endian)
2825         {
2826           elfcpp::Swap<32, false>::writeval(buffer, namesz);
2827           elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
2828           elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
2829         }
2830       else
2831         {
2832           elfcpp::Swap<32, true>::writeval(buffer, namesz);
2833           elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
2834           elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
2835         }
2836     }
2837   else if (size == 64)
2838     {
2839       if (!is_big_endian)
2840         {
2841           elfcpp::Swap<64, false>::writeval(buffer, namesz);
2842           elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
2843           elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
2844         }
2845       else
2846         {
2847           elfcpp::Swap<64, true>::writeval(buffer, namesz);
2848           elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
2849           elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
2850         }
2851     }
2852   else
2853     gold_unreachable();
2854
2855   memcpy(buffer + 3 * (size / 8), name, namesz);
2856
2857   elfcpp::Elf_Xword flags = 0;
2858   Output_section_order order = ORDER_INVALID;
2859   if (allocate)
2860     {
2861       flags = elfcpp::SHF_ALLOC;
2862       order = ORDER_RO_NOTE;
2863     }
2864   Output_section* os = this->choose_output_section(NULL, section_name,
2865                                                    elfcpp::SHT_NOTE,
2866                                                    flags, false, order, false);
2867   if (os == NULL)
2868     return NULL;
2869
2870   Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
2871                                                            size / 8,
2872                                                            "** note header");
2873   os->add_output_section_data(posd);
2874
2875   *trailing_padding = aligned_descsz - descsz;
2876
2877   return os;
2878 }
2879
2880 // For an executable or shared library, create a note to record the
2881 // version of gold used to create the binary.
2882
2883 void
2884 Layout::create_gold_note()
2885 {
2886   if (parameters->options().relocatable()
2887       || parameters->incremental_update())
2888     return;
2889
2890   std::string desc = std::string("gold ") + gold::get_version_string();
2891
2892   size_t trailing_padding;
2893   Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
2894                                          ".note.gnu.gold-version", desc.size(),
2895                                          false, &trailing_padding);
2896   if (os == NULL)
2897     return;
2898
2899   Output_section_data* posd = new Output_data_const(desc, 4);
2900   os->add_output_section_data(posd);
2901
2902   if (trailing_padding > 0)
2903     {
2904       posd = new Output_data_zero_fill(trailing_padding, 0);
2905       os->add_output_section_data(posd);
2906     }
2907 }
2908
2909 // Record whether the stack should be executable.  This can be set
2910 // from the command line using the -z execstack or -z noexecstack
2911 // options.  Otherwise, if any input file has a .note.GNU-stack
2912 // section with the SHF_EXECINSTR flag set, the stack should be
2913 // executable.  Otherwise, if at least one input file a
2914 // .note.GNU-stack section, and some input file has no .note.GNU-stack
2915 // section, we use the target default for whether the stack should be
2916 // executable.  Otherwise, we don't generate a stack note.  When
2917 // generating a object file, we create a .note.GNU-stack section with
2918 // the appropriate marking.  When generating an executable or shared
2919 // library, we create a PT_GNU_STACK segment.
2920
2921 void
2922 Layout::create_executable_stack_info()
2923 {
2924   bool is_stack_executable;
2925   if (parameters->options().is_execstack_set())
2926     is_stack_executable = parameters->options().is_stack_executable();
2927   else if (!this->input_with_gnu_stack_note_)
2928     return;
2929   else
2930     {
2931       if (this->input_requires_executable_stack_)
2932         is_stack_executable = true;
2933       else if (this->input_without_gnu_stack_note_)
2934         is_stack_executable =
2935           parameters->target().is_default_stack_executable();
2936       else
2937         is_stack_executable = false;
2938     }
2939
2940   if (parameters->options().relocatable())
2941     {
2942       const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
2943       elfcpp::Elf_Xword flags = 0;
2944       if (is_stack_executable)
2945         flags |= elfcpp::SHF_EXECINSTR;
2946       this->make_output_section(name, elfcpp::SHT_PROGBITS, flags,
2947                                 ORDER_INVALID, false);
2948     }
2949   else
2950     {
2951       if (this->script_options_->saw_phdrs_clause())
2952         return;
2953       int flags = elfcpp::PF_R | elfcpp::PF_W;
2954       if (is_stack_executable)
2955         flags |= elfcpp::PF_X;
2956       this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
2957     }
2958 }
2959
2960 // If --build-id was used, set up the build ID note.
2961
2962 void
2963 Layout::create_build_id()
2964 {
2965   if (!parameters->options().user_set_build_id())
2966     return;
2967
2968   const char* style = parameters->options().build_id();
2969   if (strcmp(style, "none") == 0)
2970     return;
2971
2972   // Set DESCSZ to the size of the note descriptor.  When possible,
2973   // set DESC to the note descriptor contents.
2974   size_t descsz;
2975   std::string desc;
2976   if (strcmp(style, "md5") == 0)
2977     descsz = 128 / 8;
2978   else if ((strcmp(style, "sha1") == 0) || (strcmp(style, "tree") == 0))
2979     descsz = 160 / 8;
2980   else if (strcmp(style, "uuid") == 0)
2981     {
2982       const size_t uuidsz = 128 / 8;
2983
2984       char buffer[uuidsz];
2985       memset(buffer, 0, uuidsz);
2986
2987       int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
2988       if (descriptor < 0)
2989         gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
2990                    strerror(errno));
2991       else
2992         {
2993           ssize_t got = ::read(descriptor, buffer, uuidsz);
2994           release_descriptor(descriptor, true);
2995           if (got < 0)
2996             gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
2997           else if (static_cast<size_t>(got) != uuidsz)
2998             gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
2999                        uuidsz, got);
3000         }
3001
3002       desc.assign(buffer, uuidsz);
3003       descsz = uuidsz;
3004     }
3005   else if (strncmp(style, "0x", 2) == 0)
3006     {
3007       hex_init();
3008       const char* p = style + 2;
3009       while (*p != '\0')
3010         {
3011           if (hex_p(p[0]) && hex_p(p[1]))
3012             {
3013               char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
3014               desc += c;
3015               p += 2;
3016             }
3017           else if (*p == '-' || *p == ':')
3018             ++p;
3019           else
3020             gold_fatal(_("--build-id argument '%s' not a valid hex number"),
3021                        style);
3022         }
3023       descsz = desc.size();
3024     }
3025   else
3026     gold_fatal(_("unrecognized --build-id argument '%s'"), style);
3027
3028   // Create the note.
3029   size_t trailing_padding;
3030   Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
3031                                          ".note.gnu.build-id", descsz, true,
3032                                          &trailing_padding);
3033   if (os == NULL)
3034     return;
3035
3036   if (!desc.empty())
3037     {
3038       // We know the value already, so we fill it in now.
3039       gold_assert(desc.size() == descsz);
3040
3041       Output_section_data* posd = new Output_data_const(desc, 4);
3042       os->add_output_section_data(posd);
3043
3044       if (trailing_padding != 0)
3045         {
3046           posd = new Output_data_zero_fill(trailing_padding, 0);
3047           os->add_output_section_data(posd);
3048         }
3049     }
3050   else
3051     {
3052       // We need to compute a checksum after we have completed the
3053       // link.
3054       gold_assert(trailing_padding == 0);
3055       this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
3056       os->add_output_section_data(this->build_id_note_);
3057     }
3058 }
3059
3060 // If we have both .stabXX and .stabXXstr sections, then the sh_link
3061 // field of the former should point to the latter.  I'm not sure who
3062 // started this, but the GNU linker does it, and some tools depend
3063 // upon it.
3064
3065 void
3066 Layout::link_stabs_sections()
3067 {
3068   if (!this->have_stabstr_section_)
3069     return;
3070
3071   for (Section_list::iterator p = this->section_list_.begin();
3072        p != this->section_list_.end();
3073        ++p)
3074     {
3075       if ((*p)->type() != elfcpp::SHT_STRTAB)
3076         continue;
3077
3078       const char* name = (*p)->name();
3079       if (strncmp(name, ".stab", 5) != 0)
3080         continue;
3081
3082       size_t len = strlen(name);
3083       if (strcmp(name + len - 3, "str") != 0)
3084         continue;
3085
3086       std::string stab_name(name, len - 3);
3087       Output_section* stab_sec;
3088       stab_sec = this->find_output_section(stab_name.c_str());
3089       if (stab_sec != NULL)
3090         stab_sec->set_link_section(*p);
3091     }
3092 }
3093
3094 // Create .gnu_incremental_inputs and related sections needed
3095 // for the next run of incremental linking to check what has changed.
3096
3097 void
3098 Layout::create_incremental_info_sections(Symbol_table* symtab)
3099 {
3100   Incremental_inputs* incr = this->incremental_inputs_;
3101
3102   gold_assert(incr != NULL);
3103
3104   // Create the .gnu_incremental_inputs, _symtab, and _relocs input sections.
3105   incr->create_data_sections(symtab);
3106
3107   // Add the .gnu_incremental_inputs section.
3108   const char* incremental_inputs_name =
3109     this->namepool_.add(".gnu_incremental_inputs", false, NULL);
3110   Output_section* incremental_inputs_os =
3111     this->make_output_section(incremental_inputs_name,
3112                               elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
3113                               ORDER_INVALID, false);
3114   incremental_inputs_os->add_output_section_data(incr->inputs_section());
3115
3116   // Add the .gnu_incremental_symtab section.
3117   const char* incremental_symtab_name =
3118     this->namepool_.add(".gnu_incremental_symtab", false, NULL);
3119   Output_section* incremental_symtab_os =
3120     this->make_output_section(incremental_symtab_name,
3121                               elfcpp::SHT_GNU_INCREMENTAL_SYMTAB, 0,
3122                               ORDER_INVALID, false);
3123   incremental_symtab_os->add_output_section_data(incr->symtab_section());
3124   incremental_symtab_os->set_entsize(4);
3125
3126   // Add the .gnu_incremental_relocs section.
3127   const char* incremental_relocs_name =
3128     this->namepool_.add(".gnu_incremental_relocs", false, NULL);
3129   Output_section* incremental_relocs_os =
3130     this->make_output_section(incremental_relocs_name,
3131                               elfcpp::SHT_GNU_INCREMENTAL_RELOCS, 0,
3132                               ORDER_INVALID, false);
3133   incremental_relocs_os->add_output_section_data(incr->relocs_section());
3134   incremental_relocs_os->set_entsize(incr->relocs_entsize());
3135
3136   // Add the .gnu_incremental_got_plt section.
3137   const char* incremental_got_plt_name =
3138     this->namepool_.add(".gnu_incremental_got_plt", false, NULL);
3139   Output_section* incremental_got_plt_os =
3140     this->make_output_section(incremental_got_plt_name,
3141                               elfcpp::SHT_GNU_INCREMENTAL_GOT_PLT, 0,
3142                               ORDER_INVALID, false);
3143   incremental_got_plt_os->add_output_section_data(incr->got_plt_section());
3144
3145   // Add the .gnu_incremental_strtab section.
3146   const char* incremental_strtab_name =
3147     this->namepool_.add(".gnu_incremental_strtab", false, NULL);
3148   Output_section* incremental_strtab_os = this->make_output_section(incremental_strtab_name,
3149                                                         elfcpp::SHT_STRTAB, 0,
3150                                                         ORDER_INVALID, false);
3151   Output_data_strtab* strtab_data =
3152       new Output_data_strtab(incr->get_stringpool());
3153   incremental_strtab_os->add_output_section_data(strtab_data);
3154
3155   incremental_inputs_os->set_after_input_sections();
3156   incremental_symtab_os->set_after_input_sections();
3157   incremental_relocs_os->set_after_input_sections();
3158   incremental_got_plt_os->set_after_input_sections();
3159
3160   incremental_inputs_os->set_link_section(incremental_strtab_os);
3161   incremental_symtab_os->set_link_section(incremental_inputs_os);
3162   incremental_relocs_os->set_link_section(incremental_inputs_os);
3163   incremental_got_plt_os->set_link_section(incremental_inputs_os);
3164 }
3165
3166 // Return whether SEG1 should be before SEG2 in the output file.  This
3167 // is based entirely on the segment type and flags.  When this is
3168 // called the segment addresses have normally not yet been set.
3169
3170 bool
3171 Layout::segment_precedes(const Output_segment* seg1,
3172                          const Output_segment* seg2)
3173 {
3174   elfcpp::Elf_Word type1 = seg1->type();
3175   elfcpp::Elf_Word type2 = seg2->type();
3176
3177   // The single PT_PHDR segment is required to precede any loadable
3178   // segment.  We simply make it always first.
3179   if (type1 == elfcpp::PT_PHDR)
3180     {
3181       gold_assert(type2 != elfcpp::PT_PHDR);
3182       return true;
3183     }
3184   if (type2 == elfcpp::PT_PHDR)
3185     return false;
3186
3187   // The single PT_INTERP segment is required to precede any loadable
3188   // segment.  We simply make it always second.
3189   if (type1 == elfcpp::PT_INTERP)
3190     {
3191       gold_assert(type2 != elfcpp::PT_INTERP);
3192       return true;
3193     }
3194   if (type2 == elfcpp::PT_INTERP)
3195     return false;
3196
3197   // We then put PT_LOAD segments before any other segments.
3198   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
3199     return true;
3200   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
3201     return false;
3202
3203   // We put the PT_TLS segment last except for the PT_GNU_RELRO
3204   // segment, because that is where the dynamic linker expects to find
3205   // it (this is just for efficiency; other positions would also work
3206   // correctly).
3207   if (type1 == elfcpp::PT_TLS
3208       && type2 != elfcpp::PT_TLS
3209       && type2 != elfcpp::PT_GNU_RELRO)
3210     return false;
3211   if (type2 == elfcpp::PT_TLS
3212       && type1 != elfcpp::PT_TLS
3213       && type1 != elfcpp::PT_GNU_RELRO)
3214     return true;
3215
3216   // We put the PT_GNU_RELRO segment last, because that is where the
3217   // dynamic linker expects to find it (as with PT_TLS, this is just
3218   // for efficiency).
3219   if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
3220     return false;
3221   if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
3222     return true;
3223
3224   const elfcpp::Elf_Word flags1 = seg1->flags();
3225   const elfcpp::Elf_Word flags2 = seg2->flags();
3226
3227   // The order of non-PT_LOAD segments is unimportant.  We simply sort
3228   // by the numeric segment type and flags values.  There should not
3229   // be more than one segment with the same type and flags, except
3230   // when a linker script specifies such.
3231   if (type1 != elfcpp::PT_LOAD)
3232     {
3233       if (type1 != type2)
3234         return type1 < type2;
3235       gold_assert(flags1 != flags2
3236                   || this->script_options_->saw_phdrs_clause());
3237       return flags1 < flags2;
3238     }
3239
3240   // If the addresses are set already, sort by load address.
3241   if (seg1->are_addresses_set())
3242     {
3243       if (!seg2->are_addresses_set())
3244         return true;
3245
3246       unsigned int section_count1 = seg1->output_section_count();
3247       unsigned int section_count2 = seg2->output_section_count();
3248       if (section_count1 == 0 && section_count2 > 0)
3249         return true;
3250       if (section_count1 > 0 && section_count2 == 0)
3251         return false;
3252
3253       uint64_t paddr1 = (seg1->are_addresses_set()
3254                          ? seg1->paddr()
3255                          : seg1->first_section_load_address());
3256       uint64_t paddr2 = (seg2->are_addresses_set()
3257                          ? seg2->paddr()
3258                          : seg2->first_section_load_address());
3259
3260       if (paddr1 != paddr2)
3261         return paddr1 < paddr2;
3262     }
3263   else if (seg2->are_addresses_set())
3264     return false;
3265
3266   // A segment which holds large data comes after a segment which does
3267   // not hold large data.
3268   if (seg1->is_large_data_segment())
3269     {
3270       if (!seg2->is_large_data_segment())
3271         return false;
3272     }
3273   else if (seg2->is_large_data_segment())
3274     return true;
3275
3276   // Otherwise, we sort PT_LOAD segments based on the flags.  Readonly
3277   // segments come before writable segments.  Then writable segments
3278   // with data come before writable segments without data.  Then
3279   // executable segments come before non-executable segments.  Then
3280   // the unlikely case of a non-readable segment comes before the
3281   // normal case of a readable segment.  If there are multiple
3282   // segments with the same type and flags, we require that the
3283   // address be set, and we sort by virtual address and then physical
3284   // address.
3285   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
3286     return (flags1 & elfcpp::PF_W) == 0;
3287   if ((flags1 & elfcpp::PF_W) != 0
3288       && seg1->has_any_data_sections() != seg2->has_any_data_sections())
3289     return seg1->has_any_data_sections();
3290   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
3291     return (flags1 & elfcpp::PF_X) != 0;
3292   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
3293     return (flags1 & elfcpp::PF_R) == 0;
3294
3295   // We shouldn't get here--we shouldn't create segments which we
3296   // can't distinguish.  Unless of course we are using a weird linker
3297   // script or overlapping --section-start options.  We could also get
3298   // here if plugins want unique segments for subsets of sections.
3299   gold_assert(this->script_options_->saw_phdrs_clause()
3300               || parameters->options().any_section_start()
3301               || this->is_unique_segment_for_sections_specified());
3302   return false;
3303 }
3304
3305 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
3306
3307 static off_t
3308 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
3309 {
3310   uint64_t unsigned_off = off;
3311   uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
3312                           | (addr & (abi_pagesize - 1)));
3313   if (aligned_off < unsigned_off)
3314     aligned_off += abi_pagesize;
3315   return aligned_off;
3316 }
3317
3318 // Set the file offsets of all the segments, and all the sections they
3319 // contain.  They have all been created.  LOAD_SEG must be be laid out
3320 // first.  Return the offset of the data to follow.
3321
3322 off_t
3323 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
3324                             unsigned int* pshndx)
3325 {
3326   // Sort them into the final order.  We use a stable sort so that we
3327   // don't randomize the order of indistinguishable segments created
3328   // by linker scripts.
3329   std::stable_sort(this->segment_list_.begin(), this->segment_list_.end(),
3330                    Layout::Compare_segments(this));
3331
3332   // Find the PT_LOAD segments, and set their addresses and offsets
3333   // and their section's addresses and offsets.
3334   uint64_t start_addr;
3335   if (parameters->options().user_set_Ttext())
3336     start_addr = parameters->options().Ttext();
3337   else if (parameters->options().output_is_position_independent())
3338     start_addr = 0;
3339   else
3340     start_addr = target->default_text_segment_address();
3341
3342   uint64_t addr = start_addr;
3343   off_t off = 0;
3344
3345   // If LOAD_SEG is NULL, then the file header and segment headers
3346   // will not be loadable.  But they still need to be at offset 0 in
3347   // the file.  Set their offsets now.
3348   if (load_seg == NULL)
3349     {
3350       for (Data_list::iterator p = this->special_output_list_.begin();
3351            p != this->special_output_list_.end();
3352            ++p)
3353         {
3354           off = align_address(off, (*p)->addralign());
3355           (*p)->set_address_and_file_offset(0, off);
3356           off += (*p)->data_size();
3357         }
3358     }
3359
3360   unsigned int increase_relro = this->increase_relro_;
3361   if (this->script_options_->saw_sections_clause())
3362     increase_relro = 0;
3363
3364   const bool check_sections = parameters->options().check_sections();
3365   Output_segment* last_load_segment = NULL;
3366
3367   unsigned int shndx_begin = *pshndx;
3368   unsigned int shndx_load_seg = *pshndx;
3369
3370   for (Segment_list::iterator p = this->segment_list_.begin();
3371        p != this->segment_list_.end();
3372        ++p)
3373     {
3374       if ((*p)->type() == elfcpp::PT_LOAD)
3375         {
3376           if (target->isolate_execinstr())
3377             {
3378               // When we hit the segment that should contain the
3379               // file headers, reset the file offset so we place
3380               // it and subsequent segments appropriately.
3381               // We'll fix up the preceding segments below.
3382               if (load_seg == *p)
3383                 {
3384                   if (off == 0)
3385                     load_seg = NULL;
3386                   else
3387                     {
3388                       off = 0;
3389                       shndx_load_seg = *pshndx;
3390                     }
3391                 }
3392             }
3393           else
3394             {
3395               // Verify that the file headers fall into the first segment.
3396               if (load_seg != NULL && load_seg != *p)
3397                 gold_unreachable();
3398               load_seg = NULL;
3399             }
3400
3401           bool are_addresses_set = (*p)->are_addresses_set();
3402           if (are_addresses_set)
3403             {
3404               // When it comes to setting file offsets, we care about
3405               // the physical address.
3406               addr = (*p)->paddr();
3407             }
3408           else if (parameters->options().user_set_Ttext()
3409                    && (parameters->options().omagic()
3410                        || ((*p)->flags() & elfcpp::PF_W) == 0))
3411             {
3412               are_addresses_set = true;
3413             }
3414           else if (parameters->options().user_set_Tdata()
3415                    && ((*p)->flags() & elfcpp::PF_W) != 0
3416                    && (!parameters->options().user_set_Tbss()
3417                        || (*p)->has_any_data_sections()))
3418             {
3419               addr = parameters->options().Tdata();
3420               are_addresses_set = true;
3421             }
3422           else if (parameters->options().user_set_Tbss()
3423                    && ((*p)->flags() & elfcpp::PF_W) != 0
3424                    && !(*p)->has_any_data_sections())
3425             {
3426               addr = parameters->options().Tbss();
3427               are_addresses_set = true;
3428             }
3429
3430           uint64_t orig_addr = addr;
3431           uint64_t orig_off = off;
3432
3433           uint64_t aligned_addr = 0;
3434           uint64_t abi_pagesize = target->abi_pagesize();
3435           uint64_t common_pagesize = target->common_pagesize();
3436
3437           if (!parameters->options().nmagic()
3438               && !parameters->options().omagic())
3439             (*p)->set_minimum_p_align(abi_pagesize);
3440
3441           if (!are_addresses_set)
3442             {
3443               // Skip the address forward one page, maintaining the same
3444               // position within the page.  This lets us store both segments
3445               // overlapping on a single page in the file, but the loader will
3446               // put them on different pages in memory. We will revisit this
3447               // decision once we know the size of the segment.
3448
3449               addr = align_address(addr, (*p)->maximum_alignment());
3450               aligned_addr = addr;
3451
3452               if (load_seg == *p)
3453                 {
3454                   // This is the segment that will contain the file
3455                   // headers, so its offset will have to be exactly zero.
3456                   gold_assert(orig_off == 0);
3457
3458                   // If the target wants a fixed minimum distance from the
3459                   // text segment to the read-only segment, move up now.
3460                   uint64_t min_addr = start_addr + target->rosegment_gap();
3461                   if (addr < min_addr)
3462                     addr = min_addr;
3463
3464                   // But this is not the first segment!  To make its
3465                   // address congruent with its offset, that address better
3466                   // be aligned to the ABI-mandated page size.
3467                   addr = align_address(addr, abi_pagesize);
3468                   aligned_addr = addr;
3469                 }
3470               else
3471                 {
3472                   if ((addr & (abi_pagesize - 1)) != 0)
3473                     addr = addr + abi_pagesize;
3474
3475                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
3476                 }
3477             }
3478
3479           if (!parameters->options().nmagic()
3480               && !parameters->options().omagic())
3481             off = align_file_offset(off, addr, abi_pagesize);
3482           else
3483             {
3484               // This is -N or -n with a section script which prevents
3485               // us from using a load segment.  We need to ensure that
3486               // the file offset is aligned to the alignment of the
3487               // segment.  This is because the linker script
3488               // implicitly assumed a zero offset.  If we don't align
3489               // here, then the alignment of the sections in the
3490               // linker script may not match the alignment of the
3491               // sections in the set_section_addresses call below,
3492               // causing an error about dot moving backward.
3493               off = align_address(off, (*p)->maximum_alignment());
3494             }
3495
3496           unsigned int shndx_hold = *pshndx;
3497           bool has_relro = false;
3498           uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
3499                                                           &increase_relro,
3500                                                           &has_relro,
3501                                                           &off, pshndx);
3502
3503           // Now that we know the size of this segment, we may be able
3504           // to save a page in memory, at the cost of wasting some
3505           // file space, by instead aligning to the start of a new
3506           // page.  Here we use the real machine page size rather than
3507           // the ABI mandated page size.  If the segment has been
3508           // aligned so that the relro data ends at a page boundary,
3509           // we do not try to realign it.
3510
3511           if (!are_addresses_set
3512               && !has_relro
3513               && aligned_addr != addr
3514               && !parameters->incremental())
3515             {
3516               uint64_t first_off = (common_pagesize
3517                                     - (aligned_addr
3518                                        & (common_pagesize - 1)));
3519               uint64_t last_off = new_addr & (common_pagesize - 1);
3520               if (first_off > 0
3521                   && last_off > 0
3522                   && ((aligned_addr & ~ (common_pagesize - 1))
3523                       != (new_addr & ~ (common_pagesize - 1)))
3524                   && first_off + last_off <= common_pagesize)
3525                 {
3526                   *pshndx = shndx_hold;
3527                   addr = align_address(aligned_addr, common_pagesize);
3528                   addr = align_address(addr, (*p)->maximum_alignment());
3529                   if ((addr & (abi_pagesize - 1)) != 0)
3530                     addr = addr + abi_pagesize;
3531                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
3532                   off = align_file_offset(off, addr, abi_pagesize);
3533
3534                   increase_relro = this->increase_relro_;
3535                   if (this->script_options_->saw_sections_clause())
3536                     increase_relro = 0;
3537                   has_relro = false;
3538
3539                   new_addr = (*p)->set_section_addresses(this, true, addr,
3540                                                          &increase_relro,
3541                                                          &has_relro,
3542                                                          &off, pshndx);
3543                 }
3544             }
3545
3546           addr = new_addr;
3547
3548           // Implement --check-sections.  We know that the segments
3549           // are sorted by LMA.
3550           if (check_sections && last_load_segment != NULL)
3551             {
3552               gold_assert(last_load_segment->paddr() <= (*p)->paddr());
3553               if (last_load_segment->paddr() + last_load_segment->memsz()
3554                   > (*p)->paddr())
3555                 {
3556                   unsigned long long lb1 = last_load_segment->paddr();
3557                   unsigned long long le1 = lb1 + last_load_segment->memsz();
3558                   unsigned long long lb2 = (*p)->paddr();
3559                   unsigned long long le2 = lb2 + (*p)->memsz();
3560                   gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
3561                                "[0x%llx -> 0x%llx]"),
3562                              lb1, le1, lb2, le2);
3563                 }
3564             }
3565           last_load_segment = *p;
3566         }
3567     }
3568
3569   if (load_seg != NULL && target->isolate_execinstr())
3570     {
3571       // Process the early segments again, setting their file offsets
3572       // so they land after the segments starting at LOAD_SEG.
3573       off = align_file_offset(off, 0, target->abi_pagesize());
3574
3575       for (Segment_list::iterator p = this->segment_list_.begin();
3576            *p != load_seg;
3577            ++p)
3578         {
3579           if ((*p)->type() == elfcpp::PT_LOAD)
3580             {
3581               // We repeat the whole job of assigning addresses and
3582               // offsets, but we really only want to change the offsets and
3583               // must ensure that the addresses all come out the same as
3584               // they did the first time through.
3585               bool has_relro = false;
3586               const uint64_t old_addr = (*p)->vaddr();
3587               const uint64_t old_end = old_addr + (*p)->memsz();
3588               uint64_t new_addr = (*p)->set_section_addresses(this, true,
3589                                                               old_addr,
3590                                                               &increase_relro,
3591                                                               &has_relro,
3592                                                               &off,
3593                                                               &shndx_begin);
3594               gold_assert(new_addr == old_end);
3595             }
3596         }
3597
3598       gold_assert(shndx_begin == shndx_load_seg);
3599     }
3600
3601   // Handle the non-PT_LOAD segments, setting their offsets from their
3602   // section's offsets.
3603   for (Segment_list::iterator p = this->segment_list_.begin();
3604        p != this->segment_list_.end();
3605        ++p)
3606     {
3607       if ((*p)->type() != elfcpp::PT_LOAD)
3608         (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
3609                          ? increase_relro
3610                          : 0);
3611     }
3612
3613   // Set the TLS offsets for each section in the PT_TLS segment.
3614   if (this->tls_segment_ != NULL)
3615     this->tls_segment_->set_tls_offsets();
3616
3617   return off;
3618 }
3619
3620 // Set the offsets of all the allocated sections when doing a
3621 // relocatable link.  This does the same jobs as set_segment_offsets,
3622 // only for a relocatable link.
3623
3624 off_t
3625 Layout::set_relocatable_section_offsets(Output_data* file_header,
3626                                         unsigned int* pshndx)
3627 {
3628   off_t off = 0;
3629
3630   file_header->set_address_and_file_offset(0, 0);
3631   off += file_header->data_size();
3632
3633   for (Section_list::iterator p = this->section_list_.begin();
3634        p != this->section_list_.end();
3635        ++p)
3636     {
3637       // We skip unallocated sections here, except that group sections
3638       // have to come first.
3639       if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
3640           && (*p)->type() != elfcpp::SHT_GROUP)
3641         continue;
3642
3643       off = align_address(off, (*p)->addralign());
3644
3645       // The linker script might have set the address.
3646       if (!(*p)->is_address_valid())
3647         (*p)->set_address(0);
3648       (*p)->set_file_offset(off);
3649       (*p)->finalize_data_size();
3650       if ((*p)->type() != elfcpp::SHT_NOBITS)
3651         off += (*p)->data_size();
3652
3653       (*p)->set_out_shndx(*pshndx);
3654       ++*pshndx;
3655     }
3656
3657   return off;
3658 }
3659
3660 // Set the file offset of all the sections not associated with a
3661 // segment.
3662
3663 off_t
3664 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
3665 {
3666   off_t startoff = off;
3667   off_t maxoff = off;
3668
3669   for (Section_list::iterator p = this->unattached_section_list_.begin();
3670        p != this->unattached_section_list_.end();
3671        ++p)
3672     {
3673       // The symtab section is handled in create_symtab_sections.
3674       if (*p == this->symtab_section_)
3675         continue;
3676
3677       // If we've already set the data size, don't set it again.
3678       if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
3679         continue;
3680
3681       if (pass == BEFORE_INPUT_SECTIONS_PASS
3682           && (*p)->requires_postprocessing())
3683         {
3684           (*p)->create_postprocessing_buffer();
3685           this->any_postprocessing_sections_ = true;
3686         }
3687
3688       if (pass == BEFORE_INPUT_SECTIONS_PASS
3689           && (*p)->after_input_sections())
3690         continue;
3691       else if (pass == POSTPROCESSING_SECTIONS_PASS
3692                && (!(*p)->after_input_sections()
3693                    || (*p)->type() == elfcpp::SHT_STRTAB))
3694         continue;
3695       else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
3696                && (!(*p)->after_input_sections()
3697                    || (*p)->type() != elfcpp::SHT_STRTAB))
3698         continue;
3699
3700       if (!parameters->incremental_update())
3701         {
3702           off = align_address(off, (*p)->addralign());
3703           (*p)->set_file_offset(off);
3704           (*p)->finalize_data_size();
3705         }
3706       else
3707         {
3708           // Incremental update: allocate file space from free list.
3709           (*p)->pre_finalize_data_size();
3710           off_t current_size = (*p)->current_data_size();
3711           off = this->allocate(current_size, (*p)->addralign(), startoff);
3712           if (off == -1)
3713             {
3714               if (is_debugging_enabled(DEBUG_INCREMENTAL))
3715                 this->free_list_.dump();
3716               gold_assert((*p)->output_section() != NULL);
3717               gold_fallback(_("out of patch space for section %s; "
3718                               "relink with --incremental-full"),
3719                             (*p)->output_section()->name());
3720             }
3721           (*p)->set_file_offset(off);
3722           (*p)->finalize_data_size();
3723           if ((*p)->data_size() > current_size)
3724             {
3725               gold_assert((*p)->output_section() != NULL);
3726               gold_fallback(_("%s: section changed size; "
3727                               "relink with --incremental-full"),
3728                             (*p)->output_section()->name());
3729             }
3730           gold_debug(DEBUG_INCREMENTAL,
3731                      "set_section_offsets: %08lx %08lx %s",
3732                      static_cast<long>(off),
3733                      static_cast<long>((*p)->data_size()),
3734                      ((*p)->output_section() != NULL
3735                       ? (*p)->output_section()->name() : "(special)"));
3736         }
3737
3738       off += (*p)->data_size();
3739       if (off > maxoff)
3740         maxoff = off;
3741
3742       // At this point the name must be set.
3743       if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
3744         this->namepool_.add((*p)->name(), false, NULL);
3745     }
3746   return maxoff;
3747 }
3748
3749 // Set the section indexes of all the sections not associated with a
3750 // segment.
3751
3752 unsigned int
3753 Layout::set_section_indexes(unsigned int shndx)
3754 {
3755   for (Section_list::iterator p = this->unattached_section_list_.begin();
3756        p != this->unattached_section_list_.end();
3757        ++p)
3758     {
3759       if (!(*p)->has_out_shndx())
3760         {
3761           (*p)->set_out_shndx(shndx);
3762           ++shndx;
3763         }
3764     }
3765   return shndx;
3766 }
3767
3768 // Set the section addresses according to the linker script.  This is
3769 // only called when we see a SECTIONS clause.  This returns the
3770 // program segment which should hold the file header and segment
3771 // headers, if any.  It will return NULL if they should not be in a
3772 // segment.
3773
3774 Output_segment*
3775 Layout::set_section_addresses_from_script(Symbol_table* symtab)
3776 {
3777   Script_sections* ss = this->script_options_->script_sections();
3778   gold_assert(ss->saw_sections_clause());
3779   return this->script_options_->set_section_addresses(symtab, this);
3780 }
3781
3782 // Place the orphan sections in the linker script.
3783
3784 void
3785 Layout::place_orphan_sections_in_script()
3786 {
3787   Script_sections* ss = this->script_options_->script_sections();
3788   gold_assert(ss->saw_sections_clause());
3789
3790   // Place each orphaned output section in the script.
3791   for (Section_list::iterator p = this->section_list_.begin();
3792        p != this->section_list_.end();
3793        ++p)
3794     {
3795       if (!(*p)->found_in_sections_clause())
3796         ss->place_orphan(*p);
3797     }
3798 }
3799
3800 // Count the local symbols in the regular symbol table and the dynamic
3801 // symbol table, and build the respective string pools.
3802
3803 void
3804 Layout::count_local_symbols(const Task* task,
3805                             const Input_objects* input_objects)
3806 {
3807   // First, figure out an upper bound on the number of symbols we'll
3808   // be inserting into each pool.  This helps us create the pools with
3809   // the right size, to avoid unnecessary hashtable resizing.
3810   unsigned int symbol_count = 0;
3811   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3812        p != input_objects->relobj_end();
3813        ++p)
3814     symbol_count += (*p)->local_symbol_count();
3815
3816   // Go from "upper bound" to "estimate."  We overcount for two
3817   // reasons: we double-count symbols that occur in more than one
3818   // object file, and we count symbols that are dropped from the
3819   // output.  Add it all together and assume we overcount by 100%.
3820   symbol_count /= 2;
3821
3822   // We assume all symbols will go into both the sympool and dynpool.
3823   this->sympool_.reserve(symbol_count);
3824   this->dynpool_.reserve(symbol_count);
3825
3826   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3827        p != input_objects->relobj_end();
3828        ++p)
3829     {
3830       Task_lock_obj<Object> tlo(task, *p);
3831       (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
3832     }
3833 }
3834
3835 // Create the symbol table sections.  Here we also set the final
3836 // values of the symbols.  At this point all the loadable sections are
3837 // fully laid out.  SHNUM is the number of sections so far.
3838
3839 void
3840 Layout::create_symtab_sections(const Input_objects* input_objects,
3841                                Symbol_table* symtab,
3842                                unsigned int shnum,
3843                                off_t* poff)
3844 {
3845   int symsize;
3846   unsigned int align;
3847   if (parameters->target().get_size() == 32)
3848     {
3849       symsize = elfcpp::Elf_sizes<32>::sym_size;
3850       align = 4;
3851     }
3852   else if (parameters->target().get_size() == 64)
3853     {
3854       symsize = elfcpp::Elf_sizes<64>::sym_size;
3855       align = 8;
3856     }
3857   else
3858     gold_unreachable();
3859
3860   // Compute file offsets relative to the start of the symtab section.
3861   off_t off = 0;
3862
3863   // Save space for the dummy symbol at the start of the section.  We
3864   // never bother to write this out--it will just be left as zero.
3865   off += symsize;
3866   unsigned int local_symbol_index = 1;
3867
3868   // Add STT_SECTION symbols for each Output section which needs one.
3869   for (Section_list::iterator p = this->section_list_.begin();
3870        p != this->section_list_.end();
3871        ++p)
3872     {
3873       if (!(*p)->needs_symtab_index())
3874         (*p)->set_symtab_index(-1U);
3875       else
3876         {
3877           (*p)->set_symtab_index(local_symbol_index);
3878           ++local_symbol_index;
3879           off += symsize;
3880         }
3881     }
3882
3883   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3884        p != input_objects->relobj_end();
3885        ++p)
3886     {
3887       unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
3888                                                         off, symtab);
3889       off += (index - local_symbol_index) * symsize;
3890       local_symbol_index = index;
3891     }
3892
3893   unsigned int local_symcount = local_symbol_index;
3894   gold_assert(static_cast<off_t>(local_symcount * symsize) == off);
3895
3896   off_t dynoff;
3897   size_t dyn_global_index;
3898   size_t dyncount;
3899   if (this->dynsym_section_ == NULL)
3900     {
3901       dynoff = 0;
3902       dyn_global_index = 0;
3903       dyncount = 0;
3904     }
3905   else
3906     {
3907       dyn_global_index = this->dynsym_section_->info();
3908       off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
3909       dynoff = this->dynsym_section_->offset() + locsize;
3910       dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
3911       gold_assert(static_cast<off_t>(dyncount * symsize)
3912                   == this->dynsym_section_->data_size() - locsize);
3913     }
3914
3915   off_t global_off = off;
3916   off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
3917                          &this->sympool_, &local_symcount);
3918
3919   if (!parameters->options().strip_all())
3920     {
3921       this->sympool_.set_string_offsets();
3922
3923       const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
3924       Output_section* osymtab = this->make_output_section(symtab_name,
3925                                                           elfcpp::SHT_SYMTAB,
3926                                                           0, ORDER_INVALID,
3927                                                           false);
3928       this->symtab_section_ = osymtab;
3929
3930       Output_section_data* pos = new Output_data_fixed_space(off, align,
3931                                                              "** symtab");
3932       osymtab->add_output_section_data(pos);
3933
3934       // We generate a .symtab_shndx section if we have more than
3935       // SHN_LORESERVE sections.  Technically it is possible that we
3936       // don't need one, because it is possible that there are no
3937       // symbols in any of sections with indexes larger than
3938       // SHN_LORESERVE.  That is probably unusual, though, and it is
3939       // easier to always create one than to compute section indexes
3940       // twice (once here, once when writing out the symbols).
3941       if (shnum >= elfcpp::SHN_LORESERVE)
3942         {
3943           const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
3944                                                                false, NULL);
3945           Output_section* osymtab_xindex =
3946             this->make_output_section(symtab_xindex_name,
3947                                       elfcpp::SHT_SYMTAB_SHNDX, 0,
3948                                       ORDER_INVALID, false);
3949
3950           size_t symcount = off / symsize;
3951           this->symtab_xindex_ = new Output_symtab_xindex(symcount);
3952
3953           osymtab_xindex->add_output_section_data(this->symtab_xindex_);
3954
3955           osymtab_xindex->set_link_section(osymtab);
3956           osymtab_xindex->set_addralign(4);
3957           osymtab_xindex->set_entsize(4);
3958
3959           osymtab_xindex->set_after_input_sections();
3960
3961           // This tells the driver code to wait until the symbol table
3962           // has written out before writing out the postprocessing
3963           // sections, including the .symtab_shndx section.
3964           this->any_postprocessing_sections_ = true;
3965         }
3966
3967       const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
3968       Output_section* ostrtab = this->make_output_section(strtab_name,
3969                                                           elfcpp::SHT_STRTAB,
3970                                                           0, ORDER_INVALID,
3971                                                           false);
3972
3973       Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
3974       ostrtab->add_output_section_data(pstr);
3975
3976       off_t symtab_off;
3977       if (!parameters->incremental_update())
3978         symtab_off = align_address(*poff, align);
3979       else
3980         {
3981           symtab_off = this->allocate(off, align, *poff);
3982           if (off == -1)
3983             gold_fallback(_("out of patch space for symbol table; "
3984                             "relink with --incremental-full"));
3985           gold_debug(DEBUG_INCREMENTAL,
3986                      "create_symtab_sections: %08lx %08lx .symtab",
3987                      static_cast<long>(symtab_off),
3988                      static_cast<long>(off));
3989         }
3990
3991       symtab->set_file_offset(symtab_off + global_off);
3992       osymtab->set_file_offset(symtab_off);
3993       osymtab->finalize_data_size();
3994       osymtab->set_link_section(ostrtab);
3995       osymtab->set_info(local_symcount);
3996       osymtab->set_entsize(symsize);
3997
3998       if (symtab_off + off > *poff)
3999         *poff = symtab_off + off;
4000     }
4001 }
4002
4003 // Create the .shstrtab section, which holds the names of the
4004 // sections.  At the time this is called, we have created all the
4005 // output sections except .shstrtab itself.
4006
4007 Output_section*
4008 Layout::create_shstrtab()
4009 {
4010   // FIXME: We don't need to create a .shstrtab section if we are
4011   // stripping everything.
4012
4013   const char* name = this->namepool_.add(".shstrtab", false, NULL);
4014
4015   Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
4016                                                  ORDER_INVALID, false);
4017
4018   if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
4019     {
4020       // We can't write out this section until we've set all the
4021       // section names, and we don't set the names of compressed
4022       // output sections until relocations are complete.  FIXME: With
4023       // the current names we use, this is unnecessary.
4024       os->set_after_input_sections();
4025     }
4026
4027   Output_section_data* posd = new Output_data_strtab(&this->namepool_);
4028   os->add_output_section_data(posd);
4029
4030   return os;
4031 }
4032
4033 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
4034 // offset.
4035
4036 void
4037 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
4038 {
4039   Output_section_headers* oshdrs;
4040   oshdrs = new Output_section_headers(this,
4041                                       &this->segment_list_,
4042                                       &this->section_list_,
4043                                       &this->unattached_section_list_,
4044                                       &this->namepool_,
4045                                       shstrtab_section);
4046   off_t off;
4047   if (!parameters->incremental_update())
4048     off = align_address(*poff, oshdrs->addralign());
4049   else
4050     {
4051       oshdrs->pre_finalize_data_size();
4052       off = this->allocate(oshdrs->data_size(), oshdrs->addralign(), *poff);
4053       if (off == -1)
4054           gold_fallback(_("out of patch space for section header table; "
4055                           "relink with --incremental-full"));
4056       gold_debug(DEBUG_INCREMENTAL,
4057                  "create_shdrs: %08lx %08lx (section header table)",
4058                  static_cast<long>(off),
4059                  static_cast<long>(off + oshdrs->data_size()));
4060     }
4061   oshdrs->set_address_and_file_offset(0, off);
4062   off += oshdrs->data_size();
4063   if (off > *poff)
4064     *poff = off;
4065   this->section_headers_ = oshdrs;
4066 }
4067
4068 // Count the allocated sections.
4069
4070 size_t
4071 Layout::allocated_output_section_count() const
4072 {
4073   size_t section_count = 0;
4074   for (Segment_list::const_iterator p = this->segment_list_.begin();
4075        p != this->segment_list_.end();
4076        ++p)
4077     section_count += (*p)->output_section_count();
4078   return section_count;
4079 }
4080
4081 // Create the dynamic symbol table.
4082
4083 void
4084 Layout::create_dynamic_symtab(const Input_objects* input_objects,
4085                               Symbol_table* symtab,
4086                               Output_section** pdynstr,
4087                               unsigned int* plocal_dynamic_count,
4088                               std::vector<Symbol*>* pdynamic_symbols,
4089                               Versions* pversions)
4090 {
4091   // Count all the symbols in the dynamic symbol table, and set the
4092   // dynamic symbol indexes.
4093
4094   // Skip symbol 0, which is always all zeroes.
4095   unsigned int index = 1;
4096
4097   // Add STT_SECTION symbols for each Output section which needs one.
4098   for (Section_list::iterator p = this->section_list_.begin();
4099        p != this->section_list_.end();
4100        ++p)
4101     {
4102       if (!(*p)->needs_dynsym_index())
4103         (*p)->set_dynsym_index(-1U);
4104       else
4105         {
4106           (*p)->set_dynsym_index(index);
4107           ++index;
4108         }
4109     }
4110
4111   // Count the local symbols that need to go in the dynamic symbol table,
4112   // and set the dynamic symbol indexes.
4113   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4114        p != input_objects->relobj_end();
4115        ++p)
4116     {
4117       unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
4118       index = new_index;
4119     }
4120
4121   unsigned int local_symcount = index;
4122   *plocal_dynamic_count = local_symcount;
4123
4124   index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
4125                                      &this->dynpool_, pversions);
4126
4127   int symsize;
4128   unsigned int align;
4129   const int size = parameters->target().get_size();
4130   if (size == 32)
4131     {
4132       symsize = elfcpp::Elf_sizes<32>::sym_size;
4133       align = 4;
4134     }
4135   else if (size == 64)
4136     {
4137       symsize = elfcpp::Elf_sizes<64>::sym_size;
4138       align = 8;
4139     }
4140   else
4141     gold_unreachable();
4142
4143   // Create the dynamic symbol table section.
4144
4145   Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
4146                                                        elfcpp::SHT_DYNSYM,
4147                                                        elfcpp::SHF_ALLOC,
4148                                                        false,
4149                                                        ORDER_DYNAMIC_LINKER,
4150                                                        false);
4151
4152   // Check for NULL as a linker script may discard .dynsym.
4153   if (dynsym != NULL)
4154     {
4155       Output_section_data* odata = new Output_data_fixed_space(index * symsize,
4156                                                                align,
4157                                                                "** dynsym");
4158       dynsym->add_output_section_data(odata);
4159
4160       dynsym->set_info(local_symcount);
4161       dynsym->set_entsize(symsize);
4162       dynsym->set_addralign(align);
4163
4164       this->dynsym_section_ = dynsym;
4165     }
4166
4167   Output_data_dynamic* const odyn = this->dynamic_data_;
4168   if (odyn != NULL)
4169     {
4170       odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
4171       odyn->add_constant(elfcpp::DT_SYMENT, symsize);
4172     }
4173
4174   // If there are more than SHN_LORESERVE allocated sections, we
4175   // create a .dynsym_shndx section.  It is possible that we don't
4176   // need one, because it is possible that there are no dynamic
4177   // symbols in any of the sections with indexes larger than
4178   // SHN_LORESERVE.  This is probably unusual, though, and at this
4179   // time we don't know the actual section indexes so it is
4180   // inconvenient to check.
4181   if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
4182     {
4183       Output_section* dynsym_xindex =
4184         this->choose_output_section(NULL, ".dynsym_shndx",
4185                                     elfcpp::SHT_SYMTAB_SHNDX,
4186                                     elfcpp::SHF_ALLOC,
4187                                     false, ORDER_DYNAMIC_LINKER, false);
4188
4189       if (dynsym_xindex != NULL)
4190         {
4191           this->dynsym_xindex_ = new Output_symtab_xindex(index);
4192
4193           dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
4194
4195           dynsym_xindex->set_link_section(dynsym);
4196           dynsym_xindex->set_addralign(4);
4197           dynsym_xindex->set_entsize(4);
4198
4199           dynsym_xindex->set_after_input_sections();
4200
4201           // This tells the driver code to wait until the symbol table
4202           // has written out before writing out the postprocessing
4203           // sections, including the .dynsym_shndx section.
4204           this->any_postprocessing_sections_ = true;
4205         }
4206     }
4207
4208   // Create the dynamic string table section.
4209
4210   Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
4211                                                        elfcpp::SHT_STRTAB,
4212                                                        elfcpp::SHF_ALLOC,
4213                                                        false,
4214                                                        ORDER_DYNAMIC_LINKER,
4215                                                        false);
4216   *pdynstr = dynstr;
4217   if (dynstr != NULL)
4218     {
4219       Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
4220       dynstr->add_output_section_data(strdata);
4221
4222       if (dynsym != NULL)
4223         dynsym->set_link_section(dynstr);
4224       if (this->dynamic_section_ != NULL)
4225         this->dynamic_section_->set_link_section(dynstr);
4226
4227       if (odyn != NULL)
4228         {
4229           odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
4230           odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
4231         }
4232     }
4233
4234   // Create the hash tables.
4235
4236   if (strcmp(parameters->options().hash_style(), "sysv") == 0
4237       || strcmp(parameters->options().hash_style(), "both") == 0)
4238     {
4239       unsigned char* phash;
4240       unsigned int hashlen;
4241       Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
4242                                     &phash, &hashlen);
4243
4244       Output_section* hashsec =
4245         this->choose_output_section(NULL, ".hash", elfcpp::SHT_HASH,
4246                                     elfcpp::SHF_ALLOC, false,
4247                                     ORDER_DYNAMIC_LINKER, false);
4248
4249       Output_section_data* hashdata = new Output_data_const_buffer(phash,
4250                                                                    hashlen,
4251                                                                    align,
4252                                                                    "** hash");
4253       if (hashsec != NULL && hashdata != NULL)
4254         hashsec->add_output_section_data(hashdata);
4255
4256       if (hashsec != NULL)
4257         {
4258           if (dynsym != NULL)
4259             hashsec->set_link_section(dynsym);
4260           hashsec->set_entsize(4);
4261         }
4262
4263       if (odyn != NULL)
4264         odyn->add_section_address(elfcpp::DT_HASH, hashsec);
4265     }
4266
4267   if (strcmp(parameters->options().hash_style(), "gnu") == 0
4268       || strcmp(parameters->options().hash_style(), "both") == 0)
4269     {
4270       unsigned char* phash;
4271       unsigned int hashlen;
4272       Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
4273                                     &phash, &hashlen);
4274
4275       Output_section* hashsec =
4276         this->choose_output_section(NULL, ".gnu.hash", elfcpp::SHT_GNU_HASH,
4277                                     elfcpp::SHF_ALLOC, false,
4278                                     ORDER_DYNAMIC_LINKER, false);
4279
4280       Output_section_data* hashdata = new Output_data_const_buffer(phash,
4281                                                                    hashlen,
4282                                                                    align,
4283                                                                    "** hash");
4284       if (hashsec != NULL && hashdata != NULL)
4285         hashsec->add_output_section_data(hashdata);
4286
4287       if (hashsec != NULL)
4288         {
4289           if (dynsym != NULL)
4290             hashsec->set_link_section(dynsym);
4291
4292           // For a 64-bit target, the entries in .gnu.hash do not have
4293           // a uniform size, so we only set the entry size for a
4294           // 32-bit target.
4295           if (parameters->target().get_size() == 32)
4296             hashsec->set_entsize(4);
4297
4298           if (odyn != NULL)
4299             odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
4300         }
4301     }
4302 }
4303
4304 // Assign offsets to each local portion of the dynamic symbol table.
4305
4306 void
4307 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
4308 {
4309   Output_section* dynsym = this->dynsym_section_;
4310   if (dynsym == NULL)
4311     return;
4312
4313   off_t off = dynsym->offset();
4314
4315   // Skip the dummy symbol at the start of the section.
4316   off += dynsym->entsize();
4317
4318   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4319        p != input_objects->relobj_end();
4320        ++p)
4321     {
4322       unsigned int count = (*p)->set_local_dynsym_offset(off);
4323       off += count * dynsym->entsize();
4324     }
4325 }
4326
4327 // Create the version sections.
4328
4329 void
4330 Layout::create_version_sections(const Versions* versions,
4331                                 const Symbol_table* symtab,
4332                                 unsigned int local_symcount,
4333                                 const std::vector<Symbol*>& dynamic_symbols,
4334                                 const Output_section* dynstr)
4335 {
4336   if (!versions->any_defs() && !versions->any_needs())
4337     return;
4338
4339   switch (parameters->size_and_endianness())
4340     {
4341 #ifdef HAVE_TARGET_32_LITTLE
4342     case Parameters::TARGET_32_LITTLE:
4343       this->sized_create_version_sections<32, false>(versions, symtab,
4344                                                      local_symcount,
4345                                                      dynamic_symbols, dynstr);
4346       break;
4347 #endif
4348 #ifdef HAVE_TARGET_32_BIG
4349     case Parameters::TARGET_32_BIG:
4350       this->sized_create_version_sections<32, true>(versions, symtab,
4351                                                     local_symcount,
4352                                                     dynamic_symbols, dynstr);
4353       break;
4354 #endif
4355 #ifdef HAVE_TARGET_64_LITTLE
4356     case Parameters::TARGET_64_LITTLE:
4357       this->sized_create_version_sections<64, false>(versions, symtab,
4358                                                      local_symcount,
4359                                                      dynamic_symbols, dynstr);
4360       break;
4361 #endif
4362 #ifdef HAVE_TARGET_64_BIG
4363     case Parameters::TARGET_64_BIG:
4364       this->sized_create_version_sections<64, true>(versions, symtab,
4365                                                     local_symcount,
4366                                                     dynamic_symbols, dynstr);
4367       break;
4368 #endif
4369     default:
4370       gold_unreachable();
4371     }
4372 }
4373
4374 // Create the version sections, sized version.
4375
4376 template<int size, bool big_endian>
4377 void
4378 Layout::sized_create_version_sections(
4379     const Versions* versions,
4380     const Symbol_table* symtab,
4381     unsigned int local_symcount,
4382     const std::vector<Symbol*>& dynamic_symbols,
4383     const Output_section* dynstr)
4384 {
4385   Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
4386                                                      elfcpp::SHT_GNU_versym,
4387                                                      elfcpp::SHF_ALLOC,
4388                                                      false,
4389                                                      ORDER_DYNAMIC_LINKER,
4390                                                      false);
4391
4392   // Check for NULL since a linker script may discard this section.
4393   if (vsec != NULL)
4394     {
4395       unsigned char* vbuf;
4396       unsigned int vsize;
4397       versions->symbol_section_contents<size, big_endian>(symtab,
4398                                                           &this->dynpool_,
4399                                                           local_symcount,
4400                                                           dynamic_symbols,
4401                                                           &vbuf, &vsize);
4402
4403       Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
4404                                                                 "** versions");
4405
4406       vsec->add_output_section_data(vdata);
4407       vsec->set_entsize(2);
4408       vsec->set_link_section(this->dynsym_section_);
4409     }
4410
4411   Output_data_dynamic* const odyn = this->dynamic_data_;
4412   if (odyn != NULL && vsec != NULL)
4413     odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
4414
4415   if (versions->any_defs())
4416     {
4417       Output_section* vdsec;
4418       vdsec = this->choose_output_section(NULL, ".gnu.version_d",
4419                                           elfcpp::SHT_GNU_verdef,
4420                                           elfcpp::SHF_ALLOC,
4421                                           false, ORDER_DYNAMIC_LINKER, false);
4422
4423       if (vdsec != NULL)
4424         {
4425           unsigned char* vdbuf;
4426           unsigned int vdsize;
4427           unsigned int vdentries;
4428           versions->def_section_contents<size, big_endian>(&this->dynpool_,
4429                                                            &vdbuf, &vdsize,
4430                                                            &vdentries);
4431
4432           Output_section_data* vddata =
4433             new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
4434
4435           vdsec->add_output_section_data(vddata);
4436           vdsec->set_link_section(dynstr);
4437           vdsec->set_info(vdentries);
4438
4439           if (odyn != NULL)
4440             {
4441               odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
4442               odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
4443             }
4444         }
4445     }
4446
4447   if (versions->any_needs())
4448     {
4449       Output_section* vnsec;
4450       vnsec = this->choose_output_section(NULL, ".gnu.version_r",
4451                                           elfcpp::SHT_GNU_verneed,
4452                                           elfcpp::SHF_ALLOC,
4453                                           false, ORDER_DYNAMIC_LINKER, false);
4454
4455       if (vnsec != NULL)
4456         {
4457           unsigned char* vnbuf;
4458           unsigned int vnsize;
4459           unsigned int vnentries;
4460           versions->need_section_contents<size, big_endian>(&this->dynpool_,
4461                                                             &vnbuf, &vnsize,
4462                                                             &vnentries);
4463
4464           Output_section_data* vndata =
4465             new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
4466
4467           vnsec->add_output_section_data(vndata);
4468           vnsec->set_link_section(dynstr);
4469           vnsec->set_info(vnentries);
4470
4471           if (odyn != NULL)
4472             {
4473               odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
4474               odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
4475             }
4476         }
4477     }
4478 }
4479
4480 // Create the .interp section and PT_INTERP segment.
4481
4482 void
4483 Layout::create_interp(const Target* target)
4484 {
4485   gold_assert(this->interp_segment_ == NULL);
4486
4487   const char* interp = parameters->options().dynamic_linker();
4488   if (interp == NULL)
4489     {
4490       interp = target->dynamic_linker();
4491       gold_assert(interp != NULL);
4492     }
4493
4494   size_t len = strlen(interp) + 1;
4495
4496   Output_section_data* odata = new Output_data_const(interp, len, 1);
4497
4498   Output_section* osec = this->choose_output_section(NULL, ".interp",
4499                                                      elfcpp::SHT_PROGBITS,
4500                                                      elfcpp::SHF_ALLOC,
4501                                                      false, ORDER_INTERP,
4502                                                      false);
4503   if (osec != NULL)
4504     osec->add_output_section_data(odata);
4505 }
4506
4507 // Add dynamic tags for the PLT and the dynamic relocs.  This is
4508 // called by the target-specific code.  This does nothing if not doing
4509 // a dynamic link.
4510
4511 // USE_REL is true for REL relocs rather than RELA relocs.
4512
4513 // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
4514
4515 // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
4516 // and we also set DT_PLTREL.  We use PLT_REL's output section, since
4517 // some targets have multiple reloc sections in PLT_REL.
4518
4519 // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
4520 // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT.  Again we use the output
4521 // section.
4522
4523 // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
4524 // executable.
4525
4526 void
4527 Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
4528                                 const Output_data* plt_rel,
4529                                 const Output_data_reloc_generic* dyn_rel,
4530                                 bool add_debug, bool dynrel_includes_plt)
4531 {
4532   Output_data_dynamic* odyn = this->dynamic_data_;
4533   if (odyn == NULL)
4534     return;
4535
4536   if (plt_got != NULL && plt_got->output_section() != NULL)
4537     odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
4538
4539   if (plt_rel != NULL && plt_rel->output_section() != NULL)
4540     {
4541       odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
4542       odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
4543       odyn->add_constant(elfcpp::DT_PLTREL,
4544                          use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
4545     }
4546
4547   if ((dyn_rel != NULL && dyn_rel->output_section() != NULL)
4548       || (dynrel_includes_plt
4549           && plt_rel != NULL
4550           && plt_rel->output_section() != NULL))
4551     {
4552       bool have_dyn_rel = dyn_rel != NULL && dyn_rel->output_section() != NULL;
4553       bool have_plt_rel = plt_rel != NULL && plt_rel->output_section() != NULL;
4554       odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
4555                                 (have_dyn_rel
4556                                  ? dyn_rel->output_section()
4557                                  : plt_rel->output_section()));
4558       elfcpp::DT size_tag = use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ;
4559       if (have_dyn_rel && have_plt_rel && dynrel_includes_plt)
4560         odyn->add_section_size(size_tag,
4561                                dyn_rel->output_section(),
4562                                plt_rel->output_section());
4563       else if (have_dyn_rel)
4564         odyn->add_section_size(size_tag, dyn_rel->output_section());
4565       else
4566         odyn->add_section_size(size_tag, plt_rel->output_section());
4567       const int size = parameters->target().get_size();
4568       elfcpp::DT rel_tag;
4569       int rel_size;
4570       if (use_rel)
4571         {
4572           rel_tag = elfcpp::DT_RELENT;
4573           if (size == 32)
4574             rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
4575           else if (size == 64)
4576             rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
4577           else
4578             gold_unreachable();
4579         }
4580       else
4581         {
4582           rel_tag = elfcpp::DT_RELAENT;
4583           if (size == 32)
4584             rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
4585           else if (size == 64)
4586             rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
4587           else
4588             gold_unreachable();
4589         }
4590       odyn->add_constant(rel_tag, rel_size);
4591
4592       if (parameters->options().combreloc() && have_dyn_rel)
4593         {
4594           size_t c = dyn_rel->relative_reloc_count();
4595           if (c > 0)
4596             odyn->add_constant((use_rel
4597                                 ? elfcpp::DT_RELCOUNT
4598                                 : elfcpp::DT_RELACOUNT),
4599                                c);
4600         }
4601     }
4602
4603   if (add_debug && !parameters->options().shared())
4604     {
4605       // The value of the DT_DEBUG tag is filled in by the dynamic
4606       // linker at run time, and used by the debugger.
4607       odyn->add_constant(elfcpp::DT_DEBUG, 0);
4608     }
4609 }
4610
4611 // Finish the .dynamic section and PT_DYNAMIC segment.
4612
4613 void
4614 Layout::finish_dynamic_section(const Input_objects* input_objects,
4615                                const Symbol_table* symtab)
4616 {
4617   if (!this->script_options_->saw_phdrs_clause()
4618       && this->dynamic_section_ != NULL)
4619     {
4620       Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
4621                                                        (elfcpp::PF_R
4622                                                         | elfcpp::PF_W));
4623       oseg->add_output_section_to_nonload(this->dynamic_section_,
4624                                           elfcpp::PF_R | elfcpp::PF_W);
4625     }
4626
4627   Output_data_dynamic* const odyn = this->dynamic_data_;
4628   if (odyn == NULL)
4629     return;
4630
4631   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
4632        p != input_objects->dynobj_end();
4633        ++p)
4634     {
4635       if (!(*p)->is_needed() && (*p)->as_needed())
4636         {
4637           // This dynamic object was linked with --as-needed, but it
4638           // is not needed.
4639           continue;
4640         }
4641
4642       odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
4643     }
4644
4645   if (parameters->options().shared())
4646     {
4647       const char* soname = parameters->options().soname();
4648       if (soname != NULL)
4649         odyn->add_string(elfcpp::DT_SONAME, soname);
4650     }
4651
4652   Symbol* sym = symtab->lookup(parameters->options().init());
4653   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
4654     odyn->add_symbol(elfcpp::DT_INIT, sym);
4655
4656   sym = symtab->lookup(parameters->options().fini());
4657   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
4658     odyn->add_symbol(elfcpp::DT_FINI, sym);
4659
4660   // Look for .init_array, .preinit_array and .fini_array by checking
4661   // section types.
4662   for(Layout::Section_list::const_iterator p = this->section_list_.begin();
4663       p != this->section_list_.end();
4664       ++p)
4665     switch((*p)->type())
4666       {
4667       case elfcpp::SHT_FINI_ARRAY:
4668         odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
4669         odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
4670         break;
4671       case elfcpp::SHT_INIT_ARRAY:
4672         odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
4673         odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
4674         break;
4675       case elfcpp::SHT_PREINIT_ARRAY:
4676         odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
4677         odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
4678         break;
4679       default:
4680         break;
4681       }
4682
4683   // Add a DT_RPATH entry if needed.
4684   const General_options::Dir_list& rpath(parameters->options().rpath());
4685   if (!rpath.empty())
4686     {
4687       std::string rpath_val;
4688       for (General_options::Dir_list::const_iterator p = rpath.begin();
4689            p != rpath.end();
4690            ++p)
4691         {
4692           if (rpath_val.empty())
4693             rpath_val = p->name();
4694           else
4695             {
4696               // Eliminate duplicates.
4697               General_options::Dir_list::const_iterator q;
4698               for (q = rpath.begin(); q != p; ++q)
4699                 if (q->name() == p->name())
4700                   break;
4701               if (q == p)
4702                 {
4703                   rpath_val += ':';
4704                   rpath_val += p->name();
4705                 }
4706             }
4707         }
4708
4709       if (!parameters->options().enable_new_dtags())
4710         odyn->add_string(elfcpp::DT_RPATH, rpath_val);
4711       else
4712         odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
4713     }
4714
4715   // Look for text segments that have dynamic relocations.
4716   bool have_textrel = false;
4717   if (!this->script_options_->saw_sections_clause())
4718     {
4719       for (Segment_list::const_iterator p = this->segment_list_.begin();
4720            p != this->segment_list_.end();
4721            ++p)
4722         {
4723           if ((*p)->type() == elfcpp::PT_LOAD
4724               && ((*p)->flags() & elfcpp::PF_W) == 0
4725               && (*p)->has_dynamic_reloc())
4726             {
4727               have_textrel = true;
4728               break;
4729             }
4730         }
4731     }
4732   else
4733     {
4734       // We don't know the section -> segment mapping, so we are
4735       // conservative and just look for readonly sections with
4736       // relocations.  If those sections wind up in writable segments,
4737       // then we have created an unnecessary DT_TEXTREL entry.
4738       for (Section_list::const_iterator p = this->section_list_.begin();
4739            p != this->section_list_.end();
4740            ++p)
4741         {
4742           if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
4743               && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
4744               && (*p)->has_dynamic_reloc())
4745             {
4746               have_textrel = true;
4747               break;
4748             }
4749         }
4750     }
4751
4752   if (parameters->options().filter() != NULL)
4753     odyn->add_string(elfcpp::DT_FILTER, parameters->options().filter());
4754   if (parameters->options().any_auxiliary())
4755     {
4756       for (options::String_set::const_iterator p =
4757              parameters->options().auxiliary_begin();
4758            p != parameters->options().auxiliary_end();
4759            ++p)
4760         odyn->add_string(elfcpp::DT_AUXILIARY, *p);
4761     }
4762
4763   // Add a DT_FLAGS entry if necessary.
4764   unsigned int flags = 0;
4765   if (have_textrel)
4766     {
4767       // Add a DT_TEXTREL for compatibility with older loaders.
4768       odyn->add_constant(elfcpp::DT_TEXTREL, 0);
4769       flags |= elfcpp::DF_TEXTREL;
4770
4771       if (parameters->options().text())
4772         gold_error(_("read-only segment has dynamic relocations"));
4773       else if (parameters->options().warn_shared_textrel()
4774                && parameters->options().shared())
4775         gold_warning(_("shared library text segment is not shareable"));
4776     }
4777   if (parameters->options().shared() && this->has_static_tls())
4778     flags |= elfcpp::DF_STATIC_TLS;
4779   if (parameters->options().origin())
4780     flags |= elfcpp::DF_ORIGIN;
4781   if (parameters->options().Bsymbolic())
4782     {
4783       flags |= elfcpp::DF_SYMBOLIC;
4784       // Add DT_SYMBOLIC for compatibility with older loaders.
4785       odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
4786     }
4787   if (parameters->options().now())
4788     flags |= elfcpp::DF_BIND_NOW;
4789   if (flags != 0)
4790     odyn->add_constant(elfcpp::DT_FLAGS, flags);
4791
4792   flags = 0;
4793   if (parameters->options().initfirst())
4794     flags |= elfcpp::DF_1_INITFIRST;
4795   if (parameters->options().interpose())
4796     flags |= elfcpp::DF_1_INTERPOSE;
4797   if (parameters->options().loadfltr())
4798     flags |= elfcpp::DF_1_LOADFLTR;
4799   if (parameters->options().nodefaultlib())
4800     flags |= elfcpp::DF_1_NODEFLIB;
4801   if (parameters->options().nodelete())
4802     flags |= elfcpp::DF_1_NODELETE;
4803   if (parameters->options().nodlopen())
4804     flags |= elfcpp::DF_1_NOOPEN;
4805   if (parameters->options().nodump())
4806     flags |= elfcpp::DF_1_NODUMP;
4807   if (!parameters->options().shared())
4808     flags &= ~(elfcpp::DF_1_INITFIRST
4809                | elfcpp::DF_1_NODELETE
4810                | elfcpp::DF_1_NOOPEN);
4811   if (parameters->options().origin())
4812     flags |= elfcpp::DF_1_ORIGIN;
4813   if (parameters->options().now())
4814     flags |= elfcpp::DF_1_NOW;
4815   if (parameters->options().Bgroup())
4816     flags |= elfcpp::DF_1_GROUP;
4817   if (flags != 0)
4818     odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
4819 }
4820
4821 // Set the size of the _DYNAMIC symbol table to be the size of the
4822 // dynamic data.
4823
4824 void
4825 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
4826 {
4827   Output_data_dynamic* const odyn = this->dynamic_data_;
4828   if (odyn == NULL)
4829     return;
4830   odyn->finalize_data_size();
4831   if (this->dynamic_symbol_ == NULL)
4832     return;
4833   off_t data_size = odyn->data_size();
4834   const int size = parameters->target().get_size();
4835   if (size == 32)
4836     symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
4837   else if (size == 64)
4838     symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
4839   else
4840     gold_unreachable();
4841 }
4842
4843 // The mapping of input section name prefixes to output section names.
4844 // In some cases one prefix is itself a prefix of another prefix; in
4845 // such a case the longer prefix must come first.  These prefixes are
4846 // based on the GNU linker default ELF linker script.
4847
4848 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
4849 #define MAPPING_INIT_EXACT(f, t) { f, 0, t, sizeof(t) - 1 }
4850 const Layout::Section_name_mapping Layout::section_name_mapping[] =
4851 {
4852   MAPPING_INIT(".text.", ".text"),
4853   MAPPING_INIT(".rodata.", ".rodata"),
4854   MAPPING_INIT(".data.rel.ro.local.", ".data.rel.ro.local"),
4855   MAPPING_INIT_EXACT(".data.rel.ro.local", ".data.rel.ro.local"),
4856   MAPPING_INIT(".data.rel.ro.", ".data.rel.ro"),
4857   MAPPING_INIT_EXACT(".data.rel.ro", ".data.rel.ro"),
4858   MAPPING_INIT(".data.", ".data"),
4859   MAPPING_INIT(".bss.", ".bss"),
4860   MAPPING_INIT(".tdata.", ".tdata"),
4861   MAPPING_INIT(".tbss.", ".tbss"),
4862   MAPPING_INIT(".init_array.", ".init_array"),
4863   MAPPING_INIT(".fini_array.", ".fini_array"),
4864   MAPPING_INIT(".sdata.", ".sdata"),
4865   MAPPING_INIT(".sbss.", ".sbss"),
4866   // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
4867   // differently depending on whether it is creating a shared library.
4868   MAPPING_INIT(".sdata2.", ".sdata"),
4869   MAPPING_INIT(".sbss2.", ".sbss"),
4870   MAPPING_INIT(".lrodata.", ".lrodata"),
4871   MAPPING_INIT(".ldata.", ".ldata"),
4872   MAPPING_INIT(".lbss.", ".lbss"),
4873   MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
4874   MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
4875   MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
4876   MAPPING_INIT(".gnu.linkonce.t.", ".text"),
4877   MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
4878   MAPPING_INIT(".gnu.linkonce.d.", ".data"),
4879   MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
4880   MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
4881   MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
4882   MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
4883   MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
4884   MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
4885   MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
4886   MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
4887   MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
4888   MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
4889   MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
4890   MAPPING_INIT(".ARM.extab", ".ARM.extab"),
4891   MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
4892   MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
4893   MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
4894 };
4895 #undef MAPPING_INIT
4896 #undef MAPPING_INIT_EXACT
4897
4898 const int Layout::section_name_mapping_count =
4899   (sizeof(Layout::section_name_mapping)
4900    / sizeof(Layout::section_name_mapping[0]));
4901
4902 // Choose the output section name to use given an input section name.
4903 // Set *PLEN to the length of the name.  *PLEN is initialized to the
4904 // length of NAME.
4905
4906 const char*
4907 Layout::output_section_name(const Relobj* relobj, const char* name,
4908                             size_t* plen)
4909 {
4910   // gcc 4.3 generates the following sorts of section names when it
4911   // needs a section name specific to a function:
4912   //   .text.FN
4913   //   .rodata.FN
4914   //   .sdata2.FN
4915   //   .data.FN
4916   //   .data.rel.FN
4917   //   .data.rel.local.FN
4918   //   .data.rel.ro.FN
4919   //   .data.rel.ro.local.FN
4920   //   .sdata.FN
4921   //   .bss.FN
4922   //   .sbss.FN
4923   //   .tdata.FN
4924   //   .tbss.FN
4925
4926   // The GNU linker maps all of those to the part before the .FN,
4927   // except that .data.rel.local.FN is mapped to .data, and
4928   // .data.rel.ro.local.FN is mapped to .data.rel.ro.  The sections
4929   // beginning with .data.rel.ro.local are grouped together.
4930
4931   // For an anonymous namespace, the string FN can contain a '.'.
4932
4933   // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
4934   // GNU linker maps to .rodata.
4935
4936   // The .data.rel.ro sections are used with -z relro.  The sections
4937   // are recognized by name.  We use the same names that the GNU
4938   // linker does for these sections.
4939
4940   // It is hard to handle this in a principled way, so we don't even
4941   // try.  We use a table of mappings.  If the input section name is
4942   // not found in the table, we simply use it as the output section
4943   // name.
4944
4945   const Section_name_mapping* psnm = section_name_mapping;
4946   for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
4947     {
4948       if (psnm->fromlen > 0)
4949         {
4950           if (strncmp(name, psnm->from, psnm->fromlen) == 0)
4951             {
4952               *plen = psnm->tolen;
4953               return psnm->to;
4954             }
4955         }
4956       else
4957         {
4958           if (strcmp(name, psnm->from) == 0)
4959             {
4960               *plen = psnm->tolen;
4961               return psnm->to;
4962             }
4963         }
4964     }
4965
4966   // As an additional complication, .ctors sections are output in
4967   // either .ctors or .init_array sections, and .dtors sections are
4968   // output in either .dtors or .fini_array sections.
4969   if (is_prefix_of(".ctors.", name) || is_prefix_of(".dtors.", name))
4970     {
4971       if (parameters->options().ctors_in_init_array())
4972         {
4973           *plen = 11;
4974           return name[1] == 'c' ? ".init_array" : ".fini_array";
4975         }
4976       else
4977         {
4978           *plen = 6;
4979           return name[1] == 'c' ? ".ctors" : ".dtors";
4980         }
4981     }
4982   if (parameters->options().ctors_in_init_array()
4983       && (strcmp(name, ".ctors") == 0 || strcmp(name, ".dtors") == 0))
4984     {
4985       // To make .init_array/.fini_array work with gcc we must exclude
4986       // .ctors and .dtors sections from the crtbegin and crtend
4987       // files.
4988       if (relobj == NULL
4989           || (!Layout::match_file_name(relobj, "crtbegin")
4990               && !Layout::match_file_name(relobj, "crtend")))
4991         {
4992           *plen = 11;
4993           return name[1] == 'c' ? ".init_array" : ".fini_array";
4994         }
4995     }
4996
4997   return name;
4998 }
4999
5000 // Return true if RELOBJ is an input file whose base name matches
5001 // FILE_NAME.  The base name must have an extension of ".o", and must
5002 // be exactly FILE_NAME.o or FILE_NAME, one character, ".o".  This is
5003 // to match crtbegin.o as well as crtbeginS.o without getting confused
5004 // by other possibilities.  Overall matching the file name this way is
5005 // a dreadful hack, but the GNU linker does it in order to better
5006 // support gcc, and we need to be compatible.
5007
5008 bool
5009 Layout::match_file_name(const Relobj* relobj, const char* match)
5010 {
5011   const std::string& file_name(relobj->name());
5012   const char* base_name = lbasename(file_name.c_str());
5013   size_t match_len = strlen(match);
5014   if (strncmp(base_name, match, match_len) != 0)
5015     return false;
5016   size_t base_len = strlen(base_name);
5017   if (base_len != match_len + 2 && base_len != match_len + 3)
5018     return false;
5019   return memcmp(base_name + base_len - 2, ".o", 2) == 0;
5020 }
5021
5022 // Check if a comdat group or .gnu.linkonce section with the given
5023 // NAME is selected for the link.  If there is already a section,
5024 // *KEPT_SECTION is set to point to the existing section and the
5025 // function returns false.  Otherwise, OBJECT, SHNDX, IS_COMDAT, and
5026 // IS_GROUP_NAME are recorded for this NAME in the layout object,
5027 // *KEPT_SECTION is set to the internal copy and the function returns
5028 // true.
5029
5030 bool
5031 Layout::find_or_add_kept_section(const std::string& name,
5032                                  Relobj* object,
5033                                  unsigned int shndx,
5034                                  bool is_comdat,
5035                                  bool is_group_name,
5036                                  Kept_section** kept_section)
5037 {
5038   // It's normal to see a couple of entries here, for the x86 thunk
5039   // sections.  If we see more than a few, we're linking a C++
5040   // program, and we resize to get more space to minimize rehashing.
5041   if (this->signatures_.size() > 4
5042       && !this->resized_signatures_)
5043     {
5044       reserve_unordered_map(&this->signatures_,
5045                             this->number_of_input_files_ * 64);
5046       this->resized_signatures_ = true;
5047     }
5048
5049   Kept_section candidate;
5050   std::pair<Signatures::iterator, bool> ins =
5051     this->signatures_.insert(std::make_pair(name, candidate));
5052
5053   if (kept_section != NULL)
5054     *kept_section = &ins.first->second;
5055   if (ins.second)
5056     {
5057       // This is the first time we've seen this signature.
5058       ins.first->second.set_object(object);
5059       ins.first->second.set_shndx(shndx);
5060       if (is_comdat)
5061         ins.first->second.set_is_comdat();
5062       if (is_group_name)
5063         ins.first->second.set_is_group_name();
5064       return true;
5065     }
5066
5067   // We have already seen this signature.
5068
5069   if (ins.first->second.is_group_name())
5070     {
5071       // We've already seen a real section group with this signature.
5072       // If the kept group is from a plugin object, and we're in the
5073       // replacement phase, accept the new one as a replacement.
5074       if (ins.first->second.object() == NULL
5075           && parameters->options().plugins()->in_replacement_phase())
5076         {
5077           ins.first->second.set_object(object);
5078           ins.first->second.set_shndx(shndx);
5079           return true;
5080         }
5081       return false;
5082     }
5083   else if (is_group_name)
5084     {
5085       // This is a real section group, and we've already seen a
5086       // linkonce section with this signature.  Record that we've seen
5087       // a section group, and don't include this section group.
5088       ins.first->second.set_is_group_name();
5089       return false;
5090     }
5091   else
5092     {
5093       // We've already seen a linkonce section and this is a linkonce
5094       // section.  These don't block each other--this may be the same
5095       // symbol name with different section types.
5096       return true;
5097     }
5098 }
5099
5100 // Store the allocated sections into the section list.
5101
5102 void
5103 Layout::get_allocated_sections(Section_list* section_list) const
5104 {
5105   for (Section_list::const_iterator p = this->section_list_.begin();
5106        p != this->section_list_.end();
5107        ++p)
5108     if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
5109       section_list->push_back(*p);
5110 }
5111
5112 // Store the executable sections into the section list.
5113
5114 void
5115 Layout::get_executable_sections(Section_list* section_list) const
5116 {
5117   for (Section_list::const_iterator p = this->section_list_.begin();
5118        p != this->section_list_.end();
5119        ++p)
5120     if (((*p)->flags() & (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
5121         == (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
5122       section_list->push_back(*p);
5123 }
5124
5125 // Create an output segment.
5126
5127 Output_segment*
5128 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
5129 {
5130   gold_assert(!parameters->options().relocatable());
5131   Output_segment* oseg = new Output_segment(type, flags);
5132   this->segment_list_.push_back(oseg);
5133
5134   if (type == elfcpp::PT_TLS)
5135     this->tls_segment_ = oseg;
5136   else if (type == elfcpp::PT_GNU_RELRO)
5137     this->relro_segment_ = oseg;
5138   else if (type == elfcpp::PT_INTERP)
5139     this->interp_segment_ = oseg;
5140
5141   return oseg;
5142 }
5143
5144 // Return the file offset of the normal symbol table.
5145
5146 off_t
5147 Layout::symtab_section_offset() const
5148 {
5149   if (this->symtab_section_ != NULL)
5150     return this->symtab_section_->offset();
5151   return 0;
5152 }
5153
5154 // Return the section index of the normal symbol table.  It may have
5155 // been stripped by the -s/--strip-all option.
5156
5157 unsigned int
5158 Layout::symtab_section_shndx() const
5159 {
5160   if (this->symtab_section_ != NULL)
5161     return this->symtab_section_->out_shndx();
5162   return 0;
5163 }
5164
5165 // Write out the Output_sections.  Most won't have anything to write,
5166 // since most of the data will come from input sections which are
5167 // handled elsewhere.  But some Output_sections do have Output_data.
5168
5169 void
5170 Layout::write_output_sections(Output_file* of) const
5171 {
5172   for (Section_list::const_iterator p = this->section_list_.begin();
5173        p != this->section_list_.end();
5174        ++p)
5175     {
5176       if (!(*p)->after_input_sections())
5177         (*p)->write(of);
5178     }
5179 }
5180
5181 // Write out data not associated with a section or the symbol table.
5182
5183 void
5184 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
5185 {
5186   if (!parameters->options().strip_all())
5187     {
5188       const Output_section* symtab_section = this->symtab_section_;
5189       for (Section_list::const_iterator p = this->section_list_.begin();
5190            p != this->section_list_.end();
5191            ++p)
5192         {
5193           if ((*p)->needs_symtab_index())
5194             {
5195               gold_assert(symtab_section != NULL);
5196               unsigned int index = (*p)->symtab_index();
5197               gold_assert(index > 0 && index != -1U);
5198               off_t off = (symtab_section->offset()
5199                            + index * symtab_section->entsize());
5200               symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
5201             }
5202         }
5203     }
5204
5205   const Output_section* dynsym_section = this->dynsym_section_;
5206   for (Section_list::const_iterator p = this->section_list_.begin();
5207        p != this->section_list_.end();
5208        ++p)
5209     {
5210       if ((*p)->needs_dynsym_index())
5211         {
5212           gold_assert(dynsym_section != NULL);
5213           unsigned int index = (*p)->dynsym_index();
5214           gold_assert(index > 0 && index != -1U);
5215           off_t off = (dynsym_section->offset()
5216                        + index * dynsym_section->entsize());
5217           symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
5218         }
5219     }
5220
5221   // Write out the Output_data which are not in an Output_section.
5222   for (Data_list::const_iterator p = this->special_output_list_.begin();
5223        p != this->special_output_list_.end();
5224        ++p)
5225     (*p)->write(of);
5226 }
5227
5228 // Write out the Output_sections which can only be written after the
5229 // input sections are complete.
5230
5231 void
5232 Layout::write_sections_after_input_sections(Output_file* of)
5233 {
5234   // Determine the final section offsets, and thus the final output
5235   // file size.  Note we finalize the .shstrab last, to allow the
5236   // after_input_section sections to modify their section-names before
5237   // writing.
5238   if (this->any_postprocessing_sections_)
5239     {
5240       off_t off = this->output_file_size_;
5241       off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
5242
5243       // Now that we've finalized the names, we can finalize the shstrab.
5244       off =
5245         this->set_section_offsets(off,
5246                                   STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
5247
5248       if (off > this->output_file_size_)
5249         {
5250           of->resize(off);
5251           this->output_file_size_ = off;
5252         }
5253     }
5254
5255   for (Section_list::const_iterator p = this->section_list_.begin();
5256        p != this->section_list_.end();
5257        ++p)
5258     {
5259       if ((*p)->after_input_sections())
5260         (*p)->write(of);
5261     }
5262
5263   this->section_headers_->write(of);
5264 }
5265
5266 // Build IDs can be computed as a "flat" sha1 or md5 of a string of bytes,
5267 // or as a "tree" where each chunk of the string is hashed and then those
5268 // hashes are put into a (much smaller) string which is hashed with sha1.
5269 // We compute a checksum over the entire file because that is simplest.
5270
5271 Task_token*
5272 Layout::queue_build_id_tasks(Workqueue* workqueue, Task_token* build_id_blocker,
5273                              Output_file* of)
5274 {
5275   const size_t filesize = (this->output_file_size() <= 0 ? 0
5276                            : static_cast<size_t>(this->output_file_size()));
5277   if (this->build_id_note_ != NULL
5278       && strcmp(parameters->options().build_id(), "tree") == 0
5279       && parameters->options().build_id_chunk_size_for_treehash() > 0
5280       && filesize > 0
5281       && (filesize >=
5282           parameters->options().build_id_min_file_size_for_treehash()))
5283     {
5284       static const size_t MD5_OUTPUT_SIZE_IN_BYTES = 16;
5285       const size_t chunk_size =
5286           parameters->options().build_id_chunk_size_for_treehash();
5287       const size_t num_hashes = ((filesize - 1) / chunk_size) + 1;
5288       Task_token* post_hash_tasks_blocker = new Task_token(true);
5289       post_hash_tasks_blocker->add_blockers(num_hashes);
5290       this->size_of_array_of_hashes_ = num_hashes * MD5_OUTPUT_SIZE_IN_BYTES;
5291       const unsigned char* src = of->get_input_view(0, filesize);
5292       this->input_view_ = src;
5293       unsigned char *dst = new unsigned char[this->size_of_array_of_hashes_];
5294       this->array_of_hashes_ = dst;
5295       for (size_t i = 0, src_offset = 0; i < num_hashes;
5296            i++, dst += MD5_OUTPUT_SIZE_IN_BYTES, src_offset += chunk_size)
5297         {
5298           size_t size = std::min(chunk_size, filesize - src_offset);
5299           workqueue->queue(new Hash_task(src + src_offset,
5300                                          size,
5301                                          dst,
5302                                          build_id_blocker,
5303                                          post_hash_tasks_blocker));
5304         }
5305       return post_hash_tasks_blocker;
5306     }
5307   return build_id_blocker;
5308 }
5309
5310 // If a tree-style build ID was requested, the parallel part of that computation
5311 // is already done, and the final hash-of-hashes is computed here.  For other
5312 // types of build IDs, all the work is done here.
5313
5314 void
5315 Layout::write_build_id(Output_file* of) const
5316 {
5317   if (this->build_id_note_ == NULL)
5318     return;
5319
5320   unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
5321                                           this->build_id_note_->data_size());
5322
5323   if (this->array_of_hashes_ == NULL)
5324     {
5325       const size_t output_file_size = this->output_file_size();
5326       const unsigned char* iv = of->get_input_view(0, output_file_size);
5327       const char* style = parameters->options().build_id();
5328
5329       // If we get here with style == "tree" then the output must be
5330       // too small for chunking, and we use SHA-1 in that case.
5331       if ((strcmp(style, "sha1") == 0) || (strcmp(style, "tree") == 0))
5332         sha1_buffer(reinterpret_cast<const char*>(iv), output_file_size, ov);
5333       else if (strcmp(style, "md5") == 0)
5334         md5_buffer(reinterpret_cast<const char*>(iv), output_file_size, ov);
5335       else
5336         gold_unreachable();
5337
5338       of->free_input_view(0, output_file_size, iv);
5339     }
5340   else
5341     {
5342       // Non-overlapping substrings of the output file have been hashed.
5343       // Compute SHA-1 hash of the hashes.
5344       sha1_buffer(reinterpret_cast<const char*>(this->array_of_hashes_),
5345                   this->size_of_array_of_hashes_, ov);
5346       delete[] this->array_of_hashes_;
5347       of->free_input_view(0, this->output_file_size(), this->input_view_);
5348     }
5349
5350   of->write_output_view(this->build_id_note_->offset(),
5351                         this->build_id_note_->data_size(),
5352                         ov);
5353 }
5354
5355 // Write out a binary file.  This is called after the link is
5356 // complete.  IN is the temporary output file we used to generate the
5357 // ELF code.  We simply walk through the segments, read them from
5358 // their file offset in IN, and write them to their load address in
5359 // the output file.  FIXME: with a bit more work, we could support
5360 // S-records and/or Intel hex format here.
5361
5362 void
5363 Layout::write_binary(Output_file* in) const
5364 {
5365   gold_assert(parameters->options().oformat_enum()
5366               == General_options::OBJECT_FORMAT_BINARY);
5367
5368   // Get the size of the binary file.
5369   uint64_t max_load_address = 0;
5370   for (Segment_list::const_iterator p = this->segment_list_.begin();
5371        p != this->segment_list_.end();
5372        ++p)
5373     {
5374       if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
5375         {
5376           uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
5377           if (max_paddr > max_load_address)
5378             max_load_address = max_paddr;
5379         }
5380     }
5381
5382   Output_file out(parameters->options().output_file_name());
5383   out.open(max_load_address);
5384
5385   for (Segment_list::const_iterator p = this->segment_list_.begin();
5386        p != this->segment_list_.end();
5387        ++p)
5388     {
5389       if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
5390         {
5391           const unsigned char* vin = in->get_input_view((*p)->offset(),
5392                                                         (*p)->filesz());
5393           unsigned char* vout = out.get_output_view((*p)->paddr(),
5394                                                     (*p)->filesz());
5395           memcpy(vout, vin, (*p)->filesz());
5396           out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
5397           in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
5398         }
5399     }
5400
5401   out.close();
5402 }
5403
5404 // Print the output sections to the map file.
5405
5406 void
5407 Layout::print_to_mapfile(Mapfile* mapfile) const
5408 {
5409   for (Segment_list::const_iterator p = this->segment_list_.begin();
5410        p != this->segment_list_.end();
5411        ++p)
5412     (*p)->print_sections_to_mapfile(mapfile);
5413 }
5414
5415 // Print statistical information to stderr.  This is used for --stats.
5416
5417 void
5418 Layout::print_stats() const
5419 {
5420   this->namepool_.print_stats("section name pool");
5421   this->sympool_.print_stats("output symbol name pool");
5422   this->dynpool_.print_stats("dynamic name pool");
5423
5424   for (Section_list::const_iterator p = this->section_list_.begin();
5425        p != this->section_list_.end();
5426        ++p)
5427     (*p)->print_merge_stats();
5428 }
5429
5430 // Write_sections_task methods.
5431
5432 // We can always run this task.
5433
5434 Task_token*
5435 Write_sections_task::is_runnable()
5436 {
5437   return NULL;
5438 }
5439
5440 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
5441 // when finished.
5442
5443 void
5444 Write_sections_task::locks(Task_locker* tl)
5445 {
5446   tl->add(this, this->output_sections_blocker_);
5447   tl->add(this, this->final_blocker_);
5448 }
5449
5450 // Run the task--write out the data.
5451
5452 void
5453 Write_sections_task::run(Workqueue*)
5454 {
5455   this->layout_->write_output_sections(this->of_);
5456 }
5457
5458 // Write_data_task methods.
5459
5460 // We can always run this task.
5461
5462 Task_token*
5463 Write_data_task::is_runnable()
5464 {
5465   return NULL;
5466 }
5467
5468 // We need to unlock FINAL_BLOCKER when finished.
5469
5470 void
5471 Write_data_task::locks(Task_locker* tl)
5472 {
5473   tl->add(this, this->final_blocker_);
5474 }
5475
5476 // Run the task--write out the data.
5477
5478 void
5479 Write_data_task::run(Workqueue*)
5480 {
5481   this->layout_->write_data(this->symtab_, this->of_);
5482 }
5483
5484 // Write_symbols_task methods.
5485
5486 // We can always run this task.
5487
5488 Task_token*
5489 Write_symbols_task::is_runnable()
5490 {
5491   return NULL;
5492 }
5493
5494 // We need to unlock FINAL_BLOCKER when finished.
5495
5496 void
5497 Write_symbols_task::locks(Task_locker* tl)
5498 {
5499   tl->add(this, this->final_blocker_);
5500 }
5501
5502 // Run the task--write out the symbols.
5503
5504 void
5505 Write_symbols_task::run(Workqueue*)
5506 {
5507   this->symtab_->write_globals(this->sympool_, this->dynpool_,
5508                                this->layout_->symtab_xindex(),
5509                                this->layout_->dynsym_xindex(), this->of_);
5510 }
5511
5512 // Write_after_input_sections_task methods.
5513
5514 // We can only run this task after the input sections have completed.
5515
5516 Task_token*
5517 Write_after_input_sections_task::is_runnable()
5518 {
5519   if (this->input_sections_blocker_->is_blocked())
5520     return this->input_sections_blocker_;
5521   return NULL;
5522 }
5523
5524 // We need to unlock FINAL_BLOCKER when finished.
5525
5526 void
5527 Write_after_input_sections_task::locks(Task_locker* tl)
5528 {
5529   tl->add(this, this->final_blocker_);
5530 }
5531
5532 // Run the task.
5533
5534 void
5535 Write_after_input_sections_task::run(Workqueue*)
5536 {
5537   this->layout_->write_sections_after_input_sections(this->of_);
5538 }
5539
5540 // Close_task_runner methods.
5541
5542 // Finish up the build ID computation, if necessary, and write a binary file,
5543 // if necessary.  Then close the output file.
5544
5545 void
5546 Close_task_runner::run(Workqueue*, const Task*)
5547 {
5548   // At this point the multi-threaded part of the build ID computation,
5549   // if any, is done.  See queue_build_id_tasks().
5550   this->layout_->write_build_id(this->of_);
5551
5552   // If we've been asked to create a binary file, we do so here.
5553   if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
5554     this->layout_->write_binary(this->of_);
5555
5556   this->of_->close();
5557 }
5558
5559 // Instantiate the templates we need.  We could use the configure
5560 // script to restrict this to only the ones for implemented targets.
5561
5562 #ifdef HAVE_TARGET_32_LITTLE
5563 template
5564 Output_section*
5565 Layout::init_fixed_output_section<32, false>(
5566     const char* name,
5567     elfcpp::Shdr<32, false>& shdr);
5568 #endif
5569
5570 #ifdef HAVE_TARGET_32_BIG
5571 template
5572 Output_section*
5573 Layout::init_fixed_output_section<32, true>(
5574     const char* name,
5575     elfcpp::Shdr<32, true>& shdr);
5576 #endif
5577
5578 #ifdef HAVE_TARGET_64_LITTLE
5579 template
5580 Output_section*
5581 Layout::init_fixed_output_section<64, false>(
5582     const char* name,
5583     elfcpp::Shdr<64, false>& shdr);
5584 #endif
5585
5586 #ifdef HAVE_TARGET_64_BIG
5587 template
5588 Output_section*
5589 Layout::init_fixed_output_section<64, true>(
5590     const char* name,
5591     elfcpp::Shdr<64, true>& shdr);
5592 #endif
5593
5594 #ifdef HAVE_TARGET_32_LITTLE
5595 template
5596 Output_section*
5597 Layout::layout<32, false>(Sized_relobj_file<32, false>* object,
5598                           unsigned int shndx,
5599                           const char* name,
5600                           const elfcpp::Shdr<32, false>& shdr,
5601                           unsigned int, unsigned int, off_t*);
5602 #endif
5603
5604 #ifdef HAVE_TARGET_32_BIG
5605 template
5606 Output_section*
5607 Layout::layout<32, true>(Sized_relobj_file<32, true>* object,
5608                          unsigned int shndx,
5609                          const char* name,
5610                          const elfcpp::Shdr<32, true>& shdr,
5611                          unsigned int, unsigned int, off_t*);
5612 #endif
5613
5614 #ifdef HAVE_TARGET_64_LITTLE
5615 template
5616 Output_section*
5617 Layout::layout<64, false>(Sized_relobj_file<64, false>* object,
5618                           unsigned int shndx,
5619                           const char* name,
5620                           const elfcpp::Shdr<64, false>& shdr,
5621                           unsigned int, unsigned int, off_t*);
5622 #endif
5623
5624 #ifdef HAVE_TARGET_64_BIG
5625 template
5626 Output_section*
5627 Layout::layout<64, true>(Sized_relobj_file<64, true>* object,
5628                          unsigned int shndx,
5629                          const char* name,
5630                          const elfcpp::Shdr<64, true>& shdr,
5631                          unsigned int, unsigned int, off_t*);
5632 #endif
5633
5634 #ifdef HAVE_TARGET_32_LITTLE
5635 template
5636 Output_section*
5637 Layout::layout_reloc<32, false>(Sized_relobj_file<32, false>* object,
5638                                 unsigned int reloc_shndx,
5639                                 const elfcpp::Shdr<32, false>& shdr,
5640                                 Output_section* data_section,
5641                                 Relocatable_relocs* rr);
5642 #endif
5643
5644 #ifdef HAVE_TARGET_32_BIG
5645 template
5646 Output_section*
5647 Layout::layout_reloc<32, true>(Sized_relobj_file<32, true>* object,
5648                                unsigned int reloc_shndx,
5649                                const elfcpp::Shdr<32, true>& shdr,
5650                                Output_section* data_section,
5651                                Relocatable_relocs* rr);
5652 #endif
5653
5654 #ifdef HAVE_TARGET_64_LITTLE
5655 template
5656 Output_section*
5657 Layout::layout_reloc<64, false>(Sized_relobj_file<64, false>* object,
5658                                 unsigned int reloc_shndx,
5659                                 const elfcpp::Shdr<64, false>& shdr,
5660                                 Output_section* data_section,
5661                                 Relocatable_relocs* rr);
5662 #endif
5663
5664 #ifdef HAVE_TARGET_64_BIG
5665 template
5666 Output_section*
5667 Layout::layout_reloc<64, true>(Sized_relobj_file<64, true>* object,
5668                                unsigned int reloc_shndx,
5669                                const elfcpp::Shdr<64, true>& shdr,
5670                                Output_section* data_section,
5671                                Relocatable_relocs* rr);
5672 #endif
5673
5674 #ifdef HAVE_TARGET_32_LITTLE
5675 template
5676 void
5677 Layout::layout_group<32, false>(Symbol_table* symtab,
5678                                 Sized_relobj_file<32, false>* object,
5679                                 unsigned int,
5680                                 const char* group_section_name,
5681                                 const char* signature,
5682                                 const elfcpp::Shdr<32, false>& shdr,
5683                                 elfcpp::Elf_Word flags,
5684                                 std::vector<unsigned int>* shndxes);
5685 #endif
5686
5687 #ifdef HAVE_TARGET_32_BIG
5688 template
5689 void
5690 Layout::layout_group<32, true>(Symbol_table* symtab,
5691                                Sized_relobj_file<32, true>* object,
5692                                unsigned int,
5693                                const char* group_section_name,
5694                                const char* signature,
5695                                const elfcpp::Shdr<32, true>& shdr,
5696                                elfcpp::Elf_Word flags,
5697                                std::vector<unsigned int>* shndxes);
5698 #endif
5699
5700 #ifdef HAVE_TARGET_64_LITTLE
5701 template
5702 void
5703 Layout::layout_group<64, false>(Symbol_table* symtab,
5704                                 Sized_relobj_file<64, false>* object,
5705                                 unsigned int,
5706                                 const char* group_section_name,
5707                                 const char* signature,
5708                                 const elfcpp::Shdr<64, false>& shdr,
5709                                 elfcpp::Elf_Word flags,
5710                                 std::vector<unsigned int>* shndxes);
5711 #endif
5712
5713 #ifdef HAVE_TARGET_64_BIG
5714 template
5715 void
5716 Layout::layout_group<64, true>(Symbol_table* symtab,
5717                                Sized_relobj_file<64, true>* object,
5718                                unsigned int,
5719                                const char* group_section_name,
5720                                const char* signature,
5721                                const elfcpp::Shdr<64, true>& shdr,
5722                                elfcpp::Elf_Word flags,
5723                                std::vector<unsigned int>* shndxes);
5724 #endif
5725
5726 #ifdef HAVE_TARGET_32_LITTLE
5727 template
5728 Output_section*
5729 Layout::layout_eh_frame<32, false>(Sized_relobj_file<32, false>* object,
5730                                    const unsigned char* symbols,
5731                                    off_t symbols_size,
5732                                    const unsigned char* symbol_names,
5733                                    off_t symbol_names_size,
5734                                    unsigned int shndx,
5735                                    const elfcpp::Shdr<32, false>& shdr,
5736                                    unsigned int reloc_shndx,
5737                                    unsigned int reloc_type,
5738                                    off_t* off);
5739 #endif
5740
5741 #ifdef HAVE_TARGET_32_BIG
5742 template
5743 Output_section*
5744 Layout::layout_eh_frame<32, true>(Sized_relobj_file<32, true>* object,
5745                                   const unsigned char* symbols,
5746                                   off_t symbols_size,
5747                                   const unsigned char* symbol_names,
5748                                   off_t symbol_names_size,
5749                                   unsigned int shndx,
5750                                   const elfcpp::Shdr<32, true>& shdr,
5751                                   unsigned int reloc_shndx,
5752                                   unsigned int reloc_type,
5753                                   off_t* off);
5754 #endif
5755
5756 #ifdef HAVE_TARGET_64_LITTLE
5757 template
5758 Output_section*
5759 Layout::layout_eh_frame<64, false>(Sized_relobj_file<64, false>* object,
5760                                    const unsigned char* symbols,
5761                                    off_t symbols_size,
5762                                    const unsigned char* symbol_names,
5763                                    off_t symbol_names_size,
5764                                    unsigned int shndx,
5765                                    const elfcpp::Shdr<64, false>& shdr,
5766                                    unsigned int reloc_shndx,
5767                                    unsigned int reloc_type,
5768                                    off_t* off);
5769 #endif
5770
5771 #ifdef HAVE_TARGET_64_BIG
5772 template
5773 Output_section*
5774 Layout::layout_eh_frame<64, true>(Sized_relobj_file<64, true>* object,
5775                                   const unsigned char* symbols,
5776                                   off_t symbols_size,
5777                                   const unsigned char* symbol_names,
5778                                   off_t symbol_names_size,
5779                                   unsigned int shndx,
5780                                   const elfcpp::Shdr<64, true>& shdr,
5781                                   unsigned int reloc_shndx,
5782                                   unsigned int reloc_type,
5783                                   off_t* off);
5784 #endif
5785
5786 #ifdef HAVE_TARGET_32_LITTLE
5787 template
5788 void
5789 Layout::add_to_gdb_index(bool is_type_unit,
5790                          Sized_relobj<32, false>* object,
5791                          const unsigned char* symbols,
5792                          off_t symbols_size,
5793                          unsigned int shndx,
5794                          unsigned int reloc_shndx,
5795                          unsigned int reloc_type);
5796 #endif
5797
5798 #ifdef HAVE_TARGET_32_BIG
5799 template
5800 void
5801 Layout::add_to_gdb_index(bool is_type_unit,
5802                          Sized_relobj<32, true>* object,
5803                          const unsigned char* symbols,
5804                          off_t symbols_size,
5805                          unsigned int shndx,
5806                          unsigned int reloc_shndx,
5807                          unsigned int reloc_type);
5808 #endif
5809
5810 #ifdef HAVE_TARGET_64_LITTLE
5811 template
5812 void
5813 Layout::add_to_gdb_index(bool is_type_unit,
5814                          Sized_relobj<64, false>* object,
5815                          const unsigned char* symbols,
5816                          off_t symbols_size,
5817                          unsigned int shndx,
5818                          unsigned int reloc_shndx,
5819                          unsigned int reloc_type);
5820 #endif
5821
5822 #ifdef HAVE_TARGET_64_BIG
5823 template
5824 void
5825 Layout::add_to_gdb_index(bool is_type_unit,
5826                          Sized_relobj<64, true>* object,
5827                          const unsigned char* symbols,
5828                          off_t symbols_size,
5829                          unsigned int shndx,
5830                          unsigned int reloc_shndx,
5831                          unsigned int reloc_type);
5832 #endif
5833
5834 } // End namespace gold.