1 // layout.cc -- lay out output file sections for gold
3 // Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
6 // This file is part of gold.
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.
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.
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.
32 #include "libiberty.h"
36 #include "parameters.h"
39 #include "script-sections.h"
44 #include "compressed_output.h"
51 // Layout_task_runner methods.
53 // Lay out the sections. This is called after all the input objects
57 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
59 off_t file_size = this->layout_->finalize(this->input_objects_,
64 // Now we know the final size of the output file and we know where
65 // each piece of information goes.
66 Output_file* of = new Output_file(parameters->options().output_file_name());
67 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
68 of->set_is_temporary();
71 // Queue up the final set of tasks.
72 gold::queue_final_tasks(this->options_, this->input_objects_,
73 this->symtab_, this->layout_, workqueue, of);
78 Layout::Layout(const General_options& options, Script_options* script_options)
80 script_options_(script_options),
88 unattached_section_list_(),
89 sections_are_attached_(false),
90 special_output_list_(),
91 section_headers_(NULL),
93 symtab_section_(NULL),
95 dynsym_section_(NULL),
97 dynamic_section_(NULL),
99 eh_frame_section_(NULL),
100 eh_frame_data_(NULL),
101 added_eh_frame_data_(false),
102 eh_frame_hdr_section_(NULL),
103 build_id_note_(NULL),
105 output_file_size_(-1),
106 input_requires_executable_stack_(false),
107 input_with_gnu_stack_note_(false),
108 input_without_gnu_stack_note_(false),
109 has_static_tls_(false),
110 any_postprocessing_sections_(false)
112 // Make space for more than enough segments for a typical file.
113 // This is just for efficiency--it's OK if we wind up needing more.
114 this->segment_list_.reserve(12);
116 // We expect two unattached Output_data objects: the file header and
117 // the segment headers.
118 this->special_output_list_.reserve(2);
121 // Hash a key we use to look up an output section mapping.
124 Layout::Hash_key::operator()(const Layout::Key& k) const
126 return k.first + k.second.first + k.second.second;
129 // Return whether PREFIX is a prefix of STR.
132 is_prefix_of(const char* prefix, const char* str)
134 return strncmp(prefix, str, strlen(prefix)) == 0;
137 // Returns whether the given section is in the list of
138 // debug-sections-used-by-some-version-of-gdb. Currently,
139 // we've checked versions of gdb up to and including 6.7.1.
141 static const char* gdb_sections[] =
143 // ".debug_aranges", // not used by gdb as of 6.7.1
149 // ".debug_pubnames", // not used by gdb as of 6.7.1
155 is_gdb_debug_section(const char* str)
157 // We can do this faster: binary search or a hashtable. But why bother?
158 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
159 if (strcmp(str, gdb_sections[i]) == 0)
164 // Whether to include this section in the link.
166 template<int size, bool big_endian>
168 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
169 const elfcpp::Shdr<size, big_endian>& shdr)
171 switch (shdr.get_sh_type())
173 case elfcpp::SHT_NULL:
174 case elfcpp::SHT_SYMTAB:
175 case elfcpp::SHT_DYNSYM:
176 case elfcpp::SHT_STRTAB:
177 case elfcpp::SHT_HASH:
178 case elfcpp::SHT_DYNAMIC:
179 case elfcpp::SHT_SYMTAB_SHNDX:
182 case elfcpp::SHT_RELA:
183 case elfcpp::SHT_REL:
184 case elfcpp::SHT_GROUP:
185 // If we are emitting relocations these should be handled
187 gold_assert(!parameters->options().relocatable()
188 && !parameters->options().emit_relocs());
191 case elfcpp::SHT_PROGBITS:
192 if (parameters->options().strip_debug()
193 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
195 if (is_debug_info_section(name))
198 if (parameters->options().strip_debug_gdb()
199 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
201 // Debugging sections can only be recognized by name.
202 if (is_prefix_of(".debug", name)
203 && !is_gdb_debug_section(name))
213 // Return an output section named NAME, or NULL if there is none.
216 Layout::find_output_section(const char* name) const
218 for (Section_list::const_iterator p = this->section_list_.begin();
219 p != this->section_list_.end();
221 if (strcmp((*p)->name(), name) == 0)
226 // Return an output segment of type TYPE, with segment flags SET set
227 // and segment flags CLEAR clear. Return NULL if there is none.
230 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
231 elfcpp::Elf_Word clear) const
233 for (Segment_list::const_iterator p = this->segment_list_.begin();
234 p != this->segment_list_.end();
236 if (static_cast<elfcpp::PT>((*p)->type()) == type
237 && ((*p)->flags() & set) == set
238 && ((*p)->flags() & clear) == 0)
243 // Return the output section to use for section NAME with type TYPE
244 // and section flags FLAGS. NAME must be canonicalized in the string
245 // pool, and NAME_KEY is the key.
248 Layout::get_output_section(const char* name, Stringpool::Key name_key,
249 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
251 elfcpp::Elf_Xword lookup_flags = flags;
253 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
254 // read-write with read-only sections. Some other ELF linkers do
255 // not do this. FIXME: Perhaps there should be an option
257 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
259 const Key key(name_key, std::make_pair(type, lookup_flags));
260 const std::pair<Key, Output_section*> v(key, NULL);
261 std::pair<Section_name_map::iterator, bool> ins(
262 this->section_name_map_.insert(v));
265 return ins.first->second;
268 // This is the first time we've seen this name/type/flags
269 // combination. For compatibility with the GNU linker, we
270 // combine sections with contents and zero flags with sections
271 // with non-zero flags. This is a workaround for cases where
272 // assembler code forgets to set section flags. FIXME: Perhaps
273 // there should be an option to control this.
274 Output_section* os = NULL;
276 if (type == elfcpp::SHT_PROGBITS)
280 Output_section* same_name = this->find_output_section(name);
281 if (same_name != NULL
282 && same_name->type() == elfcpp::SHT_PROGBITS
283 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
286 else if ((flags & elfcpp::SHF_TLS) == 0)
288 elfcpp::Elf_Xword zero_flags = 0;
289 const Key zero_key(name_key, std::make_pair(type, zero_flags));
290 Section_name_map::iterator p =
291 this->section_name_map_.find(zero_key);
292 if (p != this->section_name_map_.end())
298 os = this->make_output_section(name, type, flags);
299 ins.first->second = os;
304 // Pick the output section to use for section NAME, in input file
305 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
306 // linker created section. IS_INPUT_SECTION is true if we are
307 // choosing an output section for an input section found in a input
308 // file. This will return NULL if the input section should be
312 Layout::choose_output_section(const Relobj* relobj, const char* name,
313 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
314 bool is_input_section)
316 // We should not see any input sections after we have attached
317 // sections to segments.
318 gold_assert(!is_input_section || !this->sections_are_attached_);
320 // Some flags in the input section should not be automatically
321 // copied to the output section.
322 flags &= ~ (elfcpp::SHF_INFO_LINK
323 | elfcpp::SHF_LINK_ORDER
326 | elfcpp::SHF_STRINGS);
328 if (this->script_options_->saw_sections_clause())
330 // We are using a SECTIONS clause, so the output section is
331 // chosen based only on the name.
333 Script_sections* ss = this->script_options_->script_sections();
334 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
335 Output_section** output_section_slot;
336 name = ss->output_section_name(file_name, name, &output_section_slot);
339 // The SECTIONS clause says to discard this input section.
343 // If this is an orphan section--one not mentioned in the linker
344 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
345 // default processing below.
347 if (output_section_slot != NULL)
349 if (*output_section_slot != NULL)
350 return *output_section_slot;
352 // We don't put sections found in the linker script into
353 // SECTION_NAME_MAP_. That keeps us from getting confused
354 // if an orphan section is mapped to a section with the same
355 // name as one in the linker script.
357 name = this->namepool_.add(name, false, NULL);
359 Output_section* os = this->make_output_section(name, type, flags);
360 os->set_found_in_sections_clause();
361 *output_section_slot = os;
366 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
368 // Turn NAME from the name of the input section into the name of the
371 size_t len = strlen(name);
372 if (is_input_section && !parameters->options().relocatable())
373 name = Layout::output_section_name(name, &len);
375 Stringpool::Key name_key;
376 name = this->namepool_.add_with_length(name, len, true, &name_key);
378 // Find or make the output section. The output section is selected
379 // based on the section name, type, and flags.
380 return this->get_output_section(name, name_key, type, flags);
383 // Return the output section to use for input section SHNDX, with name
384 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
385 // index of a relocation section which applies to this section, or 0
386 // if none, or -1U if more than one. RELOC_TYPE is the type of the
387 // relocation section if there is one. Set *OFF to the offset of this
388 // input section without the output section. Return NULL if the
389 // section should be discarded. Set *OFF to -1 if the section
390 // contents should not be written directly to the output file, but
391 // will instead receive special handling.
393 template<int size, bool big_endian>
395 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
396 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
397 unsigned int reloc_shndx, unsigned int, off_t* off)
399 if (!this->include_section(object, name, shdr))
404 // In a relocatable link a grouped section must not be combined with
405 // any other sections.
406 if (parameters->options().relocatable()
407 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
409 name = this->namepool_.add(name, true, NULL);
410 os = this->make_output_section(name, shdr.get_sh_type(),
411 shdr.get_sh_flags());
415 os = this->choose_output_section(object, name, shdr.get_sh_type(),
416 shdr.get_sh_flags(), true);
421 // By default the GNU linker sorts input sections whose names match
422 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
423 // are sorted by name. This is used to implement constructor
424 // priority ordering. We are compatible.
425 if (!this->script_options_->saw_sections_clause()
426 && (is_prefix_of(".ctors.", name)
427 || is_prefix_of(".dtors.", name)
428 || is_prefix_of(".init_array.", name)
429 || is_prefix_of(".fini_array.", name)))
430 os->set_must_sort_attached_input_sections();
432 // FIXME: Handle SHF_LINK_ORDER somewhere.
434 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
435 this->script_options_->saw_sections_clause());
440 // Handle a relocation section when doing a relocatable link.
442 template<int size, bool big_endian>
444 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
446 const elfcpp::Shdr<size, big_endian>& shdr,
447 Output_section* data_section,
448 Relocatable_relocs* rr)
450 gold_assert(parameters->options().relocatable()
451 || parameters->options().emit_relocs());
453 int sh_type = shdr.get_sh_type();
456 if (sh_type == elfcpp::SHT_REL)
458 else if (sh_type == elfcpp::SHT_RELA)
462 name += data_section->name();
464 Output_section* os = this->choose_output_section(object, name.c_str(),
469 os->set_should_link_to_symtab();
470 os->set_info_section(data_section);
472 Output_section_data* posd;
473 if (sh_type == elfcpp::SHT_REL)
475 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
476 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
480 else if (sh_type == elfcpp::SHT_RELA)
482 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
483 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
490 os->add_output_section_data(posd);
491 rr->set_output_data(posd);
496 // Handle a group section when doing a relocatable link.
498 template<int size, bool big_endian>
500 Layout::layout_group(Symbol_table* symtab,
501 Sized_relobj<size, big_endian>* object,
503 const char* group_section_name,
504 const char* signature,
505 const elfcpp::Shdr<size, big_endian>& shdr,
506 const elfcpp::Elf_Word* contents)
508 gold_assert(parameters->options().relocatable());
509 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
510 group_section_name = this->namepool_.add(group_section_name, true, NULL);
511 Output_section* os = this->make_output_section(group_section_name,
513 shdr.get_sh_flags());
515 // We need to find a symbol with the signature in the symbol table.
516 // If we don't find one now, we need to look again later.
517 Symbol* sym = symtab->lookup(signature, NULL);
519 os->set_info_symndx(sym);
522 // We will wind up using a symbol whose name is the signature.
523 // So just put the signature in the symbol name pool to save it.
524 signature = symtab->canonicalize_name(signature);
525 this->group_signatures_.push_back(Group_signature(os, signature));
528 os->set_should_link_to_symtab();
531 section_size_type entry_count =
532 convert_to_section_size_type(shdr.get_sh_size() / 4);
533 Output_section_data* posd =
534 new Output_data_group<size, big_endian>(object, entry_count, contents);
535 os->add_output_section_data(posd);
538 // Special GNU handling of sections name .eh_frame. They will
539 // normally hold exception frame data as defined by the C++ ABI
540 // (http://codesourcery.com/cxx-abi/).
542 template<int size, bool big_endian>
544 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
545 const unsigned char* symbols,
547 const unsigned char* symbol_names,
548 off_t symbol_names_size,
550 const elfcpp::Shdr<size, big_endian>& shdr,
551 unsigned int reloc_shndx, unsigned int reloc_type,
554 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
555 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
557 const char* const name = ".eh_frame";
558 Output_section* os = this->choose_output_section(object,
560 elfcpp::SHT_PROGBITS,
566 if (this->eh_frame_section_ == NULL)
568 this->eh_frame_section_ = os;
569 this->eh_frame_data_ = new Eh_frame();
571 if (this->options_.eh_frame_hdr())
573 Output_section* hdr_os =
574 this->choose_output_section(NULL,
576 elfcpp::SHT_PROGBITS,
582 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
583 this->eh_frame_data_);
584 hdr_os->add_output_section_data(hdr_posd);
586 hdr_os->set_after_input_sections();
588 if (!this->script_options_->saw_phdrs_clause())
590 Output_segment* hdr_oseg;
591 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
593 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
596 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
601 gold_assert(this->eh_frame_section_ == os);
603 if (this->eh_frame_data_->add_ehframe_input_section(object,
612 os->update_flags_for_input_section(shdr.get_sh_flags());
614 // We found a .eh_frame section we are going to optimize, so now
615 // we can add the set of optimized sections to the output
616 // section. We need to postpone adding this until we've found a
617 // section we can optimize so that the .eh_frame section in
618 // crtbegin.o winds up at the start of the output section.
619 if (!this->added_eh_frame_data_)
621 os->add_output_section_data(this->eh_frame_data_);
622 this->added_eh_frame_data_ = true;
628 // We couldn't handle this .eh_frame section for some reason.
629 // Add it as a normal section.
630 bool saw_sections_clause = this->script_options_->saw_sections_clause();
631 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
632 saw_sections_clause);
638 // Add POSD to an output section using NAME, TYPE, and FLAGS.
641 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
642 elfcpp::Elf_Xword flags,
643 Output_section_data* posd)
645 Output_section* os = this->choose_output_section(NULL, name, type, flags,
648 os->add_output_section_data(posd);
651 // Map section flags to segment flags.
654 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
656 elfcpp::Elf_Word ret = elfcpp::PF_R;
657 if ((flags & elfcpp::SHF_WRITE) != 0)
659 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
664 // Sometimes we compress sections. This is typically done for
665 // sections that are not part of normal program execution (such as
666 // .debug_* sections), and where the readers of these sections know
667 // how to deal with compressed sections. (To make it easier for them,
668 // we will rename the ouput section in such cases from .foo to
669 // .foo.zlib.nnnn, where nnnn is the uncompressed size.) This routine
670 // doesn't say for certain whether we'll compress -- it depends on
671 // commandline options as well -- just whether this section is a
672 // candidate for compression.
675 is_compressible_debug_section(const char* secname)
677 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
680 // Make a new Output_section, and attach it to segments as
684 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
685 elfcpp::Elf_Xword flags)
688 if ((flags & elfcpp::SHF_ALLOC) == 0
689 && strcmp(this->options_.compress_debug_sections(), "none") != 0
690 && is_compressible_debug_section(name))
691 os = new Output_compressed_section(&this->options_, name, type, flags);
693 os = new Output_section(name, type, flags);
695 this->section_list_.push_back(os);
697 // The GNU linker by default sorts some sections by priority, so we
698 // do the same. We need to know that this might happen before we
699 // attach any input sections.
700 if (!this->script_options_->saw_sections_clause()
701 && (strcmp(name, ".ctors") == 0
702 || strcmp(name, ".dtors") == 0
703 || strcmp(name, ".init_array") == 0
704 || strcmp(name, ".fini_array") == 0))
705 os->set_may_sort_attached_input_sections();
707 // If we have already attached the sections to segments, then we
708 // need to attach this one now. This happens for sections created
709 // directly by the linker.
710 if (this->sections_are_attached_)
711 this->attach_section_to_segment(os);
716 // Attach output sections to segments. This is called after we have
717 // seen all the input sections.
720 Layout::attach_sections_to_segments()
722 for (Section_list::iterator p = this->section_list_.begin();
723 p != this->section_list_.end();
725 this->attach_section_to_segment(*p);
727 this->sections_are_attached_ = true;
730 // Attach an output section to a segment.
733 Layout::attach_section_to_segment(Output_section* os)
735 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
736 this->unattached_section_list_.push_back(os);
738 this->attach_allocated_section_to_segment(os);
741 // Attach an allocated output section to a segment.
744 Layout::attach_allocated_section_to_segment(Output_section* os)
746 elfcpp::Elf_Xword flags = os->flags();
747 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
749 if (parameters->options().relocatable())
752 // If we have a SECTIONS clause, we can't handle the attachment to
753 // segments until after we've seen all the sections.
754 if (this->script_options_->saw_sections_clause())
757 gold_assert(!this->script_options_->saw_phdrs_clause());
759 // This output section goes into a PT_LOAD segment.
761 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
763 // In general the only thing we really care about for PT_LOAD
764 // segments is whether or not they are writable, so that is how we
765 // search for them. People who need segments sorted on some other
766 // basis will have to use a linker script.
768 Segment_list::const_iterator p;
769 for (p = this->segment_list_.begin();
770 p != this->segment_list_.end();
773 if ((*p)->type() == elfcpp::PT_LOAD
774 && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
776 // If -Tbss was specified, we need to separate the data
778 if (this->options_.user_set_Tbss())
780 if ((os->type() == elfcpp::SHT_NOBITS)
781 == (*p)->has_any_data_sections())
785 (*p)->add_output_section(os, seg_flags);
790 if (p == this->segment_list_.end())
792 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
794 oseg->add_output_section(os, seg_flags);
797 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
799 if (os->type() == elfcpp::SHT_NOTE)
801 // See if we already have an equivalent PT_NOTE segment.
802 for (p = this->segment_list_.begin();
803 p != segment_list_.end();
806 if ((*p)->type() == elfcpp::PT_NOTE
807 && (((*p)->flags() & elfcpp::PF_W)
808 == (seg_flags & elfcpp::PF_W)))
810 (*p)->add_output_section(os, seg_flags);
815 if (p == this->segment_list_.end())
817 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
819 oseg->add_output_section(os, seg_flags);
823 // If we see a loadable SHF_TLS section, we create a PT_TLS
824 // segment. There can only be one such segment.
825 if ((flags & elfcpp::SHF_TLS) != 0)
827 if (this->tls_segment_ == NULL)
828 this->tls_segment_ = this->make_output_segment(elfcpp::PT_TLS,
830 this->tls_segment_->add_output_section(os, seg_flags);
834 // Make an output section for a script.
837 Layout::make_output_section_for_script(const char* name)
839 name = this->namepool_.add(name, false, NULL);
840 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
842 os->set_found_in_sections_clause();
846 // Return the number of segments we expect to see.
849 Layout::expected_segment_count() const
851 size_t ret = this->segment_list_.size();
853 // If we didn't see a SECTIONS clause in a linker script, we should
854 // already have the complete list of segments. Otherwise we ask the
855 // SECTIONS clause how many segments it expects, and add in the ones
856 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
858 if (!this->script_options_->saw_sections_clause())
862 const Script_sections* ss = this->script_options_->script_sections();
863 return ret + ss->expected_segment_count(this);
867 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
868 // is whether we saw a .note.GNU-stack section in the object file.
869 // GNU_STACK_FLAGS is the section flags. The flags give the
870 // protection required for stack memory. We record this in an
871 // executable as a PT_GNU_STACK segment. If an object file does not
872 // have a .note.GNU-stack segment, we must assume that it is an old
873 // object. On some targets that will force an executable stack.
876 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
879 this->input_without_gnu_stack_note_ = true;
882 this->input_with_gnu_stack_note_ = true;
883 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
884 this->input_requires_executable_stack_ = true;
888 // Create the dynamic sections which are needed before we read the
892 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
894 if (parameters->doing_static_link())
897 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
900 | elfcpp::SHF_WRITE),
903 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
904 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
905 elfcpp::STV_HIDDEN, 0, false, false);
907 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
909 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
912 // For each output section whose name can be represented as C symbol,
913 // define __start and __stop symbols for the section. This is a GNU
917 Layout::define_section_symbols(Symbol_table* symtab)
919 for (Section_list::const_iterator p = this->section_list_.begin();
920 p != this->section_list_.end();
923 const char* const name = (*p)->name();
924 if (name[strspn(name,
926 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
927 "abcdefghijklmnopqrstuvwxyz"
931 const std::string name_string(name);
932 const std::string start_name("__start_" + name_string);
933 const std::string stop_name("__stop_" + name_string);
935 symtab->define_in_output_data(start_name.c_str(),
944 false, // offset_is_from_end
945 true); // only_if_ref
947 symtab->define_in_output_data(stop_name.c_str(),
956 true, // offset_is_from_end
957 true); // only_if_ref
962 // Define symbols for group signatures.
965 Layout::define_group_signatures(Symbol_table* symtab)
967 for (Group_signatures::iterator p = this->group_signatures_.begin();
968 p != this->group_signatures_.end();
971 Symbol* sym = symtab->lookup(p->signature, NULL);
973 p->section->set_info_symndx(sym);
976 // Force the name of the group section to the group
977 // signature, and use the group's section symbol as the
979 if (strcmp(p->section->name(), p->signature) != 0)
981 const char* name = this->namepool_.add(p->signature,
983 p->section->set_name(name);
985 p->section->set_needs_symtab_index();
986 p->section->set_info_section_symndx(p->section);
990 this->group_signatures_.clear();
993 // Find the first read-only PT_LOAD segment, creating one if
997 Layout::find_first_load_seg()
999 for (Segment_list::const_iterator p = this->segment_list_.begin();
1000 p != this->segment_list_.end();
1003 if ((*p)->type() == elfcpp::PT_LOAD
1004 && ((*p)->flags() & elfcpp::PF_R) != 0
1005 && ((*p)->flags() & elfcpp::PF_W) == 0)
1009 gold_assert(!this->script_options_->saw_phdrs_clause());
1011 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1016 // Finalize the layout. When this is called, we have created all the
1017 // output sections and all the output segments which are based on
1018 // input sections. We have several things to do, and we have to do
1019 // them in the right order, so that we get the right results correctly
1022 // 1) Finalize the list of output segments and create the segment
1025 // 2) Finalize the dynamic symbol table and associated sections.
1027 // 3) Determine the final file offset of all the output segments.
1029 // 4) Determine the final file offset of all the SHF_ALLOC output
1032 // 5) Create the symbol table sections and the section name table
1035 // 6) Finalize the symbol table: set symbol values to their final
1036 // value and make a final determination of which symbols are going
1037 // into the output symbol table.
1039 // 7) Create the section table header.
1041 // 8) Determine the final file offset of all the output sections which
1042 // are not SHF_ALLOC, including the section table header.
1044 // 9) Finalize the ELF file header.
1046 // This function returns the size of the output file.
1049 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1050 Target* target, const Task* task)
1052 target->finalize_sections(this);
1054 this->count_local_symbols(task, input_objects);
1056 this->create_gold_note();
1057 this->create_executable_stack_info(target);
1058 this->create_build_id();
1060 Output_segment* phdr_seg = NULL;
1061 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1063 // There was a dynamic object in the link. We need to create
1064 // some information for the dynamic linker.
1066 // Create the PT_PHDR segment which will hold the program
1068 if (!this->script_options_->saw_phdrs_clause())
1069 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1071 // Create the dynamic symbol table, including the hash table.
1072 Output_section* dynstr;
1073 std::vector<Symbol*> dynamic_symbols;
1074 unsigned int local_dynamic_count;
1075 Versions versions(*this->script_options()->version_script_info(),
1077 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1078 &local_dynamic_count, &dynamic_symbols,
1081 // Create the .interp section to hold the name of the
1082 // interpreter, and put it in a PT_INTERP segment.
1083 if (!parameters->options().shared())
1084 this->create_interp(target);
1086 // Finish the .dynamic section to hold the dynamic data, and put
1087 // it in a PT_DYNAMIC segment.
1088 this->finish_dynamic_section(input_objects, symtab);
1090 // We should have added everything we need to the dynamic string
1092 this->dynpool_.set_string_offsets();
1094 // Create the version sections. We can't do this until the
1095 // dynamic string table is complete.
1096 this->create_version_sections(&versions, symtab, local_dynamic_count,
1097 dynamic_symbols, dynstr);
1100 // If there is a SECTIONS clause, put all the input sections into
1101 // the required order.
1102 Output_segment* load_seg;
1103 if (this->script_options_->saw_sections_clause())
1104 load_seg = this->set_section_addresses_from_script(symtab);
1105 else if (parameters->options().relocatable())
1108 load_seg = this->find_first_load_seg();
1110 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
1113 gold_assert(phdr_seg == NULL || load_seg != NULL);
1115 // Lay out the segment headers.
1116 Output_segment_headers* segment_headers;
1117 if (parameters->options().relocatable())
1118 segment_headers = NULL;
1121 segment_headers = new Output_segment_headers(this->segment_list_);
1122 if (load_seg != NULL)
1123 load_seg->add_initial_output_data(segment_headers);
1124 if (phdr_seg != NULL)
1125 phdr_seg->add_initial_output_data(segment_headers);
1128 // Lay out the file header.
1129 Output_file_header* file_header;
1130 file_header = new Output_file_header(target, symtab, segment_headers,
1131 this->options_.entry());
1132 if (load_seg != NULL)
1133 load_seg->add_initial_output_data(file_header);
1135 this->special_output_list_.push_back(file_header);
1136 if (segment_headers != NULL)
1137 this->special_output_list_.push_back(segment_headers);
1139 if (this->script_options_->saw_phdrs_clause()
1140 && !parameters->options().relocatable())
1142 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1143 // clause in a linker script.
1144 Script_sections* ss = this->script_options_->script_sections();
1145 ss->put_headers_in_phdrs(file_header, segment_headers);
1148 // We set the output section indexes in set_segment_offsets and
1149 // set_section_indexes.
1150 unsigned int shndx = 1;
1152 // Set the file offsets of all the segments, and all the sections
1155 if (!parameters->options().relocatable())
1156 off = this->set_segment_offsets(target, load_seg, &shndx);
1158 off = this->set_relocatable_section_offsets(file_header, &shndx);
1160 // Set the file offsets of all the non-data sections we've seen so
1161 // far which don't have to wait for the input sections. We need
1162 // this in order to finalize local symbols in non-allocated
1164 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1166 // Set the section indexes of all unallocated sections seen so far,
1167 // in case any of them are somehow referenced by a symbol.
1168 shndx = this->set_section_indexes(shndx);
1170 // Create the symbol table sections.
1171 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1172 if (!parameters->doing_static_link())
1173 this->assign_local_dynsym_offsets(input_objects);
1175 // Process any symbol assignments from a linker script. This must
1176 // be called after the symbol table has been finalized.
1177 this->script_options_->finalize_symbols(symtab, this);
1179 // Create the .shstrtab section.
1180 Output_section* shstrtab_section = this->create_shstrtab();
1182 // Set the file offsets of the rest of the non-data sections which
1183 // don't have to wait for the input sections.
1184 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1186 // Now that all sections have been created, set the section indexes
1187 // for any sections which haven't been done yet.
1188 shndx = this->set_section_indexes(shndx);
1190 // Create the section table header.
1191 this->create_shdrs(shstrtab_section, &off);
1193 // If there are no sections which require postprocessing, we can
1194 // handle the section names now, and avoid a resize later.
1195 if (!this->any_postprocessing_sections_)
1196 off = this->set_section_offsets(off,
1197 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1199 file_header->set_section_info(this->section_headers_, shstrtab_section);
1201 // Now we know exactly where everything goes in the output file
1202 // (except for non-allocated sections which require postprocessing).
1203 Output_data::layout_complete();
1205 this->output_file_size_ = off;
1210 // Create a note header following the format defined in the ELF ABI.
1211 // NAME is the name, NOTE_TYPE is the type, DESCSZ is the size of the
1212 // descriptor. ALLOCATE is true if the section should be allocated in
1213 // memory. This returns the new note section. It sets
1214 // *TRAILING_PADDING to the number of trailing zero bytes required.
1217 Layout::create_note(const char* name, int note_type, size_t descsz,
1218 bool allocate, size_t* trailing_padding)
1220 // Authorities all agree that the values in a .note field should
1221 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1222 // they differ on what the alignment is for 64-bit binaries.
1223 // The GABI says unambiguously they take 8-byte alignment:
1224 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1225 // Other documentation says alignment should always be 4 bytes:
1226 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1227 // GNU ld and GNU readelf both support the latter (at least as of
1228 // version 2.16.91), and glibc always generates the latter for
1229 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1231 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1232 const int size = parameters->target().get_size();
1234 const int size = 32;
1237 // The contents of the .note section.
1238 size_t namesz = strlen(name) + 1;
1239 size_t aligned_namesz = align_address(namesz, size / 8);
1240 size_t aligned_descsz = align_address(descsz, size / 8);
1242 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1244 unsigned char* buffer = new unsigned char[notehdrsz];
1245 memset(buffer, 0, notehdrsz);
1247 bool is_big_endian = parameters->target().is_big_endian();
1253 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1254 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1255 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1259 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1260 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1261 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1264 else if (size == 64)
1268 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1269 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1270 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1274 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1275 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1276 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1282 memcpy(buffer + 3 * (size / 8), name, namesz);
1284 const char* note_name = this->namepool_.add(".note", false, NULL);
1285 elfcpp::Elf_Xword flags = 0;
1287 flags = elfcpp::SHF_ALLOC;
1288 Output_section* os = this->make_output_section(note_name,
1291 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1293 os->add_output_section_data(posd);
1295 *trailing_padding = aligned_descsz - descsz;
1300 // For an executable or shared library, create a note to record the
1301 // version of gold used to create the binary.
1304 Layout::create_gold_note()
1306 if (parameters->options().relocatable())
1309 std::string desc = std::string("gold ") + gold::get_version_string();
1311 size_t trailing_padding;
1312 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1313 desc.size(), false, &trailing_padding);
1315 Output_section_data* posd = new Output_data_const(desc, 4);
1316 os->add_output_section_data(posd);
1318 if (trailing_padding > 0)
1320 posd = new Output_data_fixed_space(trailing_padding, 0);
1321 os->add_output_section_data(posd);
1325 // Record whether the stack should be executable. This can be set
1326 // from the command line using the -z execstack or -z noexecstack
1327 // options. Otherwise, if any input file has a .note.GNU-stack
1328 // section with the SHF_EXECINSTR flag set, the stack should be
1329 // executable. Otherwise, if at least one input file a
1330 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1331 // section, we use the target default for whether the stack should be
1332 // executable. Otherwise, we don't generate a stack note. When
1333 // generating a object file, we create a .note.GNU-stack section with
1334 // the appropriate marking. When generating an executable or shared
1335 // library, we create a PT_GNU_STACK segment.
1338 Layout::create_executable_stack_info(const Target* target)
1340 bool is_stack_executable;
1341 if (this->options_.is_execstack_set())
1342 is_stack_executable = this->options_.is_stack_executable();
1343 else if (!this->input_with_gnu_stack_note_)
1347 if (this->input_requires_executable_stack_)
1348 is_stack_executable = true;
1349 else if (this->input_without_gnu_stack_note_)
1350 is_stack_executable = target->is_default_stack_executable();
1352 is_stack_executable = false;
1355 if (parameters->options().relocatable())
1357 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1358 elfcpp::Elf_Xword flags = 0;
1359 if (is_stack_executable)
1360 flags |= elfcpp::SHF_EXECINSTR;
1361 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1365 if (this->script_options_->saw_phdrs_clause())
1367 int flags = elfcpp::PF_R | elfcpp::PF_W;
1368 if (is_stack_executable)
1369 flags |= elfcpp::PF_X;
1370 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1374 // If --build-id was used, set up the build ID note.
1377 Layout::create_build_id()
1379 if (!parameters->options().user_set_build_id())
1382 const char* style = parameters->options().build_id();
1383 if (strcmp(style, "none") == 0)
1386 // Set DESCSZ to the size of the note descriptor. When possible,
1387 // set DESC to the note descriptor contents.
1390 if (strcmp(style, "md5") == 0)
1392 else if (strcmp(style, "sha1") == 0)
1394 else if (strcmp(style, "uuid") == 0)
1396 const size_t uuidsz = 128 / 8;
1398 char buffer[uuidsz];
1399 memset(buffer, 0, uuidsz);
1401 int descriptor = ::open("/dev/urandom", O_RDONLY);
1403 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1407 ssize_t got = ::read(descriptor, buffer, uuidsz);
1408 ::close(descriptor);
1410 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1411 else if (static_cast<size_t>(got) != uuidsz)
1412 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1416 desc.assign(buffer, uuidsz);
1419 else if (strncmp(style, "0x", 2) == 0)
1422 const char* p = style + 2;
1425 if (hex_p(p[0]) && hex_p(p[1]))
1427 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1431 else if (*p == '-' || *p == ':')
1434 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1437 descsz = desc.size();
1440 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1443 size_t trailing_padding;
1444 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1445 descsz, true, &trailing_padding);
1449 // We know the value already, so we fill it in now.
1450 gold_assert(desc.size() == descsz);
1452 Output_section_data* posd = new Output_data_const(desc, 4);
1453 os->add_output_section_data(posd);
1455 if (trailing_padding != 0)
1457 posd = new Output_data_fixed_space(trailing_padding, 0);
1458 os->add_output_section_data(posd);
1463 // We need to compute a checksum after we have completed the
1465 gold_assert(trailing_padding == 0);
1466 this->build_id_note_ = new Output_data_fixed_space(descsz, 4);
1467 os->add_output_section_data(this->build_id_note_);
1468 os->set_after_input_sections();
1472 // Return whether SEG1 should be before SEG2 in the output file. This
1473 // is based entirely on the segment type and flags. When this is
1474 // called the segment addresses has normally not yet been set.
1477 Layout::segment_precedes(const Output_segment* seg1,
1478 const Output_segment* seg2)
1480 elfcpp::Elf_Word type1 = seg1->type();
1481 elfcpp::Elf_Word type2 = seg2->type();
1483 // The single PT_PHDR segment is required to precede any loadable
1484 // segment. We simply make it always first.
1485 if (type1 == elfcpp::PT_PHDR)
1487 gold_assert(type2 != elfcpp::PT_PHDR);
1490 if (type2 == elfcpp::PT_PHDR)
1493 // The single PT_INTERP segment is required to precede any loadable
1494 // segment. We simply make it always second.
1495 if (type1 == elfcpp::PT_INTERP)
1497 gold_assert(type2 != elfcpp::PT_INTERP);
1500 if (type2 == elfcpp::PT_INTERP)
1503 // We then put PT_LOAD segments before any other segments.
1504 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1506 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1509 // We put the PT_TLS segment last, because that is where the dynamic
1510 // linker expects to find it (this is just for efficiency; other
1511 // positions would also work correctly).
1512 if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
1514 if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
1517 const elfcpp::Elf_Word flags1 = seg1->flags();
1518 const elfcpp::Elf_Word flags2 = seg2->flags();
1520 // The order of non-PT_LOAD segments is unimportant. We simply sort
1521 // by the numeric segment type and flags values. There should not
1522 // be more than one segment with the same type and flags.
1523 if (type1 != elfcpp::PT_LOAD)
1526 return type1 < type2;
1527 gold_assert(flags1 != flags2);
1528 return flags1 < flags2;
1531 // If the addresses are set already, sort by load address.
1532 if (seg1->are_addresses_set())
1534 if (!seg2->are_addresses_set())
1537 unsigned int section_count1 = seg1->output_section_count();
1538 unsigned int section_count2 = seg2->output_section_count();
1539 if (section_count1 == 0 && section_count2 > 0)
1541 if (section_count1 > 0 && section_count2 == 0)
1544 uint64_t paddr1 = seg1->first_section_load_address();
1545 uint64_t paddr2 = seg2->first_section_load_address();
1546 if (paddr1 != paddr2)
1547 return paddr1 < paddr2;
1549 else if (seg2->are_addresses_set())
1552 // We sort PT_LOAD segments based on the flags. Readonly segments
1553 // come before writable segments. Then writable segments with data
1554 // come before writable segments without data. Then executable
1555 // segments come before non-executable segments. Then the unlikely
1556 // case of a non-readable segment comes before the normal case of a
1557 // readable segment. If there are multiple segments with the same
1558 // type and flags, we require that the address be set, and we sort
1559 // by virtual address and then physical address.
1560 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1561 return (flags1 & elfcpp::PF_W) == 0;
1562 if ((flags1 & elfcpp::PF_W) != 0
1563 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
1564 return seg1->has_any_data_sections();
1565 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1566 return (flags1 & elfcpp::PF_X) != 0;
1567 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1568 return (flags1 & elfcpp::PF_R) == 0;
1570 // We shouldn't get here--we shouldn't create segments which we
1571 // can't distinguish.
1575 // Set the file offsets of all the segments, and all the sections they
1576 // contain. They have all been created. LOAD_SEG must be be laid out
1577 // first. Return the offset of the data to follow.
1580 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1581 unsigned int *pshndx)
1583 // Sort them into the final order.
1584 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1585 Layout::Compare_segments());
1587 // Find the PT_LOAD segments, and set their addresses and offsets
1588 // and their section's addresses and offsets.
1590 if (this->options_.user_set_Ttext())
1591 addr = this->options_.Ttext();
1592 else if (parameters->options().shared())
1595 addr = target->default_text_segment_address();
1598 // If LOAD_SEG is NULL, then the file header and segment headers
1599 // will not be loadable. But they still need to be at offset 0 in
1600 // the file. Set their offsets now.
1601 if (load_seg == NULL)
1603 for (Data_list::iterator p = this->special_output_list_.begin();
1604 p != this->special_output_list_.end();
1607 off = align_address(off, (*p)->addralign());
1608 (*p)->set_address_and_file_offset(0, off);
1609 off += (*p)->data_size();
1613 bool was_readonly = false;
1614 for (Segment_list::iterator p = this->segment_list_.begin();
1615 p != this->segment_list_.end();
1618 if ((*p)->type() == elfcpp::PT_LOAD)
1620 if (load_seg != NULL && load_seg != *p)
1624 bool are_addresses_set = (*p)->are_addresses_set();
1625 if (are_addresses_set)
1627 // When it comes to setting file offsets, we care about
1628 // the physical address.
1629 addr = (*p)->paddr();
1631 else if (this->options_.user_set_Tdata()
1632 && ((*p)->flags() & elfcpp::PF_W) != 0
1633 && (!this->options_.user_set_Tbss()
1634 || (*p)->has_any_data_sections()))
1636 addr = this->options_.Tdata();
1637 are_addresses_set = true;
1639 else if (this->options_.user_set_Tbss()
1640 && ((*p)->flags() & elfcpp::PF_W) != 0
1641 && !(*p)->has_any_data_sections())
1643 addr = this->options_.Tbss();
1644 are_addresses_set = true;
1647 uint64_t orig_addr = addr;
1648 uint64_t orig_off = off;
1650 uint64_t aligned_addr = 0;
1651 uint64_t abi_pagesize = target->abi_pagesize();
1653 // FIXME: This should depend on the -n and -N options.
1654 (*p)->set_minimum_p_align(target->common_pagesize());
1656 if (are_addresses_set)
1658 // Adjust the file offset to the same address modulo the
1660 uint64_t unsigned_off = off;
1661 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1662 | (addr & (abi_pagesize - 1)));
1663 if (aligned_off < unsigned_off)
1664 aligned_off += abi_pagesize;
1669 // If the last segment was readonly, and this one is
1670 // not, then skip the address forward one page,
1671 // maintaining the same position within the page. This
1672 // lets us store both segments overlapping on a single
1673 // page in the file, but the loader will put them on
1674 // different pages in memory.
1676 addr = align_address(addr, (*p)->maximum_alignment());
1677 aligned_addr = addr;
1679 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1681 if ((addr & (abi_pagesize - 1)) != 0)
1682 addr = addr + abi_pagesize;
1685 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1688 unsigned int shndx_hold = *pshndx;
1689 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
1692 // Now that we know the size of this segment, we may be able
1693 // to save a page in memory, at the cost of wasting some
1694 // file space, by instead aligning to the start of a new
1695 // page. Here we use the real machine page size rather than
1696 // the ABI mandated page size.
1698 if (!are_addresses_set && aligned_addr != addr)
1700 uint64_t common_pagesize = target->common_pagesize();
1701 uint64_t first_off = (common_pagesize
1703 & (common_pagesize - 1)));
1704 uint64_t last_off = new_addr & (common_pagesize - 1);
1707 && ((aligned_addr & ~ (common_pagesize - 1))
1708 != (new_addr & ~ (common_pagesize - 1)))
1709 && first_off + last_off <= common_pagesize)
1711 *pshndx = shndx_hold;
1712 addr = align_address(aligned_addr, common_pagesize);
1713 addr = align_address(addr, (*p)->maximum_alignment());
1714 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1715 new_addr = (*p)->set_section_addresses(this, true, addr,
1722 if (((*p)->flags() & elfcpp::PF_W) == 0)
1723 was_readonly = true;
1727 // Handle the non-PT_LOAD segments, setting their offsets from their
1728 // section's offsets.
1729 for (Segment_list::iterator p = this->segment_list_.begin();
1730 p != this->segment_list_.end();
1733 if ((*p)->type() != elfcpp::PT_LOAD)
1737 // Set the TLS offsets for each section in the PT_TLS segment.
1738 if (this->tls_segment_ != NULL)
1739 this->tls_segment_->set_tls_offsets();
1744 // Set the offsets of all the allocated sections when doing a
1745 // relocatable link. This does the same jobs as set_segment_offsets,
1746 // only for a relocatable link.
1749 Layout::set_relocatable_section_offsets(Output_data* file_header,
1750 unsigned int *pshndx)
1754 file_header->set_address_and_file_offset(0, 0);
1755 off += file_header->data_size();
1757 for (Section_list::iterator p = this->section_list_.begin();
1758 p != this->section_list_.end();
1761 // We skip unallocated sections here, except that group sections
1762 // have to come first.
1763 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
1764 && (*p)->type() != elfcpp::SHT_GROUP)
1767 off = align_address(off, (*p)->addralign());
1769 // The linker script might have set the address.
1770 if (!(*p)->is_address_valid())
1771 (*p)->set_address(0);
1772 (*p)->set_file_offset(off);
1773 (*p)->finalize_data_size();
1774 off += (*p)->data_size();
1776 (*p)->set_out_shndx(*pshndx);
1783 // Set the file offset of all the sections not associated with a
1787 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1789 for (Section_list::iterator p = this->unattached_section_list_.begin();
1790 p != this->unattached_section_list_.end();
1793 // The symtab section is handled in create_symtab_sections.
1794 if (*p == this->symtab_section_)
1797 // If we've already set the data size, don't set it again.
1798 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1801 if (pass == BEFORE_INPUT_SECTIONS_PASS
1802 && (*p)->requires_postprocessing())
1804 (*p)->create_postprocessing_buffer();
1805 this->any_postprocessing_sections_ = true;
1808 if (pass == BEFORE_INPUT_SECTIONS_PASS
1809 && (*p)->after_input_sections())
1811 else if (pass == POSTPROCESSING_SECTIONS_PASS
1812 && (!(*p)->after_input_sections()
1813 || (*p)->type() == elfcpp::SHT_STRTAB))
1815 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1816 && (!(*p)->after_input_sections()
1817 || (*p)->type() != elfcpp::SHT_STRTAB))
1820 off = align_address(off, (*p)->addralign());
1821 (*p)->set_file_offset(off);
1822 (*p)->finalize_data_size();
1823 off += (*p)->data_size();
1825 // At this point the name must be set.
1826 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1827 this->namepool_.add((*p)->name(), false, NULL);
1832 // Set the section indexes of all the sections not associated with a
1836 Layout::set_section_indexes(unsigned int shndx)
1838 for (Section_list::iterator p = this->unattached_section_list_.begin();
1839 p != this->unattached_section_list_.end();
1842 if (!(*p)->has_out_shndx())
1844 (*p)->set_out_shndx(shndx);
1851 // Set the section addresses according to the linker script. This is
1852 // only called when we see a SECTIONS clause. This returns the
1853 // program segment which should hold the file header and segment
1854 // headers, if any. It will return NULL if they should not be in a
1858 Layout::set_section_addresses_from_script(Symbol_table* symtab)
1860 Script_sections* ss = this->script_options_->script_sections();
1861 gold_assert(ss->saw_sections_clause());
1863 // Place each orphaned output section in the script.
1864 for (Section_list::iterator p = this->section_list_.begin();
1865 p != this->section_list_.end();
1868 if (!(*p)->found_in_sections_clause())
1869 ss->place_orphan(*p);
1872 return this->script_options_->set_section_addresses(symtab, this);
1875 // Count the local symbols in the regular symbol table and the dynamic
1876 // symbol table, and build the respective string pools.
1879 Layout::count_local_symbols(const Task* task,
1880 const Input_objects* input_objects)
1882 // First, figure out an upper bound on the number of symbols we'll
1883 // be inserting into each pool. This helps us create the pools with
1884 // the right size, to avoid unnecessary hashtable resizing.
1885 unsigned int symbol_count = 0;
1886 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1887 p != input_objects->relobj_end();
1889 symbol_count += (*p)->local_symbol_count();
1891 // Go from "upper bound" to "estimate." We overcount for two
1892 // reasons: we double-count symbols that occur in more than one
1893 // object file, and we count symbols that are dropped from the
1894 // output. Add it all together and assume we overcount by 100%.
1897 // We assume all symbols will go into both the sympool and dynpool.
1898 this->sympool_.reserve(symbol_count);
1899 this->dynpool_.reserve(symbol_count);
1901 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1902 p != input_objects->relobj_end();
1905 Task_lock_obj<Object> tlo(task, *p);
1906 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
1910 // Create the symbol table sections. Here we also set the final
1911 // values of the symbols. At this point all the loadable sections are
1912 // fully laid out. SHNUM is the number of sections so far.
1915 Layout::create_symtab_sections(const Input_objects* input_objects,
1916 Symbol_table* symtab,
1922 if (parameters->target().get_size() == 32)
1924 symsize = elfcpp::Elf_sizes<32>::sym_size;
1927 else if (parameters->target().get_size() == 64)
1929 symsize = elfcpp::Elf_sizes<64>::sym_size;
1936 off = align_address(off, align);
1937 off_t startoff = off;
1939 // Save space for the dummy symbol at the start of the section. We
1940 // never bother to write this out--it will just be left as zero.
1942 unsigned int local_symbol_index = 1;
1944 // Add STT_SECTION symbols for each Output section which needs one.
1945 for (Section_list::iterator p = this->section_list_.begin();
1946 p != this->section_list_.end();
1949 if (!(*p)->needs_symtab_index())
1950 (*p)->set_symtab_index(-1U);
1953 (*p)->set_symtab_index(local_symbol_index);
1954 ++local_symbol_index;
1959 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1960 p != input_objects->relobj_end();
1963 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
1965 off += (index - local_symbol_index) * symsize;
1966 local_symbol_index = index;
1969 unsigned int local_symcount = local_symbol_index;
1970 gold_assert(local_symcount * symsize == off - startoff);
1973 size_t dyn_global_index;
1975 if (this->dynsym_section_ == NULL)
1978 dyn_global_index = 0;
1983 dyn_global_index = this->dynsym_section_->info();
1984 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
1985 dynoff = this->dynsym_section_->offset() + locsize;
1986 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
1987 gold_assert(static_cast<off_t>(dyncount * symsize)
1988 == this->dynsym_section_->data_size() - locsize);
1991 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
1992 &this->sympool_, &local_symcount);
1994 if (!parameters->options().strip_all())
1996 this->sympool_.set_string_offsets();
1998 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
1999 Output_section* osymtab = this->make_output_section(symtab_name,
2002 this->symtab_section_ = osymtab;
2004 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2006 osymtab->add_output_section_data(pos);
2008 // We generate a .symtab_shndx section if we have more than
2009 // SHN_LORESERVE sections. Technically it is possible that we
2010 // don't need one, because it is possible that there are no
2011 // symbols in any of sections with indexes larger than
2012 // SHN_LORESERVE. That is probably unusual, though, and it is
2013 // easier to always create one than to compute section indexes
2014 // twice (once here, once when writing out the symbols).
2015 if (shnum >= elfcpp::SHN_LORESERVE)
2017 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2019 Output_section* osymtab_xindex =
2020 this->make_output_section(symtab_xindex_name,
2021 elfcpp::SHT_SYMTAB_SHNDX, 0);
2023 size_t symcount = (off - startoff) / symsize;
2024 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2026 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2028 osymtab_xindex->set_link_section(osymtab);
2029 osymtab_xindex->set_addralign(4);
2030 osymtab_xindex->set_entsize(4);
2032 osymtab_xindex->set_after_input_sections();
2034 // This tells the driver code to wait until the symbol table
2035 // has written out before writing out the postprocessing
2036 // sections, including the .symtab_shndx section.
2037 this->any_postprocessing_sections_ = true;
2040 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2041 Output_section* ostrtab = this->make_output_section(strtab_name,
2045 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2046 ostrtab->add_output_section_data(pstr);
2048 osymtab->set_file_offset(startoff);
2049 osymtab->finalize_data_size();
2050 osymtab->set_link_section(ostrtab);
2051 osymtab->set_info(local_symcount);
2052 osymtab->set_entsize(symsize);
2058 // Create the .shstrtab section, which holds the names of the
2059 // sections. At the time this is called, we have created all the
2060 // output sections except .shstrtab itself.
2063 Layout::create_shstrtab()
2065 // FIXME: We don't need to create a .shstrtab section if we are
2066 // stripping everything.
2068 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2070 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
2072 // We can't write out this section until we've set all the section
2073 // names, and we don't set the names of compressed output sections
2074 // until relocations are complete.
2075 os->set_after_input_sections();
2077 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2078 os->add_output_section_data(posd);
2083 // Create the section headers. SIZE is 32 or 64. OFF is the file
2087 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2089 Output_section_headers* oshdrs;
2090 oshdrs = new Output_section_headers(this,
2091 &this->segment_list_,
2092 &this->section_list_,
2093 &this->unattached_section_list_,
2096 off_t off = align_address(*poff, oshdrs->addralign());
2097 oshdrs->set_address_and_file_offset(0, off);
2098 off += oshdrs->data_size();
2100 this->section_headers_ = oshdrs;
2103 // Count the allocated sections.
2106 Layout::allocated_output_section_count() const
2108 size_t section_count = 0;
2109 for (Segment_list::const_iterator p = this->segment_list_.begin();
2110 p != this->segment_list_.end();
2112 section_count += (*p)->output_section_count();
2113 return section_count;
2116 // Create the dynamic symbol table.
2119 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2120 Symbol_table* symtab,
2121 Output_section **pdynstr,
2122 unsigned int* plocal_dynamic_count,
2123 std::vector<Symbol*>* pdynamic_symbols,
2124 Versions* pversions)
2126 // Count all the symbols in the dynamic symbol table, and set the
2127 // dynamic symbol indexes.
2129 // Skip symbol 0, which is always all zeroes.
2130 unsigned int index = 1;
2132 // Add STT_SECTION symbols for each Output section which needs one.
2133 for (Section_list::iterator p = this->section_list_.begin();
2134 p != this->section_list_.end();
2137 if (!(*p)->needs_dynsym_index())
2138 (*p)->set_dynsym_index(-1U);
2141 (*p)->set_dynsym_index(index);
2146 // Count the local symbols that need to go in the dynamic symbol table,
2147 // and set the dynamic symbol indexes.
2148 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2149 p != input_objects->relobj_end();
2152 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2156 unsigned int local_symcount = index;
2157 *plocal_dynamic_count = local_symcount;
2159 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2160 &this->dynpool_, pversions);
2164 const int size = parameters->target().get_size();
2167 symsize = elfcpp::Elf_sizes<32>::sym_size;
2170 else if (size == 64)
2172 symsize = elfcpp::Elf_sizes<64>::sym_size;
2178 // Create the dynamic symbol table section.
2180 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2185 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2187 dynsym->add_output_section_data(odata);
2189 dynsym->set_info(local_symcount);
2190 dynsym->set_entsize(symsize);
2191 dynsym->set_addralign(align);
2193 this->dynsym_section_ = dynsym;
2195 Output_data_dynamic* const odyn = this->dynamic_data_;
2196 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2197 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2199 // If there are more than SHN_LORESERVE allocated sections, we
2200 // create a .dynsym_shndx section. It is possible that we don't
2201 // need one, because it is possible that there are no dynamic
2202 // symbols in any of the sections with indexes larger than
2203 // SHN_LORESERVE. This is probably unusual, though, and at this
2204 // time we don't know the actual section indexes so it is
2205 // inconvenient to check.
2206 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2208 Output_section* dynsym_xindex =
2209 this->choose_output_section(NULL, ".dynsym_shndx",
2210 elfcpp::SHT_SYMTAB_SHNDX,
2214 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2216 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2218 dynsym_xindex->set_link_section(dynsym);
2219 dynsym_xindex->set_addralign(4);
2220 dynsym_xindex->set_entsize(4);
2222 dynsym_xindex->set_after_input_sections();
2224 // This tells the driver code to wait until the symbol table has
2225 // written out before writing out the postprocessing sections,
2226 // including the .dynsym_shndx section.
2227 this->any_postprocessing_sections_ = true;
2230 // Create the dynamic string table section.
2232 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2237 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2238 dynstr->add_output_section_data(strdata);
2240 dynsym->set_link_section(dynstr);
2241 this->dynamic_section_->set_link_section(dynstr);
2243 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2244 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2248 // Create the hash tables.
2250 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2251 || strcmp(parameters->options().hash_style(), "both") == 0)
2253 unsigned char* phash;
2254 unsigned int hashlen;
2255 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2258 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2263 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2266 hashsec->add_output_section_data(hashdata);
2268 hashsec->set_link_section(dynsym);
2269 hashsec->set_entsize(4);
2271 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2274 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2275 || strcmp(parameters->options().hash_style(), "both") == 0)
2277 unsigned char* phash;
2278 unsigned int hashlen;
2279 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2282 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2283 elfcpp::SHT_GNU_HASH,
2287 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2290 hashsec->add_output_section_data(hashdata);
2292 hashsec->set_link_section(dynsym);
2293 hashsec->set_entsize(4);
2295 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2299 // Assign offsets to each local portion of the dynamic symbol table.
2302 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2304 Output_section* dynsym = this->dynsym_section_;
2305 gold_assert(dynsym != NULL);
2307 off_t off = dynsym->offset();
2309 // Skip the dummy symbol at the start of the section.
2310 off += dynsym->entsize();
2312 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2313 p != input_objects->relobj_end();
2316 unsigned int count = (*p)->set_local_dynsym_offset(off);
2317 off += count * dynsym->entsize();
2321 // Create the version sections.
2324 Layout::create_version_sections(const Versions* versions,
2325 const Symbol_table* symtab,
2326 unsigned int local_symcount,
2327 const std::vector<Symbol*>& dynamic_symbols,
2328 const Output_section* dynstr)
2330 if (!versions->any_defs() && !versions->any_needs())
2333 switch (parameters->size_and_endianness())
2335 #ifdef HAVE_TARGET_32_LITTLE
2336 case Parameters::TARGET_32_LITTLE:
2337 this->sized_create_version_sections<32, false>(versions, symtab,
2339 dynamic_symbols, dynstr);
2342 #ifdef HAVE_TARGET_32_BIG
2343 case Parameters::TARGET_32_BIG:
2344 this->sized_create_version_sections<32, true>(versions, symtab,
2346 dynamic_symbols, dynstr);
2349 #ifdef HAVE_TARGET_64_LITTLE
2350 case Parameters::TARGET_64_LITTLE:
2351 this->sized_create_version_sections<64, false>(versions, symtab,
2353 dynamic_symbols, dynstr);
2356 #ifdef HAVE_TARGET_64_BIG
2357 case Parameters::TARGET_64_BIG:
2358 this->sized_create_version_sections<64, true>(versions, symtab,
2360 dynamic_symbols, dynstr);
2368 // Create the version sections, sized version.
2370 template<int size, bool big_endian>
2372 Layout::sized_create_version_sections(
2373 const Versions* versions,
2374 const Symbol_table* symtab,
2375 unsigned int local_symcount,
2376 const std::vector<Symbol*>& dynamic_symbols,
2377 const Output_section* dynstr)
2379 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2380 elfcpp::SHT_GNU_versym,
2384 unsigned char* vbuf;
2386 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2391 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2);
2393 vsec->add_output_section_data(vdata);
2394 vsec->set_entsize(2);
2395 vsec->set_link_section(this->dynsym_section_);
2397 Output_data_dynamic* const odyn = this->dynamic_data_;
2398 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2400 if (versions->any_defs())
2402 Output_section* vdsec;
2403 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
2404 elfcpp::SHT_GNU_verdef,
2408 unsigned char* vdbuf;
2409 unsigned int vdsize;
2410 unsigned int vdentries;
2411 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
2412 &vdsize, &vdentries);
2414 Output_section_data* vddata = new Output_data_const_buffer(vdbuf,
2418 vdsec->add_output_section_data(vddata);
2419 vdsec->set_link_section(dynstr);
2420 vdsec->set_info(vdentries);
2422 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
2423 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
2426 if (versions->any_needs())
2428 Output_section* vnsec;
2429 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
2430 elfcpp::SHT_GNU_verneed,
2434 unsigned char* vnbuf;
2435 unsigned int vnsize;
2436 unsigned int vnentries;
2437 versions->need_section_contents<size, big_endian>(&this->dynpool_,
2441 Output_section_data* vndata = new Output_data_const_buffer(vnbuf,
2445 vnsec->add_output_section_data(vndata);
2446 vnsec->set_link_section(dynstr);
2447 vnsec->set_info(vnentries);
2449 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
2450 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
2454 // Create the .interp section and PT_INTERP segment.
2457 Layout::create_interp(const Target* target)
2459 const char* interp = this->options_.dynamic_linker();
2462 interp = target->dynamic_linker();
2463 gold_assert(interp != NULL);
2466 size_t len = strlen(interp) + 1;
2468 Output_section_data* odata = new Output_data_const(interp, len, 1);
2470 Output_section* osec = this->choose_output_section(NULL, ".interp",
2471 elfcpp::SHT_PROGBITS,
2474 osec->add_output_section_data(odata);
2476 if (!this->script_options_->saw_phdrs_clause())
2478 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
2480 oseg->add_initial_output_section(osec, elfcpp::PF_R);
2484 // Finish the .dynamic section and PT_DYNAMIC segment.
2487 Layout::finish_dynamic_section(const Input_objects* input_objects,
2488 const Symbol_table* symtab)
2490 if (!this->script_options_->saw_phdrs_clause())
2492 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
2495 oseg->add_initial_output_section(this->dynamic_section_,
2496 elfcpp::PF_R | elfcpp::PF_W);
2499 Output_data_dynamic* const odyn = this->dynamic_data_;
2501 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
2502 p != input_objects->dynobj_end();
2505 // FIXME: Handle --as-needed.
2506 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
2509 if (parameters->options().shared())
2511 const char* soname = this->options_.soname();
2513 odyn->add_string(elfcpp::DT_SONAME, soname);
2516 // FIXME: Support --init and --fini.
2517 Symbol* sym = symtab->lookup("_init");
2518 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2519 odyn->add_symbol(elfcpp::DT_INIT, sym);
2521 sym = symtab->lookup("_fini");
2522 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2523 odyn->add_symbol(elfcpp::DT_FINI, sym);
2525 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
2527 // Add a DT_RPATH entry if needed.
2528 const General_options::Dir_list& rpath(this->options_.rpath());
2531 std::string rpath_val;
2532 for (General_options::Dir_list::const_iterator p = rpath.begin();
2536 if (rpath_val.empty())
2537 rpath_val = p->name();
2540 // Eliminate duplicates.
2541 General_options::Dir_list::const_iterator q;
2542 for (q = rpath.begin(); q != p; ++q)
2543 if (q->name() == p->name())
2548 rpath_val += p->name();
2553 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
2554 if (parameters->options().enable_new_dtags())
2555 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
2558 // Look for text segments that have dynamic relocations.
2559 bool have_textrel = false;
2560 if (!this->script_options_->saw_sections_clause())
2562 for (Segment_list::const_iterator p = this->segment_list_.begin();
2563 p != this->segment_list_.end();
2566 if (((*p)->flags() & elfcpp::PF_W) == 0
2567 && (*p)->dynamic_reloc_count() > 0)
2569 have_textrel = true;
2576 // We don't know the section -> segment mapping, so we are
2577 // conservative and just look for readonly sections with
2578 // relocations. If those sections wind up in writable segments,
2579 // then we have created an unnecessary DT_TEXTREL entry.
2580 for (Section_list::const_iterator p = this->section_list_.begin();
2581 p != this->section_list_.end();
2584 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
2585 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
2586 && ((*p)->dynamic_reloc_count() > 0))
2588 have_textrel = true;
2594 // Add a DT_FLAGS entry. We add it even if no flags are set so that
2595 // post-link tools can easily modify these flags if desired.
2596 unsigned int flags = 0;
2599 // Add a DT_TEXTREL for compatibility with older loaders.
2600 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
2601 flags |= elfcpp::DF_TEXTREL;
2603 if (parameters->options().shared() && this->has_static_tls())
2604 flags |= elfcpp::DF_STATIC_TLS;
2605 odyn->add_constant(elfcpp::DT_FLAGS, flags);
2608 if (parameters->options().initfirst())
2609 flags |= elfcpp::DF_1_INITFIRST;
2610 if (parameters->options().interpose())
2611 flags |= elfcpp::DF_1_INTERPOSE;
2612 if (parameters->options().loadfltr())
2613 flags |= elfcpp::DF_1_LOADFLTR;
2614 if (parameters->options().nodefaultlib())
2615 flags |= elfcpp::DF_1_NODEFLIB;
2616 if (parameters->options().nodelete())
2617 flags |= elfcpp::DF_1_NODELETE;
2618 if (parameters->options().nodlopen())
2619 flags |= elfcpp::DF_1_NOOPEN;
2620 if (parameters->options().nodump())
2621 flags |= elfcpp::DF_1_NODUMP;
2622 if (!parameters->options().shared())
2623 flags &= ~(elfcpp::DF_1_INITFIRST
2624 | elfcpp::DF_1_NODELETE
2625 | elfcpp::DF_1_NOOPEN);
2627 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
2630 // The mapping of .gnu.linkonce section names to real section names.
2632 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
2633 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
2635 MAPPING_INIT("d.rel.ro", ".data.rel.ro"), // Must be before "d".
2636 MAPPING_INIT("t", ".text"),
2637 MAPPING_INIT("r", ".rodata"),
2638 MAPPING_INIT("d", ".data"),
2639 MAPPING_INIT("b", ".bss"),
2640 MAPPING_INIT("s", ".sdata"),
2641 MAPPING_INIT("sb", ".sbss"),
2642 MAPPING_INIT("s2", ".sdata2"),
2643 MAPPING_INIT("sb2", ".sbss2"),
2644 MAPPING_INIT("wi", ".debug_info"),
2645 MAPPING_INIT("td", ".tdata"),
2646 MAPPING_INIT("tb", ".tbss"),
2647 MAPPING_INIT("lr", ".lrodata"),
2648 MAPPING_INIT("l", ".ldata"),
2649 MAPPING_INIT("lb", ".lbss"),
2653 const int Layout::linkonce_mapping_count =
2654 sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
2656 // Return the name of the output section to use for a .gnu.linkonce
2657 // section. This is based on the default ELF linker script of the old
2658 // GNU linker. For example, we map a name like ".gnu.linkonce.t.foo"
2659 // to ".text". Set *PLEN to the length of the name. *PLEN is
2660 // initialized to the length of NAME.
2663 Layout::linkonce_output_name(const char* name, size_t *plen)
2665 const char* s = name + sizeof(".gnu.linkonce") - 1;
2669 const Linkonce_mapping* plm = linkonce_mapping;
2670 for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2672 if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2681 // Choose the output section name to use given an input section name.
2682 // Set *PLEN to the length of the name. *PLEN is initialized to the
2686 Layout::output_section_name(const char* name, size_t* plen)
2688 if (Layout::is_linkonce(name))
2690 // .gnu.linkonce sections are laid out as though they were named
2691 // for the sections are placed into.
2692 return Layout::linkonce_output_name(name, plen);
2695 // gcc 4.3 generates the following sorts of section names when it
2696 // needs a section name specific to a function:
2702 // .data.rel.local.FN
2704 // .data.rel.ro.local.FN
2711 // The GNU linker maps all of those to the part before the .FN,
2712 // except that .data.rel.local.FN is mapped to .data, and
2713 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
2714 // beginning with .data.rel.ro.local are grouped together.
2716 // For an anonymous namespace, the string FN can contain a '.'.
2718 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2719 // GNU linker maps to .rodata.
2721 // The .data.rel.ro sections enable a security feature triggered by
2722 // the -z relro option. Section which need to be relocated at
2723 // program startup time but which may be readonly after startup are
2724 // grouped into .data.rel.ro. They are then put into a PT_GNU_RELRO
2725 // segment. The dynamic linker will make that segment writable,
2726 // perform relocations, and then make it read-only. FIXME: We do
2727 // not yet implement this optimization.
2729 // It is hard to handle this in a principled way.
2731 // These are the rules we follow:
2733 // If the section name has no initial '.', or no dot other than an
2734 // initial '.', we use the name unchanged (i.e., "mysection" and
2735 // ".text" are unchanged).
2737 // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2739 // Otherwise, we drop the second '.' and everything that comes after
2740 // it (i.e., ".text.XXX" becomes ".text").
2742 const char* s = name;
2746 const char* sdot = strchr(s, '.');
2750 const char* const data_rel_ro = ".data.rel.ro";
2751 if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2753 *plen = strlen(data_rel_ro);
2757 *plen = sdot - name;
2761 // Record the signature of a comdat section, and return whether to
2762 // include it in the link. If GROUP is true, this is a regular
2763 // section group. If GROUP is false, this is a group signature
2764 // derived from the name of a linkonce section. We want linkonce
2765 // signatures and group signatures to block each other, but we don't
2766 // want a linkonce signature to block another linkonce signature.
2769 Layout::add_comdat(Relobj* object, unsigned int shndx,
2770 const std::string& signature, bool group)
2772 Kept_section kept(object, shndx, group);
2773 std::pair<Signatures::iterator, bool> ins(
2774 this->signatures_.insert(std::make_pair(signature, kept)));
2778 // This is the first time we've seen this signature.
2782 if (ins.first->second.group_)
2784 // We've already seen a real section group with this signature.
2789 // This is a real section group, and we've already seen a
2790 // linkonce section with this signature. Record that we've seen
2791 // a section group, and don't include this section group.
2792 ins.first->second.group_ = true;
2797 // We've already seen a linkonce section and this is a linkonce
2798 // section. These don't block each other--this may be the same
2799 // symbol name with different section types.
2804 // Find the given comdat signature, and return the object and section
2805 // index of the kept group.
2807 Layout::find_kept_object(const std::string& signature,
2808 unsigned int* pshndx) const
2810 Signatures::const_iterator p = this->signatures_.find(signature);
2811 if (p == this->signatures_.end())
2814 *pshndx = p->second.shndx_;
2815 return p->second.object_;
2818 // Store the allocated sections into the section list.
2821 Layout::get_allocated_sections(Section_list* section_list) const
2823 for (Section_list::const_iterator p = this->section_list_.begin();
2824 p != this->section_list_.end();
2826 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2827 section_list->push_back(*p);
2830 // Create an output segment.
2833 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2835 gold_assert(!parameters->options().relocatable());
2836 Output_segment* oseg = new Output_segment(type, flags);
2837 this->segment_list_.push_back(oseg);
2841 // Write out the Output_sections. Most won't have anything to write,
2842 // since most of the data will come from input sections which are
2843 // handled elsewhere. But some Output_sections do have Output_data.
2846 Layout::write_output_sections(Output_file* of) const
2848 for (Section_list::const_iterator p = this->section_list_.begin();
2849 p != this->section_list_.end();
2852 if (!(*p)->after_input_sections())
2857 // Write out data not associated with a section or the symbol table.
2860 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
2862 if (!parameters->options().strip_all())
2864 const Output_section* symtab_section = this->symtab_section_;
2865 for (Section_list::const_iterator p = this->section_list_.begin();
2866 p != this->section_list_.end();
2869 if ((*p)->needs_symtab_index())
2871 gold_assert(symtab_section != NULL);
2872 unsigned int index = (*p)->symtab_index();
2873 gold_assert(index > 0 && index != -1U);
2874 off_t off = (symtab_section->offset()
2875 + index * symtab_section->entsize());
2876 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
2881 const Output_section* dynsym_section = this->dynsym_section_;
2882 for (Section_list::const_iterator p = this->section_list_.begin();
2883 p != this->section_list_.end();
2886 if ((*p)->needs_dynsym_index())
2888 gold_assert(dynsym_section != NULL);
2889 unsigned int index = (*p)->dynsym_index();
2890 gold_assert(index > 0 && index != -1U);
2891 off_t off = (dynsym_section->offset()
2892 + index * dynsym_section->entsize());
2893 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
2897 // Write out the Output_data which are not in an Output_section.
2898 for (Data_list::const_iterator p = this->special_output_list_.begin();
2899 p != this->special_output_list_.end();
2904 // Write out the Output_sections which can only be written after the
2905 // input sections are complete.
2908 Layout::write_sections_after_input_sections(Output_file* of)
2910 // Determine the final section offsets, and thus the final output
2911 // file size. Note we finalize the .shstrab last, to allow the
2912 // after_input_section sections to modify their section-names before
2914 if (this->any_postprocessing_sections_)
2916 off_t off = this->output_file_size_;
2917 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
2919 // Now that we've finalized the names, we can finalize the shstrab.
2921 this->set_section_offsets(off,
2922 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2924 if (off > this->output_file_size_)
2927 this->output_file_size_ = off;
2931 for (Section_list::const_iterator p = this->section_list_.begin();
2932 p != this->section_list_.end();
2935 if ((*p)->after_input_sections())
2939 this->section_headers_->write(of);
2942 // If the build ID requires computing a checksum, do so here, and
2943 // write it out. We compute a checksum over the entire file because
2944 // that is simplest.
2947 Layout::write_build_id(Output_file* of) const
2949 if (this->build_id_note_ == NULL)
2952 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
2954 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
2955 this->build_id_note_->data_size());
2957 const char* style = parameters->options().build_id();
2958 if (strcmp(style, "sha1") == 0)
2961 sha1_init_ctx(&ctx);
2962 sha1_process_bytes(iv, this->output_file_size_, &ctx);
2963 sha1_finish_ctx(&ctx, ov);
2965 else if (strcmp(style, "md5") == 0)
2969 md5_process_bytes(iv, this->output_file_size_, &ctx);
2970 md5_finish_ctx(&ctx, ov);
2975 of->write_output_view(this->build_id_note_->offset(),
2976 this->build_id_note_->data_size(),
2979 of->free_input_view(0, this->output_file_size_, iv);
2982 // Write out a binary file. This is called after the link is
2983 // complete. IN is the temporary output file we used to generate the
2984 // ELF code. We simply walk through the segments, read them from
2985 // their file offset in IN, and write them to their load address in
2986 // the output file. FIXME: with a bit more work, we could support
2987 // S-records and/or Intel hex format here.
2990 Layout::write_binary(Output_file* in) const
2992 gold_assert(this->options_.oformat_enum()
2993 == General_options::OBJECT_FORMAT_BINARY);
2995 // Get the size of the binary file.
2996 uint64_t max_load_address = 0;
2997 for (Segment_list::const_iterator p = this->segment_list_.begin();
2998 p != this->segment_list_.end();
3001 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3003 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3004 if (max_paddr > max_load_address)
3005 max_load_address = max_paddr;
3009 Output_file out(parameters->options().output_file_name());
3010 out.open(max_load_address);
3012 for (Segment_list::const_iterator p = this->segment_list_.begin();
3013 p != this->segment_list_.end();
3016 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3018 const unsigned char* vin = in->get_input_view((*p)->offset(),
3020 unsigned char* vout = out.get_output_view((*p)->paddr(),
3022 memcpy(vout, vin, (*p)->filesz());
3023 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3024 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3031 // Print statistical information to stderr. This is used for --stats.
3034 Layout::print_stats() const
3036 this->namepool_.print_stats("section name pool");
3037 this->sympool_.print_stats("output symbol name pool");
3038 this->dynpool_.print_stats("dynamic name pool");
3040 for (Section_list::const_iterator p = this->section_list_.begin();
3041 p != this->section_list_.end();
3043 (*p)->print_merge_stats();
3046 // Write_sections_task methods.
3048 // We can always run this task.
3051 Write_sections_task::is_runnable()
3056 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3060 Write_sections_task::locks(Task_locker* tl)
3062 tl->add(this, this->output_sections_blocker_);
3063 tl->add(this, this->final_blocker_);
3066 // Run the task--write out the data.
3069 Write_sections_task::run(Workqueue*)
3071 this->layout_->write_output_sections(this->of_);
3074 // Write_data_task methods.
3076 // We can always run this task.
3079 Write_data_task::is_runnable()
3084 // We need to unlock FINAL_BLOCKER when finished.
3087 Write_data_task::locks(Task_locker* tl)
3089 tl->add(this, this->final_blocker_);
3092 // Run the task--write out the data.
3095 Write_data_task::run(Workqueue*)
3097 this->layout_->write_data(this->symtab_, this->of_);
3100 // Write_symbols_task methods.
3102 // We can always run this task.
3105 Write_symbols_task::is_runnable()
3110 // We need to unlock FINAL_BLOCKER when finished.
3113 Write_symbols_task::locks(Task_locker* tl)
3115 tl->add(this, this->final_blocker_);
3118 // Run the task--write out the symbols.
3121 Write_symbols_task::run(Workqueue*)
3123 this->symtab_->write_globals(this->input_objects_, this->sympool_,
3124 this->dynpool_, this->layout_->symtab_xindex(),
3125 this->layout_->dynsym_xindex(), this->of_);
3128 // Write_after_input_sections_task methods.
3130 // We can only run this task after the input sections have completed.
3133 Write_after_input_sections_task::is_runnable()
3135 if (this->input_sections_blocker_->is_blocked())
3136 return this->input_sections_blocker_;
3140 // We need to unlock FINAL_BLOCKER when finished.
3143 Write_after_input_sections_task::locks(Task_locker* tl)
3145 tl->add(this, this->final_blocker_);
3151 Write_after_input_sections_task::run(Workqueue*)
3153 this->layout_->write_sections_after_input_sections(this->of_);
3156 // Close_task_runner methods.
3158 // Run the task--close the file.
3161 Close_task_runner::run(Workqueue*, const Task*)
3163 // If we need to compute a checksum for the BUILD if, we do so here.
3164 this->layout_->write_build_id(this->of_);
3166 // If we've been asked to create a binary file, we do so here.
3167 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3168 this->layout_->write_binary(this->of_);
3173 // Instantiate the templates we need. We could use the configure
3174 // script to restrict this to only the ones for implemented targets.
3176 #ifdef HAVE_TARGET_32_LITTLE
3179 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3181 const elfcpp::Shdr<32, false>& shdr,
3182 unsigned int, unsigned int, off_t*);
3185 #ifdef HAVE_TARGET_32_BIG
3188 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3190 const elfcpp::Shdr<32, true>& shdr,
3191 unsigned int, unsigned int, off_t*);
3194 #ifdef HAVE_TARGET_64_LITTLE
3197 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3199 const elfcpp::Shdr<64, false>& shdr,
3200 unsigned int, unsigned int, off_t*);
3203 #ifdef HAVE_TARGET_64_BIG
3206 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3208 const elfcpp::Shdr<64, true>& shdr,
3209 unsigned int, unsigned int, off_t*);
3212 #ifdef HAVE_TARGET_32_LITTLE
3215 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3216 unsigned int reloc_shndx,
3217 const elfcpp::Shdr<32, false>& shdr,
3218 Output_section* data_section,
3219 Relocatable_relocs* rr);
3222 #ifdef HAVE_TARGET_32_BIG
3225 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3226 unsigned int reloc_shndx,
3227 const elfcpp::Shdr<32, true>& shdr,
3228 Output_section* data_section,
3229 Relocatable_relocs* rr);
3232 #ifdef HAVE_TARGET_64_LITTLE
3235 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3236 unsigned int reloc_shndx,
3237 const elfcpp::Shdr<64, false>& shdr,
3238 Output_section* data_section,
3239 Relocatable_relocs* rr);
3242 #ifdef HAVE_TARGET_64_BIG
3245 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3246 unsigned int reloc_shndx,
3247 const elfcpp::Shdr<64, true>& shdr,
3248 Output_section* data_section,
3249 Relocatable_relocs* rr);
3252 #ifdef HAVE_TARGET_32_LITTLE
3255 Layout::layout_group<32, false>(Symbol_table* symtab,
3256 Sized_relobj<32, false>* object,
3258 const char* group_section_name,
3259 const char* signature,
3260 const elfcpp::Shdr<32, false>& shdr,
3261 const elfcpp::Elf_Word* contents);
3264 #ifdef HAVE_TARGET_32_BIG
3267 Layout::layout_group<32, true>(Symbol_table* symtab,
3268 Sized_relobj<32, true>* object,
3270 const char* group_section_name,
3271 const char* signature,
3272 const elfcpp::Shdr<32, true>& shdr,
3273 const elfcpp::Elf_Word* contents);
3276 #ifdef HAVE_TARGET_64_LITTLE
3279 Layout::layout_group<64, false>(Symbol_table* symtab,
3280 Sized_relobj<64, false>* object,
3282 const char* group_section_name,
3283 const char* signature,
3284 const elfcpp::Shdr<64, false>& shdr,
3285 const elfcpp::Elf_Word* contents);
3288 #ifdef HAVE_TARGET_64_BIG
3291 Layout::layout_group<64, true>(Symbol_table* symtab,
3292 Sized_relobj<64, true>* object,
3294 const char* group_section_name,
3295 const char* signature,
3296 const elfcpp::Shdr<64, true>& shdr,
3297 const elfcpp::Elf_Word* contents);
3300 #ifdef HAVE_TARGET_32_LITTLE
3303 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3304 const unsigned char* symbols,
3306 const unsigned char* symbol_names,
3307 off_t symbol_names_size,
3309 const elfcpp::Shdr<32, false>& shdr,
3310 unsigned int reloc_shndx,
3311 unsigned int reloc_type,
3315 #ifdef HAVE_TARGET_32_BIG
3318 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3319 const unsigned char* symbols,
3321 const unsigned char* symbol_names,
3322 off_t symbol_names_size,
3324 const elfcpp::Shdr<32, true>& shdr,
3325 unsigned int reloc_shndx,
3326 unsigned int reloc_type,
3330 #ifdef HAVE_TARGET_64_LITTLE
3333 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3334 const unsigned char* symbols,
3336 const unsigned char* symbol_names,
3337 off_t symbol_names_size,
3339 const elfcpp::Shdr<64, false>& shdr,
3340 unsigned int reloc_shndx,
3341 unsigned int reloc_type,
3345 #ifdef HAVE_TARGET_64_BIG
3348 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
3349 const unsigned char* symbols,
3351 const unsigned char* symbol_names,
3352 off_t symbol_names_size,
3354 const elfcpp::Shdr<64, true>& shdr,
3355 unsigned int reloc_shndx,
3356 unsigned int reloc_type,
3360 } // End namespace gold.