OSDN Git Service

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