Sync toplevel and config/ from GCC.
[binutils.git] / gold / layout.cc
blob63b9e0d852f1c4d379abaf0a6d142132f4a355a6
1 // layout.cc -- lay out output file sections for gold
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011 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 // A writable .eh_frame section is a RELRO section.
916 if ((shdr.get_sh_flags() & elfcpp::SHF_WRITE) != 0)
917 os->set_is_relro();
919 // We found a .eh_frame section we are going to optimize, so now
920 // we can add the set of optimized sections to the output
921 // section. We need to postpone adding this until we've found a
922 // section we can optimize so that the .eh_frame section in
923 // crtbegin.o winds up at the start of the output section.
924 if (!this->added_eh_frame_data_)
926 os->add_output_section_data(this->eh_frame_data_);
927 this->added_eh_frame_data_ = true;
929 *off = -1;
931 else
933 // We couldn't handle this .eh_frame section for some reason.
934 // Add it as a normal section.
935 bool saw_sections_clause = this->script_options_->saw_sections_clause();
936 *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
937 saw_sections_clause);
938 this->have_added_input_section_ = true;
941 return os;
944 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
945 // the output section.
947 Output_section*
948 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
949 elfcpp::Elf_Xword flags,
950 Output_section_data* posd,
951 Output_section_order order, bool is_relro)
953 Output_section* os = this->choose_output_section(NULL, name, type, flags,
954 false, order, is_relro);
955 if (os != NULL)
956 os->add_output_section_data(posd);
957 return os;
960 // Map section flags to segment flags.
962 elfcpp::Elf_Word
963 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
965 elfcpp::Elf_Word ret = elfcpp::PF_R;
966 if ((flags & elfcpp::SHF_WRITE) != 0)
967 ret |= elfcpp::PF_W;
968 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
969 ret |= elfcpp::PF_X;
970 return ret;
973 // Make a new Output_section, and attach it to segments as
974 // appropriate. ORDER is the order in which this section should
975 // appear in the output segment. IS_RELRO is true if this is a relro
976 // (read-only after relocations) section.
978 Output_section*
979 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
980 elfcpp::Elf_Xword flags,
981 Output_section_order order, bool is_relro)
983 Output_section* os;
984 if ((flags & elfcpp::SHF_ALLOC) == 0
985 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
986 && is_compressible_debug_section(name))
987 os = new Output_compressed_section(&parameters->options(), name, type,
988 flags);
989 else if ((flags & elfcpp::SHF_ALLOC) == 0
990 && parameters->options().strip_debug_non_line()
991 && strcmp(".debug_abbrev", name) == 0)
993 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
994 name, type, flags);
995 if (this->debug_info_)
996 this->debug_info_->set_abbreviations(this->debug_abbrev_);
998 else if ((flags & elfcpp::SHF_ALLOC) == 0
999 && parameters->options().strip_debug_non_line()
1000 && strcmp(".debug_info", name) == 0)
1002 os = this->debug_info_ = new Output_reduced_debug_info_section(
1003 name, type, flags);
1004 if (this->debug_abbrev_)
1005 this->debug_info_->set_abbreviations(this->debug_abbrev_);
1007 else
1009 // FIXME: const_cast is ugly.
1010 Target* target = const_cast<Target*>(&parameters->target());
1011 os = target->make_output_section(name, type, flags);
1014 // With -z relro, we have to recognize the special sections by name.
1015 // There is no other way.
1016 bool is_relro_local = false;
1017 if (!this->script_options_->saw_sections_clause()
1018 && parameters->options().relro()
1019 && type == elfcpp::SHT_PROGBITS
1020 && (flags & elfcpp::SHF_ALLOC) != 0
1021 && (flags & elfcpp::SHF_WRITE) != 0)
1023 if (strcmp(name, ".data.rel.ro") == 0)
1024 is_relro = true;
1025 else if (strcmp(name, ".data.rel.ro.local") == 0)
1027 is_relro = true;
1028 is_relro_local = true;
1030 else if (type == elfcpp::SHT_INIT_ARRAY
1031 || type == elfcpp::SHT_FINI_ARRAY
1032 || type == elfcpp::SHT_PREINIT_ARRAY)
1033 is_relro = true;
1034 else if (strcmp(name, ".ctors") == 0
1035 || strcmp(name, ".dtors") == 0
1036 || strcmp(name, ".jcr") == 0)
1037 is_relro = true;
1040 if (is_relro)
1041 os->set_is_relro();
1043 if (order == ORDER_INVALID && (flags & elfcpp::SHF_ALLOC) != 0)
1044 order = this->default_section_order(os, is_relro_local);
1046 os->set_order(order);
1048 parameters->target().new_output_section(os);
1050 this->section_list_.push_back(os);
1052 // The GNU linker by default sorts some sections by priority, so we
1053 // do the same. We need to know that this might happen before we
1054 // attach any input sections.
1055 if (!this->script_options_->saw_sections_clause()
1056 && (strcmp(name, ".ctors") == 0
1057 || strcmp(name, ".dtors") == 0
1058 || strcmp(name, ".init_array") == 0
1059 || strcmp(name, ".fini_array") == 0))
1060 os->set_may_sort_attached_input_sections();
1062 // Check for .stab*str sections, as .stab* sections need to link to
1063 // them.
1064 if (type == elfcpp::SHT_STRTAB
1065 && !this->have_stabstr_section_
1066 && strncmp(name, ".stab", 5) == 0
1067 && strcmp(name + strlen(name) - 3, "str") == 0)
1068 this->have_stabstr_section_ = true;
1070 // If we have already attached the sections to segments, then we
1071 // need to attach this one now. This happens for sections created
1072 // directly by the linker.
1073 if (this->sections_are_attached_)
1074 this->attach_section_to_segment(os);
1076 return os;
1079 // Return the default order in which a section should be placed in an
1080 // output segment. This function captures a lot of the ideas in
1081 // ld/scripttempl/elf.sc in the GNU linker. Note that the order of a
1082 // linker created section is normally set when the section is created;
1083 // this function is used for input sections.
1085 Output_section_order
1086 Layout::default_section_order(Output_section* os, bool is_relro_local)
1088 gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
1089 bool is_write = (os->flags() & elfcpp::SHF_WRITE) != 0;
1090 bool is_execinstr = (os->flags() & elfcpp::SHF_EXECINSTR) != 0;
1091 bool is_bss = false;
1093 switch (os->type())
1095 default:
1096 case elfcpp::SHT_PROGBITS:
1097 break;
1098 case elfcpp::SHT_NOBITS:
1099 is_bss = true;
1100 break;
1101 case elfcpp::SHT_RELA:
1102 case elfcpp::SHT_REL:
1103 if (!is_write)
1104 return ORDER_DYNAMIC_RELOCS;
1105 break;
1106 case elfcpp::SHT_HASH:
1107 case elfcpp::SHT_DYNAMIC:
1108 case elfcpp::SHT_SHLIB:
1109 case elfcpp::SHT_DYNSYM:
1110 case elfcpp::SHT_GNU_HASH:
1111 case elfcpp::SHT_GNU_verdef:
1112 case elfcpp::SHT_GNU_verneed:
1113 case elfcpp::SHT_GNU_versym:
1114 if (!is_write)
1115 return ORDER_DYNAMIC_LINKER;
1116 break;
1117 case elfcpp::SHT_NOTE:
1118 return is_write ? ORDER_RW_NOTE : ORDER_RO_NOTE;
1121 if ((os->flags() & elfcpp::SHF_TLS) != 0)
1122 return is_bss ? ORDER_TLS_BSS : ORDER_TLS_DATA;
1124 if (!is_bss && !is_write)
1126 if (is_execinstr)
1128 if (strcmp(os->name(), ".init") == 0)
1129 return ORDER_INIT;
1130 else if (strcmp(os->name(), ".fini") == 0)
1131 return ORDER_FINI;
1133 return is_execinstr ? ORDER_TEXT : ORDER_READONLY;
1136 if (os->is_relro())
1137 return is_relro_local ? ORDER_RELRO_LOCAL : ORDER_RELRO;
1139 if (os->is_small_section())
1140 return is_bss ? ORDER_SMALL_BSS : ORDER_SMALL_DATA;
1141 if (os->is_large_section())
1142 return is_bss ? ORDER_LARGE_BSS : ORDER_LARGE_DATA;
1144 return is_bss ? ORDER_BSS : ORDER_DATA;
1147 // Attach output sections to segments. This is called after we have
1148 // seen all the input sections.
1150 void
1151 Layout::attach_sections_to_segments()
1153 for (Section_list::iterator p = this->section_list_.begin();
1154 p != this->section_list_.end();
1155 ++p)
1156 this->attach_section_to_segment(*p);
1158 this->sections_are_attached_ = true;
1161 // Attach an output section to a segment.
1163 void
1164 Layout::attach_section_to_segment(Output_section* os)
1166 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1167 this->unattached_section_list_.push_back(os);
1168 else
1169 this->attach_allocated_section_to_segment(os);
1172 // Attach an allocated output section to a segment.
1174 void
1175 Layout::attach_allocated_section_to_segment(Output_section* os)
1177 elfcpp::Elf_Xword flags = os->flags();
1178 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
1180 if (parameters->options().relocatable())
1181 return;
1183 // If we have a SECTIONS clause, we can't handle the attachment to
1184 // segments until after we've seen all the sections.
1185 if (this->script_options_->saw_sections_clause())
1186 return;
1188 gold_assert(!this->script_options_->saw_phdrs_clause());
1190 // This output section goes into a PT_LOAD segment.
1192 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
1194 // Check for --section-start.
1195 uint64_t addr;
1196 bool is_address_set = parameters->options().section_start(os->name(), &addr);
1198 // In general the only thing we really care about for PT_LOAD
1199 // segments is whether or not they are writable or executable,
1200 // so that is how we search for them.
1201 // Large data sections also go into their own PT_LOAD segment.
1202 // People who need segments sorted on some other basis will
1203 // have to use a linker script.
1205 Segment_list::const_iterator p;
1206 for (p = this->segment_list_.begin();
1207 p != this->segment_list_.end();
1208 ++p)
1210 if ((*p)->type() != elfcpp::PT_LOAD)
1211 continue;
1212 if (!parameters->options().omagic()
1213 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1214 continue;
1215 if (parameters->options().rosegment()
1216 && ((*p)->flags() & elfcpp::PF_X) != (seg_flags & elfcpp::PF_X))
1217 continue;
1218 // If -Tbss was specified, we need to separate the data and BSS
1219 // segments.
1220 if (parameters->options().user_set_Tbss())
1222 if ((os->type() == elfcpp::SHT_NOBITS)
1223 == (*p)->has_any_data_sections())
1224 continue;
1226 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1227 continue;
1229 if (is_address_set)
1231 if ((*p)->are_addresses_set())
1232 continue;
1234 (*p)->add_initial_output_data(os);
1235 (*p)->update_flags_for_output_section(seg_flags);
1236 (*p)->set_addresses(addr, addr);
1237 break;
1240 (*p)->add_output_section_to_load(this, os, seg_flags);
1241 break;
1244 if (p == this->segment_list_.end())
1246 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1247 seg_flags);
1248 if (os->is_large_data_section())
1249 oseg->set_is_large_data_segment();
1250 oseg->add_output_section_to_load(this, os, seg_flags);
1251 if (is_address_set)
1252 oseg->set_addresses(addr, addr);
1255 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1256 // segment.
1257 if (os->type() == elfcpp::SHT_NOTE)
1259 // See if we already have an equivalent PT_NOTE segment.
1260 for (p = this->segment_list_.begin();
1261 p != segment_list_.end();
1262 ++p)
1264 if ((*p)->type() == elfcpp::PT_NOTE
1265 && (((*p)->flags() & elfcpp::PF_W)
1266 == (seg_flags & elfcpp::PF_W)))
1268 (*p)->add_output_section_to_nonload(os, seg_flags);
1269 break;
1273 if (p == this->segment_list_.end())
1275 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1276 seg_flags);
1277 oseg->add_output_section_to_nonload(os, seg_flags);
1281 // If we see a loadable SHF_TLS section, we create a PT_TLS
1282 // segment. There can only be one such segment.
1283 if ((flags & elfcpp::SHF_TLS) != 0)
1285 if (this->tls_segment_ == NULL)
1286 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1287 this->tls_segment_->add_output_section_to_nonload(os, seg_flags);
1290 // If -z relro is in effect, and we see a relro section, we create a
1291 // PT_GNU_RELRO segment. There can only be one such segment.
1292 if (os->is_relro() && parameters->options().relro())
1294 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1295 if (this->relro_segment_ == NULL)
1296 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1297 this->relro_segment_->add_output_section_to_nonload(os, seg_flags);
1301 // Make an output section for a script.
1303 Output_section*
1304 Layout::make_output_section_for_script(
1305 const char* name,
1306 Script_sections::Section_type section_type)
1308 name = this->namepool_.add(name, false, NULL);
1309 elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
1310 if (section_type == Script_sections::ST_NOLOAD)
1311 sh_flags = 0;
1312 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1313 sh_flags, ORDER_INVALID,
1314 false);
1315 os->set_found_in_sections_clause();
1316 if (section_type == Script_sections::ST_NOLOAD)
1317 os->set_is_noload();
1318 return os;
1321 // Return the number of segments we expect to see.
1323 size_t
1324 Layout::expected_segment_count() const
1326 size_t ret = this->segment_list_.size();
1328 // If we didn't see a SECTIONS clause in a linker script, we should
1329 // already have the complete list of segments. Otherwise we ask the
1330 // SECTIONS clause how many segments it expects, and add in the ones
1331 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1333 if (!this->script_options_->saw_sections_clause())
1334 return ret;
1335 else
1337 const Script_sections* ss = this->script_options_->script_sections();
1338 return ret + ss->expected_segment_count(this);
1342 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1343 // is whether we saw a .note.GNU-stack section in the object file.
1344 // GNU_STACK_FLAGS is the section flags. The flags give the
1345 // protection required for stack memory. We record this in an
1346 // executable as a PT_GNU_STACK segment. If an object file does not
1347 // have a .note.GNU-stack segment, we must assume that it is an old
1348 // object. On some targets that will force an executable stack.
1350 void
1351 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags,
1352 const Object* obj)
1354 if (!seen_gnu_stack)
1356 this->input_without_gnu_stack_note_ = true;
1357 if (parameters->options().warn_execstack()
1358 && parameters->target().is_default_stack_executable())
1359 gold_warning(_("%s: missing .note.GNU-stack section"
1360 " implies executable stack"),
1361 obj->name().c_str());
1363 else
1365 this->input_with_gnu_stack_note_ = true;
1366 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1368 this->input_requires_executable_stack_ = true;
1369 if (parameters->options().warn_execstack()
1370 || parameters->options().is_stack_executable())
1371 gold_warning(_("%s: requires executable stack"),
1372 obj->name().c_str());
1377 // Create automatic note sections.
1379 void
1380 Layout::create_notes()
1382 this->create_gold_note();
1383 this->create_executable_stack_info();
1384 this->create_build_id();
1387 // Create the dynamic sections which are needed before we read the
1388 // relocs.
1390 void
1391 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1393 if (parameters->doing_static_link())
1394 return;
1396 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1397 elfcpp::SHT_DYNAMIC,
1398 (elfcpp::SHF_ALLOC
1399 | elfcpp::SHF_WRITE),
1400 false, ORDER_RELRO,
1401 true);
1403 this->dynamic_symbol_ =
1404 symtab->define_in_output_data("_DYNAMIC", NULL, Symbol_table::PREDEFINED,
1405 this->dynamic_section_, 0, 0,
1406 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1407 elfcpp::STV_HIDDEN, 0, false, false);
1409 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1411 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1414 // For each output section whose name can be represented as C symbol,
1415 // define __start and __stop symbols for the section. This is a GNU
1416 // extension.
1418 void
1419 Layout::define_section_symbols(Symbol_table* symtab)
1421 for (Section_list::const_iterator p = this->section_list_.begin();
1422 p != this->section_list_.end();
1423 ++p)
1425 const char* const name = (*p)->name();
1426 if (is_cident(name))
1428 const std::string name_string(name);
1429 const std::string start_name(cident_section_start_prefix
1430 + name_string);
1431 const std::string stop_name(cident_section_stop_prefix
1432 + name_string);
1434 symtab->define_in_output_data(start_name.c_str(),
1435 NULL, // version
1436 Symbol_table::PREDEFINED,
1438 0, // value
1439 0, // symsize
1440 elfcpp::STT_NOTYPE,
1441 elfcpp::STB_GLOBAL,
1442 elfcpp::STV_DEFAULT,
1443 0, // nonvis
1444 false, // offset_is_from_end
1445 true); // only_if_ref
1447 symtab->define_in_output_data(stop_name.c_str(),
1448 NULL, // version
1449 Symbol_table::PREDEFINED,
1451 0, // value
1452 0, // symsize
1453 elfcpp::STT_NOTYPE,
1454 elfcpp::STB_GLOBAL,
1455 elfcpp::STV_DEFAULT,
1456 0, // nonvis
1457 true, // offset_is_from_end
1458 true); // only_if_ref
1463 // Define symbols for group signatures.
1465 void
1466 Layout::define_group_signatures(Symbol_table* symtab)
1468 for (Group_signatures::iterator p = this->group_signatures_.begin();
1469 p != this->group_signatures_.end();
1470 ++p)
1472 Symbol* sym = symtab->lookup(p->signature, NULL);
1473 if (sym != NULL)
1474 p->section->set_info_symndx(sym);
1475 else
1477 // Force the name of the group section to the group
1478 // signature, and use the group's section symbol as the
1479 // signature symbol.
1480 if (strcmp(p->section->name(), p->signature) != 0)
1482 const char* name = this->namepool_.add(p->signature,
1483 true, NULL);
1484 p->section->set_name(name);
1486 p->section->set_needs_symtab_index();
1487 p->section->set_info_section_symndx(p->section);
1491 this->group_signatures_.clear();
1494 // Find the first read-only PT_LOAD segment, creating one if
1495 // necessary.
1497 Output_segment*
1498 Layout::find_first_load_seg()
1500 Output_segment* best = NULL;
1501 for (Segment_list::const_iterator p = this->segment_list_.begin();
1502 p != this->segment_list_.end();
1503 ++p)
1505 if ((*p)->type() == elfcpp::PT_LOAD
1506 && ((*p)->flags() & elfcpp::PF_R) != 0
1507 && (parameters->options().omagic()
1508 || ((*p)->flags() & elfcpp::PF_W) == 0))
1510 if (best == NULL || this->segment_precedes(*p, best))
1511 best = *p;
1514 if (best != NULL)
1515 return best;
1517 gold_assert(!this->script_options_->saw_phdrs_clause());
1519 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1520 elfcpp::PF_R);
1521 return load_seg;
1524 // Save states of all current output segments. Store saved states
1525 // in SEGMENT_STATES.
1527 void
1528 Layout::save_segments(Segment_states* segment_states)
1530 for (Segment_list::const_iterator p = this->segment_list_.begin();
1531 p != this->segment_list_.end();
1532 ++p)
1534 Output_segment* segment = *p;
1535 // Shallow copy.
1536 Output_segment* copy = new Output_segment(*segment);
1537 (*segment_states)[segment] = copy;
1541 // Restore states of output segments and delete any segment not found in
1542 // SEGMENT_STATES.
1544 void
1545 Layout::restore_segments(const Segment_states* segment_states)
1547 // Go through the segment list and remove any segment added in the
1548 // relaxation loop.
1549 this->tls_segment_ = NULL;
1550 this->relro_segment_ = NULL;
1551 Segment_list::iterator list_iter = this->segment_list_.begin();
1552 while (list_iter != this->segment_list_.end())
1554 Output_segment* segment = *list_iter;
1555 Segment_states::const_iterator states_iter =
1556 segment_states->find(segment);
1557 if (states_iter != segment_states->end())
1559 const Output_segment* copy = states_iter->second;
1560 // Shallow copy to restore states.
1561 *segment = *copy;
1563 // Also fix up TLS and RELRO segment pointers as appropriate.
1564 if (segment->type() == elfcpp::PT_TLS)
1565 this->tls_segment_ = segment;
1566 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1567 this->relro_segment_ = segment;
1569 ++list_iter;
1571 else
1573 list_iter = this->segment_list_.erase(list_iter);
1574 // This is a segment created during section layout. It should be
1575 // safe to remove it since we should have removed all pointers to it.
1576 delete segment;
1581 // Clean up after relaxation so that sections can be laid out again.
1583 void
1584 Layout::clean_up_after_relaxation()
1586 // Restore the segments to point state just prior to the relaxation loop.
1587 Script_sections* script_section = this->script_options_->script_sections();
1588 script_section->release_segments();
1589 this->restore_segments(this->segment_states_);
1591 // Reset section addresses and file offsets
1592 for (Section_list::iterator p = this->section_list_.begin();
1593 p != this->section_list_.end();
1594 ++p)
1596 (*p)->restore_states();
1598 // If an input section changes size because of relaxation,
1599 // we need to adjust the section offsets of all input sections.
1600 // after such a section.
1601 if ((*p)->section_offsets_need_adjustment())
1602 (*p)->adjust_section_offsets();
1604 (*p)->reset_address_and_file_offset();
1607 // Reset special output object address and file offsets.
1608 for (Data_list::iterator p = this->special_output_list_.begin();
1609 p != this->special_output_list_.end();
1610 ++p)
1611 (*p)->reset_address_and_file_offset();
1613 // A linker script may have created some output section data objects.
1614 // They are useless now.
1615 for (Output_section_data_list::const_iterator p =
1616 this->script_output_section_data_list_.begin();
1617 p != this->script_output_section_data_list_.end();
1618 ++p)
1619 delete *p;
1620 this->script_output_section_data_list_.clear();
1623 // Prepare for relaxation.
1625 void
1626 Layout::prepare_for_relaxation()
1628 // Create an relaxation debug check if in debugging mode.
1629 if (is_debugging_enabled(DEBUG_RELAXATION))
1630 this->relaxation_debug_check_ = new Relaxation_debug_check();
1632 // Save segment states.
1633 this->segment_states_ = new Segment_states();
1634 this->save_segments(this->segment_states_);
1636 for(Section_list::const_iterator p = this->section_list_.begin();
1637 p != this->section_list_.end();
1638 ++p)
1639 (*p)->save_states();
1641 if (is_debugging_enabled(DEBUG_RELAXATION))
1642 this->relaxation_debug_check_->check_output_data_for_reset_values(
1643 this->section_list_, this->special_output_list_);
1645 // Also enable recording of output section data from scripts.
1646 this->record_output_section_data_from_script_ = true;
1649 // Relaxation loop body: If target has no relaxation, this runs only once
1650 // Otherwise, the target relaxation hook is called at the end of
1651 // each iteration. If the hook returns true, it means re-layout of
1652 // section is required.
1654 // The number of segments created by a linking script without a PHDRS
1655 // clause may be affected by section sizes and alignments. There is
1656 // a remote chance that relaxation causes different number of PT_LOAD
1657 // segments are created and sections are attached to different segments.
1658 // Therefore, we always throw away all segments created during section
1659 // layout. In order to be able to restart the section layout, we keep
1660 // a copy of the segment list right before the relaxation loop and use
1661 // that to restore the segments.
1663 // PASS is the current relaxation pass number.
1664 // SYMTAB is a symbol table.
1665 // PLOAD_SEG is the address of a pointer for the load segment.
1666 // PHDR_SEG is a pointer to the PHDR segment.
1667 // SEGMENT_HEADERS points to the output segment header.
1668 // FILE_HEADER points to the output file header.
1669 // PSHNDX is the address to store the output section index.
1671 off_t inline
1672 Layout::relaxation_loop_body(
1673 int pass,
1674 Target* target,
1675 Symbol_table* symtab,
1676 Output_segment** pload_seg,
1677 Output_segment* phdr_seg,
1678 Output_segment_headers* segment_headers,
1679 Output_file_header* file_header,
1680 unsigned int* pshndx)
1682 // If this is not the first iteration, we need to clean up after
1683 // relaxation so that we can lay out the sections again.
1684 if (pass != 0)
1685 this->clean_up_after_relaxation();
1687 // If there is a SECTIONS clause, put all the input sections into
1688 // the required order.
1689 Output_segment* load_seg;
1690 if (this->script_options_->saw_sections_clause())
1691 load_seg = this->set_section_addresses_from_script(symtab);
1692 else if (parameters->options().relocatable())
1693 load_seg = NULL;
1694 else
1695 load_seg = this->find_first_load_seg();
1697 if (parameters->options().oformat_enum()
1698 != General_options::OBJECT_FORMAT_ELF)
1699 load_seg = NULL;
1701 // If the user set the address of the text segment, that may not be
1702 // compatible with putting the segment headers and file headers into
1703 // that segment.
1704 if (parameters->options().user_set_Ttext())
1705 load_seg = NULL;
1707 gold_assert(phdr_seg == NULL
1708 || load_seg != NULL
1709 || this->script_options_->saw_sections_clause());
1711 // If the address of the load segment we found has been set by
1712 // --section-start rather than by a script, then adjust the VMA and
1713 // LMA downward if possible to include the file and section headers.
1714 uint64_t header_gap = 0;
1715 if (load_seg != NULL
1716 && load_seg->are_addresses_set()
1717 && !this->script_options_->saw_sections_clause()
1718 && !parameters->options().relocatable())
1720 file_header->finalize_data_size();
1721 segment_headers->finalize_data_size();
1722 size_t sizeof_headers = (file_header->data_size()
1723 + segment_headers->data_size());
1724 const uint64_t abi_pagesize = target->abi_pagesize();
1725 uint64_t hdr_paddr = load_seg->paddr() - sizeof_headers;
1726 hdr_paddr &= ~(abi_pagesize - 1);
1727 uint64_t subtract = load_seg->paddr() - hdr_paddr;
1728 if (load_seg->paddr() < subtract || load_seg->vaddr() < subtract)
1729 load_seg = NULL;
1730 else
1732 load_seg->set_addresses(load_seg->vaddr() - subtract,
1733 load_seg->paddr() - subtract);
1734 header_gap = subtract - sizeof_headers;
1738 // Lay out the segment headers.
1739 if (!parameters->options().relocatable())
1741 gold_assert(segment_headers != NULL);
1742 if (header_gap != 0 && load_seg != NULL)
1744 Output_data_zero_fill* z = new Output_data_zero_fill(header_gap, 1);
1745 load_seg->add_initial_output_data(z);
1747 if (load_seg != NULL)
1748 load_seg->add_initial_output_data(segment_headers);
1749 if (phdr_seg != NULL)
1750 phdr_seg->add_initial_output_data(segment_headers);
1753 // Lay out the file header.
1754 if (load_seg != NULL)
1755 load_seg->add_initial_output_data(file_header);
1757 if (this->script_options_->saw_phdrs_clause()
1758 && !parameters->options().relocatable())
1760 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1761 // clause in a linker script.
1762 Script_sections* ss = this->script_options_->script_sections();
1763 ss->put_headers_in_phdrs(file_header, segment_headers);
1766 // We set the output section indexes in set_segment_offsets and
1767 // set_section_indexes.
1768 *pshndx = 1;
1770 // Set the file offsets of all the segments, and all the sections
1771 // they contain.
1772 off_t off;
1773 if (!parameters->options().relocatable())
1774 off = this->set_segment_offsets(target, load_seg, pshndx);
1775 else
1776 off = this->set_relocatable_section_offsets(file_header, pshndx);
1778 // Verify that the dummy relaxation does not change anything.
1779 if (is_debugging_enabled(DEBUG_RELAXATION))
1781 if (pass == 0)
1782 this->relaxation_debug_check_->read_sections(this->section_list_);
1783 else
1784 this->relaxation_debug_check_->verify_sections(this->section_list_);
1787 *pload_seg = load_seg;
1788 return off;
1791 // Search the list of patterns and find the postion of the given section
1792 // name in the output section. If the section name matches a glob
1793 // pattern and a non-glob name, then the non-glob position takes
1794 // precedence. Return 0 if no match is found.
1796 unsigned int
1797 Layout::find_section_order_index(const std::string& section_name)
1799 Unordered_map<std::string, unsigned int>::iterator map_it;
1800 map_it = this->input_section_position_.find(section_name);
1801 if (map_it != this->input_section_position_.end())
1802 return map_it->second;
1804 // Absolute match failed. Linear search the glob patterns.
1805 std::vector<std::string>::iterator it;
1806 for (it = this->input_section_glob_.begin();
1807 it != this->input_section_glob_.end();
1808 ++it)
1810 if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
1812 map_it = this->input_section_position_.find(*it);
1813 gold_assert(map_it != this->input_section_position_.end());
1814 return map_it->second;
1817 return 0;
1820 // Read the sequence of input sections from the file specified with
1821 // --section-ordering-file.
1823 void
1824 Layout::read_layout_from_file()
1826 const char* filename = parameters->options().section_ordering_file();
1827 std::ifstream in;
1828 std::string line;
1830 in.open(filename);
1831 if (!in)
1832 gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
1833 filename, strerror(errno));
1835 std::getline(in, line); // this chops off the trailing \n, if any
1836 unsigned int position = 1;
1838 while (in)
1840 if (!line.empty() && line[line.length() - 1] == '\r') // Windows
1841 line.resize(line.length() - 1);
1842 // Ignore comments, beginning with '#'
1843 if (line[0] == '#')
1845 std::getline(in, line);
1846 continue;
1848 this->input_section_position_[line] = position;
1849 // Store all glob patterns in a vector.
1850 if (is_wildcard_string(line.c_str()))
1851 this->input_section_glob_.push_back(line);
1852 position++;
1853 std::getline(in, line);
1857 // Finalize the layout. When this is called, we have created all the
1858 // output sections and all the output segments which are based on
1859 // input sections. We have several things to do, and we have to do
1860 // them in the right order, so that we get the right results correctly
1861 // and efficiently.
1863 // 1) Finalize the list of output segments and create the segment
1864 // table header.
1866 // 2) Finalize the dynamic symbol table and associated sections.
1868 // 3) Determine the final file offset of all the output segments.
1870 // 4) Determine the final file offset of all the SHF_ALLOC output
1871 // sections.
1873 // 5) Create the symbol table sections and the section name table
1874 // section.
1876 // 6) Finalize the symbol table: set symbol values to their final
1877 // value and make a final determination of which symbols are going
1878 // into the output symbol table.
1880 // 7) Create the section table header.
1882 // 8) Determine the final file offset of all the output sections which
1883 // are not SHF_ALLOC, including the section table header.
1885 // 9) Finalize the ELF file header.
1887 // This function returns the size of the output file.
1889 off_t
1890 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1891 Target* target, const Task* task)
1893 target->finalize_sections(this, input_objects, symtab);
1895 this->count_local_symbols(task, input_objects);
1897 this->link_stabs_sections();
1899 Output_segment* phdr_seg = NULL;
1900 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1902 // There was a dynamic object in the link. We need to create
1903 // some information for the dynamic linker.
1905 // Create the PT_PHDR segment which will hold the program
1906 // headers.
1907 if (!this->script_options_->saw_phdrs_clause())
1908 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1910 // Create the dynamic symbol table, including the hash table.
1911 Output_section* dynstr;
1912 std::vector<Symbol*> dynamic_symbols;
1913 unsigned int local_dynamic_count;
1914 Versions versions(*this->script_options()->version_script_info(),
1915 &this->dynpool_);
1916 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1917 &local_dynamic_count, &dynamic_symbols,
1918 &versions);
1920 // Create the .interp section to hold the name of the
1921 // interpreter, and put it in a PT_INTERP segment.
1922 if (!parameters->options().shared())
1923 this->create_interp(target);
1925 // Finish the .dynamic section to hold the dynamic data, and put
1926 // it in a PT_DYNAMIC segment.
1927 this->finish_dynamic_section(input_objects, symtab);
1929 // We should have added everything we need to the dynamic string
1930 // table.
1931 this->dynpool_.set_string_offsets();
1933 // Create the version sections. We can't do this until the
1934 // dynamic string table is complete.
1935 this->create_version_sections(&versions, symtab, local_dynamic_count,
1936 dynamic_symbols, dynstr);
1938 // Set the size of the _DYNAMIC symbol. We can't do this until
1939 // after we call create_version_sections.
1940 this->set_dynamic_symbol_size(symtab);
1943 // Create segment headers.
1944 Output_segment_headers* segment_headers =
1945 (parameters->options().relocatable()
1946 ? NULL
1947 : new Output_segment_headers(this->segment_list_));
1949 // Lay out the file header.
1950 Output_file_header* file_header
1951 = new Output_file_header(target, symtab, segment_headers,
1952 parameters->options().entry());
1954 this->special_output_list_.push_back(file_header);
1955 if (segment_headers != NULL)
1956 this->special_output_list_.push_back(segment_headers);
1958 // Find approriate places for orphan output sections if we are using
1959 // a linker script.
1960 if (this->script_options_->saw_sections_clause())
1961 this->place_orphan_sections_in_script();
1963 Output_segment* load_seg;
1964 off_t off;
1965 unsigned int shndx;
1966 int pass = 0;
1968 // Take a snapshot of the section layout as needed.
1969 if (target->may_relax())
1970 this->prepare_for_relaxation();
1972 // Run the relaxation loop to lay out sections.
1975 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1976 phdr_seg, segment_headers, file_header,
1977 &shndx);
1978 pass++;
1980 while (target->may_relax()
1981 && target->relax(pass, input_objects, symtab, this, task));
1983 // Set the file offsets of all the non-data sections we've seen so
1984 // far which don't have to wait for the input sections. We need
1985 // this in order to finalize local symbols in non-allocated
1986 // sections.
1987 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1989 // Set the section indexes of all unallocated sections seen so far,
1990 // in case any of them are somehow referenced by a symbol.
1991 shndx = this->set_section_indexes(shndx);
1993 // Create the symbol table sections.
1994 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1995 if (!parameters->doing_static_link())
1996 this->assign_local_dynsym_offsets(input_objects);
1998 // Process any symbol assignments from a linker script. This must
1999 // be called after the symbol table has been finalized.
2000 this->script_options_->finalize_symbols(symtab, this);
2002 // Create the incremental inputs sections.
2003 if (this->incremental_inputs_)
2005 this->incremental_inputs_->finalize();
2006 this->create_incremental_info_sections(symtab);
2009 // Create the .shstrtab section.
2010 Output_section* shstrtab_section = this->create_shstrtab();
2012 // Set the file offsets of the rest of the non-data sections which
2013 // don't have to wait for the input sections.
2014 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
2016 // Now that all sections have been created, set the section indexes
2017 // for any sections which haven't been done yet.
2018 shndx = this->set_section_indexes(shndx);
2020 // Create the section table header.
2021 this->create_shdrs(shstrtab_section, &off);
2023 // If there are no sections which require postprocessing, we can
2024 // handle the section names now, and avoid a resize later.
2025 if (!this->any_postprocessing_sections_)
2027 off = this->set_section_offsets(off,
2028 POSTPROCESSING_SECTIONS_PASS);
2029 off =
2030 this->set_section_offsets(off,
2031 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2034 file_header->set_section_info(this->section_headers_, shstrtab_section);
2036 // Now we know exactly where everything goes in the output file
2037 // (except for non-allocated sections which require postprocessing).
2038 Output_data::layout_complete();
2040 this->output_file_size_ = off;
2042 return off;
2045 // Create a note header following the format defined in the ELF ABI.
2046 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
2047 // of the section to create, DESCSZ is the size of the descriptor.
2048 // ALLOCATE is true if the section should be allocated in memory.
2049 // This returns the new note section. It sets *TRAILING_PADDING to
2050 // the number of trailing zero bytes required.
2052 Output_section*
2053 Layout::create_note(const char* name, int note_type,
2054 const char* section_name, size_t descsz,
2055 bool allocate, size_t* trailing_padding)
2057 // Authorities all agree that the values in a .note field should
2058 // be aligned on 4-byte boundaries for 32-bit binaries. However,
2059 // they differ on what the alignment is for 64-bit binaries.
2060 // The GABI says unambiguously they take 8-byte alignment:
2061 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
2062 // Other documentation says alignment should always be 4 bytes:
2063 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
2064 // GNU ld and GNU readelf both support the latter (at least as of
2065 // version 2.16.91), and glibc always generates the latter for
2066 // .note.ABI-tag (as of version 1.6), so that's the one we go with
2067 // here.
2068 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
2069 const int size = parameters->target().get_size();
2070 #else
2071 const int size = 32;
2072 #endif
2074 // The contents of the .note section.
2075 size_t namesz = strlen(name) + 1;
2076 size_t aligned_namesz = align_address(namesz, size / 8);
2077 size_t aligned_descsz = align_address(descsz, size / 8);
2079 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
2081 unsigned char* buffer = new unsigned char[notehdrsz];
2082 memset(buffer, 0, notehdrsz);
2084 bool is_big_endian = parameters->target().is_big_endian();
2086 if (size == 32)
2088 if (!is_big_endian)
2090 elfcpp::Swap<32, false>::writeval(buffer, namesz);
2091 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
2092 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
2094 else
2096 elfcpp::Swap<32, true>::writeval(buffer, namesz);
2097 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
2098 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
2101 else if (size == 64)
2103 if (!is_big_endian)
2105 elfcpp::Swap<64, false>::writeval(buffer, namesz);
2106 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
2107 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
2109 else
2111 elfcpp::Swap<64, true>::writeval(buffer, namesz);
2112 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
2113 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
2116 else
2117 gold_unreachable();
2119 memcpy(buffer + 3 * (size / 8), name, namesz);
2121 elfcpp::Elf_Xword flags = 0;
2122 Output_section_order order = ORDER_INVALID;
2123 if (allocate)
2125 flags = elfcpp::SHF_ALLOC;
2126 order = ORDER_RO_NOTE;
2128 Output_section* os = this->choose_output_section(NULL, section_name,
2129 elfcpp::SHT_NOTE,
2130 flags, false, order, false);
2131 if (os == NULL)
2132 return NULL;
2134 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
2135 size / 8,
2136 "** note header");
2137 os->add_output_section_data(posd);
2139 *trailing_padding = aligned_descsz - descsz;
2141 return os;
2144 // For an executable or shared library, create a note to record the
2145 // version of gold used to create the binary.
2147 void
2148 Layout::create_gold_note()
2150 if (parameters->options().relocatable())
2151 return;
2153 std::string desc = std::string("gold ") + gold::get_version_string();
2155 size_t trailing_padding;
2156 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
2157 ".note.gnu.gold-version", desc.size(),
2158 false, &trailing_padding);
2159 if (os == NULL)
2160 return;
2162 Output_section_data* posd = new Output_data_const(desc, 4);
2163 os->add_output_section_data(posd);
2165 if (trailing_padding > 0)
2167 posd = new Output_data_zero_fill(trailing_padding, 0);
2168 os->add_output_section_data(posd);
2172 // Record whether the stack should be executable. This can be set
2173 // from the command line using the -z execstack or -z noexecstack
2174 // options. Otherwise, if any input file has a .note.GNU-stack
2175 // section with the SHF_EXECINSTR flag set, the stack should be
2176 // executable. Otherwise, if at least one input file a
2177 // .note.GNU-stack section, and some input file has no .note.GNU-stack
2178 // section, we use the target default for whether the stack should be
2179 // executable. Otherwise, we don't generate a stack note. When
2180 // generating a object file, we create a .note.GNU-stack section with
2181 // the appropriate marking. When generating an executable or shared
2182 // library, we create a PT_GNU_STACK segment.
2184 void
2185 Layout::create_executable_stack_info()
2187 bool is_stack_executable;
2188 if (parameters->options().is_execstack_set())
2189 is_stack_executable = parameters->options().is_stack_executable();
2190 else if (!this->input_with_gnu_stack_note_)
2191 return;
2192 else
2194 if (this->input_requires_executable_stack_)
2195 is_stack_executable = true;
2196 else if (this->input_without_gnu_stack_note_)
2197 is_stack_executable =
2198 parameters->target().is_default_stack_executable();
2199 else
2200 is_stack_executable = false;
2203 if (parameters->options().relocatable())
2205 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
2206 elfcpp::Elf_Xword flags = 0;
2207 if (is_stack_executable)
2208 flags |= elfcpp::SHF_EXECINSTR;
2209 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags,
2210 ORDER_INVALID, false);
2212 else
2214 if (this->script_options_->saw_phdrs_clause())
2215 return;
2216 int flags = elfcpp::PF_R | elfcpp::PF_W;
2217 if (is_stack_executable)
2218 flags |= elfcpp::PF_X;
2219 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
2223 // If --build-id was used, set up the build ID note.
2225 void
2226 Layout::create_build_id()
2228 if (!parameters->options().user_set_build_id())
2229 return;
2231 const char* style = parameters->options().build_id();
2232 if (strcmp(style, "none") == 0)
2233 return;
2235 // Set DESCSZ to the size of the note descriptor. When possible,
2236 // set DESC to the note descriptor contents.
2237 size_t descsz;
2238 std::string desc;
2239 if (strcmp(style, "md5") == 0)
2240 descsz = 128 / 8;
2241 else if (strcmp(style, "sha1") == 0)
2242 descsz = 160 / 8;
2243 else if (strcmp(style, "uuid") == 0)
2245 const size_t uuidsz = 128 / 8;
2247 char buffer[uuidsz];
2248 memset(buffer, 0, uuidsz);
2250 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
2251 if (descriptor < 0)
2252 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
2253 strerror(errno));
2254 else
2256 ssize_t got = ::read(descriptor, buffer, uuidsz);
2257 release_descriptor(descriptor, true);
2258 if (got < 0)
2259 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
2260 else if (static_cast<size_t>(got) != uuidsz)
2261 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
2262 uuidsz, got);
2265 desc.assign(buffer, uuidsz);
2266 descsz = uuidsz;
2268 else if (strncmp(style, "0x", 2) == 0)
2270 hex_init();
2271 const char* p = style + 2;
2272 while (*p != '\0')
2274 if (hex_p(p[0]) && hex_p(p[1]))
2276 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
2277 desc += c;
2278 p += 2;
2280 else if (*p == '-' || *p == ':')
2281 ++p;
2282 else
2283 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
2284 style);
2286 descsz = desc.size();
2288 else
2289 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
2291 // Create the note.
2292 size_t trailing_padding;
2293 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
2294 ".note.gnu.build-id", descsz, true,
2295 &trailing_padding);
2296 if (os == NULL)
2297 return;
2299 if (!desc.empty())
2301 // We know the value already, so we fill it in now.
2302 gold_assert(desc.size() == descsz);
2304 Output_section_data* posd = new Output_data_const(desc, 4);
2305 os->add_output_section_data(posd);
2307 if (trailing_padding != 0)
2309 posd = new Output_data_zero_fill(trailing_padding, 0);
2310 os->add_output_section_data(posd);
2313 else
2315 // We need to compute a checksum after we have completed the
2316 // link.
2317 gold_assert(trailing_padding == 0);
2318 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
2319 os->add_output_section_data(this->build_id_note_);
2323 // If we have both .stabXX and .stabXXstr sections, then the sh_link
2324 // field of the former should point to the latter. I'm not sure who
2325 // started this, but the GNU linker does it, and some tools depend
2326 // upon it.
2328 void
2329 Layout::link_stabs_sections()
2331 if (!this->have_stabstr_section_)
2332 return;
2334 for (Section_list::iterator p = this->section_list_.begin();
2335 p != this->section_list_.end();
2336 ++p)
2338 if ((*p)->type() != elfcpp::SHT_STRTAB)
2339 continue;
2341 const char* name = (*p)->name();
2342 if (strncmp(name, ".stab", 5) != 0)
2343 continue;
2345 size_t len = strlen(name);
2346 if (strcmp(name + len - 3, "str") != 0)
2347 continue;
2349 std::string stab_name(name, len - 3);
2350 Output_section* stab_sec;
2351 stab_sec = this->find_output_section(stab_name.c_str());
2352 if (stab_sec != NULL)
2353 stab_sec->set_link_section(*p);
2357 // Create .gnu_incremental_inputs and related sections needed
2358 // for the next run of incremental linking to check what has changed.
2360 void
2361 Layout::create_incremental_info_sections(Symbol_table* symtab)
2363 Incremental_inputs* incr = this->incremental_inputs_;
2365 gold_assert(incr != NULL);
2367 // Create the .gnu_incremental_inputs, _symtab, and _relocs input sections.
2368 incr->create_data_sections(symtab);
2370 // Add the .gnu_incremental_inputs section.
2371 const char* incremental_inputs_name =
2372 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
2373 Output_section* incremental_inputs_os =
2374 this->make_output_section(incremental_inputs_name,
2375 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2376 ORDER_INVALID, false);
2377 incremental_inputs_os->add_output_section_data(incr->inputs_section());
2379 // Add the .gnu_incremental_symtab section.
2380 const char* incremental_symtab_name =
2381 this->namepool_.add(".gnu_incremental_symtab", false, NULL);
2382 Output_section* incremental_symtab_os =
2383 this->make_output_section(incremental_symtab_name,
2384 elfcpp::SHT_GNU_INCREMENTAL_SYMTAB, 0,
2385 ORDER_INVALID, false);
2386 incremental_symtab_os->add_output_section_data(incr->symtab_section());
2387 incremental_symtab_os->set_entsize(4);
2389 // Add the .gnu_incremental_relocs section.
2390 const char* incremental_relocs_name =
2391 this->namepool_.add(".gnu_incremental_relocs", false, NULL);
2392 Output_section* incremental_relocs_os =
2393 this->make_output_section(incremental_relocs_name,
2394 elfcpp::SHT_GNU_INCREMENTAL_RELOCS, 0,
2395 ORDER_INVALID, false);
2396 incremental_relocs_os->add_output_section_data(incr->relocs_section());
2397 incremental_relocs_os->set_entsize(incr->relocs_entsize());
2399 // Add the .gnu_incremental_got_plt section.
2400 const char* incremental_got_plt_name =
2401 this->namepool_.add(".gnu_incremental_got_plt", false, NULL);
2402 Output_section* incremental_got_plt_os =
2403 this->make_output_section(incremental_got_plt_name,
2404 elfcpp::SHT_GNU_INCREMENTAL_GOT_PLT, 0,
2405 ORDER_INVALID, false);
2406 incremental_got_plt_os->add_output_section_data(incr->got_plt_section());
2408 // Add the .gnu_incremental_strtab section.
2409 const char* incremental_strtab_name =
2410 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2411 Output_section* incremental_strtab_os = this->make_output_section(incremental_strtab_name,
2412 elfcpp::SHT_STRTAB, 0,
2413 ORDER_INVALID, false);
2414 Output_data_strtab* strtab_data =
2415 new Output_data_strtab(incr->get_stringpool());
2416 incremental_strtab_os->add_output_section_data(strtab_data);
2418 incremental_inputs_os->set_after_input_sections();
2419 incremental_symtab_os->set_after_input_sections();
2420 incremental_relocs_os->set_after_input_sections();
2421 incremental_got_plt_os->set_after_input_sections();
2423 incremental_inputs_os->set_link_section(incremental_strtab_os);
2424 incremental_symtab_os->set_link_section(incremental_inputs_os);
2425 incremental_relocs_os->set_link_section(incremental_inputs_os);
2426 incremental_got_plt_os->set_link_section(incremental_inputs_os);
2429 // Return whether SEG1 should be before SEG2 in the output file. This
2430 // is based entirely on the segment type and flags. When this is
2431 // called the segment addresses has normally not yet been set.
2433 bool
2434 Layout::segment_precedes(const Output_segment* seg1,
2435 const Output_segment* seg2)
2437 elfcpp::Elf_Word type1 = seg1->type();
2438 elfcpp::Elf_Word type2 = seg2->type();
2440 // The single PT_PHDR segment is required to precede any loadable
2441 // segment. We simply make it always first.
2442 if (type1 == elfcpp::PT_PHDR)
2444 gold_assert(type2 != elfcpp::PT_PHDR);
2445 return true;
2447 if (type2 == elfcpp::PT_PHDR)
2448 return false;
2450 // The single PT_INTERP segment is required to precede any loadable
2451 // segment. We simply make it always second.
2452 if (type1 == elfcpp::PT_INTERP)
2454 gold_assert(type2 != elfcpp::PT_INTERP);
2455 return true;
2457 if (type2 == elfcpp::PT_INTERP)
2458 return false;
2460 // We then put PT_LOAD segments before any other segments.
2461 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2462 return true;
2463 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2464 return false;
2466 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2467 // segment, because that is where the dynamic linker expects to find
2468 // it (this is just for efficiency; other positions would also work
2469 // correctly).
2470 if (type1 == elfcpp::PT_TLS
2471 && type2 != elfcpp::PT_TLS
2472 && type2 != elfcpp::PT_GNU_RELRO)
2473 return false;
2474 if (type2 == elfcpp::PT_TLS
2475 && type1 != elfcpp::PT_TLS
2476 && type1 != elfcpp::PT_GNU_RELRO)
2477 return true;
2479 // We put the PT_GNU_RELRO segment last, because that is where the
2480 // dynamic linker expects to find it (as with PT_TLS, this is just
2481 // for efficiency).
2482 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2483 return false;
2484 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2485 return true;
2487 const elfcpp::Elf_Word flags1 = seg1->flags();
2488 const elfcpp::Elf_Word flags2 = seg2->flags();
2490 // The order of non-PT_LOAD segments is unimportant. We simply sort
2491 // by the numeric segment type and flags values. There should not
2492 // be more than one segment with the same type and flags.
2493 if (type1 != elfcpp::PT_LOAD)
2495 if (type1 != type2)
2496 return type1 < type2;
2497 gold_assert(flags1 != flags2);
2498 return flags1 < flags2;
2501 // If the addresses are set already, sort by load address.
2502 if (seg1->are_addresses_set())
2504 if (!seg2->are_addresses_set())
2505 return true;
2507 unsigned int section_count1 = seg1->output_section_count();
2508 unsigned int section_count2 = seg2->output_section_count();
2509 if (section_count1 == 0 && section_count2 > 0)
2510 return true;
2511 if (section_count1 > 0 && section_count2 == 0)
2512 return false;
2514 uint64_t paddr1 = (seg1->are_addresses_set()
2515 ? seg1->paddr()
2516 : seg1->first_section_load_address());
2517 uint64_t paddr2 = (seg2->are_addresses_set()
2518 ? seg2->paddr()
2519 : seg2->first_section_load_address());
2521 if (paddr1 != paddr2)
2522 return paddr1 < paddr2;
2524 else if (seg2->are_addresses_set())
2525 return false;
2527 // A segment which holds large data comes after a segment which does
2528 // not hold large data.
2529 if (seg1->is_large_data_segment())
2531 if (!seg2->is_large_data_segment())
2532 return false;
2534 else if (seg2->is_large_data_segment())
2535 return true;
2537 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2538 // segments come before writable segments. Then writable segments
2539 // with data come before writable segments without data. Then
2540 // executable segments come before non-executable segments. Then
2541 // the unlikely case of a non-readable segment comes before the
2542 // normal case of a readable segment. If there are multiple
2543 // segments with the same type and flags, we require that the
2544 // address be set, and we sort by virtual address and then physical
2545 // address.
2546 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2547 return (flags1 & elfcpp::PF_W) == 0;
2548 if ((flags1 & elfcpp::PF_W) != 0
2549 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2550 return seg1->has_any_data_sections();
2551 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2552 return (flags1 & elfcpp::PF_X) != 0;
2553 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2554 return (flags1 & elfcpp::PF_R) == 0;
2556 // We shouldn't get here--we shouldn't create segments which we
2557 // can't distinguish.
2558 gold_unreachable();
2561 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2563 static off_t
2564 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2566 uint64_t unsigned_off = off;
2567 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2568 | (addr & (abi_pagesize - 1)));
2569 if (aligned_off < unsigned_off)
2570 aligned_off += abi_pagesize;
2571 return aligned_off;
2574 // Set the file offsets of all the segments, and all the sections they
2575 // contain. They have all been created. LOAD_SEG must be be laid out
2576 // first. Return the offset of the data to follow.
2578 off_t
2579 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2580 unsigned int* pshndx)
2582 // Sort them into the final order.
2583 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2584 Layout::Compare_segments());
2586 // Find the PT_LOAD segments, and set their addresses and offsets
2587 // and their section's addresses and offsets.
2588 uint64_t addr;
2589 if (parameters->options().user_set_Ttext())
2590 addr = parameters->options().Ttext();
2591 else if (parameters->options().output_is_position_independent())
2592 addr = 0;
2593 else
2594 addr = target->default_text_segment_address();
2595 off_t off = 0;
2597 // If LOAD_SEG is NULL, then the file header and segment headers
2598 // will not be loadable. But they still need to be at offset 0 in
2599 // the file. Set their offsets now.
2600 if (load_seg == NULL)
2602 for (Data_list::iterator p = this->special_output_list_.begin();
2603 p != this->special_output_list_.end();
2604 ++p)
2606 off = align_address(off, (*p)->addralign());
2607 (*p)->set_address_and_file_offset(0, off);
2608 off += (*p)->data_size();
2612 unsigned int increase_relro = this->increase_relro_;
2613 if (this->script_options_->saw_sections_clause())
2614 increase_relro = 0;
2616 const bool check_sections = parameters->options().check_sections();
2617 Output_segment* last_load_segment = NULL;
2619 for (Segment_list::iterator p = this->segment_list_.begin();
2620 p != this->segment_list_.end();
2621 ++p)
2623 if ((*p)->type() == elfcpp::PT_LOAD)
2625 if (load_seg != NULL && load_seg != *p)
2626 gold_unreachable();
2627 load_seg = NULL;
2629 bool are_addresses_set = (*p)->are_addresses_set();
2630 if (are_addresses_set)
2632 // When it comes to setting file offsets, we care about
2633 // the physical address.
2634 addr = (*p)->paddr();
2636 else if (parameters->options().user_set_Tdata()
2637 && ((*p)->flags() & elfcpp::PF_W) != 0
2638 && (!parameters->options().user_set_Tbss()
2639 || (*p)->has_any_data_sections()))
2641 addr = parameters->options().Tdata();
2642 are_addresses_set = true;
2644 else if (parameters->options().user_set_Tbss()
2645 && ((*p)->flags() & elfcpp::PF_W) != 0
2646 && !(*p)->has_any_data_sections())
2648 addr = parameters->options().Tbss();
2649 are_addresses_set = true;
2652 uint64_t orig_addr = addr;
2653 uint64_t orig_off = off;
2655 uint64_t aligned_addr = 0;
2656 uint64_t abi_pagesize = target->abi_pagesize();
2657 uint64_t common_pagesize = target->common_pagesize();
2659 if (!parameters->options().nmagic()
2660 && !parameters->options().omagic())
2661 (*p)->set_minimum_p_align(common_pagesize);
2663 if (!are_addresses_set)
2665 // Skip the address forward one page, maintaining the same
2666 // position within the page. This lets us store both segments
2667 // overlapping on a single page in the file, but the loader will
2668 // put them on different pages in memory. We will revisit this
2669 // decision once we know the size of the segment.
2671 addr = align_address(addr, (*p)->maximum_alignment());
2672 aligned_addr = addr;
2674 if ((addr & (abi_pagesize - 1)) != 0)
2675 addr = addr + abi_pagesize;
2677 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2680 if (!parameters->options().nmagic()
2681 && !parameters->options().omagic())
2682 off = align_file_offset(off, addr, abi_pagesize);
2683 else if (load_seg == NULL)
2685 // This is -N or -n with a section script which prevents
2686 // us from using a load segment. We need to ensure that
2687 // the file offset is aligned to the alignment of the
2688 // segment. This is because the linker script
2689 // implicitly assumed a zero offset. If we don't align
2690 // here, then the alignment of the sections in the
2691 // linker script may not match the alignment of the
2692 // sections in the set_section_addresses call below,
2693 // causing an error about dot moving backward.
2694 off = align_address(off, (*p)->maximum_alignment());
2697 unsigned int shndx_hold = *pshndx;
2698 bool has_relro = false;
2699 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2700 &increase_relro,
2701 &has_relro,
2702 &off, pshndx);
2704 // Now that we know the size of this segment, we may be able
2705 // to save a page in memory, at the cost of wasting some
2706 // file space, by instead aligning to the start of a new
2707 // page. Here we use the real machine page size rather than
2708 // the ABI mandated page size. If the segment has been
2709 // aligned so that the relro data ends at a page boundary,
2710 // we do not try to realign it.
2712 if (!are_addresses_set && !has_relro && aligned_addr != addr)
2714 uint64_t first_off = (common_pagesize
2715 - (aligned_addr
2716 & (common_pagesize - 1)));
2717 uint64_t last_off = new_addr & (common_pagesize - 1);
2718 if (first_off > 0
2719 && last_off > 0
2720 && ((aligned_addr & ~ (common_pagesize - 1))
2721 != (new_addr & ~ (common_pagesize - 1)))
2722 && first_off + last_off <= common_pagesize)
2724 *pshndx = shndx_hold;
2725 addr = align_address(aligned_addr, common_pagesize);
2726 addr = align_address(addr, (*p)->maximum_alignment());
2727 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2728 off = align_file_offset(off, addr, abi_pagesize);
2730 increase_relro = this->increase_relro_;
2731 if (this->script_options_->saw_sections_clause())
2732 increase_relro = 0;
2733 has_relro = false;
2735 new_addr = (*p)->set_section_addresses(this, true, addr,
2736 &increase_relro,
2737 &has_relro,
2738 &off, pshndx);
2742 addr = new_addr;
2744 // Implement --check-sections. We know that the segments
2745 // are sorted by LMA.
2746 if (check_sections && last_load_segment != NULL)
2748 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2749 if (last_load_segment->paddr() + last_load_segment->memsz()
2750 > (*p)->paddr())
2752 unsigned long long lb1 = last_load_segment->paddr();
2753 unsigned long long le1 = lb1 + last_load_segment->memsz();
2754 unsigned long long lb2 = (*p)->paddr();
2755 unsigned long long le2 = lb2 + (*p)->memsz();
2756 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2757 "[0x%llx -> 0x%llx]"),
2758 lb1, le1, lb2, le2);
2761 last_load_segment = *p;
2765 // Handle the non-PT_LOAD segments, setting their offsets from their
2766 // section's offsets.
2767 for (Segment_list::iterator p = this->segment_list_.begin();
2768 p != this->segment_list_.end();
2769 ++p)
2771 if ((*p)->type() != elfcpp::PT_LOAD)
2772 (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
2773 ? increase_relro
2774 : 0);
2777 // Set the TLS offsets for each section in the PT_TLS segment.
2778 if (this->tls_segment_ != NULL)
2779 this->tls_segment_->set_tls_offsets();
2781 return off;
2784 // Set the offsets of all the allocated sections when doing a
2785 // relocatable link. This does the same jobs as set_segment_offsets,
2786 // only for a relocatable link.
2788 off_t
2789 Layout::set_relocatable_section_offsets(Output_data* file_header,
2790 unsigned int* pshndx)
2792 off_t off = 0;
2794 file_header->set_address_and_file_offset(0, 0);
2795 off += file_header->data_size();
2797 for (Section_list::iterator p = this->section_list_.begin();
2798 p != this->section_list_.end();
2799 ++p)
2801 // We skip unallocated sections here, except that group sections
2802 // have to come first.
2803 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2804 && (*p)->type() != elfcpp::SHT_GROUP)
2805 continue;
2807 off = align_address(off, (*p)->addralign());
2809 // The linker script might have set the address.
2810 if (!(*p)->is_address_valid())
2811 (*p)->set_address(0);
2812 (*p)->set_file_offset(off);
2813 (*p)->finalize_data_size();
2814 off += (*p)->data_size();
2816 (*p)->set_out_shndx(*pshndx);
2817 ++*pshndx;
2820 return off;
2823 // Set the file offset of all the sections not associated with a
2824 // segment.
2826 off_t
2827 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2829 for (Section_list::iterator p = this->unattached_section_list_.begin();
2830 p != this->unattached_section_list_.end();
2831 ++p)
2833 // The symtab section is handled in create_symtab_sections.
2834 if (*p == this->symtab_section_)
2835 continue;
2837 // If we've already set the data size, don't set it again.
2838 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2839 continue;
2841 if (pass == BEFORE_INPUT_SECTIONS_PASS
2842 && (*p)->requires_postprocessing())
2844 (*p)->create_postprocessing_buffer();
2845 this->any_postprocessing_sections_ = true;
2848 if (pass == BEFORE_INPUT_SECTIONS_PASS
2849 && (*p)->after_input_sections())
2850 continue;
2851 else if (pass == POSTPROCESSING_SECTIONS_PASS
2852 && (!(*p)->after_input_sections()
2853 || (*p)->type() == elfcpp::SHT_STRTAB))
2854 continue;
2855 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2856 && (!(*p)->after_input_sections()
2857 || (*p)->type() != elfcpp::SHT_STRTAB))
2858 continue;
2860 off = align_address(off, (*p)->addralign());
2861 (*p)->set_file_offset(off);
2862 (*p)->finalize_data_size();
2863 off += (*p)->data_size();
2865 // At this point the name must be set.
2866 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2867 this->namepool_.add((*p)->name(), false, NULL);
2869 return off;
2872 // Set the section indexes of all the sections not associated with a
2873 // segment.
2875 unsigned int
2876 Layout::set_section_indexes(unsigned int shndx)
2878 for (Section_list::iterator p = this->unattached_section_list_.begin();
2879 p != this->unattached_section_list_.end();
2880 ++p)
2882 if (!(*p)->has_out_shndx())
2884 (*p)->set_out_shndx(shndx);
2885 ++shndx;
2888 return shndx;
2891 // Set the section addresses according to the linker script. This is
2892 // only called when we see a SECTIONS clause. This returns the
2893 // program segment which should hold the file header and segment
2894 // headers, if any. It will return NULL if they should not be in a
2895 // segment.
2897 Output_segment*
2898 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2900 Script_sections* ss = this->script_options_->script_sections();
2901 gold_assert(ss->saw_sections_clause());
2902 return this->script_options_->set_section_addresses(symtab, this);
2905 // Place the orphan sections in the linker script.
2907 void
2908 Layout::place_orphan_sections_in_script()
2910 Script_sections* ss = this->script_options_->script_sections();
2911 gold_assert(ss->saw_sections_clause());
2913 // Place each orphaned output section in the script.
2914 for (Section_list::iterator p = this->section_list_.begin();
2915 p != this->section_list_.end();
2916 ++p)
2918 if (!(*p)->found_in_sections_clause())
2919 ss->place_orphan(*p);
2923 // Count the local symbols in the regular symbol table and the dynamic
2924 // symbol table, and build the respective string pools.
2926 void
2927 Layout::count_local_symbols(const Task* task,
2928 const Input_objects* input_objects)
2930 // First, figure out an upper bound on the number of symbols we'll
2931 // be inserting into each pool. This helps us create the pools with
2932 // the right size, to avoid unnecessary hashtable resizing.
2933 unsigned int symbol_count = 0;
2934 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2935 p != input_objects->relobj_end();
2936 ++p)
2937 symbol_count += (*p)->local_symbol_count();
2939 // Go from "upper bound" to "estimate." We overcount for two
2940 // reasons: we double-count symbols that occur in more than one
2941 // object file, and we count symbols that are dropped from the
2942 // output. Add it all together and assume we overcount by 100%.
2943 symbol_count /= 2;
2945 // We assume all symbols will go into both the sympool and dynpool.
2946 this->sympool_.reserve(symbol_count);
2947 this->dynpool_.reserve(symbol_count);
2949 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2950 p != input_objects->relobj_end();
2951 ++p)
2953 Task_lock_obj<Object> tlo(task, *p);
2954 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2958 // Create the symbol table sections. Here we also set the final
2959 // values of the symbols. At this point all the loadable sections are
2960 // fully laid out. SHNUM is the number of sections so far.
2962 void
2963 Layout::create_symtab_sections(const Input_objects* input_objects,
2964 Symbol_table* symtab,
2965 unsigned int shnum,
2966 off_t* poff)
2968 int symsize;
2969 unsigned int align;
2970 if (parameters->target().get_size() == 32)
2972 symsize = elfcpp::Elf_sizes<32>::sym_size;
2973 align = 4;
2975 else if (parameters->target().get_size() == 64)
2977 symsize = elfcpp::Elf_sizes<64>::sym_size;
2978 align = 8;
2980 else
2981 gold_unreachable();
2983 off_t off = *poff;
2984 off = align_address(off, align);
2985 off_t startoff = off;
2987 // Save space for the dummy symbol at the start of the section. We
2988 // never bother to write this out--it will just be left as zero.
2989 off += symsize;
2990 unsigned int local_symbol_index = 1;
2992 // Add STT_SECTION symbols for each Output section which needs one.
2993 for (Section_list::iterator p = this->section_list_.begin();
2994 p != this->section_list_.end();
2995 ++p)
2997 if (!(*p)->needs_symtab_index())
2998 (*p)->set_symtab_index(-1U);
2999 else
3001 (*p)->set_symtab_index(local_symbol_index);
3002 ++local_symbol_index;
3003 off += symsize;
3007 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3008 p != input_objects->relobj_end();
3009 ++p)
3011 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
3012 off, symtab);
3013 off += (index - local_symbol_index) * symsize;
3014 local_symbol_index = index;
3017 unsigned int local_symcount = local_symbol_index;
3018 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
3020 off_t dynoff;
3021 size_t dyn_global_index;
3022 size_t dyncount;
3023 if (this->dynsym_section_ == NULL)
3025 dynoff = 0;
3026 dyn_global_index = 0;
3027 dyncount = 0;
3029 else
3031 dyn_global_index = this->dynsym_section_->info();
3032 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
3033 dynoff = this->dynsym_section_->offset() + locsize;
3034 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
3035 gold_assert(static_cast<off_t>(dyncount * symsize)
3036 == this->dynsym_section_->data_size() - locsize);
3039 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
3040 &this->sympool_, &local_symcount);
3042 if (!parameters->options().strip_all())
3044 this->sympool_.set_string_offsets();
3046 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
3047 Output_section* osymtab = this->make_output_section(symtab_name,
3048 elfcpp::SHT_SYMTAB,
3049 0, ORDER_INVALID,
3050 false);
3051 this->symtab_section_ = osymtab;
3053 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
3054 align,
3055 "** symtab");
3056 osymtab->add_output_section_data(pos);
3058 // We generate a .symtab_shndx section if we have more than
3059 // SHN_LORESERVE sections. Technically it is possible that we
3060 // don't need one, because it is possible that there are no
3061 // symbols in any of sections with indexes larger than
3062 // SHN_LORESERVE. That is probably unusual, though, and it is
3063 // easier to always create one than to compute section indexes
3064 // twice (once here, once when writing out the symbols).
3065 if (shnum >= elfcpp::SHN_LORESERVE)
3067 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
3068 false, NULL);
3069 Output_section* osymtab_xindex =
3070 this->make_output_section(symtab_xindex_name,
3071 elfcpp::SHT_SYMTAB_SHNDX, 0,
3072 ORDER_INVALID, false);
3074 size_t symcount = (off - startoff) / symsize;
3075 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
3077 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
3079 osymtab_xindex->set_link_section(osymtab);
3080 osymtab_xindex->set_addralign(4);
3081 osymtab_xindex->set_entsize(4);
3083 osymtab_xindex->set_after_input_sections();
3085 // This tells the driver code to wait until the symbol table
3086 // has written out before writing out the postprocessing
3087 // sections, including the .symtab_shndx section.
3088 this->any_postprocessing_sections_ = true;
3091 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
3092 Output_section* ostrtab = this->make_output_section(strtab_name,
3093 elfcpp::SHT_STRTAB,
3094 0, ORDER_INVALID,
3095 false);
3097 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
3098 ostrtab->add_output_section_data(pstr);
3100 osymtab->set_file_offset(startoff);
3101 osymtab->finalize_data_size();
3102 osymtab->set_link_section(ostrtab);
3103 osymtab->set_info(local_symcount);
3104 osymtab->set_entsize(symsize);
3106 *poff = off;
3110 // Create the .shstrtab section, which holds the names of the
3111 // sections. At the time this is called, we have created all the
3112 // output sections except .shstrtab itself.
3114 Output_section*
3115 Layout::create_shstrtab()
3117 // FIXME: We don't need to create a .shstrtab section if we are
3118 // stripping everything.
3120 const char* name = this->namepool_.add(".shstrtab", false, NULL);
3122 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
3123 ORDER_INVALID, false);
3125 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
3127 // We can't write out this section until we've set all the
3128 // section names, and we don't set the names of compressed
3129 // output sections until relocations are complete. FIXME: With
3130 // the current names we use, this is unnecessary.
3131 os->set_after_input_sections();
3134 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
3135 os->add_output_section_data(posd);
3137 return os;
3140 // Create the section headers. SIZE is 32 or 64. OFF is the file
3141 // offset.
3143 void
3144 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
3146 Output_section_headers* oshdrs;
3147 oshdrs = new Output_section_headers(this,
3148 &this->segment_list_,
3149 &this->section_list_,
3150 &this->unattached_section_list_,
3151 &this->namepool_,
3152 shstrtab_section);
3153 off_t off = align_address(*poff, oshdrs->addralign());
3154 oshdrs->set_address_and_file_offset(0, off);
3155 off += oshdrs->data_size();
3156 *poff = off;
3157 this->section_headers_ = oshdrs;
3160 // Count the allocated sections.
3162 size_t
3163 Layout::allocated_output_section_count() const
3165 size_t section_count = 0;
3166 for (Segment_list::const_iterator p = this->segment_list_.begin();
3167 p != this->segment_list_.end();
3168 ++p)
3169 section_count += (*p)->output_section_count();
3170 return section_count;
3173 // Create the dynamic symbol table.
3175 void
3176 Layout::create_dynamic_symtab(const Input_objects* input_objects,
3177 Symbol_table* symtab,
3178 Output_section** pdynstr,
3179 unsigned int* plocal_dynamic_count,
3180 std::vector<Symbol*>* pdynamic_symbols,
3181 Versions* pversions)
3183 // Count all the symbols in the dynamic symbol table, and set the
3184 // dynamic symbol indexes.
3186 // Skip symbol 0, which is always all zeroes.
3187 unsigned int index = 1;
3189 // Add STT_SECTION symbols for each Output section which needs one.
3190 for (Section_list::iterator p = this->section_list_.begin();
3191 p != this->section_list_.end();
3192 ++p)
3194 if (!(*p)->needs_dynsym_index())
3195 (*p)->set_dynsym_index(-1U);
3196 else
3198 (*p)->set_dynsym_index(index);
3199 ++index;
3203 // Count the local symbols that need to go in the dynamic symbol table,
3204 // and set the dynamic symbol indexes.
3205 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3206 p != input_objects->relobj_end();
3207 ++p)
3209 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
3210 index = new_index;
3213 unsigned int local_symcount = index;
3214 *plocal_dynamic_count = local_symcount;
3216 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
3217 &this->dynpool_, pversions);
3219 int symsize;
3220 unsigned int align;
3221 const int size = parameters->target().get_size();
3222 if (size == 32)
3224 symsize = elfcpp::Elf_sizes<32>::sym_size;
3225 align = 4;
3227 else if (size == 64)
3229 symsize = elfcpp::Elf_sizes<64>::sym_size;
3230 align = 8;
3232 else
3233 gold_unreachable();
3235 // Create the dynamic symbol table section.
3237 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
3238 elfcpp::SHT_DYNSYM,
3239 elfcpp::SHF_ALLOC,
3240 false,
3241 ORDER_DYNAMIC_LINKER,
3242 false);
3244 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
3245 align,
3246 "** dynsym");
3247 dynsym->add_output_section_data(odata);
3249 dynsym->set_info(local_symcount);
3250 dynsym->set_entsize(symsize);
3251 dynsym->set_addralign(align);
3253 this->dynsym_section_ = dynsym;
3255 Output_data_dynamic* const odyn = this->dynamic_data_;
3256 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
3257 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
3259 // If there are more than SHN_LORESERVE allocated sections, we
3260 // create a .dynsym_shndx section. It is possible that we don't
3261 // need one, because it is possible that there are no dynamic
3262 // symbols in any of the sections with indexes larger than
3263 // SHN_LORESERVE. This is probably unusual, though, and at this
3264 // time we don't know the actual section indexes so it is
3265 // inconvenient to check.
3266 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
3268 Output_section* dynsym_xindex =
3269 this->choose_output_section(NULL, ".dynsym_shndx",
3270 elfcpp::SHT_SYMTAB_SHNDX,
3271 elfcpp::SHF_ALLOC,
3272 false, ORDER_DYNAMIC_LINKER, false);
3274 this->dynsym_xindex_ = new Output_symtab_xindex(index);
3276 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
3278 dynsym_xindex->set_link_section(dynsym);
3279 dynsym_xindex->set_addralign(4);
3280 dynsym_xindex->set_entsize(4);
3282 dynsym_xindex->set_after_input_sections();
3284 // This tells the driver code to wait until the symbol table has
3285 // written out before writing out the postprocessing sections,
3286 // including the .dynsym_shndx section.
3287 this->any_postprocessing_sections_ = true;
3290 // Create the dynamic string table section.
3292 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
3293 elfcpp::SHT_STRTAB,
3294 elfcpp::SHF_ALLOC,
3295 false,
3296 ORDER_DYNAMIC_LINKER,
3297 false);
3299 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
3300 dynstr->add_output_section_data(strdata);
3302 dynsym->set_link_section(dynstr);
3303 this->dynamic_section_->set_link_section(dynstr);
3305 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
3306 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
3308 *pdynstr = dynstr;
3310 // Create the hash tables.
3312 if (strcmp(parameters->options().hash_style(), "sysv") == 0
3313 || strcmp(parameters->options().hash_style(), "both") == 0)
3315 unsigned char* phash;
3316 unsigned int hashlen;
3317 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
3318 &phash, &hashlen);
3320 Output_section* hashsec =
3321 this->choose_output_section(NULL, ".hash", elfcpp::SHT_HASH,
3322 elfcpp::SHF_ALLOC, false,
3323 ORDER_DYNAMIC_LINKER, false);
3325 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3326 hashlen,
3327 align,
3328 "** hash");
3329 hashsec->add_output_section_data(hashdata);
3331 hashsec->set_link_section(dynsym);
3332 hashsec->set_entsize(4);
3334 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
3337 if (strcmp(parameters->options().hash_style(), "gnu") == 0
3338 || strcmp(parameters->options().hash_style(), "both") == 0)
3340 unsigned char* phash;
3341 unsigned int hashlen;
3342 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
3343 &phash, &hashlen);
3345 Output_section* hashsec =
3346 this->choose_output_section(NULL, ".gnu.hash", elfcpp::SHT_GNU_HASH,
3347 elfcpp::SHF_ALLOC, false,
3348 ORDER_DYNAMIC_LINKER, false);
3350 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3351 hashlen,
3352 align,
3353 "** hash");
3354 hashsec->add_output_section_data(hashdata);
3356 hashsec->set_link_section(dynsym);
3358 // For a 64-bit target, the entries in .gnu.hash do not have a
3359 // uniform size, so we only set the entry size for a 32-bit
3360 // target.
3361 if (parameters->target().get_size() == 32)
3362 hashsec->set_entsize(4);
3364 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
3368 // Assign offsets to each local portion of the dynamic symbol table.
3370 void
3371 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
3373 Output_section* dynsym = this->dynsym_section_;
3374 gold_assert(dynsym != NULL);
3376 off_t off = dynsym->offset();
3378 // Skip the dummy symbol at the start of the section.
3379 off += dynsym->entsize();
3381 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3382 p != input_objects->relobj_end();
3383 ++p)
3385 unsigned int count = (*p)->set_local_dynsym_offset(off);
3386 off += count * dynsym->entsize();
3390 // Create the version sections.
3392 void
3393 Layout::create_version_sections(const Versions* versions,
3394 const Symbol_table* symtab,
3395 unsigned int local_symcount,
3396 const std::vector<Symbol*>& dynamic_symbols,
3397 const Output_section* dynstr)
3399 if (!versions->any_defs() && !versions->any_needs())
3400 return;
3402 switch (parameters->size_and_endianness())
3404 #ifdef HAVE_TARGET_32_LITTLE
3405 case Parameters::TARGET_32_LITTLE:
3406 this->sized_create_version_sections<32, false>(versions, symtab,
3407 local_symcount,
3408 dynamic_symbols, dynstr);
3409 break;
3410 #endif
3411 #ifdef HAVE_TARGET_32_BIG
3412 case Parameters::TARGET_32_BIG:
3413 this->sized_create_version_sections<32, true>(versions, symtab,
3414 local_symcount,
3415 dynamic_symbols, dynstr);
3416 break;
3417 #endif
3418 #ifdef HAVE_TARGET_64_LITTLE
3419 case Parameters::TARGET_64_LITTLE:
3420 this->sized_create_version_sections<64, false>(versions, symtab,
3421 local_symcount,
3422 dynamic_symbols, dynstr);
3423 break;
3424 #endif
3425 #ifdef HAVE_TARGET_64_BIG
3426 case Parameters::TARGET_64_BIG:
3427 this->sized_create_version_sections<64, true>(versions, symtab,
3428 local_symcount,
3429 dynamic_symbols, dynstr);
3430 break;
3431 #endif
3432 default:
3433 gold_unreachable();
3437 // Create the version sections, sized version.
3439 template<int size, bool big_endian>
3440 void
3441 Layout::sized_create_version_sections(
3442 const Versions* versions,
3443 const Symbol_table* symtab,
3444 unsigned int local_symcount,
3445 const std::vector<Symbol*>& dynamic_symbols,
3446 const Output_section* dynstr)
3448 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3449 elfcpp::SHT_GNU_versym,
3450 elfcpp::SHF_ALLOC,
3451 false,
3452 ORDER_DYNAMIC_LINKER,
3453 false);
3455 unsigned char* vbuf;
3456 unsigned int vsize;
3457 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3458 local_symcount,
3459 dynamic_symbols,
3460 &vbuf, &vsize);
3462 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3463 "** versions");
3465 vsec->add_output_section_data(vdata);
3466 vsec->set_entsize(2);
3467 vsec->set_link_section(this->dynsym_section_);
3469 Output_data_dynamic* const odyn = this->dynamic_data_;
3470 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3472 if (versions->any_defs())
3474 Output_section* vdsec;
3475 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3476 elfcpp::SHT_GNU_verdef,
3477 elfcpp::SHF_ALLOC,
3478 false, ORDER_DYNAMIC_LINKER, false);
3480 unsigned char* vdbuf;
3481 unsigned int vdsize;
3482 unsigned int vdentries;
3483 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3484 &vdsize, &vdentries);
3486 Output_section_data* vddata =
3487 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3489 vdsec->add_output_section_data(vddata);
3490 vdsec->set_link_section(dynstr);
3491 vdsec->set_info(vdentries);
3493 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3494 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3497 if (versions->any_needs())
3499 Output_section* vnsec;
3500 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3501 elfcpp::SHT_GNU_verneed,
3502 elfcpp::SHF_ALLOC,
3503 false, ORDER_DYNAMIC_LINKER, false);
3505 unsigned char* vnbuf;
3506 unsigned int vnsize;
3507 unsigned int vnentries;
3508 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3509 &vnbuf, &vnsize,
3510 &vnentries);
3512 Output_section_data* vndata =
3513 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3515 vnsec->add_output_section_data(vndata);
3516 vnsec->set_link_section(dynstr);
3517 vnsec->set_info(vnentries);
3519 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3520 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3524 // Create the .interp section and PT_INTERP segment.
3526 void
3527 Layout::create_interp(const Target* target)
3529 const char* interp = parameters->options().dynamic_linker();
3530 if (interp == NULL)
3532 interp = target->dynamic_linker();
3533 gold_assert(interp != NULL);
3536 size_t len = strlen(interp) + 1;
3538 Output_section_data* odata = new Output_data_const(interp, len, 1);
3540 Output_section* osec = this->choose_output_section(NULL, ".interp",
3541 elfcpp::SHT_PROGBITS,
3542 elfcpp::SHF_ALLOC,
3543 false, ORDER_INTERP,
3544 false);
3545 osec->add_output_section_data(odata);
3547 if (!this->script_options_->saw_phdrs_clause())
3549 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3550 elfcpp::PF_R);
3551 oseg->add_output_section_to_nonload(osec, elfcpp::PF_R);
3555 // Add dynamic tags for the PLT and the dynamic relocs. This is
3556 // called by the target-specific code. This does nothing if not doing
3557 // a dynamic link.
3559 // USE_REL is true for REL relocs rather than RELA relocs.
3561 // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
3563 // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
3564 // and we also set DT_PLTREL. We use PLT_REL's output section, since
3565 // some targets have multiple reloc sections in PLT_REL.
3567 // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
3568 // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT.
3570 // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
3571 // executable.
3573 void
3574 Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
3575 const Output_data* plt_rel,
3576 const Output_data_reloc_generic* dyn_rel,
3577 bool add_debug, bool dynrel_includes_plt)
3579 Output_data_dynamic* odyn = this->dynamic_data_;
3580 if (odyn == NULL)
3581 return;
3583 if (plt_got != NULL && plt_got->output_section() != NULL)
3584 odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
3586 if (plt_rel != NULL && plt_rel->output_section() != NULL)
3588 odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
3589 odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
3590 odyn->add_constant(elfcpp::DT_PLTREL,
3591 use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
3594 if (dyn_rel != NULL && dyn_rel->output_section() != NULL)
3596 odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
3597 dyn_rel);
3598 if (plt_rel != NULL && dynrel_includes_plt)
3599 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3600 dyn_rel, plt_rel);
3601 else
3602 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3603 dyn_rel);
3604 const int size = parameters->target().get_size();
3605 elfcpp::DT rel_tag;
3606 int rel_size;
3607 if (use_rel)
3609 rel_tag = elfcpp::DT_RELENT;
3610 if (size == 32)
3611 rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
3612 else if (size == 64)
3613 rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
3614 else
3615 gold_unreachable();
3617 else
3619 rel_tag = elfcpp::DT_RELAENT;
3620 if (size == 32)
3621 rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
3622 else if (size == 64)
3623 rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
3624 else
3625 gold_unreachable();
3627 odyn->add_constant(rel_tag, rel_size);
3629 if (parameters->options().combreloc())
3631 size_t c = dyn_rel->relative_reloc_count();
3632 if (c > 0)
3633 odyn->add_constant((use_rel
3634 ? elfcpp::DT_RELCOUNT
3635 : elfcpp::DT_RELACOUNT),
3640 if (add_debug && !parameters->options().shared())
3642 // The value of the DT_DEBUG tag is filled in by the dynamic
3643 // linker at run time, and used by the debugger.
3644 odyn->add_constant(elfcpp::DT_DEBUG, 0);
3648 // Finish the .dynamic section and PT_DYNAMIC segment.
3650 void
3651 Layout::finish_dynamic_section(const Input_objects* input_objects,
3652 const Symbol_table* symtab)
3654 if (!this->script_options_->saw_phdrs_clause())
3656 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3657 (elfcpp::PF_R
3658 | elfcpp::PF_W));
3659 oseg->add_output_section_to_nonload(this->dynamic_section_,
3660 elfcpp::PF_R | elfcpp::PF_W);
3663 Output_data_dynamic* const odyn = this->dynamic_data_;
3665 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3666 p != input_objects->dynobj_end();
3667 ++p)
3669 if (!(*p)->is_needed()
3670 && (*p)->input_file()->options().as_needed())
3672 // This dynamic object was linked with --as-needed, but it
3673 // is not needed.
3674 continue;
3677 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3680 if (parameters->options().shared())
3682 const char* soname = parameters->options().soname();
3683 if (soname != NULL)
3684 odyn->add_string(elfcpp::DT_SONAME, soname);
3687 Symbol* sym = symtab->lookup(parameters->options().init());
3688 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3689 odyn->add_symbol(elfcpp::DT_INIT, sym);
3691 sym = symtab->lookup(parameters->options().fini());
3692 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3693 odyn->add_symbol(elfcpp::DT_FINI, sym);
3695 // Look for .init_array, .preinit_array and .fini_array by checking
3696 // section types.
3697 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3698 p != this->section_list_.end();
3699 ++p)
3700 switch((*p)->type())
3702 case elfcpp::SHT_FINI_ARRAY:
3703 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3704 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3705 break;
3706 case elfcpp::SHT_INIT_ARRAY:
3707 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3708 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3709 break;
3710 case elfcpp::SHT_PREINIT_ARRAY:
3711 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3712 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3713 break;
3714 default:
3715 break;
3718 // Add a DT_RPATH entry if needed.
3719 const General_options::Dir_list& rpath(parameters->options().rpath());
3720 if (!rpath.empty())
3722 std::string rpath_val;
3723 for (General_options::Dir_list::const_iterator p = rpath.begin();
3724 p != rpath.end();
3725 ++p)
3727 if (rpath_val.empty())
3728 rpath_val = p->name();
3729 else
3731 // Eliminate duplicates.
3732 General_options::Dir_list::const_iterator q;
3733 for (q = rpath.begin(); q != p; ++q)
3734 if (q->name() == p->name())
3735 break;
3736 if (q == p)
3738 rpath_val += ':';
3739 rpath_val += p->name();
3744 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3745 if (parameters->options().enable_new_dtags())
3746 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3749 // Look for text segments that have dynamic relocations.
3750 bool have_textrel = false;
3751 if (!this->script_options_->saw_sections_clause())
3753 for (Segment_list::const_iterator p = this->segment_list_.begin();
3754 p != this->segment_list_.end();
3755 ++p)
3757 if (((*p)->flags() & elfcpp::PF_W) == 0
3758 && (*p)->has_dynamic_reloc())
3760 have_textrel = true;
3761 break;
3765 else
3767 // We don't know the section -> segment mapping, so we are
3768 // conservative and just look for readonly sections with
3769 // relocations. If those sections wind up in writable segments,
3770 // then we have created an unnecessary DT_TEXTREL entry.
3771 for (Section_list::const_iterator p = this->section_list_.begin();
3772 p != this->section_list_.end();
3773 ++p)
3775 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3776 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3777 && ((*p)->has_dynamic_reloc()))
3779 have_textrel = true;
3780 break;
3785 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3786 // post-link tools can easily modify these flags if desired.
3787 unsigned int flags = 0;
3788 if (have_textrel)
3790 // Add a DT_TEXTREL for compatibility with older loaders.
3791 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3792 flags |= elfcpp::DF_TEXTREL;
3794 if (parameters->options().text())
3795 gold_error(_("read-only segment has dynamic relocations"));
3796 else if (parameters->options().warn_shared_textrel()
3797 && parameters->options().shared())
3798 gold_warning(_("shared library text segment is not shareable"));
3800 if (parameters->options().shared() && this->has_static_tls())
3801 flags |= elfcpp::DF_STATIC_TLS;
3802 if (parameters->options().origin())
3803 flags |= elfcpp::DF_ORIGIN;
3804 if (parameters->options().Bsymbolic())
3806 flags |= elfcpp::DF_SYMBOLIC;
3807 // Add DT_SYMBOLIC for compatibility with older loaders.
3808 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3810 if (parameters->options().now())
3811 flags |= elfcpp::DF_BIND_NOW;
3812 odyn->add_constant(elfcpp::DT_FLAGS, flags);
3814 flags = 0;
3815 if (parameters->options().initfirst())
3816 flags |= elfcpp::DF_1_INITFIRST;
3817 if (parameters->options().interpose())
3818 flags |= elfcpp::DF_1_INTERPOSE;
3819 if (parameters->options().loadfltr())
3820 flags |= elfcpp::DF_1_LOADFLTR;
3821 if (parameters->options().nodefaultlib())
3822 flags |= elfcpp::DF_1_NODEFLIB;
3823 if (parameters->options().nodelete())
3824 flags |= elfcpp::DF_1_NODELETE;
3825 if (parameters->options().nodlopen())
3826 flags |= elfcpp::DF_1_NOOPEN;
3827 if (parameters->options().nodump())
3828 flags |= elfcpp::DF_1_NODUMP;
3829 if (!parameters->options().shared())
3830 flags &= ~(elfcpp::DF_1_INITFIRST
3831 | elfcpp::DF_1_NODELETE
3832 | elfcpp::DF_1_NOOPEN);
3833 if (parameters->options().origin())
3834 flags |= elfcpp::DF_1_ORIGIN;
3835 if (parameters->options().now())
3836 flags |= elfcpp::DF_1_NOW;
3837 if (flags)
3838 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3841 // Set the size of the _DYNAMIC symbol table to be the size of the
3842 // dynamic data.
3844 void
3845 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
3847 Output_data_dynamic* const odyn = this->dynamic_data_;
3848 odyn->finalize_data_size();
3849 off_t data_size = odyn->data_size();
3850 const int size = parameters->target().get_size();
3851 if (size == 32)
3852 symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
3853 else if (size == 64)
3854 symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
3855 else
3856 gold_unreachable();
3859 // The mapping of input section name prefixes to output section names.
3860 // In some cases one prefix is itself a prefix of another prefix; in
3861 // such a case the longer prefix must come first. These prefixes are
3862 // based on the GNU linker default ELF linker script.
3864 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3865 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3867 MAPPING_INIT(".text.", ".text"),
3868 MAPPING_INIT(".ctors.", ".ctors"),
3869 MAPPING_INIT(".dtors.", ".dtors"),
3870 MAPPING_INIT(".rodata.", ".rodata"),
3871 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3872 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3873 MAPPING_INIT(".data.", ".data"),
3874 MAPPING_INIT(".bss.", ".bss"),
3875 MAPPING_INIT(".tdata.", ".tdata"),
3876 MAPPING_INIT(".tbss.", ".tbss"),
3877 MAPPING_INIT(".init_array.", ".init_array"),
3878 MAPPING_INIT(".fini_array.", ".fini_array"),
3879 MAPPING_INIT(".sdata.", ".sdata"),
3880 MAPPING_INIT(".sbss.", ".sbss"),
3881 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3882 // differently depending on whether it is creating a shared library.
3883 MAPPING_INIT(".sdata2.", ".sdata"),
3884 MAPPING_INIT(".sbss2.", ".sbss"),
3885 MAPPING_INIT(".lrodata.", ".lrodata"),
3886 MAPPING_INIT(".ldata.", ".ldata"),
3887 MAPPING_INIT(".lbss.", ".lbss"),
3888 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3889 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3890 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3891 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3892 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3893 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3894 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3895 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3896 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3897 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3898 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3899 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3900 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3901 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3902 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3903 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3904 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3905 MAPPING_INIT(".ARM.extab", ".ARM.extab"),
3906 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3907 MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
3908 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3910 #undef MAPPING_INIT
3912 const int Layout::section_name_mapping_count =
3913 (sizeof(Layout::section_name_mapping)
3914 / sizeof(Layout::section_name_mapping[0]));
3916 // Choose the output section name to use given an input section name.
3917 // Set *PLEN to the length of the name. *PLEN is initialized to the
3918 // length of NAME.
3920 const char*
3921 Layout::output_section_name(const char* name, size_t* plen)
3923 // gcc 4.3 generates the following sorts of section names when it
3924 // needs a section name specific to a function:
3925 // .text.FN
3926 // .rodata.FN
3927 // .sdata2.FN
3928 // .data.FN
3929 // .data.rel.FN
3930 // .data.rel.local.FN
3931 // .data.rel.ro.FN
3932 // .data.rel.ro.local.FN
3933 // .sdata.FN
3934 // .bss.FN
3935 // .sbss.FN
3936 // .tdata.FN
3937 // .tbss.FN
3939 // The GNU linker maps all of those to the part before the .FN,
3940 // except that .data.rel.local.FN is mapped to .data, and
3941 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3942 // beginning with .data.rel.ro.local are grouped together.
3944 // For an anonymous namespace, the string FN can contain a '.'.
3946 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3947 // GNU linker maps to .rodata.
3949 // The .data.rel.ro sections are used with -z relro. The sections
3950 // are recognized by name. We use the same names that the GNU
3951 // linker does for these sections.
3953 // It is hard to handle this in a principled way, so we don't even
3954 // try. We use a table of mappings. If the input section name is
3955 // not found in the table, we simply use it as the output section
3956 // name.
3958 const Section_name_mapping* psnm = section_name_mapping;
3959 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3961 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3963 *plen = psnm->tolen;
3964 return psnm->to;
3968 return name;
3971 // Check if a comdat group or .gnu.linkonce section with the given
3972 // NAME is selected for the link. If there is already a section,
3973 // *KEPT_SECTION is set to point to the existing section and the
3974 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3975 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3976 // *KEPT_SECTION is set to the internal copy and the function returns
3977 // true.
3979 bool
3980 Layout::find_or_add_kept_section(const std::string& name,
3981 Relobj* object,
3982 unsigned int shndx,
3983 bool is_comdat,
3984 bool is_group_name,
3985 Kept_section** kept_section)
3987 // It's normal to see a couple of entries here, for the x86 thunk
3988 // sections. If we see more than a few, we're linking a C++
3989 // program, and we resize to get more space to minimize rehashing.
3990 if (this->signatures_.size() > 4
3991 && !this->resized_signatures_)
3993 reserve_unordered_map(&this->signatures_,
3994 this->number_of_input_files_ * 64);
3995 this->resized_signatures_ = true;
3998 Kept_section candidate;
3999 std::pair<Signatures::iterator, bool> ins =
4000 this->signatures_.insert(std::make_pair(name, candidate));
4002 if (kept_section != NULL)
4003 *kept_section = &ins.first->second;
4004 if (ins.second)
4006 // This is the first time we've seen this signature.
4007 ins.first->second.set_object(object);
4008 ins.first->second.set_shndx(shndx);
4009 if (is_comdat)
4010 ins.first->second.set_is_comdat();
4011 if (is_group_name)
4012 ins.first->second.set_is_group_name();
4013 return true;
4016 // We have already seen this signature.
4018 if (ins.first->second.is_group_name())
4020 // We've already seen a real section group with this signature.
4021 // If the kept group is from a plugin object, and we're in the
4022 // replacement phase, accept the new one as a replacement.
4023 if (ins.first->second.object() == NULL
4024 && parameters->options().plugins()->in_replacement_phase())
4026 ins.first->second.set_object(object);
4027 ins.first->second.set_shndx(shndx);
4028 return true;
4030 return false;
4032 else if (is_group_name)
4034 // This is a real section group, and we've already seen a
4035 // linkonce section with this signature. Record that we've seen
4036 // a section group, and don't include this section group.
4037 ins.first->second.set_is_group_name();
4038 return false;
4040 else
4042 // We've already seen a linkonce section and this is a linkonce
4043 // section. These don't block each other--this may be the same
4044 // symbol name with different section types.
4045 return true;
4049 // Store the allocated sections into the section list.
4051 void
4052 Layout::get_allocated_sections(Section_list* section_list) const
4054 for (Section_list::const_iterator p = this->section_list_.begin();
4055 p != this->section_list_.end();
4056 ++p)
4057 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
4058 section_list->push_back(*p);
4061 // Create an output segment.
4063 Output_segment*
4064 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
4066 gold_assert(!parameters->options().relocatable());
4067 Output_segment* oseg = new Output_segment(type, flags);
4068 this->segment_list_.push_back(oseg);
4070 if (type == elfcpp::PT_TLS)
4071 this->tls_segment_ = oseg;
4072 else if (type == elfcpp::PT_GNU_RELRO)
4073 this->relro_segment_ = oseg;
4075 return oseg;
4078 // Write out the Output_sections. Most won't have anything to write,
4079 // since most of the data will come from input sections which are
4080 // handled elsewhere. But some Output_sections do have Output_data.
4082 void
4083 Layout::write_output_sections(Output_file* of) const
4085 for (Section_list::const_iterator p = this->section_list_.begin();
4086 p != this->section_list_.end();
4087 ++p)
4089 if (!(*p)->after_input_sections())
4090 (*p)->write(of);
4094 // Write out data not associated with a section or the symbol table.
4096 void
4097 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
4099 if (!parameters->options().strip_all())
4101 const Output_section* symtab_section = this->symtab_section_;
4102 for (Section_list::const_iterator p = this->section_list_.begin();
4103 p != this->section_list_.end();
4104 ++p)
4106 if ((*p)->needs_symtab_index())
4108 gold_assert(symtab_section != NULL);
4109 unsigned int index = (*p)->symtab_index();
4110 gold_assert(index > 0 && index != -1U);
4111 off_t off = (symtab_section->offset()
4112 + index * symtab_section->entsize());
4113 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
4118 const Output_section* dynsym_section = this->dynsym_section_;
4119 for (Section_list::const_iterator p = this->section_list_.begin();
4120 p != this->section_list_.end();
4121 ++p)
4123 if ((*p)->needs_dynsym_index())
4125 gold_assert(dynsym_section != NULL);
4126 unsigned int index = (*p)->dynsym_index();
4127 gold_assert(index > 0 && index != -1U);
4128 off_t off = (dynsym_section->offset()
4129 + index * dynsym_section->entsize());
4130 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
4134 // Write out the Output_data which are not in an Output_section.
4135 for (Data_list::const_iterator p = this->special_output_list_.begin();
4136 p != this->special_output_list_.end();
4137 ++p)
4138 (*p)->write(of);
4141 // Write out the Output_sections which can only be written after the
4142 // input sections are complete.
4144 void
4145 Layout::write_sections_after_input_sections(Output_file* of)
4147 // Determine the final section offsets, and thus the final output
4148 // file size. Note we finalize the .shstrab last, to allow the
4149 // after_input_section sections to modify their section-names before
4150 // writing.
4151 if (this->any_postprocessing_sections_)
4153 off_t off = this->output_file_size_;
4154 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
4156 // Now that we've finalized the names, we can finalize the shstrab.
4157 off =
4158 this->set_section_offsets(off,
4159 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
4161 if (off > this->output_file_size_)
4163 of->resize(off);
4164 this->output_file_size_ = off;
4168 for (Section_list::const_iterator p = this->section_list_.begin();
4169 p != this->section_list_.end();
4170 ++p)
4172 if ((*p)->after_input_sections())
4173 (*p)->write(of);
4176 this->section_headers_->write(of);
4179 // If the build ID requires computing a checksum, do so here, and
4180 // write it out. We compute a checksum over the entire file because
4181 // that is simplest.
4183 void
4184 Layout::write_build_id(Output_file* of) const
4186 if (this->build_id_note_ == NULL)
4187 return;
4189 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
4191 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
4192 this->build_id_note_->data_size());
4194 const char* style = parameters->options().build_id();
4195 if (strcmp(style, "sha1") == 0)
4197 sha1_ctx ctx;
4198 sha1_init_ctx(&ctx);
4199 sha1_process_bytes(iv, this->output_file_size_, &ctx);
4200 sha1_finish_ctx(&ctx, ov);
4202 else if (strcmp(style, "md5") == 0)
4204 md5_ctx ctx;
4205 md5_init_ctx(&ctx);
4206 md5_process_bytes(iv, this->output_file_size_, &ctx);
4207 md5_finish_ctx(&ctx, ov);
4209 else
4210 gold_unreachable();
4212 of->write_output_view(this->build_id_note_->offset(),
4213 this->build_id_note_->data_size(),
4214 ov);
4216 of->free_input_view(0, this->output_file_size_, iv);
4219 // Write out a binary file. This is called after the link is
4220 // complete. IN is the temporary output file we used to generate the
4221 // ELF code. We simply walk through the segments, read them from
4222 // their file offset in IN, and write them to their load address in
4223 // the output file. FIXME: with a bit more work, we could support
4224 // S-records and/or Intel hex format here.
4226 void
4227 Layout::write_binary(Output_file* in) const
4229 gold_assert(parameters->options().oformat_enum()
4230 == General_options::OBJECT_FORMAT_BINARY);
4232 // Get the size of the binary file.
4233 uint64_t max_load_address = 0;
4234 for (Segment_list::const_iterator p = this->segment_list_.begin();
4235 p != this->segment_list_.end();
4236 ++p)
4238 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4240 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
4241 if (max_paddr > max_load_address)
4242 max_load_address = max_paddr;
4246 Output_file out(parameters->options().output_file_name());
4247 out.open(max_load_address);
4249 for (Segment_list::const_iterator p = this->segment_list_.begin();
4250 p != this->segment_list_.end();
4251 ++p)
4253 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4255 const unsigned char* vin = in->get_input_view((*p)->offset(),
4256 (*p)->filesz());
4257 unsigned char* vout = out.get_output_view((*p)->paddr(),
4258 (*p)->filesz());
4259 memcpy(vout, vin, (*p)->filesz());
4260 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
4261 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
4265 out.close();
4268 // Print the output sections to the map file.
4270 void
4271 Layout::print_to_mapfile(Mapfile* mapfile) const
4273 for (Segment_list::const_iterator p = this->segment_list_.begin();
4274 p != this->segment_list_.end();
4275 ++p)
4276 (*p)->print_sections_to_mapfile(mapfile);
4279 // Print statistical information to stderr. This is used for --stats.
4281 void
4282 Layout::print_stats() const
4284 this->namepool_.print_stats("section name pool");
4285 this->sympool_.print_stats("output symbol name pool");
4286 this->dynpool_.print_stats("dynamic name pool");
4288 for (Section_list::const_iterator p = this->section_list_.begin();
4289 p != this->section_list_.end();
4290 ++p)
4291 (*p)->print_merge_stats();
4294 // Write_sections_task methods.
4296 // We can always run this task.
4298 Task_token*
4299 Write_sections_task::is_runnable()
4301 return NULL;
4304 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
4305 // when finished.
4307 void
4308 Write_sections_task::locks(Task_locker* tl)
4310 tl->add(this, this->output_sections_blocker_);
4311 tl->add(this, this->final_blocker_);
4314 // Run the task--write out the data.
4316 void
4317 Write_sections_task::run(Workqueue*)
4319 this->layout_->write_output_sections(this->of_);
4322 // Write_data_task methods.
4324 // We can always run this task.
4326 Task_token*
4327 Write_data_task::is_runnable()
4329 return NULL;
4332 // We need to unlock FINAL_BLOCKER when finished.
4334 void
4335 Write_data_task::locks(Task_locker* tl)
4337 tl->add(this, this->final_blocker_);
4340 // Run the task--write out the data.
4342 void
4343 Write_data_task::run(Workqueue*)
4345 this->layout_->write_data(this->symtab_, this->of_);
4348 // Write_symbols_task methods.
4350 // We can always run this task.
4352 Task_token*
4353 Write_symbols_task::is_runnable()
4355 return NULL;
4358 // We need to unlock FINAL_BLOCKER when finished.
4360 void
4361 Write_symbols_task::locks(Task_locker* tl)
4363 tl->add(this, this->final_blocker_);
4366 // Run the task--write out the symbols.
4368 void
4369 Write_symbols_task::run(Workqueue*)
4371 this->symtab_->write_globals(this->sympool_, this->dynpool_,
4372 this->layout_->symtab_xindex(),
4373 this->layout_->dynsym_xindex(), this->of_);
4376 // Write_after_input_sections_task methods.
4378 // We can only run this task after the input sections have completed.
4380 Task_token*
4381 Write_after_input_sections_task::is_runnable()
4383 if (this->input_sections_blocker_->is_blocked())
4384 return this->input_sections_blocker_;
4385 return NULL;
4388 // We need to unlock FINAL_BLOCKER when finished.
4390 void
4391 Write_after_input_sections_task::locks(Task_locker* tl)
4393 tl->add(this, this->final_blocker_);
4396 // Run the task.
4398 void
4399 Write_after_input_sections_task::run(Workqueue*)
4401 this->layout_->write_sections_after_input_sections(this->of_);
4404 // Close_task_runner methods.
4406 // Run the task--close the file.
4408 void
4409 Close_task_runner::run(Workqueue*, const Task*)
4411 // If we need to compute a checksum for the BUILD if, we do so here.
4412 this->layout_->write_build_id(this->of_);
4414 // If we've been asked to create a binary file, we do so here.
4415 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
4416 this->layout_->write_binary(this->of_);
4418 this->of_->close();
4421 // Instantiate the templates we need. We could use the configure
4422 // script to restrict this to only the ones for implemented targets.
4424 #ifdef HAVE_TARGET_32_LITTLE
4425 template
4426 Output_section*
4427 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
4428 const char* name,
4429 const elfcpp::Shdr<32, false>& shdr,
4430 unsigned int, unsigned int, off_t*);
4431 #endif
4433 #ifdef HAVE_TARGET_32_BIG
4434 template
4435 Output_section*
4436 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
4437 const char* name,
4438 const elfcpp::Shdr<32, true>& shdr,
4439 unsigned int, unsigned int, off_t*);
4440 #endif
4442 #ifdef HAVE_TARGET_64_LITTLE
4443 template
4444 Output_section*
4445 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
4446 const char* name,
4447 const elfcpp::Shdr<64, false>& shdr,
4448 unsigned int, unsigned int, off_t*);
4449 #endif
4451 #ifdef HAVE_TARGET_64_BIG
4452 template
4453 Output_section*
4454 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
4455 const char* name,
4456 const elfcpp::Shdr<64, true>& shdr,
4457 unsigned int, unsigned int, off_t*);
4458 #endif
4460 #ifdef HAVE_TARGET_32_LITTLE
4461 template
4462 Output_section*
4463 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
4464 unsigned int reloc_shndx,
4465 const elfcpp::Shdr<32, false>& shdr,
4466 Output_section* data_section,
4467 Relocatable_relocs* rr);
4468 #endif
4470 #ifdef HAVE_TARGET_32_BIG
4471 template
4472 Output_section*
4473 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
4474 unsigned int reloc_shndx,
4475 const elfcpp::Shdr<32, true>& shdr,
4476 Output_section* data_section,
4477 Relocatable_relocs* rr);
4478 #endif
4480 #ifdef HAVE_TARGET_64_LITTLE
4481 template
4482 Output_section*
4483 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
4484 unsigned int reloc_shndx,
4485 const elfcpp::Shdr<64, false>& shdr,
4486 Output_section* data_section,
4487 Relocatable_relocs* rr);
4488 #endif
4490 #ifdef HAVE_TARGET_64_BIG
4491 template
4492 Output_section*
4493 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
4494 unsigned int reloc_shndx,
4495 const elfcpp::Shdr<64, true>& shdr,
4496 Output_section* data_section,
4497 Relocatable_relocs* rr);
4498 #endif
4500 #ifdef HAVE_TARGET_32_LITTLE
4501 template
4502 void
4503 Layout::layout_group<32, false>(Symbol_table* symtab,
4504 Sized_relobj<32, false>* object,
4505 unsigned int,
4506 const char* group_section_name,
4507 const char* signature,
4508 const elfcpp::Shdr<32, false>& shdr,
4509 elfcpp::Elf_Word flags,
4510 std::vector<unsigned int>* shndxes);
4511 #endif
4513 #ifdef HAVE_TARGET_32_BIG
4514 template
4515 void
4516 Layout::layout_group<32, true>(Symbol_table* symtab,
4517 Sized_relobj<32, true>* object,
4518 unsigned int,
4519 const char* group_section_name,
4520 const char* signature,
4521 const elfcpp::Shdr<32, true>& shdr,
4522 elfcpp::Elf_Word flags,
4523 std::vector<unsigned int>* shndxes);
4524 #endif
4526 #ifdef HAVE_TARGET_64_LITTLE
4527 template
4528 void
4529 Layout::layout_group<64, false>(Symbol_table* symtab,
4530 Sized_relobj<64, false>* object,
4531 unsigned int,
4532 const char* group_section_name,
4533 const char* signature,
4534 const elfcpp::Shdr<64, false>& shdr,
4535 elfcpp::Elf_Word flags,
4536 std::vector<unsigned int>* shndxes);
4537 #endif
4539 #ifdef HAVE_TARGET_64_BIG
4540 template
4541 void
4542 Layout::layout_group<64, true>(Symbol_table* symtab,
4543 Sized_relobj<64, true>* object,
4544 unsigned int,
4545 const char* group_section_name,
4546 const char* signature,
4547 const elfcpp::Shdr<64, true>& shdr,
4548 elfcpp::Elf_Word flags,
4549 std::vector<unsigned int>* shndxes);
4550 #endif
4552 #ifdef HAVE_TARGET_32_LITTLE
4553 template
4554 Output_section*
4555 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
4556 const unsigned char* symbols,
4557 off_t symbols_size,
4558 const unsigned char* symbol_names,
4559 off_t symbol_names_size,
4560 unsigned int shndx,
4561 const elfcpp::Shdr<32, false>& shdr,
4562 unsigned int reloc_shndx,
4563 unsigned int reloc_type,
4564 off_t* off);
4565 #endif
4567 #ifdef HAVE_TARGET_32_BIG
4568 template
4569 Output_section*
4570 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4571 const unsigned char* symbols,
4572 off_t symbols_size,
4573 const unsigned char* symbol_names,
4574 off_t symbol_names_size,
4575 unsigned int shndx,
4576 const elfcpp::Shdr<32, true>& shdr,
4577 unsigned int reloc_shndx,
4578 unsigned int reloc_type,
4579 off_t* off);
4580 #endif
4582 #ifdef HAVE_TARGET_64_LITTLE
4583 template
4584 Output_section*
4585 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4586 const unsigned char* symbols,
4587 off_t symbols_size,
4588 const unsigned char* symbol_names,
4589 off_t symbol_names_size,
4590 unsigned int shndx,
4591 const elfcpp::Shdr<64, false>& shdr,
4592 unsigned int reloc_shndx,
4593 unsigned int reloc_type,
4594 off_t* off);
4595 #endif
4597 #ifdef HAVE_TARGET_64_BIG
4598 template
4599 Output_section*
4600 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4601 const unsigned char* symbols,
4602 off_t symbols_size,
4603 const unsigned char* symbol_names,
4604 off_t symbol_names_size,
4605 unsigned int shndx,
4606 const elfcpp::Shdr<64, true>& shdr,
4607 unsigned int reloc_shndx,
4608 unsigned int reloc_type,
4609 off_t* off);
4610 #endif
4612 } // End namespace gold.