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