* layout.cc (Layout::include_section): Refactored check for debug
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright 2006, 2007, 2008 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 "script.h"
39 #include "script-sections.h"
40 #include "output.h"
41 #include "symtab.h"
42 #include "dynobj.h"
43 #include "ehframe.h"
44 #include "compressed_output.h"
45 #include "reloc.h"
46 #include "layout.h"
47
48 namespace gold
49 {
50
51 // Layout_task_runner methods.
52
53 // Lay out the sections.  This is called after all the input objects
54 // have been read.
55
56 void
57 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
58 {
59   off_t file_size = this->layout_->finalize(this->input_objects_,
60                                             this->symtab_,
61                                             this->target_,
62                                             task);
63
64   // Now we know the final size of the output file and we know where
65   // each piece of information goes.
66   Output_file* of = new Output_file(parameters->options().output_file_name());
67   if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
68     of->set_is_temporary();
69   of->open(file_size);
70
71   // Queue up the final set of tasks.
72   gold::queue_final_tasks(this->options_, this->input_objects_,
73                           this->symtab_, this->layout_, workqueue, of);
74 }
75
76 // Layout methods.
77
78 Layout::Layout(const General_options& options, Script_options* script_options)
79   : options_(options),
80     script_options_(script_options),
81     namepool_(),
82     sympool_(),
83     dynpool_(),
84     signatures_(),
85     section_name_map_(),
86     segment_list_(),
87     section_list_(),
88     unattached_section_list_(),
89     sections_are_attached_(false),
90     special_output_list_(),
91     section_headers_(NULL),
92     tls_segment_(NULL),
93     symtab_section_(NULL),
94     symtab_xindex_(NULL),
95     dynsym_section_(NULL),
96     dynsym_xindex_(NULL),
97     dynamic_section_(NULL),
98     dynamic_data_(NULL),
99     eh_frame_section_(NULL),
100     eh_frame_data_(NULL),
101     added_eh_frame_data_(false),
102     eh_frame_hdr_section_(NULL),
103     build_id_note_(NULL),
104     group_signatures_(),
105     output_file_size_(-1),
106     input_requires_executable_stack_(false),
107     input_with_gnu_stack_note_(false),
108     input_without_gnu_stack_note_(false),
109     has_static_tls_(false),
110     any_postprocessing_sections_(false)
111 {
112   // Make space for more than enough segments for a typical file.
113   // This is just for efficiency--it's OK if we wind up needing more.
114   this->segment_list_.reserve(12);
115
116   // We expect two unattached Output_data objects: the file header and
117   // the segment headers.
118   this->special_output_list_.reserve(2);
119 }
120
121 // Hash a key we use to look up an output section mapping.
122
123 size_t
124 Layout::Hash_key::operator()(const Layout::Key& k) const
125 {
126  return k.first + k.second.first + k.second.second;
127 }
128
129 // Return whether PREFIX is a prefix of STR.
130
131 static inline bool
132 is_prefix_of(const char* prefix, const char* str)
133 {
134   return strncmp(prefix, str, strlen(prefix)) == 0;
135 }
136
137 // Returns whether the given section is in the list of
138 // debug-sections-used-by-some-version-of-gdb.  Currently,
139 // we've checked versions of gdb up to and including 6.7.1.
140
141 static const char* gdb_sections[] =
142 { ".debug_abbrev",
143   // ".debug_aranges",   // not used by gdb as of 6.7.1
144   ".debug_frame",
145   ".debug_info",
146   ".debug_line",
147   ".debug_loc",
148   ".debug_macinfo",
149   // ".debug_pubnames",  // not used by gdb as of 6.7.1
150   ".debug_ranges",
151   ".debug_str",
152 };
153
154 static inline bool
155 is_gdb_debug_section(const char* str)
156 {
157   // We can do this faster: binary search or a hashtable.  But why bother?
158   for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
159     if (strcmp(str, gdb_sections[i]) == 0)
160       return true;
161   return false;
162 }
163
164 // Whether to include this section in the link.
165
166 template<int size, bool big_endian>
167 bool
168 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
169                         const elfcpp::Shdr<size, big_endian>& shdr)
170 {
171   switch (shdr.get_sh_type())
172     {
173     case elfcpp::SHT_NULL:
174     case elfcpp::SHT_SYMTAB:
175     case elfcpp::SHT_DYNSYM:
176     case elfcpp::SHT_STRTAB:
177     case elfcpp::SHT_HASH:
178     case elfcpp::SHT_DYNAMIC:
179     case elfcpp::SHT_SYMTAB_SHNDX:
180       return false;
181
182     case elfcpp::SHT_RELA:
183     case elfcpp::SHT_REL:
184     case elfcpp::SHT_GROUP:
185       // If we are emitting relocations these should be handled
186       // elsewhere.
187       gold_assert(!parameters->options().relocatable()
188                   && !parameters->options().emit_relocs());
189       return false;
190
191     case elfcpp::SHT_PROGBITS:
192       if (parameters->options().strip_debug()
193           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
194         {
195           if (is_debug_info_section(name))
196             return false;
197         }
198       if (parameters->options().strip_debug_gdb()
199           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
200         {
201           // Debugging sections can only be recognized by name.
202           if (is_prefix_of(".debug", name)
203               && !is_gdb_debug_section(name))
204             return false;
205         }
206       return true;
207
208     default:
209       return true;
210     }
211 }
212
213 // Return an output section named NAME, or NULL if there is none.
214
215 Output_section*
216 Layout::find_output_section(const char* name) const
217 {
218   for (Section_list::const_iterator p = this->section_list_.begin();
219        p != this->section_list_.end();
220        ++p)
221     if (strcmp((*p)->name(), name) == 0)
222       return *p;
223   return NULL;
224 }
225
226 // Return an output segment of type TYPE, with segment flags SET set
227 // and segment flags CLEAR clear.  Return NULL if there is none.
228
229 Output_segment*
230 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
231                             elfcpp::Elf_Word clear) const
232 {
233   for (Segment_list::const_iterator p = this->segment_list_.begin();
234        p != this->segment_list_.end();
235        ++p)
236     if (static_cast<elfcpp::PT>((*p)->type()) == type
237         && ((*p)->flags() & set) == set
238         && ((*p)->flags() & clear) == 0)
239       return *p;
240   return NULL;
241 }
242
243 // Return the output section to use for section NAME with type TYPE
244 // and section flags FLAGS.  NAME must be canonicalized in the string
245 // pool, and NAME_KEY is the key.
246
247 Output_section*
248 Layout::get_output_section(const char* name, Stringpool::Key name_key,
249                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
250 {
251   elfcpp::Elf_Xword lookup_flags = flags;
252
253   // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
254   // read-write with read-only sections.  Some other ELF linkers do
255   // not do this.  FIXME: Perhaps there should be an option
256   // controlling this.
257   lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
258
259   const Key key(name_key, std::make_pair(type, lookup_flags));
260   const std::pair<Key, Output_section*> v(key, NULL);
261   std::pair<Section_name_map::iterator, bool> ins(
262     this->section_name_map_.insert(v));
263
264   if (!ins.second)
265     return ins.first->second;
266   else
267     {
268       // This is the first time we've seen this name/type/flags
269       // combination.  For compatibility with the GNU linker, we
270       // combine sections with contents and zero flags with sections
271       // with non-zero flags.  This is a workaround for cases where
272       // assembler code forgets to set section flags.  FIXME: Perhaps
273       // there should be an option to control this.
274       Output_section* os = NULL;
275
276       if (type == elfcpp::SHT_PROGBITS)
277         {
278           if (flags == 0)
279             {
280               Output_section* same_name = this->find_output_section(name);
281               if (same_name != NULL
282                   && same_name->type() == elfcpp::SHT_PROGBITS
283                   && (same_name->flags() & elfcpp::SHF_TLS) == 0)
284                 os = same_name;
285             }
286           else if ((flags & elfcpp::SHF_TLS) == 0)
287             {
288               elfcpp::Elf_Xword zero_flags = 0;
289               const Key zero_key(name_key, std::make_pair(type, zero_flags));
290               Section_name_map::iterator p =
291                   this->section_name_map_.find(zero_key);
292               if (p != this->section_name_map_.end())
293                 os = p->second;
294             }
295         }
296
297       if (os == NULL)
298         os = this->make_output_section(name, type, flags);
299       ins.first->second = os;
300       return os;
301     }
302 }
303
304 // Pick the output section to use for section NAME, in input file
305 // RELOBJ, with type TYPE and flags FLAGS.  RELOBJ may be NULL for a
306 // linker created section.  IS_INPUT_SECTION is true if we are
307 // choosing an output section for an input section found in a input
308 // file.  This will return NULL if the input section should be
309 // discarded.
310
311 Output_section*
312 Layout::choose_output_section(const Relobj* relobj, const char* name,
313                               elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
314                               bool is_input_section)
315 {
316   // We should not see any input sections after we have attached
317   // sections to segments.
318   gold_assert(!is_input_section || !this->sections_are_attached_);
319
320   // Some flags in the input section should not be automatically
321   // copied to the output section.
322   flags &= ~ (elfcpp::SHF_INFO_LINK
323               | elfcpp::SHF_LINK_ORDER
324               | elfcpp::SHF_GROUP
325               | elfcpp::SHF_MERGE
326               | elfcpp::SHF_STRINGS);
327
328   if (this->script_options_->saw_sections_clause())
329     {
330       // We are using a SECTIONS clause, so the output section is
331       // chosen based only on the name.
332
333       Script_sections* ss = this->script_options_->script_sections();
334       const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
335       Output_section** output_section_slot;
336       name = ss->output_section_name(file_name, name, &output_section_slot);
337       if (name == NULL)
338         {
339           // The SECTIONS clause says to discard this input section.
340           return NULL;
341         }
342
343       // If this is an orphan section--one not mentioned in the linker
344       // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
345       // default processing below.
346
347       if (output_section_slot != NULL)
348         {
349           if (*output_section_slot != NULL)
350             return *output_section_slot;
351
352           // We don't put sections found in the linker script into
353           // SECTION_NAME_MAP_.  That keeps us from getting confused
354           // if an orphan section is mapped to a section with the same
355           // name as one in the linker script.
356
357           name = this->namepool_.add(name, false, NULL);
358
359           Output_section* os = this->make_output_section(name, type, flags);
360           os->set_found_in_sections_clause();
361           *output_section_slot = os;
362           return os;
363         }
364     }
365
366   // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
367
368   // Turn NAME from the name of the input section into the name of the
369   // output section.
370
371   size_t len = strlen(name);
372   if (is_input_section && !parameters->options().relocatable())
373     name = Layout::output_section_name(name, &len);
374
375   Stringpool::Key name_key;
376   name = this->namepool_.add_with_length(name, len, true, &name_key);
377
378   // Find or make the output section.  The output section is selected
379   // based on the section name, type, and flags.
380   return this->get_output_section(name, name_key, type, flags);
381 }
382
383 // Return the output section to use for input section SHNDX, with name
384 // NAME, with header HEADER, from object OBJECT.  RELOC_SHNDX is the
385 // index of a relocation section which applies to this section, or 0
386 // if none, or -1U if more than one.  RELOC_TYPE is the type of the
387 // relocation section if there is one.  Set *OFF to the offset of this
388 // input section without the output section.  Return NULL if the
389 // section should be discarded.  Set *OFF to -1 if the section
390 // contents should not be written directly to the output file, but
391 // will instead receive special handling.
392
393 template<int size, bool big_endian>
394 Output_section*
395 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
396                const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
397                unsigned int reloc_shndx, unsigned int, off_t* off)
398 {
399   if (!this->include_section(object, name, shdr))
400     return NULL;
401
402   Output_section* os;
403
404   // In a relocatable link a grouped section must not be combined with
405   // any other sections.
406   if (parameters->options().relocatable()
407       && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
408     {
409       name = this->namepool_.add(name, true, NULL);
410       os = this->make_output_section(name, shdr.get_sh_type(),
411                                      shdr.get_sh_flags());
412     }
413   else
414     {
415       os = this->choose_output_section(object, name, shdr.get_sh_type(),
416                                        shdr.get_sh_flags(), true);
417       if (os == NULL)
418         return NULL;
419     }
420
421   // By default the GNU linker sorts input sections whose names match
422   // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*.  The sections
423   // are sorted by name.  This is used to implement constructor
424   // priority ordering.  We are compatible.
425   if (!this->script_options_->saw_sections_clause()
426       && (is_prefix_of(".ctors.", name)
427           || is_prefix_of(".dtors.", name)
428           || is_prefix_of(".init_array.", name)
429           || is_prefix_of(".fini_array.", name)))
430     os->set_must_sort_attached_input_sections();
431
432   // FIXME: Handle SHF_LINK_ORDER somewhere.
433
434   *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
435                                this->script_options_->saw_sections_clause());
436
437   return os;
438 }
439
440 // Handle a relocation section when doing a relocatable link.
441
442 template<int size, bool big_endian>
443 Output_section*
444 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
445                      unsigned int,
446                      const elfcpp::Shdr<size, big_endian>& shdr,
447                      Output_section* data_section,
448                      Relocatable_relocs* rr)
449 {
450   gold_assert(parameters->options().relocatable()
451               || parameters->options().emit_relocs());
452
453   int sh_type = shdr.get_sh_type();
454
455   std::string name;
456   if (sh_type == elfcpp::SHT_REL)
457     name = ".rel";
458   else if (sh_type == elfcpp::SHT_RELA)
459     name = ".rela";
460   else
461     gold_unreachable();
462   name += data_section->name();
463
464   Output_section* os = this->choose_output_section(object, name.c_str(),
465                                                    sh_type,
466                                                    shdr.get_sh_flags(),
467                                                    false);
468
469   os->set_should_link_to_symtab();
470   os->set_info_section(data_section);
471
472   Output_section_data* posd;
473   if (sh_type == elfcpp::SHT_REL)
474     {
475       os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
476       posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
477                                            size,
478                                            big_endian>(rr);
479     }
480   else if (sh_type == elfcpp::SHT_RELA)
481     {
482       os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
483       posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
484                                            size,
485                                            big_endian>(rr);
486     }
487   else
488     gold_unreachable();
489
490   os->add_output_section_data(posd);
491   rr->set_output_data(posd);
492
493   return os;
494 }
495
496 // Handle a group section when doing a relocatable link.
497
498 template<int size, bool big_endian>
499 void
500 Layout::layout_group(Symbol_table* symtab,
501                      Sized_relobj<size, big_endian>* object,
502                      unsigned int,
503                      const char* group_section_name,
504                      const char* signature,
505                      const elfcpp::Shdr<size, big_endian>& shdr,
506                      const elfcpp::Elf_Word* contents)
507 {
508   gold_assert(parameters->options().relocatable());
509   gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
510   group_section_name = this->namepool_.add(group_section_name, true, NULL);
511   Output_section* os = this->make_output_section(group_section_name,
512                                                  elfcpp::SHT_GROUP,
513                                                  shdr.get_sh_flags());
514
515   // We need to find a symbol with the signature in the symbol table.
516   // If we don't find one now, we need to look again later.
517   Symbol* sym = symtab->lookup(signature, NULL);
518   if (sym != NULL)
519     os->set_info_symndx(sym);
520   else
521     {
522       // We will wind up using a symbol whose name is the signature.
523       // So just put the signature in the symbol name pool to save it.
524       signature = symtab->canonicalize_name(signature);
525       this->group_signatures_.push_back(Group_signature(os, signature));
526     }
527
528   os->set_should_link_to_symtab();
529   os->set_entsize(4);
530
531   section_size_type entry_count =
532     convert_to_section_size_type(shdr.get_sh_size() / 4);
533   Output_section_data* posd =
534     new Output_data_group<size, big_endian>(object, entry_count, contents);
535   os->add_output_section_data(posd);
536 }
537
538 // Special GNU handling of sections name .eh_frame.  They will
539 // normally hold exception frame data as defined by the C++ ABI
540 // (http://codesourcery.com/cxx-abi/).
541
542 template<int size, bool big_endian>
543 Output_section*
544 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
545                         const unsigned char* symbols,
546                         off_t symbols_size,
547                         const unsigned char* symbol_names,
548                         off_t symbol_names_size,
549                         unsigned int shndx,
550                         const elfcpp::Shdr<size, big_endian>& shdr,
551                         unsigned int reloc_shndx, unsigned int reloc_type,
552                         off_t* off)
553 {
554   gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
555   gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
556
557   const char* const name = ".eh_frame";
558   Output_section* os = this->choose_output_section(object,
559                                                    name,
560                                                    elfcpp::SHT_PROGBITS,
561                                                    elfcpp::SHF_ALLOC,
562                                                    false);
563   if (os == NULL)
564     return NULL;
565
566   if (this->eh_frame_section_ == NULL)
567     {
568       this->eh_frame_section_ = os;
569       this->eh_frame_data_ = new Eh_frame();
570
571       if (this->options_.eh_frame_hdr())
572         {
573           Output_section* hdr_os =
574             this->choose_output_section(NULL,
575                                         ".eh_frame_hdr",
576                                         elfcpp::SHT_PROGBITS,
577                                         elfcpp::SHF_ALLOC,
578                                         false);
579
580           if (hdr_os != NULL)
581             {
582               Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
583                                                         this->eh_frame_data_);
584               hdr_os->add_output_section_data(hdr_posd);
585
586               hdr_os->set_after_input_sections();
587
588               if (!this->script_options_->saw_phdrs_clause())
589                 {
590                   Output_segment* hdr_oseg;
591                   hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
592                                                        elfcpp::PF_R);
593                   hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
594                 }
595
596               this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
597             }
598         }
599     }
600
601   gold_assert(this->eh_frame_section_ == os);
602
603   if (this->eh_frame_data_->add_ehframe_input_section(object,
604                                                       symbols,
605                                                       symbols_size,
606                                                       symbol_names,
607                                                       symbol_names_size,
608                                                       shndx,
609                                                       reloc_shndx,
610                                                       reloc_type))
611     {
612       os->update_flags_for_input_section(shdr.get_sh_flags());
613
614       // We found a .eh_frame section we are going to optimize, so now
615       // we can add the set of optimized sections to the output
616       // section.  We need to postpone adding this until we've found a
617       // section we can optimize so that the .eh_frame section in
618       // crtbegin.o winds up at the start of the output section.
619       if (!this->added_eh_frame_data_)
620         {
621           os->add_output_section_data(this->eh_frame_data_);
622           this->added_eh_frame_data_ = true;
623         }
624       *off = -1;
625     }
626   else
627     {
628       // We couldn't handle this .eh_frame section for some reason.
629       // Add it as a normal section.
630       bool saw_sections_clause = this->script_options_->saw_sections_clause();
631       *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
632                                    saw_sections_clause);
633     }
634
635   return os;
636 }
637
638 // Add POSD to an output section using NAME, TYPE, and FLAGS.
639
640 void
641 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
642                                 elfcpp::Elf_Xword flags,
643                                 Output_section_data* posd)
644 {
645   Output_section* os = this->choose_output_section(NULL, name, type, flags,
646                                                    false);
647   if (os != NULL)
648     os->add_output_section_data(posd);
649 }
650
651 // Map section flags to segment flags.
652
653 elfcpp::Elf_Word
654 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
655 {
656   elfcpp::Elf_Word ret = elfcpp::PF_R;
657   if ((flags & elfcpp::SHF_WRITE) != 0)
658     ret |= elfcpp::PF_W;
659   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
660     ret |= elfcpp::PF_X;
661   return ret;
662 }
663
664 // Sometimes we compress sections.  This is typically done for
665 // sections that are not part of normal program execution (such as
666 // .debug_* sections), and where the readers of these sections know
667 // how to deal with compressed sections.  (To make it easier for them,
668 // we will rename the ouput section in such cases from .foo to
669 // .foo.zlib.nnnn, where nnnn is the uncompressed size.)  This routine
670 // doesn't say for certain whether we'll compress -- it depends on
671 // commandline options as well -- just whether this section is a
672 // candidate for compression.
673
674 static bool
675 is_compressible_debug_section(const char* secname)
676 {
677   return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
678 }
679
680 // Make a new Output_section, and attach it to segments as
681 // appropriate.
682
683 Output_section*
684 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
685                             elfcpp::Elf_Xword flags)
686 {
687   Output_section* os;
688   if ((flags & elfcpp::SHF_ALLOC) == 0
689       && strcmp(this->options_.compress_debug_sections(), "none") != 0
690       && is_compressible_debug_section(name))
691     os = new Output_compressed_section(&this->options_, name, type, flags);
692   else
693     os = new Output_section(name, type, flags);
694
695   this->section_list_.push_back(os);
696
697   // The GNU linker by default sorts some sections by priority, so we
698   // do the same.  We need to know that this might happen before we
699   // attach any input sections.
700   if (!this->script_options_->saw_sections_clause()
701       && (strcmp(name, ".ctors") == 0
702           || strcmp(name, ".dtors") == 0
703           || strcmp(name, ".init_array") == 0
704           || strcmp(name, ".fini_array") == 0))
705     os->set_may_sort_attached_input_sections();
706
707   // If we have already attached the sections to segments, then we
708   // need to attach this one now.  This happens for sections created
709   // directly by the linker.
710   if (this->sections_are_attached_)
711     this->attach_section_to_segment(os);
712
713   return os;
714 }
715
716 // Attach output sections to segments.  This is called after we have
717 // seen all the input sections.
718
719 void
720 Layout::attach_sections_to_segments()
721 {
722   for (Section_list::iterator p = this->section_list_.begin();
723        p != this->section_list_.end();
724        ++p)
725     this->attach_section_to_segment(*p);
726
727   this->sections_are_attached_ = true;
728 }
729
730 // Attach an output section to a segment.
731
732 void
733 Layout::attach_section_to_segment(Output_section* os)
734 {
735   if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
736     this->unattached_section_list_.push_back(os);
737   else
738     this->attach_allocated_section_to_segment(os);
739 }
740
741 // Attach an allocated output section to a segment.
742
743 void
744 Layout::attach_allocated_section_to_segment(Output_section* os)
745 {
746   elfcpp::Elf_Xword flags = os->flags();
747   gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
748
749   if (parameters->options().relocatable())
750     return;
751
752   // If we have a SECTIONS clause, we can't handle the attachment to
753   // segments until after we've seen all the sections.
754   if (this->script_options_->saw_sections_clause())
755     return;
756
757   gold_assert(!this->script_options_->saw_phdrs_clause());
758
759   // This output section goes into a PT_LOAD segment.
760
761   elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
762
763   // In general the only thing we really care about for PT_LOAD
764   // segments is whether or not they are writable, so that is how we
765   // search for them.  People who need segments sorted on some other
766   // basis will have to use a linker script.
767
768   Segment_list::const_iterator p;
769   for (p = this->segment_list_.begin();
770        p != this->segment_list_.end();
771        ++p)
772     {
773       if ((*p)->type() == elfcpp::PT_LOAD
774           && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
775         {
776           // If -Tbss was specified, we need to separate the data
777           // and BSS segments.
778           if (this->options_.user_set_Tbss())
779             {
780               if ((os->type() == elfcpp::SHT_NOBITS)
781                   == (*p)->has_any_data_sections())
782                 continue;
783             }
784
785           (*p)->add_output_section(os, seg_flags);
786           break;
787         }
788     }
789
790   if (p == this->segment_list_.end())
791     {
792       Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
793                                                        seg_flags);
794       oseg->add_output_section(os, seg_flags);
795     }
796
797   // If we see a loadable SHT_NOTE section, we create a PT_NOTE
798   // segment.
799   if (os->type() == elfcpp::SHT_NOTE)
800     {
801       // See if we already have an equivalent PT_NOTE segment.
802       for (p = this->segment_list_.begin();
803            p != segment_list_.end();
804            ++p)
805         {
806           if ((*p)->type() == elfcpp::PT_NOTE
807               && (((*p)->flags() & elfcpp::PF_W)
808                   == (seg_flags & elfcpp::PF_W)))
809             {
810               (*p)->add_output_section(os, seg_flags);
811               break;
812             }
813         }
814
815       if (p == this->segment_list_.end())
816         {
817           Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
818                                                            seg_flags);
819           oseg->add_output_section(os, seg_flags);
820         }
821     }
822
823   // If we see a loadable SHF_TLS section, we create a PT_TLS
824   // segment.  There can only be one such segment.
825   if ((flags & elfcpp::SHF_TLS) != 0)
826     {
827       if (this->tls_segment_ == NULL)
828         this->tls_segment_ = this->make_output_segment(elfcpp::PT_TLS,
829                                                        seg_flags);
830       this->tls_segment_->add_output_section(os, seg_flags);
831     }
832 }
833
834 // Make an output section for a script.
835
836 Output_section*
837 Layout::make_output_section_for_script(const char* name)
838 {
839   name = this->namepool_.add(name, false, NULL);
840   Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
841                                                  elfcpp::SHF_ALLOC);
842   os->set_found_in_sections_clause();
843   return os;
844 }
845
846 // Return the number of segments we expect to see.
847
848 size_t
849 Layout::expected_segment_count() const
850 {
851   size_t ret = this->segment_list_.size();
852
853   // If we didn't see a SECTIONS clause in a linker script, we should
854   // already have the complete list of segments.  Otherwise we ask the
855   // SECTIONS clause how many segments it expects, and add in the ones
856   // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
857
858   if (!this->script_options_->saw_sections_clause())
859     return ret;
860   else
861     {
862       const Script_sections* ss = this->script_options_->script_sections();
863       return ret + ss->expected_segment_count(this);
864     }
865 }
866
867 // Handle the .note.GNU-stack section at layout time.  SEEN_GNU_STACK
868 // is whether we saw a .note.GNU-stack section in the object file.
869 // GNU_STACK_FLAGS is the section flags.  The flags give the
870 // protection required for stack memory.  We record this in an
871 // executable as a PT_GNU_STACK segment.  If an object file does not
872 // have a .note.GNU-stack segment, we must assume that it is an old
873 // object.  On some targets that will force an executable stack.
874
875 void
876 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
877 {
878   if (!seen_gnu_stack)
879     this->input_without_gnu_stack_note_ = true;
880   else
881     {
882       this->input_with_gnu_stack_note_ = true;
883       if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
884         this->input_requires_executable_stack_ = true;
885     }
886 }
887
888 // Create the dynamic sections which are needed before we read the
889 // relocs.
890
891 void
892 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
893 {
894   if (parameters->doing_static_link())
895     return;
896
897   this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
898                                                        elfcpp::SHT_DYNAMIC,
899                                                        (elfcpp::SHF_ALLOC
900                                                         | elfcpp::SHF_WRITE),
901                                                        false);
902
903   symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
904                                 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
905                                 elfcpp::STV_HIDDEN, 0, false, false);
906
907   this->dynamic_data_ =  new Output_data_dynamic(&this->dynpool_);
908
909   this->dynamic_section_->add_output_section_data(this->dynamic_data_);
910 }
911
912 // For each output section whose name can be represented as C symbol,
913 // define __start and __stop symbols for the section.  This is a GNU
914 // extension.
915
916 void
917 Layout::define_section_symbols(Symbol_table* symtab)
918 {
919   for (Section_list::const_iterator p = this->section_list_.begin();
920        p != this->section_list_.end();
921        ++p)
922     {
923       const char* const name = (*p)->name();
924       if (name[strspn(name,
925                       ("0123456789"
926                        "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
927                        "abcdefghijklmnopqrstuvwxyz"
928                        "_"))]
929           == '\0')
930         {
931           const std::string name_string(name);
932           const std::string start_name("__start_" + name_string);
933           const std::string stop_name("__stop_" + name_string);
934
935           symtab->define_in_output_data(start_name.c_str(),
936                                         NULL, // version
937                                         *p,
938                                         0, // value
939                                         0, // symsize
940                                         elfcpp::STT_NOTYPE,
941                                         elfcpp::STB_GLOBAL,
942                                         elfcpp::STV_DEFAULT,
943                                         0, // nonvis
944                                         false, // offset_is_from_end
945                                         true); // only_if_ref
946
947           symtab->define_in_output_data(stop_name.c_str(),
948                                         NULL, // version
949                                         *p,
950                                         0, // value
951                                         0, // symsize
952                                         elfcpp::STT_NOTYPE,
953                                         elfcpp::STB_GLOBAL,
954                                         elfcpp::STV_DEFAULT,
955                                         0, // nonvis
956                                         true, // offset_is_from_end
957                                         true); // only_if_ref
958         }
959     }
960 }
961
962 // Define symbols for group signatures.
963
964 void
965 Layout::define_group_signatures(Symbol_table* symtab)
966 {
967   for (Group_signatures::iterator p = this->group_signatures_.begin();
968        p != this->group_signatures_.end();
969        ++p)
970     {
971       Symbol* sym = symtab->lookup(p->signature, NULL);
972       if (sym != NULL)
973         p->section->set_info_symndx(sym);
974       else
975         {
976           // Force the name of the group section to the group
977           // signature, and use the group's section symbol as the
978           // signature symbol.
979           if (strcmp(p->section->name(), p->signature) != 0)
980             {
981               const char* name = this->namepool_.add(p->signature,
982                                                      true, NULL);
983               p->section->set_name(name);
984             }
985           p->section->set_needs_symtab_index();
986           p->section->set_info_section_symndx(p->section);
987         }
988     }
989
990   this->group_signatures_.clear();
991 }
992
993 // Find the first read-only PT_LOAD segment, creating one if
994 // necessary.
995
996 Output_segment*
997 Layout::find_first_load_seg()
998 {
999   for (Segment_list::const_iterator p = this->segment_list_.begin();
1000        p != this->segment_list_.end();
1001        ++p)
1002     {
1003       if ((*p)->type() == elfcpp::PT_LOAD
1004           && ((*p)->flags() & elfcpp::PF_R) != 0
1005           && ((*p)->flags() & elfcpp::PF_W) == 0)
1006         return *p;
1007     }
1008
1009   gold_assert(!this->script_options_->saw_phdrs_clause());
1010
1011   Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1012                                                        elfcpp::PF_R);
1013   return load_seg;
1014 }
1015
1016 // Finalize the layout.  When this is called, we have created all the
1017 // output sections and all the output segments which are based on
1018 // input sections.  We have several things to do, and we have to do
1019 // them in the right order, so that we get the right results correctly
1020 // and efficiently.
1021
1022 // 1) Finalize the list of output segments and create the segment
1023 // table header.
1024
1025 // 2) Finalize the dynamic symbol table and associated sections.
1026
1027 // 3) Determine the final file offset of all the output segments.
1028
1029 // 4) Determine the final file offset of all the SHF_ALLOC output
1030 // sections.
1031
1032 // 5) Create the symbol table sections and the section name table
1033 // section.
1034
1035 // 6) Finalize the symbol table: set symbol values to their final
1036 // value and make a final determination of which symbols are going
1037 // into the output symbol table.
1038
1039 // 7) Create the section table header.
1040
1041 // 8) Determine the final file offset of all the output sections which
1042 // are not SHF_ALLOC, including the section table header.
1043
1044 // 9) Finalize the ELF file header.
1045
1046 // This function returns the size of the output file.
1047
1048 off_t
1049 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1050                  Target* target, const Task* task)
1051 {
1052   target->finalize_sections(this);
1053
1054   this->count_local_symbols(task, input_objects);
1055
1056   this->create_gold_note();
1057   this->create_executable_stack_info(target);
1058   this->create_build_id();
1059
1060   Output_segment* phdr_seg = NULL;
1061   if (!parameters->options().relocatable() && !parameters->doing_static_link())
1062     {
1063       // There was a dynamic object in the link.  We need to create
1064       // some information for the dynamic linker.
1065
1066       // Create the PT_PHDR segment which will hold the program
1067       // headers.
1068       if (!this->script_options_->saw_phdrs_clause())
1069         phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1070
1071       // Create the dynamic symbol table, including the hash table.
1072       Output_section* dynstr;
1073       std::vector<Symbol*> dynamic_symbols;
1074       unsigned int local_dynamic_count;
1075       Versions versions(*this->script_options()->version_script_info(),
1076                         &this->dynpool_);
1077       this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1078                                   &local_dynamic_count, &dynamic_symbols,
1079                                   &versions);
1080
1081       // Create the .interp section to hold the name of the
1082       // interpreter, and put it in a PT_INTERP segment.
1083       if (!parameters->options().shared())
1084         this->create_interp(target);
1085
1086       // Finish the .dynamic section to hold the dynamic data, and put
1087       // it in a PT_DYNAMIC segment.
1088       this->finish_dynamic_section(input_objects, symtab);
1089
1090       // We should have added everything we need to the dynamic string
1091       // table.
1092       this->dynpool_.set_string_offsets();
1093
1094       // Create the version sections.  We can't do this until the
1095       // dynamic string table is complete.
1096       this->create_version_sections(&versions, symtab, local_dynamic_count,
1097                                     dynamic_symbols, dynstr);
1098     }
1099
1100   // If there is a SECTIONS clause, put all the input sections into
1101   // the required order.
1102   Output_segment* load_seg;
1103   if (this->script_options_->saw_sections_clause())
1104     load_seg = this->set_section_addresses_from_script(symtab);
1105   else if (parameters->options().relocatable())
1106     load_seg = NULL;
1107   else
1108     load_seg = this->find_first_load_seg();
1109
1110   if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
1111     load_seg = NULL;
1112
1113   gold_assert(phdr_seg == NULL || load_seg != NULL);
1114
1115   // Lay out the segment headers.
1116   Output_segment_headers* segment_headers;
1117   if (parameters->options().relocatable())
1118     segment_headers = NULL;
1119   else
1120     {
1121       segment_headers = new Output_segment_headers(this->segment_list_);
1122       if (load_seg != NULL)
1123         load_seg->add_initial_output_data(segment_headers);
1124       if (phdr_seg != NULL)
1125         phdr_seg->add_initial_output_data(segment_headers);
1126     }
1127
1128   // Lay out the file header.
1129   Output_file_header* file_header;
1130   file_header = new Output_file_header(target, symtab, segment_headers,
1131                                        this->options_.entry());
1132   if (load_seg != NULL)
1133     load_seg->add_initial_output_data(file_header);
1134
1135   this->special_output_list_.push_back(file_header);
1136   if (segment_headers != NULL)
1137     this->special_output_list_.push_back(segment_headers);
1138
1139   if (this->script_options_->saw_phdrs_clause()
1140       && !parameters->options().relocatable())
1141     {
1142       // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1143       // clause in a linker script.
1144       Script_sections* ss = this->script_options_->script_sections();
1145       ss->put_headers_in_phdrs(file_header, segment_headers);
1146     }
1147
1148   // We set the output section indexes in set_segment_offsets and
1149   // set_section_indexes.
1150   unsigned int shndx = 1;
1151
1152   // Set the file offsets of all the segments, and all the sections
1153   // they contain.
1154   off_t off;
1155   if (!parameters->options().relocatable())
1156     off = this->set_segment_offsets(target, load_seg, &shndx);
1157   else
1158     off = this->set_relocatable_section_offsets(file_header, &shndx);
1159
1160   // Set the file offsets of all the non-data sections we've seen so
1161   // far which don't have to wait for the input sections.  We need
1162   // this in order to finalize local symbols in non-allocated
1163   // sections.
1164   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1165
1166   // Set the section indexes of all unallocated sections seen so far,
1167   // in case any of them are somehow referenced by a symbol.
1168   shndx = this->set_section_indexes(shndx);
1169
1170   // Create the symbol table sections.
1171   this->create_symtab_sections(input_objects, symtab, shndx, &off);
1172   if (!parameters->doing_static_link())
1173     this->assign_local_dynsym_offsets(input_objects);
1174
1175   // Process any symbol assignments from a linker script.  This must
1176   // be called after the symbol table has been finalized.
1177   this->script_options_->finalize_symbols(symtab, this);
1178
1179   // Create the .shstrtab section.
1180   Output_section* shstrtab_section = this->create_shstrtab();
1181
1182   // Set the file offsets of the rest of the non-data sections which
1183   // don't have to wait for the input sections.
1184   off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1185
1186   // Now that all sections have been created, set the section indexes
1187   // for any sections which haven't been done yet.
1188   shndx = this->set_section_indexes(shndx);
1189
1190   // Create the section table header.
1191   this->create_shdrs(shstrtab_section, &off);
1192
1193   // If there are no sections which require postprocessing, we can
1194   // handle the section names now, and avoid a resize later.
1195   if (!this->any_postprocessing_sections_)
1196     off = this->set_section_offsets(off,
1197                                     STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1198
1199   file_header->set_section_info(this->section_headers_, shstrtab_section);
1200
1201   // Now we know exactly where everything goes in the output file
1202   // (except for non-allocated sections which require postprocessing).
1203   Output_data::layout_complete();
1204
1205   this->output_file_size_ = off;
1206
1207   return off;
1208 }
1209
1210 // Create a note header following the format defined in the ELF ABI.
1211 // NAME is the name, NOTE_TYPE is the type, DESCSZ is the size of the
1212 // descriptor.  ALLOCATE is true if the section should be allocated in
1213 // memory.  This returns the new note section.  It sets
1214 // *TRAILING_PADDING to the number of trailing zero bytes required.
1215
1216 Output_section*
1217 Layout::create_note(const char* name, int note_type, size_t descsz,
1218                     bool allocate, size_t* trailing_padding)
1219 {
1220   // Authorities all agree that the values in a .note field should
1221   // be aligned on 4-byte boundaries for 32-bit binaries.  However,
1222   // they differ on what the alignment is for 64-bit binaries.
1223   // The GABI says unambiguously they take 8-byte alignment:
1224   //    http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1225   // Other documentation says alignment should always be 4 bytes:
1226   //    http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1227   // GNU ld and GNU readelf both support the latter (at least as of
1228   // version 2.16.91), and glibc always generates the latter for
1229   // .note.ABI-tag (as of version 1.6), so that's the one we go with
1230   // here.
1231 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION   // This is not defined by default.
1232   const int size = parameters->target().get_size();
1233 #else
1234   const int size = 32;
1235 #endif
1236
1237   // The contents of the .note section.
1238   size_t namesz = strlen(name) + 1;
1239   size_t aligned_namesz = align_address(namesz, size / 8);
1240   size_t aligned_descsz = align_address(descsz, size / 8);
1241
1242   size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1243
1244   unsigned char* buffer = new unsigned char[notehdrsz];
1245   memset(buffer, 0, notehdrsz);
1246
1247   bool is_big_endian = parameters->target().is_big_endian();
1248
1249   if (size == 32)
1250     {
1251       if (!is_big_endian)
1252         {
1253           elfcpp::Swap<32, false>::writeval(buffer, namesz);
1254           elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1255           elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1256         }
1257       else
1258         {
1259           elfcpp::Swap<32, true>::writeval(buffer, namesz);
1260           elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1261           elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1262         }
1263     }
1264   else if (size == 64)
1265     {
1266       if (!is_big_endian)
1267         {
1268           elfcpp::Swap<64, false>::writeval(buffer, namesz);
1269           elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1270           elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1271         }
1272       else
1273         {
1274           elfcpp::Swap<64, true>::writeval(buffer, namesz);
1275           elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1276           elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1277         }
1278     }
1279   else
1280     gold_unreachable();
1281
1282   memcpy(buffer + 3 * (size / 8), name, namesz);
1283
1284   const char* note_name = this->namepool_.add(".note", false, NULL);
1285   elfcpp::Elf_Xword flags = 0;
1286   if (allocate)
1287     flags = elfcpp::SHF_ALLOC;
1288   Output_section* os = this->make_output_section(note_name,
1289                                                  elfcpp::SHT_NOTE,
1290                                                  flags);
1291   Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1292                                                            size / 8);
1293   os->add_output_section_data(posd);
1294
1295   *trailing_padding = aligned_descsz - descsz;
1296
1297   return os;
1298 }
1299
1300 // For an executable or shared library, create a note to record the
1301 // version of gold used to create the binary.
1302
1303 void
1304 Layout::create_gold_note()
1305 {
1306   if (parameters->options().relocatable())
1307     return;
1308
1309   std::string desc = std::string("gold ") + gold::get_version_string();
1310
1311   size_t trailing_padding;
1312   Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1313                                          desc.size(), false, &trailing_padding);
1314
1315   Output_section_data* posd = new Output_data_const(desc, 4);
1316   os->add_output_section_data(posd);
1317
1318   if (trailing_padding > 0)
1319     {
1320       posd = new Output_data_fixed_space(trailing_padding, 0);
1321       os->add_output_section_data(posd);
1322     }
1323 }
1324
1325 // Record whether the stack should be executable.  This can be set
1326 // from the command line using the -z execstack or -z noexecstack
1327 // options.  Otherwise, if any input file has a .note.GNU-stack
1328 // section with the SHF_EXECINSTR flag set, the stack should be
1329 // executable.  Otherwise, if at least one input file a
1330 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1331 // section, we use the target default for whether the stack should be
1332 // executable.  Otherwise, we don't generate a stack note.  When
1333 // generating a object file, we create a .note.GNU-stack section with
1334 // the appropriate marking.  When generating an executable or shared
1335 // library, we create a PT_GNU_STACK segment.
1336
1337 void
1338 Layout::create_executable_stack_info(const Target* target)
1339 {
1340   bool is_stack_executable;
1341   if (this->options_.is_execstack_set())
1342     is_stack_executable = this->options_.is_stack_executable();
1343   else if (!this->input_with_gnu_stack_note_)
1344     return;
1345   else
1346     {
1347       if (this->input_requires_executable_stack_)
1348         is_stack_executable = true;
1349       else if (this->input_without_gnu_stack_note_)
1350         is_stack_executable = target->is_default_stack_executable();
1351       else
1352         is_stack_executable = false;
1353     }
1354
1355   if (parameters->options().relocatable())
1356     {
1357       const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1358       elfcpp::Elf_Xword flags = 0;
1359       if (is_stack_executable)
1360         flags |= elfcpp::SHF_EXECINSTR;
1361       this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1362     }
1363   else
1364     {
1365       if (this->script_options_->saw_phdrs_clause())
1366         return;
1367       int flags = elfcpp::PF_R | elfcpp::PF_W;
1368       if (is_stack_executable)
1369         flags |= elfcpp::PF_X;
1370       this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1371     }
1372 }
1373
1374 // If --build-id was used, set up the build ID note.
1375
1376 void
1377 Layout::create_build_id()
1378 {
1379   if (!parameters->options().user_set_build_id())
1380     return;
1381
1382   const char* style = parameters->options().build_id();
1383   if (strcmp(style, "none") == 0)
1384     return;
1385
1386   // Set DESCSZ to the size of the note descriptor.  When possible,
1387   // set DESC to the note descriptor contents.
1388   size_t descsz;
1389   std::string desc;
1390   if (strcmp(style, "md5") == 0)
1391     descsz = 128 / 8;
1392   else if (strcmp(style, "sha1") == 0)
1393     descsz = 160 / 8;
1394   else if (strcmp(style, "uuid") == 0)
1395     {
1396       const size_t uuidsz = 128 / 8;
1397
1398       char buffer[uuidsz];
1399       memset(buffer, 0, uuidsz);
1400
1401       int descriptor = ::open("/dev/urandom", O_RDONLY);
1402       if (descriptor < 0)
1403         gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1404                    strerror(errno));
1405       else
1406         {
1407           ssize_t got = ::read(descriptor, buffer, uuidsz);
1408           ::close(descriptor);
1409           if (got < 0)
1410             gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1411           else if (static_cast<size_t>(got) != uuidsz)
1412             gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1413                        uuidsz, got);
1414         }
1415
1416       desc.assign(buffer, uuidsz);
1417       descsz = uuidsz;
1418     }
1419   else if (strncmp(style, "0x", 2) == 0)
1420     {
1421       hex_init();
1422       const char* p = style + 2;
1423       while (*p != '\0')
1424         {
1425           if (hex_p(p[0]) && hex_p(p[1]))
1426             {
1427               char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1428               desc += c;
1429               p += 2;
1430             }
1431           else if (*p == '-' || *p == ':')
1432             ++p;
1433           else
1434             gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1435                        style);
1436         }
1437       descsz = desc.size();
1438     }
1439   else
1440     gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1441
1442   // Create the note.
1443   size_t trailing_padding;
1444   Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1445                                          descsz, true, &trailing_padding);
1446
1447   if (!desc.empty())
1448     {
1449       // We know the value already, so we fill it in now.
1450       gold_assert(desc.size() == descsz);
1451
1452       Output_section_data* posd = new Output_data_const(desc, 4);
1453       os->add_output_section_data(posd);
1454
1455       if (trailing_padding != 0)
1456         {
1457           posd = new Output_data_fixed_space(trailing_padding, 0);
1458           os->add_output_section_data(posd);
1459         }
1460     }
1461   else
1462     {
1463       // We need to compute a checksum after we have completed the
1464       // link.
1465       gold_assert(trailing_padding == 0);
1466       this->build_id_note_ = new Output_data_fixed_space(descsz, 4);
1467       os->add_output_section_data(this->build_id_note_);
1468       os->set_after_input_sections();
1469     }
1470 }
1471
1472 // Return whether SEG1 should be before SEG2 in the output file.  This
1473 // is based entirely on the segment type and flags.  When this is
1474 // called the segment addresses has normally not yet been set.
1475
1476 bool
1477 Layout::segment_precedes(const Output_segment* seg1,
1478                          const Output_segment* seg2)
1479 {
1480   elfcpp::Elf_Word type1 = seg1->type();
1481   elfcpp::Elf_Word type2 = seg2->type();
1482
1483   // The single PT_PHDR segment is required to precede any loadable
1484   // segment.  We simply make it always first.
1485   if (type1 == elfcpp::PT_PHDR)
1486     {
1487       gold_assert(type2 != elfcpp::PT_PHDR);
1488       return true;
1489     }
1490   if (type2 == elfcpp::PT_PHDR)
1491     return false;
1492
1493   // The single PT_INTERP segment is required to precede any loadable
1494   // segment.  We simply make it always second.
1495   if (type1 == elfcpp::PT_INTERP)
1496     {
1497       gold_assert(type2 != elfcpp::PT_INTERP);
1498       return true;
1499     }
1500   if (type2 == elfcpp::PT_INTERP)
1501     return false;
1502
1503   // We then put PT_LOAD segments before any other segments.
1504   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1505     return true;
1506   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1507     return false;
1508
1509   // We put the PT_TLS segment last, because that is where the dynamic
1510   // linker expects to find it (this is just for efficiency; other
1511   // positions would also work correctly).
1512   if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
1513     return false;
1514   if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
1515     return true;
1516
1517   const elfcpp::Elf_Word flags1 = seg1->flags();
1518   const elfcpp::Elf_Word flags2 = seg2->flags();
1519
1520   // The order of non-PT_LOAD segments is unimportant.  We simply sort
1521   // by the numeric segment type and flags values.  There should not
1522   // be more than one segment with the same type and flags.
1523   if (type1 != elfcpp::PT_LOAD)
1524     {
1525       if (type1 != type2)
1526         return type1 < type2;
1527       gold_assert(flags1 != flags2);
1528       return flags1 < flags2;
1529     }
1530
1531   // If the addresses are set already, sort by load address.
1532   if (seg1->are_addresses_set())
1533     {
1534       if (!seg2->are_addresses_set())
1535         return true;
1536
1537       unsigned int section_count1 = seg1->output_section_count();
1538       unsigned int section_count2 = seg2->output_section_count();
1539       if (section_count1 == 0 && section_count2 > 0)
1540         return true;
1541       if (section_count1 > 0 && section_count2 == 0)
1542         return false;
1543
1544       uint64_t paddr1 = seg1->first_section_load_address();
1545       uint64_t paddr2 = seg2->first_section_load_address();
1546       if (paddr1 != paddr2)
1547         return paddr1 < paddr2;
1548     }
1549   else if (seg2->are_addresses_set())
1550     return false;
1551
1552   // We sort PT_LOAD segments based on the flags.  Readonly segments
1553   // come before writable segments.  Then writable segments with data
1554   // come before writable segments without data.  Then executable
1555   // segments come before non-executable segments.  Then the unlikely
1556   // case of a non-readable segment comes before the normal case of a
1557   // readable segment.  If there are multiple segments with the same
1558   // type and flags, we require that the address be set, and we sort
1559   // by virtual address and then physical address.
1560   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1561     return (flags1 & elfcpp::PF_W) == 0;
1562   if ((flags1 & elfcpp::PF_W) != 0
1563       && seg1->has_any_data_sections() != seg2->has_any_data_sections())
1564     return seg1->has_any_data_sections();
1565   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1566     return (flags1 & elfcpp::PF_X) != 0;
1567   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1568     return (flags1 & elfcpp::PF_R) == 0;
1569
1570   // We shouldn't get here--we shouldn't create segments which we
1571   // can't distinguish.
1572   gold_unreachable();
1573 }
1574
1575 // Set the file offsets of all the segments, and all the sections they
1576 // contain.  They have all been created.  LOAD_SEG must be be laid out
1577 // first.  Return the offset of the data to follow.
1578
1579 off_t
1580 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1581                             unsigned int *pshndx)
1582 {
1583   // Sort them into the final order.
1584   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1585             Layout::Compare_segments());
1586
1587   // Find the PT_LOAD segments, and set their addresses and offsets
1588   // and their section's addresses and offsets.
1589   uint64_t addr;
1590   if (this->options_.user_set_Ttext())
1591     addr = this->options_.Ttext();
1592   else if (parameters->options().shared())
1593     addr = 0;
1594   else
1595     addr = target->default_text_segment_address();
1596   off_t off = 0;
1597
1598   // If LOAD_SEG is NULL, then the file header and segment headers
1599   // will not be loadable.  But they still need to be at offset 0 in
1600   // the file.  Set their offsets now.
1601   if (load_seg == NULL)
1602     {
1603       for (Data_list::iterator p = this->special_output_list_.begin();
1604            p != this->special_output_list_.end();
1605            ++p)
1606         {
1607           off = align_address(off, (*p)->addralign());
1608           (*p)->set_address_and_file_offset(0, off);
1609           off += (*p)->data_size();
1610         }
1611     }
1612
1613   bool was_readonly = false;
1614   for (Segment_list::iterator p = this->segment_list_.begin();
1615        p != this->segment_list_.end();
1616        ++p)
1617     {
1618       if ((*p)->type() == elfcpp::PT_LOAD)
1619         {
1620           if (load_seg != NULL && load_seg != *p)
1621             gold_unreachable();
1622           load_seg = NULL;
1623
1624           bool are_addresses_set = (*p)->are_addresses_set();
1625           if (are_addresses_set)
1626             {
1627               // When it comes to setting file offsets, we care about
1628               // the physical address.
1629               addr = (*p)->paddr();
1630             }
1631           else if (this->options_.user_set_Tdata()
1632                    && ((*p)->flags() & elfcpp::PF_W) != 0
1633                    && (!this->options_.user_set_Tbss()
1634                        || (*p)->has_any_data_sections()))
1635             {
1636               addr = this->options_.Tdata();
1637               are_addresses_set = true;
1638             }
1639           else if (this->options_.user_set_Tbss()
1640                    && ((*p)->flags() & elfcpp::PF_W) != 0
1641                    && !(*p)->has_any_data_sections())
1642             {
1643               addr = this->options_.Tbss();
1644               are_addresses_set = true;
1645             }
1646
1647           uint64_t orig_addr = addr;
1648           uint64_t orig_off = off;
1649
1650           uint64_t aligned_addr = 0;
1651           uint64_t abi_pagesize = target->abi_pagesize();
1652
1653           // FIXME: This should depend on the -n and -N options.
1654           (*p)->set_minimum_p_align(target->common_pagesize());
1655
1656           if (are_addresses_set)
1657             {
1658               // Adjust the file offset to the same address modulo the
1659               // page size.
1660               uint64_t unsigned_off = off;
1661               uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1662                                       | (addr & (abi_pagesize - 1)));
1663               if (aligned_off < unsigned_off)
1664                 aligned_off += abi_pagesize;
1665               off = aligned_off;
1666             }
1667           else
1668             {
1669               // If the last segment was readonly, and this one is
1670               // not, then skip the address forward one page,
1671               // maintaining the same position within the page.  This
1672               // lets us store both segments overlapping on a single
1673               // page in the file, but the loader will put them on
1674               // different pages in memory.
1675
1676               addr = align_address(addr, (*p)->maximum_alignment());
1677               aligned_addr = addr;
1678
1679               if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1680                 {
1681                   if ((addr & (abi_pagesize - 1)) != 0)
1682                     addr = addr + abi_pagesize;
1683                 }
1684
1685               off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1686             }
1687
1688           unsigned int shndx_hold = *pshndx;
1689           uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
1690                                                           &off, pshndx);
1691
1692           // Now that we know the size of this segment, we may be able
1693           // to save a page in memory, at the cost of wasting some
1694           // file space, by instead aligning to the start of a new
1695           // page.  Here we use the real machine page size rather than
1696           // the ABI mandated page size.
1697
1698           if (!are_addresses_set && aligned_addr != addr)
1699             {
1700               uint64_t common_pagesize = target->common_pagesize();
1701               uint64_t first_off = (common_pagesize
1702                                     - (aligned_addr
1703                                        & (common_pagesize - 1)));
1704               uint64_t last_off = new_addr & (common_pagesize - 1);
1705               if (first_off > 0
1706                   && last_off > 0
1707                   && ((aligned_addr & ~ (common_pagesize - 1))
1708                       != (new_addr & ~ (common_pagesize - 1)))
1709                   && first_off + last_off <= common_pagesize)
1710                 {
1711                   *pshndx = shndx_hold;
1712                   addr = align_address(aligned_addr, common_pagesize);
1713                   addr = align_address(addr, (*p)->maximum_alignment());
1714                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1715                   new_addr = (*p)->set_section_addresses(this, true, addr,
1716                                                          &off, pshndx);
1717                 }
1718             }
1719
1720           addr = new_addr;
1721
1722           if (((*p)->flags() & elfcpp::PF_W) == 0)
1723             was_readonly = true;
1724         }
1725     }
1726
1727   // Handle the non-PT_LOAD segments, setting their offsets from their
1728   // section's offsets.
1729   for (Segment_list::iterator p = this->segment_list_.begin();
1730        p != this->segment_list_.end();
1731        ++p)
1732     {
1733       if ((*p)->type() != elfcpp::PT_LOAD)
1734         (*p)->set_offset();
1735     }
1736
1737   // Set the TLS offsets for each section in the PT_TLS segment.
1738   if (this->tls_segment_ != NULL)
1739     this->tls_segment_->set_tls_offsets();
1740
1741   return off;
1742 }
1743
1744 // Set the offsets of all the allocated sections when doing a
1745 // relocatable link.  This does the same jobs as set_segment_offsets,
1746 // only for a relocatable link.
1747
1748 off_t
1749 Layout::set_relocatable_section_offsets(Output_data* file_header,
1750                                         unsigned int *pshndx)
1751 {
1752   off_t off = 0;
1753
1754   file_header->set_address_and_file_offset(0, 0);
1755   off += file_header->data_size();
1756
1757   for (Section_list::iterator p = this->section_list_.begin();
1758        p != this->section_list_.end();
1759        ++p)
1760     {
1761       // We skip unallocated sections here, except that group sections
1762       // have to come first.
1763       if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
1764           && (*p)->type() != elfcpp::SHT_GROUP)
1765         continue;
1766
1767       off = align_address(off, (*p)->addralign());
1768
1769       // The linker script might have set the address.
1770       if (!(*p)->is_address_valid())
1771         (*p)->set_address(0);
1772       (*p)->set_file_offset(off);
1773       (*p)->finalize_data_size();
1774       off += (*p)->data_size();
1775
1776       (*p)->set_out_shndx(*pshndx);
1777       ++*pshndx;
1778     }
1779
1780   return off;
1781 }
1782
1783 // Set the file offset of all the sections not associated with a
1784 // segment.
1785
1786 off_t
1787 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1788 {
1789   for (Section_list::iterator p = this->unattached_section_list_.begin();
1790        p != this->unattached_section_list_.end();
1791        ++p)
1792     {
1793       // The symtab section is handled in create_symtab_sections.
1794       if (*p == this->symtab_section_)
1795         continue;
1796
1797       // If we've already set the data size, don't set it again.
1798       if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1799         continue;
1800
1801       if (pass == BEFORE_INPUT_SECTIONS_PASS
1802           && (*p)->requires_postprocessing())
1803         {
1804           (*p)->create_postprocessing_buffer();
1805           this->any_postprocessing_sections_ = true;
1806         }
1807
1808       if (pass == BEFORE_INPUT_SECTIONS_PASS
1809           && (*p)->after_input_sections())
1810         continue;
1811       else if (pass == POSTPROCESSING_SECTIONS_PASS
1812                && (!(*p)->after_input_sections()
1813                    || (*p)->type() == elfcpp::SHT_STRTAB))
1814         continue;
1815       else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1816                && (!(*p)->after_input_sections()
1817                    || (*p)->type() != elfcpp::SHT_STRTAB))
1818         continue;
1819
1820       off = align_address(off, (*p)->addralign());
1821       (*p)->set_file_offset(off);
1822       (*p)->finalize_data_size();
1823       off += (*p)->data_size();
1824
1825       // At this point the name must be set.
1826       if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1827         this->namepool_.add((*p)->name(), false, NULL);
1828     }
1829   return off;
1830 }
1831
1832 // Set the section indexes of all the sections not associated with a
1833 // segment.
1834
1835 unsigned int
1836 Layout::set_section_indexes(unsigned int shndx)
1837 {
1838   for (Section_list::iterator p = this->unattached_section_list_.begin();
1839        p != this->unattached_section_list_.end();
1840        ++p)
1841     {
1842       if (!(*p)->has_out_shndx())
1843         {
1844           (*p)->set_out_shndx(shndx);
1845           ++shndx;
1846         }
1847     }
1848   return shndx;
1849 }
1850
1851 // Set the section addresses according to the linker script.  This is
1852 // only called when we see a SECTIONS clause.  This returns the
1853 // program segment which should hold the file header and segment
1854 // headers, if any.  It will return NULL if they should not be in a
1855 // segment.
1856
1857 Output_segment*
1858 Layout::set_section_addresses_from_script(Symbol_table* symtab)
1859 {
1860   Script_sections* ss = this->script_options_->script_sections();
1861   gold_assert(ss->saw_sections_clause());
1862
1863   // Place each orphaned output section in the script.
1864   for (Section_list::iterator p = this->section_list_.begin();
1865        p != this->section_list_.end();
1866        ++p)
1867     {
1868       if (!(*p)->found_in_sections_clause())
1869         ss->place_orphan(*p);
1870     }
1871
1872   return this->script_options_->set_section_addresses(symtab, this);
1873 }
1874
1875 // Count the local symbols in the regular symbol table and the dynamic
1876 // symbol table, and build the respective string pools.
1877
1878 void
1879 Layout::count_local_symbols(const Task* task,
1880                             const Input_objects* input_objects)
1881 {
1882   // First, figure out an upper bound on the number of symbols we'll
1883   // be inserting into each pool.  This helps us create the pools with
1884   // the right size, to avoid unnecessary hashtable resizing.
1885   unsigned int symbol_count = 0;
1886   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1887        p != input_objects->relobj_end();
1888        ++p)
1889     symbol_count += (*p)->local_symbol_count();
1890
1891   // Go from "upper bound" to "estimate."  We overcount for two
1892   // reasons: we double-count symbols that occur in more than one
1893   // object file, and we count symbols that are dropped from the
1894   // output.  Add it all together and assume we overcount by 100%.
1895   symbol_count /= 2;
1896
1897   // We assume all symbols will go into both the sympool and dynpool.
1898   this->sympool_.reserve(symbol_count);
1899   this->dynpool_.reserve(symbol_count);
1900
1901   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1902        p != input_objects->relobj_end();
1903        ++p)
1904     {
1905       Task_lock_obj<Object> tlo(task, *p);
1906       (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
1907     }
1908 }
1909
1910 // Create the symbol table sections.  Here we also set the final
1911 // values of the symbols.  At this point all the loadable sections are
1912 // fully laid out.  SHNUM is the number of sections so far.
1913
1914 void
1915 Layout::create_symtab_sections(const Input_objects* input_objects,
1916                                Symbol_table* symtab,
1917                                unsigned int shnum,
1918                                off_t* poff)
1919 {
1920   int symsize;
1921   unsigned int align;
1922   if (parameters->target().get_size() == 32)
1923     {
1924       symsize = elfcpp::Elf_sizes<32>::sym_size;
1925       align = 4;
1926     }
1927   else if (parameters->target().get_size() == 64)
1928     {
1929       symsize = elfcpp::Elf_sizes<64>::sym_size;
1930       align = 8;
1931     }
1932   else
1933     gold_unreachable();
1934
1935   off_t off = *poff;
1936   off = align_address(off, align);
1937   off_t startoff = off;
1938
1939   // Save space for the dummy symbol at the start of the section.  We
1940   // never bother to write this out--it will just be left as zero.
1941   off += symsize;
1942   unsigned int local_symbol_index = 1;
1943
1944   // Add STT_SECTION symbols for each Output section which needs one.
1945   for (Section_list::iterator p = this->section_list_.begin();
1946        p != this->section_list_.end();
1947        ++p)
1948     {
1949       if (!(*p)->needs_symtab_index())
1950         (*p)->set_symtab_index(-1U);
1951       else
1952         {
1953           (*p)->set_symtab_index(local_symbol_index);
1954           ++local_symbol_index;
1955           off += symsize;
1956         }
1957     }
1958
1959   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1960        p != input_objects->relobj_end();
1961        ++p)
1962     {
1963       unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
1964                                                         off);
1965       off += (index - local_symbol_index) * symsize;
1966       local_symbol_index = index;
1967     }
1968
1969   unsigned int local_symcount = local_symbol_index;
1970   gold_assert(local_symcount * symsize == off - startoff);
1971
1972   off_t dynoff;
1973   size_t dyn_global_index;
1974   size_t dyncount;
1975   if (this->dynsym_section_ == NULL)
1976     {
1977       dynoff = 0;
1978       dyn_global_index = 0;
1979       dyncount = 0;
1980     }
1981   else
1982     {
1983       dyn_global_index = this->dynsym_section_->info();
1984       off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
1985       dynoff = this->dynsym_section_->offset() + locsize;
1986       dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
1987       gold_assert(static_cast<off_t>(dyncount * symsize)
1988                   == this->dynsym_section_->data_size() - locsize);
1989     }
1990
1991   off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
1992                          &this->sympool_, &local_symcount);
1993
1994   if (!parameters->options().strip_all())
1995     {
1996       this->sympool_.set_string_offsets();
1997
1998       const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
1999       Output_section* osymtab = this->make_output_section(symtab_name,
2000                                                           elfcpp::SHT_SYMTAB,
2001                                                           0);
2002       this->symtab_section_ = osymtab;
2003
2004       Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2005                                                              align);
2006       osymtab->add_output_section_data(pos);
2007
2008       // We generate a .symtab_shndx section if we have more than
2009       // SHN_LORESERVE sections.  Technically it is possible that we
2010       // don't need one, because it is possible that there are no
2011       // symbols in any of sections with indexes larger than
2012       // SHN_LORESERVE.  That is probably unusual, though, and it is
2013       // easier to always create one than to compute section indexes
2014       // twice (once here, once when writing out the symbols).
2015       if (shnum >= elfcpp::SHN_LORESERVE)
2016         {
2017           const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2018                                                                false, NULL);
2019           Output_section* osymtab_xindex =
2020             this->make_output_section(symtab_xindex_name,
2021                                       elfcpp::SHT_SYMTAB_SHNDX, 0);
2022
2023           size_t symcount = (off - startoff) / symsize;
2024           this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2025
2026           osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2027
2028           osymtab_xindex->set_link_section(osymtab);
2029           osymtab_xindex->set_addralign(4);
2030           osymtab_xindex->set_entsize(4);
2031
2032           osymtab_xindex->set_after_input_sections();
2033
2034           // This tells the driver code to wait until the symbol table
2035           // has written out before writing out the postprocessing
2036           // sections, including the .symtab_shndx section.
2037           this->any_postprocessing_sections_ = true;
2038         }
2039
2040       const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2041       Output_section* ostrtab = this->make_output_section(strtab_name,
2042                                                           elfcpp::SHT_STRTAB,
2043                                                           0);
2044
2045       Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2046       ostrtab->add_output_section_data(pstr);
2047
2048       osymtab->set_file_offset(startoff);
2049       osymtab->finalize_data_size();
2050       osymtab->set_link_section(ostrtab);
2051       osymtab->set_info(local_symcount);
2052       osymtab->set_entsize(symsize);
2053
2054       *poff = off;
2055     }
2056 }
2057
2058 // Create the .shstrtab section, which holds the names of the
2059 // sections.  At the time this is called, we have created all the
2060 // output sections except .shstrtab itself.
2061
2062 Output_section*
2063 Layout::create_shstrtab()
2064 {
2065   // FIXME: We don't need to create a .shstrtab section if we are
2066   // stripping everything.
2067
2068   const char* name = this->namepool_.add(".shstrtab", false, NULL);
2069
2070   Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
2071
2072   // We can't write out this section until we've set all the section
2073   // names, and we don't set the names of compressed output sections
2074   // until relocations are complete.
2075   os->set_after_input_sections();
2076
2077   Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2078   os->add_output_section_data(posd);
2079
2080   return os;
2081 }
2082
2083 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
2084 // offset.
2085
2086 void
2087 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2088 {
2089   Output_section_headers* oshdrs;
2090   oshdrs = new Output_section_headers(this,
2091                                       &this->segment_list_,
2092                                       &this->section_list_,
2093                                       &this->unattached_section_list_,
2094                                       &this->namepool_,
2095                                       shstrtab_section);
2096   off_t off = align_address(*poff, oshdrs->addralign());
2097   oshdrs->set_address_and_file_offset(0, off);
2098   off += oshdrs->data_size();
2099   *poff = off;
2100   this->section_headers_ = oshdrs;
2101 }
2102
2103 // Count the allocated sections.
2104
2105 size_t
2106 Layout::allocated_output_section_count() const
2107 {
2108   size_t section_count = 0;
2109   for (Segment_list::const_iterator p = this->segment_list_.begin();
2110        p != this->segment_list_.end();
2111        ++p)
2112     section_count += (*p)->output_section_count();
2113   return section_count;
2114 }
2115
2116 // Create the dynamic symbol table.
2117
2118 void
2119 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2120                               Symbol_table* symtab,
2121                               Output_section **pdynstr,
2122                               unsigned int* plocal_dynamic_count,
2123                               std::vector<Symbol*>* pdynamic_symbols,
2124                               Versions* pversions)
2125 {
2126   // Count all the symbols in the dynamic symbol table, and set the
2127   // dynamic symbol indexes.
2128
2129   // Skip symbol 0, which is always all zeroes.
2130   unsigned int index = 1;
2131
2132   // Add STT_SECTION symbols for each Output section which needs one.
2133   for (Section_list::iterator p = this->section_list_.begin();
2134        p != this->section_list_.end();
2135        ++p)
2136     {
2137       if (!(*p)->needs_dynsym_index())
2138         (*p)->set_dynsym_index(-1U);
2139       else
2140         {
2141           (*p)->set_dynsym_index(index);
2142           ++index;
2143         }
2144     }
2145
2146   // Count the local symbols that need to go in the dynamic symbol table,
2147   // and set the dynamic symbol indexes.
2148   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2149        p != input_objects->relobj_end();
2150        ++p)
2151     {
2152       unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2153       index = new_index;
2154     }
2155
2156   unsigned int local_symcount = index;
2157   *plocal_dynamic_count = local_symcount;
2158
2159   index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2160                                      &this->dynpool_, pversions);
2161
2162   int symsize;
2163   unsigned int align;
2164   const int size = parameters->target().get_size();
2165   if (size == 32)
2166     {
2167       symsize = elfcpp::Elf_sizes<32>::sym_size;
2168       align = 4;
2169     }
2170   else if (size == 64)
2171     {
2172       symsize = elfcpp::Elf_sizes<64>::sym_size;
2173       align = 8;
2174     }
2175   else
2176     gold_unreachable();
2177
2178   // Create the dynamic symbol table section.
2179
2180   Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2181                                                        elfcpp::SHT_DYNSYM,
2182                                                        elfcpp::SHF_ALLOC,
2183                                                        false);
2184
2185   Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2186                                                            align);
2187   dynsym->add_output_section_data(odata);
2188
2189   dynsym->set_info(local_symcount);
2190   dynsym->set_entsize(symsize);
2191   dynsym->set_addralign(align);
2192
2193   this->dynsym_section_ = dynsym;
2194
2195   Output_data_dynamic* const odyn = this->dynamic_data_;
2196   odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2197   odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2198
2199   // If there are more than SHN_LORESERVE allocated sections, we
2200   // create a .dynsym_shndx section.  It is possible that we don't
2201   // need one, because it is possible that there are no dynamic
2202   // symbols in any of the sections with indexes larger than
2203   // SHN_LORESERVE.  This is probably unusual, though, and at this
2204   // time we don't know the actual section indexes so it is
2205   // inconvenient to check.
2206   if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2207     {
2208       Output_section* dynsym_xindex =
2209         this->choose_output_section(NULL, ".dynsym_shndx",
2210                                     elfcpp::SHT_SYMTAB_SHNDX,
2211                                     elfcpp::SHF_ALLOC,
2212                                     false);
2213
2214       this->dynsym_xindex_ = new Output_symtab_xindex(index);
2215
2216       dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2217
2218       dynsym_xindex->set_link_section(dynsym);
2219       dynsym_xindex->set_addralign(4);
2220       dynsym_xindex->set_entsize(4);
2221
2222       dynsym_xindex->set_after_input_sections();
2223
2224       // This tells the driver code to wait until the symbol table has
2225       // written out before writing out the postprocessing sections,
2226       // including the .dynsym_shndx section.
2227       this->any_postprocessing_sections_ = true;
2228     }
2229
2230   // Create the dynamic string table section.
2231
2232   Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2233                                                        elfcpp::SHT_STRTAB,
2234                                                        elfcpp::SHF_ALLOC,
2235                                                        false);
2236
2237   Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2238   dynstr->add_output_section_data(strdata);
2239
2240   dynsym->set_link_section(dynstr);
2241   this->dynamic_section_->set_link_section(dynstr);
2242
2243   odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2244   odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2245
2246   *pdynstr = dynstr;
2247
2248   // Create the hash tables.
2249
2250   if (strcmp(parameters->options().hash_style(), "sysv") == 0
2251       || strcmp(parameters->options().hash_style(), "both") == 0)
2252     {
2253       unsigned char* phash;
2254       unsigned int hashlen;
2255       Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2256                                     &phash, &hashlen);
2257
2258       Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2259                                                             elfcpp::SHT_HASH,
2260                                                             elfcpp::SHF_ALLOC,
2261                                                             false);
2262
2263       Output_section_data* hashdata = new Output_data_const_buffer(phash,
2264                                                                    hashlen,
2265                                                                    align);
2266       hashsec->add_output_section_data(hashdata);
2267
2268       hashsec->set_link_section(dynsym);
2269       hashsec->set_entsize(4);
2270
2271       odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2272     }
2273
2274   if (strcmp(parameters->options().hash_style(), "gnu") == 0
2275       || strcmp(parameters->options().hash_style(), "both") == 0)
2276     {
2277       unsigned char* phash;
2278       unsigned int hashlen;
2279       Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2280                                     &phash, &hashlen);
2281
2282       Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2283                                                             elfcpp::SHT_GNU_HASH,
2284                                                             elfcpp::SHF_ALLOC,
2285                                                             false);
2286
2287       Output_section_data* hashdata = new Output_data_const_buffer(phash,
2288                                                                    hashlen,
2289                                                                    align);
2290       hashsec->add_output_section_data(hashdata);
2291
2292       hashsec->set_link_section(dynsym);
2293       hashsec->set_entsize(4);
2294
2295       odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2296     }
2297 }
2298
2299 // Assign offsets to each local portion of the dynamic symbol table.
2300
2301 void
2302 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2303 {
2304   Output_section* dynsym = this->dynsym_section_;
2305   gold_assert(dynsym != NULL);
2306
2307   off_t off = dynsym->offset();
2308
2309   // Skip the dummy symbol at the start of the section.
2310   off += dynsym->entsize();
2311
2312   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2313        p != input_objects->relobj_end();
2314        ++p)
2315     {
2316       unsigned int count = (*p)->set_local_dynsym_offset(off);
2317       off += count * dynsym->entsize();
2318     }
2319 }
2320
2321 // Create the version sections.
2322
2323 void
2324 Layout::create_version_sections(const Versions* versions,
2325                                 const Symbol_table* symtab,
2326                                 unsigned int local_symcount,
2327                                 const std::vector<Symbol*>& dynamic_symbols,
2328                                 const Output_section* dynstr)
2329 {
2330   if (!versions->any_defs() && !versions->any_needs())
2331     return;
2332
2333   switch (parameters->size_and_endianness())
2334     {
2335 #ifdef HAVE_TARGET_32_LITTLE
2336     case Parameters::TARGET_32_LITTLE:
2337       this->sized_create_version_sections<32, false>(versions, symtab,
2338                                                      local_symcount,
2339                                                      dynamic_symbols, dynstr);
2340       break;
2341 #endif
2342 #ifdef HAVE_TARGET_32_BIG
2343     case Parameters::TARGET_32_BIG:
2344       this->sized_create_version_sections<32, true>(versions, symtab,
2345                                                     local_symcount,
2346                                                     dynamic_symbols, dynstr);
2347       break;
2348 #endif
2349 #ifdef HAVE_TARGET_64_LITTLE
2350     case Parameters::TARGET_64_LITTLE:
2351       this->sized_create_version_sections<64, false>(versions, symtab,
2352                                                      local_symcount,
2353                                                      dynamic_symbols, dynstr);
2354       break;
2355 #endif
2356 #ifdef HAVE_TARGET_64_BIG
2357     case Parameters::TARGET_64_BIG:
2358       this->sized_create_version_sections<64, true>(versions, symtab,
2359                                                     local_symcount,
2360                                                     dynamic_symbols, dynstr);
2361       break;
2362 #endif
2363     default:
2364       gold_unreachable();
2365     }
2366 }
2367
2368 // Create the version sections, sized version.
2369
2370 template<int size, bool big_endian>
2371 void
2372 Layout::sized_create_version_sections(
2373     const Versions* versions,
2374     const Symbol_table* symtab,
2375     unsigned int local_symcount,
2376     const std::vector<Symbol*>& dynamic_symbols,
2377     const Output_section* dynstr)
2378 {
2379   Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2380                                                      elfcpp::SHT_GNU_versym,
2381                                                      elfcpp::SHF_ALLOC,
2382                                                      false);
2383
2384   unsigned char* vbuf;
2385   unsigned int vsize;
2386   versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2387                                                       local_symcount,
2388                                                       dynamic_symbols,
2389                                                       &vbuf, &vsize);
2390
2391   Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2);
2392
2393   vsec->add_output_section_data(vdata);
2394   vsec->set_entsize(2);
2395   vsec->set_link_section(this->dynsym_section_);
2396
2397   Output_data_dynamic* const odyn = this->dynamic_data_;
2398   odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2399
2400   if (versions->any_defs())
2401     {
2402       Output_section* vdsec;
2403       vdsec= this->choose_output_section(NULL, ".gnu.version_d",
2404                                          elfcpp::SHT_GNU_verdef,
2405                                          elfcpp::SHF_ALLOC,
2406                                          false);
2407
2408       unsigned char* vdbuf;
2409       unsigned int vdsize;
2410       unsigned int vdentries;
2411       versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
2412                                                        &vdsize, &vdentries);
2413
2414       Output_section_data* vddata = new Output_data_const_buffer(vdbuf,
2415                                                                  vdsize,
2416                                                                  4);
2417
2418       vdsec->add_output_section_data(vddata);
2419       vdsec->set_link_section(dynstr);
2420       vdsec->set_info(vdentries);
2421
2422       odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
2423       odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
2424     }
2425
2426   if (versions->any_needs())
2427     {
2428       Output_section* vnsec;
2429       vnsec = this->choose_output_section(NULL, ".gnu.version_r",
2430                                           elfcpp::SHT_GNU_verneed,
2431                                           elfcpp::SHF_ALLOC,
2432                                           false);
2433
2434       unsigned char* vnbuf;
2435       unsigned int vnsize;
2436       unsigned int vnentries;
2437       versions->need_section_contents<size, big_endian>(&this->dynpool_,
2438                                                         &vnbuf, &vnsize,
2439                                                         &vnentries);
2440
2441       Output_section_data* vndata = new Output_data_const_buffer(vnbuf,
2442                                                                  vnsize,
2443                                                                  4);
2444
2445       vnsec->add_output_section_data(vndata);
2446       vnsec->set_link_section(dynstr);
2447       vnsec->set_info(vnentries);
2448
2449       odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
2450       odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
2451     }
2452 }
2453
2454 // Create the .interp section and PT_INTERP segment.
2455
2456 void
2457 Layout::create_interp(const Target* target)
2458 {
2459   const char* interp = this->options_.dynamic_linker();
2460   if (interp == NULL)
2461     {
2462       interp = target->dynamic_linker();
2463       gold_assert(interp != NULL);
2464     }
2465
2466   size_t len = strlen(interp) + 1;
2467
2468   Output_section_data* odata = new Output_data_const(interp, len, 1);
2469
2470   Output_section* osec = this->choose_output_section(NULL, ".interp",
2471                                                      elfcpp::SHT_PROGBITS,
2472                                                      elfcpp::SHF_ALLOC,
2473                                                      false);
2474   osec->add_output_section_data(odata);
2475
2476   if (!this->script_options_->saw_phdrs_clause())
2477     {
2478       Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
2479                                                        elfcpp::PF_R);
2480       oseg->add_initial_output_section(osec, elfcpp::PF_R);
2481     }
2482 }
2483
2484 // Finish the .dynamic section and PT_DYNAMIC segment.
2485
2486 void
2487 Layout::finish_dynamic_section(const Input_objects* input_objects,
2488                                const Symbol_table* symtab)
2489 {
2490   if (!this->script_options_->saw_phdrs_clause())
2491     {
2492       Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
2493                                                        (elfcpp::PF_R
2494                                                         | elfcpp::PF_W));
2495       oseg->add_initial_output_section(this->dynamic_section_,
2496                                        elfcpp::PF_R | elfcpp::PF_W);
2497     }
2498
2499   Output_data_dynamic* const odyn = this->dynamic_data_;
2500
2501   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
2502        p != input_objects->dynobj_end();
2503        ++p)
2504     {
2505       // FIXME: Handle --as-needed.
2506       odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
2507     }
2508
2509   if (parameters->options().shared())
2510     {
2511       const char* soname = this->options_.soname();
2512       if (soname != NULL)
2513         odyn->add_string(elfcpp::DT_SONAME, soname);
2514     }
2515
2516   // FIXME: Support --init and --fini.
2517   Symbol* sym = symtab->lookup("_init");
2518   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2519     odyn->add_symbol(elfcpp::DT_INIT, sym);
2520
2521   sym = symtab->lookup("_fini");
2522   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2523     odyn->add_symbol(elfcpp::DT_FINI, sym);
2524
2525   // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
2526
2527   // Add a DT_RPATH entry if needed.
2528   const General_options::Dir_list& rpath(this->options_.rpath());
2529   if (!rpath.empty())
2530     {
2531       std::string rpath_val;
2532       for (General_options::Dir_list::const_iterator p = rpath.begin();
2533            p != rpath.end();
2534            ++p)
2535         {
2536           if (rpath_val.empty())
2537             rpath_val = p->name();
2538           else
2539             {
2540               // Eliminate duplicates.
2541               General_options::Dir_list::const_iterator q;
2542               for (q = rpath.begin(); q != p; ++q)
2543                 if (q->name() == p->name())
2544                   break;
2545               if (q == p)
2546                 {
2547                   rpath_val += ':';
2548                   rpath_val += p->name();
2549                 }
2550             }
2551         }
2552
2553       odyn->add_string(elfcpp::DT_RPATH, rpath_val);
2554       if (parameters->options().enable_new_dtags())
2555         odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
2556     }
2557
2558   // Look for text segments that have dynamic relocations.
2559   bool have_textrel = false;
2560   if (!this->script_options_->saw_sections_clause())
2561     {
2562       for (Segment_list::const_iterator p = this->segment_list_.begin();
2563            p != this->segment_list_.end();
2564            ++p)
2565         {
2566           if (((*p)->flags() & elfcpp::PF_W) == 0
2567               && (*p)->dynamic_reloc_count() > 0)
2568             {
2569               have_textrel = true;
2570               break;
2571             }
2572         }
2573     }
2574   else
2575     {
2576       // We don't know the section -> segment mapping, so we are
2577       // conservative and just look for readonly sections with
2578       // relocations.  If those sections wind up in writable segments,
2579       // then we have created an unnecessary DT_TEXTREL entry.
2580       for (Section_list::const_iterator p = this->section_list_.begin();
2581            p != this->section_list_.end();
2582            ++p)
2583         {
2584           if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
2585               && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
2586               && ((*p)->dynamic_reloc_count() > 0))
2587             {
2588               have_textrel = true;
2589               break;
2590             }
2591         }
2592     }
2593
2594   // Add a DT_FLAGS entry. We add it even if no flags are set so that
2595   // post-link tools can easily modify these flags if desired.
2596   unsigned int flags = 0;
2597   if (have_textrel)
2598     {
2599       // Add a DT_TEXTREL for compatibility with older loaders.
2600       odyn->add_constant(elfcpp::DT_TEXTREL, 0);
2601       flags |= elfcpp::DF_TEXTREL;
2602     }
2603   if (parameters->options().shared() && this->has_static_tls())
2604     flags |= elfcpp::DF_STATIC_TLS;
2605   odyn->add_constant(elfcpp::DT_FLAGS, flags);
2606
2607   flags = 0;
2608   if (parameters->options().initfirst())
2609     flags |= elfcpp::DF_1_INITFIRST;
2610   if (parameters->options().interpose())
2611     flags |= elfcpp::DF_1_INTERPOSE;
2612   if (parameters->options().loadfltr())
2613     flags |= elfcpp::DF_1_LOADFLTR;
2614   if (parameters->options().nodefaultlib())
2615     flags |= elfcpp::DF_1_NODEFLIB;
2616   if (parameters->options().nodelete())
2617     flags |= elfcpp::DF_1_NODELETE;
2618   if (parameters->options().nodlopen())
2619     flags |= elfcpp::DF_1_NOOPEN;
2620   if (parameters->options().nodump())
2621     flags |= elfcpp::DF_1_NODUMP;
2622   if (!parameters->options().shared())
2623     flags &= ~(elfcpp::DF_1_INITFIRST
2624                | elfcpp::DF_1_NODELETE
2625                | elfcpp::DF_1_NOOPEN);
2626   if (flags)
2627     odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
2628 }
2629
2630 // The mapping of .gnu.linkonce section names to real section names.
2631
2632 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
2633 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
2634 {
2635   MAPPING_INIT("d.rel.ro", ".data.rel.ro"),     // Must be before "d".
2636   MAPPING_INIT("t", ".text"),
2637   MAPPING_INIT("r", ".rodata"),
2638   MAPPING_INIT("d", ".data"),
2639   MAPPING_INIT("b", ".bss"),
2640   MAPPING_INIT("s", ".sdata"),
2641   MAPPING_INIT("sb", ".sbss"),
2642   MAPPING_INIT("s2", ".sdata2"),
2643   MAPPING_INIT("sb2", ".sbss2"),
2644   MAPPING_INIT("wi", ".debug_info"),
2645   MAPPING_INIT("td", ".tdata"),
2646   MAPPING_INIT("tb", ".tbss"),
2647   MAPPING_INIT("lr", ".lrodata"),
2648   MAPPING_INIT("l", ".ldata"),
2649   MAPPING_INIT("lb", ".lbss"),
2650 };
2651 #undef MAPPING_INIT
2652
2653 const int Layout::linkonce_mapping_count =
2654   sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
2655
2656 // Return the name of the output section to use for a .gnu.linkonce
2657 // section.  This is based on the default ELF linker script of the old
2658 // GNU linker.  For example, we map a name like ".gnu.linkonce.t.foo"
2659 // to ".text".  Set *PLEN to the length of the name.  *PLEN is
2660 // initialized to the length of NAME.
2661
2662 const char*
2663 Layout::linkonce_output_name(const char* name, size_t *plen)
2664 {
2665   const char* s = name + sizeof(".gnu.linkonce") - 1;
2666   if (*s != '.')
2667     return name;
2668   ++s;
2669   const Linkonce_mapping* plm = linkonce_mapping;
2670   for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2671     {
2672       if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2673         {
2674           *plen = plm->tolen;
2675           return plm->to;
2676         }
2677     }
2678   return name;
2679 }
2680
2681 // Choose the output section name to use given an input section name.
2682 // Set *PLEN to the length of the name.  *PLEN is initialized to the
2683 // length of NAME.
2684
2685 const char*
2686 Layout::output_section_name(const char* name, size_t* plen)
2687 {
2688   if (Layout::is_linkonce(name))
2689     {
2690       // .gnu.linkonce sections are laid out as though they were named
2691       // for the sections are placed into.
2692       return Layout::linkonce_output_name(name, plen);
2693     }
2694
2695   // gcc 4.3 generates the following sorts of section names when it
2696   // needs a section name specific to a function:
2697   //   .text.FN
2698   //   .rodata.FN
2699   //   .sdata2.FN
2700   //   .data.FN
2701   //   .data.rel.FN
2702   //   .data.rel.local.FN
2703   //   .data.rel.ro.FN
2704   //   .data.rel.ro.local.FN
2705   //   .sdata.FN
2706   //   .bss.FN
2707   //   .sbss.FN
2708   //   .tdata.FN
2709   //   .tbss.FN
2710
2711   // The GNU linker maps all of those to the part before the .FN,
2712   // except that .data.rel.local.FN is mapped to .data, and
2713   // .data.rel.ro.local.FN is mapped to .data.rel.ro.  The sections
2714   // beginning with .data.rel.ro.local are grouped together.
2715
2716   // For an anonymous namespace, the string FN can contain a '.'.
2717
2718   // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2719   // GNU linker maps to .rodata.
2720
2721   // The .data.rel.ro sections enable a security feature triggered by
2722   // the -z relro option.  Section which need to be relocated at
2723   // program startup time but which may be readonly after startup are
2724   // grouped into .data.rel.ro.  They are then put into a PT_GNU_RELRO
2725   // segment.  The dynamic linker will make that segment writable,
2726   // perform relocations, and then make it read-only.  FIXME: We do
2727   // not yet implement this optimization.
2728
2729   // It is hard to handle this in a principled way.
2730
2731   // These are the rules we follow:
2732
2733   // If the section name has no initial '.', or no dot other than an
2734   // initial '.', we use the name unchanged (i.e., "mysection" and
2735   // ".text" are unchanged).
2736
2737   // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2738
2739   // Otherwise, we drop the second '.' and everything that comes after
2740   // it (i.e., ".text.XXX" becomes ".text").
2741
2742   const char* s = name;
2743   if (*s != '.')
2744     return name;
2745   ++s;
2746   const char* sdot = strchr(s, '.');
2747   if (sdot == NULL)
2748     return name;
2749
2750   const char* const data_rel_ro = ".data.rel.ro";
2751   if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2752     {
2753       *plen = strlen(data_rel_ro);
2754       return data_rel_ro;
2755     }
2756
2757   *plen = sdot - name;
2758   return name;
2759 }
2760
2761 // Record the signature of a comdat section, and return whether to
2762 // include it in the link.  If GROUP is true, this is a regular
2763 // section group.  If GROUP is false, this is a group signature
2764 // derived from the name of a linkonce section.  We want linkonce
2765 // signatures and group signatures to block each other, but we don't
2766 // want a linkonce signature to block another linkonce signature.
2767
2768 bool
2769 Layout::add_comdat(Relobj* object, unsigned int shndx,
2770                    const std::string& signature, bool group)
2771 {
2772   Kept_section kept(object, shndx, group);
2773   std::pair<Signatures::iterator, bool> ins(
2774     this->signatures_.insert(std::make_pair(signature, kept)));
2775
2776   if (ins.second)
2777     {
2778       // This is the first time we've seen this signature.
2779       return true;
2780     }
2781
2782   if (ins.first->second.group_)
2783     {
2784       // We've already seen a real section group with this signature.
2785       return false;
2786     }
2787   else if (group)
2788     {
2789       // This is a real section group, and we've already seen a
2790       // linkonce section with this signature.  Record that we've seen
2791       // a section group, and don't include this section group.
2792       ins.first->second.group_ = true;
2793       return false;
2794     }
2795   else
2796     {
2797       // We've already seen a linkonce section and this is a linkonce
2798       // section.  These don't block each other--this may be the same
2799       // symbol name with different section types.
2800       return true;
2801     }
2802 }
2803
2804 // Find the given comdat signature, and return the object and section
2805 // index of the kept group.
2806 Relobj*
2807 Layout::find_kept_object(const std::string& signature,
2808                          unsigned int* pshndx) const
2809 {
2810   Signatures::const_iterator p = this->signatures_.find(signature);
2811   if (p == this->signatures_.end())
2812     return NULL;
2813   if (pshndx != NULL)
2814     *pshndx = p->second.shndx_;
2815   return p->second.object_;
2816 }
2817
2818 // Store the allocated sections into the section list.
2819
2820 void
2821 Layout::get_allocated_sections(Section_list* section_list) const
2822 {
2823   for (Section_list::const_iterator p = this->section_list_.begin();
2824        p != this->section_list_.end();
2825        ++p)
2826     if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2827       section_list->push_back(*p);
2828 }
2829
2830 // Create an output segment.
2831
2832 Output_segment*
2833 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2834 {
2835   gold_assert(!parameters->options().relocatable());
2836   Output_segment* oseg = new Output_segment(type, flags);
2837   this->segment_list_.push_back(oseg);
2838   return oseg;
2839 }
2840
2841 // Write out the Output_sections.  Most won't have anything to write,
2842 // since most of the data will come from input sections which are
2843 // handled elsewhere.  But some Output_sections do have Output_data.
2844
2845 void
2846 Layout::write_output_sections(Output_file* of) const
2847 {
2848   for (Section_list::const_iterator p = this->section_list_.begin();
2849        p != this->section_list_.end();
2850        ++p)
2851     {
2852       if (!(*p)->after_input_sections())
2853         (*p)->write(of);
2854     }
2855 }
2856
2857 // Write out data not associated with a section or the symbol table.
2858
2859 void
2860 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
2861 {
2862   if (!parameters->options().strip_all())
2863     {
2864       const Output_section* symtab_section = this->symtab_section_;
2865       for (Section_list::const_iterator p = this->section_list_.begin();
2866            p != this->section_list_.end();
2867            ++p)
2868         {
2869           if ((*p)->needs_symtab_index())
2870             {
2871               gold_assert(symtab_section != NULL);
2872               unsigned int index = (*p)->symtab_index();
2873               gold_assert(index > 0 && index != -1U);
2874               off_t off = (symtab_section->offset()
2875                            + index * symtab_section->entsize());
2876               symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
2877             }
2878         }
2879     }
2880
2881   const Output_section* dynsym_section = this->dynsym_section_;
2882   for (Section_list::const_iterator p = this->section_list_.begin();
2883        p != this->section_list_.end();
2884        ++p)
2885     {
2886       if ((*p)->needs_dynsym_index())
2887         {
2888           gold_assert(dynsym_section != NULL);
2889           unsigned int index = (*p)->dynsym_index();
2890           gold_assert(index > 0 && index != -1U);
2891           off_t off = (dynsym_section->offset()
2892                        + index * dynsym_section->entsize());
2893           symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
2894         }
2895     }
2896
2897   // Write out the Output_data which are not in an Output_section.
2898   for (Data_list::const_iterator p = this->special_output_list_.begin();
2899        p != this->special_output_list_.end();
2900        ++p)
2901     (*p)->write(of);
2902 }
2903
2904 // Write out the Output_sections which can only be written after the
2905 // input sections are complete.
2906
2907 void
2908 Layout::write_sections_after_input_sections(Output_file* of)
2909 {
2910   // Determine the final section offsets, and thus the final output
2911   // file size.  Note we finalize the .shstrab last, to allow the
2912   // after_input_section sections to modify their section-names before
2913   // writing.
2914   if (this->any_postprocessing_sections_)
2915     {
2916       off_t off = this->output_file_size_;
2917       off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
2918       
2919       // Now that we've finalized the names, we can finalize the shstrab.
2920       off =
2921         this->set_section_offsets(off,
2922                                   STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2923
2924       if (off > this->output_file_size_)
2925         {
2926           of->resize(off);
2927           this->output_file_size_ = off;
2928         }
2929     }
2930
2931   for (Section_list::const_iterator p = this->section_list_.begin();
2932        p != this->section_list_.end();
2933        ++p)
2934     {
2935       if ((*p)->after_input_sections())
2936         (*p)->write(of);
2937     }
2938
2939   this->section_headers_->write(of);
2940 }
2941
2942 // If the build ID requires computing a checksum, do so here, and
2943 // write it out.  We compute a checksum over the entire file because
2944 // that is simplest.
2945
2946 void
2947 Layout::write_build_id(Output_file* of) const
2948 {
2949   if (this->build_id_note_ == NULL)
2950     return;
2951
2952   const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
2953
2954   unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
2955                                           this->build_id_note_->data_size());
2956
2957   const char* style = parameters->options().build_id();
2958   if (strcmp(style, "sha1") == 0)
2959     {
2960       sha1_ctx ctx;
2961       sha1_init_ctx(&ctx);
2962       sha1_process_bytes(iv, this->output_file_size_, &ctx);
2963       sha1_finish_ctx(&ctx, ov);
2964     }
2965   else if (strcmp(style, "md5") == 0)
2966     {
2967       md5_ctx ctx;
2968       md5_init_ctx(&ctx);
2969       md5_process_bytes(iv, this->output_file_size_, &ctx);
2970       md5_finish_ctx(&ctx, ov);
2971     }
2972   else
2973     gold_unreachable();
2974
2975   of->write_output_view(this->build_id_note_->offset(),
2976                         this->build_id_note_->data_size(),
2977                         ov);
2978
2979   of->free_input_view(0, this->output_file_size_, iv);
2980 }
2981
2982 // Write out a binary file.  This is called after the link is
2983 // complete.  IN is the temporary output file we used to generate the
2984 // ELF code.  We simply walk through the segments, read them from
2985 // their file offset in IN, and write them to their load address in
2986 // the output file.  FIXME: with a bit more work, we could support
2987 // S-records and/or Intel hex format here.
2988
2989 void
2990 Layout::write_binary(Output_file* in) const
2991 {
2992   gold_assert(this->options_.oformat_enum()
2993               == General_options::OBJECT_FORMAT_BINARY);
2994
2995   // Get the size of the binary file.
2996   uint64_t max_load_address = 0;
2997   for (Segment_list::const_iterator p = this->segment_list_.begin();
2998        p != this->segment_list_.end();
2999        ++p)
3000     {
3001       if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3002         {
3003           uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3004           if (max_paddr > max_load_address)
3005             max_load_address = max_paddr;
3006         }
3007     }
3008
3009   Output_file out(parameters->options().output_file_name());
3010   out.open(max_load_address);
3011
3012   for (Segment_list::const_iterator p = this->segment_list_.begin();
3013        p != this->segment_list_.end();
3014        ++p)
3015     {
3016       if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3017         {
3018           const unsigned char* vin = in->get_input_view((*p)->offset(),
3019                                                         (*p)->filesz());
3020           unsigned char* vout = out.get_output_view((*p)->paddr(),
3021                                                     (*p)->filesz());
3022           memcpy(vout, vin, (*p)->filesz());
3023           out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3024           in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3025         }
3026     }
3027
3028   out.close();
3029 }
3030
3031 // Print statistical information to stderr.  This is used for --stats.
3032
3033 void
3034 Layout::print_stats() const
3035 {
3036   this->namepool_.print_stats("section name pool");
3037   this->sympool_.print_stats("output symbol name pool");
3038   this->dynpool_.print_stats("dynamic name pool");
3039
3040   for (Section_list::const_iterator p = this->section_list_.begin();
3041        p != this->section_list_.end();
3042        ++p)
3043     (*p)->print_merge_stats();
3044 }
3045
3046 // Write_sections_task methods.
3047
3048 // We can always run this task.
3049
3050 Task_token*
3051 Write_sections_task::is_runnable()
3052 {
3053   return NULL;
3054 }
3055
3056 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3057 // when finished.
3058
3059 void
3060 Write_sections_task::locks(Task_locker* tl)
3061 {
3062   tl->add(this, this->output_sections_blocker_);
3063   tl->add(this, this->final_blocker_);
3064 }
3065
3066 // Run the task--write out the data.
3067
3068 void
3069 Write_sections_task::run(Workqueue*)
3070 {
3071   this->layout_->write_output_sections(this->of_);
3072 }
3073
3074 // Write_data_task methods.
3075
3076 // We can always run this task.
3077
3078 Task_token*
3079 Write_data_task::is_runnable()
3080 {
3081   return NULL;
3082 }
3083
3084 // We need to unlock FINAL_BLOCKER when finished.
3085
3086 void
3087 Write_data_task::locks(Task_locker* tl)
3088 {
3089   tl->add(this, this->final_blocker_);
3090 }
3091
3092 // Run the task--write out the data.
3093
3094 void
3095 Write_data_task::run(Workqueue*)
3096 {
3097   this->layout_->write_data(this->symtab_, this->of_);
3098 }
3099
3100 // Write_symbols_task methods.
3101
3102 // We can always run this task.
3103
3104 Task_token*
3105 Write_symbols_task::is_runnable()
3106 {
3107   return NULL;
3108 }
3109
3110 // We need to unlock FINAL_BLOCKER when finished.
3111
3112 void
3113 Write_symbols_task::locks(Task_locker* tl)
3114 {
3115   tl->add(this, this->final_blocker_);
3116 }
3117
3118 // Run the task--write out the symbols.
3119
3120 void
3121 Write_symbols_task::run(Workqueue*)
3122 {
3123   this->symtab_->write_globals(this->input_objects_, this->sympool_,
3124                                this->dynpool_, this->layout_->symtab_xindex(),
3125                                this->layout_->dynsym_xindex(), this->of_);
3126 }
3127
3128 // Write_after_input_sections_task methods.
3129
3130 // We can only run this task after the input sections have completed.
3131
3132 Task_token*
3133 Write_after_input_sections_task::is_runnable()
3134 {
3135   if (this->input_sections_blocker_->is_blocked())
3136     return this->input_sections_blocker_;
3137   return NULL;
3138 }
3139
3140 // We need to unlock FINAL_BLOCKER when finished.
3141
3142 void
3143 Write_after_input_sections_task::locks(Task_locker* tl)
3144 {
3145   tl->add(this, this->final_blocker_);
3146 }
3147
3148 // Run the task.
3149
3150 void
3151 Write_after_input_sections_task::run(Workqueue*)
3152 {
3153   this->layout_->write_sections_after_input_sections(this->of_);
3154 }
3155
3156 // Close_task_runner methods.
3157
3158 // Run the task--close the file.
3159
3160 void
3161 Close_task_runner::run(Workqueue*, const Task*)
3162 {
3163   // If we need to compute a checksum for the BUILD if, we do so here.
3164   this->layout_->write_build_id(this->of_);
3165
3166   // If we've been asked to create a binary file, we do so here.
3167   if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3168     this->layout_->write_binary(this->of_);
3169
3170   this->of_->close();
3171 }
3172
3173 // Instantiate the templates we need.  We could use the configure
3174 // script to restrict this to only the ones for implemented targets.
3175
3176 #ifdef HAVE_TARGET_32_LITTLE
3177 template
3178 Output_section*
3179 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3180                           const char* name,
3181                           const elfcpp::Shdr<32, false>& shdr,
3182                           unsigned int, unsigned int, off_t*);
3183 #endif
3184
3185 #ifdef HAVE_TARGET_32_BIG
3186 template
3187 Output_section*
3188 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3189                          const char* name,
3190                          const elfcpp::Shdr<32, true>& shdr,
3191                          unsigned int, unsigned int, off_t*);
3192 #endif
3193
3194 #ifdef HAVE_TARGET_64_LITTLE
3195 template
3196 Output_section*
3197 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3198                           const char* name,
3199                           const elfcpp::Shdr<64, false>& shdr,
3200                           unsigned int, unsigned int, off_t*);
3201 #endif
3202
3203 #ifdef HAVE_TARGET_64_BIG
3204 template
3205 Output_section*
3206 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3207                          const char* name,
3208                          const elfcpp::Shdr<64, true>& shdr,
3209                          unsigned int, unsigned int, off_t*);
3210 #endif
3211
3212 #ifdef HAVE_TARGET_32_LITTLE
3213 template
3214 Output_section*
3215 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3216                                 unsigned int reloc_shndx,
3217                                 const elfcpp::Shdr<32, false>& shdr,
3218                                 Output_section* data_section,
3219                                 Relocatable_relocs* rr);
3220 #endif
3221
3222 #ifdef HAVE_TARGET_32_BIG
3223 template
3224 Output_section*
3225 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3226                                unsigned int reloc_shndx,
3227                                const elfcpp::Shdr<32, true>& shdr,
3228                                Output_section* data_section,
3229                                Relocatable_relocs* rr);
3230 #endif
3231
3232 #ifdef HAVE_TARGET_64_LITTLE
3233 template
3234 Output_section*
3235 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3236                                 unsigned int reloc_shndx,
3237                                 const elfcpp::Shdr<64, false>& shdr,
3238                                 Output_section* data_section,
3239                                 Relocatable_relocs* rr);
3240 #endif
3241
3242 #ifdef HAVE_TARGET_64_BIG
3243 template
3244 Output_section*
3245 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3246                                unsigned int reloc_shndx,
3247                                const elfcpp::Shdr<64, true>& shdr,
3248                                Output_section* data_section,
3249                                Relocatable_relocs* rr);
3250 #endif
3251
3252 #ifdef HAVE_TARGET_32_LITTLE
3253 template
3254 void
3255 Layout::layout_group<32, false>(Symbol_table* symtab,
3256                                 Sized_relobj<32, false>* object,
3257                                 unsigned int,
3258                                 const char* group_section_name,
3259                                 const char* signature,
3260                                 const elfcpp::Shdr<32, false>& shdr,
3261                                 const elfcpp::Elf_Word* contents);
3262 #endif
3263
3264 #ifdef HAVE_TARGET_32_BIG
3265 template
3266 void
3267 Layout::layout_group<32, true>(Symbol_table* symtab,
3268                                Sized_relobj<32, true>* object,
3269                                unsigned int,
3270                                const char* group_section_name,
3271                                const char* signature,
3272                                const elfcpp::Shdr<32, true>& shdr,
3273                                const elfcpp::Elf_Word* contents);
3274 #endif
3275
3276 #ifdef HAVE_TARGET_64_LITTLE
3277 template
3278 void
3279 Layout::layout_group<64, false>(Symbol_table* symtab,
3280                                 Sized_relobj<64, false>* object,
3281                                 unsigned int,
3282                                 const char* group_section_name,
3283                                 const char* signature,
3284                                 const elfcpp::Shdr<64, false>& shdr,
3285                                 const elfcpp::Elf_Word* contents);
3286 #endif
3287
3288 #ifdef HAVE_TARGET_64_BIG
3289 template
3290 void
3291 Layout::layout_group<64, true>(Symbol_table* symtab,
3292                                Sized_relobj<64, true>* object,
3293                                unsigned int,
3294                                const char* group_section_name,
3295                                const char* signature,
3296                                const elfcpp::Shdr<64, true>& shdr,
3297                                const elfcpp::Elf_Word* contents);
3298 #endif
3299
3300 #ifdef HAVE_TARGET_32_LITTLE
3301 template
3302 Output_section*
3303 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3304                                    const unsigned char* symbols,
3305                                    off_t symbols_size,
3306                                    const unsigned char* symbol_names,
3307                                    off_t symbol_names_size,
3308                                    unsigned int shndx,
3309                                    const elfcpp::Shdr<32, false>& shdr,
3310                                    unsigned int reloc_shndx,
3311                                    unsigned int reloc_type,
3312                                    off_t* off);
3313 #endif
3314
3315 #ifdef HAVE_TARGET_32_BIG
3316 template
3317 Output_section*
3318 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3319                                    const unsigned char* symbols,
3320                                    off_t symbols_size,
3321                                   const unsigned char* symbol_names,
3322                                   off_t symbol_names_size,
3323                                   unsigned int shndx,
3324                                   const elfcpp::Shdr<32, true>& shdr,
3325                                   unsigned int reloc_shndx,
3326                                   unsigned int reloc_type,
3327                                   off_t* off);
3328 #endif
3329
3330 #ifdef HAVE_TARGET_64_LITTLE
3331 template
3332 Output_section*
3333 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3334                                    const unsigned char* symbols,
3335                                    off_t symbols_size,
3336                                    const unsigned char* symbol_names,
3337                                    off_t symbol_names_size,
3338                                    unsigned int shndx,
3339                                    const elfcpp::Shdr<64, false>& shdr,
3340                                    unsigned int reloc_shndx,
3341                                    unsigned int reloc_type,
3342                                    off_t* off);
3343 #endif
3344
3345 #ifdef HAVE_TARGET_64_BIG
3346 template
3347 Output_section*
3348 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
3349                                    const unsigned char* symbols,
3350                                    off_t symbols_size,
3351                                   const unsigned char* symbol_names,
3352                                   off_t symbol_names_size,
3353                                   unsigned int shndx,
3354                                   const elfcpp::Shdr<64, true>& shdr,
3355                                   unsigned int reloc_shndx,
3356                                   unsigned int reloc_type,
3357                                   off_t* off);
3358 #endif
3359
3360 } // End namespace gold.