2010-03-01 Doug Kwan <dougkwan@google.com>
[binutils.git] / gold / layout.cc
blobf95813bd34d91d440f25b607d7ce29df5c4249bc
1 // layout.cc -- lay out output file sections for gold
3 // Copyright 2006, 2007, 2008, 2009, 2010 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.
23 #include "gold.h"
25 #include <cerrno>
26 #include <cstring>
27 #include <algorithm>
28 #include <iostream>
29 #include <utility>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include "libiberty.h"
33 #include "md5.h"
34 #include "sha1.h"
36 #include "parameters.h"
37 #include "options.h"
38 #include "mapfile.h"
39 #include "script.h"
40 #include "script-sections.h"
41 #include "output.h"
42 #include "symtab.h"
43 #include "dynobj.h"
44 #include "ehframe.h"
45 #include "compressed_output.h"
46 #include "reduced_debug_output.h"
47 #include "reloc.h"
48 #include "descriptors.h"
49 #include "plugin.h"
50 #include "incremental.h"
51 #include "layout.h"
53 namespace gold
56 // Layout::Relaxation_debug_check methods.
58 // Check that sections and special data are in reset states.
59 // We do not save states for Output_sections and special Output_data.
60 // So we check that they have not assigned any addresses or offsets.
61 // clean_up_after_relaxation simply resets their addresses and offsets.
62 void
63 Layout::Relaxation_debug_check::check_output_data_for_reset_values(
64 const Layout::Section_list& sections,
65 const Layout::Data_list& special_outputs)
67 for(Layout::Section_list::const_iterator p = sections.begin();
68 p != sections.end();
69 ++p)
70 gold_assert((*p)->address_and_file_offset_have_reset_values());
72 for(Layout::Data_list::const_iterator p = special_outputs.begin();
73 p != special_outputs.end();
74 ++p)
75 gold_assert((*p)->address_and_file_offset_have_reset_values());
78 // Save information of SECTIONS for checking later.
80 void
81 Layout::Relaxation_debug_check::read_sections(
82 const Layout::Section_list& sections)
84 for(Layout::Section_list::const_iterator p = sections.begin();
85 p != sections.end();
86 ++p)
88 Output_section* os = *p;
89 Section_info info;
90 info.output_section = os;
91 info.address = os->is_address_valid() ? os->address() : 0;
92 info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
93 info.offset = os->is_offset_valid()? os->offset() : -1 ;
94 this->section_infos_.push_back(info);
98 // Verify SECTIONS using previously recorded information.
100 void
101 Layout::Relaxation_debug_check::verify_sections(
102 const Layout::Section_list& sections)
104 size_t i = 0;
105 for(Layout::Section_list::const_iterator p = sections.begin();
106 p != sections.end();
107 ++p, ++i)
109 Output_section* os = *p;
110 uint64_t address = os->is_address_valid() ? os->address() : 0;
111 off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
112 off_t offset = os->is_offset_valid()? os->offset() : -1 ;
114 if (i >= this->section_infos_.size())
116 gold_fatal("Section_info of %s missing.\n", os->name());
118 const Section_info& info = this->section_infos_[i];
119 if (os != info.output_section)
120 gold_fatal("Section order changed. Expecting %s but see %s\n",
121 info.output_section->name(), os->name());
122 if (address != info.address
123 || data_size != info.data_size
124 || offset != info.offset)
125 gold_fatal("Section %s changed.\n", os->name());
129 // Layout_task_runner methods.
131 // Lay out the sections. This is called after all the input objects
132 // have been read.
134 void
135 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
137 off_t file_size = this->layout_->finalize(this->input_objects_,
138 this->symtab_,
139 this->target_,
140 task);
142 // Now we know the final size of the output file and we know where
143 // each piece of information goes.
145 if (this->mapfile_ != NULL)
147 this->mapfile_->print_discarded_sections(this->input_objects_);
148 this->layout_->print_to_mapfile(this->mapfile_);
151 Output_file* of = new Output_file(parameters->options().output_file_name());
152 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
153 of->set_is_temporary();
154 of->open(file_size);
156 // Queue up the final set of tasks.
157 gold::queue_final_tasks(this->options_, this->input_objects_,
158 this->symtab_, this->layout_, workqueue, of);
161 // Layout methods.
163 Layout::Layout(int number_of_input_files, Script_options* script_options)
164 : number_of_input_files_(number_of_input_files),
165 script_options_(script_options),
166 namepool_(),
167 sympool_(),
168 dynpool_(),
169 signatures_(),
170 section_name_map_(),
171 segment_list_(),
172 section_list_(),
173 unattached_section_list_(),
174 special_output_list_(),
175 section_headers_(NULL),
176 tls_segment_(NULL),
177 relro_segment_(NULL),
178 increase_relro_(0),
179 symtab_section_(NULL),
180 symtab_xindex_(NULL),
181 dynsym_section_(NULL),
182 dynsym_xindex_(NULL),
183 dynamic_section_(NULL),
184 dynamic_symbol_(NULL),
185 dynamic_data_(NULL),
186 eh_frame_section_(NULL),
187 eh_frame_data_(NULL),
188 added_eh_frame_data_(false),
189 eh_frame_hdr_section_(NULL),
190 build_id_note_(NULL),
191 debug_abbrev_(NULL),
192 debug_info_(NULL),
193 group_signatures_(),
194 output_file_size_(-1),
195 have_added_input_section_(false),
196 sections_are_attached_(false),
197 input_requires_executable_stack_(false),
198 input_with_gnu_stack_note_(false),
199 input_without_gnu_stack_note_(false),
200 has_static_tls_(false),
201 any_postprocessing_sections_(false),
202 resized_signatures_(false),
203 have_stabstr_section_(false),
204 incremental_inputs_(NULL),
205 record_output_section_data_from_script_(false),
206 script_output_section_data_list_(),
207 segment_states_(NULL),
208 relaxation_debug_check_(NULL)
210 // Make space for more than enough segments for a typical file.
211 // This is just for efficiency--it's OK if we wind up needing more.
212 this->segment_list_.reserve(12);
214 // We expect two unattached Output_data objects: the file header and
215 // the segment headers.
216 this->special_output_list_.reserve(2);
218 // Initialize structure needed for an incremental build.
219 if (parameters->options().incremental())
220 this->incremental_inputs_ = new Incremental_inputs;
222 // The section name pool is worth optimizing in all cases, because
223 // it is small, but there are often overlaps due to .rel sections.
224 this->namepool_.set_optimize();
227 // Hash a key we use to look up an output section mapping.
229 size_t
230 Layout::Hash_key::operator()(const Layout::Key& k) const
232 return k.first + k.second.first + k.second.second;
235 // Returns whether the given section is in the list of
236 // debug-sections-used-by-some-version-of-gdb. Currently,
237 // we've checked versions of gdb up to and including 6.7.1.
239 static const char* gdb_sections[] =
240 { ".debug_abbrev",
241 // ".debug_aranges", // not used by gdb as of 6.7.1
242 ".debug_frame",
243 ".debug_info",
244 ".debug_line",
245 ".debug_loc",
246 ".debug_macinfo",
247 // ".debug_pubnames", // not used by gdb as of 6.7.1
248 ".debug_ranges",
249 ".debug_str",
252 static const char* lines_only_debug_sections[] =
253 { ".debug_abbrev",
254 // ".debug_aranges", // not used by gdb as of 6.7.1
255 // ".debug_frame",
256 ".debug_info",
257 ".debug_line",
258 // ".debug_loc",
259 // ".debug_macinfo",
260 // ".debug_pubnames", // not used by gdb as of 6.7.1
261 // ".debug_ranges",
262 ".debug_str",
265 static inline bool
266 is_gdb_debug_section(const char* str)
268 // We can do this faster: binary search or a hashtable. But why bother?
269 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
270 if (strcmp(str, gdb_sections[i]) == 0)
271 return true;
272 return false;
275 static inline bool
276 is_lines_only_debug_section(const char* str)
278 // We can do this faster: binary search or a hashtable. But why bother?
279 for (size_t i = 0;
280 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
281 ++i)
282 if (strcmp(str, lines_only_debug_sections[i]) == 0)
283 return true;
284 return false;
287 // Whether to include this section in the link.
289 template<int size, bool big_endian>
290 bool
291 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
292 const elfcpp::Shdr<size, big_endian>& shdr)
294 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
295 return false;
297 switch (shdr.get_sh_type())
299 case elfcpp::SHT_NULL:
300 case elfcpp::SHT_SYMTAB:
301 case elfcpp::SHT_DYNSYM:
302 case elfcpp::SHT_HASH:
303 case elfcpp::SHT_DYNAMIC:
304 case elfcpp::SHT_SYMTAB_SHNDX:
305 return false;
307 case elfcpp::SHT_STRTAB:
308 // Discard the sections which have special meanings in the ELF
309 // ABI. Keep others (e.g., .stabstr). We could also do this by
310 // checking the sh_link fields of the appropriate sections.
311 return (strcmp(name, ".dynstr") != 0
312 && strcmp(name, ".strtab") != 0
313 && strcmp(name, ".shstrtab") != 0);
315 case elfcpp::SHT_RELA:
316 case elfcpp::SHT_REL:
317 case elfcpp::SHT_GROUP:
318 // If we are emitting relocations these should be handled
319 // elsewhere.
320 gold_assert(!parameters->options().relocatable()
321 && !parameters->options().emit_relocs());
322 return false;
324 case elfcpp::SHT_PROGBITS:
325 if (parameters->options().strip_debug()
326 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
328 if (is_debug_info_section(name))
329 return false;
331 if (parameters->options().strip_debug_non_line()
332 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
334 // Debugging sections can only be recognized by name.
335 if (is_prefix_of(".debug", name)
336 && !is_lines_only_debug_section(name))
337 return false;
339 if (parameters->options().strip_debug_gdb()
340 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
342 // Debugging sections can only be recognized by name.
343 if (is_prefix_of(".debug", name)
344 && !is_gdb_debug_section(name))
345 return false;
347 if (parameters->options().strip_lto_sections()
348 && !parameters->options().relocatable()
349 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
351 // Ignore LTO sections containing intermediate code.
352 if (is_prefix_of(".gnu.lto_", name))
353 return false;
355 // The GNU linker strips .gnu_debuglink sections, so we do too.
356 // This is a feature used to keep debugging information in
357 // separate files.
358 if (strcmp(name, ".gnu_debuglink") == 0)
359 return false;
360 return true;
362 default:
363 return true;
367 // Return an output section named NAME, or NULL if there is none.
369 Output_section*
370 Layout::find_output_section(const char* name) const
372 for (Section_list::const_iterator p = this->section_list_.begin();
373 p != this->section_list_.end();
374 ++p)
375 if (strcmp((*p)->name(), name) == 0)
376 return *p;
377 return NULL;
380 // Return an output segment of type TYPE, with segment flags SET set
381 // and segment flags CLEAR clear. Return NULL if there is none.
383 Output_segment*
384 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
385 elfcpp::Elf_Word clear) const
387 for (Segment_list::const_iterator p = this->segment_list_.begin();
388 p != this->segment_list_.end();
389 ++p)
390 if (static_cast<elfcpp::PT>((*p)->type()) == type
391 && ((*p)->flags() & set) == set
392 && ((*p)->flags() & clear) == 0)
393 return *p;
394 return NULL;
397 // Return the output section to use for section NAME with type TYPE
398 // and section flags FLAGS. NAME must be canonicalized in the string
399 // pool, and NAME_KEY is the key. IS_INTERP is true if this is the
400 // .interp section. IS_DYNAMIC_LINKER_SECTION is true if this section
401 // is used by the dynamic linker. IS_RELRO is true for a relro
402 // section. IS_LAST_RELRO is true for the last relro section.
403 // IS_FIRST_NON_RELRO is true for the first non-relro section.
405 Output_section*
406 Layout::get_output_section(const char* name, Stringpool::Key name_key,
407 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
408 bool is_interp, bool is_dynamic_linker_section,
409 bool is_relro, bool is_last_relro,
410 bool is_first_non_relro)
412 elfcpp::Elf_Xword lookup_flags = flags;
414 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
415 // read-write with read-only sections. Some other ELF linkers do
416 // not do this. FIXME: Perhaps there should be an option
417 // controlling this.
418 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
420 const Key key(name_key, std::make_pair(type, lookup_flags));
421 const std::pair<Key, Output_section*> v(key, NULL);
422 std::pair<Section_name_map::iterator, bool> ins(
423 this->section_name_map_.insert(v));
425 if (!ins.second)
426 return ins.first->second;
427 else
429 // This is the first time we've seen this name/type/flags
430 // combination. For compatibility with the GNU linker, we
431 // combine sections with contents and zero flags with sections
432 // with non-zero flags. This is a workaround for cases where
433 // assembler code forgets to set section flags. FIXME: Perhaps
434 // there should be an option to control this.
435 Output_section* os = NULL;
437 if (type == elfcpp::SHT_PROGBITS)
439 if (flags == 0)
441 Output_section* same_name = this->find_output_section(name);
442 if (same_name != NULL
443 && same_name->type() == elfcpp::SHT_PROGBITS
444 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
445 os = same_name;
447 else if ((flags & elfcpp::SHF_TLS) == 0)
449 elfcpp::Elf_Xword zero_flags = 0;
450 const Key zero_key(name_key, std::make_pair(type, zero_flags));
451 Section_name_map::iterator p =
452 this->section_name_map_.find(zero_key);
453 if (p != this->section_name_map_.end())
454 os = p->second;
458 if (os == NULL)
459 os = this->make_output_section(name, type, flags, is_interp,
460 is_dynamic_linker_section, is_relro,
461 is_last_relro, is_first_non_relro);
462 ins.first->second = os;
463 return os;
467 // Pick the output section to use for section NAME, in input file
468 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
469 // linker created section. IS_INPUT_SECTION is true if we are
470 // choosing an output section for an input section found in a input
471 // file. IS_INTERP is true if this is the .interp section.
472 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
473 // dynamic linker. IS_RELRO is true for a relro section.
474 // IS_LAST_RELRO is true for the last relro section.
475 // IS_FIRST_NON_RELRO is true for the first non-relro section. This
476 // will return NULL if the input section should be discarded.
478 Output_section*
479 Layout::choose_output_section(const Relobj* relobj, const char* name,
480 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
481 bool is_input_section, bool is_interp,
482 bool is_dynamic_linker_section, bool is_relro,
483 bool is_last_relro, bool is_first_non_relro)
485 // We should not see any input sections after we have attached
486 // sections to segments.
487 gold_assert(!is_input_section || !this->sections_are_attached_);
489 // Some flags in the input section should not be automatically
490 // copied to the output section.
491 flags &= ~ (elfcpp::SHF_INFO_LINK
492 | elfcpp::SHF_LINK_ORDER
493 | elfcpp::SHF_GROUP
494 | elfcpp::SHF_MERGE
495 | elfcpp::SHF_STRINGS);
497 if (this->script_options_->saw_sections_clause())
499 // We are using a SECTIONS clause, so the output section is
500 // chosen based only on the name.
502 Script_sections* ss = this->script_options_->script_sections();
503 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
504 Output_section** output_section_slot;
505 name = ss->output_section_name(file_name, name, &output_section_slot);
506 if (name == NULL)
508 // The SECTIONS clause says to discard this input section.
509 return NULL;
512 // If this is an orphan section--one not mentioned in the linker
513 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
514 // default processing below.
516 if (output_section_slot != NULL)
518 if (*output_section_slot != NULL)
520 (*output_section_slot)->update_flags_for_input_section(flags);
521 return *output_section_slot;
524 // We don't put sections found in the linker script into
525 // SECTION_NAME_MAP_. That keeps us from getting confused
526 // if an orphan section is mapped to a section with the same
527 // name as one in the linker script.
529 name = this->namepool_.add(name, false, NULL);
531 Output_section* os =
532 this->make_output_section(name, type, flags, is_interp,
533 is_dynamic_linker_section, is_relro,
534 is_last_relro, is_first_non_relro);
535 os->set_found_in_sections_clause();
536 *output_section_slot = os;
537 return os;
541 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
543 // Turn NAME from the name of the input section into the name of the
544 // output section.
546 size_t len = strlen(name);
547 if (is_input_section
548 && !this->script_options_->saw_sections_clause()
549 && !parameters->options().relocatable())
550 name = Layout::output_section_name(name, &len);
552 Stringpool::Key name_key;
553 name = this->namepool_.add_with_length(name, len, true, &name_key);
555 // Find or make the output section. The output section is selected
556 // based on the section name, type, and flags.
557 return this->get_output_section(name, name_key, type, flags, is_interp,
558 is_dynamic_linker_section, is_relro,
559 is_last_relro, is_first_non_relro);
562 // Return the output section to use for input section SHNDX, with name
563 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
564 // index of a relocation section which applies to this section, or 0
565 // if none, or -1U if more than one. RELOC_TYPE is the type of the
566 // relocation section if there is one. Set *OFF to the offset of this
567 // input section without the output section. Return NULL if the
568 // section should be discarded. Set *OFF to -1 if the section
569 // contents should not be written directly to the output file, but
570 // will instead receive special handling.
572 template<int size, bool big_endian>
573 Output_section*
574 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
575 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
576 unsigned int reloc_shndx, unsigned int, off_t* off)
578 *off = 0;
580 if (!this->include_section(object, name, shdr))
581 return NULL;
583 Output_section* os;
585 // Sometimes .init_array*, .preinit_array* and .fini_array* do not have
586 // correct section types. Force them here.
587 elfcpp::Elf_Word sh_type = shdr.get_sh_type();
588 if (sh_type == elfcpp::SHT_PROGBITS)
590 static const char init_array_prefix[] = ".init_array";
591 static const char preinit_array_prefix[] = ".preinit_array";
592 static const char fini_array_prefix[] = ".fini_array";
593 static size_t init_array_prefix_size = sizeof(init_array_prefix) - 1;
594 static size_t preinit_array_prefix_size =
595 sizeof(preinit_array_prefix) - 1;
596 static size_t fini_array_prefix_size = sizeof(fini_array_prefix) - 1;
598 if (strncmp(name, init_array_prefix, init_array_prefix_size) == 0)
599 sh_type = elfcpp::SHT_INIT_ARRAY;
600 else if (strncmp(name, preinit_array_prefix, preinit_array_prefix_size)
601 == 0)
602 sh_type = elfcpp::SHT_PREINIT_ARRAY;
603 else if (strncmp(name, fini_array_prefix, fini_array_prefix_size) == 0)
604 sh_type = elfcpp::SHT_FINI_ARRAY;
607 // In a relocatable link a grouped section must not be combined with
608 // any other sections.
609 if (parameters->options().relocatable()
610 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
612 name = this->namepool_.add(name, true, NULL);
613 os = this->make_output_section(name, sh_type, shdr.get_sh_flags(), false,
614 false, false, false, false);
616 else
618 os = this->choose_output_section(object, name, sh_type,
619 shdr.get_sh_flags(), true, false,
620 false, false, false, false);
621 if (os == NULL)
622 return NULL;
625 // By default the GNU linker sorts input sections whose names match
626 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
627 // are sorted by name. This is used to implement constructor
628 // priority ordering. We are compatible.
629 if (!this->script_options_->saw_sections_clause()
630 && (is_prefix_of(".ctors.", name)
631 || is_prefix_of(".dtors.", name)
632 || is_prefix_of(".init_array.", name)
633 || is_prefix_of(".fini_array.", name)))
634 os->set_must_sort_attached_input_sections();
636 // FIXME: Handle SHF_LINK_ORDER somewhere.
638 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
639 this->script_options_->saw_sections_clause());
640 this->have_added_input_section_ = true;
642 return os;
645 // Handle a relocation section when doing a relocatable link.
647 template<int size, bool big_endian>
648 Output_section*
649 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
650 unsigned int,
651 const elfcpp::Shdr<size, big_endian>& shdr,
652 Output_section* data_section,
653 Relocatable_relocs* rr)
655 gold_assert(parameters->options().relocatable()
656 || parameters->options().emit_relocs());
658 int sh_type = shdr.get_sh_type();
660 std::string name;
661 if (sh_type == elfcpp::SHT_REL)
662 name = ".rel";
663 else if (sh_type == elfcpp::SHT_RELA)
664 name = ".rela";
665 else
666 gold_unreachable();
667 name += data_section->name();
669 Output_section* os = this->choose_output_section(object, name.c_str(),
670 sh_type,
671 shdr.get_sh_flags(),
672 false, false, false,
673 false, false, false);
675 os->set_should_link_to_symtab();
676 os->set_info_section(data_section);
678 Output_section_data* posd;
679 if (sh_type == elfcpp::SHT_REL)
681 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
682 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
683 size,
684 big_endian>(rr);
686 else if (sh_type == elfcpp::SHT_RELA)
688 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
689 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
690 size,
691 big_endian>(rr);
693 else
694 gold_unreachable();
696 os->add_output_section_data(posd);
697 rr->set_output_data(posd);
699 return os;
702 // Handle a group section when doing a relocatable link.
704 template<int size, bool big_endian>
705 void
706 Layout::layout_group(Symbol_table* symtab,
707 Sized_relobj<size, big_endian>* object,
708 unsigned int,
709 const char* group_section_name,
710 const char* signature,
711 const elfcpp::Shdr<size, big_endian>& shdr,
712 elfcpp::Elf_Word flags,
713 std::vector<unsigned int>* shndxes)
715 gold_assert(parameters->options().relocatable());
716 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
717 group_section_name = this->namepool_.add(group_section_name, true, NULL);
718 Output_section* os = this->make_output_section(group_section_name,
719 elfcpp::SHT_GROUP,
720 shdr.get_sh_flags(),
721 false, false, false,
722 false, false);
724 // We need to find a symbol with the signature in the symbol table.
725 // If we don't find one now, we need to look again later.
726 Symbol* sym = symtab->lookup(signature, NULL);
727 if (sym != NULL)
728 os->set_info_symndx(sym);
729 else
731 // Reserve some space to minimize reallocations.
732 if (this->group_signatures_.empty())
733 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
735 // We will wind up using a symbol whose name is the signature.
736 // So just put the signature in the symbol name pool to save it.
737 signature = symtab->canonicalize_name(signature);
738 this->group_signatures_.push_back(Group_signature(os, signature));
741 os->set_should_link_to_symtab();
742 os->set_entsize(4);
744 section_size_type entry_count =
745 convert_to_section_size_type(shdr.get_sh_size() / 4);
746 Output_section_data* posd =
747 new Output_data_group<size, big_endian>(object, entry_count, flags,
748 shndxes);
749 os->add_output_section_data(posd);
752 // Special GNU handling of sections name .eh_frame. They will
753 // normally hold exception frame data as defined by the C++ ABI
754 // (http://codesourcery.com/cxx-abi/).
756 template<int size, bool big_endian>
757 Output_section*
758 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
759 const unsigned char* symbols,
760 off_t symbols_size,
761 const unsigned char* symbol_names,
762 off_t symbol_names_size,
763 unsigned int shndx,
764 const elfcpp::Shdr<size, big_endian>& shdr,
765 unsigned int reloc_shndx, unsigned int reloc_type,
766 off_t* off)
768 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
769 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
771 const char* const name = ".eh_frame";
772 Output_section* os = this->choose_output_section(object,
773 name,
774 elfcpp::SHT_PROGBITS,
775 elfcpp::SHF_ALLOC,
776 false, false, false,
777 false, false, false);
778 if (os == NULL)
779 return NULL;
781 if (this->eh_frame_section_ == NULL)
783 this->eh_frame_section_ = os;
784 this->eh_frame_data_ = new Eh_frame();
786 if (parameters->options().eh_frame_hdr())
788 Output_section* hdr_os =
789 this->choose_output_section(NULL,
790 ".eh_frame_hdr",
791 elfcpp::SHT_PROGBITS,
792 elfcpp::SHF_ALLOC,
793 false, false, false,
794 false, false, false);
796 if (hdr_os != NULL)
798 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
799 this->eh_frame_data_);
800 hdr_os->add_output_section_data(hdr_posd);
802 hdr_os->set_after_input_sections();
804 if (!this->script_options_->saw_phdrs_clause())
806 Output_segment* hdr_oseg;
807 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
808 elfcpp::PF_R);
809 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R, false);
812 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
817 gold_assert(this->eh_frame_section_ == os);
819 if (this->eh_frame_data_->add_ehframe_input_section(object,
820 symbols,
821 symbols_size,
822 symbol_names,
823 symbol_names_size,
824 shndx,
825 reloc_shndx,
826 reloc_type))
828 os->update_flags_for_input_section(shdr.get_sh_flags());
830 // We found a .eh_frame section we are going to optimize, so now
831 // we can add the set of optimized sections to the output
832 // section. We need to postpone adding this until we've found a
833 // section we can optimize so that the .eh_frame section in
834 // crtbegin.o winds up at the start of the output section.
835 if (!this->added_eh_frame_data_)
837 os->add_output_section_data(this->eh_frame_data_);
838 this->added_eh_frame_data_ = true;
840 *off = -1;
842 else
844 // We couldn't handle this .eh_frame section for some reason.
845 // Add it as a normal section.
846 bool saw_sections_clause = this->script_options_->saw_sections_clause();
847 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
848 saw_sections_clause);
849 this->have_added_input_section_ = true;
852 return os;
855 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
856 // the output section.
858 Output_section*
859 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
860 elfcpp::Elf_Xword flags,
861 Output_section_data* posd,
862 bool is_dynamic_linker_section,
863 bool is_relro, bool is_last_relro,
864 bool is_first_non_relro)
866 Output_section* os = this->choose_output_section(NULL, name, type, flags,
867 false, false,
868 is_dynamic_linker_section,
869 is_relro, is_last_relro,
870 is_first_non_relro);
871 if (os != NULL)
872 os->add_output_section_data(posd);
873 return os;
876 // Map section flags to segment flags.
878 elfcpp::Elf_Word
879 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
881 elfcpp::Elf_Word ret = elfcpp::PF_R;
882 if ((flags & elfcpp::SHF_WRITE) != 0)
883 ret |= elfcpp::PF_W;
884 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
885 ret |= elfcpp::PF_X;
886 return ret;
889 // Sometimes we compress sections. This is typically done for
890 // sections that are not part of normal program execution (such as
891 // .debug_* sections), and where the readers of these sections know
892 // how to deal with compressed sections. This routine doesn't say for
893 // certain whether we'll compress -- it depends on commandline options
894 // as well -- just whether this section is a candidate for compression.
895 // (The Output_compressed_section class decides whether to compress
896 // a given section, and picks the name of the compressed section.)
898 static bool
899 is_compressible_debug_section(const char* secname)
901 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
904 // Make a new Output_section, and attach it to segments as
905 // appropriate. IS_INTERP is true if this is the .interp section.
906 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
907 // dynamic linker. IS_RELRO is true if this is a relro section.
908 // IS_LAST_RELRO is true if this is the last relro section.
909 // IS_FIRST_NON_RELRO is true if this is the first non relro section.
911 Output_section*
912 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
913 elfcpp::Elf_Xword flags, bool is_interp,
914 bool is_dynamic_linker_section, bool is_relro,
915 bool is_last_relro, bool is_first_non_relro)
917 Output_section* os;
918 if ((flags & elfcpp::SHF_ALLOC) == 0
919 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
920 && is_compressible_debug_section(name))
921 os = new Output_compressed_section(&parameters->options(), name, type,
922 flags);
923 else if ((flags & elfcpp::SHF_ALLOC) == 0
924 && parameters->options().strip_debug_non_line()
925 && strcmp(".debug_abbrev", name) == 0)
927 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
928 name, type, flags);
929 if (this->debug_info_)
930 this->debug_info_->set_abbreviations(this->debug_abbrev_);
932 else if ((flags & elfcpp::SHF_ALLOC) == 0
933 && parameters->options().strip_debug_non_line()
934 && strcmp(".debug_info", name) == 0)
936 os = this->debug_info_ = new Output_reduced_debug_info_section(
937 name, type, flags);
938 if (this->debug_abbrev_)
939 this->debug_info_->set_abbreviations(this->debug_abbrev_);
941 else
943 // FIXME: const_cast is ugly.
944 Target* target = const_cast<Target*>(&parameters->target());
945 os = target->make_output_section(name, type, flags);
948 if (is_interp)
949 os->set_is_interp();
950 if (is_dynamic_linker_section)
951 os->set_is_dynamic_linker_section();
952 if (is_relro)
953 os->set_is_relro();
954 if (is_last_relro)
955 os->set_is_last_relro();
956 if (is_first_non_relro)
957 os->set_is_first_non_relro();
959 parameters->target().new_output_section(os);
961 this->section_list_.push_back(os);
963 // The GNU linker by default sorts some sections by priority, so we
964 // do the same. We need to know that this might happen before we
965 // attach any input sections.
966 if (!this->script_options_->saw_sections_clause()
967 && (strcmp(name, ".ctors") == 0
968 || strcmp(name, ".dtors") == 0
969 || strcmp(name, ".init_array") == 0
970 || strcmp(name, ".fini_array") == 0))
971 os->set_may_sort_attached_input_sections();
973 // With -z relro, we have to recognize the special sections by name.
974 // There is no other way.
975 if (!this->script_options_->saw_sections_clause()
976 && parameters->options().relro()
977 && type == elfcpp::SHT_PROGBITS
978 && (flags & elfcpp::SHF_ALLOC) != 0
979 && (flags & elfcpp::SHF_WRITE) != 0)
981 if (strcmp(name, ".data.rel.ro") == 0)
982 os->set_is_relro();
983 else if (strcmp(name, ".data.rel.ro.local") == 0)
985 os->set_is_relro();
986 os->set_is_relro_local();
990 // Check for .stab*str sections, as .stab* sections need to link to
991 // them.
992 if (type == elfcpp::SHT_STRTAB
993 && !this->have_stabstr_section_
994 && strncmp(name, ".stab", 5) == 0
995 && strcmp(name + strlen(name) - 3, "str") == 0)
996 this->have_stabstr_section_ = true;
998 // If we have already attached the sections to segments, then we
999 // need to attach this one now. This happens for sections created
1000 // directly by the linker.
1001 if (this->sections_are_attached_)
1002 this->attach_section_to_segment(os);
1004 return os;
1007 // Attach output sections to segments. This is called after we have
1008 // seen all the input sections.
1010 void
1011 Layout::attach_sections_to_segments()
1013 for (Section_list::iterator p = this->section_list_.begin();
1014 p != this->section_list_.end();
1015 ++p)
1016 this->attach_section_to_segment(*p);
1018 this->sections_are_attached_ = true;
1021 // Attach an output section to a segment.
1023 void
1024 Layout::attach_section_to_segment(Output_section* os)
1026 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1027 this->unattached_section_list_.push_back(os);
1028 else
1029 this->attach_allocated_section_to_segment(os);
1032 // Attach an allocated output section to a segment.
1034 void
1035 Layout::attach_allocated_section_to_segment(Output_section* os)
1037 elfcpp::Elf_Xword flags = os->flags();
1038 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
1040 if (parameters->options().relocatable())
1041 return;
1043 // If we have a SECTIONS clause, we can't handle the attachment to
1044 // segments until after we've seen all the sections.
1045 if (this->script_options_->saw_sections_clause())
1046 return;
1048 gold_assert(!this->script_options_->saw_phdrs_clause());
1050 // This output section goes into a PT_LOAD segment.
1052 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
1054 // Check for --section-start.
1055 uint64_t addr;
1056 bool is_address_set = parameters->options().section_start(os->name(), &addr);
1058 // In general the only thing we really care about for PT_LOAD
1059 // segments is whether or not they are writable, so that is how we
1060 // search for them. Large data sections also go into their own
1061 // PT_LOAD segment. People who need segments sorted on some other
1062 // basis will have to use a linker script.
1064 Segment_list::const_iterator p;
1065 for (p = this->segment_list_.begin();
1066 p != this->segment_list_.end();
1067 ++p)
1069 if ((*p)->type() != elfcpp::PT_LOAD)
1070 continue;
1071 if (!parameters->options().omagic()
1072 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1073 continue;
1074 // If -Tbss was specified, we need to separate the data and BSS
1075 // segments.
1076 if (parameters->options().user_set_Tbss())
1078 if ((os->type() == elfcpp::SHT_NOBITS)
1079 == (*p)->has_any_data_sections())
1080 continue;
1082 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1083 continue;
1085 if (is_address_set)
1087 if ((*p)->are_addresses_set())
1088 continue;
1090 (*p)->add_initial_output_data(os);
1091 (*p)->update_flags_for_output_section(seg_flags);
1092 (*p)->set_addresses(addr, addr);
1093 break;
1096 (*p)->add_output_section(os, seg_flags, true);
1097 break;
1100 if (p == this->segment_list_.end())
1102 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1103 seg_flags);
1104 if (os->is_large_data_section())
1105 oseg->set_is_large_data_segment();
1106 oseg->add_output_section(os, seg_flags, true);
1107 if (is_address_set)
1108 oseg->set_addresses(addr, addr);
1111 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1112 // segment.
1113 if (os->type() == elfcpp::SHT_NOTE)
1115 // See if we already have an equivalent PT_NOTE segment.
1116 for (p = this->segment_list_.begin();
1117 p != segment_list_.end();
1118 ++p)
1120 if ((*p)->type() == elfcpp::PT_NOTE
1121 && (((*p)->flags() & elfcpp::PF_W)
1122 == (seg_flags & elfcpp::PF_W)))
1124 (*p)->add_output_section(os, seg_flags, false);
1125 break;
1129 if (p == this->segment_list_.end())
1131 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1132 seg_flags);
1133 oseg->add_output_section(os, seg_flags, false);
1137 // If we see a loadable SHF_TLS section, we create a PT_TLS
1138 // segment. There can only be one such segment.
1139 if ((flags & elfcpp::SHF_TLS) != 0)
1141 if (this->tls_segment_ == NULL)
1142 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1143 this->tls_segment_->add_output_section(os, seg_flags, false);
1146 // If -z relro is in effect, and we see a relro section, we create a
1147 // PT_GNU_RELRO segment. There can only be one such segment.
1148 if (os->is_relro() && parameters->options().relro())
1150 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1151 if (this->relro_segment_ == NULL)
1152 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1153 this->relro_segment_->add_output_section(os, seg_flags, false);
1157 // Make an output section for a script.
1159 Output_section*
1160 Layout::make_output_section_for_script(const char* name)
1162 name = this->namepool_.add(name, false, NULL);
1163 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1164 elfcpp::SHF_ALLOC, false,
1165 false, false, false, false);
1166 os->set_found_in_sections_clause();
1167 return os;
1170 // Return the number of segments we expect to see.
1172 size_t
1173 Layout::expected_segment_count() const
1175 size_t ret = this->segment_list_.size();
1177 // If we didn't see a SECTIONS clause in a linker script, we should
1178 // already have the complete list of segments. Otherwise we ask the
1179 // SECTIONS clause how many segments it expects, and add in the ones
1180 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1182 if (!this->script_options_->saw_sections_clause())
1183 return ret;
1184 else
1186 const Script_sections* ss = this->script_options_->script_sections();
1187 return ret + ss->expected_segment_count(this);
1191 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1192 // is whether we saw a .note.GNU-stack section in the object file.
1193 // GNU_STACK_FLAGS is the section flags. The flags give the
1194 // protection required for stack memory. We record this in an
1195 // executable as a PT_GNU_STACK segment. If an object file does not
1196 // have a .note.GNU-stack segment, we must assume that it is an old
1197 // object. On some targets that will force an executable stack.
1199 void
1200 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1202 if (!seen_gnu_stack)
1203 this->input_without_gnu_stack_note_ = true;
1204 else
1206 this->input_with_gnu_stack_note_ = true;
1207 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1208 this->input_requires_executable_stack_ = true;
1212 // Create automatic note sections.
1214 void
1215 Layout::create_notes()
1217 this->create_gold_note();
1218 this->create_executable_stack_info();
1219 this->create_build_id();
1222 // Create the dynamic sections which are needed before we read the
1223 // relocs.
1225 void
1226 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1228 if (parameters->doing_static_link())
1229 return;
1231 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1232 elfcpp::SHT_DYNAMIC,
1233 (elfcpp::SHF_ALLOC
1234 | elfcpp::SHF_WRITE),
1235 false, false, true,
1236 true, false, false);
1238 this->dynamic_symbol_ =
1239 symtab->define_in_output_data("_DYNAMIC", NULL, Symbol_table::PREDEFINED,
1240 this->dynamic_section_, 0, 0,
1241 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1242 elfcpp::STV_HIDDEN, 0, false, false);
1244 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1246 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1249 // For each output section whose name can be represented as C symbol,
1250 // define __start and __stop symbols for the section. This is a GNU
1251 // extension.
1253 void
1254 Layout::define_section_symbols(Symbol_table* symtab)
1256 for (Section_list::const_iterator p = this->section_list_.begin();
1257 p != this->section_list_.end();
1258 ++p)
1260 const char* const name = (*p)->name();
1261 if (is_cident(name))
1263 const std::string name_string(name);
1264 const std::string start_name(cident_section_start_prefix
1265 + name_string);
1266 const std::string stop_name(cident_section_stop_prefix
1267 + name_string);
1269 symtab->define_in_output_data(start_name.c_str(),
1270 NULL, // version
1271 Symbol_table::PREDEFINED,
1273 0, // value
1274 0, // symsize
1275 elfcpp::STT_NOTYPE,
1276 elfcpp::STB_GLOBAL,
1277 elfcpp::STV_DEFAULT,
1278 0, // nonvis
1279 false, // offset_is_from_end
1280 true); // only_if_ref
1282 symtab->define_in_output_data(stop_name.c_str(),
1283 NULL, // version
1284 Symbol_table::PREDEFINED,
1286 0, // value
1287 0, // symsize
1288 elfcpp::STT_NOTYPE,
1289 elfcpp::STB_GLOBAL,
1290 elfcpp::STV_DEFAULT,
1291 0, // nonvis
1292 true, // offset_is_from_end
1293 true); // only_if_ref
1298 // Define symbols for group signatures.
1300 void
1301 Layout::define_group_signatures(Symbol_table* symtab)
1303 for (Group_signatures::iterator p = this->group_signatures_.begin();
1304 p != this->group_signatures_.end();
1305 ++p)
1307 Symbol* sym = symtab->lookup(p->signature, NULL);
1308 if (sym != NULL)
1309 p->section->set_info_symndx(sym);
1310 else
1312 // Force the name of the group section to the group
1313 // signature, and use the group's section symbol as the
1314 // signature symbol.
1315 if (strcmp(p->section->name(), p->signature) != 0)
1317 const char* name = this->namepool_.add(p->signature,
1318 true, NULL);
1319 p->section->set_name(name);
1321 p->section->set_needs_symtab_index();
1322 p->section->set_info_section_symndx(p->section);
1326 this->group_signatures_.clear();
1329 // Find the first read-only PT_LOAD segment, creating one if
1330 // necessary.
1332 Output_segment*
1333 Layout::find_first_load_seg()
1335 for (Segment_list::const_iterator p = this->segment_list_.begin();
1336 p != this->segment_list_.end();
1337 ++p)
1339 if ((*p)->type() == elfcpp::PT_LOAD
1340 && ((*p)->flags() & elfcpp::PF_R) != 0
1341 && (parameters->options().omagic()
1342 || ((*p)->flags() & elfcpp::PF_W) == 0))
1343 return *p;
1346 gold_assert(!this->script_options_->saw_phdrs_clause());
1348 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1349 elfcpp::PF_R);
1350 return load_seg;
1353 // Save states of all current output segments. Store saved states
1354 // in SEGMENT_STATES.
1356 void
1357 Layout::save_segments(Segment_states* segment_states)
1359 for (Segment_list::const_iterator p = this->segment_list_.begin();
1360 p != this->segment_list_.end();
1361 ++p)
1363 Output_segment* segment = *p;
1364 // Shallow copy.
1365 Output_segment* copy = new Output_segment(*segment);
1366 (*segment_states)[segment] = copy;
1370 // Restore states of output segments and delete any segment not found in
1371 // SEGMENT_STATES.
1373 void
1374 Layout::restore_segments(const Segment_states* segment_states)
1376 // Go through the segment list and remove any segment added in the
1377 // relaxation loop.
1378 this->tls_segment_ = NULL;
1379 this->relro_segment_ = NULL;
1380 Segment_list::iterator list_iter = this->segment_list_.begin();
1381 while (list_iter != this->segment_list_.end())
1383 Output_segment* segment = *list_iter;
1384 Segment_states::const_iterator states_iter =
1385 segment_states->find(segment);
1386 if (states_iter != segment_states->end())
1388 const Output_segment* copy = states_iter->second;
1389 // Shallow copy to restore states.
1390 *segment = *copy;
1392 // Also fix up TLS and RELRO segment pointers as appropriate.
1393 if (segment->type() == elfcpp::PT_TLS)
1394 this->tls_segment_ = segment;
1395 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1396 this->relro_segment_ = segment;
1398 ++list_iter;
1400 else
1402 list_iter = this->segment_list_.erase(list_iter);
1403 // This is a segment created during section layout. It should be
1404 // safe to remove it since we should have removed all pointers to it.
1405 delete segment;
1410 // Clean up after relaxation so that sections can be laid out again.
1412 void
1413 Layout::clean_up_after_relaxation()
1415 // Restore the segments to point state just prior to the relaxation loop.
1416 Script_sections* script_section = this->script_options_->script_sections();
1417 script_section->release_segments();
1418 this->restore_segments(this->segment_states_);
1420 // Reset section addresses and file offsets
1421 for (Section_list::iterator p = this->section_list_.begin();
1422 p != this->section_list_.end();
1423 ++p)
1425 (*p)->restore_states();
1427 // If an input section changes size because of relaxation,
1428 // we need to adjust the section offsets of all input sections.
1429 // after such a section.
1430 if ((*p)->section_offsets_need_adjustment())
1431 (*p)->adjust_section_offsets();
1433 (*p)->reset_address_and_file_offset();
1436 // Reset special output object address and file offsets.
1437 for (Data_list::iterator p = this->special_output_list_.begin();
1438 p != this->special_output_list_.end();
1439 ++p)
1440 (*p)->reset_address_and_file_offset();
1442 // A linker script may have created some output section data objects.
1443 // They are useless now.
1444 for (Output_section_data_list::const_iterator p =
1445 this->script_output_section_data_list_.begin();
1446 p != this->script_output_section_data_list_.end();
1447 ++p)
1448 delete *p;
1449 this->script_output_section_data_list_.clear();
1452 // Prepare for relaxation.
1454 void
1455 Layout::prepare_for_relaxation()
1457 // Create an relaxation debug check if in debugging mode.
1458 if (is_debugging_enabled(DEBUG_RELAXATION))
1459 this->relaxation_debug_check_ = new Relaxation_debug_check();
1461 // Save segment states.
1462 this->segment_states_ = new Segment_states();
1463 this->save_segments(this->segment_states_);
1465 for(Section_list::const_iterator p = this->section_list_.begin();
1466 p != this->section_list_.end();
1467 ++p)
1468 (*p)->save_states();
1470 if (is_debugging_enabled(DEBUG_RELAXATION))
1471 this->relaxation_debug_check_->check_output_data_for_reset_values(
1472 this->section_list_, this->special_output_list_);
1474 // Also enable recording of output section data from scripts.
1475 this->record_output_section_data_from_script_ = true;
1478 // Relaxation loop body: If target has no relaxation, this runs only once
1479 // Otherwise, the target relaxation hook is called at the end of
1480 // each iteration. If the hook returns true, it means re-layout of
1481 // section is required.
1483 // The number of segments created by a linking script without a PHDRS
1484 // clause may be affected by section sizes and alignments. There is
1485 // a remote chance that relaxation causes different number of PT_LOAD
1486 // segments are created and sections are attached to different segments.
1487 // Therefore, we always throw away all segments created during section
1488 // layout. In order to be able to restart the section layout, we keep
1489 // a copy of the segment list right before the relaxation loop and use
1490 // that to restore the segments.
1492 // PASS is the current relaxation pass number.
1493 // SYMTAB is a symbol table.
1494 // PLOAD_SEG is the address of a pointer for the load segment.
1495 // PHDR_SEG is a pointer to the PHDR segment.
1496 // SEGMENT_HEADERS points to the output segment header.
1497 // FILE_HEADER points to the output file header.
1498 // PSHNDX is the address to store the output section index.
1500 off_t inline
1501 Layout::relaxation_loop_body(
1502 int pass,
1503 Target* target,
1504 Symbol_table* symtab,
1505 Output_segment** pload_seg,
1506 Output_segment* phdr_seg,
1507 Output_segment_headers* segment_headers,
1508 Output_file_header* file_header,
1509 unsigned int* pshndx)
1511 // If this is not the first iteration, we need to clean up after
1512 // relaxation so that we can lay out the sections again.
1513 if (pass != 0)
1514 this->clean_up_after_relaxation();
1516 // If there is a SECTIONS clause, put all the input sections into
1517 // the required order.
1518 Output_segment* load_seg;
1519 if (this->script_options_->saw_sections_clause())
1520 load_seg = this->set_section_addresses_from_script(symtab);
1521 else if (parameters->options().relocatable())
1522 load_seg = NULL;
1523 else
1524 load_seg = this->find_first_load_seg();
1526 if (parameters->options().oformat_enum()
1527 != General_options::OBJECT_FORMAT_ELF)
1528 load_seg = NULL;
1530 // If the user set the address of the text segment, that may not be
1531 // compatible with putting the segment headers and file headers into
1532 // that segment.
1533 if (parameters->options().user_set_Ttext())
1534 load_seg = NULL;
1536 gold_assert(phdr_seg == NULL
1537 || load_seg != NULL
1538 || this->script_options_->saw_sections_clause());
1540 // If the address of the load segment we found has been set by
1541 // --section-start rather than by a script, then we don't want to
1542 // use it for the file and segment headers.
1543 if (load_seg != NULL
1544 && load_seg->are_addresses_set()
1545 && !this->script_options_->saw_sections_clause())
1546 load_seg = NULL;
1548 // Lay out the segment headers.
1549 if (!parameters->options().relocatable())
1551 gold_assert(segment_headers != NULL);
1552 if (load_seg != NULL)
1553 load_seg->add_initial_output_data(segment_headers);
1554 if (phdr_seg != NULL)
1555 phdr_seg->add_initial_output_data(segment_headers);
1558 // Lay out the file header.
1559 if (load_seg != NULL)
1560 load_seg->add_initial_output_data(file_header);
1562 if (this->script_options_->saw_phdrs_clause()
1563 && !parameters->options().relocatable())
1565 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1566 // clause in a linker script.
1567 Script_sections* ss = this->script_options_->script_sections();
1568 ss->put_headers_in_phdrs(file_header, segment_headers);
1571 // We set the output section indexes in set_segment_offsets and
1572 // set_section_indexes.
1573 *pshndx = 1;
1575 // Set the file offsets of all the segments, and all the sections
1576 // they contain.
1577 off_t off;
1578 if (!parameters->options().relocatable())
1579 off = this->set_segment_offsets(target, load_seg, pshndx);
1580 else
1581 off = this->set_relocatable_section_offsets(file_header, pshndx);
1583 // Verify that the dummy relaxation does not change anything.
1584 if (is_debugging_enabled(DEBUG_RELAXATION))
1586 if (pass == 0)
1587 this->relaxation_debug_check_->read_sections(this->section_list_);
1588 else
1589 this->relaxation_debug_check_->verify_sections(this->section_list_);
1592 *pload_seg = load_seg;
1593 return off;
1596 // Finalize the layout. When this is called, we have created all the
1597 // output sections and all the output segments which are based on
1598 // input sections. We have several things to do, and we have to do
1599 // them in the right order, so that we get the right results correctly
1600 // and efficiently.
1602 // 1) Finalize the list of output segments and create the segment
1603 // table header.
1605 // 2) Finalize the dynamic symbol table and associated sections.
1607 // 3) Determine the final file offset of all the output segments.
1609 // 4) Determine the final file offset of all the SHF_ALLOC output
1610 // sections.
1612 // 5) Create the symbol table sections and the section name table
1613 // section.
1615 // 6) Finalize the symbol table: set symbol values to their final
1616 // value and make a final determination of which symbols are going
1617 // into the output symbol table.
1619 // 7) Create the section table header.
1621 // 8) Determine the final file offset of all the output sections which
1622 // are not SHF_ALLOC, including the section table header.
1624 // 9) Finalize the ELF file header.
1626 // This function returns the size of the output file.
1628 off_t
1629 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1630 Target* target, const Task* task)
1632 target->finalize_sections(this, input_objects, symtab);
1634 this->count_local_symbols(task, input_objects);
1636 this->link_stabs_sections();
1638 Output_segment* phdr_seg = NULL;
1639 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1641 // There was a dynamic object in the link. We need to create
1642 // some information for the dynamic linker.
1644 // Create the PT_PHDR segment which will hold the program
1645 // headers.
1646 if (!this->script_options_->saw_phdrs_clause())
1647 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1649 // Create the dynamic symbol table, including the hash table.
1650 Output_section* dynstr;
1651 std::vector<Symbol*> dynamic_symbols;
1652 unsigned int local_dynamic_count;
1653 Versions versions(*this->script_options()->version_script_info(),
1654 &this->dynpool_);
1655 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1656 &local_dynamic_count, &dynamic_symbols,
1657 &versions);
1659 // Create the .interp section to hold the name of the
1660 // interpreter, and put it in a PT_INTERP segment.
1661 if (!parameters->options().shared())
1662 this->create_interp(target);
1664 // Finish the .dynamic section to hold the dynamic data, and put
1665 // it in a PT_DYNAMIC segment.
1666 this->finish_dynamic_section(input_objects, symtab);
1668 // We should have added everything we need to the dynamic string
1669 // table.
1670 this->dynpool_.set_string_offsets();
1672 // Create the version sections. We can't do this until the
1673 // dynamic string table is complete.
1674 this->create_version_sections(&versions, symtab, local_dynamic_count,
1675 dynamic_symbols, dynstr);
1677 // Set the size of the _DYNAMIC symbol. We can't do this until
1678 // after we call create_version_sections.
1679 this->set_dynamic_symbol_size(symtab);
1682 if (this->incremental_inputs_)
1684 this->incremental_inputs_->finalize();
1685 this->create_incremental_info_sections();
1688 // Create segment headers.
1689 Output_segment_headers* segment_headers =
1690 (parameters->options().relocatable()
1691 ? NULL
1692 : new Output_segment_headers(this->segment_list_));
1694 // Lay out the file header.
1695 Output_file_header* file_header
1696 = new Output_file_header(target, symtab, segment_headers,
1697 parameters->options().entry());
1699 this->special_output_list_.push_back(file_header);
1700 if (segment_headers != NULL)
1701 this->special_output_list_.push_back(segment_headers);
1703 // Find approriate places for orphan output sections if we are using
1704 // a linker script.
1705 if (this->script_options_->saw_sections_clause())
1706 this->place_orphan_sections_in_script();
1708 Output_segment* load_seg;
1709 off_t off;
1710 unsigned int shndx;
1711 int pass = 0;
1713 // Take a snapshot of the section layout as needed.
1714 if (target->may_relax())
1715 this->prepare_for_relaxation();
1717 // Run the relaxation loop to lay out sections.
1720 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1721 phdr_seg, segment_headers, file_header,
1722 &shndx);
1723 pass++;
1725 while (target->may_relax()
1726 && target->relax(pass, input_objects, symtab, this));
1728 // Set the file offsets of all the non-data sections we've seen so
1729 // far which don't have to wait for the input sections. We need
1730 // this in order to finalize local symbols in non-allocated
1731 // sections.
1732 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1734 // Set the section indexes of all unallocated sections seen so far,
1735 // in case any of them are somehow referenced by a symbol.
1736 shndx = this->set_section_indexes(shndx);
1738 // Create the symbol table sections.
1739 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1740 if (!parameters->doing_static_link())
1741 this->assign_local_dynsym_offsets(input_objects);
1743 // Process any symbol assignments from a linker script. This must
1744 // be called after the symbol table has been finalized.
1745 this->script_options_->finalize_symbols(symtab, this);
1747 // Create the .shstrtab section.
1748 Output_section* shstrtab_section = this->create_shstrtab();
1750 // Set the file offsets of the rest of the non-data sections which
1751 // don't have to wait for the input sections.
1752 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1754 // Now that all sections have been created, set the section indexes
1755 // for any sections which haven't been done yet.
1756 shndx = this->set_section_indexes(shndx);
1758 // Create the section table header.
1759 this->create_shdrs(shstrtab_section, &off);
1761 // If there are no sections which require postprocessing, we can
1762 // handle the section names now, and avoid a resize later.
1763 if (!this->any_postprocessing_sections_)
1764 off = this->set_section_offsets(off,
1765 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1767 file_header->set_section_info(this->section_headers_, shstrtab_section);
1769 // Now we know exactly where everything goes in the output file
1770 // (except for non-allocated sections which require postprocessing).
1771 Output_data::layout_complete();
1773 this->output_file_size_ = off;
1775 return off;
1778 // Create a note header following the format defined in the ELF ABI.
1779 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1780 // of the section to create, DESCSZ is the size of the descriptor.
1781 // ALLOCATE is true if the section should be allocated in memory.
1782 // This returns the new note section. It sets *TRAILING_PADDING to
1783 // the number of trailing zero bytes required.
1785 Output_section*
1786 Layout::create_note(const char* name, int note_type,
1787 const char* section_name, size_t descsz,
1788 bool allocate, size_t* trailing_padding)
1790 // Authorities all agree that the values in a .note field should
1791 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1792 // they differ on what the alignment is for 64-bit binaries.
1793 // The GABI says unambiguously they take 8-byte alignment:
1794 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1795 // Other documentation says alignment should always be 4 bytes:
1796 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1797 // GNU ld and GNU readelf both support the latter (at least as of
1798 // version 2.16.91), and glibc always generates the latter for
1799 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1800 // here.
1801 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1802 const int size = parameters->target().get_size();
1803 #else
1804 const int size = 32;
1805 #endif
1807 // The contents of the .note section.
1808 size_t namesz = strlen(name) + 1;
1809 size_t aligned_namesz = align_address(namesz, size / 8);
1810 size_t aligned_descsz = align_address(descsz, size / 8);
1812 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1814 unsigned char* buffer = new unsigned char[notehdrsz];
1815 memset(buffer, 0, notehdrsz);
1817 bool is_big_endian = parameters->target().is_big_endian();
1819 if (size == 32)
1821 if (!is_big_endian)
1823 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1824 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1825 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1827 else
1829 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1830 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1831 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1834 else if (size == 64)
1836 if (!is_big_endian)
1838 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1839 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1840 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1842 else
1844 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1845 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1846 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1849 else
1850 gold_unreachable();
1852 memcpy(buffer + 3 * (size / 8), name, namesz);
1854 elfcpp::Elf_Xword flags = 0;
1855 if (allocate)
1856 flags = elfcpp::SHF_ALLOC;
1857 Output_section* os = this->choose_output_section(NULL, section_name,
1858 elfcpp::SHT_NOTE,
1859 flags, false, false,
1860 false, false, false, false);
1861 if (os == NULL)
1862 return NULL;
1864 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1865 size / 8,
1866 "** note header");
1867 os->add_output_section_data(posd);
1869 *trailing_padding = aligned_descsz - descsz;
1871 return os;
1874 // For an executable or shared library, create a note to record the
1875 // version of gold used to create the binary.
1877 void
1878 Layout::create_gold_note()
1880 if (parameters->options().relocatable())
1881 return;
1883 std::string desc = std::string("gold ") + gold::get_version_string();
1885 size_t trailing_padding;
1886 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1887 ".note.gnu.gold-version", desc.size(),
1888 false, &trailing_padding);
1889 if (os == NULL)
1890 return;
1892 Output_section_data* posd = new Output_data_const(desc, 4);
1893 os->add_output_section_data(posd);
1895 if (trailing_padding > 0)
1897 posd = new Output_data_zero_fill(trailing_padding, 0);
1898 os->add_output_section_data(posd);
1902 // Record whether the stack should be executable. This can be set
1903 // from the command line using the -z execstack or -z noexecstack
1904 // options. Otherwise, if any input file has a .note.GNU-stack
1905 // section with the SHF_EXECINSTR flag set, the stack should be
1906 // executable. Otherwise, if at least one input file a
1907 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1908 // section, we use the target default for whether the stack should be
1909 // executable. Otherwise, we don't generate a stack note. When
1910 // generating a object file, we create a .note.GNU-stack section with
1911 // the appropriate marking. When generating an executable or shared
1912 // library, we create a PT_GNU_STACK segment.
1914 void
1915 Layout::create_executable_stack_info()
1917 bool is_stack_executable;
1918 if (parameters->options().is_execstack_set())
1919 is_stack_executable = parameters->options().is_stack_executable();
1920 else if (!this->input_with_gnu_stack_note_)
1921 return;
1922 else
1924 if (this->input_requires_executable_stack_)
1925 is_stack_executable = true;
1926 else if (this->input_without_gnu_stack_note_)
1927 is_stack_executable =
1928 parameters->target().is_default_stack_executable();
1929 else
1930 is_stack_executable = false;
1933 if (parameters->options().relocatable())
1935 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1936 elfcpp::Elf_Xword flags = 0;
1937 if (is_stack_executable)
1938 flags |= elfcpp::SHF_EXECINSTR;
1939 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags, false,
1940 false, false, false, false);
1942 else
1944 if (this->script_options_->saw_phdrs_clause())
1945 return;
1946 int flags = elfcpp::PF_R | elfcpp::PF_W;
1947 if (is_stack_executable)
1948 flags |= elfcpp::PF_X;
1949 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1953 // If --build-id was used, set up the build ID note.
1955 void
1956 Layout::create_build_id()
1958 if (!parameters->options().user_set_build_id())
1959 return;
1961 const char* style = parameters->options().build_id();
1962 if (strcmp(style, "none") == 0)
1963 return;
1965 // Set DESCSZ to the size of the note descriptor. When possible,
1966 // set DESC to the note descriptor contents.
1967 size_t descsz;
1968 std::string desc;
1969 if (strcmp(style, "md5") == 0)
1970 descsz = 128 / 8;
1971 else if (strcmp(style, "sha1") == 0)
1972 descsz = 160 / 8;
1973 else if (strcmp(style, "uuid") == 0)
1975 const size_t uuidsz = 128 / 8;
1977 char buffer[uuidsz];
1978 memset(buffer, 0, uuidsz);
1980 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
1981 if (descriptor < 0)
1982 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1983 strerror(errno));
1984 else
1986 ssize_t got = ::read(descriptor, buffer, uuidsz);
1987 release_descriptor(descriptor, true);
1988 if (got < 0)
1989 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1990 else if (static_cast<size_t>(got) != uuidsz)
1991 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1992 uuidsz, got);
1995 desc.assign(buffer, uuidsz);
1996 descsz = uuidsz;
1998 else if (strncmp(style, "0x", 2) == 0)
2000 hex_init();
2001 const char* p = style + 2;
2002 while (*p != '\0')
2004 if (hex_p(p[0]) && hex_p(p[1]))
2006 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
2007 desc += c;
2008 p += 2;
2010 else if (*p == '-' || *p == ':')
2011 ++p;
2012 else
2013 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
2014 style);
2016 descsz = desc.size();
2018 else
2019 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
2021 // Create the note.
2022 size_t trailing_padding;
2023 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
2024 ".note.gnu.build-id", descsz, true,
2025 &trailing_padding);
2026 if (os == NULL)
2027 return;
2029 if (!desc.empty())
2031 // We know the value already, so we fill it in now.
2032 gold_assert(desc.size() == descsz);
2034 Output_section_data* posd = new Output_data_const(desc, 4);
2035 os->add_output_section_data(posd);
2037 if (trailing_padding != 0)
2039 posd = new Output_data_zero_fill(trailing_padding, 0);
2040 os->add_output_section_data(posd);
2043 else
2045 // We need to compute a checksum after we have completed the
2046 // link.
2047 gold_assert(trailing_padding == 0);
2048 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
2049 os->add_output_section_data(this->build_id_note_);
2053 // If we have both .stabXX and .stabXXstr sections, then the sh_link
2054 // field of the former should point to the latter. I'm not sure who
2055 // started this, but the GNU linker does it, and some tools depend
2056 // upon it.
2058 void
2059 Layout::link_stabs_sections()
2061 if (!this->have_stabstr_section_)
2062 return;
2064 for (Section_list::iterator p = this->section_list_.begin();
2065 p != this->section_list_.end();
2066 ++p)
2068 if ((*p)->type() != elfcpp::SHT_STRTAB)
2069 continue;
2071 const char* name = (*p)->name();
2072 if (strncmp(name, ".stab", 5) != 0)
2073 continue;
2075 size_t len = strlen(name);
2076 if (strcmp(name + len - 3, "str") != 0)
2077 continue;
2079 std::string stab_name(name, len - 3);
2080 Output_section* stab_sec;
2081 stab_sec = this->find_output_section(stab_name.c_str());
2082 if (stab_sec != NULL)
2083 stab_sec->set_link_section(*p);
2087 // Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
2088 // for the next run of incremental linking to check what has changed.
2090 void
2091 Layout::create_incremental_info_sections()
2093 gold_assert(this->incremental_inputs_ != NULL);
2095 // Add the .gnu_incremental_inputs section.
2096 const char *incremental_inputs_name =
2097 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
2098 Output_section* inputs_os =
2099 this->make_output_section(incremental_inputs_name,
2100 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2101 false, false, false, false, false);
2102 Output_section_data* posd =
2103 this->incremental_inputs_->create_incremental_inputs_section_data();
2104 inputs_os->add_output_section_data(posd);
2106 // Add the .gnu_incremental_strtab section.
2107 const char *incremental_strtab_name =
2108 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2109 Output_section* strtab_os = this->make_output_section(incremental_strtab_name,
2110 elfcpp::SHT_STRTAB,
2111 0, false, false,
2112 false, false, false);
2113 Output_data_strtab* strtab_data =
2114 new Output_data_strtab(this->incremental_inputs_->get_stringpool());
2115 strtab_os->add_output_section_data(strtab_data);
2117 inputs_os->set_link_section(strtab_data);
2120 // Return whether SEG1 should be before SEG2 in the output file. This
2121 // is based entirely on the segment type and flags. When this is
2122 // called the segment addresses has normally not yet been set.
2124 bool
2125 Layout::segment_precedes(const Output_segment* seg1,
2126 const Output_segment* seg2)
2128 elfcpp::Elf_Word type1 = seg1->type();
2129 elfcpp::Elf_Word type2 = seg2->type();
2131 // The single PT_PHDR segment is required to precede any loadable
2132 // segment. We simply make it always first.
2133 if (type1 == elfcpp::PT_PHDR)
2135 gold_assert(type2 != elfcpp::PT_PHDR);
2136 return true;
2138 if (type2 == elfcpp::PT_PHDR)
2139 return false;
2141 // The single PT_INTERP segment is required to precede any loadable
2142 // segment. We simply make it always second.
2143 if (type1 == elfcpp::PT_INTERP)
2145 gold_assert(type2 != elfcpp::PT_INTERP);
2146 return true;
2148 if (type2 == elfcpp::PT_INTERP)
2149 return false;
2151 // We then put PT_LOAD segments before any other segments.
2152 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2153 return true;
2154 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2155 return false;
2157 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2158 // segment, because that is where the dynamic linker expects to find
2159 // it (this is just for efficiency; other positions would also work
2160 // correctly).
2161 if (type1 == elfcpp::PT_TLS
2162 && type2 != elfcpp::PT_TLS
2163 && type2 != elfcpp::PT_GNU_RELRO)
2164 return false;
2165 if (type2 == elfcpp::PT_TLS
2166 && type1 != elfcpp::PT_TLS
2167 && type1 != elfcpp::PT_GNU_RELRO)
2168 return true;
2170 // We put the PT_GNU_RELRO segment last, because that is where the
2171 // dynamic linker expects to find it (as with PT_TLS, this is just
2172 // for efficiency).
2173 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2174 return false;
2175 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2176 return true;
2178 const elfcpp::Elf_Word flags1 = seg1->flags();
2179 const elfcpp::Elf_Word flags2 = seg2->flags();
2181 // The order of non-PT_LOAD segments is unimportant. We simply sort
2182 // by the numeric segment type and flags values. There should not
2183 // be more than one segment with the same type and flags.
2184 if (type1 != elfcpp::PT_LOAD)
2186 if (type1 != type2)
2187 return type1 < type2;
2188 gold_assert(flags1 != flags2);
2189 return flags1 < flags2;
2192 // If the addresses are set already, sort by load address.
2193 if (seg1->are_addresses_set())
2195 if (!seg2->are_addresses_set())
2196 return true;
2198 unsigned int section_count1 = seg1->output_section_count();
2199 unsigned int section_count2 = seg2->output_section_count();
2200 if (section_count1 == 0 && section_count2 > 0)
2201 return true;
2202 if (section_count1 > 0 && section_count2 == 0)
2203 return false;
2205 uint64_t paddr1 = seg1->first_section_load_address();
2206 uint64_t paddr2 = seg2->first_section_load_address();
2207 if (paddr1 != paddr2)
2208 return paddr1 < paddr2;
2210 else if (seg2->are_addresses_set())
2211 return false;
2213 // A segment which holds large data comes after a segment which does
2214 // not hold large data.
2215 if (seg1->is_large_data_segment())
2217 if (!seg2->is_large_data_segment())
2218 return false;
2220 else if (seg2->is_large_data_segment())
2221 return true;
2223 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2224 // segments come before writable segments. Then writable segments
2225 // with data come before writable segments without data. Then
2226 // executable segments come before non-executable segments. Then
2227 // the unlikely case of a non-readable segment comes before the
2228 // normal case of a readable segment. If there are multiple
2229 // segments with the same type and flags, we require that the
2230 // address be set, and we sort by virtual address and then physical
2231 // address.
2232 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2233 return (flags1 & elfcpp::PF_W) == 0;
2234 if ((flags1 & elfcpp::PF_W) != 0
2235 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2236 return seg1->has_any_data_sections();
2237 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2238 return (flags1 & elfcpp::PF_X) != 0;
2239 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2240 return (flags1 & elfcpp::PF_R) == 0;
2242 // We shouldn't get here--we shouldn't create segments which we
2243 // can't distinguish.
2244 gold_unreachable();
2247 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2249 static off_t
2250 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2252 uint64_t unsigned_off = off;
2253 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2254 | (addr & (abi_pagesize - 1)));
2255 if (aligned_off < unsigned_off)
2256 aligned_off += abi_pagesize;
2257 return aligned_off;
2260 // Set the file offsets of all the segments, and all the sections they
2261 // contain. They have all been created. LOAD_SEG must be be laid out
2262 // first. Return the offset of the data to follow.
2264 off_t
2265 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2266 unsigned int *pshndx)
2268 // Sort them into the final order.
2269 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2270 Layout::Compare_segments());
2272 // Find the PT_LOAD segments, and set their addresses and offsets
2273 // and their section's addresses and offsets.
2274 uint64_t addr;
2275 if (parameters->options().user_set_Ttext())
2276 addr = parameters->options().Ttext();
2277 else if (parameters->options().output_is_position_independent())
2278 addr = 0;
2279 else
2280 addr = target->default_text_segment_address();
2281 off_t off = 0;
2283 // If LOAD_SEG is NULL, then the file header and segment headers
2284 // will not be loadable. But they still need to be at offset 0 in
2285 // the file. Set their offsets now.
2286 if (load_seg == NULL)
2288 for (Data_list::iterator p = this->special_output_list_.begin();
2289 p != this->special_output_list_.end();
2290 ++p)
2292 off = align_address(off, (*p)->addralign());
2293 (*p)->set_address_and_file_offset(0, off);
2294 off += (*p)->data_size();
2298 unsigned int increase_relro = this->increase_relro_;
2299 if (this->script_options_->saw_sections_clause())
2300 increase_relro = 0;
2302 const bool check_sections = parameters->options().check_sections();
2303 Output_segment* last_load_segment = NULL;
2305 bool was_readonly = false;
2306 for (Segment_list::iterator p = this->segment_list_.begin();
2307 p != this->segment_list_.end();
2308 ++p)
2310 if ((*p)->type() == elfcpp::PT_LOAD)
2312 if (load_seg != NULL && load_seg != *p)
2313 gold_unreachable();
2314 load_seg = NULL;
2316 bool are_addresses_set = (*p)->are_addresses_set();
2317 if (are_addresses_set)
2319 // When it comes to setting file offsets, we care about
2320 // the physical address.
2321 addr = (*p)->paddr();
2323 else if (parameters->options().user_set_Tdata()
2324 && ((*p)->flags() & elfcpp::PF_W) != 0
2325 && (!parameters->options().user_set_Tbss()
2326 || (*p)->has_any_data_sections()))
2328 addr = parameters->options().Tdata();
2329 are_addresses_set = true;
2331 else if (parameters->options().user_set_Tbss()
2332 && ((*p)->flags() & elfcpp::PF_W) != 0
2333 && !(*p)->has_any_data_sections())
2335 addr = parameters->options().Tbss();
2336 are_addresses_set = true;
2339 uint64_t orig_addr = addr;
2340 uint64_t orig_off = off;
2342 uint64_t aligned_addr = 0;
2343 uint64_t abi_pagesize = target->abi_pagesize();
2344 uint64_t common_pagesize = target->common_pagesize();
2346 if (!parameters->options().nmagic()
2347 && !parameters->options().omagic())
2348 (*p)->set_minimum_p_align(common_pagesize);
2350 if (!are_addresses_set)
2352 // If the last segment was readonly, and this one is
2353 // not, then skip the address forward one page,
2354 // maintaining the same position within the page. This
2355 // lets us store both segments overlapping on a single
2356 // page in the file, but the loader will put them on
2357 // different pages in memory.
2359 addr = align_address(addr, (*p)->maximum_alignment());
2360 aligned_addr = addr;
2362 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2364 if ((addr & (abi_pagesize - 1)) != 0)
2365 addr = addr + abi_pagesize;
2368 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2371 if (!parameters->options().nmagic()
2372 && !parameters->options().omagic())
2373 off = align_file_offset(off, addr, abi_pagesize);
2374 else if (load_seg == NULL)
2376 // This is -N or -n with a section script which prevents
2377 // us from using a load segment. We need to ensure that
2378 // the file offset is aligned to the alignment of the
2379 // segment. This is because the linker script
2380 // implicitly assumed a zero offset. If we don't align
2381 // here, then the alignment of the sections in the
2382 // linker script may not match the alignment of the
2383 // sections in the set_section_addresses call below,
2384 // causing an error about dot moving backward.
2385 off = align_address(off, (*p)->maximum_alignment());
2388 unsigned int shndx_hold = *pshndx;
2389 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2390 increase_relro,
2391 &off, pshndx);
2393 // Now that we know the size of this segment, we may be able
2394 // to save a page in memory, at the cost of wasting some
2395 // file space, by instead aligning to the start of a new
2396 // page. Here we use the real machine page size rather than
2397 // the ABI mandated page size.
2399 if (!are_addresses_set && aligned_addr != addr)
2401 uint64_t first_off = (common_pagesize
2402 - (aligned_addr
2403 & (common_pagesize - 1)));
2404 uint64_t last_off = new_addr & (common_pagesize - 1);
2405 if (first_off > 0
2406 && last_off > 0
2407 && ((aligned_addr & ~ (common_pagesize - 1))
2408 != (new_addr & ~ (common_pagesize - 1)))
2409 && first_off + last_off <= common_pagesize)
2411 *pshndx = shndx_hold;
2412 addr = align_address(aligned_addr, common_pagesize);
2413 addr = align_address(addr, (*p)->maximum_alignment());
2414 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2415 off = align_file_offset(off, addr, abi_pagesize);
2416 new_addr = (*p)->set_section_addresses(this, true, addr,
2417 increase_relro,
2418 &off, pshndx);
2422 addr = new_addr;
2424 if (((*p)->flags() & elfcpp::PF_W) == 0)
2425 was_readonly = true;
2427 // Implement --check-sections. We know that the segments
2428 // are sorted by LMA.
2429 if (check_sections && last_load_segment != NULL)
2431 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2432 if (last_load_segment->paddr() + last_load_segment->memsz()
2433 > (*p)->paddr())
2435 unsigned long long lb1 = last_load_segment->paddr();
2436 unsigned long long le1 = lb1 + last_load_segment->memsz();
2437 unsigned long long lb2 = (*p)->paddr();
2438 unsigned long long le2 = lb2 + (*p)->memsz();
2439 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2440 "[0x%llx -> 0x%llx]"),
2441 lb1, le1, lb2, le2);
2444 last_load_segment = *p;
2448 // Handle the non-PT_LOAD segments, setting their offsets from their
2449 // section's offsets.
2450 for (Segment_list::iterator p = this->segment_list_.begin();
2451 p != this->segment_list_.end();
2452 ++p)
2454 if ((*p)->type() != elfcpp::PT_LOAD)
2455 (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
2456 ? increase_relro
2457 : 0);
2460 // Set the TLS offsets for each section in the PT_TLS segment.
2461 if (this->tls_segment_ != NULL)
2462 this->tls_segment_->set_tls_offsets();
2464 return off;
2467 // Set the offsets of all the allocated sections when doing a
2468 // relocatable link. This does the same jobs as set_segment_offsets,
2469 // only for a relocatable link.
2471 off_t
2472 Layout::set_relocatable_section_offsets(Output_data* file_header,
2473 unsigned int *pshndx)
2475 off_t off = 0;
2477 file_header->set_address_and_file_offset(0, 0);
2478 off += file_header->data_size();
2480 for (Section_list::iterator p = this->section_list_.begin();
2481 p != this->section_list_.end();
2482 ++p)
2484 // We skip unallocated sections here, except that group sections
2485 // have to come first.
2486 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2487 && (*p)->type() != elfcpp::SHT_GROUP)
2488 continue;
2490 off = align_address(off, (*p)->addralign());
2492 // The linker script might have set the address.
2493 if (!(*p)->is_address_valid())
2494 (*p)->set_address(0);
2495 (*p)->set_file_offset(off);
2496 (*p)->finalize_data_size();
2497 off += (*p)->data_size();
2499 (*p)->set_out_shndx(*pshndx);
2500 ++*pshndx;
2503 return off;
2506 // Set the file offset of all the sections not associated with a
2507 // segment.
2509 off_t
2510 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2512 for (Section_list::iterator p = this->unattached_section_list_.begin();
2513 p != this->unattached_section_list_.end();
2514 ++p)
2516 // The symtab section is handled in create_symtab_sections.
2517 if (*p == this->symtab_section_)
2518 continue;
2520 // If we've already set the data size, don't set it again.
2521 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2522 continue;
2524 if (pass == BEFORE_INPUT_SECTIONS_PASS
2525 && (*p)->requires_postprocessing())
2527 (*p)->create_postprocessing_buffer();
2528 this->any_postprocessing_sections_ = true;
2531 if (pass == BEFORE_INPUT_SECTIONS_PASS
2532 && (*p)->after_input_sections())
2533 continue;
2534 else if (pass == POSTPROCESSING_SECTIONS_PASS
2535 && (!(*p)->after_input_sections()
2536 || (*p)->type() == elfcpp::SHT_STRTAB))
2537 continue;
2538 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2539 && (!(*p)->after_input_sections()
2540 || (*p)->type() != elfcpp::SHT_STRTAB))
2541 continue;
2543 off = align_address(off, (*p)->addralign());
2544 (*p)->set_file_offset(off);
2545 (*p)->finalize_data_size();
2546 off += (*p)->data_size();
2548 // At this point the name must be set.
2549 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2550 this->namepool_.add((*p)->name(), false, NULL);
2552 return off;
2555 // Set the section indexes of all the sections not associated with a
2556 // segment.
2558 unsigned int
2559 Layout::set_section_indexes(unsigned int shndx)
2561 for (Section_list::iterator p = this->unattached_section_list_.begin();
2562 p != this->unattached_section_list_.end();
2563 ++p)
2565 if (!(*p)->has_out_shndx())
2567 (*p)->set_out_shndx(shndx);
2568 ++shndx;
2571 return shndx;
2574 // Set the section addresses according to the linker script. This is
2575 // only called when we see a SECTIONS clause. This returns the
2576 // program segment which should hold the file header and segment
2577 // headers, if any. It will return NULL if they should not be in a
2578 // segment.
2580 Output_segment*
2581 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2583 Script_sections* ss = this->script_options_->script_sections();
2584 gold_assert(ss->saw_sections_clause());
2585 return this->script_options_->set_section_addresses(symtab, this);
2588 // Place the orphan sections in the linker script.
2590 void
2591 Layout::place_orphan_sections_in_script()
2593 Script_sections* ss = this->script_options_->script_sections();
2594 gold_assert(ss->saw_sections_clause());
2596 // Place each orphaned output section in the script.
2597 for (Section_list::iterator p = this->section_list_.begin();
2598 p != this->section_list_.end();
2599 ++p)
2601 if (!(*p)->found_in_sections_clause())
2602 ss->place_orphan(*p);
2606 // Count the local symbols in the regular symbol table and the dynamic
2607 // symbol table, and build the respective string pools.
2609 void
2610 Layout::count_local_symbols(const Task* task,
2611 const Input_objects* input_objects)
2613 // First, figure out an upper bound on the number of symbols we'll
2614 // be inserting into each pool. This helps us create the pools with
2615 // the right size, to avoid unnecessary hashtable resizing.
2616 unsigned int symbol_count = 0;
2617 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2618 p != input_objects->relobj_end();
2619 ++p)
2620 symbol_count += (*p)->local_symbol_count();
2622 // Go from "upper bound" to "estimate." We overcount for two
2623 // reasons: we double-count symbols that occur in more than one
2624 // object file, and we count symbols that are dropped from the
2625 // output. Add it all together and assume we overcount by 100%.
2626 symbol_count /= 2;
2628 // We assume all symbols will go into both the sympool and dynpool.
2629 this->sympool_.reserve(symbol_count);
2630 this->dynpool_.reserve(symbol_count);
2632 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2633 p != input_objects->relobj_end();
2634 ++p)
2636 Task_lock_obj<Object> tlo(task, *p);
2637 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2641 // Create the symbol table sections. Here we also set the final
2642 // values of the symbols. At this point all the loadable sections are
2643 // fully laid out. SHNUM is the number of sections so far.
2645 void
2646 Layout::create_symtab_sections(const Input_objects* input_objects,
2647 Symbol_table* symtab,
2648 unsigned int shnum,
2649 off_t* poff)
2651 int symsize;
2652 unsigned int align;
2653 if (parameters->target().get_size() == 32)
2655 symsize = elfcpp::Elf_sizes<32>::sym_size;
2656 align = 4;
2658 else if (parameters->target().get_size() == 64)
2660 symsize = elfcpp::Elf_sizes<64>::sym_size;
2661 align = 8;
2663 else
2664 gold_unreachable();
2666 off_t off = *poff;
2667 off = align_address(off, align);
2668 off_t startoff = off;
2670 // Save space for the dummy symbol at the start of the section. We
2671 // never bother to write this out--it will just be left as zero.
2672 off += symsize;
2673 unsigned int local_symbol_index = 1;
2675 // Add STT_SECTION symbols for each Output section which needs one.
2676 for (Section_list::iterator p = this->section_list_.begin();
2677 p != this->section_list_.end();
2678 ++p)
2680 if (!(*p)->needs_symtab_index())
2681 (*p)->set_symtab_index(-1U);
2682 else
2684 (*p)->set_symtab_index(local_symbol_index);
2685 ++local_symbol_index;
2686 off += symsize;
2690 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2691 p != input_objects->relobj_end();
2692 ++p)
2694 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2695 off, symtab);
2696 off += (index - local_symbol_index) * symsize;
2697 local_symbol_index = index;
2700 unsigned int local_symcount = local_symbol_index;
2701 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
2703 off_t dynoff;
2704 size_t dyn_global_index;
2705 size_t dyncount;
2706 if (this->dynsym_section_ == NULL)
2708 dynoff = 0;
2709 dyn_global_index = 0;
2710 dyncount = 0;
2712 else
2714 dyn_global_index = this->dynsym_section_->info();
2715 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2716 dynoff = this->dynsym_section_->offset() + locsize;
2717 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2718 gold_assert(static_cast<off_t>(dyncount * symsize)
2719 == this->dynsym_section_->data_size() - locsize);
2722 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2723 &this->sympool_, &local_symcount);
2725 if (!parameters->options().strip_all())
2727 this->sympool_.set_string_offsets();
2729 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2730 Output_section* osymtab = this->make_output_section(symtab_name,
2731 elfcpp::SHT_SYMTAB,
2732 0, false, false,
2733 false, false, false);
2734 this->symtab_section_ = osymtab;
2736 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2737 align,
2738 "** symtab");
2739 osymtab->add_output_section_data(pos);
2741 // We generate a .symtab_shndx section if we have more than
2742 // SHN_LORESERVE sections. Technically it is possible that we
2743 // don't need one, because it is possible that there are no
2744 // symbols in any of sections with indexes larger than
2745 // SHN_LORESERVE. That is probably unusual, though, and it is
2746 // easier to always create one than to compute section indexes
2747 // twice (once here, once when writing out the symbols).
2748 if (shnum >= elfcpp::SHN_LORESERVE)
2750 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2751 false, NULL);
2752 Output_section* osymtab_xindex =
2753 this->make_output_section(symtab_xindex_name,
2754 elfcpp::SHT_SYMTAB_SHNDX, 0, false,
2755 false, false, false, false);
2757 size_t symcount = (off - startoff) / symsize;
2758 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2760 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2762 osymtab_xindex->set_link_section(osymtab);
2763 osymtab_xindex->set_addralign(4);
2764 osymtab_xindex->set_entsize(4);
2766 osymtab_xindex->set_after_input_sections();
2768 // This tells the driver code to wait until the symbol table
2769 // has written out before writing out the postprocessing
2770 // sections, including the .symtab_shndx section.
2771 this->any_postprocessing_sections_ = true;
2774 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2775 Output_section* ostrtab = this->make_output_section(strtab_name,
2776 elfcpp::SHT_STRTAB,
2777 0, false, false,
2778 false, false, false);
2780 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2781 ostrtab->add_output_section_data(pstr);
2783 osymtab->set_file_offset(startoff);
2784 osymtab->finalize_data_size();
2785 osymtab->set_link_section(ostrtab);
2786 osymtab->set_info(local_symcount);
2787 osymtab->set_entsize(symsize);
2789 *poff = off;
2793 // Create the .shstrtab section, which holds the names of the
2794 // sections. At the time this is called, we have created all the
2795 // output sections except .shstrtab itself.
2797 Output_section*
2798 Layout::create_shstrtab()
2800 // FIXME: We don't need to create a .shstrtab section if we are
2801 // stripping everything.
2803 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2805 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
2806 false, false, false, false,
2807 false);
2809 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
2811 // We can't write out this section until we've set all the
2812 // section names, and we don't set the names of compressed
2813 // output sections until relocations are complete. FIXME: With
2814 // the current names we use, this is unnecessary.
2815 os->set_after_input_sections();
2818 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2819 os->add_output_section_data(posd);
2821 return os;
2824 // Create the section headers. SIZE is 32 or 64. OFF is the file
2825 // offset.
2827 void
2828 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2830 Output_section_headers* oshdrs;
2831 oshdrs = new Output_section_headers(this,
2832 &this->segment_list_,
2833 &this->section_list_,
2834 &this->unattached_section_list_,
2835 &this->namepool_,
2836 shstrtab_section);
2837 off_t off = align_address(*poff, oshdrs->addralign());
2838 oshdrs->set_address_and_file_offset(0, off);
2839 off += oshdrs->data_size();
2840 *poff = off;
2841 this->section_headers_ = oshdrs;
2844 // Count the allocated sections.
2846 size_t
2847 Layout::allocated_output_section_count() const
2849 size_t section_count = 0;
2850 for (Segment_list::const_iterator p = this->segment_list_.begin();
2851 p != this->segment_list_.end();
2852 ++p)
2853 section_count += (*p)->output_section_count();
2854 return section_count;
2857 // Create the dynamic symbol table.
2859 void
2860 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2861 Symbol_table* symtab,
2862 Output_section **pdynstr,
2863 unsigned int* plocal_dynamic_count,
2864 std::vector<Symbol*>* pdynamic_symbols,
2865 Versions* pversions)
2867 // Count all the symbols in the dynamic symbol table, and set the
2868 // dynamic symbol indexes.
2870 // Skip symbol 0, which is always all zeroes.
2871 unsigned int index = 1;
2873 // Add STT_SECTION symbols for each Output section which needs one.
2874 for (Section_list::iterator p = this->section_list_.begin();
2875 p != this->section_list_.end();
2876 ++p)
2878 if (!(*p)->needs_dynsym_index())
2879 (*p)->set_dynsym_index(-1U);
2880 else
2882 (*p)->set_dynsym_index(index);
2883 ++index;
2887 // Count the local symbols that need to go in the dynamic symbol table,
2888 // and set the dynamic symbol indexes.
2889 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2890 p != input_objects->relobj_end();
2891 ++p)
2893 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2894 index = new_index;
2897 unsigned int local_symcount = index;
2898 *plocal_dynamic_count = local_symcount;
2900 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2901 &this->dynpool_, pversions);
2903 int symsize;
2904 unsigned int align;
2905 const int size = parameters->target().get_size();
2906 if (size == 32)
2908 symsize = elfcpp::Elf_sizes<32>::sym_size;
2909 align = 4;
2911 else if (size == 64)
2913 symsize = elfcpp::Elf_sizes<64>::sym_size;
2914 align = 8;
2916 else
2917 gold_unreachable();
2919 // Create the dynamic symbol table section.
2921 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2922 elfcpp::SHT_DYNSYM,
2923 elfcpp::SHF_ALLOC,
2924 false, false, true,
2925 false, false, false);
2927 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2928 align,
2929 "** dynsym");
2930 dynsym->add_output_section_data(odata);
2932 dynsym->set_info(local_symcount);
2933 dynsym->set_entsize(symsize);
2934 dynsym->set_addralign(align);
2936 this->dynsym_section_ = dynsym;
2938 Output_data_dynamic* const odyn = this->dynamic_data_;
2939 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2940 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2942 // If there are more than SHN_LORESERVE allocated sections, we
2943 // create a .dynsym_shndx section. It is possible that we don't
2944 // need one, because it is possible that there are no dynamic
2945 // symbols in any of the sections with indexes larger than
2946 // SHN_LORESERVE. This is probably unusual, though, and at this
2947 // time we don't know the actual section indexes so it is
2948 // inconvenient to check.
2949 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2951 Output_section* dynsym_xindex =
2952 this->choose_output_section(NULL, ".dynsym_shndx",
2953 elfcpp::SHT_SYMTAB_SHNDX,
2954 elfcpp::SHF_ALLOC,
2955 false, false, true, false, false, false);
2957 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2959 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2961 dynsym_xindex->set_link_section(dynsym);
2962 dynsym_xindex->set_addralign(4);
2963 dynsym_xindex->set_entsize(4);
2965 dynsym_xindex->set_after_input_sections();
2967 // This tells the driver code to wait until the symbol table has
2968 // written out before writing out the postprocessing sections,
2969 // including the .dynsym_shndx section.
2970 this->any_postprocessing_sections_ = true;
2973 // Create the dynamic string table section.
2975 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2976 elfcpp::SHT_STRTAB,
2977 elfcpp::SHF_ALLOC,
2978 false, false, true,
2979 false, false, false);
2981 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2982 dynstr->add_output_section_data(strdata);
2984 dynsym->set_link_section(dynstr);
2985 this->dynamic_section_->set_link_section(dynstr);
2987 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2988 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2990 *pdynstr = dynstr;
2992 // Create the hash tables.
2994 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2995 || strcmp(parameters->options().hash_style(), "both") == 0)
2997 unsigned char* phash;
2998 unsigned int hashlen;
2999 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
3000 &phash, &hashlen);
3002 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
3003 elfcpp::SHT_HASH,
3004 elfcpp::SHF_ALLOC,
3005 false, false, true,
3006 false, false,
3007 false);
3009 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3010 hashlen,
3011 align,
3012 "** hash");
3013 hashsec->add_output_section_data(hashdata);
3015 hashsec->set_link_section(dynsym);
3016 hashsec->set_entsize(4);
3018 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
3021 if (strcmp(parameters->options().hash_style(), "gnu") == 0
3022 || strcmp(parameters->options().hash_style(), "both") == 0)
3024 unsigned char* phash;
3025 unsigned int hashlen;
3026 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
3027 &phash, &hashlen);
3029 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
3030 elfcpp::SHT_GNU_HASH,
3031 elfcpp::SHF_ALLOC,
3032 false, false, true,
3033 false, false,
3034 false);
3036 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3037 hashlen,
3038 align,
3039 "** hash");
3040 hashsec->add_output_section_data(hashdata);
3042 hashsec->set_link_section(dynsym);
3044 // For a 64-bit target, the entries in .gnu.hash do not have a
3045 // uniform size, so we only set the entry size for a 32-bit
3046 // target.
3047 if (parameters->target().get_size() == 32)
3048 hashsec->set_entsize(4);
3050 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
3054 // Assign offsets to each local portion of the dynamic symbol table.
3056 void
3057 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
3059 Output_section* dynsym = this->dynsym_section_;
3060 gold_assert(dynsym != NULL);
3062 off_t off = dynsym->offset();
3064 // Skip the dummy symbol at the start of the section.
3065 off += dynsym->entsize();
3067 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3068 p != input_objects->relobj_end();
3069 ++p)
3071 unsigned int count = (*p)->set_local_dynsym_offset(off);
3072 off += count * dynsym->entsize();
3076 // Create the version sections.
3078 void
3079 Layout::create_version_sections(const Versions* versions,
3080 const Symbol_table* symtab,
3081 unsigned int local_symcount,
3082 const std::vector<Symbol*>& dynamic_symbols,
3083 const Output_section* dynstr)
3085 if (!versions->any_defs() && !versions->any_needs())
3086 return;
3088 switch (parameters->size_and_endianness())
3090 #ifdef HAVE_TARGET_32_LITTLE
3091 case Parameters::TARGET_32_LITTLE:
3092 this->sized_create_version_sections<32, false>(versions, symtab,
3093 local_symcount,
3094 dynamic_symbols, dynstr);
3095 break;
3096 #endif
3097 #ifdef HAVE_TARGET_32_BIG
3098 case Parameters::TARGET_32_BIG:
3099 this->sized_create_version_sections<32, true>(versions, symtab,
3100 local_symcount,
3101 dynamic_symbols, dynstr);
3102 break;
3103 #endif
3104 #ifdef HAVE_TARGET_64_LITTLE
3105 case Parameters::TARGET_64_LITTLE:
3106 this->sized_create_version_sections<64, false>(versions, symtab,
3107 local_symcount,
3108 dynamic_symbols, dynstr);
3109 break;
3110 #endif
3111 #ifdef HAVE_TARGET_64_BIG
3112 case Parameters::TARGET_64_BIG:
3113 this->sized_create_version_sections<64, true>(versions, symtab,
3114 local_symcount,
3115 dynamic_symbols, dynstr);
3116 break;
3117 #endif
3118 default:
3119 gold_unreachable();
3123 // Create the version sections, sized version.
3125 template<int size, bool big_endian>
3126 void
3127 Layout::sized_create_version_sections(
3128 const Versions* versions,
3129 const Symbol_table* symtab,
3130 unsigned int local_symcount,
3131 const std::vector<Symbol*>& dynamic_symbols,
3132 const Output_section* dynstr)
3134 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3135 elfcpp::SHT_GNU_versym,
3136 elfcpp::SHF_ALLOC,
3137 false, false, true,
3138 false, false, false);
3140 unsigned char* vbuf;
3141 unsigned int vsize;
3142 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3143 local_symcount,
3144 dynamic_symbols,
3145 &vbuf, &vsize);
3147 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3148 "** versions");
3150 vsec->add_output_section_data(vdata);
3151 vsec->set_entsize(2);
3152 vsec->set_link_section(this->dynsym_section_);
3154 Output_data_dynamic* const odyn = this->dynamic_data_;
3155 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3157 if (versions->any_defs())
3159 Output_section* vdsec;
3160 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3161 elfcpp::SHT_GNU_verdef,
3162 elfcpp::SHF_ALLOC,
3163 false, false, true, false, false,
3164 false);
3166 unsigned char* vdbuf;
3167 unsigned int vdsize;
3168 unsigned int vdentries;
3169 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3170 &vdsize, &vdentries);
3172 Output_section_data* vddata =
3173 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3175 vdsec->add_output_section_data(vddata);
3176 vdsec->set_link_section(dynstr);
3177 vdsec->set_info(vdentries);
3179 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3180 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3183 if (versions->any_needs())
3185 Output_section* vnsec;
3186 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3187 elfcpp::SHT_GNU_verneed,
3188 elfcpp::SHF_ALLOC,
3189 false, false, true, false, false,
3190 false);
3192 unsigned char* vnbuf;
3193 unsigned int vnsize;
3194 unsigned int vnentries;
3195 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3196 &vnbuf, &vnsize,
3197 &vnentries);
3199 Output_section_data* vndata =
3200 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3202 vnsec->add_output_section_data(vndata);
3203 vnsec->set_link_section(dynstr);
3204 vnsec->set_info(vnentries);
3206 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3207 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3211 // Create the .interp section and PT_INTERP segment.
3213 void
3214 Layout::create_interp(const Target* target)
3216 const char* interp = parameters->options().dynamic_linker();
3217 if (interp == NULL)
3219 interp = target->dynamic_linker();
3220 gold_assert(interp != NULL);
3223 size_t len = strlen(interp) + 1;
3225 Output_section_data* odata = new Output_data_const(interp, len, 1);
3227 Output_section* osec = this->choose_output_section(NULL, ".interp",
3228 elfcpp::SHT_PROGBITS,
3229 elfcpp::SHF_ALLOC,
3230 false, true, true,
3231 false, false, false);
3232 osec->add_output_section_data(odata);
3234 if (!this->script_options_->saw_phdrs_clause())
3236 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3237 elfcpp::PF_R);
3238 oseg->add_output_section(osec, elfcpp::PF_R, false);
3242 // Add dynamic tags for the PLT and the dynamic relocs. This is
3243 // called by the target-specific code. This does nothing if not doing
3244 // a dynamic link.
3246 // USE_REL is true for REL relocs rather than RELA relocs.
3248 // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
3250 // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
3251 // and we also set DT_PLTREL. We use PLT_REL's output section, since
3252 // some targets have multiple reloc sections in PLT_REL.
3254 // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
3255 // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT.
3257 // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
3258 // executable.
3260 void
3261 Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
3262 const Output_data* plt_rel,
3263 const Output_data_reloc_generic* dyn_rel,
3264 bool add_debug, bool dynrel_includes_plt)
3266 Output_data_dynamic* odyn = this->dynamic_data_;
3267 if (odyn == NULL)
3268 return;
3270 if (plt_got != NULL && plt_got->output_section() != NULL)
3271 odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
3273 if (plt_rel != NULL && plt_rel->output_section() != NULL)
3275 odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
3276 odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
3277 odyn->add_constant(elfcpp::DT_PLTREL,
3278 use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
3281 if (dyn_rel != NULL && dyn_rel->output_section() != NULL)
3283 odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
3284 dyn_rel);
3285 if (plt_rel != NULL && dynrel_includes_plt)
3286 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3287 dyn_rel, plt_rel);
3288 else
3289 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3290 dyn_rel);
3291 const int size = parameters->target().get_size();
3292 elfcpp::DT rel_tag;
3293 int rel_size;
3294 if (use_rel)
3296 rel_tag = elfcpp::DT_RELENT;
3297 if (size == 32)
3298 rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
3299 else if (size == 64)
3300 rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
3301 else
3302 gold_unreachable();
3304 else
3306 rel_tag = elfcpp::DT_RELAENT;
3307 if (size == 32)
3308 rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
3309 else if (size == 64)
3310 rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
3311 else
3312 gold_unreachable();
3314 odyn->add_constant(rel_tag, rel_size);
3316 if (parameters->options().combreloc())
3318 size_t c = dyn_rel->relative_reloc_count();
3319 if (c > 0)
3320 odyn->add_constant((use_rel
3321 ? elfcpp::DT_RELCOUNT
3322 : elfcpp::DT_RELACOUNT),
3327 if (add_debug && !parameters->options().shared())
3329 // The value of the DT_DEBUG tag is filled in by the dynamic
3330 // linker at run time, and used by the debugger.
3331 odyn->add_constant(elfcpp::DT_DEBUG, 0);
3335 // Finish the .dynamic section and PT_DYNAMIC segment.
3337 void
3338 Layout::finish_dynamic_section(const Input_objects* input_objects,
3339 const Symbol_table* symtab)
3341 if (!this->script_options_->saw_phdrs_clause())
3343 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3344 (elfcpp::PF_R
3345 | elfcpp::PF_W));
3346 oseg->add_output_section(this->dynamic_section_,
3347 elfcpp::PF_R | elfcpp::PF_W,
3348 false);
3351 Output_data_dynamic* const odyn = this->dynamic_data_;
3353 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3354 p != input_objects->dynobj_end();
3355 ++p)
3357 if (!(*p)->is_needed()
3358 && (*p)->input_file()->options().as_needed())
3360 // This dynamic object was linked with --as-needed, but it
3361 // is not needed.
3362 continue;
3365 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3368 if (parameters->options().shared())
3370 const char* soname = parameters->options().soname();
3371 if (soname != NULL)
3372 odyn->add_string(elfcpp::DT_SONAME, soname);
3375 Symbol* sym = symtab->lookup(parameters->options().init());
3376 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3377 odyn->add_symbol(elfcpp::DT_INIT, sym);
3379 sym = symtab->lookup(parameters->options().fini());
3380 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3381 odyn->add_symbol(elfcpp::DT_FINI, sym);
3383 // Look for .init_array, .preinit_array and .fini_array by checking
3384 // section types.
3385 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3386 p != this->section_list_.end();
3387 ++p)
3388 switch((*p)->type())
3390 case elfcpp::SHT_FINI_ARRAY:
3391 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3392 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3393 break;
3394 case elfcpp::SHT_INIT_ARRAY:
3395 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3396 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3397 break;
3398 case elfcpp::SHT_PREINIT_ARRAY:
3399 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3400 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3401 break;
3402 default:
3403 break;
3406 // Add a DT_RPATH entry if needed.
3407 const General_options::Dir_list& rpath(parameters->options().rpath());
3408 if (!rpath.empty())
3410 std::string rpath_val;
3411 for (General_options::Dir_list::const_iterator p = rpath.begin();
3412 p != rpath.end();
3413 ++p)
3415 if (rpath_val.empty())
3416 rpath_val = p->name();
3417 else
3419 // Eliminate duplicates.
3420 General_options::Dir_list::const_iterator q;
3421 for (q = rpath.begin(); q != p; ++q)
3422 if (q->name() == p->name())
3423 break;
3424 if (q == p)
3426 rpath_val += ':';
3427 rpath_val += p->name();
3432 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3433 if (parameters->options().enable_new_dtags())
3434 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3437 // Look for text segments that have dynamic relocations.
3438 bool have_textrel = false;
3439 if (!this->script_options_->saw_sections_clause())
3441 for (Segment_list::const_iterator p = this->segment_list_.begin();
3442 p != this->segment_list_.end();
3443 ++p)
3445 if (((*p)->flags() & elfcpp::PF_W) == 0
3446 && (*p)->dynamic_reloc_count() > 0)
3448 have_textrel = true;
3449 break;
3453 else
3455 // We don't know the section -> segment mapping, so we are
3456 // conservative and just look for readonly sections with
3457 // relocations. If those sections wind up in writable segments,
3458 // then we have created an unnecessary DT_TEXTREL entry.
3459 for (Section_list::const_iterator p = this->section_list_.begin();
3460 p != this->section_list_.end();
3461 ++p)
3463 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3464 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3465 && ((*p)->dynamic_reloc_count() > 0))
3467 have_textrel = true;
3468 break;
3473 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3474 // post-link tools can easily modify these flags if desired.
3475 unsigned int flags = 0;
3476 if (have_textrel)
3478 // Add a DT_TEXTREL for compatibility with older loaders.
3479 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3480 flags |= elfcpp::DF_TEXTREL;
3482 if (parameters->options().text())
3483 gold_error(_("read-only segment has dynamic relocations"));
3484 else if (parameters->options().warn_shared_textrel()
3485 && parameters->options().shared())
3486 gold_warning(_("shared library text segment is not shareable"));
3488 if (parameters->options().shared() && this->has_static_tls())
3489 flags |= elfcpp::DF_STATIC_TLS;
3490 if (parameters->options().origin())
3491 flags |= elfcpp::DF_ORIGIN;
3492 if (parameters->options().Bsymbolic())
3494 flags |= elfcpp::DF_SYMBOLIC;
3495 // Add DT_SYMBOLIC for compatibility with older loaders.
3496 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3498 if (parameters->options().now())
3499 flags |= elfcpp::DF_BIND_NOW;
3500 odyn->add_constant(elfcpp::DT_FLAGS, flags);
3502 flags = 0;
3503 if (parameters->options().initfirst())
3504 flags |= elfcpp::DF_1_INITFIRST;
3505 if (parameters->options().interpose())
3506 flags |= elfcpp::DF_1_INTERPOSE;
3507 if (parameters->options().loadfltr())
3508 flags |= elfcpp::DF_1_LOADFLTR;
3509 if (parameters->options().nodefaultlib())
3510 flags |= elfcpp::DF_1_NODEFLIB;
3511 if (parameters->options().nodelete())
3512 flags |= elfcpp::DF_1_NODELETE;
3513 if (parameters->options().nodlopen())
3514 flags |= elfcpp::DF_1_NOOPEN;
3515 if (parameters->options().nodump())
3516 flags |= elfcpp::DF_1_NODUMP;
3517 if (!parameters->options().shared())
3518 flags &= ~(elfcpp::DF_1_INITFIRST
3519 | elfcpp::DF_1_NODELETE
3520 | elfcpp::DF_1_NOOPEN);
3521 if (parameters->options().origin())
3522 flags |= elfcpp::DF_1_ORIGIN;
3523 if (parameters->options().now())
3524 flags |= elfcpp::DF_1_NOW;
3525 if (flags)
3526 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3529 // Set the size of the _DYNAMIC symbol table to be the size of the
3530 // dynamic data.
3532 void
3533 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
3535 Output_data_dynamic* const odyn = this->dynamic_data_;
3536 odyn->finalize_data_size();
3537 off_t data_size = odyn->data_size();
3538 const int size = parameters->target().get_size();
3539 if (size == 32)
3540 symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
3541 else if (size == 64)
3542 symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
3543 else
3544 gold_unreachable();
3547 // The mapping of input section name prefixes to output section names.
3548 // In some cases one prefix is itself a prefix of another prefix; in
3549 // such a case the longer prefix must come first. These prefixes are
3550 // based on the GNU linker default ELF linker script.
3552 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3553 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3555 MAPPING_INIT(".text.", ".text"),
3556 MAPPING_INIT(".ctors.", ".ctors"),
3557 MAPPING_INIT(".dtors.", ".dtors"),
3558 MAPPING_INIT(".rodata.", ".rodata"),
3559 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3560 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3561 MAPPING_INIT(".data.", ".data"),
3562 MAPPING_INIT(".bss.", ".bss"),
3563 MAPPING_INIT(".tdata.", ".tdata"),
3564 MAPPING_INIT(".tbss.", ".tbss"),
3565 MAPPING_INIT(".init_array.", ".init_array"),
3566 MAPPING_INIT(".fini_array.", ".fini_array"),
3567 MAPPING_INIT(".sdata.", ".sdata"),
3568 MAPPING_INIT(".sbss.", ".sbss"),
3569 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3570 // differently depending on whether it is creating a shared library.
3571 MAPPING_INIT(".sdata2.", ".sdata"),
3572 MAPPING_INIT(".sbss2.", ".sbss"),
3573 MAPPING_INIT(".lrodata.", ".lrodata"),
3574 MAPPING_INIT(".ldata.", ".ldata"),
3575 MAPPING_INIT(".lbss.", ".lbss"),
3576 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3577 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3578 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3579 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3580 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3581 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3582 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3583 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3584 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3585 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3586 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3587 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3588 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3589 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3590 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3591 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3592 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3593 MAPPING_INIT(".ARM.extab", ".ARM.extab"),
3594 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3595 MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
3596 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3598 #undef MAPPING_INIT
3600 const int Layout::section_name_mapping_count =
3601 (sizeof(Layout::section_name_mapping)
3602 / sizeof(Layout::section_name_mapping[0]));
3604 // Choose the output section name to use given an input section name.
3605 // Set *PLEN to the length of the name. *PLEN is initialized to the
3606 // length of NAME.
3608 const char*
3609 Layout::output_section_name(const char* name, size_t* plen)
3611 // gcc 4.3 generates the following sorts of section names when it
3612 // needs a section name specific to a function:
3613 // .text.FN
3614 // .rodata.FN
3615 // .sdata2.FN
3616 // .data.FN
3617 // .data.rel.FN
3618 // .data.rel.local.FN
3619 // .data.rel.ro.FN
3620 // .data.rel.ro.local.FN
3621 // .sdata.FN
3622 // .bss.FN
3623 // .sbss.FN
3624 // .tdata.FN
3625 // .tbss.FN
3627 // The GNU linker maps all of those to the part before the .FN,
3628 // except that .data.rel.local.FN is mapped to .data, and
3629 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3630 // beginning with .data.rel.ro.local are grouped together.
3632 // For an anonymous namespace, the string FN can contain a '.'.
3634 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3635 // GNU linker maps to .rodata.
3637 // The .data.rel.ro sections are used with -z relro. The sections
3638 // are recognized by name. We use the same names that the GNU
3639 // linker does for these sections.
3641 // It is hard to handle this in a principled way, so we don't even
3642 // try. We use a table of mappings. If the input section name is
3643 // not found in the table, we simply use it as the output section
3644 // name.
3646 const Section_name_mapping* psnm = section_name_mapping;
3647 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3649 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3651 *plen = psnm->tolen;
3652 return psnm->to;
3656 return name;
3659 // Check if a comdat group or .gnu.linkonce section with the given
3660 // NAME is selected for the link. If there is already a section,
3661 // *KEPT_SECTION is set to point to the existing section and the
3662 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3663 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3664 // *KEPT_SECTION is set to the internal copy and the function returns
3665 // true.
3667 bool
3668 Layout::find_or_add_kept_section(const std::string& name,
3669 Relobj* object,
3670 unsigned int shndx,
3671 bool is_comdat,
3672 bool is_group_name,
3673 Kept_section** kept_section)
3675 // It's normal to see a couple of entries here, for the x86 thunk
3676 // sections. If we see more than a few, we're linking a C++
3677 // program, and we resize to get more space to minimize rehashing.
3678 if (this->signatures_.size() > 4
3679 && !this->resized_signatures_)
3681 reserve_unordered_map(&this->signatures_,
3682 this->number_of_input_files_ * 64);
3683 this->resized_signatures_ = true;
3686 Kept_section candidate;
3687 std::pair<Signatures::iterator, bool> ins =
3688 this->signatures_.insert(std::make_pair(name, candidate));
3690 if (kept_section != NULL)
3691 *kept_section = &ins.first->second;
3692 if (ins.second)
3694 // This is the first time we've seen this signature.
3695 ins.first->second.set_object(object);
3696 ins.first->second.set_shndx(shndx);
3697 if (is_comdat)
3698 ins.first->second.set_is_comdat();
3699 if (is_group_name)
3700 ins.first->second.set_is_group_name();
3701 return true;
3704 // We have already seen this signature.
3706 if (ins.first->second.is_group_name())
3708 // We've already seen a real section group with this signature.
3709 // If the kept group is from a plugin object, and we're in the
3710 // replacement phase, accept the new one as a replacement.
3711 if (ins.first->second.object() == NULL
3712 && parameters->options().plugins()->in_replacement_phase())
3714 ins.first->second.set_object(object);
3715 ins.first->second.set_shndx(shndx);
3716 return true;
3718 return false;
3720 else if (is_group_name)
3722 // This is a real section group, and we've already seen a
3723 // linkonce section with this signature. Record that we've seen
3724 // a section group, and don't include this section group.
3725 ins.first->second.set_is_group_name();
3726 return false;
3728 else
3730 // We've already seen a linkonce section and this is a linkonce
3731 // section. These don't block each other--this may be the same
3732 // symbol name with different section types.
3733 return true;
3737 // Store the allocated sections into the section list.
3739 void
3740 Layout::get_allocated_sections(Section_list* section_list) const
3742 for (Section_list::const_iterator p = this->section_list_.begin();
3743 p != this->section_list_.end();
3744 ++p)
3745 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3746 section_list->push_back(*p);
3749 // Create an output segment.
3751 Output_segment*
3752 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3754 gold_assert(!parameters->options().relocatable());
3755 Output_segment* oseg = new Output_segment(type, flags);
3756 this->segment_list_.push_back(oseg);
3758 if (type == elfcpp::PT_TLS)
3759 this->tls_segment_ = oseg;
3760 else if (type == elfcpp::PT_GNU_RELRO)
3761 this->relro_segment_ = oseg;
3763 return oseg;
3766 // Write out the Output_sections. Most won't have anything to write,
3767 // since most of the data will come from input sections which are
3768 // handled elsewhere. But some Output_sections do have Output_data.
3770 void
3771 Layout::write_output_sections(Output_file* of) const
3773 for (Section_list::const_iterator p = this->section_list_.begin();
3774 p != this->section_list_.end();
3775 ++p)
3777 if (!(*p)->after_input_sections())
3778 (*p)->write(of);
3782 // Write out data not associated with a section or the symbol table.
3784 void
3785 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
3787 if (!parameters->options().strip_all())
3789 const Output_section* symtab_section = this->symtab_section_;
3790 for (Section_list::const_iterator p = this->section_list_.begin();
3791 p != this->section_list_.end();
3792 ++p)
3794 if ((*p)->needs_symtab_index())
3796 gold_assert(symtab_section != NULL);
3797 unsigned int index = (*p)->symtab_index();
3798 gold_assert(index > 0 && index != -1U);
3799 off_t off = (symtab_section->offset()
3800 + index * symtab_section->entsize());
3801 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3806 const Output_section* dynsym_section = this->dynsym_section_;
3807 for (Section_list::const_iterator p = this->section_list_.begin();
3808 p != this->section_list_.end();
3809 ++p)
3811 if ((*p)->needs_dynsym_index())
3813 gold_assert(dynsym_section != NULL);
3814 unsigned int index = (*p)->dynsym_index();
3815 gold_assert(index > 0 && index != -1U);
3816 off_t off = (dynsym_section->offset()
3817 + index * dynsym_section->entsize());
3818 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3822 // Write out the Output_data which are not in an Output_section.
3823 for (Data_list::const_iterator p = this->special_output_list_.begin();
3824 p != this->special_output_list_.end();
3825 ++p)
3826 (*p)->write(of);
3829 // Write out the Output_sections which can only be written after the
3830 // input sections are complete.
3832 void
3833 Layout::write_sections_after_input_sections(Output_file* of)
3835 // Determine the final section offsets, and thus the final output
3836 // file size. Note we finalize the .shstrab last, to allow the
3837 // after_input_section sections to modify their section-names before
3838 // writing.
3839 if (this->any_postprocessing_sections_)
3841 off_t off = this->output_file_size_;
3842 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3844 // Now that we've finalized the names, we can finalize the shstrab.
3845 off =
3846 this->set_section_offsets(off,
3847 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3849 if (off > this->output_file_size_)
3851 of->resize(off);
3852 this->output_file_size_ = off;
3856 for (Section_list::const_iterator p = this->section_list_.begin();
3857 p != this->section_list_.end();
3858 ++p)
3860 if ((*p)->after_input_sections())
3861 (*p)->write(of);
3864 this->section_headers_->write(of);
3867 // If the build ID requires computing a checksum, do so here, and
3868 // write it out. We compute a checksum over the entire file because
3869 // that is simplest.
3871 void
3872 Layout::write_build_id(Output_file* of) const
3874 if (this->build_id_note_ == NULL)
3875 return;
3877 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3879 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3880 this->build_id_note_->data_size());
3882 const char* style = parameters->options().build_id();
3883 if (strcmp(style, "sha1") == 0)
3885 sha1_ctx ctx;
3886 sha1_init_ctx(&ctx);
3887 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3888 sha1_finish_ctx(&ctx, ov);
3890 else if (strcmp(style, "md5") == 0)
3892 md5_ctx ctx;
3893 md5_init_ctx(&ctx);
3894 md5_process_bytes(iv, this->output_file_size_, &ctx);
3895 md5_finish_ctx(&ctx, ov);
3897 else
3898 gold_unreachable();
3900 of->write_output_view(this->build_id_note_->offset(),
3901 this->build_id_note_->data_size(),
3902 ov);
3904 of->free_input_view(0, this->output_file_size_, iv);
3907 // Write out a binary file. This is called after the link is
3908 // complete. IN is the temporary output file we used to generate the
3909 // ELF code. We simply walk through the segments, read them from
3910 // their file offset in IN, and write them to their load address in
3911 // the output file. FIXME: with a bit more work, we could support
3912 // S-records and/or Intel hex format here.
3914 void
3915 Layout::write_binary(Output_file* in) const
3917 gold_assert(parameters->options().oformat_enum()
3918 == General_options::OBJECT_FORMAT_BINARY);
3920 // Get the size of the binary file.
3921 uint64_t max_load_address = 0;
3922 for (Segment_list::const_iterator p = this->segment_list_.begin();
3923 p != this->segment_list_.end();
3924 ++p)
3926 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3928 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3929 if (max_paddr > max_load_address)
3930 max_load_address = max_paddr;
3934 Output_file out(parameters->options().output_file_name());
3935 out.open(max_load_address);
3937 for (Segment_list::const_iterator p = this->segment_list_.begin();
3938 p != this->segment_list_.end();
3939 ++p)
3941 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3943 const unsigned char* vin = in->get_input_view((*p)->offset(),
3944 (*p)->filesz());
3945 unsigned char* vout = out.get_output_view((*p)->paddr(),
3946 (*p)->filesz());
3947 memcpy(vout, vin, (*p)->filesz());
3948 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3949 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3953 out.close();
3956 // Print the output sections to the map file.
3958 void
3959 Layout::print_to_mapfile(Mapfile* mapfile) const
3961 for (Segment_list::const_iterator p = this->segment_list_.begin();
3962 p != this->segment_list_.end();
3963 ++p)
3964 (*p)->print_sections_to_mapfile(mapfile);
3967 // Print statistical information to stderr. This is used for --stats.
3969 void
3970 Layout::print_stats() const
3972 this->namepool_.print_stats("section name pool");
3973 this->sympool_.print_stats("output symbol name pool");
3974 this->dynpool_.print_stats("dynamic name pool");
3976 for (Section_list::const_iterator p = this->section_list_.begin();
3977 p != this->section_list_.end();
3978 ++p)
3979 (*p)->print_merge_stats();
3982 // Write_sections_task methods.
3984 // We can always run this task.
3986 Task_token*
3987 Write_sections_task::is_runnable()
3989 return NULL;
3992 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3993 // when finished.
3995 void
3996 Write_sections_task::locks(Task_locker* tl)
3998 tl->add(this, this->output_sections_blocker_);
3999 tl->add(this, this->final_blocker_);
4002 // Run the task--write out the data.
4004 void
4005 Write_sections_task::run(Workqueue*)
4007 this->layout_->write_output_sections(this->of_);
4010 // Write_data_task methods.
4012 // We can always run this task.
4014 Task_token*
4015 Write_data_task::is_runnable()
4017 return NULL;
4020 // We need to unlock FINAL_BLOCKER when finished.
4022 void
4023 Write_data_task::locks(Task_locker* tl)
4025 tl->add(this, this->final_blocker_);
4028 // Run the task--write out the data.
4030 void
4031 Write_data_task::run(Workqueue*)
4033 this->layout_->write_data(this->symtab_, this->of_);
4036 // Write_symbols_task methods.
4038 // We can always run this task.
4040 Task_token*
4041 Write_symbols_task::is_runnable()
4043 return NULL;
4046 // We need to unlock FINAL_BLOCKER when finished.
4048 void
4049 Write_symbols_task::locks(Task_locker* tl)
4051 tl->add(this, this->final_blocker_);
4054 // Run the task--write out the symbols.
4056 void
4057 Write_symbols_task::run(Workqueue*)
4059 this->symtab_->write_globals(this->sympool_, this->dynpool_,
4060 this->layout_->symtab_xindex(),
4061 this->layout_->dynsym_xindex(), this->of_);
4064 // Write_after_input_sections_task methods.
4066 // We can only run this task after the input sections have completed.
4068 Task_token*
4069 Write_after_input_sections_task::is_runnable()
4071 if (this->input_sections_blocker_->is_blocked())
4072 return this->input_sections_blocker_;
4073 return NULL;
4076 // We need to unlock FINAL_BLOCKER when finished.
4078 void
4079 Write_after_input_sections_task::locks(Task_locker* tl)
4081 tl->add(this, this->final_blocker_);
4084 // Run the task.
4086 void
4087 Write_after_input_sections_task::run(Workqueue*)
4089 this->layout_->write_sections_after_input_sections(this->of_);
4092 // Close_task_runner methods.
4094 // Run the task--close the file.
4096 void
4097 Close_task_runner::run(Workqueue*, const Task*)
4099 // If we need to compute a checksum for the BUILD if, we do so here.
4100 this->layout_->write_build_id(this->of_);
4102 // If we've been asked to create a binary file, we do so here.
4103 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
4104 this->layout_->write_binary(this->of_);
4106 this->of_->close();
4109 // Instantiate the templates we need. We could use the configure
4110 // script to restrict this to only the ones for implemented targets.
4112 #ifdef HAVE_TARGET_32_LITTLE
4113 template
4114 Output_section*
4115 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
4116 const char* name,
4117 const elfcpp::Shdr<32, false>& shdr,
4118 unsigned int, unsigned int, off_t*);
4119 #endif
4121 #ifdef HAVE_TARGET_32_BIG
4122 template
4123 Output_section*
4124 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
4125 const char* name,
4126 const elfcpp::Shdr<32, true>& shdr,
4127 unsigned int, unsigned int, off_t*);
4128 #endif
4130 #ifdef HAVE_TARGET_64_LITTLE
4131 template
4132 Output_section*
4133 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
4134 const char* name,
4135 const elfcpp::Shdr<64, false>& shdr,
4136 unsigned int, unsigned int, off_t*);
4137 #endif
4139 #ifdef HAVE_TARGET_64_BIG
4140 template
4141 Output_section*
4142 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
4143 const char* name,
4144 const elfcpp::Shdr<64, true>& shdr,
4145 unsigned int, unsigned int, off_t*);
4146 #endif
4148 #ifdef HAVE_TARGET_32_LITTLE
4149 template
4150 Output_section*
4151 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
4152 unsigned int reloc_shndx,
4153 const elfcpp::Shdr<32, false>& shdr,
4154 Output_section* data_section,
4155 Relocatable_relocs* rr);
4156 #endif
4158 #ifdef HAVE_TARGET_32_BIG
4159 template
4160 Output_section*
4161 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
4162 unsigned int reloc_shndx,
4163 const elfcpp::Shdr<32, true>& shdr,
4164 Output_section* data_section,
4165 Relocatable_relocs* rr);
4166 #endif
4168 #ifdef HAVE_TARGET_64_LITTLE
4169 template
4170 Output_section*
4171 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
4172 unsigned int reloc_shndx,
4173 const elfcpp::Shdr<64, false>& shdr,
4174 Output_section* data_section,
4175 Relocatable_relocs* rr);
4176 #endif
4178 #ifdef HAVE_TARGET_64_BIG
4179 template
4180 Output_section*
4181 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
4182 unsigned int reloc_shndx,
4183 const elfcpp::Shdr<64, true>& shdr,
4184 Output_section* data_section,
4185 Relocatable_relocs* rr);
4186 #endif
4188 #ifdef HAVE_TARGET_32_LITTLE
4189 template
4190 void
4191 Layout::layout_group<32, false>(Symbol_table* symtab,
4192 Sized_relobj<32, false>* object,
4193 unsigned int,
4194 const char* group_section_name,
4195 const char* signature,
4196 const elfcpp::Shdr<32, false>& shdr,
4197 elfcpp::Elf_Word flags,
4198 std::vector<unsigned int>* shndxes);
4199 #endif
4201 #ifdef HAVE_TARGET_32_BIG
4202 template
4203 void
4204 Layout::layout_group<32, true>(Symbol_table* symtab,
4205 Sized_relobj<32, true>* object,
4206 unsigned int,
4207 const char* group_section_name,
4208 const char* signature,
4209 const elfcpp::Shdr<32, true>& shdr,
4210 elfcpp::Elf_Word flags,
4211 std::vector<unsigned int>* shndxes);
4212 #endif
4214 #ifdef HAVE_TARGET_64_LITTLE
4215 template
4216 void
4217 Layout::layout_group<64, false>(Symbol_table* symtab,
4218 Sized_relobj<64, false>* object,
4219 unsigned int,
4220 const char* group_section_name,
4221 const char* signature,
4222 const elfcpp::Shdr<64, false>& shdr,
4223 elfcpp::Elf_Word flags,
4224 std::vector<unsigned int>* shndxes);
4225 #endif
4227 #ifdef HAVE_TARGET_64_BIG
4228 template
4229 void
4230 Layout::layout_group<64, true>(Symbol_table* symtab,
4231 Sized_relobj<64, true>* object,
4232 unsigned int,
4233 const char* group_section_name,
4234 const char* signature,
4235 const elfcpp::Shdr<64, true>& shdr,
4236 elfcpp::Elf_Word flags,
4237 std::vector<unsigned int>* shndxes);
4238 #endif
4240 #ifdef HAVE_TARGET_32_LITTLE
4241 template
4242 Output_section*
4243 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
4244 const unsigned char* symbols,
4245 off_t symbols_size,
4246 const unsigned char* symbol_names,
4247 off_t symbol_names_size,
4248 unsigned int shndx,
4249 const elfcpp::Shdr<32, false>& shdr,
4250 unsigned int reloc_shndx,
4251 unsigned int reloc_type,
4252 off_t* off);
4253 #endif
4255 #ifdef HAVE_TARGET_32_BIG
4256 template
4257 Output_section*
4258 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4259 const unsigned char* symbols,
4260 off_t symbols_size,
4261 const unsigned char* symbol_names,
4262 off_t symbol_names_size,
4263 unsigned int shndx,
4264 const elfcpp::Shdr<32, true>& shdr,
4265 unsigned int reloc_shndx,
4266 unsigned int reloc_type,
4267 off_t* off);
4268 #endif
4270 #ifdef HAVE_TARGET_64_LITTLE
4271 template
4272 Output_section*
4273 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4274 const unsigned char* symbols,
4275 off_t symbols_size,
4276 const unsigned char* symbol_names,
4277 off_t symbol_names_size,
4278 unsigned int shndx,
4279 const elfcpp::Shdr<64, false>& shdr,
4280 unsigned int reloc_shndx,
4281 unsigned int reloc_type,
4282 off_t* off);
4283 #endif
4285 #ifdef HAVE_TARGET_64_BIG
4286 template
4287 Output_section*
4288 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4289 const unsigned char* symbols,
4290 off_t symbols_size,
4291 const unsigned char* symbol_names,
4292 off_t symbol_names_size,
4293 unsigned int shndx,
4294 const elfcpp::Shdr<64, true>& shdr,
4295 unsigned int reloc_shndx,
4296 unsigned int reloc_type,
4297 off_t* off);
4298 #endif
4300 } // End namespace gold.