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