* elf.c (bfd_elf_get_elf_syms): Don't leak memory on error.
[binutils.git] / gold / layout.cc
bloba08ec72193799af5645909454f774c00f6bfeb2a
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->tls_segment_ = this->make_output_segment(elfcpp::PT_TLS,
925 seg_flags);
926 this->tls_segment_->add_output_section(os, seg_flags);
929 // If -z relro is in effect, and we see a relro section, we create a
930 // PT_GNU_RELRO segment. There can only be one such segment.
931 if (os->is_relro() && parameters->options().relro())
933 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
934 if (this->relro_segment_ == NULL)
935 this->relro_segment_ = this->make_output_segment(elfcpp::PT_GNU_RELRO,
936 seg_flags);
937 this->relro_segment_->add_output_section(os, seg_flags);
941 // Make an output section for a script.
943 Output_section*
944 Layout::make_output_section_for_script(const char* name)
946 name = this->namepool_.add(name, false, NULL);
947 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
948 elfcpp::SHF_ALLOC);
949 os->set_found_in_sections_clause();
950 return os;
953 // Return the number of segments we expect to see.
955 size_t
956 Layout::expected_segment_count() const
958 size_t ret = this->segment_list_.size();
960 // If we didn't see a SECTIONS clause in a linker script, we should
961 // already have the complete list of segments. Otherwise we ask the
962 // SECTIONS clause how many segments it expects, and add in the ones
963 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
965 if (!this->script_options_->saw_sections_clause())
966 return ret;
967 else
969 const Script_sections* ss = this->script_options_->script_sections();
970 return ret + ss->expected_segment_count(this);
974 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
975 // is whether we saw a .note.GNU-stack section in the object file.
976 // GNU_STACK_FLAGS is the section flags. The flags give the
977 // protection required for stack memory. We record this in an
978 // executable as a PT_GNU_STACK segment. If an object file does not
979 // have a .note.GNU-stack segment, we must assume that it is an old
980 // object. On some targets that will force an executable stack.
982 void
983 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
985 if (!seen_gnu_stack)
986 this->input_without_gnu_stack_note_ = true;
987 else
989 this->input_with_gnu_stack_note_ = true;
990 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
991 this->input_requires_executable_stack_ = true;
995 // Create the dynamic sections which are needed before we read the
996 // relocs.
998 void
999 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1001 if (parameters->doing_static_link())
1002 return;
1004 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1005 elfcpp::SHT_DYNAMIC,
1006 (elfcpp::SHF_ALLOC
1007 | elfcpp::SHF_WRITE),
1008 false);
1009 this->dynamic_section_->set_is_relro();
1011 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
1012 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1013 elfcpp::STV_HIDDEN, 0, false, false);
1015 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1017 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1020 // For each output section whose name can be represented as C symbol,
1021 // define __start and __stop symbols for the section. This is a GNU
1022 // extension.
1024 void
1025 Layout::define_section_symbols(Symbol_table* symtab)
1027 for (Section_list::const_iterator p = this->section_list_.begin();
1028 p != this->section_list_.end();
1029 ++p)
1031 const char* const name = (*p)->name();
1032 if (name[strspn(name,
1033 ("0123456789"
1034 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1035 "abcdefghijklmnopqrstuvwxyz"
1036 "_"))]
1037 == '\0')
1039 const std::string name_string(name);
1040 const std::string start_name("__start_" + name_string);
1041 const std::string stop_name("__stop_" + name_string);
1043 symtab->define_in_output_data(start_name.c_str(),
1044 NULL, // version
1046 0, // value
1047 0, // symsize
1048 elfcpp::STT_NOTYPE,
1049 elfcpp::STB_GLOBAL,
1050 elfcpp::STV_DEFAULT,
1051 0, // nonvis
1052 false, // offset_is_from_end
1053 true); // only_if_ref
1055 symtab->define_in_output_data(stop_name.c_str(),
1056 NULL, // version
1058 0, // value
1059 0, // symsize
1060 elfcpp::STT_NOTYPE,
1061 elfcpp::STB_GLOBAL,
1062 elfcpp::STV_DEFAULT,
1063 0, // nonvis
1064 true, // offset_is_from_end
1065 true); // only_if_ref
1070 // Define symbols for group signatures.
1072 void
1073 Layout::define_group_signatures(Symbol_table* symtab)
1075 for (Group_signatures::iterator p = this->group_signatures_.begin();
1076 p != this->group_signatures_.end();
1077 ++p)
1079 Symbol* sym = symtab->lookup(p->signature, NULL);
1080 if (sym != NULL)
1081 p->section->set_info_symndx(sym);
1082 else
1084 // Force the name of the group section to the group
1085 // signature, and use the group's section symbol as the
1086 // signature symbol.
1087 if (strcmp(p->section->name(), p->signature) != 0)
1089 const char* name = this->namepool_.add(p->signature,
1090 true, NULL);
1091 p->section->set_name(name);
1093 p->section->set_needs_symtab_index();
1094 p->section->set_info_section_symndx(p->section);
1098 this->group_signatures_.clear();
1101 // Find the first read-only PT_LOAD segment, creating one if
1102 // necessary.
1104 Output_segment*
1105 Layout::find_first_load_seg()
1107 for (Segment_list::const_iterator p = this->segment_list_.begin();
1108 p != this->segment_list_.end();
1109 ++p)
1111 if ((*p)->type() == elfcpp::PT_LOAD
1112 && ((*p)->flags() & elfcpp::PF_R) != 0
1113 && (parameters->options().omagic()
1114 || ((*p)->flags() & elfcpp::PF_W) == 0))
1115 return *p;
1118 gold_assert(!this->script_options_->saw_phdrs_clause());
1120 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1121 elfcpp::PF_R);
1122 return load_seg;
1125 // Finalize the layout. When this is called, we have created all the
1126 // output sections and all the output segments which are based on
1127 // input sections. We have several things to do, and we have to do
1128 // them in the right order, so that we get the right results correctly
1129 // and efficiently.
1131 // 1) Finalize the list of output segments and create the segment
1132 // table header.
1134 // 2) Finalize the dynamic symbol table and associated sections.
1136 // 3) Determine the final file offset of all the output segments.
1138 // 4) Determine the final file offset of all the SHF_ALLOC output
1139 // sections.
1141 // 5) Create the symbol table sections and the section name table
1142 // section.
1144 // 6) Finalize the symbol table: set symbol values to their final
1145 // value and make a final determination of which symbols are going
1146 // into the output symbol table.
1148 // 7) Create the section table header.
1150 // 8) Determine the final file offset of all the output sections which
1151 // are not SHF_ALLOC, including the section table header.
1153 // 9) Finalize the ELF file header.
1155 // This function returns the size of the output file.
1157 off_t
1158 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1159 Target* target, const Task* task)
1161 target->finalize_sections(this);
1163 this->count_local_symbols(task, input_objects);
1165 this->create_gold_note();
1166 this->create_executable_stack_info(target);
1167 this->create_build_id();
1169 Output_segment* phdr_seg = NULL;
1170 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1172 // There was a dynamic object in the link. We need to create
1173 // some information for the dynamic linker.
1175 // Create the PT_PHDR segment which will hold the program
1176 // headers.
1177 if (!this->script_options_->saw_phdrs_clause())
1178 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1180 // Create the dynamic symbol table, including the hash table.
1181 Output_section* dynstr;
1182 std::vector<Symbol*> dynamic_symbols;
1183 unsigned int local_dynamic_count;
1184 Versions versions(*this->script_options()->version_script_info(),
1185 &this->dynpool_);
1186 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1187 &local_dynamic_count, &dynamic_symbols,
1188 &versions);
1190 // Create the .interp section to hold the name of the
1191 // interpreter, and put it in a PT_INTERP segment.
1192 if (!parameters->options().shared())
1193 this->create_interp(target);
1195 // Finish the .dynamic section to hold the dynamic data, and put
1196 // it in a PT_DYNAMIC segment.
1197 this->finish_dynamic_section(input_objects, symtab);
1199 // We should have added everything we need to the dynamic string
1200 // table.
1201 this->dynpool_.set_string_offsets();
1203 // Create the version sections. We can't do this until the
1204 // dynamic string table is complete.
1205 this->create_version_sections(&versions, symtab, local_dynamic_count,
1206 dynamic_symbols, dynstr);
1209 // If there is a SECTIONS clause, put all the input sections into
1210 // the required order.
1211 Output_segment* load_seg;
1212 if (this->script_options_->saw_sections_clause())
1213 load_seg = this->set_section_addresses_from_script(symtab);
1214 else if (parameters->options().relocatable())
1215 load_seg = NULL;
1216 else
1217 load_seg = this->find_first_load_seg();
1219 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
1220 load_seg = NULL;
1222 gold_assert(phdr_seg == NULL || load_seg != NULL);
1224 // Lay out the segment headers.
1225 Output_segment_headers* segment_headers;
1226 if (parameters->options().relocatable())
1227 segment_headers = NULL;
1228 else
1230 segment_headers = new Output_segment_headers(this->segment_list_);
1231 if (load_seg != NULL)
1232 load_seg->add_initial_output_data(segment_headers);
1233 if (phdr_seg != NULL)
1234 phdr_seg->add_initial_output_data(segment_headers);
1237 // Lay out the file header.
1238 Output_file_header* file_header;
1239 file_header = new Output_file_header(target, symtab, segment_headers,
1240 this->options_.entry());
1241 if (load_seg != NULL)
1242 load_seg->add_initial_output_data(file_header);
1244 this->special_output_list_.push_back(file_header);
1245 if (segment_headers != NULL)
1246 this->special_output_list_.push_back(segment_headers);
1248 if (this->script_options_->saw_phdrs_clause()
1249 && !parameters->options().relocatable())
1251 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1252 // clause in a linker script.
1253 Script_sections* ss = this->script_options_->script_sections();
1254 ss->put_headers_in_phdrs(file_header, segment_headers);
1257 // We set the output section indexes in set_segment_offsets and
1258 // set_section_indexes.
1259 unsigned int shndx = 1;
1261 // Set the file offsets of all the segments, and all the sections
1262 // they contain.
1263 off_t off;
1264 if (!parameters->options().relocatable())
1265 off = this->set_segment_offsets(target, load_seg, &shndx);
1266 else
1267 off = this->set_relocatable_section_offsets(file_header, &shndx);
1269 // Set the file offsets of all the non-data sections we've seen so
1270 // far which don't have to wait for the input sections. We need
1271 // this in order to finalize local symbols in non-allocated
1272 // sections.
1273 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1275 // Set the section indexes of all unallocated sections seen so far,
1276 // in case any of them are somehow referenced by a symbol.
1277 shndx = this->set_section_indexes(shndx);
1279 // Create the symbol table sections.
1280 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1281 if (!parameters->doing_static_link())
1282 this->assign_local_dynsym_offsets(input_objects);
1284 // Process any symbol assignments from a linker script. This must
1285 // be called after the symbol table has been finalized.
1286 this->script_options_->finalize_symbols(symtab, this);
1288 // Create the .shstrtab section.
1289 Output_section* shstrtab_section = this->create_shstrtab();
1291 // Set the file offsets of the rest of the non-data sections which
1292 // don't have to wait for the input sections.
1293 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1295 // Now that all sections have been created, set the section indexes
1296 // for any sections which haven't been done yet.
1297 shndx = this->set_section_indexes(shndx);
1299 // Create the section table header.
1300 this->create_shdrs(shstrtab_section, &off);
1302 // If there are no sections which require postprocessing, we can
1303 // handle the section names now, and avoid a resize later.
1304 if (!this->any_postprocessing_sections_)
1305 off = this->set_section_offsets(off,
1306 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1308 file_header->set_section_info(this->section_headers_, shstrtab_section);
1310 // Now we know exactly where everything goes in the output file
1311 // (except for non-allocated sections which require postprocessing).
1312 Output_data::layout_complete();
1314 this->output_file_size_ = off;
1316 return off;
1319 // Create a note header following the format defined in the ELF ABI.
1320 // NAME is the name, NOTE_TYPE is the type, DESCSZ is the size of the
1321 // descriptor. ALLOCATE is true if the section should be allocated in
1322 // memory. This returns the new note section. It sets
1323 // *TRAILING_PADDING to the number of trailing zero bytes required.
1325 Output_section*
1326 Layout::create_note(const char* name, int note_type, size_t descsz,
1327 bool allocate, size_t* trailing_padding)
1329 // Authorities all agree that the values in a .note field should
1330 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1331 // they differ on what the alignment is for 64-bit binaries.
1332 // The GABI says unambiguously they take 8-byte alignment:
1333 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1334 // Other documentation says alignment should always be 4 bytes:
1335 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1336 // GNU ld and GNU readelf both support the latter (at least as of
1337 // version 2.16.91), and glibc always generates the latter for
1338 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1339 // here.
1340 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1341 const int size = parameters->target().get_size();
1342 #else
1343 const int size = 32;
1344 #endif
1346 // The contents of the .note section.
1347 size_t namesz = strlen(name) + 1;
1348 size_t aligned_namesz = align_address(namesz, size / 8);
1349 size_t aligned_descsz = align_address(descsz, size / 8);
1351 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1353 unsigned char* buffer = new unsigned char[notehdrsz];
1354 memset(buffer, 0, notehdrsz);
1356 bool is_big_endian = parameters->target().is_big_endian();
1358 if (size == 32)
1360 if (!is_big_endian)
1362 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1363 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1364 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1366 else
1368 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1369 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1370 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1373 else if (size == 64)
1375 if (!is_big_endian)
1377 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1378 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1379 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1381 else
1383 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1384 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1385 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1388 else
1389 gold_unreachable();
1391 memcpy(buffer + 3 * (size / 8), name, namesz);
1393 const char* note_name = this->namepool_.add(".note", false, NULL);
1394 elfcpp::Elf_Xword flags = 0;
1395 if (allocate)
1396 flags = elfcpp::SHF_ALLOC;
1397 Output_section* os = this->make_output_section(note_name,
1398 elfcpp::SHT_NOTE,
1399 flags);
1400 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1401 size / 8,
1402 "** note header");
1403 os->add_output_section_data(posd);
1405 *trailing_padding = aligned_descsz - descsz;
1407 return os;
1410 // For an executable or shared library, create a note to record the
1411 // version of gold used to create the binary.
1413 void
1414 Layout::create_gold_note()
1416 if (parameters->options().relocatable())
1417 return;
1419 std::string desc = std::string("gold ") + gold::get_version_string();
1421 size_t trailing_padding;
1422 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1423 desc.size(), false, &trailing_padding);
1425 Output_section_data* posd = new Output_data_const(desc, 4);
1426 os->add_output_section_data(posd);
1428 if (trailing_padding > 0)
1430 posd = new Output_data_zero_fill(trailing_padding, 0);
1431 os->add_output_section_data(posd);
1435 // Record whether the stack should be executable. This can be set
1436 // from the command line using the -z execstack or -z noexecstack
1437 // options. Otherwise, if any input file has a .note.GNU-stack
1438 // section with the SHF_EXECINSTR flag set, the stack should be
1439 // executable. Otherwise, if at least one input file a
1440 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1441 // section, we use the target default for whether the stack should be
1442 // executable. Otherwise, we don't generate a stack note. When
1443 // generating a object file, we create a .note.GNU-stack section with
1444 // the appropriate marking. When generating an executable or shared
1445 // library, we create a PT_GNU_STACK segment.
1447 void
1448 Layout::create_executable_stack_info(const Target* target)
1450 bool is_stack_executable;
1451 if (this->options_.is_execstack_set())
1452 is_stack_executable = this->options_.is_stack_executable();
1453 else if (!this->input_with_gnu_stack_note_)
1454 return;
1455 else
1457 if (this->input_requires_executable_stack_)
1458 is_stack_executable = true;
1459 else if (this->input_without_gnu_stack_note_)
1460 is_stack_executable = target->is_default_stack_executable();
1461 else
1462 is_stack_executable = false;
1465 if (parameters->options().relocatable())
1467 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1468 elfcpp::Elf_Xword flags = 0;
1469 if (is_stack_executable)
1470 flags |= elfcpp::SHF_EXECINSTR;
1471 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1473 else
1475 if (this->script_options_->saw_phdrs_clause())
1476 return;
1477 int flags = elfcpp::PF_R | elfcpp::PF_W;
1478 if (is_stack_executable)
1479 flags |= elfcpp::PF_X;
1480 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1484 // If --build-id was used, set up the build ID note.
1486 void
1487 Layout::create_build_id()
1489 if (!parameters->options().user_set_build_id())
1490 return;
1492 const char* style = parameters->options().build_id();
1493 if (strcmp(style, "none") == 0)
1494 return;
1496 // Set DESCSZ to the size of the note descriptor. When possible,
1497 // set DESC to the note descriptor contents.
1498 size_t descsz;
1499 std::string desc;
1500 if (strcmp(style, "md5") == 0)
1501 descsz = 128 / 8;
1502 else if (strcmp(style, "sha1") == 0)
1503 descsz = 160 / 8;
1504 else if (strcmp(style, "uuid") == 0)
1506 const size_t uuidsz = 128 / 8;
1508 char buffer[uuidsz];
1509 memset(buffer, 0, uuidsz);
1511 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
1512 if (descriptor < 0)
1513 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1514 strerror(errno));
1515 else
1517 ssize_t got = ::read(descriptor, buffer, uuidsz);
1518 release_descriptor(descriptor, true);
1519 if (got < 0)
1520 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1521 else if (static_cast<size_t>(got) != uuidsz)
1522 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1523 uuidsz, got);
1526 desc.assign(buffer, uuidsz);
1527 descsz = uuidsz;
1529 else if (strncmp(style, "0x", 2) == 0)
1531 hex_init();
1532 const char* p = style + 2;
1533 while (*p != '\0')
1535 if (hex_p(p[0]) && hex_p(p[1]))
1537 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1538 desc += c;
1539 p += 2;
1541 else if (*p == '-' || *p == ':')
1542 ++p;
1543 else
1544 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1545 style);
1547 descsz = desc.size();
1549 else
1550 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1552 // Create the note.
1553 size_t trailing_padding;
1554 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1555 descsz, true, &trailing_padding);
1557 if (!desc.empty())
1559 // We know the value already, so we fill it in now.
1560 gold_assert(desc.size() == descsz);
1562 Output_section_data* posd = new Output_data_const(desc, 4);
1563 os->add_output_section_data(posd);
1565 if (trailing_padding != 0)
1567 posd = new Output_data_zero_fill(trailing_padding, 0);
1568 os->add_output_section_data(posd);
1571 else
1573 // We need to compute a checksum after we have completed the
1574 // link.
1575 gold_assert(trailing_padding == 0);
1576 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
1577 os->add_output_section_data(this->build_id_note_);
1578 os->set_after_input_sections();
1582 // Return whether SEG1 should be before SEG2 in the output file. This
1583 // is based entirely on the segment type and flags. When this is
1584 // called the segment addresses has normally not yet been set.
1586 bool
1587 Layout::segment_precedes(const Output_segment* seg1,
1588 const Output_segment* seg2)
1590 elfcpp::Elf_Word type1 = seg1->type();
1591 elfcpp::Elf_Word type2 = seg2->type();
1593 // The single PT_PHDR segment is required to precede any loadable
1594 // segment. We simply make it always first.
1595 if (type1 == elfcpp::PT_PHDR)
1597 gold_assert(type2 != elfcpp::PT_PHDR);
1598 return true;
1600 if (type2 == elfcpp::PT_PHDR)
1601 return false;
1603 // The single PT_INTERP segment is required to precede any loadable
1604 // segment. We simply make it always second.
1605 if (type1 == elfcpp::PT_INTERP)
1607 gold_assert(type2 != elfcpp::PT_INTERP);
1608 return true;
1610 if (type2 == elfcpp::PT_INTERP)
1611 return false;
1613 // We then put PT_LOAD segments before any other segments.
1614 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1615 return true;
1616 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1617 return false;
1619 // We put the PT_TLS segment last except for the PT_GNU_RELRO
1620 // segment, because that is where the dynamic linker expects to find
1621 // it (this is just for efficiency; other positions would also work
1622 // correctly).
1623 if (type1 == elfcpp::PT_TLS
1624 && type2 != elfcpp::PT_TLS
1625 && type2 != elfcpp::PT_GNU_RELRO)
1626 return false;
1627 if (type2 == elfcpp::PT_TLS
1628 && type1 != elfcpp::PT_TLS
1629 && type1 != elfcpp::PT_GNU_RELRO)
1630 return true;
1632 // We put the PT_GNU_RELRO segment last, because that is where the
1633 // dynamic linker expects to find it (as with PT_TLS, this is just
1634 // for efficiency).
1635 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
1636 return false;
1637 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
1638 return true;
1640 const elfcpp::Elf_Word flags1 = seg1->flags();
1641 const elfcpp::Elf_Word flags2 = seg2->flags();
1643 // The order of non-PT_LOAD segments is unimportant. We simply sort
1644 // by the numeric segment type and flags values. There should not
1645 // be more than one segment with the same type and flags.
1646 if (type1 != elfcpp::PT_LOAD)
1648 if (type1 != type2)
1649 return type1 < type2;
1650 gold_assert(flags1 != flags2);
1651 return flags1 < flags2;
1654 // If the addresses are set already, sort by load address.
1655 if (seg1->are_addresses_set())
1657 if (!seg2->are_addresses_set())
1658 return true;
1660 unsigned int section_count1 = seg1->output_section_count();
1661 unsigned int section_count2 = seg2->output_section_count();
1662 if (section_count1 == 0 && section_count2 > 0)
1663 return true;
1664 if (section_count1 > 0 && section_count2 == 0)
1665 return false;
1667 uint64_t paddr1 = seg1->first_section_load_address();
1668 uint64_t paddr2 = seg2->first_section_load_address();
1669 if (paddr1 != paddr2)
1670 return paddr1 < paddr2;
1672 else if (seg2->are_addresses_set())
1673 return false;
1675 // We sort PT_LOAD segments based on the flags. Readonly segments
1676 // come before writable segments. Then writable segments with data
1677 // come before writable segments without data. Then executable
1678 // segments come before non-executable segments. Then the unlikely
1679 // case of a non-readable segment comes before the normal case of a
1680 // readable segment. If there are multiple segments with the same
1681 // type and flags, we require that the address be set, and we sort
1682 // by virtual address and then physical address.
1683 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1684 return (flags1 & elfcpp::PF_W) == 0;
1685 if ((flags1 & elfcpp::PF_W) != 0
1686 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
1687 return seg1->has_any_data_sections();
1688 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1689 return (flags1 & elfcpp::PF_X) != 0;
1690 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1691 return (flags1 & elfcpp::PF_R) == 0;
1693 // We shouldn't get here--we shouldn't create segments which we
1694 // can't distinguish.
1695 gold_unreachable();
1698 // Set the file offsets of all the segments, and all the sections they
1699 // contain. They have all been created. LOAD_SEG must be be laid out
1700 // first. Return the offset of the data to follow.
1702 off_t
1703 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1704 unsigned int *pshndx)
1706 // Sort them into the final order.
1707 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1708 Layout::Compare_segments());
1710 // Find the PT_LOAD segments, and set their addresses and offsets
1711 // and their section's addresses and offsets.
1712 uint64_t addr;
1713 if (this->options_.user_set_Ttext())
1714 addr = this->options_.Ttext();
1715 else if (parameters->options().shared())
1716 addr = 0;
1717 else
1718 addr = target->default_text_segment_address();
1719 off_t off = 0;
1721 // If LOAD_SEG is NULL, then the file header and segment headers
1722 // will not be loadable. But they still need to be at offset 0 in
1723 // the file. Set their offsets now.
1724 if (load_seg == NULL)
1726 for (Data_list::iterator p = this->special_output_list_.begin();
1727 p != this->special_output_list_.end();
1728 ++p)
1730 off = align_address(off, (*p)->addralign());
1731 (*p)->set_address_and_file_offset(0, off);
1732 off += (*p)->data_size();
1736 const bool check_sections = parameters->options().check_sections();
1737 Output_segment* last_load_segment = NULL;
1739 bool was_readonly = false;
1740 for (Segment_list::iterator p = this->segment_list_.begin();
1741 p != this->segment_list_.end();
1742 ++p)
1744 if ((*p)->type() == elfcpp::PT_LOAD)
1746 if (load_seg != NULL && load_seg != *p)
1747 gold_unreachable();
1748 load_seg = NULL;
1750 bool are_addresses_set = (*p)->are_addresses_set();
1751 if (are_addresses_set)
1753 // When it comes to setting file offsets, we care about
1754 // the physical address.
1755 addr = (*p)->paddr();
1757 else if (this->options_.user_set_Tdata()
1758 && ((*p)->flags() & elfcpp::PF_W) != 0
1759 && (!this->options_.user_set_Tbss()
1760 || (*p)->has_any_data_sections()))
1762 addr = this->options_.Tdata();
1763 are_addresses_set = true;
1765 else if (this->options_.user_set_Tbss()
1766 && ((*p)->flags() & elfcpp::PF_W) != 0
1767 && !(*p)->has_any_data_sections())
1769 addr = this->options_.Tbss();
1770 are_addresses_set = true;
1773 uint64_t orig_addr = addr;
1774 uint64_t orig_off = off;
1776 uint64_t aligned_addr = 0;
1777 uint64_t abi_pagesize = target->abi_pagesize();
1778 uint64_t common_pagesize = target->common_pagesize();
1780 if (!parameters->options().nmagic()
1781 && !parameters->options().omagic())
1782 (*p)->set_minimum_p_align(common_pagesize);
1784 if (are_addresses_set)
1786 if (!parameters->options().nmagic()
1787 && !parameters->options().omagic())
1789 // Adjust the file offset to the same address modulo
1790 // the page size.
1791 uint64_t unsigned_off = off;
1792 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1793 | (addr & (abi_pagesize - 1)));
1794 if (aligned_off < unsigned_off)
1795 aligned_off += abi_pagesize;
1796 off = aligned_off;
1799 else
1801 // If the last segment was readonly, and this one is
1802 // not, then skip the address forward one page,
1803 // maintaining the same position within the page. This
1804 // lets us store both segments overlapping on a single
1805 // page in the file, but the loader will put them on
1806 // different pages in memory.
1808 addr = align_address(addr, (*p)->maximum_alignment());
1809 aligned_addr = addr;
1811 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1813 if ((addr & (abi_pagesize - 1)) != 0)
1814 addr = addr + abi_pagesize;
1817 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1820 unsigned int shndx_hold = *pshndx;
1821 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
1822 &off, pshndx);
1824 // Now that we know the size of this segment, we may be able
1825 // to save a page in memory, at the cost of wasting some
1826 // file space, by instead aligning to the start of a new
1827 // page. Here we use the real machine page size rather than
1828 // the ABI mandated page size.
1830 if (!are_addresses_set && aligned_addr != addr)
1832 uint64_t first_off = (common_pagesize
1833 - (aligned_addr
1834 & (common_pagesize - 1)));
1835 uint64_t last_off = new_addr & (common_pagesize - 1);
1836 if (first_off > 0
1837 && last_off > 0
1838 && ((aligned_addr & ~ (common_pagesize - 1))
1839 != (new_addr & ~ (common_pagesize - 1)))
1840 && first_off + last_off <= common_pagesize)
1842 *pshndx = shndx_hold;
1843 addr = align_address(aligned_addr, common_pagesize);
1844 addr = align_address(addr, (*p)->maximum_alignment());
1845 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1846 new_addr = (*p)->set_section_addresses(this, true, addr,
1847 &off, pshndx);
1851 addr = new_addr;
1853 if (((*p)->flags() & elfcpp::PF_W) == 0)
1854 was_readonly = true;
1856 // Implement --check-sections. We know that the segments
1857 // are sorted by LMA.
1858 if (check_sections && last_load_segment != NULL)
1860 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
1861 if (last_load_segment->paddr() + last_load_segment->memsz()
1862 > (*p)->paddr())
1864 unsigned long long lb1 = last_load_segment->paddr();
1865 unsigned long long le1 = lb1 + last_load_segment->memsz();
1866 unsigned long long lb2 = (*p)->paddr();
1867 unsigned long long le2 = lb2 + (*p)->memsz();
1868 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
1869 "[0x%llx -> 0x%llx]"),
1870 lb1, le1, lb2, le2);
1873 last_load_segment = *p;
1877 // Handle the non-PT_LOAD segments, setting their offsets from their
1878 // section's offsets.
1879 for (Segment_list::iterator p = this->segment_list_.begin();
1880 p != this->segment_list_.end();
1881 ++p)
1883 if ((*p)->type() != elfcpp::PT_LOAD)
1884 (*p)->set_offset();
1887 // Set the TLS offsets for each section in the PT_TLS segment.
1888 if (this->tls_segment_ != NULL)
1889 this->tls_segment_->set_tls_offsets();
1891 return off;
1894 // Set the offsets of all the allocated sections when doing a
1895 // relocatable link. This does the same jobs as set_segment_offsets,
1896 // only for a relocatable link.
1898 off_t
1899 Layout::set_relocatable_section_offsets(Output_data* file_header,
1900 unsigned int *pshndx)
1902 off_t off = 0;
1904 file_header->set_address_and_file_offset(0, 0);
1905 off += file_header->data_size();
1907 for (Section_list::iterator p = this->section_list_.begin();
1908 p != this->section_list_.end();
1909 ++p)
1911 // We skip unallocated sections here, except that group sections
1912 // have to come first.
1913 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
1914 && (*p)->type() != elfcpp::SHT_GROUP)
1915 continue;
1917 off = align_address(off, (*p)->addralign());
1919 // The linker script might have set the address.
1920 if (!(*p)->is_address_valid())
1921 (*p)->set_address(0);
1922 (*p)->set_file_offset(off);
1923 (*p)->finalize_data_size();
1924 off += (*p)->data_size();
1926 (*p)->set_out_shndx(*pshndx);
1927 ++*pshndx;
1930 return off;
1933 // Set the file offset of all the sections not associated with a
1934 // segment.
1936 off_t
1937 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1939 for (Section_list::iterator p = this->unattached_section_list_.begin();
1940 p != this->unattached_section_list_.end();
1941 ++p)
1943 // The symtab section is handled in create_symtab_sections.
1944 if (*p == this->symtab_section_)
1945 continue;
1947 // If we've already set the data size, don't set it again.
1948 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1949 continue;
1951 if (pass == BEFORE_INPUT_SECTIONS_PASS
1952 && (*p)->requires_postprocessing())
1954 (*p)->create_postprocessing_buffer();
1955 this->any_postprocessing_sections_ = true;
1958 if (pass == BEFORE_INPUT_SECTIONS_PASS
1959 && (*p)->after_input_sections())
1960 continue;
1961 else if (pass == POSTPROCESSING_SECTIONS_PASS
1962 && (!(*p)->after_input_sections()
1963 || (*p)->type() == elfcpp::SHT_STRTAB))
1964 continue;
1965 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1966 && (!(*p)->after_input_sections()
1967 || (*p)->type() != elfcpp::SHT_STRTAB))
1968 continue;
1970 off = align_address(off, (*p)->addralign());
1971 (*p)->set_file_offset(off);
1972 (*p)->finalize_data_size();
1973 off += (*p)->data_size();
1975 // At this point the name must be set.
1976 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1977 this->namepool_.add((*p)->name(), false, NULL);
1979 return off;
1982 // Set the section indexes of all the sections not associated with a
1983 // segment.
1985 unsigned int
1986 Layout::set_section_indexes(unsigned int shndx)
1988 for (Section_list::iterator p = this->unattached_section_list_.begin();
1989 p != this->unattached_section_list_.end();
1990 ++p)
1992 if (!(*p)->has_out_shndx())
1994 (*p)->set_out_shndx(shndx);
1995 ++shndx;
1998 return shndx;
2001 // Set the section addresses according to the linker script. This is
2002 // only called when we see a SECTIONS clause. This returns the
2003 // program segment which should hold the file header and segment
2004 // headers, if any. It will return NULL if they should not be in a
2005 // segment.
2007 Output_segment*
2008 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2010 Script_sections* ss = this->script_options_->script_sections();
2011 gold_assert(ss->saw_sections_clause());
2013 // Place each orphaned output section in the script.
2014 for (Section_list::iterator p = this->section_list_.begin();
2015 p != this->section_list_.end();
2016 ++p)
2018 if (!(*p)->found_in_sections_clause())
2019 ss->place_orphan(*p);
2022 return this->script_options_->set_section_addresses(symtab, this);
2025 // Count the local symbols in the regular symbol table and the dynamic
2026 // symbol table, and build the respective string pools.
2028 void
2029 Layout::count_local_symbols(const Task* task,
2030 const Input_objects* input_objects)
2032 // First, figure out an upper bound on the number of symbols we'll
2033 // be inserting into each pool. This helps us create the pools with
2034 // the right size, to avoid unnecessary hashtable resizing.
2035 unsigned int symbol_count = 0;
2036 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2037 p != input_objects->relobj_end();
2038 ++p)
2039 symbol_count += (*p)->local_symbol_count();
2041 // Go from "upper bound" to "estimate." We overcount for two
2042 // reasons: we double-count symbols that occur in more than one
2043 // object file, and we count symbols that are dropped from the
2044 // output. Add it all together and assume we overcount by 100%.
2045 symbol_count /= 2;
2047 // We assume all symbols will go into both the sympool and dynpool.
2048 this->sympool_.reserve(symbol_count);
2049 this->dynpool_.reserve(symbol_count);
2051 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2052 p != input_objects->relobj_end();
2053 ++p)
2055 Task_lock_obj<Object> tlo(task, *p);
2056 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2060 // Create the symbol table sections. Here we also set the final
2061 // values of the symbols. At this point all the loadable sections are
2062 // fully laid out. SHNUM is the number of sections so far.
2064 void
2065 Layout::create_symtab_sections(const Input_objects* input_objects,
2066 Symbol_table* symtab,
2067 unsigned int shnum,
2068 off_t* poff)
2070 int symsize;
2071 unsigned int align;
2072 if (parameters->target().get_size() == 32)
2074 symsize = elfcpp::Elf_sizes<32>::sym_size;
2075 align = 4;
2077 else if (parameters->target().get_size() == 64)
2079 symsize = elfcpp::Elf_sizes<64>::sym_size;
2080 align = 8;
2082 else
2083 gold_unreachable();
2085 off_t off = *poff;
2086 off = align_address(off, align);
2087 off_t startoff = off;
2089 // Save space for the dummy symbol at the start of the section. We
2090 // never bother to write this out--it will just be left as zero.
2091 off += symsize;
2092 unsigned int local_symbol_index = 1;
2094 // Add STT_SECTION symbols for each Output section which needs one.
2095 for (Section_list::iterator p = this->section_list_.begin();
2096 p != this->section_list_.end();
2097 ++p)
2099 if (!(*p)->needs_symtab_index())
2100 (*p)->set_symtab_index(-1U);
2101 else
2103 (*p)->set_symtab_index(local_symbol_index);
2104 ++local_symbol_index;
2105 off += symsize;
2109 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2110 p != input_objects->relobj_end();
2111 ++p)
2113 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2114 off);
2115 off += (index - local_symbol_index) * symsize;
2116 local_symbol_index = index;
2119 unsigned int local_symcount = local_symbol_index;
2120 gold_assert(local_symcount * symsize == off - startoff);
2122 off_t dynoff;
2123 size_t dyn_global_index;
2124 size_t dyncount;
2125 if (this->dynsym_section_ == NULL)
2127 dynoff = 0;
2128 dyn_global_index = 0;
2129 dyncount = 0;
2131 else
2133 dyn_global_index = this->dynsym_section_->info();
2134 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2135 dynoff = this->dynsym_section_->offset() + locsize;
2136 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2137 gold_assert(static_cast<off_t>(dyncount * symsize)
2138 == this->dynsym_section_->data_size() - locsize);
2141 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2142 &this->sympool_, &local_symcount);
2144 if (!parameters->options().strip_all())
2146 this->sympool_.set_string_offsets();
2148 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2149 Output_section* osymtab = this->make_output_section(symtab_name,
2150 elfcpp::SHT_SYMTAB,
2152 this->symtab_section_ = osymtab;
2154 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2155 align,
2156 "** symtab");
2157 osymtab->add_output_section_data(pos);
2159 // We generate a .symtab_shndx section if we have more than
2160 // SHN_LORESERVE sections. Technically it is possible that we
2161 // don't need one, because it is possible that there are no
2162 // symbols in any of sections with indexes larger than
2163 // SHN_LORESERVE. That is probably unusual, though, and it is
2164 // easier to always create one than to compute section indexes
2165 // twice (once here, once when writing out the symbols).
2166 if (shnum >= elfcpp::SHN_LORESERVE)
2168 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2169 false, NULL);
2170 Output_section* osymtab_xindex =
2171 this->make_output_section(symtab_xindex_name,
2172 elfcpp::SHT_SYMTAB_SHNDX, 0);
2174 size_t symcount = (off - startoff) / symsize;
2175 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2177 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2179 osymtab_xindex->set_link_section(osymtab);
2180 osymtab_xindex->set_addralign(4);
2181 osymtab_xindex->set_entsize(4);
2183 osymtab_xindex->set_after_input_sections();
2185 // This tells the driver code to wait until the symbol table
2186 // has written out before writing out the postprocessing
2187 // sections, including the .symtab_shndx section.
2188 this->any_postprocessing_sections_ = true;
2191 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2192 Output_section* ostrtab = this->make_output_section(strtab_name,
2193 elfcpp::SHT_STRTAB,
2196 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2197 ostrtab->add_output_section_data(pstr);
2199 osymtab->set_file_offset(startoff);
2200 osymtab->finalize_data_size();
2201 osymtab->set_link_section(ostrtab);
2202 osymtab->set_info(local_symcount);
2203 osymtab->set_entsize(symsize);
2205 *poff = off;
2209 // Create the .shstrtab section, which holds the names of the
2210 // sections. At the time this is called, we have created all the
2211 // output sections except .shstrtab itself.
2213 Output_section*
2214 Layout::create_shstrtab()
2216 // FIXME: We don't need to create a .shstrtab section if we are
2217 // stripping everything.
2219 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2221 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
2223 // We can't write out this section until we've set all the section
2224 // names, and we don't set the names of compressed output sections
2225 // until relocations are complete.
2226 os->set_after_input_sections();
2228 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2229 os->add_output_section_data(posd);
2231 return os;
2234 // Create the section headers. SIZE is 32 or 64. OFF is the file
2235 // offset.
2237 void
2238 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2240 Output_section_headers* oshdrs;
2241 oshdrs = new Output_section_headers(this,
2242 &this->segment_list_,
2243 &this->section_list_,
2244 &this->unattached_section_list_,
2245 &this->namepool_,
2246 shstrtab_section);
2247 off_t off = align_address(*poff, oshdrs->addralign());
2248 oshdrs->set_address_and_file_offset(0, off);
2249 off += oshdrs->data_size();
2250 *poff = off;
2251 this->section_headers_ = oshdrs;
2254 // Count the allocated sections.
2256 size_t
2257 Layout::allocated_output_section_count() const
2259 size_t section_count = 0;
2260 for (Segment_list::const_iterator p = this->segment_list_.begin();
2261 p != this->segment_list_.end();
2262 ++p)
2263 section_count += (*p)->output_section_count();
2264 return section_count;
2267 // Create the dynamic symbol table.
2269 void
2270 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2271 Symbol_table* symtab,
2272 Output_section **pdynstr,
2273 unsigned int* plocal_dynamic_count,
2274 std::vector<Symbol*>* pdynamic_symbols,
2275 Versions* pversions)
2277 // Count all the symbols in the dynamic symbol table, and set the
2278 // dynamic symbol indexes.
2280 // Skip symbol 0, which is always all zeroes.
2281 unsigned int index = 1;
2283 // Add STT_SECTION symbols for each Output section which needs one.
2284 for (Section_list::iterator p = this->section_list_.begin();
2285 p != this->section_list_.end();
2286 ++p)
2288 if (!(*p)->needs_dynsym_index())
2289 (*p)->set_dynsym_index(-1U);
2290 else
2292 (*p)->set_dynsym_index(index);
2293 ++index;
2297 // Count the local symbols that need to go in the dynamic symbol table,
2298 // and set the dynamic symbol indexes.
2299 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2300 p != input_objects->relobj_end();
2301 ++p)
2303 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2304 index = new_index;
2307 unsigned int local_symcount = index;
2308 *plocal_dynamic_count = local_symcount;
2310 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2311 &this->dynpool_, pversions);
2313 int symsize;
2314 unsigned int align;
2315 const int size = parameters->target().get_size();
2316 if (size == 32)
2318 symsize = elfcpp::Elf_sizes<32>::sym_size;
2319 align = 4;
2321 else if (size == 64)
2323 symsize = elfcpp::Elf_sizes<64>::sym_size;
2324 align = 8;
2326 else
2327 gold_unreachable();
2329 // Create the dynamic symbol table section.
2331 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2332 elfcpp::SHT_DYNSYM,
2333 elfcpp::SHF_ALLOC,
2334 false);
2336 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2337 align,
2338 "** dynsym");
2339 dynsym->add_output_section_data(odata);
2341 dynsym->set_info(local_symcount);
2342 dynsym->set_entsize(symsize);
2343 dynsym->set_addralign(align);
2345 this->dynsym_section_ = dynsym;
2347 Output_data_dynamic* const odyn = this->dynamic_data_;
2348 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2349 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2351 // If there are more than SHN_LORESERVE allocated sections, we
2352 // create a .dynsym_shndx section. It is possible that we don't
2353 // need one, because it is possible that there are no dynamic
2354 // symbols in any of the sections with indexes larger than
2355 // SHN_LORESERVE. This is probably unusual, though, and at this
2356 // time we don't know the actual section indexes so it is
2357 // inconvenient to check.
2358 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2360 Output_section* dynsym_xindex =
2361 this->choose_output_section(NULL, ".dynsym_shndx",
2362 elfcpp::SHT_SYMTAB_SHNDX,
2363 elfcpp::SHF_ALLOC,
2364 false);
2366 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2368 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2370 dynsym_xindex->set_link_section(dynsym);
2371 dynsym_xindex->set_addralign(4);
2372 dynsym_xindex->set_entsize(4);
2374 dynsym_xindex->set_after_input_sections();
2376 // This tells the driver code to wait until the symbol table has
2377 // written out before writing out the postprocessing sections,
2378 // including the .dynsym_shndx section.
2379 this->any_postprocessing_sections_ = true;
2382 // Create the dynamic string table section.
2384 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2385 elfcpp::SHT_STRTAB,
2386 elfcpp::SHF_ALLOC,
2387 false);
2389 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2390 dynstr->add_output_section_data(strdata);
2392 dynsym->set_link_section(dynstr);
2393 this->dynamic_section_->set_link_section(dynstr);
2395 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2396 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2398 *pdynstr = dynstr;
2400 // Create the hash tables.
2402 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2403 || strcmp(parameters->options().hash_style(), "both") == 0)
2405 unsigned char* phash;
2406 unsigned int hashlen;
2407 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2408 &phash, &hashlen);
2410 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2411 elfcpp::SHT_HASH,
2412 elfcpp::SHF_ALLOC,
2413 false);
2415 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2416 hashlen,
2417 align,
2418 "** hash");
2419 hashsec->add_output_section_data(hashdata);
2421 hashsec->set_link_section(dynsym);
2422 hashsec->set_entsize(4);
2424 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2427 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2428 || strcmp(parameters->options().hash_style(), "both") == 0)
2430 unsigned char* phash;
2431 unsigned int hashlen;
2432 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2433 &phash, &hashlen);
2435 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2436 elfcpp::SHT_GNU_HASH,
2437 elfcpp::SHF_ALLOC,
2438 false);
2440 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2441 hashlen,
2442 align,
2443 "** hash");
2444 hashsec->add_output_section_data(hashdata);
2446 hashsec->set_link_section(dynsym);
2447 hashsec->set_entsize(4);
2449 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2453 // Assign offsets to each local portion of the dynamic symbol table.
2455 void
2456 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2458 Output_section* dynsym = this->dynsym_section_;
2459 gold_assert(dynsym != NULL);
2461 off_t off = dynsym->offset();
2463 // Skip the dummy symbol at the start of the section.
2464 off += dynsym->entsize();
2466 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2467 p != input_objects->relobj_end();
2468 ++p)
2470 unsigned int count = (*p)->set_local_dynsym_offset(off);
2471 off += count * dynsym->entsize();
2475 // Create the version sections.
2477 void
2478 Layout::create_version_sections(const Versions* versions,
2479 const Symbol_table* symtab,
2480 unsigned int local_symcount,
2481 const std::vector<Symbol*>& dynamic_symbols,
2482 const Output_section* dynstr)
2484 if (!versions->any_defs() && !versions->any_needs())
2485 return;
2487 switch (parameters->size_and_endianness())
2489 #ifdef HAVE_TARGET_32_LITTLE
2490 case Parameters::TARGET_32_LITTLE:
2491 this->sized_create_version_sections<32, false>(versions, symtab,
2492 local_symcount,
2493 dynamic_symbols, dynstr);
2494 break;
2495 #endif
2496 #ifdef HAVE_TARGET_32_BIG
2497 case Parameters::TARGET_32_BIG:
2498 this->sized_create_version_sections<32, true>(versions, symtab,
2499 local_symcount,
2500 dynamic_symbols, dynstr);
2501 break;
2502 #endif
2503 #ifdef HAVE_TARGET_64_LITTLE
2504 case Parameters::TARGET_64_LITTLE:
2505 this->sized_create_version_sections<64, false>(versions, symtab,
2506 local_symcount,
2507 dynamic_symbols, dynstr);
2508 break;
2509 #endif
2510 #ifdef HAVE_TARGET_64_BIG
2511 case Parameters::TARGET_64_BIG:
2512 this->sized_create_version_sections<64, true>(versions, symtab,
2513 local_symcount,
2514 dynamic_symbols, dynstr);
2515 break;
2516 #endif
2517 default:
2518 gold_unreachable();
2522 // Create the version sections, sized version.
2524 template<int size, bool big_endian>
2525 void
2526 Layout::sized_create_version_sections(
2527 const Versions* versions,
2528 const Symbol_table* symtab,
2529 unsigned int local_symcount,
2530 const std::vector<Symbol*>& dynamic_symbols,
2531 const Output_section* dynstr)
2533 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2534 elfcpp::SHT_GNU_versym,
2535 elfcpp::SHF_ALLOC,
2536 false);
2538 unsigned char* vbuf;
2539 unsigned int vsize;
2540 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2541 local_symcount,
2542 dynamic_symbols,
2543 &vbuf, &vsize);
2545 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
2546 "** versions");
2548 vsec->add_output_section_data(vdata);
2549 vsec->set_entsize(2);
2550 vsec->set_link_section(this->dynsym_section_);
2552 Output_data_dynamic* const odyn = this->dynamic_data_;
2553 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2555 if (versions->any_defs())
2557 Output_section* vdsec;
2558 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
2559 elfcpp::SHT_GNU_verdef,
2560 elfcpp::SHF_ALLOC,
2561 false);
2563 unsigned char* vdbuf;
2564 unsigned int vdsize;
2565 unsigned int vdentries;
2566 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
2567 &vdsize, &vdentries);
2569 Output_section_data* vddata =
2570 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
2572 vdsec->add_output_section_data(vddata);
2573 vdsec->set_link_section(dynstr);
2574 vdsec->set_info(vdentries);
2576 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
2577 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
2580 if (versions->any_needs())
2582 Output_section* vnsec;
2583 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
2584 elfcpp::SHT_GNU_verneed,
2585 elfcpp::SHF_ALLOC,
2586 false);
2588 unsigned char* vnbuf;
2589 unsigned int vnsize;
2590 unsigned int vnentries;
2591 versions->need_section_contents<size, big_endian>(&this->dynpool_,
2592 &vnbuf, &vnsize,
2593 &vnentries);
2595 Output_section_data* vndata =
2596 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
2598 vnsec->add_output_section_data(vndata);
2599 vnsec->set_link_section(dynstr);
2600 vnsec->set_info(vnentries);
2602 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
2603 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
2607 // Create the .interp section and PT_INTERP segment.
2609 void
2610 Layout::create_interp(const Target* target)
2612 const char* interp = this->options_.dynamic_linker();
2613 if (interp == NULL)
2615 interp = target->dynamic_linker();
2616 gold_assert(interp != NULL);
2619 size_t len = strlen(interp) + 1;
2621 Output_section_data* odata = new Output_data_const(interp, len, 1);
2623 Output_section* osec = this->choose_output_section(NULL, ".interp",
2624 elfcpp::SHT_PROGBITS,
2625 elfcpp::SHF_ALLOC,
2626 false);
2627 osec->add_output_section_data(odata);
2629 if (!this->script_options_->saw_phdrs_clause())
2631 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
2632 elfcpp::PF_R);
2633 oseg->add_output_section(osec, elfcpp::PF_R);
2637 // Finish the .dynamic section and PT_DYNAMIC segment.
2639 void
2640 Layout::finish_dynamic_section(const Input_objects* input_objects,
2641 const Symbol_table* symtab)
2643 if (!this->script_options_->saw_phdrs_clause())
2645 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
2646 (elfcpp::PF_R
2647 | elfcpp::PF_W));
2648 oseg->add_output_section(this->dynamic_section_,
2649 elfcpp::PF_R | elfcpp::PF_W);
2652 Output_data_dynamic* const odyn = this->dynamic_data_;
2654 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
2655 p != input_objects->dynobj_end();
2656 ++p)
2658 // FIXME: Handle --as-needed.
2659 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
2662 if (parameters->options().shared())
2664 const char* soname = this->options_.soname();
2665 if (soname != NULL)
2666 odyn->add_string(elfcpp::DT_SONAME, soname);
2669 // FIXME: Support --init and --fini.
2670 Symbol* sym = symtab->lookup("_init");
2671 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2672 odyn->add_symbol(elfcpp::DT_INIT, sym);
2674 sym = symtab->lookup("_fini");
2675 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2676 odyn->add_symbol(elfcpp::DT_FINI, sym);
2678 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
2680 // Add a DT_RPATH entry if needed.
2681 const General_options::Dir_list& rpath(this->options_.rpath());
2682 if (!rpath.empty())
2684 std::string rpath_val;
2685 for (General_options::Dir_list::const_iterator p = rpath.begin();
2686 p != rpath.end();
2687 ++p)
2689 if (rpath_val.empty())
2690 rpath_val = p->name();
2691 else
2693 // Eliminate duplicates.
2694 General_options::Dir_list::const_iterator q;
2695 for (q = rpath.begin(); q != p; ++q)
2696 if (q->name() == p->name())
2697 break;
2698 if (q == p)
2700 rpath_val += ':';
2701 rpath_val += p->name();
2706 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
2707 if (parameters->options().enable_new_dtags())
2708 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
2711 // Look for text segments that have dynamic relocations.
2712 bool have_textrel = false;
2713 if (!this->script_options_->saw_sections_clause())
2715 for (Segment_list::const_iterator p = this->segment_list_.begin();
2716 p != this->segment_list_.end();
2717 ++p)
2719 if (((*p)->flags() & elfcpp::PF_W) == 0
2720 && (*p)->dynamic_reloc_count() > 0)
2722 have_textrel = true;
2723 break;
2727 else
2729 // We don't know the section -> segment mapping, so we are
2730 // conservative and just look for readonly sections with
2731 // relocations. If those sections wind up in writable segments,
2732 // then we have created an unnecessary DT_TEXTREL entry.
2733 for (Section_list::const_iterator p = this->section_list_.begin();
2734 p != this->section_list_.end();
2735 ++p)
2737 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
2738 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
2739 && ((*p)->dynamic_reloc_count() > 0))
2741 have_textrel = true;
2742 break;
2747 // Add a DT_FLAGS entry. We add it even if no flags are set so that
2748 // post-link tools can easily modify these flags if desired.
2749 unsigned int flags = 0;
2750 if (have_textrel)
2752 // Add a DT_TEXTREL for compatibility with older loaders.
2753 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
2754 flags |= elfcpp::DF_TEXTREL;
2756 if (parameters->options().shared() && this->has_static_tls())
2757 flags |= elfcpp::DF_STATIC_TLS;
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 (flags)
2780 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
2783 // The mapping of .gnu.linkonce section names to real section names.
2785 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
2786 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
2788 MAPPING_INIT("d.rel.ro.local", ".data.rel.ro.local"), // Before "d.rel.ro".
2789 MAPPING_INIT("d.rel.ro", ".data.rel.ro"), // Before "d".
2790 MAPPING_INIT("t", ".text"),
2791 MAPPING_INIT("r", ".rodata"),
2792 MAPPING_INIT("d", ".data"),
2793 MAPPING_INIT("b", ".bss"),
2794 MAPPING_INIT("s", ".sdata"),
2795 MAPPING_INIT("sb", ".sbss"),
2796 MAPPING_INIT("s2", ".sdata2"),
2797 MAPPING_INIT("sb2", ".sbss2"),
2798 MAPPING_INIT("wi", ".debug_info"),
2799 MAPPING_INIT("td", ".tdata"),
2800 MAPPING_INIT("tb", ".tbss"),
2801 MAPPING_INIT("lr", ".lrodata"),
2802 MAPPING_INIT("l", ".ldata"),
2803 MAPPING_INIT("lb", ".lbss"),
2805 #undef MAPPING_INIT
2807 const int Layout::linkonce_mapping_count =
2808 sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
2810 // Return the name of the output section to use for a .gnu.linkonce
2811 // section. This is based on the default ELF linker script of the old
2812 // GNU linker. For example, we map a name like ".gnu.linkonce.t.foo"
2813 // to ".text". Set *PLEN to the length of the name. *PLEN is
2814 // initialized to the length of NAME.
2816 const char*
2817 Layout::linkonce_output_name(const char* name, size_t *plen)
2819 const char* s = name + sizeof(".gnu.linkonce") - 1;
2820 if (*s != '.')
2821 return name;
2822 ++s;
2823 const Linkonce_mapping* plm = linkonce_mapping;
2824 for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2826 if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2828 *plen = plm->tolen;
2829 return plm->to;
2832 return name;
2835 // Choose the output section name to use given an input section name.
2836 // Set *PLEN to the length of the name. *PLEN is initialized to the
2837 // length of NAME.
2839 const char*
2840 Layout::output_section_name(const char* name, size_t* plen)
2842 if (Layout::is_linkonce(name))
2844 // .gnu.linkonce sections are laid out as though they were named
2845 // for the sections are placed into.
2846 return Layout::linkonce_output_name(name, plen);
2849 // gcc 4.3 generates the following sorts of section names when it
2850 // needs a section name specific to a function:
2851 // .text.FN
2852 // .rodata.FN
2853 // .sdata2.FN
2854 // .data.FN
2855 // .data.rel.FN
2856 // .data.rel.local.FN
2857 // .data.rel.ro.FN
2858 // .data.rel.ro.local.FN
2859 // .sdata.FN
2860 // .bss.FN
2861 // .sbss.FN
2862 // .tdata.FN
2863 // .tbss.FN
2865 // The GNU linker maps all of those to the part before the .FN,
2866 // except that .data.rel.local.FN is mapped to .data, and
2867 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
2868 // beginning with .data.rel.ro.local are grouped together.
2870 // For an anonymous namespace, the string FN can contain a '.'.
2872 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2873 // GNU linker maps to .rodata.
2875 // The .data.rel.ro sections enable a security feature triggered by
2876 // the -z relro option. Section which need to be relocated at
2877 // program startup time but which may be readonly after startup are
2878 // grouped into .data.rel.ro. They are then put into a PT_GNU_RELRO
2879 // segment. The dynamic linker will make that segment writable,
2880 // perform relocations, and then make it read-only. FIXME: We do
2881 // not yet implement this optimization.
2883 // It is hard to handle this in a principled way.
2885 // These are the rules we follow:
2887 // If the section name has no initial '.', or no dot other than an
2888 // initial '.', we use the name unchanged (i.e., "mysection" and
2889 // ".text" are unchanged).
2891 // If the name starts with ".data.rel.ro.local" we use
2892 // ".data.rel.ro.local".
2894 // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2896 // Otherwise, we drop the second '.' and everything that comes after
2897 // it (i.e., ".text.XXX" becomes ".text").
2899 const char* s = name;
2900 if (*s != '.')
2901 return name;
2902 ++s;
2903 const char* sdot = strchr(s, '.');
2904 if (sdot == NULL)
2905 return name;
2907 const char* const data_rel_ro_local = ".data.rel.ro.local";
2908 if (strncmp(name, data_rel_ro_local, strlen(data_rel_ro_local)) == 0)
2910 *plen = strlen(data_rel_ro_local);
2911 return data_rel_ro_local;
2914 const char* const data_rel_ro = ".data.rel.ro";
2915 if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2917 *plen = strlen(data_rel_ro);
2918 return data_rel_ro;
2921 *plen = sdot - name;
2922 return name;
2925 // Record the signature of a comdat section, and return whether to
2926 // include it in the link. If GROUP is true, this is a regular
2927 // section group. If GROUP is false, this is a group signature
2928 // derived from the name of a linkonce section. We want linkonce
2929 // signatures and group signatures to block each other, but we don't
2930 // want a linkonce signature to block another linkonce signature.
2932 bool
2933 Layout::add_comdat(Relobj* object, unsigned int shndx,
2934 const std::string& signature, bool group)
2936 Kept_section kept(object, shndx, group);
2937 std::pair<Signatures::iterator, bool> ins(
2938 this->signatures_.insert(std::make_pair(signature, kept)));
2940 if (ins.second)
2942 // This is the first time we've seen this signature.
2943 return true;
2946 if (ins.first->second.group_)
2948 // We've already seen a real section group with this signature.
2949 return false;
2951 else if (group)
2953 // This is a real section group, and we've already seen a
2954 // linkonce section with this signature. Record that we've seen
2955 // a section group, and don't include this section group.
2956 ins.first->second.group_ = true;
2957 return false;
2959 else
2961 // We've already seen a linkonce section and this is a linkonce
2962 // section. These don't block each other--this may be the same
2963 // symbol name with different section types.
2964 return true;
2968 // Find the given comdat signature, and return the object and section
2969 // index of the kept group.
2970 Relobj*
2971 Layout::find_kept_object(const std::string& signature,
2972 unsigned int* pshndx) const
2974 Signatures::const_iterator p = this->signatures_.find(signature);
2975 if (p == this->signatures_.end())
2976 return NULL;
2977 if (pshndx != NULL)
2978 *pshndx = p->second.shndx_;
2979 return p->second.object_;
2982 // Store the allocated sections into the section list.
2984 void
2985 Layout::get_allocated_sections(Section_list* section_list) const
2987 for (Section_list::const_iterator p = this->section_list_.begin();
2988 p != this->section_list_.end();
2989 ++p)
2990 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2991 section_list->push_back(*p);
2994 // Create an output segment.
2996 Output_segment*
2997 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2999 gold_assert(!parameters->options().relocatable());
3000 Output_segment* oseg = new Output_segment(type, flags);
3001 this->segment_list_.push_back(oseg);
3002 return oseg;
3005 // Write out the Output_sections. Most won't have anything to write,
3006 // since most of the data will come from input sections which are
3007 // handled elsewhere. But some Output_sections do have Output_data.
3009 void
3010 Layout::write_output_sections(Output_file* of) const
3012 for (Section_list::const_iterator p = this->section_list_.begin();
3013 p != this->section_list_.end();
3014 ++p)
3016 if (!(*p)->after_input_sections())
3017 (*p)->write(of);
3021 // Write out data not associated with a section or the symbol table.
3023 void
3024 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
3026 if (!parameters->options().strip_all())
3028 const Output_section* symtab_section = this->symtab_section_;
3029 for (Section_list::const_iterator p = this->section_list_.begin();
3030 p != this->section_list_.end();
3031 ++p)
3033 if ((*p)->needs_symtab_index())
3035 gold_assert(symtab_section != NULL);
3036 unsigned int index = (*p)->symtab_index();
3037 gold_assert(index > 0 && index != -1U);
3038 off_t off = (symtab_section->offset()
3039 + index * symtab_section->entsize());
3040 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3045 const Output_section* dynsym_section = this->dynsym_section_;
3046 for (Section_list::const_iterator p = this->section_list_.begin();
3047 p != this->section_list_.end();
3048 ++p)
3050 if ((*p)->needs_dynsym_index())
3052 gold_assert(dynsym_section != NULL);
3053 unsigned int index = (*p)->dynsym_index();
3054 gold_assert(index > 0 && index != -1U);
3055 off_t off = (dynsym_section->offset()
3056 + index * dynsym_section->entsize());
3057 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3061 // Write out the Output_data which are not in an Output_section.
3062 for (Data_list::const_iterator p = this->special_output_list_.begin();
3063 p != this->special_output_list_.end();
3064 ++p)
3065 (*p)->write(of);
3068 // Write out the Output_sections which can only be written after the
3069 // input sections are complete.
3071 void
3072 Layout::write_sections_after_input_sections(Output_file* of)
3074 // Determine the final section offsets, and thus the final output
3075 // file size. Note we finalize the .shstrab last, to allow the
3076 // after_input_section sections to modify their section-names before
3077 // writing.
3078 if (this->any_postprocessing_sections_)
3080 off_t off = this->output_file_size_;
3081 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3083 // Now that we've finalized the names, we can finalize the shstrab.
3084 off =
3085 this->set_section_offsets(off,
3086 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3088 if (off > this->output_file_size_)
3090 of->resize(off);
3091 this->output_file_size_ = off;
3095 for (Section_list::const_iterator p = this->section_list_.begin();
3096 p != this->section_list_.end();
3097 ++p)
3099 if ((*p)->after_input_sections())
3100 (*p)->write(of);
3103 this->section_headers_->write(of);
3106 // If the build ID requires computing a checksum, do so here, and
3107 // write it out. We compute a checksum over the entire file because
3108 // that is simplest.
3110 void
3111 Layout::write_build_id(Output_file* of) const
3113 if (this->build_id_note_ == NULL)
3114 return;
3116 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3118 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3119 this->build_id_note_->data_size());
3121 const char* style = parameters->options().build_id();
3122 if (strcmp(style, "sha1") == 0)
3124 sha1_ctx ctx;
3125 sha1_init_ctx(&ctx);
3126 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3127 sha1_finish_ctx(&ctx, ov);
3129 else if (strcmp(style, "md5") == 0)
3131 md5_ctx ctx;
3132 md5_init_ctx(&ctx);
3133 md5_process_bytes(iv, this->output_file_size_, &ctx);
3134 md5_finish_ctx(&ctx, ov);
3136 else
3137 gold_unreachable();
3139 of->write_output_view(this->build_id_note_->offset(),
3140 this->build_id_note_->data_size(),
3141 ov);
3143 of->free_input_view(0, this->output_file_size_, iv);
3146 // Write out a binary file. This is called after the link is
3147 // complete. IN is the temporary output file we used to generate the
3148 // ELF code. We simply walk through the segments, read them from
3149 // their file offset in IN, and write them to their load address in
3150 // the output file. FIXME: with a bit more work, we could support
3151 // S-records and/or Intel hex format here.
3153 void
3154 Layout::write_binary(Output_file* in) const
3156 gold_assert(this->options_.oformat_enum()
3157 == General_options::OBJECT_FORMAT_BINARY);
3159 // Get the size of the binary file.
3160 uint64_t max_load_address = 0;
3161 for (Segment_list::const_iterator p = this->segment_list_.begin();
3162 p != this->segment_list_.end();
3163 ++p)
3165 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3167 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3168 if (max_paddr > max_load_address)
3169 max_load_address = max_paddr;
3173 Output_file out(parameters->options().output_file_name());
3174 out.open(max_load_address);
3176 for (Segment_list::const_iterator p = this->segment_list_.begin();
3177 p != this->segment_list_.end();
3178 ++p)
3180 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3182 const unsigned char* vin = in->get_input_view((*p)->offset(),
3183 (*p)->filesz());
3184 unsigned char* vout = out.get_output_view((*p)->paddr(),
3185 (*p)->filesz());
3186 memcpy(vout, vin, (*p)->filesz());
3187 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3188 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3192 out.close();
3195 // Print the output sections to the map file.
3197 void
3198 Layout::print_to_mapfile(Mapfile* mapfile) const
3200 for (Segment_list::const_iterator p = this->segment_list_.begin();
3201 p != this->segment_list_.end();
3202 ++p)
3203 (*p)->print_sections_to_mapfile(mapfile);
3206 // Print statistical information to stderr. This is used for --stats.
3208 void
3209 Layout::print_stats() const
3211 this->namepool_.print_stats("section name pool");
3212 this->sympool_.print_stats("output symbol name pool");
3213 this->dynpool_.print_stats("dynamic name pool");
3215 for (Section_list::const_iterator p = this->section_list_.begin();
3216 p != this->section_list_.end();
3217 ++p)
3218 (*p)->print_merge_stats();
3221 // Write_sections_task methods.
3223 // We can always run this task.
3225 Task_token*
3226 Write_sections_task::is_runnable()
3228 return NULL;
3231 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3232 // when finished.
3234 void
3235 Write_sections_task::locks(Task_locker* tl)
3237 tl->add(this, this->output_sections_blocker_);
3238 tl->add(this, this->final_blocker_);
3241 // Run the task--write out the data.
3243 void
3244 Write_sections_task::run(Workqueue*)
3246 this->layout_->write_output_sections(this->of_);
3249 // Write_data_task methods.
3251 // We can always run this task.
3253 Task_token*
3254 Write_data_task::is_runnable()
3256 return NULL;
3259 // We need to unlock FINAL_BLOCKER when finished.
3261 void
3262 Write_data_task::locks(Task_locker* tl)
3264 tl->add(this, this->final_blocker_);
3267 // Run the task--write out the data.
3269 void
3270 Write_data_task::run(Workqueue*)
3272 this->layout_->write_data(this->symtab_, this->of_);
3275 // Write_symbols_task methods.
3277 // We can always run this task.
3279 Task_token*
3280 Write_symbols_task::is_runnable()
3282 return NULL;
3285 // We need to unlock FINAL_BLOCKER when finished.
3287 void
3288 Write_symbols_task::locks(Task_locker* tl)
3290 tl->add(this, this->final_blocker_);
3293 // Run the task--write out the symbols.
3295 void
3296 Write_symbols_task::run(Workqueue*)
3298 this->symtab_->write_globals(this->input_objects_, this->sympool_,
3299 this->dynpool_, this->layout_->symtab_xindex(),
3300 this->layout_->dynsym_xindex(), this->of_);
3303 // Write_after_input_sections_task methods.
3305 // We can only run this task after the input sections have completed.
3307 Task_token*
3308 Write_after_input_sections_task::is_runnable()
3310 if (this->input_sections_blocker_->is_blocked())
3311 return this->input_sections_blocker_;
3312 return NULL;
3315 // We need to unlock FINAL_BLOCKER when finished.
3317 void
3318 Write_after_input_sections_task::locks(Task_locker* tl)
3320 tl->add(this, this->final_blocker_);
3323 // Run the task.
3325 void
3326 Write_after_input_sections_task::run(Workqueue*)
3328 this->layout_->write_sections_after_input_sections(this->of_);
3331 // Close_task_runner methods.
3333 // Run the task--close the file.
3335 void
3336 Close_task_runner::run(Workqueue*, const Task*)
3338 // If we need to compute a checksum for the BUILD if, we do so here.
3339 this->layout_->write_build_id(this->of_);
3341 // If we've been asked to create a binary file, we do so here.
3342 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3343 this->layout_->write_binary(this->of_);
3345 this->of_->close();
3348 // Instantiate the templates we need. We could use the configure
3349 // script to restrict this to only the ones for implemented targets.
3351 #ifdef HAVE_TARGET_32_LITTLE
3352 template
3353 Output_section*
3354 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3355 const char* name,
3356 const elfcpp::Shdr<32, false>& shdr,
3357 unsigned int, unsigned int, off_t*);
3358 #endif
3360 #ifdef HAVE_TARGET_32_BIG
3361 template
3362 Output_section*
3363 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3364 const char* name,
3365 const elfcpp::Shdr<32, true>& shdr,
3366 unsigned int, unsigned int, off_t*);
3367 #endif
3369 #ifdef HAVE_TARGET_64_LITTLE
3370 template
3371 Output_section*
3372 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3373 const char* name,
3374 const elfcpp::Shdr<64, false>& shdr,
3375 unsigned int, unsigned int, off_t*);
3376 #endif
3378 #ifdef HAVE_TARGET_64_BIG
3379 template
3380 Output_section*
3381 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3382 const char* name,
3383 const elfcpp::Shdr<64, true>& shdr,
3384 unsigned int, unsigned int, off_t*);
3385 #endif
3387 #ifdef HAVE_TARGET_32_LITTLE
3388 template
3389 Output_section*
3390 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3391 unsigned int reloc_shndx,
3392 const elfcpp::Shdr<32, false>& shdr,
3393 Output_section* data_section,
3394 Relocatable_relocs* rr);
3395 #endif
3397 #ifdef HAVE_TARGET_32_BIG
3398 template
3399 Output_section*
3400 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3401 unsigned int reloc_shndx,
3402 const elfcpp::Shdr<32, true>& shdr,
3403 Output_section* data_section,
3404 Relocatable_relocs* rr);
3405 #endif
3407 #ifdef HAVE_TARGET_64_LITTLE
3408 template
3409 Output_section*
3410 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3411 unsigned int reloc_shndx,
3412 const elfcpp::Shdr<64, false>& shdr,
3413 Output_section* data_section,
3414 Relocatable_relocs* rr);
3415 #endif
3417 #ifdef HAVE_TARGET_64_BIG
3418 template
3419 Output_section*
3420 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3421 unsigned int reloc_shndx,
3422 const elfcpp::Shdr<64, true>& shdr,
3423 Output_section* data_section,
3424 Relocatable_relocs* rr);
3425 #endif
3427 #ifdef HAVE_TARGET_32_LITTLE
3428 template
3429 void
3430 Layout::layout_group<32, false>(Symbol_table* symtab,
3431 Sized_relobj<32, false>* object,
3432 unsigned int,
3433 const char* group_section_name,
3434 const char* signature,
3435 const elfcpp::Shdr<32, false>& shdr,
3436 elfcpp::Elf_Word flags,
3437 std::vector<unsigned int>* shndxes);
3438 #endif
3440 #ifdef HAVE_TARGET_32_BIG
3441 template
3442 void
3443 Layout::layout_group<32, true>(Symbol_table* symtab,
3444 Sized_relobj<32, true>* object,
3445 unsigned int,
3446 const char* group_section_name,
3447 const char* signature,
3448 const elfcpp::Shdr<32, true>& shdr,
3449 elfcpp::Elf_Word flags,
3450 std::vector<unsigned int>* shndxes);
3451 #endif
3453 #ifdef HAVE_TARGET_64_LITTLE
3454 template
3455 void
3456 Layout::layout_group<64, false>(Symbol_table* symtab,
3457 Sized_relobj<64, false>* object,
3458 unsigned int,
3459 const char* group_section_name,
3460 const char* signature,
3461 const elfcpp::Shdr<64, false>& shdr,
3462 elfcpp::Elf_Word flags,
3463 std::vector<unsigned int>* shndxes);
3464 #endif
3466 #ifdef HAVE_TARGET_64_BIG
3467 template
3468 void
3469 Layout::layout_group<64, true>(Symbol_table* symtab,
3470 Sized_relobj<64, true>* object,
3471 unsigned int,
3472 const char* group_section_name,
3473 const char* signature,
3474 const elfcpp::Shdr<64, true>& shdr,
3475 elfcpp::Elf_Word flags,
3476 std::vector<unsigned int>* shndxes);
3477 #endif
3479 #ifdef HAVE_TARGET_32_LITTLE
3480 template
3481 Output_section*
3482 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3483 const unsigned char* symbols,
3484 off_t symbols_size,
3485 const unsigned char* symbol_names,
3486 off_t symbol_names_size,
3487 unsigned int shndx,
3488 const elfcpp::Shdr<32, false>& shdr,
3489 unsigned int reloc_shndx,
3490 unsigned int reloc_type,
3491 off_t* off);
3492 #endif
3494 #ifdef HAVE_TARGET_32_BIG
3495 template
3496 Output_section*
3497 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3498 const unsigned char* symbols,
3499 off_t symbols_size,
3500 const unsigned char* symbol_names,
3501 off_t symbol_names_size,
3502 unsigned int shndx,
3503 const elfcpp::Shdr<32, true>& shdr,
3504 unsigned int reloc_shndx,
3505 unsigned int reloc_type,
3506 off_t* off);
3507 #endif
3509 #ifdef HAVE_TARGET_64_LITTLE
3510 template
3511 Output_section*
3512 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3513 const unsigned char* symbols,
3514 off_t symbols_size,
3515 const unsigned char* symbol_names,
3516 off_t symbol_names_size,
3517 unsigned int shndx,
3518 const elfcpp::Shdr<64, false>& shdr,
3519 unsigned int reloc_shndx,
3520 unsigned int reloc_type,
3521 off_t* off);
3522 #endif
3524 #ifdef HAVE_TARGET_64_BIG
3525 template
3526 Output_section*
3527 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
3528 const unsigned char* symbols,
3529 off_t symbols_size,
3530 const unsigned char* symbol_names,
3531 off_t symbol_names_size,
3532 unsigned int shndx,
3533 const elfcpp::Shdr<64, true>& shdr,
3534 unsigned int reloc_shndx,
3535 unsigned int reloc_type,
3536 off_t* off);
3537 #endif
3539 } // End namespace gold.