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 if (!this->script_options_->saw_phdrs_clause())
402 Output_segment* hdr_oseg;
403 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
405 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
408 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
413 gold_assert(this->eh_frame_section_ == os);
415 if (this->eh_frame_data_->add_ehframe_input_section(object,
426 // We couldn't handle this .eh_frame section for some reason.
427 // Add it as a normal section.
428 bool saw_sections_clause = this->script_options_->saw_sections_clause();
429 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
430 saw_sections_clause);
436 // Add POSD to an output section using NAME, TYPE, and FLAGS.
439 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
440 elfcpp::Elf_Xword flags,
441 Output_section_data* posd)
443 Output_section* os = this->choose_output_section(NULL, name, type, flags,
446 os->add_output_section_data(posd);
449 // Map section flags to segment flags.
452 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
454 elfcpp::Elf_Word ret = elfcpp::PF_R;
455 if ((flags & elfcpp::SHF_WRITE) != 0)
457 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
462 // Sometimes we compress sections. This is typically done for
463 // sections that are not part of normal program execution (such as
464 // .debug_* sections), and where the readers of these sections know
465 // how to deal with compressed sections. (To make it easier for them,
466 // we will rename the ouput section in such cases from .foo to
467 // .foo.zlib.nnnn, where nnnn is the uncompressed size.) This routine
468 // doesn't say for certain whether we'll compress -- it depends on
469 // commandline options as well -- just whether this section is a
470 // candidate for compression.
473 is_compressible_debug_section(const char* secname)
475 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
478 // Make a new Output_section, and attach it to segments as
482 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
483 elfcpp::Elf_Xword flags)
486 if ((flags & elfcpp::SHF_ALLOC) == 0
487 && this->options_.compress_debug_sections()
488 && is_compressible_debug_section(name))
489 os = new Output_compressed_section(&this->options_, name, type, flags);
491 os = new Output_section(name, type, flags);
493 this->section_list_.push_back(os);
495 if ((flags & elfcpp::SHF_ALLOC) == 0)
496 this->unattached_section_list_.push_back(os);
499 // If we have a SECTIONS clause, we can't handle the attachment
500 // to segments until after we've seen all the sections.
501 if (this->script_options_->saw_sections_clause())
504 gold_assert(!this->script_options_->saw_phdrs_clause());
506 // This output section goes into a PT_LOAD segment.
508 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
510 // The only thing we really care about for PT_LOAD segments is
511 // whether or not they are writable, so that is how we search
512 // for them. People who need segments sorted on some other
513 // basis will have to wait until we implement a mechanism for
514 // them to describe the segments they want.
516 Segment_list::const_iterator p;
517 for (p = this->segment_list_.begin();
518 p != this->segment_list_.end();
521 if ((*p)->type() == elfcpp::PT_LOAD
522 && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
524 (*p)->add_output_section(os, seg_flags);
529 if (p == this->segment_list_.end())
531 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
533 oseg->add_output_section(os, seg_flags);
536 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
538 if (type == elfcpp::SHT_NOTE)
540 // See if we already have an equivalent PT_NOTE segment.
541 for (p = this->segment_list_.begin();
542 p != segment_list_.end();
545 if ((*p)->type() == elfcpp::PT_NOTE
546 && (((*p)->flags() & elfcpp::PF_W)
547 == (seg_flags & elfcpp::PF_W)))
549 (*p)->add_output_section(os, seg_flags);
554 if (p == this->segment_list_.end())
556 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
558 oseg->add_output_section(os, seg_flags);
562 // If we see a loadable SHF_TLS section, we create a PT_TLS
563 // segment. There can only be one such segment.
564 if ((flags & elfcpp::SHF_TLS) != 0)
566 if (this->tls_segment_ == NULL)
567 this->tls_segment_ = this->make_output_segment(elfcpp::PT_TLS,
569 this->tls_segment_->add_output_section(os, seg_flags);
576 // Return the number of segments we expect to see.
579 Layout::expected_segment_count() const
581 size_t ret = this->segment_list_.size();
583 // If we didn't see a SECTIONS clause in a linker script, we should
584 // already have the complete list of segments. Otherwise we ask the
585 // SECTIONS clause how many segments it expects, and add in the ones
586 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
588 if (!this->script_options_->saw_sections_clause())
592 const Script_sections* ss = this->script_options_->script_sections();
593 return ret + ss->expected_segment_count(this);
597 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
598 // is whether we saw a .note.GNU-stack section in the object file.
599 // GNU_STACK_FLAGS is the section flags. The flags give the
600 // protection required for stack memory. We record this in an
601 // executable as a PT_GNU_STACK segment. If an object file does not
602 // have a .note.GNU-stack segment, we must assume that it is an old
603 // object. On some targets that will force an executable stack.
606 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
609 this->input_without_gnu_stack_note_ = true;
612 this->input_with_gnu_stack_note_ = true;
613 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
614 this->input_requires_executable_stack_ = true;
618 // Create the dynamic sections which are needed before we read the
622 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
624 if (parameters->doing_static_link())
627 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
630 | elfcpp::SHF_WRITE),
633 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
634 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
635 elfcpp::STV_HIDDEN, 0, false, false);
637 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
639 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
642 // For each output section whose name can be represented as C symbol,
643 // define __start and __stop symbols for the section. This is a GNU
647 Layout::define_section_symbols(Symbol_table* symtab)
649 for (Section_list::const_iterator p = this->section_list_.begin();
650 p != this->section_list_.end();
653 const char* const name = (*p)->name();
654 if (name[strspn(name,
656 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
657 "abcdefghijklmnopqrstuvwxyz"
661 const std::string name_string(name);
662 const std::string start_name("__start_" + name_string);
663 const std::string stop_name("__stop_" + name_string);
665 symtab->define_in_output_data(start_name.c_str(),
674 false, // offset_is_from_end
675 true); // only_if_ref
677 symtab->define_in_output_data(stop_name.c_str(),
686 true, // offset_is_from_end
687 true); // only_if_ref
692 // Find the first read-only PT_LOAD segment, creating one if
696 Layout::find_first_load_seg()
698 for (Segment_list::const_iterator p = this->segment_list_.begin();
699 p != this->segment_list_.end();
702 if ((*p)->type() == elfcpp::PT_LOAD
703 && ((*p)->flags() & elfcpp::PF_R) != 0
704 && ((*p)->flags() & elfcpp::PF_W) == 0)
708 gold_assert(!this->script_options_->saw_phdrs_clause());
710 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
715 // Finalize the layout. When this is called, we have created all the
716 // output sections and all the output segments which are based on
717 // input sections. We have several things to do, and we have to do
718 // them in the right order, so that we get the right results correctly
721 // 1) Finalize the list of output segments and create the segment
724 // 2) Finalize the dynamic symbol table and associated sections.
726 // 3) Determine the final file offset of all the output segments.
728 // 4) Determine the final file offset of all the SHF_ALLOC output
731 // 5) Create the symbol table sections and the section name table
734 // 6) Finalize the symbol table: set symbol values to their final
735 // value and make a final determination of which symbols are going
736 // into the output symbol table.
738 // 7) Create the section table header.
740 // 8) Determine the final file offset of all the output sections which
741 // are not SHF_ALLOC, including the section table header.
743 // 9) Finalize the ELF file header.
745 // This function returns the size of the output file.
748 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
751 Target* const target = input_objects->target();
753 target->finalize_sections(this);
755 this->count_local_symbols(task, input_objects);
757 this->create_gold_note();
758 this->create_executable_stack_info(target);
760 Output_segment* phdr_seg = NULL;
761 if (!parameters->output_is_object() && !parameters->doing_static_link())
763 // There was a dynamic object in the link. We need to create
764 // some information for the dynamic linker.
766 // Create the PT_PHDR segment which will hold the program
768 if (!this->script_options_->saw_phdrs_clause())
769 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
771 // Create the dynamic symbol table, including the hash table.
772 Output_section* dynstr;
773 std::vector<Symbol*> dynamic_symbols;
774 unsigned int local_dynamic_count;
775 Versions versions(this->options_, &this->dynpool_);
776 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
777 &local_dynamic_count, &dynamic_symbols,
780 // Create the .interp section to hold the name of the
781 // interpreter, and put it in a PT_INTERP segment.
782 if (!parameters->output_is_shared())
783 this->create_interp(target);
785 // Finish the .dynamic section to hold the dynamic data, and put
786 // it in a PT_DYNAMIC segment.
787 this->finish_dynamic_section(input_objects, symtab);
789 // We should have added everything we need to the dynamic string
791 this->dynpool_.set_string_offsets();
793 // Create the version sections. We can't do this until the
794 // dynamic string table is complete.
795 this->create_version_sections(&versions, symtab, local_dynamic_count,
796 dynamic_symbols, dynstr);
799 // If there is a SECTIONS clause, put all the input sections into
800 // the required order.
801 Output_segment* load_seg;
802 if (this->script_options_->saw_sections_clause())
803 load_seg = this->set_section_addresses_from_script(symtab);
805 load_seg = this->find_first_load_seg();
807 gold_assert(phdr_seg == NULL || load_seg != NULL);
809 // Lay out the segment headers.
810 Output_segment_headers* segment_headers;
811 segment_headers = new Output_segment_headers(this->segment_list_);
812 if (load_seg != NULL)
813 load_seg->add_initial_output_data(segment_headers);
814 if (phdr_seg != NULL)
815 phdr_seg->add_initial_output_data(segment_headers);
817 // Lay out the file header.
818 Output_file_header* file_header;
819 file_header = new Output_file_header(target, symtab, segment_headers,
820 this->script_options_->entry());
821 if (load_seg != NULL)
822 load_seg->add_initial_output_data(file_header);
824 this->special_output_list_.push_back(file_header);
825 this->special_output_list_.push_back(segment_headers);
827 if (this->script_options_->saw_phdrs_clause())
829 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
830 // clause in a linker script.
831 Script_sections* ss = this->script_options_->script_sections();
832 ss->put_headers_in_phdrs(file_header, segment_headers);
835 // We set the output section indexes in set_segment_offsets and
836 // set_section_indexes.
837 unsigned int shndx = 1;
839 // Set the file offsets of all the segments, and all the sections
841 off_t off = this->set_segment_offsets(target, load_seg, &shndx);
843 // Set the file offsets of all the non-data sections we've seen so
844 // far which don't have to wait for the input sections. We need
845 // this in order to finalize local symbols in non-allocated
847 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
849 // Create the symbol table sections.
850 this->create_symtab_sections(input_objects, symtab, &off);
851 if (!parameters->doing_static_link())
852 this->assign_local_dynsym_offsets(input_objects);
854 // Process any symbol assignments from a linker script. This must
855 // be called after the symbol table has been finalized.
856 this->script_options_->finalize_symbols(symtab, this);
858 // Create the .shstrtab section.
859 Output_section* shstrtab_section = this->create_shstrtab();
861 // Set the file offsets of the rest of the non-data sections which
862 // don't have to wait for the input sections.
863 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
865 // Now that all sections have been created, set the section indexes.
866 shndx = this->set_section_indexes(shndx);
868 // Create the section table header.
869 this->create_shdrs(&off);
871 // If there are no sections which require postprocessing, we can
872 // handle the section names now, and avoid a resize later.
873 if (!this->any_postprocessing_sections_)
874 off = this->set_section_offsets(off,
875 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
877 file_header->set_section_info(this->section_headers_, shstrtab_section);
879 // Now we know exactly where everything goes in the output file
880 // (except for non-allocated sections which require postprocessing).
881 Output_data::layout_complete();
883 this->output_file_size_ = off;
888 // Create a .note section for an executable or shared library. This
889 // records the version of gold used to create the binary.
892 Layout::create_gold_note()
894 if (parameters->output_is_object())
897 // Authorities all agree that the values in a .note field should
898 // be aligned on 4-byte boundaries for 32-bit binaries. However,
899 // they differ on what the alignment is for 64-bit binaries.
900 // The GABI says unambiguously they take 8-byte alignment:
901 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
902 // Other documentation says alignment should always be 4 bytes:
903 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
904 // GNU ld and GNU readelf both support the latter (at least as of
905 // version 2.16.91), and glibc always generates the latter for
906 // .note.ABI-tag (as of version 1.6), so that's the one we go with
908 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
909 const int size = parameters->get_size();
914 // The contents of the .note section.
915 const char* name = "GNU";
916 std::string desc(std::string("gold ") + gold::get_version_string());
917 size_t namesz = strlen(name) + 1;
918 size_t aligned_namesz = align_address(namesz, size / 8);
919 size_t descsz = desc.length() + 1;
920 size_t aligned_descsz = align_address(descsz, size / 8);
921 const int note_type = 4;
923 size_t notesz = 3 * (size / 8) + aligned_namesz + aligned_descsz;
925 unsigned char buffer[128];
926 gold_assert(sizeof buffer >= notesz);
927 memset(buffer, 0, notesz);
929 bool is_big_endian = parameters->is_big_endian();
935 elfcpp::Swap<32, false>::writeval(buffer, namesz);
936 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
937 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
941 elfcpp::Swap<32, true>::writeval(buffer, namesz);
942 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
943 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
950 elfcpp::Swap<64, false>::writeval(buffer, namesz);
951 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
952 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
956 elfcpp::Swap<64, true>::writeval(buffer, namesz);
957 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
958 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
964 memcpy(buffer + 3 * (size / 8), name, namesz);
965 memcpy(buffer + 3 * (size / 8) + aligned_namesz, desc.data(), descsz);
967 const char* note_name = this->namepool_.add(".note", false, NULL);
968 Output_section* os = this->make_output_section(note_name,
971 Output_section_data* posd = new Output_data_const(buffer, notesz,
973 os->add_output_section_data(posd);
976 // Record whether the stack should be executable. This can be set
977 // from the command line using the -z execstack or -z noexecstack
978 // options. Otherwise, if any input file has a .note.GNU-stack
979 // section with the SHF_EXECINSTR flag set, the stack should be
980 // executable. Otherwise, if at least one input file a
981 // .note.GNU-stack section, and some input file has no .note.GNU-stack
982 // section, we use the target default for whether the stack should be
983 // executable. Otherwise, we don't generate a stack note. When
984 // generating a object file, we create a .note.GNU-stack section with
985 // the appropriate marking. When generating an executable or shared
986 // library, we create a PT_GNU_STACK segment.
989 Layout::create_executable_stack_info(const Target* target)
991 bool is_stack_executable;
992 if (this->options_.is_execstack_set())
993 is_stack_executable = this->options_.is_stack_executable();
994 else if (!this->input_with_gnu_stack_note_)
998 if (this->input_requires_executable_stack_)
999 is_stack_executable = true;
1000 else if (this->input_without_gnu_stack_note_)
1001 is_stack_executable = target->is_default_stack_executable();
1003 is_stack_executable = false;
1006 if (parameters->output_is_object())
1008 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1009 elfcpp::Elf_Xword flags = 0;
1010 if (is_stack_executable)
1011 flags |= elfcpp::SHF_EXECINSTR;
1012 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1016 if (this->script_options_->saw_phdrs_clause())
1018 int flags = elfcpp::PF_R | elfcpp::PF_W;
1019 if (is_stack_executable)
1020 flags |= elfcpp::PF_X;
1021 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1025 // Return whether SEG1 should be before SEG2 in the output file. This
1026 // is based entirely on the segment type and flags. When this is
1027 // called the segment addresses has normally not yet been set.
1030 Layout::segment_precedes(const Output_segment* seg1,
1031 const Output_segment* seg2)
1033 elfcpp::Elf_Word type1 = seg1->type();
1034 elfcpp::Elf_Word type2 = seg2->type();
1036 // The single PT_PHDR segment is required to precede any loadable
1037 // segment. We simply make it always first.
1038 if (type1 == elfcpp::PT_PHDR)
1040 gold_assert(type2 != elfcpp::PT_PHDR);
1043 if (type2 == elfcpp::PT_PHDR)
1046 // The single PT_INTERP segment is required to precede any loadable
1047 // segment. We simply make it always second.
1048 if (type1 == elfcpp::PT_INTERP)
1050 gold_assert(type2 != elfcpp::PT_INTERP);
1053 if (type2 == elfcpp::PT_INTERP)
1056 // We then put PT_LOAD segments before any other segments.
1057 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1059 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1062 // We put the PT_TLS segment last, because that is where the dynamic
1063 // linker expects to find it (this is just for efficiency; other
1064 // positions would also work correctly).
1065 if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
1067 if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
1070 const elfcpp::Elf_Word flags1 = seg1->flags();
1071 const elfcpp::Elf_Word flags2 = seg2->flags();
1073 // The order of non-PT_LOAD segments is unimportant. We simply sort
1074 // by the numeric segment type and flags values. There should not
1075 // be more than one segment with the same type and flags.
1076 if (type1 != elfcpp::PT_LOAD)
1079 return type1 < type2;
1080 gold_assert(flags1 != flags2);
1081 return flags1 < flags2;
1084 // If the addresses are set already, sort by load address.
1085 if (seg1->are_addresses_set())
1087 if (!seg2->are_addresses_set())
1090 unsigned int section_count1 = seg1->output_section_count();
1091 unsigned int section_count2 = seg2->output_section_count();
1092 if (section_count1 == 0 && section_count2 > 0)
1094 if (section_count1 > 0 && section_count2 == 0)
1097 uint64_t paddr1 = seg1->first_section_load_address();
1098 uint64_t paddr2 = seg2->first_section_load_address();
1099 if (paddr1 != paddr2)
1100 return paddr1 < paddr2;
1102 else if (seg2->are_addresses_set())
1105 // We sort PT_LOAD segments based on the flags. Readonly segments
1106 // come before writable segments. Then executable segments come
1107 // before non-executable segments. Then the unlikely case of a
1108 // non-readable segment comes before the normal case of a readable
1109 // segment. If there are multiple segments with the same type and
1110 // flags, we require that the address be set, and we sort by
1111 // virtual address and then physical address.
1112 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1113 return (flags1 & elfcpp::PF_W) == 0;
1114 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1115 return (flags1 & elfcpp::PF_X) != 0;
1116 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1117 return (flags1 & elfcpp::PF_R) == 0;
1119 // We shouldn't get here--we shouldn't create segments which we
1120 // can't distinguish.
1124 // Set the file offsets of all the segments, and all the sections they
1125 // contain. They have all been created. LOAD_SEG must be be laid out
1126 // first. Return the offset of the data to follow.
1129 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1130 unsigned int *pshndx)
1132 // Sort them into the final order.
1133 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1134 Layout::Compare_segments());
1136 // Find the PT_LOAD segments, and set their addresses and offsets
1137 // and their section's addresses and offsets.
1139 if (this->options_.user_set_text_segment_address())
1140 addr = options_.text_segment_address();
1141 else if (parameters->output_is_shared())
1144 addr = target->default_text_segment_address();
1147 // If LOAD_SEG is NULL, then the file header and segment headers
1148 // will not be loadable. But they still need to be at offset 0 in
1149 // the file. Set their offsets now.
1150 if (load_seg == NULL)
1152 for (Data_list::iterator p = this->special_output_list_.begin();
1153 p != this->special_output_list_.end();
1156 off = align_address(off, (*p)->addralign());
1157 (*p)->set_address_and_file_offset(0, off);
1158 off += (*p)->data_size();
1162 bool was_readonly = false;
1163 for (Segment_list::iterator p = this->segment_list_.begin();
1164 p != this->segment_list_.end();
1167 if ((*p)->type() == elfcpp::PT_LOAD)
1169 if (load_seg != NULL && load_seg != *p)
1173 uint64_t orig_addr = addr;
1174 uint64_t orig_off = off;
1176 uint64_t aligned_addr = 0;
1177 uint64_t abi_pagesize = target->abi_pagesize();
1179 // FIXME: This should depend on the -n and -N options.
1180 (*p)->set_minimum_p_align(target->common_pagesize());
1182 bool are_addresses_set = (*p)->are_addresses_set();
1183 if (are_addresses_set)
1185 // When it comes to setting file offsets, we care about
1186 // the physical address.
1187 addr = (*p)->paddr();
1189 // Adjust the file offset to the same address modulo the
1191 uint64_t unsigned_off = off;
1192 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1193 | (addr & (abi_pagesize - 1)));
1194 if (aligned_off < unsigned_off)
1195 aligned_off += abi_pagesize;
1200 // If the last segment was readonly, and this one is
1201 // not, then skip the address forward one page,
1202 // maintaining the same position within the page. This
1203 // lets us store both segments overlapping on a single
1204 // page in the file, but the loader will put them on
1205 // different pages in memory.
1207 addr = align_address(addr, (*p)->maximum_alignment());
1208 aligned_addr = addr;
1210 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1212 if ((addr & (abi_pagesize - 1)) != 0)
1213 addr = addr + abi_pagesize;
1216 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1219 unsigned int shndx_hold = *pshndx;
1220 uint64_t new_addr = (*p)->set_section_addresses(false, addr, &off,
1223 // Now that we know the size of this segment, we may be able
1224 // to save a page in memory, at the cost of wasting some
1225 // file space, by instead aligning to the start of a new
1226 // page. Here we use the real machine page size rather than
1227 // the ABI mandated page size.
1229 if (!are_addresses_set && aligned_addr != addr)
1231 uint64_t common_pagesize = target->common_pagesize();
1232 uint64_t first_off = (common_pagesize
1234 & (common_pagesize - 1)));
1235 uint64_t last_off = new_addr & (common_pagesize - 1);
1238 && ((aligned_addr & ~ (common_pagesize - 1))
1239 != (new_addr & ~ (common_pagesize - 1)))
1240 && first_off + last_off <= common_pagesize)
1242 *pshndx = shndx_hold;
1243 addr = align_address(aligned_addr, common_pagesize);
1244 addr = align_address(addr, (*p)->maximum_alignment());
1245 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1246 new_addr = (*p)->set_section_addresses(true, addr, &off,
1253 if (((*p)->flags() & elfcpp::PF_W) == 0)
1254 was_readonly = true;
1258 // Handle the non-PT_LOAD segments, setting their offsets from their
1259 // section's offsets.
1260 for (Segment_list::iterator p = this->segment_list_.begin();
1261 p != this->segment_list_.end();
1264 if ((*p)->type() != elfcpp::PT_LOAD)
1268 // Set the TLS offsets for each section in the PT_TLS segment.
1269 if (this->tls_segment_ != NULL)
1270 this->tls_segment_->set_tls_offsets();
1275 // Set the file offset of all the sections not associated with a
1279 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1281 for (Section_list::iterator p = this->unattached_section_list_.begin();
1282 p != this->unattached_section_list_.end();
1285 // The symtab section is handled in create_symtab_sections.
1286 if (*p == this->symtab_section_)
1289 // If we've already set the data size, don't set it again.
1290 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1293 if (pass == BEFORE_INPUT_SECTIONS_PASS
1294 && (*p)->requires_postprocessing())
1296 (*p)->create_postprocessing_buffer();
1297 this->any_postprocessing_sections_ = true;
1300 if (pass == BEFORE_INPUT_SECTIONS_PASS
1301 && (*p)->after_input_sections())
1303 else if (pass == POSTPROCESSING_SECTIONS_PASS
1304 && (!(*p)->after_input_sections()
1305 || (*p)->type() == elfcpp::SHT_STRTAB))
1307 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1308 && (!(*p)->after_input_sections()
1309 || (*p)->type() != elfcpp::SHT_STRTAB))
1312 off = align_address(off, (*p)->addralign());
1313 (*p)->set_file_offset(off);
1314 (*p)->finalize_data_size();
1315 off += (*p)->data_size();
1317 // At this point the name must be set.
1318 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1319 this->namepool_.add((*p)->name(), false, NULL);
1324 // Set the section indexes of all the sections not associated with a
1328 Layout::set_section_indexes(unsigned int shndx)
1330 for (Section_list::iterator p = this->unattached_section_list_.begin();
1331 p != this->unattached_section_list_.end();
1334 (*p)->set_out_shndx(shndx);
1340 // Set the section addresses according to the linker script. This is
1341 // only called when we see a SECTIONS clause. This returns the
1342 // program segment which should hold the file header and segment
1343 // headers, if any. It will return NULL if they should not be in a
1347 Layout::set_section_addresses_from_script(Symbol_table* symtab)
1349 Script_sections* ss = this->script_options_->script_sections();
1350 gold_assert(ss->saw_sections_clause());
1352 // Place each orphaned output section in the script.
1353 for (Section_list::iterator p = this->section_list_.begin();
1354 p != this->section_list_.end();
1357 if (!(*p)->found_in_sections_clause())
1358 ss->place_orphan(*p);
1361 return this->script_options_->set_section_addresses(symtab, this);
1364 // Count the local symbols in the regular symbol table and the dynamic
1365 // symbol table, and build the respective string pools.
1368 Layout::count_local_symbols(const Task* task,
1369 const Input_objects* input_objects)
1371 // First, figure out an upper bound on the number of symbols we'll
1372 // be inserting into each pool. This helps us create the pools with
1373 // the right size, to avoid unnecessary hashtable resizing.
1374 unsigned int symbol_count = 0;
1375 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1376 p != input_objects->relobj_end();
1378 symbol_count += (*p)->local_symbol_count();
1380 // Go from "upper bound" to "estimate." We overcount for two
1381 // reasons: we double-count symbols that occur in more than one
1382 // object file, and we count symbols that are dropped from the
1383 // output. Add it all together and assume we overcount by 100%.
1386 // We assume all symbols will go into both the sympool and dynpool.
1387 this->sympool_.reserve(symbol_count);
1388 this->dynpool_.reserve(symbol_count);
1390 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1391 p != input_objects->relobj_end();
1394 Task_lock_obj<Object> tlo(task, *p);
1395 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
1399 // Create the symbol table sections. Here we also set the final
1400 // values of the symbols. At this point all the loadable sections are
1404 Layout::create_symtab_sections(const Input_objects* input_objects,
1405 Symbol_table* symtab,
1410 if (parameters->get_size() == 32)
1412 symsize = elfcpp::Elf_sizes<32>::sym_size;
1415 else if (parameters->get_size() == 64)
1417 symsize = elfcpp::Elf_sizes<64>::sym_size;
1424 off = align_address(off, align);
1425 off_t startoff = off;
1427 // Save space for the dummy symbol at the start of the section. We
1428 // never bother to write this out--it will just be left as zero.
1430 unsigned int local_symbol_index = 1;
1432 // Add STT_SECTION symbols for each Output section which needs one.
1433 for (Section_list::iterator p = this->section_list_.begin();
1434 p != this->section_list_.end();
1437 if (!(*p)->needs_symtab_index())
1438 (*p)->set_symtab_index(-1U);
1441 (*p)->set_symtab_index(local_symbol_index);
1442 ++local_symbol_index;
1447 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1448 p != input_objects->relobj_end();
1451 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
1453 off += (index - local_symbol_index) * symsize;
1454 local_symbol_index = index;
1457 unsigned int local_symcount = local_symbol_index;
1458 gold_assert(local_symcount * symsize == off - startoff);
1461 size_t dyn_global_index;
1463 if (this->dynsym_section_ == NULL)
1466 dyn_global_index = 0;
1471 dyn_global_index = this->dynsym_section_->info();
1472 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
1473 dynoff = this->dynsym_section_->offset() + locsize;
1474 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
1475 gold_assert(static_cast<off_t>(dyncount * symsize)
1476 == this->dynsym_section_->data_size() - locsize);
1479 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
1480 &this->sympool_, &local_symcount);
1482 if (!parameters->strip_all())
1484 this->sympool_.set_string_offsets();
1486 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
1487 Output_section* osymtab = this->make_output_section(symtab_name,
1490 this->symtab_section_ = osymtab;
1492 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
1494 osymtab->add_output_section_data(pos);
1496 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
1497 Output_section* ostrtab = this->make_output_section(strtab_name,
1501 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
1502 ostrtab->add_output_section_data(pstr);
1504 osymtab->set_file_offset(startoff);
1505 osymtab->finalize_data_size();
1506 osymtab->set_link_section(ostrtab);
1507 osymtab->set_info(local_symcount);
1508 osymtab->set_entsize(symsize);
1514 // Create the .shstrtab section, which holds the names of the
1515 // sections. At the time this is called, we have created all the
1516 // output sections except .shstrtab itself.
1519 Layout::create_shstrtab()
1521 // FIXME: We don't need to create a .shstrtab section if we are
1522 // stripping everything.
1524 const char* name = this->namepool_.add(".shstrtab", false, NULL);
1526 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
1528 // We can't write out this section until we've set all the section
1529 // names, and we don't set the names of compressed output sections
1530 // until relocations are complete.
1531 os->set_after_input_sections();
1533 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
1534 os->add_output_section_data(posd);
1539 // Create the section headers. SIZE is 32 or 64. OFF is the file
1543 Layout::create_shdrs(off_t* poff)
1545 Output_section_headers* oshdrs;
1546 oshdrs = new Output_section_headers(this,
1547 &this->segment_list_,
1548 &this->unattached_section_list_,
1550 off_t off = align_address(*poff, oshdrs->addralign());
1551 oshdrs->set_address_and_file_offset(0, off);
1552 off += oshdrs->data_size();
1554 this->section_headers_ = oshdrs;
1557 // Create the dynamic symbol table.
1560 Layout::create_dynamic_symtab(const Input_objects* input_objects,
1561 Symbol_table* symtab,
1562 Output_section **pdynstr,
1563 unsigned int* plocal_dynamic_count,
1564 std::vector<Symbol*>* pdynamic_symbols,
1565 Versions* pversions)
1567 // Count all the symbols in the dynamic symbol table, and set the
1568 // dynamic symbol indexes.
1570 // Skip symbol 0, which is always all zeroes.
1571 unsigned int index = 1;
1573 // Add STT_SECTION symbols for each Output section which needs one.
1574 for (Section_list::iterator p = this->section_list_.begin();
1575 p != this->section_list_.end();
1578 if (!(*p)->needs_dynsym_index())
1579 (*p)->set_dynsym_index(-1U);
1582 (*p)->set_dynsym_index(index);
1587 // Count the local symbols that need to go in the dynamic symbol table,
1588 // and set the dynamic symbol indexes.
1589 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1590 p != input_objects->relobj_end();
1593 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
1597 unsigned int local_symcount = index;
1598 *plocal_dynamic_count = local_symcount;
1600 // FIXME: We have to tell set_dynsym_indexes whether the
1601 // -E/--export-dynamic option was used.
1602 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
1603 &this->dynpool_, pversions);
1607 const int size = parameters->get_size();
1610 symsize = elfcpp::Elf_sizes<32>::sym_size;
1613 else if (size == 64)
1615 symsize = elfcpp::Elf_sizes<64>::sym_size;
1621 // Create the dynamic symbol table section.
1623 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
1628 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
1630 dynsym->add_output_section_data(odata);
1632 dynsym->set_info(local_symcount);
1633 dynsym->set_entsize(symsize);
1634 dynsym->set_addralign(align);
1636 this->dynsym_section_ = dynsym;
1638 Output_data_dynamic* const odyn = this->dynamic_data_;
1639 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
1640 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
1642 // Create the dynamic string table section.
1644 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
1649 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
1650 dynstr->add_output_section_data(strdata);
1652 dynsym->set_link_section(dynstr);
1653 this->dynamic_section_->set_link_section(dynstr);
1655 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
1656 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
1660 // Create the hash tables.
1662 // FIXME: We need an option to create a GNU hash table.
1664 unsigned char* phash;
1665 unsigned int hashlen;
1666 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
1669 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
1674 Output_section_data* hashdata = new Output_data_const_buffer(phash,
1677 hashsec->add_output_section_data(hashdata);
1679 hashsec->set_link_section(dynsym);
1680 hashsec->set_entsize(4);
1682 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
1685 // Assign offsets to each local portion of the dynamic symbol table.
1688 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
1690 Output_section* dynsym = this->dynsym_section_;
1691 gold_assert(dynsym != NULL);
1693 off_t off = dynsym->offset();
1695 // Skip the dummy symbol at the start of the section.
1696 off += dynsym->entsize();
1698 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1699 p != input_objects->relobj_end();
1702 unsigned int count = (*p)->set_local_dynsym_offset(off);
1703 off += count * dynsym->entsize();
1707 // Create the version sections.
1710 Layout::create_version_sections(const Versions* versions,
1711 const Symbol_table* symtab,
1712 unsigned int local_symcount,
1713 const std::vector<Symbol*>& dynamic_symbols,
1714 const Output_section* dynstr)
1716 if (!versions->any_defs() && !versions->any_needs())
1719 if (parameters->get_size() == 32)
1721 if (parameters->is_big_endian())
1723 #ifdef HAVE_TARGET_32_BIG
1724 this->sized_create_version_sections
1725 SELECT_SIZE_ENDIAN_NAME(32, true)(
1726 versions, symtab, local_symcount, dynamic_symbols, dynstr
1727 SELECT_SIZE_ENDIAN(32, true));
1734 #ifdef HAVE_TARGET_32_LITTLE
1735 this->sized_create_version_sections
1736 SELECT_SIZE_ENDIAN_NAME(32, false)(
1737 versions, symtab, local_symcount, dynamic_symbols, dynstr
1738 SELECT_SIZE_ENDIAN(32, false));
1744 else if (parameters->get_size() == 64)
1746 if (parameters->is_big_endian())
1748 #ifdef HAVE_TARGET_64_BIG
1749 this->sized_create_version_sections
1750 SELECT_SIZE_ENDIAN_NAME(64, true)(
1751 versions, symtab, local_symcount, dynamic_symbols, dynstr
1752 SELECT_SIZE_ENDIAN(64, true));
1759 #ifdef HAVE_TARGET_64_LITTLE
1760 this->sized_create_version_sections
1761 SELECT_SIZE_ENDIAN_NAME(64, false)(
1762 versions, symtab, local_symcount, dynamic_symbols, dynstr
1763 SELECT_SIZE_ENDIAN(64, false));
1773 // Create the version sections, sized version.
1775 template<int size, bool big_endian>
1777 Layout::sized_create_version_sections(
1778 const Versions* versions,
1779 const Symbol_table* symtab,
1780 unsigned int local_symcount,
1781 const std::vector<Symbol*>& dynamic_symbols,
1782 const Output_section* dynstr
1785 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
1786 elfcpp::SHT_GNU_versym,
1790 unsigned char* vbuf;
1792 versions->symbol_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1793 symtab, &this->dynpool_, local_symcount, dynamic_symbols, &vbuf, &vsize
1794 SELECT_SIZE_ENDIAN(size, big_endian));
1796 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2);
1798 vsec->add_output_section_data(vdata);
1799 vsec->set_entsize(2);
1800 vsec->set_link_section(this->dynsym_section_);
1802 Output_data_dynamic* const odyn = this->dynamic_data_;
1803 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
1805 if (versions->any_defs())
1807 Output_section* vdsec;
1808 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
1809 elfcpp::SHT_GNU_verdef,
1813 unsigned char* vdbuf;
1814 unsigned int vdsize;
1815 unsigned int vdentries;
1816 versions->def_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1817 &this->dynpool_, &vdbuf, &vdsize, &vdentries
1818 SELECT_SIZE_ENDIAN(size, big_endian));
1820 Output_section_data* vddata = new Output_data_const_buffer(vdbuf,
1824 vdsec->add_output_section_data(vddata);
1825 vdsec->set_link_section(dynstr);
1826 vdsec->set_info(vdentries);
1828 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
1829 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
1832 if (versions->any_needs())
1834 Output_section* vnsec;
1835 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
1836 elfcpp::SHT_GNU_verneed,
1840 unsigned char* vnbuf;
1841 unsigned int vnsize;
1842 unsigned int vnentries;
1843 versions->need_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)
1844 (&this->dynpool_, &vnbuf, &vnsize, &vnentries
1845 SELECT_SIZE_ENDIAN(size, big_endian));
1847 Output_section_data* vndata = new Output_data_const_buffer(vnbuf,
1851 vnsec->add_output_section_data(vndata);
1852 vnsec->set_link_section(dynstr);
1853 vnsec->set_info(vnentries);
1855 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
1856 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
1860 // Create the .interp section and PT_INTERP segment.
1863 Layout::create_interp(const Target* target)
1865 const char* interp = this->options_.dynamic_linker();
1868 interp = target->dynamic_linker();
1869 gold_assert(interp != NULL);
1872 size_t len = strlen(interp) + 1;
1874 Output_section_data* odata = new Output_data_const(interp, len, 1);
1876 Output_section* osec = this->choose_output_section(NULL, ".interp",
1877 elfcpp::SHT_PROGBITS,
1880 osec->add_output_section_data(odata);
1882 if (!this->script_options_->saw_phdrs_clause())
1884 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
1886 oseg->add_initial_output_section(osec, elfcpp::PF_R);
1890 // Finish the .dynamic section and PT_DYNAMIC segment.
1893 Layout::finish_dynamic_section(const Input_objects* input_objects,
1894 const Symbol_table* symtab)
1896 if (!this->script_options_->saw_phdrs_clause())
1898 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
1901 oseg->add_initial_output_section(this->dynamic_section_,
1902 elfcpp::PF_R | elfcpp::PF_W);
1905 Output_data_dynamic* const odyn = this->dynamic_data_;
1907 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
1908 p != input_objects->dynobj_end();
1911 // FIXME: Handle --as-needed.
1912 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
1915 if (parameters->output_is_shared())
1917 const char* soname = this->options_.soname();
1919 odyn->add_string(elfcpp::DT_SONAME, soname);
1922 // FIXME: Support --init and --fini.
1923 Symbol* sym = symtab->lookup("_init");
1924 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1925 odyn->add_symbol(elfcpp::DT_INIT, sym);
1927 sym = symtab->lookup("_fini");
1928 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1929 odyn->add_symbol(elfcpp::DT_FINI, sym);
1931 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
1933 // Add a DT_RPATH entry if needed.
1934 const General_options::Dir_list& rpath(this->options_.rpath());
1937 std::string rpath_val;
1938 for (General_options::Dir_list::const_iterator p = rpath.begin();
1942 if (rpath_val.empty())
1943 rpath_val = p->name();
1946 // Eliminate duplicates.
1947 General_options::Dir_list::const_iterator q;
1948 for (q = rpath.begin(); q != p; ++q)
1949 if (q->name() == p->name())
1954 rpath_val += p->name();
1959 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
1962 // Look for text segments that have dynamic relocations.
1963 bool have_textrel = false;
1964 for (Segment_list::const_iterator p = this->segment_list_.begin();
1965 p != this->segment_list_.end();
1968 if (((*p)->flags() & elfcpp::PF_W) == 0
1969 && (*p)->dynamic_reloc_count() > 0)
1971 have_textrel = true;
1976 // Add a DT_FLAGS entry. We add it even if no flags are set so that
1977 // post-link tools can easily modify these flags if desired.
1978 unsigned int flags = 0;
1981 // Add a DT_TEXTREL for compatibility with older loaders.
1982 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
1983 flags |= elfcpp::DF_TEXTREL;
1985 if (parameters->output_is_shared() && this->has_static_tls())
1986 flags |= elfcpp::DF_STATIC_TLS;
1987 odyn->add_constant(elfcpp::DT_FLAGS, flags);
1990 // The mapping of .gnu.linkonce section names to real section names.
1992 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
1993 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
1995 MAPPING_INIT("d.rel.ro", ".data.rel.ro"), // Must be before "d".
1996 MAPPING_INIT("t", ".text"),
1997 MAPPING_INIT("r", ".rodata"),
1998 MAPPING_INIT("d", ".data"),
1999 MAPPING_INIT("b", ".bss"),
2000 MAPPING_INIT("s", ".sdata"),
2001 MAPPING_INIT("sb", ".sbss"),
2002 MAPPING_INIT("s2", ".sdata2"),
2003 MAPPING_INIT("sb2", ".sbss2"),
2004 MAPPING_INIT("wi", ".debug_info"),
2005 MAPPING_INIT("td", ".tdata"),
2006 MAPPING_INIT("tb", ".tbss"),
2007 MAPPING_INIT("lr", ".lrodata"),
2008 MAPPING_INIT("l", ".ldata"),
2009 MAPPING_INIT("lb", ".lbss"),
2013 const int Layout::linkonce_mapping_count =
2014 sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
2016 // Return the name of the output section to use for a .gnu.linkonce
2017 // section. This is based on the default ELF linker script of the old
2018 // GNU linker. For example, we map a name like ".gnu.linkonce.t.foo"
2019 // to ".text". Set *PLEN to the length of the name. *PLEN is
2020 // initialized to the length of NAME.
2023 Layout::linkonce_output_name(const char* name, size_t *plen)
2025 const char* s = name + sizeof(".gnu.linkonce") - 1;
2029 const Linkonce_mapping* plm = linkonce_mapping;
2030 for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2032 if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2041 // Choose the output section name to use given an input section name.
2042 // Set *PLEN to the length of the name. *PLEN is initialized to the
2046 Layout::output_section_name(const char* name, size_t* plen)
2048 if (Layout::is_linkonce(name))
2050 // .gnu.linkonce sections are laid out as though they were named
2051 // for the sections are placed into.
2052 return Layout::linkonce_output_name(name, plen);
2055 // gcc 4.3 generates the following sorts of section names when it
2056 // needs a section name specific to a function:
2062 // .data.rel.local.FN
2064 // .data.rel.ro.local.FN
2071 // The GNU linker maps all of those to the part before the .FN,
2072 // except that .data.rel.local.FN is mapped to .data, and
2073 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
2074 // beginning with .data.rel.ro.local are grouped together.
2076 // For an anonymous namespace, the string FN can contain a '.'.
2078 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2079 // GNU linker maps to .rodata.
2081 // The .data.rel.ro sections enable a security feature triggered by
2082 // the -z relro option. Section which need to be relocated at
2083 // program startup time but which may be readonly after startup are
2084 // grouped into .data.rel.ro. They are then put into a PT_GNU_RELRO
2085 // segment. The dynamic linker will make that segment writable,
2086 // perform relocations, and then make it read-only. FIXME: We do
2087 // not yet implement this optimization.
2089 // It is hard to handle this in a principled way.
2091 // These are the rules we follow:
2093 // If the section name has no initial '.', or no dot other than an
2094 // initial '.', we use the name unchanged (i.e., "mysection" and
2095 // ".text" are unchanged).
2097 // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2099 // Otherwise, we drop the second '.' and everything that comes after
2100 // it (i.e., ".text.XXX" becomes ".text").
2102 const char* s = name;
2106 const char* sdot = strchr(s, '.');
2110 const char* const data_rel_ro = ".data.rel.ro";
2111 if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2113 *plen = strlen(data_rel_ro);
2117 *plen = sdot - name;
2121 // Record the signature of a comdat section, and return whether to
2122 // include it in the link. If GROUP is true, this is a regular
2123 // section group. If GROUP is false, this is a group signature
2124 // derived from the name of a linkonce section. We want linkonce
2125 // signatures and group signatures to block each other, but we don't
2126 // want a linkonce signature to block another linkonce signature.
2129 Layout::add_comdat(const char* signature, bool group)
2131 std::string sig(signature);
2132 std::pair<Signatures::iterator, bool> ins(
2133 this->signatures_.insert(std::make_pair(sig, group)));
2137 // This is the first time we've seen this signature.
2141 if (ins.first->second)
2143 // We've already seen a real section group with this signature.
2148 // This is a real section group, and we've already seen a
2149 // linkonce section with this signature. Record that we've seen
2150 // a section group, and don't include this section group.
2151 ins.first->second = true;
2156 // We've already seen a linkonce section and this is a linkonce
2157 // section. These don't block each other--this may be the same
2158 // symbol name with different section types.
2163 // Store the allocated sections into the section list.
2166 Layout::get_allocated_sections(Section_list* section_list) const
2168 for (Section_list::const_iterator p = this->section_list_.begin();
2169 p != this->section_list_.end();
2171 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2172 section_list->push_back(*p);
2175 // Create an output segment.
2178 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2180 Output_segment* oseg = new Output_segment(type, flags);
2181 this->segment_list_.push_back(oseg);
2185 // Write out the Output_sections. Most won't have anything to write,
2186 // since most of the data will come from input sections which are
2187 // handled elsewhere. But some Output_sections do have Output_data.
2190 Layout::write_output_sections(Output_file* of) const
2192 for (Section_list::const_iterator p = this->section_list_.begin();
2193 p != this->section_list_.end();
2196 if (!(*p)->after_input_sections())
2201 // Write out data not associated with a section or the symbol table.
2204 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
2206 if (!parameters->strip_all())
2208 const Output_section* symtab_section = this->symtab_section_;
2209 for (Section_list::const_iterator p = this->section_list_.begin();
2210 p != this->section_list_.end();
2213 if ((*p)->needs_symtab_index())
2215 gold_assert(symtab_section != NULL);
2216 unsigned int index = (*p)->symtab_index();
2217 gold_assert(index > 0 && index != -1U);
2218 off_t off = (symtab_section->offset()
2219 + index * symtab_section->entsize());
2220 symtab->write_section_symbol(*p, of, off);
2225 const Output_section* dynsym_section = this->dynsym_section_;
2226 for (Section_list::const_iterator p = this->section_list_.begin();
2227 p != this->section_list_.end();
2230 if ((*p)->needs_dynsym_index())
2232 gold_assert(dynsym_section != NULL);
2233 unsigned int index = (*p)->dynsym_index();
2234 gold_assert(index > 0 && index != -1U);
2235 off_t off = (dynsym_section->offset()
2236 + index * dynsym_section->entsize());
2237 symtab->write_section_symbol(*p, of, off);
2241 // Write out the Output_data which are not in an Output_section.
2242 for (Data_list::const_iterator p = this->special_output_list_.begin();
2243 p != this->special_output_list_.end();
2248 // Write out the Output_sections which can only be written after the
2249 // input sections are complete.
2252 Layout::write_sections_after_input_sections(Output_file* of)
2254 // Determine the final section offsets, and thus the final output
2255 // file size. Note we finalize the .shstrab last, to allow the
2256 // after_input_section sections to modify their section-names before
2258 if (this->any_postprocessing_sections_)
2260 off_t off = this->output_file_size_;
2261 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
2263 // Now that we've finalized the names, we can finalize the shstrab.
2265 this->set_section_offsets(off,
2266 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2268 if (off > this->output_file_size_)
2271 this->output_file_size_ = off;
2275 for (Section_list::const_iterator p = this->section_list_.begin();
2276 p != this->section_list_.end();
2279 if ((*p)->after_input_sections())
2283 this->section_headers_->write(of);
2286 // Print statistical information to stderr. This is used for --stats.
2289 Layout::print_stats() const
2291 this->namepool_.print_stats("section name pool");
2292 this->sympool_.print_stats("output symbol name pool");
2293 this->dynpool_.print_stats("dynamic name pool");
2295 for (Section_list::const_iterator p = this->section_list_.begin();
2296 p != this->section_list_.end();
2298 (*p)->print_merge_stats();
2301 // Write_sections_task methods.
2303 // We can always run this task.
2306 Write_sections_task::is_runnable()
2311 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
2315 Write_sections_task::locks(Task_locker* tl)
2317 tl->add(this, this->output_sections_blocker_);
2318 tl->add(this, this->final_blocker_);
2321 // Run the task--write out the data.
2324 Write_sections_task::run(Workqueue*)
2326 this->layout_->write_output_sections(this->of_);
2329 // Write_data_task methods.
2331 // We can always run this task.
2334 Write_data_task::is_runnable()
2339 // We need to unlock FINAL_BLOCKER when finished.
2342 Write_data_task::locks(Task_locker* tl)
2344 tl->add(this, this->final_blocker_);
2347 // Run the task--write out the data.
2350 Write_data_task::run(Workqueue*)
2352 this->layout_->write_data(this->symtab_, this->of_);
2355 // Write_symbols_task methods.
2357 // We can always run this task.
2360 Write_symbols_task::is_runnable()
2365 // We need to unlock FINAL_BLOCKER when finished.
2368 Write_symbols_task::locks(Task_locker* tl)
2370 tl->add(this, this->final_blocker_);
2373 // Run the task--write out the symbols.
2376 Write_symbols_task::run(Workqueue*)
2378 this->symtab_->write_globals(this->input_objects_, this->sympool_,
2379 this->dynpool_, this->of_);
2382 // Write_after_input_sections_task methods.
2384 // We can only run this task after the input sections have completed.
2387 Write_after_input_sections_task::is_runnable()
2389 if (this->input_sections_blocker_->is_blocked())
2390 return this->input_sections_blocker_;
2394 // We need to unlock FINAL_BLOCKER when finished.
2397 Write_after_input_sections_task::locks(Task_locker* tl)
2399 tl->add(this, this->final_blocker_);
2405 Write_after_input_sections_task::run(Workqueue*)
2407 this->layout_->write_sections_after_input_sections(this->of_);
2410 // Close_task_runner methods.
2412 // Run the task--close the file.
2415 Close_task_runner::run(Workqueue*, const Task*)
2420 // Instantiate the templates we need. We could use the configure
2421 // script to restrict this to only the ones for implemented targets.
2423 #ifdef HAVE_TARGET_32_LITTLE
2426 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
2428 const elfcpp::Shdr<32, false>& shdr,
2429 unsigned int, unsigned int, off_t*);
2432 #ifdef HAVE_TARGET_32_BIG
2435 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
2437 const elfcpp::Shdr<32, true>& shdr,
2438 unsigned int, unsigned int, off_t*);
2441 #ifdef HAVE_TARGET_64_LITTLE
2444 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
2446 const elfcpp::Shdr<64, false>& shdr,
2447 unsigned int, unsigned int, off_t*);
2450 #ifdef HAVE_TARGET_64_BIG
2453 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
2455 const elfcpp::Shdr<64, true>& shdr,
2456 unsigned int, unsigned int, off_t*);
2459 #ifdef HAVE_TARGET_32_LITTLE
2462 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
2463 const unsigned char* symbols,
2465 const unsigned char* symbol_names,
2466 off_t symbol_names_size,
2468 const elfcpp::Shdr<32, false>& shdr,
2469 unsigned int reloc_shndx,
2470 unsigned int reloc_type,
2474 #ifdef HAVE_TARGET_32_BIG
2477 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
2478 const unsigned char* symbols,
2480 const unsigned char* symbol_names,
2481 off_t symbol_names_size,
2483 const elfcpp::Shdr<32, true>& shdr,
2484 unsigned int reloc_shndx,
2485 unsigned int reloc_type,
2489 #ifdef HAVE_TARGET_64_LITTLE
2492 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
2493 const unsigned char* symbols,
2495 const unsigned char* symbol_names,
2496 off_t symbol_names_size,
2498 const elfcpp::Shdr<64, false>& shdr,
2499 unsigned int reloc_shndx,
2500 unsigned int reloc_type,
2504 #ifdef HAVE_TARGET_64_BIG
2507 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
2508 const unsigned char* symbols,
2510 const unsigned char* symbol_names,
2511 off_t symbol_names_size,
2513 const elfcpp::Shdr<64, true>& shdr,
2514 unsigned int reloc_shndx,
2515 unsigned int reloc_type,
2519 } // End namespace gold.