Optimize _bfd_elf_allocate_ifunc_dyn_relocs.
[binutils.git] / gold / layout.cc
blob9bf9a9f7325ff9d2d3fc714ec6508343ba58a54d
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 <fstream>
30 #include <utility>
31 #include <fcntl.h>
32 #include <fnmatch.h>
33 #include <unistd.h>
34 #include "libiberty.h"
35 #include "md5.h"
36 #include "sha1.h"
38 #include "parameters.h"
39 #include "options.h"
40 #include "mapfile.h"
41 #include "script.h"
42 #include "script-sections.h"
43 #include "output.h"
44 #include "symtab.h"
45 #include "dynobj.h"
46 #include "ehframe.h"
47 #include "compressed_output.h"
48 #include "reduced_debug_output.h"
49 #include "reloc.h"
50 #include "descriptors.h"
51 #include "plugin.h"
52 #include "incremental.h"
53 #include "layout.h"
55 namespace gold
58 // Layout::Relaxation_debug_check methods.
60 // Check that sections and special data are in reset states.
61 // We do not save states for Output_sections and special Output_data.
62 // So we check that they have not assigned any addresses or offsets.
63 // clean_up_after_relaxation simply resets their addresses and offsets.
64 void
65 Layout::Relaxation_debug_check::check_output_data_for_reset_values(
66 const Layout::Section_list& sections,
67 const Layout::Data_list& special_outputs)
69 for(Layout::Section_list::const_iterator p = sections.begin();
70 p != sections.end();
71 ++p)
72 gold_assert((*p)->address_and_file_offset_have_reset_values());
74 for(Layout::Data_list::const_iterator p = special_outputs.begin();
75 p != special_outputs.end();
76 ++p)
77 gold_assert((*p)->address_and_file_offset_have_reset_values());
80 // Save information of SECTIONS for checking later.
82 void
83 Layout::Relaxation_debug_check::read_sections(
84 const Layout::Section_list& sections)
86 for(Layout::Section_list::const_iterator p = sections.begin();
87 p != sections.end();
88 ++p)
90 Output_section* os = *p;
91 Section_info info;
92 info.output_section = os;
93 info.address = os->is_address_valid() ? os->address() : 0;
94 info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
95 info.offset = os->is_offset_valid()? os->offset() : -1 ;
96 this->section_infos_.push_back(info);
100 // Verify SECTIONS using previously recorded information.
102 void
103 Layout::Relaxation_debug_check::verify_sections(
104 const Layout::Section_list& sections)
106 size_t i = 0;
107 for(Layout::Section_list::const_iterator p = sections.begin();
108 p != sections.end();
109 ++p, ++i)
111 Output_section* os = *p;
112 uint64_t address = os->is_address_valid() ? os->address() : 0;
113 off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
114 off_t offset = os->is_offset_valid()? os->offset() : -1 ;
116 if (i >= this->section_infos_.size())
118 gold_fatal("Section_info of %s missing.\n", os->name());
120 const Section_info& info = this->section_infos_[i];
121 if (os != info.output_section)
122 gold_fatal("Section order changed. Expecting %s but see %s\n",
123 info.output_section->name(), os->name());
124 if (address != info.address
125 || data_size != info.data_size
126 || offset != info.offset)
127 gold_fatal("Section %s changed.\n", os->name());
131 // Layout_task_runner methods.
133 // Lay out the sections. This is called after all the input objects
134 // have been read.
136 void
137 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
139 off_t file_size = this->layout_->finalize(this->input_objects_,
140 this->symtab_,
141 this->target_,
142 task);
144 // Now we know the final size of the output file and we know where
145 // each piece of information goes.
147 if (this->mapfile_ != NULL)
149 this->mapfile_->print_discarded_sections(this->input_objects_);
150 this->layout_->print_to_mapfile(this->mapfile_);
153 Output_file* of = new Output_file(parameters->options().output_file_name());
154 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
155 of->set_is_temporary();
156 of->open(file_size);
158 // Queue up the final set of tasks.
159 gold::queue_final_tasks(this->options_, this->input_objects_,
160 this->symtab_, this->layout_, workqueue, of);
163 // Layout methods.
165 Layout::Layout(int number_of_input_files, Script_options* script_options)
166 : number_of_input_files_(number_of_input_files),
167 script_options_(script_options),
168 namepool_(),
169 sympool_(),
170 dynpool_(),
171 signatures_(),
172 section_name_map_(),
173 segment_list_(),
174 section_list_(),
175 unattached_section_list_(),
176 special_output_list_(),
177 section_headers_(NULL),
178 tls_segment_(NULL),
179 relro_segment_(NULL),
180 increase_relro_(0),
181 symtab_section_(NULL),
182 symtab_xindex_(NULL),
183 dynsym_section_(NULL),
184 dynsym_xindex_(NULL),
185 dynamic_section_(NULL),
186 dynamic_symbol_(NULL),
187 dynamic_data_(NULL),
188 eh_frame_section_(NULL),
189 eh_frame_data_(NULL),
190 added_eh_frame_data_(false),
191 eh_frame_hdr_section_(NULL),
192 build_id_note_(NULL),
193 debug_abbrev_(NULL),
194 debug_info_(NULL),
195 group_signatures_(),
196 output_file_size_(-1),
197 have_added_input_section_(false),
198 sections_are_attached_(false),
199 input_requires_executable_stack_(false),
200 input_with_gnu_stack_note_(false),
201 input_without_gnu_stack_note_(false),
202 has_static_tls_(false),
203 any_postprocessing_sections_(false),
204 resized_signatures_(false),
205 have_stabstr_section_(false),
206 incremental_inputs_(NULL),
207 record_output_section_data_from_script_(false),
208 script_output_section_data_list_(),
209 segment_states_(NULL),
210 relaxation_debug_check_(NULL)
212 // Make space for more than enough segments for a typical file.
213 // This is just for efficiency--it's OK if we wind up needing more.
214 this->segment_list_.reserve(12);
216 // We expect two unattached Output_data objects: the file header and
217 // the segment headers.
218 this->special_output_list_.reserve(2);
220 // Initialize structure needed for an incremental build.
221 if (parameters->incremental())
222 this->incremental_inputs_ = new Incremental_inputs;
224 // The section name pool is worth optimizing in all cases, because
225 // it is small, but there are often overlaps due to .rel sections.
226 this->namepool_.set_optimize();
229 // Hash a key we use to look up an output section mapping.
231 size_t
232 Layout::Hash_key::operator()(const Layout::Key& k) const
234 return k.first + k.second.first + k.second.second;
237 // Returns whether the given section is in the list of
238 // debug-sections-used-by-some-version-of-gdb. Currently,
239 // we've checked versions of gdb up to and including 6.7.1.
241 static const char* gdb_sections[] =
242 { ".debug_abbrev",
243 // ".debug_aranges", // not used by gdb as of 6.7.1
244 ".debug_frame",
245 ".debug_info",
246 ".debug_types",
247 ".debug_line",
248 ".debug_loc",
249 ".debug_macinfo",
250 // ".debug_pubnames", // not used by gdb as of 6.7.1
251 ".debug_ranges",
252 ".debug_str",
255 static const char* lines_only_debug_sections[] =
256 { ".debug_abbrev",
257 // ".debug_aranges", // not used by gdb as of 6.7.1
258 // ".debug_frame",
259 ".debug_info",
260 // ".debug_types",
261 ".debug_line",
262 // ".debug_loc",
263 // ".debug_macinfo",
264 // ".debug_pubnames", // not used by gdb as of 6.7.1
265 // ".debug_ranges",
266 ".debug_str",
269 static inline bool
270 is_gdb_debug_section(const char* str)
272 // We can do this faster: binary search or a hashtable. But why bother?
273 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
274 if (strcmp(str, gdb_sections[i]) == 0)
275 return true;
276 return false;
279 static inline bool
280 is_lines_only_debug_section(const char* str)
282 // We can do this faster: binary search or a hashtable. But why bother?
283 for (size_t i = 0;
284 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
285 ++i)
286 if (strcmp(str, lines_only_debug_sections[i]) == 0)
287 return true;
288 return false;
291 // Sometimes we compress sections. This is typically done for
292 // sections that are not part of normal program execution (such as
293 // .debug_* sections), and where the readers of these sections know
294 // how to deal with compressed sections. This routine doesn't say for
295 // certain whether we'll compress -- it depends on commandline options
296 // as well -- just whether this section is a candidate for compression.
297 // (The Output_compressed_section class decides whether to compress
298 // a given section, and picks the name of the compressed section.)
300 static bool
301 is_compressible_debug_section(const char* secname)
303 return (is_prefix_of(".debug", secname));
306 // We may see compressed debug sections in input files. Return TRUE
307 // if this is the name of a compressed debug section.
309 bool
310 is_compressed_debug_section(const char* secname)
312 return (is_prefix_of(".zdebug", secname));
315 // Whether to include this section in the link.
317 template<int size, bool big_endian>
318 bool
319 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
320 const elfcpp::Shdr<size, big_endian>& shdr)
322 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
323 return false;
325 switch (shdr.get_sh_type())
327 case elfcpp::SHT_NULL:
328 case elfcpp::SHT_SYMTAB:
329 case elfcpp::SHT_DYNSYM:
330 case elfcpp::SHT_HASH:
331 case elfcpp::SHT_DYNAMIC:
332 case elfcpp::SHT_SYMTAB_SHNDX:
333 return false;
335 case elfcpp::SHT_STRTAB:
336 // Discard the sections which have special meanings in the ELF
337 // ABI. Keep others (e.g., .stabstr). We could also do this by
338 // checking the sh_link fields of the appropriate sections.
339 return (strcmp(name, ".dynstr") != 0
340 && strcmp(name, ".strtab") != 0
341 && strcmp(name, ".shstrtab") != 0);
343 case elfcpp::SHT_RELA:
344 case elfcpp::SHT_REL:
345 case elfcpp::SHT_GROUP:
346 // If we are emitting relocations these should be handled
347 // elsewhere.
348 gold_assert(!parameters->options().relocatable()
349 && !parameters->options().emit_relocs());
350 return false;
352 case elfcpp::SHT_PROGBITS:
353 if (parameters->options().strip_debug()
354 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
356 if (is_debug_info_section(name))
357 return false;
359 if (parameters->options().strip_debug_non_line()
360 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
362 // Debugging sections can only be recognized by name.
363 if (is_prefix_of(".debug", name)
364 && !is_lines_only_debug_section(name))
365 return false;
367 if (parameters->options().strip_debug_gdb()
368 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
370 // Debugging sections can only be recognized by name.
371 if (is_prefix_of(".debug", name)
372 && !is_gdb_debug_section(name))
373 return false;
375 if (parameters->options().strip_lto_sections()
376 && !parameters->options().relocatable()
377 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
379 // Ignore LTO sections containing intermediate code.
380 if (is_prefix_of(".gnu.lto_", name))
381 return false;
383 // The GNU linker strips .gnu_debuglink sections, so we do too.
384 // This is a feature used to keep debugging information in
385 // separate files.
386 if (strcmp(name, ".gnu_debuglink") == 0)
387 return false;
388 return true;
390 default:
391 return true;
395 // Return an output section named NAME, or NULL if there is none.
397 Output_section*
398 Layout::find_output_section(const char* name) const
400 for (Section_list::const_iterator p = this->section_list_.begin();
401 p != this->section_list_.end();
402 ++p)
403 if (strcmp((*p)->name(), name) == 0)
404 return *p;
405 return NULL;
408 // Return an output segment of type TYPE, with segment flags SET set
409 // and segment flags CLEAR clear. Return NULL if there is none.
411 Output_segment*
412 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
413 elfcpp::Elf_Word clear) const
415 for (Segment_list::const_iterator p = this->segment_list_.begin();
416 p != this->segment_list_.end();
417 ++p)
418 if (static_cast<elfcpp::PT>((*p)->type()) == type
419 && ((*p)->flags() & set) == set
420 && ((*p)->flags() & clear) == 0)
421 return *p;
422 return NULL;
425 // Return the output section to use for section NAME with type TYPE
426 // and section flags FLAGS. NAME must be canonicalized in the string
427 // pool, and NAME_KEY is the key. IS_INTERP is true if this is the
428 // .interp section. IS_DYNAMIC_LINKER_SECTION is true if this section
429 // is used by the dynamic linker. IS_RELRO is true for a relro
430 // section. IS_LAST_RELRO is true for the last relro section.
431 // IS_FIRST_NON_RELRO is true for the first non-relro section.
433 Output_section*
434 Layout::get_output_section(const char* name, Stringpool::Key name_key,
435 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
436 Output_section_order order, bool is_relro)
438 elfcpp::Elf_Xword lookup_flags = flags;
440 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
441 // read-write with read-only sections. Some other ELF linkers do
442 // not do this. FIXME: Perhaps there should be an option
443 // controlling this.
444 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
446 const Key key(name_key, std::make_pair(type, lookup_flags));
447 const std::pair<Key, Output_section*> v(key, NULL);
448 std::pair<Section_name_map::iterator, bool> ins(
449 this->section_name_map_.insert(v));
451 if (!ins.second)
452 return ins.first->second;
453 else
455 // This is the first time we've seen this name/type/flags
456 // combination. For compatibility with the GNU linker, we
457 // combine sections with contents and zero flags with sections
458 // with non-zero flags. This is a workaround for cases where
459 // assembler code forgets to set section flags. FIXME: Perhaps
460 // there should be an option to control this.
461 Output_section* os = NULL;
463 if (type == elfcpp::SHT_PROGBITS)
465 if (flags == 0)
467 Output_section* same_name = this->find_output_section(name);
468 if (same_name != NULL
469 && same_name->type() == elfcpp::SHT_PROGBITS
470 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
471 os = same_name;
473 else if ((flags & elfcpp::SHF_TLS) == 0)
475 elfcpp::Elf_Xword zero_flags = 0;
476 const Key zero_key(name_key, std::make_pair(type, zero_flags));
477 Section_name_map::iterator p =
478 this->section_name_map_.find(zero_key);
479 if (p != this->section_name_map_.end())
480 os = p->second;
484 if (os == NULL)
485 os = this->make_output_section(name, type, flags, order, is_relro);
487 ins.first->second = os;
488 return os;
492 // Pick the output section to use for section NAME, in input file
493 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
494 // linker created section. IS_INPUT_SECTION is true if we are
495 // choosing an output section for an input section found in a input
496 // file. IS_INTERP is true if this is the .interp section.
497 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
498 // dynamic linker. IS_RELRO is true for a relro section.
499 // IS_LAST_RELRO is true for the last relro section.
500 // IS_FIRST_NON_RELRO is true for the first non-relro section. This
501 // will return NULL if the input section should be discarded.
503 Output_section*
504 Layout::choose_output_section(const Relobj* relobj, const char* name,
505 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
506 bool is_input_section, Output_section_order order,
507 bool is_relro)
509 // We should not see any input sections after we have attached
510 // sections to segments.
511 gold_assert(!is_input_section || !this->sections_are_attached_);
513 // Some flags in the input section should not be automatically
514 // copied to the output section.
515 flags &= ~ (elfcpp::SHF_INFO_LINK
516 | elfcpp::SHF_GROUP
517 | elfcpp::SHF_MERGE
518 | elfcpp::SHF_STRINGS);
520 // We only clear the SHF_LINK_ORDER flag in for
521 // a non-relocatable link.
522 if (!parameters->options().relocatable())
523 flags &= ~elfcpp::SHF_LINK_ORDER;
525 if (this->script_options_->saw_sections_clause())
527 // We are using a SECTIONS clause, so the output section is
528 // chosen based only on the name.
530 Script_sections* ss = this->script_options_->script_sections();
531 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
532 Output_section** output_section_slot;
533 Script_sections::Section_type script_section_type;
534 const char* orig_name = name;
535 name = ss->output_section_name(file_name, name, &output_section_slot,
536 &script_section_type);
537 if (name == NULL)
539 gold_debug(DEBUG_SCRIPT, _("Unable to create output section '%s' "
540 "because it is not allowed by the "
541 "SECTIONS clause of the linker script"),
542 orig_name);
543 // The SECTIONS clause says to discard this input section.
544 return NULL;
547 // We can only handle script section types ST_NONE and ST_NOLOAD.
548 switch (script_section_type)
550 case Script_sections::ST_NONE:
551 break;
552 case Script_sections::ST_NOLOAD:
553 flags &= elfcpp::SHF_ALLOC;
554 break;
555 default:
556 gold_unreachable();
559 // If this is an orphan section--one not mentioned in the linker
560 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
561 // default processing below.
563 if (output_section_slot != NULL)
565 if (*output_section_slot != NULL)
567 (*output_section_slot)->update_flags_for_input_section(flags);
568 return *output_section_slot;
571 // We don't put sections found in the linker script into
572 // SECTION_NAME_MAP_. That keeps us from getting confused
573 // if an orphan section is mapped to a section with the same
574 // name as one in the linker script.
576 name = this->namepool_.add(name, false, NULL);
578 Output_section* os = this->make_output_section(name, type, flags,
579 order, is_relro);
581 os->set_found_in_sections_clause();
583 // Special handling for NOLOAD sections.
584 if (script_section_type == Script_sections::ST_NOLOAD)
586 os->set_is_noload();
588 // The constructor of Output_section sets addresses of non-ALLOC
589 // sections to 0 by default. We don't want that for NOLOAD
590 // sections even if they have no SHF_ALLOC flag.
591 if ((os->flags() & elfcpp::SHF_ALLOC) == 0
592 && os->is_address_valid())
594 gold_assert(os->address() == 0
595 && !os->is_offset_valid()
596 && !os->is_data_size_valid());
597 os->reset_address_and_file_offset();
601 *output_section_slot = os;
602 return os;
606 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
608 size_t len = strlen(name);
609 char* uncompressed_name = NULL;
611 // Compressed debug sections should be mapped to the corresponding
612 // uncompressed section.
613 if (is_compressed_debug_section(name))
615 uncompressed_name = new char[len];
616 uncompressed_name[0] = '.';
617 gold_assert(name[0] == '.' && name[1] == 'z');
618 strncpy(&uncompressed_name[1], &name[2], len - 2);
619 uncompressed_name[len - 1] = '\0';
620 len -= 1;
621 name = uncompressed_name;
624 // Turn NAME from the name of the input section into the name of the
625 // output section.
626 if (is_input_section
627 && !this->script_options_->saw_sections_clause()
628 && !parameters->options().relocatable())
629 name = Layout::output_section_name(name, &len);
631 Stringpool::Key name_key;
632 name = this->namepool_.add_with_length(name, len, true, &name_key);
634 if (uncompressed_name != NULL)
635 delete[] uncompressed_name;
637 // Find or make the output section. The output section is selected
638 // based on the section name, type, and flags.
639 return this->get_output_section(name, name_key, type, flags, order, is_relro);
642 // Return the output section to use for input section SHNDX, with name
643 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
644 // index of a relocation section which applies to this section, or 0
645 // if none, or -1U if more than one. RELOC_TYPE is the type of the
646 // relocation section if there is one. Set *OFF to the offset of this
647 // input section without the output section. Return NULL if the
648 // section should be discarded. Set *OFF to -1 if the section
649 // contents should not be written directly to the output file, but
650 // will instead receive special handling.
652 template<int size, bool big_endian>
653 Output_section*
654 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
655 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
656 unsigned int reloc_shndx, unsigned int, off_t* off)
658 *off = 0;
660 if (!this->include_section(object, name, shdr))
661 return NULL;
663 Output_section* os;
665 // Sometimes .init_array*, .preinit_array* and .fini_array* do not have
666 // correct section types. Force them here.
667 elfcpp::Elf_Word sh_type = shdr.get_sh_type();
668 if (sh_type == elfcpp::SHT_PROGBITS)
670 static const char init_array_prefix[] = ".init_array";
671 static const char preinit_array_prefix[] = ".preinit_array";
672 static const char fini_array_prefix[] = ".fini_array";
673 static size_t init_array_prefix_size = sizeof(init_array_prefix) - 1;
674 static size_t preinit_array_prefix_size =
675 sizeof(preinit_array_prefix) - 1;
676 static size_t fini_array_prefix_size = sizeof(fini_array_prefix) - 1;
678 if (strncmp(name, init_array_prefix, init_array_prefix_size) == 0)
679 sh_type = elfcpp::SHT_INIT_ARRAY;
680 else if (strncmp(name, preinit_array_prefix, preinit_array_prefix_size)
681 == 0)
682 sh_type = elfcpp::SHT_PREINIT_ARRAY;
683 else if (strncmp(name, fini_array_prefix, fini_array_prefix_size) == 0)
684 sh_type = elfcpp::SHT_FINI_ARRAY;
687 // In a relocatable link a grouped section must not be combined with
688 // any other sections.
689 if (parameters->options().relocatable()
690 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
692 name = this->namepool_.add(name, true, NULL);
693 os = this->make_output_section(name, sh_type, shdr.get_sh_flags(),
694 ORDER_INVALID, false);
696 else
698 os = this->choose_output_section(object, name, sh_type,
699 shdr.get_sh_flags(), true,
700 ORDER_INVALID, false);
701 if (os == NULL)
702 return NULL;
705 // By default the GNU linker sorts input sections whose names match
706 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
707 // are sorted by name. This is used to implement constructor
708 // priority ordering. We are compatible.
709 if (!this->script_options_->saw_sections_clause()
710 && (is_prefix_of(".ctors.", name)
711 || is_prefix_of(".dtors.", name)
712 || is_prefix_of(".init_array.", name)
713 || is_prefix_of(".fini_array.", name)))
714 os->set_must_sort_attached_input_sections();
716 // FIXME: Handle SHF_LINK_ORDER somewhere.
718 *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
719 this->script_options_->saw_sections_clause());
720 this->have_added_input_section_ = true;
722 return os;
725 // Handle a relocation section when doing a relocatable link.
727 template<int size, bool big_endian>
728 Output_section*
729 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
730 unsigned int,
731 const elfcpp::Shdr<size, big_endian>& shdr,
732 Output_section* data_section,
733 Relocatable_relocs* rr)
735 gold_assert(parameters->options().relocatable()
736 || parameters->options().emit_relocs());
738 int sh_type = shdr.get_sh_type();
740 std::string name;
741 if (sh_type == elfcpp::SHT_REL)
742 name = ".rel";
743 else if (sh_type == elfcpp::SHT_RELA)
744 name = ".rela";
745 else
746 gold_unreachable();
747 name += data_section->name();
749 // In a relocatable link relocs for a grouped section must not be
750 // combined with other reloc sections.
751 Output_section* os;
752 if (!parameters->options().relocatable()
753 || (data_section->flags() & elfcpp::SHF_GROUP) == 0)
754 os = this->choose_output_section(object, name.c_str(), sh_type,
755 shdr.get_sh_flags(), false,
756 ORDER_INVALID, false);
757 else
759 const char* n = this->namepool_.add(name.c_str(), true, NULL);
760 os = this->make_output_section(n, sh_type, shdr.get_sh_flags(),
761 ORDER_INVALID, false);
764 os->set_should_link_to_symtab();
765 os->set_info_section(data_section);
767 Output_section_data* posd;
768 if (sh_type == elfcpp::SHT_REL)
770 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
771 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
772 size,
773 big_endian>(rr);
775 else if (sh_type == elfcpp::SHT_RELA)
777 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
778 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
779 size,
780 big_endian>(rr);
782 else
783 gold_unreachable();
785 os->add_output_section_data(posd);
786 rr->set_output_data(posd);
788 return os;
791 // Handle a group section when doing a relocatable link.
793 template<int size, bool big_endian>
794 void
795 Layout::layout_group(Symbol_table* symtab,
796 Sized_relobj<size, big_endian>* object,
797 unsigned int,
798 const char* group_section_name,
799 const char* signature,
800 const elfcpp::Shdr<size, big_endian>& shdr,
801 elfcpp::Elf_Word flags,
802 std::vector<unsigned int>* shndxes)
804 gold_assert(parameters->options().relocatable());
805 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
806 group_section_name = this->namepool_.add(group_section_name, true, NULL);
807 Output_section* os = this->make_output_section(group_section_name,
808 elfcpp::SHT_GROUP,
809 shdr.get_sh_flags(),
810 ORDER_INVALID, false);
812 // We need to find a symbol with the signature in the symbol table.
813 // If we don't find one now, we need to look again later.
814 Symbol* sym = symtab->lookup(signature, NULL);
815 if (sym != NULL)
816 os->set_info_symndx(sym);
817 else
819 // Reserve some space to minimize reallocations.
820 if (this->group_signatures_.empty())
821 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
823 // We will wind up using a symbol whose name is the signature.
824 // So just put the signature in the symbol name pool to save it.
825 signature = symtab->canonicalize_name(signature);
826 this->group_signatures_.push_back(Group_signature(os, signature));
829 os->set_should_link_to_symtab();
830 os->set_entsize(4);
832 section_size_type entry_count =
833 convert_to_section_size_type(shdr.get_sh_size() / 4);
834 Output_section_data* posd =
835 new Output_data_group<size, big_endian>(object, entry_count, flags,
836 shndxes);
837 os->add_output_section_data(posd);
840 // Special GNU handling of sections name .eh_frame. They will
841 // normally hold exception frame data as defined by the C++ ABI
842 // (http://codesourcery.com/cxx-abi/).
844 template<int size, bool big_endian>
845 Output_section*
846 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
847 const unsigned char* symbols,
848 off_t symbols_size,
849 const unsigned char* symbol_names,
850 off_t symbol_names_size,
851 unsigned int shndx,
852 const elfcpp::Shdr<size, big_endian>& shdr,
853 unsigned int reloc_shndx, unsigned int reloc_type,
854 off_t* off)
856 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
857 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
859 const char* const name = ".eh_frame";
860 Output_section* os = this->choose_output_section(object, name,
861 elfcpp::SHT_PROGBITS,
862 elfcpp::SHF_ALLOC, false,
863 ORDER_EHFRAME, false);
864 if (os == NULL)
865 return NULL;
867 if (this->eh_frame_section_ == NULL)
869 this->eh_frame_section_ = os;
870 this->eh_frame_data_ = new Eh_frame();
872 if (parameters->options().eh_frame_hdr())
874 Output_section* hdr_os =
875 this->choose_output_section(NULL, ".eh_frame_hdr",
876 elfcpp::SHT_PROGBITS,
877 elfcpp::SHF_ALLOC, false,
878 ORDER_EHFRAME, false);
880 if (hdr_os != NULL)
882 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
883 this->eh_frame_data_);
884 hdr_os->add_output_section_data(hdr_posd);
886 hdr_os->set_after_input_sections();
888 if (!this->script_options_->saw_phdrs_clause())
890 Output_segment* hdr_oseg;
891 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
892 elfcpp::PF_R);
893 hdr_oseg->add_output_section_to_nonload(hdr_os,
894 elfcpp::PF_R);
897 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
902 gold_assert(this->eh_frame_section_ == os);
904 if (this->eh_frame_data_->add_ehframe_input_section(object,
905 symbols,
906 symbols_size,
907 symbol_names,
908 symbol_names_size,
909 shndx,
910 reloc_shndx,
911 reloc_type))
913 os->update_flags_for_input_section(shdr.get_sh_flags());
915 // We found a .eh_frame section we are going to optimize, so now
916 // we can add the set of optimized sections to the output
917 // section. We need to postpone adding this until we've found a
918 // section we can optimize so that the .eh_frame section in
919 // crtbegin.o winds up at the start of the output section.
920 if (!this->added_eh_frame_data_)
922 os->add_output_section_data(this->eh_frame_data_);
923 this->added_eh_frame_data_ = true;
925 *off = -1;
927 else
929 // We couldn't handle this .eh_frame section for some reason.
930 // Add it as a normal section.
931 bool saw_sections_clause = this->script_options_->saw_sections_clause();
932 *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
933 saw_sections_clause);
934 this->have_added_input_section_ = true;
937 return os;
940 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
941 // the output section.
943 Output_section*
944 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
945 elfcpp::Elf_Xword flags,
946 Output_section_data* posd,
947 Output_section_order order, bool is_relro)
949 Output_section* os = this->choose_output_section(NULL, name, type, flags,
950 false, order, is_relro);
951 if (os != NULL)
952 os->add_output_section_data(posd);
953 return os;
956 // Map section flags to segment flags.
958 elfcpp::Elf_Word
959 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
961 elfcpp::Elf_Word ret = elfcpp::PF_R;
962 if ((flags & elfcpp::SHF_WRITE) != 0)
963 ret |= elfcpp::PF_W;
964 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
965 ret |= elfcpp::PF_X;
966 return ret;
969 // Make a new Output_section, and attach it to segments as
970 // appropriate. ORDER is the order in which this section should
971 // appear in the output segment. IS_RELRO is true if this is a relro
972 // (read-only after relocations) section.
974 Output_section*
975 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
976 elfcpp::Elf_Xword flags,
977 Output_section_order order, bool is_relro)
979 Output_section* os;
980 if ((flags & elfcpp::SHF_ALLOC) == 0
981 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
982 && is_compressible_debug_section(name))
983 os = new Output_compressed_section(&parameters->options(), name, type,
984 flags);
985 else if ((flags & elfcpp::SHF_ALLOC) == 0
986 && parameters->options().strip_debug_non_line()
987 && strcmp(".debug_abbrev", name) == 0)
989 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
990 name, type, flags);
991 if (this->debug_info_)
992 this->debug_info_->set_abbreviations(this->debug_abbrev_);
994 else if ((flags & elfcpp::SHF_ALLOC) == 0
995 && parameters->options().strip_debug_non_line()
996 && strcmp(".debug_info", name) == 0)
998 os = this->debug_info_ = new Output_reduced_debug_info_section(
999 name, type, flags);
1000 if (this->debug_abbrev_)
1001 this->debug_info_->set_abbreviations(this->debug_abbrev_);
1003 else
1005 // FIXME: const_cast is ugly.
1006 Target* target = const_cast<Target*>(&parameters->target());
1007 os = target->make_output_section(name, type, flags);
1010 // With -z relro, we have to recognize the special sections by name.
1011 // There is no other way.
1012 bool is_relro_local = false;
1013 if (!this->script_options_->saw_sections_clause()
1014 && parameters->options().relro()
1015 && type == elfcpp::SHT_PROGBITS
1016 && (flags & elfcpp::SHF_ALLOC) != 0
1017 && (flags & elfcpp::SHF_WRITE) != 0)
1019 if (strcmp(name, ".data.rel.ro") == 0)
1020 is_relro = true;
1021 else if (strcmp(name, ".data.rel.ro.local") == 0)
1023 is_relro = true;
1024 is_relro_local = true;
1026 else if (type == elfcpp::SHT_INIT_ARRAY
1027 || type == elfcpp::SHT_FINI_ARRAY
1028 || type == elfcpp::SHT_PREINIT_ARRAY)
1029 is_relro = true;
1030 else if (strcmp(name, ".ctors") == 0
1031 || strcmp(name, ".dtors") == 0
1032 || strcmp(name, ".jcr") == 0)
1033 is_relro = true;
1036 if (is_relro)
1037 os->set_is_relro();
1039 if (order == ORDER_INVALID && (flags & elfcpp::SHF_ALLOC) != 0)
1040 order = this->default_section_order(os, is_relro_local);
1042 os->set_order(order);
1044 parameters->target().new_output_section(os);
1046 this->section_list_.push_back(os);
1048 // The GNU linker by default sorts some sections by priority, so we
1049 // do the same. We need to know that this might happen before we
1050 // attach any input sections.
1051 if (!this->script_options_->saw_sections_clause()
1052 && (strcmp(name, ".ctors") == 0
1053 || strcmp(name, ".dtors") == 0
1054 || strcmp(name, ".init_array") == 0
1055 || strcmp(name, ".fini_array") == 0))
1056 os->set_may_sort_attached_input_sections();
1058 // Check for .stab*str sections, as .stab* sections need to link to
1059 // them.
1060 if (type == elfcpp::SHT_STRTAB
1061 && !this->have_stabstr_section_
1062 && strncmp(name, ".stab", 5) == 0
1063 && strcmp(name + strlen(name) - 3, "str") == 0)
1064 this->have_stabstr_section_ = true;
1066 // If we have already attached the sections to segments, then we
1067 // need to attach this one now. This happens for sections created
1068 // directly by the linker.
1069 if (this->sections_are_attached_)
1070 this->attach_section_to_segment(os);
1072 return os;
1075 // Return the default order in which a section should be placed in an
1076 // output segment. This function captures a lot of the ideas in
1077 // ld/scripttempl/elf.sc in the GNU linker. Note that the order of a
1078 // linker created section is normally set when the section is created;
1079 // this function is used for input sections.
1081 Output_section_order
1082 Layout::default_section_order(Output_section* os, bool is_relro_local)
1084 gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
1085 bool is_write = (os->flags() & elfcpp::SHF_WRITE) != 0;
1086 bool is_execinstr = (os->flags() & elfcpp::SHF_EXECINSTR) != 0;
1087 bool is_bss = false;
1089 switch (os->type())
1091 default:
1092 case elfcpp::SHT_PROGBITS:
1093 break;
1094 case elfcpp::SHT_NOBITS:
1095 is_bss = true;
1096 break;
1097 case elfcpp::SHT_RELA:
1098 case elfcpp::SHT_REL:
1099 if (!is_write)
1100 return ORDER_DYNAMIC_RELOCS;
1101 break;
1102 case elfcpp::SHT_HASH:
1103 case elfcpp::SHT_DYNAMIC:
1104 case elfcpp::SHT_SHLIB:
1105 case elfcpp::SHT_DYNSYM:
1106 case elfcpp::SHT_GNU_HASH:
1107 case elfcpp::SHT_GNU_verdef:
1108 case elfcpp::SHT_GNU_verneed:
1109 case elfcpp::SHT_GNU_versym:
1110 if (!is_write)
1111 return ORDER_DYNAMIC_LINKER;
1112 break;
1113 case elfcpp::SHT_NOTE:
1114 return is_write ? ORDER_RW_NOTE : ORDER_RO_NOTE;
1117 if ((os->flags() & elfcpp::SHF_TLS) != 0)
1118 return is_bss ? ORDER_TLS_BSS : ORDER_TLS_DATA;
1120 if (!is_bss && !is_write)
1122 if (is_execinstr)
1124 if (strcmp(os->name(), ".init") == 0)
1125 return ORDER_INIT;
1126 else if (strcmp(os->name(), ".fini") == 0)
1127 return ORDER_FINI;
1129 return is_execinstr ? ORDER_TEXT : ORDER_READONLY;
1132 if (os->is_relro())
1133 return is_relro_local ? ORDER_RELRO_LOCAL : ORDER_RELRO;
1135 if (os->is_small_section())
1136 return is_bss ? ORDER_SMALL_BSS : ORDER_SMALL_DATA;
1137 if (os->is_large_section())
1138 return is_bss ? ORDER_LARGE_BSS : ORDER_LARGE_DATA;
1140 return is_bss ? ORDER_BSS : ORDER_DATA;
1143 // Attach output sections to segments. This is called after we have
1144 // seen all the input sections.
1146 void
1147 Layout::attach_sections_to_segments()
1149 for (Section_list::iterator p = this->section_list_.begin();
1150 p != this->section_list_.end();
1151 ++p)
1152 this->attach_section_to_segment(*p);
1154 this->sections_are_attached_ = true;
1157 // Attach an output section to a segment.
1159 void
1160 Layout::attach_section_to_segment(Output_section* os)
1162 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1163 this->unattached_section_list_.push_back(os);
1164 else
1165 this->attach_allocated_section_to_segment(os);
1168 // Attach an allocated output section to a segment.
1170 void
1171 Layout::attach_allocated_section_to_segment(Output_section* os)
1173 elfcpp::Elf_Xword flags = os->flags();
1174 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
1176 if (parameters->options().relocatable())
1177 return;
1179 // If we have a SECTIONS clause, we can't handle the attachment to
1180 // segments until after we've seen all the sections.
1181 if (this->script_options_->saw_sections_clause())
1182 return;
1184 gold_assert(!this->script_options_->saw_phdrs_clause());
1186 // This output section goes into a PT_LOAD segment.
1188 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
1190 // Check for --section-start.
1191 uint64_t addr;
1192 bool is_address_set = parameters->options().section_start(os->name(), &addr);
1194 // In general the only thing we really care about for PT_LOAD
1195 // segments is whether or not they are writable or executable,
1196 // so that is how we search for them.
1197 // Large data sections also go into their own PT_LOAD segment.
1198 // People who need segments sorted on some other basis will
1199 // have to use a linker script.
1201 Segment_list::const_iterator p;
1202 for (p = this->segment_list_.begin();
1203 p != this->segment_list_.end();
1204 ++p)
1206 if ((*p)->type() != elfcpp::PT_LOAD)
1207 continue;
1208 if (!parameters->options().omagic()
1209 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1210 continue;
1211 if (parameters->options().rosegment()
1212 && ((*p)->flags() & elfcpp::PF_X) != (seg_flags & elfcpp::PF_X))
1213 continue;
1214 // If -Tbss was specified, we need to separate the data and BSS
1215 // segments.
1216 if (parameters->options().user_set_Tbss())
1218 if ((os->type() == elfcpp::SHT_NOBITS)
1219 == (*p)->has_any_data_sections())
1220 continue;
1222 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1223 continue;
1225 if (is_address_set)
1227 if ((*p)->are_addresses_set())
1228 continue;
1230 (*p)->add_initial_output_data(os);
1231 (*p)->update_flags_for_output_section(seg_flags);
1232 (*p)->set_addresses(addr, addr);
1233 break;
1236 (*p)->add_output_section_to_load(this, os, seg_flags);
1237 break;
1240 if (p == this->segment_list_.end())
1242 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1243 seg_flags);
1244 if (os->is_large_data_section())
1245 oseg->set_is_large_data_segment();
1246 oseg->add_output_section_to_load(this, os, seg_flags);
1247 if (is_address_set)
1248 oseg->set_addresses(addr, addr);
1251 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1252 // segment.
1253 if (os->type() == elfcpp::SHT_NOTE)
1255 // See if we already have an equivalent PT_NOTE segment.
1256 for (p = this->segment_list_.begin();
1257 p != segment_list_.end();
1258 ++p)
1260 if ((*p)->type() == elfcpp::PT_NOTE
1261 && (((*p)->flags() & elfcpp::PF_W)
1262 == (seg_flags & elfcpp::PF_W)))
1264 (*p)->add_output_section_to_nonload(os, seg_flags);
1265 break;
1269 if (p == this->segment_list_.end())
1271 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1272 seg_flags);
1273 oseg->add_output_section_to_nonload(os, seg_flags);
1277 // If we see a loadable SHF_TLS section, we create a PT_TLS
1278 // segment. There can only be one such segment.
1279 if ((flags & elfcpp::SHF_TLS) != 0)
1281 if (this->tls_segment_ == NULL)
1282 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1283 this->tls_segment_->add_output_section_to_nonload(os, seg_flags);
1286 // If -z relro is in effect, and we see a relro section, we create a
1287 // PT_GNU_RELRO segment. There can only be one such segment.
1288 if (os->is_relro() && parameters->options().relro())
1290 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1291 if (this->relro_segment_ == NULL)
1292 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1293 this->relro_segment_->add_output_section_to_nonload(os, seg_flags);
1297 // Make an output section for a script.
1299 Output_section*
1300 Layout::make_output_section_for_script(
1301 const char* name,
1302 Script_sections::Section_type section_type)
1304 name = this->namepool_.add(name, false, NULL);
1305 elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
1306 if (section_type == Script_sections::ST_NOLOAD)
1307 sh_flags = 0;
1308 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1309 sh_flags, ORDER_INVALID,
1310 false);
1311 os->set_found_in_sections_clause();
1312 if (section_type == Script_sections::ST_NOLOAD)
1313 os->set_is_noload();
1314 return os;
1317 // Return the number of segments we expect to see.
1319 size_t
1320 Layout::expected_segment_count() const
1322 size_t ret = this->segment_list_.size();
1324 // If we didn't see a SECTIONS clause in a linker script, we should
1325 // already have the complete list of segments. Otherwise we ask the
1326 // SECTIONS clause how many segments it expects, and add in the ones
1327 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1329 if (!this->script_options_->saw_sections_clause())
1330 return ret;
1331 else
1333 const Script_sections* ss = this->script_options_->script_sections();
1334 return ret + ss->expected_segment_count(this);
1338 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1339 // is whether we saw a .note.GNU-stack section in the object file.
1340 // GNU_STACK_FLAGS is the section flags. The flags give the
1341 // protection required for stack memory. We record this in an
1342 // executable as a PT_GNU_STACK segment. If an object file does not
1343 // have a .note.GNU-stack segment, we must assume that it is an old
1344 // object. On some targets that will force an executable stack.
1346 void
1347 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags,
1348 const Object* obj)
1350 if (!seen_gnu_stack)
1352 this->input_without_gnu_stack_note_ = true;
1353 if (parameters->options().warn_execstack()
1354 && parameters->target().is_default_stack_executable())
1355 gold_warning(_("%s: missing .note.GNU-stack section"
1356 " implies executable stack"),
1357 obj->name().c_str());
1359 else
1361 this->input_with_gnu_stack_note_ = true;
1362 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1364 this->input_requires_executable_stack_ = true;
1365 if (parameters->options().warn_execstack()
1366 || parameters->options().is_stack_executable())
1367 gold_warning(_("%s: requires executable stack"),
1368 obj->name().c_str());
1373 // Create automatic note sections.
1375 void
1376 Layout::create_notes()
1378 this->create_gold_note();
1379 this->create_executable_stack_info();
1380 this->create_build_id();
1383 // Create the dynamic sections which are needed before we read the
1384 // relocs.
1386 void
1387 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1389 if (parameters->doing_static_link())
1390 return;
1392 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1393 elfcpp::SHT_DYNAMIC,
1394 (elfcpp::SHF_ALLOC
1395 | elfcpp::SHF_WRITE),
1396 false, ORDER_RELRO,
1397 true);
1399 this->dynamic_symbol_ =
1400 symtab->define_in_output_data("_DYNAMIC", NULL, Symbol_table::PREDEFINED,
1401 this->dynamic_section_, 0, 0,
1402 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1403 elfcpp::STV_HIDDEN, 0, false, false);
1405 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1407 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1410 // For each output section whose name can be represented as C symbol,
1411 // define __start and __stop symbols for the section. This is a GNU
1412 // extension.
1414 void
1415 Layout::define_section_symbols(Symbol_table* symtab)
1417 for (Section_list::const_iterator p = this->section_list_.begin();
1418 p != this->section_list_.end();
1419 ++p)
1421 const char* const name = (*p)->name();
1422 if (is_cident(name))
1424 const std::string name_string(name);
1425 const std::string start_name(cident_section_start_prefix
1426 + name_string);
1427 const std::string stop_name(cident_section_stop_prefix
1428 + name_string);
1430 symtab->define_in_output_data(start_name.c_str(),
1431 NULL, // version
1432 Symbol_table::PREDEFINED,
1434 0, // value
1435 0, // symsize
1436 elfcpp::STT_NOTYPE,
1437 elfcpp::STB_GLOBAL,
1438 elfcpp::STV_DEFAULT,
1439 0, // nonvis
1440 false, // offset_is_from_end
1441 true); // only_if_ref
1443 symtab->define_in_output_data(stop_name.c_str(),
1444 NULL, // version
1445 Symbol_table::PREDEFINED,
1447 0, // value
1448 0, // symsize
1449 elfcpp::STT_NOTYPE,
1450 elfcpp::STB_GLOBAL,
1451 elfcpp::STV_DEFAULT,
1452 0, // nonvis
1453 true, // offset_is_from_end
1454 true); // only_if_ref
1459 // Define symbols for group signatures.
1461 void
1462 Layout::define_group_signatures(Symbol_table* symtab)
1464 for (Group_signatures::iterator p = this->group_signatures_.begin();
1465 p != this->group_signatures_.end();
1466 ++p)
1468 Symbol* sym = symtab->lookup(p->signature, NULL);
1469 if (sym != NULL)
1470 p->section->set_info_symndx(sym);
1471 else
1473 // Force the name of the group section to the group
1474 // signature, and use the group's section symbol as the
1475 // signature symbol.
1476 if (strcmp(p->section->name(), p->signature) != 0)
1478 const char* name = this->namepool_.add(p->signature,
1479 true, NULL);
1480 p->section->set_name(name);
1482 p->section->set_needs_symtab_index();
1483 p->section->set_info_section_symndx(p->section);
1487 this->group_signatures_.clear();
1490 // Find the first read-only PT_LOAD segment, creating one if
1491 // necessary.
1493 Output_segment*
1494 Layout::find_first_load_seg()
1496 Output_segment* best = NULL;
1497 for (Segment_list::const_iterator p = this->segment_list_.begin();
1498 p != this->segment_list_.end();
1499 ++p)
1501 if ((*p)->type() == elfcpp::PT_LOAD
1502 && ((*p)->flags() & elfcpp::PF_R) != 0
1503 && (parameters->options().omagic()
1504 || ((*p)->flags() & elfcpp::PF_W) == 0))
1506 if (best == NULL || this->segment_precedes(*p, best))
1507 best = *p;
1510 if (best != NULL)
1511 return best;
1513 gold_assert(!this->script_options_->saw_phdrs_clause());
1515 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1516 elfcpp::PF_R);
1517 return load_seg;
1520 // Save states of all current output segments. Store saved states
1521 // in SEGMENT_STATES.
1523 void
1524 Layout::save_segments(Segment_states* segment_states)
1526 for (Segment_list::const_iterator p = this->segment_list_.begin();
1527 p != this->segment_list_.end();
1528 ++p)
1530 Output_segment* segment = *p;
1531 // Shallow copy.
1532 Output_segment* copy = new Output_segment(*segment);
1533 (*segment_states)[segment] = copy;
1537 // Restore states of output segments and delete any segment not found in
1538 // SEGMENT_STATES.
1540 void
1541 Layout::restore_segments(const Segment_states* segment_states)
1543 // Go through the segment list and remove any segment added in the
1544 // relaxation loop.
1545 this->tls_segment_ = NULL;
1546 this->relro_segment_ = NULL;
1547 Segment_list::iterator list_iter = this->segment_list_.begin();
1548 while (list_iter != this->segment_list_.end())
1550 Output_segment* segment = *list_iter;
1551 Segment_states::const_iterator states_iter =
1552 segment_states->find(segment);
1553 if (states_iter != segment_states->end())
1555 const Output_segment* copy = states_iter->second;
1556 // Shallow copy to restore states.
1557 *segment = *copy;
1559 // Also fix up TLS and RELRO segment pointers as appropriate.
1560 if (segment->type() == elfcpp::PT_TLS)
1561 this->tls_segment_ = segment;
1562 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1563 this->relro_segment_ = segment;
1565 ++list_iter;
1567 else
1569 list_iter = this->segment_list_.erase(list_iter);
1570 // This is a segment created during section layout. It should be
1571 // safe to remove it since we should have removed all pointers to it.
1572 delete segment;
1577 // Clean up after relaxation so that sections can be laid out again.
1579 void
1580 Layout::clean_up_after_relaxation()
1582 // Restore the segments to point state just prior to the relaxation loop.
1583 Script_sections* script_section = this->script_options_->script_sections();
1584 script_section->release_segments();
1585 this->restore_segments(this->segment_states_);
1587 // Reset section addresses and file offsets
1588 for (Section_list::iterator p = this->section_list_.begin();
1589 p != this->section_list_.end();
1590 ++p)
1592 (*p)->restore_states();
1594 // If an input section changes size because of relaxation,
1595 // we need to adjust the section offsets of all input sections.
1596 // after such a section.
1597 if ((*p)->section_offsets_need_adjustment())
1598 (*p)->adjust_section_offsets();
1600 (*p)->reset_address_and_file_offset();
1603 // Reset special output object address and file offsets.
1604 for (Data_list::iterator p = this->special_output_list_.begin();
1605 p != this->special_output_list_.end();
1606 ++p)
1607 (*p)->reset_address_and_file_offset();
1609 // A linker script may have created some output section data objects.
1610 // They are useless now.
1611 for (Output_section_data_list::const_iterator p =
1612 this->script_output_section_data_list_.begin();
1613 p != this->script_output_section_data_list_.end();
1614 ++p)
1615 delete *p;
1616 this->script_output_section_data_list_.clear();
1619 // Prepare for relaxation.
1621 void
1622 Layout::prepare_for_relaxation()
1624 // Create an relaxation debug check if in debugging mode.
1625 if (is_debugging_enabled(DEBUG_RELAXATION))
1626 this->relaxation_debug_check_ = new Relaxation_debug_check();
1628 // Save segment states.
1629 this->segment_states_ = new Segment_states();
1630 this->save_segments(this->segment_states_);
1632 for(Section_list::const_iterator p = this->section_list_.begin();
1633 p != this->section_list_.end();
1634 ++p)
1635 (*p)->save_states();
1637 if (is_debugging_enabled(DEBUG_RELAXATION))
1638 this->relaxation_debug_check_->check_output_data_for_reset_values(
1639 this->section_list_, this->special_output_list_);
1641 // Also enable recording of output section data from scripts.
1642 this->record_output_section_data_from_script_ = true;
1645 // Relaxation loop body: If target has no relaxation, this runs only once
1646 // Otherwise, the target relaxation hook is called at the end of
1647 // each iteration. If the hook returns true, it means re-layout of
1648 // section is required.
1650 // The number of segments created by a linking script without a PHDRS
1651 // clause may be affected by section sizes and alignments. There is
1652 // a remote chance that relaxation causes different number of PT_LOAD
1653 // segments are created and sections are attached to different segments.
1654 // Therefore, we always throw away all segments created during section
1655 // layout. In order to be able to restart the section layout, we keep
1656 // a copy of the segment list right before the relaxation loop and use
1657 // that to restore the segments.
1659 // PASS is the current relaxation pass number.
1660 // SYMTAB is a symbol table.
1661 // PLOAD_SEG is the address of a pointer for the load segment.
1662 // PHDR_SEG is a pointer to the PHDR segment.
1663 // SEGMENT_HEADERS points to the output segment header.
1664 // FILE_HEADER points to the output file header.
1665 // PSHNDX is the address to store the output section index.
1667 off_t inline
1668 Layout::relaxation_loop_body(
1669 int pass,
1670 Target* target,
1671 Symbol_table* symtab,
1672 Output_segment** pload_seg,
1673 Output_segment* phdr_seg,
1674 Output_segment_headers* segment_headers,
1675 Output_file_header* file_header,
1676 unsigned int* pshndx)
1678 // If this is not the first iteration, we need to clean up after
1679 // relaxation so that we can lay out the sections again.
1680 if (pass != 0)
1681 this->clean_up_after_relaxation();
1683 // If there is a SECTIONS clause, put all the input sections into
1684 // the required order.
1685 Output_segment* load_seg;
1686 if (this->script_options_->saw_sections_clause())
1687 load_seg = this->set_section_addresses_from_script(symtab);
1688 else if (parameters->options().relocatable())
1689 load_seg = NULL;
1690 else
1691 load_seg = this->find_first_load_seg();
1693 if (parameters->options().oformat_enum()
1694 != General_options::OBJECT_FORMAT_ELF)
1695 load_seg = NULL;
1697 // If the user set the address of the text segment, that may not be
1698 // compatible with putting the segment headers and file headers into
1699 // that segment.
1700 if (parameters->options().user_set_Ttext())
1701 load_seg = NULL;
1703 gold_assert(phdr_seg == NULL
1704 || load_seg != NULL
1705 || this->script_options_->saw_sections_clause());
1707 // If the address of the load segment we found has been set by
1708 // --section-start rather than by a script, then adjust the VMA and
1709 // LMA downward if possible to include the file and section headers.
1710 uint64_t header_gap = 0;
1711 if (load_seg != NULL
1712 && load_seg->are_addresses_set()
1713 && !this->script_options_->saw_sections_clause()
1714 && !parameters->options().relocatable())
1716 file_header->finalize_data_size();
1717 segment_headers->finalize_data_size();
1718 size_t sizeof_headers = (file_header->data_size()
1719 + segment_headers->data_size());
1720 const uint64_t abi_pagesize = target->abi_pagesize();
1721 uint64_t hdr_paddr = load_seg->paddr() - sizeof_headers;
1722 hdr_paddr &= ~(abi_pagesize - 1);
1723 uint64_t subtract = load_seg->paddr() - hdr_paddr;
1724 if (load_seg->paddr() < subtract || load_seg->vaddr() < subtract)
1725 load_seg = NULL;
1726 else
1728 load_seg->set_addresses(load_seg->vaddr() - subtract,
1729 load_seg->paddr() - subtract);
1730 header_gap = subtract - sizeof_headers;
1734 // Lay out the segment headers.
1735 if (!parameters->options().relocatable())
1737 gold_assert(segment_headers != NULL);
1738 if (header_gap != 0 && load_seg != NULL)
1740 Output_data_zero_fill* z = new Output_data_zero_fill(header_gap, 1);
1741 load_seg->add_initial_output_data(z);
1743 if (load_seg != NULL)
1744 load_seg->add_initial_output_data(segment_headers);
1745 if (phdr_seg != NULL)
1746 phdr_seg->add_initial_output_data(segment_headers);
1749 // Lay out the file header.
1750 if (load_seg != NULL)
1751 load_seg->add_initial_output_data(file_header);
1753 if (this->script_options_->saw_phdrs_clause()
1754 && !parameters->options().relocatable())
1756 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1757 // clause in a linker script.
1758 Script_sections* ss = this->script_options_->script_sections();
1759 ss->put_headers_in_phdrs(file_header, segment_headers);
1762 // We set the output section indexes in set_segment_offsets and
1763 // set_section_indexes.
1764 *pshndx = 1;
1766 // Set the file offsets of all the segments, and all the sections
1767 // they contain.
1768 off_t off;
1769 if (!parameters->options().relocatable())
1770 off = this->set_segment_offsets(target, load_seg, pshndx);
1771 else
1772 off = this->set_relocatable_section_offsets(file_header, pshndx);
1774 // Verify that the dummy relaxation does not change anything.
1775 if (is_debugging_enabled(DEBUG_RELAXATION))
1777 if (pass == 0)
1778 this->relaxation_debug_check_->read_sections(this->section_list_);
1779 else
1780 this->relaxation_debug_check_->verify_sections(this->section_list_);
1783 *pload_seg = load_seg;
1784 return off;
1787 // Search the list of patterns and find the postion of the given section
1788 // name in the output section. If the section name matches a glob
1789 // pattern and a non-glob name, then the non-glob position takes
1790 // precedence. Return 0 if no match is found.
1792 unsigned int
1793 Layout::find_section_order_index(const std::string& section_name)
1795 Unordered_map<std::string, unsigned int>::iterator map_it;
1796 map_it = this->input_section_position_.find(section_name);
1797 if (map_it != this->input_section_position_.end())
1798 return map_it->second;
1800 // Absolute match failed. Linear search the glob patterns.
1801 std::vector<std::string>::iterator it;
1802 for (it = this->input_section_glob_.begin();
1803 it != this->input_section_glob_.end();
1804 ++it)
1806 if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
1808 map_it = this->input_section_position_.find(*it);
1809 gold_assert(map_it != this->input_section_position_.end());
1810 return map_it->second;
1813 return 0;
1816 // Read the sequence of input sections from the file specified with
1817 // --section-ordering-file.
1819 void
1820 Layout::read_layout_from_file()
1822 const char* filename = parameters->options().section_ordering_file();
1823 std::ifstream in;
1824 std::string line;
1826 in.open(filename);
1827 if (!in)
1828 gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
1829 filename, strerror(errno));
1831 std::getline(in, line); // this chops off the trailing \n, if any
1832 unsigned int position = 1;
1834 while (in)
1836 if (!line.empty() && line[line.length() - 1] == '\r') // Windows
1837 line.resize(line.length() - 1);
1838 // Ignore comments, beginning with '#'
1839 if (line[0] == '#')
1841 std::getline(in, line);
1842 continue;
1844 this->input_section_position_[line] = position;
1845 // Store all glob patterns in a vector.
1846 if (is_wildcard_string(line.c_str()))
1847 this->input_section_glob_.push_back(line);
1848 position++;
1849 std::getline(in, line);
1853 // Finalize the layout. When this is called, we have created all the
1854 // output sections and all the output segments which are based on
1855 // input sections. We have several things to do, and we have to do
1856 // them in the right order, so that we get the right results correctly
1857 // and efficiently.
1859 // 1) Finalize the list of output segments and create the segment
1860 // table header.
1862 // 2) Finalize the dynamic symbol table and associated sections.
1864 // 3) Determine the final file offset of all the output segments.
1866 // 4) Determine the final file offset of all the SHF_ALLOC output
1867 // sections.
1869 // 5) Create the symbol table sections and the section name table
1870 // section.
1872 // 6) Finalize the symbol table: set symbol values to their final
1873 // value and make a final determination of which symbols are going
1874 // into the output symbol table.
1876 // 7) Create the section table header.
1878 // 8) Determine the final file offset of all the output sections which
1879 // are not SHF_ALLOC, including the section table header.
1881 // 9) Finalize the ELF file header.
1883 // This function returns the size of the output file.
1885 off_t
1886 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1887 Target* target, const Task* task)
1889 target->finalize_sections(this, input_objects, symtab);
1891 this->count_local_symbols(task, input_objects);
1893 this->link_stabs_sections();
1895 Output_segment* phdr_seg = NULL;
1896 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1898 // There was a dynamic object in the link. We need to create
1899 // some information for the dynamic linker.
1901 // Create the PT_PHDR segment which will hold the program
1902 // headers.
1903 if (!this->script_options_->saw_phdrs_clause())
1904 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1906 // Create the dynamic symbol table, including the hash table.
1907 Output_section* dynstr;
1908 std::vector<Symbol*> dynamic_symbols;
1909 unsigned int local_dynamic_count;
1910 Versions versions(*this->script_options()->version_script_info(),
1911 &this->dynpool_);
1912 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1913 &local_dynamic_count, &dynamic_symbols,
1914 &versions);
1916 // Create the .interp section to hold the name of the
1917 // interpreter, and put it in a PT_INTERP segment.
1918 if (!parameters->options().shared())
1919 this->create_interp(target);
1921 // Finish the .dynamic section to hold the dynamic data, and put
1922 // it in a PT_DYNAMIC segment.
1923 this->finish_dynamic_section(input_objects, symtab);
1925 // We should have added everything we need to the dynamic string
1926 // table.
1927 this->dynpool_.set_string_offsets();
1929 // Create the version sections. We can't do this until the
1930 // dynamic string table is complete.
1931 this->create_version_sections(&versions, symtab, local_dynamic_count,
1932 dynamic_symbols, dynstr);
1934 // Set the size of the _DYNAMIC symbol. We can't do this until
1935 // after we call create_version_sections.
1936 this->set_dynamic_symbol_size(symtab);
1939 // Create segment headers.
1940 Output_segment_headers* segment_headers =
1941 (parameters->options().relocatable()
1942 ? NULL
1943 : new Output_segment_headers(this->segment_list_));
1945 // Lay out the file header.
1946 Output_file_header* file_header
1947 = new Output_file_header(target, symtab, segment_headers,
1948 parameters->options().entry());
1950 this->special_output_list_.push_back(file_header);
1951 if (segment_headers != NULL)
1952 this->special_output_list_.push_back(segment_headers);
1954 // Find approriate places for orphan output sections if we are using
1955 // a linker script.
1956 if (this->script_options_->saw_sections_clause())
1957 this->place_orphan_sections_in_script();
1959 Output_segment* load_seg;
1960 off_t off;
1961 unsigned int shndx;
1962 int pass = 0;
1964 // Take a snapshot of the section layout as needed.
1965 if (target->may_relax())
1966 this->prepare_for_relaxation();
1968 // Run the relaxation loop to lay out sections.
1971 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1972 phdr_seg, segment_headers, file_header,
1973 &shndx);
1974 pass++;
1976 while (target->may_relax()
1977 && target->relax(pass, input_objects, symtab, this, task));
1979 // Set the file offsets of all the non-data sections we've seen so
1980 // far which don't have to wait for the input sections. We need
1981 // this in order to finalize local symbols in non-allocated
1982 // sections.
1983 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1985 // Set the section indexes of all unallocated sections seen so far,
1986 // in case any of them are somehow referenced by a symbol.
1987 shndx = this->set_section_indexes(shndx);
1989 // Create the symbol table sections.
1990 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1991 if (!parameters->doing_static_link())
1992 this->assign_local_dynsym_offsets(input_objects);
1994 // Process any symbol assignments from a linker script. This must
1995 // be called after the symbol table has been finalized.
1996 this->script_options_->finalize_symbols(symtab, this);
1998 // Create the incremental inputs sections.
1999 if (this->incremental_inputs_)
2001 this->incremental_inputs_->finalize();
2002 this->create_incremental_info_sections(symtab);
2005 // Create the .shstrtab section.
2006 Output_section* shstrtab_section = this->create_shstrtab();
2008 // Set the file offsets of the rest of the non-data sections which
2009 // don't have to wait for the input sections.
2010 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
2012 // Now that all sections have been created, set the section indexes
2013 // for any sections which haven't been done yet.
2014 shndx = this->set_section_indexes(shndx);
2016 // Create the section table header.
2017 this->create_shdrs(shstrtab_section, &off);
2019 // If there are no sections which require postprocessing, we can
2020 // handle the section names now, and avoid a resize later.
2021 if (!this->any_postprocessing_sections_)
2023 off = this->set_section_offsets(off,
2024 POSTPROCESSING_SECTIONS_PASS);
2025 off =
2026 this->set_section_offsets(off,
2027 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2030 file_header->set_section_info(this->section_headers_, shstrtab_section);
2032 // Now we know exactly where everything goes in the output file
2033 // (except for non-allocated sections which require postprocessing).
2034 Output_data::layout_complete();
2036 this->output_file_size_ = off;
2038 return off;
2041 // Create a note header following the format defined in the ELF ABI.
2042 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
2043 // of the section to create, DESCSZ is the size of the descriptor.
2044 // ALLOCATE is true if the section should be allocated in memory.
2045 // This returns the new note section. It sets *TRAILING_PADDING to
2046 // the number of trailing zero bytes required.
2048 Output_section*
2049 Layout::create_note(const char* name, int note_type,
2050 const char* section_name, size_t descsz,
2051 bool allocate, size_t* trailing_padding)
2053 // Authorities all agree that the values in a .note field should
2054 // be aligned on 4-byte boundaries for 32-bit binaries. However,
2055 // they differ on what the alignment is for 64-bit binaries.
2056 // The GABI says unambiguously they take 8-byte alignment:
2057 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
2058 // Other documentation says alignment should always be 4 bytes:
2059 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
2060 // GNU ld and GNU readelf both support the latter (at least as of
2061 // version 2.16.91), and glibc always generates the latter for
2062 // .note.ABI-tag (as of version 1.6), so that's the one we go with
2063 // here.
2064 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
2065 const int size = parameters->target().get_size();
2066 #else
2067 const int size = 32;
2068 #endif
2070 // The contents of the .note section.
2071 size_t namesz = strlen(name) + 1;
2072 size_t aligned_namesz = align_address(namesz, size / 8);
2073 size_t aligned_descsz = align_address(descsz, size / 8);
2075 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
2077 unsigned char* buffer = new unsigned char[notehdrsz];
2078 memset(buffer, 0, notehdrsz);
2080 bool is_big_endian = parameters->target().is_big_endian();
2082 if (size == 32)
2084 if (!is_big_endian)
2086 elfcpp::Swap<32, false>::writeval(buffer, namesz);
2087 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
2088 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
2090 else
2092 elfcpp::Swap<32, true>::writeval(buffer, namesz);
2093 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
2094 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
2097 else if (size == 64)
2099 if (!is_big_endian)
2101 elfcpp::Swap<64, false>::writeval(buffer, namesz);
2102 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
2103 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
2105 else
2107 elfcpp::Swap<64, true>::writeval(buffer, namesz);
2108 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
2109 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
2112 else
2113 gold_unreachable();
2115 memcpy(buffer + 3 * (size / 8), name, namesz);
2117 elfcpp::Elf_Xword flags = 0;
2118 Output_section_order order = ORDER_INVALID;
2119 if (allocate)
2121 flags = elfcpp::SHF_ALLOC;
2122 order = ORDER_RO_NOTE;
2124 Output_section* os = this->choose_output_section(NULL, section_name,
2125 elfcpp::SHT_NOTE,
2126 flags, false, order, false);
2127 if (os == NULL)
2128 return NULL;
2130 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
2131 size / 8,
2132 "** note header");
2133 os->add_output_section_data(posd);
2135 *trailing_padding = aligned_descsz - descsz;
2137 return os;
2140 // For an executable or shared library, create a note to record the
2141 // version of gold used to create the binary.
2143 void
2144 Layout::create_gold_note()
2146 if (parameters->options().relocatable())
2147 return;
2149 std::string desc = std::string("gold ") + gold::get_version_string();
2151 size_t trailing_padding;
2152 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
2153 ".note.gnu.gold-version", desc.size(),
2154 false, &trailing_padding);
2155 if (os == NULL)
2156 return;
2158 Output_section_data* posd = new Output_data_const(desc, 4);
2159 os->add_output_section_data(posd);
2161 if (trailing_padding > 0)
2163 posd = new Output_data_zero_fill(trailing_padding, 0);
2164 os->add_output_section_data(posd);
2168 // Record whether the stack should be executable. This can be set
2169 // from the command line using the -z execstack or -z noexecstack
2170 // options. Otherwise, if any input file has a .note.GNU-stack
2171 // section with the SHF_EXECINSTR flag set, the stack should be
2172 // executable. Otherwise, if at least one input file a
2173 // .note.GNU-stack section, and some input file has no .note.GNU-stack
2174 // section, we use the target default for whether the stack should be
2175 // executable. Otherwise, we don't generate a stack note. When
2176 // generating a object file, we create a .note.GNU-stack section with
2177 // the appropriate marking. When generating an executable or shared
2178 // library, we create a PT_GNU_STACK segment.
2180 void
2181 Layout::create_executable_stack_info()
2183 bool is_stack_executable;
2184 if (parameters->options().is_execstack_set())
2185 is_stack_executable = parameters->options().is_stack_executable();
2186 else if (!this->input_with_gnu_stack_note_)
2187 return;
2188 else
2190 if (this->input_requires_executable_stack_)
2191 is_stack_executable = true;
2192 else if (this->input_without_gnu_stack_note_)
2193 is_stack_executable =
2194 parameters->target().is_default_stack_executable();
2195 else
2196 is_stack_executable = false;
2199 if (parameters->options().relocatable())
2201 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
2202 elfcpp::Elf_Xword flags = 0;
2203 if (is_stack_executable)
2204 flags |= elfcpp::SHF_EXECINSTR;
2205 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags,
2206 ORDER_INVALID, false);
2208 else
2210 if (this->script_options_->saw_phdrs_clause())
2211 return;
2212 int flags = elfcpp::PF_R | elfcpp::PF_W;
2213 if (is_stack_executable)
2214 flags |= elfcpp::PF_X;
2215 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
2219 // If --build-id was used, set up the build ID note.
2221 void
2222 Layout::create_build_id()
2224 if (!parameters->options().user_set_build_id())
2225 return;
2227 const char* style = parameters->options().build_id();
2228 if (strcmp(style, "none") == 0)
2229 return;
2231 // Set DESCSZ to the size of the note descriptor. When possible,
2232 // set DESC to the note descriptor contents.
2233 size_t descsz;
2234 std::string desc;
2235 if (strcmp(style, "md5") == 0)
2236 descsz = 128 / 8;
2237 else if (strcmp(style, "sha1") == 0)
2238 descsz = 160 / 8;
2239 else if (strcmp(style, "uuid") == 0)
2241 const size_t uuidsz = 128 / 8;
2243 char buffer[uuidsz];
2244 memset(buffer, 0, uuidsz);
2246 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
2247 if (descriptor < 0)
2248 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
2249 strerror(errno));
2250 else
2252 ssize_t got = ::read(descriptor, buffer, uuidsz);
2253 release_descriptor(descriptor, true);
2254 if (got < 0)
2255 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
2256 else if (static_cast<size_t>(got) != uuidsz)
2257 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
2258 uuidsz, got);
2261 desc.assign(buffer, uuidsz);
2262 descsz = uuidsz;
2264 else if (strncmp(style, "0x", 2) == 0)
2266 hex_init();
2267 const char* p = style + 2;
2268 while (*p != '\0')
2270 if (hex_p(p[0]) && hex_p(p[1]))
2272 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
2273 desc += c;
2274 p += 2;
2276 else if (*p == '-' || *p == ':')
2277 ++p;
2278 else
2279 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
2280 style);
2282 descsz = desc.size();
2284 else
2285 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
2287 // Create the note.
2288 size_t trailing_padding;
2289 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
2290 ".note.gnu.build-id", descsz, true,
2291 &trailing_padding);
2292 if (os == NULL)
2293 return;
2295 if (!desc.empty())
2297 // We know the value already, so we fill it in now.
2298 gold_assert(desc.size() == descsz);
2300 Output_section_data* posd = new Output_data_const(desc, 4);
2301 os->add_output_section_data(posd);
2303 if (trailing_padding != 0)
2305 posd = new Output_data_zero_fill(trailing_padding, 0);
2306 os->add_output_section_data(posd);
2309 else
2311 // We need to compute a checksum after we have completed the
2312 // link.
2313 gold_assert(trailing_padding == 0);
2314 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
2315 os->add_output_section_data(this->build_id_note_);
2319 // If we have both .stabXX and .stabXXstr sections, then the sh_link
2320 // field of the former should point to the latter. I'm not sure who
2321 // started this, but the GNU linker does it, and some tools depend
2322 // upon it.
2324 void
2325 Layout::link_stabs_sections()
2327 if (!this->have_stabstr_section_)
2328 return;
2330 for (Section_list::iterator p = this->section_list_.begin();
2331 p != this->section_list_.end();
2332 ++p)
2334 if ((*p)->type() != elfcpp::SHT_STRTAB)
2335 continue;
2337 const char* name = (*p)->name();
2338 if (strncmp(name, ".stab", 5) != 0)
2339 continue;
2341 size_t len = strlen(name);
2342 if (strcmp(name + len - 3, "str") != 0)
2343 continue;
2345 std::string stab_name(name, len - 3);
2346 Output_section* stab_sec;
2347 stab_sec = this->find_output_section(stab_name.c_str());
2348 if (stab_sec != NULL)
2349 stab_sec->set_link_section(*p);
2353 // Create .gnu_incremental_inputs and related sections needed
2354 // for the next run of incremental linking to check what has changed.
2356 void
2357 Layout::create_incremental_info_sections(Symbol_table* symtab)
2359 Incremental_inputs* incr = this->incremental_inputs_;
2361 gold_assert(incr != NULL);
2363 // Create the .gnu_incremental_inputs, _symtab, and _relocs input sections.
2364 incr->create_data_sections(symtab);
2366 // Add the .gnu_incremental_inputs section.
2367 const char* incremental_inputs_name =
2368 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
2369 Output_section* incremental_inputs_os =
2370 this->make_output_section(incremental_inputs_name,
2371 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2372 ORDER_INVALID, false);
2373 incremental_inputs_os->add_output_section_data(incr->inputs_section());
2375 // Add the .gnu_incremental_symtab section.
2376 const char* incremental_symtab_name =
2377 this->namepool_.add(".gnu_incremental_symtab", false, NULL);
2378 Output_section* incremental_symtab_os =
2379 this->make_output_section(incremental_symtab_name,
2380 elfcpp::SHT_GNU_INCREMENTAL_SYMTAB, 0,
2381 ORDER_INVALID, false);
2382 incremental_symtab_os->add_output_section_data(incr->symtab_section());
2383 incremental_symtab_os->set_entsize(4);
2385 // Add the .gnu_incremental_relocs section.
2386 const char* incremental_relocs_name =
2387 this->namepool_.add(".gnu_incremental_relocs", false, NULL);
2388 Output_section* incremental_relocs_os =
2389 this->make_output_section(incremental_relocs_name,
2390 elfcpp::SHT_GNU_INCREMENTAL_RELOCS, 0,
2391 ORDER_INVALID, false);
2392 incremental_relocs_os->add_output_section_data(incr->relocs_section());
2393 incremental_relocs_os->set_entsize(incr->relocs_entsize());
2395 // Add the .gnu_incremental_got_plt section.
2396 const char* incremental_got_plt_name =
2397 this->namepool_.add(".gnu_incremental_got_plt", false, NULL);
2398 Output_section* incremental_got_plt_os =
2399 this->make_output_section(incremental_got_plt_name,
2400 elfcpp::SHT_GNU_INCREMENTAL_GOT_PLT, 0,
2401 ORDER_INVALID, false);
2402 incremental_got_plt_os->add_output_section_data(incr->got_plt_section());
2404 // Add the .gnu_incremental_strtab section.
2405 const char* incremental_strtab_name =
2406 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2407 Output_section* incremental_strtab_os = this->make_output_section(incremental_strtab_name,
2408 elfcpp::SHT_STRTAB, 0,
2409 ORDER_INVALID, false);
2410 Output_data_strtab* strtab_data =
2411 new Output_data_strtab(incr->get_stringpool());
2412 incremental_strtab_os->add_output_section_data(strtab_data);
2414 incremental_inputs_os->set_after_input_sections();
2415 incremental_symtab_os->set_after_input_sections();
2416 incremental_relocs_os->set_after_input_sections();
2417 incremental_got_plt_os->set_after_input_sections();
2419 incremental_inputs_os->set_link_section(incremental_strtab_os);
2420 incremental_symtab_os->set_link_section(incremental_inputs_os);
2421 incremental_relocs_os->set_link_section(incremental_inputs_os);
2422 incremental_got_plt_os->set_link_section(incremental_inputs_os);
2425 // Return whether SEG1 should be before SEG2 in the output file. This
2426 // is based entirely on the segment type and flags. When this is
2427 // called the segment addresses has normally not yet been set.
2429 bool
2430 Layout::segment_precedes(const Output_segment* seg1,
2431 const Output_segment* seg2)
2433 elfcpp::Elf_Word type1 = seg1->type();
2434 elfcpp::Elf_Word type2 = seg2->type();
2436 // The single PT_PHDR segment is required to precede any loadable
2437 // segment. We simply make it always first.
2438 if (type1 == elfcpp::PT_PHDR)
2440 gold_assert(type2 != elfcpp::PT_PHDR);
2441 return true;
2443 if (type2 == elfcpp::PT_PHDR)
2444 return false;
2446 // The single PT_INTERP segment is required to precede any loadable
2447 // segment. We simply make it always second.
2448 if (type1 == elfcpp::PT_INTERP)
2450 gold_assert(type2 != elfcpp::PT_INTERP);
2451 return true;
2453 if (type2 == elfcpp::PT_INTERP)
2454 return false;
2456 // We then put PT_LOAD segments before any other segments.
2457 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2458 return true;
2459 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2460 return false;
2462 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2463 // segment, because that is where the dynamic linker expects to find
2464 // it (this is just for efficiency; other positions would also work
2465 // correctly).
2466 if (type1 == elfcpp::PT_TLS
2467 && type2 != elfcpp::PT_TLS
2468 && type2 != elfcpp::PT_GNU_RELRO)
2469 return false;
2470 if (type2 == elfcpp::PT_TLS
2471 && type1 != elfcpp::PT_TLS
2472 && type1 != elfcpp::PT_GNU_RELRO)
2473 return true;
2475 // We put the PT_GNU_RELRO segment last, because that is where the
2476 // dynamic linker expects to find it (as with PT_TLS, this is just
2477 // for efficiency).
2478 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2479 return false;
2480 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2481 return true;
2483 const elfcpp::Elf_Word flags1 = seg1->flags();
2484 const elfcpp::Elf_Word flags2 = seg2->flags();
2486 // The order of non-PT_LOAD segments is unimportant. We simply sort
2487 // by the numeric segment type and flags values. There should not
2488 // be more than one segment with the same type and flags.
2489 if (type1 != elfcpp::PT_LOAD)
2491 if (type1 != type2)
2492 return type1 < type2;
2493 gold_assert(flags1 != flags2);
2494 return flags1 < flags2;
2497 // If the addresses are set already, sort by load address.
2498 if (seg1->are_addresses_set())
2500 if (!seg2->are_addresses_set())
2501 return true;
2503 unsigned int section_count1 = seg1->output_section_count();
2504 unsigned int section_count2 = seg2->output_section_count();
2505 if (section_count1 == 0 && section_count2 > 0)
2506 return true;
2507 if (section_count1 > 0 && section_count2 == 0)
2508 return false;
2510 uint64_t paddr1 = (seg1->are_addresses_set()
2511 ? seg1->paddr()
2512 : seg1->first_section_load_address());
2513 uint64_t paddr2 = (seg2->are_addresses_set()
2514 ? seg2->paddr()
2515 : seg2->first_section_load_address());
2517 if (paddr1 != paddr2)
2518 return paddr1 < paddr2;
2520 else if (seg2->are_addresses_set())
2521 return false;
2523 // A segment which holds large data comes after a segment which does
2524 // not hold large data.
2525 if (seg1->is_large_data_segment())
2527 if (!seg2->is_large_data_segment())
2528 return false;
2530 else if (seg2->is_large_data_segment())
2531 return true;
2533 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2534 // segments come before writable segments. Then writable segments
2535 // with data come before writable segments without data. Then
2536 // executable segments come before non-executable segments. Then
2537 // the unlikely case of a non-readable segment comes before the
2538 // normal case of a readable segment. If there are multiple
2539 // segments with the same type and flags, we require that the
2540 // address be set, and we sort by virtual address and then physical
2541 // address.
2542 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2543 return (flags1 & elfcpp::PF_W) == 0;
2544 if ((flags1 & elfcpp::PF_W) != 0
2545 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2546 return seg1->has_any_data_sections();
2547 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2548 return (flags1 & elfcpp::PF_X) != 0;
2549 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2550 return (flags1 & elfcpp::PF_R) == 0;
2552 // We shouldn't get here--we shouldn't create segments which we
2553 // can't distinguish.
2554 gold_unreachable();
2557 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2559 static off_t
2560 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2562 uint64_t unsigned_off = off;
2563 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2564 | (addr & (abi_pagesize - 1)));
2565 if (aligned_off < unsigned_off)
2566 aligned_off += abi_pagesize;
2567 return aligned_off;
2570 // Set the file offsets of all the segments, and all the sections they
2571 // contain. They have all been created. LOAD_SEG must be be laid out
2572 // first. Return the offset of the data to follow.
2574 off_t
2575 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2576 unsigned int* pshndx)
2578 // Sort them into the final order.
2579 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2580 Layout::Compare_segments());
2582 // Find the PT_LOAD segments, and set their addresses and offsets
2583 // and their section's addresses and offsets.
2584 uint64_t addr;
2585 if (parameters->options().user_set_Ttext())
2586 addr = parameters->options().Ttext();
2587 else if (parameters->options().output_is_position_independent())
2588 addr = 0;
2589 else
2590 addr = target->default_text_segment_address();
2591 off_t off = 0;
2593 // If LOAD_SEG is NULL, then the file header and segment headers
2594 // will not be loadable. But they still need to be at offset 0 in
2595 // the file. Set their offsets now.
2596 if (load_seg == NULL)
2598 for (Data_list::iterator p = this->special_output_list_.begin();
2599 p != this->special_output_list_.end();
2600 ++p)
2602 off = align_address(off, (*p)->addralign());
2603 (*p)->set_address_and_file_offset(0, off);
2604 off += (*p)->data_size();
2608 unsigned int increase_relro = this->increase_relro_;
2609 if (this->script_options_->saw_sections_clause())
2610 increase_relro = 0;
2612 const bool check_sections = parameters->options().check_sections();
2613 Output_segment* last_load_segment = NULL;
2615 for (Segment_list::iterator p = this->segment_list_.begin();
2616 p != this->segment_list_.end();
2617 ++p)
2619 if ((*p)->type() == elfcpp::PT_LOAD)
2621 if (load_seg != NULL && load_seg != *p)
2622 gold_unreachable();
2623 load_seg = NULL;
2625 bool are_addresses_set = (*p)->are_addresses_set();
2626 if (are_addresses_set)
2628 // When it comes to setting file offsets, we care about
2629 // the physical address.
2630 addr = (*p)->paddr();
2632 else if (parameters->options().user_set_Tdata()
2633 && ((*p)->flags() & elfcpp::PF_W) != 0
2634 && (!parameters->options().user_set_Tbss()
2635 || (*p)->has_any_data_sections()))
2637 addr = parameters->options().Tdata();
2638 are_addresses_set = true;
2640 else if (parameters->options().user_set_Tbss()
2641 && ((*p)->flags() & elfcpp::PF_W) != 0
2642 && !(*p)->has_any_data_sections())
2644 addr = parameters->options().Tbss();
2645 are_addresses_set = true;
2648 uint64_t orig_addr = addr;
2649 uint64_t orig_off = off;
2651 uint64_t aligned_addr = 0;
2652 uint64_t abi_pagesize = target->abi_pagesize();
2653 uint64_t common_pagesize = target->common_pagesize();
2655 if (!parameters->options().nmagic()
2656 && !parameters->options().omagic())
2657 (*p)->set_minimum_p_align(common_pagesize);
2659 if (!are_addresses_set)
2661 // Skip the address forward one page, maintaining the same
2662 // position within the page. This lets us store both segments
2663 // overlapping on a single page in the file, but the loader will
2664 // put them on different pages in memory. We will revisit this
2665 // decision once we know the size of the segment.
2667 addr = align_address(addr, (*p)->maximum_alignment());
2668 aligned_addr = addr;
2670 if ((addr & (abi_pagesize - 1)) != 0)
2671 addr = addr + abi_pagesize;
2673 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2676 if (!parameters->options().nmagic()
2677 && !parameters->options().omagic())
2678 off = align_file_offset(off, addr, abi_pagesize);
2679 else if (load_seg == NULL)
2681 // This is -N or -n with a section script which prevents
2682 // us from using a load segment. We need to ensure that
2683 // the file offset is aligned to the alignment of the
2684 // segment. This is because the linker script
2685 // implicitly assumed a zero offset. If we don't align
2686 // here, then the alignment of the sections in the
2687 // linker script may not match the alignment of the
2688 // sections in the set_section_addresses call below,
2689 // causing an error about dot moving backward.
2690 off = align_address(off, (*p)->maximum_alignment());
2693 unsigned int shndx_hold = *pshndx;
2694 bool has_relro = false;
2695 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2696 &increase_relro,
2697 &has_relro,
2698 &off, pshndx);
2700 // Now that we know the size of this segment, we may be able
2701 // to save a page in memory, at the cost of wasting some
2702 // file space, by instead aligning to the start of a new
2703 // page. Here we use the real machine page size rather than
2704 // the ABI mandated page size. If the segment has been
2705 // aligned so that the relro data ends at a page boundary,
2706 // we do not try to realign it.
2708 if (!are_addresses_set && !has_relro && aligned_addr != addr)
2710 uint64_t first_off = (common_pagesize
2711 - (aligned_addr
2712 & (common_pagesize - 1)));
2713 uint64_t last_off = new_addr & (common_pagesize - 1);
2714 if (first_off > 0
2715 && last_off > 0
2716 && ((aligned_addr & ~ (common_pagesize - 1))
2717 != (new_addr & ~ (common_pagesize - 1)))
2718 && first_off + last_off <= common_pagesize)
2720 *pshndx = shndx_hold;
2721 addr = align_address(aligned_addr, common_pagesize);
2722 addr = align_address(addr, (*p)->maximum_alignment());
2723 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2724 off = align_file_offset(off, addr, abi_pagesize);
2725 new_addr = (*p)->set_section_addresses(this, true, addr,
2726 &increase_relro,
2727 &has_relro,
2728 &off, pshndx);
2732 addr = new_addr;
2734 // Implement --check-sections. We know that the segments
2735 // are sorted by LMA.
2736 if (check_sections && last_load_segment != NULL)
2738 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2739 if (last_load_segment->paddr() + last_load_segment->memsz()
2740 > (*p)->paddr())
2742 unsigned long long lb1 = last_load_segment->paddr();
2743 unsigned long long le1 = lb1 + last_load_segment->memsz();
2744 unsigned long long lb2 = (*p)->paddr();
2745 unsigned long long le2 = lb2 + (*p)->memsz();
2746 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2747 "[0x%llx -> 0x%llx]"),
2748 lb1, le1, lb2, le2);
2751 last_load_segment = *p;
2755 // Handle the non-PT_LOAD segments, setting their offsets from their
2756 // section's offsets.
2757 for (Segment_list::iterator p = this->segment_list_.begin();
2758 p != this->segment_list_.end();
2759 ++p)
2761 if ((*p)->type() != elfcpp::PT_LOAD)
2762 (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
2763 ? increase_relro
2764 : 0);
2767 // Set the TLS offsets for each section in the PT_TLS segment.
2768 if (this->tls_segment_ != NULL)
2769 this->tls_segment_->set_tls_offsets();
2771 return off;
2774 // Set the offsets of all the allocated sections when doing a
2775 // relocatable link. This does the same jobs as set_segment_offsets,
2776 // only for a relocatable link.
2778 off_t
2779 Layout::set_relocatable_section_offsets(Output_data* file_header,
2780 unsigned int* pshndx)
2782 off_t off = 0;
2784 file_header->set_address_and_file_offset(0, 0);
2785 off += file_header->data_size();
2787 for (Section_list::iterator p = this->section_list_.begin();
2788 p != this->section_list_.end();
2789 ++p)
2791 // We skip unallocated sections here, except that group sections
2792 // have to come first.
2793 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2794 && (*p)->type() != elfcpp::SHT_GROUP)
2795 continue;
2797 off = align_address(off, (*p)->addralign());
2799 // The linker script might have set the address.
2800 if (!(*p)->is_address_valid())
2801 (*p)->set_address(0);
2802 (*p)->set_file_offset(off);
2803 (*p)->finalize_data_size();
2804 off += (*p)->data_size();
2806 (*p)->set_out_shndx(*pshndx);
2807 ++*pshndx;
2810 return off;
2813 // Set the file offset of all the sections not associated with a
2814 // segment.
2816 off_t
2817 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2819 for (Section_list::iterator p = this->unattached_section_list_.begin();
2820 p != this->unattached_section_list_.end();
2821 ++p)
2823 // The symtab section is handled in create_symtab_sections.
2824 if (*p == this->symtab_section_)
2825 continue;
2827 // If we've already set the data size, don't set it again.
2828 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2829 continue;
2831 if (pass == BEFORE_INPUT_SECTIONS_PASS
2832 && (*p)->requires_postprocessing())
2834 (*p)->create_postprocessing_buffer();
2835 this->any_postprocessing_sections_ = true;
2838 if (pass == BEFORE_INPUT_SECTIONS_PASS
2839 && (*p)->after_input_sections())
2840 continue;
2841 else if (pass == POSTPROCESSING_SECTIONS_PASS
2842 && (!(*p)->after_input_sections()
2843 || (*p)->type() == elfcpp::SHT_STRTAB))
2844 continue;
2845 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2846 && (!(*p)->after_input_sections()
2847 || (*p)->type() != elfcpp::SHT_STRTAB))
2848 continue;
2850 off = align_address(off, (*p)->addralign());
2851 (*p)->set_file_offset(off);
2852 (*p)->finalize_data_size();
2853 off += (*p)->data_size();
2855 // At this point the name must be set.
2856 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2857 this->namepool_.add((*p)->name(), false, NULL);
2859 return off;
2862 // Set the section indexes of all the sections not associated with a
2863 // segment.
2865 unsigned int
2866 Layout::set_section_indexes(unsigned int shndx)
2868 for (Section_list::iterator p = this->unattached_section_list_.begin();
2869 p != this->unattached_section_list_.end();
2870 ++p)
2872 if (!(*p)->has_out_shndx())
2874 (*p)->set_out_shndx(shndx);
2875 ++shndx;
2878 return shndx;
2881 // Set the section addresses according to the linker script. This is
2882 // only called when we see a SECTIONS clause. This returns the
2883 // program segment which should hold the file header and segment
2884 // headers, if any. It will return NULL if they should not be in a
2885 // segment.
2887 Output_segment*
2888 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2890 Script_sections* ss = this->script_options_->script_sections();
2891 gold_assert(ss->saw_sections_clause());
2892 return this->script_options_->set_section_addresses(symtab, this);
2895 // Place the orphan sections in the linker script.
2897 void
2898 Layout::place_orphan_sections_in_script()
2900 Script_sections* ss = this->script_options_->script_sections();
2901 gold_assert(ss->saw_sections_clause());
2903 // Place each orphaned output section in the script.
2904 for (Section_list::iterator p = this->section_list_.begin();
2905 p != this->section_list_.end();
2906 ++p)
2908 if (!(*p)->found_in_sections_clause())
2909 ss->place_orphan(*p);
2913 // Count the local symbols in the regular symbol table and the dynamic
2914 // symbol table, and build the respective string pools.
2916 void
2917 Layout::count_local_symbols(const Task* task,
2918 const Input_objects* input_objects)
2920 // First, figure out an upper bound on the number of symbols we'll
2921 // be inserting into each pool. This helps us create the pools with
2922 // the right size, to avoid unnecessary hashtable resizing.
2923 unsigned int symbol_count = 0;
2924 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2925 p != input_objects->relobj_end();
2926 ++p)
2927 symbol_count += (*p)->local_symbol_count();
2929 // Go from "upper bound" to "estimate." We overcount for two
2930 // reasons: we double-count symbols that occur in more than one
2931 // object file, and we count symbols that are dropped from the
2932 // output. Add it all together and assume we overcount by 100%.
2933 symbol_count /= 2;
2935 // We assume all symbols will go into both the sympool and dynpool.
2936 this->sympool_.reserve(symbol_count);
2937 this->dynpool_.reserve(symbol_count);
2939 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2940 p != input_objects->relobj_end();
2941 ++p)
2943 Task_lock_obj<Object> tlo(task, *p);
2944 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2948 // Create the symbol table sections. Here we also set the final
2949 // values of the symbols. At this point all the loadable sections are
2950 // fully laid out. SHNUM is the number of sections so far.
2952 void
2953 Layout::create_symtab_sections(const Input_objects* input_objects,
2954 Symbol_table* symtab,
2955 unsigned int shnum,
2956 off_t* poff)
2958 int symsize;
2959 unsigned int align;
2960 if (parameters->target().get_size() == 32)
2962 symsize = elfcpp::Elf_sizes<32>::sym_size;
2963 align = 4;
2965 else if (parameters->target().get_size() == 64)
2967 symsize = elfcpp::Elf_sizes<64>::sym_size;
2968 align = 8;
2970 else
2971 gold_unreachable();
2973 off_t off = *poff;
2974 off = align_address(off, align);
2975 off_t startoff = off;
2977 // Save space for the dummy symbol at the start of the section. We
2978 // never bother to write this out--it will just be left as zero.
2979 off += symsize;
2980 unsigned int local_symbol_index = 1;
2982 // Add STT_SECTION symbols for each Output section which needs one.
2983 for (Section_list::iterator p = this->section_list_.begin();
2984 p != this->section_list_.end();
2985 ++p)
2987 if (!(*p)->needs_symtab_index())
2988 (*p)->set_symtab_index(-1U);
2989 else
2991 (*p)->set_symtab_index(local_symbol_index);
2992 ++local_symbol_index;
2993 off += symsize;
2997 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2998 p != input_objects->relobj_end();
2999 ++p)
3001 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
3002 off, symtab);
3003 off += (index - local_symbol_index) * symsize;
3004 local_symbol_index = index;
3007 unsigned int local_symcount = local_symbol_index;
3008 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
3010 off_t dynoff;
3011 size_t dyn_global_index;
3012 size_t dyncount;
3013 if (this->dynsym_section_ == NULL)
3015 dynoff = 0;
3016 dyn_global_index = 0;
3017 dyncount = 0;
3019 else
3021 dyn_global_index = this->dynsym_section_->info();
3022 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
3023 dynoff = this->dynsym_section_->offset() + locsize;
3024 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
3025 gold_assert(static_cast<off_t>(dyncount * symsize)
3026 == this->dynsym_section_->data_size() - locsize);
3029 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
3030 &this->sympool_, &local_symcount);
3032 if (!parameters->options().strip_all())
3034 this->sympool_.set_string_offsets();
3036 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
3037 Output_section* osymtab = this->make_output_section(symtab_name,
3038 elfcpp::SHT_SYMTAB,
3039 0, ORDER_INVALID,
3040 false);
3041 this->symtab_section_ = osymtab;
3043 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
3044 align,
3045 "** symtab");
3046 osymtab->add_output_section_data(pos);
3048 // We generate a .symtab_shndx section if we have more than
3049 // SHN_LORESERVE sections. Technically it is possible that we
3050 // don't need one, because it is possible that there are no
3051 // symbols in any of sections with indexes larger than
3052 // SHN_LORESERVE. That is probably unusual, though, and it is
3053 // easier to always create one than to compute section indexes
3054 // twice (once here, once when writing out the symbols).
3055 if (shnum >= elfcpp::SHN_LORESERVE)
3057 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
3058 false, NULL);
3059 Output_section* osymtab_xindex =
3060 this->make_output_section(symtab_xindex_name,
3061 elfcpp::SHT_SYMTAB_SHNDX, 0,
3062 ORDER_INVALID, false);
3064 size_t symcount = (off - startoff) / symsize;
3065 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
3067 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
3069 osymtab_xindex->set_link_section(osymtab);
3070 osymtab_xindex->set_addralign(4);
3071 osymtab_xindex->set_entsize(4);
3073 osymtab_xindex->set_after_input_sections();
3075 // This tells the driver code to wait until the symbol table
3076 // has written out before writing out the postprocessing
3077 // sections, including the .symtab_shndx section.
3078 this->any_postprocessing_sections_ = true;
3081 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
3082 Output_section* ostrtab = this->make_output_section(strtab_name,
3083 elfcpp::SHT_STRTAB,
3084 0, ORDER_INVALID,
3085 false);
3087 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
3088 ostrtab->add_output_section_data(pstr);
3090 osymtab->set_file_offset(startoff);
3091 osymtab->finalize_data_size();
3092 osymtab->set_link_section(ostrtab);
3093 osymtab->set_info(local_symcount);
3094 osymtab->set_entsize(symsize);
3096 *poff = off;
3100 // Create the .shstrtab section, which holds the names of the
3101 // sections. At the time this is called, we have created all the
3102 // output sections except .shstrtab itself.
3104 Output_section*
3105 Layout::create_shstrtab()
3107 // FIXME: We don't need to create a .shstrtab section if we are
3108 // stripping everything.
3110 const char* name = this->namepool_.add(".shstrtab", false, NULL);
3112 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
3113 ORDER_INVALID, false);
3115 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
3117 // We can't write out this section until we've set all the
3118 // section names, and we don't set the names of compressed
3119 // output sections until relocations are complete. FIXME: With
3120 // the current names we use, this is unnecessary.
3121 os->set_after_input_sections();
3124 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
3125 os->add_output_section_data(posd);
3127 return os;
3130 // Create the section headers. SIZE is 32 or 64. OFF is the file
3131 // offset.
3133 void
3134 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
3136 Output_section_headers* oshdrs;
3137 oshdrs = new Output_section_headers(this,
3138 &this->segment_list_,
3139 &this->section_list_,
3140 &this->unattached_section_list_,
3141 &this->namepool_,
3142 shstrtab_section);
3143 off_t off = align_address(*poff, oshdrs->addralign());
3144 oshdrs->set_address_and_file_offset(0, off);
3145 off += oshdrs->data_size();
3146 *poff = off;
3147 this->section_headers_ = oshdrs;
3150 // Count the allocated sections.
3152 size_t
3153 Layout::allocated_output_section_count() const
3155 size_t section_count = 0;
3156 for (Segment_list::const_iterator p = this->segment_list_.begin();
3157 p != this->segment_list_.end();
3158 ++p)
3159 section_count += (*p)->output_section_count();
3160 return section_count;
3163 // Create the dynamic symbol table.
3165 void
3166 Layout::create_dynamic_symtab(const Input_objects* input_objects,
3167 Symbol_table* symtab,
3168 Output_section** pdynstr,
3169 unsigned int* plocal_dynamic_count,
3170 std::vector<Symbol*>* pdynamic_symbols,
3171 Versions* pversions)
3173 // Count all the symbols in the dynamic symbol table, and set the
3174 // dynamic symbol indexes.
3176 // Skip symbol 0, which is always all zeroes.
3177 unsigned int index = 1;
3179 // Add STT_SECTION symbols for each Output section which needs one.
3180 for (Section_list::iterator p = this->section_list_.begin();
3181 p != this->section_list_.end();
3182 ++p)
3184 if (!(*p)->needs_dynsym_index())
3185 (*p)->set_dynsym_index(-1U);
3186 else
3188 (*p)->set_dynsym_index(index);
3189 ++index;
3193 // Count the local symbols that need to go in the dynamic symbol table,
3194 // and set the dynamic symbol indexes.
3195 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3196 p != input_objects->relobj_end();
3197 ++p)
3199 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
3200 index = new_index;
3203 unsigned int local_symcount = index;
3204 *plocal_dynamic_count = local_symcount;
3206 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
3207 &this->dynpool_, pversions);
3209 int symsize;
3210 unsigned int align;
3211 const int size = parameters->target().get_size();
3212 if (size == 32)
3214 symsize = elfcpp::Elf_sizes<32>::sym_size;
3215 align = 4;
3217 else if (size == 64)
3219 symsize = elfcpp::Elf_sizes<64>::sym_size;
3220 align = 8;
3222 else
3223 gold_unreachable();
3225 // Create the dynamic symbol table section.
3227 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
3228 elfcpp::SHT_DYNSYM,
3229 elfcpp::SHF_ALLOC,
3230 false,
3231 ORDER_DYNAMIC_LINKER,
3232 false);
3234 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
3235 align,
3236 "** dynsym");
3237 dynsym->add_output_section_data(odata);
3239 dynsym->set_info(local_symcount);
3240 dynsym->set_entsize(symsize);
3241 dynsym->set_addralign(align);
3243 this->dynsym_section_ = dynsym;
3245 Output_data_dynamic* const odyn = this->dynamic_data_;
3246 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
3247 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
3249 // If there are more than SHN_LORESERVE allocated sections, we
3250 // create a .dynsym_shndx section. It is possible that we don't
3251 // need one, because it is possible that there are no dynamic
3252 // symbols in any of the sections with indexes larger than
3253 // SHN_LORESERVE. This is probably unusual, though, and at this
3254 // time we don't know the actual section indexes so it is
3255 // inconvenient to check.
3256 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
3258 Output_section* dynsym_xindex =
3259 this->choose_output_section(NULL, ".dynsym_shndx",
3260 elfcpp::SHT_SYMTAB_SHNDX,
3261 elfcpp::SHF_ALLOC,
3262 false, ORDER_DYNAMIC_LINKER, false);
3264 this->dynsym_xindex_ = new Output_symtab_xindex(index);
3266 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
3268 dynsym_xindex->set_link_section(dynsym);
3269 dynsym_xindex->set_addralign(4);
3270 dynsym_xindex->set_entsize(4);
3272 dynsym_xindex->set_after_input_sections();
3274 // This tells the driver code to wait until the symbol table has
3275 // written out before writing out the postprocessing sections,
3276 // including the .dynsym_shndx section.
3277 this->any_postprocessing_sections_ = true;
3280 // Create the dynamic string table section.
3282 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
3283 elfcpp::SHT_STRTAB,
3284 elfcpp::SHF_ALLOC,
3285 false,
3286 ORDER_DYNAMIC_LINKER,
3287 false);
3289 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
3290 dynstr->add_output_section_data(strdata);
3292 dynsym->set_link_section(dynstr);
3293 this->dynamic_section_->set_link_section(dynstr);
3295 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
3296 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
3298 *pdynstr = dynstr;
3300 // Create the hash tables.
3302 if (strcmp(parameters->options().hash_style(), "sysv") == 0
3303 || strcmp(parameters->options().hash_style(), "both") == 0)
3305 unsigned char* phash;
3306 unsigned int hashlen;
3307 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
3308 &phash, &hashlen);
3310 Output_section* hashsec =
3311 this->choose_output_section(NULL, ".hash", elfcpp::SHT_HASH,
3312 elfcpp::SHF_ALLOC, false,
3313 ORDER_DYNAMIC_LINKER, false);
3315 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3316 hashlen,
3317 align,
3318 "** hash");
3319 hashsec->add_output_section_data(hashdata);
3321 hashsec->set_link_section(dynsym);
3322 hashsec->set_entsize(4);
3324 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
3327 if (strcmp(parameters->options().hash_style(), "gnu") == 0
3328 || strcmp(parameters->options().hash_style(), "both") == 0)
3330 unsigned char* phash;
3331 unsigned int hashlen;
3332 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
3333 &phash, &hashlen);
3335 Output_section* hashsec =
3336 this->choose_output_section(NULL, ".gnu.hash", elfcpp::SHT_GNU_HASH,
3337 elfcpp::SHF_ALLOC, false,
3338 ORDER_DYNAMIC_LINKER, false);
3340 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3341 hashlen,
3342 align,
3343 "** hash");
3344 hashsec->add_output_section_data(hashdata);
3346 hashsec->set_link_section(dynsym);
3348 // For a 64-bit target, the entries in .gnu.hash do not have a
3349 // uniform size, so we only set the entry size for a 32-bit
3350 // target.
3351 if (parameters->target().get_size() == 32)
3352 hashsec->set_entsize(4);
3354 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
3358 // Assign offsets to each local portion of the dynamic symbol table.
3360 void
3361 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
3363 Output_section* dynsym = this->dynsym_section_;
3364 gold_assert(dynsym != NULL);
3366 off_t off = dynsym->offset();
3368 // Skip the dummy symbol at the start of the section.
3369 off += dynsym->entsize();
3371 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3372 p != input_objects->relobj_end();
3373 ++p)
3375 unsigned int count = (*p)->set_local_dynsym_offset(off);
3376 off += count * dynsym->entsize();
3380 // Create the version sections.
3382 void
3383 Layout::create_version_sections(const Versions* versions,
3384 const Symbol_table* symtab,
3385 unsigned int local_symcount,
3386 const std::vector<Symbol*>& dynamic_symbols,
3387 const Output_section* dynstr)
3389 if (!versions->any_defs() && !versions->any_needs())
3390 return;
3392 switch (parameters->size_and_endianness())
3394 #ifdef HAVE_TARGET_32_LITTLE
3395 case Parameters::TARGET_32_LITTLE:
3396 this->sized_create_version_sections<32, false>(versions, symtab,
3397 local_symcount,
3398 dynamic_symbols, dynstr);
3399 break;
3400 #endif
3401 #ifdef HAVE_TARGET_32_BIG
3402 case Parameters::TARGET_32_BIG:
3403 this->sized_create_version_sections<32, true>(versions, symtab,
3404 local_symcount,
3405 dynamic_symbols, dynstr);
3406 break;
3407 #endif
3408 #ifdef HAVE_TARGET_64_LITTLE
3409 case Parameters::TARGET_64_LITTLE:
3410 this->sized_create_version_sections<64, false>(versions, symtab,
3411 local_symcount,
3412 dynamic_symbols, dynstr);
3413 break;
3414 #endif
3415 #ifdef HAVE_TARGET_64_BIG
3416 case Parameters::TARGET_64_BIG:
3417 this->sized_create_version_sections<64, true>(versions, symtab,
3418 local_symcount,
3419 dynamic_symbols, dynstr);
3420 break;
3421 #endif
3422 default:
3423 gold_unreachable();
3427 // Create the version sections, sized version.
3429 template<int size, bool big_endian>
3430 void
3431 Layout::sized_create_version_sections(
3432 const Versions* versions,
3433 const Symbol_table* symtab,
3434 unsigned int local_symcount,
3435 const std::vector<Symbol*>& dynamic_symbols,
3436 const Output_section* dynstr)
3438 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3439 elfcpp::SHT_GNU_versym,
3440 elfcpp::SHF_ALLOC,
3441 false,
3442 ORDER_DYNAMIC_LINKER,
3443 false);
3445 unsigned char* vbuf;
3446 unsigned int vsize;
3447 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3448 local_symcount,
3449 dynamic_symbols,
3450 &vbuf, &vsize);
3452 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3453 "** versions");
3455 vsec->add_output_section_data(vdata);
3456 vsec->set_entsize(2);
3457 vsec->set_link_section(this->dynsym_section_);
3459 Output_data_dynamic* const odyn = this->dynamic_data_;
3460 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3462 if (versions->any_defs())
3464 Output_section* vdsec;
3465 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3466 elfcpp::SHT_GNU_verdef,
3467 elfcpp::SHF_ALLOC,
3468 false, ORDER_DYNAMIC_LINKER, false);
3470 unsigned char* vdbuf;
3471 unsigned int vdsize;
3472 unsigned int vdentries;
3473 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3474 &vdsize, &vdentries);
3476 Output_section_data* vddata =
3477 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3479 vdsec->add_output_section_data(vddata);
3480 vdsec->set_link_section(dynstr);
3481 vdsec->set_info(vdentries);
3483 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3484 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3487 if (versions->any_needs())
3489 Output_section* vnsec;
3490 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3491 elfcpp::SHT_GNU_verneed,
3492 elfcpp::SHF_ALLOC,
3493 false, ORDER_DYNAMIC_LINKER, false);
3495 unsigned char* vnbuf;
3496 unsigned int vnsize;
3497 unsigned int vnentries;
3498 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3499 &vnbuf, &vnsize,
3500 &vnentries);
3502 Output_section_data* vndata =
3503 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3505 vnsec->add_output_section_data(vndata);
3506 vnsec->set_link_section(dynstr);
3507 vnsec->set_info(vnentries);
3509 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3510 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3514 // Create the .interp section and PT_INTERP segment.
3516 void
3517 Layout::create_interp(const Target* target)
3519 const char* interp = parameters->options().dynamic_linker();
3520 if (interp == NULL)
3522 interp = target->dynamic_linker();
3523 gold_assert(interp != NULL);
3526 size_t len = strlen(interp) + 1;
3528 Output_section_data* odata = new Output_data_const(interp, len, 1);
3530 Output_section* osec = this->choose_output_section(NULL, ".interp",
3531 elfcpp::SHT_PROGBITS,
3532 elfcpp::SHF_ALLOC,
3533 false, ORDER_INTERP,
3534 false);
3535 osec->add_output_section_data(odata);
3537 if (!this->script_options_->saw_phdrs_clause())
3539 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3540 elfcpp::PF_R);
3541 oseg->add_output_section_to_nonload(osec, elfcpp::PF_R);
3545 // Add dynamic tags for the PLT and the dynamic relocs. This is
3546 // called by the target-specific code. This does nothing if not doing
3547 // a dynamic link.
3549 // USE_REL is true for REL relocs rather than RELA relocs.
3551 // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
3553 // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
3554 // and we also set DT_PLTREL. We use PLT_REL's output section, since
3555 // some targets have multiple reloc sections in PLT_REL.
3557 // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
3558 // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT.
3560 // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
3561 // executable.
3563 void
3564 Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
3565 const Output_data* plt_rel,
3566 const Output_data_reloc_generic* dyn_rel,
3567 bool add_debug, bool dynrel_includes_plt)
3569 Output_data_dynamic* odyn = this->dynamic_data_;
3570 if (odyn == NULL)
3571 return;
3573 if (plt_got != NULL && plt_got->output_section() != NULL)
3574 odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
3576 if (plt_rel != NULL && plt_rel->output_section() != NULL)
3578 odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
3579 odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
3580 odyn->add_constant(elfcpp::DT_PLTREL,
3581 use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
3584 if (dyn_rel != NULL && dyn_rel->output_section() != NULL)
3586 odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
3587 dyn_rel);
3588 if (plt_rel != NULL && dynrel_includes_plt)
3589 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3590 dyn_rel, plt_rel);
3591 else
3592 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3593 dyn_rel);
3594 const int size = parameters->target().get_size();
3595 elfcpp::DT rel_tag;
3596 int rel_size;
3597 if (use_rel)
3599 rel_tag = elfcpp::DT_RELENT;
3600 if (size == 32)
3601 rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
3602 else if (size == 64)
3603 rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
3604 else
3605 gold_unreachable();
3607 else
3609 rel_tag = elfcpp::DT_RELAENT;
3610 if (size == 32)
3611 rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
3612 else if (size == 64)
3613 rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
3614 else
3615 gold_unreachable();
3617 odyn->add_constant(rel_tag, rel_size);
3619 if (parameters->options().combreloc())
3621 size_t c = dyn_rel->relative_reloc_count();
3622 if (c > 0)
3623 odyn->add_constant((use_rel
3624 ? elfcpp::DT_RELCOUNT
3625 : elfcpp::DT_RELACOUNT),
3630 if (add_debug && !parameters->options().shared())
3632 // The value of the DT_DEBUG tag is filled in by the dynamic
3633 // linker at run time, and used by the debugger.
3634 odyn->add_constant(elfcpp::DT_DEBUG, 0);
3638 // Finish the .dynamic section and PT_DYNAMIC segment.
3640 void
3641 Layout::finish_dynamic_section(const Input_objects* input_objects,
3642 const Symbol_table* symtab)
3644 if (!this->script_options_->saw_phdrs_clause())
3646 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3647 (elfcpp::PF_R
3648 | elfcpp::PF_W));
3649 oseg->add_output_section_to_nonload(this->dynamic_section_,
3650 elfcpp::PF_R | elfcpp::PF_W);
3653 Output_data_dynamic* const odyn = this->dynamic_data_;
3655 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3656 p != input_objects->dynobj_end();
3657 ++p)
3659 if (!(*p)->is_needed()
3660 && (*p)->input_file()->options().as_needed())
3662 // This dynamic object was linked with --as-needed, but it
3663 // is not needed.
3664 continue;
3667 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3670 if (parameters->options().shared())
3672 const char* soname = parameters->options().soname();
3673 if (soname != NULL)
3674 odyn->add_string(elfcpp::DT_SONAME, soname);
3677 Symbol* sym = symtab->lookup(parameters->options().init());
3678 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3679 odyn->add_symbol(elfcpp::DT_INIT, sym);
3681 sym = symtab->lookup(parameters->options().fini());
3682 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3683 odyn->add_symbol(elfcpp::DT_FINI, sym);
3685 // Look for .init_array, .preinit_array and .fini_array by checking
3686 // section types.
3687 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3688 p != this->section_list_.end();
3689 ++p)
3690 switch((*p)->type())
3692 case elfcpp::SHT_FINI_ARRAY:
3693 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3694 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3695 break;
3696 case elfcpp::SHT_INIT_ARRAY:
3697 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3698 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3699 break;
3700 case elfcpp::SHT_PREINIT_ARRAY:
3701 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3702 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3703 break;
3704 default:
3705 break;
3708 // Add a DT_RPATH entry if needed.
3709 const General_options::Dir_list& rpath(parameters->options().rpath());
3710 if (!rpath.empty())
3712 std::string rpath_val;
3713 for (General_options::Dir_list::const_iterator p = rpath.begin();
3714 p != rpath.end();
3715 ++p)
3717 if (rpath_val.empty())
3718 rpath_val = p->name();
3719 else
3721 // Eliminate duplicates.
3722 General_options::Dir_list::const_iterator q;
3723 for (q = rpath.begin(); q != p; ++q)
3724 if (q->name() == p->name())
3725 break;
3726 if (q == p)
3728 rpath_val += ':';
3729 rpath_val += p->name();
3734 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3735 if (parameters->options().enable_new_dtags())
3736 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3739 // Look for text segments that have dynamic relocations.
3740 bool have_textrel = false;
3741 if (!this->script_options_->saw_sections_clause())
3743 for (Segment_list::const_iterator p = this->segment_list_.begin();
3744 p != this->segment_list_.end();
3745 ++p)
3747 if (((*p)->flags() & elfcpp::PF_W) == 0
3748 && (*p)->has_dynamic_reloc())
3750 have_textrel = true;
3751 break;
3755 else
3757 // We don't know the section -> segment mapping, so we are
3758 // conservative and just look for readonly sections with
3759 // relocations. If those sections wind up in writable segments,
3760 // then we have created an unnecessary DT_TEXTREL entry.
3761 for (Section_list::const_iterator p = this->section_list_.begin();
3762 p != this->section_list_.end();
3763 ++p)
3765 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3766 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3767 && ((*p)->has_dynamic_reloc()))
3769 have_textrel = true;
3770 break;
3775 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3776 // post-link tools can easily modify these flags if desired.
3777 unsigned int flags = 0;
3778 if (have_textrel)
3780 // Add a DT_TEXTREL for compatibility with older loaders.
3781 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3782 flags |= elfcpp::DF_TEXTREL;
3784 if (parameters->options().text())
3785 gold_error(_("read-only segment has dynamic relocations"));
3786 else if (parameters->options().warn_shared_textrel()
3787 && parameters->options().shared())
3788 gold_warning(_("shared library text segment is not shareable"));
3790 if (parameters->options().shared() && this->has_static_tls())
3791 flags |= elfcpp::DF_STATIC_TLS;
3792 if (parameters->options().origin())
3793 flags |= elfcpp::DF_ORIGIN;
3794 if (parameters->options().Bsymbolic())
3796 flags |= elfcpp::DF_SYMBOLIC;
3797 // Add DT_SYMBOLIC for compatibility with older loaders.
3798 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3800 if (parameters->options().now())
3801 flags |= elfcpp::DF_BIND_NOW;
3802 odyn->add_constant(elfcpp::DT_FLAGS, flags);
3804 flags = 0;
3805 if (parameters->options().initfirst())
3806 flags |= elfcpp::DF_1_INITFIRST;
3807 if (parameters->options().interpose())
3808 flags |= elfcpp::DF_1_INTERPOSE;
3809 if (parameters->options().loadfltr())
3810 flags |= elfcpp::DF_1_LOADFLTR;
3811 if (parameters->options().nodefaultlib())
3812 flags |= elfcpp::DF_1_NODEFLIB;
3813 if (parameters->options().nodelete())
3814 flags |= elfcpp::DF_1_NODELETE;
3815 if (parameters->options().nodlopen())
3816 flags |= elfcpp::DF_1_NOOPEN;
3817 if (parameters->options().nodump())
3818 flags |= elfcpp::DF_1_NODUMP;
3819 if (!parameters->options().shared())
3820 flags &= ~(elfcpp::DF_1_INITFIRST
3821 | elfcpp::DF_1_NODELETE
3822 | elfcpp::DF_1_NOOPEN);
3823 if (parameters->options().origin())
3824 flags |= elfcpp::DF_1_ORIGIN;
3825 if (parameters->options().now())
3826 flags |= elfcpp::DF_1_NOW;
3827 if (flags)
3828 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3831 // Set the size of the _DYNAMIC symbol table to be the size of the
3832 // dynamic data.
3834 void
3835 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
3837 Output_data_dynamic* const odyn = this->dynamic_data_;
3838 odyn->finalize_data_size();
3839 off_t data_size = odyn->data_size();
3840 const int size = parameters->target().get_size();
3841 if (size == 32)
3842 symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
3843 else if (size == 64)
3844 symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
3845 else
3846 gold_unreachable();
3849 // The mapping of input section name prefixes to output section names.
3850 // In some cases one prefix is itself a prefix of another prefix; in
3851 // such a case the longer prefix must come first. These prefixes are
3852 // based on the GNU linker default ELF linker script.
3854 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3855 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3857 MAPPING_INIT(".text.", ".text"),
3858 MAPPING_INIT(".ctors.", ".ctors"),
3859 MAPPING_INIT(".dtors.", ".dtors"),
3860 MAPPING_INIT(".rodata.", ".rodata"),
3861 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3862 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3863 MAPPING_INIT(".data.", ".data"),
3864 MAPPING_INIT(".bss.", ".bss"),
3865 MAPPING_INIT(".tdata.", ".tdata"),
3866 MAPPING_INIT(".tbss.", ".tbss"),
3867 MAPPING_INIT(".init_array.", ".init_array"),
3868 MAPPING_INIT(".fini_array.", ".fini_array"),
3869 MAPPING_INIT(".sdata.", ".sdata"),
3870 MAPPING_INIT(".sbss.", ".sbss"),
3871 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3872 // differently depending on whether it is creating a shared library.
3873 MAPPING_INIT(".sdata2.", ".sdata"),
3874 MAPPING_INIT(".sbss2.", ".sbss"),
3875 MAPPING_INIT(".lrodata.", ".lrodata"),
3876 MAPPING_INIT(".ldata.", ".ldata"),
3877 MAPPING_INIT(".lbss.", ".lbss"),
3878 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3879 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3880 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3881 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3882 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3883 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3884 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3885 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3886 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3887 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3888 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3889 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3890 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3891 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3892 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3893 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3894 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3895 MAPPING_INIT(".ARM.extab", ".ARM.extab"),
3896 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3897 MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
3898 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3900 #undef MAPPING_INIT
3902 const int Layout::section_name_mapping_count =
3903 (sizeof(Layout::section_name_mapping)
3904 / sizeof(Layout::section_name_mapping[0]));
3906 // Choose the output section name to use given an input section name.
3907 // Set *PLEN to the length of the name. *PLEN is initialized to the
3908 // length of NAME.
3910 const char*
3911 Layout::output_section_name(const char* name, size_t* plen)
3913 // gcc 4.3 generates the following sorts of section names when it
3914 // needs a section name specific to a function:
3915 // .text.FN
3916 // .rodata.FN
3917 // .sdata2.FN
3918 // .data.FN
3919 // .data.rel.FN
3920 // .data.rel.local.FN
3921 // .data.rel.ro.FN
3922 // .data.rel.ro.local.FN
3923 // .sdata.FN
3924 // .bss.FN
3925 // .sbss.FN
3926 // .tdata.FN
3927 // .tbss.FN
3929 // The GNU linker maps all of those to the part before the .FN,
3930 // except that .data.rel.local.FN is mapped to .data, and
3931 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3932 // beginning with .data.rel.ro.local are grouped together.
3934 // For an anonymous namespace, the string FN can contain a '.'.
3936 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3937 // GNU linker maps to .rodata.
3939 // The .data.rel.ro sections are used with -z relro. The sections
3940 // are recognized by name. We use the same names that the GNU
3941 // linker does for these sections.
3943 // It is hard to handle this in a principled way, so we don't even
3944 // try. We use a table of mappings. If the input section name is
3945 // not found in the table, we simply use it as the output section
3946 // name.
3948 const Section_name_mapping* psnm = section_name_mapping;
3949 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3951 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3953 *plen = psnm->tolen;
3954 return psnm->to;
3958 return name;
3961 // Check if a comdat group or .gnu.linkonce section with the given
3962 // NAME is selected for the link. If there is already a section,
3963 // *KEPT_SECTION is set to point to the existing section and the
3964 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3965 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3966 // *KEPT_SECTION is set to the internal copy and the function returns
3967 // true.
3969 bool
3970 Layout::find_or_add_kept_section(const std::string& name,
3971 Relobj* object,
3972 unsigned int shndx,
3973 bool is_comdat,
3974 bool is_group_name,
3975 Kept_section** kept_section)
3977 // It's normal to see a couple of entries here, for the x86 thunk
3978 // sections. If we see more than a few, we're linking a C++
3979 // program, and we resize to get more space to minimize rehashing.
3980 if (this->signatures_.size() > 4
3981 && !this->resized_signatures_)
3983 reserve_unordered_map(&this->signatures_,
3984 this->number_of_input_files_ * 64);
3985 this->resized_signatures_ = true;
3988 Kept_section candidate;
3989 std::pair<Signatures::iterator, bool> ins =
3990 this->signatures_.insert(std::make_pair(name, candidate));
3992 if (kept_section != NULL)
3993 *kept_section = &ins.first->second;
3994 if (ins.second)
3996 // This is the first time we've seen this signature.
3997 ins.first->second.set_object(object);
3998 ins.first->second.set_shndx(shndx);
3999 if (is_comdat)
4000 ins.first->second.set_is_comdat();
4001 if (is_group_name)
4002 ins.first->second.set_is_group_name();
4003 return true;
4006 // We have already seen this signature.
4008 if (ins.first->second.is_group_name())
4010 // We've already seen a real section group with this signature.
4011 // If the kept group is from a plugin object, and we're in the
4012 // replacement phase, accept the new one as a replacement.
4013 if (ins.first->second.object() == NULL
4014 && parameters->options().plugins()->in_replacement_phase())
4016 ins.first->second.set_object(object);
4017 ins.first->second.set_shndx(shndx);
4018 return true;
4020 return false;
4022 else if (is_group_name)
4024 // This is a real section group, and we've already seen a
4025 // linkonce section with this signature. Record that we've seen
4026 // a section group, and don't include this section group.
4027 ins.first->second.set_is_group_name();
4028 return false;
4030 else
4032 // We've already seen a linkonce section and this is a linkonce
4033 // section. These don't block each other--this may be the same
4034 // symbol name with different section types.
4035 return true;
4039 // Store the allocated sections into the section list.
4041 void
4042 Layout::get_allocated_sections(Section_list* section_list) const
4044 for (Section_list::const_iterator p = this->section_list_.begin();
4045 p != this->section_list_.end();
4046 ++p)
4047 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
4048 section_list->push_back(*p);
4051 // Create an output segment.
4053 Output_segment*
4054 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
4056 gold_assert(!parameters->options().relocatable());
4057 Output_segment* oseg = new Output_segment(type, flags);
4058 this->segment_list_.push_back(oseg);
4060 if (type == elfcpp::PT_TLS)
4061 this->tls_segment_ = oseg;
4062 else if (type == elfcpp::PT_GNU_RELRO)
4063 this->relro_segment_ = oseg;
4065 return oseg;
4068 // Write out the Output_sections. Most won't have anything to write,
4069 // since most of the data will come from input sections which are
4070 // handled elsewhere. But some Output_sections do have Output_data.
4072 void
4073 Layout::write_output_sections(Output_file* of) const
4075 for (Section_list::const_iterator p = this->section_list_.begin();
4076 p != this->section_list_.end();
4077 ++p)
4079 if (!(*p)->after_input_sections())
4080 (*p)->write(of);
4084 // Write out data not associated with a section or the symbol table.
4086 void
4087 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
4089 if (!parameters->options().strip_all())
4091 const Output_section* symtab_section = this->symtab_section_;
4092 for (Section_list::const_iterator p = this->section_list_.begin();
4093 p != this->section_list_.end();
4094 ++p)
4096 if ((*p)->needs_symtab_index())
4098 gold_assert(symtab_section != NULL);
4099 unsigned int index = (*p)->symtab_index();
4100 gold_assert(index > 0 && index != -1U);
4101 off_t off = (symtab_section->offset()
4102 + index * symtab_section->entsize());
4103 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
4108 const Output_section* dynsym_section = this->dynsym_section_;
4109 for (Section_list::const_iterator p = this->section_list_.begin();
4110 p != this->section_list_.end();
4111 ++p)
4113 if ((*p)->needs_dynsym_index())
4115 gold_assert(dynsym_section != NULL);
4116 unsigned int index = (*p)->dynsym_index();
4117 gold_assert(index > 0 && index != -1U);
4118 off_t off = (dynsym_section->offset()
4119 + index * dynsym_section->entsize());
4120 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
4124 // Write out the Output_data which are not in an Output_section.
4125 for (Data_list::const_iterator p = this->special_output_list_.begin();
4126 p != this->special_output_list_.end();
4127 ++p)
4128 (*p)->write(of);
4131 // Write out the Output_sections which can only be written after the
4132 // input sections are complete.
4134 void
4135 Layout::write_sections_after_input_sections(Output_file* of)
4137 // Determine the final section offsets, and thus the final output
4138 // file size. Note we finalize the .shstrab last, to allow the
4139 // after_input_section sections to modify their section-names before
4140 // writing.
4141 if (this->any_postprocessing_sections_)
4143 off_t off = this->output_file_size_;
4144 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
4146 // Now that we've finalized the names, we can finalize the shstrab.
4147 off =
4148 this->set_section_offsets(off,
4149 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
4151 if (off > this->output_file_size_)
4153 of->resize(off);
4154 this->output_file_size_ = off;
4158 for (Section_list::const_iterator p = this->section_list_.begin();
4159 p != this->section_list_.end();
4160 ++p)
4162 if ((*p)->after_input_sections())
4163 (*p)->write(of);
4166 this->section_headers_->write(of);
4169 // If the build ID requires computing a checksum, do so here, and
4170 // write it out. We compute a checksum over the entire file because
4171 // that is simplest.
4173 void
4174 Layout::write_build_id(Output_file* of) const
4176 if (this->build_id_note_ == NULL)
4177 return;
4179 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
4181 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
4182 this->build_id_note_->data_size());
4184 const char* style = parameters->options().build_id();
4185 if (strcmp(style, "sha1") == 0)
4187 sha1_ctx ctx;
4188 sha1_init_ctx(&ctx);
4189 sha1_process_bytes(iv, this->output_file_size_, &ctx);
4190 sha1_finish_ctx(&ctx, ov);
4192 else if (strcmp(style, "md5") == 0)
4194 md5_ctx ctx;
4195 md5_init_ctx(&ctx);
4196 md5_process_bytes(iv, this->output_file_size_, &ctx);
4197 md5_finish_ctx(&ctx, ov);
4199 else
4200 gold_unreachable();
4202 of->write_output_view(this->build_id_note_->offset(),
4203 this->build_id_note_->data_size(),
4204 ov);
4206 of->free_input_view(0, this->output_file_size_, iv);
4209 // Write out a binary file. This is called after the link is
4210 // complete. IN is the temporary output file we used to generate the
4211 // ELF code. We simply walk through the segments, read them from
4212 // their file offset in IN, and write them to their load address in
4213 // the output file. FIXME: with a bit more work, we could support
4214 // S-records and/or Intel hex format here.
4216 void
4217 Layout::write_binary(Output_file* in) const
4219 gold_assert(parameters->options().oformat_enum()
4220 == General_options::OBJECT_FORMAT_BINARY);
4222 // Get the size of the binary file.
4223 uint64_t max_load_address = 0;
4224 for (Segment_list::const_iterator p = this->segment_list_.begin();
4225 p != this->segment_list_.end();
4226 ++p)
4228 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4230 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
4231 if (max_paddr > max_load_address)
4232 max_load_address = max_paddr;
4236 Output_file out(parameters->options().output_file_name());
4237 out.open(max_load_address);
4239 for (Segment_list::const_iterator p = this->segment_list_.begin();
4240 p != this->segment_list_.end();
4241 ++p)
4243 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4245 const unsigned char* vin = in->get_input_view((*p)->offset(),
4246 (*p)->filesz());
4247 unsigned char* vout = out.get_output_view((*p)->paddr(),
4248 (*p)->filesz());
4249 memcpy(vout, vin, (*p)->filesz());
4250 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
4251 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
4255 out.close();
4258 // Print the output sections to the map file.
4260 void
4261 Layout::print_to_mapfile(Mapfile* mapfile) const
4263 for (Segment_list::const_iterator p = this->segment_list_.begin();
4264 p != this->segment_list_.end();
4265 ++p)
4266 (*p)->print_sections_to_mapfile(mapfile);
4269 // Print statistical information to stderr. This is used for --stats.
4271 void
4272 Layout::print_stats() const
4274 this->namepool_.print_stats("section name pool");
4275 this->sympool_.print_stats("output symbol name pool");
4276 this->dynpool_.print_stats("dynamic name pool");
4278 for (Section_list::const_iterator p = this->section_list_.begin();
4279 p != this->section_list_.end();
4280 ++p)
4281 (*p)->print_merge_stats();
4284 // Write_sections_task methods.
4286 // We can always run this task.
4288 Task_token*
4289 Write_sections_task::is_runnable()
4291 return NULL;
4294 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
4295 // when finished.
4297 void
4298 Write_sections_task::locks(Task_locker* tl)
4300 tl->add(this, this->output_sections_blocker_);
4301 tl->add(this, this->final_blocker_);
4304 // Run the task--write out the data.
4306 void
4307 Write_sections_task::run(Workqueue*)
4309 this->layout_->write_output_sections(this->of_);
4312 // Write_data_task methods.
4314 // We can always run this task.
4316 Task_token*
4317 Write_data_task::is_runnable()
4319 return NULL;
4322 // We need to unlock FINAL_BLOCKER when finished.
4324 void
4325 Write_data_task::locks(Task_locker* tl)
4327 tl->add(this, this->final_blocker_);
4330 // Run the task--write out the data.
4332 void
4333 Write_data_task::run(Workqueue*)
4335 this->layout_->write_data(this->symtab_, this->of_);
4338 // Write_symbols_task methods.
4340 // We can always run this task.
4342 Task_token*
4343 Write_symbols_task::is_runnable()
4345 return NULL;
4348 // We need to unlock FINAL_BLOCKER when finished.
4350 void
4351 Write_symbols_task::locks(Task_locker* tl)
4353 tl->add(this, this->final_blocker_);
4356 // Run the task--write out the symbols.
4358 void
4359 Write_symbols_task::run(Workqueue*)
4361 this->symtab_->write_globals(this->sympool_, this->dynpool_,
4362 this->layout_->symtab_xindex(),
4363 this->layout_->dynsym_xindex(), this->of_);
4366 // Write_after_input_sections_task methods.
4368 // We can only run this task after the input sections have completed.
4370 Task_token*
4371 Write_after_input_sections_task::is_runnable()
4373 if (this->input_sections_blocker_->is_blocked())
4374 return this->input_sections_blocker_;
4375 return NULL;
4378 // We need to unlock FINAL_BLOCKER when finished.
4380 void
4381 Write_after_input_sections_task::locks(Task_locker* tl)
4383 tl->add(this, this->final_blocker_);
4386 // Run the task.
4388 void
4389 Write_after_input_sections_task::run(Workqueue*)
4391 this->layout_->write_sections_after_input_sections(this->of_);
4394 // Close_task_runner methods.
4396 // Run the task--close the file.
4398 void
4399 Close_task_runner::run(Workqueue*, const Task*)
4401 // If we need to compute a checksum for the BUILD if, we do so here.
4402 this->layout_->write_build_id(this->of_);
4404 // If we've been asked to create a binary file, we do so here.
4405 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
4406 this->layout_->write_binary(this->of_);
4408 this->of_->close();
4411 // Instantiate the templates we need. We could use the configure
4412 // script to restrict this to only the ones for implemented targets.
4414 #ifdef HAVE_TARGET_32_LITTLE
4415 template
4416 Output_section*
4417 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
4418 const char* name,
4419 const elfcpp::Shdr<32, false>& shdr,
4420 unsigned int, unsigned int, off_t*);
4421 #endif
4423 #ifdef HAVE_TARGET_32_BIG
4424 template
4425 Output_section*
4426 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
4427 const char* name,
4428 const elfcpp::Shdr<32, true>& shdr,
4429 unsigned int, unsigned int, off_t*);
4430 #endif
4432 #ifdef HAVE_TARGET_64_LITTLE
4433 template
4434 Output_section*
4435 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
4436 const char* name,
4437 const elfcpp::Shdr<64, false>& shdr,
4438 unsigned int, unsigned int, off_t*);
4439 #endif
4441 #ifdef HAVE_TARGET_64_BIG
4442 template
4443 Output_section*
4444 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
4445 const char* name,
4446 const elfcpp::Shdr<64, true>& shdr,
4447 unsigned int, unsigned int, off_t*);
4448 #endif
4450 #ifdef HAVE_TARGET_32_LITTLE
4451 template
4452 Output_section*
4453 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
4454 unsigned int reloc_shndx,
4455 const elfcpp::Shdr<32, false>& shdr,
4456 Output_section* data_section,
4457 Relocatable_relocs* rr);
4458 #endif
4460 #ifdef HAVE_TARGET_32_BIG
4461 template
4462 Output_section*
4463 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
4464 unsigned int reloc_shndx,
4465 const elfcpp::Shdr<32, true>& shdr,
4466 Output_section* data_section,
4467 Relocatable_relocs* rr);
4468 #endif
4470 #ifdef HAVE_TARGET_64_LITTLE
4471 template
4472 Output_section*
4473 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
4474 unsigned int reloc_shndx,
4475 const elfcpp::Shdr<64, false>& shdr,
4476 Output_section* data_section,
4477 Relocatable_relocs* rr);
4478 #endif
4480 #ifdef HAVE_TARGET_64_BIG
4481 template
4482 Output_section*
4483 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
4484 unsigned int reloc_shndx,
4485 const elfcpp::Shdr<64, true>& shdr,
4486 Output_section* data_section,
4487 Relocatable_relocs* rr);
4488 #endif
4490 #ifdef HAVE_TARGET_32_LITTLE
4491 template
4492 void
4493 Layout::layout_group<32, false>(Symbol_table* symtab,
4494 Sized_relobj<32, false>* object,
4495 unsigned int,
4496 const char* group_section_name,
4497 const char* signature,
4498 const elfcpp::Shdr<32, false>& shdr,
4499 elfcpp::Elf_Word flags,
4500 std::vector<unsigned int>* shndxes);
4501 #endif
4503 #ifdef HAVE_TARGET_32_BIG
4504 template
4505 void
4506 Layout::layout_group<32, true>(Symbol_table* symtab,
4507 Sized_relobj<32, true>* object,
4508 unsigned int,
4509 const char* group_section_name,
4510 const char* signature,
4511 const elfcpp::Shdr<32, true>& shdr,
4512 elfcpp::Elf_Word flags,
4513 std::vector<unsigned int>* shndxes);
4514 #endif
4516 #ifdef HAVE_TARGET_64_LITTLE
4517 template
4518 void
4519 Layout::layout_group<64, false>(Symbol_table* symtab,
4520 Sized_relobj<64, false>* object,
4521 unsigned int,
4522 const char* group_section_name,
4523 const char* signature,
4524 const elfcpp::Shdr<64, false>& shdr,
4525 elfcpp::Elf_Word flags,
4526 std::vector<unsigned int>* shndxes);
4527 #endif
4529 #ifdef HAVE_TARGET_64_BIG
4530 template
4531 void
4532 Layout::layout_group<64, true>(Symbol_table* symtab,
4533 Sized_relobj<64, true>* object,
4534 unsigned int,
4535 const char* group_section_name,
4536 const char* signature,
4537 const elfcpp::Shdr<64, true>& shdr,
4538 elfcpp::Elf_Word flags,
4539 std::vector<unsigned int>* shndxes);
4540 #endif
4542 #ifdef HAVE_TARGET_32_LITTLE
4543 template
4544 Output_section*
4545 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
4546 const unsigned char* symbols,
4547 off_t symbols_size,
4548 const unsigned char* symbol_names,
4549 off_t symbol_names_size,
4550 unsigned int shndx,
4551 const elfcpp::Shdr<32, false>& shdr,
4552 unsigned int reloc_shndx,
4553 unsigned int reloc_type,
4554 off_t* off);
4555 #endif
4557 #ifdef HAVE_TARGET_32_BIG
4558 template
4559 Output_section*
4560 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4561 const unsigned char* symbols,
4562 off_t symbols_size,
4563 const unsigned char* symbol_names,
4564 off_t symbol_names_size,
4565 unsigned int shndx,
4566 const elfcpp::Shdr<32, true>& shdr,
4567 unsigned int reloc_shndx,
4568 unsigned int reloc_type,
4569 off_t* off);
4570 #endif
4572 #ifdef HAVE_TARGET_64_LITTLE
4573 template
4574 Output_section*
4575 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4576 const unsigned char* symbols,
4577 off_t symbols_size,
4578 const unsigned char* symbol_names,
4579 off_t symbol_names_size,
4580 unsigned int shndx,
4581 const elfcpp::Shdr<64, false>& shdr,
4582 unsigned int reloc_shndx,
4583 unsigned int reloc_type,
4584 off_t* off);
4585 #endif
4587 #ifdef HAVE_TARGET_64_BIG
4588 template
4589 Output_section*
4590 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4591 const unsigned char* symbols,
4592 off_t symbols_size,
4593 const unsigned char* symbol_names,
4594 off_t symbol_names_size,
4595 unsigned int shndx,
4596 const elfcpp::Shdr<64, true>& shdr,
4597 unsigned int reloc_shndx,
4598 unsigned int reloc_type,
4599 off_t* off);
4600 #endif
4602 } // End namespace gold.