1 // layout.cc -- lay out output file sections for gold
3 // Copyright 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
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"
40 #include "script-sections.h"
45 #include "compressed_output.h"
46 #include "reduced_debug_output.h"
48 #include "descriptors.h"
50 #include "incremental.h"
56 // Layout::Relaxation_debug_check methods.
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.
63 Layout::Relaxation_debug_check::check_output_data_for_reset_values(
64 const Layout::Section_list& sections,
65 const Layout::Data_list& special_outputs)
67 for(Layout::Section_list::const_iterator p = sections.begin();
70 gold_assert((*p)->address_and_file_offset_have_reset_values());
72 for(Layout::Data_list::const_iterator p = special_outputs.begin();
73 p != special_outputs.end();
75 gold_assert((*p)->address_and_file_offset_have_reset_values());
78 // Save information of SECTIONS for checking later.
81 Layout::Relaxation_debug_check::read_sections(
82 const Layout::Section_list& sections)
84 for(Layout::Section_list::const_iterator p = sections.begin();
88 Output_section* os = *p;
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);
98 // Verify SECTIONS using previously recorded information.
101 Layout::Relaxation_debug_check::verify_sections(
102 const Layout::Section_list& sections)
105 for(Layout::Section_list::const_iterator p = sections.begin();
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 ;
114 if (i >= this->section_infos_.size())
116 gold_fatal("Section_info of %s missing.\n", os->name());
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());
129 // Layout_task_runner methods.
131 // Lay out the sections. This is called after all the input objects
135 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
137 off_t file_size = this->layout_->finalize(this->input_objects_,
142 // Now we know the final size of the output file and we know where
143 // each piece of information goes.
145 if (this->mapfile_ != NULL)
147 this->mapfile_->print_discarded_sections(this->input_objects_);
148 this->layout_->print_to_mapfile(this->mapfile_);
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();
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);
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),
173 unattached_section_list_(),
174 special_output_list_(),
175 section_headers_(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),
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),
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)
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);
211 // We expect two unattached Output_data objects: the file header and
212 // the segment headers.
213 this->special_output_list_.reserve(2);
215 // Initialize structure needed for an incremental build.
216 if (parameters->options().incremental())
217 this->incremental_inputs_ = new Incremental_inputs;
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();
224 // Hash a key we use to look up an output section mapping.
227 Layout::Hash_key::operator()(const Layout::Key& k) const
229 return k.first + k.second.first + k.second.second;
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.
236 static const char* gdb_sections[] =
238 // ".debug_aranges", // not used by gdb as of 6.7.1
244 // ".debug_pubnames", // not used by gdb as of 6.7.1
249 static const char* lines_only_debug_sections[] =
251 // ".debug_aranges", // not used by gdb as of 6.7.1
257 // ".debug_pubnames", // not used by gdb as of 6.7.1
263 is_gdb_debug_section(const char* str)
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)
273 is_lines_only_debug_section(const char* str)
275 // We can do this faster: binary search or a hashtable. But why bother?
277 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
279 if (strcmp(str, lines_only_debug_sections[i]) == 0)
284 // Whether to include this section in the link.
286 template<int size, bool big_endian>
288 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
289 const elfcpp::Shdr<size, big_endian>& shdr)
291 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
294 switch (shdr.get_sh_type())
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:
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);
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
317 gold_assert(!parameters->options().relocatable()
318 && !parameters->options().emit_relocs());
321 case elfcpp::SHT_PROGBITS:
322 if (parameters->options().strip_debug()
323 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
325 if (is_debug_info_section(name))
328 if (parameters->options().strip_debug_non_line()
329 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
331 // Debugging sections can only be recognized by name.
332 if (is_prefix_of(".debug", name)
333 && !is_lines_only_debug_section(name))
336 if (parameters->options().strip_debug_gdb()
337 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
339 // Debugging sections can only be recognized by name.
340 if (is_prefix_of(".debug", name)
341 && !is_gdb_debug_section(name))
344 if (parameters->options().strip_lto_sections()
345 && !parameters->options().relocatable()
346 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
348 // Ignore LTO sections containing intermediate code.
349 if (is_prefix_of(".gnu.lto_", name))
359 // Return an output section named NAME, or NULL if there is none.
362 Layout::find_output_section(const char* name) const
364 for (Section_list::const_iterator p = this->section_list_.begin();
365 p != this->section_list_.end();
367 if (strcmp((*p)->name(), name) == 0)
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.
376 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
377 elfcpp::Elf_Word clear) const
379 for (Segment_list::const_iterator p = this->segment_list_.begin();
380 p != this->segment_list_.end();
382 if (static_cast<elfcpp::PT>((*p)->type()) == type
383 && ((*p)->flags() & set) == set
384 && ((*p)->flags() & clear) == 0)
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. IS_INTERP is true if this is the
392 // .interp section. IS_DYNAMIC_LINKER_SECTION is true if this section
393 // is used by the dynamic linker.
396 Layout::get_output_section(const char* name, Stringpool::Key name_key,
397 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
398 bool is_interp, bool is_dynamic_linker_section)
400 elfcpp::Elf_Xword lookup_flags = flags;
402 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
403 // read-write with read-only sections. Some other ELF linkers do
404 // not do this. FIXME: Perhaps there should be an option
406 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
408 const Key key(name_key, std::make_pair(type, lookup_flags));
409 const std::pair<Key, Output_section*> v(key, NULL);
410 std::pair<Section_name_map::iterator, bool> ins(
411 this->section_name_map_.insert(v));
414 return ins.first->second;
417 // This is the first time we've seen this name/type/flags
418 // combination. For compatibility with the GNU linker, we
419 // combine sections with contents and zero flags with sections
420 // with non-zero flags. This is a workaround for cases where
421 // assembler code forgets to set section flags. FIXME: Perhaps
422 // there should be an option to control this.
423 Output_section* os = NULL;
425 if (type == elfcpp::SHT_PROGBITS)
429 Output_section* same_name = this->find_output_section(name);
430 if (same_name != NULL
431 && same_name->type() == elfcpp::SHT_PROGBITS
432 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
435 else if ((flags & elfcpp::SHF_TLS) == 0)
437 elfcpp::Elf_Xword zero_flags = 0;
438 const Key zero_key(name_key, std::make_pair(type, zero_flags));
439 Section_name_map::iterator p =
440 this->section_name_map_.find(zero_key);
441 if (p != this->section_name_map_.end())
447 os = this->make_output_section(name, type, flags, is_interp,
448 is_dynamic_linker_section);
449 ins.first->second = os;
454 // Pick the output section to use for section NAME, in input file
455 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
456 // linker created section. IS_INPUT_SECTION is true if we are
457 // choosing an output section for an input section found in a input
458 // file. IS_INTERP is true if this is the .interp section.
459 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
460 // dynamic linker. This will return NULL if the input section should
464 Layout::choose_output_section(const Relobj* relobj, const char* name,
465 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
466 bool is_input_section, bool is_interp,
467 bool is_dynamic_linker_section)
469 // We should not see any input sections after we have attached
470 // sections to segments.
471 gold_assert(!is_input_section || !this->sections_are_attached_);
473 // Some flags in the input section should not be automatically
474 // copied to the output section.
475 flags &= ~ (elfcpp::SHF_INFO_LINK
476 | elfcpp::SHF_LINK_ORDER
479 | elfcpp::SHF_STRINGS);
481 if (this->script_options_->saw_sections_clause())
483 // We are using a SECTIONS clause, so the output section is
484 // chosen based only on the name.
486 Script_sections* ss = this->script_options_->script_sections();
487 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
488 Output_section** output_section_slot;
489 name = ss->output_section_name(file_name, name, &output_section_slot);
492 // The SECTIONS clause says to discard this input section.
496 // If this is an orphan section--one not mentioned in the linker
497 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
498 // default processing below.
500 if (output_section_slot != NULL)
502 if (*output_section_slot != NULL)
504 (*output_section_slot)->update_flags_for_input_section(flags);
505 return *output_section_slot;
508 // We don't put sections found in the linker script into
509 // SECTION_NAME_MAP_. That keeps us from getting confused
510 // if an orphan section is mapped to a section with the same
511 // name as one in the linker script.
513 name = this->namepool_.add(name, false, NULL);
516 this->make_output_section(name, type, flags, is_interp,
517 is_dynamic_linker_section);
518 os->set_found_in_sections_clause();
519 *output_section_slot = os;
524 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
526 // Turn NAME from the name of the input section into the name of the
529 size_t len = strlen(name);
531 && !this->script_options_->saw_sections_clause()
532 && !parameters->options().relocatable())
533 name = Layout::output_section_name(name, &len);
535 Stringpool::Key name_key;
536 name = this->namepool_.add_with_length(name, len, true, &name_key);
538 // Find or make the output section. The output section is selected
539 // based on the section name, type, and flags.
540 return this->get_output_section(name, name_key, type, flags, is_interp,
541 is_dynamic_linker_section);
544 // Return the output section to use for input section SHNDX, with name
545 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
546 // index of a relocation section which applies to this section, or 0
547 // if none, or -1U if more than one. RELOC_TYPE is the type of the
548 // relocation section if there is one. Set *OFF to the offset of this
549 // input section without the output section. Return NULL if the
550 // section should be discarded. Set *OFF to -1 if the section
551 // contents should not be written directly to the output file, but
552 // will instead receive special handling.
554 template<int size, bool big_endian>
556 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
557 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
558 unsigned int reloc_shndx, unsigned int, off_t* off)
562 if (!this->include_section(object, name, shdr))
567 // In a relocatable link a grouped section must not be combined with
568 // any other sections.
569 if (parameters->options().relocatable()
570 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
572 name = this->namepool_.add(name, true, NULL);
573 os = this->make_output_section(name, shdr.get_sh_type(),
574 shdr.get_sh_flags(), false, false);
578 os = this->choose_output_section(object, name, shdr.get_sh_type(),
579 shdr.get_sh_flags(), true, false,
585 // By default the GNU linker sorts input sections whose names match
586 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
587 // are sorted by name. This is used to implement constructor
588 // priority ordering. We are compatible.
589 if (!this->script_options_->saw_sections_clause()
590 && (is_prefix_of(".ctors.", name)
591 || is_prefix_of(".dtors.", name)
592 || is_prefix_of(".init_array.", name)
593 || is_prefix_of(".fini_array.", name)))
594 os->set_must_sort_attached_input_sections();
596 // FIXME: Handle SHF_LINK_ORDER somewhere.
598 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
599 this->script_options_->saw_sections_clause());
604 // Handle a relocation section when doing a relocatable link.
606 template<int size, bool big_endian>
608 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
610 const elfcpp::Shdr<size, big_endian>& shdr,
611 Output_section* data_section,
612 Relocatable_relocs* rr)
614 gold_assert(parameters->options().relocatable()
615 || parameters->options().emit_relocs());
617 int sh_type = shdr.get_sh_type();
620 if (sh_type == elfcpp::SHT_REL)
622 else if (sh_type == elfcpp::SHT_RELA)
626 name += data_section->name();
628 Output_section* os = this->choose_output_section(object, name.c_str(),
631 false, false, false);
633 os->set_should_link_to_symtab();
634 os->set_info_section(data_section);
636 Output_section_data* posd;
637 if (sh_type == elfcpp::SHT_REL)
639 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
640 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
644 else if (sh_type == elfcpp::SHT_RELA)
646 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
647 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
654 os->add_output_section_data(posd);
655 rr->set_output_data(posd);
660 // Handle a group section when doing a relocatable link.
662 template<int size, bool big_endian>
664 Layout::layout_group(Symbol_table* symtab,
665 Sized_relobj<size, big_endian>* object,
667 const char* group_section_name,
668 const char* signature,
669 const elfcpp::Shdr<size, big_endian>& shdr,
670 elfcpp::Elf_Word flags,
671 std::vector<unsigned int>* shndxes)
673 gold_assert(parameters->options().relocatable());
674 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
675 group_section_name = this->namepool_.add(group_section_name, true, NULL);
676 Output_section* os = this->make_output_section(group_section_name,
681 // We need to find a symbol with the signature in the symbol table.
682 // If we don't find one now, we need to look again later.
683 Symbol* sym = symtab->lookup(signature, NULL);
685 os->set_info_symndx(sym);
688 // Reserve some space to minimize reallocations.
689 if (this->group_signatures_.empty())
690 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
692 // We will wind up using a symbol whose name is the signature.
693 // So just put the signature in the symbol name pool to save it.
694 signature = symtab->canonicalize_name(signature);
695 this->group_signatures_.push_back(Group_signature(os, signature));
698 os->set_should_link_to_symtab();
701 section_size_type entry_count =
702 convert_to_section_size_type(shdr.get_sh_size() / 4);
703 Output_section_data* posd =
704 new Output_data_group<size, big_endian>(object, entry_count, flags,
706 os->add_output_section_data(posd);
709 // Special GNU handling of sections name .eh_frame. They will
710 // normally hold exception frame data as defined by the C++ ABI
711 // (http://codesourcery.com/cxx-abi/).
713 template<int size, bool big_endian>
715 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
716 const unsigned char* symbols,
718 const unsigned char* symbol_names,
719 off_t symbol_names_size,
721 const elfcpp::Shdr<size, big_endian>& shdr,
722 unsigned int reloc_shndx, unsigned int reloc_type,
725 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
726 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
728 const char* const name = ".eh_frame";
729 Output_section* os = this->choose_output_section(object,
731 elfcpp::SHT_PROGBITS,
733 false, false, false);
737 if (this->eh_frame_section_ == NULL)
739 this->eh_frame_section_ = os;
740 this->eh_frame_data_ = new Eh_frame();
742 if (parameters->options().eh_frame_hdr())
744 Output_section* hdr_os =
745 this->choose_output_section(NULL,
747 elfcpp::SHT_PROGBITS,
749 false, false, false);
753 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
754 this->eh_frame_data_);
755 hdr_os->add_output_section_data(hdr_posd);
757 hdr_os->set_after_input_sections();
759 if (!this->script_options_->saw_phdrs_clause())
761 Output_segment* hdr_oseg;
762 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
764 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R, false);
767 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
772 gold_assert(this->eh_frame_section_ == os);
774 if (this->eh_frame_data_->add_ehframe_input_section(object,
783 os->update_flags_for_input_section(shdr.get_sh_flags());
785 // We found a .eh_frame section we are going to optimize, so now
786 // we can add the set of optimized sections to the output
787 // section. We need to postpone adding this until we've found a
788 // section we can optimize so that the .eh_frame section in
789 // crtbegin.o winds up at the start of the output section.
790 if (!this->added_eh_frame_data_)
792 os->add_output_section_data(this->eh_frame_data_);
793 this->added_eh_frame_data_ = true;
799 // We couldn't handle this .eh_frame section for some reason.
800 // Add it as a normal section.
801 bool saw_sections_clause = this->script_options_->saw_sections_clause();
802 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
803 saw_sections_clause);
809 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
810 // the output section.
813 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
814 elfcpp::Elf_Xword flags,
815 Output_section_data* posd,
816 bool is_dynamic_linker_section)
818 Output_section* os = this->choose_output_section(NULL, name, type, flags,
820 is_dynamic_linker_section);
822 os->add_output_section_data(posd);
826 // Map section flags to segment flags.
829 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
831 elfcpp::Elf_Word ret = elfcpp::PF_R;
832 if ((flags & elfcpp::SHF_WRITE) != 0)
834 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
839 // Sometimes we compress sections. This is typically done for
840 // sections that are not part of normal program execution (such as
841 // .debug_* sections), and where the readers of these sections know
842 // how to deal with compressed sections. This routine doesn't say for
843 // certain whether we'll compress -- it depends on commandline options
844 // as well -- just whether this section is a candidate for compression.
845 // (The Output_compressed_section class decides whether to compress
846 // a given section, and picks the name of the compressed section.)
849 is_compressible_debug_section(const char* secname)
851 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
854 // Make a new Output_section, and attach it to segments as
855 // appropriate. IS_INTERP is true if this is the .interp section.
856 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
860 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
861 elfcpp::Elf_Xword flags, bool is_interp,
862 bool is_dynamic_linker_section)
865 if ((flags & elfcpp::SHF_ALLOC) == 0
866 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
867 && is_compressible_debug_section(name))
868 os = new Output_compressed_section(¶meters->options(), name, type,
870 else if ((flags & elfcpp::SHF_ALLOC) == 0
871 && parameters->options().strip_debug_non_line()
872 && strcmp(".debug_abbrev", name) == 0)
874 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
876 if (this->debug_info_)
877 this->debug_info_->set_abbreviations(this->debug_abbrev_);
879 else if ((flags & elfcpp::SHF_ALLOC) == 0
880 && parameters->options().strip_debug_non_line()
881 && strcmp(".debug_info", name) == 0)
883 os = this->debug_info_ = new Output_reduced_debug_info_section(
885 if (this->debug_abbrev_)
886 this->debug_info_->set_abbreviations(this->debug_abbrev_);
890 // FIXME: const_cast is ugly.
891 Target* target = const_cast<Target*>(¶meters->target());
892 os = target->make_output_section(name, type, flags);
897 if (is_dynamic_linker_section)
898 os->set_is_dynamic_linker_section();
900 parameters->target().new_output_section(os);
902 this->section_list_.push_back(os);
904 // The GNU linker by default sorts some sections by priority, so we
905 // do the same. We need to know that this might happen before we
906 // attach any input sections.
907 if (!this->script_options_->saw_sections_clause()
908 && (strcmp(name, ".ctors") == 0
909 || strcmp(name, ".dtors") == 0
910 || strcmp(name, ".init_array") == 0
911 || strcmp(name, ".fini_array") == 0))
912 os->set_may_sort_attached_input_sections();
914 // With -z relro, we have to recognize the special sections by name.
915 // There is no other way.
916 if (!this->script_options_->saw_sections_clause()
917 && parameters->options().relro()
918 && type == elfcpp::SHT_PROGBITS
919 && (flags & elfcpp::SHF_ALLOC) != 0
920 && (flags & elfcpp::SHF_WRITE) != 0)
922 if (strcmp(name, ".data.rel.ro") == 0)
924 else if (strcmp(name, ".data.rel.ro.local") == 0)
927 os->set_is_relro_local();
931 // Check for .stab*str sections, as .stab* sections need to link to
933 if (type == elfcpp::SHT_STRTAB
934 && !this->have_stabstr_section_
935 && strncmp(name, ".stab", 5) == 0
936 && strcmp(name + strlen(name) - 3, "str") == 0)
937 this->have_stabstr_section_ = true;
939 // If we have already attached the sections to segments, then we
940 // need to attach this one now. This happens for sections created
941 // directly by the linker.
942 if (this->sections_are_attached_)
943 this->attach_section_to_segment(os);
948 // Attach output sections to segments. This is called after we have
949 // seen all the input sections.
952 Layout::attach_sections_to_segments()
954 for (Section_list::iterator p = this->section_list_.begin();
955 p != this->section_list_.end();
957 this->attach_section_to_segment(*p);
959 this->sections_are_attached_ = true;
962 // Attach an output section to a segment.
965 Layout::attach_section_to_segment(Output_section* os)
967 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
968 this->unattached_section_list_.push_back(os);
970 this->attach_allocated_section_to_segment(os);
973 // Attach an allocated output section to a segment.
976 Layout::attach_allocated_section_to_segment(Output_section* os)
978 elfcpp::Elf_Xword flags = os->flags();
979 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
981 if (parameters->options().relocatable())
984 // If we have a SECTIONS clause, we can't handle the attachment to
985 // segments until after we've seen all the sections.
986 if (this->script_options_->saw_sections_clause())
989 gold_assert(!this->script_options_->saw_phdrs_clause());
991 // This output section goes into a PT_LOAD segment.
993 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
995 bool sort_sections = !this->script_options_->saw_sections_clause();
997 // In general the only thing we really care about for PT_LOAD
998 // segments is whether or not they are writable, so that is how we
999 // search for them. Large data sections also go into their own
1000 // PT_LOAD segment. People who need segments sorted on some other
1001 // basis will have to use a linker script.
1003 Segment_list::const_iterator p;
1004 for (p = this->segment_list_.begin();
1005 p != this->segment_list_.end();
1008 if ((*p)->type() != elfcpp::PT_LOAD)
1010 if (!parameters->options().omagic()
1011 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1013 // If -Tbss was specified, we need to separate the data and BSS
1015 if (parameters->options().user_set_Tbss())
1017 if ((os->type() == elfcpp::SHT_NOBITS)
1018 == (*p)->has_any_data_sections())
1021 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1024 (*p)->add_output_section(os, seg_flags, sort_sections);
1028 if (p == this->segment_list_.end())
1030 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1032 if (os->is_large_data_section())
1033 oseg->set_is_large_data_segment();
1034 oseg->add_output_section(os, seg_flags, sort_sections);
1037 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1039 if (os->type() == elfcpp::SHT_NOTE)
1041 // See if we already have an equivalent PT_NOTE segment.
1042 for (p = this->segment_list_.begin();
1043 p != segment_list_.end();
1046 if ((*p)->type() == elfcpp::PT_NOTE
1047 && (((*p)->flags() & elfcpp::PF_W)
1048 == (seg_flags & elfcpp::PF_W)))
1050 (*p)->add_output_section(os, seg_flags, false);
1055 if (p == this->segment_list_.end())
1057 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1059 oseg->add_output_section(os, seg_flags, false);
1063 // If we see a loadable SHF_TLS section, we create a PT_TLS
1064 // segment. There can only be one such segment.
1065 if ((flags & elfcpp::SHF_TLS) != 0)
1067 if (this->tls_segment_ == NULL)
1068 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1069 this->tls_segment_->add_output_section(os, seg_flags, false);
1072 // If -z relro is in effect, and we see a relro section, we create a
1073 // PT_GNU_RELRO segment. There can only be one such segment.
1074 if (os->is_relro() && parameters->options().relro())
1076 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1077 if (this->relro_segment_ == NULL)
1078 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1079 this->relro_segment_->add_output_section(os, seg_flags, false);
1083 // Make an output section for a script.
1086 Layout::make_output_section_for_script(const char* name)
1088 name = this->namepool_.add(name, false, NULL);
1089 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1090 elfcpp::SHF_ALLOC, false,
1092 os->set_found_in_sections_clause();
1096 // Return the number of segments we expect to see.
1099 Layout::expected_segment_count() const
1101 size_t ret = this->segment_list_.size();
1103 // If we didn't see a SECTIONS clause in a linker script, we should
1104 // already have the complete list of segments. Otherwise we ask the
1105 // SECTIONS clause how many segments it expects, and add in the ones
1106 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1108 if (!this->script_options_->saw_sections_clause())
1112 const Script_sections* ss = this->script_options_->script_sections();
1113 return ret + ss->expected_segment_count(this);
1117 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1118 // is whether we saw a .note.GNU-stack section in the object file.
1119 // GNU_STACK_FLAGS is the section flags. The flags give the
1120 // protection required for stack memory. We record this in an
1121 // executable as a PT_GNU_STACK segment. If an object file does not
1122 // have a .note.GNU-stack segment, we must assume that it is an old
1123 // object. On some targets that will force an executable stack.
1126 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1128 if (!seen_gnu_stack)
1129 this->input_without_gnu_stack_note_ = true;
1132 this->input_with_gnu_stack_note_ = true;
1133 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1134 this->input_requires_executable_stack_ = true;
1138 // Create automatic note sections.
1141 Layout::create_notes()
1143 this->create_gold_note();
1144 this->create_executable_stack_info();
1145 this->create_build_id();
1148 // Create the dynamic sections which are needed before we read the
1152 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1154 if (parameters->doing_static_link())
1157 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1158 elfcpp::SHT_DYNAMIC,
1160 | elfcpp::SHF_WRITE),
1161 false, false, true);
1162 this->dynamic_section_->set_is_relro();
1164 symtab->define_in_output_data("_DYNAMIC", NULL, Symbol_table::PREDEFINED,
1165 this->dynamic_section_, 0, 0,
1166 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1167 elfcpp::STV_HIDDEN, 0, false, false);
1169 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1171 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1174 // For each output section whose name can be represented as C symbol,
1175 // define __start and __stop symbols for the section. This is a GNU
1179 Layout::define_section_symbols(Symbol_table* symtab)
1181 for (Section_list::const_iterator p = this->section_list_.begin();
1182 p != this->section_list_.end();
1185 const char* const name = (*p)->name();
1186 if (name[strspn(name,
1188 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1189 "abcdefghijklmnopqrstuvwxyz"
1193 const std::string name_string(name);
1194 const std::string start_name("__start_" + name_string);
1195 const std::string stop_name("__stop_" + name_string);
1197 symtab->define_in_output_data(start_name.c_str(),
1199 Symbol_table::PREDEFINED,
1205 elfcpp::STV_DEFAULT,
1207 false, // offset_is_from_end
1208 true); // only_if_ref
1210 symtab->define_in_output_data(stop_name.c_str(),
1212 Symbol_table::PREDEFINED,
1218 elfcpp::STV_DEFAULT,
1220 true, // offset_is_from_end
1221 true); // only_if_ref
1226 // Define symbols for group signatures.
1229 Layout::define_group_signatures(Symbol_table* symtab)
1231 for (Group_signatures::iterator p = this->group_signatures_.begin();
1232 p != this->group_signatures_.end();
1235 Symbol* sym = symtab->lookup(p->signature, NULL);
1237 p->section->set_info_symndx(sym);
1240 // Force the name of the group section to the group
1241 // signature, and use the group's section symbol as the
1242 // signature symbol.
1243 if (strcmp(p->section->name(), p->signature) != 0)
1245 const char* name = this->namepool_.add(p->signature,
1247 p->section->set_name(name);
1249 p->section->set_needs_symtab_index();
1250 p->section->set_info_section_symndx(p->section);
1254 this->group_signatures_.clear();
1257 // Find the first read-only PT_LOAD segment, creating one if
1261 Layout::find_first_load_seg()
1263 for (Segment_list::const_iterator p = this->segment_list_.begin();
1264 p != this->segment_list_.end();
1267 if ((*p)->type() == elfcpp::PT_LOAD
1268 && ((*p)->flags() & elfcpp::PF_R) != 0
1269 && (parameters->options().omagic()
1270 || ((*p)->flags() & elfcpp::PF_W) == 0))
1274 gold_assert(!this->script_options_->saw_phdrs_clause());
1276 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1281 // Save states of all current output segments. Store saved states
1282 // in SEGMENT_STATES.
1285 Layout::save_segments(Segment_states* segment_states)
1287 for (Segment_list::const_iterator p = this->segment_list_.begin();
1288 p != this->segment_list_.end();
1291 Output_segment* segment = *p;
1293 Output_segment* copy = new Output_segment(*segment);
1294 (*segment_states)[segment] = copy;
1298 // Restore states of output segments and delete any segment not found in
1302 Layout::restore_segments(const Segment_states* segment_states)
1304 // Go through the segment list and remove any segment added in the
1306 this->tls_segment_ = NULL;
1307 this->relro_segment_ = NULL;
1308 Segment_list::iterator list_iter = this->segment_list_.begin();
1309 while (list_iter != this->segment_list_.end())
1311 Output_segment* segment = *list_iter;
1312 Segment_states::const_iterator states_iter =
1313 segment_states->find(segment);
1314 if (states_iter != segment_states->end())
1316 const Output_segment* copy = states_iter->second;
1317 // Shallow copy to restore states.
1320 // Also fix up TLS and RELRO segment pointers as appropriate.
1321 if (segment->type() == elfcpp::PT_TLS)
1322 this->tls_segment_ = segment;
1323 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1324 this->relro_segment_ = segment;
1330 list_iter = this->segment_list_.erase(list_iter);
1331 // This is a segment created during section layout. It should be
1332 // safe to remove it since we should have removed all pointers to it.
1338 // Clean up after relaxation so that sections can be laid out again.
1341 Layout::clean_up_after_relaxation()
1343 // Restore the segments to point state just prior to the relaxation loop.
1344 Script_sections* script_section = this->script_options_->script_sections();
1345 script_section->release_segments();
1346 this->restore_segments(this->segment_states_);
1348 // Reset section addresses and file offsets
1349 for (Section_list::iterator p = this->section_list_.begin();
1350 p != this->section_list_.end();
1353 (*p)->reset_address_and_file_offset();
1354 (*p)->restore_states();
1357 // Reset special output object address and file offsets.
1358 for (Data_list::iterator p = this->special_output_list_.begin();
1359 p != this->special_output_list_.end();
1361 (*p)->reset_address_and_file_offset();
1363 // A linker script may have created some output section data objects.
1364 // They are useless now.
1365 for (Output_section_data_list::const_iterator p =
1366 this->script_output_section_data_list_.begin();
1367 p != this->script_output_section_data_list_.end();
1370 this->script_output_section_data_list_.clear();
1373 // Prepare for relaxation.
1376 Layout::prepare_for_relaxation()
1378 // Create an relaxation debug check if in debugging mode.
1379 if (is_debugging_enabled(DEBUG_RELAXATION))
1380 this->relaxation_debug_check_ = new Relaxation_debug_check();
1382 // Save segment states.
1383 this->segment_states_ = new Segment_states();
1384 this->save_segments(this->segment_states_);
1386 for(Section_list::const_iterator p = this->section_list_.begin();
1387 p != this->section_list_.end();
1389 (*p)->save_states();
1391 if (is_debugging_enabled(DEBUG_RELAXATION))
1392 this->relaxation_debug_check_->check_output_data_for_reset_values(
1393 this->section_list_, this->special_output_list_);
1395 // Also enable recording of output section data from scripts.
1396 this->record_output_section_data_from_script_ = true;
1399 // Relaxation loop body: If target has no relaxation, this runs only once
1400 // Otherwise, the target relaxation hook is called at the end of
1401 // each iteration. If the hook returns true, it means re-layout of
1402 // section is required.
1404 // The number of segments created by a linking script without a PHDRS
1405 // clause may be affected by section sizes and alignments. There is
1406 // a remote chance that relaxation causes different number of PT_LOAD
1407 // segments are created and sections are attached to different segments.
1408 // Therefore, we always throw away all segments created during section
1409 // layout. In order to be able to restart the section layout, we keep
1410 // a copy of the segment list right before the relaxation loop and use
1411 // that to restore the segments.
1413 // PASS is the current relaxation pass number.
1414 // SYMTAB is a symbol table.
1415 // PLOAD_SEG is the address of a pointer for the load segment.
1416 // PHDR_SEG is a pointer to the PHDR segment.
1417 // SEGMENT_HEADERS points to the output segment header.
1418 // FILE_HEADER points to the output file header.
1419 // PSHNDX is the address to store the output section index.
1422 Layout::relaxation_loop_body(
1425 Symbol_table* symtab,
1426 Output_segment** pload_seg,
1427 Output_segment* phdr_seg,
1428 Output_segment_headers* segment_headers,
1429 Output_file_header* file_header,
1430 unsigned int* pshndx)
1432 // If this is not the first iteration, we need to clean up after
1433 // relaxation so that we can lay out the sections again.
1435 this->clean_up_after_relaxation();
1437 // If there is a SECTIONS clause, put all the input sections into
1438 // the required order.
1439 Output_segment* load_seg;
1440 if (this->script_options_->saw_sections_clause())
1441 load_seg = this->set_section_addresses_from_script(symtab);
1442 else if (parameters->options().relocatable())
1445 load_seg = this->find_first_load_seg();
1447 if (parameters->options().oformat_enum()
1448 != General_options::OBJECT_FORMAT_ELF)
1451 gold_assert(phdr_seg == NULL
1453 || this->script_options_->saw_sections_clause());
1455 // Lay out the segment headers.
1456 if (!parameters->options().relocatable())
1458 gold_assert(segment_headers != NULL);
1459 if (load_seg != NULL)
1460 load_seg->add_initial_output_data(segment_headers);
1461 if (phdr_seg != NULL)
1462 phdr_seg->add_initial_output_data(segment_headers);
1465 // Lay out the file header.
1466 if (load_seg != NULL)
1467 load_seg->add_initial_output_data(file_header);
1469 if (this->script_options_->saw_phdrs_clause()
1470 && !parameters->options().relocatable())
1472 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1473 // clause in a linker script.
1474 Script_sections* ss = this->script_options_->script_sections();
1475 ss->put_headers_in_phdrs(file_header, segment_headers);
1478 // We set the output section indexes in set_segment_offsets and
1479 // set_section_indexes.
1482 // Set the file offsets of all the segments, and all the sections
1485 if (!parameters->options().relocatable())
1486 off = this->set_segment_offsets(target, load_seg, pshndx);
1488 off = this->set_relocatable_section_offsets(file_header, pshndx);
1490 // Verify that the dummy relaxation does not change anything.
1491 if (is_debugging_enabled(DEBUG_RELAXATION))
1494 this->relaxation_debug_check_->read_sections(this->section_list_);
1496 this->relaxation_debug_check_->verify_sections(this->section_list_);
1499 *pload_seg = load_seg;
1503 // Finalize the layout. When this is called, we have created all the
1504 // output sections and all the output segments which are based on
1505 // input sections. We have several things to do, and we have to do
1506 // them in the right order, so that we get the right results correctly
1509 // 1) Finalize the list of output segments and create the segment
1512 // 2) Finalize the dynamic symbol table and associated sections.
1514 // 3) Determine the final file offset of all the output segments.
1516 // 4) Determine the final file offset of all the SHF_ALLOC output
1519 // 5) Create the symbol table sections and the section name table
1522 // 6) Finalize the symbol table: set symbol values to their final
1523 // value and make a final determination of which symbols are going
1524 // into the output symbol table.
1526 // 7) Create the section table header.
1528 // 8) Determine the final file offset of all the output sections which
1529 // are not SHF_ALLOC, including the section table header.
1531 // 9) Finalize the ELF file header.
1533 // This function returns the size of the output file.
1536 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1537 Target* target, const Task* task)
1539 target->finalize_sections(this, input_objects, symtab);
1541 this->count_local_symbols(task, input_objects);
1543 this->link_stabs_sections();
1545 Output_segment* phdr_seg = NULL;
1546 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1548 // There was a dynamic object in the link. We need to create
1549 // some information for the dynamic linker.
1551 // Create the PT_PHDR segment which will hold the program
1553 if (!this->script_options_->saw_phdrs_clause())
1554 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1556 // Create the dynamic symbol table, including the hash table.
1557 Output_section* dynstr;
1558 std::vector<Symbol*> dynamic_symbols;
1559 unsigned int local_dynamic_count;
1560 Versions versions(*this->script_options()->version_script_info(),
1562 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1563 &local_dynamic_count, &dynamic_symbols,
1566 // Create the .interp section to hold the name of the
1567 // interpreter, and put it in a PT_INTERP segment.
1568 if (!parameters->options().shared())
1569 this->create_interp(target);
1571 // Finish the .dynamic section to hold the dynamic data, and put
1572 // it in a PT_DYNAMIC segment.
1573 this->finish_dynamic_section(input_objects, symtab);
1575 // We should have added everything we need to the dynamic string
1577 this->dynpool_.set_string_offsets();
1579 // Create the version sections. We can't do this until the
1580 // dynamic string table is complete.
1581 this->create_version_sections(&versions, symtab, local_dynamic_count,
1582 dynamic_symbols, dynstr);
1585 if (this->incremental_inputs_)
1587 this->incremental_inputs_->finalize();
1588 this->create_incremental_info_sections();
1591 // Create segment headers.
1592 Output_segment_headers* segment_headers =
1593 (parameters->options().relocatable()
1595 : new Output_segment_headers(this->segment_list_));
1597 // Lay out the file header.
1598 Output_file_header* file_header
1599 = new Output_file_header(target, symtab, segment_headers,
1600 parameters->options().entry());
1602 this->special_output_list_.push_back(file_header);
1603 if (segment_headers != NULL)
1604 this->special_output_list_.push_back(segment_headers);
1606 // Find approriate places for orphan output sections if we are using
1608 if (this->script_options_->saw_sections_clause())
1609 this->place_orphan_sections_in_script();
1611 Output_segment* load_seg;
1616 // Take a snapshot of the section layout as needed.
1617 if (target->may_relax())
1618 this->prepare_for_relaxation();
1620 // Run the relaxation loop to lay out sections.
1623 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1624 phdr_seg, segment_headers, file_header,
1628 while (target->may_relax()
1629 && target->relax(pass, input_objects, symtab, this));
1631 // Set the file offsets of all the non-data sections we've seen so
1632 // far which don't have to wait for the input sections. We need
1633 // this in order to finalize local symbols in non-allocated
1635 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1637 // Set the section indexes of all unallocated sections seen so far,
1638 // in case any of them are somehow referenced by a symbol.
1639 shndx = this->set_section_indexes(shndx);
1641 // Create the symbol table sections.
1642 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1643 if (!parameters->doing_static_link())
1644 this->assign_local_dynsym_offsets(input_objects);
1646 // Process any symbol assignments from a linker script. This must
1647 // be called after the symbol table has been finalized.
1648 this->script_options_->finalize_symbols(symtab, this);
1650 // Create the .shstrtab section.
1651 Output_section* shstrtab_section = this->create_shstrtab();
1653 // Set the file offsets of the rest of the non-data sections which
1654 // don't have to wait for the input sections.
1655 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1657 // Now that all sections have been created, set the section indexes
1658 // for any sections which haven't been done yet.
1659 shndx = this->set_section_indexes(shndx);
1661 // Create the section table header.
1662 this->create_shdrs(shstrtab_section, &off);
1664 // If there are no sections which require postprocessing, we can
1665 // handle the section names now, and avoid a resize later.
1666 if (!this->any_postprocessing_sections_)
1667 off = this->set_section_offsets(off,
1668 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1670 file_header->set_section_info(this->section_headers_, shstrtab_section);
1672 // Now we know exactly where everything goes in the output file
1673 // (except for non-allocated sections which require postprocessing).
1674 Output_data::layout_complete();
1676 this->output_file_size_ = off;
1681 // Create a note header following the format defined in the ELF ABI.
1682 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1683 // of the section to create, DESCSZ is the size of the descriptor.
1684 // ALLOCATE is true if the section should be allocated in memory.
1685 // This returns the new note section. It sets *TRAILING_PADDING to
1686 // the number of trailing zero bytes required.
1689 Layout::create_note(const char* name, int note_type,
1690 const char* section_name, size_t descsz,
1691 bool allocate, size_t* trailing_padding)
1693 // Authorities all agree that the values in a .note field should
1694 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1695 // they differ on what the alignment is for 64-bit binaries.
1696 // The GABI says unambiguously they take 8-byte alignment:
1697 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1698 // Other documentation says alignment should always be 4 bytes:
1699 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1700 // GNU ld and GNU readelf both support the latter (at least as of
1701 // version 2.16.91), and glibc always generates the latter for
1702 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1704 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1705 const int size = parameters->target().get_size();
1707 const int size = 32;
1710 // The contents of the .note section.
1711 size_t namesz = strlen(name) + 1;
1712 size_t aligned_namesz = align_address(namesz, size / 8);
1713 size_t aligned_descsz = align_address(descsz, size / 8);
1715 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1717 unsigned char* buffer = new unsigned char[notehdrsz];
1718 memset(buffer, 0, notehdrsz);
1720 bool is_big_endian = parameters->target().is_big_endian();
1726 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1727 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1728 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1732 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1733 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1734 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1737 else if (size == 64)
1741 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1742 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1743 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1747 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1748 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1749 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1755 memcpy(buffer + 3 * (size / 8), name, namesz);
1757 elfcpp::Elf_Xword flags = 0;
1759 flags = elfcpp::SHF_ALLOC;
1760 Output_section* os = this->choose_output_section(NULL, section_name,
1762 flags, false, false,
1767 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1770 os->add_output_section_data(posd);
1772 *trailing_padding = aligned_descsz - descsz;
1777 // For an executable or shared library, create a note to record the
1778 // version of gold used to create the binary.
1781 Layout::create_gold_note()
1783 if (parameters->options().relocatable())
1786 std::string desc = std::string("gold ") + gold::get_version_string();
1788 size_t trailing_padding;
1789 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1790 ".note.gnu.gold-version", desc.size(),
1791 false, &trailing_padding);
1795 Output_section_data* posd = new Output_data_const(desc, 4);
1796 os->add_output_section_data(posd);
1798 if (trailing_padding > 0)
1800 posd = new Output_data_zero_fill(trailing_padding, 0);
1801 os->add_output_section_data(posd);
1805 // Record whether the stack should be executable. This can be set
1806 // from the command line using the -z execstack or -z noexecstack
1807 // options. Otherwise, if any input file has a .note.GNU-stack
1808 // section with the SHF_EXECINSTR flag set, the stack should be
1809 // executable. Otherwise, if at least one input file a
1810 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1811 // section, we use the target default for whether the stack should be
1812 // executable. Otherwise, we don't generate a stack note. When
1813 // generating a object file, we create a .note.GNU-stack section with
1814 // the appropriate marking. When generating an executable or shared
1815 // library, we create a PT_GNU_STACK segment.
1818 Layout::create_executable_stack_info()
1820 bool is_stack_executable;
1821 if (parameters->options().is_execstack_set())
1822 is_stack_executable = parameters->options().is_stack_executable();
1823 else if (!this->input_with_gnu_stack_note_)
1827 if (this->input_requires_executable_stack_)
1828 is_stack_executable = true;
1829 else if (this->input_without_gnu_stack_note_)
1830 is_stack_executable =
1831 parameters->target().is_default_stack_executable();
1833 is_stack_executable = false;
1836 if (parameters->options().relocatable())
1838 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1839 elfcpp::Elf_Xword flags = 0;
1840 if (is_stack_executable)
1841 flags |= elfcpp::SHF_EXECINSTR;
1842 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags, false,
1847 if (this->script_options_->saw_phdrs_clause())
1849 int flags = elfcpp::PF_R | elfcpp::PF_W;
1850 if (is_stack_executable)
1851 flags |= elfcpp::PF_X;
1852 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1856 // If --build-id was used, set up the build ID note.
1859 Layout::create_build_id()
1861 if (!parameters->options().user_set_build_id())
1864 const char* style = parameters->options().build_id();
1865 if (strcmp(style, "none") == 0)
1868 // Set DESCSZ to the size of the note descriptor. When possible,
1869 // set DESC to the note descriptor contents.
1872 if (strcmp(style, "md5") == 0)
1874 else if (strcmp(style, "sha1") == 0)
1876 else if (strcmp(style, "uuid") == 0)
1878 const size_t uuidsz = 128 / 8;
1880 char buffer[uuidsz];
1881 memset(buffer, 0, uuidsz);
1883 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
1885 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1889 ssize_t got = ::read(descriptor, buffer, uuidsz);
1890 release_descriptor(descriptor, true);
1892 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1893 else if (static_cast<size_t>(got) != uuidsz)
1894 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1898 desc.assign(buffer, uuidsz);
1901 else if (strncmp(style, "0x", 2) == 0)
1904 const char* p = style + 2;
1907 if (hex_p(p[0]) && hex_p(p[1]))
1909 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1913 else if (*p == '-' || *p == ':')
1916 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1919 descsz = desc.size();
1922 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1925 size_t trailing_padding;
1926 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1927 ".note.gnu.build-id", descsz, true,
1934 // We know the value already, so we fill it in now.
1935 gold_assert(desc.size() == descsz);
1937 Output_section_data* posd = new Output_data_const(desc, 4);
1938 os->add_output_section_data(posd);
1940 if (trailing_padding != 0)
1942 posd = new Output_data_zero_fill(trailing_padding, 0);
1943 os->add_output_section_data(posd);
1948 // We need to compute a checksum after we have completed the
1950 gold_assert(trailing_padding == 0);
1951 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
1952 os->add_output_section_data(this->build_id_note_);
1956 // If we have both .stabXX and .stabXXstr sections, then the sh_link
1957 // field of the former should point to the latter. I'm not sure who
1958 // started this, but the GNU linker does it, and some tools depend
1962 Layout::link_stabs_sections()
1964 if (!this->have_stabstr_section_)
1967 for (Section_list::iterator p = this->section_list_.begin();
1968 p != this->section_list_.end();
1971 if ((*p)->type() != elfcpp::SHT_STRTAB)
1974 const char* name = (*p)->name();
1975 if (strncmp(name, ".stab", 5) != 0)
1978 size_t len = strlen(name);
1979 if (strcmp(name + len - 3, "str") != 0)
1982 std::string stab_name(name, len - 3);
1983 Output_section* stab_sec;
1984 stab_sec = this->find_output_section(stab_name.c_str());
1985 if (stab_sec != NULL)
1986 stab_sec->set_link_section(*p);
1990 // Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
1991 // for the next run of incremental linking to check what has changed.
1994 Layout::create_incremental_info_sections()
1996 gold_assert(this->incremental_inputs_ != NULL);
1998 // Add the .gnu_incremental_inputs section.
1999 const char *incremental_inputs_name =
2000 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
2001 Output_section* inputs_os =
2002 this->make_output_section(incremental_inputs_name,
2003 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2005 Output_section_data* posd =
2006 this->incremental_inputs_->create_incremental_inputs_section_data();
2007 inputs_os->add_output_section_data(posd);
2009 // Add the .gnu_incremental_strtab section.
2010 const char *incremental_strtab_name =
2011 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2012 Output_section* strtab_os = this->make_output_section(incremental_strtab_name,
2015 Output_data_strtab* strtab_data =
2016 new Output_data_strtab(this->incremental_inputs_->get_stringpool());
2017 strtab_os->add_output_section_data(strtab_data);
2019 inputs_os->set_link_section(strtab_data);
2022 // Return whether SEG1 should be before SEG2 in the output file. This
2023 // is based entirely on the segment type and flags. When this is
2024 // called the segment addresses has normally not yet been set.
2027 Layout::segment_precedes(const Output_segment* seg1,
2028 const Output_segment* seg2)
2030 elfcpp::Elf_Word type1 = seg1->type();
2031 elfcpp::Elf_Word type2 = seg2->type();
2033 // The single PT_PHDR segment is required to precede any loadable
2034 // segment. We simply make it always first.
2035 if (type1 == elfcpp::PT_PHDR)
2037 gold_assert(type2 != elfcpp::PT_PHDR);
2040 if (type2 == elfcpp::PT_PHDR)
2043 // The single PT_INTERP segment is required to precede any loadable
2044 // segment. We simply make it always second.
2045 if (type1 == elfcpp::PT_INTERP)
2047 gold_assert(type2 != elfcpp::PT_INTERP);
2050 if (type2 == elfcpp::PT_INTERP)
2053 // We then put PT_LOAD segments before any other segments.
2054 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2056 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2059 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2060 // segment, because that is where the dynamic linker expects to find
2061 // it (this is just for efficiency; other positions would also work
2063 if (type1 == elfcpp::PT_TLS
2064 && type2 != elfcpp::PT_TLS
2065 && type2 != elfcpp::PT_GNU_RELRO)
2067 if (type2 == elfcpp::PT_TLS
2068 && type1 != elfcpp::PT_TLS
2069 && type1 != elfcpp::PT_GNU_RELRO)
2072 // We put the PT_GNU_RELRO segment last, because that is where the
2073 // dynamic linker expects to find it (as with PT_TLS, this is just
2075 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2077 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2080 const elfcpp::Elf_Word flags1 = seg1->flags();
2081 const elfcpp::Elf_Word flags2 = seg2->flags();
2083 // The order of non-PT_LOAD segments is unimportant. We simply sort
2084 // by the numeric segment type and flags values. There should not
2085 // be more than one segment with the same type and flags.
2086 if (type1 != elfcpp::PT_LOAD)
2089 return type1 < type2;
2090 gold_assert(flags1 != flags2);
2091 return flags1 < flags2;
2094 // If the addresses are set already, sort by load address.
2095 if (seg1->are_addresses_set())
2097 if (!seg2->are_addresses_set())
2100 unsigned int section_count1 = seg1->output_section_count();
2101 unsigned int section_count2 = seg2->output_section_count();
2102 if (section_count1 == 0 && section_count2 > 0)
2104 if (section_count1 > 0 && section_count2 == 0)
2107 uint64_t paddr1 = seg1->first_section_load_address();
2108 uint64_t paddr2 = seg2->first_section_load_address();
2109 if (paddr1 != paddr2)
2110 return paddr1 < paddr2;
2112 else if (seg2->are_addresses_set())
2115 // A segment which holds large data comes after a segment which does
2116 // not hold large data.
2117 if (seg1->is_large_data_segment())
2119 if (!seg2->is_large_data_segment())
2122 else if (seg2->is_large_data_segment())
2125 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2126 // segments come before writable segments. Then writable segments
2127 // with data come before writable segments without data. Then
2128 // executable segments come before non-executable segments. Then
2129 // the unlikely case of a non-readable segment comes before the
2130 // normal case of a readable segment. If there are multiple
2131 // segments with the same type and flags, we require that the
2132 // address be set, and we sort by virtual address and then physical
2134 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2135 return (flags1 & elfcpp::PF_W) == 0;
2136 if ((flags1 & elfcpp::PF_W) != 0
2137 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2138 return seg1->has_any_data_sections();
2139 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2140 return (flags1 & elfcpp::PF_X) != 0;
2141 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2142 return (flags1 & elfcpp::PF_R) == 0;
2144 // We shouldn't get here--we shouldn't create segments which we
2145 // can't distinguish.
2149 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2152 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2154 uint64_t unsigned_off = off;
2155 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2156 | (addr & (abi_pagesize - 1)));
2157 if (aligned_off < unsigned_off)
2158 aligned_off += abi_pagesize;
2162 // Set the file offsets of all the segments, and all the sections they
2163 // contain. They have all been created. LOAD_SEG must be be laid out
2164 // first. Return the offset of the data to follow.
2167 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2168 unsigned int *pshndx)
2170 // Sort them into the final order.
2171 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2172 Layout::Compare_segments());
2174 // Find the PT_LOAD segments, and set their addresses and offsets
2175 // and their section's addresses and offsets.
2177 if (parameters->options().user_set_Ttext())
2178 addr = parameters->options().Ttext();
2179 else if (parameters->options().output_is_position_independent())
2182 addr = target->default_text_segment_address();
2185 // If LOAD_SEG is NULL, then the file header and segment headers
2186 // will not be loadable. But they still need to be at offset 0 in
2187 // the file. Set their offsets now.
2188 if (load_seg == NULL)
2190 for (Data_list::iterator p = this->special_output_list_.begin();
2191 p != this->special_output_list_.end();
2194 off = align_address(off, (*p)->addralign());
2195 (*p)->set_address_and_file_offset(0, off);
2196 off += (*p)->data_size();
2200 const bool check_sections = parameters->options().check_sections();
2201 Output_segment* last_load_segment = NULL;
2203 bool was_readonly = false;
2204 for (Segment_list::iterator p = this->segment_list_.begin();
2205 p != this->segment_list_.end();
2208 if ((*p)->type() == elfcpp::PT_LOAD)
2210 if (load_seg != NULL && load_seg != *p)
2214 bool are_addresses_set = (*p)->are_addresses_set();
2215 if (are_addresses_set)
2217 // When it comes to setting file offsets, we care about
2218 // the physical address.
2219 addr = (*p)->paddr();
2221 else if (parameters->options().user_set_Tdata()
2222 && ((*p)->flags() & elfcpp::PF_W) != 0
2223 && (!parameters->options().user_set_Tbss()
2224 || (*p)->has_any_data_sections()))
2226 addr = parameters->options().Tdata();
2227 are_addresses_set = true;
2229 else if (parameters->options().user_set_Tbss()
2230 && ((*p)->flags() & elfcpp::PF_W) != 0
2231 && !(*p)->has_any_data_sections())
2233 addr = parameters->options().Tbss();
2234 are_addresses_set = true;
2237 uint64_t orig_addr = addr;
2238 uint64_t orig_off = off;
2240 uint64_t aligned_addr = 0;
2241 uint64_t abi_pagesize = target->abi_pagesize();
2242 uint64_t common_pagesize = target->common_pagesize();
2244 if (!parameters->options().nmagic()
2245 && !parameters->options().omagic())
2246 (*p)->set_minimum_p_align(common_pagesize);
2248 if (!are_addresses_set)
2250 // If the last segment was readonly, and this one is
2251 // not, then skip the address forward one page,
2252 // maintaining the same position within the page. This
2253 // lets us store both segments overlapping on a single
2254 // page in the file, but the loader will put them on
2255 // different pages in memory.
2257 addr = align_address(addr, (*p)->maximum_alignment());
2258 aligned_addr = addr;
2260 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2262 if ((addr & (abi_pagesize - 1)) != 0)
2263 addr = addr + abi_pagesize;
2266 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2269 if (!parameters->options().nmagic()
2270 && !parameters->options().omagic())
2271 off = align_file_offset(off, addr, abi_pagesize);
2272 else if (load_seg == NULL)
2274 // This is -N or -n with a section script which prevents
2275 // us from using a load segment. We need to ensure that
2276 // the file offset is aligned to the alignment of the
2277 // segment. This is because the linker script
2278 // implicitly assumed a zero offset. If we don't align
2279 // here, then the alignment of the sections in the
2280 // linker script may not match the alignment of the
2281 // sections in the set_section_addresses call below,
2282 // causing an error about dot moving backward.
2283 off = align_address(off, (*p)->maximum_alignment());
2286 unsigned int shndx_hold = *pshndx;
2287 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2290 // Now that we know the size of this segment, we may be able
2291 // to save a page in memory, at the cost of wasting some
2292 // file space, by instead aligning to the start of a new
2293 // page. Here we use the real machine page size rather than
2294 // the ABI mandated page size.
2296 if (!are_addresses_set && aligned_addr != addr)
2298 uint64_t first_off = (common_pagesize
2300 & (common_pagesize - 1)));
2301 uint64_t last_off = new_addr & (common_pagesize - 1);
2304 && ((aligned_addr & ~ (common_pagesize - 1))
2305 != (new_addr & ~ (common_pagesize - 1)))
2306 && first_off + last_off <= common_pagesize)
2308 *pshndx = shndx_hold;
2309 addr = align_address(aligned_addr, common_pagesize);
2310 addr = align_address(addr, (*p)->maximum_alignment());
2311 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2312 off = align_file_offset(off, addr, abi_pagesize);
2313 new_addr = (*p)->set_section_addresses(this, true, addr,
2320 if (((*p)->flags() & elfcpp::PF_W) == 0)
2321 was_readonly = true;
2323 // Implement --check-sections. We know that the segments
2324 // are sorted by LMA.
2325 if (check_sections && last_load_segment != NULL)
2327 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2328 if (last_load_segment->paddr() + last_load_segment->memsz()
2331 unsigned long long lb1 = last_load_segment->paddr();
2332 unsigned long long le1 = lb1 + last_load_segment->memsz();
2333 unsigned long long lb2 = (*p)->paddr();
2334 unsigned long long le2 = lb2 + (*p)->memsz();
2335 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2336 "[0x%llx -> 0x%llx]"),
2337 lb1, le1, lb2, le2);
2340 last_load_segment = *p;
2344 // Handle the non-PT_LOAD segments, setting their offsets from their
2345 // section's offsets.
2346 for (Segment_list::iterator p = this->segment_list_.begin();
2347 p != this->segment_list_.end();
2350 if ((*p)->type() != elfcpp::PT_LOAD)
2354 // Set the TLS offsets for each section in the PT_TLS segment.
2355 if (this->tls_segment_ != NULL)
2356 this->tls_segment_->set_tls_offsets();
2361 // Set the offsets of all the allocated sections when doing a
2362 // relocatable link. This does the same jobs as set_segment_offsets,
2363 // only for a relocatable link.
2366 Layout::set_relocatable_section_offsets(Output_data* file_header,
2367 unsigned int *pshndx)
2371 file_header->set_address_and_file_offset(0, 0);
2372 off += file_header->data_size();
2374 for (Section_list::iterator p = this->section_list_.begin();
2375 p != this->section_list_.end();
2378 // We skip unallocated sections here, except that group sections
2379 // have to come first.
2380 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2381 && (*p)->type() != elfcpp::SHT_GROUP)
2384 off = align_address(off, (*p)->addralign());
2386 // The linker script might have set the address.
2387 if (!(*p)->is_address_valid())
2388 (*p)->set_address(0);
2389 (*p)->set_file_offset(off);
2390 (*p)->finalize_data_size();
2391 off += (*p)->data_size();
2393 (*p)->set_out_shndx(*pshndx);
2400 // Set the file offset of all the sections not associated with a
2404 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2406 for (Section_list::iterator p = this->unattached_section_list_.begin();
2407 p != this->unattached_section_list_.end();
2410 // The symtab section is handled in create_symtab_sections.
2411 if (*p == this->symtab_section_)
2414 // If we've already set the data size, don't set it again.
2415 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2418 if (pass == BEFORE_INPUT_SECTIONS_PASS
2419 && (*p)->requires_postprocessing())
2421 (*p)->create_postprocessing_buffer();
2422 this->any_postprocessing_sections_ = true;
2425 if (pass == BEFORE_INPUT_SECTIONS_PASS
2426 && (*p)->after_input_sections())
2428 else if (pass == POSTPROCESSING_SECTIONS_PASS
2429 && (!(*p)->after_input_sections()
2430 || (*p)->type() == elfcpp::SHT_STRTAB))
2432 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2433 && (!(*p)->after_input_sections()
2434 || (*p)->type() != elfcpp::SHT_STRTAB))
2437 off = align_address(off, (*p)->addralign());
2438 (*p)->set_file_offset(off);
2439 (*p)->finalize_data_size();
2440 off += (*p)->data_size();
2442 // At this point the name must be set.
2443 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2444 this->namepool_.add((*p)->name(), false, NULL);
2449 // Set the section indexes of all the sections not associated with a
2453 Layout::set_section_indexes(unsigned int shndx)
2455 for (Section_list::iterator p = this->unattached_section_list_.begin();
2456 p != this->unattached_section_list_.end();
2459 if (!(*p)->has_out_shndx())
2461 (*p)->set_out_shndx(shndx);
2468 // Set the section addresses according to the linker script. This is
2469 // only called when we see a SECTIONS clause. This returns the
2470 // program segment which should hold the file header and segment
2471 // headers, if any. It will return NULL if they should not be in a
2475 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2477 Script_sections* ss = this->script_options_->script_sections();
2478 gold_assert(ss->saw_sections_clause());
2479 return this->script_options_->set_section_addresses(symtab, this);
2482 // Place the orphan sections in the linker script.
2485 Layout::place_orphan_sections_in_script()
2487 Script_sections* ss = this->script_options_->script_sections();
2488 gold_assert(ss->saw_sections_clause());
2490 // Place each orphaned output section in the script.
2491 for (Section_list::iterator p = this->section_list_.begin();
2492 p != this->section_list_.end();
2495 if (!(*p)->found_in_sections_clause())
2496 ss->place_orphan(*p);
2500 // Count the local symbols in the regular symbol table and the dynamic
2501 // symbol table, and build the respective string pools.
2504 Layout::count_local_symbols(const Task* task,
2505 const Input_objects* input_objects)
2507 // First, figure out an upper bound on the number of symbols we'll
2508 // be inserting into each pool. This helps us create the pools with
2509 // the right size, to avoid unnecessary hashtable resizing.
2510 unsigned int symbol_count = 0;
2511 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2512 p != input_objects->relobj_end();
2514 symbol_count += (*p)->local_symbol_count();
2516 // Go from "upper bound" to "estimate." We overcount for two
2517 // reasons: we double-count symbols that occur in more than one
2518 // object file, and we count symbols that are dropped from the
2519 // output. Add it all together and assume we overcount by 100%.
2522 // We assume all symbols will go into both the sympool and dynpool.
2523 this->sympool_.reserve(symbol_count);
2524 this->dynpool_.reserve(symbol_count);
2526 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2527 p != input_objects->relobj_end();
2530 Task_lock_obj<Object> tlo(task, *p);
2531 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2535 // Create the symbol table sections. Here we also set the final
2536 // values of the symbols. At this point all the loadable sections are
2537 // fully laid out. SHNUM is the number of sections so far.
2540 Layout::create_symtab_sections(const Input_objects* input_objects,
2541 Symbol_table* symtab,
2547 if (parameters->target().get_size() == 32)
2549 symsize = elfcpp::Elf_sizes<32>::sym_size;
2552 else if (parameters->target().get_size() == 64)
2554 symsize = elfcpp::Elf_sizes<64>::sym_size;
2561 off = align_address(off, align);
2562 off_t startoff = off;
2564 // Save space for the dummy symbol at the start of the section. We
2565 // never bother to write this out--it will just be left as zero.
2567 unsigned int local_symbol_index = 1;
2569 // Add STT_SECTION symbols for each Output section which needs one.
2570 for (Section_list::iterator p = this->section_list_.begin();
2571 p != this->section_list_.end();
2574 if (!(*p)->needs_symtab_index())
2575 (*p)->set_symtab_index(-1U);
2578 (*p)->set_symtab_index(local_symbol_index);
2579 ++local_symbol_index;
2584 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2585 p != input_objects->relobj_end();
2588 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2590 off += (index - local_symbol_index) * symsize;
2591 local_symbol_index = index;
2594 unsigned int local_symcount = local_symbol_index;
2595 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
2598 size_t dyn_global_index;
2600 if (this->dynsym_section_ == NULL)
2603 dyn_global_index = 0;
2608 dyn_global_index = this->dynsym_section_->info();
2609 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2610 dynoff = this->dynsym_section_->offset() + locsize;
2611 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2612 gold_assert(static_cast<off_t>(dyncount * symsize)
2613 == this->dynsym_section_->data_size() - locsize);
2616 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2617 &this->sympool_, &local_symcount);
2619 if (!parameters->options().strip_all())
2621 this->sympool_.set_string_offsets();
2623 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2624 Output_section* osymtab = this->make_output_section(symtab_name,
2627 this->symtab_section_ = osymtab;
2629 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2632 osymtab->add_output_section_data(pos);
2634 // We generate a .symtab_shndx section if we have more than
2635 // SHN_LORESERVE sections. Technically it is possible that we
2636 // don't need one, because it is possible that there are no
2637 // symbols in any of sections with indexes larger than
2638 // SHN_LORESERVE. That is probably unusual, though, and it is
2639 // easier to always create one than to compute section indexes
2640 // twice (once here, once when writing out the symbols).
2641 if (shnum >= elfcpp::SHN_LORESERVE)
2643 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2645 Output_section* osymtab_xindex =
2646 this->make_output_section(symtab_xindex_name,
2647 elfcpp::SHT_SYMTAB_SHNDX, 0, false,
2650 size_t symcount = (off - startoff) / symsize;
2651 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2653 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2655 osymtab_xindex->set_link_section(osymtab);
2656 osymtab_xindex->set_addralign(4);
2657 osymtab_xindex->set_entsize(4);
2659 osymtab_xindex->set_after_input_sections();
2661 // This tells the driver code to wait until the symbol table
2662 // has written out before writing out the postprocessing
2663 // sections, including the .symtab_shndx section.
2664 this->any_postprocessing_sections_ = true;
2667 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2668 Output_section* ostrtab = this->make_output_section(strtab_name,
2672 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2673 ostrtab->add_output_section_data(pstr);
2675 osymtab->set_file_offset(startoff);
2676 osymtab->finalize_data_size();
2677 osymtab->set_link_section(ostrtab);
2678 osymtab->set_info(local_symcount);
2679 osymtab->set_entsize(symsize);
2685 // Create the .shstrtab section, which holds the names of the
2686 // sections. At the time this is called, we have created all the
2687 // output sections except .shstrtab itself.
2690 Layout::create_shstrtab()
2692 // FIXME: We don't need to create a .shstrtab section if we are
2693 // stripping everything.
2695 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2697 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
2700 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
2702 // We can't write out this section until we've set all the
2703 // section names, and we don't set the names of compressed
2704 // output sections until relocations are complete. FIXME: With
2705 // the current names we use, this is unnecessary.
2706 os->set_after_input_sections();
2709 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2710 os->add_output_section_data(posd);
2715 // Create the section headers. SIZE is 32 or 64. OFF is the file
2719 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2721 Output_section_headers* oshdrs;
2722 oshdrs = new Output_section_headers(this,
2723 &this->segment_list_,
2724 &this->section_list_,
2725 &this->unattached_section_list_,
2728 off_t off = align_address(*poff, oshdrs->addralign());
2729 oshdrs->set_address_and_file_offset(0, off);
2730 off += oshdrs->data_size();
2732 this->section_headers_ = oshdrs;
2735 // Count the allocated sections.
2738 Layout::allocated_output_section_count() const
2740 size_t section_count = 0;
2741 for (Segment_list::const_iterator p = this->segment_list_.begin();
2742 p != this->segment_list_.end();
2744 section_count += (*p)->output_section_count();
2745 return section_count;
2748 // Create the dynamic symbol table.
2751 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2752 Symbol_table* symtab,
2753 Output_section **pdynstr,
2754 unsigned int* plocal_dynamic_count,
2755 std::vector<Symbol*>* pdynamic_symbols,
2756 Versions* pversions)
2758 // Count all the symbols in the dynamic symbol table, and set the
2759 // dynamic symbol indexes.
2761 // Skip symbol 0, which is always all zeroes.
2762 unsigned int index = 1;
2764 // Add STT_SECTION symbols for each Output section which needs one.
2765 for (Section_list::iterator p = this->section_list_.begin();
2766 p != this->section_list_.end();
2769 if (!(*p)->needs_dynsym_index())
2770 (*p)->set_dynsym_index(-1U);
2773 (*p)->set_dynsym_index(index);
2778 // Count the local symbols that need to go in the dynamic symbol table,
2779 // and set the dynamic symbol indexes.
2780 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2781 p != input_objects->relobj_end();
2784 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2788 unsigned int local_symcount = index;
2789 *plocal_dynamic_count = local_symcount;
2791 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2792 &this->dynpool_, pversions);
2796 const int size = parameters->target().get_size();
2799 symsize = elfcpp::Elf_sizes<32>::sym_size;
2802 else if (size == 64)
2804 symsize = elfcpp::Elf_sizes<64>::sym_size;
2810 // Create the dynamic symbol table section.
2812 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2815 false, false, true);
2817 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2820 dynsym->add_output_section_data(odata);
2822 dynsym->set_info(local_symcount);
2823 dynsym->set_entsize(symsize);
2824 dynsym->set_addralign(align);
2826 this->dynsym_section_ = dynsym;
2828 Output_data_dynamic* const odyn = this->dynamic_data_;
2829 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2830 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2832 // If there are more than SHN_LORESERVE allocated sections, we
2833 // create a .dynsym_shndx section. It is possible that we don't
2834 // need one, because it is possible that there are no dynamic
2835 // symbols in any of the sections with indexes larger than
2836 // SHN_LORESERVE. This is probably unusual, though, and at this
2837 // time we don't know the actual section indexes so it is
2838 // inconvenient to check.
2839 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2841 Output_section* dynsym_xindex =
2842 this->choose_output_section(NULL, ".dynsym_shndx",
2843 elfcpp::SHT_SYMTAB_SHNDX,
2845 false, false, true);
2847 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2849 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2851 dynsym_xindex->set_link_section(dynsym);
2852 dynsym_xindex->set_addralign(4);
2853 dynsym_xindex->set_entsize(4);
2855 dynsym_xindex->set_after_input_sections();
2857 // This tells the driver code to wait until the symbol table has
2858 // written out before writing out the postprocessing sections,
2859 // including the .dynsym_shndx section.
2860 this->any_postprocessing_sections_ = true;
2863 // Create the dynamic string table section.
2865 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2868 false, false, true);
2870 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2871 dynstr->add_output_section_data(strdata);
2873 dynsym->set_link_section(dynstr);
2874 this->dynamic_section_->set_link_section(dynstr);
2876 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2877 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2881 // Create the hash tables.
2883 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2884 || strcmp(parameters->options().hash_style(), "both") == 0)
2886 unsigned char* phash;
2887 unsigned int hashlen;
2888 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2891 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2894 false, false, true);
2896 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2900 hashsec->add_output_section_data(hashdata);
2902 hashsec->set_link_section(dynsym);
2903 hashsec->set_entsize(4);
2905 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2908 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2909 || strcmp(parameters->options().hash_style(), "both") == 0)
2911 unsigned char* phash;
2912 unsigned int hashlen;
2913 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2916 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2917 elfcpp::SHT_GNU_HASH,
2919 false, false, true);
2921 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2925 hashsec->add_output_section_data(hashdata);
2927 hashsec->set_link_section(dynsym);
2928 hashsec->set_entsize(4);
2930 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2934 // Assign offsets to each local portion of the dynamic symbol table.
2937 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2939 Output_section* dynsym = this->dynsym_section_;
2940 gold_assert(dynsym != NULL);
2942 off_t off = dynsym->offset();
2944 // Skip the dummy symbol at the start of the section.
2945 off += dynsym->entsize();
2947 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2948 p != input_objects->relobj_end();
2951 unsigned int count = (*p)->set_local_dynsym_offset(off);
2952 off += count * dynsym->entsize();
2956 // Create the version sections.
2959 Layout::create_version_sections(const Versions* versions,
2960 const Symbol_table* symtab,
2961 unsigned int local_symcount,
2962 const std::vector<Symbol*>& dynamic_symbols,
2963 const Output_section* dynstr)
2965 if (!versions->any_defs() && !versions->any_needs())
2968 switch (parameters->size_and_endianness())
2970 #ifdef HAVE_TARGET_32_LITTLE
2971 case Parameters::TARGET_32_LITTLE:
2972 this->sized_create_version_sections<32, false>(versions, symtab,
2974 dynamic_symbols, dynstr);
2977 #ifdef HAVE_TARGET_32_BIG
2978 case Parameters::TARGET_32_BIG:
2979 this->sized_create_version_sections<32, true>(versions, symtab,
2981 dynamic_symbols, dynstr);
2984 #ifdef HAVE_TARGET_64_LITTLE
2985 case Parameters::TARGET_64_LITTLE:
2986 this->sized_create_version_sections<64, false>(versions, symtab,
2988 dynamic_symbols, dynstr);
2991 #ifdef HAVE_TARGET_64_BIG
2992 case Parameters::TARGET_64_BIG:
2993 this->sized_create_version_sections<64, true>(versions, symtab,
2995 dynamic_symbols, dynstr);
3003 // Create the version sections, sized version.
3005 template<int size, bool big_endian>
3007 Layout::sized_create_version_sections(
3008 const Versions* versions,
3009 const Symbol_table* symtab,
3010 unsigned int local_symcount,
3011 const std::vector<Symbol*>& dynamic_symbols,
3012 const Output_section* dynstr)
3014 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3015 elfcpp::SHT_GNU_versym,
3017 false, false, true);
3019 unsigned char* vbuf;
3021 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3026 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3029 vsec->add_output_section_data(vdata);
3030 vsec->set_entsize(2);
3031 vsec->set_link_section(this->dynsym_section_);
3033 Output_data_dynamic* const odyn = this->dynamic_data_;
3034 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3036 if (versions->any_defs())
3038 Output_section* vdsec;
3039 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3040 elfcpp::SHT_GNU_verdef,
3042 false, false, true);
3044 unsigned char* vdbuf;
3045 unsigned int vdsize;
3046 unsigned int vdentries;
3047 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3048 &vdsize, &vdentries);
3050 Output_section_data* vddata =
3051 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3053 vdsec->add_output_section_data(vddata);
3054 vdsec->set_link_section(dynstr);
3055 vdsec->set_info(vdentries);
3057 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3058 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3061 if (versions->any_needs())
3063 Output_section* vnsec;
3064 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3065 elfcpp::SHT_GNU_verneed,
3067 false, false, true);
3069 unsigned char* vnbuf;
3070 unsigned int vnsize;
3071 unsigned int vnentries;
3072 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3076 Output_section_data* vndata =
3077 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3079 vnsec->add_output_section_data(vndata);
3080 vnsec->set_link_section(dynstr);
3081 vnsec->set_info(vnentries);
3083 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3084 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3088 // Create the .interp section and PT_INTERP segment.
3091 Layout::create_interp(const Target* target)
3093 const char* interp = parameters->options().dynamic_linker();
3096 interp = target->dynamic_linker();
3097 gold_assert(interp != NULL);
3100 size_t len = strlen(interp) + 1;
3102 Output_section_data* odata = new Output_data_const(interp, len, 1);
3104 Output_section* osec = this->choose_output_section(NULL, ".interp",
3105 elfcpp::SHT_PROGBITS,
3108 osec->add_output_section_data(odata);
3110 if (!this->script_options_->saw_phdrs_clause())
3112 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3114 oseg->add_output_section(osec, elfcpp::PF_R, false);
3118 // Finish the .dynamic section and PT_DYNAMIC segment.
3121 Layout::finish_dynamic_section(const Input_objects* input_objects,
3122 const Symbol_table* symtab)
3124 if (!this->script_options_->saw_phdrs_clause())
3126 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3129 oseg->add_output_section(this->dynamic_section_,
3130 elfcpp::PF_R | elfcpp::PF_W,
3134 Output_data_dynamic* const odyn = this->dynamic_data_;
3136 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3137 p != input_objects->dynobj_end();
3140 if (!(*p)->is_needed()
3141 && (*p)->input_file()->options().as_needed())
3143 // This dynamic object was linked with --as-needed, but it
3148 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3151 if (parameters->options().shared())
3153 const char* soname = parameters->options().soname();
3155 odyn->add_string(elfcpp::DT_SONAME, soname);
3158 Symbol* sym = symtab->lookup(parameters->options().init());
3159 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3160 odyn->add_symbol(elfcpp::DT_INIT, sym);
3162 sym = symtab->lookup(parameters->options().fini());
3163 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3164 odyn->add_symbol(elfcpp::DT_FINI, sym);
3166 // Look for .init_array, .preinit_array and .fini_array by checking
3168 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3169 p != this->section_list_.end();
3171 switch((*p)->type())
3173 case elfcpp::SHT_FINI_ARRAY:
3174 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3175 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3177 case elfcpp::SHT_INIT_ARRAY:
3178 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3179 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3181 case elfcpp::SHT_PREINIT_ARRAY:
3182 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3183 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3189 // Add a DT_RPATH entry if needed.
3190 const General_options::Dir_list& rpath(parameters->options().rpath());
3193 std::string rpath_val;
3194 for (General_options::Dir_list::const_iterator p = rpath.begin();
3198 if (rpath_val.empty())
3199 rpath_val = p->name();
3202 // Eliminate duplicates.
3203 General_options::Dir_list::const_iterator q;
3204 for (q = rpath.begin(); q != p; ++q)
3205 if (q->name() == p->name())
3210 rpath_val += p->name();
3215 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3216 if (parameters->options().enable_new_dtags())
3217 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3220 // Look for text segments that have dynamic relocations.
3221 bool have_textrel = false;
3222 if (!this->script_options_->saw_sections_clause())
3224 for (Segment_list::const_iterator p = this->segment_list_.begin();
3225 p != this->segment_list_.end();
3228 if (((*p)->flags() & elfcpp::PF_W) == 0
3229 && (*p)->dynamic_reloc_count() > 0)
3231 have_textrel = true;
3238 // We don't know the section -> segment mapping, so we are
3239 // conservative and just look for readonly sections with
3240 // relocations. If those sections wind up in writable segments,
3241 // then we have created an unnecessary DT_TEXTREL entry.
3242 for (Section_list::const_iterator p = this->section_list_.begin();
3243 p != this->section_list_.end();
3246 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3247 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3248 && ((*p)->dynamic_reloc_count() > 0))
3250 have_textrel = true;
3256 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3257 // post-link tools can easily modify these flags if desired.
3258 unsigned int flags = 0;
3261 // Add a DT_TEXTREL for compatibility with older loaders.
3262 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3263 flags |= elfcpp::DF_TEXTREL;
3265 if (parameters->options().shared() && this->has_static_tls())
3266 flags |= elfcpp::DF_STATIC_TLS;
3267 if (parameters->options().origin())
3268 flags |= elfcpp::DF_ORIGIN;
3269 if (parameters->options().Bsymbolic())
3271 flags |= elfcpp::DF_SYMBOLIC;
3272 // Add DT_SYMBOLIC for compatibility with older loaders.
3273 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3275 if (parameters->options().now())
3276 flags |= elfcpp::DF_BIND_NOW;
3277 odyn->add_constant(elfcpp::DT_FLAGS, flags);
3280 if (parameters->options().initfirst())
3281 flags |= elfcpp::DF_1_INITFIRST;
3282 if (parameters->options().interpose())
3283 flags |= elfcpp::DF_1_INTERPOSE;
3284 if (parameters->options().loadfltr())
3285 flags |= elfcpp::DF_1_LOADFLTR;
3286 if (parameters->options().nodefaultlib())
3287 flags |= elfcpp::DF_1_NODEFLIB;
3288 if (parameters->options().nodelete())
3289 flags |= elfcpp::DF_1_NODELETE;
3290 if (parameters->options().nodlopen())
3291 flags |= elfcpp::DF_1_NOOPEN;
3292 if (parameters->options().nodump())
3293 flags |= elfcpp::DF_1_NODUMP;
3294 if (!parameters->options().shared())
3295 flags &= ~(elfcpp::DF_1_INITFIRST
3296 | elfcpp::DF_1_NODELETE
3297 | elfcpp::DF_1_NOOPEN);
3298 if (parameters->options().origin())
3299 flags |= elfcpp::DF_1_ORIGIN;
3300 if (parameters->options().now())
3301 flags |= elfcpp::DF_1_NOW;
3303 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3306 // The mapping of input section name prefixes to output section names.
3307 // In some cases one prefix is itself a prefix of another prefix; in
3308 // such a case the longer prefix must come first. These prefixes are
3309 // based on the GNU linker default ELF linker script.
3311 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3312 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3314 MAPPING_INIT(".text.", ".text"),
3315 MAPPING_INIT(".ctors.", ".ctors"),
3316 MAPPING_INIT(".dtors.", ".dtors"),
3317 MAPPING_INIT(".rodata.", ".rodata"),
3318 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3319 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3320 MAPPING_INIT(".data.", ".data"),
3321 MAPPING_INIT(".bss.", ".bss"),
3322 MAPPING_INIT(".tdata.", ".tdata"),
3323 MAPPING_INIT(".tbss.", ".tbss"),
3324 MAPPING_INIT(".init_array.", ".init_array"),
3325 MAPPING_INIT(".fini_array.", ".fini_array"),
3326 MAPPING_INIT(".sdata.", ".sdata"),
3327 MAPPING_INIT(".sbss.", ".sbss"),
3328 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3329 // differently depending on whether it is creating a shared library.
3330 MAPPING_INIT(".sdata2.", ".sdata"),
3331 MAPPING_INIT(".sbss2.", ".sbss"),
3332 MAPPING_INIT(".lrodata.", ".lrodata"),
3333 MAPPING_INIT(".ldata.", ".ldata"),
3334 MAPPING_INIT(".lbss.", ".lbss"),
3335 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3336 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3337 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3338 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3339 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3340 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3341 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3342 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3343 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3344 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3345 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3346 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3347 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3348 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3349 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3350 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3351 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3352 MAPPING_INIT(".ARM.extab.", ".ARM.extab"),
3353 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3354 MAPPING_INIT(".ARM.exidx.", ".ARM.exidx"),
3355 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3359 const int Layout::section_name_mapping_count =
3360 (sizeof(Layout::section_name_mapping)
3361 / sizeof(Layout::section_name_mapping[0]));
3363 // Choose the output section name to use given an input section name.
3364 // Set *PLEN to the length of the name. *PLEN is initialized to the
3368 Layout::output_section_name(const char* name, size_t* plen)
3370 // gcc 4.3 generates the following sorts of section names when it
3371 // needs a section name specific to a function:
3377 // .data.rel.local.FN
3379 // .data.rel.ro.local.FN
3386 // The GNU linker maps all of those to the part before the .FN,
3387 // except that .data.rel.local.FN is mapped to .data, and
3388 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3389 // beginning with .data.rel.ro.local are grouped together.
3391 // For an anonymous namespace, the string FN can contain a '.'.
3393 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3394 // GNU linker maps to .rodata.
3396 // The .data.rel.ro sections are used with -z relro. The sections
3397 // are recognized by name. We use the same names that the GNU
3398 // linker does for these sections.
3400 // It is hard to handle this in a principled way, so we don't even
3401 // try. We use a table of mappings. If the input section name is
3402 // not found in the table, we simply use it as the output section
3405 const Section_name_mapping* psnm = section_name_mapping;
3406 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3408 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3410 *plen = psnm->tolen;
3418 // Check if a comdat group or .gnu.linkonce section with the given
3419 // NAME is selected for the link. If there is already a section,
3420 // *KEPT_SECTION is set to point to the existing section and the
3421 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3422 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3423 // *KEPT_SECTION is set to the internal copy and the function returns
3427 Layout::find_or_add_kept_section(const std::string& name,
3432 Kept_section** kept_section)
3434 // It's normal to see a couple of entries here, for the x86 thunk
3435 // sections. If we see more than a few, we're linking a C++
3436 // program, and we resize to get more space to minimize rehashing.
3437 if (this->signatures_.size() > 4
3438 && !this->resized_signatures_)
3440 reserve_unordered_map(&this->signatures_,
3441 this->number_of_input_files_ * 64);
3442 this->resized_signatures_ = true;
3445 Kept_section candidate;
3446 std::pair<Signatures::iterator, bool> ins =
3447 this->signatures_.insert(std::make_pair(name, candidate));
3449 if (kept_section != NULL)
3450 *kept_section = &ins.first->second;
3453 // This is the first time we've seen this signature.
3454 ins.first->second.set_object(object);
3455 ins.first->second.set_shndx(shndx);
3457 ins.first->second.set_is_comdat();
3459 ins.first->second.set_is_group_name();
3463 // We have already seen this signature.
3465 if (ins.first->second.is_group_name())
3467 // We've already seen a real section group with this signature.
3468 // If the kept group is from a plugin object, and we're in the
3469 // replacement phase, accept the new one as a replacement.
3470 if (ins.first->second.object() == NULL
3471 && parameters->options().plugins()->in_replacement_phase())
3473 ins.first->second.set_object(object);
3474 ins.first->second.set_shndx(shndx);
3479 else if (is_group_name)
3481 // This is a real section group, and we've already seen a
3482 // linkonce section with this signature. Record that we've seen
3483 // a section group, and don't include this section group.
3484 ins.first->second.set_is_group_name();
3489 // We've already seen a linkonce section and this is a linkonce
3490 // section. These don't block each other--this may be the same
3491 // symbol name with different section types.
3496 // Store the allocated sections into the section list.
3499 Layout::get_allocated_sections(Section_list* section_list) const
3501 for (Section_list::const_iterator p = this->section_list_.begin();
3502 p != this->section_list_.end();
3504 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3505 section_list->push_back(*p);
3508 // Create an output segment.
3511 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3513 gold_assert(!parameters->options().relocatable());
3514 Output_segment* oseg = new Output_segment(type, flags);
3515 this->segment_list_.push_back(oseg);
3517 if (type == elfcpp::PT_TLS)
3518 this->tls_segment_ = oseg;
3519 else if (type == elfcpp::PT_GNU_RELRO)
3520 this->relro_segment_ = oseg;
3525 // Write out the Output_sections. Most won't have anything to write,
3526 // since most of the data will come from input sections which are
3527 // handled elsewhere. But some Output_sections do have Output_data.
3530 Layout::write_output_sections(Output_file* of) const
3532 for (Section_list::const_iterator p = this->section_list_.begin();
3533 p != this->section_list_.end();
3536 if (!(*p)->after_input_sections())
3541 // Write out data not associated with a section or the symbol table.
3544 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
3546 if (!parameters->options().strip_all())
3548 const Output_section* symtab_section = this->symtab_section_;
3549 for (Section_list::const_iterator p = this->section_list_.begin();
3550 p != this->section_list_.end();
3553 if ((*p)->needs_symtab_index())
3555 gold_assert(symtab_section != NULL);
3556 unsigned int index = (*p)->symtab_index();
3557 gold_assert(index > 0 && index != -1U);
3558 off_t off = (symtab_section->offset()
3559 + index * symtab_section->entsize());
3560 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3565 const Output_section* dynsym_section = this->dynsym_section_;
3566 for (Section_list::const_iterator p = this->section_list_.begin();
3567 p != this->section_list_.end();
3570 if ((*p)->needs_dynsym_index())
3572 gold_assert(dynsym_section != NULL);
3573 unsigned int index = (*p)->dynsym_index();
3574 gold_assert(index > 0 && index != -1U);
3575 off_t off = (dynsym_section->offset()
3576 + index * dynsym_section->entsize());
3577 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3581 // Write out the Output_data which are not in an Output_section.
3582 for (Data_list::const_iterator p = this->special_output_list_.begin();
3583 p != this->special_output_list_.end();
3588 // Write out the Output_sections which can only be written after the
3589 // input sections are complete.
3592 Layout::write_sections_after_input_sections(Output_file* of)
3594 // Determine the final section offsets, and thus the final output
3595 // file size. Note we finalize the .shstrab last, to allow the
3596 // after_input_section sections to modify their section-names before
3598 if (this->any_postprocessing_sections_)
3600 off_t off = this->output_file_size_;
3601 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3603 // Now that we've finalized the names, we can finalize the shstrab.
3605 this->set_section_offsets(off,
3606 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3608 if (off > this->output_file_size_)
3611 this->output_file_size_ = off;
3615 for (Section_list::const_iterator p = this->section_list_.begin();
3616 p != this->section_list_.end();
3619 if ((*p)->after_input_sections())
3623 this->section_headers_->write(of);
3626 // If the build ID requires computing a checksum, do so here, and
3627 // write it out. We compute a checksum over the entire file because
3628 // that is simplest.
3631 Layout::write_build_id(Output_file* of) const
3633 if (this->build_id_note_ == NULL)
3636 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3638 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3639 this->build_id_note_->data_size());
3641 const char* style = parameters->options().build_id();
3642 if (strcmp(style, "sha1") == 0)
3645 sha1_init_ctx(&ctx);
3646 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3647 sha1_finish_ctx(&ctx, ov);
3649 else if (strcmp(style, "md5") == 0)
3653 md5_process_bytes(iv, this->output_file_size_, &ctx);
3654 md5_finish_ctx(&ctx, ov);
3659 of->write_output_view(this->build_id_note_->offset(),
3660 this->build_id_note_->data_size(),
3663 of->free_input_view(0, this->output_file_size_, iv);
3666 // Write out a binary file. This is called after the link is
3667 // complete. IN is the temporary output file we used to generate the
3668 // ELF code. We simply walk through the segments, read them from
3669 // their file offset in IN, and write them to their load address in
3670 // the output file. FIXME: with a bit more work, we could support
3671 // S-records and/or Intel hex format here.
3674 Layout::write_binary(Output_file* in) const
3676 gold_assert(parameters->options().oformat_enum()
3677 == General_options::OBJECT_FORMAT_BINARY);
3679 // Get the size of the binary file.
3680 uint64_t max_load_address = 0;
3681 for (Segment_list::const_iterator p = this->segment_list_.begin();
3682 p != this->segment_list_.end();
3685 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3687 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3688 if (max_paddr > max_load_address)
3689 max_load_address = max_paddr;
3693 Output_file out(parameters->options().output_file_name());
3694 out.open(max_load_address);
3696 for (Segment_list::const_iterator p = this->segment_list_.begin();
3697 p != this->segment_list_.end();
3700 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3702 const unsigned char* vin = in->get_input_view((*p)->offset(),
3704 unsigned char* vout = out.get_output_view((*p)->paddr(),
3706 memcpy(vout, vin, (*p)->filesz());
3707 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3708 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3715 // Print the output sections to the map file.
3718 Layout::print_to_mapfile(Mapfile* mapfile) const
3720 for (Segment_list::const_iterator p = this->segment_list_.begin();
3721 p != this->segment_list_.end();
3723 (*p)->print_sections_to_mapfile(mapfile);
3726 // Print statistical information to stderr. This is used for --stats.
3729 Layout::print_stats() const
3731 this->namepool_.print_stats("section name pool");
3732 this->sympool_.print_stats("output symbol name pool");
3733 this->dynpool_.print_stats("dynamic name pool");
3735 for (Section_list::const_iterator p = this->section_list_.begin();
3736 p != this->section_list_.end();
3738 (*p)->print_merge_stats();
3741 // Write_sections_task methods.
3743 // We can always run this task.
3746 Write_sections_task::is_runnable()
3751 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3755 Write_sections_task::locks(Task_locker* tl)
3757 tl->add(this, this->output_sections_blocker_);
3758 tl->add(this, this->final_blocker_);
3761 // Run the task--write out the data.
3764 Write_sections_task::run(Workqueue*)
3766 this->layout_->write_output_sections(this->of_);
3769 // Write_data_task methods.
3771 // We can always run this task.
3774 Write_data_task::is_runnable()
3779 // We need to unlock FINAL_BLOCKER when finished.
3782 Write_data_task::locks(Task_locker* tl)
3784 tl->add(this, this->final_blocker_);
3787 // Run the task--write out the data.
3790 Write_data_task::run(Workqueue*)
3792 this->layout_->write_data(this->symtab_, this->of_);
3795 // Write_symbols_task methods.
3797 // We can always run this task.
3800 Write_symbols_task::is_runnable()
3805 // We need to unlock FINAL_BLOCKER when finished.
3808 Write_symbols_task::locks(Task_locker* tl)
3810 tl->add(this, this->final_blocker_);
3813 // Run the task--write out the symbols.
3816 Write_symbols_task::run(Workqueue*)
3818 this->symtab_->write_globals(this->sympool_, this->dynpool_,
3819 this->layout_->symtab_xindex(),
3820 this->layout_->dynsym_xindex(), this->of_);
3823 // Write_after_input_sections_task methods.
3825 // We can only run this task after the input sections have completed.
3828 Write_after_input_sections_task::is_runnable()
3830 if (this->input_sections_blocker_->is_blocked())
3831 return this->input_sections_blocker_;
3835 // We need to unlock FINAL_BLOCKER when finished.
3838 Write_after_input_sections_task::locks(Task_locker* tl)
3840 tl->add(this, this->final_blocker_);
3846 Write_after_input_sections_task::run(Workqueue*)
3848 this->layout_->write_sections_after_input_sections(this->of_);
3851 // Close_task_runner methods.
3853 // Run the task--close the file.
3856 Close_task_runner::run(Workqueue*, const Task*)
3858 // If we need to compute a checksum for the BUILD if, we do so here.
3859 this->layout_->write_build_id(this->of_);
3861 // If we've been asked to create a binary file, we do so here.
3862 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3863 this->layout_->write_binary(this->of_);
3868 // Instantiate the templates we need. We could use the configure
3869 // script to restrict this to only the ones for implemented targets.
3871 #ifdef HAVE_TARGET_32_LITTLE
3874 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3876 const elfcpp::Shdr<32, false>& shdr,
3877 unsigned int, unsigned int, off_t*);
3880 #ifdef HAVE_TARGET_32_BIG
3883 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3885 const elfcpp::Shdr<32, true>& shdr,
3886 unsigned int, unsigned int, off_t*);
3889 #ifdef HAVE_TARGET_64_LITTLE
3892 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3894 const elfcpp::Shdr<64, false>& shdr,
3895 unsigned int, unsigned int, off_t*);
3898 #ifdef HAVE_TARGET_64_BIG
3901 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3903 const elfcpp::Shdr<64, true>& shdr,
3904 unsigned int, unsigned int, off_t*);
3907 #ifdef HAVE_TARGET_32_LITTLE
3910 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3911 unsigned int reloc_shndx,
3912 const elfcpp::Shdr<32, false>& shdr,
3913 Output_section* data_section,
3914 Relocatable_relocs* rr);
3917 #ifdef HAVE_TARGET_32_BIG
3920 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3921 unsigned int reloc_shndx,
3922 const elfcpp::Shdr<32, true>& shdr,
3923 Output_section* data_section,
3924 Relocatable_relocs* rr);
3927 #ifdef HAVE_TARGET_64_LITTLE
3930 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3931 unsigned int reloc_shndx,
3932 const elfcpp::Shdr<64, false>& shdr,
3933 Output_section* data_section,
3934 Relocatable_relocs* rr);
3937 #ifdef HAVE_TARGET_64_BIG
3940 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3941 unsigned int reloc_shndx,
3942 const elfcpp::Shdr<64, true>& shdr,
3943 Output_section* data_section,
3944 Relocatable_relocs* rr);
3947 #ifdef HAVE_TARGET_32_LITTLE
3950 Layout::layout_group<32, false>(Symbol_table* symtab,
3951 Sized_relobj<32, false>* object,
3953 const char* group_section_name,
3954 const char* signature,
3955 const elfcpp::Shdr<32, false>& shdr,
3956 elfcpp::Elf_Word flags,
3957 std::vector<unsigned int>* shndxes);
3960 #ifdef HAVE_TARGET_32_BIG
3963 Layout::layout_group<32, true>(Symbol_table* symtab,
3964 Sized_relobj<32, true>* object,
3966 const char* group_section_name,
3967 const char* signature,
3968 const elfcpp::Shdr<32, true>& shdr,
3969 elfcpp::Elf_Word flags,
3970 std::vector<unsigned int>* shndxes);
3973 #ifdef HAVE_TARGET_64_LITTLE
3976 Layout::layout_group<64, false>(Symbol_table* symtab,
3977 Sized_relobj<64, false>* object,
3979 const char* group_section_name,
3980 const char* signature,
3981 const elfcpp::Shdr<64, false>& shdr,
3982 elfcpp::Elf_Word flags,
3983 std::vector<unsigned int>* shndxes);
3986 #ifdef HAVE_TARGET_64_BIG
3989 Layout::layout_group<64, true>(Symbol_table* symtab,
3990 Sized_relobj<64, true>* object,
3992 const char* group_section_name,
3993 const char* signature,
3994 const elfcpp::Shdr<64, true>& shdr,
3995 elfcpp::Elf_Word flags,
3996 std::vector<unsigned int>* shndxes);
3999 #ifdef HAVE_TARGET_32_LITTLE
4002 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
4003 const unsigned char* symbols,
4005 const unsigned char* symbol_names,
4006 off_t symbol_names_size,
4008 const elfcpp::Shdr<32, false>& shdr,
4009 unsigned int reloc_shndx,
4010 unsigned int reloc_type,
4014 #ifdef HAVE_TARGET_32_BIG
4017 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4018 const unsigned char* symbols,
4020 const unsigned char* symbol_names,
4021 off_t symbol_names_size,
4023 const elfcpp::Shdr<32, true>& shdr,
4024 unsigned int reloc_shndx,
4025 unsigned int reloc_type,
4029 #ifdef HAVE_TARGET_64_LITTLE
4032 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4033 const unsigned char* symbols,
4035 const unsigned char* symbol_names,
4036 off_t symbol_names_size,
4038 const elfcpp::Shdr<64, false>& shdr,
4039 unsigned int reloc_shndx,
4040 unsigned int reloc_type,
4044 #ifdef HAVE_TARGET_64_BIG
4047 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4048 const unsigned char* symbols,
4050 const unsigned char* symbol_names,
4051 off_t symbol_names_size,
4053 const elfcpp::Shdr<64, true>& shdr,
4054 unsigned int reloc_shndx,
4055 unsigned int reloc_type,
4059 } // End namespace gold.