1 // layout.cc -- lay out output file sections for gold
3 // Copyright 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
6 // This file is part of gold.
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
32 #include "libiberty.h"
36 #include "parameters.h"
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),
183 dynamic_symbol_(NULL),
185 eh_frame_section_(NULL),
186 eh_frame_data_(NULL),
187 added_eh_frame_data_(false),
188 eh_frame_hdr_section_(NULL),
189 build_id_note_(NULL),
193 output_file_size_(-1),
194 sections_are_attached_(false),
195 input_requires_executable_stack_(false),
196 input_with_gnu_stack_note_(false),
197 input_without_gnu_stack_note_(false),
198 has_static_tls_(false),
199 any_postprocessing_sections_(false),
200 resized_signatures_(false),
201 have_stabstr_section_(false),
202 incremental_inputs_(NULL),
203 record_output_section_data_from_script_(false),
204 script_output_section_data_list_(),
205 segment_states_(NULL),
206 relaxation_debug_check_(NULL)
208 // Make space for more than enough segments for a typical file.
209 // This is just for efficiency--it's OK if we wind up needing more.
210 this->segment_list_.reserve(12);
212 // We expect two unattached Output_data objects: the file header and
213 // the segment headers.
214 this->special_output_list_.reserve(2);
216 // Initialize structure needed for an incremental build.
217 if (parameters->options().incremental())
218 this->incremental_inputs_ = new Incremental_inputs;
220 // The section name pool is worth optimizing in all cases, because
221 // it is small, but there are often overlaps due to .rel sections.
222 this->namepool_.set_optimize();
225 // Hash a key we use to look up an output section mapping.
228 Layout::Hash_key::operator()(const Layout::Key& k) const
230 return k.first + k.second.first + k.second.second;
233 // Returns whether the given section is in the list of
234 // debug-sections-used-by-some-version-of-gdb. Currently,
235 // we've checked versions of gdb up to and including 6.7.1.
237 static const char* gdb_sections[] =
239 // ".debug_aranges", // not used by gdb as of 6.7.1
245 // ".debug_pubnames", // not used by gdb as of 6.7.1
250 static const char* lines_only_debug_sections[] =
252 // ".debug_aranges", // not used by gdb as of 6.7.1
258 // ".debug_pubnames", // not used by gdb as of 6.7.1
264 is_gdb_debug_section(const char* str)
266 // We can do this faster: binary search or a hashtable. But why bother?
267 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
268 if (strcmp(str, gdb_sections[i]) == 0)
274 is_lines_only_debug_section(const char* str)
276 // We can do this faster: binary search or a hashtable. But why bother?
278 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
280 if (strcmp(str, lines_only_debug_sections[i]) == 0)
285 // Whether to include this section in the link.
287 template<int size, bool big_endian>
289 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
290 const elfcpp::Shdr<size, big_endian>& shdr)
292 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
295 switch (shdr.get_sh_type())
297 case elfcpp::SHT_NULL:
298 case elfcpp::SHT_SYMTAB:
299 case elfcpp::SHT_DYNSYM:
300 case elfcpp::SHT_HASH:
301 case elfcpp::SHT_DYNAMIC:
302 case elfcpp::SHT_SYMTAB_SHNDX:
305 case elfcpp::SHT_STRTAB:
306 // Discard the sections which have special meanings in the ELF
307 // ABI. Keep others (e.g., .stabstr). We could also do this by
308 // checking the sh_link fields of the appropriate sections.
309 return (strcmp(name, ".dynstr") != 0
310 && strcmp(name, ".strtab") != 0
311 && strcmp(name, ".shstrtab") != 0);
313 case elfcpp::SHT_RELA:
314 case elfcpp::SHT_REL:
315 case elfcpp::SHT_GROUP:
316 // If we are emitting relocations these should be handled
318 gold_assert(!parameters->options().relocatable()
319 && !parameters->options().emit_relocs());
322 case elfcpp::SHT_PROGBITS:
323 if (parameters->options().strip_debug()
324 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
326 if (is_debug_info_section(name))
329 if (parameters->options().strip_debug_non_line()
330 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
332 // Debugging sections can only be recognized by name.
333 if (is_prefix_of(".debug", name)
334 && !is_lines_only_debug_section(name))
337 if (parameters->options().strip_debug_gdb()
338 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
340 // Debugging sections can only be recognized by name.
341 if (is_prefix_of(".debug", name)
342 && !is_gdb_debug_section(name))
345 if (parameters->options().strip_lto_sections()
346 && !parameters->options().relocatable()
347 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
349 // Ignore LTO sections containing intermediate code.
350 if (is_prefix_of(".gnu.lto_", name))
360 // Return an output section named NAME, or NULL if there is none.
363 Layout::find_output_section(const char* name) const
365 for (Section_list::const_iterator p = this->section_list_.begin();
366 p != this->section_list_.end();
368 if (strcmp((*p)->name(), name) == 0)
373 // Return an output segment of type TYPE, with segment flags SET set
374 // and segment flags CLEAR clear. Return NULL if there is none.
377 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
378 elfcpp::Elf_Word clear) const
380 for (Segment_list::const_iterator p = this->segment_list_.begin();
381 p != this->segment_list_.end();
383 if (static_cast<elfcpp::PT>((*p)->type()) == type
384 && ((*p)->flags() & set) == set
385 && ((*p)->flags() & clear) == 0)
390 // Return the output section to use for section NAME with type TYPE
391 // and section flags FLAGS. NAME must be canonicalized in the string
392 // pool, and NAME_KEY is the key. IS_INTERP is true if this is the
393 // .interp section. IS_DYNAMIC_LINKER_SECTION is true if this section
394 // is used by the dynamic linker.
397 Layout::get_output_section(const char* name, Stringpool::Key name_key,
398 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
399 bool is_interp, bool is_dynamic_linker_section)
401 elfcpp::Elf_Xword lookup_flags = flags;
403 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
404 // read-write with read-only sections. Some other ELF linkers do
405 // not do this. FIXME: Perhaps there should be an option
407 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
409 const Key key(name_key, std::make_pair(type, lookup_flags));
410 const std::pair<Key, Output_section*> v(key, NULL);
411 std::pair<Section_name_map::iterator, bool> ins(
412 this->section_name_map_.insert(v));
415 return ins.first->second;
418 // This is the first time we've seen this name/type/flags
419 // combination. For compatibility with the GNU linker, we
420 // combine sections with contents and zero flags with sections
421 // with non-zero flags. This is a workaround for cases where
422 // assembler code forgets to set section flags. FIXME: Perhaps
423 // there should be an option to control this.
424 Output_section* os = NULL;
426 if (type == elfcpp::SHT_PROGBITS)
430 Output_section* same_name = this->find_output_section(name);
431 if (same_name != NULL
432 && same_name->type() == elfcpp::SHT_PROGBITS
433 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
436 else if ((flags & elfcpp::SHF_TLS) == 0)
438 elfcpp::Elf_Xword zero_flags = 0;
439 const Key zero_key(name_key, std::make_pair(type, zero_flags));
440 Section_name_map::iterator p =
441 this->section_name_map_.find(zero_key);
442 if (p != this->section_name_map_.end())
448 os = this->make_output_section(name, type, flags, is_interp,
449 is_dynamic_linker_section);
450 ins.first->second = os;
455 // Pick the output section to use for section NAME, in input file
456 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
457 // linker created section. IS_INPUT_SECTION is true if we are
458 // choosing an output section for an input section found in a input
459 // file. IS_INTERP is true if this is the .interp section.
460 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
461 // dynamic linker. This will return NULL if the input section should
465 Layout::choose_output_section(const Relobj* relobj, const char* name,
466 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
467 bool is_input_section, bool is_interp,
468 bool is_dynamic_linker_section)
470 // We should not see any input sections after we have attached
471 // sections to segments.
472 gold_assert(!is_input_section || !this->sections_are_attached_);
474 // Some flags in the input section should not be automatically
475 // copied to the output section.
476 flags &= ~ (elfcpp::SHF_INFO_LINK
477 | elfcpp::SHF_LINK_ORDER
480 | elfcpp::SHF_STRINGS);
482 if (this->script_options_->saw_sections_clause())
484 // We are using a SECTIONS clause, so the output section is
485 // chosen based only on the name.
487 Script_sections* ss = this->script_options_->script_sections();
488 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
489 Output_section** output_section_slot;
490 name = ss->output_section_name(file_name, name, &output_section_slot);
493 // The SECTIONS clause says to discard this input section.
497 // If this is an orphan section--one not mentioned in the linker
498 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
499 // default processing below.
501 if (output_section_slot != NULL)
503 if (*output_section_slot != NULL)
505 (*output_section_slot)->update_flags_for_input_section(flags);
506 return *output_section_slot;
509 // We don't put sections found in the linker script into
510 // SECTION_NAME_MAP_. That keeps us from getting confused
511 // if an orphan section is mapped to a section with the same
512 // name as one in the linker script.
514 name = this->namepool_.add(name, false, NULL);
517 this->make_output_section(name, type, flags, is_interp,
518 is_dynamic_linker_section);
519 os->set_found_in_sections_clause();
520 *output_section_slot = os;
525 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
527 // Turn NAME from the name of the input section into the name of the
530 size_t len = strlen(name);
532 && !this->script_options_->saw_sections_clause()
533 && !parameters->options().relocatable())
534 name = Layout::output_section_name(name, &len);
536 Stringpool::Key name_key;
537 name = this->namepool_.add_with_length(name, len, true, &name_key);
539 // Find or make the output section. The output section is selected
540 // based on the section name, type, and flags.
541 return this->get_output_section(name, name_key, type, flags, is_interp,
542 is_dynamic_linker_section);
545 // Return the output section to use for input section SHNDX, with name
546 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
547 // index of a relocation section which applies to this section, or 0
548 // if none, or -1U if more than one. RELOC_TYPE is the type of the
549 // relocation section if there is one. Set *OFF to the offset of this
550 // input section without the output section. Return NULL if the
551 // section should be discarded. Set *OFF to -1 if the section
552 // contents should not be written directly to the output file, but
553 // will instead receive special handling.
555 template<int size, bool big_endian>
557 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
558 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
559 unsigned int reloc_shndx, unsigned int, off_t* off)
563 if (!this->include_section(object, name, shdr))
568 // In a relocatable link a grouped section must not be combined with
569 // any other sections.
570 if (parameters->options().relocatable()
571 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
573 name = this->namepool_.add(name, true, NULL);
574 os = this->make_output_section(name, shdr.get_sh_type(),
575 shdr.get_sh_flags(), false, false);
579 os = this->choose_output_section(object, name, shdr.get_sh_type(),
580 shdr.get_sh_flags(), true, false,
586 // By default the GNU linker sorts input sections whose names match
587 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
588 // are sorted by name. This is used to implement constructor
589 // priority ordering. We are compatible.
590 if (!this->script_options_->saw_sections_clause()
591 && (is_prefix_of(".ctors.", name)
592 || is_prefix_of(".dtors.", name)
593 || is_prefix_of(".init_array.", name)
594 || is_prefix_of(".fini_array.", name)))
595 os->set_must_sort_attached_input_sections();
597 // FIXME: Handle SHF_LINK_ORDER somewhere.
599 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
600 this->script_options_->saw_sections_clause());
605 // Handle a relocation section when doing a relocatable link.
607 template<int size, bool big_endian>
609 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
611 const elfcpp::Shdr<size, big_endian>& shdr,
612 Output_section* data_section,
613 Relocatable_relocs* rr)
615 gold_assert(parameters->options().relocatable()
616 || parameters->options().emit_relocs());
618 int sh_type = shdr.get_sh_type();
621 if (sh_type == elfcpp::SHT_REL)
623 else if (sh_type == elfcpp::SHT_RELA)
627 name += data_section->name();
629 Output_section* os = this->choose_output_section(object, name.c_str(),
632 false, false, false);
634 os->set_should_link_to_symtab();
635 os->set_info_section(data_section);
637 Output_section_data* posd;
638 if (sh_type == elfcpp::SHT_REL)
640 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
641 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
645 else if (sh_type == elfcpp::SHT_RELA)
647 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
648 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
655 os->add_output_section_data(posd);
656 rr->set_output_data(posd);
661 // Handle a group section when doing a relocatable link.
663 template<int size, bool big_endian>
665 Layout::layout_group(Symbol_table* symtab,
666 Sized_relobj<size, big_endian>* object,
668 const char* group_section_name,
669 const char* signature,
670 const elfcpp::Shdr<size, big_endian>& shdr,
671 elfcpp::Elf_Word flags,
672 std::vector<unsigned int>* shndxes)
674 gold_assert(parameters->options().relocatable());
675 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
676 group_section_name = this->namepool_.add(group_section_name, true, NULL);
677 Output_section* os = this->make_output_section(group_section_name,
682 // We need to find a symbol with the signature in the symbol table.
683 // If we don't find one now, we need to look again later.
684 Symbol* sym = symtab->lookup(signature, NULL);
686 os->set_info_symndx(sym);
689 // Reserve some space to minimize reallocations.
690 if (this->group_signatures_.empty())
691 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
693 // We will wind up using a symbol whose name is the signature.
694 // So just put the signature in the symbol name pool to save it.
695 signature = symtab->canonicalize_name(signature);
696 this->group_signatures_.push_back(Group_signature(os, signature));
699 os->set_should_link_to_symtab();
702 section_size_type entry_count =
703 convert_to_section_size_type(shdr.get_sh_size() / 4);
704 Output_section_data* posd =
705 new Output_data_group<size, big_endian>(object, entry_count, flags,
707 os->add_output_section_data(posd);
710 // Special GNU handling of sections name .eh_frame. They will
711 // normally hold exception frame data as defined by the C++ ABI
712 // (http://codesourcery.com/cxx-abi/).
714 template<int size, bool big_endian>
716 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
717 const unsigned char* symbols,
719 const unsigned char* symbol_names,
720 off_t symbol_names_size,
722 const elfcpp::Shdr<size, big_endian>& shdr,
723 unsigned int reloc_shndx, unsigned int reloc_type,
726 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
727 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
729 const char* const name = ".eh_frame";
730 Output_section* os = this->choose_output_section(object,
732 elfcpp::SHT_PROGBITS,
734 false, false, false);
738 if (this->eh_frame_section_ == NULL)
740 this->eh_frame_section_ = os;
741 this->eh_frame_data_ = new Eh_frame();
743 if (parameters->options().eh_frame_hdr())
745 Output_section* hdr_os =
746 this->choose_output_section(NULL,
748 elfcpp::SHT_PROGBITS,
750 false, false, false);
754 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
755 this->eh_frame_data_);
756 hdr_os->add_output_section_data(hdr_posd);
758 hdr_os->set_after_input_sections();
760 if (!this->script_options_->saw_phdrs_clause())
762 Output_segment* hdr_oseg;
763 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
765 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R, false);
768 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
773 gold_assert(this->eh_frame_section_ == os);
775 if (this->eh_frame_data_->add_ehframe_input_section(object,
784 os->update_flags_for_input_section(shdr.get_sh_flags());
786 // We found a .eh_frame section we are going to optimize, so now
787 // we can add the set of optimized sections to the output
788 // section. We need to postpone adding this until we've found a
789 // section we can optimize so that the .eh_frame section in
790 // crtbegin.o winds up at the start of the output section.
791 if (!this->added_eh_frame_data_)
793 os->add_output_section_data(this->eh_frame_data_);
794 this->added_eh_frame_data_ = true;
800 // We couldn't handle this .eh_frame section for some reason.
801 // Add it as a normal section.
802 bool saw_sections_clause = this->script_options_->saw_sections_clause();
803 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
804 saw_sections_clause);
810 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
811 // the output section.
814 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
815 elfcpp::Elf_Xword flags,
816 Output_section_data* posd,
817 bool is_dynamic_linker_section)
819 Output_section* os = this->choose_output_section(NULL, name, type, flags,
821 is_dynamic_linker_section);
823 os->add_output_section_data(posd);
827 // Map section flags to segment flags.
830 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
832 elfcpp::Elf_Word ret = elfcpp::PF_R;
833 if ((flags & elfcpp::SHF_WRITE) != 0)
835 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
840 // Sometimes we compress sections. This is typically done for
841 // sections that are not part of normal program execution (such as
842 // .debug_* sections), and where the readers of these sections know
843 // how to deal with compressed sections. This routine doesn't say for
844 // certain whether we'll compress -- it depends on commandline options
845 // as well -- just whether this section is a candidate for compression.
846 // (The Output_compressed_section class decides whether to compress
847 // a given section, and picks the name of the compressed section.)
850 is_compressible_debug_section(const char* secname)
852 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
855 // Make a new Output_section, and attach it to segments as
856 // appropriate. IS_INTERP is true if this is the .interp section.
857 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
861 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
862 elfcpp::Elf_Xword flags, bool is_interp,
863 bool is_dynamic_linker_section)
866 if ((flags & elfcpp::SHF_ALLOC) == 0
867 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
868 && is_compressible_debug_section(name))
869 os = new Output_compressed_section(¶meters->options(), name, type,
871 else if ((flags & elfcpp::SHF_ALLOC) == 0
872 && parameters->options().strip_debug_non_line()
873 && strcmp(".debug_abbrev", name) == 0)
875 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
877 if (this->debug_info_)
878 this->debug_info_->set_abbreviations(this->debug_abbrev_);
880 else if ((flags & elfcpp::SHF_ALLOC) == 0
881 && parameters->options().strip_debug_non_line()
882 && strcmp(".debug_info", name) == 0)
884 os = this->debug_info_ = new Output_reduced_debug_info_section(
886 if (this->debug_abbrev_)
887 this->debug_info_->set_abbreviations(this->debug_abbrev_);
891 // FIXME: const_cast is ugly.
892 Target* target = const_cast<Target*>(¶meters->target());
893 os = target->make_output_section(name, type, flags);
898 if (is_dynamic_linker_section)
899 os->set_is_dynamic_linker_section();
901 parameters->target().new_output_section(os);
903 this->section_list_.push_back(os);
905 // The GNU linker by default sorts some sections by priority, so we
906 // do the same. We need to know that this might happen before we
907 // attach any input sections.
908 if (!this->script_options_->saw_sections_clause()
909 && (strcmp(name, ".ctors") == 0
910 || strcmp(name, ".dtors") == 0
911 || strcmp(name, ".init_array") == 0
912 || strcmp(name, ".fini_array") == 0))
913 os->set_may_sort_attached_input_sections();
915 // With -z relro, we have to recognize the special sections by name.
916 // There is no other way.
917 if (!this->script_options_->saw_sections_clause()
918 && parameters->options().relro()
919 && type == elfcpp::SHT_PROGBITS
920 && (flags & elfcpp::SHF_ALLOC) != 0
921 && (flags & elfcpp::SHF_WRITE) != 0)
923 if (strcmp(name, ".data.rel.ro") == 0)
925 else if (strcmp(name, ".data.rel.ro.local") == 0)
928 os->set_is_relro_local();
932 // Check for .stab*str sections, as .stab* sections need to link to
934 if (type == elfcpp::SHT_STRTAB
935 && !this->have_stabstr_section_
936 && strncmp(name, ".stab", 5) == 0
937 && strcmp(name + strlen(name) - 3, "str") == 0)
938 this->have_stabstr_section_ = true;
940 // If we have already attached the sections to segments, then we
941 // need to attach this one now. This happens for sections created
942 // directly by the linker.
943 if (this->sections_are_attached_)
944 this->attach_section_to_segment(os);
949 // Attach output sections to segments. This is called after we have
950 // seen all the input sections.
953 Layout::attach_sections_to_segments()
955 for (Section_list::iterator p = this->section_list_.begin();
956 p != this->section_list_.end();
958 this->attach_section_to_segment(*p);
960 this->sections_are_attached_ = true;
963 // Attach an output section to a segment.
966 Layout::attach_section_to_segment(Output_section* os)
968 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
969 this->unattached_section_list_.push_back(os);
971 this->attach_allocated_section_to_segment(os);
974 // Attach an allocated output section to a segment.
977 Layout::attach_allocated_section_to_segment(Output_section* os)
979 elfcpp::Elf_Xword flags = os->flags();
980 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
982 if (parameters->options().relocatable())
985 // If we have a SECTIONS clause, we can't handle the attachment to
986 // segments until after we've seen all the sections.
987 if (this->script_options_->saw_sections_clause())
990 gold_assert(!this->script_options_->saw_phdrs_clause());
992 // This output section goes into a PT_LOAD segment.
994 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
996 bool sort_sections = !this->script_options_->saw_sections_clause();
998 // In general the only thing we really care about for PT_LOAD
999 // segments is whether or not they are writable, so that is how we
1000 // search for them. Large data sections also go into their own
1001 // PT_LOAD segment. People who need segments sorted on some other
1002 // basis will have to use a linker script.
1004 Segment_list::const_iterator p;
1005 for (p = this->segment_list_.begin();
1006 p != this->segment_list_.end();
1009 if ((*p)->type() != elfcpp::PT_LOAD)
1011 if (!parameters->options().omagic()
1012 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1014 // If -Tbss was specified, we need to separate the data and BSS
1016 if (parameters->options().user_set_Tbss())
1018 if ((os->type() == elfcpp::SHT_NOBITS)
1019 == (*p)->has_any_data_sections())
1022 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1025 (*p)->add_output_section(os, seg_flags, sort_sections);
1029 if (p == this->segment_list_.end())
1031 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1033 if (os->is_large_data_section())
1034 oseg->set_is_large_data_segment();
1035 oseg->add_output_section(os, seg_flags, sort_sections);
1038 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1040 if (os->type() == elfcpp::SHT_NOTE)
1042 // See if we already have an equivalent PT_NOTE segment.
1043 for (p = this->segment_list_.begin();
1044 p != segment_list_.end();
1047 if ((*p)->type() == elfcpp::PT_NOTE
1048 && (((*p)->flags() & elfcpp::PF_W)
1049 == (seg_flags & elfcpp::PF_W)))
1051 (*p)->add_output_section(os, seg_flags, false);
1056 if (p == this->segment_list_.end())
1058 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1060 oseg->add_output_section(os, seg_flags, false);
1064 // If we see a loadable SHF_TLS section, we create a PT_TLS
1065 // segment. There can only be one such segment.
1066 if ((flags & elfcpp::SHF_TLS) != 0)
1068 if (this->tls_segment_ == NULL)
1069 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1070 this->tls_segment_->add_output_section(os, seg_flags, false);
1073 // If -z relro is in effect, and we see a relro section, we create a
1074 // PT_GNU_RELRO segment. There can only be one such segment.
1075 if (os->is_relro() && parameters->options().relro())
1077 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1078 if (this->relro_segment_ == NULL)
1079 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1080 this->relro_segment_->add_output_section(os, seg_flags, false);
1084 // Make an output section for a script.
1087 Layout::make_output_section_for_script(const char* name)
1089 name = this->namepool_.add(name, false, NULL);
1090 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1091 elfcpp::SHF_ALLOC, false,
1093 os->set_found_in_sections_clause();
1097 // Return the number of segments we expect to see.
1100 Layout::expected_segment_count() const
1102 size_t ret = this->segment_list_.size();
1104 // If we didn't see a SECTIONS clause in a linker script, we should
1105 // already have the complete list of segments. Otherwise we ask the
1106 // SECTIONS clause how many segments it expects, and add in the ones
1107 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1109 if (!this->script_options_->saw_sections_clause())
1113 const Script_sections* ss = this->script_options_->script_sections();
1114 return ret + ss->expected_segment_count(this);
1118 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1119 // is whether we saw a .note.GNU-stack section in the object file.
1120 // GNU_STACK_FLAGS is the section flags. The flags give the
1121 // protection required for stack memory. We record this in an
1122 // executable as a PT_GNU_STACK segment. If an object file does not
1123 // have a .note.GNU-stack segment, we must assume that it is an old
1124 // object. On some targets that will force an executable stack.
1127 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1129 if (!seen_gnu_stack)
1130 this->input_without_gnu_stack_note_ = true;
1133 this->input_with_gnu_stack_note_ = true;
1134 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1135 this->input_requires_executable_stack_ = true;
1139 // Create automatic note sections.
1142 Layout::create_notes()
1144 this->create_gold_note();
1145 this->create_executable_stack_info();
1146 this->create_build_id();
1149 // Create the dynamic sections which are needed before we read the
1153 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1155 if (parameters->doing_static_link())
1158 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1159 elfcpp::SHT_DYNAMIC,
1161 | elfcpp::SHF_WRITE),
1162 false, false, true);
1163 this->dynamic_section_->set_is_relro();
1165 this->dynamic_symbol_ =
1166 symtab->define_in_output_data("_DYNAMIC", NULL, Symbol_table::PREDEFINED,
1167 this->dynamic_section_, 0, 0,
1168 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1169 elfcpp::STV_HIDDEN, 0, false, false);
1171 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1173 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1176 // For each output section whose name can be represented as C symbol,
1177 // define __start and __stop symbols for the section. This is a GNU
1181 Layout::define_section_symbols(Symbol_table* symtab)
1183 for (Section_list::const_iterator p = this->section_list_.begin();
1184 p != this->section_list_.end();
1187 const char* const name = (*p)->name();
1188 if (name[strspn(name,
1190 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1191 "abcdefghijklmnopqrstuvwxyz"
1195 const std::string name_string(name);
1196 const std::string start_name("__start_" + name_string);
1197 const std::string stop_name("__stop_" + name_string);
1199 symtab->define_in_output_data(start_name.c_str(),
1201 Symbol_table::PREDEFINED,
1207 elfcpp::STV_DEFAULT,
1209 false, // offset_is_from_end
1210 true); // only_if_ref
1212 symtab->define_in_output_data(stop_name.c_str(),
1214 Symbol_table::PREDEFINED,
1220 elfcpp::STV_DEFAULT,
1222 true, // offset_is_from_end
1223 true); // only_if_ref
1228 // Define symbols for group signatures.
1231 Layout::define_group_signatures(Symbol_table* symtab)
1233 for (Group_signatures::iterator p = this->group_signatures_.begin();
1234 p != this->group_signatures_.end();
1237 Symbol* sym = symtab->lookup(p->signature, NULL);
1239 p->section->set_info_symndx(sym);
1242 // Force the name of the group section to the group
1243 // signature, and use the group's section symbol as the
1244 // signature symbol.
1245 if (strcmp(p->section->name(), p->signature) != 0)
1247 const char* name = this->namepool_.add(p->signature,
1249 p->section->set_name(name);
1251 p->section->set_needs_symtab_index();
1252 p->section->set_info_section_symndx(p->section);
1256 this->group_signatures_.clear();
1259 // Find the first read-only PT_LOAD segment, creating one if
1263 Layout::find_first_load_seg()
1265 for (Segment_list::const_iterator p = this->segment_list_.begin();
1266 p != this->segment_list_.end();
1269 if ((*p)->type() == elfcpp::PT_LOAD
1270 && ((*p)->flags() & elfcpp::PF_R) != 0
1271 && (parameters->options().omagic()
1272 || ((*p)->flags() & elfcpp::PF_W) == 0))
1276 gold_assert(!this->script_options_->saw_phdrs_clause());
1278 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1283 // Save states of all current output segments. Store saved states
1284 // in SEGMENT_STATES.
1287 Layout::save_segments(Segment_states* segment_states)
1289 for (Segment_list::const_iterator p = this->segment_list_.begin();
1290 p != this->segment_list_.end();
1293 Output_segment* segment = *p;
1295 Output_segment* copy = new Output_segment(*segment);
1296 (*segment_states)[segment] = copy;
1300 // Restore states of output segments and delete any segment not found in
1304 Layout::restore_segments(const Segment_states* segment_states)
1306 // Go through the segment list and remove any segment added in the
1308 this->tls_segment_ = NULL;
1309 this->relro_segment_ = NULL;
1310 Segment_list::iterator list_iter = this->segment_list_.begin();
1311 while (list_iter != this->segment_list_.end())
1313 Output_segment* segment = *list_iter;
1314 Segment_states::const_iterator states_iter =
1315 segment_states->find(segment);
1316 if (states_iter != segment_states->end())
1318 const Output_segment* copy = states_iter->second;
1319 // Shallow copy to restore states.
1322 // Also fix up TLS and RELRO segment pointers as appropriate.
1323 if (segment->type() == elfcpp::PT_TLS)
1324 this->tls_segment_ = segment;
1325 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1326 this->relro_segment_ = segment;
1332 list_iter = this->segment_list_.erase(list_iter);
1333 // This is a segment created during section layout. It should be
1334 // safe to remove it since we should have removed all pointers to it.
1340 // Clean up after relaxation so that sections can be laid out again.
1343 Layout::clean_up_after_relaxation()
1345 // Restore the segments to point state just prior to the relaxation loop.
1346 Script_sections* script_section = this->script_options_->script_sections();
1347 script_section->release_segments();
1348 this->restore_segments(this->segment_states_);
1350 // Reset section addresses and file offsets
1351 for (Section_list::iterator p = this->section_list_.begin();
1352 p != this->section_list_.end();
1355 (*p)->reset_address_and_file_offset();
1356 (*p)->restore_states();
1359 // Reset special output object address and file offsets.
1360 for (Data_list::iterator p = this->special_output_list_.begin();
1361 p != this->special_output_list_.end();
1363 (*p)->reset_address_and_file_offset();
1365 // A linker script may have created some output section data objects.
1366 // They are useless now.
1367 for (Output_section_data_list::const_iterator p =
1368 this->script_output_section_data_list_.begin();
1369 p != this->script_output_section_data_list_.end();
1372 this->script_output_section_data_list_.clear();
1375 // Prepare for relaxation.
1378 Layout::prepare_for_relaxation()
1380 // Create an relaxation debug check if in debugging mode.
1381 if (is_debugging_enabled(DEBUG_RELAXATION))
1382 this->relaxation_debug_check_ = new Relaxation_debug_check();
1384 // Save segment states.
1385 this->segment_states_ = new Segment_states();
1386 this->save_segments(this->segment_states_);
1388 for(Section_list::const_iterator p = this->section_list_.begin();
1389 p != this->section_list_.end();
1391 (*p)->save_states();
1393 if (is_debugging_enabled(DEBUG_RELAXATION))
1394 this->relaxation_debug_check_->check_output_data_for_reset_values(
1395 this->section_list_, this->special_output_list_);
1397 // Also enable recording of output section data from scripts.
1398 this->record_output_section_data_from_script_ = true;
1401 // Relaxation loop body: If target has no relaxation, this runs only once
1402 // Otherwise, the target relaxation hook is called at the end of
1403 // each iteration. If the hook returns true, it means re-layout of
1404 // section is required.
1406 // The number of segments created by a linking script without a PHDRS
1407 // clause may be affected by section sizes and alignments. There is
1408 // a remote chance that relaxation causes different number of PT_LOAD
1409 // segments are created and sections are attached to different segments.
1410 // Therefore, we always throw away all segments created during section
1411 // layout. In order to be able to restart the section layout, we keep
1412 // a copy of the segment list right before the relaxation loop and use
1413 // that to restore the segments.
1415 // PASS is the current relaxation pass number.
1416 // SYMTAB is a symbol table.
1417 // PLOAD_SEG is the address of a pointer for the load segment.
1418 // PHDR_SEG is a pointer to the PHDR segment.
1419 // SEGMENT_HEADERS points to the output segment header.
1420 // FILE_HEADER points to the output file header.
1421 // PSHNDX is the address to store the output section index.
1424 Layout::relaxation_loop_body(
1427 Symbol_table* symtab,
1428 Output_segment** pload_seg,
1429 Output_segment* phdr_seg,
1430 Output_segment_headers* segment_headers,
1431 Output_file_header* file_header,
1432 unsigned int* pshndx)
1434 // If this is not the first iteration, we need to clean up after
1435 // relaxation so that we can lay out the sections again.
1437 this->clean_up_after_relaxation();
1439 // If there is a SECTIONS clause, put all the input sections into
1440 // the required order.
1441 Output_segment* load_seg;
1442 if (this->script_options_->saw_sections_clause())
1443 load_seg = this->set_section_addresses_from_script(symtab);
1444 else if (parameters->options().relocatable())
1447 load_seg = this->find_first_load_seg();
1449 if (parameters->options().oformat_enum()
1450 != General_options::OBJECT_FORMAT_ELF)
1453 gold_assert(phdr_seg == NULL
1455 || this->script_options_->saw_sections_clause());
1457 // Lay out the segment headers.
1458 if (!parameters->options().relocatable())
1460 gold_assert(segment_headers != NULL);
1461 if (load_seg != NULL)
1462 load_seg->add_initial_output_data(segment_headers);
1463 if (phdr_seg != NULL)
1464 phdr_seg->add_initial_output_data(segment_headers);
1467 // Lay out the file header.
1468 if (load_seg != NULL)
1469 load_seg->add_initial_output_data(file_header);
1471 if (this->script_options_->saw_phdrs_clause()
1472 && !parameters->options().relocatable())
1474 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1475 // clause in a linker script.
1476 Script_sections* ss = this->script_options_->script_sections();
1477 ss->put_headers_in_phdrs(file_header, segment_headers);
1480 // We set the output section indexes in set_segment_offsets and
1481 // set_section_indexes.
1484 // Set the file offsets of all the segments, and all the sections
1487 if (!parameters->options().relocatable())
1488 off = this->set_segment_offsets(target, load_seg, pshndx);
1490 off = this->set_relocatable_section_offsets(file_header, pshndx);
1492 // Verify that the dummy relaxation does not change anything.
1493 if (is_debugging_enabled(DEBUG_RELAXATION))
1496 this->relaxation_debug_check_->read_sections(this->section_list_);
1498 this->relaxation_debug_check_->verify_sections(this->section_list_);
1501 *pload_seg = load_seg;
1505 // Finalize the layout. When this is called, we have created all the
1506 // output sections and all the output segments which are based on
1507 // input sections. We have several things to do, and we have to do
1508 // them in the right order, so that we get the right results correctly
1511 // 1) Finalize the list of output segments and create the segment
1514 // 2) Finalize the dynamic symbol table and associated sections.
1516 // 3) Determine the final file offset of all the output segments.
1518 // 4) Determine the final file offset of all the SHF_ALLOC output
1521 // 5) Create the symbol table sections and the section name table
1524 // 6) Finalize the symbol table: set symbol values to their final
1525 // value and make a final determination of which symbols are going
1526 // into the output symbol table.
1528 // 7) Create the section table header.
1530 // 8) Determine the final file offset of all the output sections which
1531 // are not SHF_ALLOC, including the section table header.
1533 // 9) Finalize the ELF file header.
1535 // This function returns the size of the output file.
1538 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1539 Target* target, const Task* task)
1541 target->finalize_sections(this, input_objects, symtab);
1543 this->count_local_symbols(task, input_objects);
1545 this->link_stabs_sections();
1547 Output_segment* phdr_seg = NULL;
1548 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1550 // There was a dynamic object in the link. We need to create
1551 // some information for the dynamic linker.
1553 // Create the PT_PHDR segment which will hold the program
1555 if (!this->script_options_->saw_phdrs_clause())
1556 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1558 // Create the dynamic symbol table, including the hash table.
1559 Output_section* dynstr;
1560 std::vector<Symbol*> dynamic_symbols;
1561 unsigned int local_dynamic_count;
1562 Versions versions(*this->script_options()->version_script_info(),
1564 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1565 &local_dynamic_count, &dynamic_symbols,
1568 // Create the .interp section to hold the name of the
1569 // interpreter, and put it in a PT_INTERP segment.
1570 if (!parameters->options().shared())
1571 this->create_interp(target);
1573 // Finish the .dynamic section to hold the dynamic data, and put
1574 // it in a PT_DYNAMIC segment.
1575 this->finish_dynamic_section(input_objects, symtab);
1577 // We should have added everything we need to the dynamic string
1579 this->dynpool_.set_string_offsets();
1581 // Create the version sections. We can't do this until the
1582 // dynamic string table is complete.
1583 this->create_version_sections(&versions, symtab, local_dynamic_count,
1584 dynamic_symbols, dynstr);
1586 // Set the size of the _DYNAMIC symbol. We can't do this until
1587 // after we call create_version_sections.
1588 this->set_dynamic_symbol_size(symtab);
1591 if (this->incremental_inputs_)
1593 this->incremental_inputs_->finalize();
1594 this->create_incremental_info_sections();
1597 // Create segment headers.
1598 Output_segment_headers* segment_headers =
1599 (parameters->options().relocatable()
1601 : new Output_segment_headers(this->segment_list_));
1603 // Lay out the file header.
1604 Output_file_header* file_header
1605 = new Output_file_header(target, symtab, segment_headers,
1606 parameters->options().entry());
1608 this->special_output_list_.push_back(file_header);
1609 if (segment_headers != NULL)
1610 this->special_output_list_.push_back(segment_headers);
1612 // Find approriate places for orphan output sections if we are using
1614 if (this->script_options_->saw_sections_clause())
1615 this->place_orphan_sections_in_script();
1617 Output_segment* load_seg;
1622 // Take a snapshot of the section layout as needed.
1623 if (target->may_relax())
1624 this->prepare_for_relaxation();
1626 // Run the relaxation loop to lay out sections.
1629 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1630 phdr_seg, segment_headers, file_header,
1634 while (target->may_relax()
1635 && target->relax(pass, input_objects, symtab, this));
1637 // Set the file offsets of all the non-data sections we've seen so
1638 // far which don't have to wait for the input sections. We need
1639 // this in order to finalize local symbols in non-allocated
1641 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1643 // Set the section indexes of all unallocated sections seen so far,
1644 // in case any of them are somehow referenced by a symbol.
1645 shndx = this->set_section_indexes(shndx);
1647 // Create the symbol table sections.
1648 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1649 if (!parameters->doing_static_link())
1650 this->assign_local_dynsym_offsets(input_objects);
1652 // Process any symbol assignments from a linker script. This must
1653 // be called after the symbol table has been finalized.
1654 this->script_options_->finalize_symbols(symtab, this);
1656 // Create the .shstrtab section.
1657 Output_section* shstrtab_section = this->create_shstrtab();
1659 // Set the file offsets of the rest of the non-data sections which
1660 // don't have to wait for the input sections.
1661 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1663 // Now that all sections have been created, set the section indexes
1664 // for any sections which haven't been done yet.
1665 shndx = this->set_section_indexes(shndx);
1667 // Create the section table header.
1668 this->create_shdrs(shstrtab_section, &off);
1670 // If there are no sections which require postprocessing, we can
1671 // handle the section names now, and avoid a resize later.
1672 if (!this->any_postprocessing_sections_)
1673 off = this->set_section_offsets(off,
1674 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1676 file_header->set_section_info(this->section_headers_, shstrtab_section);
1678 // Now we know exactly where everything goes in the output file
1679 // (except for non-allocated sections which require postprocessing).
1680 Output_data::layout_complete();
1682 this->output_file_size_ = off;
1687 // Create a note header following the format defined in the ELF ABI.
1688 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1689 // of the section to create, DESCSZ is the size of the descriptor.
1690 // ALLOCATE is true if the section should be allocated in memory.
1691 // This returns the new note section. It sets *TRAILING_PADDING to
1692 // the number of trailing zero bytes required.
1695 Layout::create_note(const char* name, int note_type,
1696 const char* section_name, size_t descsz,
1697 bool allocate, size_t* trailing_padding)
1699 // Authorities all agree that the values in a .note field should
1700 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1701 // they differ on what the alignment is for 64-bit binaries.
1702 // The GABI says unambiguously they take 8-byte alignment:
1703 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1704 // Other documentation says alignment should always be 4 bytes:
1705 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1706 // GNU ld and GNU readelf both support the latter (at least as of
1707 // version 2.16.91), and glibc always generates the latter for
1708 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1710 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1711 const int size = parameters->target().get_size();
1713 const int size = 32;
1716 // The contents of the .note section.
1717 size_t namesz = strlen(name) + 1;
1718 size_t aligned_namesz = align_address(namesz, size / 8);
1719 size_t aligned_descsz = align_address(descsz, size / 8);
1721 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1723 unsigned char* buffer = new unsigned char[notehdrsz];
1724 memset(buffer, 0, notehdrsz);
1726 bool is_big_endian = parameters->target().is_big_endian();
1732 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1733 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1734 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1738 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1739 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1740 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1743 else if (size == 64)
1747 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1748 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1749 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1753 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1754 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1755 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1761 memcpy(buffer + 3 * (size / 8), name, namesz);
1763 elfcpp::Elf_Xword flags = 0;
1765 flags = elfcpp::SHF_ALLOC;
1766 Output_section* os = this->choose_output_section(NULL, section_name,
1768 flags, false, false,
1773 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1776 os->add_output_section_data(posd);
1778 *trailing_padding = aligned_descsz - descsz;
1783 // For an executable or shared library, create a note to record the
1784 // version of gold used to create the binary.
1787 Layout::create_gold_note()
1789 if (parameters->options().relocatable())
1792 std::string desc = std::string("gold ") + gold::get_version_string();
1794 size_t trailing_padding;
1795 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1796 ".note.gnu.gold-version", desc.size(),
1797 false, &trailing_padding);
1801 Output_section_data* posd = new Output_data_const(desc, 4);
1802 os->add_output_section_data(posd);
1804 if (trailing_padding > 0)
1806 posd = new Output_data_zero_fill(trailing_padding, 0);
1807 os->add_output_section_data(posd);
1811 // Record whether the stack should be executable. This can be set
1812 // from the command line using the -z execstack or -z noexecstack
1813 // options. Otherwise, if any input file has a .note.GNU-stack
1814 // section with the SHF_EXECINSTR flag set, the stack should be
1815 // executable. Otherwise, if at least one input file a
1816 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1817 // section, we use the target default for whether the stack should be
1818 // executable. Otherwise, we don't generate a stack note. When
1819 // generating a object file, we create a .note.GNU-stack section with
1820 // the appropriate marking. When generating an executable or shared
1821 // library, we create a PT_GNU_STACK segment.
1824 Layout::create_executable_stack_info()
1826 bool is_stack_executable;
1827 if (parameters->options().is_execstack_set())
1828 is_stack_executable = parameters->options().is_stack_executable();
1829 else if (!this->input_with_gnu_stack_note_)
1833 if (this->input_requires_executable_stack_)
1834 is_stack_executable = true;
1835 else if (this->input_without_gnu_stack_note_)
1836 is_stack_executable =
1837 parameters->target().is_default_stack_executable();
1839 is_stack_executable = false;
1842 if (parameters->options().relocatable())
1844 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1845 elfcpp::Elf_Xword flags = 0;
1846 if (is_stack_executable)
1847 flags |= elfcpp::SHF_EXECINSTR;
1848 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags, false,
1853 if (this->script_options_->saw_phdrs_clause())
1855 int flags = elfcpp::PF_R | elfcpp::PF_W;
1856 if (is_stack_executable)
1857 flags |= elfcpp::PF_X;
1858 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1862 // If --build-id was used, set up the build ID note.
1865 Layout::create_build_id()
1867 if (!parameters->options().user_set_build_id())
1870 const char* style = parameters->options().build_id();
1871 if (strcmp(style, "none") == 0)
1874 // Set DESCSZ to the size of the note descriptor. When possible,
1875 // set DESC to the note descriptor contents.
1878 if (strcmp(style, "md5") == 0)
1880 else if (strcmp(style, "sha1") == 0)
1882 else if (strcmp(style, "uuid") == 0)
1884 const size_t uuidsz = 128 / 8;
1886 char buffer[uuidsz];
1887 memset(buffer, 0, uuidsz);
1889 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
1891 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1895 ssize_t got = ::read(descriptor, buffer, uuidsz);
1896 release_descriptor(descriptor, true);
1898 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1899 else if (static_cast<size_t>(got) != uuidsz)
1900 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1904 desc.assign(buffer, uuidsz);
1907 else if (strncmp(style, "0x", 2) == 0)
1910 const char* p = style + 2;
1913 if (hex_p(p[0]) && hex_p(p[1]))
1915 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1919 else if (*p == '-' || *p == ':')
1922 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1925 descsz = desc.size();
1928 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1931 size_t trailing_padding;
1932 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1933 ".note.gnu.build-id", descsz, true,
1940 // We know the value already, so we fill it in now.
1941 gold_assert(desc.size() == descsz);
1943 Output_section_data* posd = new Output_data_const(desc, 4);
1944 os->add_output_section_data(posd);
1946 if (trailing_padding != 0)
1948 posd = new Output_data_zero_fill(trailing_padding, 0);
1949 os->add_output_section_data(posd);
1954 // We need to compute a checksum after we have completed the
1956 gold_assert(trailing_padding == 0);
1957 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
1958 os->add_output_section_data(this->build_id_note_);
1962 // If we have both .stabXX and .stabXXstr sections, then the sh_link
1963 // field of the former should point to the latter. I'm not sure who
1964 // started this, but the GNU linker does it, and some tools depend
1968 Layout::link_stabs_sections()
1970 if (!this->have_stabstr_section_)
1973 for (Section_list::iterator p = this->section_list_.begin();
1974 p != this->section_list_.end();
1977 if ((*p)->type() != elfcpp::SHT_STRTAB)
1980 const char* name = (*p)->name();
1981 if (strncmp(name, ".stab", 5) != 0)
1984 size_t len = strlen(name);
1985 if (strcmp(name + len - 3, "str") != 0)
1988 std::string stab_name(name, len - 3);
1989 Output_section* stab_sec;
1990 stab_sec = this->find_output_section(stab_name.c_str());
1991 if (stab_sec != NULL)
1992 stab_sec->set_link_section(*p);
1996 // Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
1997 // for the next run of incremental linking to check what has changed.
2000 Layout::create_incremental_info_sections()
2002 gold_assert(this->incremental_inputs_ != NULL);
2004 // Add the .gnu_incremental_inputs section.
2005 const char *incremental_inputs_name =
2006 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
2007 Output_section* inputs_os =
2008 this->make_output_section(incremental_inputs_name,
2009 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2011 Output_section_data* posd =
2012 this->incremental_inputs_->create_incremental_inputs_section_data();
2013 inputs_os->add_output_section_data(posd);
2015 // Add the .gnu_incremental_strtab section.
2016 const char *incremental_strtab_name =
2017 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2018 Output_section* strtab_os = this->make_output_section(incremental_strtab_name,
2021 Output_data_strtab* strtab_data =
2022 new Output_data_strtab(this->incremental_inputs_->get_stringpool());
2023 strtab_os->add_output_section_data(strtab_data);
2025 inputs_os->set_link_section(strtab_data);
2028 // Return whether SEG1 should be before SEG2 in the output file. This
2029 // is based entirely on the segment type and flags. When this is
2030 // called the segment addresses has normally not yet been set.
2033 Layout::segment_precedes(const Output_segment* seg1,
2034 const Output_segment* seg2)
2036 elfcpp::Elf_Word type1 = seg1->type();
2037 elfcpp::Elf_Word type2 = seg2->type();
2039 // The single PT_PHDR segment is required to precede any loadable
2040 // segment. We simply make it always first.
2041 if (type1 == elfcpp::PT_PHDR)
2043 gold_assert(type2 != elfcpp::PT_PHDR);
2046 if (type2 == elfcpp::PT_PHDR)
2049 // The single PT_INTERP segment is required to precede any loadable
2050 // segment. We simply make it always second.
2051 if (type1 == elfcpp::PT_INTERP)
2053 gold_assert(type2 != elfcpp::PT_INTERP);
2056 if (type2 == elfcpp::PT_INTERP)
2059 // We then put PT_LOAD segments before any other segments.
2060 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2062 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2065 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2066 // segment, because that is where the dynamic linker expects to find
2067 // it (this is just for efficiency; other positions would also work
2069 if (type1 == elfcpp::PT_TLS
2070 && type2 != elfcpp::PT_TLS
2071 && type2 != elfcpp::PT_GNU_RELRO)
2073 if (type2 == elfcpp::PT_TLS
2074 && type1 != elfcpp::PT_TLS
2075 && type1 != elfcpp::PT_GNU_RELRO)
2078 // We put the PT_GNU_RELRO segment last, because that is where the
2079 // dynamic linker expects to find it (as with PT_TLS, this is just
2081 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2083 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2086 const elfcpp::Elf_Word flags1 = seg1->flags();
2087 const elfcpp::Elf_Word flags2 = seg2->flags();
2089 // The order of non-PT_LOAD segments is unimportant. We simply sort
2090 // by the numeric segment type and flags values. There should not
2091 // be more than one segment with the same type and flags.
2092 if (type1 != elfcpp::PT_LOAD)
2095 return type1 < type2;
2096 gold_assert(flags1 != flags2);
2097 return flags1 < flags2;
2100 // If the addresses are set already, sort by load address.
2101 if (seg1->are_addresses_set())
2103 if (!seg2->are_addresses_set())
2106 unsigned int section_count1 = seg1->output_section_count();
2107 unsigned int section_count2 = seg2->output_section_count();
2108 if (section_count1 == 0 && section_count2 > 0)
2110 if (section_count1 > 0 && section_count2 == 0)
2113 uint64_t paddr1 = seg1->first_section_load_address();
2114 uint64_t paddr2 = seg2->first_section_load_address();
2115 if (paddr1 != paddr2)
2116 return paddr1 < paddr2;
2118 else if (seg2->are_addresses_set())
2121 // A segment which holds large data comes after a segment which does
2122 // not hold large data.
2123 if (seg1->is_large_data_segment())
2125 if (!seg2->is_large_data_segment())
2128 else if (seg2->is_large_data_segment())
2131 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2132 // segments come before writable segments. Then writable segments
2133 // with data come before writable segments without data. Then
2134 // executable segments come before non-executable segments. Then
2135 // the unlikely case of a non-readable segment comes before the
2136 // normal case of a readable segment. If there are multiple
2137 // segments with the same type and flags, we require that the
2138 // address be set, and we sort by virtual address and then physical
2140 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2141 return (flags1 & elfcpp::PF_W) == 0;
2142 if ((flags1 & elfcpp::PF_W) != 0
2143 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2144 return seg1->has_any_data_sections();
2145 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2146 return (flags1 & elfcpp::PF_X) != 0;
2147 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2148 return (flags1 & elfcpp::PF_R) == 0;
2150 // We shouldn't get here--we shouldn't create segments which we
2151 // can't distinguish.
2155 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2158 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2160 uint64_t unsigned_off = off;
2161 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2162 | (addr & (abi_pagesize - 1)));
2163 if (aligned_off < unsigned_off)
2164 aligned_off += abi_pagesize;
2168 // Set the file offsets of all the segments, and all the sections they
2169 // contain. They have all been created. LOAD_SEG must be be laid out
2170 // first. Return the offset of the data to follow.
2173 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2174 unsigned int *pshndx)
2176 // Sort them into the final order.
2177 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2178 Layout::Compare_segments());
2180 // Find the PT_LOAD segments, and set their addresses and offsets
2181 // and their section's addresses and offsets.
2183 if (parameters->options().user_set_Ttext())
2184 addr = parameters->options().Ttext();
2185 else if (parameters->options().output_is_position_independent())
2188 addr = target->default_text_segment_address();
2191 // If LOAD_SEG is NULL, then the file header and segment headers
2192 // will not be loadable. But they still need to be at offset 0 in
2193 // the file. Set their offsets now.
2194 if (load_seg == NULL)
2196 for (Data_list::iterator p = this->special_output_list_.begin();
2197 p != this->special_output_list_.end();
2200 off = align_address(off, (*p)->addralign());
2201 (*p)->set_address_and_file_offset(0, off);
2202 off += (*p)->data_size();
2206 const bool check_sections = parameters->options().check_sections();
2207 Output_segment* last_load_segment = NULL;
2209 bool was_readonly = false;
2210 for (Segment_list::iterator p = this->segment_list_.begin();
2211 p != this->segment_list_.end();
2214 if ((*p)->type() == elfcpp::PT_LOAD)
2216 if (load_seg != NULL && load_seg != *p)
2220 bool are_addresses_set = (*p)->are_addresses_set();
2221 if (are_addresses_set)
2223 // When it comes to setting file offsets, we care about
2224 // the physical address.
2225 addr = (*p)->paddr();
2227 else if (parameters->options().user_set_Tdata()
2228 && ((*p)->flags() & elfcpp::PF_W) != 0
2229 && (!parameters->options().user_set_Tbss()
2230 || (*p)->has_any_data_sections()))
2232 addr = parameters->options().Tdata();
2233 are_addresses_set = true;
2235 else if (parameters->options().user_set_Tbss()
2236 && ((*p)->flags() & elfcpp::PF_W) != 0
2237 && !(*p)->has_any_data_sections())
2239 addr = parameters->options().Tbss();
2240 are_addresses_set = true;
2243 uint64_t orig_addr = addr;
2244 uint64_t orig_off = off;
2246 uint64_t aligned_addr = 0;
2247 uint64_t abi_pagesize = target->abi_pagesize();
2248 uint64_t common_pagesize = target->common_pagesize();
2250 if (!parameters->options().nmagic()
2251 && !parameters->options().omagic())
2252 (*p)->set_minimum_p_align(common_pagesize);
2254 if (!are_addresses_set)
2256 // If the last segment was readonly, and this one is
2257 // not, then skip the address forward one page,
2258 // maintaining the same position within the page. This
2259 // lets us store both segments overlapping on a single
2260 // page in the file, but the loader will put them on
2261 // different pages in memory.
2263 addr = align_address(addr, (*p)->maximum_alignment());
2264 aligned_addr = addr;
2266 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2268 if ((addr & (abi_pagesize - 1)) != 0)
2269 addr = addr + abi_pagesize;
2272 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2275 if (!parameters->options().nmagic()
2276 && !parameters->options().omagic())
2277 off = align_file_offset(off, addr, abi_pagesize);
2278 else if (load_seg == NULL)
2280 // This is -N or -n with a section script which prevents
2281 // us from using a load segment. We need to ensure that
2282 // the file offset is aligned to the alignment of the
2283 // segment. This is because the linker script
2284 // implicitly assumed a zero offset. If we don't align
2285 // here, then the alignment of the sections in the
2286 // linker script may not match the alignment of the
2287 // sections in the set_section_addresses call below,
2288 // causing an error about dot moving backward.
2289 off = align_address(off, (*p)->maximum_alignment());
2292 unsigned int shndx_hold = *pshndx;
2293 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2296 // Now that we know the size of this segment, we may be able
2297 // to save a page in memory, at the cost of wasting some
2298 // file space, by instead aligning to the start of a new
2299 // page. Here we use the real machine page size rather than
2300 // the ABI mandated page size.
2302 if (!are_addresses_set && aligned_addr != addr)
2304 uint64_t first_off = (common_pagesize
2306 & (common_pagesize - 1)));
2307 uint64_t last_off = new_addr & (common_pagesize - 1);
2310 && ((aligned_addr & ~ (common_pagesize - 1))
2311 != (new_addr & ~ (common_pagesize - 1)))
2312 && first_off + last_off <= common_pagesize)
2314 *pshndx = shndx_hold;
2315 addr = align_address(aligned_addr, common_pagesize);
2316 addr = align_address(addr, (*p)->maximum_alignment());
2317 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2318 off = align_file_offset(off, addr, abi_pagesize);
2319 new_addr = (*p)->set_section_addresses(this, true, addr,
2326 if (((*p)->flags() & elfcpp::PF_W) == 0)
2327 was_readonly = true;
2329 // Implement --check-sections. We know that the segments
2330 // are sorted by LMA.
2331 if (check_sections && last_load_segment != NULL)
2333 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2334 if (last_load_segment->paddr() + last_load_segment->memsz()
2337 unsigned long long lb1 = last_load_segment->paddr();
2338 unsigned long long le1 = lb1 + last_load_segment->memsz();
2339 unsigned long long lb2 = (*p)->paddr();
2340 unsigned long long le2 = lb2 + (*p)->memsz();
2341 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2342 "[0x%llx -> 0x%llx]"),
2343 lb1, le1, lb2, le2);
2346 last_load_segment = *p;
2350 // Handle the non-PT_LOAD segments, setting their offsets from their
2351 // section's offsets.
2352 for (Segment_list::iterator p = this->segment_list_.begin();
2353 p != this->segment_list_.end();
2356 if ((*p)->type() != elfcpp::PT_LOAD)
2360 // Set the TLS offsets for each section in the PT_TLS segment.
2361 if (this->tls_segment_ != NULL)
2362 this->tls_segment_->set_tls_offsets();
2367 // Set the offsets of all the allocated sections when doing a
2368 // relocatable link. This does the same jobs as set_segment_offsets,
2369 // only for a relocatable link.
2372 Layout::set_relocatable_section_offsets(Output_data* file_header,
2373 unsigned int *pshndx)
2377 file_header->set_address_and_file_offset(0, 0);
2378 off += file_header->data_size();
2380 for (Section_list::iterator p = this->section_list_.begin();
2381 p != this->section_list_.end();
2384 // We skip unallocated sections here, except that group sections
2385 // have to come first.
2386 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2387 && (*p)->type() != elfcpp::SHT_GROUP)
2390 off = align_address(off, (*p)->addralign());
2392 // The linker script might have set the address.
2393 if (!(*p)->is_address_valid())
2394 (*p)->set_address(0);
2395 (*p)->set_file_offset(off);
2396 (*p)->finalize_data_size();
2397 off += (*p)->data_size();
2399 (*p)->set_out_shndx(*pshndx);
2406 // Set the file offset of all the sections not associated with a
2410 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2412 for (Section_list::iterator p = this->unattached_section_list_.begin();
2413 p != this->unattached_section_list_.end();
2416 // The symtab section is handled in create_symtab_sections.
2417 if (*p == this->symtab_section_)
2420 // If we've already set the data size, don't set it again.
2421 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2424 if (pass == BEFORE_INPUT_SECTIONS_PASS
2425 && (*p)->requires_postprocessing())
2427 (*p)->create_postprocessing_buffer();
2428 this->any_postprocessing_sections_ = true;
2431 if (pass == BEFORE_INPUT_SECTIONS_PASS
2432 && (*p)->after_input_sections())
2434 else if (pass == POSTPROCESSING_SECTIONS_PASS
2435 && (!(*p)->after_input_sections()
2436 || (*p)->type() == elfcpp::SHT_STRTAB))
2438 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2439 && (!(*p)->after_input_sections()
2440 || (*p)->type() != elfcpp::SHT_STRTAB))
2443 off = align_address(off, (*p)->addralign());
2444 (*p)->set_file_offset(off);
2445 (*p)->finalize_data_size();
2446 off += (*p)->data_size();
2448 // At this point the name must be set.
2449 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2450 this->namepool_.add((*p)->name(), false, NULL);
2455 // Set the section indexes of all the sections not associated with a
2459 Layout::set_section_indexes(unsigned int shndx)
2461 for (Section_list::iterator p = this->unattached_section_list_.begin();
2462 p != this->unattached_section_list_.end();
2465 if (!(*p)->has_out_shndx())
2467 (*p)->set_out_shndx(shndx);
2474 // Set the section addresses according to the linker script. This is
2475 // only called when we see a SECTIONS clause. This returns the
2476 // program segment which should hold the file header and segment
2477 // headers, if any. It will return NULL if they should not be in a
2481 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2483 Script_sections* ss = this->script_options_->script_sections();
2484 gold_assert(ss->saw_sections_clause());
2485 return this->script_options_->set_section_addresses(symtab, this);
2488 // Place the orphan sections in the linker script.
2491 Layout::place_orphan_sections_in_script()
2493 Script_sections* ss = this->script_options_->script_sections();
2494 gold_assert(ss->saw_sections_clause());
2496 // Place each orphaned output section in the script.
2497 for (Section_list::iterator p = this->section_list_.begin();
2498 p != this->section_list_.end();
2501 if (!(*p)->found_in_sections_clause())
2502 ss->place_orphan(*p);
2506 // Count the local symbols in the regular symbol table and the dynamic
2507 // symbol table, and build the respective string pools.
2510 Layout::count_local_symbols(const Task* task,
2511 const Input_objects* input_objects)
2513 // First, figure out an upper bound on the number of symbols we'll
2514 // be inserting into each pool. This helps us create the pools with
2515 // the right size, to avoid unnecessary hashtable resizing.
2516 unsigned int symbol_count = 0;
2517 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2518 p != input_objects->relobj_end();
2520 symbol_count += (*p)->local_symbol_count();
2522 // Go from "upper bound" to "estimate." We overcount for two
2523 // reasons: we double-count symbols that occur in more than one
2524 // object file, and we count symbols that are dropped from the
2525 // output. Add it all together and assume we overcount by 100%.
2528 // We assume all symbols will go into both the sympool and dynpool.
2529 this->sympool_.reserve(symbol_count);
2530 this->dynpool_.reserve(symbol_count);
2532 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2533 p != input_objects->relobj_end();
2536 Task_lock_obj<Object> tlo(task, *p);
2537 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2541 // Create the symbol table sections. Here we also set the final
2542 // values of the symbols. At this point all the loadable sections are
2543 // fully laid out. SHNUM is the number of sections so far.
2546 Layout::create_symtab_sections(const Input_objects* input_objects,
2547 Symbol_table* symtab,
2553 if (parameters->target().get_size() == 32)
2555 symsize = elfcpp::Elf_sizes<32>::sym_size;
2558 else if (parameters->target().get_size() == 64)
2560 symsize = elfcpp::Elf_sizes<64>::sym_size;
2567 off = align_address(off, align);
2568 off_t startoff = off;
2570 // Save space for the dummy symbol at the start of the section. We
2571 // never bother to write this out--it will just be left as zero.
2573 unsigned int local_symbol_index = 1;
2575 // Add STT_SECTION symbols for each Output section which needs one.
2576 for (Section_list::iterator p = this->section_list_.begin();
2577 p != this->section_list_.end();
2580 if (!(*p)->needs_symtab_index())
2581 (*p)->set_symtab_index(-1U);
2584 (*p)->set_symtab_index(local_symbol_index);
2585 ++local_symbol_index;
2590 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2591 p != input_objects->relobj_end();
2594 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2596 off += (index - local_symbol_index) * symsize;
2597 local_symbol_index = index;
2600 unsigned int local_symcount = local_symbol_index;
2601 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
2604 size_t dyn_global_index;
2606 if (this->dynsym_section_ == NULL)
2609 dyn_global_index = 0;
2614 dyn_global_index = this->dynsym_section_->info();
2615 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2616 dynoff = this->dynsym_section_->offset() + locsize;
2617 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2618 gold_assert(static_cast<off_t>(dyncount * symsize)
2619 == this->dynsym_section_->data_size() - locsize);
2622 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2623 &this->sympool_, &local_symcount);
2625 if (!parameters->options().strip_all())
2627 this->sympool_.set_string_offsets();
2629 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2630 Output_section* osymtab = this->make_output_section(symtab_name,
2633 this->symtab_section_ = osymtab;
2635 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2638 osymtab->add_output_section_data(pos);
2640 // We generate a .symtab_shndx section if we have more than
2641 // SHN_LORESERVE sections. Technically it is possible that we
2642 // don't need one, because it is possible that there are no
2643 // symbols in any of sections with indexes larger than
2644 // SHN_LORESERVE. That is probably unusual, though, and it is
2645 // easier to always create one than to compute section indexes
2646 // twice (once here, once when writing out the symbols).
2647 if (shnum >= elfcpp::SHN_LORESERVE)
2649 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2651 Output_section* osymtab_xindex =
2652 this->make_output_section(symtab_xindex_name,
2653 elfcpp::SHT_SYMTAB_SHNDX, 0, false,
2656 size_t symcount = (off - startoff) / symsize;
2657 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2659 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2661 osymtab_xindex->set_link_section(osymtab);
2662 osymtab_xindex->set_addralign(4);
2663 osymtab_xindex->set_entsize(4);
2665 osymtab_xindex->set_after_input_sections();
2667 // This tells the driver code to wait until the symbol table
2668 // has written out before writing out the postprocessing
2669 // sections, including the .symtab_shndx section.
2670 this->any_postprocessing_sections_ = true;
2673 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2674 Output_section* ostrtab = this->make_output_section(strtab_name,
2678 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2679 ostrtab->add_output_section_data(pstr);
2681 osymtab->set_file_offset(startoff);
2682 osymtab->finalize_data_size();
2683 osymtab->set_link_section(ostrtab);
2684 osymtab->set_info(local_symcount);
2685 osymtab->set_entsize(symsize);
2691 // Create the .shstrtab section, which holds the names of the
2692 // sections. At the time this is called, we have created all the
2693 // output sections except .shstrtab itself.
2696 Layout::create_shstrtab()
2698 // FIXME: We don't need to create a .shstrtab section if we are
2699 // stripping everything.
2701 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2703 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
2706 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
2708 // We can't write out this section until we've set all the
2709 // section names, and we don't set the names of compressed
2710 // output sections until relocations are complete. FIXME: With
2711 // the current names we use, this is unnecessary.
2712 os->set_after_input_sections();
2715 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2716 os->add_output_section_data(posd);
2721 // Create the section headers. SIZE is 32 or 64. OFF is the file
2725 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2727 Output_section_headers* oshdrs;
2728 oshdrs = new Output_section_headers(this,
2729 &this->segment_list_,
2730 &this->section_list_,
2731 &this->unattached_section_list_,
2734 off_t off = align_address(*poff, oshdrs->addralign());
2735 oshdrs->set_address_and_file_offset(0, off);
2736 off += oshdrs->data_size();
2738 this->section_headers_ = oshdrs;
2741 // Count the allocated sections.
2744 Layout::allocated_output_section_count() const
2746 size_t section_count = 0;
2747 for (Segment_list::const_iterator p = this->segment_list_.begin();
2748 p != this->segment_list_.end();
2750 section_count += (*p)->output_section_count();
2751 return section_count;
2754 // Create the dynamic symbol table.
2757 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2758 Symbol_table* symtab,
2759 Output_section **pdynstr,
2760 unsigned int* plocal_dynamic_count,
2761 std::vector<Symbol*>* pdynamic_symbols,
2762 Versions* pversions)
2764 // Count all the symbols in the dynamic symbol table, and set the
2765 // dynamic symbol indexes.
2767 // Skip symbol 0, which is always all zeroes.
2768 unsigned int index = 1;
2770 // Add STT_SECTION symbols for each Output section which needs one.
2771 for (Section_list::iterator p = this->section_list_.begin();
2772 p != this->section_list_.end();
2775 if (!(*p)->needs_dynsym_index())
2776 (*p)->set_dynsym_index(-1U);
2779 (*p)->set_dynsym_index(index);
2784 // Count the local symbols that need to go in the dynamic symbol table,
2785 // and set the dynamic symbol indexes.
2786 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2787 p != input_objects->relobj_end();
2790 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2794 unsigned int local_symcount = index;
2795 *plocal_dynamic_count = local_symcount;
2797 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2798 &this->dynpool_, pversions);
2802 const int size = parameters->target().get_size();
2805 symsize = elfcpp::Elf_sizes<32>::sym_size;
2808 else if (size == 64)
2810 symsize = elfcpp::Elf_sizes<64>::sym_size;
2816 // Create the dynamic symbol table section.
2818 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2821 false, false, true);
2823 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2826 dynsym->add_output_section_data(odata);
2828 dynsym->set_info(local_symcount);
2829 dynsym->set_entsize(symsize);
2830 dynsym->set_addralign(align);
2832 this->dynsym_section_ = dynsym;
2834 Output_data_dynamic* const odyn = this->dynamic_data_;
2835 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2836 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2838 // If there are more than SHN_LORESERVE allocated sections, we
2839 // create a .dynsym_shndx section. It is possible that we don't
2840 // need one, because it is possible that there are no dynamic
2841 // symbols in any of the sections with indexes larger than
2842 // SHN_LORESERVE. This is probably unusual, though, and at this
2843 // time we don't know the actual section indexes so it is
2844 // inconvenient to check.
2845 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2847 Output_section* dynsym_xindex =
2848 this->choose_output_section(NULL, ".dynsym_shndx",
2849 elfcpp::SHT_SYMTAB_SHNDX,
2851 false, false, true);
2853 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2855 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2857 dynsym_xindex->set_link_section(dynsym);
2858 dynsym_xindex->set_addralign(4);
2859 dynsym_xindex->set_entsize(4);
2861 dynsym_xindex->set_after_input_sections();
2863 // This tells the driver code to wait until the symbol table has
2864 // written out before writing out the postprocessing sections,
2865 // including the .dynsym_shndx section.
2866 this->any_postprocessing_sections_ = true;
2869 // Create the dynamic string table section.
2871 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2874 false, false, true);
2876 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2877 dynstr->add_output_section_data(strdata);
2879 dynsym->set_link_section(dynstr);
2880 this->dynamic_section_->set_link_section(dynstr);
2882 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2883 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2887 // Create the hash tables.
2889 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2890 || strcmp(parameters->options().hash_style(), "both") == 0)
2892 unsigned char* phash;
2893 unsigned int hashlen;
2894 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2897 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2900 false, false, true);
2902 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2906 hashsec->add_output_section_data(hashdata);
2908 hashsec->set_link_section(dynsym);
2909 hashsec->set_entsize(4);
2911 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2914 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2915 || strcmp(parameters->options().hash_style(), "both") == 0)
2917 unsigned char* phash;
2918 unsigned int hashlen;
2919 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2922 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2923 elfcpp::SHT_GNU_HASH,
2925 false, false, true);
2927 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2931 hashsec->add_output_section_data(hashdata);
2933 hashsec->set_link_section(dynsym);
2934 hashsec->set_entsize(4);
2936 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2940 // Assign offsets to each local portion of the dynamic symbol table.
2943 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2945 Output_section* dynsym = this->dynsym_section_;
2946 gold_assert(dynsym != NULL);
2948 off_t off = dynsym->offset();
2950 // Skip the dummy symbol at the start of the section.
2951 off += dynsym->entsize();
2953 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2954 p != input_objects->relobj_end();
2957 unsigned int count = (*p)->set_local_dynsym_offset(off);
2958 off += count * dynsym->entsize();
2962 // Create the version sections.
2965 Layout::create_version_sections(const Versions* versions,
2966 const Symbol_table* symtab,
2967 unsigned int local_symcount,
2968 const std::vector<Symbol*>& dynamic_symbols,
2969 const Output_section* dynstr)
2971 if (!versions->any_defs() && !versions->any_needs())
2974 switch (parameters->size_and_endianness())
2976 #ifdef HAVE_TARGET_32_LITTLE
2977 case Parameters::TARGET_32_LITTLE:
2978 this->sized_create_version_sections<32, false>(versions, symtab,
2980 dynamic_symbols, dynstr);
2983 #ifdef HAVE_TARGET_32_BIG
2984 case Parameters::TARGET_32_BIG:
2985 this->sized_create_version_sections<32, true>(versions, symtab,
2987 dynamic_symbols, dynstr);
2990 #ifdef HAVE_TARGET_64_LITTLE
2991 case Parameters::TARGET_64_LITTLE:
2992 this->sized_create_version_sections<64, false>(versions, symtab,
2994 dynamic_symbols, dynstr);
2997 #ifdef HAVE_TARGET_64_BIG
2998 case Parameters::TARGET_64_BIG:
2999 this->sized_create_version_sections<64, true>(versions, symtab,
3001 dynamic_symbols, dynstr);
3009 // Create the version sections, sized version.
3011 template<int size, bool big_endian>
3013 Layout::sized_create_version_sections(
3014 const Versions* versions,
3015 const Symbol_table* symtab,
3016 unsigned int local_symcount,
3017 const std::vector<Symbol*>& dynamic_symbols,
3018 const Output_section* dynstr)
3020 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3021 elfcpp::SHT_GNU_versym,
3023 false, false, true);
3025 unsigned char* vbuf;
3027 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3032 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3035 vsec->add_output_section_data(vdata);
3036 vsec->set_entsize(2);
3037 vsec->set_link_section(this->dynsym_section_);
3039 Output_data_dynamic* const odyn = this->dynamic_data_;
3040 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3042 if (versions->any_defs())
3044 Output_section* vdsec;
3045 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3046 elfcpp::SHT_GNU_verdef,
3048 false, false, true);
3050 unsigned char* vdbuf;
3051 unsigned int vdsize;
3052 unsigned int vdentries;
3053 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3054 &vdsize, &vdentries);
3056 Output_section_data* vddata =
3057 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3059 vdsec->add_output_section_data(vddata);
3060 vdsec->set_link_section(dynstr);
3061 vdsec->set_info(vdentries);
3063 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3064 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3067 if (versions->any_needs())
3069 Output_section* vnsec;
3070 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3071 elfcpp::SHT_GNU_verneed,
3073 false, false, true);
3075 unsigned char* vnbuf;
3076 unsigned int vnsize;
3077 unsigned int vnentries;
3078 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3082 Output_section_data* vndata =
3083 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3085 vnsec->add_output_section_data(vndata);
3086 vnsec->set_link_section(dynstr);
3087 vnsec->set_info(vnentries);
3089 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3090 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3094 // Create the .interp section and PT_INTERP segment.
3097 Layout::create_interp(const Target* target)
3099 const char* interp = parameters->options().dynamic_linker();
3102 interp = target->dynamic_linker();
3103 gold_assert(interp != NULL);
3106 size_t len = strlen(interp) + 1;
3108 Output_section_data* odata = new Output_data_const(interp, len, 1);
3110 Output_section* osec = this->choose_output_section(NULL, ".interp",
3111 elfcpp::SHT_PROGBITS,
3114 osec->add_output_section_data(odata);
3116 if (!this->script_options_->saw_phdrs_clause())
3118 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3120 oseg->add_output_section(osec, elfcpp::PF_R, false);
3124 // Finish the .dynamic section and PT_DYNAMIC segment.
3127 Layout::finish_dynamic_section(const Input_objects* input_objects,
3128 const Symbol_table* symtab)
3130 if (!this->script_options_->saw_phdrs_clause())
3132 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3135 oseg->add_output_section(this->dynamic_section_,
3136 elfcpp::PF_R | elfcpp::PF_W,
3140 Output_data_dynamic* const odyn = this->dynamic_data_;
3142 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3143 p != input_objects->dynobj_end();
3146 if (!(*p)->is_needed()
3147 && (*p)->input_file()->options().as_needed())
3149 // This dynamic object was linked with --as-needed, but it
3154 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3157 if (parameters->options().shared())
3159 const char* soname = parameters->options().soname();
3161 odyn->add_string(elfcpp::DT_SONAME, soname);
3164 Symbol* sym = symtab->lookup(parameters->options().init());
3165 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3166 odyn->add_symbol(elfcpp::DT_INIT, sym);
3168 sym = symtab->lookup(parameters->options().fini());
3169 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3170 odyn->add_symbol(elfcpp::DT_FINI, sym);
3172 // Look for .init_array, .preinit_array and .fini_array by checking
3174 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3175 p != this->section_list_.end();
3177 switch((*p)->type())
3179 case elfcpp::SHT_FINI_ARRAY:
3180 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3181 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3183 case elfcpp::SHT_INIT_ARRAY:
3184 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3185 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3187 case elfcpp::SHT_PREINIT_ARRAY:
3188 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3189 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3195 // Add a DT_RPATH entry if needed.
3196 const General_options::Dir_list& rpath(parameters->options().rpath());
3199 std::string rpath_val;
3200 for (General_options::Dir_list::const_iterator p = rpath.begin();
3204 if (rpath_val.empty())
3205 rpath_val = p->name();
3208 // Eliminate duplicates.
3209 General_options::Dir_list::const_iterator q;
3210 for (q = rpath.begin(); q != p; ++q)
3211 if (q->name() == p->name())
3216 rpath_val += p->name();
3221 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3222 if (parameters->options().enable_new_dtags())
3223 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3226 // Look for text segments that have dynamic relocations.
3227 bool have_textrel = false;
3228 if (!this->script_options_->saw_sections_clause())
3230 for (Segment_list::const_iterator p = this->segment_list_.begin();
3231 p != this->segment_list_.end();
3234 if (((*p)->flags() & elfcpp::PF_W) == 0
3235 && (*p)->dynamic_reloc_count() > 0)
3237 have_textrel = true;
3244 // We don't know the section -> segment mapping, so we are
3245 // conservative and just look for readonly sections with
3246 // relocations. If those sections wind up in writable segments,
3247 // then we have created an unnecessary DT_TEXTREL entry.
3248 for (Section_list::const_iterator p = this->section_list_.begin();
3249 p != this->section_list_.end();
3252 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3253 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3254 && ((*p)->dynamic_reloc_count() > 0))
3256 have_textrel = true;
3262 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3263 // post-link tools can easily modify these flags if desired.
3264 unsigned int flags = 0;
3267 // Add a DT_TEXTREL for compatibility with older loaders.
3268 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3269 flags |= elfcpp::DF_TEXTREL;
3271 if (parameters->options().shared() && this->has_static_tls())
3272 flags |= elfcpp::DF_STATIC_TLS;
3273 if (parameters->options().origin())
3274 flags |= elfcpp::DF_ORIGIN;
3275 if (parameters->options().Bsymbolic())
3277 flags |= elfcpp::DF_SYMBOLIC;
3278 // Add DT_SYMBOLIC for compatibility with older loaders.
3279 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3281 if (parameters->options().now())
3282 flags |= elfcpp::DF_BIND_NOW;
3283 odyn->add_constant(elfcpp::DT_FLAGS, flags);
3286 if (parameters->options().initfirst())
3287 flags |= elfcpp::DF_1_INITFIRST;
3288 if (parameters->options().interpose())
3289 flags |= elfcpp::DF_1_INTERPOSE;
3290 if (parameters->options().loadfltr())
3291 flags |= elfcpp::DF_1_LOADFLTR;
3292 if (parameters->options().nodefaultlib())
3293 flags |= elfcpp::DF_1_NODEFLIB;
3294 if (parameters->options().nodelete())
3295 flags |= elfcpp::DF_1_NODELETE;
3296 if (parameters->options().nodlopen())
3297 flags |= elfcpp::DF_1_NOOPEN;
3298 if (parameters->options().nodump())
3299 flags |= elfcpp::DF_1_NODUMP;
3300 if (!parameters->options().shared())
3301 flags &= ~(elfcpp::DF_1_INITFIRST
3302 | elfcpp::DF_1_NODELETE
3303 | elfcpp::DF_1_NOOPEN);
3304 if (parameters->options().origin())
3305 flags |= elfcpp::DF_1_ORIGIN;
3306 if (parameters->options().now())
3307 flags |= elfcpp::DF_1_NOW;
3309 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3312 // Set the size of the _DYNAMIC symbol table to be the size of the
3316 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
3318 Output_data_dynamic* const odyn = this->dynamic_data_;
3319 odyn->finalize_data_size();
3320 off_t data_size = odyn->data_size();
3321 const int size = parameters->target().get_size();
3323 symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
3324 else if (size == 64)
3325 symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
3330 // The mapping of input section name prefixes to output section names.
3331 // In some cases one prefix is itself a prefix of another prefix; in
3332 // such a case the longer prefix must come first. These prefixes are
3333 // based on the GNU linker default ELF linker script.
3335 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3336 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3338 MAPPING_INIT(".text.", ".text"),
3339 MAPPING_INIT(".ctors.", ".ctors"),
3340 MAPPING_INIT(".dtors.", ".dtors"),
3341 MAPPING_INIT(".rodata.", ".rodata"),
3342 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3343 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3344 MAPPING_INIT(".data.", ".data"),
3345 MAPPING_INIT(".bss.", ".bss"),
3346 MAPPING_INIT(".tdata.", ".tdata"),
3347 MAPPING_INIT(".tbss.", ".tbss"),
3348 MAPPING_INIT(".init_array.", ".init_array"),
3349 MAPPING_INIT(".fini_array.", ".fini_array"),
3350 MAPPING_INIT(".sdata.", ".sdata"),
3351 MAPPING_INIT(".sbss.", ".sbss"),
3352 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3353 // differently depending on whether it is creating a shared library.
3354 MAPPING_INIT(".sdata2.", ".sdata"),
3355 MAPPING_INIT(".sbss2.", ".sbss"),
3356 MAPPING_INIT(".lrodata.", ".lrodata"),
3357 MAPPING_INIT(".ldata.", ".ldata"),
3358 MAPPING_INIT(".lbss.", ".lbss"),
3359 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3360 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3361 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3362 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3363 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3364 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3365 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3366 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3367 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3368 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3369 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3370 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3371 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3372 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3373 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3374 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3375 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3376 MAPPING_INIT(".ARM.extab.", ".ARM.extab"),
3377 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3378 MAPPING_INIT(".ARM.exidx.", ".ARM.exidx"),
3379 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3383 const int Layout::section_name_mapping_count =
3384 (sizeof(Layout::section_name_mapping)
3385 / sizeof(Layout::section_name_mapping[0]));
3387 // Choose the output section name to use given an input section name.
3388 // Set *PLEN to the length of the name. *PLEN is initialized to the
3392 Layout::output_section_name(const char* name, size_t* plen)
3394 // gcc 4.3 generates the following sorts of section names when it
3395 // needs a section name specific to a function:
3401 // .data.rel.local.FN
3403 // .data.rel.ro.local.FN
3410 // The GNU linker maps all of those to the part before the .FN,
3411 // except that .data.rel.local.FN is mapped to .data, and
3412 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3413 // beginning with .data.rel.ro.local are grouped together.
3415 // For an anonymous namespace, the string FN can contain a '.'.
3417 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3418 // GNU linker maps to .rodata.
3420 // The .data.rel.ro sections are used with -z relro. The sections
3421 // are recognized by name. We use the same names that the GNU
3422 // linker does for these sections.
3424 // It is hard to handle this in a principled way, so we don't even
3425 // try. We use a table of mappings. If the input section name is
3426 // not found in the table, we simply use it as the output section
3429 const Section_name_mapping* psnm = section_name_mapping;
3430 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3432 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3434 *plen = psnm->tolen;
3442 // Check if a comdat group or .gnu.linkonce section with the given
3443 // NAME is selected for the link. If there is already a section,
3444 // *KEPT_SECTION is set to point to the existing section and the
3445 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3446 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3447 // *KEPT_SECTION is set to the internal copy and the function returns
3451 Layout::find_or_add_kept_section(const std::string& name,
3456 Kept_section** kept_section)
3458 // It's normal to see a couple of entries here, for the x86 thunk
3459 // sections. If we see more than a few, we're linking a C++
3460 // program, and we resize to get more space to minimize rehashing.
3461 if (this->signatures_.size() > 4
3462 && !this->resized_signatures_)
3464 reserve_unordered_map(&this->signatures_,
3465 this->number_of_input_files_ * 64);
3466 this->resized_signatures_ = true;
3469 Kept_section candidate;
3470 std::pair<Signatures::iterator, bool> ins =
3471 this->signatures_.insert(std::make_pair(name, candidate));
3473 if (kept_section != NULL)
3474 *kept_section = &ins.first->second;
3477 // This is the first time we've seen this signature.
3478 ins.first->second.set_object(object);
3479 ins.first->second.set_shndx(shndx);
3481 ins.first->second.set_is_comdat();
3483 ins.first->second.set_is_group_name();
3487 // We have already seen this signature.
3489 if (ins.first->second.is_group_name())
3491 // We've already seen a real section group with this signature.
3492 // If the kept group is from a plugin object, and we're in the
3493 // replacement phase, accept the new one as a replacement.
3494 if (ins.first->second.object() == NULL
3495 && parameters->options().plugins()->in_replacement_phase())
3497 ins.first->second.set_object(object);
3498 ins.first->second.set_shndx(shndx);
3503 else if (is_group_name)
3505 // This is a real section group, and we've already seen a
3506 // linkonce section with this signature. Record that we've seen
3507 // a section group, and don't include this section group.
3508 ins.first->second.set_is_group_name();
3513 // We've already seen a linkonce section and this is a linkonce
3514 // section. These don't block each other--this may be the same
3515 // symbol name with different section types.
3520 // Store the allocated sections into the section list.
3523 Layout::get_allocated_sections(Section_list* section_list) const
3525 for (Section_list::const_iterator p = this->section_list_.begin();
3526 p != this->section_list_.end();
3528 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3529 section_list->push_back(*p);
3532 // Create an output segment.
3535 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3537 gold_assert(!parameters->options().relocatable());
3538 Output_segment* oseg = new Output_segment(type, flags);
3539 this->segment_list_.push_back(oseg);
3541 if (type == elfcpp::PT_TLS)
3542 this->tls_segment_ = oseg;
3543 else if (type == elfcpp::PT_GNU_RELRO)
3544 this->relro_segment_ = oseg;
3549 // Write out the Output_sections. Most won't have anything to write,
3550 // since most of the data will come from input sections which are
3551 // handled elsewhere. But some Output_sections do have Output_data.
3554 Layout::write_output_sections(Output_file* of) const
3556 for (Section_list::const_iterator p = this->section_list_.begin();
3557 p != this->section_list_.end();
3560 if (!(*p)->after_input_sections())
3565 // Write out data not associated with a section or the symbol table.
3568 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
3570 if (!parameters->options().strip_all())
3572 const Output_section* symtab_section = this->symtab_section_;
3573 for (Section_list::const_iterator p = this->section_list_.begin();
3574 p != this->section_list_.end();
3577 if ((*p)->needs_symtab_index())
3579 gold_assert(symtab_section != NULL);
3580 unsigned int index = (*p)->symtab_index();
3581 gold_assert(index > 0 && index != -1U);
3582 off_t off = (symtab_section->offset()
3583 + index * symtab_section->entsize());
3584 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3589 const Output_section* dynsym_section = this->dynsym_section_;
3590 for (Section_list::const_iterator p = this->section_list_.begin();
3591 p != this->section_list_.end();
3594 if ((*p)->needs_dynsym_index())
3596 gold_assert(dynsym_section != NULL);
3597 unsigned int index = (*p)->dynsym_index();
3598 gold_assert(index > 0 && index != -1U);
3599 off_t off = (dynsym_section->offset()
3600 + index * dynsym_section->entsize());
3601 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3605 // Write out the Output_data which are not in an Output_section.
3606 for (Data_list::const_iterator p = this->special_output_list_.begin();
3607 p != this->special_output_list_.end();
3612 // Write out the Output_sections which can only be written after the
3613 // input sections are complete.
3616 Layout::write_sections_after_input_sections(Output_file* of)
3618 // Determine the final section offsets, and thus the final output
3619 // file size. Note we finalize the .shstrab last, to allow the
3620 // after_input_section sections to modify their section-names before
3622 if (this->any_postprocessing_sections_)
3624 off_t off = this->output_file_size_;
3625 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3627 // Now that we've finalized the names, we can finalize the shstrab.
3629 this->set_section_offsets(off,
3630 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3632 if (off > this->output_file_size_)
3635 this->output_file_size_ = off;
3639 for (Section_list::const_iterator p = this->section_list_.begin();
3640 p != this->section_list_.end();
3643 if ((*p)->after_input_sections())
3647 this->section_headers_->write(of);
3650 // If the build ID requires computing a checksum, do so here, and
3651 // write it out. We compute a checksum over the entire file because
3652 // that is simplest.
3655 Layout::write_build_id(Output_file* of) const
3657 if (this->build_id_note_ == NULL)
3660 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3662 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3663 this->build_id_note_->data_size());
3665 const char* style = parameters->options().build_id();
3666 if (strcmp(style, "sha1") == 0)
3669 sha1_init_ctx(&ctx);
3670 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3671 sha1_finish_ctx(&ctx, ov);
3673 else if (strcmp(style, "md5") == 0)
3677 md5_process_bytes(iv, this->output_file_size_, &ctx);
3678 md5_finish_ctx(&ctx, ov);
3683 of->write_output_view(this->build_id_note_->offset(),
3684 this->build_id_note_->data_size(),
3687 of->free_input_view(0, this->output_file_size_, iv);
3690 // Write out a binary file. This is called after the link is
3691 // complete. IN is the temporary output file we used to generate the
3692 // ELF code. We simply walk through the segments, read them from
3693 // their file offset in IN, and write them to their load address in
3694 // the output file. FIXME: with a bit more work, we could support
3695 // S-records and/or Intel hex format here.
3698 Layout::write_binary(Output_file* in) const
3700 gold_assert(parameters->options().oformat_enum()
3701 == General_options::OBJECT_FORMAT_BINARY);
3703 // Get the size of the binary file.
3704 uint64_t max_load_address = 0;
3705 for (Segment_list::const_iterator p = this->segment_list_.begin();
3706 p != this->segment_list_.end();
3709 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3711 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3712 if (max_paddr > max_load_address)
3713 max_load_address = max_paddr;
3717 Output_file out(parameters->options().output_file_name());
3718 out.open(max_load_address);
3720 for (Segment_list::const_iterator p = this->segment_list_.begin();
3721 p != this->segment_list_.end();
3724 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3726 const unsigned char* vin = in->get_input_view((*p)->offset(),
3728 unsigned char* vout = out.get_output_view((*p)->paddr(),
3730 memcpy(vout, vin, (*p)->filesz());
3731 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3732 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3739 // Print the output sections to the map file.
3742 Layout::print_to_mapfile(Mapfile* mapfile) const
3744 for (Segment_list::const_iterator p = this->segment_list_.begin();
3745 p != this->segment_list_.end();
3747 (*p)->print_sections_to_mapfile(mapfile);
3750 // Print statistical information to stderr. This is used for --stats.
3753 Layout::print_stats() const
3755 this->namepool_.print_stats("section name pool");
3756 this->sympool_.print_stats("output symbol name pool");
3757 this->dynpool_.print_stats("dynamic name pool");
3759 for (Section_list::const_iterator p = this->section_list_.begin();
3760 p != this->section_list_.end();
3762 (*p)->print_merge_stats();
3765 // Write_sections_task methods.
3767 // We can always run this task.
3770 Write_sections_task::is_runnable()
3775 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3779 Write_sections_task::locks(Task_locker* tl)
3781 tl->add(this, this->output_sections_blocker_);
3782 tl->add(this, this->final_blocker_);
3785 // Run the task--write out the data.
3788 Write_sections_task::run(Workqueue*)
3790 this->layout_->write_output_sections(this->of_);
3793 // Write_data_task methods.
3795 // We can always run this task.
3798 Write_data_task::is_runnable()
3803 // We need to unlock FINAL_BLOCKER when finished.
3806 Write_data_task::locks(Task_locker* tl)
3808 tl->add(this, this->final_blocker_);
3811 // Run the task--write out the data.
3814 Write_data_task::run(Workqueue*)
3816 this->layout_->write_data(this->symtab_, this->of_);
3819 // Write_symbols_task methods.
3821 // We can always run this task.
3824 Write_symbols_task::is_runnable()
3829 // We need to unlock FINAL_BLOCKER when finished.
3832 Write_symbols_task::locks(Task_locker* tl)
3834 tl->add(this, this->final_blocker_);
3837 // Run the task--write out the symbols.
3840 Write_symbols_task::run(Workqueue*)
3842 this->symtab_->write_globals(this->sympool_, this->dynpool_,
3843 this->layout_->symtab_xindex(),
3844 this->layout_->dynsym_xindex(), this->of_);
3847 // Write_after_input_sections_task methods.
3849 // We can only run this task after the input sections have completed.
3852 Write_after_input_sections_task::is_runnable()
3854 if (this->input_sections_blocker_->is_blocked())
3855 return this->input_sections_blocker_;
3859 // We need to unlock FINAL_BLOCKER when finished.
3862 Write_after_input_sections_task::locks(Task_locker* tl)
3864 tl->add(this, this->final_blocker_);
3870 Write_after_input_sections_task::run(Workqueue*)
3872 this->layout_->write_sections_after_input_sections(this->of_);
3875 // Close_task_runner methods.
3877 // Run the task--close the file.
3880 Close_task_runner::run(Workqueue*, const Task*)
3882 // If we need to compute a checksum for the BUILD if, we do so here.
3883 this->layout_->write_build_id(this->of_);
3885 // If we've been asked to create a binary file, we do so here.
3886 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3887 this->layout_->write_binary(this->of_);
3892 // Instantiate the templates we need. We could use the configure
3893 // script to restrict this to only the ones for implemented targets.
3895 #ifdef HAVE_TARGET_32_LITTLE
3898 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3900 const elfcpp::Shdr<32, false>& shdr,
3901 unsigned int, unsigned int, off_t*);
3904 #ifdef HAVE_TARGET_32_BIG
3907 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3909 const elfcpp::Shdr<32, true>& shdr,
3910 unsigned int, unsigned int, off_t*);
3913 #ifdef HAVE_TARGET_64_LITTLE
3916 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3918 const elfcpp::Shdr<64, false>& shdr,
3919 unsigned int, unsigned int, off_t*);
3922 #ifdef HAVE_TARGET_64_BIG
3925 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3927 const elfcpp::Shdr<64, true>& shdr,
3928 unsigned int, unsigned int, off_t*);
3931 #ifdef HAVE_TARGET_32_LITTLE
3934 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3935 unsigned int reloc_shndx,
3936 const elfcpp::Shdr<32, false>& shdr,
3937 Output_section* data_section,
3938 Relocatable_relocs* rr);
3941 #ifdef HAVE_TARGET_32_BIG
3944 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3945 unsigned int reloc_shndx,
3946 const elfcpp::Shdr<32, true>& shdr,
3947 Output_section* data_section,
3948 Relocatable_relocs* rr);
3951 #ifdef HAVE_TARGET_64_LITTLE
3954 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3955 unsigned int reloc_shndx,
3956 const elfcpp::Shdr<64, false>& shdr,
3957 Output_section* data_section,
3958 Relocatable_relocs* rr);
3961 #ifdef HAVE_TARGET_64_BIG
3964 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3965 unsigned int reloc_shndx,
3966 const elfcpp::Shdr<64, true>& shdr,
3967 Output_section* data_section,
3968 Relocatable_relocs* rr);
3971 #ifdef HAVE_TARGET_32_LITTLE
3974 Layout::layout_group<32, false>(Symbol_table* symtab,
3975 Sized_relobj<32, false>* object,
3977 const char* group_section_name,
3978 const char* signature,
3979 const elfcpp::Shdr<32, false>& shdr,
3980 elfcpp::Elf_Word flags,
3981 std::vector<unsigned int>* shndxes);
3984 #ifdef HAVE_TARGET_32_BIG
3987 Layout::layout_group<32, true>(Symbol_table* symtab,
3988 Sized_relobj<32, true>* object,
3990 const char* group_section_name,
3991 const char* signature,
3992 const elfcpp::Shdr<32, true>& shdr,
3993 elfcpp::Elf_Word flags,
3994 std::vector<unsigned int>* shndxes);
3997 #ifdef HAVE_TARGET_64_LITTLE
4000 Layout::layout_group<64, false>(Symbol_table* symtab,
4001 Sized_relobj<64, false>* object,
4003 const char* group_section_name,
4004 const char* signature,
4005 const elfcpp::Shdr<64, false>& shdr,
4006 elfcpp::Elf_Word flags,
4007 std::vector<unsigned int>* shndxes);
4010 #ifdef HAVE_TARGET_64_BIG
4013 Layout::layout_group<64, true>(Symbol_table* symtab,
4014 Sized_relobj<64, true>* object,
4016 const char* group_section_name,
4017 const char* signature,
4018 const elfcpp::Shdr<64, true>& shdr,
4019 elfcpp::Elf_Word flags,
4020 std::vector<unsigned int>* shndxes);
4023 #ifdef HAVE_TARGET_32_LITTLE
4026 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
4027 const unsigned char* symbols,
4029 const unsigned char* symbol_names,
4030 off_t symbol_names_size,
4032 const elfcpp::Shdr<32, false>& shdr,
4033 unsigned int reloc_shndx,
4034 unsigned int reloc_type,
4038 #ifdef HAVE_TARGET_32_BIG
4041 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4042 const unsigned char* symbols,
4044 const unsigned char* symbol_names,
4045 off_t symbol_names_size,
4047 const elfcpp::Shdr<32, true>& shdr,
4048 unsigned int reloc_shndx,
4049 unsigned int reloc_type,
4053 #ifdef HAVE_TARGET_64_LITTLE
4056 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4057 const unsigned char* symbols,
4059 const unsigned char* symbol_names,
4060 off_t symbol_names_size,
4062 const elfcpp::Shdr<64, false>& shdr,
4063 unsigned int reloc_shndx,
4064 unsigned int reloc_type,
4068 #ifdef HAVE_TARGET_64_BIG
4071 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4072 const unsigned char* symbols,
4074 const unsigned char* symbol_names,
4075 off_t symbol_names_size,
4077 const elfcpp::Shdr<64, true>& shdr,
4078 unsigned int reloc_shndx,
4079 unsigned int reloc_type,
4083 } // End namespace gold.