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