2008-09-26 Kai Tietz <kai.tietz@onevision.com>
[binutils.git] / gold / layout.cc
blobec9654e0eefa97fd6a78d112e43dd451bfdb7076
1 // layout.cc -- lay out output file sections for gold
3 // Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
6 // This file is part of gold.
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
23 #include "gold.h"
25 #include <cerrno>
26 #include <cstring>
27 #include <algorithm>
28 #include <iostream>
29 #include <utility>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include "libiberty.h"
33 #include "md5.h"
34 #include "sha1.h"
36 #include "parameters.h"
37 #include "options.h"
38 #include "mapfile.h"
39 #include "script.h"
40 #include "script-sections.h"
41 #include "output.h"
42 #include "symtab.h"
43 #include "dynobj.h"
44 #include "ehframe.h"
45 #include "compressed_output.h"
46 #include "reduced_debug_output.h"
47 #include "reloc.h"
48 #include "descriptors.h"
49 #include "layout.h"
51 namespace gold
54 // Layout_task_runner methods.
56 // Lay out the sections. This is called after all the input objects
57 // have been read.
59 void
60 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
62 off_t file_size = this->layout_->finalize(this->input_objects_,
63 this->symtab_,
64 this->target_,
65 task);
67 // Now we know the final size of the output file and we know where
68 // each piece of information goes.
70 if (this->mapfile_ != NULL)
72 this->mapfile_->print_discarded_sections(this->input_objects_);
73 this->layout_->print_to_mapfile(this->mapfile_);
76 Output_file* of = new Output_file(parameters->options().output_file_name());
77 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
78 of->set_is_temporary();
79 of->open(file_size);
81 // Queue up the final set of tasks.
82 gold::queue_final_tasks(this->options_, this->input_objects_,
83 this->symtab_, this->layout_, workqueue, of);
86 // Layout methods.
88 Layout::Layout(const General_options& options, Script_options* script_options)
89 : options_(options),
90 script_options_(script_options),
91 namepool_(),
92 sympool_(),
93 dynpool_(),
94 signatures_(),
95 section_name_map_(),
96 segment_list_(),
97 section_list_(),
98 unattached_section_list_(),
99 sections_are_attached_(false),
100 special_output_list_(),
101 section_headers_(NULL),
102 tls_segment_(NULL),
103 relro_segment_(NULL),
104 symtab_section_(NULL),
105 symtab_xindex_(NULL),
106 dynsym_section_(NULL),
107 dynsym_xindex_(NULL),
108 dynamic_section_(NULL),
109 dynamic_data_(NULL),
110 eh_frame_section_(NULL),
111 eh_frame_data_(NULL),
112 added_eh_frame_data_(false),
113 eh_frame_hdr_section_(NULL),
114 build_id_note_(NULL),
115 debug_abbrev_(NULL),
116 debug_info_(NULL),
117 group_signatures_(),
118 output_file_size_(-1),
119 input_requires_executable_stack_(false),
120 input_with_gnu_stack_note_(false),
121 input_without_gnu_stack_note_(false),
122 has_static_tls_(false),
123 any_postprocessing_sections_(false)
125 // Make space for more than enough segments for a typical file.
126 // This is just for efficiency--it's OK if we wind up needing more.
127 this->segment_list_.reserve(12);
129 // We expect two unattached Output_data objects: the file header and
130 // the segment headers.
131 this->special_output_list_.reserve(2);
134 // Hash a key we use to look up an output section mapping.
136 size_t
137 Layout::Hash_key::operator()(const Layout::Key& k) const
139 return k.first + k.second.first + k.second.second;
142 // Return whether PREFIX is a prefix of STR.
144 static inline bool
145 is_prefix_of(const char* prefix, const char* str)
147 return strncmp(prefix, str, strlen(prefix)) == 0;
150 // Returns whether the given section is in the list of
151 // debug-sections-used-by-some-version-of-gdb. Currently,
152 // we've checked versions of gdb up to and including 6.7.1.
154 static const char* gdb_sections[] =
155 { ".debug_abbrev",
156 // ".debug_aranges", // not used by gdb as of 6.7.1
157 ".debug_frame",
158 ".debug_info",
159 ".debug_line",
160 ".debug_loc",
161 ".debug_macinfo",
162 // ".debug_pubnames", // not used by gdb as of 6.7.1
163 ".debug_ranges",
164 ".debug_str",
167 static const char* lines_only_debug_sections[] =
168 { ".debug_abbrev",
169 // ".debug_aranges", // not used by gdb as of 6.7.1
170 // ".debug_frame",
171 ".debug_info",
172 ".debug_line",
173 // ".debug_loc",
174 // ".debug_macinfo",
175 // ".debug_pubnames", // not used by gdb as of 6.7.1
176 // ".debug_ranges",
177 ".debug_str",
180 static inline bool
181 is_gdb_debug_section(const char* str)
183 // We can do this faster: binary search or a hashtable. But why bother?
184 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
185 if (strcmp(str, gdb_sections[i]) == 0)
186 return true;
187 return false;
190 static inline bool
191 is_lines_only_debug_section(const char* str)
193 // We can do this faster: binary search or a hashtable. But why bother?
194 for (size_t i = 0;
195 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
196 ++i)
197 if (strcmp(str, lines_only_debug_sections[i]) == 0)
198 return true;
199 return false;
202 // Whether to include this section in the link.
204 template<int size, bool big_endian>
205 bool
206 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
207 const elfcpp::Shdr<size, big_endian>& shdr)
209 switch (shdr.get_sh_type())
211 case elfcpp::SHT_NULL:
212 case elfcpp::SHT_SYMTAB:
213 case elfcpp::SHT_DYNSYM:
214 case elfcpp::SHT_HASH:
215 case elfcpp::SHT_DYNAMIC:
216 case elfcpp::SHT_SYMTAB_SHNDX:
217 return false;
219 case elfcpp::SHT_STRTAB:
220 // Discard the sections which have special meanings in the ELF
221 // ABI. Keep others (e.g., .stabstr). We could also do this by
222 // checking the sh_link fields of the appropriate sections.
223 return (strcmp(name, ".dynstr") != 0
224 && strcmp(name, ".strtab") != 0
225 && strcmp(name, ".shstrtab") != 0);
227 case elfcpp::SHT_RELA:
228 case elfcpp::SHT_REL:
229 case elfcpp::SHT_GROUP:
230 // If we are emitting relocations these should be handled
231 // elsewhere.
232 gold_assert(!parameters->options().relocatable()
233 && !parameters->options().emit_relocs());
234 return false;
236 case elfcpp::SHT_PROGBITS:
237 if (parameters->options().strip_debug()
238 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
240 if (is_debug_info_section(name))
241 return false;
243 if (parameters->options().strip_debug_non_line()
244 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
246 // Debugging sections can only be recognized by name.
247 if (is_prefix_of(".debug", name)
248 && !is_lines_only_debug_section(name))
249 return false;
251 if (parameters->options().strip_debug_gdb()
252 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
254 // Debugging sections can only be recognized by name.
255 if (is_prefix_of(".debug", name)
256 && !is_gdb_debug_section(name))
257 return false;
259 return true;
261 default:
262 return true;
266 // Return an output section named NAME, or NULL if there is none.
268 Output_section*
269 Layout::find_output_section(const char* name) const
271 for (Section_list::const_iterator p = this->section_list_.begin();
272 p != this->section_list_.end();
273 ++p)
274 if (strcmp((*p)->name(), name) == 0)
275 return *p;
276 return NULL;
279 // Return an output segment of type TYPE, with segment flags SET set
280 // and segment flags CLEAR clear. Return NULL if there is none.
282 Output_segment*
283 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
284 elfcpp::Elf_Word clear) const
286 for (Segment_list::const_iterator p = this->segment_list_.begin();
287 p != this->segment_list_.end();
288 ++p)
289 if (static_cast<elfcpp::PT>((*p)->type()) == type
290 && ((*p)->flags() & set) == set
291 && ((*p)->flags() & clear) == 0)
292 return *p;
293 return NULL;
296 // Return the output section to use for section NAME with type TYPE
297 // and section flags FLAGS. NAME must be canonicalized in the string
298 // pool, and NAME_KEY is the key.
300 Output_section*
301 Layout::get_output_section(const char* name, Stringpool::Key name_key,
302 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
304 elfcpp::Elf_Xword lookup_flags = flags;
306 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
307 // read-write with read-only sections. Some other ELF linkers do
308 // not do this. FIXME: Perhaps there should be an option
309 // controlling this.
310 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
312 const Key key(name_key, std::make_pair(type, lookup_flags));
313 const std::pair<Key, Output_section*> v(key, NULL);
314 std::pair<Section_name_map::iterator, bool> ins(
315 this->section_name_map_.insert(v));
317 if (!ins.second)
318 return ins.first->second;
319 else
321 // This is the first time we've seen this name/type/flags
322 // combination. For compatibility with the GNU linker, we
323 // combine sections with contents and zero flags with sections
324 // with non-zero flags. This is a workaround for cases where
325 // assembler code forgets to set section flags. FIXME: Perhaps
326 // there should be an option to control this.
327 Output_section* os = NULL;
329 if (type == elfcpp::SHT_PROGBITS)
331 if (flags == 0)
333 Output_section* same_name = this->find_output_section(name);
334 if (same_name != NULL
335 && same_name->type() == elfcpp::SHT_PROGBITS
336 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
337 os = same_name;
339 else if ((flags & elfcpp::SHF_TLS) == 0)
341 elfcpp::Elf_Xword zero_flags = 0;
342 const Key zero_key(name_key, std::make_pair(type, zero_flags));
343 Section_name_map::iterator p =
344 this->section_name_map_.find(zero_key);
345 if (p != this->section_name_map_.end())
346 os = p->second;
350 if (os == NULL)
351 os = this->make_output_section(name, type, flags);
352 ins.first->second = os;
353 return os;
357 // Pick the output section to use for section NAME, in input file
358 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
359 // linker created section. IS_INPUT_SECTION is true if we are
360 // choosing an output section for an input section found in a input
361 // file. This will return NULL if the input section should be
362 // discarded.
364 Output_section*
365 Layout::choose_output_section(const Relobj* relobj, const char* name,
366 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
367 bool is_input_section)
369 // We should not see any input sections after we have attached
370 // sections to segments.
371 gold_assert(!is_input_section || !this->sections_are_attached_);
373 // Some flags in the input section should not be automatically
374 // copied to the output section.
375 flags &= ~ (elfcpp::SHF_INFO_LINK
376 | elfcpp::SHF_LINK_ORDER
377 | elfcpp::SHF_GROUP
378 | elfcpp::SHF_MERGE
379 | elfcpp::SHF_STRINGS);
381 if (this->script_options_->saw_sections_clause())
383 // We are using a SECTIONS clause, so the output section is
384 // chosen based only on the name.
386 Script_sections* ss = this->script_options_->script_sections();
387 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
388 Output_section** output_section_slot;
389 name = ss->output_section_name(file_name, name, &output_section_slot);
390 if (name == NULL)
392 // The SECTIONS clause says to discard this input section.
393 return NULL;
396 // If this is an orphan section--one not mentioned in the linker
397 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
398 // default processing below.
400 if (output_section_slot != NULL)
402 if (*output_section_slot != NULL)
403 return *output_section_slot;
405 // We don't put sections found in the linker script into
406 // SECTION_NAME_MAP_. That keeps us from getting confused
407 // if an orphan section is mapped to a section with the same
408 // name as one in the linker script.
410 name = this->namepool_.add(name, false, NULL);
412 Output_section* os = this->make_output_section(name, type, flags);
413 os->set_found_in_sections_clause();
414 *output_section_slot = os;
415 return os;
419 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
421 // Turn NAME from the name of the input section into the name of the
422 // output section.
424 size_t len = strlen(name);
425 if (is_input_section && !parameters->options().relocatable())
426 name = Layout::output_section_name(name, &len);
428 Stringpool::Key name_key;
429 name = this->namepool_.add_with_length(name, len, true, &name_key);
431 // Find or make the output section. The output section is selected
432 // based on the section name, type, and flags.
433 return this->get_output_section(name, name_key, type, flags);
436 // Return the output section to use for input section SHNDX, with name
437 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
438 // index of a relocation section which applies to this section, or 0
439 // if none, or -1U if more than one. RELOC_TYPE is the type of the
440 // relocation section if there is one. Set *OFF to the offset of this
441 // input section without the output section. Return NULL if the
442 // section should be discarded. Set *OFF to -1 if the section
443 // contents should not be written directly to the output file, but
444 // will instead receive special handling.
446 template<int size, bool big_endian>
447 Output_section*
448 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
449 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
450 unsigned int reloc_shndx, unsigned int, off_t* off)
452 *off = 0;
454 if (!this->include_section(object, name, shdr))
455 return NULL;
457 Output_section* os;
459 // In a relocatable link a grouped section must not be combined with
460 // any other sections.
461 if (parameters->options().relocatable()
462 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
464 name = this->namepool_.add(name, true, NULL);
465 os = this->make_output_section(name, shdr.get_sh_type(),
466 shdr.get_sh_flags());
468 else
470 os = this->choose_output_section(object, name, shdr.get_sh_type(),
471 shdr.get_sh_flags(), true);
472 if (os == NULL)
473 return NULL;
476 // By default the GNU linker sorts input sections whose names match
477 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
478 // are sorted by name. This is used to implement constructor
479 // priority ordering. We are compatible.
480 if (!this->script_options_->saw_sections_clause()
481 && (is_prefix_of(".ctors.", name)
482 || is_prefix_of(".dtors.", name)
483 || is_prefix_of(".init_array.", name)
484 || is_prefix_of(".fini_array.", name)))
485 os->set_must_sort_attached_input_sections();
487 // FIXME: Handle SHF_LINK_ORDER somewhere.
489 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
490 this->script_options_->saw_sections_clause());
492 return os;
495 // Handle a relocation section when doing a relocatable link.
497 template<int size, bool big_endian>
498 Output_section*
499 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
500 unsigned int,
501 const elfcpp::Shdr<size, big_endian>& shdr,
502 Output_section* data_section,
503 Relocatable_relocs* rr)
505 gold_assert(parameters->options().relocatable()
506 || parameters->options().emit_relocs());
508 int sh_type = shdr.get_sh_type();
510 std::string name;
511 if (sh_type == elfcpp::SHT_REL)
512 name = ".rel";
513 else if (sh_type == elfcpp::SHT_RELA)
514 name = ".rela";
515 else
516 gold_unreachable();
517 name += data_section->name();
519 Output_section* os = this->choose_output_section(object, name.c_str(),
520 sh_type,
521 shdr.get_sh_flags(),
522 false);
524 os->set_should_link_to_symtab();
525 os->set_info_section(data_section);
527 Output_section_data* posd;
528 if (sh_type == elfcpp::SHT_REL)
530 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
531 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
532 size,
533 big_endian>(rr);
535 else if (sh_type == elfcpp::SHT_RELA)
537 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
538 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
539 size,
540 big_endian>(rr);
542 else
543 gold_unreachable();
545 os->add_output_section_data(posd);
546 rr->set_output_data(posd);
548 return os;
551 // Handle a group section when doing a relocatable link.
553 template<int size, bool big_endian>
554 void
555 Layout::layout_group(Symbol_table* symtab,
556 Sized_relobj<size, big_endian>* object,
557 unsigned int,
558 const char* group_section_name,
559 const char* signature,
560 const elfcpp::Shdr<size, big_endian>& shdr,
561 elfcpp::Elf_Word flags,
562 std::vector<unsigned int>* shndxes)
564 gold_assert(parameters->options().relocatable());
565 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
566 group_section_name = this->namepool_.add(group_section_name, true, NULL);
567 Output_section* os = this->make_output_section(group_section_name,
568 elfcpp::SHT_GROUP,
569 shdr.get_sh_flags());
571 // We need to find a symbol with the signature in the symbol table.
572 // If we don't find one now, we need to look again later.
573 Symbol* sym = symtab->lookup(signature, NULL);
574 if (sym != NULL)
575 os->set_info_symndx(sym);
576 else
578 // We will wind up using a symbol whose name is the signature.
579 // So just put the signature in the symbol name pool to save it.
580 signature = symtab->canonicalize_name(signature);
581 this->group_signatures_.push_back(Group_signature(os, signature));
584 os->set_should_link_to_symtab();
585 os->set_entsize(4);
587 section_size_type entry_count =
588 convert_to_section_size_type(shdr.get_sh_size() / 4);
589 Output_section_data* posd =
590 new Output_data_group<size, big_endian>(object, entry_count, flags,
591 shndxes);
592 os->add_output_section_data(posd);
595 // Special GNU handling of sections name .eh_frame. They will
596 // normally hold exception frame data as defined by the C++ ABI
597 // (http://codesourcery.com/cxx-abi/).
599 template<int size, bool big_endian>
600 Output_section*
601 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
602 const unsigned char* symbols,
603 off_t symbols_size,
604 const unsigned char* symbol_names,
605 off_t symbol_names_size,
606 unsigned int shndx,
607 const elfcpp::Shdr<size, big_endian>& shdr,
608 unsigned int reloc_shndx, unsigned int reloc_type,
609 off_t* off)
611 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
612 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
614 const char* const name = ".eh_frame";
615 Output_section* os = this->choose_output_section(object,
616 name,
617 elfcpp::SHT_PROGBITS,
618 elfcpp::SHF_ALLOC,
619 false);
620 if (os == NULL)
621 return NULL;
623 if (this->eh_frame_section_ == NULL)
625 this->eh_frame_section_ = os;
626 this->eh_frame_data_ = new Eh_frame();
628 if (this->options_.eh_frame_hdr())
630 Output_section* hdr_os =
631 this->choose_output_section(NULL,
632 ".eh_frame_hdr",
633 elfcpp::SHT_PROGBITS,
634 elfcpp::SHF_ALLOC,
635 false);
637 if (hdr_os != NULL)
639 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
640 this->eh_frame_data_);
641 hdr_os->add_output_section_data(hdr_posd);
643 hdr_os->set_after_input_sections();
645 if (!this->script_options_->saw_phdrs_clause())
647 Output_segment* hdr_oseg;
648 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
649 elfcpp::PF_R);
650 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
653 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
658 gold_assert(this->eh_frame_section_ == os);
660 if (this->eh_frame_data_->add_ehframe_input_section(object,
661 symbols,
662 symbols_size,
663 symbol_names,
664 symbol_names_size,
665 shndx,
666 reloc_shndx,
667 reloc_type))
669 os->update_flags_for_input_section(shdr.get_sh_flags());
671 // We found a .eh_frame section we are going to optimize, so now
672 // we can add the set of optimized sections to the output
673 // section. We need to postpone adding this until we've found a
674 // section we can optimize so that the .eh_frame section in
675 // crtbegin.o winds up at the start of the output section.
676 if (!this->added_eh_frame_data_)
678 os->add_output_section_data(this->eh_frame_data_);
679 this->added_eh_frame_data_ = true;
681 *off = -1;
683 else
685 // We couldn't handle this .eh_frame section for some reason.
686 // Add it as a normal section.
687 bool saw_sections_clause = this->script_options_->saw_sections_clause();
688 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
689 saw_sections_clause);
692 return os;
695 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
696 // the output section.
698 Output_section*
699 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
700 elfcpp::Elf_Xword flags,
701 Output_section_data* posd)
703 Output_section* os = this->choose_output_section(NULL, name, type, flags,
704 false);
705 if (os != NULL)
706 os->add_output_section_data(posd);
707 return os;
710 // Map section flags to segment flags.
712 elfcpp::Elf_Word
713 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
715 elfcpp::Elf_Word ret = elfcpp::PF_R;
716 if ((flags & elfcpp::SHF_WRITE) != 0)
717 ret |= elfcpp::PF_W;
718 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
719 ret |= elfcpp::PF_X;
720 return ret;
723 // Sometimes we compress sections. This is typically done for
724 // sections that are not part of normal program execution (such as
725 // .debug_* sections), and where the readers of these sections know
726 // how to deal with compressed sections. (To make it easier for them,
727 // we will rename the ouput section in such cases from .foo to
728 // .foo.zlib.nnnn, where nnnn is the uncompressed size.) This routine
729 // doesn't say for certain whether we'll compress -- it depends on
730 // commandline options as well -- just whether this section is a
731 // candidate for compression.
733 static bool
734 is_compressible_debug_section(const char* secname)
736 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
739 // Make a new Output_section, and attach it to segments as
740 // appropriate.
742 Output_section*
743 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
744 elfcpp::Elf_Xword flags)
746 Output_section* os;
747 if ((flags & elfcpp::SHF_ALLOC) == 0
748 && strcmp(this->options_.compress_debug_sections(), "none") != 0
749 && is_compressible_debug_section(name))
750 os = new Output_compressed_section(&this->options_, name, type, flags);
752 else if ((flags & elfcpp::SHF_ALLOC) == 0
753 && this->options_.strip_debug_non_line()
754 && strcmp(".debug_abbrev", name) == 0)
756 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
757 name, type, flags);
758 if (this->debug_info_)
759 this->debug_info_->set_abbreviations(this->debug_abbrev_);
761 else if ((flags & elfcpp::SHF_ALLOC) == 0
762 && this->options_.strip_debug_non_line()
763 && strcmp(".debug_info", name) == 0)
765 os = this->debug_info_ = new Output_reduced_debug_info_section(
766 name, type, flags);
767 if (this->debug_abbrev_)
768 this->debug_info_->set_abbreviations(this->debug_abbrev_);
770 else
771 os = new Output_section(name, type, flags);
773 this->section_list_.push_back(os);
775 // The GNU linker by default sorts some sections by priority, so we
776 // do the same. We need to know that this might happen before we
777 // attach any input sections.
778 if (!this->script_options_->saw_sections_clause()
779 && (strcmp(name, ".ctors") == 0
780 || strcmp(name, ".dtors") == 0
781 || strcmp(name, ".init_array") == 0
782 || strcmp(name, ".fini_array") == 0))
783 os->set_may_sort_attached_input_sections();
785 // With -z relro, we have to recognize the special sections by name.
786 // There is no other way.
787 if (!this->script_options_->saw_sections_clause()
788 && parameters->options().relro()
789 && type == elfcpp::SHT_PROGBITS
790 && (flags & elfcpp::SHF_ALLOC) != 0
791 && (flags & elfcpp::SHF_WRITE) != 0)
793 if (strcmp(name, ".data.rel.ro") == 0)
794 os->set_is_relro();
795 else if (strcmp(name, ".data.rel.ro.local") == 0)
797 os->set_is_relro();
798 os->set_is_relro_local();
802 // If we have already attached the sections to segments, then we
803 // need to attach this one now. This happens for sections created
804 // directly by the linker.
805 if (this->sections_are_attached_)
806 this->attach_section_to_segment(os);
808 return os;
811 // Attach output sections to segments. This is called after we have
812 // seen all the input sections.
814 void
815 Layout::attach_sections_to_segments()
817 for (Section_list::iterator p = this->section_list_.begin();
818 p != this->section_list_.end();
819 ++p)
820 this->attach_section_to_segment(*p);
822 this->sections_are_attached_ = true;
825 // Attach an output section to a segment.
827 void
828 Layout::attach_section_to_segment(Output_section* os)
830 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
831 this->unattached_section_list_.push_back(os);
832 else
833 this->attach_allocated_section_to_segment(os);
836 // Attach an allocated output section to a segment.
838 void
839 Layout::attach_allocated_section_to_segment(Output_section* os)
841 elfcpp::Elf_Xword flags = os->flags();
842 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
844 if (parameters->options().relocatable())
845 return;
847 // If we have a SECTIONS clause, we can't handle the attachment to
848 // segments until after we've seen all the sections.
849 if (this->script_options_->saw_sections_clause())
850 return;
852 gold_assert(!this->script_options_->saw_phdrs_clause());
854 // This output section goes into a PT_LOAD segment.
856 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
858 // In general the only thing we really care about for PT_LOAD
859 // segments is whether or not they are writable, so that is how we
860 // search for them. People who need segments sorted on some other
861 // basis will have to use a linker script.
863 Segment_list::const_iterator p;
864 for (p = this->segment_list_.begin();
865 p != this->segment_list_.end();
866 ++p)
868 if ((*p)->type() == elfcpp::PT_LOAD
869 && (parameters->options().omagic()
870 || ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W)))
872 // If -Tbss was specified, we need to separate the data
873 // and BSS segments.
874 if (this->options_.user_set_Tbss())
876 if ((os->type() == elfcpp::SHT_NOBITS)
877 == (*p)->has_any_data_sections())
878 continue;
881 (*p)->add_output_section(os, seg_flags);
882 break;
886 if (p == this->segment_list_.end())
888 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
889 seg_flags);
890 oseg->add_output_section(os, seg_flags);
893 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
894 // segment.
895 if (os->type() == elfcpp::SHT_NOTE)
897 // See if we already have an equivalent PT_NOTE segment.
898 for (p = this->segment_list_.begin();
899 p != segment_list_.end();
900 ++p)
902 if ((*p)->type() == elfcpp::PT_NOTE
903 && (((*p)->flags() & elfcpp::PF_W)
904 == (seg_flags & elfcpp::PF_W)))
906 (*p)->add_output_section(os, seg_flags);
907 break;
911 if (p == this->segment_list_.end())
913 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
914 seg_flags);
915 oseg->add_output_section(os, seg_flags);
919 // If we see a loadable SHF_TLS section, we create a PT_TLS
920 // segment. There can only be one such segment.
921 if ((flags & elfcpp::SHF_TLS) != 0)
923 if (this->tls_segment_ == NULL)
924 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
925 this->tls_segment_->add_output_section(os, seg_flags);
928 // If -z relro is in effect, and we see a relro section, we create a
929 // PT_GNU_RELRO segment. There can only be one such segment.
930 if (os->is_relro() && parameters->options().relro())
932 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
933 if (this->relro_segment_ == NULL)
934 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
935 this->relro_segment_->add_output_section(os, seg_flags);
939 // Make an output section for a script.
941 Output_section*
942 Layout::make_output_section_for_script(const char* name)
944 name = this->namepool_.add(name, false, NULL);
945 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
946 elfcpp::SHF_ALLOC);
947 os->set_found_in_sections_clause();
948 return os;
951 // Return the number of segments we expect to see.
953 size_t
954 Layout::expected_segment_count() const
956 size_t ret = this->segment_list_.size();
958 // If we didn't see a SECTIONS clause in a linker script, we should
959 // already have the complete list of segments. Otherwise we ask the
960 // SECTIONS clause how many segments it expects, and add in the ones
961 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
963 if (!this->script_options_->saw_sections_clause())
964 return ret;
965 else
967 const Script_sections* ss = this->script_options_->script_sections();
968 return ret + ss->expected_segment_count(this);
972 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
973 // is whether we saw a .note.GNU-stack section in the object file.
974 // GNU_STACK_FLAGS is the section flags. The flags give the
975 // protection required for stack memory. We record this in an
976 // executable as a PT_GNU_STACK segment. If an object file does not
977 // have a .note.GNU-stack segment, we must assume that it is an old
978 // object. On some targets that will force an executable stack.
980 void
981 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
983 if (!seen_gnu_stack)
984 this->input_without_gnu_stack_note_ = true;
985 else
987 this->input_with_gnu_stack_note_ = true;
988 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
989 this->input_requires_executable_stack_ = true;
993 // Create the dynamic sections which are needed before we read the
994 // relocs.
996 void
997 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
999 if (parameters->doing_static_link())
1000 return;
1002 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1003 elfcpp::SHT_DYNAMIC,
1004 (elfcpp::SHF_ALLOC
1005 | elfcpp::SHF_WRITE),
1006 false);
1007 this->dynamic_section_->set_is_relro();
1009 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
1010 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1011 elfcpp::STV_HIDDEN, 0, false, false);
1013 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1015 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1018 // For each output section whose name can be represented as C symbol,
1019 // define __start and __stop symbols for the section. This is a GNU
1020 // extension.
1022 void
1023 Layout::define_section_symbols(Symbol_table* symtab)
1025 for (Section_list::const_iterator p = this->section_list_.begin();
1026 p != this->section_list_.end();
1027 ++p)
1029 const char* const name = (*p)->name();
1030 if (name[strspn(name,
1031 ("0123456789"
1032 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1033 "abcdefghijklmnopqrstuvwxyz"
1034 "_"))]
1035 == '\0')
1037 const std::string name_string(name);
1038 const std::string start_name("__start_" + name_string);
1039 const std::string stop_name("__stop_" + name_string);
1041 symtab->define_in_output_data(start_name.c_str(),
1042 NULL, // version
1044 0, // value
1045 0, // symsize
1046 elfcpp::STT_NOTYPE,
1047 elfcpp::STB_GLOBAL,
1048 elfcpp::STV_DEFAULT,
1049 0, // nonvis
1050 false, // offset_is_from_end
1051 true); // only_if_ref
1053 symtab->define_in_output_data(stop_name.c_str(),
1054 NULL, // version
1056 0, // value
1057 0, // symsize
1058 elfcpp::STT_NOTYPE,
1059 elfcpp::STB_GLOBAL,
1060 elfcpp::STV_DEFAULT,
1061 0, // nonvis
1062 true, // offset_is_from_end
1063 true); // only_if_ref
1068 // Define symbols for group signatures.
1070 void
1071 Layout::define_group_signatures(Symbol_table* symtab)
1073 for (Group_signatures::iterator p = this->group_signatures_.begin();
1074 p != this->group_signatures_.end();
1075 ++p)
1077 Symbol* sym = symtab->lookup(p->signature, NULL);
1078 if (sym != NULL)
1079 p->section->set_info_symndx(sym);
1080 else
1082 // Force the name of the group section to the group
1083 // signature, and use the group's section symbol as the
1084 // signature symbol.
1085 if (strcmp(p->section->name(), p->signature) != 0)
1087 const char* name = this->namepool_.add(p->signature,
1088 true, NULL);
1089 p->section->set_name(name);
1091 p->section->set_needs_symtab_index();
1092 p->section->set_info_section_symndx(p->section);
1096 this->group_signatures_.clear();
1099 // Find the first read-only PT_LOAD segment, creating one if
1100 // necessary.
1102 Output_segment*
1103 Layout::find_first_load_seg()
1105 for (Segment_list::const_iterator p = this->segment_list_.begin();
1106 p != this->segment_list_.end();
1107 ++p)
1109 if ((*p)->type() == elfcpp::PT_LOAD
1110 && ((*p)->flags() & elfcpp::PF_R) != 0
1111 && (parameters->options().omagic()
1112 || ((*p)->flags() & elfcpp::PF_W) == 0))
1113 return *p;
1116 gold_assert(!this->script_options_->saw_phdrs_clause());
1118 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1119 elfcpp::PF_R);
1120 return load_seg;
1123 // Finalize the layout. When this is called, we have created all the
1124 // output sections and all the output segments which are based on
1125 // input sections. We have several things to do, and we have to do
1126 // them in the right order, so that we get the right results correctly
1127 // and efficiently.
1129 // 1) Finalize the list of output segments and create the segment
1130 // table header.
1132 // 2) Finalize the dynamic symbol table and associated sections.
1134 // 3) Determine the final file offset of all the output segments.
1136 // 4) Determine the final file offset of all the SHF_ALLOC output
1137 // sections.
1139 // 5) Create the symbol table sections and the section name table
1140 // section.
1142 // 6) Finalize the symbol table: set symbol values to their final
1143 // value and make a final determination of which symbols are going
1144 // into the output symbol table.
1146 // 7) Create the section table header.
1148 // 8) Determine the final file offset of all the output sections which
1149 // are not SHF_ALLOC, including the section table header.
1151 // 9) Finalize the ELF file header.
1153 // This function returns the size of the output file.
1155 off_t
1156 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1157 Target* target, const Task* task)
1159 target->finalize_sections(this);
1161 this->count_local_symbols(task, input_objects);
1163 this->create_gold_note();
1164 this->create_executable_stack_info(target);
1165 this->create_build_id();
1167 Output_segment* phdr_seg = NULL;
1168 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1170 // There was a dynamic object in the link. We need to create
1171 // some information for the dynamic linker.
1173 // Create the PT_PHDR segment which will hold the program
1174 // headers.
1175 if (!this->script_options_->saw_phdrs_clause())
1176 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1178 // Create the dynamic symbol table, including the hash table.
1179 Output_section* dynstr;
1180 std::vector<Symbol*> dynamic_symbols;
1181 unsigned int local_dynamic_count;
1182 Versions versions(*this->script_options()->version_script_info(),
1183 &this->dynpool_);
1184 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1185 &local_dynamic_count, &dynamic_symbols,
1186 &versions);
1188 // Create the .interp section to hold the name of the
1189 // interpreter, and put it in a PT_INTERP segment.
1190 if (!parameters->options().shared())
1191 this->create_interp(target);
1193 // Finish the .dynamic section to hold the dynamic data, and put
1194 // it in a PT_DYNAMIC segment.
1195 this->finish_dynamic_section(input_objects, symtab);
1197 // We should have added everything we need to the dynamic string
1198 // table.
1199 this->dynpool_.set_string_offsets();
1201 // Create the version sections. We can't do this until the
1202 // dynamic string table is complete.
1203 this->create_version_sections(&versions, symtab, local_dynamic_count,
1204 dynamic_symbols, dynstr);
1207 // If there is a SECTIONS clause, put all the input sections into
1208 // the required order.
1209 Output_segment* load_seg;
1210 if (this->script_options_->saw_sections_clause())
1211 load_seg = this->set_section_addresses_from_script(symtab);
1212 else if (parameters->options().relocatable())
1213 load_seg = NULL;
1214 else
1215 load_seg = this->find_first_load_seg();
1217 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
1218 load_seg = NULL;
1220 gold_assert(phdr_seg == NULL || load_seg != NULL);
1222 // Lay out the segment headers.
1223 Output_segment_headers* segment_headers;
1224 if (parameters->options().relocatable())
1225 segment_headers = NULL;
1226 else
1228 segment_headers = new Output_segment_headers(this->segment_list_);
1229 if (load_seg != NULL)
1230 load_seg->add_initial_output_data(segment_headers);
1231 if (phdr_seg != NULL)
1232 phdr_seg->add_initial_output_data(segment_headers);
1235 // Lay out the file header.
1236 Output_file_header* file_header;
1237 file_header = new Output_file_header(target, symtab, segment_headers,
1238 this->options_.entry());
1239 if (load_seg != NULL)
1240 load_seg->add_initial_output_data(file_header);
1242 this->special_output_list_.push_back(file_header);
1243 if (segment_headers != NULL)
1244 this->special_output_list_.push_back(segment_headers);
1246 if (this->script_options_->saw_phdrs_clause()
1247 && !parameters->options().relocatable())
1249 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1250 // clause in a linker script.
1251 Script_sections* ss = this->script_options_->script_sections();
1252 ss->put_headers_in_phdrs(file_header, segment_headers);
1255 // We set the output section indexes in set_segment_offsets and
1256 // set_section_indexes.
1257 unsigned int shndx = 1;
1259 // Set the file offsets of all the segments, and all the sections
1260 // they contain.
1261 off_t off;
1262 if (!parameters->options().relocatable())
1263 off = this->set_segment_offsets(target, load_seg, &shndx);
1264 else
1265 off = this->set_relocatable_section_offsets(file_header, &shndx);
1267 // Set the file offsets of all the non-data sections we've seen so
1268 // far which don't have to wait for the input sections. We need
1269 // this in order to finalize local symbols in non-allocated
1270 // sections.
1271 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1273 // Set the section indexes of all unallocated sections seen so far,
1274 // in case any of them are somehow referenced by a symbol.
1275 shndx = this->set_section_indexes(shndx);
1277 // Create the symbol table sections.
1278 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1279 if (!parameters->doing_static_link())
1280 this->assign_local_dynsym_offsets(input_objects);
1282 // Process any symbol assignments from a linker script. This must
1283 // be called after the symbol table has been finalized.
1284 this->script_options_->finalize_symbols(symtab, this);
1286 // Create the .shstrtab section.
1287 Output_section* shstrtab_section = this->create_shstrtab();
1289 // Set the file offsets of the rest of the non-data sections which
1290 // don't have to wait for the input sections.
1291 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1293 // Now that all sections have been created, set the section indexes
1294 // for any sections which haven't been done yet.
1295 shndx = this->set_section_indexes(shndx);
1297 // Create the section table header.
1298 this->create_shdrs(shstrtab_section, &off);
1300 // If there are no sections which require postprocessing, we can
1301 // handle the section names now, and avoid a resize later.
1302 if (!this->any_postprocessing_sections_)
1303 off = this->set_section_offsets(off,
1304 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1306 file_header->set_section_info(this->section_headers_, shstrtab_section);
1308 // Now we know exactly where everything goes in the output file
1309 // (except for non-allocated sections which require postprocessing).
1310 Output_data::layout_complete();
1312 this->output_file_size_ = off;
1314 return off;
1317 // Create a note header following the format defined in the ELF ABI.
1318 // NAME is the name, NOTE_TYPE is the type, DESCSZ is the size of the
1319 // descriptor. ALLOCATE is true if the section should be allocated in
1320 // memory. This returns the new note section. It sets
1321 // *TRAILING_PADDING to the number of trailing zero bytes required.
1323 Output_section*
1324 Layout::create_note(const char* name, int note_type, size_t descsz,
1325 bool allocate, size_t* trailing_padding)
1327 // Authorities all agree that the values in a .note field should
1328 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1329 // they differ on what the alignment is for 64-bit binaries.
1330 // The GABI says unambiguously they take 8-byte alignment:
1331 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1332 // Other documentation says alignment should always be 4 bytes:
1333 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1334 // GNU ld and GNU readelf both support the latter (at least as of
1335 // version 2.16.91), and glibc always generates the latter for
1336 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1337 // here.
1338 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1339 const int size = parameters->target().get_size();
1340 #else
1341 const int size = 32;
1342 #endif
1344 // The contents of the .note section.
1345 size_t namesz = strlen(name) + 1;
1346 size_t aligned_namesz = align_address(namesz, size / 8);
1347 size_t aligned_descsz = align_address(descsz, size / 8);
1349 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1351 unsigned char* buffer = new unsigned char[notehdrsz];
1352 memset(buffer, 0, notehdrsz);
1354 bool is_big_endian = parameters->target().is_big_endian();
1356 if (size == 32)
1358 if (!is_big_endian)
1360 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1361 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1362 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1364 else
1366 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1367 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1368 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1371 else if (size == 64)
1373 if (!is_big_endian)
1375 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1376 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1377 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1379 else
1381 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1382 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1383 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1386 else
1387 gold_unreachable();
1389 memcpy(buffer + 3 * (size / 8), name, namesz);
1391 const char* note_name = this->namepool_.add(".note", false, NULL);
1392 elfcpp::Elf_Xword flags = 0;
1393 if (allocate)
1394 flags = elfcpp::SHF_ALLOC;
1395 Output_section* os = this->make_output_section(note_name,
1396 elfcpp::SHT_NOTE,
1397 flags);
1398 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1399 size / 8,
1400 "** note header");
1401 os->add_output_section_data(posd);
1403 *trailing_padding = aligned_descsz - descsz;
1405 return os;
1408 // For an executable or shared library, create a note to record the
1409 // version of gold used to create the binary.
1411 void
1412 Layout::create_gold_note()
1414 if (parameters->options().relocatable())
1415 return;
1417 std::string desc = std::string("gold ") + gold::get_version_string();
1419 size_t trailing_padding;
1420 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1421 desc.size(), false, &trailing_padding);
1423 Output_section_data* posd = new Output_data_const(desc, 4);
1424 os->add_output_section_data(posd);
1426 if (trailing_padding > 0)
1428 posd = new Output_data_zero_fill(trailing_padding, 0);
1429 os->add_output_section_data(posd);
1433 // Record whether the stack should be executable. This can be set
1434 // from the command line using the -z execstack or -z noexecstack
1435 // options. Otherwise, if any input file has a .note.GNU-stack
1436 // section with the SHF_EXECINSTR flag set, the stack should be
1437 // executable. Otherwise, if at least one input file a
1438 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1439 // section, we use the target default for whether the stack should be
1440 // executable. Otherwise, we don't generate a stack note. When
1441 // generating a object file, we create a .note.GNU-stack section with
1442 // the appropriate marking. When generating an executable or shared
1443 // library, we create a PT_GNU_STACK segment.
1445 void
1446 Layout::create_executable_stack_info(const Target* target)
1448 bool is_stack_executable;
1449 if (this->options_.is_execstack_set())
1450 is_stack_executable = this->options_.is_stack_executable();
1451 else if (!this->input_with_gnu_stack_note_)
1452 return;
1453 else
1455 if (this->input_requires_executable_stack_)
1456 is_stack_executable = true;
1457 else if (this->input_without_gnu_stack_note_)
1458 is_stack_executable = target->is_default_stack_executable();
1459 else
1460 is_stack_executable = false;
1463 if (parameters->options().relocatable())
1465 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1466 elfcpp::Elf_Xword flags = 0;
1467 if (is_stack_executable)
1468 flags |= elfcpp::SHF_EXECINSTR;
1469 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1471 else
1473 if (this->script_options_->saw_phdrs_clause())
1474 return;
1475 int flags = elfcpp::PF_R | elfcpp::PF_W;
1476 if (is_stack_executable)
1477 flags |= elfcpp::PF_X;
1478 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1482 // If --build-id was used, set up the build ID note.
1484 void
1485 Layout::create_build_id()
1487 if (!parameters->options().user_set_build_id())
1488 return;
1490 const char* style = parameters->options().build_id();
1491 if (strcmp(style, "none") == 0)
1492 return;
1494 // Set DESCSZ to the size of the note descriptor. When possible,
1495 // set DESC to the note descriptor contents.
1496 size_t descsz;
1497 std::string desc;
1498 if (strcmp(style, "md5") == 0)
1499 descsz = 128 / 8;
1500 else if (strcmp(style, "sha1") == 0)
1501 descsz = 160 / 8;
1502 else if (strcmp(style, "uuid") == 0)
1504 const size_t uuidsz = 128 / 8;
1506 char buffer[uuidsz];
1507 memset(buffer, 0, uuidsz);
1509 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
1510 if (descriptor < 0)
1511 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1512 strerror(errno));
1513 else
1515 ssize_t got = ::read(descriptor, buffer, uuidsz);
1516 release_descriptor(descriptor, true);
1517 if (got < 0)
1518 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1519 else if (static_cast<size_t>(got) != uuidsz)
1520 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1521 uuidsz, got);
1524 desc.assign(buffer, uuidsz);
1525 descsz = uuidsz;
1527 else if (strncmp(style, "0x", 2) == 0)
1529 hex_init();
1530 const char* p = style + 2;
1531 while (*p != '\0')
1533 if (hex_p(p[0]) && hex_p(p[1]))
1535 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1536 desc += c;
1537 p += 2;
1539 else if (*p == '-' || *p == ':')
1540 ++p;
1541 else
1542 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1543 style);
1545 descsz = desc.size();
1547 else
1548 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1550 // Create the note.
1551 size_t trailing_padding;
1552 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1553 descsz, true, &trailing_padding);
1555 if (!desc.empty())
1557 // We know the value already, so we fill it in now.
1558 gold_assert(desc.size() == descsz);
1560 Output_section_data* posd = new Output_data_const(desc, 4);
1561 os->add_output_section_data(posd);
1563 if (trailing_padding != 0)
1565 posd = new Output_data_zero_fill(trailing_padding, 0);
1566 os->add_output_section_data(posd);
1569 else
1571 // We need to compute a checksum after we have completed the
1572 // link.
1573 gold_assert(trailing_padding == 0);
1574 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
1575 os->add_output_section_data(this->build_id_note_);
1576 os->set_after_input_sections();
1580 // Return whether SEG1 should be before SEG2 in the output file. This
1581 // is based entirely on the segment type and flags. When this is
1582 // called the segment addresses has normally not yet been set.
1584 bool
1585 Layout::segment_precedes(const Output_segment* seg1,
1586 const Output_segment* seg2)
1588 elfcpp::Elf_Word type1 = seg1->type();
1589 elfcpp::Elf_Word type2 = seg2->type();
1591 // The single PT_PHDR segment is required to precede any loadable
1592 // segment. We simply make it always first.
1593 if (type1 == elfcpp::PT_PHDR)
1595 gold_assert(type2 != elfcpp::PT_PHDR);
1596 return true;
1598 if (type2 == elfcpp::PT_PHDR)
1599 return false;
1601 // The single PT_INTERP segment is required to precede any loadable
1602 // segment. We simply make it always second.
1603 if (type1 == elfcpp::PT_INTERP)
1605 gold_assert(type2 != elfcpp::PT_INTERP);
1606 return true;
1608 if (type2 == elfcpp::PT_INTERP)
1609 return false;
1611 // We then put PT_LOAD segments before any other segments.
1612 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1613 return true;
1614 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1615 return false;
1617 // We put the PT_TLS segment last except for the PT_GNU_RELRO
1618 // segment, because that is where the dynamic linker expects to find
1619 // it (this is just for efficiency; other positions would also work
1620 // correctly).
1621 if (type1 == elfcpp::PT_TLS
1622 && type2 != elfcpp::PT_TLS
1623 && type2 != elfcpp::PT_GNU_RELRO)
1624 return false;
1625 if (type2 == elfcpp::PT_TLS
1626 && type1 != elfcpp::PT_TLS
1627 && type1 != elfcpp::PT_GNU_RELRO)
1628 return true;
1630 // We put the PT_GNU_RELRO segment last, because that is where the
1631 // dynamic linker expects to find it (as with PT_TLS, this is just
1632 // for efficiency).
1633 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
1634 return false;
1635 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
1636 return true;
1638 const elfcpp::Elf_Word flags1 = seg1->flags();
1639 const elfcpp::Elf_Word flags2 = seg2->flags();
1641 // The order of non-PT_LOAD segments is unimportant. We simply sort
1642 // by the numeric segment type and flags values. There should not
1643 // be more than one segment with the same type and flags.
1644 if (type1 != elfcpp::PT_LOAD)
1646 if (type1 != type2)
1647 return type1 < type2;
1648 gold_assert(flags1 != flags2);
1649 return flags1 < flags2;
1652 // If the addresses are set already, sort by load address.
1653 if (seg1->are_addresses_set())
1655 if (!seg2->are_addresses_set())
1656 return true;
1658 unsigned int section_count1 = seg1->output_section_count();
1659 unsigned int section_count2 = seg2->output_section_count();
1660 if (section_count1 == 0 && section_count2 > 0)
1661 return true;
1662 if (section_count1 > 0 && section_count2 == 0)
1663 return false;
1665 uint64_t paddr1 = seg1->first_section_load_address();
1666 uint64_t paddr2 = seg2->first_section_load_address();
1667 if (paddr1 != paddr2)
1668 return paddr1 < paddr2;
1670 else if (seg2->are_addresses_set())
1671 return false;
1673 // We sort PT_LOAD segments based on the flags. Readonly segments
1674 // come before writable segments. Then writable segments with data
1675 // come before writable segments without data. Then executable
1676 // segments come before non-executable segments. Then the unlikely
1677 // case of a non-readable segment comes before the normal case of a
1678 // readable segment. If there are multiple segments with the same
1679 // type and flags, we require that the address be set, and we sort
1680 // by virtual address and then physical address.
1681 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1682 return (flags1 & elfcpp::PF_W) == 0;
1683 if ((flags1 & elfcpp::PF_W) != 0
1684 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
1685 return seg1->has_any_data_sections();
1686 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1687 return (flags1 & elfcpp::PF_X) != 0;
1688 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1689 return (flags1 & elfcpp::PF_R) == 0;
1691 // We shouldn't get here--we shouldn't create segments which we
1692 // can't distinguish.
1693 gold_unreachable();
1696 // Set the file offsets of all the segments, and all the sections they
1697 // contain. They have all been created. LOAD_SEG must be be laid out
1698 // first. Return the offset of the data to follow.
1700 off_t
1701 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1702 unsigned int *pshndx)
1704 // Sort them into the final order.
1705 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1706 Layout::Compare_segments());
1708 // Find the PT_LOAD segments, and set their addresses and offsets
1709 // and their section's addresses and offsets.
1710 uint64_t addr;
1711 if (this->options_.user_set_Ttext())
1712 addr = this->options_.Ttext();
1713 else if (parameters->options().shared())
1714 addr = 0;
1715 else
1716 addr = target->default_text_segment_address();
1717 off_t off = 0;
1719 // If LOAD_SEG is NULL, then the file header and segment headers
1720 // will not be loadable. But they still need to be at offset 0 in
1721 // the file. Set their offsets now.
1722 if (load_seg == NULL)
1724 for (Data_list::iterator p = this->special_output_list_.begin();
1725 p != this->special_output_list_.end();
1726 ++p)
1728 off = align_address(off, (*p)->addralign());
1729 (*p)->set_address_and_file_offset(0, off);
1730 off += (*p)->data_size();
1734 const bool check_sections = parameters->options().check_sections();
1735 Output_segment* last_load_segment = NULL;
1737 bool was_readonly = false;
1738 for (Segment_list::iterator p = this->segment_list_.begin();
1739 p != this->segment_list_.end();
1740 ++p)
1742 if ((*p)->type() == elfcpp::PT_LOAD)
1744 if (load_seg != NULL && load_seg != *p)
1745 gold_unreachable();
1746 load_seg = NULL;
1748 bool are_addresses_set = (*p)->are_addresses_set();
1749 if (are_addresses_set)
1751 // When it comes to setting file offsets, we care about
1752 // the physical address.
1753 addr = (*p)->paddr();
1755 else if (this->options_.user_set_Tdata()
1756 && ((*p)->flags() & elfcpp::PF_W) != 0
1757 && (!this->options_.user_set_Tbss()
1758 || (*p)->has_any_data_sections()))
1760 addr = this->options_.Tdata();
1761 are_addresses_set = true;
1763 else if (this->options_.user_set_Tbss()
1764 && ((*p)->flags() & elfcpp::PF_W) != 0
1765 && !(*p)->has_any_data_sections())
1767 addr = this->options_.Tbss();
1768 are_addresses_set = true;
1771 uint64_t orig_addr = addr;
1772 uint64_t orig_off = off;
1774 uint64_t aligned_addr = 0;
1775 uint64_t abi_pagesize = target->abi_pagesize();
1776 uint64_t common_pagesize = target->common_pagesize();
1778 if (!parameters->options().nmagic()
1779 && !parameters->options().omagic())
1780 (*p)->set_minimum_p_align(common_pagesize);
1782 if (are_addresses_set)
1784 if (!parameters->options().nmagic()
1785 && !parameters->options().omagic())
1787 // Adjust the file offset to the same address modulo
1788 // the page size.
1789 uint64_t unsigned_off = off;
1790 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1791 | (addr & (abi_pagesize - 1)));
1792 if (aligned_off < unsigned_off)
1793 aligned_off += abi_pagesize;
1794 off = aligned_off;
1797 else
1799 // If the last segment was readonly, and this one is
1800 // not, then skip the address forward one page,
1801 // maintaining the same position within the page. This
1802 // lets us store both segments overlapping on a single
1803 // page in the file, but the loader will put them on
1804 // different pages in memory.
1806 addr = align_address(addr, (*p)->maximum_alignment());
1807 aligned_addr = addr;
1809 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1811 if ((addr & (abi_pagesize - 1)) != 0)
1812 addr = addr + abi_pagesize;
1815 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1818 unsigned int shndx_hold = *pshndx;
1819 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
1820 &off, pshndx);
1822 // Now that we know the size of this segment, we may be able
1823 // to save a page in memory, at the cost of wasting some
1824 // file space, by instead aligning to the start of a new
1825 // page. Here we use the real machine page size rather than
1826 // the ABI mandated page size.
1828 if (!are_addresses_set && aligned_addr != addr)
1830 uint64_t first_off = (common_pagesize
1831 - (aligned_addr
1832 & (common_pagesize - 1)));
1833 uint64_t last_off = new_addr & (common_pagesize - 1);
1834 if (first_off > 0
1835 && last_off > 0
1836 && ((aligned_addr & ~ (common_pagesize - 1))
1837 != (new_addr & ~ (common_pagesize - 1)))
1838 && first_off + last_off <= common_pagesize)
1840 *pshndx = shndx_hold;
1841 addr = align_address(aligned_addr, common_pagesize);
1842 addr = align_address(addr, (*p)->maximum_alignment());
1843 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1844 new_addr = (*p)->set_section_addresses(this, true, addr,
1845 &off, pshndx);
1849 addr = new_addr;
1851 if (((*p)->flags() & elfcpp::PF_W) == 0)
1852 was_readonly = true;
1854 // Implement --check-sections. We know that the segments
1855 // are sorted by LMA.
1856 if (check_sections && last_load_segment != NULL)
1858 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
1859 if (last_load_segment->paddr() + last_load_segment->memsz()
1860 > (*p)->paddr())
1862 unsigned long long lb1 = last_load_segment->paddr();
1863 unsigned long long le1 = lb1 + last_load_segment->memsz();
1864 unsigned long long lb2 = (*p)->paddr();
1865 unsigned long long le2 = lb2 + (*p)->memsz();
1866 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
1867 "[0x%llx -> 0x%llx]"),
1868 lb1, le1, lb2, le2);
1871 last_load_segment = *p;
1875 // Handle the non-PT_LOAD segments, setting their offsets from their
1876 // section's offsets.
1877 for (Segment_list::iterator p = this->segment_list_.begin();
1878 p != this->segment_list_.end();
1879 ++p)
1881 if ((*p)->type() != elfcpp::PT_LOAD)
1882 (*p)->set_offset();
1885 // Set the TLS offsets for each section in the PT_TLS segment.
1886 if (this->tls_segment_ != NULL)
1887 this->tls_segment_->set_tls_offsets();
1889 return off;
1892 // Set the offsets of all the allocated sections when doing a
1893 // relocatable link. This does the same jobs as set_segment_offsets,
1894 // only for a relocatable link.
1896 off_t
1897 Layout::set_relocatable_section_offsets(Output_data* file_header,
1898 unsigned int *pshndx)
1900 off_t off = 0;
1902 file_header->set_address_and_file_offset(0, 0);
1903 off += file_header->data_size();
1905 for (Section_list::iterator p = this->section_list_.begin();
1906 p != this->section_list_.end();
1907 ++p)
1909 // We skip unallocated sections here, except that group sections
1910 // have to come first.
1911 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
1912 && (*p)->type() != elfcpp::SHT_GROUP)
1913 continue;
1915 off = align_address(off, (*p)->addralign());
1917 // The linker script might have set the address.
1918 if (!(*p)->is_address_valid())
1919 (*p)->set_address(0);
1920 (*p)->set_file_offset(off);
1921 (*p)->finalize_data_size();
1922 off += (*p)->data_size();
1924 (*p)->set_out_shndx(*pshndx);
1925 ++*pshndx;
1928 return off;
1931 // Set the file offset of all the sections not associated with a
1932 // segment.
1934 off_t
1935 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1937 for (Section_list::iterator p = this->unattached_section_list_.begin();
1938 p != this->unattached_section_list_.end();
1939 ++p)
1941 // The symtab section is handled in create_symtab_sections.
1942 if (*p == this->symtab_section_)
1943 continue;
1945 // If we've already set the data size, don't set it again.
1946 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1947 continue;
1949 if (pass == BEFORE_INPUT_SECTIONS_PASS
1950 && (*p)->requires_postprocessing())
1952 (*p)->create_postprocessing_buffer();
1953 this->any_postprocessing_sections_ = true;
1956 if (pass == BEFORE_INPUT_SECTIONS_PASS
1957 && (*p)->after_input_sections())
1958 continue;
1959 else if (pass == POSTPROCESSING_SECTIONS_PASS
1960 && (!(*p)->after_input_sections()
1961 || (*p)->type() == elfcpp::SHT_STRTAB))
1962 continue;
1963 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1964 && (!(*p)->after_input_sections()
1965 || (*p)->type() != elfcpp::SHT_STRTAB))
1966 continue;
1968 off = align_address(off, (*p)->addralign());
1969 (*p)->set_file_offset(off);
1970 (*p)->finalize_data_size();
1971 off += (*p)->data_size();
1973 // At this point the name must be set.
1974 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1975 this->namepool_.add((*p)->name(), false, NULL);
1977 return off;
1980 // Set the section indexes of all the sections not associated with a
1981 // segment.
1983 unsigned int
1984 Layout::set_section_indexes(unsigned int shndx)
1986 for (Section_list::iterator p = this->unattached_section_list_.begin();
1987 p != this->unattached_section_list_.end();
1988 ++p)
1990 if (!(*p)->has_out_shndx())
1992 (*p)->set_out_shndx(shndx);
1993 ++shndx;
1996 return shndx;
1999 // Set the section addresses according to the linker script. This is
2000 // only called when we see a SECTIONS clause. This returns the
2001 // program segment which should hold the file header and segment
2002 // headers, if any. It will return NULL if they should not be in a
2003 // segment.
2005 Output_segment*
2006 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2008 Script_sections* ss = this->script_options_->script_sections();
2009 gold_assert(ss->saw_sections_clause());
2011 // Place each orphaned output section in the script.
2012 for (Section_list::iterator p = this->section_list_.begin();
2013 p != this->section_list_.end();
2014 ++p)
2016 if (!(*p)->found_in_sections_clause())
2017 ss->place_orphan(*p);
2020 return this->script_options_->set_section_addresses(symtab, this);
2023 // Count the local symbols in the regular symbol table and the dynamic
2024 // symbol table, and build the respective string pools.
2026 void
2027 Layout::count_local_symbols(const Task* task,
2028 const Input_objects* input_objects)
2030 // First, figure out an upper bound on the number of symbols we'll
2031 // be inserting into each pool. This helps us create the pools with
2032 // the right size, to avoid unnecessary hashtable resizing.
2033 unsigned int symbol_count = 0;
2034 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2035 p != input_objects->relobj_end();
2036 ++p)
2037 symbol_count += (*p)->local_symbol_count();
2039 // Go from "upper bound" to "estimate." We overcount for two
2040 // reasons: we double-count symbols that occur in more than one
2041 // object file, and we count symbols that are dropped from the
2042 // output. Add it all together and assume we overcount by 100%.
2043 symbol_count /= 2;
2045 // We assume all symbols will go into both the sympool and dynpool.
2046 this->sympool_.reserve(symbol_count);
2047 this->dynpool_.reserve(symbol_count);
2049 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2050 p != input_objects->relobj_end();
2051 ++p)
2053 Task_lock_obj<Object> tlo(task, *p);
2054 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2058 // Create the symbol table sections. Here we also set the final
2059 // values of the symbols. At this point all the loadable sections are
2060 // fully laid out. SHNUM is the number of sections so far.
2062 void
2063 Layout::create_symtab_sections(const Input_objects* input_objects,
2064 Symbol_table* symtab,
2065 unsigned int shnum,
2066 off_t* poff)
2068 int symsize;
2069 unsigned int align;
2070 if (parameters->target().get_size() == 32)
2072 symsize = elfcpp::Elf_sizes<32>::sym_size;
2073 align = 4;
2075 else if (parameters->target().get_size() == 64)
2077 symsize = elfcpp::Elf_sizes<64>::sym_size;
2078 align = 8;
2080 else
2081 gold_unreachable();
2083 off_t off = *poff;
2084 off = align_address(off, align);
2085 off_t startoff = off;
2087 // Save space for the dummy symbol at the start of the section. We
2088 // never bother to write this out--it will just be left as zero.
2089 off += symsize;
2090 unsigned int local_symbol_index = 1;
2092 // Add STT_SECTION symbols for each Output section which needs one.
2093 for (Section_list::iterator p = this->section_list_.begin();
2094 p != this->section_list_.end();
2095 ++p)
2097 if (!(*p)->needs_symtab_index())
2098 (*p)->set_symtab_index(-1U);
2099 else
2101 (*p)->set_symtab_index(local_symbol_index);
2102 ++local_symbol_index;
2103 off += symsize;
2107 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2108 p != input_objects->relobj_end();
2109 ++p)
2111 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2112 off);
2113 off += (index - local_symbol_index) * symsize;
2114 local_symbol_index = index;
2117 unsigned int local_symcount = local_symbol_index;
2118 gold_assert(local_symcount * symsize == off - startoff);
2120 off_t dynoff;
2121 size_t dyn_global_index;
2122 size_t dyncount;
2123 if (this->dynsym_section_ == NULL)
2125 dynoff = 0;
2126 dyn_global_index = 0;
2127 dyncount = 0;
2129 else
2131 dyn_global_index = this->dynsym_section_->info();
2132 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2133 dynoff = this->dynsym_section_->offset() + locsize;
2134 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2135 gold_assert(static_cast<off_t>(dyncount * symsize)
2136 == this->dynsym_section_->data_size() - locsize);
2139 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2140 &this->sympool_, &local_symcount);
2142 if (!parameters->options().strip_all())
2144 this->sympool_.set_string_offsets();
2146 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2147 Output_section* osymtab = this->make_output_section(symtab_name,
2148 elfcpp::SHT_SYMTAB,
2150 this->symtab_section_ = osymtab;
2152 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2153 align,
2154 "** symtab");
2155 osymtab->add_output_section_data(pos);
2157 // We generate a .symtab_shndx section if we have more than
2158 // SHN_LORESERVE sections. Technically it is possible that we
2159 // don't need one, because it is possible that there are no
2160 // symbols in any of sections with indexes larger than
2161 // SHN_LORESERVE. That is probably unusual, though, and it is
2162 // easier to always create one than to compute section indexes
2163 // twice (once here, once when writing out the symbols).
2164 if (shnum >= elfcpp::SHN_LORESERVE)
2166 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2167 false, NULL);
2168 Output_section* osymtab_xindex =
2169 this->make_output_section(symtab_xindex_name,
2170 elfcpp::SHT_SYMTAB_SHNDX, 0);
2172 size_t symcount = (off - startoff) / symsize;
2173 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2175 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2177 osymtab_xindex->set_link_section(osymtab);
2178 osymtab_xindex->set_addralign(4);
2179 osymtab_xindex->set_entsize(4);
2181 osymtab_xindex->set_after_input_sections();
2183 // This tells the driver code to wait until the symbol table
2184 // has written out before writing out the postprocessing
2185 // sections, including the .symtab_shndx section.
2186 this->any_postprocessing_sections_ = true;
2189 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2190 Output_section* ostrtab = this->make_output_section(strtab_name,
2191 elfcpp::SHT_STRTAB,
2194 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2195 ostrtab->add_output_section_data(pstr);
2197 osymtab->set_file_offset(startoff);
2198 osymtab->finalize_data_size();
2199 osymtab->set_link_section(ostrtab);
2200 osymtab->set_info(local_symcount);
2201 osymtab->set_entsize(symsize);
2203 *poff = off;
2207 // Create the .shstrtab section, which holds the names of the
2208 // sections. At the time this is called, we have created all the
2209 // output sections except .shstrtab itself.
2211 Output_section*
2212 Layout::create_shstrtab()
2214 // FIXME: We don't need to create a .shstrtab section if we are
2215 // stripping everything.
2217 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2219 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
2221 // We can't write out this section until we've set all the section
2222 // names, and we don't set the names of compressed output sections
2223 // until relocations are complete.
2224 os->set_after_input_sections();
2226 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2227 os->add_output_section_data(posd);
2229 return os;
2232 // Create the section headers. SIZE is 32 or 64. OFF is the file
2233 // offset.
2235 void
2236 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2238 Output_section_headers* oshdrs;
2239 oshdrs = new Output_section_headers(this,
2240 &this->segment_list_,
2241 &this->section_list_,
2242 &this->unattached_section_list_,
2243 &this->namepool_,
2244 shstrtab_section);
2245 off_t off = align_address(*poff, oshdrs->addralign());
2246 oshdrs->set_address_and_file_offset(0, off);
2247 off += oshdrs->data_size();
2248 *poff = off;
2249 this->section_headers_ = oshdrs;
2252 // Count the allocated sections.
2254 size_t
2255 Layout::allocated_output_section_count() const
2257 size_t section_count = 0;
2258 for (Segment_list::const_iterator p = this->segment_list_.begin();
2259 p != this->segment_list_.end();
2260 ++p)
2261 section_count += (*p)->output_section_count();
2262 return section_count;
2265 // Create the dynamic symbol table.
2267 void
2268 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2269 Symbol_table* symtab,
2270 Output_section **pdynstr,
2271 unsigned int* plocal_dynamic_count,
2272 std::vector<Symbol*>* pdynamic_symbols,
2273 Versions* pversions)
2275 // Count all the symbols in the dynamic symbol table, and set the
2276 // dynamic symbol indexes.
2278 // Skip symbol 0, which is always all zeroes.
2279 unsigned int index = 1;
2281 // Add STT_SECTION symbols for each Output section which needs one.
2282 for (Section_list::iterator p = this->section_list_.begin();
2283 p != this->section_list_.end();
2284 ++p)
2286 if (!(*p)->needs_dynsym_index())
2287 (*p)->set_dynsym_index(-1U);
2288 else
2290 (*p)->set_dynsym_index(index);
2291 ++index;
2295 // Count the local symbols that need to go in the dynamic symbol table,
2296 // and set the dynamic symbol indexes.
2297 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2298 p != input_objects->relobj_end();
2299 ++p)
2301 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2302 index = new_index;
2305 unsigned int local_symcount = index;
2306 *plocal_dynamic_count = local_symcount;
2308 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2309 &this->dynpool_, pversions);
2311 int symsize;
2312 unsigned int align;
2313 const int size = parameters->target().get_size();
2314 if (size == 32)
2316 symsize = elfcpp::Elf_sizes<32>::sym_size;
2317 align = 4;
2319 else if (size == 64)
2321 symsize = elfcpp::Elf_sizes<64>::sym_size;
2322 align = 8;
2324 else
2325 gold_unreachable();
2327 // Create the dynamic symbol table section.
2329 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2330 elfcpp::SHT_DYNSYM,
2331 elfcpp::SHF_ALLOC,
2332 false);
2334 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2335 align,
2336 "** dynsym");
2337 dynsym->add_output_section_data(odata);
2339 dynsym->set_info(local_symcount);
2340 dynsym->set_entsize(symsize);
2341 dynsym->set_addralign(align);
2343 this->dynsym_section_ = dynsym;
2345 Output_data_dynamic* const odyn = this->dynamic_data_;
2346 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2347 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2349 // If there are more than SHN_LORESERVE allocated sections, we
2350 // create a .dynsym_shndx section. It is possible that we don't
2351 // need one, because it is possible that there are no dynamic
2352 // symbols in any of the sections with indexes larger than
2353 // SHN_LORESERVE. This is probably unusual, though, and at this
2354 // time we don't know the actual section indexes so it is
2355 // inconvenient to check.
2356 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2358 Output_section* dynsym_xindex =
2359 this->choose_output_section(NULL, ".dynsym_shndx",
2360 elfcpp::SHT_SYMTAB_SHNDX,
2361 elfcpp::SHF_ALLOC,
2362 false);
2364 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2366 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2368 dynsym_xindex->set_link_section(dynsym);
2369 dynsym_xindex->set_addralign(4);
2370 dynsym_xindex->set_entsize(4);
2372 dynsym_xindex->set_after_input_sections();
2374 // This tells the driver code to wait until the symbol table has
2375 // written out before writing out the postprocessing sections,
2376 // including the .dynsym_shndx section.
2377 this->any_postprocessing_sections_ = true;
2380 // Create the dynamic string table section.
2382 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2383 elfcpp::SHT_STRTAB,
2384 elfcpp::SHF_ALLOC,
2385 false);
2387 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2388 dynstr->add_output_section_data(strdata);
2390 dynsym->set_link_section(dynstr);
2391 this->dynamic_section_->set_link_section(dynstr);
2393 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2394 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2396 *pdynstr = dynstr;
2398 // Create the hash tables.
2400 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2401 || strcmp(parameters->options().hash_style(), "both") == 0)
2403 unsigned char* phash;
2404 unsigned int hashlen;
2405 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2406 &phash, &hashlen);
2408 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2409 elfcpp::SHT_HASH,
2410 elfcpp::SHF_ALLOC,
2411 false);
2413 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2414 hashlen,
2415 align,
2416 "** hash");
2417 hashsec->add_output_section_data(hashdata);
2419 hashsec->set_link_section(dynsym);
2420 hashsec->set_entsize(4);
2422 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2425 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2426 || strcmp(parameters->options().hash_style(), "both") == 0)
2428 unsigned char* phash;
2429 unsigned int hashlen;
2430 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2431 &phash, &hashlen);
2433 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2434 elfcpp::SHT_GNU_HASH,
2435 elfcpp::SHF_ALLOC,
2436 false);
2438 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2439 hashlen,
2440 align,
2441 "** hash");
2442 hashsec->add_output_section_data(hashdata);
2444 hashsec->set_link_section(dynsym);
2445 hashsec->set_entsize(4);
2447 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2451 // Assign offsets to each local portion of the dynamic symbol table.
2453 void
2454 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2456 Output_section* dynsym = this->dynsym_section_;
2457 gold_assert(dynsym != NULL);
2459 off_t off = dynsym->offset();
2461 // Skip the dummy symbol at the start of the section.
2462 off += dynsym->entsize();
2464 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2465 p != input_objects->relobj_end();
2466 ++p)
2468 unsigned int count = (*p)->set_local_dynsym_offset(off);
2469 off += count * dynsym->entsize();
2473 // Create the version sections.
2475 void
2476 Layout::create_version_sections(const Versions* versions,
2477 const Symbol_table* symtab,
2478 unsigned int local_symcount,
2479 const std::vector<Symbol*>& dynamic_symbols,
2480 const Output_section* dynstr)
2482 if (!versions->any_defs() && !versions->any_needs())
2483 return;
2485 switch (parameters->size_and_endianness())
2487 #ifdef HAVE_TARGET_32_LITTLE
2488 case Parameters::TARGET_32_LITTLE:
2489 this->sized_create_version_sections<32, false>(versions, symtab,
2490 local_symcount,
2491 dynamic_symbols, dynstr);
2492 break;
2493 #endif
2494 #ifdef HAVE_TARGET_32_BIG
2495 case Parameters::TARGET_32_BIG:
2496 this->sized_create_version_sections<32, true>(versions, symtab,
2497 local_symcount,
2498 dynamic_symbols, dynstr);
2499 break;
2500 #endif
2501 #ifdef HAVE_TARGET_64_LITTLE
2502 case Parameters::TARGET_64_LITTLE:
2503 this->sized_create_version_sections<64, false>(versions, symtab,
2504 local_symcount,
2505 dynamic_symbols, dynstr);
2506 break;
2507 #endif
2508 #ifdef HAVE_TARGET_64_BIG
2509 case Parameters::TARGET_64_BIG:
2510 this->sized_create_version_sections<64, true>(versions, symtab,
2511 local_symcount,
2512 dynamic_symbols, dynstr);
2513 break;
2514 #endif
2515 default:
2516 gold_unreachable();
2520 // Create the version sections, sized version.
2522 template<int size, bool big_endian>
2523 void
2524 Layout::sized_create_version_sections(
2525 const Versions* versions,
2526 const Symbol_table* symtab,
2527 unsigned int local_symcount,
2528 const std::vector<Symbol*>& dynamic_symbols,
2529 const Output_section* dynstr)
2531 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2532 elfcpp::SHT_GNU_versym,
2533 elfcpp::SHF_ALLOC,
2534 false);
2536 unsigned char* vbuf;
2537 unsigned int vsize;
2538 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2539 local_symcount,
2540 dynamic_symbols,
2541 &vbuf, &vsize);
2543 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
2544 "** versions");
2546 vsec->add_output_section_data(vdata);
2547 vsec->set_entsize(2);
2548 vsec->set_link_section(this->dynsym_section_);
2550 Output_data_dynamic* const odyn = this->dynamic_data_;
2551 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2553 if (versions->any_defs())
2555 Output_section* vdsec;
2556 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
2557 elfcpp::SHT_GNU_verdef,
2558 elfcpp::SHF_ALLOC,
2559 false);
2561 unsigned char* vdbuf;
2562 unsigned int vdsize;
2563 unsigned int vdentries;
2564 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
2565 &vdsize, &vdentries);
2567 Output_section_data* vddata =
2568 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
2570 vdsec->add_output_section_data(vddata);
2571 vdsec->set_link_section(dynstr);
2572 vdsec->set_info(vdentries);
2574 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
2575 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
2578 if (versions->any_needs())
2580 Output_section* vnsec;
2581 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
2582 elfcpp::SHT_GNU_verneed,
2583 elfcpp::SHF_ALLOC,
2584 false);
2586 unsigned char* vnbuf;
2587 unsigned int vnsize;
2588 unsigned int vnentries;
2589 versions->need_section_contents<size, big_endian>(&this->dynpool_,
2590 &vnbuf, &vnsize,
2591 &vnentries);
2593 Output_section_data* vndata =
2594 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
2596 vnsec->add_output_section_data(vndata);
2597 vnsec->set_link_section(dynstr);
2598 vnsec->set_info(vnentries);
2600 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
2601 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
2605 // Create the .interp section and PT_INTERP segment.
2607 void
2608 Layout::create_interp(const Target* target)
2610 const char* interp = this->options_.dynamic_linker();
2611 if (interp == NULL)
2613 interp = target->dynamic_linker();
2614 gold_assert(interp != NULL);
2617 size_t len = strlen(interp) + 1;
2619 Output_section_data* odata = new Output_data_const(interp, len, 1);
2621 Output_section* osec = this->choose_output_section(NULL, ".interp",
2622 elfcpp::SHT_PROGBITS,
2623 elfcpp::SHF_ALLOC,
2624 false);
2625 osec->add_output_section_data(odata);
2627 if (!this->script_options_->saw_phdrs_clause())
2629 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
2630 elfcpp::PF_R);
2631 oseg->add_output_section(osec, elfcpp::PF_R);
2635 // Finish the .dynamic section and PT_DYNAMIC segment.
2637 void
2638 Layout::finish_dynamic_section(const Input_objects* input_objects,
2639 const Symbol_table* symtab)
2641 if (!this->script_options_->saw_phdrs_clause())
2643 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
2644 (elfcpp::PF_R
2645 | elfcpp::PF_W));
2646 oseg->add_output_section(this->dynamic_section_,
2647 elfcpp::PF_R | elfcpp::PF_W);
2650 Output_data_dynamic* const odyn = this->dynamic_data_;
2652 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
2653 p != input_objects->dynobj_end();
2654 ++p)
2656 // FIXME: Handle --as-needed.
2657 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
2660 if (parameters->options().shared())
2662 const char* soname = this->options_.soname();
2663 if (soname != NULL)
2664 odyn->add_string(elfcpp::DT_SONAME, soname);
2667 // FIXME: Support --init and --fini.
2668 Symbol* sym = symtab->lookup("_init");
2669 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2670 odyn->add_symbol(elfcpp::DT_INIT, sym);
2672 sym = symtab->lookup("_fini");
2673 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2674 odyn->add_symbol(elfcpp::DT_FINI, sym);
2676 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
2678 // Add a DT_RPATH entry if needed.
2679 const General_options::Dir_list& rpath(this->options_.rpath());
2680 if (!rpath.empty())
2682 std::string rpath_val;
2683 for (General_options::Dir_list::const_iterator p = rpath.begin();
2684 p != rpath.end();
2685 ++p)
2687 if (rpath_val.empty())
2688 rpath_val = p->name();
2689 else
2691 // Eliminate duplicates.
2692 General_options::Dir_list::const_iterator q;
2693 for (q = rpath.begin(); q != p; ++q)
2694 if (q->name() == p->name())
2695 break;
2696 if (q == p)
2698 rpath_val += ':';
2699 rpath_val += p->name();
2704 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
2705 if (parameters->options().enable_new_dtags())
2706 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
2709 // Look for text segments that have dynamic relocations.
2710 bool have_textrel = false;
2711 if (!this->script_options_->saw_sections_clause())
2713 for (Segment_list::const_iterator p = this->segment_list_.begin();
2714 p != this->segment_list_.end();
2715 ++p)
2717 if (((*p)->flags() & elfcpp::PF_W) == 0
2718 && (*p)->dynamic_reloc_count() > 0)
2720 have_textrel = true;
2721 break;
2725 else
2727 // We don't know the section -> segment mapping, so we are
2728 // conservative and just look for readonly sections with
2729 // relocations. If those sections wind up in writable segments,
2730 // then we have created an unnecessary DT_TEXTREL entry.
2731 for (Section_list::const_iterator p = this->section_list_.begin();
2732 p != this->section_list_.end();
2733 ++p)
2735 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
2736 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
2737 && ((*p)->dynamic_reloc_count() > 0))
2739 have_textrel = true;
2740 break;
2745 // Add a DT_FLAGS entry. We add it even if no flags are set so that
2746 // post-link tools can easily modify these flags if desired.
2747 unsigned int flags = 0;
2748 if (have_textrel)
2750 // Add a DT_TEXTREL for compatibility with older loaders.
2751 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
2752 flags |= elfcpp::DF_TEXTREL;
2754 if (parameters->options().shared() && this->has_static_tls())
2755 flags |= elfcpp::DF_STATIC_TLS;
2756 if (parameters->options().origin())
2757 flags |= elfcpp::DF_ORIGIN;
2758 odyn->add_constant(elfcpp::DT_FLAGS, flags);
2760 flags = 0;
2761 if (parameters->options().initfirst())
2762 flags |= elfcpp::DF_1_INITFIRST;
2763 if (parameters->options().interpose())
2764 flags |= elfcpp::DF_1_INTERPOSE;
2765 if (parameters->options().loadfltr())
2766 flags |= elfcpp::DF_1_LOADFLTR;
2767 if (parameters->options().nodefaultlib())
2768 flags |= elfcpp::DF_1_NODEFLIB;
2769 if (parameters->options().nodelete())
2770 flags |= elfcpp::DF_1_NODELETE;
2771 if (parameters->options().nodlopen())
2772 flags |= elfcpp::DF_1_NOOPEN;
2773 if (parameters->options().nodump())
2774 flags |= elfcpp::DF_1_NODUMP;
2775 if (!parameters->options().shared())
2776 flags &= ~(elfcpp::DF_1_INITFIRST
2777 | elfcpp::DF_1_NODELETE
2778 | elfcpp::DF_1_NOOPEN);
2779 if (parameters->options().origin())
2780 flags |= elfcpp::DF_1_ORIGIN;
2781 if (flags)
2782 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
2785 // The mapping of .gnu.linkonce section names to real section names.
2787 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
2788 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
2790 MAPPING_INIT("d.rel.ro.local", ".data.rel.ro.local"), // Before "d.rel.ro".
2791 MAPPING_INIT("d.rel.ro", ".data.rel.ro"), // Before "d".
2792 MAPPING_INIT("t", ".text"),
2793 MAPPING_INIT("r", ".rodata"),
2794 MAPPING_INIT("d", ".data"),
2795 MAPPING_INIT("b", ".bss"),
2796 MAPPING_INIT("s", ".sdata"),
2797 MAPPING_INIT("sb", ".sbss"),
2798 MAPPING_INIT("s2", ".sdata2"),
2799 MAPPING_INIT("sb2", ".sbss2"),
2800 MAPPING_INIT("wi", ".debug_info"),
2801 MAPPING_INIT("td", ".tdata"),
2802 MAPPING_INIT("tb", ".tbss"),
2803 MAPPING_INIT("lr", ".lrodata"),
2804 MAPPING_INIT("l", ".ldata"),
2805 MAPPING_INIT("lb", ".lbss"),
2807 #undef MAPPING_INIT
2809 const int Layout::linkonce_mapping_count =
2810 sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
2812 // Return the name of the output section to use for a .gnu.linkonce
2813 // section. This is based on the default ELF linker script of the old
2814 // GNU linker. For example, we map a name like ".gnu.linkonce.t.foo"
2815 // to ".text". Set *PLEN to the length of the name. *PLEN is
2816 // initialized to the length of NAME.
2818 const char*
2819 Layout::linkonce_output_name(const char* name, size_t *plen)
2821 const char* s = name + sizeof(".gnu.linkonce") - 1;
2822 if (*s != '.')
2823 return name;
2824 ++s;
2825 const Linkonce_mapping* plm = linkonce_mapping;
2826 for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2828 if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2830 *plen = plm->tolen;
2831 return plm->to;
2834 return name;
2837 // Choose the output section name to use given an input section name.
2838 // Set *PLEN to the length of the name. *PLEN is initialized to the
2839 // length of NAME.
2841 const char*
2842 Layout::output_section_name(const char* name, size_t* plen)
2844 if (Layout::is_linkonce(name))
2846 // .gnu.linkonce sections are laid out as though they were named
2847 // for the sections are placed into.
2848 return Layout::linkonce_output_name(name, plen);
2851 // gcc 4.3 generates the following sorts of section names when it
2852 // needs a section name specific to a function:
2853 // .text.FN
2854 // .rodata.FN
2855 // .sdata2.FN
2856 // .data.FN
2857 // .data.rel.FN
2858 // .data.rel.local.FN
2859 // .data.rel.ro.FN
2860 // .data.rel.ro.local.FN
2861 // .sdata.FN
2862 // .bss.FN
2863 // .sbss.FN
2864 // .tdata.FN
2865 // .tbss.FN
2867 // The GNU linker maps all of those to the part before the .FN,
2868 // except that .data.rel.local.FN is mapped to .data, and
2869 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
2870 // beginning with .data.rel.ro.local are grouped together.
2872 // For an anonymous namespace, the string FN can contain a '.'.
2874 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2875 // GNU linker maps to .rodata.
2877 // The .data.rel.ro sections enable a security feature triggered by
2878 // the -z relro option. Section which need to be relocated at
2879 // program startup time but which may be readonly after startup are
2880 // grouped into .data.rel.ro. They are then put into a PT_GNU_RELRO
2881 // segment. The dynamic linker will make that segment writable,
2882 // perform relocations, and then make it read-only. FIXME: We do
2883 // not yet implement this optimization.
2885 // It is hard to handle this in a principled way.
2887 // These are the rules we follow:
2889 // If the section name has no initial '.', or no dot other than an
2890 // initial '.', we use the name unchanged (i.e., "mysection" and
2891 // ".text" are unchanged).
2893 // If the name starts with ".data.rel.ro.local" we use
2894 // ".data.rel.ro.local".
2896 // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2898 // Otherwise, we drop the second '.' and everything that comes after
2899 // it (i.e., ".text.XXX" becomes ".text").
2901 const char* s = name;
2902 if (*s != '.')
2903 return name;
2904 ++s;
2905 const char* sdot = strchr(s, '.');
2906 if (sdot == NULL)
2907 return name;
2909 const char* const data_rel_ro_local = ".data.rel.ro.local";
2910 if (strncmp(name, data_rel_ro_local, strlen(data_rel_ro_local)) == 0)
2912 *plen = strlen(data_rel_ro_local);
2913 return data_rel_ro_local;
2916 const char* const data_rel_ro = ".data.rel.ro";
2917 if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2919 *plen = strlen(data_rel_ro);
2920 return data_rel_ro;
2923 *plen = sdot - name;
2924 return name;
2927 // Record the signature of a comdat section, and return whether to
2928 // include it in the link. If GROUP is true, this is a regular
2929 // section group. If GROUP is false, this is a group signature
2930 // derived from the name of a linkonce section. We want linkonce
2931 // signatures and group signatures to block each other, but we don't
2932 // want a linkonce signature to block another linkonce signature.
2934 bool
2935 Layout::add_comdat(Relobj* object, unsigned int shndx,
2936 const std::string& signature, bool group)
2938 Kept_section kept(object, shndx, group);
2939 std::pair<Signatures::iterator, bool> ins(
2940 this->signatures_.insert(std::make_pair(signature, kept)));
2942 if (ins.second)
2944 // This is the first time we've seen this signature.
2945 return true;
2948 if (ins.first->second.group_)
2950 // We've already seen a real section group with this signature.
2951 return false;
2953 else if (group)
2955 // This is a real section group, and we've already seen a
2956 // linkonce section with this signature. Record that we've seen
2957 // a section group, and don't include this section group.
2958 ins.first->second.group_ = true;
2959 return false;
2961 else
2963 // We've already seen a linkonce section and this is a linkonce
2964 // section. These don't block each other--this may be the same
2965 // symbol name with different section types.
2966 return true;
2970 // Find the given comdat signature, and return the object and section
2971 // index of the kept group.
2972 Relobj*
2973 Layout::find_kept_object(const std::string& signature,
2974 unsigned int* pshndx) const
2976 Signatures::const_iterator p = this->signatures_.find(signature);
2977 if (p == this->signatures_.end())
2978 return NULL;
2979 if (pshndx != NULL)
2980 *pshndx = p->second.shndx_;
2981 return p->second.object_;
2984 // Store the allocated sections into the section list.
2986 void
2987 Layout::get_allocated_sections(Section_list* section_list) const
2989 for (Section_list::const_iterator p = this->section_list_.begin();
2990 p != this->section_list_.end();
2991 ++p)
2992 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2993 section_list->push_back(*p);
2996 // Create an output segment.
2998 Output_segment*
2999 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3001 gold_assert(!parameters->options().relocatable());
3002 Output_segment* oseg = new Output_segment(type, flags);
3003 this->segment_list_.push_back(oseg);
3005 if (type == elfcpp::PT_TLS)
3006 this->tls_segment_ = oseg;
3007 else if (type == elfcpp::PT_GNU_RELRO)
3008 this->relro_segment_ = oseg;
3010 return oseg;
3013 // Write out the Output_sections. Most won't have anything to write,
3014 // since most of the data will come from input sections which are
3015 // handled elsewhere. But some Output_sections do have Output_data.
3017 void
3018 Layout::write_output_sections(Output_file* of) const
3020 for (Section_list::const_iterator p = this->section_list_.begin();
3021 p != this->section_list_.end();
3022 ++p)
3024 if (!(*p)->after_input_sections())
3025 (*p)->write(of);
3029 // Write out data not associated with a section or the symbol table.
3031 void
3032 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
3034 if (!parameters->options().strip_all())
3036 const Output_section* symtab_section = this->symtab_section_;
3037 for (Section_list::const_iterator p = this->section_list_.begin();
3038 p != this->section_list_.end();
3039 ++p)
3041 if ((*p)->needs_symtab_index())
3043 gold_assert(symtab_section != NULL);
3044 unsigned int index = (*p)->symtab_index();
3045 gold_assert(index > 0 && index != -1U);
3046 off_t off = (symtab_section->offset()
3047 + index * symtab_section->entsize());
3048 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3053 const Output_section* dynsym_section = this->dynsym_section_;
3054 for (Section_list::const_iterator p = this->section_list_.begin();
3055 p != this->section_list_.end();
3056 ++p)
3058 if ((*p)->needs_dynsym_index())
3060 gold_assert(dynsym_section != NULL);
3061 unsigned int index = (*p)->dynsym_index();
3062 gold_assert(index > 0 && index != -1U);
3063 off_t off = (dynsym_section->offset()
3064 + index * dynsym_section->entsize());
3065 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3069 // Write out the Output_data which are not in an Output_section.
3070 for (Data_list::const_iterator p = this->special_output_list_.begin();
3071 p != this->special_output_list_.end();
3072 ++p)
3073 (*p)->write(of);
3076 // Write out the Output_sections which can only be written after the
3077 // input sections are complete.
3079 void
3080 Layout::write_sections_after_input_sections(Output_file* of)
3082 // Determine the final section offsets, and thus the final output
3083 // file size. Note we finalize the .shstrab last, to allow the
3084 // after_input_section sections to modify their section-names before
3085 // writing.
3086 if (this->any_postprocessing_sections_)
3088 off_t off = this->output_file_size_;
3089 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3091 // Now that we've finalized the names, we can finalize the shstrab.
3092 off =
3093 this->set_section_offsets(off,
3094 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3096 if (off > this->output_file_size_)
3098 of->resize(off);
3099 this->output_file_size_ = off;
3103 for (Section_list::const_iterator p = this->section_list_.begin();
3104 p != this->section_list_.end();
3105 ++p)
3107 if ((*p)->after_input_sections())
3108 (*p)->write(of);
3111 this->section_headers_->write(of);
3114 // If the build ID requires computing a checksum, do so here, and
3115 // write it out. We compute a checksum over the entire file because
3116 // that is simplest.
3118 void
3119 Layout::write_build_id(Output_file* of) const
3121 if (this->build_id_note_ == NULL)
3122 return;
3124 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3126 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3127 this->build_id_note_->data_size());
3129 const char* style = parameters->options().build_id();
3130 if (strcmp(style, "sha1") == 0)
3132 sha1_ctx ctx;
3133 sha1_init_ctx(&ctx);
3134 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3135 sha1_finish_ctx(&ctx, ov);
3137 else if (strcmp(style, "md5") == 0)
3139 md5_ctx ctx;
3140 md5_init_ctx(&ctx);
3141 md5_process_bytes(iv, this->output_file_size_, &ctx);
3142 md5_finish_ctx(&ctx, ov);
3144 else
3145 gold_unreachable();
3147 of->write_output_view(this->build_id_note_->offset(),
3148 this->build_id_note_->data_size(),
3149 ov);
3151 of->free_input_view(0, this->output_file_size_, iv);
3154 // Write out a binary file. This is called after the link is
3155 // complete. IN is the temporary output file we used to generate the
3156 // ELF code. We simply walk through the segments, read them from
3157 // their file offset in IN, and write them to their load address in
3158 // the output file. FIXME: with a bit more work, we could support
3159 // S-records and/or Intel hex format here.
3161 void
3162 Layout::write_binary(Output_file* in) const
3164 gold_assert(this->options_.oformat_enum()
3165 == General_options::OBJECT_FORMAT_BINARY);
3167 // Get the size of the binary file.
3168 uint64_t max_load_address = 0;
3169 for (Segment_list::const_iterator p = this->segment_list_.begin();
3170 p != this->segment_list_.end();
3171 ++p)
3173 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3175 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3176 if (max_paddr > max_load_address)
3177 max_load_address = max_paddr;
3181 Output_file out(parameters->options().output_file_name());
3182 out.open(max_load_address);
3184 for (Segment_list::const_iterator p = this->segment_list_.begin();
3185 p != this->segment_list_.end();
3186 ++p)
3188 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3190 const unsigned char* vin = in->get_input_view((*p)->offset(),
3191 (*p)->filesz());
3192 unsigned char* vout = out.get_output_view((*p)->paddr(),
3193 (*p)->filesz());
3194 memcpy(vout, vin, (*p)->filesz());
3195 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3196 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3200 out.close();
3203 // Print the output sections to the map file.
3205 void
3206 Layout::print_to_mapfile(Mapfile* mapfile) const
3208 for (Segment_list::const_iterator p = this->segment_list_.begin();
3209 p != this->segment_list_.end();
3210 ++p)
3211 (*p)->print_sections_to_mapfile(mapfile);
3214 // Print statistical information to stderr. This is used for --stats.
3216 void
3217 Layout::print_stats() const
3219 this->namepool_.print_stats("section name pool");
3220 this->sympool_.print_stats("output symbol name pool");
3221 this->dynpool_.print_stats("dynamic name pool");
3223 for (Section_list::const_iterator p = this->section_list_.begin();
3224 p != this->section_list_.end();
3225 ++p)
3226 (*p)->print_merge_stats();
3229 // Write_sections_task methods.
3231 // We can always run this task.
3233 Task_token*
3234 Write_sections_task::is_runnable()
3236 return NULL;
3239 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3240 // when finished.
3242 void
3243 Write_sections_task::locks(Task_locker* tl)
3245 tl->add(this, this->output_sections_blocker_);
3246 tl->add(this, this->final_blocker_);
3249 // Run the task--write out the data.
3251 void
3252 Write_sections_task::run(Workqueue*)
3254 this->layout_->write_output_sections(this->of_);
3257 // Write_data_task methods.
3259 // We can always run this task.
3261 Task_token*
3262 Write_data_task::is_runnable()
3264 return NULL;
3267 // We need to unlock FINAL_BLOCKER when finished.
3269 void
3270 Write_data_task::locks(Task_locker* tl)
3272 tl->add(this, this->final_blocker_);
3275 // Run the task--write out the data.
3277 void
3278 Write_data_task::run(Workqueue*)
3280 this->layout_->write_data(this->symtab_, this->of_);
3283 // Write_symbols_task methods.
3285 // We can always run this task.
3287 Task_token*
3288 Write_symbols_task::is_runnable()
3290 return NULL;
3293 // We need to unlock FINAL_BLOCKER when finished.
3295 void
3296 Write_symbols_task::locks(Task_locker* tl)
3298 tl->add(this, this->final_blocker_);
3301 // Run the task--write out the symbols.
3303 void
3304 Write_symbols_task::run(Workqueue*)
3306 this->symtab_->write_globals(this->input_objects_, this->sympool_,
3307 this->dynpool_, this->layout_->symtab_xindex(),
3308 this->layout_->dynsym_xindex(), this->of_);
3311 // Write_after_input_sections_task methods.
3313 // We can only run this task after the input sections have completed.
3315 Task_token*
3316 Write_after_input_sections_task::is_runnable()
3318 if (this->input_sections_blocker_->is_blocked())
3319 return this->input_sections_blocker_;
3320 return NULL;
3323 // We need to unlock FINAL_BLOCKER when finished.
3325 void
3326 Write_after_input_sections_task::locks(Task_locker* tl)
3328 tl->add(this, this->final_blocker_);
3331 // Run the task.
3333 void
3334 Write_after_input_sections_task::run(Workqueue*)
3336 this->layout_->write_sections_after_input_sections(this->of_);
3339 // Close_task_runner methods.
3341 // Run the task--close the file.
3343 void
3344 Close_task_runner::run(Workqueue*, const Task*)
3346 // If we need to compute a checksum for the BUILD if, we do so here.
3347 this->layout_->write_build_id(this->of_);
3349 // If we've been asked to create a binary file, we do so here.
3350 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3351 this->layout_->write_binary(this->of_);
3353 this->of_->close();
3356 // Instantiate the templates we need. We could use the configure
3357 // script to restrict this to only the ones for implemented targets.
3359 #ifdef HAVE_TARGET_32_LITTLE
3360 template
3361 Output_section*
3362 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3363 const char* name,
3364 const elfcpp::Shdr<32, false>& shdr,
3365 unsigned int, unsigned int, off_t*);
3366 #endif
3368 #ifdef HAVE_TARGET_32_BIG
3369 template
3370 Output_section*
3371 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3372 const char* name,
3373 const elfcpp::Shdr<32, true>& shdr,
3374 unsigned int, unsigned int, off_t*);
3375 #endif
3377 #ifdef HAVE_TARGET_64_LITTLE
3378 template
3379 Output_section*
3380 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3381 const char* name,
3382 const elfcpp::Shdr<64, false>& shdr,
3383 unsigned int, unsigned int, off_t*);
3384 #endif
3386 #ifdef HAVE_TARGET_64_BIG
3387 template
3388 Output_section*
3389 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3390 const char* name,
3391 const elfcpp::Shdr<64, true>& shdr,
3392 unsigned int, unsigned int, off_t*);
3393 #endif
3395 #ifdef HAVE_TARGET_32_LITTLE
3396 template
3397 Output_section*
3398 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3399 unsigned int reloc_shndx,
3400 const elfcpp::Shdr<32, false>& shdr,
3401 Output_section* data_section,
3402 Relocatable_relocs* rr);
3403 #endif
3405 #ifdef HAVE_TARGET_32_BIG
3406 template
3407 Output_section*
3408 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3409 unsigned int reloc_shndx,
3410 const elfcpp::Shdr<32, true>& shdr,
3411 Output_section* data_section,
3412 Relocatable_relocs* rr);
3413 #endif
3415 #ifdef HAVE_TARGET_64_LITTLE
3416 template
3417 Output_section*
3418 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3419 unsigned int reloc_shndx,
3420 const elfcpp::Shdr<64, false>& shdr,
3421 Output_section* data_section,
3422 Relocatable_relocs* rr);
3423 #endif
3425 #ifdef HAVE_TARGET_64_BIG
3426 template
3427 Output_section*
3428 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3429 unsigned int reloc_shndx,
3430 const elfcpp::Shdr<64, true>& shdr,
3431 Output_section* data_section,
3432 Relocatable_relocs* rr);
3433 #endif
3435 #ifdef HAVE_TARGET_32_LITTLE
3436 template
3437 void
3438 Layout::layout_group<32, false>(Symbol_table* symtab,
3439 Sized_relobj<32, false>* object,
3440 unsigned int,
3441 const char* group_section_name,
3442 const char* signature,
3443 const elfcpp::Shdr<32, false>& shdr,
3444 elfcpp::Elf_Word flags,
3445 std::vector<unsigned int>* shndxes);
3446 #endif
3448 #ifdef HAVE_TARGET_32_BIG
3449 template
3450 void
3451 Layout::layout_group<32, true>(Symbol_table* symtab,
3452 Sized_relobj<32, true>* object,
3453 unsigned int,
3454 const char* group_section_name,
3455 const char* signature,
3456 const elfcpp::Shdr<32, true>& shdr,
3457 elfcpp::Elf_Word flags,
3458 std::vector<unsigned int>* shndxes);
3459 #endif
3461 #ifdef HAVE_TARGET_64_LITTLE
3462 template
3463 void
3464 Layout::layout_group<64, false>(Symbol_table* symtab,
3465 Sized_relobj<64, false>* object,
3466 unsigned int,
3467 const char* group_section_name,
3468 const char* signature,
3469 const elfcpp::Shdr<64, false>& shdr,
3470 elfcpp::Elf_Word flags,
3471 std::vector<unsigned int>* shndxes);
3472 #endif
3474 #ifdef HAVE_TARGET_64_BIG
3475 template
3476 void
3477 Layout::layout_group<64, true>(Symbol_table* symtab,
3478 Sized_relobj<64, true>* object,
3479 unsigned int,
3480 const char* group_section_name,
3481 const char* signature,
3482 const elfcpp::Shdr<64, true>& shdr,
3483 elfcpp::Elf_Word flags,
3484 std::vector<unsigned int>* shndxes);
3485 #endif
3487 #ifdef HAVE_TARGET_32_LITTLE
3488 template
3489 Output_section*
3490 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3491 const unsigned char* symbols,
3492 off_t symbols_size,
3493 const unsigned char* symbol_names,
3494 off_t symbol_names_size,
3495 unsigned int shndx,
3496 const elfcpp::Shdr<32, false>& shdr,
3497 unsigned int reloc_shndx,
3498 unsigned int reloc_type,
3499 off_t* off);
3500 #endif
3502 #ifdef HAVE_TARGET_32_BIG
3503 template
3504 Output_section*
3505 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3506 const unsigned char* symbols,
3507 off_t symbols_size,
3508 const unsigned char* symbol_names,
3509 off_t symbol_names_size,
3510 unsigned int shndx,
3511 const elfcpp::Shdr<32, true>& shdr,
3512 unsigned int reloc_shndx,
3513 unsigned int reloc_type,
3514 off_t* off);
3515 #endif
3517 #ifdef HAVE_TARGET_64_LITTLE
3518 template
3519 Output_section*
3520 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3521 const unsigned char* symbols,
3522 off_t symbols_size,
3523 const unsigned char* symbol_names,
3524 off_t symbol_names_size,
3525 unsigned int shndx,
3526 const elfcpp::Shdr<64, false>& shdr,
3527 unsigned int reloc_shndx,
3528 unsigned int reloc_type,
3529 off_t* off);
3530 #endif
3532 #ifdef HAVE_TARGET_64_BIG
3533 template
3534 Output_section*
3535 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
3536 const unsigned char* symbols,
3537 off_t symbols_size,
3538 const unsigned char* symbol_names,
3539 off_t symbol_names_size,
3540 unsigned int shndx,
3541 const elfcpp::Shdr<64, true>& shdr,
3542 unsigned int reloc_shndx,
3543 unsigned int reloc_type,
3544 off_t* off);
3545 #endif
3547 } // End namespace gold.