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),
184 eh_frame_section_(NULL),
185 eh_frame_data_(NULL),
186 added_eh_frame_data_(false),
187 eh_frame_hdr_section_(NULL),
188 build_id_note_(NULL),
192 output_file_size_(-1),
193 sections_are_attached_(false),
194 input_requires_executable_stack_(false),
195 input_with_gnu_stack_note_(false),
196 input_without_gnu_stack_note_(false),
197 has_static_tls_(false),
198 any_postprocessing_sections_(false),
199 resized_signatures_(false),
200 have_stabstr_section_(false),
201 incremental_inputs_(NULL),
202 record_output_section_data_from_script_(false),
203 script_output_section_data_list_(),
204 segment_states_(NULL),
205 relaxation_debug_check_(NULL)
207 // Make space for more than enough segments for a typical file.
208 // This is just for efficiency--it's OK if we wind up needing more.
209 this->segment_list_.reserve(12);
211 // We expect two unattached Output_data objects: the file header and
212 // the segment headers.
213 this->special_output_list_.reserve(2);
215 // Initialize structure needed for an incremental build.
216 if (parameters->options().incremental())
217 this->incremental_inputs_ = new Incremental_inputs;
219 // The section name pool is worth optimizing in all cases, because
220 // it is small, but there are often overlaps due to .rel sections.
221 this->namepool_.set_optimize();
224 // Hash a key we use to look up an output section mapping.
227 Layout::Hash_key::operator()(const Layout::Key& k) const
229 return k.first + k.second.first + k.second.second;
232 // Returns whether the given section is in the list of
233 // debug-sections-used-by-some-version-of-gdb. Currently,
234 // we've checked versions of gdb up to and including 6.7.1.
236 static const char* gdb_sections[] =
238 // ".debug_aranges", // not used by gdb as of 6.7.1
244 // ".debug_pubnames", // not used by gdb as of 6.7.1
249 static const char* lines_only_debug_sections[] =
251 // ".debug_aranges", // not used by gdb as of 6.7.1
257 // ".debug_pubnames", // not used by gdb as of 6.7.1
263 is_gdb_debug_section(const char* str)
265 // We can do this faster: binary search or a hashtable. But why bother?
266 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
267 if (strcmp(str, gdb_sections[i]) == 0)
273 is_lines_only_debug_section(const char* str)
275 // We can do this faster: binary search or a hashtable. But why bother?
277 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
279 if (strcmp(str, lines_only_debug_sections[i]) == 0)
284 // Whether to include this section in the link.
286 template<int size, bool big_endian>
288 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
289 const elfcpp::Shdr<size, big_endian>& shdr)
291 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
294 switch (shdr.get_sh_type())
296 case elfcpp::SHT_NULL:
297 case elfcpp::SHT_SYMTAB:
298 case elfcpp::SHT_DYNSYM:
299 case elfcpp::SHT_HASH:
300 case elfcpp::SHT_DYNAMIC:
301 case elfcpp::SHT_SYMTAB_SHNDX:
304 case elfcpp::SHT_STRTAB:
305 // Discard the sections which have special meanings in the ELF
306 // ABI. Keep others (e.g., .stabstr). We could also do this by
307 // checking the sh_link fields of the appropriate sections.
308 return (strcmp(name, ".dynstr") != 0
309 && strcmp(name, ".strtab") != 0
310 && strcmp(name, ".shstrtab") != 0);
312 case elfcpp::SHT_RELA:
313 case elfcpp::SHT_REL:
314 case elfcpp::SHT_GROUP:
315 // If we are emitting relocations these should be handled
317 gold_assert(!parameters->options().relocatable()
318 && !parameters->options().emit_relocs());
321 case elfcpp::SHT_PROGBITS:
322 if (parameters->options().strip_debug()
323 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
325 if (is_debug_info_section(name))
328 if (parameters->options().strip_debug_non_line()
329 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
331 // Debugging sections can only be recognized by name.
332 if (is_prefix_of(".debug", name)
333 && !is_lines_only_debug_section(name))
336 if (parameters->options().strip_debug_gdb()
337 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
339 // Debugging sections can only be recognized by name.
340 if (is_prefix_of(".debug", name)
341 && !is_gdb_debug_section(name))
344 if (parameters->options().strip_lto_sections()
345 && !parameters->options().relocatable()
346 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
348 // Ignore LTO sections containing intermediate code.
349 if (is_prefix_of(".gnu.lto_", name))
359 // Return an output section named NAME, or NULL if there is none.
362 Layout::find_output_section(const char* name) const
364 for (Section_list::const_iterator p = this->section_list_.begin();
365 p != this->section_list_.end();
367 if (strcmp((*p)->name(), name) == 0)
372 // Return an output segment of type TYPE, with segment flags SET set
373 // and segment flags CLEAR clear. Return NULL if there is none.
376 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
377 elfcpp::Elf_Word clear) const
379 for (Segment_list::const_iterator p = this->segment_list_.begin();
380 p != this->segment_list_.end();
382 if (static_cast<elfcpp::PT>((*p)->type()) == type
383 && ((*p)->flags() & set) == set
384 && ((*p)->flags() & clear) == 0)
389 // Return the output section to use for section NAME with type TYPE
390 // and section flags FLAGS. NAME must be canonicalized in the string
391 // pool, and NAME_KEY is the key. IS_INTERP is true if this is the
392 // .interp section. IS_DYNAMIC_LINKER_SECTION is true if this section
393 // is used by the dynamic linker.
396 Layout::get_output_section(const char* name, Stringpool::Key name_key,
397 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
398 bool is_interp, bool is_dynamic_linker_section)
400 elfcpp::Elf_Xword lookup_flags = flags;
402 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
403 // read-write with read-only sections. Some other ELF linkers do
404 // not do this. FIXME: Perhaps there should be an option
406 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
408 const Key key(name_key, std::make_pair(type, lookup_flags));
409 const std::pair<Key, Output_section*> v(key, NULL);
410 std::pair<Section_name_map::iterator, bool> ins(
411 this->section_name_map_.insert(v));
414 return ins.first->second;
417 // This is the first time we've seen this name/type/flags
418 // combination. For compatibility with the GNU linker, we
419 // combine sections with contents and zero flags with sections
420 // with non-zero flags. This is a workaround for cases where
421 // assembler code forgets to set section flags. FIXME: Perhaps
422 // there should be an option to control this.
423 Output_section* os = NULL;
425 if (type == elfcpp::SHT_PROGBITS)
429 Output_section* same_name = this->find_output_section(name);
430 if (same_name != NULL
431 && same_name->type() == elfcpp::SHT_PROGBITS
432 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
435 else if ((flags & elfcpp::SHF_TLS) == 0)
437 elfcpp::Elf_Xword zero_flags = 0;
438 const Key zero_key(name_key, std::make_pair(type, zero_flags));
439 Section_name_map::iterator p =
440 this->section_name_map_.find(zero_key);
441 if (p != this->section_name_map_.end())
447 os = this->make_output_section(name, type, flags, is_interp,
448 is_dynamic_linker_section);
449 ins.first->second = os;
454 // Pick the output section to use for section NAME, in input file
455 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
456 // linker created section. IS_INPUT_SECTION is true if we are
457 // choosing an output section for an input section found in a input
458 // file. IS_INTERP is true if this is the .interp section.
459 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
460 // dynamic linker. This will return NULL if the input section should
464 Layout::choose_output_section(const Relobj* relobj, const char* name,
465 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
466 bool is_input_section, bool is_interp,
467 bool is_dynamic_linker_section)
469 // We should not see any input sections after we have attached
470 // sections to segments.
471 gold_assert(!is_input_section || !this->sections_are_attached_);
473 // Some flags in the input section should not be automatically
474 // copied to the output section.
475 flags &= ~ (elfcpp::SHF_INFO_LINK
476 | elfcpp::SHF_LINK_ORDER
479 | elfcpp::SHF_STRINGS);
481 if (this->script_options_->saw_sections_clause())
483 // We are using a SECTIONS clause, so the output section is
484 // chosen based only on the name.
486 Script_sections* ss = this->script_options_->script_sections();
487 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
488 Output_section** output_section_slot;
489 name = ss->output_section_name(file_name, name, &output_section_slot);
492 // The SECTIONS clause says to discard this input section.
496 // If this is an orphan section--one not mentioned in the linker
497 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
498 // default processing below.
500 if (output_section_slot != NULL)
502 if (*output_section_slot != NULL)
504 (*output_section_slot)->update_flags_for_input_section(flags);
505 return *output_section_slot;
508 // We don't put sections found in the linker script into
509 // SECTION_NAME_MAP_. That keeps us from getting confused
510 // if an orphan section is mapped to a section with the same
511 // name as one in the linker script.
513 name = this->namepool_.add(name, false, NULL);
516 this->make_output_section(name, type, flags, is_interp,
517 is_dynamic_linker_section);
518 os->set_found_in_sections_clause();
519 *output_section_slot = os;
524 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
526 // Turn NAME from the name of the input section into the name of the
529 size_t len = strlen(name);
531 && !this->script_options_->saw_sections_clause()
532 && !parameters->options().relocatable())
533 name = Layout::output_section_name(name, &len);
535 Stringpool::Key name_key;
536 name = this->namepool_.add_with_length(name, len, true, &name_key);
538 // Find or make the output section. The output section is selected
539 // based on the section name, type, and flags.
540 return this->get_output_section(name, name_key, type, flags, is_interp,
541 is_dynamic_linker_section);
544 // Return the output section to use for input section SHNDX, with name
545 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
546 // index of a relocation section which applies to this section, or 0
547 // if none, or -1U if more than one. RELOC_TYPE is the type of the
548 // relocation section if there is one. Set *OFF to the offset of this
549 // input section without the output section. Return NULL if the
550 // section should be discarded. Set *OFF to -1 if the section
551 // contents should not be written directly to the output file, but
552 // will instead receive special handling.
554 template<int size, bool big_endian>
556 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
557 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
558 unsigned int reloc_shndx, unsigned int, off_t* off)
562 if (!this->include_section(object, name, shdr))
567 // In a relocatable link a grouped section must not be combined with
568 // any other sections.
569 if (parameters->options().relocatable()
570 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
572 name = this->namepool_.add(name, true, NULL);
573 os = this->make_output_section(name, shdr.get_sh_type(),
574 shdr.get_sh_flags(), false, false);
578 os = this->choose_output_section(object, name, shdr.get_sh_type(),
579 shdr.get_sh_flags(), true, false,
585 // By default the GNU linker sorts input sections whose names match
586 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
587 // are sorted by name. This is used to implement constructor
588 // priority ordering. We are compatible.
589 if (!this->script_options_->saw_sections_clause()
590 && (is_prefix_of(".ctors.", name)
591 || is_prefix_of(".dtors.", name)
592 || is_prefix_of(".init_array.", name)
593 || is_prefix_of(".fini_array.", name)))
594 os->set_must_sort_attached_input_sections();
596 // FIXME: Handle SHF_LINK_ORDER somewhere.
598 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
599 this->script_options_->saw_sections_clause());
604 // Handle a relocation section when doing a relocatable link.
606 template<int size, bool big_endian>
608 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
610 const elfcpp::Shdr<size, big_endian>& shdr,
611 Output_section* data_section,
612 Relocatable_relocs* rr)
614 gold_assert(parameters->options().relocatable()
615 || parameters->options().emit_relocs());
617 int sh_type = shdr.get_sh_type();
620 if (sh_type == elfcpp::SHT_REL)
622 else if (sh_type == elfcpp::SHT_RELA)
626 name += data_section->name();
628 Output_section* os = this->choose_output_section(object, name.c_str(),
631 false, false, false);
633 os->set_should_link_to_symtab();
634 os->set_info_section(data_section);
636 Output_section_data* posd;
637 if (sh_type == elfcpp::SHT_REL)
639 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
640 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
644 else if (sh_type == elfcpp::SHT_RELA)
646 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
647 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
654 os->add_output_section_data(posd);
655 rr->set_output_data(posd);
660 // Handle a group section when doing a relocatable link.
662 template<int size, bool big_endian>
664 Layout::layout_group(Symbol_table* symtab,
665 Sized_relobj<size, big_endian>* object,
667 const char* group_section_name,
668 const char* signature,
669 const elfcpp::Shdr<size, big_endian>& shdr,
670 elfcpp::Elf_Word flags,
671 std::vector<unsigned int>* shndxes)
673 gold_assert(parameters->options().relocatable());
674 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
675 group_section_name = this->namepool_.add(group_section_name, true, NULL);
676 Output_section* os = this->make_output_section(group_section_name,
681 // We need to find a symbol with the signature in the symbol table.
682 // If we don't find one now, we need to look again later.
683 Symbol* sym = symtab->lookup(signature, NULL);
685 os->set_info_symndx(sym);
688 // Reserve some space to minimize reallocations.
689 if (this->group_signatures_.empty())
690 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
692 // We will wind up using a symbol whose name is the signature.
693 // So just put the signature in the symbol name pool to save it.
694 signature = symtab->canonicalize_name(signature);
695 this->group_signatures_.push_back(Group_signature(os, signature));
698 os->set_should_link_to_symtab();
701 section_size_type entry_count =
702 convert_to_section_size_type(shdr.get_sh_size() / 4);
703 Output_section_data* posd =
704 new Output_data_group<size, big_endian>(object, entry_count, flags,
706 os->add_output_section_data(posd);
709 // Special GNU handling of sections name .eh_frame. They will
710 // normally hold exception frame data as defined by the C++ ABI
711 // (http://codesourcery.com/cxx-abi/).
713 template<int size, bool big_endian>
715 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
716 const unsigned char* symbols,
718 const unsigned char* symbol_names,
719 off_t symbol_names_size,
721 const elfcpp::Shdr<size, big_endian>& shdr,
722 unsigned int reloc_shndx, unsigned int reloc_type,
725 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
726 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
728 const char* const name = ".eh_frame";
729 Output_section* os = this->choose_output_section(object,
731 elfcpp::SHT_PROGBITS,
733 false, false, false);
737 if (this->eh_frame_section_ == NULL)
739 this->eh_frame_section_ = os;
740 this->eh_frame_data_ = new Eh_frame();
742 if (parameters->options().eh_frame_hdr())
744 Output_section* hdr_os =
745 this->choose_output_section(NULL,
747 elfcpp::SHT_PROGBITS,
749 false, false, false);
753 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
754 this->eh_frame_data_);
755 hdr_os->add_output_section_data(hdr_posd);
757 hdr_os->set_after_input_sections();
759 if (!this->script_options_->saw_phdrs_clause())
761 Output_segment* hdr_oseg;
762 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
764 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R, false);
767 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
772 gold_assert(this->eh_frame_section_ == os);
774 if (this->eh_frame_data_->add_ehframe_input_section(object,
783 os->update_flags_for_input_section(shdr.get_sh_flags());
785 // We found a .eh_frame section we are going to optimize, so now
786 // we can add the set of optimized sections to the output
787 // section. We need to postpone adding this until we've found a
788 // section we can optimize so that the .eh_frame section in
789 // crtbegin.o winds up at the start of the output section.
790 if (!this->added_eh_frame_data_)
792 os->add_output_section_data(this->eh_frame_data_);
793 this->added_eh_frame_data_ = true;
799 // We couldn't handle this .eh_frame section for some reason.
800 // Add it as a normal section.
801 bool saw_sections_clause = this->script_options_->saw_sections_clause();
802 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
803 saw_sections_clause);
809 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
810 // the output section.
813 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
814 elfcpp::Elf_Xword flags,
815 Output_section_data* posd,
816 bool is_dynamic_linker_section)
818 Output_section* os = this->choose_output_section(NULL, name, type, flags,
820 is_dynamic_linker_section);
822 os->add_output_section_data(posd);
826 // Map section flags to segment flags.
829 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
831 elfcpp::Elf_Word ret = elfcpp::PF_R;
832 if ((flags & elfcpp::SHF_WRITE) != 0)
834 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
839 // Sometimes we compress sections. This is typically done for
840 // sections that are not part of normal program execution (such as
841 // .debug_* sections), and where the readers of these sections know
842 // how to deal with compressed sections. This routine doesn't say for
843 // certain whether we'll compress -- it depends on commandline options
844 // as well -- just whether this section is a candidate for compression.
845 // (The Output_compressed_section class decides whether to compress
846 // a given section, and picks the name of the compressed section.)
849 is_compressible_debug_section(const char* secname)
851 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
854 // Make a new Output_section, and attach it to segments as
855 // appropriate. IS_INTERP is true if this is the .interp section.
856 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
860 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
861 elfcpp::Elf_Xword flags, bool is_interp,
862 bool is_dynamic_linker_section)
865 if ((flags & elfcpp::SHF_ALLOC) == 0
866 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
867 && is_compressible_debug_section(name))
868 os = new Output_compressed_section(¶meters->options(), name, type,
870 else if ((flags & elfcpp::SHF_ALLOC) == 0
871 && parameters->options().strip_debug_non_line()
872 && strcmp(".debug_abbrev", name) == 0)
874 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
876 if (this->debug_info_)
877 this->debug_info_->set_abbreviations(this->debug_abbrev_);
879 else if ((flags & elfcpp::SHF_ALLOC) == 0
880 && parameters->options().strip_debug_non_line()
881 && strcmp(".debug_info", name) == 0)
883 os = this->debug_info_ = new Output_reduced_debug_info_section(
885 if (this->debug_abbrev_)
886 this->debug_info_->set_abbreviations(this->debug_abbrev_);
890 // FIXME: const_cast is ugly.
891 Target* target = const_cast<Target*>(¶meters->target());
892 os = target->make_output_section(name, type, flags);
897 if (is_dynamic_linker_section)
898 os->set_is_dynamic_linker_section();
900 parameters->target().new_output_section(os);
902 this->section_list_.push_back(os);
904 // The GNU linker by default sorts some sections by priority, so we
905 // do the same. We need to know that this might happen before we
906 // attach any input sections.
907 if (!this->script_options_->saw_sections_clause()
908 && (strcmp(name, ".ctors") == 0
909 || strcmp(name, ".dtors") == 0
910 || strcmp(name, ".init_array") == 0
911 || strcmp(name, ".fini_array") == 0))
912 os->set_may_sort_attached_input_sections();
914 // With -z relro, we have to recognize the special sections by name.
915 // There is no other way.
916 if (!this->script_options_->saw_sections_clause()
917 && parameters->options().relro()
918 && type == elfcpp::SHT_PROGBITS
919 && (flags & elfcpp::SHF_ALLOC) != 0
920 && (flags & elfcpp::SHF_WRITE) != 0)
922 if (strcmp(name, ".data.rel.ro") == 0)
924 else if (strcmp(name, ".data.rel.ro.local") == 0)
927 os->set_is_relro_local();
931 // Check for .stab*str sections, as .stab* sections need to link to
933 if (type == elfcpp::SHT_STRTAB
934 && !this->have_stabstr_section_
935 && strncmp(name, ".stab", 5) == 0
936 && strcmp(name + strlen(name) - 3, "str") == 0)
937 this->have_stabstr_section_ = true;
939 // If we have already attached the sections to segments, then we
940 // need to attach this one now. This happens for sections created
941 // directly by the linker.
942 if (this->sections_are_attached_)
943 this->attach_section_to_segment(os);
948 // Attach output sections to segments. This is called after we have
949 // seen all the input sections.
952 Layout::attach_sections_to_segments()
954 for (Section_list::iterator p = this->section_list_.begin();
955 p != this->section_list_.end();
957 this->attach_section_to_segment(*p);
959 this->sections_are_attached_ = true;
962 // Attach an output section to a segment.
965 Layout::attach_section_to_segment(Output_section* os)
967 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
968 this->unattached_section_list_.push_back(os);
970 this->attach_allocated_section_to_segment(os);
973 // Attach an allocated output section to a segment.
976 Layout::attach_allocated_section_to_segment(Output_section* os)
978 elfcpp::Elf_Xword flags = os->flags();
979 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
981 if (parameters->options().relocatable())
984 // If we have a SECTIONS clause, we can't handle the attachment to
985 // segments until after we've seen all the sections.
986 if (this->script_options_->saw_sections_clause())
989 gold_assert(!this->script_options_->saw_phdrs_clause());
991 // This output section goes into a PT_LOAD segment.
993 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
995 bool sort_sections = !this->script_options_->saw_sections_clause();
997 // In general the only thing we really care about for PT_LOAD
998 // segments is whether or not they are writable, so that is how we
999 // search for them. Large data sections also go into their own
1000 // PT_LOAD segment. People who need segments sorted on some other
1001 // basis will have to use a linker script.
1003 Segment_list::const_iterator p;
1004 for (p = this->segment_list_.begin();
1005 p != this->segment_list_.end();
1008 if ((*p)->type() != elfcpp::PT_LOAD)
1010 if (!parameters->options().omagic()
1011 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1013 // If -Tbss was specified, we need to separate the data and BSS
1015 if (parameters->options().user_set_Tbss())
1017 if ((os->type() == elfcpp::SHT_NOBITS)
1018 == (*p)->has_any_data_sections())
1021 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1024 (*p)->add_output_section(os, seg_flags, sort_sections);
1028 if (p == this->segment_list_.end())
1030 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1032 if (os->is_large_data_section())
1033 oseg->set_is_large_data_segment();
1034 oseg->add_output_section(os, seg_flags, sort_sections);
1037 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1039 if (os->type() == elfcpp::SHT_NOTE)
1041 // See if we already have an equivalent PT_NOTE segment.
1042 for (p = this->segment_list_.begin();
1043 p != segment_list_.end();
1046 if ((*p)->type() == elfcpp::PT_NOTE
1047 && (((*p)->flags() & elfcpp::PF_W)
1048 == (seg_flags & elfcpp::PF_W)))
1050 (*p)->add_output_section(os, seg_flags, false);
1055 if (p == this->segment_list_.end())
1057 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1059 oseg->add_output_section(os, seg_flags, false);
1063 // If we see a loadable SHF_TLS section, we create a PT_TLS
1064 // segment. There can only be one such segment.
1065 if ((flags & elfcpp::SHF_TLS) != 0)
1067 if (this->tls_segment_ == NULL)
1068 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1069 this->tls_segment_->add_output_section(os, seg_flags, false);
1072 // If -z relro is in effect, and we see a relro section, we create a
1073 // PT_GNU_RELRO segment. There can only be one such segment.
1074 if (os->is_relro() && parameters->options().relro())
1076 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1077 if (this->relro_segment_ == NULL)
1078 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1079 this->relro_segment_->add_output_section(os, seg_flags, false);
1083 // Make an output section for a script.
1086 Layout::make_output_section_for_script(const char* name)
1088 name = this->namepool_.add(name, false, NULL);
1089 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1090 elfcpp::SHF_ALLOC, false,
1092 os->set_found_in_sections_clause();
1096 // Return the number of segments we expect to see.
1099 Layout::expected_segment_count() const
1101 size_t ret = this->segment_list_.size();
1103 // If we didn't see a SECTIONS clause in a linker script, we should
1104 // already have the complete list of segments. Otherwise we ask the
1105 // SECTIONS clause how many segments it expects, and add in the ones
1106 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1108 if (!this->script_options_->saw_sections_clause())
1112 const Script_sections* ss = this->script_options_->script_sections();
1113 return ret + ss->expected_segment_count(this);
1117 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1118 // is whether we saw a .note.GNU-stack section in the object file.
1119 // GNU_STACK_FLAGS is the section flags. The flags give the
1120 // protection required for stack memory. We record this in an
1121 // executable as a PT_GNU_STACK segment. If an object file does not
1122 // have a .note.GNU-stack segment, we must assume that it is an old
1123 // object. On some targets that will force an executable stack.
1126 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1128 if (!seen_gnu_stack)
1129 this->input_without_gnu_stack_note_ = true;
1132 this->input_with_gnu_stack_note_ = true;
1133 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1134 this->input_requires_executable_stack_ = true;
1138 // Create automatic note sections.
1141 Layout::create_notes()
1143 this->create_gold_note();
1144 this->create_executable_stack_info();
1145 this->create_build_id();
1148 // Create the dynamic sections which are needed before we read the
1152 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1154 if (parameters->doing_static_link())
1157 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1158 elfcpp::SHT_DYNAMIC,
1160 | elfcpp::SHF_WRITE),
1161 false, false, true);
1162 this->dynamic_section_->set_is_relro();
1164 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
1165 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1166 elfcpp::STV_HIDDEN, 0, false, false);
1168 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1170 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1173 // For each output section whose name can be represented as C symbol,
1174 // define __start and __stop symbols for the section. This is a GNU
1178 Layout::define_section_symbols(Symbol_table* symtab)
1180 for (Section_list::const_iterator p = this->section_list_.begin();
1181 p != this->section_list_.end();
1184 const char* const name = (*p)->name();
1185 if (name[strspn(name,
1187 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1188 "abcdefghijklmnopqrstuvwxyz"
1192 const std::string name_string(name);
1193 const std::string start_name("__start_" + name_string);
1194 const std::string stop_name("__stop_" + name_string);
1196 symtab->define_in_output_data(start_name.c_str(),
1203 elfcpp::STV_DEFAULT,
1205 false, // offset_is_from_end
1206 true); // only_if_ref
1208 symtab->define_in_output_data(stop_name.c_str(),
1215 elfcpp::STV_DEFAULT,
1217 true, // offset_is_from_end
1218 true); // only_if_ref
1223 // Define symbols for group signatures.
1226 Layout::define_group_signatures(Symbol_table* symtab)
1228 for (Group_signatures::iterator p = this->group_signatures_.begin();
1229 p != this->group_signatures_.end();
1232 Symbol* sym = symtab->lookup(p->signature, NULL);
1234 p->section->set_info_symndx(sym);
1237 // Force the name of the group section to the group
1238 // signature, and use the group's section symbol as the
1239 // signature symbol.
1240 if (strcmp(p->section->name(), p->signature) != 0)
1242 const char* name = this->namepool_.add(p->signature,
1244 p->section->set_name(name);
1246 p->section->set_needs_symtab_index();
1247 p->section->set_info_section_symndx(p->section);
1251 this->group_signatures_.clear();
1254 // Find the first read-only PT_LOAD segment, creating one if
1258 Layout::find_first_load_seg()
1260 for (Segment_list::const_iterator p = this->segment_list_.begin();
1261 p != this->segment_list_.end();
1264 if ((*p)->type() == elfcpp::PT_LOAD
1265 && ((*p)->flags() & elfcpp::PF_R) != 0
1266 && (parameters->options().omagic()
1267 || ((*p)->flags() & elfcpp::PF_W) == 0))
1271 gold_assert(!this->script_options_->saw_phdrs_clause());
1273 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1278 // Save states of all current output segments. Store saved states
1279 // in SEGMENT_STATES.
1282 Layout::save_segments(Segment_states* segment_states)
1284 for (Segment_list::const_iterator p = this->segment_list_.begin();
1285 p != this->segment_list_.end();
1288 Output_segment* segment = *p;
1290 Output_segment* copy = new Output_segment(*segment);
1291 (*segment_states)[segment] = copy;
1295 // Restore states of output segments and delete any segment not found in
1299 Layout::restore_segments(const Segment_states* segment_states)
1301 // Go through the segment list and remove any segment added in the
1303 this->tls_segment_ = NULL;
1304 this->relro_segment_ = NULL;
1305 Segment_list::iterator list_iter = this->segment_list_.begin();
1306 while (list_iter != this->segment_list_.end())
1308 Output_segment* segment = *list_iter;
1309 Segment_states::const_iterator states_iter =
1310 segment_states->find(segment);
1311 if (states_iter != segment_states->end())
1313 const Output_segment* copy = states_iter->second;
1314 // Shallow copy to restore states.
1317 // Also fix up TLS and RELRO segment pointers as appropriate.
1318 if (segment->type() == elfcpp::PT_TLS)
1319 this->tls_segment_ = segment;
1320 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1321 this->relro_segment_ = segment;
1327 list_iter = this->segment_list_.erase(list_iter);
1328 // This is a segment created during section layout. It should be
1329 // safe to remove it since we should have removed all pointers to it.
1335 // Clean up after relaxation so that sections can be laid out again.
1338 Layout::clean_up_after_relaxation()
1340 // Restore the segments to point state just prior to the relaxation loop.
1341 Script_sections* script_section = this->script_options_->script_sections();
1342 script_section->release_segments();
1343 this->restore_segments(this->segment_states_);
1345 // Reset section addresses and file offsets
1346 for (Section_list::iterator p = this->section_list_.begin();
1347 p != this->section_list_.end();
1350 (*p)->reset_address_and_file_offset();
1351 (*p)->restore_states();
1354 // Reset special output object address and file offsets.
1355 for (Data_list::iterator p = this->special_output_list_.begin();
1356 p != this->special_output_list_.end();
1358 (*p)->reset_address_and_file_offset();
1360 // A linker script may have created some output section data objects.
1361 // They are useless now.
1362 for (Output_section_data_list::const_iterator p =
1363 this->script_output_section_data_list_.begin();
1364 p != this->script_output_section_data_list_.end();
1367 this->script_output_section_data_list_.clear();
1370 // Prepare for relaxation.
1373 Layout::prepare_for_relaxation()
1375 // Create an relaxation debug check if in debugging mode.
1376 if (is_debugging_enabled(DEBUG_RELAXATION))
1377 this->relaxation_debug_check_ = new Relaxation_debug_check();
1379 // Save segment states.
1380 this->segment_states_ = new Segment_states();
1381 this->save_segments(this->segment_states_);
1383 for(Section_list::const_iterator p = this->section_list_.begin();
1384 p != this->section_list_.end();
1386 (*p)->save_states();
1388 if (is_debugging_enabled(DEBUG_RELAXATION))
1389 this->relaxation_debug_check_->check_output_data_for_reset_values(
1390 this->section_list_, this->special_output_list_);
1392 // Also enable recording of output section data from scripts.
1393 this->record_output_section_data_from_script_ = true;
1396 // Relaxation loop body: If target has no relaxation, this runs only once
1397 // Otherwise, the target relaxation hook is called at the end of
1398 // each iteration. If the hook returns true, it means re-layout of
1399 // section is required.
1401 // The number of segments created by a linking script without a PHDRS
1402 // clause may be affected by section sizes and alignments. There is
1403 // a remote chance that relaxation causes different number of PT_LOAD
1404 // segments are created and sections are attached to different segments.
1405 // Therefore, we always throw away all segments created during section
1406 // layout. In order to be able to restart the section layout, we keep
1407 // a copy of the segment list right before the relaxation loop and use
1408 // that to restore the segments.
1410 // PASS is the current relaxation pass number.
1411 // SYMTAB is a symbol table.
1412 // PLOAD_SEG is the address of a pointer for the load segment.
1413 // PHDR_SEG is a pointer to the PHDR segment.
1414 // SEGMENT_HEADERS points to the output segment header.
1415 // FILE_HEADER points to the output file header.
1416 // PSHNDX is the address to store the output section index.
1419 Layout::relaxation_loop_body(
1422 Symbol_table* symtab,
1423 Output_segment** pload_seg,
1424 Output_segment* phdr_seg,
1425 Output_segment_headers* segment_headers,
1426 Output_file_header* file_header,
1427 unsigned int* pshndx)
1429 // If this is not the first iteration, we need to clean up after
1430 // relaxation so that we can lay out the sections again.
1432 this->clean_up_after_relaxation();
1434 // If there is a SECTIONS clause, put all the input sections into
1435 // the required order.
1436 Output_segment* load_seg;
1437 if (this->script_options_->saw_sections_clause())
1438 load_seg = this->set_section_addresses_from_script(symtab);
1439 else if (parameters->options().relocatable())
1442 load_seg = this->find_first_load_seg();
1444 if (parameters->options().oformat_enum()
1445 != General_options::OBJECT_FORMAT_ELF)
1448 gold_assert(phdr_seg == NULL
1450 || this->script_options_->saw_sections_clause());
1452 // Lay out the segment headers.
1453 if (!parameters->options().relocatable())
1455 gold_assert(segment_headers != NULL);
1456 if (load_seg != NULL)
1457 load_seg->add_initial_output_data(segment_headers);
1458 if (phdr_seg != NULL)
1459 phdr_seg->add_initial_output_data(segment_headers);
1462 // Lay out the file header.
1463 if (load_seg != NULL)
1464 load_seg->add_initial_output_data(file_header);
1466 if (this->script_options_->saw_phdrs_clause()
1467 && !parameters->options().relocatable())
1469 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1470 // clause in a linker script.
1471 Script_sections* ss = this->script_options_->script_sections();
1472 ss->put_headers_in_phdrs(file_header, segment_headers);
1475 // We set the output section indexes in set_segment_offsets and
1476 // set_section_indexes.
1479 // Set the file offsets of all the segments, and all the sections
1482 if (!parameters->options().relocatable())
1483 off = this->set_segment_offsets(target, load_seg, pshndx);
1485 off = this->set_relocatable_section_offsets(file_header, pshndx);
1487 // Verify that the dummy relaxation does not change anything.
1488 if (is_debugging_enabled(DEBUG_RELAXATION))
1491 this->relaxation_debug_check_->read_sections(this->section_list_);
1493 this->relaxation_debug_check_->verify_sections(this->section_list_);
1496 *pload_seg = load_seg;
1500 // Finalize the layout. When this is called, we have created all the
1501 // output sections and all the output segments which are based on
1502 // input sections. We have several things to do, and we have to do
1503 // them in the right order, so that we get the right results correctly
1506 // 1) Finalize the list of output segments and create the segment
1509 // 2) Finalize the dynamic symbol table and associated sections.
1511 // 3) Determine the final file offset of all the output segments.
1513 // 4) Determine the final file offset of all the SHF_ALLOC output
1516 // 5) Create the symbol table sections and the section name table
1519 // 6) Finalize the symbol table: set symbol values to their final
1520 // value and make a final determination of which symbols are going
1521 // into the output symbol table.
1523 // 7) Create the section table header.
1525 // 8) Determine the final file offset of all the output sections which
1526 // are not SHF_ALLOC, including the section table header.
1528 // 9) Finalize the ELF file header.
1530 // This function returns the size of the output file.
1533 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1534 Target* target, const Task* task)
1536 target->finalize_sections(this, input_objects);
1538 this->count_local_symbols(task, input_objects);
1540 this->link_stabs_sections();
1542 Output_segment* phdr_seg = NULL;
1543 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1545 // There was a dynamic object in the link. We need to create
1546 // some information for the dynamic linker.
1548 // Create the PT_PHDR segment which will hold the program
1550 if (!this->script_options_->saw_phdrs_clause())
1551 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1553 // Create the dynamic symbol table, including the hash table.
1554 Output_section* dynstr;
1555 std::vector<Symbol*> dynamic_symbols;
1556 unsigned int local_dynamic_count;
1557 Versions versions(*this->script_options()->version_script_info(),
1559 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1560 &local_dynamic_count, &dynamic_symbols,
1563 // Create the .interp section to hold the name of the
1564 // interpreter, and put it in a PT_INTERP segment.
1565 if (!parameters->options().shared())
1566 this->create_interp(target);
1568 // Finish the .dynamic section to hold the dynamic data, and put
1569 // it in a PT_DYNAMIC segment.
1570 this->finish_dynamic_section(input_objects, symtab);
1572 // We should have added everything we need to the dynamic string
1574 this->dynpool_.set_string_offsets();
1576 // Create the version sections. We can't do this until the
1577 // dynamic string table is complete.
1578 this->create_version_sections(&versions, symtab, local_dynamic_count,
1579 dynamic_symbols, dynstr);
1582 if (this->incremental_inputs_)
1584 this->incremental_inputs_->finalize();
1585 this->create_incremental_info_sections();
1588 // Create segment headers.
1589 Output_segment_headers* segment_headers =
1590 (parameters->options().relocatable()
1592 : new Output_segment_headers(this->segment_list_));
1594 // Lay out the file header.
1595 Output_file_header* file_header
1596 = new Output_file_header(target, symtab, segment_headers,
1597 parameters->options().entry());
1599 this->special_output_list_.push_back(file_header);
1600 if (segment_headers != NULL)
1601 this->special_output_list_.push_back(segment_headers);
1603 // Find approriate places for orphan output sections if we are using
1605 if (this->script_options_->saw_sections_clause())
1606 this->place_orphan_sections_in_script();
1608 Output_segment* load_seg;
1613 // Take a snapshot of the section layout as needed.
1614 if (target->may_relax())
1615 this->prepare_for_relaxation();
1617 // Run the relaxation loop to lay out sections.
1620 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1621 phdr_seg, segment_headers, file_header,
1625 while (target->may_relax()
1626 && target->relax(pass, input_objects, symtab, this));
1628 // Set the file offsets of all the non-data sections we've seen so
1629 // far which don't have to wait for the input sections. We need
1630 // this in order to finalize local symbols in non-allocated
1632 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1634 // Set the section indexes of all unallocated sections seen so far,
1635 // in case any of them are somehow referenced by a symbol.
1636 shndx = this->set_section_indexes(shndx);
1638 // Create the symbol table sections.
1639 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1640 if (!parameters->doing_static_link())
1641 this->assign_local_dynsym_offsets(input_objects);
1643 // Process any symbol assignments from a linker script. This must
1644 // be called after the symbol table has been finalized.
1645 this->script_options_->finalize_symbols(symtab, this);
1647 // Create the .shstrtab section.
1648 Output_section* shstrtab_section = this->create_shstrtab();
1650 // Set the file offsets of the rest of the non-data sections which
1651 // don't have to wait for the input sections.
1652 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1654 // Now that all sections have been created, set the section indexes
1655 // for any sections which haven't been done yet.
1656 shndx = this->set_section_indexes(shndx);
1658 // Create the section table header.
1659 this->create_shdrs(shstrtab_section, &off);
1661 // If there are no sections which require postprocessing, we can
1662 // handle the section names now, and avoid a resize later.
1663 if (!this->any_postprocessing_sections_)
1664 off = this->set_section_offsets(off,
1665 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1667 file_header->set_section_info(this->section_headers_, shstrtab_section);
1669 // Now we know exactly where everything goes in the output file
1670 // (except for non-allocated sections which require postprocessing).
1671 Output_data::layout_complete();
1673 this->output_file_size_ = off;
1678 // Create a note header following the format defined in the ELF ABI.
1679 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1680 // of the section to create, DESCSZ is the size of the descriptor.
1681 // ALLOCATE is true if the section should be allocated in memory.
1682 // This returns the new note section. It sets *TRAILING_PADDING to
1683 // the number of trailing zero bytes required.
1686 Layout::create_note(const char* name, int note_type,
1687 const char* section_name, size_t descsz,
1688 bool allocate, size_t* trailing_padding)
1690 // Authorities all agree that the values in a .note field should
1691 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1692 // they differ on what the alignment is for 64-bit binaries.
1693 // The GABI says unambiguously they take 8-byte alignment:
1694 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1695 // Other documentation says alignment should always be 4 bytes:
1696 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1697 // GNU ld and GNU readelf both support the latter (at least as of
1698 // version 2.16.91), and glibc always generates the latter for
1699 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1701 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1702 const int size = parameters->target().get_size();
1704 const int size = 32;
1707 // The contents of the .note section.
1708 size_t namesz = strlen(name) + 1;
1709 size_t aligned_namesz = align_address(namesz, size / 8);
1710 size_t aligned_descsz = align_address(descsz, size / 8);
1712 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1714 unsigned char* buffer = new unsigned char[notehdrsz];
1715 memset(buffer, 0, notehdrsz);
1717 bool is_big_endian = parameters->target().is_big_endian();
1723 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1724 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1725 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1729 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1730 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1731 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1734 else if (size == 64)
1738 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1739 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1740 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1744 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1745 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1746 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1752 memcpy(buffer + 3 * (size / 8), name, namesz);
1754 elfcpp::Elf_Xword flags = 0;
1756 flags = elfcpp::SHF_ALLOC;
1757 Output_section* os = this->choose_output_section(NULL, section_name,
1759 flags, false, false,
1764 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1767 os->add_output_section_data(posd);
1769 *trailing_padding = aligned_descsz - descsz;
1774 // For an executable or shared library, create a note to record the
1775 // version of gold used to create the binary.
1778 Layout::create_gold_note()
1780 if (parameters->options().relocatable())
1783 std::string desc = std::string("gold ") + gold::get_version_string();
1785 size_t trailing_padding;
1786 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1787 ".note.gnu.gold-version", desc.size(),
1788 false, &trailing_padding);
1792 Output_section_data* posd = new Output_data_const(desc, 4);
1793 os->add_output_section_data(posd);
1795 if (trailing_padding > 0)
1797 posd = new Output_data_zero_fill(trailing_padding, 0);
1798 os->add_output_section_data(posd);
1802 // Record whether the stack should be executable. This can be set
1803 // from the command line using the -z execstack or -z noexecstack
1804 // options. Otherwise, if any input file has a .note.GNU-stack
1805 // section with the SHF_EXECINSTR flag set, the stack should be
1806 // executable. Otherwise, if at least one input file a
1807 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1808 // section, we use the target default for whether the stack should be
1809 // executable. Otherwise, we don't generate a stack note. When
1810 // generating a object file, we create a .note.GNU-stack section with
1811 // the appropriate marking. When generating an executable or shared
1812 // library, we create a PT_GNU_STACK segment.
1815 Layout::create_executable_stack_info()
1817 bool is_stack_executable;
1818 if (parameters->options().is_execstack_set())
1819 is_stack_executable = parameters->options().is_stack_executable();
1820 else if (!this->input_with_gnu_stack_note_)
1824 if (this->input_requires_executable_stack_)
1825 is_stack_executable = true;
1826 else if (this->input_without_gnu_stack_note_)
1827 is_stack_executable =
1828 parameters->target().is_default_stack_executable();
1830 is_stack_executable = false;
1833 if (parameters->options().relocatable())
1835 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1836 elfcpp::Elf_Xword flags = 0;
1837 if (is_stack_executable)
1838 flags |= elfcpp::SHF_EXECINSTR;
1839 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags, false,
1844 if (this->script_options_->saw_phdrs_clause())
1846 int flags = elfcpp::PF_R | elfcpp::PF_W;
1847 if (is_stack_executable)
1848 flags |= elfcpp::PF_X;
1849 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1853 // If --build-id was used, set up the build ID note.
1856 Layout::create_build_id()
1858 if (!parameters->options().user_set_build_id())
1861 const char* style = parameters->options().build_id();
1862 if (strcmp(style, "none") == 0)
1865 // Set DESCSZ to the size of the note descriptor. When possible,
1866 // set DESC to the note descriptor contents.
1869 if (strcmp(style, "md5") == 0)
1871 else if (strcmp(style, "sha1") == 0)
1873 else if (strcmp(style, "uuid") == 0)
1875 const size_t uuidsz = 128 / 8;
1877 char buffer[uuidsz];
1878 memset(buffer, 0, uuidsz);
1880 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
1882 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1886 ssize_t got = ::read(descriptor, buffer, uuidsz);
1887 release_descriptor(descriptor, true);
1889 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1890 else if (static_cast<size_t>(got) != uuidsz)
1891 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1895 desc.assign(buffer, uuidsz);
1898 else if (strncmp(style, "0x", 2) == 0)
1901 const char* p = style + 2;
1904 if (hex_p(p[0]) && hex_p(p[1]))
1906 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1910 else if (*p == '-' || *p == ':')
1913 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1916 descsz = desc.size();
1919 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1922 size_t trailing_padding;
1923 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1924 ".note.gnu.build-id", descsz, true,
1931 // We know the value already, so we fill it in now.
1932 gold_assert(desc.size() == descsz);
1934 Output_section_data* posd = new Output_data_const(desc, 4);
1935 os->add_output_section_data(posd);
1937 if (trailing_padding != 0)
1939 posd = new Output_data_zero_fill(trailing_padding, 0);
1940 os->add_output_section_data(posd);
1945 // We need to compute a checksum after we have completed the
1947 gold_assert(trailing_padding == 0);
1948 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
1949 os->add_output_section_data(this->build_id_note_);
1953 // If we have both .stabXX and .stabXXstr sections, then the sh_link
1954 // field of the former should point to the latter. I'm not sure who
1955 // started this, but the GNU linker does it, and some tools depend
1959 Layout::link_stabs_sections()
1961 if (!this->have_stabstr_section_)
1964 for (Section_list::iterator p = this->section_list_.begin();
1965 p != this->section_list_.end();
1968 if ((*p)->type() != elfcpp::SHT_STRTAB)
1971 const char* name = (*p)->name();
1972 if (strncmp(name, ".stab", 5) != 0)
1975 size_t len = strlen(name);
1976 if (strcmp(name + len - 3, "str") != 0)
1979 std::string stab_name(name, len - 3);
1980 Output_section* stab_sec;
1981 stab_sec = this->find_output_section(stab_name.c_str());
1982 if (stab_sec != NULL)
1983 stab_sec->set_link_section(*p);
1987 // Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
1988 // for the next run of incremental linking to check what has changed.
1991 Layout::create_incremental_info_sections()
1993 gold_assert(this->incremental_inputs_ != NULL);
1995 // Add the .gnu_incremental_inputs section.
1996 const char *incremental_inputs_name =
1997 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
1998 Output_section* inputs_os =
1999 this->make_output_section(incremental_inputs_name,
2000 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2002 Output_section_data* posd =
2003 this->incremental_inputs_->create_incremental_inputs_section_data();
2004 inputs_os->add_output_section_data(posd);
2006 // Add the .gnu_incremental_strtab section.
2007 const char *incremental_strtab_name =
2008 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2009 Output_section* strtab_os = this->make_output_section(incremental_strtab_name,
2012 Output_data_strtab* strtab_data =
2013 new Output_data_strtab(this->incremental_inputs_->get_stringpool());
2014 strtab_os->add_output_section_data(strtab_data);
2016 inputs_os->set_link_section(strtab_data);
2019 // Return whether SEG1 should be before SEG2 in the output file. This
2020 // is based entirely on the segment type and flags. When this is
2021 // called the segment addresses has normally not yet been set.
2024 Layout::segment_precedes(const Output_segment* seg1,
2025 const Output_segment* seg2)
2027 elfcpp::Elf_Word type1 = seg1->type();
2028 elfcpp::Elf_Word type2 = seg2->type();
2030 // The single PT_PHDR segment is required to precede any loadable
2031 // segment. We simply make it always first.
2032 if (type1 == elfcpp::PT_PHDR)
2034 gold_assert(type2 != elfcpp::PT_PHDR);
2037 if (type2 == elfcpp::PT_PHDR)
2040 // The single PT_INTERP segment is required to precede any loadable
2041 // segment. We simply make it always second.
2042 if (type1 == elfcpp::PT_INTERP)
2044 gold_assert(type2 != elfcpp::PT_INTERP);
2047 if (type2 == elfcpp::PT_INTERP)
2050 // We then put PT_LOAD segments before any other segments.
2051 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2053 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2056 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2057 // segment, because that is where the dynamic linker expects to find
2058 // it (this is just for efficiency; other positions would also work
2060 if (type1 == elfcpp::PT_TLS
2061 && type2 != elfcpp::PT_TLS
2062 && type2 != elfcpp::PT_GNU_RELRO)
2064 if (type2 == elfcpp::PT_TLS
2065 && type1 != elfcpp::PT_TLS
2066 && type1 != elfcpp::PT_GNU_RELRO)
2069 // We put the PT_GNU_RELRO segment last, because that is where the
2070 // dynamic linker expects to find it (as with PT_TLS, this is just
2072 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2074 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2077 const elfcpp::Elf_Word flags1 = seg1->flags();
2078 const elfcpp::Elf_Word flags2 = seg2->flags();
2080 // The order of non-PT_LOAD segments is unimportant. We simply sort
2081 // by the numeric segment type and flags values. There should not
2082 // be more than one segment with the same type and flags.
2083 if (type1 != elfcpp::PT_LOAD)
2086 return type1 < type2;
2087 gold_assert(flags1 != flags2);
2088 return flags1 < flags2;
2091 // If the addresses are set already, sort by load address.
2092 if (seg1->are_addresses_set())
2094 if (!seg2->are_addresses_set())
2097 unsigned int section_count1 = seg1->output_section_count();
2098 unsigned int section_count2 = seg2->output_section_count();
2099 if (section_count1 == 0 && section_count2 > 0)
2101 if (section_count1 > 0 && section_count2 == 0)
2104 uint64_t paddr1 = seg1->first_section_load_address();
2105 uint64_t paddr2 = seg2->first_section_load_address();
2106 if (paddr1 != paddr2)
2107 return paddr1 < paddr2;
2109 else if (seg2->are_addresses_set())
2112 // A segment which holds large data comes after a segment which does
2113 // not hold large data.
2114 if (seg1->is_large_data_segment())
2116 if (!seg2->is_large_data_segment())
2119 else if (seg2->is_large_data_segment())
2122 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2123 // segments come before writable segments. Then writable segments
2124 // with data come before writable segments without data. Then
2125 // executable segments come before non-executable segments. Then
2126 // the unlikely case of a non-readable segment comes before the
2127 // normal case of a readable segment. If there are multiple
2128 // segments with the same type and flags, we require that the
2129 // address be set, and we sort by virtual address and then physical
2131 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2132 return (flags1 & elfcpp::PF_W) == 0;
2133 if ((flags1 & elfcpp::PF_W) != 0
2134 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2135 return seg1->has_any_data_sections();
2136 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2137 return (flags1 & elfcpp::PF_X) != 0;
2138 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2139 return (flags1 & elfcpp::PF_R) == 0;
2141 // We shouldn't get here--we shouldn't create segments which we
2142 // can't distinguish.
2146 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2149 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2151 uint64_t unsigned_off = off;
2152 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2153 | (addr & (abi_pagesize - 1)));
2154 if (aligned_off < unsigned_off)
2155 aligned_off += abi_pagesize;
2159 // Set the file offsets of all the segments, and all the sections they
2160 // contain. They have all been created. LOAD_SEG must be be laid out
2161 // first. Return the offset of the data to follow.
2164 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2165 unsigned int *pshndx)
2167 // Sort them into the final order.
2168 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2169 Layout::Compare_segments());
2171 // Find the PT_LOAD segments, and set their addresses and offsets
2172 // and their section's addresses and offsets.
2174 if (parameters->options().user_set_Ttext())
2175 addr = parameters->options().Ttext();
2176 else if (parameters->options().output_is_position_independent())
2179 addr = target->default_text_segment_address();
2182 // If LOAD_SEG is NULL, then the file header and segment headers
2183 // will not be loadable. But they still need to be at offset 0 in
2184 // the file. Set their offsets now.
2185 if (load_seg == NULL)
2187 for (Data_list::iterator p = this->special_output_list_.begin();
2188 p != this->special_output_list_.end();
2191 off = align_address(off, (*p)->addralign());
2192 (*p)->set_address_and_file_offset(0, off);
2193 off += (*p)->data_size();
2197 const bool check_sections = parameters->options().check_sections();
2198 Output_segment* last_load_segment = NULL;
2200 bool was_readonly = false;
2201 for (Segment_list::iterator p = this->segment_list_.begin();
2202 p != this->segment_list_.end();
2205 if ((*p)->type() == elfcpp::PT_LOAD)
2207 if (load_seg != NULL && load_seg != *p)
2211 bool are_addresses_set = (*p)->are_addresses_set();
2212 if (are_addresses_set)
2214 // When it comes to setting file offsets, we care about
2215 // the physical address.
2216 addr = (*p)->paddr();
2218 else if (parameters->options().user_set_Tdata()
2219 && ((*p)->flags() & elfcpp::PF_W) != 0
2220 && (!parameters->options().user_set_Tbss()
2221 || (*p)->has_any_data_sections()))
2223 addr = parameters->options().Tdata();
2224 are_addresses_set = true;
2226 else if (parameters->options().user_set_Tbss()
2227 && ((*p)->flags() & elfcpp::PF_W) != 0
2228 && !(*p)->has_any_data_sections())
2230 addr = parameters->options().Tbss();
2231 are_addresses_set = true;
2234 uint64_t orig_addr = addr;
2235 uint64_t orig_off = off;
2237 uint64_t aligned_addr = 0;
2238 uint64_t abi_pagesize = target->abi_pagesize();
2239 uint64_t common_pagesize = target->common_pagesize();
2241 if (!parameters->options().nmagic()
2242 && !parameters->options().omagic())
2243 (*p)->set_minimum_p_align(common_pagesize);
2245 if (!are_addresses_set)
2247 // If the last segment was readonly, and this one is
2248 // not, then skip the address forward one page,
2249 // maintaining the same position within the page. This
2250 // lets us store both segments overlapping on a single
2251 // page in the file, but the loader will put them on
2252 // different pages in memory.
2254 addr = align_address(addr, (*p)->maximum_alignment());
2255 aligned_addr = addr;
2257 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2259 if ((addr & (abi_pagesize - 1)) != 0)
2260 addr = addr + abi_pagesize;
2263 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2266 if (!parameters->options().nmagic()
2267 && !parameters->options().omagic())
2268 off = align_file_offset(off, addr, abi_pagesize);
2269 else if (load_seg == NULL)
2271 // This is -N or -n with a section script which prevents
2272 // us from using a load segment. We need to ensure that
2273 // the file offset is aligned to the alignment of the
2274 // segment. This is because the linker script
2275 // implicitly assumed a zero offset. If we don't align
2276 // here, then the alignment of the sections in the
2277 // linker script may not match the alignment of the
2278 // sections in the set_section_addresses call below,
2279 // causing an error about dot moving backward.
2280 off = align_address(off, (*p)->maximum_alignment());
2283 unsigned int shndx_hold = *pshndx;
2284 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2287 // Now that we know the size of this segment, we may be able
2288 // to save a page in memory, at the cost of wasting some
2289 // file space, by instead aligning to the start of a new
2290 // page. Here we use the real machine page size rather than
2291 // the ABI mandated page size.
2293 if (!are_addresses_set && aligned_addr != addr)
2295 uint64_t first_off = (common_pagesize
2297 & (common_pagesize - 1)));
2298 uint64_t last_off = new_addr & (common_pagesize - 1);
2301 && ((aligned_addr & ~ (common_pagesize - 1))
2302 != (new_addr & ~ (common_pagesize - 1)))
2303 && first_off + last_off <= common_pagesize)
2305 *pshndx = shndx_hold;
2306 addr = align_address(aligned_addr, common_pagesize);
2307 addr = align_address(addr, (*p)->maximum_alignment());
2308 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2309 off = align_file_offset(off, addr, abi_pagesize);
2310 new_addr = (*p)->set_section_addresses(this, true, addr,
2317 if (((*p)->flags() & elfcpp::PF_W) == 0)
2318 was_readonly = true;
2320 // Implement --check-sections. We know that the segments
2321 // are sorted by LMA.
2322 if (check_sections && last_load_segment != NULL)
2324 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2325 if (last_load_segment->paddr() + last_load_segment->memsz()
2328 unsigned long long lb1 = last_load_segment->paddr();
2329 unsigned long long le1 = lb1 + last_load_segment->memsz();
2330 unsigned long long lb2 = (*p)->paddr();
2331 unsigned long long le2 = lb2 + (*p)->memsz();
2332 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2333 "[0x%llx -> 0x%llx]"),
2334 lb1, le1, lb2, le2);
2337 last_load_segment = *p;
2341 // Handle the non-PT_LOAD segments, setting their offsets from their
2342 // section's offsets.
2343 for (Segment_list::iterator p = this->segment_list_.begin();
2344 p != this->segment_list_.end();
2347 if ((*p)->type() != elfcpp::PT_LOAD)
2351 // Set the TLS offsets for each section in the PT_TLS segment.
2352 if (this->tls_segment_ != NULL)
2353 this->tls_segment_->set_tls_offsets();
2358 // Set the offsets of all the allocated sections when doing a
2359 // relocatable link. This does the same jobs as set_segment_offsets,
2360 // only for a relocatable link.
2363 Layout::set_relocatable_section_offsets(Output_data* file_header,
2364 unsigned int *pshndx)
2368 file_header->set_address_and_file_offset(0, 0);
2369 off += file_header->data_size();
2371 for (Section_list::iterator p = this->section_list_.begin();
2372 p != this->section_list_.end();
2375 // We skip unallocated sections here, except that group sections
2376 // have to come first.
2377 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2378 && (*p)->type() != elfcpp::SHT_GROUP)
2381 off = align_address(off, (*p)->addralign());
2383 // The linker script might have set the address.
2384 if (!(*p)->is_address_valid())
2385 (*p)->set_address(0);
2386 (*p)->set_file_offset(off);
2387 (*p)->finalize_data_size();
2388 off += (*p)->data_size();
2390 (*p)->set_out_shndx(*pshndx);
2397 // Set the file offset of all the sections not associated with a
2401 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2403 for (Section_list::iterator p = this->unattached_section_list_.begin();
2404 p != this->unattached_section_list_.end();
2407 // The symtab section is handled in create_symtab_sections.
2408 if (*p == this->symtab_section_)
2411 // If we've already set the data size, don't set it again.
2412 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2415 if (pass == BEFORE_INPUT_SECTIONS_PASS
2416 && (*p)->requires_postprocessing())
2418 (*p)->create_postprocessing_buffer();
2419 this->any_postprocessing_sections_ = true;
2422 if (pass == BEFORE_INPUT_SECTIONS_PASS
2423 && (*p)->after_input_sections())
2425 else if (pass == POSTPROCESSING_SECTIONS_PASS
2426 && (!(*p)->after_input_sections()
2427 || (*p)->type() == elfcpp::SHT_STRTAB))
2429 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2430 && (!(*p)->after_input_sections()
2431 || (*p)->type() != elfcpp::SHT_STRTAB))
2434 off = align_address(off, (*p)->addralign());
2435 (*p)->set_file_offset(off);
2436 (*p)->finalize_data_size();
2437 off += (*p)->data_size();
2439 // At this point the name must be set.
2440 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2441 this->namepool_.add((*p)->name(), false, NULL);
2446 // Set the section indexes of all the sections not associated with a
2450 Layout::set_section_indexes(unsigned int shndx)
2452 for (Section_list::iterator p = this->unattached_section_list_.begin();
2453 p != this->unattached_section_list_.end();
2456 if (!(*p)->has_out_shndx())
2458 (*p)->set_out_shndx(shndx);
2465 // Set the section addresses according to the linker script. This is
2466 // only called when we see a SECTIONS clause. This returns the
2467 // program segment which should hold the file header and segment
2468 // headers, if any. It will return NULL if they should not be in a
2472 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2474 Script_sections* ss = this->script_options_->script_sections();
2475 gold_assert(ss->saw_sections_clause());
2476 return this->script_options_->set_section_addresses(symtab, this);
2479 // Place the orphan sections in the linker script.
2482 Layout::place_orphan_sections_in_script()
2484 Script_sections* ss = this->script_options_->script_sections();
2485 gold_assert(ss->saw_sections_clause());
2487 // Place each orphaned output section in the script.
2488 for (Section_list::iterator p = this->section_list_.begin();
2489 p != this->section_list_.end();
2492 if (!(*p)->found_in_sections_clause())
2493 ss->place_orphan(*p);
2497 // Count the local symbols in the regular symbol table and the dynamic
2498 // symbol table, and build the respective string pools.
2501 Layout::count_local_symbols(const Task* task,
2502 const Input_objects* input_objects)
2504 // First, figure out an upper bound on the number of symbols we'll
2505 // be inserting into each pool. This helps us create the pools with
2506 // the right size, to avoid unnecessary hashtable resizing.
2507 unsigned int symbol_count = 0;
2508 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2509 p != input_objects->relobj_end();
2511 symbol_count += (*p)->local_symbol_count();
2513 // Go from "upper bound" to "estimate." We overcount for two
2514 // reasons: we double-count symbols that occur in more than one
2515 // object file, and we count symbols that are dropped from the
2516 // output. Add it all together and assume we overcount by 100%.
2519 // We assume all symbols will go into both the sympool and dynpool.
2520 this->sympool_.reserve(symbol_count);
2521 this->dynpool_.reserve(symbol_count);
2523 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2524 p != input_objects->relobj_end();
2527 Task_lock_obj<Object> tlo(task, *p);
2528 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2532 // Create the symbol table sections. Here we also set the final
2533 // values of the symbols. At this point all the loadable sections are
2534 // fully laid out. SHNUM is the number of sections so far.
2537 Layout::create_symtab_sections(const Input_objects* input_objects,
2538 Symbol_table* symtab,
2544 if (parameters->target().get_size() == 32)
2546 symsize = elfcpp::Elf_sizes<32>::sym_size;
2549 else if (parameters->target().get_size() == 64)
2551 symsize = elfcpp::Elf_sizes<64>::sym_size;
2558 off = align_address(off, align);
2559 off_t startoff = off;
2561 // Save space for the dummy symbol at the start of the section. We
2562 // never bother to write this out--it will just be left as zero.
2564 unsigned int local_symbol_index = 1;
2566 // Add STT_SECTION symbols for each Output section which needs one.
2567 for (Section_list::iterator p = this->section_list_.begin();
2568 p != this->section_list_.end();
2571 if (!(*p)->needs_symtab_index())
2572 (*p)->set_symtab_index(-1U);
2575 (*p)->set_symtab_index(local_symbol_index);
2576 ++local_symbol_index;
2581 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2582 p != input_objects->relobj_end();
2585 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2587 off += (index - local_symbol_index) * symsize;
2588 local_symbol_index = index;
2591 unsigned int local_symcount = local_symbol_index;
2592 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
2595 size_t dyn_global_index;
2597 if (this->dynsym_section_ == NULL)
2600 dyn_global_index = 0;
2605 dyn_global_index = this->dynsym_section_->info();
2606 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2607 dynoff = this->dynsym_section_->offset() + locsize;
2608 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2609 gold_assert(static_cast<off_t>(dyncount * symsize)
2610 == this->dynsym_section_->data_size() - locsize);
2613 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2614 &this->sympool_, &local_symcount);
2616 if (!parameters->options().strip_all())
2618 this->sympool_.set_string_offsets();
2620 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2621 Output_section* osymtab = this->make_output_section(symtab_name,
2624 this->symtab_section_ = osymtab;
2626 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2629 osymtab->add_output_section_data(pos);
2631 // We generate a .symtab_shndx section if we have more than
2632 // SHN_LORESERVE sections. Technically it is possible that we
2633 // don't need one, because it is possible that there are no
2634 // symbols in any of sections with indexes larger than
2635 // SHN_LORESERVE. That is probably unusual, though, and it is
2636 // easier to always create one than to compute section indexes
2637 // twice (once here, once when writing out the symbols).
2638 if (shnum >= elfcpp::SHN_LORESERVE)
2640 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2642 Output_section* osymtab_xindex =
2643 this->make_output_section(symtab_xindex_name,
2644 elfcpp::SHT_SYMTAB_SHNDX, 0, false,
2647 size_t symcount = (off - startoff) / symsize;
2648 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2650 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2652 osymtab_xindex->set_link_section(osymtab);
2653 osymtab_xindex->set_addralign(4);
2654 osymtab_xindex->set_entsize(4);
2656 osymtab_xindex->set_after_input_sections();
2658 // This tells the driver code to wait until the symbol table
2659 // has written out before writing out the postprocessing
2660 // sections, including the .symtab_shndx section.
2661 this->any_postprocessing_sections_ = true;
2664 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2665 Output_section* ostrtab = this->make_output_section(strtab_name,
2669 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2670 ostrtab->add_output_section_data(pstr);
2672 osymtab->set_file_offset(startoff);
2673 osymtab->finalize_data_size();
2674 osymtab->set_link_section(ostrtab);
2675 osymtab->set_info(local_symcount);
2676 osymtab->set_entsize(symsize);
2682 // Create the .shstrtab section, which holds the names of the
2683 // sections. At the time this is called, we have created all the
2684 // output sections except .shstrtab itself.
2687 Layout::create_shstrtab()
2689 // FIXME: We don't need to create a .shstrtab section if we are
2690 // stripping everything.
2692 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2694 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
2697 // We can't write out this section until we've set all the section
2698 // names, and we don't set the names of compressed output sections
2699 // until relocations are complete.
2700 os->set_after_input_sections();
2702 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2703 os->add_output_section_data(posd);
2708 // Create the section headers. SIZE is 32 or 64. OFF is the file
2712 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2714 Output_section_headers* oshdrs;
2715 oshdrs = new Output_section_headers(this,
2716 &this->segment_list_,
2717 &this->section_list_,
2718 &this->unattached_section_list_,
2721 off_t off = align_address(*poff, oshdrs->addralign());
2722 oshdrs->set_address_and_file_offset(0, off);
2723 off += oshdrs->data_size();
2725 this->section_headers_ = oshdrs;
2728 // Count the allocated sections.
2731 Layout::allocated_output_section_count() const
2733 size_t section_count = 0;
2734 for (Segment_list::const_iterator p = this->segment_list_.begin();
2735 p != this->segment_list_.end();
2737 section_count += (*p)->output_section_count();
2738 return section_count;
2741 // Create the dynamic symbol table.
2744 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2745 Symbol_table* symtab,
2746 Output_section **pdynstr,
2747 unsigned int* plocal_dynamic_count,
2748 std::vector<Symbol*>* pdynamic_symbols,
2749 Versions* pversions)
2751 // Count all the symbols in the dynamic symbol table, and set the
2752 // dynamic symbol indexes.
2754 // Skip symbol 0, which is always all zeroes.
2755 unsigned int index = 1;
2757 // Add STT_SECTION symbols for each Output section which needs one.
2758 for (Section_list::iterator p = this->section_list_.begin();
2759 p != this->section_list_.end();
2762 if (!(*p)->needs_dynsym_index())
2763 (*p)->set_dynsym_index(-1U);
2766 (*p)->set_dynsym_index(index);
2771 // Count the local symbols that need to go in the dynamic symbol table,
2772 // and set the dynamic symbol indexes.
2773 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2774 p != input_objects->relobj_end();
2777 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2781 unsigned int local_symcount = index;
2782 *plocal_dynamic_count = local_symcount;
2784 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2785 &this->dynpool_, pversions);
2789 const int size = parameters->target().get_size();
2792 symsize = elfcpp::Elf_sizes<32>::sym_size;
2795 else if (size == 64)
2797 symsize = elfcpp::Elf_sizes<64>::sym_size;
2803 // Create the dynamic symbol table section.
2805 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2808 false, false, true);
2810 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2813 dynsym->add_output_section_data(odata);
2815 dynsym->set_info(local_symcount);
2816 dynsym->set_entsize(symsize);
2817 dynsym->set_addralign(align);
2819 this->dynsym_section_ = dynsym;
2821 Output_data_dynamic* const odyn = this->dynamic_data_;
2822 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2823 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2825 // If there are more than SHN_LORESERVE allocated sections, we
2826 // create a .dynsym_shndx section. It is possible that we don't
2827 // need one, because it is possible that there are no dynamic
2828 // symbols in any of the sections with indexes larger than
2829 // SHN_LORESERVE. This is probably unusual, though, and at this
2830 // time we don't know the actual section indexes so it is
2831 // inconvenient to check.
2832 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2834 Output_section* dynsym_xindex =
2835 this->choose_output_section(NULL, ".dynsym_shndx",
2836 elfcpp::SHT_SYMTAB_SHNDX,
2838 false, false, true);
2840 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2842 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2844 dynsym_xindex->set_link_section(dynsym);
2845 dynsym_xindex->set_addralign(4);
2846 dynsym_xindex->set_entsize(4);
2848 dynsym_xindex->set_after_input_sections();
2850 // This tells the driver code to wait until the symbol table has
2851 // written out before writing out the postprocessing sections,
2852 // including the .dynsym_shndx section.
2853 this->any_postprocessing_sections_ = true;
2856 // Create the dynamic string table section.
2858 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2861 false, false, true);
2863 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2864 dynstr->add_output_section_data(strdata);
2866 dynsym->set_link_section(dynstr);
2867 this->dynamic_section_->set_link_section(dynstr);
2869 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2870 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2874 // Create the hash tables.
2876 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2877 || strcmp(parameters->options().hash_style(), "both") == 0)
2879 unsigned char* phash;
2880 unsigned int hashlen;
2881 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2884 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2887 false, false, true);
2889 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2893 hashsec->add_output_section_data(hashdata);
2895 hashsec->set_link_section(dynsym);
2896 hashsec->set_entsize(4);
2898 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2901 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2902 || strcmp(parameters->options().hash_style(), "both") == 0)
2904 unsigned char* phash;
2905 unsigned int hashlen;
2906 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2909 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2910 elfcpp::SHT_GNU_HASH,
2912 false, false, true);
2914 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2918 hashsec->add_output_section_data(hashdata);
2920 hashsec->set_link_section(dynsym);
2921 hashsec->set_entsize(4);
2923 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2927 // Assign offsets to each local portion of the dynamic symbol table.
2930 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2932 Output_section* dynsym = this->dynsym_section_;
2933 gold_assert(dynsym != NULL);
2935 off_t off = dynsym->offset();
2937 // Skip the dummy symbol at the start of the section.
2938 off += dynsym->entsize();
2940 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2941 p != input_objects->relobj_end();
2944 unsigned int count = (*p)->set_local_dynsym_offset(off);
2945 off += count * dynsym->entsize();
2949 // Create the version sections.
2952 Layout::create_version_sections(const Versions* versions,
2953 const Symbol_table* symtab,
2954 unsigned int local_symcount,
2955 const std::vector<Symbol*>& dynamic_symbols,
2956 const Output_section* dynstr)
2958 if (!versions->any_defs() && !versions->any_needs())
2961 switch (parameters->size_and_endianness())
2963 #ifdef HAVE_TARGET_32_LITTLE
2964 case Parameters::TARGET_32_LITTLE:
2965 this->sized_create_version_sections<32, false>(versions, symtab,
2967 dynamic_symbols, dynstr);
2970 #ifdef HAVE_TARGET_32_BIG
2971 case Parameters::TARGET_32_BIG:
2972 this->sized_create_version_sections<32, true>(versions, symtab,
2974 dynamic_symbols, dynstr);
2977 #ifdef HAVE_TARGET_64_LITTLE
2978 case Parameters::TARGET_64_LITTLE:
2979 this->sized_create_version_sections<64, false>(versions, symtab,
2981 dynamic_symbols, dynstr);
2984 #ifdef HAVE_TARGET_64_BIG
2985 case Parameters::TARGET_64_BIG:
2986 this->sized_create_version_sections<64, true>(versions, symtab,
2988 dynamic_symbols, dynstr);
2996 // Create the version sections, sized version.
2998 template<int size, bool big_endian>
3000 Layout::sized_create_version_sections(
3001 const Versions* versions,
3002 const Symbol_table* symtab,
3003 unsigned int local_symcount,
3004 const std::vector<Symbol*>& dynamic_symbols,
3005 const Output_section* dynstr)
3007 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3008 elfcpp::SHT_GNU_versym,
3010 false, false, true);
3012 unsigned char* vbuf;
3014 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3019 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3022 vsec->add_output_section_data(vdata);
3023 vsec->set_entsize(2);
3024 vsec->set_link_section(this->dynsym_section_);
3026 Output_data_dynamic* const odyn = this->dynamic_data_;
3027 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3029 if (versions->any_defs())
3031 Output_section* vdsec;
3032 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3033 elfcpp::SHT_GNU_verdef,
3035 false, false, true);
3037 unsigned char* vdbuf;
3038 unsigned int vdsize;
3039 unsigned int vdentries;
3040 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3041 &vdsize, &vdentries);
3043 Output_section_data* vddata =
3044 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3046 vdsec->add_output_section_data(vddata);
3047 vdsec->set_link_section(dynstr);
3048 vdsec->set_info(vdentries);
3050 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3051 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3054 if (versions->any_needs())
3056 Output_section* vnsec;
3057 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3058 elfcpp::SHT_GNU_verneed,
3060 false, false, true);
3062 unsigned char* vnbuf;
3063 unsigned int vnsize;
3064 unsigned int vnentries;
3065 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3069 Output_section_data* vndata =
3070 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3072 vnsec->add_output_section_data(vndata);
3073 vnsec->set_link_section(dynstr);
3074 vnsec->set_info(vnentries);
3076 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3077 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3081 // Create the .interp section and PT_INTERP segment.
3084 Layout::create_interp(const Target* target)
3086 const char* interp = parameters->options().dynamic_linker();
3089 interp = target->dynamic_linker();
3090 gold_assert(interp != NULL);
3093 size_t len = strlen(interp) + 1;
3095 Output_section_data* odata = new Output_data_const(interp, len, 1);
3097 Output_section* osec = this->choose_output_section(NULL, ".interp",
3098 elfcpp::SHT_PROGBITS,
3101 osec->add_output_section_data(odata);
3103 if (!this->script_options_->saw_phdrs_clause())
3105 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3107 oseg->add_output_section(osec, elfcpp::PF_R, false);
3111 // Finish the .dynamic section and PT_DYNAMIC segment.
3114 Layout::finish_dynamic_section(const Input_objects* input_objects,
3115 const Symbol_table* symtab)
3117 if (!this->script_options_->saw_phdrs_clause())
3119 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3122 oseg->add_output_section(this->dynamic_section_,
3123 elfcpp::PF_R | elfcpp::PF_W,
3127 Output_data_dynamic* const odyn = this->dynamic_data_;
3129 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3130 p != input_objects->dynobj_end();
3133 // FIXME: Handle --as-needed.
3134 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3137 if (parameters->options().shared())
3139 const char* soname = parameters->options().soname();
3141 odyn->add_string(elfcpp::DT_SONAME, soname);
3144 Symbol* sym = symtab->lookup(parameters->options().init());
3145 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3146 odyn->add_symbol(elfcpp::DT_INIT, sym);
3148 sym = symtab->lookup(parameters->options().fini());
3149 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3150 odyn->add_symbol(elfcpp::DT_FINI, sym);
3152 // Look for .init_array, .preinit_array and .fini_array by checking
3154 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3155 p != this->section_list_.end();
3157 switch((*p)->type())
3159 case elfcpp::SHT_FINI_ARRAY:
3160 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3161 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3163 case elfcpp::SHT_INIT_ARRAY:
3164 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3165 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3167 case elfcpp::SHT_PREINIT_ARRAY:
3168 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3169 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3175 // Add a DT_RPATH entry if needed.
3176 const General_options::Dir_list& rpath(parameters->options().rpath());
3179 std::string rpath_val;
3180 for (General_options::Dir_list::const_iterator p = rpath.begin();
3184 if (rpath_val.empty())
3185 rpath_val = p->name();
3188 // Eliminate duplicates.
3189 General_options::Dir_list::const_iterator q;
3190 for (q = rpath.begin(); q != p; ++q)
3191 if (q->name() == p->name())
3196 rpath_val += p->name();
3201 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3202 if (parameters->options().enable_new_dtags())
3203 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3206 // Look for text segments that have dynamic relocations.
3207 bool have_textrel = false;
3208 if (!this->script_options_->saw_sections_clause())
3210 for (Segment_list::const_iterator p = this->segment_list_.begin();
3211 p != this->segment_list_.end();
3214 if (((*p)->flags() & elfcpp::PF_W) == 0
3215 && (*p)->dynamic_reloc_count() > 0)
3217 have_textrel = true;
3224 // We don't know the section -> segment mapping, so we are
3225 // conservative and just look for readonly sections with
3226 // relocations. If those sections wind up in writable segments,
3227 // then we have created an unnecessary DT_TEXTREL entry.
3228 for (Section_list::const_iterator p = this->section_list_.begin();
3229 p != this->section_list_.end();
3232 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3233 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3234 && ((*p)->dynamic_reloc_count() > 0))
3236 have_textrel = true;
3242 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3243 // post-link tools can easily modify these flags if desired.
3244 unsigned int flags = 0;
3247 // Add a DT_TEXTREL for compatibility with older loaders.
3248 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3249 flags |= elfcpp::DF_TEXTREL;
3251 if (parameters->options().shared() && this->has_static_tls())
3252 flags |= elfcpp::DF_STATIC_TLS;
3253 if (parameters->options().origin())
3254 flags |= elfcpp::DF_ORIGIN;
3255 if (parameters->options().Bsymbolic())
3257 flags |= elfcpp::DF_SYMBOLIC;
3258 // Add DT_SYMBOLIC for compatibility with older loaders.
3259 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3261 if (parameters->options().now())
3262 flags |= elfcpp::DF_BIND_NOW;
3263 odyn->add_constant(elfcpp::DT_FLAGS, flags);
3266 if (parameters->options().initfirst())
3267 flags |= elfcpp::DF_1_INITFIRST;
3268 if (parameters->options().interpose())
3269 flags |= elfcpp::DF_1_INTERPOSE;
3270 if (parameters->options().loadfltr())
3271 flags |= elfcpp::DF_1_LOADFLTR;
3272 if (parameters->options().nodefaultlib())
3273 flags |= elfcpp::DF_1_NODEFLIB;
3274 if (parameters->options().nodelete())
3275 flags |= elfcpp::DF_1_NODELETE;
3276 if (parameters->options().nodlopen())
3277 flags |= elfcpp::DF_1_NOOPEN;
3278 if (parameters->options().nodump())
3279 flags |= elfcpp::DF_1_NODUMP;
3280 if (!parameters->options().shared())
3281 flags &= ~(elfcpp::DF_1_INITFIRST
3282 | elfcpp::DF_1_NODELETE
3283 | elfcpp::DF_1_NOOPEN);
3284 if (parameters->options().origin())
3285 flags |= elfcpp::DF_1_ORIGIN;
3286 if (parameters->options().now())
3287 flags |= elfcpp::DF_1_NOW;
3289 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3292 // The mapping of input section name prefixes to output section names.
3293 // In some cases one prefix is itself a prefix of another prefix; in
3294 // such a case the longer prefix must come first. These prefixes are
3295 // based on the GNU linker default ELF linker script.
3297 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3298 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3300 MAPPING_INIT(".text.", ".text"),
3301 MAPPING_INIT(".ctors.", ".ctors"),
3302 MAPPING_INIT(".dtors.", ".dtors"),
3303 MAPPING_INIT(".rodata.", ".rodata"),
3304 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3305 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3306 MAPPING_INIT(".data.", ".data"),
3307 MAPPING_INIT(".bss.", ".bss"),
3308 MAPPING_INIT(".tdata.", ".tdata"),
3309 MAPPING_INIT(".tbss.", ".tbss"),
3310 MAPPING_INIT(".init_array.", ".init_array"),
3311 MAPPING_INIT(".fini_array.", ".fini_array"),
3312 MAPPING_INIT(".sdata.", ".sdata"),
3313 MAPPING_INIT(".sbss.", ".sbss"),
3314 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3315 // differently depending on whether it is creating a shared library.
3316 MAPPING_INIT(".sdata2.", ".sdata"),
3317 MAPPING_INIT(".sbss2.", ".sbss"),
3318 MAPPING_INIT(".lrodata.", ".lrodata"),
3319 MAPPING_INIT(".ldata.", ".ldata"),
3320 MAPPING_INIT(".lbss.", ".lbss"),
3321 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3322 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3323 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3324 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3325 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3326 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3327 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3328 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3329 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3330 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3331 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3332 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3333 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3334 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3335 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3336 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3337 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3338 MAPPING_INIT(".ARM.extab.", ".ARM.extab"),
3339 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3340 MAPPING_INIT(".ARM.exidx.", ".ARM.exidx"),
3341 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3345 const int Layout::section_name_mapping_count =
3346 (sizeof(Layout::section_name_mapping)
3347 / sizeof(Layout::section_name_mapping[0]));
3349 // Choose the output section name to use given an input section name.
3350 // Set *PLEN to the length of the name. *PLEN is initialized to the
3354 Layout::output_section_name(const char* name, size_t* plen)
3356 // gcc 4.3 generates the following sorts of section names when it
3357 // needs a section name specific to a function:
3363 // .data.rel.local.FN
3365 // .data.rel.ro.local.FN
3372 // The GNU linker maps all of those to the part before the .FN,
3373 // except that .data.rel.local.FN is mapped to .data, and
3374 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3375 // beginning with .data.rel.ro.local are grouped together.
3377 // For an anonymous namespace, the string FN can contain a '.'.
3379 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3380 // GNU linker maps to .rodata.
3382 // The .data.rel.ro sections are used with -z relro. The sections
3383 // are recognized by name. We use the same names that the GNU
3384 // linker does for these sections.
3386 // It is hard to handle this in a principled way, so we don't even
3387 // try. We use a table of mappings. If the input section name is
3388 // not found in the table, we simply use it as the output section
3391 const Section_name_mapping* psnm = section_name_mapping;
3392 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3394 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3396 *plen = psnm->tolen;
3404 // Check if a comdat group or .gnu.linkonce section with the given
3405 // NAME is selected for the link. If there is already a section,
3406 // *KEPT_SECTION is set to point to the existing section and the
3407 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3408 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3409 // *KEPT_SECTION is set to the internal copy and the function returns
3413 Layout::find_or_add_kept_section(const std::string& name,
3418 Kept_section** kept_section)
3420 // It's normal to see a couple of entries here, for the x86 thunk
3421 // sections. If we see more than a few, we're linking a C++
3422 // program, and we resize to get more space to minimize rehashing.
3423 if (this->signatures_.size() > 4
3424 && !this->resized_signatures_)
3426 reserve_unordered_map(&this->signatures_,
3427 this->number_of_input_files_ * 64);
3428 this->resized_signatures_ = true;
3431 Kept_section candidate;
3432 std::pair<Signatures::iterator, bool> ins =
3433 this->signatures_.insert(std::make_pair(name, candidate));
3435 if (kept_section != NULL)
3436 *kept_section = &ins.first->second;
3439 // This is the first time we've seen this signature.
3440 ins.first->second.set_object(object);
3441 ins.first->second.set_shndx(shndx);
3443 ins.first->second.set_is_comdat();
3445 ins.first->second.set_is_group_name();
3449 // We have already seen this signature.
3451 if (ins.first->second.is_group_name())
3453 // We've already seen a real section group with this signature.
3454 // If the kept group is from a plugin object, and we're in the
3455 // replacement phase, accept the new one as a replacement.
3456 if (ins.first->second.object() == NULL
3457 && parameters->options().plugins()->in_replacement_phase())
3459 ins.first->second.set_object(object);
3460 ins.first->second.set_shndx(shndx);
3465 else if (is_group_name)
3467 // This is a real section group, and we've already seen a
3468 // linkonce section with this signature. Record that we've seen
3469 // a section group, and don't include this section group.
3470 ins.first->second.set_is_group_name();
3475 // We've already seen a linkonce section and this is a linkonce
3476 // section. These don't block each other--this may be the same
3477 // symbol name with different section types.
3482 // Store the allocated sections into the section list.
3485 Layout::get_allocated_sections(Section_list* section_list) const
3487 for (Section_list::const_iterator p = this->section_list_.begin();
3488 p != this->section_list_.end();
3490 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3491 section_list->push_back(*p);
3494 // Create an output segment.
3497 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3499 gold_assert(!parameters->options().relocatable());
3500 Output_segment* oseg = new Output_segment(type, flags);
3501 this->segment_list_.push_back(oseg);
3503 if (type == elfcpp::PT_TLS)
3504 this->tls_segment_ = oseg;
3505 else if (type == elfcpp::PT_GNU_RELRO)
3506 this->relro_segment_ = oseg;
3511 // Write out the Output_sections. Most won't have anything to write,
3512 // since most of the data will come from input sections which are
3513 // handled elsewhere. But some Output_sections do have Output_data.
3516 Layout::write_output_sections(Output_file* of) const
3518 for (Section_list::const_iterator p = this->section_list_.begin();
3519 p != this->section_list_.end();
3522 if (!(*p)->after_input_sections())
3527 // Write out data not associated with a section or the symbol table.
3530 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
3532 if (!parameters->options().strip_all())
3534 const Output_section* symtab_section = this->symtab_section_;
3535 for (Section_list::const_iterator p = this->section_list_.begin();
3536 p != this->section_list_.end();
3539 if ((*p)->needs_symtab_index())
3541 gold_assert(symtab_section != NULL);
3542 unsigned int index = (*p)->symtab_index();
3543 gold_assert(index > 0 && index != -1U);
3544 off_t off = (symtab_section->offset()
3545 + index * symtab_section->entsize());
3546 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3551 const Output_section* dynsym_section = this->dynsym_section_;
3552 for (Section_list::const_iterator p = this->section_list_.begin();
3553 p != this->section_list_.end();
3556 if ((*p)->needs_dynsym_index())
3558 gold_assert(dynsym_section != NULL);
3559 unsigned int index = (*p)->dynsym_index();
3560 gold_assert(index > 0 && index != -1U);
3561 off_t off = (dynsym_section->offset()
3562 + index * dynsym_section->entsize());
3563 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3567 // Write out the Output_data which are not in an Output_section.
3568 for (Data_list::const_iterator p = this->special_output_list_.begin();
3569 p != this->special_output_list_.end();
3574 // Write out the Output_sections which can only be written after the
3575 // input sections are complete.
3578 Layout::write_sections_after_input_sections(Output_file* of)
3580 // Determine the final section offsets, and thus the final output
3581 // file size. Note we finalize the .shstrab last, to allow the
3582 // after_input_section sections to modify their section-names before
3584 if (this->any_postprocessing_sections_)
3586 off_t off = this->output_file_size_;
3587 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3589 // Now that we've finalized the names, we can finalize the shstrab.
3591 this->set_section_offsets(off,
3592 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3594 if (off > this->output_file_size_)
3597 this->output_file_size_ = off;
3601 for (Section_list::const_iterator p = this->section_list_.begin();
3602 p != this->section_list_.end();
3605 if ((*p)->after_input_sections())
3609 this->section_headers_->write(of);
3612 // If the build ID requires computing a checksum, do so here, and
3613 // write it out. We compute a checksum over the entire file because
3614 // that is simplest.
3617 Layout::write_build_id(Output_file* of) const
3619 if (this->build_id_note_ == NULL)
3622 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3624 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3625 this->build_id_note_->data_size());
3627 const char* style = parameters->options().build_id();
3628 if (strcmp(style, "sha1") == 0)
3631 sha1_init_ctx(&ctx);
3632 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3633 sha1_finish_ctx(&ctx, ov);
3635 else if (strcmp(style, "md5") == 0)
3639 md5_process_bytes(iv, this->output_file_size_, &ctx);
3640 md5_finish_ctx(&ctx, ov);
3645 of->write_output_view(this->build_id_note_->offset(),
3646 this->build_id_note_->data_size(),
3649 of->free_input_view(0, this->output_file_size_, iv);
3652 // Write out a binary file. This is called after the link is
3653 // complete. IN is the temporary output file we used to generate the
3654 // ELF code. We simply walk through the segments, read them from
3655 // their file offset in IN, and write them to their load address in
3656 // the output file. FIXME: with a bit more work, we could support
3657 // S-records and/or Intel hex format here.
3660 Layout::write_binary(Output_file* in) const
3662 gold_assert(parameters->options().oformat_enum()
3663 == General_options::OBJECT_FORMAT_BINARY);
3665 // Get the size of the binary file.
3666 uint64_t max_load_address = 0;
3667 for (Segment_list::const_iterator p = this->segment_list_.begin();
3668 p != this->segment_list_.end();
3671 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3673 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3674 if (max_paddr > max_load_address)
3675 max_load_address = max_paddr;
3679 Output_file out(parameters->options().output_file_name());
3680 out.open(max_load_address);
3682 for (Segment_list::const_iterator p = this->segment_list_.begin();
3683 p != this->segment_list_.end();
3686 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3688 const unsigned char* vin = in->get_input_view((*p)->offset(),
3690 unsigned char* vout = out.get_output_view((*p)->paddr(),
3692 memcpy(vout, vin, (*p)->filesz());
3693 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3694 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3701 // Print the output sections to the map file.
3704 Layout::print_to_mapfile(Mapfile* mapfile) const
3706 for (Segment_list::const_iterator p = this->segment_list_.begin();
3707 p != this->segment_list_.end();
3709 (*p)->print_sections_to_mapfile(mapfile);
3712 // Print statistical information to stderr. This is used for --stats.
3715 Layout::print_stats() const
3717 this->namepool_.print_stats("section name pool");
3718 this->sympool_.print_stats("output symbol name pool");
3719 this->dynpool_.print_stats("dynamic name pool");
3721 for (Section_list::const_iterator p = this->section_list_.begin();
3722 p != this->section_list_.end();
3724 (*p)->print_merge_stats();
3727 // Write_sections_task methods.
3729 // We can always run this task.
3732 Write_sections_task::is_runnable()
3737 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3741 Write_sections_task::locks(Task_locker* tl)
3743 tl->add(this, this->output_sections_blocker_);
3744 tl->add(this, this->final_blocker_);
3747 // Run the task--write out the data.
3750 Write_sections_task::run(Workqueue*)
3752 this->layout_->write_output_sections(this->of_);
3755 // Write_data_task methods.
3757 // We can always run this task.
3760 Write_data_task::is_runnable()
3765 // We need to unlock FINAL_BLOCKER when finished.
3768 Write_data_task::locks(Task_locker* tl)
3770 tl->add(this, this->final_blocker_);
3773 // Run the task--write out the data.
3776 Write_data_task::run(Workqueue*)
3778 this->layout_->write_data(this->symtab_, this->of_);
3781 // Write_symbols_task methods.
3783 // We can always run this task.
3786 Write_symbols_task::is_runnable()
3791 // We need to unlock FINAL_BLOCKER when finished.
3794 Write_symbols_task::locks(Task_locker* tl)
3796 tl->add(this, this->final_blocker_);
3799 // Run the task--write out the symbols.
3802 Write_symbols_task::run(Workqueue*)
3804 this->symtab_->write_globals(this->sympool_, this->dynpool_,
3805 this->layout_->symtab_xindex(),
3806 this->layout_->dynsym_xindex(), this->of_);
3809 // Write_after_input_sections_task methods.
3811 // We can only run this task after the input sections have completed.
3814 Write_after_input_sections_task::is_runnable()
3816 if (this->input_sections_blocker_->is_blocked())
3817 return this->input_sections_blocker_;
3821 // We need to unlock FINAL_BLOCKER when finished.
3824 Write_after_input_sections_task::locks(Task_locker* tl)
3826 tl->add(this, this->final_blocker_);
3832 Write_after_input_sections_task::run(Workqueue*)
3834 this->layout_->write_sections_after_input_sections(this->of_);
3837 // Close_task_runner methods.
3839 // Run the task--close the file.
3842 Close_task_runner::run(Workqueue*, const Task*)
3844 // If we need to compute a checksum for the BUILD if, we do so here.
3845 this->layout_->write_build_id(this->of_);
3847 // If we've been asked to create a binary file, we do so here.
3848 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3849 this->layout_->write_binary(this->of_);
3854 // Instantiate the templates we need. We could use the configure
3855 // script to restrict this to only the ones for implemented targets.
3857 #ifdef HAVE_TARGET_32_LITTLE
3860 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3862 const elfcpp::Shdr<32, false>& shdr,
3863 unsigned int, unsigned int, off_t*);
3866 #ifdef HAVE_TARGET_32_BIG
3869 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3871 const elfcpp::Shdr<32, true>& shdr,
3872 unsigned int, unsigned int, off_t*);
3875 #ifdef HAVE_TARGET_64_LITTLE
3878 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3880 const elfcpp::Shdr<64, false>& shdr,
3881 unsigned int, unsigned int, off_t*);
3884 #ifdef HAVE_TARGET_64_BIG
3887 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3889 const elfcpp::Shdr<64, true>& shdr,
3890 unsigned int, unsigned int, off_t*);
3893 #ifdef HAVE_TARGET_32_LITTLE
3896 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3897 unsigned int reloc_shndx,
3898 const elfcpp::Shdr<32, false>& shdr,
3899 Output_section* data_section,
3900 Relocatable_relocs* rr);
3903 #ifdef HAVE_TARGET_32_BIG
3906 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3907 unsigned int reloc_shndx,
3908 const elfcpp::Shdr<32, true>& shdr,
3909 Output_section* data_section,
3910 Relocatable_relocs* rr);
3913 #ifdef HAVE_TARGET_64_LITTLE
3916 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3917 unsigned int reloc_shndx,
3918 const elfcpp::Shdr<64, false>& shdr,
3919 Output_section* data_section,
3920 Relocatable_relocs* rr);
3923 #ifdef HAVE_TARGET_64_BIG
3926 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3927 unsigned int reloc_shndx,
3928 const elfcpp::Shdr<64, true>& shdr,
3929 Output_section* data_section,
3930 Relocatable_relocs* rr);
3933 #ifdef HAVE_TARGET_32_LITTLE
3936 Layout::layout_group<32, false>(Symbol_table* symtab,
3937 Sized_relobj<32, false>* object,
3939 const char* group_section_name,
3940 const char* signature,
3941 const elfcpp::Shdr<32, false>& shdr,
3942 elfcpp::Elf_Word flags,
3943 std::vector<unsigned int>* shndxes);
3946 #ifdef HAVE_TARGET_32_BIG
3949 Layout::layout_group<32, true>(Symbol_table* symtab,
3950 Sized_relobj<32, true>* object,
3952 const char* group_section_name,
3953 const char* signature,
3954 const elfcpp::Shdr<32, true>& shdr,
3955 elfcpp::Elf_Word flags,
3956 std::vector<unsigned int>* shndxes);
3959 #ifdef HAVE_TARGET_64_LITTLE
3962 Layout::layout_group<64, false>(Symbol_table* symtab,
3963 Sized_relobj<64, false>* object,
3965 const char* group_section_name,
3966 const char* signature,
3967 const elfcpp::Shdr<64, false>& shdr,
3968 elfcpp::Elf_Word flags,
3969 std::vector<unsigned int>* shndxes);
3972 #ifdef HAVE_TARGET_64_BIG
3975 Layout::layout_group<64, true>(Symbol_table* symtab,
3976 Sized_relobj<64, true>* object,
3978 const char* group_section_name,
3979 const char* signature,
3980 const elfcpp::Shdr<64, true>& shdr,
3981 elfcpp::Elf_Word flags,
3982 std::vector<unsigned int>* shndxes);
3985 #ifdef HAVE_TARGET_32_LITTLE
3988 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3989 const unsigned char* symbols,
3991 const unsigned char* symbol_names,
3992 off_t symbol_names_size,
3994 const elfcpp::Shdr<32, false>& shdr,
3995 unsigned int reloc_shndx,
3996 unsigned int reloc_type,
4000 #ifdef HAVE_TARGET_32_BIG
4003 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4004 const unsigned char* symbols,
4006 const unsigned char* symbol_names,
4007 off_t symbol_names_size,
4009 const elfcpp::Shdr<32, true>& shdr,
4010 unsigned int reloc_shndx,
4011 unsigned int reloc_type,
4015 #ifdef HAVE_TARGET_64_LITTLE
4018 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4019 const unsigned char* symbols,
4021 const unsigned char* symbol_names,
4022 off_t symbol_names_size,
4024 const elfcpp::Shdr<64, false>& shdr,
4025 unsigned int reloc_shndx,
4026 unsigned int reloc_type,
4030 #ifdef HAVE_TARGET_64_BIG
4033 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4034 const unsigned char* symbols,
4036 const unsigned char* symbol_names,
4037 off_t symbol_names_size,
4039 const elfcpp::Shdr<64, true>& shdr,
4040 unsigned int reloc_shndx,
4041 unsigned int reloc_type,
4045 } // End namespace gold.