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