daily update
[binutils.git] / gold / layout.cc
blob2c8c5241fb5eedba0c98860c3d49373d523e9eaa
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 "layout.h"
50 namespace gold
53 // Layout_task_runner methods.
55 // Lay out the sections. This is called after all the input objects
56 // have been read.
58 void
59 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
61 off_t file_size = this->layout_->finalize(this->input_objects_,
62 this->symtab_,
63 this->target_,
64 task);
66 // Now we know the final size of the output file and we know where
67 // each piece of information goes.
69 if (this->mapfile_ != NULL)
71 this->mapfile_->print_discarded_sections(this->input_objects_);
72 this->layout_->print_to_mapfile(this->mapfile_);
75 Output_file* of = new Output_file(parameters->options().output_file_name());
76 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
77 of->set_is_temporary();
78 of->open(file_size);
80 // Queue up the final set of tasks.
81 gold::queue_final_tasks(this->options_, this->input_objects_,
82 this->symtab_, this->layout_, workqueue, of);
85 // Layout methods.
87 Layout::Layout(const General_options& options, Script_options* script_options)
88 : options_(options),
89 script_options_(script_options),
90 namepool_(),
91 sympool_(),
92 dynpool_(),
93 signatures_(),
94 section_name_map_(),
95 segment_list_(),
96 section_list_(),
97 unattached_section_list_(),
98 sections_are_attached_(false),
99 special_output_list_(),
100 section_headers_(NULL),
101 tls_segment_(NULL),
102 relro_segment_(NULL),
103 symtab_section_(NULL),
104 symtab_xindex_(NULL),
105 dynsym_section_(NULL),
106 dynsym_xindex_(NULL),
107 dynamic_section_(NULL),
108 dynamic_data_(NULL),
109 eh_frame_section_(NULL),
110 eh_frame_data_(NULL),
111 added_eh_frame_data_(false),
112 eh_frame_hdr_section_(NULL),
113 build_id_note_(NULL),
114 debug_abbrev_(NULL),
115 debug_info_(NULL),
116 group_signatures_(),
117 output_file_size_(-1),
118 input_requires_executable_stack_(false),
119 input_with_gnu_stack_note_(false),
120 input_without_gnu_stack_note_(false),
121 has_static_tls_(false),
122 any_postprocessing_sections_(false)
124 // Make space for more than enough segments for a typical file.
125 // This is just for efficiency--it's OK if we wind up needing more.
126 this->segment_list_.reserve(12);
128 // We expect two unattached Output_data objects: the file header and
129 // the segment headers.
130 this->special_output_list_.reserve(2);
133 // Hash a key we use to look up an output section mapping.
135 size_t
136 Layout::Hash_key::operator()(const Layout::Key& k) const
138 return k.first + k.second.first + k.second.second;
141 // Return whether PREFIX is a prefix of STR.
143 static inline bool
144 is_prefix_of(const char* prefix, const char* str)
146 return strncmp(prefix, str, strlen(prefix)) == 0;
149 // Returns whether the given section is in the list of
150 // debug-sections-used-by-some-version-of-gdb. Currently,
151 // we've checked versions of gdb up to and including 6.7.1.
153 static const char* gdb_sections[] =
154 { ".debug_abbrev",
155 // ".debug_aranges", // not used by gdb as of 6.7.1
156 ".debug_frame",
157 ".debug_info",
158 ".debug_line",
159 ".debug_loc",
160 ".debug_macinfo",
161 // ".debug_pubnames", // not used by gdb as of 6.7.1
162 ".debug_ranges",
163 ".debug_str",
166 static const char* lines_only_debug_sections[] =
167 { ".debug_abbrev",
168 // ".debug_aranges", // not used by gdb as of 6.7.1
169 // ".debug_frame",
170 ".debug_info",
171 ".debug_line",
172 // ".debug_loc",
173 // ".debug_macinfo",
174 // ".debug_pubnames", // not used by gdb as of 6.7.1
175 // ".debug_ranges",
176 ".debug_str",
179 static inline bool
180 is_gdb_debug_section(const char* str)
182 // We can do this faster: binary search or a hashtable. But why bother?
183 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
184 if (strcmp(str, gdb_sections[i]) == 0)
185 return true;
186 return false;
189 static inline bool
190 is_lines_only_debug_section(const char* str)
192 // We can do this faster: binary search or a hashtable. But why bother?
193 for (size_t i = 0;
194 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
195 ++i)
196 if (strcmp(str, lines_only_debug_sections[i]) == 0)
197 return true;
198 return false;
201 // Whether to include this section in the link.
203 template<int size, bool big_endian>
204 bool
205 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
206 const elfcpp::Shdr<size, big_endian>& shdr)
208 switch (shdr.get_sh_type())
210 case elfcpp::SHT_NULL:
211 case elfcpp::SHT_SYMTAB:
212 case elfcpp::SHT_DYNSYM:
213 case elfcpp::SHT_STRTAB:
214 case elfcpp::SHT_HASH:
215 case elfcpp::SHT_DYNAMIC:
216 case elfcpp::SHT_SYMTAB_SHNDX:
217 return false;
219 case elfcpp::SHT_RELA:
220 case elfcpp::SHT_REL:
221 case elfcpp::SHT_GROUP:
222 // If we are emitting relocations these should be handled
223 // elsewhere.
224 gold_assert(!parameters->options().relocatable()
225 && !parameters->options().emit_relocs());
226 return false;
228 case elfcpp::SHT_PROGBITS:
229 if (parameters->options().strip_debug()
230 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
232 if (is_debug_info_section(name))
233 return false;
235 if (parameters->options().strip_debug_non_line()
236 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
238 // Debugging sections can only be recognized by name.
239 if (is_prefix_of(".debug", name)
240 && !is_lines_only_debug_section(name))
241 return false;
243 if (parameters->options().strip_debug_gdb()
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_gdb_debug_section(name))
249 return false;
251 return true;
253 default:
254 return true;
258 // Return an output section named NAME, or NULL if there is none.
260 Output_section*
261 Layout::find_output_section(const char* name) const
263 for (Section_list::const_iterator p = this->section_list_.begin();
264 p != this->section_list_.end();
265 ++p)
266 if (strcmp((*p)->name(), name) == 0)
267 return *p;
268 return NULL;
271 // Return an output segment of type TYPE, with segment flags SET set
272 // and segment flags CLEAR clear. Return NULL if there is none.
274 Output_segment*
275 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
276 elfcpp::Elf_Word clear) const
278 for (Segment_list::const_iterator p = this->segment_list_.begin();
279 p != this->segment_list_.end();
280 ++p)
281 if (static_cast<elfcpp::PT>((*p)->type()) == type
282 && ((*p)->flags() & set) == set
283 && ((*p)->flags() & clear) == 0)
284 return *p;
285 return NULL;
288 // Return the output section to use for section NAME with type TYPE
289 // and section flags FLAGS. NAME must be canonicalized in the string
290 // pool, and NAME_KEY is the key.
292 Output_section*
293 Layout::get_output_section(const char* name, Stringpool::Key name_key,
294 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
296 elfcpp::Elf_Xword lookup_flags = flags;
298 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
299 // read-write with read-only sections. Some other ELF linkers do
300 // not do this. FIXME: Perhaps there should be an option
301 // controlling this.
302 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
304 const Key key(name_key, std::make_pair(type, lookup_flags));
305 const std::pair<Key, Output_section*> v(key, NULL);
306 std::pair<Section_name_map::iterator, bool> ins(
307 this->section_name_map_.insert(v));
309 if (!ins.second)
310 return ins.first->second;
311 else
313 // This is the first time we've seen this name/type/flags
314 // combination. For compatibility with the GNU linker, we
315 // combine sections with contents and zero flags with sections
316 // with non-zero flags. This is a workaround for cases where
317 // assembler code forgets to set section flags. FIXME: Perhaps
318 // there should be an option to control this.
319 Output_section* os = NULL;
321 if (type == elfcpp::SHT_PROGBITS)
323 if (flags == 0)
325 Output_section* same_name = this->find_output_section(name);
326 if (same_name != NULL
327 && same_name->type() == elfcpp::SHT_PROGBITS
328 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
329 os = same_name;
331 else if ((flags & elfcpp::SHF_TLS) == 0)
333 elfcpp::Elf_Xword zero_flags = 0;
334 const Key zero_key(name_key, std::make_pair(type, zero_flags));
335 Section_name_map::iterator p =
336 this->section_name_map_.find(zero_key);
337 if (p != this->section_name_map_.end())
338 os = p->second;
342 if (os == NULL)
343 os = this->make_output_section(name, type, flags);
344 ins.first->second = os;
345 return os;
349 // Pick the output section to use for section NAME, in input file
350 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
351 // linker created section. IS_INPUT_SECTION is true if we are
352 // choosing an output section for an input section found in a input
353 // file. This will return NULL if the input section should be
354 // discarded.
356 Output_section*
357 Layout::choose_output_section(const Relobj* relobj, const char* name,
358 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
359 bool is_input_section)
361 // We should not see any input sections after we have attached
362 // sections to segments.
363 gold_assert(!is_input_section || !this->sections_are_attached_);
365 // Some flags in the input section should not be automatically
366 // copied to the output section.
367 flags &= ~ (elfcpp::SHF_INFO_LINK
368 | elfcpp::SHF_LINK_ORDER
369 | elfcpp::SHF_GROUP
370 | elfcpp::SHF_MERGE
371 | elfcpp::SHF_STRINGS);
373 if (this->script_options_->saw_sections_clause())
375 // We are using a SECTIONS clause, so the output section is
376 // chosen based only on the name.
378 Script_sections* ss = this->script_options_->script_sections();
379 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
380 Output_section** output_section_slot;
381 name = ss->output_section_name(file_name, name, &output_section_slot);
382 if (name == NULL)
384 // The SECTIONS clause says to discard this input section.
385 return NULL;
388 // If this is an orphan section--one not mentioned in the linker
389 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
390 // default processing below.
392 if (output_section_slot != NULL)
394 if (*output_section_slot != NULL)
395 return *output_section_slot;
397 // We don't put sections found in the linker script into
398 // SECTION_NAME_MAP_. That keeps us from getting confused
399 // if an orphan section is mapped to a section with the same
400 // name as one in the linker script.
402 name = this->namepool_.add(name, false, NULL);
404 Output_section* os = this->make_output_section(name, type, flags);
405 os->set_found_in_sections_clause();
406 *output_section_slot = os;
407 return os;
411 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
413 // Turn NAME from the name of the input section into the name of the
414 // output section.
416 size_t len = strlen(name);
417 if (is_input_section && !parameters->options().relocatable())
418 name = Layout::output_section_name(name, &len);
420 Stringpool::Key name_key;
421 name = this->namepool_.add_with_length(name, len, true, &name_key);
423 // Find or make the output section. The output section is selected
424 // based on the section name, type, and flags.
425 return this->get_output_section(name, name_key, type, flags);
428 // Return the output section to use for input section SHNDX, with name
429 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
430 // index of a relocation section which applies to this section, or 0
431 // if none, or -1U if more than one. RELOC_TYPE is the type of the
432 // relocation section if there is one. Set *OFF to the offset of this
433 // input section without the output section. Return NULL if the
434 // section should be discarded. Set *OFF to -1 if the section
435 // contents should not be written directly to the output file, but
436 // will instead receive special handling.
438 template<int size, bool big_endian>
439 Output_section*
440 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
441 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
442 unsigned int reloc_shndx, unsigned int, off_t* off)
444 if (!this->include_section(object, name, shdr))
445 return NULL;
447 Output_section* os;
449 // In a relocatable link a grouped section must not be combined with
450 // any other sections.
451 if (parameters->options().relocatable()
452 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
454 name = this->namepool_.add(name, true, NULL);
455 os = this->make_output_section(name, shdr.get_sh_type(),
456 shdr.get_sh_flags());
458 else
460 os = this->choose_output_section(object, name, shdr.get_sh_type(),
461 shdr.get_sh_flags(), true);
462 if (os == NULL)
463 return NULL;
466 // By default the GNU linker sorts input sections whose names match
467 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
468 // are sorted by name. This is used to implement constructor
469 // priority ordering. We are compatible.
470 if (!this->script_options_->saw_sections_clause()
471 && (is_prefix_of(".ctors.", name)
472 || is_prefix_of(".dtors.", name)
473 || is_prefix_of(".init_array.", name)
474 || is_prefix_of(".fini_array.", name)))
475 os->set_must_sort_attached_input_sections();
477 // FIXME: Handle SHF_LINK_ORDER somewhere.
479 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
480 this->script_options_->saw_sections_clause());
482 return os;
485 // Handle a relocation section when doing a relocatable link.
487 template<int size, bool big_endian>
488 Output_section*
489 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
490 unsigned int,
491 const elfcpp::Shdr<size, big_endian>& shdr,
492 Output_section* data_section,
493 Relocatable_relocs* rr)
495 gold_assert(parameters->options().relocatable()
496 || parameters->options().emit_relocs());
498 int sh_type = shdr.get_sh_type();
500 std::string name;
501 if (sh_type == elfcpp::SHT_REL)
502 name = ".rel";
503 else if (sh_type == elfcpp::SHT_RELA)
504 name = ".rela";
505 else
506 gold_unreachable();
507 name += data_section->name();
509 Output_section* os = this->choose_output_section(object, name.c_str(),
510 sh_type,
511 shdr.get_sh_flags(),
512 false);
514 os->set_should_link_to_symtab();
515 os->set_info_section(data_section);
517 Output_section_data* posd;
518 if (sh_type == elfcpp::SHT_REL)
520 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
521 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
522 size,
523 big_endian>(rr);
525 else if (sh_type == elfcpp::SHT_RELA)
527 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
528 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
529 size,
530 big_endian>(rr);
532 else
533 gold_unreachable();
535 os->add_output_section_data(posd);
536 rr->set_output_data(posd);
538 return os;
541 // Handle a group section when doing a relocatable link.
543 template<int size, bool big_endian>
544 void
545 Layout::layout_group(Symbol_table* symtab,
546 Sized_relobj<size, big_endian>* object,
547 unsigned int,
548 const char* group_section_name,
549 const char* signature,
550 const elfcpp::Shdr<size, big_endian>& shdr,
551 elfcpp::Elf_Word flags,
552 std::vector<unsigned int>* shndxes)
554 gold_assert(parameters->options().relocatable());
555 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
556 group_section_name = this->namepool_.add(group_section_name, true, NULL);
557 Output_section* os = this->make_output_section(group_section_name,
558 elfcpp::SHT_GROUP,
559 shdr.get_sh_flags());
561 // We need to find a symbol with the signature in the symbol table.
562 // If we don't find one now, we need to look again later.
563 Symbol* sym = symtab->lookup(signature, NULL);
564 if (sym != NULL)
565 os->set_info_symndx(sym);
566 else
568 // We will wind up using a symbol whose name is the signature.
569 // So just put the signature in the symbol name pool to save it.
570 signature = symtab->canonicalize_name(signature);
571 this->group_signatures_.push_back(Group_signature(os, signature));
574 os->set_should_link_to_symtab();
575 os->set_entsize(4);
577 section_size_type entry_count =
578 convert_to_section_size_type(shdr.get_sh_size() / 4);
579 Output_section_data* posd =
580 new Output_data_group<size, big_endian>(object, entry_count, flags,
581 shndxes);
582 os->add_output_section_data(posd);
585 // Special GNU handling of sections name .eh_frame. They will
586 // normally hold exception frame data as defined by the C++ ABI
587 // (http://codesourcery.com/cxx-abi/).
589 template<int size, bool big_endian>
590 Output_section*
591 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
592 const unsigned char* symbols,
593 off_t symbols_size,
594 const unsigned char* symbol_names,
595 off_t symbol_names_size,
596 unsigned int shndx,
597 const elfcpp::Shdr<size, big_endian>& shdr,
598 unsigned int reloc_shndx, unsigned int reloc_type,
599 off_t* off)
601 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
602 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
604 const char* const name = ".eh_frame";
605 Output_section* os = this->choose_output_section(object,
606 name,
607 elfcpp::SHT_PROGBITS,
608 elfcpp::SHF_ALLOC,
609 false);
610 if (os == NULL)
611 return NULL;
613 if (this->eh_frame_section_ == NULL)
615 this->eh_frame_section_ = os;
616 this->eh_frame_data_ = new Eh_frame();
618 if (this->options_.eh_frame_hdr())
620 Output_section* hdr_os =
621 this->choose_output_section(NULL,
622 ".eh_frame_hdr",
623 elfcpp::SHT_PROGBITS,
624 elfcpp::SHF_ALLOC,
625 false);
627 if (hdr_os != NULL)
629 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
630 this->eh_frame_data_);
631 hdr_os->add_output_section_data(hdr_posd);
633 hdr_os->set_after_input_sections();
635 if (!this->script_options_->saw_phdrs_clause())
637 Output_segment* hdr_oseg;
638 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
639 elfcpp::PF_R);
640 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
643 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
648 gold_assert(this->eh_frame_section_ == os);
650 if (this->eh_frame_data_->add_ehframe_input_section(object,
651 symbols,
652 symbols_size,
653 symbol_names,
654 symbol_names_size,
655 shndx,
656 reloc_shndx,
657 reloc_type))
659 os->update_flags_for_input_section(shdr.get_sh_flags());
661 // We found a .eh_frame section we are going to optimize, so now
662 // we can add the set of optimized sections to the output
663 // section. We need to postpone adding this until we've found a
664 // section we can optimize so that the .eh_frame section in
665 // crtbegin.o winds up at the start of the output section.
666 if (!this->added_eh_frame_data_)
668 os->add_output_section_data(this->eh_frame_data_);
669 this->added_eh_frame_data_ = true;
671 *off = -1;
673 else
675 // We couldn't handle this .eh_frame section for some reason.
676 // Add it as a normal section.
677 bool saw_sections_clause = this->script_options_->saw_sections_clause();
678 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
679 saw_sections_clause);
682 return os;
685 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
686 // the output section.
688 Output_section*
689 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
690 elfcpp::Elf_Xword flags,
691 Output_section_data* posd)
693 Output_section* os = this->choose_output_section(NULL, name, type, flags,
694 false);
695 if (os != NULL)
696 os->add_output_section_data(posd);
697 return os;
700 // Map section flags to segment flags.
702 elfcpp::Elf_Word
703 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
705 elfcpp::Elf_Word ret = elfcpp::PF_R;
706 if ((flags & elfcpp::SHF_WRITE) != 0)
707 ret |= elfcpp::PF_W;
708 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
709 ret |= elfcpp::PF_X;
710 return ret;
713 // Sometimes we compress sections. This is typically done for
714 // sections that are not part of normal program execution (such as
715 // .debug_* sections), and where the readers of these sections know
716 // how to deal with compressed sections. (To make it easier for them,
717 // we will rename the ouput section in such cases from .foo to
718 // .foo.zlib.nnnn, where nnnn is the uncompressed size.) This routine
719 // doesn't say for certain whether we'll compress -- it depends on
720 // commandline options as well -- just whether this section is a
721 // candidate for compression.
723 static bool
724 is_compressible_debug_section(const char* secname)
726 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
729 // Make a new Output_section, and attach it to segments as
730 // appropriate.
732 Output_section*
733 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
734 elfcpp::Elf_Xword flags)
736 Output_section* os;
737 if ((flags & elfcpp::SHF_ALLOC) == 0
738 && strcmp(this->options_.compress_debug_sections(), "none") != 0
739 && is_compressible_debug_section(name))
740 os = new Output_compressed_section(&this->options_, name, type, flags);
742 else if ((flags & elfcpp::SHF_ALLOC) == 0
743 && this->options_.strip_debug_non_line()
744 && strcmp(".debug_abbrev", name) == 0)
746 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
747 name, type, flags);
748 if (this->debug_info_)
749 this->debug_info_->set_abbreviations(this->debug_abbrev_);
751 else if ((flags & elfcpp::SHF_ALLOC) == 0
752 && this->options_.strip_debug_non_line()
753 && strcmp(".debug_info", name) == 0)
755 os = this->debug_info_ = new Output_reduced_debug_info_section(
756 name, type, flags);
757 if (this->debug_abbrev_)
758 this->debug_info_->set_abbreviations(this->debug_abbrev_);
760 else
761 os = new Output_section(name, type, flags);
763 this->section_list_.push_back(os);
765 // The GNU linker by default sorts some sections by priority, so we
766 // do the same. We need to know that this might happen before we
767 // attach any input sections.
768 if (!this->script_options_->saw_sections_clause()
769 && (strcmp(name, ".ctors") == 0
770 || strcmp(name, ".dtors") == 0
771 || strcmp(name, ".init_array") == 0
772 || strcmp(name, ".fini_array") == 0))
773 os->set_may_sort_attached_input_sections();
775 // With -z relro, we have to recognize the special sections by name.
776 // There is no other way.
777 if (!this->script_options_->saw_sections_clause()
778 && parameters->options().relro()
779 && type == elfcpp::SHT_PROGBITS
780 && (flags & elfcpp::SHF_ALLOC) != 0
781 && (flags & elfcpp::SHF_WRITE) != 0)
783 if (strcmp(name, ".data.rel.ro") == 0)
784 os->set_is_relro();
785 else if (strcmp(name, ".data.rel.ro.local") == 0)
787 os->set_is_relro();
788 os->set_is_relro_local();
792 // If we have already attached the sections to segments, then we
793 // need to attach this one now. This happens for sections created
794 // directly by the linker.
795 if (this->sections_are_attached_)
796 this->attach_section_to_segment(os);
798 return os;
801 // Attach output sections to segments. This is called after we have
802 // seen all the input sections.
804 void
805 Layout::attach_sections_to_segments()
807 for (Section_list::iterator p = this->section_list_.begin();
808 p != this->section_list_.end();
809 ++p)
810 this->attach_section_to_segment(*p);
812 this->sections_are_attached_ = true;
815 // Attach an output section to a segment.
817 void
818 Layout::attach_section_to_segment(Output_section* os)
820 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
821 this->unattached_section_list_.push_back(os);
822 else
823 this->attach_allocated_section_to_segment(os);
826 // Attach an allocated output section to a segment.
828 void
829 Layout::attach_allocated_section_to_segment(Output_section* os)
831 elfcpp::Elf_Xword flags = os->flags();
832 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
834 if (parameters->options().relocatable())
835 return;
837 // If we have a SECTIONS clause, we can't handle the attachment to
838 // segments until after we've seen all the sections.
839 if (this->script_options_->saw_sections_clause())
840 return;
842 gold_assert(!this->script_options_->saw_phdrs_clause());
844 // This output section goes into a PT_LOAD segment.
846 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
848 // In general the only thing we really care about for PT_LOAD
849 // segments is whether or not they are writable, so that is how we
850 // search for them. People who need segments sorted on some other
851 // basis will have to use a linker script.
853 Segment_list::const_iterator p;
854 for (p = this->segment_list_.begin();
855 p != this->segment_list_.end();
856 ++p)
858 if ((*p)->type() == elfcpp::PT_LOAD
859 && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
861 // If -Tbss was specified, we need to separate the data
862 // and BSS segments.
863 if (this->options_.user_set_Tbss())
865 if ((os->type() == elfcpp::SHT_NOBITS)
866 == (*p)->has_any_data_sections())
867 continue;
870 (*p)->add_output_section(os, seg_flags);
871 break;
875 if (p == this->segment_list_.end())
877 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
878 seg_flags);
879 oseg->add_output_section(os, seg_flags);
882 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
883 // segment.
884 if (os->type() == elfcpp::SHT_NOTE)
886 // See if we already have an equivalent PT_NOTE segment.
887 for (p = this->segment_list_.begin();
888 p != segment_list_.end();
889 ++p)
891 if ((*p)->type() == elfcpp::PT_NOTE
892 && (((*p)->flags() & elfcpp::PF_W)
893 == (seg_flags & elfcpp::PF_W)))
895 (*p)->add_output_section(os, seg_flags);
896 break;
900 if (p == this->segment_list_.end())
902 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
903 seg_flags);
904 oseg->add_output_section(os, seg_flags);
908 // If we see a loadable SHF_TLS section, we create a PT_TLS
909 // segment. There can only be one such segment.
910 if ((flags & elfcpp::SHF_TLS) != 0)
912 if (this->tls_segment_ == NULL)
913 this->tls_segment_ = this->make_output_segment(elfcpp::PT_TLS,
914 seg_flags);
915 this->tls_segment_->add_output_section(os, seg_flags);
918 // If -z relro is in effect, and we see a relro section, we create a
919 // PT_GNU_RELRO segment. There can only be one such segment.
920 if (os->is_relro() && parameters->options().relro())
922 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
923 if (this->relro_segment_ == NULL)
924 this->relro_segment_ = this->make_output_segment(elfcpp::PT_GNU_RELRO,
925 seg_flags);
926 this->relro_segment_->add_output_section(os, seg_flags);
930 // Make an output section for a script.
932 Output_section*
933 Layout::make_output_section_for_script(const char* name)
935 name = this->namepool_.add(name, false, NULL);
936 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
937 elfcpp::SHF_ALLOC);
938 os->set_found_in_sections_clause();
939 return os;
942 // Return the number of segments we expect to see.
944 size_t
945 Layout::expected_segment_count() const
947 size_t ret = this->segment_list_.size();
949 // If we didn't see a SECTIONS clause in a linker script, we should
950 // already have the complete list of segments. Otherwise we ask the
951 // SECTIONS clause how many segments it expects, and add in the ones
952 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
954 if (!this->script_options_->saw_sections_clause())
955 return ret;
956 else
958 const Script_sections* ss = this->script_options_->script_sections();
959 return ret + ss->expected_segment_count(this);
963 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
964 // is whether we saw a .note.GNU-stack section in the object file.
965 // GNU_STACK_FLAGS is the section flags. The flags give the
966 // protection required for stack memory. We record this in an
967 // executable as a PT_GNU_STACK segment. If an object file does not
968 // have a .note.GNU-stack segment, we must assume that it is an old
969 // object. On some targets that will force an executable stack.
971 void
972 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
974 if (!seen_gnu_stack)
975 this->input_without_gnu_stack_note_ = true;
976 else
978 this->input_with_gnu_stack_note_ = true;
979 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
980 this->input_requires_executable_stack_ = true;
984 // Create the dynamic sections which are needed before we read the
985 // relocs.
987 void
988 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
990 if (parameters->doing_static_link())
991 return;
993 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
994 elfcpp::SHT_DYNAMIC,
995 (elfcpp::SHF_ALLOC
996 | elfcpp::SHF_WRITE),
997 false);
998 this->dynamic_section_->set_is_relro();
1000 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
1001 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1002 elfcpp::STV_HIDDEN, 0, false, false);
1004 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1006 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1009 // For each output section whose name can be represented as C symbol,
1010 // define __start and __stop symbols for the section. This is a GNU
1011 // extension.
1013 void
1014 Layout::define_section_symbols(Symbol_table* symtab)
1016 for (Section_list::const_iterator p = this->section_list_.begin();
1017 p != this->section_list_.end();
1018 ++p)
1020 const char* const name = (*p)->name();
1021 if (name[strspn(name,
1022 ("0123456789"
1023 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1024 "abcdefghijklmnopqrstuvwxyz"
1025 "_"))]
1026 == '\0')
1028 const std::string name_string(name);
1029 const std::string start_name("__start_" + name_string);
1030 const std::string stop_name("__stop_" + name_string);
1032 symtab->define_in_output_data(start_name.c_str(),
1033 NULL, // version
1035 0, // value
1036 0, // symsize
1037 elfcpp::STT_NOTYPE,
1038 elfcpp::STB_GLOBAL,
1039 elfcpp::STV_DEFAULT,
1040 0, // nonvis
1041 false, // offset_is_from_end
1042 true); // only_if_ref
1044 symtab->define_in_output_data(stop_name.c_str(),
1045 NULL, // version
1047 0, // value
1048 0, // symsize
1049 elfcpp::STT_NOTYPE,
1050 elfcpp::STB_GLOBAL,
1051 elfcpp::STV_DEFAULT,
1052 0, // nonvis
1053 true, // offset_is_from_end
1054 true); // only_if_ref
1059 // Define symbols for group signatures.
1061 void
1062 Layout::define_group_signatures(Symbol_table* symtab)
1064 for (Group_signatures::iterator p = this->group_signatures_.begin();
1065 p != this->group_signatures_.end();
1066 ++p)
1068 Symbol* sym = symtab->lookup(p->signature, NULL);
1069 if (sym != NULL)
1070 p->section->set_info_symndx(sym);
1071 else
1073 // Force the name of the group section to the group
1074 // signature, and use the group's section symbol as the
1075 // signature symbol.
1076 if (strcmp(p->section->name(), p->signature) != 0)
1078 const char* name = this->namepool_.add(p->signature,
1079 true, NULL);
1080 p->section->set_name(name);
1082 p->section->set_needs_symtab_index();
1083 p->section->set_info_section_symndx(p->section);
1087 this->group_signatures_.clear();
1090 // Find the first read-only PT_LOAD segment, creating one if
1091 // necessary.
1093 Output_segment*
1094 Layout::find_first_load_seg()
1096 for (Segment_list::const_iterator p = this->segment_list_.begin();
1097 p != this->segment_list_.end();
1098 ++p)
1100 if ((*p)->type() == elfcpp::PT_LOAD
1101 && ((*p)->flags() & elfcpp::PF_R) != 0
1102 && ((*p)->flags() & elfcpp::PF_W) == 0)
1103 return *p;
1106 gold_assert(!this->script_options_->saw_phdrs_clause());
1108 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1109 elfcpp::PF_R);
1110 return load_seg;
1113 // Finalize the layout. When this is called, we have created all the
1114 // output sections and all the output segments which are based on
1115 // input sections. We have several things to do, and we have to do
1116 // them in the right order, so that we get the right results correctly
1117 // and efficiently.
1119 // 1) Finalize the list of output segments and create the segment
1120 // table header.
1122 // 2) Finalize the dynamic symbol table and associated sections.
1124 // 3) Determine the final file offset of all the output segments.
1126 // 4) Determine the final file offset of all the SHF_ALLOC output
1127 // sections.
1129 // 5) Create the symbol table sections and the section name table
1130 // section.
1132 // 6) Finalize the symbol table: set symbol values to their final
1133 // value and make a final determination of which symbols are going
1134 // into the output symbol table.
1136 // 7) Create the section table header.
1138 // 8) Determine the final file offset of all the output sections which
1139 // are not SHF_ALLOC, including the section table header.
1141 // 9) Finalize the ELF file header.
1143 // This function returns the size of the output file.
1145 off_t
1146 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1147 Target* target, const Task* task)
1149 target->finalize_sections(this);
1151 this->count_local_symbols(task, input_objects);
1153 this->create_gold_note();
1154 this->create_executable_stack_info(target);
1155 this->create_build_id();
1157 Output_segment* phdr_seg = NULL;
1158 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1160 // There was a dynamic object in the link. We need to create
1161 // some information for the dynamic linker.
1163 // Create the PT_PHDR segment which will hold the program
1164 // headers.
1165 if (!this->script_options_->saw_phdrs_clause())
1166 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1168 // Create the dynamic symbol table, including the hash table.
1169 Output_section* dynstr;
1170 std::vector<Symbol*> dynamic_symbols;
1171 unsigned int local_dynamic_count;
1172 Versions versions(*this->script_options()->version_script_info(),
1173 &this->dynpool_);
1174 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1175 &local_dynamic_count, &dynamic_symbols,
1176 &versions);
1178 // Create the .interp section to hold the name of the
1179 // interpreter, and put it in a PT_INTERP segment.
1180 if (!parameters->options().shared())
1181 this->create_interp(target);
1183 // Finish the .dynamic section to hold the dynamic data, and put
1184 // it in a PT_DYNAMIC segment.
1185 this->finish_dynamic_section(input_objects, symtab);
1187 // We should have added everything we need to the dynamic string
1188 // table.
1189 this->dynpool_.set_string_offsets();
1191 // Create the version sections. We can't do this until the
1192 // dynamic string table is complete.
1193 this->create_version_sections(&versions, symtab, local_dynamic_count,
1194 dynamic_symbols, dynstr);
1197 // If there is a SECTIONS clause, put all the input sections into
1198 // the required order.
1199 Output_segment* load_seg;
1200 if (this->script_options_->saw_sections_clause())
1201 load_seg = this->set_section_addresses_from_script(symtab);
1202 else if (parameters->options().relocatable())
1203 load_seg = NULL;
1204 else
1205 load_seg = this->find_first_load_seg();
1207 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
1208 load_seg = NULL;
1210 gold_assert(phdr_seg == NULL || load_seg != NULL);
1212 // Lay out the segment headers.
1213 Output_segment_headers* segment_headers;
1214 if (parameters->options().relocatable())
1215 segment_headers = NULL;
1216 else
1218 segment_headers = new Output_segment_headers(this->segment_list_);
1219 if (load_seg != NULL)
1220 load_seg->add_initial_output_data(segment_headers);
1221 if (phdr_seg != NULL)
1222 phdr_seg->add_initial_output_data(segment_headers);
1225 // Lay out the file header.
1226 Output_file_header* file_header;
1227 file_header = new Output_file_header(target, symtab, segment_headers,
1228 this->options_.entry());
1229 if (load_seg != NULL)
1230 load_seg->add_initial_output_data(file_header);
1232 this->special_output_list_.push_back(file_header);
1233 if (segment_headers != NULL)
1234 this->special_output_list_.push_back(segment_headers);
1236 if (this->script_options_->saw_phdrs_clause()
1237 && !parameters->options().relocatable())
1239 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1240 // clause in a linker script.
1241 Script_sections* ss = this->script_options_->script_sections();
1242 ss->put_headers_in_phdrs(file_header, segment_headers);
1245 // We set the output section indexes in set_segment_offsets and
1246 // set_section_indexes.
1247 unsigned int shndx = 1;
1249 // Set the file offsets of all the segments, and all the sections
1250 // they contain.
1251 off_t off;
1252 if (!parameters->options().relocatable())
1253 off = this->set_segment_offsets(target, load_seg, &shndx);
1254 else
1255 off = this->set_relocatable_section_offsets(file_header, &shndx);
1257 // Set the file offsets of all the non-data sections we've seen so
1258 // far which don't have to wait for the input sections. We need
1259 // this in order to finalize local symbols in non-allocated
1260 // sections.
1261 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1263 // Set the section indexes of all unallocated sections seen so far,
1264 // in case any of them are somehow referenced by a symbol.
1265 shndx = this->set_section_indexes(shndx);
1267 // Create the symbol table sections.
1268 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1269 if (!parameters->doing_static_link())
1270 this->assign_local_dynsym_offsets(input_objects);
1272 // Process any symbol assignments from a linker script. This must
1273 // be called after the symbol table has been finalized.
1274 this->script_options_->finalize_symbols(symtab, this);
1276 // Create the .shstrtab section.
1277 Output_section* shstrtab_section = this->create_shstrtab();
1279 // Set the file offsets of the rest of the non-data sections which
1280 // don't have to wait for the input sections.
1281 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1283 // Now that all sections have been created, set the section indexes
1284 // for any sections which haven't been done yet.
1285 shndx = this->set_section_indexes(shndx);
1287 // Create the section table header.
1288 this->create_shdrs(shstrtab_section, &off);
1290 // If there are no sections which require postprocessing, we can
1291 // handle the section names now, and avoid a resize later.
1292 if (!this->any_postprocessing_sections_)
1293 off = this->set_section_offsets(off,
1294 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1296 file_header->set_section_info(this->section_headers_, shstrtab_section);
1298 // Now we know exactly where everything goes in the output file
1299 // (except for non-allocated sections which require postprocessing).
1300 Output_data::layout_complete();
1302 this->output_file_size_ = off;
1304 return off;
1307 // Create a note header following the format defined in the ELF ABI.
1308 // NAME is the name, NOTE_TYPE is the type, DESCSZ is the size of the
1309 // descriptor. ALLOCATE is true if the section should be allocated in
1310 // memory. This returns the new note section. It sets
1311 // *TRAILING_PADDING to the number of trailing zero bytes required.
1313 Output_section*
1314 Layout::create_note(const char* name, int note_type, size_t descsz,
1315 bool allocate, size_t* trailing_padding)
1317 // Authorities all agree that the values in a .note field should
1318 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1319 // they differ on what the alignment is for 64-bit binaries.
1320 // The GABI says unambiguously they take 8-byte alignment:
1321 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1322 // Other documentation says alignment should always be 4 bytes:
1323 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1324 // GNU ld and GNU readelf both support the latter (at least as of
1325 // version 2.16.91), and glibc always generates the latter for
1326 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1327 // here.
1328 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
1329 const int size = parameters->target().get_size();
1330 #else
1331 const int size = 32;
1332 #endif
1334 // The contents of the .note section.
1335 size_t namesz = strlen(name) + 1;
1336 size_t aligned_namesz = align_address(namesz, size / 8);
1337 size_t aligned_descsz = align_address(descsz, size / 8);
1339 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
1341 unsigned char* buffer = new unsigned char[notehdrsz];
1342 memset(buffer, 0, notehdrsz);
1344 bool is_big_endian = parameters->target().is_big_endian();
1346 if (size == 32)
1348 if (!is_big_endian)
1350 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1351 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1352 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1354 else
1356 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1357 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1358 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1361 else if (size == 64)
1363 if (!is_big_endian)
1365 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1366 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1367 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1369 else
1371 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1372 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1373 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1376 else
1377 gold_unreachable();
1379 memcpy(buffer + 3 * (size / 8), name, namesz);
1381 const char* note_name = this->namepool_.add(".note", false, NULL);
1382 elfcpp::Elf_Xword flags = 0;
1383 if (allocate)
1384 flags = elfcpp::SHF_ALLOC;
1385 Output_section* os = this->make_output_section(note_name,
1386 elfcpp::SHT_NOTE,
1387 flags);
1388 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
1389 size / 8,
1390 "** note header");
1391 os->add_output_section_data(posd);
1393 *trailing_padding = aligned_descsz - descsz;
1395 return os;
1398 // For an executable or shared library, create a note to record the
1399 // version of gold used to create the binary.
1401 void
1402 Layout::create_gold_note()
1404 if (parameters->options().relocatable())
1405 return;
1407 std::string desc = std::string("gold ") + gold::get_version_string();
1409 size_t trailing_padding;
1410 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
1411 desc.size(), false, &trailing_padding);
1413 Output_section_data* posd = new Output_data_const(desc, 4);
1414 os->add_output_section_data(posd);
1416 if (trailing_padding > 0)
1418 posd = new Output_data_zero_fill(trailing_padding, 0);
1419 os->add_output_section_data(posd);
1423 // Record whether the stack should be executable. This can be set
1424 // from the command line using the -z execstack or -z noexecstack
1425 // options. Otherwise, if any input file has a .note.GNU-stack
1426 // section with the SHF_EXECINSTR flag set, the stack should be
1427 // executable. Otherwise, if at least one input file a
1428 // .note.GNU-stack section, and some input file has no .note.GNU-stack
1429 // section, we use the target default for whether the stack should be
1430 // executable. Otherwise, we don't generate a stack note. When
1431 // generating a object file, we create a .note.GNU-stack section with
1432 // the appropriate marking. When generating an executable or shared
1433 // library, we create a PT_GNU_STACK segment.
1435 void
1436 Layout::create_executable_stack_info(const Target* target)
1438 bool is_stack_executable;
1439 if (this->options_.is_execstack_set())
1440 is_stack_executable = this->options_.is_stack_executable();
1441 else if (!this->input_with_gnu_stack_note_)
1442 return;
1443 else
1445 if (this->input_requires_executable_stack_)
1446 is_stack_executable = true;
1447 else if (this->input_without_gnu_stack_note_)
1448 is_stack_executable = target->is_default_stack_executable();
1449 else
1450 is_stack_executable = false;
1453 if (parameters->options().relocatable())
1455 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1456 elfcpp::Elf_Xword flags = 0;
1457 if (is_stack_executable)
1458 flags |= elfcpp::SHF_EXECINSTR;
1459 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1461 else
1463 if (this->script_options_->saw_phdrs_clause())
1464 return;
1465 int flags = elfcpp::PF_R | elfcpp::PF_W;
1466 if (is_stack_executable)
1467 flags |= elfcpp::PF_X;
1468 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
1472 // If --build-id was used, set up the build ID note.
1474 void
1475 Layout::create_build_id()
1477 if (!parameters->options().user_set_build_id())
1478 return;
1480 const char* style = parameters->options().build_id();
1481 if (strcmp(style, "none") == 0)
1482 return;
1484 // Set DESCSZ to the size of the note descriptor. When possible,
1485 // set DESC to the note descriptor contents.
1486 size_t descsz;
1487 std::string desc;
1488 if (strcmp(style, "md5") == 0)
1489 descsz = 128 / 8;
1490 else if (strcmp(style, "sha1") == 0)
1491 descsz = 160 / 8;
1492 else if (strcmp(style, "uuid") == 0)
1494 const size_t uuidsz = 128 / 8;
1496 char buffer[uuidsz];
1497 memset(buffer, 0, uuidsz);
1499 int descriptor = ::open("/dev/urandom", O_RDONLY);
1500 if (descriptor < 0)
1501 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1502 strerror(errno));
1503 else
1505 ssize_t got = ::read(descriptor, buffer, uuidsz);
1506 ::close(descriptor);
1507 if (got < 0)
1508 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1509 else if (static_cast<size_t>(got) != uuidsz)
1510 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1511 uuidsz, got);
1514 desc.assign(buffer, uuidsz);
1515 descsz = uuidsz;
1517 else if (strncmp(style, "0x", 2) == 0)
1519 hex_init();
1520 const char* p = style + 2;
1521 while (*p != '\0')
1523 if (hex_p(p[0]) && hex_p(p[1]))
1525 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1526 desc += c;
1527 p += 2;
1529 else if (*p == '-' || *p == ':')
1530 ++p;
1531 else
1532 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1533 style);
1535 descsz = desc.size();
1537 else
1538 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1540 // Create the note.
1541 size_t trailing_padding;
1542 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
1543 descsz, true, &trailing_padding);
1545 if (!desc.empty())
1547 // We know the value already, so we fill it in now.
1548 gold_assert(desc.size() == descsz);
1550 Output_section_data* posd = new Output_data_const(desc, 4);
1551 os->add_output_section_data(posd);
1553 if (trailing_padding != 0)
1555 posd = new Output_data_zero_fill(trailing_padding, 0);
1556 os->add_output_section_data(posd);
1559 else
1561 // We need to compute a checksum after we have completed the
1562 // link.
1563 gold_assert(trailing_padding == 0);
1564 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
1565 os->add_output_section_data(this->build_id_note_);
1566 os->set_after_input_sections();
1570 // Return whether SEG1 should be before SEG2 in the output file. This
1571 // is based entirely on the segment type and flags. When this is
1572 // called the segment addresses has normally not yet been set.
1574 bool
1575 Layout::segment_precedes(const Output_segment* seg1,
1576 const Output_segment* seg2)
1578 elfcpp::Elf_Word type1 = seg1->type();
1579 elfcpp::Elf_Word type2 = seg2->type();
1581 // The single PT_PHDR segment is required to precede any loadable
1582 // segment. We simply make it always first.
1583 if (type1 == elfcpp::PT_PHDR)
1585 gold_assert(type2 != elfcpp::PT_PHDR);
1586 return true;
1588 if (type2 == elfcpp::PT_PHDR)
1589 return false;
1591 // The single PT_INTERP segment is required to precede any loadable
1592 // segment. We simply make it always second.
1593 if (type1 == elfcpp::PT_INTERP)
1595 gold_assert(type2 != elfcpp::PT_INTERP);
1596 return true;
1598 if (type2 == elfcpp::PT_INTERP)
1599 return false;
1601 // We then put PT_LOAD segments before any other segments.
1602 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1603 return true;
1604 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1605 return false;
1607 // We put the PT_TLS segment last except for the PT_GNU_RELRO
1608 // segment, because that is where the dynamic linker expects to find
1609 // it (this is just for efficiency; other positions would also work
1610 // correctly).
1611 if (type1 == elfcpp::PT_TLS
1612 && type2 != elfcpp::PT_TLS
1613 && type2 != elfcpp::PT_GNU_RELRO)
1614 return false;
1615 if (type2 == elfcpp::PT_TLS
1616 && type1 != elfcpp::PT_TLS
1617 && type1 != elfcpp::PT_GNU_RELRO)
1618 return true;
1620 // We put the PT_GNU_RELRO segment last, because that is where the
1621 // dynamic linker expects to find it (as with PT_TLS, this is just
1622 // for efficiency).
1623 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
1624 return false;
1625 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
1626 return true;
1628 const elfcpp::Elf_Word flags1 = seg1->flags();
1629 const elfcpp::Elf_Word flags2 = seg2->flags();
1631 // The order of non-PT_LOAD segments is unimportant. We simply sort
1632 // by the numeric segment type and flags values. There should not
1633 // be more than one segment with the same type and flags.
1634 if (type1 != elfcpp::PT_LOAD)
1636 if (type1 != type2)
1637 return type1 < type2;
1638 gold_assert(flags1 != flags2);
1639 return flags1 < flags2;
1642 // If the addresses are set already, sort by load address.
1643 if (seg1->are_addresses_set())
1645 if (!seg2->are_addresses_set())
1646 return true;
1648 unsigned int section_count1 = seg1->output_section_count();
1649 unsigned int section_count2 = seg2->output_section_count();
1650 if (section_count1 == 0 && section_count2 > 0)
1651 return true;
1652 if (section_count1 > 0 && section_count2 == 0)
1653 return false;
1655 uint64_t paddr1 = seg1->first_section_load_address();
1656 uint64_t paddr2 = seg2->first_section_load_address();
1657 if (paddr1 != paddr2)
1658 return paddr1 < paddr2;
1660 else if (seg2->are_addresses_set())
1661 return false;
1663 // We sort PT_LOAD segments based on the flags. Readonly segments
1664 // come before writable segments. Then writable segments with data
1665 // come before writable segments without data. Then executable
1666 // segments come before non-executable segments. Then the unlikely
1667 // case of a non-readable segment comes before the normal case of a
1668 // readable segment. If there are multiple segments with the same
1669 // type and flags, we require that the address be set, and we sort
1670 // by virtual address and then physical address.
1671 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1672 return (flags1 & elfcpp::PF_W) == 0;
1673 if ((flags1 & elfcpp::PF_W) != 0
1674 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
1675 return seg1->has_any_data_sections();
1676 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1677 return (flags1 & elfcpp::PF_X) != 0;
1678 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1679 return (flags1 & elfcpp::PF_R) == 0;
1681 // We shouldn't get here--we shouldn't create segments which we
1682 // can't distinguish.
1683 gold_unreachable();
1686 // Set the file offsets of all the segments, and all the sections they
1687 // contain. They have all been created. LOAD_SEG must be be laid out
1688 // first. Return the offset of the data to follow.
1690 off_t
1691 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1692 unsigned int *pshndx)
1694 // Sort them into the final order.
1695 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1696 Layout::Compare_segments());
1698 // Find the PT_LOAD segments, and set their addresses and offsets
1699 // and their section's addresses and offsets.
1700 uint64_t addr;
1701 if (this->options_.user_set_Ttext())
1702 addr = this->options_.Ttext();
1703 else if (parameters->options().shared())
1704 addr = 0;
1705 else
1706 addr = target->default_text_segment_address();
1707 off_t off = 0;
1709 // If LOAD_SEG is NULL, then the file header and segment headers
1710 // will not be loadable. But they still need to be at offset 0 in
1711 // the file. Set their offsets now.
1712 if (load_seg == NULL)
1714 for (Data_list::iterator p = this->special_output_list_.begin();
1715 p != this->special_output_list_.end();
1716 ++p)
1718 off = align_address(off, (*p)->addralign());
1719 (*p)->set_address_and_file_offset(0, off);
1720 off += (*p)->data_size();
1724 bool was_readonly = false;
1725 for (Segment_list::iterator p = this->segment_list_.begin();
1726 p != this->segment_list_.end();
1727 ++p)
1729 if ((*p)->type() == elfcpp::PT_LOAD)
1731 if (load_seg != NULL && load_seg != *p)
1732 gold_unreachable();
1733 load_seg = NULL;
1735 bool are_addresses_set = (*p)->are_addresses_set();
1736 if (are_addresses_set)
1738 // When it comes to setting file offsets, we care about
1739 // the physical address.
1740 addr = (*p)->paddr();
1742 else if (this->options_.user_set_Tdata()
1743 && ((*p)->flags() & elfcpp::PF_W) != 0
1744 && (!this->options_.user_set_Tbss()
1745 || (*p)->has_any_data_sections()))
1747 addr = this->options_.Tdata();
1748 are_addresses_set = true;
1750 else if (this->options_.user_set_Tbss()
1751 && ((*p)->flags() & elfcpp::PF_W) != 0
1752 && !(*p)->has_any_data_sections())
1754 addr = this->options_.Tbss();
1755 are_addresses_set = true;
1758 uint64_t orig_addr = addr;
1759 uint64_t orig_off = off;
1761 uint64_t aligned_addr = 0;
1762 uint64_t abi_pagesize = target->abi_pagesize();
1764 // FIXME: This should depend on the -n and -N options.
1765 (*p)->set_minimum_p_align(target->common_pagesize());
1767 if (are_addresses_set)
1769 // Adjust the file offset to the same address modulo the
1770 // page size.
1771 uint64_t unsigned_off = off;
1772 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1773 | (addr & (abi_pagesize - 1)));
1774 if (aligned_off < unsigned_off)
1775 aligned_off += abi_pagesize;
1776 off = aligned_off;
1778 else
1780 // If the last segment was readonly, and this one is
1781 // not, then skip the address forward one page,
1782 // maintaining the same position within the page. This
1783 // lets us store both segments overlapping on a single
1784 // page in the file, but the loader will put them on
1785 // different pages in memory.
1787 addr = align_address(addr, (*p)->maximum_alignment());
1788 aligned_addr = addr;
1790 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1792 if ((addr & (abi_pagesize - 1)) != 0)
1793 addr = addr + abi_pagesize;
1796 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1799 unsigned int shndx_hold = *pshndx;
1800 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
1801 &off, pshndx);
1803 // Now that we know the size of this segment, we may be able
1804 // to save a page in memory, at the cost of wasting some
1805 // file space, by instead aligning to the start of a new
1806 // page. Here we use the real machine page size rather than
1807 // the ABI mandated page size.
1809 if (!are_addresses_set && aligned_addr != addr)
1811 uint64_t common_pagesize = target->common_pagesize();
1812 uint64_t first_off = (common_pagesize
1813 - (aligned_addr
1814 & (common_pagesize - 1)));
1815 uint64_t last_off = new_addr & (common_pagesize - 1);
1816 if (first_off > 0
1817 && last_off > 0
1818 && ((aligned_addr & ~ (common_pagesize - 1))
1819 != (new_addr & ~ (common_pagesize - 1)))
1820 && first_off + last_off <= common_pagesize)
1822 *pshndx = shndx_hold;
1823 addr = align_address(aligned_addr, common_pagesize);
1824 addr = align_address(addr, (*p)->maximum_alignment());
1825 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
1826 new_addr = (*p)->set_section_addresses(this, true, addr,
1827 &off, pshndx);
1831 addr = new_addr;
1833 if (((*p)->flags() & elfcpp::PF_W) == 0)
1834 was_readonly = true;
1838 // Handle the non-PT_LOAD segments, setting their offsets from their
1839 // section's offsets.
1840 for (Segment_list::iterator p = this->segment_list_.begin();
1841 p != this->segment_list_.end();
1842 ++p)
1844 if ((*p)->type() != elfcpp::PT_LOAD)
1845 (*p)->set_offset();
1848 // Set the TLS offsets for each section in the PT_TLS segment.
1849 if (this->tls_segment_ != NULL)
1850 this->tls_segment_->set_tls_offsets();
1852 return off;
1855 // Set the offsets of all the allocated sections when doing a
1856 // relocatable link. This does the same jobs as set_segment_offsets,
1857 // only for a relocatable link.
1859 off_t
1860 Layout::set_relocatable_section_offsets(Output_data* file_header,
1861 unsigned int *pshndx)
1863 off_t off = 0;
1865 file_header->set_address_and_file_offset(0, 0);
1866 off += file_header->data_size();
1868 for (Section_list::iterator p = this->section_list_.begin();
1869 p != this->section_list_.end();
1870 ++p)
1872 // We skip unallocated sections here, except that group sections
1873 // have to come first.
1874 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
1875 && (*p)->type() != elfcpp::SHT_GROUP)
1876 continue;
1878 off = align_address(off, (*p)->addralign());
1880 // The linker script might have set the address.
1881 if (!(*p)->is_address_valid())
1882 (*p)->set_address(0);
1883 (*p)->set_file_offset(off);
1884 (*p)->finalize_data_size();
1885 off += (*p)->data_size();
1887 (*p)->set_out_shndx(*pshndx);
1888 ++*pshndx;
1891 return off;
1894 // Set the file offset of all the sections not associated with a
1895 // segment.
1897 off_t
1898 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
1900 for (Section_list::iterator p = this->unattached_section_list_.begin();
1901 p != this->unattached_section_list_.end();
1902 ++p)
1904 // The symtab section is handled in create_symtab_sections.
1905 if (*p == this->symtab_section_)
1906 continue;
1908 // If we've already set the data size, don't set it again.
1909 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1910 continue;
1912 if (pass == BEFORE_INPUT_SECTIONS_PASS
1913 && (*p)->requires_postprocessing())
1915 (*p)->create_postprocessing_buffer();
1916 this->any_postprocessing_sections_ = true;
1919 if (pass == BEFORE_INPUT_SECTIONS_PASS
1920 && (*p)->after_input_sections())
1921 continue;
1922 else if (pass == POSTPROCESSING_SECTIONS_PASS
1923 && (!(*p)->after_input_sections()
1924 || (*p)->type() == elfcpp::SHT_STRTAB))
1925 continue;
1926 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1927 && (!(*p)->after_input_sections()
1928 || (*p)->type() != elfcpp::SHT_STRTAB))
1929 continue;
1931 off = align_address(off, (*p)->addralign());
1932 (*p)->set_file_offset(off);
1933 (*p)->finalize_data_size();
1934 off += (*p)->data_size();
1936 // At this point the name must be set.
1937 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
1938 this->namepool_.add((*p)->name(), false, NULL);
1940 return off;
1943 // Set the section indexes of all the sections not associated with a
1944 // segment.
1946 unsigned int
1947 Layout::set_section_indexes(unsigned int shndx)
1949 for (Section_list::iterator p = this->unattached_section_list_.begin();
1950 p != this->unattached_section_list_.end();
1951 ++p)
1953 if (!(*p)->has_out_shndx())
1955 (*p)->set_out_shndx(shndx);
1956 ++shndx;
1959 return shndx;
1962 // Set the section addresses according to the linker script. This is
1963 // only called when we see a SECTIONS clause. This returns the
1964 // program segment which should hold the file header and segment
1965 // headers, if any. It will return NULL if they should not be in a
1966 // segment.
1968 Output_segment*
1969 Layout::set_section_addresses_from_script(Symbol_table* symtab)
1971 Script_sections* ss = this->script_options_->script_sections();
1972 gold_assert(ss->saw_sections_clause());
1974 // Place each orphaned output section in the script.
1975 for (Section_list::iterator p = this->section_list_.begin();
1976 p != this->section_list_.end();
1977 ++p)
1979 if (!(*p)->found_in_sections_clause())
1980 ss->place_orphan(*p);
1983 return this->script_options_->set_section_addresses(symtab, this);
1986 // Count the local symbols in the regular symbol table and the dynamic
1987 // symbol table, and build the respective string pools.
1989 void
1990 Layout::count_local_symbols(const Task* task,
1991 const Input_objects* input_objects)
1993 // First, figure out an upper bound on the number of symbols we'll
1994 // be inserting into each pool. This helps us create the pools with
1995 // the right size, to avoid unnecessary hashtable resizing.
1996 unsigned int symbol_count = 0;
1997 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
1998 p != input_objects->relobj_end();
1999 ++p)
2000 symbol_count += (*p)->local_symbol_count();
2002 // Go from "upper bound" to "estimate." We overcount for two
2003 // reasons: we double-count symbols that occur in more than one
2004 // object file, and we count symbols that are dropped from the
2005 // output. Add it all together and assume we overcount by 100%.
2006 symbol_count /= 2;
2008 // We assume all symbols will go into both the sympool and dynpool.
2009 this->sympool_.reserve(symbol_count);
2010 this->dynpool_.reserve(symbol_count);
2012 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2013 p != input_objects->relobj_end();
2014 ++p)
2016 Task_lock_obj<Object> tlo(task, *p);
2017 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2021 // Create the symbol table sections. Here we also set the final
2022 // values of the symbols. At this point all the loadable sections are
2023 // fully laid out. SHNUM is the number of sections so far.
2025 void
2026 Layout::create_symtab_sections(const Input_objects* input_objects,
2027 Symbol_table* symtab,
2028 unsigned int shnum,
2029 off_t* poff)
2031 int symsize;
2032 unsigned int align;
2033 if (parameters->target().get_size() == 32)
2035 symsize = elfcpp::Elf_sizes<32>::sym_size;
2036 align = 4;
2038 else if (parameters->target().get_size() == 64)
2040 symsize = elfcpp::Elf_sizes<64>::sym_size;
2041 align = 8;
2043 else
2044 gold_unreachable();
2046 off_t off = *poff;
2047 off = align_address(off, align);
2048 off_t startoff = off;
2050 // Save space for the dummy symbol at the start of the section. We
2051 // never bother to write this out--it will just be left as zero.
2052 off += symsize;
2053 unsigned int local_symbol_index = 1;
2055 // Add STT_SECTION symbols for each Output section which needs one.
2056 for (Section_list::iterator p = this->section_list_.begin();
2057 p != this->section_list_.end();
2058 ++p)
2060 if (!(*p)->needs_symtab_index())
2061 (*p)->set_symtab_index(-1U);
2062 else
2064 (*p)->set_symtab_index(local_symbol_index);
2065 ++local_symbol_index;
2066 off += symsize;
2070 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2071 p != input_objects->relobj_end();
2072 ++p)
2074 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2075 off);
2076 off += (index - local_symbol_index) * symsize;
2077 local_symbol_index = index;
2080 unsigned int local_symcount = local_symbol_index;
2081 gold_assert(local_symcount * symsize == off - startoff);
2083 off_t dynoff;
2084 size_t dyn_global_index;
2085 size_t dyncount;
2086 if (this->dynsym_section_ == NULL)
2088 dynoff = 0;
2089 dyn_global_index = 0;
2090 dyncount = 0;
2092 else
2094 dyn_global_index = this->dynsym_section_->info();
2095 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2096 dynoff = this->dynsym_section_->offset() + locsize;
2097 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2098 gold_assert(static_cast<off_t>(dyncount * symsize)
2099 == this->dynsym_section_->data_size() - locsize);
2102 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2103 &this->sympool_, &local_symcount);
2105 if (!parameters->options().strip_all())
2107 this->sympool_.set_string_offsets();
2109 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2110 Output_section* osymtab = this->make_output_section(symtab_name,
2111 elfcpp::SHT_SYMTAB,
2113 this->symtab_section_ = osymtab;
2115 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
2116 align,
2117 "** symtab");
2118 osymtab->add_output_section_data(pos);
2120 // We generate a .symtab_shndx section if we have more than
2121 // SHN_LORESERVE sections. Technically it is possible that we
2122 // don't need one, because it is possible that there are no
2123 // symbols in any of sections with indexes larger than
2124 // SHN_LORESERVE. That is probably unusual, though, and it is
2125 // easier to always create one than to compute section indexes
2126 // twice (once here, once when writing out the symbols).
2127 if (shnum >= elfcpp::SHN_LORESERVE)
2129 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2130 false, NULL);
2131 Output_section* osymtab_xindex =
2132 this->make_output_section(symtab_xindex_name,
2133 elfcpp::SHT_SYMTAB_SHNDX, 0);
2135 size_t symcount = (off - startoff) / symsize;
2136 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2138 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2140 osymtab_xindex->set_link_section(osymtab);
2141 osymtab_xindex->set_addralign(4);
2142 osymtab_xindex->set_entsize(4);
2144 osymtab_xindex->set_after_input_sections();
2146 // This tells the driver code to wait until the symbol table
2147 // has written out before writing out the postprocessing
2148 // sections, including the .symtab_shndx section.
2149 this->any_postprocessing_sections_ = true;
2152 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
2153 Output_section* ostrtab = this->make_output_section(strtab_name,
2154 elfcpp::SHT_STRTAB,
2157 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2158 ostrtab->add_output_section_data(pstr);
2160 osymtab->set_file_offset(startoff);
2161 osymtab->finalize_data_size();
2162 osymtab->set_link_section(ostrtab);
2163 osymtab->set_info(local_symcount);
2164 osymtab->set_entsize(symsize);
2166 *poff = off;
2170 // Create the .shstrtab section, which holds the names of the
2171 // sections. At the time this is called, we have created all the
2172 // output sections except .shstrtab itself.
2174 Output_section*
2175 Layout::create_shstrtab()
2177 // FIXME: We don't need to create a .shstrtab section if we are
2178 // stripping everything.
2180 const char* name = this->namepool_.add(".shstrtab", false, NULL);
2182 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
2184 // We can't write out this section until we've set all the section
2185 // names, and we don't set the names of compressed output sections
2186 // until relocations are complete.
2187 os->set_after_input_sections();
2189 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2190 os->add_output_section_data(posd);
2192 return os;
2195 // Create the section headers. SIZE is 32 or 64. OFF is the file
2196 // offset.
2198 void
2199 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
2201 Output_section_headers* oshdrs;
2202 oshdrs = new Output_section_headers(this,
2203 &this->segment_list_,
2204 &this->section_list_,
2205 &this->unattached_section_list_,
2206 &this->namepool_,
2207 shstrtab_section);
2208 off_t off = align_address(*poff, oshdrs->addralign());
2209 oshdrs->set_address_and_file_offset(0, off);
2210 off += oshdrs->data_size();
2211 *poff = off;
2212 this->section_headers_ = oshdrs;
2215 // Count the allocated sections.
2217 size_t
2218 Layout::allocated_output_section_count() const
2220 size_t section_count = 0;
2221 for (Segment_list::const_iterator p = this->segment_list_.begin();
2222 p != this->segment_list_.end();
2223 ++p)
2224 section_count += (*p)->output_section_count();
2225 return section_count;
2228 // Create the dynamic symbol table.
2230 void
2231 Layout::create_dynamic_symtab(const Input_objects* input_objects,
2232 Symbol_table* symtab,
2233 Output_section **pdynstr,
2234 unsigned int* plocal_dynamic_count,
2235 std::vector<Symbol*>* pdynamic_symbols,
2236 Versions* pversions)
2238 // Count all the symbols in the dynamic symbol table, and set the
2239 // dynamic symbol indexes.
2241 // Skip symbol 0, which is always all zeroes.
2242 unsigned int index = 1;
2244 // Add STT_SECTION symbols for each Output section which needs one.
2245 for (Section_list::iterator p = this->section_list_.begin();
2246 p != this->section_list_.end();
2247 ++p)
2249 if (!(*p)->needs_dynsym_index())
2250 (*p)->set_dynsym_index(-1U);
2251 else
2253 (*p)->set_dynsym_index(index);
2254 ++index;
2258 // Count the local symbols that need to go in the dynamic symbol table,
2259 // and set the dynamic symbol indexes.
2260 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2261 p != input_objects->relobj_end();
2262 ++p)
2264 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2265 index = new_index;
2268 unsigned int local_symcount = index;
2269 *plocal_dynamic_count = local_symcount;
2271 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
2272 &this->dynpool_, pversions);
2274 int symsize;
2275 unsigned int align;
2276 const int size = parameters->target().get_size();
2277 if (size == 32)
2279 symsize = elfcpp::Elf_sizes<32>::sym_size;
2280 align = 4;
2282 else if (size == 64)
2284 symsize = elfcpp::Elf_sizes<64>::sym_size;
2285 align = 8;
2287 else
2288 gold_unreachable();
2290 // Create the dynamic symbol table section.
2292 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2293 elfcpp::SHT_DYNSYM,
2294 elfcpp::SHF_ALLOC,
2295 false);
2297 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
2298 align,
2299 "** dynsym");
2300 dynsym->add_output_section_data(odata);
2302 dynsym->set_info(local_symcount);
2303 dynsym->set_entsize(symsize);
2304 dynsym->set_addralign(align);
2306 this->dynsym_section_ = dynsym;
2308 Output_data_dynamic* const odyn = this->dynamic_data_;
2309 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2310 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2312 // If there are more than SHN_LORESERVE allocated sections, we
2313 // create a .dynsym_shndx section. It is possible that we don't
2314 // need one, because it is possible that there are no dynamic
2315 // symbols in any of the sections with indexes larger than
2316 // SHN_LORESERVE. This is probably unusual, though, and at this
2317 // time we don't know the actual section indexes so it is
2318 // inconvenient to check.
2319 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2321 Output_section* dynsym_xindex =
2322 this->choose_output_section(NULL, ".dynsym_shndx",
2323 elfcpp::SHT_SYMTAB_SHNDX,
2324 elfcpp::SHF_ALLOC,
2325 false);
2327 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2329 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2331 dynsym_xindex->set_link_section(dynsym);
2332 dynsym_xindex->set_addralign(4);
2333 dynsym_xindex->set_entsize(4);
2335 dynsym_xindex->set_after_input_sections();
2337 // This tells the driver code to wait until the symbol table has
2338 // written out before writing out the postprocessing sections,
2339 // including the .dynsym_shndx section.
2340 this->any_postprocessing_sections_ = true;
2343 // Create the dynamic string table section.
2345 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2346 elfcpp::SHT_STRTAB,
2347 elfcpp::SHF_ALLOC,
2348 false);
2350 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2351 dynstr->add_output_section_data(strdata);
2353 dynsym->set_link_section(dynstr);
2354 this->dynamic_section_->set_link_section(dynstr);
2356 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2357 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2359 *pdynstr = dynstr;
2361 // Create the hash tables.
2363 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2364 || strcmp(parameters->options().hash_style(), "both") == 0)
2366 unsigned char* phash;
2367 unsigned int hashlen;
2368 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2369 &phash, &hashlen);
2371 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2372 elfcpp::SHT_HASH,
2373 elfcpp::SHF_ALLOC,
2374 false);
2376 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2377 hashlen,
2378 align,
2379 "** hash");
2380 hashsec->add_output_section_data(hashdata);
2382 hashsec->set_link_section(dynsym);
2383 hashsec->set_entsize(4);
2385 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2388 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2389 || strcmp(parameters->options().hash_style(), "both") == 0)
2391 unsigned char* phash;
2392 unsigned int hashlen;
2393 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2394 &phash, &hashlen);
2396 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2397 elfcpp::SHT_GNU_HASH,
2398 elfcpp::SHF_ALLOC,
2399 false);
2401 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2402 hashlen,
2403 align,
2404 "** hash");
2405 hashsec->add_output_section_data(hashdata);
2407 hashsec->set_link_section(dynsym);
2408 hashsec->set_entsize(4);
2410 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2414 // Assign offsets to each local portion of the dynamic symbol table.
2416 void
2417 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2419 Output_section* dynsym = this->dynsym_section_;
2420 gold_assert(dynsym != NULL);
2422 off_t off = dynsym->offset();
2424 // Skip the dummy symbol at the start of the section.
2425 off += dynsym->entsize();
2427 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2428 p != input_objects->relobj_end();
2429 ++p)
2431 unsigned int count = (*p)->set_local_dynsym_offset(off);
2432 off += count * dynsym->entsize();
2436 // Create the version sections.
2438 void
2439 Layout::create_version_sections(const Versions* versions,
2440 const Symbol_table* symtab,
2441 unsigned int local_symcount,
2442 const std::vector<Symbol*>& dynamic_symbols,
2443 const Output_section* dynstr)
2445 if (!versions->any_defs() && !versions->any_needs())
2446 return;
2448 switch (parameters->size_and_endianness())
2450 #ifdef HAVE_TARGET_32_LITTLE
2451 case Parameters::TARGET_32_LITTLE:
2452 this->sized_create_version_sections<32, false>(versions, symtab,
2453 local_symcount,
2454 dynamic_symbols, dynstr);
2455 break;
2456 #endif
2457 #ifdef HAVE_TARGET_32_BIG
2458 case Parameters::TARGET_32_BIG:
2459 this->sized_create_version_sections<32, true>(versions, symtab,
2460 local_symcount,
2461 dynamic_symbols, dynstr);
2462 break;
2463 #endif
2464 #ifdef HAVE_TARGET_64_LITTLE
2465 case Parameters::TARGET_64_LITTLE:
2466 this->sized_create_version_sections<64, false>(versions, symtab,
2467 local_symcount,
2468 dynamic_symbols, dynstr);
2469 break;
2470 #endif
2471 #ifdef HAVE_TARGET_64_BIG
2472 case Parameters::TARGET_64_BIG:
2473 this->sized_create_version_sections<64, true>(versions, symtab,
2474 local_symcount,
2475 dynamic_symbols, dynstr);
2476 break;
2477 #endif
2478 default:
2479 gold_unreachable();
2483 // Create the version sections, sized version.
2485 template<int size, bool big_endian>
2486 void
2487 Layout::sized_create_version_sections(
2488 const Versions* versions,
2489 const Symbol_table* symtab,
2490 unsigned int local_symcount,
2491 const std::vector<Symbol*>& dynamic_symbols,
2492 const Output_section* dynstr)
2494 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2495 elfcpp::SHT_GNU_versym,
2496 elfcpp::SHF_ALLOC,
2497 false);
2499 unsigned char* vbuf;
2500 unsigned int vsize;
2501 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2502 local_symcount,
2503 dynamic_symbols,
2504 &vbuf, &vsize);
2506 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
2507 "** versions");
2509 vsec->add_output_section_data(vdata);
2510 vsec->set_entsize(2);
2511 vsec->set_link_section(this->dynsym_section_);
2513 Output_data_dynamic* const odyn = this->dynamic_data_;
2514 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2516 if (versions->any_defs())
2518 Output_section* vdsec;
2519 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
2520 elfcpp::SHT_GNU_verdef,
2521 elfcpp::SHF_ALLOC,
2522 false);
2524 unsigned char* vdbuf;
2525 unsigned int vdsize;
2526 unsigned int vdentries;
2527 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
2528 &vdsize, &vdentries);
2530 Output_section_data* vddata =
2531 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
2533 vdsec->add_output_section_data(vddata);
2534 vdsec->set_link_section(dynstr);
2535 vdsec->set_info(vdentries);
2537 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
2538 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
2541 if (versions->any_needs())
2543 Output_section* vnsec;
2544 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
2545 elfcpp::SHT_GNU_verneed,
2546 elfcpp::SHF_ALLOC,
2547 false);
2549 unsigned char* vnbuf;
2550 unsigned int vnsize;
2551 unsigned int vnentries;
2552 versions->need_section_contents<size, big_endian>(&this->dynpool_,
2553 &vnbuf, &vnsize,
2554 &vnentries);
2556 Output_section_data* vndata =
2557 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
2559 vnsec->add_output_section_data(vndata);
2560 vnsec->set_link_section(dynstr);
2561 vnsec->set_info(vnentries);
2563 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
2564 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
2568 // Create the .interp section and PT_INTERP segment.
2570 void
2571 Layout::create_interp(const Target* target)
2573 const char* interp = this->options_.dynamic_linker();
2574 if (interp == NULL)
2576 interp = target->dynamic_linker();
2577 gold_assert(interp != NULL);
2580 size_t len = strlen(interp) + 1;
2582 Output_section_data* odata = new Output_data_const(interp, len, 1);
2584 Output_section* osec = this->choose_output_section(NULL, ".interp",
2585 elfcpp::SHT_PROGBITS,
2586 elfcpp::SHF_ALLOC,
2587 false);
2588 osec->add_output_section_data(odata);
2590 if (!this->script_options_->saw_phdrs_clause())
2592 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
2593 elfcpp::PF_R);
2594 oseg->add_output_section(osec, elfcpp::PF_R);
2598 // Finish the .dynamic section and PT_DYNAMIC segment.
2600 void
2601 Layout::finish_dynamic_section(const Input_objects* input_objects,
2602 const Symbol_table* symtab)
2604 if (!this->script_options_->saw_phdrs_clause())
2606 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
2607 (elfcpp::PF_R
2608 | elfcpp::PF_W));
2609 oseg->add_output_section(this->dynamic_section_,
2610 elfcpp::PF_R | elfcpp::PF_W);
2613 Output_data_dynamic* const odyn = this->dynamic_data_;
2615 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
2616 p != input_objects->dynobj_end();
2617 ++p)
2619 // FIXME: Handle --as-needed.
2620 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
2623 if (parameters->options().shared())
2625 const char* soname = this->options_.soname();
2626 if (soname != NULL)
2627 odyn->add_string(elfcpp::DT_SONAME, soname);
2630 // FIXME: Support --init and --fini.
2631 Symbol* sym = symtab->lookup("_init");
2632 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2633 odyn->add_symbol(elfcpp::DT_INIT, sym);
2635 sym = symtab->lookup("_fini");
2636 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
2637 odyn->add_symbol(elfcpp::DT_FINI, sym);
2639 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
2641 // Add a DT_RPATH entry if needed.
2642 const General_options::Dir_list& rpath(this->options_.rpath());
2643 if (!rpath.empty())
2645 std::string rpath_val;
2646 for (General_options::Dir_list::const_iterator p = rpath.begin();
2647 p != rpath.end();
2648 ++p)
2650 if (rpath_val.empty())
2651 rpath_val = p->name();
2652 else
2654 // Eliminate duplicates.
2655 General_options::Dir_list::const_iterator q;
2656 for (q = rpath.begin(); q != p; ++q)
2657 if (q->name() == p->name())
2658 break;
2659 if (q == p)
2661 rpath_val += ':';
2662 rpath_val += p->name();
2667 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
2668 if (parameters->options().enable_new_dtags())
2669 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
2672 // Look for text segments that have dynamic relocations.
2673 bool have_textrel = false;
2674 if (!this->script_options_->saw_sections_clause())
2676 for (Segment_list::const_iterator p = this->segment_list_.begin();
2677 p != this->segment_list_.end();
2678 ++p)
2680 if (((*p)->flags() & elfcpp::PF_W) == 0
2681 && (*p)->dynamic_reloc_count() > 0)
2683 have_textrel = true;
2684 break;
2688 else
2690 // We don't know the section -> segment mapping, so we are
2691 // conservative and just look for readonly sections with
2692 // relocations. If those sections wind up in writable segments,
2693 // then we have created an unnecessary DT_TEXTREL entry.
2694 for (Section_list::const_iterator p = this->section_list_.begin();
2695 p != this->section_list_.end();
2696 ++p)
2698 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
2699 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
2700 && ((*p)->dynamic_reloc_count() > 0))
2702 have_textrel = true;
2703 break;
2708 // Add a DT_FLAGS entry. We add it even if no flags are set so that
2709 // post-link tools can easily modify these flags if desired.
2710 unsigned int flags = 0;
2711 if (have_textrel)
2713 // Add a DT_TEXTREL for compatibility with older loaders.
2714 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
2715 flags |= elfcpp::DF_TEXTREL;
2717 if (parameters->options().shared() && this->has_static_tls())
2718 flags |= elfcpp::DF_STATIC_TLS;
2719 odyn->add_constant(elfcpp::DT_FLAGS, flags);
2721 flags = 0;
2722 if (parameters->options().initfirst())
2723 flags |= elfcpp::DF_1_INITFIRST;
2724 if (parameters->options().interpose())
2725 flags |= elfcpp::DF_1_INTERPOSE;
2726 if (parameters->options().loadfltr())
2727 flags |= elfcpp::DF_1_LOADFLTR;
2728 if (parameters->options().nodefaultlib())
2729 flags |= elfcpp::DF_1_NODEFLIB;
2730 if (parameters->options().nodelete())
2731 flags |= elfcpp::DF_1_NODELETE;
2732 if (parameters->options().nodlopen())
2733 flags |= elfcpp::DF_1_NOOPEN;
2734 if (parameters->options().nodump())
2735 flags |= elfcpp::DF_1_NODUMP;
2736 if (!parameters->options().shared())
2737 flags &= ~(elfcpp::DF_1_INITFIRST
2738 | elfcpp::DF_1_NODELETE
2739 | elfcpp::DF_1_NOOPEN);
2740 if (flags)
2741 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
2744 // The mapping of .gnu.linkonce section names to real section names.
2746 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
2747 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
2749 MAPPING_INIT("d.rel.ro.local", ".data.rel.ro.local"), // Before "d.rel.ro".
2750 MAPPING_INIT("d.rel.ro", ".data.rel.ro"), // Before "d".
2751 MAPPING_INIT("t", ".text"),
2752 MAPPING_INIT("r", ".rodata"),
2753 MAPPING_INIT("d", ".data"),
2754 MAPPING_INIT("b", ".bss"),
2755 MAPPING_INIT("s", ".sdata"),
2756 MAPPING_INIT("sb", ".sbss"),
2757 MAPPING_INIT("s2", ".sdata2"),
2758 MAPPING_INIT("sb2", ".sbss2"),
2759 MAPPING_INIT("wi", ".debug_info"),
2760 MAPPING_INIT("td", ".tdata"),
2761 MAPPING_INIT("tb", ".tbss"),
2762 MAPPING_INIT("lr", ".lrodata"),
2763 MAPPING_INIT("l", ".ldata"),
2764 MAPPING_INIT("lb", ".lbss"),
2766 #undef MAPPING_INIT
2768 const int Layout::linkonce_mapping_count =
2769 sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
2771 // Return the name of the output section to use for a .gnu.linkonce
2772 // section. This is based on the default ELF linker script of the old
2773 // GNU linker. For example, we map a name like ".gnu.linkonce.t.foo"
2774 // to ".text". Set *PLEN to the length of the name. *PLEN is
2775 // initialized to the length of NAME.
2777 const char*
2778 Layout::linkonce_output_name(const char* name, size_t *plen)
2780 const char* s = name + sizeof(".gnu.linkonce") - 1;
2781 if (*s != '.')
2782 return name;
2783 ++s;
2784 const Linkonce_mapping* plm = linkonce_mapping;
2785 for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2787 if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
2789 *plen = plm->tolen;
2790 return plm->to;
2793 return name;
2796 // Choose the output section name to use given an input section name.
2797 // Set *PLEN to the length of the name. *PLEN is initialized to the
2798 // length of NAME.
2800 const char*
2801 Layout::output_section_name(const char* name, size_t* plen)
2803 if (Layout::is_linkonce(name))
2805 // .gnu.linkonce sections are laid out as though they were named
2806 // for the sections are placed into.
2807 return Layout::linkonce_output_name(name, plen);
2810 // gcc 4.3 generates the following sorts of section names when it
2811 // needs a section name specific to a function:
2812 // .text.FN
2813 // .rodata.FN
2814 // .sdata2.FN
2815 // .data.FN
2816 // .data.rel.FN
2817 // .data.rel.local.FN
2818 // .data.rel.ro.FN
2819 // .data.rel.ro.local.FN
2820 // .sdata.FN
2821 // .bss.FN
2822 // .sbss.FN
2823 // .tdata.FN
2824 // .tbss.FN
2826 // The GNU linker maps all of those to the part before the .FN,
2827 // except that .data.rel.local.FN is mapped to .data, and
2828 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
2829 // beginning with .data.rel.ro.local are grouped together.
2831 // For an anonymous namespace, the string FN can contain a '.'.
2833 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2834 // GNU linker maps to .rodata.
2836 // The .data.rel.ro sections enable a security feature triggered by
2837 // the -z relro option. Section which need to be relocated at
2838 // program startup time but which may be readonly after startup are
2839 // grouped into .data.rel.ro. They are then put into a PT_GNU_RELRO
2840 // segment. The dynamic linker will make that segment writable,
2841 // perform relocations, and then make it read-only. FIXME: We do
2842 // not yet implement this optimization.
2844 // It is hard to handle this in a principled way.
2846 // These are the rules we follow:
2848 // If the section name has no initial '.', or no dot other than an
2849 // initial '.', we use the name unchanged (i.e., "mysection" and
2850 // ".text" are unchanged).
2852 // If the name starts with ".data.rel.ro.local" we use
2853 // ".data.rel.ro.local".
2855 // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2857 // Otherwise, we drop the second '.' and everything that comes after
2858 // it (i.e., ".text.XXX" becomes ".text").
2860 const char* s = name;
2861 if (*s != '.')
2862 return name;
2863 ++s;
2864 const char* sdot = strchr(s, '.');
2865 if (sdot == NULL)
2866 return name;
2868 const char* const data_rel_ro_local = ".data.rel.ro.local";
2869 if (strncmp(name, data_rel_ro_local, strlen(data_rel_ro_local)) == 0)
2871 *plen = strlen(data_rel_ro_local);
2872 return data_rel_ro_local;
2875 const char* const data_rel_ro = ".data.rel.ro";
2876 if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
2878 *plen = strlen(data_rel_ro);
2879 return data_rel_ro;
2882 *plen = sdot - name;
2883 return name;
2886 // Record the signature of a comdat section, and return whether to
2887 // include it in the link. If GROUP is true, this is a regular
2888 // section group. If GROUP is false, this is a group signature
2889 // derived from the name of a linkonce section. We want linkonce
2890 // signatures and group signatures to block each other, but we don't
2891 // want a linkonce signature to block another linkonce signature.
2893 bool
2894 Layout::add_comdat(Relobj* object, unsigned int shndx,
2895 const std::string& signature, bool group)
2897 Kept_section kept(object, shndx, group);
2898 std::pair<Signatures::iterator, bool> ins(
2899 this->signatures_.insert(std::make_pair(signature, kept)));
2901 if (ins.second)
2903 // This is the first time we've seen this signature.
2904 return true;
2907 if (ins.first->second.group_)
2909 // We've already seen a real section group with this signature.
2910 return false;
2912 else if (group)
2914 // This is a real section group, and we've already seen a
2915 // linkonce section with this signature. Record that we've seen
2916 // a section group, and don't include this section group.
2917 ins.first->second.group_ = true;
2918 return false;
2920 else
2922 // We've already seen a linkonce section and this is a linkonce
2923 // section. These don't block each other--this may be the same
2924 // symbol name with different section types.
2925 return true;
2929 // Find the given comdat signature, and return the object and section
2930 // index of the kept group.
2931 Relobj*
2932 Layout::find_kept_object(const std::string& signature,
2933 unsigned int* pshndx) const
2935 Signatures::const_iterator p = this->signatures_.find(signature);
2936 if (p == this->signatures_.end())
2937 return NULL;
2938 if (pshndx != NULL)
2939 *pshndx = p->second.shndx_;
2940 return p->second.object_;
2943 // Store the allocated sections into the section list.
2945 void
2946 Layout::get_allocated_sections(Section_list* section_list) const
2948 for (Section_list::const_iterator p = this->section_list_.begin();
2949 p != this->section_list_.end();
2950 ++p)
2951 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2952 section_list->push_back(*p);
2955 // Create an output segment.
2957 Output_segment*
2958 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
2960 gold_assert(!parameters->options().relocatable());
2961 Output_segment* oseg = new Output_segment(type, flags);
2962 this->segment_list_.push_back(oseg);
2963 return oseg;
2966 // Write out the Output_sections. Most won't have anything to write,
2967 // since most of the data will come from input sections which are
2968 // handled elsewhere. But some Output_sections do have Output_data.
2970 void
2971 Layout::write_output_sections(Output_file* of) const
2973 for (Section_list::const_iterator p = this->section_list_.begin();
2974 p != this->section_list_.end();
2975 ++p)
2977 if (!(*p)->after_input_sections())
2978 (*p)->write(of);
2982 // Write out data not associated with a section or the symbol table.
2984 void
2985 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
2987 if (!parameters->options().strip_all())
2989 const Output_section* symtab_section = this->symtab_section_;
2990 for (Section_list::const_iterator p = this->section_list_.begin();
2991 p != this->section_list_.end();
2992 ++p)
2994 if ((*p)->needs_symtab_index())
2996 gold_assert(symtab_section != NULL);
2997 unsigned int index = (*p)->symtab_index();
2998 gold_assert(index > 0 && index != -1U);
2999 off_t off = (symtab_section->offset()
3000 + index * symtab_section->entsize());
3001 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
3006 const Output_section* dynsym_section = this->dynsym_section_;
3007 for (Section_list::const_iterator p = this->section_list_.begin();
3008 p != this->section_list_.end();
3009 ++p)
3011 if ((*p)->needs_dynsym_index())
3013 gold_assert(dynsym_section != NULL);
3014 unsigned int index = (*p)->dynsym_index();
3015 gold_assert(index > 0 && index != -1U);
3016 off_t off = (dynsym_section->offset()
3017 + index * dynsym_section->entsize());
3018 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
3022 // Write out the Output_data which are not in an Output_section.
3023 for (Data_list::const_iterator p = this->special_output_list_.begin();
3024 p != this->special_output_list_.end();
3025 ++p)
3026 (*p)->write(of);
3029 // Write out the Output_sections which can only be written after the
3030 // input sections are complete.
3032 void
3033 Layout::write_sections_after_input_sections(Output_file* of)
3035 // Determine the final section offsets, and thus the final output
3036 // file size. Note we finalize the .shstrab last, to allow the
3037 // after_input_section sections to modify their section-names before
3038 // writing.
3039 if (this->any_postprocessing_sections_)
3041 off_t off = this->output_file_size_;
3042 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
3044 // Now that we've finalized the names, we can finalize the shstrab.
3045 off =
3046 this->set_section_offsets(off,
3047 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3049 if (off > this->output_file_size_)
3051 of->resize(off);
3052 this->output_file_size_ = off;
3056 for (Section_list::const_iterator p = this->section_list_.begin();
3057 p != this->section_list_.end();
3058 ++p)
3060 if ((*p)->after_input_sections())
3061 (*p)->write(of);
3064 this->section_headers_->write(of);
3067 // If the build ID requires computing a checksum, do so here, and
3068 // write it out. We compute a checksum over the entire file because
3069 // that is simplest.
3071 void
3072 Layout::write_build_id(Output_file* of) const
3074 if (this->build_id_note_ == NULL)
3075 return;
3077 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3079 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3080 this->build_id_note_->data_size());
3082 const char* style = parameters->options().build_id();
3083 if (strcmp(style, "sha1") == 0)
3085 sha1_ctx ctx;
3086 sha1_init_ctx(&ctx);
3087 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3088 sha1_finish_ctx(&ctx, ov);
3090 else if (strcmp(style, "md5") == 0)
3092 md5_ctx ctx;
3093 md5_init_ctx(&ctx);
3094 md5_process_bytes(iv, this->output_file_size_, &ctx);
3095 md5_finish_ctx(&ctx, ov);
3097 else
3098 gold_unreachable();
3100 of->write_output_view(this->build_id_note_->offset(),
3101 this->build_id_note_->data_size(),
3102 ov);
3104 of->free_input_view(0, this->output_file_size_, iv);
3107 // Write out a binary file. This is called after the link is
3108 // complete. IN is the temporary output file we used to generate the
3109 // ELF code. We simply walk through the segments, read them from
3110 // their file offset in IN, and write them to their load address in
3111 // the output file. FIXME: with a bit more work, we could support
3112 // S-records and/or Intel hex format here.
3114 void
3115 Layout::write_binary(Output_file* in) const
3117 gold_assert(this->options_.oformat_enum()
3118 == General_options::OBJECT_FORMAT_BINARY);
3120 // Get the size of the binary file.
3121 uint64_t max_load_address = 0;
3122 for (Segment_list::const_iterator p = this->segment_list_.begin();
3123 p != this->segment_list_.end();
3124 ++p)
3126 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3128 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3129 if (max_paddr > max_load_address)
3130 max_load_address = max_paddr;
3134 Output_file out(parameters->options().output_file_name());
3135 out.open(max_load_address);
3137 for (Segment_list::const_iterator p = this->segment_list_.begin();
3138 p != this->segment_list_.end();
3139 ++p)
3141 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3143 const unsigned char* vin = in->get_input_view((*p)->offset(),
3144 (*p)->filesz());
3145 unsigned char* vout = out.get_output_view((*p)->paddr(),
3146 (*p)->filesz());
3147 memcpy(vout, vin, (*p)->filesz());
3148 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3149 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3153 out.close();
3156 // Print the output sections to the map file.
3158 void
3159 Layout::print_to_mapfile(Mapfile* mapfile) const
3161 for (Segment_list::const_iterator p = this->segment_list_.begin();
3162 p != this->segment_list_.end();
3163 ++p)
3164 (*p)->print_sections_to_mapfile(mapfile);
3167 // Print statistical information to stderr. This is used for --stats.
3169 void
3170 Layout::print_stats() const
3172 this->namepool_.print_stats("section name pool");
3173 this->sympool_.print_stats("output symbol name pool");
3174 this->dynpool_.print_stats("dynamic name pool");
3176 for (Section_list::const_iterator p = this->section_list_.begin();
3177 p != this->section_list_.end();
3178 ++p)
3179 (*p)->print_merge_stats();
3182 // Write_sections_task methods.
3184 // We can always run this task.
3186 Task_token*
3187 Write_sections_task::is_runnable()
3189 return NULL;
3192 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3193 // when finished.
3195 void
3196 Write_sections_task::locks(Task_locker* tl)
3198 tl->add(this, this->output_sections_blocker_);
3199 tl->add(this, this->final_blocker_);
3202 // Run the task--write out the data.
3204 void
3205 Write_sections_task::run(Workqueue*)
3207 this->layout_->write_output_sections(this->of_);
3210 // Write_data_task methods.
3212 // We can always run this task.
3214 Task_token*
3215 Write_data_task::is_runnable()
3217 return NULL;
3220 // We need to unlock FINAL_BLOCKER when finished.
3222 void
3223 Write_data_task::locks(Task_locker* tl)
3225 tl->add(this, this->final_blocker_);
3228 // Run the task--write out the data.
3230 void
3231 Write_data_task::run(Workqueue*)
3233 this->layout_->write_data(this->symtab_, this->of_);
3236 // Write_symbols_task methods.
3238 // We can always run this task.
3240 Task_token*
3241 Write_symbols_task::is_runnable()
3243 return NULL;
3246 // We need to unlock FINAL_BLOCKER when finished.
3248 void
3249 Write_symbols_task::locks(Task_locker* tl)
3251 tl->add(this, this->final_blocker_);
3254 // Run the task--write out the symbols.
3256 void
3257 Write_symbols_task::run(Workqueue*)
3259 this->symtab_->write_globals(this->input_objects_, this->sympool_,
3260 this->dynpool_, this->layout_->symtab_xindex(),
3261 this->layout_->dynsym_xindex(), this->of_);
3264 // Write_after_input_sections_task methods.
3266 // We can only run this task after the input sections have completed.
3268 Task_token*
3269 Write_after_input_sections_task::is_runnable()
3271 if (this->input_sections_blocker_->is_blocked())
3272 return this->input_sections_blocker_;
3273 return NULL;
3276 // We need to unlock FINAL_BLOCKER when finished.
3278 void
3279 Write_after_input_sections_task::locks(Task_locker* tl)
3281 tl->add(this, this->final_blocker_);
3284 // Run the task.
3286 void
3287 Write_after_input_sections_task::run(Workqueue*)
3289 this->layout_->write_sections_after_input_sections(this->of_);
3292 // Close_task_runner methods.
3294 // Run the task--close the file.
3296 void
3297 Close_task_runner::run(Workqueue*, const Task*)
3299 // If we need to compute a checksum for the BUILD if, we do so here.
3300 this->layout_->write_build_id(this->of_);
3302 // If we've been asked to create a binary file, we do so here.
3303 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
3304 this->layout_->write_binary(this->of_);
3306 this->of_->close();
3309 // Instantiate the templates we need. We could use the configure
3310 // script to restrict this to only the ones for implemented targets.
3312 #ifdef HAVE_TARGET_32_LITTLE
3313 template
3314 Output_section*
3315 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3316 const char* name,
3317 const elfcpp::Shdr<32, false>& shdr,
3318 unsigned int, unsigned int, off_t*);
3319 #endif
3321 #ifdef HAVE_TARGET_32_BIG
3322 template
3323 Output_section*
3324 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3325 const char* name,
3326 const elfcpp::Shdr<32, true>& shdr,
3327 unsigned int, unsigned int, off_t*);
3328 #endif
3330 #ifdef HAVE_TARGET_64_LITTLE
3331 template
3332 Output_section*
3333 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3334 const char* name,
3335 const elfcpp::Shdr<64, false>& shdr,
3336 unsigned int, unsigned int, off_t*);
3337 #endif
3339 #ifdef HAVE_TARGET_64_BIG
3340 template
3341 Output_section*
3342 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3343 const char* name,
3344 const elfcpp::Shdr<64, true>& shdr,
3345 unsigned int, unsigned int, off_t*);
3346 #endif
3348 #ifdef HAVE_TARGET_32_LITTLE
3349 template
3350 Output_section*
3351 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3352 unsigned int reloc_shndx,
3353 const elfcpp::Shdr<32, false>& shdr,
3354 Output_section* data_section,
3355 Relocatable_relocs* rr);
3356 #endif
3358 #ifdef HAVE_TARGET_32_BIG
3359 template
3360 Output_section*
3361 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3362 unsigned int reloc_shndx,
3363 const elfcpp::Shdr<32, true>& shdr,
3364 Output_section* data_section,
3365 Relocatable_relocs* rr);
3366 #endif
3368 #ifdef HAVE_TARGET_64_LITTLE
3369 template
3370 Output_section*
3371 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3372 unsigned int reloc_shndx,
3373 const elfcpp::Shdr<64, false>& shdr,
3374 Output_section* data_section,
3375 Relocatable_relocs* rr);
3376 #endif
3378 #ifdef HAVE_TARGET_64_BIG
3379 template
3380 Output_section*
3381 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3382 unsigned int reloc_shndx,
3383 const elfcpp::Shdr<64, true>& shdr,
3384 Output_section* data_section,
3385 Relocatable_relocs* rr);
3386 #endif
3388 #ifdef HAVE_TARGET_32_LITTLE
3389 template
3390 void
3391 Layout::layout_group<32, false>(Symbol_table* symtab,
3392 Sized_relobj<32, false>* object,
3393 unsigned int,
3394 const char* group_section_name,
3395 const char* signature,
3396 const elfcpp::Shdr<32, false>& shdr,
3397 elfcpp::Elf_Word flags,
3398 std::vector<unsigned int>* shndxes);
3399 #endif
3401 #ifdef HAVE_TARGET_32_BIG
3402 template
3403 void
3404 Layout::layout_group<32, true>(Symbol_table* symtab,
3405 Sized_relobj<32, true>* object,
3406 unsigned int,
3407 const char* group_section_name,
3408 const char* signature,
3409 const elfcpp::Shdr<32, true>& shdr,
3410 elfcpp::Elf_Word flags,
3411 std::vector<unsigned int>* shndxes);
3412 #endif
3414 #ifdef HAVE_TARGET_64_LITTLE
3415 template
3416 void
3417 Layout::layout_group<64, false>(Symbol_table* symtab,
3418 Sized_relobj<64, false>* object,
3419 unsigned int,
3420 const char* group_section_name,
3421 const char* signature,
3422 const elfcpp::Shdr<64, false>& shdr,
3423 elfcpp::Elf_Word flags,
3424 std::vector<unsigned int>* shndxes);
3425 #endif
3427 #ifdef HAVE_TARGET_64_BIG
3428 template
3429 void
3430 Layout::layout_group<64, true>(Symbol_table* symtab,
3431 Sized_relobj<64, true>* object,
3432 unsigned int,
3433 const char* group_section_name,
3434 const char* signature,
3435 const elfcpp::Shdr<64, true>& shdr,
3436 elfcpp::Elf_Word flags,
3437 std::vector<unsigned int>* shndxes);
3438 #endif
3440 #ifdef HAVE_TARGET_32_LITTLE
3441 template
3442 Output_section*
3443 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3444 const unsigned char* symbols,
3445 off_t symbols_size,
3446 const unsigned char* symbol_names,
3447 off_t symbol_names_size,
3448 unsigned int shndx,
3449 const elfcpp::Shdr<32, false>& shdr,
3450 unsigned int reloc_shndx,
3451 unsigned int reloc_type,
3452 off_t* off);
3453 #endif
3455 #ifdef HAVE_TARGET_32_BIG
3456 template
3457 Output_section*
3458 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3459 const unsigned char* symbols,
3460 off_t symbols_size,
3461 const unsigned char* symbol_names,
3462 off_t symbol_names_size,
3463 unsigned int shndx,
3464 const elfcpp::Shdr<32, true>& shdr,
3465 unsigned int reloc_shndx,
3466 unsigned int reloc_type,
3467 off_t* off);
3468 #endif
3470 #ifdef HAVE_TARGET_64_LITTLE
3471 template
3472 Output_section*
3473 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3474 const unsigned char* symbols,
3475 off_t symbols_size,
3476 const unsigned char* symbol_names,
3477 off_t symbol_names_size,
3478 unsigned int shndx,
3479 const elfcpp::Shdr<64, false>& shdr,
3480 unsigned int reloc_shndx,
3481 unsigned int reloc_type,
3482 off_t* off);
3483 #endif
3485 #ifdef HAVE_TARGET_64_BIG
3486 template
3487 Output_section*
3488 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
3489 const unsigned char* symbols,
3490 off_t symbols_size,
3491 const unsigned char* symbol_names,
3492 off_t symbol_names_size,
3493 unsigned int shndx,
3494 const elfcpp::Shdr<64, true>& shdr,
3495 unsigned int reloc_shndx,
3496 unsigned int reloc_type,
3497 off_t* off);
3498 #endif
3500 } // End namespace gold.