* layout.cc (gdb_sections): Add .debug_types.
[platform/upstream/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cerrno>
26 #include <cstring>
27 #include <algorithm>
28 #include <iostream>
29 #include <fstream>
30 #include <utility>
31 #include <fcntl.h>
32 #include <fnmatch.h>
33 #include <unistd.h>
34 #include "libiberty.h"
35 #include "md5.h"
36 #include "sha1.h"
37
38 #include "parameters.h"
39 #include "options.h"
40 #include "mapfile.h"
41 #include "script.h"
42 #include "script-sections.h"
43 #include "output.h"
44 #include "symtab.h"
45 #include "dynobj.h"
46 #include "ehframe.h"
47 #include "compressed_output.h"
48 #include "reduced_debug_output.h"
49 #include "reloc.h"
50 #include "descriptors.h"
51 #include "plugin.h"
52 #include "incremental.h"
53 #include "layout.h"
54
55 namespace gold
56 {
57
58 // Layout::Relaxation_debug_check methods.
59
60 // Check that sections and special data are in reset states.
61 // We do not save states for Output_sections and special Output_data.
62 // So we check that they have not assigned any addresses or offsets.
63 // clean_up_after_relaxation simply resets their addresses and offsets.
64 void
65 Layout::Relaxation_debug_check::check_output_data_for_reset_values(
66     const Layout::Section_list& sections,
67     const Layout::Data_list& special_outputs)
68 {
69   for(Layout::Section_list::const_iterator p = sections.begin();
70       p != sections.end();
71       ++p)
72     gold_assert((*p)->address_and_file_offset_have_reset_values());
73
74   for(Layout::Data_list::const_iterator p = special_outputs.begin();
75       p != special_outputs.end();
76       ++p)
77     gold_assert((*p)->address_and_file_offset_have_reset_values());
78 }
79   
80 // Save information of SECTIONS for checking later.
81
82 void
83 Layout::Relaxation_debug_check::read_sections(
84     const Layout::Section_list& sections)
85 {
86   for(Layout::Section_list::const_iterator p = sections.begin();
87       p != sections.end();
88       ++p)
89     {
90       Output_section* os = *p;
91       Section_info info;
92       info.output_section = os;
93       info.address = os->is_address_valid() ? os->address() : 0;
94       info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
95       info.offset = os->is_offset_valid()? os->offset() : -1 ;
96       this->section_infos_.push_back(info);
97     }
98 }
99
100 // Verify SECTIONS using previously recorded information.
101
102 void
103 Layout::Relaxation_debug_check::verify_sections(
104     const Layout::Section_list& sections)
105 {
106   size_t i = 0;
107   for(Layout::Section_list::const_iterator p = sections.begin();
108       p != sections.end();
109       ++p, ++i)
110     {
111       Output_section* os = *p;
112       uint64_t address = os->is_address_valid() ? os->address() : 0;
113       off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
114       off_t offset = os->is_offset_valid()? os->offset() : -1 ;
115
116       if (i >= this->section_infos_.size())
117         {
118           gold_fatal("Section_info of %s missing.\n", os->name());
119         }
120       const Section_info& info = this->section_infos_[i];
121       if (os != info.output_section)
122         gold_fatal("Section order changed.  Expecting %s but see %s\n",
123                    info.output_section->name(), os->name());
124       if (address != info.address
125           || data_size != info.data_size
126           || offset != info.offset)
127         gold_fatal("Section %s changed.\n", os->name());
128     }
129 }
130
131 // Layout_task_runner methods.
132
133 // Lay out the sections.  This is called after all the input objects
134 // have been read.
135
136 void
137 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
138 {
139   off_t file_size = this->layout_->finalize(this->input_objects_,
140                                             this->symtab_,
141                                             this->target_,
142                                             task);
143
144   // Now we know the final size of the output file and we know where
145   // each piece of information goes.
146
147   if (this->mapfile_ != NULL)
148     {
149       this->mapfile_->print_discarded_sections(this->input_objects_);
150       this->layout_->print_to_mapfile(this->mapfile_);
151     }
152
153   Output_file* of = new Output_file(parameters->options().output_file_name());
154   if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
155     of->set_is_temporary();
156   of->open(file_size);
157
158   // Queue up the final set of tasks.
159   gold::queue_final_tasks(this->options_, this->input_objects_,
160                           this->symtab_, this->layout_, workqueue, of);
161 }
162
163 // Layout methods.
164
165 Layout::Layout(int number_of_input_files, Script_options* script_options)
166   : number_of_input_files_(number_of_input_files),
167     script_options_(script_options),
168     namepool_(),
169     sympool_(),
170     dynpool_(),
171     signatures_(),
172     section_name_map_(),
173     segment_list_(),
174     section_list_(),
175     unattached_section_list_(),
176     special_output_list_(),
177     section_headers_(NULL),
178     tls_segment_(NULL),
179     relro_segment_(NULL),
180     increase_relro_(0),
181     symtab_section_(NULL),
182     symtab_xindex_(NULL),
183     dynsym_section_(NULL),
184     dynsym_xindex_(NULL),
185     dynamic_section_(NULL),
186     dynamic_symbol_(NULL),
187     dynamic_data_(NULL),
188     eh_frame_section_(NULL),
189     eh_frame_data_(NULL),
190     added_eh_frame_data_(false),
191     eh_frame_hdr_section_(NULL),
192     build_id_note_(NULL),
193     debug_abbrev_(NULL),
194     debug_info_(NULL),
195     group_signatures_(),
196     output_file_size_(-1),
197     have_added_input_section_(false),
198     sections_are_attached_(false),
199     input_requires_executable_stack_(false),
200     input_with_gnu_stack_note_(false),
201     input_without_gnu_stack_note_(false),
202     has_static_tls_(false),
203     any_postprocessing_sections_(false),
204     resized_signatures_(false),
205     have_stabstr_section_(false),
206     incremental_inputs_(NULL),
207     record_output_section_data_from_script_(false),
208     script_output_section_data_list_(),
209     segment_states_(NULL),
210     relaxation_debug_check_(NULL)
211 {
212   // Make space for more than enough segments for a typical file.
213   // This is just for efficiency--it's OK if we wind up needing more.
214   this->segment_list_.reserve(12);
215
216   // We expect two unattached Output_data objects: the file header and
217   // the segment headers.
218   this->special_output_list_.reserve(2);
219
220   // Initialize structure needed for an incremental build.
221   if (parameters->options().incremental())
222     this->incremental_inputs_ = new Incremental_inputs;
223
224   // The section name pool is worth optimizing in all cases, because
225   // it is small, but there are often overlaps due to .rel sections.
226   this->namepool_.set_optimize();
227 }
228
229 // Hash a key we use to look up an output section mapping.
230
231 size_t
232 Layout::Hash_key::operator()(const Layout::Key& k) const
233 {
234  return k.first + k.second.first + k.second.second;
235 }
236
237 // Returns whether the given section is in the list of
238 // debug-sections-used-by-some-version-of-gdb.  Currently,
239 // we've checked versions of gdb up to and including 6.7.1.
240
241 static const char* gdb_sections[] =
242 { ".debug_abbrev",
243   // ".debug_aranges",   // not used by gdb as of 6.7.1
244   ".debug_frame",
245   ".debug_info",
246   ".debug_types",
247   ".debug_line",
248   ".debug_loc",
249   ".debug_macinfo",
250   // ".debug_pubnames",  // not used by gdb as of 6.7.1
251   ".debug_ranges",
252   ".debug_str",
253 };
254
255 static const char* lines_only_debug_sections[] =
256 { ".debug_abbrev",
257   // ".debug_aranges",   // not used by gdb as of 6.7.1
258   // ".debug_frame",
259   ".debug_info",
260   // ".debug_types",
261   ".debug_line",
262   // ".debug_loc",
263   // ".debug_macinfo",
264   // ".debug_pubnames",  // not used by gdb as of 6.7.1
265   // ".debug_ranges",
266   ".debug_str",
267 };
268
269 static inline bool
270 is_gdb_debug_section(const char* str)
271 {
272   // We can do this faster: binary search or a hashtable.  But why bother?
273   for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
274     if (strcmp(str, gdb_sections[i]) == 0)
275       return true;
276   return false;
277 }
278
279 static inline bool
280 is_lines_only_debug_section(const char* str)
281 {
282   // We can do this faster: binary search or a hashtable.  But why bother?
283   for (size_t i = 0;
284        i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
285        ++i)
286     if (strcmp(str, lines_only_debug_sections[i]) == 0)
287       return true;
288   return false;
289 }
290
291 // Whether to include this section in the link.
292
293 template<int size, bool big_endian>
294 bool
295 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
296                         const elfcpp::Shdr<size, big_endian>& shdr)
297 {
298   if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
299     return false;
300
301   switch (shdr.get_sh_type())
302     {
303     case elfcpp::SHT_NULL:
304     case elfcpp::SHT_SYMTAB:
305     case elfcpp::SHT_DYNSYM:
306     case elfcpp::SHT_HASH:
307     case elfcpp::SHT_DYNAMIC:
308     case elfcpp::SHT_SYMTAB_SHNDX:
309       return false;
310
311     case elfcpp::SHT_STRTAB:
312       // Discard the sections which have special meanings in the ELF
313       // ABI.  Keep others (e.g., .stabstr).  We could also do this by
314       // checking the sh_link fields of the appropriate sections.
315       return (strcmp(name, ".dynstr") != 0
316               && strcmp(name, ".strtab") != 0
317               && strcmp(name, ".shstrtab") != 0);
318
319     case elfcpp::SHT_RELA:
320     case elfcpp::SHT_REL:
321     case elfcpp::SHT_GROUP:
322       // If we are emitting relocations these should be handled
323       // elsewhere.
324       gold_assert(!parameters->options().relocatable()
325                   && !parameters->options().emit_relocs());
326       return false;
327
328     case elfcpp::SHT_PROGBITS:
329       if (parameters->options().strip_debug()
330           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
331         {
332           if (is_debug_info_section(name))
333             return false;
334         }
335       if (parameters->options().strip_debug_non_line()
336           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
337         {
338           // Debugging sections can only be recognized by name.
339           if (is_prefix_of(".debug", name)
340               && !is_lines_only_debug_section(name))
341             return false;
342         }
343       if (parameters->options().strip_debug_gdb()
344           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
345         {
346           // Debugging sections can only be recognized by name.
347           if (is_prefix_of(".debug", name)
348               && !is_gdb_debug_section(name))
349             return false;
350         }
351       if (parameters->options().strip_lto_sections()
352           && !parameters->options().relocatable()
353           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
354         {
355           // Ignore LTO sections containing intermediate code.
356           if (is_prefix_of(".gnu.lto_", name))
357             return false;
358         }
359       // The GNU linker strips .gnu_debuglink sections, so we do too.
360       // This is a feature used to keep debugging information in
361       // separate files.
362       if (strcmp(name, ".gnu_debuglink") == 0)
363         return false;
364       return true;
365
366     default:
367       return true;
368     }
369 }
370
371 // Return an output section named NAME, or NULL if there is none.
372
373 Output_section*
374 Layout::find_output_section(const char* name) const
375 {
376   for (Section_list::const_iterator p = this->section_list_.begin();
377        p != this->section_list_.end();
378        ++p)
379     if (strcmp((*p)->name(), name) == 0)
380       return *p;
381   return NULL;
382 }
383
384 // Return an output segment of type TYPE, with segment flags SET set
385 // and segment flags CLEAR clear.  Return NULL if there is none.
386
387 Output_segment*
388 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
389                             elfcpp::Elf_Word clear) const
390 {
391   for (Segment_list::const_iterator p = this->segment_list_.begin();
392        p != this->segment_list_.end();
393        ++p)
394     if (static_cast<elfcpp::PT>((*p)->type()) == type
395         && ((*p)->flags() & set) == set
396         && ((*p)->flags() & clear) == 0)
397       return *p;
398   return NULL;
399 }
400
401 // Return the output section to use for section NAME with type TYPE
402 // and section flags FLAGS.  NAME must be canonicalized in the string
403 // pool, and NAME_KEY is the key.  IS_INTERP is true if this is the
404 // .interp section.  IS_DYNAMIC_LINKER_SECTION is true if this section
405 // is used by the dynamic linker.  IS_RELRO is true for a relro
406 // section.  IS_LAST_RELRO is true for the last relro section.
407 // IS_FIRST_NON_RELRO is true for the first non-relro section.
408
409 Output_section*
410 Layout::get_output_section(const char* name, Stringpool::Key name_key,
411                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
412                            bool is_interp, bool is_dynamic_linker_section,
413                            bool is_relro, bool is_last_relro,
414                            bool is_first_non_relro)
415 {
416   elfcpp::Elf_Xword lookup_flags = flags;
417
418   // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
419   // read-write with read-only sections.  Some other ELF linkers do
420   // not do this.  FIXME: Perhaps there should be an option
421   // controlling this.
422   lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
423
424   const Key key(name_key, std::make_pair(type, lookup_flags));
425   const std::pair<Key, Output_section*> v(key, NULL);
426   std::pair<Section_name_map::iterator, bool> ins(
427     this->section_name_map_.insert(v));
428
429   if (!ins.second)
430     return ins.first->second;
431   else
432     {
433       // This is the first time we've seen this name/type/flags
434       // combination.  For compatibility with the GNU linker, we
435       // combine sections with contents and zero flags with sections
436       // with non-zero flags.  This is a workaround for cases where
437       // assembler code forgets to set section flags.  FIXME: Perhaps
438       // there should be an option to control this.
439       Output_section* os = NULL;
440
441       if (type == elfcpp::SHT_PROGBITS)
442         {
443           if (flags == 0)
444             {
445               Output_section* same_name = this->find_output_section(name);
446               if (same_name != NULL
447                   && same_name->type() == elfcpp::SHT_PROGBITS
448                   && (same_name->flags() & elfcpp::SHF_TLS) == 0)
449                 os = same_name;
450             }
451           else if ((flags & elfcpp::SHF_TLS) == 0)
452             {
453               elfcpp::Elf_Xword zero_flags = 0;
454               const Key zero_key(name_key, std::make_pair(type, zero_flags));
455               Section_name_map::iterator p =
456                   this->section_name_map_.find(zero_key);
457               if (p != this->section_name_map_.end())
458                 os = p->second;
459             }
460         }
461
462       if (os == NULL)
463         os = this->make_output_section(name, type, flags, is_interp,
464                                        is_dynamic_linker_section, is_relro,
465                                        is_last_relro, is_first_non_relro);
466       ins.first->second = os;
467       return os;
468     }
469 }
470
471 // Pick the output section to use for section NAME, in input file
472 // RELOBJ, with type TYPE and flags FLAGS.  RELOBJ may be NULL for a
473 // linker created section.  IS_INPUT_SECTION is true if we are
474 // choosing an output section for an input section found in a input
475 // file.  IS_INTERP is true if this is the .interp section.
476 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
477 // dynamic linker.  IS_RELRO is true for a relro section.
478 // IS_LAST_RELRO is true for the last relro section.
479 // IS_FIRST_NON_RELRO is true for the first non-relro section.  This
480 // will return NULL if the input section should be discarded.
481
482 Output_section*
483 Layout::choose_output_section(const Relobj* relobj, const char* name,
484                               elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
485                               bool is_input_section, bool is_interp,
486                               bool is_dynamic_linker_section, bool is_relro,
487                               bool is_last_relro, bool is_first_non_relro)
488 {
489   // We should not see any input sections after we have attached
490   // sections to segments.
491   gold_assert(!is_input_section || !this->sections_are_attached_);
492
493   // Some flags in the input section should not be automatically
494   // copied to the output section.
495   flags &= ~ (elfcpp::SHF_INFO_LINK
496               | elfcpp::SHF_LINK_ORDER
497               | elfcpp::SHF_GROUP
498               | elfcpp::SHF_MERGE
499               | elfcpp::SHF_STRINGS);
500
501   if (this->script_options_->saw_sections_clause())
502     {
503       // We are using a SECTIONS clause, so the output section is
504       // chosen based only on the name.
505
506       Script_sections* ss = this->script_options_->script_sections();
507       const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
508       Output_section** output_section_slot;
509       Script_sections::Section_type script_section_type;
510       name = ss->output_section_name(file_name, name, &output_section_slot,
511                                      &script_section_type);
512       if (name == NULL)
513         {
514           // The SECTIONS clause says to discard this input section.
515           return NULL;
516         }
517
518       // We can only handle script section types ST_NONE and ST_NOLOAD.
519       switch (script_section_type)
520         {
521         case Script_sections::ST_NONE:
522           break;
523         case Script_sections::ST_NOLOAD:
524           flags &= elfcpp::SHF_ALLOC;
525           break;
526         default:
527           gold_unreachable();
528         }
529
530       // If this is an orphan section--one not mentioned in the linker
531       // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
532       // default processing below.
533
534       if (output_section_slot != NULL)
535         {
536           if (*output_section_slot != NULL)
537             {
538               (*output_section_slot)->update_flags_for_input_section(flags);
539               return *output_section_slot;
540             }
541
542           // We don't put sections found in the linker script into
543           // SECTION_NAME_MAP_.  That keeps us from getting confused
544           // if an orphan section is mapped to a section with the same
545           // name as one in the linker script.
546
547           name = this->namepool_.add(name, false, NULL);
548
549           Output_section* os =
550             this->make_output_section(name, type, flags, is_interp,
551                                       is_dynamic_linker_section, is_relro,
552                                       is_last_relro, is_first_non_relro);
553           os->set_found_in_sections_clause();
554
555           // Special handling for NOLOAD sections.
556           if (script_section_type == Script_sections::ST_NOLOAD)
557             {
558               os->set_is_noload();
559
560               // The constructor of Output_section sets addresses of non-ALLOC
561               // sections to 0 by default.  We don't want that for NOLOAD
562               // sections even if they have no SHF_ALLOC flag.
563               if ((os->flags() & elfcpp::SHF_ALLOC) == 0
564                   && os->is_address_valid())
565                 {
566                   gold_assert(os->address() == 0
567                               && !os->is_offset_valid()
568                               && !os->is_data_size_valid());
569                   os->reset_address_and_file_offset();
570                 }
571             }
572
573           *output_section_slot = os;
574           return os;
575         }
576     }
577
578   // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
579
580   // Turn NAME from the name of the input section into the name of the
581   // output section.
582
583   size_t len = strlen(name);
584   if (is_input_section
585       && !this->script_options_->saw_sections_clause()
586       && !parameters->options().relocatable())
587     name = Layout::output_section_name(name, &len);
588
589   Stringpool::Key name_key;
590   name = this->namepool_.add_with_length(name, len, true, &name_key);
591
592   // Find or make the output section.  The output section is selected
593   // based on the section name, type, and flags.
594   return this->get_output_section(name, name_key, type, flags, is_interp,
595                                   is_dynamic_linker_section, is_relro,
596                                   is_last_relro, is_first_non_relro);
597 }
598
599 // Return the output section to use for input section SHNDX, with name
600 // NAME, with header HEADER, from object OBJECT.  RELOC_SHNDX is the
601 // index of a relocation section which applies to this section, or 0
602 // if none, or -1U if more than one.  RELOC_TYPE is the type of the
603 // relocation section if there is one.  Set *OFF to the offset of this
604 // input section without the output section.  Return NULL if the
605 // section should be discarded.  Set *OFF to -1 if the section
606 // contents should not be written directly to the output file, but
607 // will instead receive special handling.
608
609 template<int size, bool big_endian>
610 Output_section*
611 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
612                const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
613                unsigned int reloc_shndx, unsigned int, off_t* off)
614 {
615   *off = 0;
616
617   if (!this->include_section(object, name, shdr))
618     return NULL;
619
620   Output_section* os;
621
622   // Sometimes .init_array*, .preinit_array* and .fini_array* do not have
623   // correct section types.  Force them here.
624   elfcpp::Elf_Word sh_type = shdr.get_sh_type();
625   if (sh_type == elfcpp::SHT_PROGBITS)
626     {
627       static const char init_array_prefix[] = ".init_array";
628       static const char preinit_array_prefix[] = ".preinit_array";
629       static const char fini_array_prefix[] = ".fini_array";
630       static size_t init_array_prefix_size = sizeof(init_array_prefix) - 1;
631       static size_t preinit_array_prefix_size =
632         sizeof(preinit_array_prefix) - 1;
633       static size_t fini_array_prefix_size = sizeof(fini_array_prefix) - 1;
634
635       if (strncmp(name, init_array_prefix, init_array_prefix_size) == 0)
636         sh_type = elfcpp::SHT_INIT_ARRAY;
637       else if (strncmp(name, preinit_array_prefix, preinit_array_prefix_size)
638                == 0)
639         sh_type = elfcpp::SHT_PREINIT_ARRAY;
640       else if (strncmp(name, fini_array_prefix, fini_array_prefix_size) == 0)
641         sh_type = elfcpp::SHT_FINI_ARRAY;
642     }
643
644   // In a relocatable link a grouped section must not be combined with
645   // any other sections.
646   if (parameters->options().relocatable()
647       && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
648     {
649       name = this->namepool_.add(name, true, NULL);
650       os = this->make_output_section(name, sh_type, shdr.get_sh_flags(), false,
651                                      false, false, false, false);
652     }
653   else
654     {
655       os = this->choose_output_section(object, name, sh_type,
656                                        shdr.get_sh_flags(), true, false,
657                                        false, false, false, false);
658       if (os == NULL)
659         return NULL;
660     }
661
662   // By default the GNU linker sorts input sections whose names match
663   // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*.  The sections
664   // are sorted by name.  This is used to implement constructor
665   // priority ordering.  We are compatible.
666   if (!this->script_options_->saw_sections_clause()
667       && (is_prefix_of(".ctors.", name)
668           || is_prefix_of(".dtors.", name)
669           || is_prefix_of(".init_array.", name)
670           || is_prefix_of(".fini_array.", name)))
671     os->set_must_sort_attached_input_sections();
672
673   // FIXME: Handle SHF_LINK_ORDER somewhere.
674
675   *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
676                                this->script_options_->saw_sections_clause());
677   this->have_added_input_section_ = true;
678
679   return os;
680 }
681
682 // Handle a relocation section when doing a relocatable link.
683
684 template<int size, bool big_endian>
685 Output_section*
686 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
687                      unsigned int,
688                      const elfcpp::Shdr<size, big_endian>& shdr,
689                      Output_section* data_section,
690                      Relocatable_relocs* rr)
691 {
692   gold_assert(parameters->options().relocatable()
693               || parameters->options().emit_relocs());
694
695   int sh_type = shdr.get_sh_type();
696
697   std::string name;
698   if (sh_type == elfcpp::SHT_REL)
699     name = ".rel";
700   else if (sh_type == elfcpp::SHT_RELA)
701     name = ".rela";
702   else
703     gold_unreachable();
704   name += data_section->name();
705
706   // In a relocatable link relocs for a grouped section must not be
707   // combined with other reloc sections.
708   Output_section* os;
709   if (!parameters->options().relocatable()
710       || (data_section->flags() & elfcpp::SHF_GROUP) == 0)
711     os = this->choose_output_section(object, name.c_str(), sh_type,
712                                      shdr.get_sh_flags(), false, false,
713                                      false, false, false, false);
714   else
715     {
716       const char* n = this->namepool_.add(name.c_str(), true, NULL);
717       os = this->make_output_section(n, sh_type, shdr.get_sh_flags(),
718                                      false, false, false, false, false);
719     }
720
721   os->set_should_link_to_symtab();
722   os->set_info_section(data_section);
723
724   Output_section_data* posd;
725   if (sh_type == elfcpp::SHT_REL)
726     {
727       os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
728       posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
729                                            size,
730                                            big_endian>(rr);
731     }
732   else if (sh_type == elfcpp::SHT_RELA)
733     {
734       os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
735       posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
736                                            size,
737                                            big_endian>(rr);
738     }
739   else
740     gold_unreachable();
741
742   os->add_output_section_data(posd);
743   rr->set_output_data(posd);
744
745   return os;
746 }
747
748 // Handle a group section when doing a relocatable link.
749
750 template<int size, bool big_endian>
751 void
752 Layout::layout_group(Symbol_table* symtab,
753                      Sized_relobj<size, big_endian>* object,
754                      unsigned int,
755                      const char* group_section_name,
756                      const char* signature,
757                      const elfcpp::Shdr<size, big_endian>& shdr,
758                      elfcpp::Elf_Word flags,
759                      std::vector<unsigned int>* shndxes)
760 {
761   gold_assert(parameters->options().relocatable());
762   gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
763   group_section_name = this->namepool_.add(group_section_name, true, NULL);
764   Output_section* os = this->make_output_section(group_section_name,
765                                                  elfcpp::SHT_GROUP,
766                                                  shdr.get_sh_flags(),
767                                                  false, false, false,
768                                                  false, false);
769
770   // We need to find a symbol with the signature in the symbol table.
771   // If we don't find one now, we need to look again later.
772   Symbol* sym = symtab->lookup(signature, NULL);
773   if (sym != NULL)
774     os->set_info_symndx(sym);
775   else
776     {
777       // Reserve some space to minimize reallocations.
778       if (this->group_signatures_.empty())
779         this->group_signatures_.reserve(this->number_of_input_files_ * 16);
780
781       // We will wind up using a symbol whose name is the signature.
782       // So just put the signature in the symbol name pool to save it.
783       signature = symtab->canonicalize_name(signature);
784       this->group_signatures_.push_back(Group_signature(os, signature));
785     }
786
787   os->set_should_link_to_symtab();
788   os->set_entsize(4);
789
790   section_size_type entry_count =
791     convert_to_section_size_type(shdr.get_sh_size() / 4);
792   Output_section_data* posd =
793     new Output_data_group<size, big_endian>(object, entry_count, flags,
794                                             shndxes);
795   os->add_output_section_data(posd);
796 }
797
798 // Special GNU handling of sections name .eh_frame.  They will
799 // normally hold exception frame data as defined by the C++ ABI
800 // (http://codesourcery.com/cxx-abi/).
801
802 template<int size, bool big_endian>
803 Output_section*
804 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
805                         const unsigned char* symbols,
806                         off_t symbols_size,
807                         const unsigned char* symbol_names,
808                         off_t symbol_names_size,
809                         unsigned int shndx,
810                         const elfcpp::Shdr<size, big_endian>& shdr,
811                         unsigned int reloc_shndx, unsigned int reloc_type,
812                         off_t* off)
813 {
814   gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
815   gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
816
817   const char* const name = ".eh_frame";
818   Output_section* os = this->choose_output_section(object,
819                                                    name,
820                                                    elfcpp::SHT_PROGBITS,
821                                                    elfcpp::SHF_ALLOC,
822                                                    false, false, false,
823                                                    false, false, false);
824   if (os == NULL)
825     return NULL;
826
827   if (this->eh_frame_section_ == NULL)
828     {
829       this->eh_frame_section_ = os;
830       this->eh_frame_data_ = new Eh_frame();
831
832       if (parameters->options().eh_frame_hdr())
833         {
834           Output_section* hdr_os =
835             this->choose_output_section(NULL,
836                                         ".eh_frame_hdr",
837                                         elfcpp::SHT_PROGBITS,
838                                         elfcpp::SHF_ALLOC,
839                                         false, false, false,
840                                         false, false, false);
841
842           if (hdr_os != NULL)
843             {
844               Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
845                                                         this->eh_frame_data_);
846               hdr_os->add_output_section_data(hdr_posd);
847
848               hdr_os->set_after_input_sections();
849
850               if (!this->script_options_->saw_phdrs_clause())
851                 {
852                   Output_segment* hdr_oseg;
853                   hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
854                                                        elfcpp::PF_R);
855                   hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R, false);
856                 }
857
858               this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
859             }
860         }
861     }
862
863   gold_assert(this->eh_frame_section_ == os);
864
865   if (this->eh_frame_data_->add_ehframe_input_section(object,
866                                                       symbols,
867                                                       symbols_size,
868                                                       symbol_names,
869                                                       symbol_names_size,
870                                                       shndx,
871                                                       reloc_shndx,
872                                                       reloc_type))
873     {
874       os->update_flags_for_input_section(shdr.get_sh_flags());
875
876       // We found a .eh_frame section we are going to optimize, so now
877       // we can add the set of optimized sections to the output
878       // section.  We need to postpone adding this until we've found a
879       // section we can optimize so that the .eh_frame section in
880       // crtbegin.o winds up at the start of the output section.
881       if (!this->added_eh_frame_data_)
882         {
883           os->add_output_section_data(this->eh_frame_data_);
884           this->added_eh_frame_data_ = true;
885         }
886       *off = -1;
887     }
888   else
889     {
890       // We couldn't handle this .eh_frame section for some reason.
891       // Add it as a normal section.
892       bool saw_sections_clause = this->script_options_->saw_sections_clause();
893       *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
894                                    saw_sections_clause);
895       this->have_added_input_section_ = true;
896     }
897
898   return os;
899 }
900
901 // Add POSD to an output section using NAME, TYPE, and FLAGS.  Return
902 // the output section.
903
904 Output_section*
905 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
906                                 elfcpp::Elf_Xword flags,
907                                 Output_section_data* posd,
908                                 bool is_dynamic_linker_section,
909                                 bool is_relro, bool is_last_relro,
910                                 bool is_first_non_relro)
911 {
912   Output_section* os = this->choose_output_section(NULL, name, type, flags,
913                                                    false, false,
914                                                    is_dynamic_linker_section,
915                                                    is_relro, is_last_relro,
916                                                    is_first_non_relro);
917   if (os != NULL)
918     os->add_output_section_data(posd);
919   return os;
920 }
921
922 // Map section flags to segment flags.
923
924 elfcpp::Elf_Word
925 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
926 {
927   elfcpp::Elf_Word ret = elfcpp::PF_R;
928   if ((flags & elfcpp::SHF_WRITE) != 0)
929     ret |= elfcpp::PF_W;
930   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
931     ret |= elfcpp::PF_X;
932   return ret;
933 }
934
935 // Sometimes we compress sections.  This is typically done for
936 // sections that are not part of normal program execution (such as
937 // .debug_* sections), and where the readers of these sections know
938 // how to deal with compressed sections.  This routine doesn't say for
939 // certain whether we'll compress -- it depends on commandline options
940 // as well -- just whether this section is a candidate for compression.
941 // (The Output_compressed_section class decides whether to compress
942 // a given section, and picks the name of the compressed section.)
943
944 static bool
945 is_compressible_debug_section(const char* secname)
946 {
947   return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
948 }
949
950 // Make a new Output_section, and attach it to segments as
951 // appropriate.  IS_INTERP is true if this is the .interp section.
952 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
953 // dynamic linker.  IS_RELRO is true if this is a relro section.
954 // IS_LAST_RELRO is true if this is the last relro section.
955 // IS_FIRST_NON_RELRO is true if this is the first non relro section.
956
957 Output_section*
958 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
959                             elfcpp::Elf_Xword flags, bool is_interp,
960                             bool is_dynamic_linker_section, bool is_relro,
961                             bool is_last_relro, bool is_first_non_relro)
962 {
963   Output_section* os;
964   if ((flags & elfcpp::SHF_ALLOC) == 0
965       && strcmp(parameters->options().compress_debug_sections(), "none") != 0
966       && is_compressible_debug_section(name))
967     os = new Output_compressed_section(&parameters->options(), name, type,
968                                        flags);
969   else if ((flags & elfcpp::SHF_ALLOC) == 0
970            && parameters->options().strip_debug_non_line()
971            && strcmp(".debug_abbrev", name) == 0)
972     {
973       os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
974           name, type, flags);
975       if (this->debug_info_)
976         this->debug_info_->set_abbreviations(this->debug_abbrev_);
977     }
978   else if ((flags & elfcpp::SHF_ALLOC) == 0
979            && parameters->options().strip_debug_non_line()
980            && strcmp(".debug_info", name) == 0)
981     {
982       os = this->debug_info_ = new Output_reduced_debug_info_section(
983           name, type, flags);
984       if (this->debug_abbrev_)
985         this->debug_info_->set_abbreviations(this->debug_abbrev_);
986     }
987  else
988     {
989       // FIXME: const_cast is ugly.
990       Target* target = const_cast<Target*>(&parameters->target());
991       os = target->make_output_section(name, type, flags);
992     }
993
994   if (is_interp)
995     os->set_is_interp();
996   if (is_dynamic_linker_section)
997     os->set_is_dynamic_linker_section();
998   if (is_relro)
999     os->set_is_relro();
1000   if (is_last_relro)
1001     os->set_is_last_relro();
1002   if (is_first_non_relro)
1003     os->set_is_first_non_relro();
1004
1005   parameters->target().new_output_section(os);
1006
1007   this->section_list_.push_back(os);
1008
1009   // The GNU linker by default sorts some sections by priority, so we
1010   // do the same.  We need to know that this might happen before we
1011   // attach any input sections.
1012   if (!this->script_options_->saw_sections_clause()
1013       && (strcmp(name, ".ctors") == 0
1014           || strcmp(name, ".dtors") == 0
1015           || strcmp(name, ".init_array") == 0
1016           || strcmp(name, ".fini_array") == 0))
1017     os->set_may_sort_attached_input_sections();
1018
1019   // With -z relro, we have to recognize the special sections by name.
1020   // There is no other way.
1021   if (!this->script_options_->saw_sections_clause()
1022       && parameters->options().relro()
1023       && type == elfcpp::SHT_PROGBITS
1024       && (flags & elfcpp::SHF_ALLOC) != 0
1025       && (flags & elfcpp::SHF_WRITE) != 0)
1026     {
1027       if (strcmp(name, ".data.rel.ro") == 0)
1028         os->set_is_relro();
1029       else if (strcmp(name, ".data.rel.ro.local") == 0)
1030         {
1031           os->set_is_relro();
1032           os->set_is_relro_local();
1033         }
1034     }
1035
1036   // Check for .stab*str sections, as .stab* sections need to link to
1037   // them.
1038   if (type == elfcpp::SHT_STRTAB
1039       && !this->have_stabstr_section_
1040       && strncmp(name, ".stab", 5) == 0
1041       && strcmp(name + strlen(name) - 3, "str") == 0)
1042     this->have_stabstr_section_ = true;
1043
1044   // If we have already attached the sections to segments, then we
1045   // need to attach this one now.  This happens for sections created
1046   // directly by the linker.
1047   if (this->sections_are_attached_)
1048     this->attach_section_to_segment(os);
1049
1050   return os;
1051 }
1052
1053 // Attach output sections to segments.  This is called after we have
1054 // seen all the input sections.
1055
1056 void
1057 Layout::attach_sections_to_segments()
1058 {
1059   for (Section_list::iterator p = this->section_list_.begin();
1060        p != this->section_list_.end();
1061        ++p)
1062     this->attach_section_to_segment(*p);
1063
1064   this->sections_are_attached_ = true;
1065 }
1066
1067 // Attach an output section to a segment.
1068
1069 void
1070 Layout::attach_section_to_segment(Output_section* os)
1071 {
1072   if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1073     this->unattached_section_list_.push_back(os);
1074   else
1075     this->attach_allocated_section_to_segment(os);
1076 }
1077
1078 // Attach an allocated output section to a segment.
1079
1080 void
1081 Layout::attach_allocated_section_to_segment(Output_section* os)
1082 {
1083   elfcpp::Elf_Xword flags = os->flags();
1084   gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
1085
1086   if (parameters->options().relocatable())
1087     return;
1088
1089   // If we have a SECTIONS clause, we can't handle the attachment to
1090   // segments until after we've seen all the sections.
1091   if (this->script_options_->saw_sections_clause())
1092     return;
1093
1094   gold_assert(!this->script_options_->saw_phdrs_clause());
1095
1096   // This output section goes into a PT_LOAD segment.
1097
1098   elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
1099
1100   // Check for --section-start.
1101   uint64_t addr;
1102   bool is_address_set = parameters->options().section_start(os->name(), &addr);
1103
1104   // In general the only thing we really care about for PT_LOAD
1105   // segments is whether or not they are writable, so that is how we
1106   // search for them.  Large data sections also go into their own
1107   // PT_LOAD segment.  People who need segments sorted on some other
1108   // basis will have to use a linker script.
1109
1110   Segment_list::const_iterator p;
1111   for (p = this->segment_list_.begin();
1112        p != this->segment_list_.end();
1113        ++p)
1114     {
1115       if ((*p)->type() != elfcpp::PT_LOAD)
1116         continue;
1117       if (!parameters->options().omagic()
1118           && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1119         continue;
1120       // If -Tbss was specified, we need to separate the data and BSS
1121       // segments.
1122       if (parameters->options().user_set_Tbss())
1123         {
1124           if ((os->type() == elfcpp::SHT_NOBITS)
1125               == (*p)->has_any_data_sections())
1126             continue;
1127         }
1128       if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1129         continue;
1130
1131       if (is_address_set)
1132         {
1133           if ((*p)->are_addresses_set())
1134             continue;
1135
1136           (*p)->add_initial_output_data(os);
1137           (*p)->update_flags_for_output_section(seg_flags);
1138           (*p)->set_addresses(addr, addr);
1139           break;
1140         }
1141
1142       (*p)->add_output_section(os, seg_flags, true);
1143       break;
1144     }
1145
1146   if (p == this->segment_list_.end())
1147     {
1148       Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1149                                                        seg_flags);
1150       if (os->is_large_data_section())
1151         oseg->set_is_large_data_segment();
1152       oseg->add_output_section(os, seg_flags, true);
1153       if (is_address_set)
1154         oseg->set_addresses(addr, addr);
1155     }
1156
1157   // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1158   // segment.
1159   if (os->type() == elfcpp::SHT_NOTE)
1160     {
1161       // See if we already have an equivalent PT_NOTE segment.
1162       for (p = this->segment_list_.begin();
1163            p != segment_list_.end();
1164            ++p)
1165         {
1166           if ((*p)->type() == elfcpp::PT_NOTE
1167               && (((*p)->flags() & elfcpp::PF_W)
1168                   == (seg_flags & elfcpp::PF_W)))
1169             {
1170               (*p)->add_output_section(os, seg_flags, false);
1171               break;
1172             }
1173         }
1174
1175       if (p == this->segment_list_.end())
1176         {
1177           Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1178                                                            seg_flags);
1179           oseg->add_output_section(os, seg_flags, false);
1180         }
1181     }
1182
1183   // If we see a loadable SHF_TLS section, we create a PT_TLS
1184   // segment.  There can only be one such segment.
1185   if ((flags & elfcpp::SHF_TLS) != 0)
1186     {
1187       if (this->tls_segment_ == NULL)
1188         this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1189       this->tls_segment_->add_output_section(os, seg_flags, false);
1190     }
1191
1192   // If -z relro is in effect, and we see a relro section, we create a
1193   // PT_GNU_RELRO segment.  There can only be one such segment.
1194   if (os->is_relro() && parameters->options().relro())
1195     {
1196       gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1197       if (this->relro_segment_ == NULL)
1198         this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1199       this->relro_segment_->add_output_section(os, seg_flags, false);
1200     }
1201 }
1202
1203 // Make an output section for a script.
1204
1205 Output_section*
1206 Layout::make_output_section_for_script(
1207     const char* name,
1208     Script_sections::Section_type section_type)
1209 {
1210   name = this->namepool_.add(name, false, NULL);
1211   elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
1212   if (section_type == Script_sections::ST_NOLOAD)
1213     sh_flags = 0;
1214   Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1215                                                  sh_flags, false,
1216                                                  false, false, false, false);
1217   os->set_found_in_sections_clause();
1218   if (section_type == Script_sections::ST_NOLOAD)
1219     os->set_is_noload();
1220   return os;
1221 }
1222
1223 // Return the number of segments we expect to see.
1224
1225 size_t
1226 Layout::expected_segment_count() const
1227 {
1228   size_t ret = this->segment_list_.size();
1229
1230   // If we didn't see a SECTIONS clause in a linker script, we should
1231   // already have the complete list of segments.  Otherwise we ask the
1232   // SECTIONS clause how many segments it expects, and add in the ones
1233   // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1234
1235   if (!this->script_options_->saw_sections_clause())
1236     return ret;
1237   else
1238     {
1239       const Script_sections* ss = this->script_options_->script_sections();
1240       return ret + ss->expected_segment_count(this);
1241     }
1242 }
1243
1244 // Handle the .note.GNU-stack section at layout time.  SEEN_GNU_STACK
1245 // is whether we saw a .note.GNU-stack section in the object file.
1246 // GNU_STACK_FLAGS is the section flags.  The flags give the
1247 // protection required for stack memory.  We record this in an
1248 // executable as a PT_GNU_STACK segment.  If an object file does not
1249 // have a .note.GNU-stack segment, we must assume that it is an old
1250 // object.  On some targets that will force an executable stack.
1251
1252 void
1253 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1254 {
1255   if (!seen_gnu_stack)
1256     this->input_without_gnu_stack_note_ = true;
1257   else
1258     {
1259       this->input_with_gnu_stack_note_ = true;
1260       if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1261         this->input_requires_executable_stack_ = true;
1262     }
1263 }
1264
1265 // Create automatic note sections.
1266
1267 void
1268 Layout::create_notes()
1269 {
1270   this->create_gold_note();
1271   this->create_executable_stack_info();
1272   this->create_build_id();
1273 }
1274
1275 // Create the dynamic sections which are needed before we read the
1276 // relocs.
1277
1278 void
1279 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1280 {
1281   if (parameters->doing_static_link())
1282     return;
1283
1284   this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1285                                                        elfcpp::SHT_DYNAMIC,
1286                                                        (elfcpp::SHF_ALLOC
1287                                                         | elfcpp::SHF_WRITE),
1288                                                        false, false, true,
1289                                                        true, false, false);
1290
1291   this->dynamic_symbol_ =
1292     symtab->define_in_output_data("_DYNAMIC", NULL, Symbol_table::PREDEFINED,
1293                                   this->dynamic_section_, 0, 0,
1294                                   elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1295                                   elfcpp::STV_HIDDEN, 0, false, false);
1296
1297   this->dynamic_data_ =  new Output_data_dynamic(&this->dynpool_);
1298
1299   this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1300 }
1301
1302 // For each output section whose name can be represented as C symbol,
1303 // define __start and __stop symbols for the section.  This is a GNU
1304 // extension.
1305
1306 void
1307 Layout::define_section_symbols(Symbol_table* symtab)
1308 {
1309   for (Section_list::const_iterator p = this->section_list_.begin();
1310        p != this->section_list_.end();
1311        ++p)
1312     {
1313       const char* const name = (*p)->name();
1314       if (is_cident(name))
1315         {
1316           const std::string name_string(name);
1317           const std::string start_name(cident_section_start_prefix
1318                                        + name_string);
1319           const std::string stop_name(cident_section_stop_prefix
1320                                       + name_string);
1321
1322           symtab->define_in_output_data(start_name.c_str(),
1323                                         NULL, // version
1324                                         Symbol_table::PREDEFINED,
1325                                         *p,
1326                                         0, // value
1327                                         0, // symsize
1328                                         elfcpp::STT_NOTYPE,
1329                                         elfcpp::STB_GLOBAL,
1330                                         elfcpp::STV_DEFAULT,
1331                                         0, // nonvis
1332                                         false, // offset_is_from_end
1333                                         true); // only_if_ref
1334
1335           symtab->define_in_output_data(stop_name.c_str(),
1336                                         NULL, // version
1337                                         Symbol_table::PREDEFINED,
1338                                         *p,
1339                                         0, // value
1340                                         0, // symsize
1341                                         elfcpp::STT_NOTYPE,
1342                                         elfcpp::STB_GLOBAL,
1343                                         elfcpp::STV_DEFAULT,
1344                                         0, // nonvis
1345                                         true, // offset_is_from_end
1346                                         true); // only_if_ref
1347         }
1348     }
1349 }
1350
1351 // Define symbols for group signatures.
1352
1353 void
1354 Layout::define_group_signatures(Symbol_table* symtab)
1355 {
1356   for (Group_signatures::iterator p = this->group_signatures_.begin();
1357        p != this->group_signatures_.end();
1358        ++p)
1359     {
1360       Symbol* sym = symtab->lookup(p->signature, NULL);
1361       if (sym != NULL)
1362         p->section->set_info_symndx(sym);
1363       else
1364         {
1365           // Force the name of the group section to the group
1366           // signature, and use the group's section symbol as the
1367           // signature symbol.
1368           if (strcmp(p->section->name(), p->signature) != 0)
1369             {
1370               const char* name = this->namepool_.add(p->signature,
1371                                                      true, NULL);
1372               p->section->set_name(name);
1373             }
1374           p->section->set_needs_symtab_index();
1375           p->section->set_info_section_symndx(p->section);
1376         }
1377     }
1378
1379   this->group_signatures_.clear();
1380 }
1381
1382 // Find the first read-only PT_LOAD segment, creating one if
1383 // necessary.
1384
1385 Output_segment*
1386 Layout::find_first_load_seg()
1387 {
1388   for (Segment_list::const_iterator p = this->segment_list_.begin();
1389        p != this->segment_list_.end();
1390        ++p)
1391     {
1392       if ((*p)->type() == elfcpp::PT_LOAD
1393           && ((*p)->flags() & elfcpp::PF_R) != 0
1394           && (parameters->options().omagic()
1395               || ((*p)->flags() & elfcpp::PF_W) == 0))
1396         return *p;
1397     }
1398
1399   gold_assert(!this->script_options_->saw_phdrs_clause());
1400
1401   Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1402                                                        elfcpp::PF_R);
1403   return load_seg;
1404 }
1405
1406 // Save states of all current output segments.  Store saved states
1407 // in SEGMENT_STATES.
1408
1409 void
1410 Layout::save_segments(Segment_states* segment_states)
1411 {
1412   for (Segment_list::const_iterator p = this->segment_list_.begin();
1413        p != this->segment_list_.end();
1414        ++p)
1415     {
1416       Output_segment* segment = *p;
1417       // Shallow copy.
1418       Output_segment* copy = new Output_segment(*segment);
1419       (*segment_states)[segment] = copy;
1420     }
1421 }
1422
1423 // Restore states of output segments and delete any segment not found in
1424 // SEGMENT_STATES.
1425
1426 void
1427 Layout::restore_segments(const Segment_states* segment_states)
1428 {
1429   // Go through the segment list and remove any segment added in the
1430   // relaxation loop.
1431   this->tls_segment_ = NULL;
1432   this->relro_segment_ = NULL;
1433   Segment_list::iterator list_iter = this->segment_list_.begin();
1434   while (list_iter != this->segment_list_.end())
1435     {
1436       Output_segment* segment = *list_iter;
1437       Segment_states::const_iterator states_iter =
1438           segment_states->find(segment);
1439       if (states_iter != segment_states->end())
1440         {
1441           const Output_segment* copy = states_iter->second;
1442           // Shallow copy to restore states.
1443           *segment = *copy;
1444
1445           // Also fix up TLS and RELRO segment pointers as appropriate.
1446           if (segment->type() == elfcpp::PT_TLS)
1447             this->tls_segment_ = segment;
1448           else if (segment->type() == elfcpp::PT_GNU_RELRO)
1449             this->relro_segment_ = segment;
1450
1451           ++list_iter;
1452         } 
1453       else
1454         {
1455           list_iter = this->segment_list_.erase(list_iter); 
1456           // This is a segment created during section layout.  It should be
1457           // safe to remove it since we should have removed all pointers to it.
1458           delete segment;
1459         }
1460     }
1461 }
1462
1463 // Clean up after relaxation so that sections can be laid out again.
1464
1465 void
1466 Layout::clean_up_after_relaxation()
1467 {
1468   // Restore the segments to point state just prior to the relaxation loop.
1469   Script_sections* script_section = this->script_options_->script_sections();
1470   script_section->release_segments();
1471   this->restore_segments(this->segment_states_);
1472
1473   // Reset section addresses and file offsets
1474   for (Section_list::iterator p = this->section_list_.begin();
1475        p != this->section_list_.end();
1476        ++p)
1477     {
1478       (*p)->restore_states();
1479
1480       // If an input section changes size because of relaxation,
1481       // we need to adjust the section offsets of all input sections.
1482       // after such a section.
1483       if ((*p)->section_offsets_need_adjustment())
1484         (*p)->adjust_section_offsets();
1485
1486       (*p)->reset_address_and_file_offset();
1487     }
1488   
1489   // Reset special output object address and file offsets.
1490   for (Data_list::iterator p = this->special_output_list_.begin();
1491        p != this->special_output_list_.end();
1492        ++p)
1493     (*p)->reset_address_and_file_offset();
1494
1495   // A linker script may have created some output section data objects.
1496   // They are useless now.
1497   for (Output_section_data_list::const_iterator p =
1498          this->script_output_section_data_list_.begin();
1499        p != this->script_output_section_data_list_.end();
1500        ++p)
1501     delete *p;
1502   this->script_output_section_data_list_.clear(); 
1503 }
1504
1505 // Prepare for relaxation.
1506
1507 void
1508 Layout::prepare_for_relaxation()
1509 {
1510   // Create an relaxation debug check if in debugging mode.
1511   if (is_debugging_enabled(DEBUG_RELAXATION))
1512     this->relaxation_debug_check_ = new Relaxation_debug_check();
1513
1514   // Save segment states.
1515   this->segment_states_ = new Segment_states();
1516   this->save_segments(this->segment_states_);
1517
1518   for(Section_list::const_iterator p = this->section_list_.begin();
1519       p != this->section_list_.end();
1520       ++p)
1521     (*p)->save_states();
1522
1523   if (is_debugging_enabled(DEBUG_RELAXATION))
1524     this->relaxation_debug_check_->check_output_data_for_reset_values(
1525         this->section_list_, this->special_output_list_);
1526
1527   // Also enable recording of output section data from scripts.
1528   this->record_output_section_data_from_script_ = true;
1529 }
1530
1531 // Relaxation loop body:  If target has no relaxation, this runs only once
1532 // Otherwise, the target relaxation hook is called at the end of
1533 // each iteration.  If the hook returns true, it means re-layout of
1534 // section is required.  
1535 //
1536 // The number of segments created by a linking script without a PHDRS
1537 // clause may be affected by section sizes and alignments.  There is
1538 // a remote chance that relaxation causes different number of PT_LOAD
1539 // segments are created and sections are attached to different segments.
1540 // Therefore, we always throw away all segments created during section
1541 // layout.  In order to be able to restart the section layout, we keep
1542 // a copy of the segment list right before the relaxation loop and use
1543 // that to restore the segments.
1544 // 
1545 // PASS is the current relaxation pass number. 
1546 // SYMTAB is a symbol table.
1547 // PLOAD_SEG is the address of a pointer for the load segment.
1548 // PHDR_SEG is a pointer to the PHDR segment.
1549 // SEGMENT_HEADERS points to the output segment header.
1550 // FILE_HEADER points to the output file header.
1551 // PSHNDX is the address to store the output section index.
1552
1553 off_t inline
1554 Layout::relaxation_loop_body(
1555     int pass,
1556     Target* target,
1557     Symbol_table* symtab,
1558     Output_segment** pload_seg,
1559     Output_segment* phdr_seg,
1560     Output_segment_headers* segment_headers,
1561     Output_file_header* file_header,
1562     unsigned int* pshndx)
1563 {
1564   // If this is not the first iteration, we need to clean up after
1565   // relaxation so that we can lay out the sections again.
1566   if (pass != 0)
1567     this->clean_up_after_relaxation();
1568
1569   // If there is a SECTIONS clause, put all the input sections into
1570   // the required order.
1571   Output_segment* load_seg;
1572   if (this->script_options_->saw_sections_clause())
1573     load_seg = this->set_section_addresses_from_script(symtab);
1574   else if (parameters->options().relocatable())
1575     load_seg = NULL;
1576   else
1577     load_seg = this->find_first_load_seg();
1578
1579   if (parameters->options().oformat_enum()
1580       != General_options::OBJECT_FORMAT_ELF)
1581     load_seg = NULL;
1582
1583   // If the user set the address of the text segment, that may not be
1584   // compatible with putting the segment headers and file headers into
1585   // that segment.
1586   if (parameters->options().user_set_Ttext())
1587     load_seg = NULL;
1588
1589   gold_assert(phdr_seg == NULL
1590               || load_seg != NULL
1591               || this->script_options_->saw_sections_clause());
1592
1593   // If the address of the load segment we found has been set by
1594   // --section-start rather than by a script, then we don't want to
1595   // use it for the file and segment headers.
1596   if (load_seg != NULL
1597       && load_seg->are_addresses_set()
1598       && !this->script_options_->saw_sections_clause())
1599     load_seg = NULL;
1600
1601   // Lay out the segment headers.
1602   if (!parameters->options().relocatable())
1603     {
1604       gold_assert(segment_headers != NULL);
1605       if (load_seg != NULL)
1606         load_seg->add_initial_output_data(segment_headers);
1607       if (phdr_seg != NULL)
1608         phdr_seg->add_initial_output_data(segment_headers);
1609     }
1610
1611   // Lay out the file header.
1612   if (load_seg != NULL)
1613     load_seg->add_initial_output_data(file_header);
1614
1615   if (this->script_options_->saw_phdrs_clause()
1616       && !parameters->options().relocatable())
1617     {
1618       // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1619       // clause in a linker script.
1620       Script_sections* ss = this->script_options_->script_sections();
1621       ss->put_headers_in_phdrs(file_header, segment_headers);
1622     }
1623
1624   // We set the output section indexes in set_segment_offsets and
1625   // set_section_indexes.
1626   *pshndx = 1;
1627
1628   // Set the file offsets of all the segments, and all the sections
1629   // they contain.
1630   off_t off;
1631   if (!parameters->options().relocatable())
1632     off = this->set_segment_offsets(target, load_seg, pshndx);
1633   else
1634     off = this->set_relocatable_section_offsets(file_header, pshndx);
1635
1636    // Verify that the dummy relaxation does not change anything.
1637   if (is_debugging_enabled(DEBUG_RELAXATION))
1638     {
1639       if (pass == 0)
1640         this->relaxation_debug_check_->read_sections(this->section_list_);
1641       else
1642         this->relaxation_debug_check_->verify_sections(this->section_list_);
1643     }
1644
1645   *pload_seg = load_seg;
1646   return off;
1647 }
1648
1649 // Search the list of patterns and find the postion of the given section
1650 // name in the output section.  If the section name matches a glob
1651 // pattern and a non-glob name, then the non-glob position takes
1652 // precedence.  Return 0 if no match is found.
1653
1654 unsigned int
1655 Layout::find_section_order_index(const std::string& section_name)
1656 {
1657   Unordered_map<std::string, unsigned int>::iterator map_it;
1658   map_it = this->input_section_position_.find(section_name);
1659   if (map_it != this->input_section_position_.end())
1660     return map_it->second;
1661
1662   // Absolute match failed.  Linear search the glob patterns.
1663   std::vector<std::string>::iterator it;
1664   for (it = this->input_section_glob_.begin();
1665        it != this->input_section_glob_.end();
1666        ++it)
1667     {
1668        if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
1669          {
1670            map_it = this->input_section_position_.find(*it);
1671            gold_assert(map_it != this->input_section_position_.end());
1672            return map_it->second;
1673          }
1674     }
1675   return 0;
1676 }
1677
1678 // Read the sequence of input sections from the file specified with
1679 // --section-ordering-file.
1680
1681 void
1682 Layout::read_layout_from_file()
1683 {
1684   const char* filename = parameters->options().section_ordering_file();
1685   std::ifstream in;
1686   std::string line;
1687
1688   in.open(filename);
1689   if (!in)
1690     gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
1691                filename, strerror(errno));
1692
1693   std::getline(in, line);   // this chops off the trailing \n, if any
1694   unsigned int position = 1;
1695
1696   while (in)
1697     {
1698       if (!line.empty() && line[line.length() - 1] == '\r')   // Windows
1699         line.resize(line.length() - 1);
1700       // Ignore comments, beginning with '#'
1701       if (line[0] == '#')
1702         {
1703           std::getline(in, line);
1704           continue;
1705         }
1706       this->input_section_position_[line] = position;
1707       // Store all glob patterns in a vector.
1708       if (is_wildcard_string(line.c_str()))
1709         this->input_section_glob_.push_back(line);
1710       position++;
1711       std::getline(in, line);
1712     }
1713 }
1714
1715 // Finalize the layout.  When this is called, we have created all the
1716 // output sections and all the output segments which are based on
1717 // input sections.  We have several things to do, and we have to do
1718 // them in the right order, so that we get the right results correctly
1719 // and efficiently.
1720
1721 // 1) Finalize the list of output segments and create the segment
1722 // table header.
1723
1724 // 2) Finalize the dynamic symbol table and associated sections.
1725
1726 // 3) Determine the final file offset of all the output segments.
1727
1728 // 4) Determine the final file offset of all the SHF_ALLOC output
1729 // sections.
1730
1731 // 5) Create the symbol table sections and the section name table
1732 // section.
1733
1734 // 6) Finalize the symbol table: set symbol values to their final
1735 // value and make a final determination of which symbols are going
1736 // into the output symbol table.
1737
1738 // 7) Create the section table header.
1739
1740 // 8) Determine the final file offset of all the output sections which
1741 // are not SHF_ALLOC, including the section table header.
1742
1743 // 9) Finalize the ELF file header.
1744
1745 // This function returns the size of the output file.
1746
1747 off_t
1748 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1749                  Target* target, const Task* task)
1750 {
1751   target->finalize_sections(this, input_objects, symtab);
1752
1753   this->count_local_symbols(task, input_objects);
1754
1755   this->link_stabs_sections();
1756
1757   Output_segment* phdr_seg = NULL;
1758   if (!parameters->options().relocatable() && !parameters->doing_static_link())
1759     {
1760       // There was a dynamic object in the link.  We need to create
1761       // some information for the dynamic linker.
1762
1763       // Create the PT_PHDR segment which will hold the program
1764       // headers.
1765       if (!this->script_options_->saw_phdrs_clause())
1766         phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1767
1768       // Create the dynamic symbol table, including the hash table.
1769       Output_section* dynstr;
1770       std::vector<Symbol*> dynamic_symbols;
1771       unsigned int local_dynamic_count;
1772       Versions versions(*this->script_options()->version_script_info(),
1773                         &this->dynpool_);
1774       this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1775                                   &local_dynamic_count, &dynamic_symbols,
1776                                   &versions);
1777
1778       // Create the .interp section to hold the name of the
1779       // interpreter, and put it in a PT_INTERP segment.
1780       if (!parameters->options().shared())
1781         this->create_interp(target);
1782
1783       // Finish the .dynamic section to hold the dynamic data, and put
1784       // it in a PT_DYNAMIC segment.
1785       this->finish_dynamic_section(input_objects, symtab);
1786
1787       // We should have added everything we need to the dynamic string
1788       // table.
1789       this->dynpool_.set_string_offsets();
1790
1791       // Create the version sections.  We can't do this until the
1792       // dynamic string table is complete.
1793       this->create_version_sections(&versions, symtab, local_dynamic_count,
1794                                     dynamic_symbols, dynstr);
1795
1796       // Set the size of the _DYNAMIC symbol.  We can't do this until
1797       // after we call create_version_sections.
1798       this->set_dynamic_symbol_size(symtab);
1799     }
1800   
1801   if (this->incremental_inputs_)
1802     {
1803       this->incremental_inputs_->finalize();
1804       this->create_incremental_info_sections();
1805     }
1806
1807   // Create segment headers.
1808   Output_segment_headers* segment_headers =
1809     (parameters->options().relocatable()
1810      ? NULL
1811      : new Output_segment_headers(this->segment_list_));
1812
1813   // Lay out the file header.
1814   Output_file_header* file_header
1815     = new Output_file_header(target, symtab, segment_headers,
1816                              parameters->options().entry());
1817
1818   this->special_output_list_.push_back(file_header);
1819   if (segment_headers != NULL)
1820     this->special_output_list_.push_back(segment_headers);
1821
1822   // Find approriate places for orphan output sections if we are using
1823   // a linker script.
1824   if (this->script_options_->saw_sections_clause())
1825     this->place_orphan_sections_in_script();
1826   
1827   Output_segment* load_seg;
1828   off_t off;
1829   unsigned int shndx;
1830   int pass = 0;
1831
1832   // Take a snapshot of the section layout as needed.
1833   if (target->may_relax())
1834     this->prepare_for_relaxation();
1835   
1836   // Run the relaxation loop to lay out sections.
1837   do
1838     {
1839       off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1840                                        phdr_seg, segment_headers, file_header,
1841                                        &shndx);
1842       pass++;
1843     }
1844   while (target->may_relax()
1845          && target->relax(pass, input_objects, symtab, this));
1846
1847   // Set the file offsets of all the non-data sections we've seen so
1848   // far which don't have to wait for the input sections.  We need
1849   // this in order to finalize local symbols in non-allocated
1850   // sections.
1851   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1852
1853   // Set the section indexes of all unallocated sections seen so far,
1854   // in case any of them are somehow referenced by a symbol.
1855   shndx = this->set_section_indexes(shndx);
1856
1857   // Create the symbol table sections.
1858   this->create_symtab_sections(input_objects, symtab, shndx, &off);
1859   if (!parameters->doing_static_link())
1860     this->assign_local_dynsym_offsets(input_objects);
1861
1862   // Process any symbol assignments from a linker script.  This must
1863   // be called after the symbol table has been finalized.
1864   this->script_options_->finalize_symbols(symtab, this);
1865
1866   // Create the .shstrtab section.
1867   Output_section* shstrtab_section = this->create_shstrtab();
1868
1869   // Set the file offsets of the rest of the non-data sections which
1870   // don't have to wait for the input sections.
1871   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1872
1873   // Now that all sections have been created, set the section indexes
1874   // for any sections which haven't been done yet.
1875   shndx = this->set_section_indexes(shndx);
1876
1877   // Create the section table header.
1878   this->create_shdrs(shstrtab_section, &off);
1879
1880   // If there are no sections which require postprocessing, we can
1881   // handle the section names now, and avoid a resize later.
1882   if (!this->any_postprocessing_sections_)
1883     off = this->set_section_offsets(off,
1884                                     STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1885
1886   file_header->set_section_info(this->section_headers_, shstrtab_section);
1887
1888   // Now we know exactly where everything goes in the output file
1889   // (except for non-allocated sections which require postprocessing).
1890   Output_data::layout_complete();
1891
1892   this->output_file_size_ = off;
1893
1894   return off;
1895 }
1896
1897 // Create a note header following the format defined in the ELF ABI.
1898 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1899 // of the section to create, DESCSZ is the size of the descriptor.
1900 // ALLOCATE is true if the section should be allocated in memory.
1901 // This returns the new note section.  It sets *TRAILING_PADDING to
1902 // the number of trailing zero bytes required.
1903
1904 Output_section*
1905 Layout::create_note(const char* name, int note_type,
1906                     const char* section_name, size_t descsz,
1907                     bool allocate, size_t* trailing_padding)
1908 {
1909   // Authorities all agree that the values in a .note field should
1910   // be aligned on 4-byte boundaries for 32-bit binaries.  However,
1911   // they differ on what the alignment is for 64-bit binaries.
1912   // The GABI says unambiguously they take 8-byte alignment:
1913   //    http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1914   // Other documentation says alignment should always be 4 bytes:
1915   //    http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1916   // GNU ld and GNU readelf both support the latter (at least as of
1917   // version 2.16.91), and glibc always generates the latter for
1918   // .note.ABI-tag (as of version 1.6), so that's the one we go with
1919   // here.
1920 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION   // This is not defined by default.
1921   const int size = parameters->target().get_size();
1922 #else
1923   const int size = 32;
1924 #endif
1925
1926   // The contents of the .note section.
1927   size_t namesz = strlen(name) + 1;
1928   size_t aligned_namesz = align_address(namesz, size / 8);
1929   size_t aligned_descsz = align_address(descsz, size / 8);
1930
1931   size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1932
1933   unsigned char* buffer = new unsigned char[notehdrsz];
1934   memset(buffer, 0, notehdrsz);
1935
1936   bool is_big_endian = parameters->target().is_big_endian();
1937
1938   if (size == 32)
1939     {
1940       if (!is_big_endian)
1941         {
1942           elfcpp::Swap<32, false>::writeval(buffer, namesz);
1943           elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1944           elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1945         }
1946       else
1947         {
1948           elfcpp::Swap<32, true>::writeval(buffer, namesz);
1949           elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1950           elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1951         }
1952     }
1953   else if (size == 64)
1954     {
1955       if (!is_big_endian)
1956         {
1957           elfcpp::Swap<64, false>::writeval(buffer, namesz);
1958           elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1959           elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1960         }
1961       else
1962         {
1963           elfcpp::Swap<64, true>::writeval(buffer, namesz);
1964           elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1965           elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1966         }
1967     }
1968   else
1969     gold_unreachable();
1970
1971   memcpy(buffer + 3 * (size / 8), name, namesz);
1972
1973   elfcpp::Elf_Xword flags = 0;
1974   if (allocate)
1975     flags = elfcpp::SHF_ALLOC;
1976   Output_section* os = this->choose_output_section(NULL, section_name,
1977                                                    elfcpp::SHT_NOTE,
1978                                                    flags, false, false,
1979                                                    false, false, false, false);
1980   if (os == NULL)
1981     return NULL;
1982
1983   Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1984                                                            size / 8,
1985                                                            "** note header");
1986   os->add_output_section_data(posd);
1987
1988   *trailing_padding = aligned_descsz - descsz;
1989
1990   return os;
1991 }
1992
1993 // For an executable or shared library, create a note to record the
1994 // version of gold used to create the binary.
1995
1996 void
1997 Layout::create_gold_note()
1998 {
1999   if (parameters->options().relocatable())
2000     return;
2001
2002   std::string desc = std::string("gold ") + gold::get_version_string();
2003
2004   size_t trailing_padding;
2005   Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
2006                                          ".note.gnu.gold-version", desc.size(),
2007                                          false, &trailing_padding);
2008   if (os == NULL)
2009     return;
2010
2011   Output_section_data* posd = new Output_data_const(desc, 4);
2012   os->add_output_section_data(posd);
2013
2014   if (trailing_padding > 0)
2015     {
2016       posd = new Output_data_zero_fill(trailing_padding, 0);
2017       os->add_output_section_data(posd);
2018     }
2019 }
2020
2021 // Record whether the stack should be executable.  This can be set
2022 // from the command line using the -z execstack or -z noexecstack
2023 // options.  Otherwise, if any input file has a .note.GNU-stack
2024 // section with the SHF_EXECINSTR flag set, the stack should be
2025 // executable.  Otherwise, if at least one input file a
2026 // .note.GNU-stack section, and some input file has no .note.GNU-stack
2027 // section, we use the target default for whether the stack should be
2028 // executable.  Otherwise, we don't generate a stack note.  When
2029 // generating a object file, we create a .note.GNU-stack section with
2030 // the appropriate marking.  When generating an executable or shared
2031 // library, we create a PT_GNU_STACK segment.
2032
2033 void
2034 Layout::create_executable_stack_info()
2035 {
2036   bool is_stack_executable;
2037   if (parameters->options().is_execstack_set())
2038     is_stack_executable = parameters->options().is_stack_executable();
2039   else if (!this->input_with_gnu_stack_note_)
2040     return;
2041   else
2042     {
2043       if (this->input_requires_executable_stack_)
2044         is_stack_executable = true;
2045       else if (this->input_without_gnu_stack_note_)
2046         is_stack_executable =
2047           parameters->target().is_default_stack_executable();
2048       else
2049         is_stack_executable = false;
2050     }
2051
2052   if (parameters->options().relocatable())
2053     {
2054       const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
2055       elfcpp::Elf_Xword flags = 0;
2056       if (is_stack_executable)
2057         flags |= elfcpp::SHF_EXECINSTR;
2058       this->make_output_section(name, elfcpp::SHT_PROGBITS, flags, false,
2059                                 false, false, false, false);
2060     }
2061   else
2062     {
2063       if (this->script_options_->saw_phdrs_clause())
2064         return;
2065       int flags = elfcpp::PF_R | elfcpp::PF_W;
2066       if (is_stack_executable)
2067         flags |= elfcpp::PF_X;
2068       this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
2069     }
2070 }
2071
2072 // If --build-id was used, set up the build ID note.
2073
2074 void
2075 Layout::create_build_id()
2076 {
2077   if (!parameters->options().user_set_build_id())
2078     return;
2079
2080   const char* style = parameters->options().build_id();
2081   if (strcmp(style, "none") == 0)
2082     return;
2083
2084   // Set DESCSZ to the size of the note descriptor.  When possible,
2085   // set DESC to the note descriptor contents.
2086   size_t descsz;
2087   std::string desc;
2088   if (strcmp(style, "md5") == 0)
2089     descsz = 128 / 8;
2090   else if (strcmp(style, "sha1") == 0)
2091     descsz = 160 / 8;
2092   else if (strcmp(style, "uuid") == 0)
2093     {
2094       const size_t uuidsz = 128 / 8;
2095
2096       char buffer[uuidsz];
2097       memset(buffer, 0, uuidsz);
2098
2099       int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
2100       if (descriptor < 0)
2101         gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
2102                    strerror(errno));
2103       else
2104         {
2105           ssize_t got = ::read(descriptor, buffer, uuidsz);
2106           release_descriptor(descriptor, true);
2107           if (got < 0)
2108             gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
2109           else if (static_cast<size_t>(got) != uuidsz)
2110             gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
2111                        uuidsz, got);
2112         }
2113
2114       desc.assign(buffer, uuidsz);
2115       descsz = uuidsz;
2116     }
2117   else if (strncmp(style, "0x", 2) == 0)
2118     {
2119       hex_init();
2120       const char* p = style + 2;
2121       while (*p != '\0')
2122         {
2123           if (hex_p(p[0]) && hex_p(p[1]))
2124             {
2125               char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
2126               desc += c;
2127               p += 2;
2128             }
2129           else if (*p == '-' || *p == ':')
2130             ++p;
2131           else
2132             gold_fatal(_("--build-id argument '%s' not a valid hex number"),
2133                        style);
2134         }
2135       descsz = desc.size();
2136     }
2137   else
2138     gold_fatal(_("unrecognized --build-id argument '%s'"), style);
2139
2140   // Create the note.
2141   size_t trailing_padding;
2142   Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
2143                                          ".note.gnu.build-id", descsz, true,
2144                                          &trailing_padding);
2145   if (os == NULL)
2146     return;
2147
2148   if (!desc.empty())
2149     {
2150       // We know the value already, so we fill it in now.
2151       gold_assert(desc.size() == descsz);
2152
2153       Output_section_data* posd = new Output_data_const(desc, 4);
2154       os->add_output_section_data(posd);
2155
2156       if (trailing_padding != 0)
2157         {
2158           posd = new Output_data_zero_fill(trailing_padding, 0);
2159           os->add_output_section_data(posd);
2160         }
2161     }
2162   else
2163     {
2164       // We need to compute a checksum after we have completed the
2165       // link.
2166       gold_assert(trailing_padding == 0);
2167       this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
2168       os->add_output_section_data(this->build_id_note_);
2169     }
2170 }
2171
2172 // If we have both .stabXX and .stabXXstr sections, then the sh_link
2173 // field of the former should point to the latter.  I'm not sure who
2174 // started this, but the GNU linker does it, and some tools depend
2175 // upon it.
2176
2177 void
2178 Layout::link_stabs_sections()
2179 {
2180   if (!this->have_stabstr_section_)
2181     return;
2182
2183   for (Section_list::iterator p = this->section_list_.begin();
2184        p != this->section_list_.end();
2185        ++p)
2186     {
2187       if ((*p)->type() != elfcpp::SHT_STRTAB)
2188         continue;
2189
2190       const char* name = (*p)->name();
2191       if (strncmp(name, ".stab", 5) != 0)
2192         continue;
2193
2194       size_t len = strlen(name);
2195       if (strcmp(name + len - 3, "str") != 0)
2196         continue;
2197
2198       std::string stab_name(name, len - 3);
2199       Output_section* stab_sec;
2200       stab_sec = this->find_output_section(stab_name.c_str());
2201       if (stab_sec != NULL)
2202         stab_sec->set_link_section(*p);
2203     }
2204 }
2205
2206 // Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
2207 // for the next run of incremental linking to check what has changed.
2208
2209 void
2210 Layout::create_incremental_info_sections()
2211 {
2212   gold_assert(this->incremental_inputs_ != NULL);
2213
2214   // Add the .gnu_incremental_inputs section.
2215   const char *incremental_inputs_name =
2216     this->namepool_.add(".gnu_incremental_inputs", false, NULL);
2217   Output_section* inputs_os =
2218     this->make_output_section(incremental_inputs_name,
2219                               elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2220                               false, false, false, false, false);
2221   Output_section_data* posd =
2222       this->incremental_inputs_->create_incremental_inputs_section_data();
2223   inputs_os->add_output_section_data(posd);
2224   
2225   // Add the .gnu_incremental_strtab section.
2226   const char *incremental_strtab_name =
2227     this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2228   Output_section* strtab_os = this->make_output_section(incremental_strtab_name,
2229                                                         elfcpp::SHT_STRTAB,
2230                                                         0, false, false,
2231                                                         false, false, false);
2232   Output_data_strtab* strtab_data =
2233     new Output_data_strtab(this->incremental_inputs_->get_stringpool());
2234   strtab_os->add_output_section_data(strtab_data);
2235   
2236   inputs_os->set_link_section(strtab_data);
2237 }
2238
2239 // Return whether SEG1 should be before SEG2 in the output file.  This
2240 // is based entirely on the segment type and flags.  When this is
2241 // called the segment addresses has normally not yet been set.
2242
2243 bool
2244 Layout::segment_precedes(const Output_segment* seg1,
2245                          const Output_segment* seg2)
2246 {
2247   elfcpp::Elf_Word type1 = seg1->type();
2248   elfcpp::Elf_Word type2 = seg2->type();
2249
2250   // The single PT_PHDR segment is required to precede any loadable
2251   // segment.  We simply make it always first.
2252   if (type1 == elfcpp::PT_PHDR)
2253     {
2254       gold_assert(type2 != elfcpp::PT_PHDR);
2255       return true;
2256     }
2257   if (type2 == elfcpp::PT_PHDR)
2258     return false;
2259
2260   // The single PT_INTERP segment is required to precede any loadable
2261   // segment.  We simply make it always second.
2262   if (type1 == elfcpp::PT_INTERP)
2263     {
2264       gold_assert(type2 != elfcpp::PT_INTERP);
2265       return true;
2266     }
2267   if (type2 == elfcpp::PT_INTERP)
2268     return false;
2269
2270   // We then put PT_LOAD segments before any other segments.
2271   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2272     return true;
2273   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2274     return false;
2275
2276   // We put the PT_TLS segment last except for the PT_GNU_RELRO
2277   // segment, because that is where the dynamic linker expects to find
2278   // it (this is just for efficiency; other positions would also work
2279   // correctly).
2280   if (type1 == elfcpp::PT_TLS
2281       && type2 != elfcpp::PT_TLS
2282       && type2 != elfcpp::PT_GNU_RELRO)
2283     return false;
2284   if (type2 == elfcpp::PT_TLS
2285       && type1 != elfcpp::PT_TLS
2286       && type1 != elfcpp::PT_GNU_RELRO)
2287     return true;
2288
2289   // We put the PT_GNU_RELRO segment last, because that is where the
2290   // dynamic linker expects to find it (as with PT_TLS, this is just
2291   // for efficiency).
2292   if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2293     return false;
2294   if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2295     return true;
2296
2297   const elfcpp::Elf_Word flags1 = seg1->flags();
2298   const elfcpp::Elf_Word flags2 = seg2->flags();
2299
2300   // The order of non-PT_LOAD segments is unimportant.  We simply sort
2301   // by the numeric segment type and flags values.  There should not
2302   // be more than one segment with the same type and flags.
2303   if (type1 != elfcpp::PT_LOAD)
2304     {
2305       if (type1 != type2)
2306         return type1 < type2;
2307       gold_assert(flags1 != flags2);
2308       return flags1 < flags2;
2309     }
2310
2311   // If the addresses are set already, sort by load address.
2312   if (seg1->are_addresses_set())
2313     {
2314       if (!seg2->are_addresses_set())
2315         return true;
2316
2317       unsigned int section_count1 = seg1->output_section_count();
2318       unsigned int section_count2 = seg2->output_section_count();
2319       if (section_count1 == 0 && section_count2 > 0)
2320         return true;
2321       if (section_count1 > 0 && section_count2 == 0)
2322         return false;
2323
2324       uint64_t paddr1 = seg1->first_section_load_address();
2325       uint64_t paddr2 = seg2->first_section_load_address();
2326       if (paddr1 != paddr2)
2327         return paddr1 < paddr2;
2328     }
2329   else if (seg2->are_addresses_set())
2330     return false;
2331
2332   // A segment which holds large data comes after a segment which does
2333   // not hold large data.
2334   if (seg1->is_large_data_segment())
2335     {
2336       if (!seg2->is_large_data_segment())
2337         return false;
2338     }
2339   else if (seg2->is_large_data_segment())
2340     return true;
2341
2342   // Otherwise, we sort PT_LOAD segments based on the flags.  Readonly
2343   // segments come before writable segments.  Then writable segments
2344   // with data come before writable segments without data.  Then
2345   // executable segments come before non-executable segments.  Then
2346   // the unlikely case of a non-readable segment comes before the
2347   // normal case of a readable segment.  If there are multiple
2348   // segments with the same type and flags, we require that the
2349   // address be set, and we sort by virtual address and then physical
2350   // address.
2351   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2352     return (flags1 & elfcpp::PF_W) == 0;
2353   if ((flags1 & elfcpp::PF_W) != 0
2354       && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2355     return seg1->has_any_data_sections();
2356   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2357     return (flags1 & elfcpp::PF_X) != 0;
2358   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2359     return (flags1 & elfcpp::PF_R) == 0;
2360
2361   // We shouldn't get here--we shouldn't create segments which we
2362   // can't distinguish.
2363   gold_unreachable();
2364 }
2365
2366 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2367
2368 static off_t
2369 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2370 {
2371   uint64_t unsigned_off = off;
2372   uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2373                           | (addr & (abi_pagesize - 1)));
2374   if (aligned_off < unsigned_off)
2375     aligned_off += abi_pagesize;
2376   return aligned_off;
2377 }
2378
2379 // Set the file offsets of all the segments, and all the sections they
2380 // contain.  They have all been created.  LOAD_SEG must be be laid out
2381 // first.  Return the offset of the data to follow.
2382
2383 off_t
2384 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2385                             unsigned int *pshndx)
2386 {
2387   // Sort them into the final order.
2388   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2389             Layout::Compare_segments());
2390
2391   // Find the PT_LOAD segments, and set their addresses and offsets
2392   // and their section's addresses and offsets.
2393   uint64_t addr;
2394   if (parameters->options().user_set_Ttext())
2395     addr = parameters->options().Ttext();
2396   else if (parameters->options().output_is_position_independent())
2397     addr = 0;
2398   else
2399     addr = target->default_text_segment_address();
2400   off_t off = 0;
2401
2402   // If LOAD_SEG is NULL, then the file header and segment headers
2403   // will not be loadable.  But they still need to be at offset 0 in
2404   // the file.  Set their offsets now.
2405   if (load_seg == NULL)
2406     {
2407       for (Data_list::iterator p = this->special_output_list_.begin();
2408            p != this->special_output_list_.end();
2409            ++p)
2410         {
2411           off = align_address(off, (*p)->addralign());
2412           (*p)->set_address_and_file_offset(0, off);
2413           off += (*p)->data_size();
2414         }
2415     }
2416
2417   unsigned int increase_relro = this->increase_relro_;
2418   if (this->script_options_->saw_sections_clause())
2419     increase_relro = 0;
2420
2421   const bool check_sections = parameters->options().check_sections();
2422   Output_segment* last_load_segment = NULL;
2423
2424   bool was_readonly = false;
2425   for (Segment_list::iterator p = this->segment_list_.begin();
2426        p != this->segment_list_.end();
2427        ++p)
2428     {
2429       if ((*p)->type() == elfcpp::PT_LOAD)
2430         {
2431           if (load_seg != NULL && load_seg != *p)
2432             gold_unreachable();
2433           load_seg = NULL;
2434
2435           bool are_addresses_set = (*p)->are_addresses_set();
2436           if (are_addresses_set)
2437             {
2438               // When it comes to setting file offsets, we care about
2439               // the physical address.
2440               addr = (*p)->paddr();
2441             }
2442           else if (parameters->options().user_set_Tdata()
2443                    && ((*p)->flags() & elfcpp::PF_W) != 0
2444                    && (!parameters->options().user_set_Tbss()
2445                        || (*p)->has_any_data_sections()))
2446             {
2447               addr = parameters->options().Tdata();
2448               are_addresses_set = true;
2449             }
2450           else if (parameters->options().user_set_Tbss()
2451                    && ((*p)->flags() & elfcpp::PF_W) != 0
2452                    && !(*p)->has_any_data_sections())
2453             {
2454               addr = parameters->options().Tbss();
2455               are_addresses_set = true;
2456             }
2457
2458           uint64_t orig_addr = addr;
2459           uint64_t orig_off = off;
2460
2461           uint64_t aligned_addr = 0;
2462           uint64_t abi_pagesize = target->abi_pagesize();
2463           uint64_t common_pagesize = target->common_pagesize();
2464
2465           if (!parameters->options().nmagic()
2466               && !parameters->options().omagic())
2467             (*p)->set_minimum_p_align(common_pagesize);
2468
2469           if (!are_addresses_set)
2470             {
2471               // If the last segment was readonly, and this one is
2472               // not, then skip the address forward one page,
2473               // maintaining the same position within the page.  This
2474               // lets us store both segments overlapping on a single
2475               // page in the file, but the loader will put them on
2476               // different pages in memory.
2477
2478               addr = align_address(addr, (*p)->maximum_alignment());
2479               aligned_addr = addr;
2480
2481               if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2482                 {
2483                   if ((addr & (abi_pagesize - 1)) != 0)
2484                     addr = addr + abi_pagesize;
2485                 }
2486
2487               off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2488             }
2489
2490           if (!parameters->options().nmagic()
2491               && !parameters->options().omagic())
2492             off = align_file_offset(off, addr, abi_pagesize);
2493           else if (load_seg == NULL)
2494             {
2495               // This is -N or -n with a section script which prevents
2496               // us from using a load segment.  We need to ensure that
2497               // the file offset is aligned to the alignment of the
2498               // segment.  This is because the linker script
2499               // implicitly assumed a zero offset.  If we don't align
2500               // here, then the alignment of the sections in the
2501               // linker script may not match the alignment of the
2502               // sections in the set_section_addresses call below,
2503               // causing an error about dot moving backward.
2504               off = align_address(off, (*p)->maximum_alignment());
2505             }
2506
2507           unsigned int shndx_hold = *pshndx;
2508           uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2509                                                           increase_relro,
2510                                                           &off, pshndx);
2511
2512           // Now that we know the size of this segment, we may be able
2513           // to save a page in memory, at the cost of wasting some
2514           // file space, by instead aligning to the start of a new
2515           // page.  Here we use the real machine page size rather than
2516           // the ABI mandated page size.
2517
2518           if (!are_addresses_set && aligned_addr != addr)
2519             {
2520               uint64_t first_off = (common_pagesize
2521                                     - (aligned_addr
2522                                        & (common_pagesize - 1)));
2523               uint64_t last_off = new_addr & (common_pagesize - 1);
2524               if (first_off > 0
2525                   && last_off > 0
2526                   && ((aligned_addr & ~ (common_pagesize - 1))
2527                       != (new_addr & ~ (common_pagesize - 1)))
2528                   && first_off + last_off <= common_pagesize)
2529                 {
2530                   *pshndx = shndx_hold;
2531                   addr = align_address(aligned_addr, common_pagesize);
2532                   addr = align_address(addr, (*p)->maximum_alignment());
2533                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2534                   off = align_file_offset(off, addr, abi_pagesize);
2535                   new_addr = (*p)->set_section_addresses(this, true, addr,
2536                                                          increase_relro,
2537                                                          &off, pshndx);
2538                 }
2539             }
2540
2541           addr = new_addr;
2542
2543           if (((*p)->flags() & elfcpp::PF_W) == 0)
2544             was_readonly = true;
2545
2546           // Implement --check-sections.  We know that the segments
2547           // are sorted by LMA.
2548           if (check_sections && last_load_segment != NULL)
2549             {
2550               gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2551               if (last_load_segment->paddr() + last_load_segment->memsz()
2552                   > (*p)->paddr())
2553                 {
2554                   unsigned long long lb1 = last_load_segment->paddr();
2555                   unsigned long long le1 = lb1 + last_load_segment->memsz();
2556                   unsigned long long lb2 = (*p)->paddr();
2557                   unsigned long long le2 = lb2 + (*p)->memsz();
2558                   gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2559                                "[0x%llx -> 0x%llx]"),
2560                              lb1, le1, lb2, le2);
2561                 }
2562             }
2563           last_load_segment = *p;
2564         }
2565     }
2566
2567   // Handle the non-PT_LOAD segments, setting their offsets from their
2568   // section's offsets.
2569   for (Segment_list::iterator p = this->segment_list_.begin();
2570        p != this->segment_list_.end();
2571        ++p)
2572     {
2573       if ((*p)->type() != elfcpp::PT_LOAD)
2574         (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
2575                          ? increase_relro
2576                          : 0);
2577     }
2578
2579   // Set the TLS offsets for each section in the PT_TLS segment.
2580   if (this->tls_segment_ != NULL)
2581     this->tls_segment_->set_tls_offsets();
2582
2583   return off;
2584 }
2585
2586 // Set the offsets of all the allocated sections when doing a
2587 // relocatable link.  This does the same jobs as set_segment_offsets,
2588 // only for a relocatable link.
2589
2590 off_t
2591 Layout::set_relocatable_section_offsets(Output_data* file_header,
2592                                         unsigned int *pshndx)
2593 {
2594   off_t off = 0;
2595
2596   file_header->set_address_and_file_offset(0, 0);
2597   off += file_header->data_size();
2598
2599   for (Section_list::iterator p = this->section_list_.begin();
2600        p != this->section_list_.end();
2601        ++p)
2602     {
2603       // We skip unallocated sections here, except that group sections
2604       // have to come first.
2605       if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2606           && (*p)->type() != elfcpp::SHT_GROUP)
2607         continue;
2608
2609       off = align_address(off, (*p)->addralign());
2610
2611       // The linker script might have set the address.
2612       if (!(*p)->is_address_valid())
2613         (*p)->set_address(0);
2614       (*p)->set_file_offset(off);
2615       (*p)->finalize_data_size();
2616       off += (*p)->data_size();
2617
2618       (*p)->set_out_shndx(*pshndx);
2619       ++*pshndx;
2620     }
2621
2622   return off;
2623 }
2624
2625 // Set the file offset of all the sections not associated with a
2626 // segment.
2627
2628 off_t
2629 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2630 {
2631   for (Section_list::iterator p = this->unattached_section_list_.begin();
2632        p != this->unattached_section_list_.end();
2633        ++p)
2634     {
2635       // The symtab section is handled in create_symtab_sections.
2636       if (*p == this->symtab_section_)
2637         continue;
2638
2639       // If we've already set the data size, don't set it again.
2640       if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2641         continue;
2642
2643       if (pass == BEFORE_INPUT_SECTIONS_PASS
2644           && (*p)->requires_postprocessing())
2645         {
2646           (*p)->create_postprocessing_buffer();
2647           this->any_postprocessing_sections_ = true;
2648         }
2649
2650       if (pass == BEFORE_INPUT_SECTIONS_PASS
2651           && (*p)->after_input_sections())
2652         continue;
2653       else if (pass == POSTPROCESSING_SECTIONS_PASS
2654                && (!(*p)->after_input_sections()
2655                    || (*p)->type() == elfcpp::SHT_STRTAB))
2656         continue;
2657       else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2658                && (!(*p)->after_input_sections()
2659                    || (*p)->type() != elfcpp::SHT_STRTAB))
2660         continue;
2661
2662       off = align_address(off, (*p)->addralign());
2663       (*p)->set_file_offset(off);
2664       (*p)->finalize_data_size();
2665       off += (*p)->data_size();
2666
2667       // At this point the name must be set.
2668       if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2669         this->namepool_.add((*p)->name(), false, NULL);
2670     }
2671   return off;
2672 }
2673
2674 // Set the section indexes of all the sections not associated with a
2675 // segment.
2676
2677 unsigned int
2678 Layout::set_section_indexes(unsigned int shndx)
2679 {
2680   for (Section_list::iterator p = this->unattached_section_list_.begin();
2681        p != this->unattached_section_list_.end();
2682        ++p)
2683     {
2684       if (!(*p)->has_out_shndx())
2685         {
2686           (*p)->set_out_shndx(shndx);
2687           ++shndx;
2688         }
2689     }
2690   return shndx;
2691 }
2692
2693 // Set the section addresses according to the linker script.  This is
2694 // only called when we see a SECTIONS clause.  This returns the
2695 // program segment which should hold the file header and segment
2696 // headers, if any.  It will return NULL if they should not be in a
2697 // segment.
2698
2699 Output_segment*
2700 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2701 {
2702   Script_sections* ss = this->script_options_->script_sections();
2703   gold_assert(ss->saw_sections_clause());
2704   return this->script_options_->set_section_addresses(symtab, this);
2705 }
2706
2707 // Place the orphan sections in the linker script.
2708
2709 void
2710 Layout::place_orphan_sections_in_script()
2711 {
2712   Script_sections* ss = this->script_options_->script_sections();
2713   gold_assert(ss->saw_sections_clause());
2714
2715   // Place each orphaned output section in the script.
2716   for (Section_list::iterator p = this->section_list_.begin();
2717        p != this->section_list_.end();
2718        ++p)
2719     {
2720       if (!(*p)->found_in_sections_clause())
2721         ss->place_orphan(*p);
2722     }
2723 }
2724
2725 // Count the local symbols in the regular symbol table and the dynamic
2726 // symbol table, and build the respective string pools.
2727
2728 void
2729 Layout::count_local_symbols(const Task* task,
2730                             const Input_objects* input_objects)
2731 {
2732   // First, figure out an upper bound on the number of symbols we'll
2733   // be inserting into each pool.  This helps us create the pools with
2734   // the right size, to avoid unnecessary hashtable resizing.
2735   unsigned int symbol_count = 0;
2736   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2737        p != input_objects->relobj_end();
2738        ++p)
2739     symbol_count += (*p)->local_symbol_count();
2740
2741   // Go from "upper bound" to "estimate."  We overcount for two
2742   // reasons: we double-count symbols that occur in more than one
2743   // object file, and we count symbols that are dropped from the
2744   // output.  Add it all together and assume we overcount by 100%.
2745   symbol_count /= 2;
2746
2747   // We assume all symbols will go into both the sympool and dynpool.
2748   this->sympool_.reserve(symbol_count);
2749   this->dynpool_.reserve(symbol_count);
2750
2751   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2752        p != input_objects->relobj_end();
2753        ++p)
2754     {
2755       Task_lock_obj<Object> tlo(task, *p);
2756       (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2757     }
2758 }
2759
2760 // Create the symbol table sections.  Here we also set the final
2761 // values of the symbols.  At this point all the loadable sections are
2762 // fully laid out.  SHNUM is the number of sections so far.
2763
2764 void
2765 Layout::create_symtab_sections(const Input_objects* input_objects,
2766                                Symbol_table* symtab,
2767                                unsigned int shnum,
2768                                off_t* poff)
2769 {
2770   int symsize;
2771   unsigned int align;
2772   if (parameters->target().get_size() == 32)
2773     {
2774       symsize = elfcpp::Elf_sizes<32>::sym_size;
2775       align = 4;
2776     }
2777   else if (parameters->target().get_size() == 64)
2778     {
2779       symsize = elfcpp::Elf_sizes<64>::sym_size;
2780       align = 8;
2781     }
2782   else
2783     gold_unreachable();
2784
2785   off_t off = *poff;
2786   off = align_address(off, align);
2787   off_t startoff = off;
2788
2789   // Save space for the dummy symbol at the start of the section.  We
2790   // never bother to write this out--it will just be left as zero.
2791   off += symsize;
2792   unsigned int local_symbol_index = 1;
2793
2794   // Add STT_SECTION symbols for each Output section which needs one.
2795   for (Section_list::iterator p = this->section_list_.begin();
2796        p != this->section_list_.end();
2797        ++p)
2798     {
2799       if (!(*p)->needs_symtab_index())
2800         (*p)->set_symtab_index(-1U);
2801       else
2802         {
2803           (*p)->set_symtab_index(local_symbol_index);
2804           ++local_symbol_index;
2805           off += symsize;
2806         }
2807     }
2808
2809   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2810        p != input_objects->relobj_end();
2811        ++p)
2812     {
2813       unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2814                                                         off, symtab);
2815       off += (index - local_symbol_index) * symsize;
2816       local_symbol_index = index;
2817     }
2818
2819   unsigned int local_symcount = local_symbol_index;
2820   gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
2821
2822   off_t dynoff;
2823   size_t dyn_global_index;
2824   size_t dyncount;
2825   if (this->dynsym_section_ == NULL)
2826     {
2827       dynoff = 0;
2828       dyn_global_index = 0;
2829       dyncount = 0;
2830     }
2831   else
2832     {
2833       dyn_global_index = this->dynsym_section_->info();
2834       off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2835       dynoff = this->dynsym_section_->offset() + locsize;
2836       dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2837       gold_assert(static_cast<off_t>(dyncount * symsize)
2838                   == this->dynsym_section_->data_size() - locsize);
2839     }
2840
2841   off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2842                          &this->sympool_, &local_symcount);
2843
2844   if (!parameters->options().strip_all())
2845     {
2846       this->sympool_.set_string_offsets();
2847
2848       const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2849       Output_section* osymtab = this->make_output_section(symtab_name,
2850                                                           elfcpp::SHT_SYMTAB,
2851                                                           0, false, false,
2852                                                           false, false, false);
2853       this->symtab_section_ = osymtab;
2854
2855       Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2856                                                              align,
2857                                                              "** symtab");
2858       osymtab->add_output_section_data(pos);
2859
2860       // We generate a .symtab_shndx section if we have more than
2861       // SHN_LORESERVE sections.  Technically it is possible that we
2862       // don't need one, because it is possible that there are no
2863       // symbols in any of sections with indexes larger than
2864       // SHN_LORESERVE.  That is probably unusual, though, and it is
2865       // easier to always create one than to compute section indexes
2866       // twice (once here, once when writing out the symbols).
2867       if (shnum >= elfcpp::SHN_LORESERVE)
2868         {
2869           const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2870                                                                false, NULL);
2871           Output_section* osymtab_xindex =
2872             this->make_output_section(symtab_xindex_name,
2873                                       elfcpp::SHT_SYMTAB_SHNDX, 0, false,
2874                                       false, false, false, false);
2875
2876           size_t symcount = (off - startoff) / symsize;
2877           this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2878
2879           osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2880
2881           osymtab_xindex->set_link_section(osymtab);
2882           osymtab_xindex->set_addralign(4);
2883           osymtab_xindex->set_entsize(4);
2884
2885           osymtab_xindex->set_after_input_sections();
2886
2887           // This tells the driver code to wait until the symbol table
2888           // has written out before writing out the postprocessing
2889           // sections, including the .symtab_shndx section.
2890           this->any_postprocessing_sections_ = true;
2891         }
2892
2893       const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2894       Output_section* ostrtab = this->make_output_section(strtab_name,
2895                                                           elfcpp::SHT_STRTAB,
2896                                                           0, false, false,
2897                                                           false, false, false);
2898
2899       Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2900       ostrtab->add_output_section_data(pstr);
2901
2902       osymtab->set_file_offset(startoff);
2903       osymtab->finalize_data_size();
2904       osymtab->set_link_section(ostrtab);
2905       osymtab->set_info(local_symcount);
2906       osymtab->set_entsize(symsize);
2907
2908       *poff = off;
2909     }
2910 }
2911
2912 // Create the .shstrtab section, which holds the names of the
2913 // sections.  At the time this is called, we have created all the
2914 // output sections except .shstrtab itself.
2915
2916 Output_section*
2917 Layout::create_shstrtab()
2918 {
2919   // FIXME: We don't need to create a .shstrtab section if we are
2920   // stripping everything.
2921
2922   const char* name = this->namepool_.add(".shstrtab", false, NULL);
2923
2924   Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
2925                                                  false, false, false, false,
2926                                                  false);
2927
2928   if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
2929     {
2930       // We can't write out this section until we've set all the
2931       // section names, and we don't set the names of compressed
2932       // output sections until relocations are complete.  FIXME: With
2933       // the current names we use, this is unnecessary.
2934       os->set_after_input_sections();
2935     }
2936
2937   Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2938   os->add_output_section_data(posd);
2939
2940   return os;
2941 }
2942
2943 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
2944 // offset.
2945
2946 void
2947 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2948 {
2949   Output_section_headers* oshdrs;
2950   oshdrs = new Output_section_headers(this,
2951                                       &this->segment_list_,
2952                                       &this->section_list_,
2953                                       &this->unattached_section_list_,
2954                                       &this->namepool_,
2955                                       shstrtab_section);
2956   off_t off = align_address(*poff, oshdrs->addralign());
2957   oshdrs->set_address_and_file_offset(0, off);
2958   off += oshdrs->data_size();
2959   *poff = off;
2960   this->section_headers_ = oshdrs;
2961 }
2962
2963 // Count the allocated sections.
2964
2965 size_t
2966 Layout::allocated_output_section_count() const
2967 {
2968   size_t section_count = 0;
2969   for (Segment_list::const_iterator p = this->segment_list_.begin();
2970        p != this->segment_list_.end();
2971        ++p)
2972     section_count += (*p)->output_section_count();
2973   return section_count;
2974 }
2975
2976 // Create the dynamic symbol table.
2977
2978 void
2979 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2980                               Symbol_table* symtab,
2981                               Output_section **pdynstr,
2982                               unsigned int* plocal_dynamic_count,
2983                               std::vector<Symbol*>* pdynamic_symbols,
2984                               Versions* pversions)
2985 {
2986   // Count all the symbols in the dynamic symbol table, and set the
2987   // dynamic symbol indexes.
2988
2989   // Skip symbol 0, which is always all zeroes.
2990   unsigned int index = 1;
2991
2992   // Add STT_SECTION symbols for each Output section which needs one.
2993   for (Section_list::iterator p = this->section_list_.begin();
2994        p != this->section_list_.end();
2995        ++p)
2996     {
2997       if (!(*p)->needs_dynsym_index())
2998         (*p)->set_dynsym_index(-1U);
2999       else
3000         {
3001           (*p)->set_dynsym_index(index);
3002           ++index;
3003         }
3004     }
3005
3006   // Count the local symbols that need to go in the dynamic symbol table,
3007   // and set the dynamic symbol indexes.
3008   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3009        p != input_objects->relobj_end();
3010        ++p)
3011     {
3012       unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
3013       index = new_index;
3014     }
3015
3016   unsigned int local_symcount = index;
3017   *plocal_dynamic_count = local_symcount;
3018
3019   index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
3020                                      &this->dynpool_, pversions);
3021
3022   int symsize;
3023   unsigned int align;
3024   const int size = parameters->target().get_size();
3025   if (size == 32)
3026     {
3027       symsize = elfcpp::Elf_sizes<32>::sym_size;
3028       align = 4;
3029     }
3030   else if (size == 64)
3031     {
3032       symsize = elfcpp::Elf_sizes<64>::sym_size;
3033       align = 8;
3034     }
3035   else
3036     gold_unreachable();
3037
3038   // Create the dynamic symbol table section.
3039
3040   Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
3041                                                        elfcpp::SHT_DYNSYM,
3042                                                        elfcpp::SHF_ALLOC,
3043                                                        false, false, true,
3044                                                        false, false, false);
3045
3046   Output_section_data* odata = new Output_data_fixed_space(index * symsize,
3047                                                            align,
3048                                                            "** dynsym");
3049   dynsym->add_output_section_data(odata);
3050
3051   dynsym->set_info(local_symcount);
3052   dynsym->set_entsize(symsize);
3053   dynsym->set_addralign(align);
3054
3055   this->dynsym_section_ = dynsym;
3056
3057   Output_data_dynamic* const odyn = this->dynamic_data_;
3058   odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
3059   odyn->add_constant(elfcpp::DT_SYMENT, symsize);
3060
3061   // If there are more than SHN_LORESERVE allocated sections, we
3062   // create a .dynsym_shndx section.  It is possible that we don't
3063   // need one, because it is possible that there are no dynamic
3064   // symbols in any of the sections with indexes larger than
3065   // SHN_LORESERVE.  This is probably unusual, though, and at this
3066   // time we don't know the actual section indexes so it is
3067   // inconvenient to check.
3068   if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
3069     {
3070       Output_section* dynsym_xindex =
3071         this->choose_output_section(NULL, ".dynsym_shndx",
3072                                     elfcpp::SHT_SYMTAB_SHNDX,
3073                                     elfcpp::SHF_ALLOC,
3074                                     false, false, true, false, false, false);
3075
3076       this->dynsym_xindex_ = new Output_symtab_xindex(index);
3077
3078       dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
3079
3080       dynsym_xindex->set_link_section(dynsym);
3081       dynsym_xindex->set_addralign(4);
3082       dynsym_xindex->set_entsize(4);
3083
3084       dynsym_xindex->set_after_input_sections();
3085
3086       // This tells the driver code to wait until the symbol table has
3087       // written out before writing out the postprocessing sections,
3088       // including the .dynsym_shndx section.
3089       this->any_postprocessing_sections_ = true;
3090     }
3091
3092   // Create the dynamic string table section.
3093
3094   Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
3095                                                        elfcpp::SHT_STRTAB,
3096                                                        elfcpp::SHF_ALLOC,
3097                                                        false, false, true,
3098                                                        false, false, false);
3099
3100   Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
3101   dynstr->add_output_section_data(strdata);
3102
3103   dynsym->set_link_section(dynstr);
3104   this->dynamic_section_->set_link_section(dynstr);
3105
3106   odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
3107   odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
3108
3109   *pdynstr = dynstr;
3110
3111   // Create the hash tables.
3112
3113   if (strcmp(parameters->options().hash_style(), "sysv") == 0
3114       || strcmp(parameters->options().hash_style(), "both") == 0)
3115     {
3116       unsigned char* phash;
3117       unsigned int hashlen;
3118       Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
3119                                     &phash, &hashlen);
3120
3121       Output_section* hashsec = this->choose_output_section(NULL, ".hash",
3122                                                             elfcpp::SHT_HASH,
3123                                                             elfcpp::SHF_ALLOC,
3124                                                             false, false, true,
3125                                                             false, false,
3126                                                             false);
3127
3128       Output_section_data* hashdata = new Output_data_const_buffer(phash,
3129                                                                    hashlen,
3130                                                                    align,
3131                                                                    "** hash");
3132       hashsec->add_output_section_data(hashdata);
3133
3134       hashsec->set_link_section(dynsym);
3135       hashsec->set_entsize(4);
3136
3137       odyn->add_section_address(elfcpp::DT_HASH, hashsec);
3138     }
3139
3140   if (strcmp(parameters->options().hash_style(), "gnu") == 0
3141       || strcmp(parameters->options().hash_style(), "both") == 0)
3142     {
3143       unsigned char* phash;
3144       unsigned int hashlen;
3145       Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
3146                                     &phash, &hashlen);
3147
3148       Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
3149                                                             elfcpp::SHT_GNU_HASH,
3150                                                             elfcpp::SHF_ALLOC,
3151                                                             false, false, true,
3152                                                             false, false,
3153                                                             false);
3154
3155       Output_section_data* hashdata = new Output_data_const_buffer(phash,
3156                                                                    hashlen,
3157                                                                    align,
3158                                                                    "** hash");
3159       hashsec->add_output_section_data(hashdata);
3160
3161       hashsec->set_link_section(dynsym);
3162
3163       // For a 64-bit target, the entries in .gnu.hash do not have a
3164       // uniform size, so we only set the entry size for a 32-bit
3165       // target.
3166       if (parameters->target().get_size() == 32)
3167         hashsec->set_entsize(4);
3168
3169       odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
3170     }
3171 }
3172
3173 // Assign offsets to each local portion of the dynamic symbol table.
3174
3175 void
3176 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
3177 {
3178   Output_section* dynsym = this->dynsym_section_;
3179   gold_assert(dynsym != NULL);
3180
3181   off_t off = dynsym->offset();
3182
3183   // Skip the dummy symbol at the start of the section.
3184   off += dynsym->entsize();
3185
3186   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3187        p != input_objects->relobj_end();
3188        ++p)
3189     {
3190       unsigned int count = (*p)->set_local_dynsym_offset(off);
3191       off += count * dynsym->entsize();
3192     }
3193 }
3194
3195 // Create the version sections.
3196
3197 void
3198 Layout::create_version_sections(const Versions* versions,
3199                                 const Symbol_table* symtab,
3200                                 unsigned int local_symcount,
3201                                 const std::vector<Symbol*>& dynamic_symbols,
3202                                 const Output_section* dynstr)
3203 {
3204   if (!versions->any_defs() && !versions->any_needs())
3205     return;
3206
3207   switch (parameters->size_and_endianness())
3208     {
3209 #ifdef HAVE_TARGET_32_LITTLE
3210     case Parameters::TARGET_32_LITTLE:
3211       this->sized_create_version_sections<32, false>(versions, symtab,
3212                                                      local_symcount,
3213                                                      dynamic_symbols, dynstr);
3214       break;
3215 #endif
3216 #ifdef HAVE_TARGET_32_BIG
3217     case Parameters::TARGET_32_BIG:
3218       this->sized_create_version_sections<32, true>(versions, symtab,
3219                                                     local_symcount,
3220                                                     dynamic_symbols, dynstr);
3221       break;
3222 #endif
3223 #ifdef HAVE_TARGET_64_LITTLE
3224     case Parameters::TARGET_64_LITTLE:
3225       this->sized_create_version_sections<64, false>(versions, symtab,
3226                                                      local_symcount,
3227                                                      dynamic_symbols, dynstr);
3228       break;
3229 #endif
3230 #ifdef HAVE_TARGET_64_BIG
3231     case Parameters::TARGET_64_BIG:
3232       this->sized_create_version_sections<64, true>(versions, symtab,
3233                                                     local_symcount,
3234                                                     dynamic_symbols, dynstr);
3235       break;
3236 #endif
3237     default:
3238       gold_unreachable();
3239     }
3240 }
3241
3242 // Create the version sections, sized version.
3243
3244 template<int size, bool big_endian>
3245 void
3246 Layout::sized_create_version_sections(
3247     const Versions* versions,
3248     const Symbol_table* symtab,
3249     unsigned int local_symcount,
3250     const std::vector<Symbol*>& dynamic_symbols,
3251     const Output_section* dynstr)
3252 {
3253   Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3254                                                      elfcpp::SHT_GNU_versym,
3255                                                      elfcpp::SHF_ALLOC,
3256                                                      false, false, true,
3257                                                      false, false, false);
3258
3259   unsigned char* vbuf;
3260   unsigned int vsize;
3261   versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3262                                                       local_symcount,
3263                                                       dynamic_symbols,
3264                                                       &vbuf, &vsize);
3265
3266   Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3267                                                             "** versions");
3268
3269   vsec->add_output_section_data(vdata);
3270   vsec->set_entsize(2);
3271   vsec->set_link_section(this->dynsym_section_);
3272
3273   Output_data_dynamic* const odyn = this->dynamic_data_;
3274   odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3275
3276   if (versions->any_defs())
3277     {
3278       Output_section* vdsec;
3279       vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3280                                          elfcpp::SHT_GNU_verdef,
3281                                          elfcpp::SHF_ALLOC,
3282                                          false, false, true, false, false,
3283                                          false);
3284
3285       unsigned char* vdbuf;
3286       unsigned int vdsize;
3287       unsigned int vdentries;
3288       versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3289                                                        &vdsize, &vdentries);
3290
3291       Output_section_data* vddata =
3292         new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3293
3294       vdsec->add_output_section_data(vddata);
3295       vdsec->set_link_section(dynstr);
3296       vdsec->set_info(vdentries);
3297
3298       odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3299       odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3300     }
3301
3302   if (versions->any_needs())
3303     {
3304       Output_section* vnsec;
3305       vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3306                                           elfcpp::SHT_GNU_verneed,
3307                                           elfcpp::SHF_ALLOC,
3308                                           false, false, true, false, false,
3309                                           false);
3310
3311       unsigned char* vnbuf;
3312       unsigned int vnsize;
3313       unsigned int vnentries;
3314       versions->need_section_contents<size, big_endian>(&this->dynpool_,
3315                                                         &vnbuf, &vnsize,
3316                                                         &vnentries);
3317
3318       Output_section_data* vndata =
3319         new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3320
3321       vnsec->add_output_section_data(vndata);
3322       vnsec->set_link_section(dynstr);
3323       vnsec->set_info(vnentries);
3324
3325       odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3326       odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3327     }
3328 }
3329
3330 // Create the .interp section and PT_INTERP segment.
3331
3332 void
3333 Layout::create_interp(const Target* target)
3334 {
3335   const char* interp = parameters->options().dynamic_linker();
3336   if (interp == NULL)
3337     {
3338       interp = target->dynamic_linker();
3339       gold_assert(interp != NULL);
3340     }
3341
3342   size_t len = strlen(interp) + 1;
3343
3344   Output_section_data* odata = new Output_data_const(interp, len, 1);
3345
3346   Output_section* osec = this->choose_output_section(NULL, ".interp",
3347                                                      elfcpp::SHT_PROGBITS,
3348                                                      elfcpp::SHF_ALLOC,
3349                                                      false, true, true,
3350                                                      false, false, false);
3351   osec->add_output_section_data(odata);
3352
3353   if (!this->script_options_->saw_phdrs_clause())
3354     {
3355       Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3356                                                        elfcpp::PF_R);
3357       oseg->add_output_section(osec, elfcpp::PF_R, false);
3358     }
3359 }
3360
3361 // Add dynamic tags for the PLT and the dynamic relocs.  This is
3362 // called by the target-specific code.  This does nothing if not doing
3363 // a dynamic link.
3364
3365 // USE_REL is true for REL relocs rather than RELA relocs.
3366
3367 // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
3368
3369 // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
3370 // and we also set DT_PLTREL.  We use PLT_REL's output section, since
3371 // some targets have multiple reloc sections in PLT_REL.
3372
3373 // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
3374 // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT.
3375
3376 // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
3377 // executable.
3378
3379 void
3380 Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
3381                                 const Output_data* plt_rel,
3382                                 const Output_data_reloc_generic* dyn_rel,
3383                                 bool add_debug, bool dynrel_includes_plt)
3384 {
3385   Output_data_dynamic* odyn = this->dynamic_data_;
3386   if (odyn == NULL)
3387     return;
3388
3389   if (plt_got != NULL && plt_got->output_section() != NULL)
3390     odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
3391
3392   if (plt_rel != NULL && plt_rel->output_section() != NULL)
3393     {
3394       odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
3395       odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
3396       odyn->add_constant(elfcpp::DT_PLTREL,
3397                          use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
3398     }
3399
3400   if (dyn_rel != NULL && dyn_rel->output_section() != NULL)
3401     {
3402       odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
3403                                 dyn_rel);
3404       if (plt_rel != NULL && dynrel_includes_plt)
3405         odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3406                                dyn_rel, plt_rel);
3407       else
3408         odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3409                                dyn_rel);
3410       const int size = parameters->target().get_size();
3411       elfcpp::DT rel_tag;
3412       int rel_size;
3413       if (use_rel)
3414         {
3415           rel_tag = elfcpp::DT_RELENT;
3416           if (size == 32)
3417             rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
3418           else if (size == 64)
3419             rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
3420           else
3421             gold_unreachable();
3422         }
3423       else
3424         {
3425           rel_tag = elfcpp::DT_RELAENT;
3426           if (size == 32)
3427             rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
3428           else if (size == 64)
3429             rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
3430           else
3431             gold_unreachable();
3432         }
3433       odyn->add_constant(rel_tag, rel_size);
3434
3435       if (parameters->options().combreloc())
3436         {
3437           size_t c = dyn_rel->relative_reloc_count();
3438           if (c > 0)
3439             odyn->add_constant((use_rel
3440                                 ? elfcpp::DT_RELCOUNT
3441                                 : elfcpp::DT_RELACOUNT),
3442                                c);
3443         }
3444     }
3445
3446   if (add_debug && !parameters->options().shared())
3447     {
3448       // The value of the DT_DEBUG tag is filled in by the dynamic
3449       // linker at run time, and used by the debugger.
3450       odyn->add_constant(elfcpp::DT_DEBUG, 0);
3451     }
3452 }
3453
3454 // Finish the .dynamic section and PT_DYNAMIC segment.
3455
3456 void
3457 Layout::finish_dynamic_section(const Input_objects* input_objects,
3458                                const Symbol_table* symtab)
3459 {
3460   if (!this->script_options_->saw_phdrs_clause())
3461     {
3462       Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3463                                                        (elfcpp::PF_R
3464                                                         | elfcpp::PF_W));
3465       oseg->add_output_section(this->dynamic_section_,
3466                                elfcpp::PF_R | elfcpp::PF_W,
3467                                false);
3468     }
3469
3470   Output_data_dynamic* const odyn = this->dynamic_data_;
3471
3472   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3473        p != input_objects->dynobj_end();
3474        ++p)
3475     {
3476       if (!(*p)->is_needed()
3477           && (*p)->input_file()->options().as_needed())
3478         {
3479           // This dynamic object was linked with --as-needed, but it
3480           // is not needed.
3481           continue;
3482         }
3483
3484       odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3485     }
3486
3487   if (parameters->options().shared())
3488     {
3489       const char* soname = parameters->options().soname();
3490       if (soname != NULL)
3491         odyn->add_string(elfcpp::DT_SONAME, soname);
3492     }
3493
3494   Symbol* sym = symtab->lookup(parameters->options().init());
3495   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3496     odyn->add_symbol(elfcpp::DT_INIT, sym);
3497
3498   sym = symtab->lookup(parameters->options().fini());
3499   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3500     odyn->add_symbol(elfcpp::DT_FINI, sym);
3501
3502   // Look for .init_array, .preinit_array and .fini_array by checking
3503   // section types.
3504   for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3505       p != this->section_list_.end();
3506       ++p)
3507     switch((*p)->type())
3508       {
3509       case elfcpp::SHT_FINI_ARRAY:
3510         odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3511         odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p); 
3512         break;
3513       case elfcpp::SHT_INIT_ARRAY:
3514         odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3515         odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p); 
3516         break;
3517       case elfcpp::SHT_PREINIT_ARRAY:
3518         odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3519         odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p); 
3520         break;
3521       default:
3522         break;
3523       }
3524   
3525   // Add a DT_RPATH entry if needed.
3526   const General_options::Dir_list& rpath(parameters->options().rpath());
3527   if (!rpath.empty())
3528     {
3529       std::string rpath_val;
3530       for (General_options::Dir_list::const_iterator p = rpath.begin();
3531            p != rpath.end();
3532            ++p)
3533         {
3534           if (rpath_val.empty())
3535             rpath_val = p->name();
3536           else
3537             {
3538               // Eliminate duplicates.
3539               General_options::Dir_list::const_iterator q;
3540               for (q = rpath.begin(); q != p; ++q)
3541                 if (q->name() == p->name())
3542                   break;
3543               if (q == p)
3544                 {
3545                   rpath_val += ':';
3546                   rpath_val += p->name();
3547                 }
3548             }
3549         }
3550
3551       odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3552       if (parameters->options().enable_new_dtags())
3553         odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3554     }
3555
3556   // Look for text segments that have dynamic relocations.
3557   bool have_textrel = false;
3558   if (!this->script_options_->saw_sections_clause())
3559     {
3560       for (Segment_list::const_iterator p = this->segment_list_.begin();
3561            p != this->segment_list_.end();
3562            ++p)
3563         {
3564           if (((*p)->flags() & elfcpp::PF_W) == 0
3565               && (*p)->dynamic_reloc_count() > 0)
3566             {
3567               have_textrel = true;
3568               break;
3569             }
3570         }
3571     }
3572   else
3573     {
3574       // We don't know the section -> segment mapping, so we are
3575       // conservative and just look for readonly sections with
3576       // relocations.  If those sections wind up in writable segments,
3577       // then we have created an unnecessary DT_TEXTREL entry.
3578       for (Section_list::const_iterator p = this->section_list_.begin();
3579            p != this->section_list_.end();
3580            ++p)
3581         {
3582           if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3583               && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3584               && ((*p)->dynamic_reloc_count() > 0))
3585             {
3586               have_textrel = true;
3587               break;
3588             }
3589         }
3590     }
3591
3592   // Add a DT_FLAGS entry. We add it even if no flags are set so that
3593   // post-link tools can easily modify these flags if desired.
3594   unsigned int flags = 0;
3595   if (have_textrel)
3596     {
3597       // Add a DT_TEXTREL for compatibility with older loaders.
3598       odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3599       flags |= elfcpp::DF_TEXTREL;
3600
3601       if (parameters->options().text())
3602         gold_error(_("read-only segment has dynamic relocations"));
3603       else if (parameters->options().warn_shared_textrel()
3604                && parameters->options().shared())
3605         gold_warning(_("shared library text segment is not shareable"));
3606     }
3607   if (parameters->options().shared() && this->has_static_tls())
3608     flags |= elfcpp::DF_STATIC_TLS;
3609   if (parameters->options().origin())
3610     flags |= elfcpp::DF_ORIGIN;
3611   if (parameters->options().Bsymbolic())
3612     {
3613       flags |= elfcpp::DF_SYMBOLIC;
3614       // Add DT_SYMBOLIC for compatibility with older loaders.
3615       odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3616     }
3617   if (parameters->options().now())
3618     flags |= elfcpp::DF_BIND_NOW;
3619   odyn->add_constant(elfcpp::DT_FLAGS, flags);
3620
3621   flags = 0;
3622   if (parameters->options().initfirst())
3623     flags |= elfcpp::DF_1_INITFIRST;
3624   if (parameters->options().interpose())
3625     flags |= elfcpp::DF_1_INTERPOSE;
3626   if (parameters->options().loadfltr())
3627     flags |= elfcpp::DF_1_LOADFLTR;
3628   if (parameters->options().nodefaultlib())
3629     flags |= elfcpp::DF_1_NODEFLIB;
3630   if (parameters->options().nodelete())
3631     flags |= elfcpp::DF_1_NODELETE;
3632   if (parameters->options().nodlopen())
3633     flags |= elfcpp::DF_1_NOOPEN;
3634   if (parameters->options().nodump())
3635     flags |= elfcpp::DF_1_NODUMP;
3636   if (!parameters->options().shared())
3637     flags &= ~(elfcpp::DF_1_INITFIRST
3638                | elfcpp::DF_1_NODELETE
3639                | elfcpp::DF_1_NOOPEN);
3640   if (parameters->options().origin())
3641     flags |= elfcpp::DF_1_ORIGIN;
3642   if (parameters->options().now())
3643     flags |= elfcpp::DF_1_NOW;
3644   if (flags)
3645     odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3646 }
3647
3648 // Set the size of the _DYNAMIC symbol table to be the size of the
3649 // dynamic data.
3650
3651 void
3652 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
3653 {
3654   Output_data_dynamic* const odyn = this->dynamic_data_;
3655   odyn->finalize_data_size();
3656   off_t data_size = odyn->data_size();
3657   const int size = parameters->target().get_size();
3658   if (size == 32)
3659     symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
3660   else if (size == 64)
3661     symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
3662   else
3663     gold_unreachable();
3664 }
3665
3666 // The mapping of input section name prefixes to output section names.
3667 // In some cases one prefix is itself a prefix of another prefix; in
3668 // such a case the longer prefix must come first.  These prefixes are
3669 // based on the GNU linker default ELF linker script.
3670
3671 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3672 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3673 {
3674   MAPPING_INIT(".text.", ".text"),
3675   MAPPING_INIT(".ctors.", ".ctors"),
3676   MAPPING_INIT(".dtors.", ".dtors"),
3677   MAPPING_INIT(".rodata.", ".rodata"),
3678   MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3679   MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3680   MAPPING_INIT(".data.", ".data"),
3681   MAPPING_INIT(".bss.", ".bss"),
3682   MAPPING_INIT(".tdata.", ".tdata"),
3683   MAPPING_INIT(".tbss.", ".tbss"),
3684   MAPPING_INIT(".init_array.", ".init_array"),
3685   MAPPING_INIT(".fini_array.", ".fini_array"),
3686   MAPPING_INIT(".sdata.", ".sdata"),
3687   MAPPING_INIT(".sbss.", ".sbss"),
3688   // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3689   // differently depending on whether it is creating a shared library.
3690   MAPPING_INIT(".sdata2.", ".sdata"),
3691   MAPPING_INIT(".sbss2.", ".sbss"),
3692   MAPPING_INIT(".lrodata.", ".lrodata"),
3693   MAPPING_INIT(".ldata.", ".ldata"),
3694   MAPPING_INIT(".lbss.", ".lbss"),
3695   MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3696   MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3697   MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3698   MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3699   MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3700   MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3701   MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3702   MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3703   MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3704   MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3705   MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3706   MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3707   MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3708   MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3709   MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3710   MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3711   MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3712   MAPPING_INIT(".ARM.extab", ".ARM.extab"),
3713   MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3714   MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
3715   MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3716 };
3717 #undef MAPPING_INIT
3718
3719 const int Layout::section_name_mapping_count =
3720   (sizeof(Layout::section_name_mapping)
3721    / sizeof(Layout::section_name_mapping[0]));
3722
3723 // Choose the output section name to use given an input section name.
3724 // Set *PLEN to the length of the name.  *PLEN is initialized to the
3725 // length of NAME.
3726
3727 const char*
3728 Layout::output_section_name(const char* name, size_t* plen)
3729 {
3730   // gcc 4.3 generates the following sorts of section names when it
3731   // needs a section name specific to a function:
3732   //   .text.FN
3733   //   .rodata.FN
3734   //   .sdata2.FN
3735   //   .data.FN
3736   //   .data.rel.FN
3737   //   .data.rel.local.FN
3738   //   .data.rel.ro.FN
3739   //   .data.rel.ro.local.FN
3740   //   .sdata.FN
3741   //   .bss.FN
3742   //   .sbss.FN
3743   //   .tdata.FN
3744   //   .tbss.FN
3745
3746   // The GNU linker maps all of those to the part before the .FN,
3747   // except that .data.rel.local.FN is mapped to .data, and
3748   // .data.rel.ro.local.FN is mapped to .data.rel.ro.  The sections
3749   // beginning with .data.rel.ro.local are grouped together.
3750
3751   // For an anonymous namespace, the string FN can contain a '.'.
3752
3753   // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3754   // GNU linker maps to .rodata.
3755
3756   // The .data.rel.ro sections are used with -z relro.  The sections
3757   // are recognized by name.  We use the same names that the GNU
3758   // linker does for these sections.
3759
3760   // It is hard to handle this in a principled way, so we don't even
3761   // try.  We use a table of mappings.  If the input section name is
3762   // not found in the table, we simply use it as the output section
3763   // name.
3764
3765   const Section_name_mapping* psnm = section_name_mapping;
3766   for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3767     {
3768       if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3769         {
3770           *plen = psnm->tolen;
3771           return psnm->to;
3772         }
3773     }
3774
3775   return name;
3776 }
3777
3778 // Check if a comdat group or .gnu.linkonce section with the given
3779 // NAME is selected for the link.  If there is already a section,
3780 // *KEPT_SECTION is set to point to the existing section and the
3781 // function returns false.  Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3782 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3783 // *KEPT_SECTION is set to the internal copy and the function returns
3784 // true.
3785
3786 bool
3787 Layout::find_or_add_kept_section(const std::string& name,
3788                                  Relobj* object,
3789                                  unsigned int shndx,
3790                                  bool is_comdat,
3791                                  bool is_group_name,
3792                                  Kept_section** kept_section)
3793 {
3794   // It's normal to see a couple of entries here, for the x86 thunk
3795   // sections.  If we see more than a few, we're linking a C++
3796   // program, and we resize to get more space to minimize rehashing.
3797   if (this->signatures_.size() > 4
3798       && !this->resized_signatures_)
3799     {
3800       reserve_unordered_map(&this->signatures_,
3801                             this->number_of_input_files_ * 64);
3802       this->resized_signatures_ = true;
3803     }
3804
3805   Kept_section candidate;
3806   std::pair<Signatures::iterator, bool> ins =
3807     this->signatures_.insert(std::make_pair(name, candidate));
3808
3809   if (kept_section != NULL)
3810     *kept_section = &ins.first->second;
3811   if (ins.second)
3812     {
3813       // This is the first time we've seen this signature.
3814       ins.first->second.set_object(object);
3815       ins.first->second.set_shndx(shndx);
3816       if (is_comdat)
3817         ins.first->second.set_is_comdat();
3818       if (is_group_name)
3819         ins.first->second.set_is_group_name();
3820       return true;
3821     }
3822
3823   // We have already seen this signature.
3824
3825   if (ins.first->second.is_group_name())
3826     {
3827       // We've already seen a real section group with this signature.
3828       // If the kept group is from a plugin object, and we're in the
3829       // replacement phase, accept the new one as a replacement.
3830       if (ins.first->second.object() == NULL
3831           && parameters->options().plugins()->in_replacement_phase())
3832         {
3833           ins.first->second.set_object(object);
3834           ins.first->second.set_shndx(shndx);
3835           return true;
3836         }
3837       return false;
3838     }
3839   else if (is_group_name)
3840     {
3841       // This is a real section group, and we've already seen a
3842       // linkonce section with this signature.  Record that we've seen
3843       // a section group, and don't include this section group.
3844       ins.first->second.set_is_group_name();
3845       return false;
3846     }
3847   else
3848     {
3849       // We've already seen a linkonce section and this is a linkonce
3850       // section.  These don't block each other--this may be the same
3851       // symbol name with different section types.
3852       return true;
3853     }
3854 }
3855
3856 // Store the allocated sections into the section list.
3857
3858 void
3859 Layout::get_allocated_sections(Section_list* section_list) const
3860 {
3861   for (Section_list::const_iterator p = this->section_list_.begin();
3862        p != this->section_list_.end();
3863        ++p)
3864     if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3865       section_list->push_back(*p);
3866 }
3867
3868 // Create an output segment.
3869
3870 Output_segment*
3871 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3872 {
3873   gold_assert(!parameters->options().relocatable());
3874   Output_segment* oseg = new Output_segment(type, flags);
3875   this->segment_list_.push_back(oseg);
3876
3877   if (type == elfcpp::PT_TLS)
3878     this->tls_segment_ = oseg;
3879   else if (type == elfcpp::PT_GNU_RELRO)
3880     this->relro_segment_ = oseg;
3881
3882   return oseg;
3883 }
3884
3885 // Write out the Output_sections.  Most won't have anything to write,
3886 // since most of the data will come from input sections which are
3887 // handled elsewhere.  But some Output_sections do have Output_data.
3888
3889 void
3890 Layout::write_output_sections(Output_file* of) const
3891 {
3892   for (Section_list::const_iterator p = this->section_list_.begin();
3893        p != this->section_list_.end();
3894        ++p)
3895     {
3896       if (!(*p)->after_input_sections())
3897         (*p)->write(of);
3898     }
3899 }
3900
3901 // Write out data not associated with a section or the symbol table.
3902
3903 void
3904 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
3905 {
3906   if (!parameters->options().strip_all())
3907     {
3908       const Output_section* symtab_section = this->symtab_section_;
3909       for (Section_list::const_iterator p = this->section_list_.begin();
3910            p != this->section_list_.end();
3911            ++p)
3912         {
3913           if ((*p)->needs_symtab_index())
3914             {
3915               gold_assert(symtab_section != NULL);
3916               unsigned int index = (*p)->symtab_index();
3917               gold_assert(index > 0 && index != -1U);
3918               off_t off = (symtab_section->offset()
3919                            + index * symtab_section->entsize());
3920               symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3921             }
3922         }
3923     }
3924
3925   const Output_section* dynsym_section = this->dynsym_section_;
3926   for (Section_list::const_iterator p = this->section_list_.begin();
3927        p != this->section_list_.end();
3928        ++p)
3929     {
3930       if ((*p)->needs_dynsym_index())
3931         {
3932           gold_assert(dynsym_section != NULL);
3933           unsigned int index = (*p)->dynsym_index();
3934           gold_assert(index > 0 && index != -1U);
3935           off_t off = (dynsym_section->offset()
3936                        + index * dynsym_section->entsize());
3937           symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3938         }
3939     }
3940
3941   // Write out the Output_data which are not in an Output_section.
3942   for (Data_list::const_iterator p = this->special_output_list_.begin();
3943        p != this->special_output_list_.end();
3944        ++p)
3945     (*p)->write(of);
3946 }
3947
3948 // Write out the Output_sections which can only be written after the
3949 // input sections are complete.
3950
3951 void
3952 Layout::write_sections_after_input_sections(Output_file* of)
3953 {
3954   // Determine the final section offsets, and thus the final output
3955   // file size.  Note we finalize the .shstrab last, to allow the
3956   // after_input_section sections to modify their section-names before
3957   // writing.
3958   if (this->any_postprocessing_sections_)
3959     {
3960       off_t off = this->output_file_size_;
3961       off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3962
3963       // Now that we've finalized the names, we can finalize the shstrab.
3964       off =
3965         this->set_section_offsets(off,
3966                                   STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3967
3968       if (off > this->output_file_size_)
3969         {
3970           of->resize(off);
3971           this->output_file_size_ = off;
3972         }
3973     }
3974
3975   for (Section_list::const_iterator p = this->section_list_.begin();
3976        p != this->section_list_.end();
3977        ++p)
3978     {
3979       if ((*p)->after_input_sections())
3980         (*p)->write(of);
3981     }
3982
3983   this->section_headers_->write(of);
3984 }
3985
3986 // If the build ID requires computing a checksum, do so here, and
3987 // write it out.  We compute a checksum over the entire file because
3988 // that is simplest.
3989
3990 void
3991 Layout::write_build_id(Output_file* of) const
3992 {
3993   if (this->build_id_note_ == NULL)
3994     return;
3995
3996   const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3997
3998   unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3999                                           this->build_id_note_->data_size());
4000
4001   const char* style = parameters->options().build_id();
4002   if (strcmp(style, "sha1") == 0)
4003     {
4004       sha1_ctx ctx;
4005       sha1_init_ctx(&ctx);
4006       sha1_process_bytes(iv, this->output_file_size_, &ctx);
4007       sha1_finish_ctx(&ctx, ov);
4008     }
4009   else if (strcmp(style, "md5") == 0)
4010     {
4011       md5_ctx ctx;
4012       md5_init_ctx(&ctx);
4013       md5_process_bytes(iv, this->output_file_size_, &ctx);
4014       md5_finish_ctx(&ctx, ov);
4015     }
4016   else
4017     gold_unreachable();
4018
4019   of->write_output_view(this->build_id_note_->offset(),
4020                         this->build_id_note_->data_size(),
4021                         ov);
4022
4023   of->free_input_view(0, this->output_file_size_, iv);
4024 }
4025
4026 // Write out a binary file.  This is called after the link is
4027 // complete.  IN is the temporary output file we used to generate the
4028 // ELF code.  We simply walk through the segments, read them from
4029 // their file offset in IN, and write them to their load address in
4030 // the output file.  FIXME: with a bit more work, we could support
4031 // S-records and/or Intel hex format here.
4032
4033 void
4034 Layout::write_binary(Output_file* in) const
4035 {
4036   gold_assert(parameters->options().oformat_enum()
4037               == General_options::OBJECT_FORMAT_BINARY);
4038
4039   // Get the size of the binary file.
4040   uint64_t max_load_address = 0;
4041   for (Segment_list::const_iterator p = this->segment_list_.begin();
4042        p != this->segment_list_.end();
4043        ++p)
4044     {
4045       if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4046         {
4047           uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
4048           if (max_paddr > max_load_address)
4049             max_load_address = max_paddr;
4050         }
4051     }
4052
4053   Output_file out(parameters->options().output_file_name());
4054   out.open(max_load_address);
4055
4056   for (Segment_list::const_iterator p = this->segment_list_.begin();
4057        p != this->segment_list_.end();
4058        ++p)
4059     {
4060       if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4061         {
4062           const unsigned char* vin = in->get_input_view((*p)->offset(),
4063                                                         (*p)->filesz());
4064           unsigned char* vout = out.get_output_view((*p)->paddr(),
4065                                                     (*p)->filesz());
4066           memcpy(vout, vin, (*p)->filesz());
4067           out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
4068           in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
4069         }
4070     }
4071
4072   out.close();
4073 }
4074
4075 // Print the output sections to the map file.
4076
4077 void
4078 Layout::print_to_mapfile(Mapfile* mapfile) const
4079 {
4080   for (Segment_list::const_iterator p = this->segment_list_.begin();
4081        p != this->segment_list_.end();
4082        ++p)
4083     (*p)->print_sections_to_mapfile(mapfile);
4084 }
4085
4086 // Print statistical information to stderr.  This is used for --stats.
4087
4088 void
4089 Layout::print_stats() const
4090 {
4091   this->namepool_.print_stats("section name pool");
4092   this->sympool_.print_stats("output symbol name pool");
4093   this->dynpool_.print_stats("dynamic name pool");
4094
4095   for (Section_list::const_iterator p = this->section_list_.begin();
4096        p != this->section_list_.end();
4097        ++p)
4098     (*p)->print_merge_stats();
4099 }
4100
4101 // Write_sections_task methods.
4102
4103 // We can always run this task.
4104
4105 Task_token*
4106 Write_sections_task::is_runnable()
4107 {
4108   return NULL;
4109 }
4110
4111 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
4112 // when finished.
4113
4114 void
4115 Write_sections_task::locks(Task_locker* tl)
4116 {
4117   tl->add(this, this->output_sections_blocker_);
4118   tl->add(this, this->final_blocker_);
4119 }
4120
4121 // Run the task--write out the data.
4122
4123 void
4124 Write_sections_task::run(Workqueue*)
4125 {
4126   this->layout_->write_output_sections(this->of_);
4127 }
4128
4129 // Write_data_task methods.
4130
4131 // We can always run this task.
4132
4133 Task_token*
4134 Write_data_task::is_runnable()
4135 {
4136   return NULL;
4137 }
4138
4139 // We need to unlock FINAL_BLOCKER when finished.
4140
4141 void
4142 Write_data_task::locks(Task_locker* tl)
4143 {
4144   tl->add(this, this->final_blocker_);
4145 }
4146
4147 // Run the task--write out the data.
4148
4149 void
4150 Write_data_task::run(Workqueue*)
4151 {
4152   this->layout_->write_data(this->symtab_, this->of_);
4153 }
4154
4155 // Write_symbols_task methods.
4156
4157 // We can always run this task.
4158
4159 Task_token*
4160 Write_symbols_task::is_runnable()
4161 {
4162   return NULL;
4163 }
4164
4165 // We need to unlock FINAL_BLOCKER when finished.
4166
4167 void
4168 Write_symbols_task::locks(Task_locker* tl)
4169 {
4170   tl->add(this, this->final_blocker_);
4171 }
4172
4173 // Run the task--write out the symbols.
4174
4175 void
4176 Write_symbols_task::run(Workqueue*)
4177 {
4178   this->symtab_->write_globals(this->sympool_, this->dynpool_,
4179                                this->layout_->symtab_xindex(),
4180                                this->layout_->dynsym_xindex(), this->of_);
4181 }
4182
4183 // Write_after_input_sections_task methods.
4184
4185 // We can only run this task after the input sections have completed.
4186
4187 Task_token*
4188 Write_after_input_sections_task::is_runnable()
4189 {
4190   if (this->input_sections_blocker_->is_blocked())
4191     return this->input_sections_blocker_;
4192   return NULL;
4193 }
4194
4195 // We need to unlock FINAL_BLOCKER when finished.
4196
4197 void
4198 Write_after_input_sections_task::locks(Task_locker* tl)
4199 {
4200   tl->add(this, this->final_blocker_);
4201 }
4202
4203 // Run the task.
4204
4205 void
4206 Write_after_input_sections_task::run(Workqueue*)
4207 {
4208   this->layout_->write_sections_after_input_sections(this->of_);
4209 }
4210
4211 // Close_task_runner methods.
4212
4213 // Run the task--close the file.
4214
4215 void
4216 Close_task_runner::run(Workqueue*, const Task*)
4217 {
4218   // If we need to compute a checksum for the BUILD if, we do so here.
4219   this->layout_->write_build_id(this->of_);
4220
4221   // If we've been asked to create a binary file, we do so here.
4222   if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
4223     this->layout_->write_binary(this->of_);
4224
4225   this->of_->close();
4226 }
4227
4228 // Instantiate the templates we need.  We could use the configure
4229 // script to restrict this to only the ones for implemented targets.
4230
4231 #ifdef HAVE_TARGET_32_LITTLE
4232 template
4233 Output_section*
4234 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
4235                           const char* name,
4236                           const elfcpp::Shdr<32, false>& shdr,
4237                           unsigned int, unsigned int, off_t*);
4238 #endif
4239
4240 #ifdef HAVE_TARGET_32_BIG
4241 template
4242 Output_section*
4243 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
4244                          const char* name,
4245                          const elfcpp::Shdr<32, true>& shdr,
4246                          unsigned int, unsigned int, off_t*);
4247 #endif
4248
4249 #ifdef HAVE_TARGET_64_LITTLE
4250 template
4251 Output_section*
4252 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
4253                           const char* name,
4254                           const elfcpp::Shdr<64, false>& shdr,
4255                           unsigned int, unsigned int, off_t*);
4256 #endif
4257
4258 #ifdef HAVE_TARGET_64_BIG
4259 template
4260 Output_section*
4261 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
4262                          const char* name,
4263                          const elfcpp::Shdr<64, true>& shdr,
4264                          unsigned int, unsigned int, off_t*);
4265 #endif
4266
4267 #ifdef HAVE_TARGET_32_LITTLE
4268 template
4269 Output_section*
4270 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
4271                                 unsigned int reloc_shndx,
4272                                 const elfcpp::Shdr<32, false>& shdr,
4273                                 Output_section* data_section,
4274                                 Relocatable_relocs* rr);
4275 #endif
4276
4277 #ifdef HAVE_TARGET_32_BIG
4278 template
4279 Output_section*
4280 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
4281                                unsigned int reloc_shndx,
4282                                const elfcpp::Shdr<32, true>& shdr,
4283                                Output_section* data_section,
4284                                Relocatable_relocs* rr);
4285 #endif
4286
4287 #ifdef HAVE_TARGET_64_LITTLE
4288 template
4289 Output_section*
4290 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
4291                                 unsigned int reloc_shndx,
4292                                 const elfcpp::Shdr<64, false>& shdr,
4293                                 Output_section* data_section,
4294                                 Relocatable_relocs* rr);
4295 #endif
4296
4297 #ifdef HAVE_TARGET_64_BIG
4298 template
4299 Output_section*
4300 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
4301                                unsigned int reloc_shndx,
4302                                const elfcpp::Shdr<64, true>& shdr,
4303                                Output_section* data_section,
4304                                Relocatable_relocs* rr);
4305 #endif
4306
4307 #ifdef HAVE_TARGET_32_LITTLE
4308 template
4309 void
4310 Layout::layout_group<32, false>(Symbol_table* symtab,
4311                                 Sized_relobj<32, false>* object,
4312                                 unsigned int,
4313                                 const char* group_section_name,
4314                                 const char* signature,
4315                                 const elfcpp::Shdr<32, false>& shdr,
4316                                 elfcpp::Elf_Word flags,
4317                                 std::vector<unsigned int>* shndxes);
4318 #endif
4319
4320 #ifdef HAVE_TARGET_32_BIG
4321 template
4322 void
4323 Layout::layout_group<32, true>(Symbol_table* symtab,
4324                                Sized_relobj<32, true>* object,
4325                                unsigned int,
4326                                const char* group_section_name,
4327                                const char* signature,
4328                                const elfcpp::Shdr<32, true>& shdr,
4329                                elfcpp::Elf_Word flags,
4330                                std::vector<unsigned int>* shndxes);
4331 #endif
4332
4333 #ifdef HAVE_TARGET_64_LITTLE
4334 template
4335 void
4336 Layout::layout_group<64, false>(Symbol_table* symtab,
4337                                 Sized_relobj<64, false>* object,
4338                                 unsigned int,
4339                                 const char* group_section_name,
4340                                 const char* signature,
4341                                 const elfcpp::Shdr<64, false>& shdr,
4342                                 elfcpp::Elf_Word flags,
4343                                 std::vector<unsigned int>* shndxes);
4344 #endif
4345
4346 #ifdef HAVE_TARGET_64_BIG
4347 template
4348 void
4349 Layout::layout_group<64, true>(Symbol_table* symtab,
4350                                Sized_relobj<64, true>* object,
4351                                unsigned int,
4352                                const char* group_section_name,
4353                                const char* signature,
4354                                const elfcpp::Shdr<64, true>& shdr,
4355                                elfcpp::Elf_Word flags,
4356                                std::vector<unsigned int>* shndxes);
4357 #endif
4358
4359 #ifdef HAVE_TARGET_32_LITTLE
4360 template
4361 Output_section*
4362 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
4363                                    const unsigned char* symbols,
4364                                    off_t symbols_size,
4365                                    const unsigned char* symbol_names,
4366                                    off_t symbol_names_size,
4367                                    unsigned int shndx,
4368                                    const elfcpp::Shdr<32, false>& shdr,
4369                                    unsigned int reloc_shndx,
4370                                    unsigned int reloc_type,
4371                                    off_t* off);
4372 #endif
4373
4374 #ifdef HAVE_TARGET_32_BIG
4375 template
4376 Output_section*
4377 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4378                                    const unsigned char* symbols,
4379                                    off_t symbols_size,
4380                                   const unsigned char* symbol_names,
4381                                   off_t symbol_names_size,
4382                                   unsigned int shndx,
4383                                   const elfcpp::Shdr<32, true>& shdr,
4384                                   unsigned int reloc_shndx,
4385                                   unsigned int reloc_type,
4386                                   off_t* off);
4387 #endif
4388
4389 #ifdef HAVE_TARGET_64_LITTLE
4390 template
4391 Output_section*
4392 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4393                                    const unsigned char* symbols,
4394                                    off_t symbols_size,
4395                                    const unsigned char* symbol_names,
4396                                    off_t symbol_names_size,
4397                                    unsigned int shndx,
4398                                    const elfcpp::Shdr<64, false>& shdr,
4399                                    unsigned int reloc_shndx,
4400                                    unsigned int reloc_type,
4401                                    off_t* off);
4402 #endif
4403
4404 #ifdef HAVE_TARGET_64_BIG
4405 template
4406 Output_section*
4407 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4408                                    const unsigned char* symbols,
4409                                    off_t symbols_size,
4410                                   const unsigned char* symbol_names,
4411                                   off_t symbol_names_size,
4412                                   unsigned int shndx,
4413                                   const elfcpp::Shdr<64, true>& shdr,
4414                                   unsigned int reloc_shndx,
4415                                   unsigned int reloc_type,
4416                                   off_t* off);
4417 #endif
4418
4419 } // End namespace gold.