1 // layout.cc -- lay out output file sections for gold
3 // Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
6 // This file is part of gold.
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
30 #include "parameters.h"
33 #include "script-sections.h"
38 #include "compressed_output.h"
44 // Layout_task_runner methods.
46 // Lay out the sections. This is called after all the input objects
50 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
52 off_t file_size = this->layout_->finalize(this->input_objects_,
56 // Now we know the final size of the output file and we know where
57 // each piece of information goes.
58 Output_file* of = new Output_file(parameters->output_file_name());
61 // Queue up the final set of tasks.
62 gold::queue_final_tasks(this->options_, this->input_objects_,
63 this->symtab_, this->layout_, workqueue, of);
68 Layout::Layout(const General_options& options, Script_options* script_options)
69 : options_(options), script_options_(script_options), namepool_(),
70 sympool_(), dynpool_(), signatures_(),
71 section_name_map_(), segment_list_(), section_list_(),
72 unattached_section_list_(), special_output_list_(),
73 section_headers_(NULL), tls_segment_(NULL), symtab_section_(NULL),
74 dynsym_section_(NULL), dynamic_section_(NULL), dynamic_data_(NULL),
75 eh_frame_section_(NULL), output_file_size_(-1),
76 input_requires_executable_stack_(false),
77 input_with_gnu_stack_note_(false),
78 input_without_gnu_stack_note_(false),
79 has_static_tls_(false),
80 any_postprocessing_sections_(false)
82 // Make space for more than enough segments for a typical file.
83 // This is just for efficiency--it's OK if we wind up needing more.
84 this->segment_list_.reserve(12);
86 // We expect two unattached Output_data objects: the file header and
87 // the segment headers.
88 this->special_output_list_.reserve(2);
91 // Hash a key we use to look up an output section mapping.
94 Layout::Hash_key::operator()(const Layout::Key& k) const
96 return k.first + k.second.first + k.second.second;
99 // Return whether PREFIX is a prefix of STR.
102 is_prefix_of(const char* prefix, const char* str)
104 return strncmp(prefix, str, strlen(prefix)) == 0;
107 // Returns whether the given section is in the list of
108 // debug-sections-used-by-some-version-of-gdb. Currently,
109 // we've checked versions of gdb up to and including 6.7.1.
111 static const char* gdb_sections[] =
113 // ".debug_aranges", // not used by gdb as of 6.7.1
119 // ".debug_pubnames", // not used by gdb as of 6.7.1
125 is_gdb_debug_section(const char* str)
127 // We can do this faster: binary search or a hashtable. But why bother?
128 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
129 if (strcmp(str, gdb_sections[i]) == 0)
134 // Whether to include this section in the link.
136 template<int size, bool big_endian>
138 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
139 const elfcpp::Shdr<size, big_endian>& shdr)
141 // Some section types are never linked. Some are only linked when
142 // doing a relocateable link.
143 switch (shdr.get_sh_type())
145 case elfcpp::SHT_NULL:
146 case elfcpp::SHT_SYMTAB:
147 case elfcpp::SHT_DYNSYM:
148 case elfcpp::SHT_STRTAB:
149 case elfcpp::SHT_HASH:
150 case elfcpp::SHT_DYNAMIC:
151 case elfcpp::SHT_SYMTAB_SHNDX:
154 case elfcpp::SHT_RELA:
155 case elfcpp::SHT_REL:
156 case elfcpp::SHT_GROUP:
157 return parameters->output_is_object();
159 case elfcpp::SHT_PROGBITS:
160 if (parameters->strip_debug()
161 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
163 // Debugging sections can only be recognized by name.
164 if (is_prefix_of(".debug", name)
165 || is_prefix_of(".gnu.linkonce.wi.", name)
166 || is_prefix_of(".line", name)
167 || is_prefix_of(".stab", name))
170 if (parameters->strip_debug_gdb()
171 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
173 // Debugging sections can only be recognized by name.
174 if (is_prefix_of(".debug", name)
175 && !is_gdb_debug_section(name))
185 // Return an output section named NAME, or NULL if there is none.
188 Layout::find_output_section(const char* name) const
190 for (Section_list::const_iterator p = this->section_list_.begin();
191 p != this->section_list_.end();
193 if (strcmp((*p)->name(), name) == 0)
198 // Return an output segment of type TYPE, with segment flags SET set
199 // and segment flags CLEAR clear. Return NULL if there is none.
202 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
203 elfcpp::Elf_Word clear) const
205 for (Segment_list::const_iterator p = this->segment_list_.begin();
206 p != this->segment_list_.end();
208 if (static_cast<elfcpp::PT>((*p)->type()) == type
209 && ((*p)->flags() & set) == set
210 && ((*p)->flags() & clear) == 0)
215 // Return the output section to use for section NAME with type TYPE
216 // and section flags FLAGS. NAME must be canonicalized in the string
217 // pool, and NAME_KEY is the key.
220 Layout::get_output_section(const char* name, Stringpool::Key name_key,
221 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
223 const Key key(name_key, std::make_pair(type, flags));
224 const std::pair<Key, Output_section*> v(key, NULL);
225 std::pair<Section_name_map::iterator, bool> ins(
226 this->section_name_map_.insert(v));
229 return ins.first->second;
232 // This is the first time we've seen this name/type/flags
234 Output_section* os = this->make_output_section(name, type, flags);
235 ins.first->second = os;
240 // Pick the output section to use for section NAME, in input file
241 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
242 // linker created section. ADJUST_NAME is true if we should apply the
243 // standard name mappings in Layout::output_section_name. This will
244 // return NULL if the input section should be discarded.
247 Layout::choose_output_section(const Relobj* relobj, const char* name,
248 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
251 // We should ignore some flags. FIXME: This will need some
252 // adjustment for ld -r.
253 flags &= ~ (elfcpp::SHF_INFO_LINK
254 | elfcpp::SHF_LINK_ORDER
257 | elfcpp::SHF_STRINGS);
259 if (this->script_options_->saw_sections_clause())
261 // We are using a SECTIONS clause, so the output section is
262 // chosen based only on the name.
264 Script_sections* ss = this->script_options_->script_sections();
265 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
266 Output_section** output_section_slot;
267 name = ss->output_section_name(file_name, name, &output_section_slot);
270 // The SECTIONS clause says to discard this input section.
274 // If this is an orphan section--one not mentioned in the linker
275 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
276 // default processing below.
278 if (output_section_slot != NULL)
280 if (*output_section_slot != NULL)
281 return *output_section_slot;
283 // We don't put sections found in the linker script into
284 // SECTION_NAME_MAP_. That keeps us from getting confused
285 // if an orphan section is mapped to a section with the same
286 // name as one in the linker script.
288 name = this->namepool_.add(name, false, NULL);
290 Output_section* os = this->make_output_section(name, type, flags);
291 os->set_found_in_sections_clause();
292 *output_section_slot = os;
297 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
299 // Turn NAME from the name of the input section into the name of the
302 size_t len = strlen(name);
303 if (adjust_name && !parameters->output_is_object())
304 name = Layout::output_section_name(name, &len);
306 Stringpool::Key name_key;
307 name = this->namepool_.add_with_length(name, len, true, &name_key);
309 // Find or make the output section. The output section is selected
310 // based on the section name, type, and flags.
311 return this->get_output_section(name, name_key, type, flags);
314 // Return the output section to use for input section SHNDX, with name
315 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
316 // index of a relocation section which applies to this section, or 0
317 // if none, or -1U if more than one. RELOC_TYPE is the type of the
318 // relocation section if there is one. Set *OFF to the offset of this
319 // input section without the output section. Return NULL if the
320 // section should be discarded. Set *OFF to -1 if the section
321 // contents should not be written directly to the output file, but
322 // will instead receive special handling.
324 template<int size, bool big_endian>
326 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
327 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
328 unsigned int reloc_shndx, unsigned int, off_t* off)
330 if (!this->include_section(object, name, shdr))
333 Output_section* os = this->choose_output_section(object,
341 // FIXME: Handle SHF_LINK_ORDER somewhere.
343 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
344 this->script_options_->saw_sections_clause());
349 // Special GNU handling of sections name .eh_frame. They will
350 // normally hold exception frame data as defined by the C++ ABI
351 // (http://codesourcery.com/cxx-abi/).
353 template<int size, bool big_endian>
355 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
356 const unsigned char* symbols,
358 const unsigned char* symbol_names,
359 off_t symbol_names_size,
361 const elfcpp::Shdr<size, big_endian>& shdr,
362 unsigned int reloc_shndx, unsigned int reloc_type,
365 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
366 gold_assert(shdr.get_sh_flags() == elfcpp::SHF_ALLOC);
368 const char* const name = ".eh_frame";
369 Output_section* os = this->choose_output_section(object,
371 elfcpp::SHT_PROGBITS,
377 if (this->eh_frame_section_ == NULL)
379 this->eh_frame_section_ = os;
380 this->eh_frame_data_ = new Eh_frame();
381 os->add_output_section_data(this->eh_frame_data_);
383 if (this->options_.create_eh_frame_hdr())
385 Output_section* hdr_os =
386 this->choose_output_section(NULL,
388 elfcpp::SHT_PROGBITS,
394 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
395 this->eh_frame_data_);
396 hdr_os->add_output_section_data(hdr_posd);
398 hdr_os->set_after_input_sections();
400 Output_segment* hdr_oseg =
401 new Output_segment(elfcpp::PT_GNU_EH_FRAME, elfcpp::PF_R);
402 this->segment_list_.push_back(hdr_oseg);
403 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
405 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
410 gold_assert(this->eh_frame_section_ == os);
412 if (this->eh_frame_data_->add_ehframe_input_section(object,
423 // We couldn't handle this .eh_frame section for some reason.
424 // Add it as a normal section.
425 bool saw_sections_clause = this->script_options_->saw_sections_clause();
426 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
427 saw_sections_clause);
433 // Add POSD to an output section using NAME, TYPE, and FLAGS.
436 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
437 elfcpp::Elf_Xword flags,
438 Output_section_data* posd)
440 Output_section* os = this->choose_output_section(NULL, name, type, flags,
443 os->add_output_section_data(posd);
446 // Map section flags to segment flags.
449 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
451 elfcpp::Elf_Word ret = elfcpp::PF_R;
452 if ((flags & elfcpp::SHF_WRITE) != 0)
454 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
459 // Sometimes we compress sections. This is typically done for
460 // sections that are not part of normal program execution (such as
461 // .debug_* sections), and where the readers of these sections know
462 // how to deal with compressed sections. (To make it easier for them,
463 // we will rename the ouput section in such cases from .foo to
464 // .foo.zlib.nnnn, where nnnn is the uncompressed size.) This routine
465 // doesn't say for certain whether we'll compress -- it depends on
466 // commandline options as well -- just whether this section is a
467 // candidate for compression.
470 is_compressible_debug_section(const char* secname)
472 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
475 // Make a new Output_section, and attach it to segments as
479 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
480 elfcpp::Elf_Xword flags)
483 if ((flags & elfcpp::SHF_ALLOC) == 0
484 && this->options_.compress_debug_sections()
485 && is_compressible_debug_section(name))
486 os = new Output_compressed_section(&this->options_, name, type, flags);
488 os = new Output_section(name, type, flags);
490 this->section_list_.push_back(os);
492 if ((flags & elfcpp::SHF_ALLOC) == 0)
493 this->unattached_section_list_.push_back(os);
496 // If we have a SECTIONS clause, we can't handle the attachment
497 // to segments until after we've seen all the sections.
498 if (this->script_options_->saw_sections_clause())
501 // This output section goes into a PT_LOAD segment.
503 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
505 // The only thing we really care about for PT_LOAD segments is
506 // whether or not they are writable, so that is how we search
507 // for them. People who need segments sorted on some other
508 // basis will have to wait until we implement a mechanism for
509 // them to describe the segments they want.
511 Segment_list::const_iterator p;
512 for (p = this->segment_list_.begin();
513 p != this->segment_list_.end();
516 if ((*p)->type() == elfcpp::PT_LOAD
517 && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
519 (*p)->add_output_section(os, seg_flags);
524 if (p == this->segment_list_.end())
526 Output_segment* oseg = new Output_segment(elfcpp::PT_LOAD,
528 this->segment_list_.push_back(oseg);
529 oseg->add_output_section(os, seg_flags);
532 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
534 if (type == elfcpp::SHT_NOTE)
536 // See if we already have an equivalent PT_NOTE segment.
537 for (p = this->segment_list_.begin();
538 p != segment_list_.end();
541 if ((*p)->type() == elfcpp::PT_NOTE
542 && (((*p)->flags() & elfcpp::PF_W)
543 == (seg_flags & elfcpp::PF_W)))
545 (*p)->add_output_section(os, seg_flags);
550 if (p == this->segment_list_.end())
552 Output_segment* oseg = new Output_segment(elfcpp::PT_NOTE,
554 this->segment_list_.push_back(oseg);
555 oseg->add_output_section(os, seg_flags);
559 // If we see a loadable SHF_TLS section, we create a PT_TLS
560 // segment. There can only be one such segment.
561 if ((flags & elfcpp::SHF_TLS) != 0)
563 if (this->tls_segment_ == NULL)
565 this->tls_segment_ = new Output_segment(elfcpp::PT_TLS,
567 this->segment_list_.push_back(this->tls_segment_);
569 this->tls_segment_->add_output_section(os, seg_flags);
576 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
577 // is whether we saw a .note.GNU-stack section in the object file.
578 // GNU_STACK_FLAGS is the section flags. The flags give the
579 // protection required for stack memory. We record this in an
580 // executable as a PT_GNU_STACK segment. If an object file does not
581 // have a .note.GNU-stack segment, we must assume that it is an old
582 // object. On some targets that will force an executable stack.
585 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
588 this->input_without_gnu_stack_note_ = true;
591 this->input_with_gnu_stack_note_ = true;
592 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
593 this->input_requires_executable_stack_ = true;
597 // Create the dynamic sections which are needed before we read the
601 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
603 if (parameters->doing_static_link())
606 const char* dynamic_name = this->namepool_.add(".dynamic", false, NULL);
607 this->dynamic_section_ = this->make_output_section(dynamic_name,
610 | elfcpp::SHF_WRITE));
612 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
613 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
614 elfcpp::STV_HIDDEN, 0, false, false);
616 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
618 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
621 // For each output section whose name can be represented as C symbol,
622 // define __start and __stop symbols for the section. This is a GNU
626 Layout::define_section_symbols(Symbol_table* symtab)
628 for (Section_list::const_iterator p = this->section_list_.begin();
629 p != this->section_list_.end();
632 const char* const name = (*p)->name();
633 if (name[strspn(name,
635 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
636 "abcdefghijklmnopqrstuvwxyz"
640 const std::string name_string(name);
641 const std::string start_name("__start_" + name_string);
642 const std::string stop_name("__stop_" + name_string);
644 symtab->define_in_output_data(start_name.c_str(),
653 false, // offset_is_from_end
654 true); // only_if_ref
656 symtab->define_in_output_data(stop_name.c_str(),
665 true, // offset_is_from_end
666 true); // only_if_ref
671 // Find the first read-only PT_LOAD segment, creating one if
675 Layout::find_first_load_seg()
677 for (Segment_list::const_iterator p = this->segment_list_.begin();
678 p != this->segment_list_.end();
681 if ((*p)->type() == elfcpp::PT_LOAD
682 && ((*p)->flags() & elfcpp::PF_R) != 0
683 && ((*p)->flags() & elfcpp::PF_W) == 0)
687 Output_segment* load_seg = new Output_segment(elfcpp::PT_LOAD, elfcpp::PF_R);
688 this->segment_list_.push_back(load_seg);
692 // Finalize the layout. When this is called, we have created all the
693 // output sections and all the output segments which are based on
694 // input sections. We have several things to do, and we have to do
695 // them in the right order, so that we get the right results correctly
698 // 1) Finalize the list of output segments and create the segment
701 // 2) Finalize the dynamic symbol table and associated sections.
703 // 3) Determine the final file offset of all the output segments.
705 // 4) Determine the final file offset of all the SHF_ALLOC output
708 // 5) Create the symbol table sections and the section name table
711 // 6) Finalize the symbol table: set symbol values to their final
712 // value and make a final determination of which symbols are going
713 // into the output symbol table.
715 // 7) Create the section table header.
717 // 8) Determine the final file offset of all the output sections which
718 // are not SHF_ALLOC, including the section table header.
720 // 9) Finalize the ELF file header.
722 // This function returns the size of the output file.
725 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
728 Target* const target = input_objects->target();
730 target->finalize_sections(this);
732 this->count_local_symbols(task, input_objects);
734 this->create_gold_note();
735 this->create_executable_stack_info(target);
737 if (!parameters->output_is_object() && !parameters->doing_static_link())
739 // There was a dynamic object in the link. We need to create
740 // some information for the dynamic linker.
742 // Create the dynamic symbol table, including the hash table.
743 Output_section* dynstr;
744 std::vector<Symbol*> dynamic_symbols;
745 unsigned int local_dynamic_count;
746 Versions versions(this->options_, &this->dynpool_);
747 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
748 &local_dynamic_count, &dynamic_symbols,
751 // Create the .interp section to hold the name of the
752 // interpreter, and put it in a PT_INTERP segment.
753 if (!parameters->output_is_shared())
754 this->create_interp(target);
756 // Finish the .dynamic section to hold the dynamic data, and put
757 // it in a PT_DYNAMIC segment.
758 this->finish_dynamic_section(input_objects, symtab);
760 // We should have added everything we need to the dynamic string
762 this->dynpool_.set_string_offsets();
764 // Create the version sections. We can't do this until the
765 // dynamic string table is complete.
766 this->create_version_sections(&versions, symtab, local_dynamic_count,
767 dynamic_symbols, dynstr);
770 // If there is a SECTIONS clause, put all the input sections into
771 // the required order.
772 Output_segment* load_seg;
773 if (this->script_options_->saw_sections_clause())
774 load_seg = this->set_section_addresses_from_script(symtab);
776 load_seg = this->find_first_load_seg();
778 Output_segment* phdr_seg = NULL;
780 && !parameters->output_is_object()
781 && !parameters->doing_static_link())
783 // Create the PT_PHDR segment which will hold the program
785 phdr_seg = new Output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
786 this->segment_list_.push_back(phdr_seg);
789 // Lay out the segment headers.
790 Output_segment_headers* segment_headers;
791 segment_headers = new Output_segment_headers(this->segment_list_);
792 if (load_seg != NULL)
793 load_seg->add_initial_output_data(segment_headers);
794 if (phdr_seg != NULL)
795 phdr_seg->add_initial_output_data(segment_headers);
797 // Lay out the file header.
798 Output_file_header* file_header;
799 file_header = new Output_file_header(target, symtab, segment_headers,
800 this->script_options_->entry());
801 if (load_seg != NULL)
802 load_seg->add_initial_output_data(file_header);
804 this->special_output_list_.push_back(file_header);
805 this->special_output_list_.push_back(segment_headers);
807 // We set the output section indexes in set_segment_offsets and
808 // set_section_indexes.
809 unsigned int shndx = 1;
811 // Set the file offsets of all the segments, and all the sections
813 off_t off = this->set_segment_offsets(target, load_seg, &shndx);
815 // Set the file offsets of all the non-data sections we've seen so
816 // far which don't have to wait for the input sections. We need
817 // this in order to finalize local symbols in non-allocated
819 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
821 // Create the symbol table sections.
822 this->create_symtab_sections(input_objects, symtab, &off);
823 if (!parameters->doing_static_link())
824 this->assign_local_dynsym_offsets(input_objects);
826 // Process any symbol assignments from a linker script. This must
827 // be called after the symbol table has been finalized.
828 this->script_options_->finalize_symbols(symtab, this);
830 // Create the .shstrtab section.
831 Output_section* shstrtab_section = this->create_shstrtab();
833 // Set the file offsets of the rest of the non-data sections which
834 // don't have to wait for the input sections.
835 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
837 // Now that all sections have been created, set the section indexes.
838 shndx = this->set_section_indexes(shndx);
840 // Create the section table header.
841 this->create_shdrs(&off);
843 // If there are no sections which require postprocessing, we can
844 // handle the section names now, and avoid a resize later.
845 if (!this->any_postprocessing_sections_)
846 off = this->set_section_offsets(off,
847 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
849 file_header->set_section_info(this->section_headers_, shstrtab_section);
851 // Now we know exactly where everything goes in the output file
852 // (except for non-allocated sections which require postprocessing).
853 Output_data::layout_complete();
855 this->output_file_size_ = off;
860 // Create a .note section for an executable or shared library. This
861 // records the version of gold used to create the binary.
864 Layout::create_gold_note()
866 if (parameters->output_is_object())
869 // Authorities all agree that the values in a .note field should
870 // be aligned on 4-byte boundaries for 32-bit binaries. However,
871 // they differ on what the alignment is for 64-bit binaries.
872 // The GABI says unambiguously they take 8-byte alignment:
873 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
874 // Other documentation says alignment should always be 4 bytes:
875 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
876 // GNU ld and GNU readelf both support the latter (at least as of
877 // version 2.16.91), and glibc always generates the latter for
878 // .note.ABI-tag (as of version 1.6), so that's the one we go with
880 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
881 const int size = parameters->get_size();
886 // The contents of the .note section.
887 const char* name = "GNU";
888 std::string desc(std::string("gold ") + gold::get_version_string());
889 size_t namesz = strlen(name) + 1;
890 size_t aligned_namesz = align_address(namesz, size / 8);
891 size_t descsz = desc.length() + 1;
892 size_t aligned_descsz = align_address(descsz, size / 8);
893 const int note_type = 4;
895 size_t notesz = 3 * (size / 8) + aligned_namesz + aligned_descsz;
897 unsigned char buffer[128];
898 gold_assert(sizeof buffer >= notesz);
899 memset(buffer, 0, notesz);
901 bool is_big_endian = parameters->is_big_endian();
907 elfcpp::Swap<32, false>::writeval(buffer, namesz);
908 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
909 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
913 elfcpp::Swap<32, true>::writeval(buffer, namesz);
914 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
915 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
922 elfcpp::Swap<64, false>::writeval(buffer, namesz);
923 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
924 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
928 elfcpp::Swap<64, true>::writeval(buffer, namesz);
929 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
930 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
936 memcpy(buffer + 3 * (size / 8), name, namesz);
937 memcpy(buffer + 3 * (size / 8) + aligned_namesz, desc.data(), descsz);
939 const char* note_name = this->namepool_.add(".note", false, NULL);
940 Output_section* os = this->make_output_section(note_name,
943 Output_section_data* posd = new Output_data_const(buffer, notesz,
945 os->add_output_section_data(posd);
948 // Record whether the stack should be executable. This can be set
949 // from the command line using the -z execstack or -z noexecstack
950 // options. Otherwise, if any input file has a .note.GNU-stack
951 // section with the SHF_EXECINSTR flag set, the stack should be
952 // executable. Otherwise, if at least one input file a
953 // .note.GNU-stack section, and some input file has no .note.GNU-stack
954 // section, we use the target default for whether the stack should be
955 // executable. Otherwise, we don't generate a stack note. When
956 // generating a object file, we create a .note.GNU-stack section with
957 // the appropriate marking. When generating an executable or shared
958 // library, we create a PT_GNU_STACK segment.
961 Layout::create_executable_stack_info(const Target* target)
963 bool is_stack_executable;
964 if (this->options_.is_execstack_set())
965 is_stack_executable = this->options_.is_stack_executable();
966 else if (!this->input_with_gnu_stack_note_)
970 if (this->input_requires_executable_stack_)
971 is_stack_executable = true;
972 else if (this->input_without_gnu_stack_note_)
973 is_stack_executable = target->is_default_stack_executable();
975 is_stack_executable = false;
978 if (parameters->output_is_object())
980 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
981 elfcpp::Elf_Xword flags = 0;
982 if (is_stack_executable)
983 flags |= elfcpp::SHF_EXECINSTR;
984 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
988 int flags = elfcpp::PF_R | elfcpp::PF_W;
989 if (is_stack_executable)
990 flags |= elfcpp::PF_X;
991 Output_segment* oseg = new Output_segment(elfcpp::PT_GNU_STACK, flags);
992 this->segment_list_.push_back(oseg);
996 // Return whether SEG1 should be before SEG2 in the output file. This
997 // is based entirely on the segment type and flags. When this is
998 // called the segment addresses has normally not yet been set.
1001 Layout::segment_precedes(const Output_segment* seg1,
1002 const Output_segment* seg2)
1004 elfcpp::Elf_Word type1 = seg1->type();
1005 elfcpp::Elf_Word type2 = seg2->type();
1007 // The single PT_PHDR segment is required to precede any loadable
1008 // segment. We simply make it always first.
1009 if (type1 == elfcpp::PT_PHDR)
1011 gold_assert(type2 != elfcpp::PT_PHDR);
1014 if (type2 == elfcpp::PT_PHDR)
1017 // The single PT_INTERP segment is required to precede any loadable
1018 // segment. We simply make it always second.
1019 if (type1 == elfcpp::PT_INTERP)
1021 gold_assert(type2 != elfcpp::PT_INTERP);
1024 if (type2 == elfcpp::PT_INTERP)
1027 // We then put PT_LOAD segments before any other segments.
1028 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1030 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1033 // We put the PT_TLS segment last, because that is where the dynamic
1034 // linker expects to find it (this is just for efficiency; other
1035 // positions would also work correctly).
1036 if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
1038 if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
1041 const elfcpp::Elf_Word flags1 = seg1->flags();
1042 const elfcpp::Elf_Word flags2 = seg2->flags();
1044 // The order of non-PT_LOAD segments is unimportant. We simply sort
1045 // by the numeric segment type and flags values. There should not
1046 // be more than one segment with the same type and flags.
1047 if (type1 != elfcpp::PT_LOAD)
1050 return type1 < type2;
1051 gold_assert(flags1 != flags2);
1052 return flags1 < flags2;
1055 // If the addresses are set already, sort by load address.
1056 if (seg1->are_addresses_set())
1058 if (!seg2->are_addresses_set())
1061 unsigned int section_count1 = seg1->output_section_count();
1062 unsigned int section_count2 = seg2->output_section_count();
1063 if (section_count1 == 0 && section_count2 > 0)
1065 if (section_count1 > 0 && section_count2 == 0)
1068 uint64_t paddr1 = seg1->first_section_load_address();
1069 uint64_t paddr2 = seg2->first_section_load_address();
1070 if (paddr1 != paddr2)
1071 return paddr1 < paddr2;
1073 else if (seg2->are_addresses_set())
1076 // We sort PT_LOAD segments based on the flags. Readonly segments
1077 // come before writable segments. Then executable segments come
1078 // before non-executable segments. Then the unlikely case of a
1079 // non-readable segment comes before the normal case of a readable
1080 // segment. If there are multiple segments with the same type and
1081 // flags, we require that the address be set, and we sort by
1082 // virtual address and then physical address.
1083 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1084 return (flags1 & elfcpp::PF_W) == 0;
1085 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1086 return (flags1 & elfcpp::PF_X) != 0;
1087 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1088 return (flags1 & elfcpp::PF_R) == 0;
1090 // We shouldn't get here--we shouldn't create segments which we
1091 // can't distinguish.
1095 // Set the file offsets of all the segments, and all the sections they
1096 // contain. They have all been created. LOAD_SEG must be be laid out
1097 // first. Return the offset of the data to follow.
1100 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1101 unsigned int *pshndx)
1103 // Sort them into the final order.
1104 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1105 Layout::Compare_segments());
1107 // Find the PT_LOAD segments, and set their addresses and offsets
1108 // and their section's addresses and offsets.
1110 if (this->options_.user_set_text_segment_address())
1111 addr = options_.text_segment_address();
1112 else if (parameters->output_is_shared())
1115 addr = target->default_text_segment_address();
1118 // If LOAD_SEG is NULL, then the file header and segment headers
1119 // will not be loadable. But they still need to be at offset 0 in
1120 // the file. Set their offsets now.
1121 if (load_seg == NULL)
1123 for (Data_list::iterator p = this->special_output_list_.begin();
1124 p != this->special_output_list_.end();
1127 off = align_address(off, (*p)->addralign());
1128 (*p)->set_address_and_file_offset(0, off);
1129 off += (*p)->data_size();
1133 bool was_readonly = false;
1134 for (Segment_list::iterator p = this->segment_list_.begin();
1135 p != this->segment_list_.end();
1138 if ((*p)->type() == elfcpp::PT_LOAD)
1140 if (load_seg != NULL && load_seg != *p)
1144 uint64_t orig_addr = addr;
1145 uint64_t orig_off = off;
1147 uint64_t aligned_addr = 0;
1148 uint64_t abi_pagesize = target->abi_pagesize();
1150 // FIXME: This should depend on the -n and -N options.
1151 (*p)->set_minimum_p_align(target->common_pagesize());
1153 bool are_addresses_set = (*p)->are_addresses_set();
1154 if (are_addresses_set)
1156 // When it comes to setting file offsets, we care about
1157 // the physical address.
1158 addr = (*p)->paddr();
1160 // Adjust the file offset to the same address modulo the
1162 uint64_t unsigned_off = off;
1163 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1164 | (addr & (abi_pagesize - 1)));
1165 if (aligned_off < unsigned_off)
1166 aligned_off += abi_pagesize;
1171 // If the last segment was readonly, and this one is
1172 // not, then skip the address forward one page,
1173 // maintaining the same position within the page. This
1174 // lets us store both segments overlapping on a single
1175 // page in the file, but the loader will put them on
1176 // different pages in memory.
1178 addr = align_address(addr, (*p)->maximum_alignment());
1179 aligned_addr = addr;
1181 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1183 if ((addr & (abi_pagesize - 1)) != 0)
1184 addr = addr + abi_pagesize;
1187 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1190 unsigned int shndx_hold = *pshndx;
1191 uint64_t new_addr = (*p)->set_section_addresses(false, addr, &off,
1194 // Now that we know the size of this segment, we may be able
1195 // to save a page in memory, at the cost of wasting some
1196 // file space, by instead aligning to the start of a new
1197 // page. Here we use the real machine page size rather than
1198 // the ABI mandated page size.
1200 if (!are_addresses_set && aligned_addr != addr)
1202 uint64_t common_pagesize = target->common_pagesize();
1203 uint64_t first_off = (common_pagesize
1205 & (common_pagesize - 1)));
1206 uint64_t last_off = new_addr & (common_pagesize - 1);
1209 && ((aligned_addr & ~ (common_pagesize - 1))
1210 != (new_addr & ~ (common_pagesize - 1)))
1211 && first_off + last_off <= common_pagesize)
1213 *pshndx = shndx_hold;
1214 addr = align_address(aligned_addr, common_pagesize);
1215 addr = align_address(addr, (*p)->maximum_alignment());
1216 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1217 new_addr = (*p)->set_section_addresses(true, addr, &off,
1224 if (((*p)->flags() & elfcpp::PF_W) == 0)
1225 was_readonly = true;
1229 // Handle the non-PT_LOAD segments, setting their offsets from their
1230 // section's offsets.
1231 for (Segment_list::iterator p = this->segment_list_.begin();
1232 p != this->segment_list_.end();
1235 if ((*p)->type() != elfcpp::PT_LOAD)
1239 // Set the TLS offsets for each section in the PT_TLS segment.
1240 if (this->tls_segment_ != NULL)
1241 this->tls_segment_->set_tls_offsets();
1246 // Set the file offset of all the sections not associated with a
1250 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1252 for (Section_list::iterator p = this->unattached_section_list_.begin();
1253 p != this->unattached_section_list_.end();
1256 // The symtab section is handled in create_symtab_sections.
1257 if (*p == this->symtab_section_)
1260 // If we've already set the data size, don't set it again.
1261 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1264 if (pass == BEFORE_INPUT_SECTIONS_PASS
1265 && (*p)->requires_postprocessing())
1267 (*p)->create_postprocessing_buffer();
1268 this->any_postprocessing_sections_ = true;
1271 if (pass == BEFORE_INPUT_SECTIONS_PASS
1272 && (*p)->after_input_sections())
1274 else if (pass == POSTPROCESSING_SECTIONS_PASS
1275 && (!(*p)->after_input_sections()
1276 || (*p)->type() == elfcpp::SHT_STRTAB))
1278 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1279 && (!(*p)->after_input_sections()
1280 || (*p)->type() != elfcpp::SHT_STRTAB))
1283 off = align_address(off, (*p)->addralign());
1284 (*p)->set_file_offset(off);
1285 (*p)->finalize_data_size();
1286 off += (*p)->data_size();
1288 // At this point the name must be set.
1289 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1290 this->namepool_.add((*p)->name(), false, NULL);
1295 // Set the section indexes of all the sections not associated with a
1299 Layout::set_section_indexes(unsigned int shndx)
1301 for (Section_list::iterator p = this->unattached_section_list_.begin();
1302 p != this->unattached_section_list_.end();
1305 (*p)->set_out_shndx(shndx);
1311 // Set the section addresses according to the linker script. This is
1312 // only called when we see a SECTIONS clause. This returns the
1313 // program segment which should hold the file header and segment
1314 // headers, if any. It will return NULL if they should not be in a
1318 Layout::set_section_addresses_from_script(Symbol_table* symtab)
1320 Script_sections* ss = this->script_options_->script_sections();
1321 gold_assert(ss->saw_sections_clause());
1323 // Place each orphaned output section in the script.
1324 for (Section_list::iterator p = this->section_list_.begin();
1325 p != this->section_list_.end();
1328 if (!(*p)->found_in_sections_clause())
1329 ss->place_orphan(*p);
1332 return this->script_options_->set_section_addresses(symtab, this);
1335 // Count the local symbols in the regular symbol table and the dynamic
1336 // symbol table, and build the respective string pools.
1339 Layout::count_local_symbols(const Task* task,
1340 const Input_objects* input_objects)
1342 // First, figure out an upper bound on the number of symbols we'll
1343 // be inserting into each pool. This helps us create the pools with
1344 // the right size, to avoid unnecessary hashtable resizing.
1345 unsigned int symbol_count = 0;
1346 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1347 p != input_objects->relobj_end();
1349 symbol_count += (*p)->local_symbol_count();
1351 // Go from "upper bound" to "estimate." We overcount for two
1352 // reasons: we double-count symbols that occur in more than one
1353 // object file, and we count symbols that are dropped from the
1354 // output. Add it all together and assume we overcount by 100%.
1357 // We assume all symbols will go into both the sympool and dynpool.
1358 this->sympool_.reserve(symbol_count);
1359 this->dynpool_.reserve(symbol_count);
1361 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1362 p != input_objects->relobj_end();
1365 Task_lock_obj<Object> tlo(task, *p);
1366 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
1370 // Create the symbol table sections. Here we also set the final
1371 // values of the symbols. At this point all the loadable sections are
1375 Layout::create_symtab_sections(const Input_objects* input_objects,
1376 Symbol_table* symtab,
1381 if (parameters->get_size() == 32)
1383 symsize = elfcpp::Elf_sizes<32>::sym_size;
1386 else if (parameters->get_size() == 64)
1388 symsize = elfcpp::Elf_sizes<64>::sym_size;
1395 off = align_address(off, align);
1396 off_t startoff = off;
1398 // Save space for the dummy symbol at the start of the section. We
1399 // never bother to write this out--it will just be left as zero.
1401 unsigned int local_symbol_index = 1;
1403 // Add STT_SECTION symbols for each Output section which needs one.
1404 for (Section_list::iterator p = this->section_list_.begin();
1405 p != this->section_list_.end();
1408 if (!(*p)->needs_symtab_index())
1409 (*p)->set_symtab_index(-1U);
1412 (*p)->set_symtab_index(local_symbol_index);
1413 ++local_symbol_index;
1418 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1419 p != input_objects->relobj_end();
1422 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
1424 off += (index - local_symbol_index) * symsize;
1425 local_symbol_index = index;
1428 unsigned int local_symcount = local_symbol_index;
1429 gold_assert(local_symcount * symsize == off - startoff);
1432 size_t dyn_global_index;
1434 if (this->dynsym_section_ == NULL)
1437 dyn_global_index = 0;
1442 dyn_global_index = this->dynsym_section_->info();
1443 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
1444 dynoff = this->dynsym_section_->offset() + locsize;
1445 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
1446 gold_assert(static_cast<off_t>(dyncount * symsize)
1447 == this->dynsym_section_->data_size() - locsize);
1450 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
1451 &this->sympool_, &local_symcount);
1453 if (!parameters->strip_all())
1455 this->sympool_.set_string_offsets();
1457 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
1458 Output_section* osymtab = this->make_output_section(symtab_name,
1461 this->symtab_section_ = osymtab;
1463 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
1465 osymtab->add_output_section_data(pos);
1467 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
1468 Output_section* ostrtab = this->make_output_section(strtab_name,
1472 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
1473 ostrtab->add_output_section_data(pstr);
1475 osymtab->set_file_offset(startoff);
1476 osymtab->finalize_data_size();
1477 osymtab->set_link_section(ostrtab);
1478 osymtab->set_info(local_symcount);
1479 osymtab->set_entsize(symsize);
1485 // Create the .shstrtab section, which holds the names of the
1486 // sections. At the time this is called, we have created all the
1487 // output sections except .shstrtab itself.
1490 Layout::create_shstrtab()
1492 // FIXME: We don't need to create a .shstrtab section if we are
1493 // stripping everything.
1495 const char* name = this->namepool_.add(".shstrtab", false, NULL);
1497 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
1499 // We can't write out this section until we've set all the section
1500 // names, and we don't set the names of compressed output sections
1501 // until relocations are complete.
1502 os->set_after_input_sections();
1504 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
1505 os->add_output_section_data(posd);
1510 // Create the section headers. SIZE is 32 or 64. OFF is the file
1514 Layout::create_shdrs(off_t* poff)
1516 Output_section_headers* oshdrs;
1517 oshdrs = new Output_section_headers(this,
1518 &this->segment_list_,
1519 &this->unattached_section_list_,
1521 off_t off = align_address(*poff, oshdrs->addralign());
1522 oshdrs->set_address_and_file_offset(0, off);
1523 off += oshdrs->data_size();
1525 this->section_headers_ = oshdrs;
1528 // Create the dynamic symbol table.
1531 Layout::create_dynamic_symtab(const Input_objects* input_objects,
1532 Symbol_table* symtab,
1533 Output_section **pdynstr,
1534 unsigned int* plocal_dynamic_count,
1535 std::vector<Symbol*>* pdynamic_symbols,
1536 Versions* pversions)
1538 // Count all the symbols in the dynamic symbol table, and set the
1539 // dynamic symbol indexes.
1541 // Skip symbol 0, which is always all zeroes.
1542 unsigned int index = 1;
1544 // Add STT_SECTION symbols for each Output section which needs one.
1545 for (Section_list::iterator p = this->section_list_.begin();
1546 p != this->section_list_.end();
1549 if (!(*p)->needs_dynsym_index())
1550 (*p)->set_dynsym_index(-1U);
1553 (*p)->set_dynsym_index(index);
1558 // Count the local symbols that need to go in the dynamic symbol table,
1559 // and set the dynamic symbol indexes.
1560 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1561 p != input_objects->relobj_end();
1564 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
1568 unsigned int local_symcount = index;
1569 *plocal_dynamic_count = local_symcount;
1571 // FIXME: We have to tell set_dynsym_indexes whether the
1572 // -E/--export-dynamic option was used.
1573 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
1574 &this->dynpool_, pversions);
1578 const int size = parameters->get_size();
1581 symsize = elfcpp::Elf_sizes<32>::sym_size;
1584 else if (size == 64)
1586 symsize = elfcpp::Elf_sizes<64>::sym_size;
1592 // Create the dynamic symbol table section.
1594 const char* dynsym_name = this->namepool_.add(".dynsym", false, NULL);
1595 Output_section* dynsym = this->make_output_section(dynsym_name,
1599 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
1601 dynsym->add_output_section_data(odata);
1603 dynsym->set_info(local_symcount);
1604 dynsym->set_entsize(symsize);
1605 dynsym->set_addralign(align);
1607 this->dynsym_section_ = dynsym;
1609 Output_data_dynamic* const odyn = this->dynamic_data_;
1610 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
1611 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
1613 // Create the dynamic string table section.
1615 const char* dynstr_name = this->namepool_.add(".dynstr", false, NULL);
1616 Output_section* dynstr = this->make_output_section(dynstr_name,
1620 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
1621 dynstr->add_output_section_data(strdata);
1623 dynsym->set_link_section(dynstr);
1624 this->dynamic_section_->set_link_section(dynstr);
1626 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
1627 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
1631 // Create the hash tables.
1633 // FIXME: We need an option to create a GNU hash table.
1635 unsigned char* phash;
1636 unsigned int hashlen;
1637 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
1640 const char* hash_name = this->namepool_.add(".hash", false, NULL);
1641 Output_section* hashsec = this->make_output_section(hash_name,
1645 Output_section_data* hashdata = new Output_data_const_buffer(phash,
1648 hashsec->add_output_section_data(hashdata);
1650 hashsec->set_link_section(dynsym);
1651 hashsec->set_entsize(4);
1653 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
1656 // Assign offsets to each local portion of the dynamic symbol table.
1659 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
1661 Output_section* dynsym = this->dynsym_section_;
1662 gold_assert(dynsym != NULL);
1664 off_t off = dynsym->offset();
1666 // Skip the dummy symbol at the start of the section.
1667 off += dynsym->entsize();
1669 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1670 p != input_objects->relobj_end();
1673 unsigned int count = (*p)->set_local_dynsym_offset(off);
1674 off += count * dynsym->entsize();
1678 // Create the version sections.
1681 Layout::create_version_sections(const Versions* versions,
1682 const Symbol_table* symtab,
1683 unsigned int local_symcount,
1684 const std::vector<Symbol*>& dynamic_symbols,
1685 const Output_section* dynstr)
1687 if (!versions->any_defs() && !versions->any_needs())
1690 if (parameters->get_size() == 32)
1692 if (parameters->is_big_endian())
1694 #ifdef HAVE_TARGET_32_BIG
1695 this->sized_create_version_sections
1696 SELECT_SIZE_ENDIAN_NAME(32, true)(
1697 versions, symtab, local_symcount, dynamic_symbols, dynstr
1698 SELECT_SIZE_ENDIAN(32, true));
1705 #ifdef HAVE_TARGET_32_LITTLE
1706 this->sized_create_version_sections
1707 SELECT_SIZE_ENDIAN_NAME(32, false)(
1708 versions, symtab, local_symcount, dynamic_symbols, dynstr
1709 SELECT_SIZE_ENDIAN(32, false));
1715 else if (parameters->get_size() == 64)
1717 if (parameters->is_big_endian())
1719 #ifdef HAVE_TARGET_64_BIG
1720 this->sized_create_version_sections
1721 SELECT_SIZE_ENDIAN_NAME(64, true)(
1722 versions, symtab, local_symcount, dynamic_symbols, dynstr
1723 SELECT_SIZE_ENDIAN(64, true));
1730 #ifdef HAVE_TARGET_64_LITTLE
1731 this->sized_create_version_sections
1732 SELECT_SIZE_ENDIAN_NAME(64, false)(
1733 versions, symtab, local_symcount, dynamic_symbols, dynstr
1734 SELECT_SIZE_ENDIAN(64, false));
1744 // Create the version sections, sized version.
1746 template<int size, bool big_endian>
1748 Layout::sized_create_version_sections(
1749 const Versions* versions,
1750 const Symbol_table* symtab,
1751 unsigned int local_symcount,
1752 const std::vector<Symbol*>& dynamic_symbols,
1753 const Output_section* dynstr
1756 const char* vname = this->namepool_.add(".gnu.version", false, NULL);
1757 Output_section* vsec = this->make_output_section(vname,
1758 elfcpp::SHT_GNU_versym,
1761 unsigned char* vbuf;
1763 versions->symbol_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1764 symtab, &this->dynpool_, local_symcount, dynamic_symbols, &vbuf, &vsize
1765 SELECT_SIZE_ENDIAN(size, big_endian));
1767 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2);
1769 vsec->add_output_section_data(vdata);
1770 vsec->set_entsize(2);
1771 vsec->set_link_section(this->dynsym_section_);
1773 Output_data_dynamic* const odyn = this->dynamic_data_;
1774 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
1776 if (versions->any_defs())
1778 const char* vdname = this->namepool_.add(".gnu.version_d", false, NULL);
1779 Output_section *vdsec;
1780 vdsec = this->make_output_section(vdname, elfcpp::SHT_GNU_verdef,
1783 unsigned char* vdbuf;
1784 unsigned int vdsize;
1785 unsigned int vdentries;
1786 versions->def_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1787 &this->dynpool_, &vdbuf, &vdsize, &vdentries
1788 SELECT_SIZE_ENDIAN(size, big_endian));
1790 Output_section_data* vddata = new Output_data_const_buffer(vdbuf,
1794 vdsec->add_output_section_data(vddata);
1795 vdsec->set_link_section(dynstr);
1796 vdsec->set_info(vdentries);
1798 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
1799 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
1802 if (versions->any_needs())
1804 const char* vnname = this->namepool_.add(".gnu.version_r", false, NULL);
1805 Output_section* vnsec;
1806 vnsec = this->make_output_section(vnname, elfcpp::SHT_GNU_verneed,
1809 unsigned char* vnbuf;
1810 unsigned int vnsize;
1811 unsigned int vnentries;
1812 versions->need_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)
1813 (&this->dynpool_, &vnbuf, &vnsize, &vnentries
1814 SELECT_SIZE_ENDIAN(size, big_endian));
1816 Output_section_data* vndata = new Output_data_const_buffer(vnbuf,
1820 vnsec->add_output_section_data(vndata);
1821 vnsec->set_link_section(dynstr);
1822 vnsec->set_info(vnentries);
1824 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
1825 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
1829 // Create the .interp section and PT_INTERP segment.
1832 Layout::create_interp(const Target* target)
1834 const char* interp = this->options_.dynamic_linker();
1837 interp = target->dynamic_linker();
1838 gold_assert(interp != NULL);
1841 size_t len = strlen(interp) + 1;
1843 Output_section_data* odata = new Output_data_const(interp, len, 1);
1845 const char* interp_name = this->namepool_.add(".interp", false, NULL);
1846 Output_section* osec = this->make_output_section(interp_name,
1847 elfcpp::SHT_PROGBITS,
1849 osec->add_output_section_data(odata);
1851 Output_segment* oseg = new Output_segment(elfcpp::PT_INTERP, elfcpp::PF_R);
1852 this->segment_list_.push_back(oseg);
1853 oseg->add_initial_output_section(osec, elfcpp::PF_R);
1856 // Finish the .dynamic section and PT_DYNAMIC segment.
1859 Layout::finish_dynamic_section(const Input_objects* input_objects,
1860 const Symbol_table* symtab)
1862 Output_segment* oseg = new Output_segment(elfcpp::PT_DYNAMIC,
1863 elfcpp::PF_R | elfcpp::PF_W);
1864 this->segment_list_.push_back(oseg);
1865 oseg->add_initial_output_section(this->dynamic_section_,
1866 elfcpp::PF_R | elfcpp::PF_W);
1868 Output_data_dynamic* const odyn = this->dynamic_data_;
1870 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
1871 p != input_objects->dynobj_end();
1874 // FIXME: Handle --as-needed.
1875 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
1878 if (parameters->output_is_shared())
1880 const char* soname = this->options_.soname();
1882 odyn->add_string(elfcpp::DT_SONAME, soname);
1885 // FIXME: Support --init and --fini.
1886 Symbol* sym = symtab->lookup("_init");
1887 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1888 odyn->add_symbol(elfcpp::DT_INIT, sym);
1890 sym = symtab->lookup("_fini");
1891 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1892 odyn->add_symbol(elfcpp::DT_FINI, sym);
1894 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
1896 // Add a DT_RPATH entry if needed.
1897 const General_options::Dir_list& rpath(this->options_.rpath());
1900 std::string rpath_val;
1901 for (General_options::Dir_list::const_iterator p = rpath.begin();
1905 if (rpath_val.empty())
1906 rpath_val = p->name();
1909 // Eliminate duplicates.
1910 General_options::Dir_list::const_iterator q;
1911 for (q = rpath.begin(); q != p; ++q)
1912 if (q->name() == p->name())
1917 rpath_val += p->name();
1922 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
1925 // Look for text segments that have dynamic relocations.
1926 bool have_textrel = false;
1927 for (Segment_list::const_iterator p = this->segment_list_.begin();
1928 p != this->segment_list_.end();
1931 if (((*p)->flags() & elfcpp::PF_W) == 0
1932 && (*p)->dynamic_reloc_count() > 0)
1934 have_textrel = true;
1939 // Add a DT_FLAGS entry. We add it even if no flags are set so that
1940 // post-link tools can easily modify these flags if desired.
1941 unsigned int flags = 0;
1944 // Add a DT_TEXTREL for compatibility with older loaders.
1945 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
1946 flags |= elfcpp::DF_TEXTREL;
1948 if (parameters->output_is_shared() && this->has_static_tls())
1949 flags |= elfcpp::DF_STATIC_TLS;
1950 odyn->add_constant(elfcpp::DT_FLAGS, flags);
1953 // The mapping of .gnu.linkonce section names to real section names.
1955 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
1956 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
1958 MAPPING_INIT("d.rel.ro", ".data.rel.ro"), // Must be before "d".
1959 MAPPING_INIT("t", ".text"),
1960 MAPPING_INIT("r", ".rodata"),
1961 MAPPING_INIT("d", ".data"),
1962 MAPPING_INIT("b", ".bss"),
1963 MAPPING_INIT("s", ".sdata"),
1964 MAPPING_INIT("sb", ".sbss"),
1965 MAPPING_INIT("s2", ".sdata2"),
1966 MAPPING_INIT("sb2", ".sbss2"),
1967 MAPPING_INIT("wi", ".debug_info"),
1968 MAPPING_INIT("td", ".tdata"),
1969 MAPPING_INIT("tb", ".tbss"),
1970 MAPPING_INIT("lr", ".lrodata"),
1971 MAPPING_INIT("l", ".ldata"),
1972 MAPPING_INIT("lb", ".lbss"),
1976 const int Layout::linkonce_mapping_count =
1977 sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
1979 // Return the name of the output section to use for a .gnu.linkonce
1980 // section. This is based on the default ELF linker script of the old
1981 // GNU linker. For example, we map a name like ".gnu.linkonce.t.foo"
1982 // to ".text". Set *PLEN to the length of the name. *PLEN is
1983 // initialized to the length of NAME.
1986 Layout::linkonce_output_name(const char* name, size_t *plen)
1988 const char* s = name + sizeof(".gnu.linkonce") - 1;
1992 const Linkonce_mapping* plm = linkonce_mapping;
1993 for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
1995 if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2004 // Choose the output section name to use given an input section name.
2005 // Set *PLEN to the length of the name. *PLEN is initialized to the
2009 Layout::output_section_name(const char* name, size_t* plen)
2011 if (Layout::is_linkonce(name))
2013 // .gnu.linkonce sections are laid out as though they were named
2014 // for the sections are placed into.
2015 return Layout::linkonce_output_name(name, plen);
2018 // gcc 4.3 generates the following sorts of section names when it
2019 // needs a section name specific to a function:
2025 // .data.rel.local.FN
2027 // .data.rel.ro.local.FN
2034 // The GNU linker maps all of those to the part before the .FN,
2035 // except that .data.rel.local.FN is mapped to .data, and
2036 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
2037 // beginning with .data.rel.ro.local are grouped together.
2039 // For an anonymous namespace, the string FN can contain a '.'.
2041 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2042 // GNU linker maps to .rodata.
2044 // The .data.rel.ro sections enable a security feature triggered by
2045 // the -z relro option. Section which need to be relocated at
2046 // program startup time but which may be readonly after startup are
2047 // grouped into .data.rel.ro. They are then put into a PT_GNU_RELRO
2048 // segment. The dynamic linker will make that segment writable,
2049 // perform relocations, and then make it read-only. FIXME: We do
2050 // not yet implement this optimization.
2052 // It is hard to handle this in a principled way.
2054 // These are the rules we follow:
2056 // If the section name has no initial '.', or no dot other than an
2057 // initial '.', we use the name unchanged (i.e., "mysection" and
2058 // ".text" are unchanged).
2060 // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2062 // Otherwise, we drop the second '.' and everything that comes after
2063 // it (i.e., ".text.XXX" becomes ".text").
2065 const char* s = name;
2069 const char* sdot = strchr(s, '.');
2073 const char* const data_rel_ro = ".data.rel.ro";
2074 if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2076 *plen = strlen(data_rel_ro);
2080 *plen = sdot - name;
2084 // Record the signature of a comdat section, and return whether to
2085 // include it in the link. If GROUP is true, this is a regular
2086 // section group. If GROUP is false, this is a group signature
2087 // derived from the name of a linkonce section. We want linkonce
2088 // signatures and group signatures to block each other, but we don't
2089 // want a linkonce signature to block another linkonce signature.
2092 Layout::add_comdat(const char* signature, bool group)
2094 std::string sig(signature);
2095 std::pair<Signatures::iterator, bool> ins(
2096 this->signatures_.insert(std::make_pair(sig, group)));
2100 // This is the first time we've seen this signature.
2104 if (ins.first->second)
2106 // We've already seen a real section group with this signature.
2111 // This is a real section group, and we've already seen a
2112 // linkonce section with this signature. Record that we've seen
2113 // a section group, and don't include this section group.
2114 ins.first->second = true;
2119 // We've already seen a linkonce section and this is a linkonce
2120 // section. These don't block each other--this may be the same
2121 // symbol name with different section types.
2126 // Store the allocated sections into the section list.
2129 Layout::get_allocated_sections(Section_list* section_list) const
2131 for (Section_list::const_iterator p = this->section_list_.begin();
2132 p != this->section_list_.end();
2134 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2135 section_list->push_back(*p);
2138 // Create an output segment.
2141 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2143 Output_segment* oseg = new Output_segment(type, flags);
2144 this->segment_list_.push_back(oseg);
2148 // Write out the Output_sections. Most won't have anything to write,
2149 // since most of the data will come from input sections which are
2150 // handled elsewhere. But some Output_sections do have Output_data.
2153 Layout::write_output_sections(Output_file* of) const
2155 for (Section_list::const_iterator p = this->section_list_.begin();
2156 p != this->section_list_.end();
2159 if (!(*p)->after_input_sections())
2164 // Write out data not associated with a section or the symbol table.
2167 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
2169 if (!parameters->strip_all())
2171 const Output_section* symtab_section = this->symtab_section_;
2172 for (Section_list::const_iterator p = this->section_list_.begin();
2173 p != this->section_list_.end();
2176 if ((*p)->needs_symtab_index())
2178 gold_assert(symtab_section != NULL);
2179 unsigned int index = (*p)->symtab_index();
2180 gold_assert(index > 0 && index != -1U);
2181 off_t off = (symtab_section->offset()
2182 + index * symtab_section->entsize());
2183 symtab->write_section_symbol(*p, of, off);
2188 const Output_section* dynsym_section = this->dynsym_section_;
2189 for (Section_list::const_iterator p = this->section_list_.begin();
2190 p != this->section_list_.end();
2193 if ((*p)->needs_dynsym_index())
2195 gold_assert(dynsym_section != NULL);
2196 unsigned int index = (*p)->dynsym_index();
2197 gold_assert(index > 0 && index != -1U);
2198 off_t off = (dynsym_section->offset()
2199 + index * dynsym_section->entsize());
2200 symtab->write_section_symbol(*p, of, off);
2204 // Write out the Output_data which are not in an Output_section.
2205 for (Data_list::const_iterator p = this->special_output_list_.begin();
2206 p != this->special_output_list_.end();
2211 // Write out the Output_sections which can only be written after the
2212 // input sections are complete.
2215 Layout::write_sections_after_input_sections(Output_file* of)
2217 // Determine the final section offsets, and thus the final output
2218 // file size. Note we finalize the .shstrab last, to allow the
2219 // after_input_section sections to modify their section-names before
2221 if (this->any_postprocessing_sections_)
2223 off_t off = this->output_file_size_;
2224 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
2226 // Now that we've finalized the names, we can finalize the shstrab.
2228 this->set_section_offsets(off,
2229 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2231 if (off > this->output_file_size_)
2234 this->output_file_size_ = off;
2238 for (Section_list::const_iterator p = this->section_list_.begin();
2239 p != this->section_list_.end();
2242 if ((*p)->after_input_sections())
2246 this->section_headers_->write(of);
2249 // Print statistical information to stderr. This is used for --stats.
2252 Layout::print_stats() const
2254 this->namepool_.print_stats("section name pool");
2255 this->sympool_.print_stats("output symbol name pool");
2256 this->dynpool_.print_stats("dynamic name pool");
2258 for (Section_list::const_iterator p = this->section_list_.begin();
2259 p != this->section_list_.end();
2261 (*p)->print_merge_stats();
2264 // Write_sections_task methods.
2266 // We can always run this task.
2269 Write_sections_task::is_runnable()
2274 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
2278 Write_sections_task::locks(Task_locker* tl)
2280 tl->add(this, this->output_sections_blocker_);
2281 tl->add(this, this->final_blocker_);
2284 // Run the task--write out the data.
2287 Write_sections_task::run(Workqueue*)
2289 this->layout_->write_output_sections(this->of_);
2292 // Write_data_task methods.
2294 // We can always run this task.
2297 Write_data_task::is_runnable()
2302 // We need to unlock FINAL_BLOCKER when finished.
2305 Write_data_task::locks(Task_locker* tl)
2307 tl->add(this, this->final_blocker_);
2310 // Run the task--write out the data.
2313 Write_data_task::run(Workqueue*)
2315 this->layout_->write_data(this->symtab_, this->of_);
2318 // Write_symbols_task methods.
2320 // We can always run this task.
2323 Write_symbols_task::is_runnable()
2328 // We need to unlock FINAL_BLOCKER when finished.
2331 Write_symbols_task::locks(Task_locker* tl)
2333 tl->add(this, this->final_blocker_);
2336 // Run the task--write out the symbols.
2339 Write_symbols_task::run(Workqueue*)
2341 this->symtab_->write_globals(this->input_objects_, this->sympool_,
2342 this->dynpool_, this->of_);
2345 // Write_after_input_sections_task methods.
2347 // We can only run this task after the input sections have completed.
2350 Write_after_input_sections_task::is_runnable()
2352 if (this->input_sections_blocker_->is_blocked())
2353 return this->input_sections_blocker_;
2357 // We need to unlock FINAL_BLOCKER when finished.
2360 Write_after_input_sections_task::locks(Task_locker* tl)
2362 tl->add(this, this->final_blocker_);
2368 Write_after_input_sections_task::run(Workqueue*)
2370 this->layout_->write_sections_after_input_sections(this->of_);
2373 // Close_task_runner methods.
2375 // Run the task--close the file.
2378 Close_task_runner::run(Workqueue*, const Task*)
2383 // Instantiate the templates we need. We could use the configure
2384 // script to restrict this to only the ones for implemented targets.
2386 #ifdef HAVE_TARGET_32_LITTLE
2389 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
2391 const elfcpp::Shdr<32, false>& shdr,
2392 unsigned int, unsigned int, off_t*);
2395 #ifdef HAVE_TARGET_32_BIG
2398 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
2400 const elfcpp::Shdr<32, true>& shdr,
2401 unsigned int, unsigned int, off_t*);
2404 #ifdef HAVE_TARGET_64_LITTLE
2407 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
2409 const elfcpp::Shdr<64, false>& shdr,
2410 unsigned int, unsigned int, off_t*);
2413 #ifdef HAVE_TARGET_64_BIG
2416 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
2418 const elfcpp::Shdr<64, true>& shdr,
2419 unsigned int, unsigned int, off_t*);
2422 #ifdef HAVE_TARGET_32_LITTLE
2425 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
2426 const unsigned char* symbols,
2428 const unsigned char* symbol_names,
2429 off_t symbol_names_size,
2431 const elfcpp::Shdr<32, false>& shdr,
2432 unsigned int reloc_shndx,
2433 unsigned int reloc_type,
2437 #ifdef HAVE_TARGET_32_BIG
2440 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
2441 const unsigned char* symbols,
2443 const unsigned char* symbol_names,
2444 off_t symbol_names_size,
2446 const elfcpp::Shdr<32, true>& shdr,
2447 unsigned int reloc_shndx,
2448 unsigned int reloc_type,
2452 #ifdef HAVE_TARGET_64_LITTLE
2455 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
2456 const unsigned char* symbols,
2458 const unsigned char* symbol_names,
2459 off_t symbol_names_size,
2461 const elfcpp::Shdr<64, false>& shdr,
2462 unsigned int reloc_shndx,
2463 unsigned int reloc_type,
2467 #ifdef HAVE_TARGET_64_BIG
2470 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
2471 const unsigned char* symbols,
2473 const unsigned char* symbol_names,
2474 off_t symbol_names_size,
2476 const elfcpp::Shdr<64, true>& shdr,
2477 unsigned int reloc_shndx,
2478 unsigned int reloc_type,
2482 } // End namespace gold.