* dwarf_reader.cc (Sized_dwarf_line_info::Sized_dwarf_line_info):
[deliverable/binutils-gdb.git] / gold / layout.cc
CommitLineData
a2fb1b05
ILT
1// layout.cc -- lay out output file sections for gold
2
6d03d481 3// Copyright 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6cb15b7f
ILT
4// Written by Ian Lance Taylor <iant@google.com>.
5
6// This file is part of gold.
7
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.
12
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.
17
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.
22
a2fb1b05
ILT
23#include "gold.h"
24
8ed814a9 25#include <cerrno>
a2fb1b05 26#include <cstring>
54dc6425 27#include <algorithm>
a2fb1b05
ILT
28#include <iostream>
29#include <utility>
8ed814a9
ILT
30#include <fcntl.h>
31#include <unistd.h>
32#include "libiberty.h"
33#include "md5.h"
34#include "sha1.h"
a2fb1b05 35
7e1edb90 36#include "parameters.h"
14144f39 37#include "options.h"
7d9e3d98 38#include "mapfile.h"
a445fddf
ILT
39#include "script.h"
40#include "script-sections.h"
a2fb1b05 41#include "output.h"
f6ce93d6 42#include "symtab.h"
a3ad94ed 43#include "dynobj.h"
3151305a 44#include "ehframe.h"
96803768 45#include "compressed_output.h"
62b01cb5 46#include "reduced_debug_output.h"
6a74a719 47#include "reloc.h"
2a00e4fb 48#include "descriptors.h"
2756a258 49#include "plugin.h"
3ce2c28e
ILT
50#include "incremental.h"
51#include "layout.h"
a2fb1b05
ILT
52
53namespace gold
54{
55
20e6d0d6
DK
56// Layout::Relaxation_debug_check methods.
57
58// Check that sections and special data are in reset states.
59// We do not save states for Output_sections and special Output_data.
60// So we check that they have not assigned any addresses or offsets.
61// clean_up_after_relaxation simply resets their addresses and offsets.
62void
63Layout::Relaxation_debug_check::check_output_data_for_reset_values(
64 const Layout::Section_list& sections,
65 const Layout::Data_list& special_outputs)
66{
67 for(Layout::Section_list::const_iterator p = sections.begin();
68 p != sections.end();
69 ++p)
70 gold_assert((*p)->address_and_file_offset_have_reset_values());
71
72 for(Layout::Data_list::const_iterator p = special_outputs.begin();
73 p != special_outputs.end();
74 ++p)
75 gold_assert((*p)->address_and_file_offset_have_reset_values());
76}
77
78// Save information of SECTIONS for checking later.
79
80void
81Layout::Relaxation_debug_check::read_sections(
82 const Layout::Section_list& sections)
83{
84 for(Layout::Section_list::const_iterator p = sections.begin();
85 p != sections.end();
86 ++p)
87 {
88 Output_section* os = *p;
89 Section_info info;
90 info.output_section = os;
91 info.address = os->is_address_valid() ? os->address() : 0;
92 info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
93 info.offset = os->is_offset_valid()? os->offset() : -1 ;
94 this->section_infos_.push_back(info);
95 }
96}
97
98// Verify SECTIONS using previously recorded information.
99
100void
101Layout::Relaxation_debug_check::verify_sections(
102 const Layout::Section_list& sections)
103{
104 size_t i = 0;
105 for(Layout::Section_list::const_iterator p = sections.begin();
106 p != sections.end();
107 ++p, ++i)
108 {
109 Output_section* os = *p;
110 uint64_t address = os->is_address_valid() ? os->address() : 0;
111 off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
112 off_t offset = os->is_offset_valid()? os->offset() : -1 ;
113
114 if (i >= this->section_infos_.size())
115 {
116 gold_fatal("Section_info of %s missing.\n", os->name());
117 }
118 const Section_info& info = this->section_infos_[i];
119 if (os != info.output_section)
120 gold_fatal("Section order changed. Expecting %s but see %s\n",
121 info.output_section->name(), os->name());
122 if (address != info.address
123 || data_size != info.data_size
124 || offset != info.offset)
125 gold_fatal("Section %s changed.\n", os->name());
126 }
127}
128
92e059d8 129// Layout_task_runner methods.
a2fb1b05
ILT
130
131// Lay out the sections. This is called after all the input objects
132// have been read.
133
134void
17a1d0a9 135Layout_task_runner::run(Workqueue* workqueue, const Task* task)
a2fb1b05 136{
12e14209 137 off_t file_size = this->layout_->finalize(this->input_objects_,
17a1d0a9 138 this->symtab_,
8851ecca 139 this->target_,
17a1d0a9 140 task);
61ba1cf9
ILT
141
142 // Now we know the final size of the output file and we know where
143 // each piece of information goes.
7d9e3d98
ILT
144
145 if (this->mapfile_ != NULL)
146 {
147 this->mapfile_->print_discarded_sections(this->input_objects_);
148 this->layout_->print_to_mapfile(this->mapfile_);
149 }
150
8851ecca 151 Output_file* of = new Output_file(parameters->options().output_file_name());
7cc619c3 152 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
516cb3d0 153 of->set_is_temporary();
61ba1cf9
ILT
154 of->open(file_size);
155
156 // Queue up the final set of tasks.
157 gold::queue_final_tasks(this->options_, this->input_objects_,
12e14209 158 this->symtab_, this->layout_, workqueue, of);
a2fb1b05
ILT
159}
160
161// Layout methods.
162
e55bde5e
ILT
163Layout::Layout(int number_of_input_files, Script_options* script_options)
164 : number_of_input_files_(number_of_input_files),
d491d34e
ILT
165 script_options_(script_options),
166 namepool_(),
167 sympool_(),
168 dynpool_(),
169 signatures_(),
170 section_name_map_(),
171 segment_list_(),
172 section_list_(),
173 unattached_section_list_(),
d491d34e
ILT
174 special_output_list_(),
175 section_headers_(NULL),
176 tls_segment_(NULL),
9f1d377b 177 relro_segment_(NULL),
d491d34e
ILT
178 symtab_section_(NULL),
179 symtab_xindex_(NULL),
180 dynsym_section_(NULL),
181 dynsym_xindex_(NULL),
182 dynamic_section_(NULL),
183 dynamic_data_(NULL),
184 eh_frame_section_(NULL),
185 eh_frame_data_(NULL),
186 added_eh_frame_data_(false),
187 eh_frame_hdr_section_(NULL),
188 build_id_note_(NULL),
62b01cb5
ILT
189 debug_abbrev_(NULL),
190 debug_info_(NULL),
d491d34e
ILT
191 group_signatures_(),
192 output_file_size_(-1),
e55bde5e 193 sections_are_attached_(false),
35cdfc9a
ILT
194 input_requires_executable_stack_(false),
195 input_with_gnu_stack_note_(false),
535890bb 196 input_without_gnu_stack_note_(false),
17a1d0a9 197 has_static_tls_(false),
e55bde5e 198 any_postprocessing_sections_(false),
3ce2c28e 199 resized_signatures_(false),
1518dc8f 200 have_stabstr_section_(false),
20e6d0d6
DK
201 incremental_inputs_(NULL),
202 record_output_section_data_from_script_(false),
203 script_output_section_data_list_(),
204 segment_states_(NULL),
205 relaxation_debug_check_(NULL)
54dc6425
ILT
206{
207 // Make space for more than enough segments for a typical file.
208 // This is just for efficiency--it's OK if we wind up needing more.
a3ad94ed
ILT
209 this->segment_list_.reserve(12);
210
27bc2bce
ILT
211 // We expect two unattached Output_data objects: the file header and
212 // the segment headers.
213 this->special_output_list_.reserve(2);
3ce2c28e
ILT
214
215 // Initialize structure needed for an incremental build.
216 if (parameters->options().incremental())
217 this->incremental_inputs_ = new Incremental_inputs;
f7c8a183
ILT
218
219 // The section name pool is worth optimizing in all cases, because
220 // it is small, but there are often overlaps due to .rel sections.
221 this->namepool_.set_optimize();
54dc6425
ILT
222}
223
a2fb1b05
ILT
224// Hash a key we use to look up an output section mapping.
225
226size_t
227Layout::Hash_key::operator()(const Layout::Key& k) const
228{
f0641a0b 229 return k.first + k.second.first + k.second.second;
a2fb1b05
ILT
230}
231
02d2ba74
ILT
232// Returns whether the given section is in the list of
233// debug-sections-used-by-some-version-of-gdb. Currently,
234// we've checked versions of gdb up to and including 6.7.1.
235
236static const char* gdb_sections[] =
237{ ".debug_abbrev",
238 // ".debug_aranges", // not used by gdb as of 6.7.1
239 ".debug_frame",
240 ".debug_info",
241 ".debug_line",
242 ".debug_loc",
243 ".debug_macinfo",
244 // ".debug_pubnames", // not used by gdb as of 6.7.1
245 ".debug_ranges",
246 ".debug_str",
247};
248
62b01cb5
ILT
249static const char* lines_only_debug_sections[] =
250{ ".debug_abbrev",
251 // ".debug_aranges", // not used by gdb as of 6.7.1
252 // ".debug_frame",
253 ".debug_info",
254 ".debug_line",
255 // ".debug_loc",
256 // ".debug_macinfo",
257 // ".debug_pubnames", // not used by gdb as of 6.7.1
258 // ".debug_ranges",
259 ".debug_str",
260};
261
02d2ba74
ILT
262static inline bool
263is_gdb_debug_section(const char* str)
264{
265 // We can do this faster: binary search or a hashtable. But why bother?
266 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
267 if (strcmp(str, gdb_sections[i]) == 0)
268 return true;
269 return false;
270}
271
62b01cb5
ILT
272static inline bool
273is_lines_only_debug_section(const char* str)
274{
275 // We can do this faster: binary search or a hashtable. But why bother?
276 for (size_t i = 0;
277 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
278 ++i)
279 if (strcmp(str, lines_only_debug_sections[i]) == 0)
280 return true;
281 return false;
282}
283
a2fb1b05
ILT
284// Whether to include this section in the link.
285
286template<int size, bool big_endian>
287bool
730cdc88 288Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
a2fb1b05
ILT
289 const elfcpp::Shdr<size, big_endian>& shdr)
290{
fd06b4aa
CC
291 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
292 return false;
293
a2fb1b05
ILT
294 switch (shdr.get_sh_type())
295 {
296 case elfcpp::SHT_NULL:
297 case elfcpp::SHT_SYMTAB:
298 case elfcpp::SHT_DYNSYM:
a2fb1b05
ILT
299 case elfcpp::SHT_HASH:
300 case elfcpp::SHT_DYNAMIC:
301 case elfcpp::SHT_SYMTAB_SHNDX:
302 return false;
303
5cb66f97
ILT
304 case elfcpp::SHT_STRTAB:
305 // Discard the sections which have special meanings in the ELF
306 // ABI. Keep others (e.g., .stabstr). We could also do this by
307 // checking the sh_link fields of the appropriate sections.
308 return (strcmp(name, ".dynstr") != 0
309 && strcmp(name, ".strtab") != 0
310 && strcmp(name, ".shstrtab") != 0);
311
a2fb1b05
ILT
312 case elfcpp::SHT_RELA:
313 case elfcpp::SHT_REL:
314 case elfcpp::SHT_GROUP:
7019cd25
ILT
315 // If we are emitting relocations these should be handled
316 // elsewhere.
8851ecca
ILT
317 gold_assert(!parameters->options().relocatable()
318 && !parameters->options().emit_relocs());
6a74a719 319 return false;
a2fb1b05 320
9e2dcb77 321 case elfcpp::SHT_PROGBITS:
8851ecca 322 if (parameters->options().strip_debug()
9e2dcb77
ILT
323 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
324 {
e94cf127 325 if (is_debug_info_section(name))
9e2dcb77
ILT
326 return false;
327 }
62b01cb5
ILT
328 if (parameters->options().strip_debug_non_line()
329 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
330 {
331 // Debugging sections can only be recognized by name.
332 if (is_prefix_of(".debug", name)
333 && !is_lines_only_debug_section(name))
334 return false;
335 }
8851ecca 336 if (parameters->options().strip_debug_gdb()
02d2ba74
ILT
337 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
338 {
339 // Debugging sections can only be recognized by name.
340 if (is_prefix_of(".debug", name)
341 && !is_gdb_debug_section(name))
342 return false;
343 }
fd06b4aa
CC
344 if (parameters->options().strip_lto_sections()
345 && !parameters->options().relocatable()
346 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
347 {
348 // Ignore LTO sections containing intermediate code.
349 if (is_prefix_of(".gnu.lto_", name))
350 return false;
351 }
9e2dcb77
ILT
352 return true;
353
a2fb1b05 354 default:
a2fb1b05
ILT
355 return true;
356 }
357}
358
ead1e424 359// Return an output section named NAME, or NULL if there is none.
a2fb1b05 360
a2fb1b05 361Output_section*
ead1e424 362Layout::find_output_section(const char* name) const
a2fb1b05 363{
a445fddf
ILT
364 for (Section_list::const_iterator p = this->section_list_.begin();
365 p != this->section_list_.end();
ead1e424 366 ++p)
a445fddf
ILT
367 if (strcmp((*p)->name(), name) == 0)
368 return *p;
ead1e424
ILT
369 return NULL;
370}
a2fb1b05 371
ead1e424
ILT
372// Return an output segment of type TYPE, with segment flags SET set
373// and segment flags CLEAR clear. Return NULL if there is none.
a2fb1b05 374
ead1e424
ILT
375Output_segment*
376Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
377 elfcpp::Elf_Word clear) const
378{
379 for (Segment_list::const_iterator p = this->segment_list_.begin();
380 p != this->segment_list_.end();
381 ++p)
382 if (static_cast<elfcpp::PT>((*p)->type()) == type
383 && ((*p)->flags() & set) == set
384 && ((*p)->flags() & clear) == 0)
385 return *p;
386 return NULL;
387}
a2fb1b05 388
ead1e424 389// Return the output section to use for section NAME with type TYPE
a445fddf
ILT
390// and section flags FLAGS. NAME must be canonicalized in the string
391// pool, and NAME_KEY is the key.
a2fb1b05 392
ead1e424 393Output_section*
f0641a0b
ILT
394Layout::get_output_section(const char* name, Stringpool::Key name_key,
395 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
ead1e424 396{
154e0e9a
ILT
397 elfcpp::Elf_Xword lookup_flags = flags;
398
399 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
400 // read-write with read-only sections. Some other ELF linkers do
401 // not do this. FIXME: Perhaps there should be an option
402 // controlling this.
403 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
404
405 const Key key(name_key, std::make_pair(type, lookup_flags));
a2fb1b05
ILT
406 const std::pair<Key, Output_section*> v(key, NULL);
407 std::pair<Section_name_map::iterator, bool> ins(
408 this->section_name_map_.insert(v));
409
a2fb1b05 410 if (!ins.second)
ead1e424 411 return ins.first->second;
a2fb1b05
ILT
412 else
413 {
414 // This is the first time we've seen this name/type/flags
4e2b1697
ILT
415 // combination. For compatibility with the GNU linker, we
416 // combine sections with contents and zero flags with sections
417 // with non-zero flags. This is a workaround for cases where
418 // assembler code forgets to set section flags. FIXME: Perhaps
419 // there should be an option to control this.
15cf077e 420 Output_section* os = NULL;
4e2b1697
ILT
421
422 if (type == elfcpp::SHT_PROGBITS)
15cf077e 423 {
4e2b1697
ILT
424 if (flags == 0)
425 {
426 Output_section* same_name = this->find_output_section(name);
427 if (same_name != NULL
428 && same_name->type() == elfcpp::SHT_PROGBITS
429 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
430 os = same_name;
431 }
432 else if ((flags & elfcpp::SHF_TLS) == 0)
433 {
434 elfcpp::Elf_Xword zero_flags = 0;
435 const Key zero_key(name_key, std::make_pair(type, zero_flags));
436 Section_name_map::iterator p =
437 this->section_name_map_.find(zero_key);
438 if (p != this->section_name_map_.end())
154e0e9a 439 os = p->second;
4e2b1697 440 }
15cf077e 441 }
4e2b1697 442
15cf077e
ILT
443 if (os == NULL)
444 os = this->make_output_section(name, type, flags);
a2fb1b05 445 ins.first->second = os;
ead1e424 446 return os;
a2fb1b05 447 }
ead1e424
ILT
448}
449
a445fddf
ILT
450// Pick the output section to use for section NAME, in input file
451// RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
154e0e9a
ILT
452// linker created section. IS_INPUT_SECTION is true if we are
453// choosing an output section for an input section found in a input
454// file. This will return NULL if the input section should be
455// discarded.
a445fddf
ILT
456
457Output_section*
458Layout::choose_output_section(const Relobj* relobj, const char* name,
459 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
154e0e9a 460 bool is_input_section)
a445fddf 461{
154e0e9a
ILT
462 // We should not see any input sections after we have attached
463 // sections to segments.
464 gold_assert(!is_input_section || !this->sections_are_attached_);
465
466 // Some flags in the input section should not be automatically
467 // copied to the output section.
a445fddf
ILT
468 flags &= ~ (elfcpp::SHF_INFO_LINK
469 | elfcpp::SHF_LINK_ORDER
470 | elfcpp::SHF_GROUP
471 | elfcpp::SHF_MERGE
472 | elfcpp::SHF_STRINGS);
473
474 if (this->script_options_->saw_sections_clause())
475 {
476 // We are using a SECTIONS clause, so the output section is
477 // chosen based only on the name.
478
479 Script_sections* ss = this->script_options_->script_sections();
480 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
481 Output_section** output_section_slot;
482 name = ss->output_section_name(file_name, name, &output_section_slot);
483 if (name == NULL)
484 {
485 // The SECTIONS clause says to discard this input section.
486 return NULL;
487 }
488
489 // If this is an orphan section--one not mentioned in the linker
490 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
491 // default processing below.
492
493 if (output_section_slot != NULL)
494 {
495 if (*output_section_slot != NULL)
9c547ec3
ILT
496 {
497 (*output_section_slot)->update_flags_for_input_section(flags);
498 return *output_section_slot;
499 }
a445fddf
ILT
500
501 // We don't put sections found in the linker script into
502 // SECTION_NAME_MAP_. That keeps us from getting confused
503 // if an orphan section is mapped to a section with the same
504 // name as one in the linker script.
505
506 name = this->namepool_.add(name, false, NULL);
507
508 Output_section* os = this->make_output_section(name, type, flags);
509 os->set_found_in_sections_clause();
510 *output_section_slot = os;
511 return os;
512 }
513 }
514
515 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
516
517 // Turn NAME from the name of the input section into the name of the
518 // output section.
519
520 size_t len = strlen(name);
401a9a73
CC
521 if (is_input_section
522 && !this->script_options_->saw_sections_clause()
523 && !parameters->options().relocatable())
a445fddf
ILT
524 name = Layout::output_section_name(name, &len);
525
526 Stringpool::Key name_key;
527 name = this->namepool_.add_with_length(name, len, true, &name_key);
528
529 // Find or make the output section. The output section is selected
530 // based on the section name, type, and flags.
531 return this->get_output_section(name, name_key, type, flags);
532}
533
ead1e424 534// Return the output section to use for input section SHNDX, with name
730cdc88
ILT
535// NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
536// index of a relocation section which applies to this section, or 0
537// if none, or -1U if more than one. RELOC_TYPE is the type of the
538// relocation section if there is one. Set *OFF to the offset of this
539// input section without the output section. Return NULL if the
540// section should be discarded. Set *OFF to -1 if the section
541// contents should not be written directly to the output file, but
542// will instead receive special handling.
ead1e424
ILT
543
544template<int size, bool big_endian>
545Output_section*
730cdc88
ILT
546Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
547 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
548 unsigned int reloc_shndx, unsigned int, off_t* off)
ead1e424 549{
ef9beddf
ILT
550 *off = 0;
551
ead1e424
ILT
552 if (!this->include_section(object, name, shdr))
553 return NULL;
554
6a74a719
ILT
555 Output_section* os;
556
557 // In a relocatable link a grouped section must not be combined with
558 // any other sections.
8851ecca 559 if (parameters->options().relocatable()
6a74a719
ILT
560 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
561 {
562 name = this->namepool_.add(name, true, NULL);
563 os = this->make_output_section(name, shdr.get_sh_type(),
564 shdr.get_sh_flags());
565 }
566 else
567 {
568 os = this->choose_output_section(object, name, shdr.get_sh_type(),
569 shdr.get_sh_flags(), true);
570 if (os == NULL)
571 return NULL;
572 }
a2fb1b05 573
2fd32231
ILT
574 // By default the GNU linker sorts input sections whose names match
575 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
576 // are sorted by name. This is used to implement constructor
577 // priority ordering. We are compatible.
578 if (!this->script_options_->saw_sections_clause()
579 && (is_prefix_of(".ctors.", name)
580 || is_prefix_of(".dtors.", name)
581 || is_prefix_of(".init_array.", name)
582 || is_prefix_of(".fini_array.", name)))
583 os->set_must_sort_attached_input_sections();
584
a2fb1b05
ILT
585 // FIXME: Handle SHF_LINK_ORDER somewhere.
586
a445fddf
ILT
587 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
588 this->script_options_->saw_sections_clause());
a2fb1b05
ILT
589
590 return os;
591}
592
6a74a719
ILT
593// Handle a relocation section when doing a relocatable link.
594
595template<int size, bool big_endian>
596Output_section*
597Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
598 unsigned int,
599 const elfcpp::Shdr<size, big_endian>& shdr,
600 Output_section* data_section,
601 Relocatable_relocs* rr)
602{
8851ecca
ILT
603 gold_assert(parameters->options().relocatable()
604 || parameters->options().emit_relocs());
6a74a719
ILT
605
606 int sh_type = shdr.get_sh_type();
607
608 std::string name;
609 if (sh_type == elfcpp::SHT_REL)
610 name = ".rel";
611 else if (sh_type == elfcpp::SHT_RELA)
612 name = ".rela";
613 else
614 gold_unreachable();
615 name += data_section->name();
616
617 Output_section* os = this->choose_output_section(object, name.c_str(),
618 sh_type,
619 shdr.get_sh_flags(),
620 false);
621
622 os->set_should_link_to_symtab();
623 os->set_info_section(data_section);
624
625 Output_section_data* posd;
626 if (sh_type == elfcpp::SHT_REL)
627 {
628 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
629 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
630 size,
631 big_endian>(rr);
632 }
633 else if (sh_type == elfcpp::SHT_RELA)
634 {
635 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
636 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
637 size,
638 big_endian>(rr);
639 }
640 else
641 gold_unreachable();
642
643 os->add_output_section_data(posd);
644 rr->set_output_data(posd);
645
646 return os;
647}
648
649// Handle a group section when doing a relocatable link.
650
651template<int size, bool big_endian>
652void
653Layout::layout_group(Symbol_table* symtab,
654 Sized_relobj<size, big_endian>* object,
655 unsigned int,
656 const char* group_section_name,
657 const char* signature,
658 const elfcpp::Shdr<size, big_endian>& shdr,
8825ac63
ILT
659 elfcpp::Elf_Word flags,
660 std::vector<unsigned int>* shndxes)
6a74a719 661{
8851ecca 662 gold_assert(parameters->options().relocatable());
6a74a719
ILT
663 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
664 group_section_name = this->namepool_.add(group_section_name, true, NULL);
665 Output_section* os = this->make_output_section(group_section_name,
666 elfcpp::SHT_GROUP,
667 shdr.get_sh_flags());
668
669 // We need to find a symbol with the signature in the symbol table.
755ab8af 670 // If we don't find one now, we need to look again later.
6a74a719 671 Symbol* sym = symtab->lookup(signature, NULL);
755ab8af
ILT
672 if (sym != NULL)
673 os->set_info_symndx(sym);
674 else
675 {
e55bde5e
ILT
676 // Reserve some space to minimize reallocations.
677 if (this->group_signatures_.empty())
678 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
679
755ab8af
ILT
680 // We will wind up using a symbol whose name is the signature.
681 // So just put the signature in the symbol name pool to save it.
682 signature = symtab->canonicalize_name(signature);
683 this->group_signatures_.push_back(Group_signature(os, signature));
684 }
6a74a719
ILT
685
686 os->set_should_link_to_symtab();
6a74a719
ILT
687 os->set_entsize(4);
688
689 section_size_type entry_count =
690 convert_to_section_size_type(shdr.get_sh_size() / 4);
691 Output_section_data* posd =
8825ac63
ILT
692 new Output_data_group<size, big_endian>(object, entry_count, flags,
693 shndxes);
6a74a719
ILT
694 os->add_output_section_data(posd);
695}
696
730cdc88
ILT
697// Special GNU handling of sections name .eh_frame. They will
698// normally hold exception frame data as defined by the C++ ABI
699// (http://codesourcery.com/cxx-abi/).
3151305a
ILT
700
701template<int size, bool big_endian>
730cdc88
ILT
702Output_section*
703Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
704 const unsigned char* symbols,
705 off_t symbols_size,
706 const unsigned char* symbol_names,
707 off_t symbol_names_size,
3151305a 708 unsigned int shndx,
3151305a 709 const elfcpp::Shdr<size, big_endian>& shdr,
730cdc88
ILT
710 unsigned int reloc_shndx, unsigned int reloc_type,
711 off_t* off)
3151305a 712{
730cdc88 713 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
1650c4ff 714 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
730cdc88 715
a445fddf
ILT
716 const char* const name = ".eh_frame";
717 Output_section* os = this->choose_output_section(object,
718 name,
719 elfcpp::SHT_PROGBITS,
720 elfcpp::SHF_ALLOC,
721 false);
722 if (os == NULL)
723 return NULL;
730cdc88 724
3151305a
ILT
725 if (this->eh_frame_section_ == NULL)
726 {
727 this->eh_frame_section_ = os;
730cdc88 728 this->eh_frame_data_ = new Eh_frame();
3151305a 729
e55bde5e 730 if (parameters->options().eh_frame_hdr())
3151305a 731 {
3151305a 732 Output_section* hdr_os =
a445fddf
ILT
733 this->choose_output_section(NULL,
734 ".eh_frame_hdr",
735 elfcpp::SHT_PROGBITS,
736 elfcpp::SHF_ALLOC,
737 false);
3151305a 738
a445fddf
ILT
739 if (hdr_os != NULL)
740 {
741 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
742 this->eh_frame_data_);
743 hdr_os->add_output_section_data(hdr_posd);
3151305a 744
a445fddf 745 hdr_os->set_after_input_sections();
730cdc88 746
1c4f3631
ILT
747 if (!this->script_options_->saw_phdrs_clause())
748 {
749 Output_segment* hdr_oseg;
750 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
751 elfcpp::PF_R);
752 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
753 }
730cdc88 754
a445fddf
ILT
755 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
756 }
3151305a
ILT
757 }
758 }
759
760 gold_assert(this->eh_frame_section_ == os);
761
730cdc88
ILT
762 if (this->eh_frame_data_->add_ehframe_input_section(object,
763 symbols,
764 symbols_size,
765 symbol_names,
766 symbol_names_size,
767 shndx,
768 reloc_shndx,
769 reloc_type))
2c38906f 770 {
154e0e9a
ILT
771 os->update_flags_for_input_section(shdr.get_sh_flags());
772
2c38906f
ILT
773 // We found a .eh_frame section we are going to optimize, so now
774 // we can add the set of optimized sections to the output
775 // section. We need to postpone adding this until we've found a
776 // section we can optimize so that the .eh_frame section in
777 // crtbegin.o winds up at the start of the output section.
778 if (!this->added_eh_frame_data_)
779 {
780 os->add_output_section_data(this->eh_frame_data_);
781 this->added_eh_frame_data_ = true;
782 }
783 *off = -1;
784 }
730cdc88
ILT
785 else
786 {
787 // We couldn't handle this .eh_frame section for some reason.
788 // Add it as a normal section.
a445fddf
ILT
789 bool saw_sections_clause = this->script_options_->saw_sections_clause();
790 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
791 saw_sections_clause);
730cdc88
ILT
792 }
793
794 return os;
3151305a
ILT
795}
796
9f1d377b
ILT
797// Add POSD to an output section using NAME, TYPE, and FLAGS. Return
798// the output section.
ead1e424 799
9f1d377b 800Output_section*
ead1e424
ILT
801Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
802 elfcpp::Elf_Xword flags,
803 Output_section_data* posd)
804{
a445fddf
ILT
805 Output_section* os = this->choose_output_section(NULL, name, type, flags,
806 false);
807 if (os != NULL)
808 os->add_output_section_data(posd);
9f1d377b 809 return os;
ead1e424
ILT
810}
811
a2fb1b05
ILT
812// Map section flags to segment flags.
813
814elfcpp::Elf_Word
815Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
816{
817 elfcpp::Elf_Word ret = elfcpp::PF_R;
818 if ((flags & elfcpp::SHF_WRITE) != 0)
819 ret |= elfcpp::PF_W;
820 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
821 ret |= elfcpp::PF_X;
822 return ret;
823}
824
96803768
ILT
825// Sometimes we compress sections. This is typically done for
826// sections that are not part of normal program execution (such as
827// .debug_* sections), and where the readers of these sections know
c3b65ac4
CD
828// how to deal with compressed sections. This routine doesn't say for
829// certain whether we'll compress -- it depends on commandline options
830// as well -- just whether this section is a candidate for compression.
831// (The Output_compressed_section class decides whether to compress
832// a given section, and picks the name of the compressed section.)
96803768
ILT
833
834static bool
835is_compressible_debug_section(const char* secname)
836{
837 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
838}
839
a2fb1b05
ILT
840// Make a new Output_section, and attach it to segments as
841// appropriate.
842
843Output_section*
844Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
845 elfcpp::Elf_Xword flags)
846{
96803768
ILT
847 Output_section* os;
848 if ((flags & elfcpp::SHF_ALLOC) == 0
e55bde5e 849 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
96803768 850 && is_compressible_debug_section(name))
e55bde5e
ILT
851 os = new Output_compressed_section(&parameters->options(), name, type,
852 flags);
62b01cb5
ILT
853
854 else if ((flags & elfcpp::SHF_ALLOC) == 0
e55bde5e 855 && parameters->options().strip_debug_non_line()
62b01cb5
ILT
856 && strcmp(".debug_abbrev", name) == 0)
857 {
858 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
859 name, type, flags);
860 if (this->debug_info_)
861 this->debug_info_->set_abbreviations(this->debug_abbrev_);
862 }
863 else if ((flags & elfcpp::SHF_ALLOC) == 0
e55bde5e 864 && parameters->options().strip_debug_non_line()
62b01cb5
ILT
865 && strcmp(".debug_info", name) == 0)
866 {
867 os = this->debug_info_ = new Output_reduced_debug_info_section(
868 name, type, flags);
869 if (this->debug_abbrev_)
870 this->debug_info_->set_abbreviations(this->debug_abbrev_);
871 }
872 else
96803768
ILT
873 os = new Output_section(name, type, flags);
874
8a5e3e08
ILT
875 parameters->target().new_output_section(os);
876
a3ad94ed 877 this->section_list_.push_back(os);
a2fb1b05 878
2fd32231
ILT
879 // The GNU linker by default sorts some sections by priority, so we
880 // do the same. We need to know that this might happen before we
881 // attach any input sections.
882 if (!this->script_options_->saw_sections_clause()
883 && (strcmp(name, ".ctors") == 0
884 || strcmp(name, ".dtors") == 0
885 || strcmp(name, ".init_array") == 0
886 || strcmp(name, ".fini_array") == 0))
887 os->set_may_sort_attached_input_sections();
888
9f1d377b
ILT
889 // With -z relro, we have to recognize the special sections by name.
890 // There is no other way.
891 if (!this->script_options_->saw_sections_clause()
892 && parameters->options().relro()
893 && type == elfcpp::SHT_PROGBITS
894 && (flags & elfcpp::SHF_ALLOC) != 0
895 && (flags & elfcpp::SHF_WRITE) != 0)
896 {
897 if (strcmp(name, ".data.rel.ro") == 0)
898 os->set_is_relro();
899 else if (strcmp(name, ".data.rel.ro.local") == 0)
900 {
901 os->set_is_relro();
902 os->set_is_relro_local();
903 }
904 }
905
1518dc8f
ILT
906 // Check for .stab*str sections, as .stab* sections need to link to
907 // them.
908 if (type == elfcpp::SHT_STRTAB
909 && !this->have_stabstr_section_
910 && strncmp(name, ".stab", 5) == 0
911 && strcmp(name + strlen(name) - 3, "str") == 0)
912 this->have_stabstr_section_ = true;
913
154e0e9a
ILT
914 // If we have already attached the sections to segments, then we
915 // need to attach this one now. This happens for sections created
916 // directly by the linker.
917 if (this->sections_are_attached_)
918 this->attach_section_to_segment(os);
919
4e2b1697
ILT
920 return os;
921}
a445fddf 922
154e0e9a
ILT
923// Attach output sections to segments. This is called after we have
924// seen all the input sections.
925
926void
927Layout::attach_sections_to_segments()
928{
929 for (Section_list::iterator p = this->section_list_.begin();
930 p != this->section_list_.end();
931 ++p)
932 this->attach_section_to_segment(*p);
933
934 this->sections_are_attached_ = true;
935}
936
937// Attach an output section to a segment.
938
939void
940Layout::attach_section_to_segment(Output_section* os)
941{
942 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
943 this->unattached_section_list_.push_back(os);
944 else
945 this->attach_allocated_section_to_segment(os);
946}
947
4e2b1697 948// Attach an allocated output section to a segment.
1c4f3631 949
4e2b1697 950void
154e0e9a 951Layout::attach_allocated_section_to_segment(Output_section* os)
4e2b1697 952{
154e0e9a 953 elfcpp::Elf_Xword flags = os->flags();
4e2b1697 954 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
a2fb1b05 955
4e2b1697
ILT
956 if (parameters->options().relocatable())
957 return;
a2fb1b05 958
4e2b1697
ILT
959 // If we have a SECTIONS clause, we can't handle the attachment to
960 // segments until after we've seen all the sections.
961 if (this->script_options_->saw_sections_clause())
962 return;
a2fb1b05 963
4e2b1697 964 gold_assert(!this->script_options_->saw_phdrs_clause());
756ac4a8 965
4e2b1697 966 // This output section goes into a PT_LOAD segment.
a2fb1b05 967
4e2b1697 968 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
a2fb1b05 969
4e2b1697
ILT
970 // In general the only thing we really care about for PT_LOAD
971 // segments is whether or not they are writable, so that is how we
8a5e3e08
ILT
972 // search for them. Large data sections also go into their own
973 // PT_LOAD segment. People who need segments sorted on some other
4e2b1697 974 // basis will have to use a linker script.
a2fb1b05 975
4e2b1697
ILT
976 Segment_list::const_iterator p;
977 for (p = this->segment_list_.begin();
978 p != this->segment_list_.end();
979 ++p)
980 {
8a5e3e08
ILT
981 if ((*p)->type() != elfcpp::PT_LOAD)
982 continue;
983 if (!parameters->options().omagic()
984 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
985 continue;
986 // If -Tbss was specified, we need to separate the data and BSS
987 // segments.
988 if (parameters->options().user_set_Tbss())
989 {
990 if ((os->type() == elfcpp::SHT_NOBITS)
991 == (*p)->has_any_data_sections())
992 continue;
993 }
994 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
995 continue;
4e2b1697 996
8a5e3e08
ILT
997 (*p)->add_output_section(os, seg_flags);
998 break;
4e2b1697 999 }
54dc6425 1000
4e2b1697
ILT
1001 if (p == this->segment_list_.end())
1002 {
1003 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1004 seg_flags);
8a5e3e08
ILT
1005 if (os->is_large_data_section())
1006 oseg->set_is_large_data_segment();
4e2b1697 1007 oseg->add_output_section(os, seg_flags);
a2fb1b05
ILT
1008 }
1009
4e2b1697
ILT
1010 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1011 // segment.
1012 if (os->type() == elfcpp::SHT_NOTE)
1013 {
1014 // See if we already have an equivalent PT_NOTE segment.
1015 for (p = this->segment_list_.begin();
1016 p != segment_list_.end();
1017 ++p)
1018 {
1019 if ((*p)->type() == elfcpp::PT_NOTE
1020 && (((*p)->flags() & elfcpp::PF_W)
1021 == (seg_flags & elfcpp::PF_W)))
1022 {
1023 (*p)->add_output_section(os, seg_flags);
1024 break;
1025 }
1026 }
1027
1028 if (p == this->segment_list_.end())
1029 {
1030 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1031 seg_flags);
1032 oseg->add_output_section(os, seg_flags);
1033 }
1034 }
1035
1036 // If we see a loadable SHF_TLS section, we create a PT_TLS
1037 // segment. There can only be one such segment.
1038 if ((flags & elfcpp::SHF_TLS) != 0)
1039 {
1040 if (this->tls_segment_ == NULL)
2d924fd9 1041 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
4e2b1697
ILT
1042 this->tls_segment_->add_output_section(os, seg_flags);
1043 }
9f1d377b
ILT
1044
1045 // If -z relro is in effect, and we see a relro section, we create a
1046 // PT_GNU_RELRO segment. There can only be one such segment.
1047 if (os->is_relro() && parameters->options().relro())
1048 {
1049 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1050 if (this->relro_segment_ == NULL)
2d924fd9 1051 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
9f1d377b
ILT
1052 this->relro_segment_->add_output_section(os, seg_flags);
1053 }
a2fb1b05
ILT
1054}
1055
919ed24c
ILT
1056// Make an output section for a script.
1057
1058Output_section*
1059Layout::make_output_section_for_script(const char* name)
1060{
1061 name = this->namepool_.add(name, false, NULL);
1062 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1063 elfcpp::SHF_ALLOC);
1064 os->set_found_in_sections_clause();
1065 return os;
1066}
1067
3802b2dd
ILT
1068// Return the number of segments we expect to see.
1069
1070size_t
1071Layout::expected_segment_count() const
1072{
1073 size_t ret = this->segment_list_.size();
1074
1075 // If we didn't see a SECTIONS clause in a linker script, we should
1076 // already have the complete list of segments. Otherwise we ask the
1077 // SECTIONS clause how many segments it expects, and add in the ones
1078 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1079
1080 if (!this->script_options_->saw_sections_clause())
1081 return ret;
1082 else
1083 {
1084 const Script_sections* ss = this->script_options_->script_sections();
1085 return ret + ss->expected_segment_count(this);
1086 }
1087}
1088
35cdfc9a
ILT
1089// Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1090// is whether we saw a .note.GNU-stack section in the object file.
1091// GNU_STACK_FLAGS is the section flags. The flags give the
1092// protection required for stack memory. We record this in an
1093// executable as a PT_GNU_STACK segment. If an object file does not
1094// have a .note.GNU-stack segment, we must assume that it is an old
1095// object. On some targets that will force an executable stack.
1096
1097void
1098Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1099{
1100 if (!seen_gnu_stack)
1101 this->input_without_gnu_stack_note_ = true;
1102 else
1103 {
1104 this->input_with_gnu_stack_note_ = true;
1105 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1106 this->input_requires_executable_stack_ = true;
1107 }
1108}
1109
9c547ec3
ILT
1110// Create automatic note sections.
1111
1112void
1113Layout::create_notes()
1114{
1115 this->create_gold_note();
1116 this->create_executable_stack_info();
1117 this->create_build_id();
1118}
1119
a3ad94ed
ILT
1120// Create the dynamic sections which are needed before we read the
1121// relocs.
1122
1123void
9b07f471 1124Layout::create_initial_dynamic_sections(Symbol_table* symtab)
a3ad94ed 1125{
436ca963 1126 if (parameters->doing_static_link())
a3ad94ed
ILT
1127 return;
1128
3802b2dd
ILT
1129 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1130 elfcpp::SHT_DYNAMIC,
1131 (elfcpp::SHF_ALLOC
1132 | elfcpp::SHF_WRITE),
1133 false);
9f1d377b 1134 this->dynamic_section_->set_is_relro();
a3ad94ed 1135
9b07f471 1136 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
a3ad94ed
ILT
1137 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1138 elfcpp::STV_HIDDEN, 0, false, false);
16649710 1139
9025d29d 1140 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
16649710
ILT
1141
1142 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
a3ad94ed
ILT
1143}
1144
bfd58944
ILT
1145// For each output section whose name can be represented as C symbol,
1146// define __start and __stop symbols for the section. This is a GNU
1147// extension.
1148
1149void
9b07f471 1150Layout::define_section_symbols(Symbol_table* symtab)
bfd58944
ILT
1151{
1152 for (Section_list::const_iterator p = this->section_list_.begin();
1153 p != this->section_list_.end();
1154 ++p)
1155 {
1156 const char* const name = (*p)->name();
1157 if (name[strspn(name,
1158 ("0123456789"
1159 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1160 "abcdefghijklmnopqrstuvwxyz"
1161 "_"))]
1162 == '\0')
1163 {
1164 const std::string name_string(name);
1165 const std::string start_name("__start_" + name_string);
1166 const std::string stop_name("__stop_" + name_string);
1167
9b07f471 1168 symtab->define_in_output_data(start_name.c_str(),
bfd58944
ILT
1169 NULL, // version
1170 *p,
1171 0, // value
1172 0, // symsize
1173 elfcpp::STT_NOTYPE,
1174 elfcpp::STB_GLOBAL,
1175 elfcpp::STV_DEFAULT,
1176 0, // nonvis
1177 false, // offset_is_from_end
a445fddf 1178 true); // only_if_ref
bfd58944 1179
9b07f471 1180 symtab->define_in_output_data(stop_name.c_str(),
bfd58944
ILT
1181 NULL, // version
1182 *p,
1183 0, // value
1184 0, // symsize
1185 elfcpp::STT_NOTYPE,
1186 elfcpp::STB_GLOBAL,
1187 elfcpp::STV_DEFAULT,
1188 0, // nonvis
1189 true, // offset_is_from_end
a445fddf 1190 true); // only_if_ref
bfd58944
ILT
1191 }
1192 }
1193}
1194
755ab8af
ILT
1195// Define symbols for group signatures.
1196
1197void
1198Layout::define_group_signatures(Symbol_table* symtab)
1199{
1200 for (Group_signatures::iterator p = this->group_signatures_.begin();
1201 p != this->group_signatures_.end();
1202 ++p)
1203 {
1204 Symbol* sym = symtab->lookup(p->signature, NULL);
1205 if (sym != NULL)
1206 p->section->set_info_symndx(sym);
1207 else
1208 {
1209 // Force the name of the group section to the group
1210 // signature, and use the group's section symbol as the
1211 // signature symbol.
1212 if (strcmp(p->section->name(), p->signature) != 0)
1213 {
1214 const char* name = this->namepool_.add(p->signature,
1215 true, NULL);
1216 p->section->set_name(name);
1217 }
1218 p->section->set_needs_symtab_index();
1219 p->section->set_info_section_symndx(p->section);
1220 }
1221 }
1222
1223 this->group_signatures_.clear();
1224}
1225
75f65a3e
ILT
1226// Find the first read-only PT_LOAD segment, creating one if
1227// necessary.
54dc6425 1228
75f65a3e
ILT
1229Output_segment*
1230Layout::find_first_load_seg()
54dc6425 1231{
75f65a3e
ILT
1232 for (Segment_list::const_iterator p = this->segment_list_.begin();
1233 p != this->segment_list_.end();
1234 ++p)
1235 {
1236 if ((*p)->type() == elfcpp::PT_LOAD
1237 && ((*p)->flags() & elfcpp::PF_R) != 0
af6156ef
ILT
1238 && (parameters->options().omagic()
1239 || ((*p)->flags() & elfcpp::PF_W) == 0))
75f65a3e
ILT
1240 return *p;
1241 }
1242
1c4f3631
ILT
1243 gold_assert(!this->script_options_->saw_phdrs_clause());
1244
3802b2dd
ILT
1245 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1246 elfcpp::PF_R);
75f65a3e 1247 return load_seg;
54dc6425
ILT
1248}
1249
20e6d0d6
DK
1250// Save states of all current output segments. Store saved states
1251// in SEGMENT_STATES.
1252
1253void
1254Layout::save_segments(Segment_states* segment_states)
1255{
1256 for (Segment_list::const_iterator p = this->segment_list_.begin();
1257 p != this->segment_list_.end();
1258 ++p)
1259 {
1260 Output_segment* segment = *p;
1261 // Shallow copy.
1262 Output_segment* copy = new Output_segment(*segment);
1263 (*segment_states)[segment] = copy;
1264 }
1265}
1266
1267// Restore states of output segments and delete any segment not found in
1268// SEGMENT_STATES.
1269
1270void
1271Layout::restore_segments(const Segment_states* segment_states)
1272{
1273 // Go through the segment list and remove any segment added in the
1274 // relaxation loop.
1275 this->tls_segment_ = NULL;
1276 this->relro_segment_ = NULL;
1277 Segment_list::iterator list_iter = this->segment_list_.begin();
1278 while (list_iter != this->segment_list_.end())
1279 {
1280 Output_segment* segment = *list_iter;
1281 Segment_states::const_iterator states_iter =
1282 segment_states->find(segment);
1283 if (states_iter != segment_states->end())
1284 {
1285 const Output_segment* copy = states_iter->second;
1286 // Shallow copy to restore states.
1287 *segment = *copy;
1288
1289 // Also fix up TLS and RELRO segment pointers as appropriate.
1290 if (segment->type() == elfcpp::PT_TLS)
1291 this->tls_segment_ = segment;
1292 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1293 this->relro_segment_ = segment;
1294
1295 ++list_iter;
1296 }
1297 else
1298 {
1299 list_iter = this->segment_list_.erase(list_iter);
1300 // This is a segment created during section layout. It should be
1301 // safe to remove it since we should have removed all pointers to it.
1302 delete segment;
1303 }
1304 }
1305}
1306
1307// Clean up after relaxation so that sections can be laid out again.
1308
1309void
1310Layout::clean_up_after_relaxation()
1311{
1312 // Restore the segments to point state just prior to the relaxation loop.
1313 Script_sections* script_section = this->script_options_->script_sections();
1314 script_section->release_segments();
1315 this->restore_segments(this->segment_states_);
1316
1317 // Reset section addresses and file offsets
1318 for (Section_list::iterator p = this->section_list_.begin();
1319 p != this->section_list_.end();
1320 ++p)
1321 {
1322 (*p)->reset_address_and_file_offset();
1323 (*p)->restore_states();
1324 }
1325
1326 // Reset special output object address and file offsets.
1327 for (Data_list::iterator p = this->special_output_list_.begin();
1328 p != this->special_output_list_.end();
1329 ++p)
1330 (*p)->reset_address_and_file_offset();
1331
1332 // A linker script may have created some output section data objects.
1333 // They are useless now.
1334 for (Output_section_data_list::const_iterator p =
1335 this->script_output_section_data_list_.begin();
1336 p != this->script_output_section_data_list_.end();
1337 ++p)
1338 delete *p;
1339 this->script_output_section_data_list_.clear();
1340}
1341
1342// Prepare for relaxation.
1343
1344void
1345Layout::prepare_for_relaxation()
1346{
1347 // Create an relaxation debug check if in debugging mode.
1348 if (is_debugging_enabled(DEBUG_RELAXATION))
1349 this->relaxation_debug_check_ = new Relaxation_debug_check();
1350
1351 // Save segment states.
1352 this->segment_states_ = new Segment_states();
1353 this->save_segments(this->segment_states_);
1354
1355 for(Section_list::const_iterator p = this->section_list_.begin();
1356 p != this->section_list_.end();
1357 ++p)
1358 (*p)->save_states();
1359
1360 if (is_debugging_enabled(DEBUG_RELAXATION))
1361 this->relaxation_debug_check_->check_output_data_for_reset_values(
1362 this->section_list_, this->special_output_list_);
1363
1364 // Also enable recording of output section data from scripts.
1365 this->record_output_section_data_from_script_ = true;
1366}
1367
1368// Relaxation loop body: If target has no relaxation, this runs only once
1369// Otherwise, the target relaxation hook is called at the end of
1370// each iteration. If the hook returns true, it means re-layout of
1371// section is required.
1372//
1373// The number of segments created by a linking script without a PHDRS
1374// clause may be affected by section sizes and alignments. There is
1375// a remote chance that relaxation causes different number of PT_LOAD
1376// segments are created and sections are attached to different segments.
1377// Therefore, we always throw away all segments created during section
1378// layout. In order to be able to restart the section layout, we keep
1379// a copy of the segment list right before the relaxation loop and use
1380// that to restore the segments.
1381//
1382// PASS is the current relaxation pass number.
1383// SYMTAB is a symbol table.
1384// PLOAD_SEG is the address of a pointer for the load segment.
1385// PHDR_SEG is a pointer to the PHDR segment.
1386// SEGMENT_HEADERS points to the output segment header.
1387// FILE_HEADER points to the output file header.
1388// PSHNDX is the address to store the output section index.
1389
1390off_t inline
1391Layout::relaxation_loop_body(
1392 int pass,
1393 Target* target,
1394 Symbol_table* symtab,
1395 Output_segment** pload_seg,
1396 Output_segment* phdr_seg,
1397 Output_segment_headers* segment_headers,
1398 Output_file_header* file_header,
1399 unsigned int* pshndx)
1400{
1401 // If this is not the first iteration, we need to clean up after
1402 // relaxation so that we can lay out the sections again.
1403 if (pass != 0)
1404 this->clean_up_after_relaxation();
1405
1406 // If there is a SECTIONS clause, put all the input sections into
1407 // the required order.
1408 Output_segment* load_seg;
1409 if (this->script_options_->saw_sections_clause())
1410 load_seg = this->set_section_addresses_from_script(symtab);
1411 else if (parameters->options().relocatable())
1412 load_seg = NULL;
1413 else
1414 load_seg = this->find_first_load_seg();
1415
1416 if (parameters->options().oformat_enum()
1417 != General_options::OBJECT_FORMAT_ELF)
1418 load_seg = NULL;
1419
1420 gold_assert(phdr_seg == NULL || load_seg != NULL);
1421
1422 // Lay out the segment headers.
1423 if (!parameters->options().relocatable())
1424 {
1425 gold_assert(segment_headers != NULL);
1426 if (load_seg != NULL)
1427 load_seg->add_initial_output_data(segment_headers);
1428 if (phdr_seg != NULL)
1429 phdr_seg->add_initial_output_data(segment_headers);
1430 }
1431
1432 // Lay out the file header.
1433 if (load_seg != NULL)
1434 load_seg->add_initial_output_data(file_header);
1435
1436 if (this->script_options_->saw_phdrs_clause()
1437 && !parameters->options().relocatable())
1438 {
1439 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1440 // clause in a linker script.
1441 Script_sections* ss = this->script_options_->script_sections();
1442 ss->put_headers_in_phdrs(file_header, segment_headers);
1443 }
1444
1445 // We set the output section indexes in set_segment_offsets and
1446 // set_section_indexes.
1447 *pshndx = 1;
1448
1449 // Set the file offsets of all the segments, and all the sections
1450 // they contain.
1451 off_t off;
1452 if (!parameters->options().relocatable())
1453 off = this->set_segment_offsets(target, load_seg, pshndx);
1454 else
1455 off = this->set_relocatable_section_offsets(file_header, pshndx);
1456
1457 // Verify that the dummy relaxation does not change anything.
1458 if (is_debugging_enabled(DEBUG_RELAXATION))
1459 {
1460 if (pass == 0)
1461 this->relaxation_debug_check_->read_sections(this->section_list_);
1462 else
1463 this->relaxation_debug_check_->verify_sections(this->section_list_);
1464 }
1465
1466 *pload_seg = load_seg;
1467 return off;
1468}
1469
54dc6425
ILT
1470// Finalize the layout. When this is called, we have created all the
1471// output sections and all the output segments which are based on
1472// input sections. We have several things to do, and we have to do
1473// them in the right order, so that we get the right results correctly
1474// and efficiently.
1475
1476// 1) Finalize the list of output segments and create the segment
1477// table header.
1478
1479// 2) Finalize the dynamic symbol table and associated sections.
1480
1481// 3) Determine the final file offset of all the output segments.
1482
1483// 4) Determine the final file offset of all the SHF_ALLOC output
1484// sections.
1485
75f65a3e
ILT
1486// 5) Create the symbol table sections and the section name table
1487// section.
1488
1489// 6) Finalize the symbol table: set symbol values to their final
54dc6425
ILT
1490// value and make a final determination of which symbols are going
1491// into the output symbol table.
1492
54dc6425
ILT
1493// 7) Create the section table header.
1494
1495// 8) Determine the final file offset of all the output sections which
1496// are not SHF_ALLOC, including the section table header.
1497
1498// 9) Finalize the ELF file header.
1499
75f65a3e
ILT
1500// This function returns the size of the output file.
1501
1502off_t
17a1d0a9 1503Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
8851ecca 1504 Target* target, const Task* task)
54dc6425 1505{
7e1edb90 1506 target->finalize_sections(this);
5a6f7e2d 1507
17a1d0a9 1508 this->count_local_symbols(task, input_objects);
7bf1f802 1509
1518dc8f 1510 this->link_stabs_sections();
4f211c8b 1511
3802b2dd 1512 Output_segment* phdr_seg = NULL;
8851ecca 1513 if (!parameters->options().relocatable() && !parameters->doing_static_link())
54dc6425 1514 {
dbe717ef
ILT
1515 // There was a dynamic object in the link. We need to create
1516 // some information for the dynamic linker.
1517
3802b2dd
ILT
1518 // Create the PT_PHDR segment which will hold the program
1519 // headers.
1c4f3631
ILT
1520 if (!this->script_options_->saw_phdrs_clause())
1521 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
3802b2dd 1522
14b31740
ILT
1523 // Create the dynamic symbol table, including the hash table.
1524 Output_section* dynstr;
1525 std::vector<Symbol*> dynamic_symbols;
1526 unsigned int local_dynamic_count;
a5dc0706
ILT
1527 Versions versions(*this->script_options()->version_script_info(),
1528 &this->dynpool_);
9b07f471 1529 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
14b31740
ILT
1530 &local_dynamic_count, &dynamic_symbols,
1531 &versions);
dbe717ef
ILT
1532
1533 // Create the .interp section to hold the name of the
1534 // interpreter, and put it in a PT_INTERP segment.
8851ecca 1535 if (!parameters->options().shared())
96f2030e 1536 this->create_interp(target);
a3ad94ed
ILT
1537
1538 // Finish the .dynamic section to hold the dynamic data, and put
1539 // it in a PT_DYNAMIC segment.
16649710 1540 this->finish_dynamic_section(input_objects, symtab);
14b31740
ILT
1541
1542 // We should have added everything we need to the dynamic string
1543 // table.
1544 this->dynpool_.set_string_offsets();
1545
1546 // Create the version sections. We can't do this until the
1547 // dynamic string table is complete.
46fe1623 1548 this->create_version_sections(&versions, symtab, local_dynamic_count,
14b31740 1549 dynamic_symbols, dynstr);
54dc6425 1550 }
3ce2c28e
ILT
1551
1552 if (this->incremental_inputs_)
1553 {
1554 this->incremental_inputs_->finalize();
1555 this->create_incremental_info_sections();
1556 }
54dc6425 1557
20e6d0d6
DK
1558 // Create segment headers.
1559 Output_segment_headers* segment_headers =
1560 (parameters->options().relocatable()
1561 ? NULL
1562 : new Output_segment_headers(this->segment_list_));
75f65a3e
ILT
1563
1564 // Lay out the file header.
20e6d0d6
DK
1565 Output_file_header* file_header
1566 = new Output_file_header(target, symtab, segment_headers,
1567 parameters->options().entry());
a445fddf 1568
61ba1cf9 1569 this->special_output_list_.push_back(file_header);
6a74a719
ILT
1570 if (segment_headers != NULL)
1571 this->special_output_list_.push_back(segment_headers);
75f65a3e 1572
20e6d0d6
DK
1573 // Find approriate places for orphan output sections if we are using
1574 // a linker script.
1575 if (this->script_options_->saw_sections_clause())
1576 this->place_orphan_sections_in_script();
1577
1578 Output_segment* load_seg;
1579 off_t off;
1580 unsigned int shndx;
1581 int pass = 0;
1582
1583 // Take a snapshot of the section layout as needed.
1584 if (target->may_relax())
1585 this->prepare_for_relaxation();
1586
1587 // Run the relaxation loop to lay out sections.
1588 do
1c4f3631 1589 {
20e6d0d6
DK
1590 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1591 phdr_seg, segment_headers, file_header,
1592 &shndx);
1593 pass++;
1c4f3631 1594 }
20e6d0d6 1595 while (target->may_relax() && target->relax(pass));
75f65a3e 1596
a9a60db6
ILT
1597 // Set the file offsets of all the non-data sections we've seen so
1598 // far which don't have to wait for the input sections. We need
1599 // this in order to finalize local symbols in non-allocated
1600 // sections.
1601 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1602
d491d34e
ILT
1603 // Set the section indexes of all unallocated sections seen so far,
1604 // in case any of them are somehow referenced by a symbol.
1605 shndx = this->set_section_indexes(shndx);
1606
75f65a3e 1607 // Create the symbol table sections.
d491d34e 1608 this->create_symtab_sections(input_objects, symtab, shndx, &off);
7bf1f802
ILT
1609 if (!parameters->doing_static_link())
1610 this->assign_local_dynsym_offsets(input_objects);
75f65a3e 1611
e5756efb
ILT
1612 // Process any symbol assignments from a linker script. This must
1613 // be called after the symbol table has been finalized.
1614 this->script_options_->finalize_symbols(symtab, this);
1615
75f65a3e
ILT
1616 // Create the .shstrtab section.
1617 Output_section* shstrtab_section = this->create_shstrtab();
1618
a9a60db6
ILT
1619 // Set the file offsets of the rest of the non-data sections which
1620 // don't have to wait for the input sections.
9a0910c3 1621 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
86887060 1622
d491d34e
ILT
1623 // Now that all sections have been created, set the section indexes
1624 // for any sections which haven't been done yet.
86887060 1625 shndx = this->set_section_indexes(shndx);
ead1e424 1626
75f65a3e 1627 // Create the section table header.
d491d34e 1628 this->create_shdrs(shstrtab_section, &off);
75f65a3e 1629
17a1d0a9
ILT
1630 // If there are no sections which require postprocessing, we can
1631 // handle the section names now, and avoid a resize later.
1632 if (!this->any_postprocessing_sections_)
1633 off = this->set_section_offsets(off,
1634 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1635
27bc2bce 1636 file_header->set_section_info(this->section_headers_, shstrtab_section);
75f65a3e 1637
27bc2bce
ILT
1638 // Now we know exactly where everything goes in the output file
1639 // (except for non-allocated sections which require postprocessing).
a3ad94ed 1640 Output_data::layout_complete();
75f65a3e 1641
e44fcf3b
ILT
1642 this->output_file_size_ = off;
1643
75f65a3e
ILT
1644 return off;
1645}
1646
8ed814a9 1647// Create a note header following the format defined in the ELF ABI.
ec3f783e
ILT
1648// NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1649// of the section to create, DESCSZ is the size of the descriptor.
1650// ALLOCATE is true if the section should be allocated in memory.
1651// This returns the new note section. It sets *TRAILING_PADDING to
1652// the number of trailing zero bytes required.
4f211c8b 1653
8ed814a9 1654Output_section*
ef4ab7a8
PP
1655Layout::create_note(const char* name, int note_type,
1656 const char* section_name, size_t descsz,
8ed814a9 1657 bool allocate, size_t* trailing_padding)
4f211c8b 1658{
e2305dc0
ILT
1659 // Authorities all agree that the values in a .note field should
1660 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1661 // they differ on what the alignment is for 64-bit binaries.
1662 // The GABI says unambiguously they take 8-byte alignment:
1663 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1664 // Other documentation says alignment should always be 4 bytes:
1665 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1666 // GNU ld and GNU readelf both support the latter (at least as of
1667 // version 2.16.91), and glibc always generates the latter for
1668 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1669 // here.
35cdfc9a 1670#ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
8851ecca 1671 const int size = parameters->target().get_size();
e2305dc0
ILT
1672#else
1673 const int size = 32;
1674#endif
4f211c8b
ILT
1675
1676 // The contents of the .note section.
4f211c8b
ILT
1677 size_t namesz = strlen(name) + 1;
1678 size_t aligned_namesz = align_address(namesz, size / 8);
4f211c8b 1679 size_t aligned_descsz = align_address(descsz, size / 8);
4f211c8b 1680
8ed814a9 1681 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
4f211c8b 1682
8ed814a9
ILT
1683 unsigned char* buffer = new unsigned char[notehdrsz];
1684 memset(buffer, 0, notehdrsz);
4f211c8b 1685
8851ecca 1686 bool is_big_endian = parameters->target().is_big_endian();
4f211c8b
ILT
1687
1688 if (size == 32)
1689 {
1690 if (!is_big_endian)
1691 {
1692 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1693 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1694 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1695 }
1696 else
1697 {
1698 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1699 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1700 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1701 }
1702 }
1703 else if (size == 64)
1704 {
1705 if (!is_big_endian)
1706 {
1707 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1708 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1709 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1710 }
1711 else
1712 {
1713 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1714 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1715 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1716 }
1717 }
1718 else
1719 gold_unreachable();
1720
1721 memcpy(buffer + 3 * (size / 8), name, namesz);
4f211c8b 1722
8ed814a9
ILT
1723 elfcpp::Elf_Xword flags = 0;
1724 if (allocate)
1725 flags = elfcpp::SHF_ALLOC;
ec3f783e
ILT
1726 Output_section* os = this->choose_output_section(NULL, section_name,
1727 elfcpp::SHT_NOTE,
1728 flags, false);
9c547ec3
ILT
1729 if (os == NULL)
1730 return NULL;
1731
8ed814a9 1732 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
7d9e3d98
ILT
1733 size / 8,
1734 "** note header");
8ed814a9
ILT
1735 os->add_output_section_data(posd);
1736
1737 *trailing_padding = aligned_descsz - descsz;
1738
1739 return os;
1740}
1741
1742// For an executable or shared library, create a note to record the
1743// version of gold used to create the binary.
1744
1745void
1746Layout::create_gold_note()
1747{
1748 if (parameters->options().relocatable())
1749 return;
1750
1751 std::string desc = std::string("gold ") + gold::get_version_string();
1752
1753 size_t trailing_padding;
1754 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
ef4ab7a8
PP
1755 ".note.gnu.gold-version", desc.size(),
1756 false, &trailing_padding);
9c547ec3
ILT
1757 if (os == NULL)
1758 return;
8ed814a9
ILT
1759
1760 Output_section_data* posd = new Output_data_const(desc, 4);
4f211c8b 1761 os->add_output_section_data(posd);
8ed814a9
ILT
1762
1763 if (trailing_padding > 0)
1764 {
7d9e3d98 1765 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
1766 os->add_output_section_data(posd);
1767 }
4f211c8b
ILT
1768}
1769
35cdfc9a
ILT
1770// Record whether the stack should be executable. This can be set
1771// from the command line using the -z execstack or -z noexecstack
1772// options. Otherwise, if any input file has a .note.GNU-stack
1773// section with the SHF_EXECINSTR flag set, the stack should be
1774// executable. Otherwise, if at least one input file a
1775// .note.GNU-stack section, and some input file has no .note.GNU-stack
1776// section, we use the target default for whether the stack should be
1777// executable. Otherwise, we don't generate a stack note. When
1778// generating a object file, we create a .note.GNU-stack section with
1779// the appropriate marking. When generating an executable or shared
1780// library, we create a PT_GNU_STACK segment.
1781
1782void
9c547ec3 1783Layout::create_executable_stack_info()
35cdfc9a
ILT
1784{
1785 bool is_stack_executable;
e55bde5e
ILT
1786 if (parameters->options().is_execstack_set())
1787 is_stack_executable = parameters->options().is_stack_executable();
35cdfc9a
ILT
1788 else if (!this->input_with_gnu_stack_note_)
1789 return;
1790 else
1791 {
1792 if (this->input_requires_executable_stack_)
1793 is_stack_executable = true;
1794 else if (this->input_without_gnu_stack_note_)
9c547ec3
ILT
1795 is_stack_executable =
1796 parameters->target().is_default_stack_executable();
35cdfc9a
ILT
1797 else
1798 is_stack_executable = false;
1799 }
1800
8851ecca 1801 if (parameters->options().relocatable())
35cdfc9a
ILT
1802 {
1803 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1804 elfcpp::Elf_Xword flags = 0;
1805 if (is_stack_executable)
1806 flags |= elfcpp::SHF_EXECINSTR;
1807 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1808 }
1809 else
1810 {
1c4f3631
ILT
1811 if (this->script_options_->saw_phdrs_clause())
1812 return;
35cdfc9a
ILT
1813 int flags = elfcpp::PF_R | elfcpp::PF_W;
1814 if (is_stack_executable)
1815 flags |= elfcpp::PF_X;
3802b2dd 1816 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
35cdfc9a
ILT
1817 }
1818}
1819
8ed814a9
ILT
1820// If --build-id was used, set up the build ID note.
1821
1822void
1823Layout::create_build_id()
1824{
1825 if (!parameters->options().user_set_build_id())
1826 return;
1827
1828 const char* style = parameters->options().build_id();
1829 if (strcmp(style, "none") == 0)
1830 return;
1831
1832 // Set DESCSZ to the size of the note descriptor. When possible,
1833 // set DESC to the note descriptor contents.
1834 size_t descsz;
1835 std::string desc;
1836 if (strcmp(style, "md5") == 0)
1837 descsz = 128 / 8;
1838 else if (strcmp(style, "sha1") == 0)
1839 descsz = 160 / 8;
1840 else if (strcmp(style, "uuid") == 0)
1841 {
1842 const size_t uuidsz = 128 / 8;
1843
1844 char buffer[uuidsz];
1845 memset(buffer, 0, uuidsz);
1846
2a00e4fb 1847 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
8ed814a9
ILT
1848 if (descriptor < 0)
1849 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1850 strerror(errno));
1851 else
1852 {
1853 ssize_t got = ::read(descriptor, buffer, uuidsz);
2a00e4fb 1854 release_descriptor(descriptor, true);
8ed814a9
ILT
1855 if (got < 0)
1856 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1857 else if (static_cast<size_t>(got) != uuidsz)
1858 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1859 uuidsz, got);
1860 }
1861
1862 desc.assign(buffer, uuidsz);
1863 descsz = uuidsz;
1864 }
1865 else if (strncmp(style, "0x", 2) == 0)
1866 {
1867 hex_init();
1868 const char* p = style + 2;
1869 while (*p != '\0')
1870 {
1871 if (hex_p(p[0]) && hex_p(p[1]))
1872 {
1873 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1874 desc += c;
1875 p += 2;
1876 }
1877 else if (*p == '-' || *p == ':')
1878 ++p;
1879 else
1880 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1881 style);
1882 }
1883 descsz = desc.size();
1884 }
1885 else
1886 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1887
1888 // Create the note.
1889 size_t trailing_padding;
1890 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
ef4ab7a8
PP
1891 ".note.gnu.build-id", descsz, true,
1892 &trailing_padding);
9c547ec3
ILT
1893 if (os == NULL)
1894 return;
8ed814a9
ILT
1895
1896 if (!desc.empty())
1897 {
1898 // We know the value already, so we fill it in now.
1899 gold_assert(desc.size() == descsz);
1900
1901 Output_section_data* posd = new Output_data_const(desc, 4);
1902 os->add_output_section_data(posd);
1903
1904 if (trailing_padding != 0)
1905 {
7d9e3d98 1906 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
1907 os->add_output_section_data(posd);
1908 }
1909 }
1910 else
1911 {
1912 // We need to compute a checksum after we have completed the
1913 // link.
1914 gold_assert(trailing_padding == 0);
7d9e3d98 1915 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
8ed814a9 1916 os->add_output_section_data(this->build_id_note_);
8ed814a9
ILT
1917 }
1918}
1919
1518dc8f
ILT
1920// If we have both .stabXX and .stabXXstr sections, then the sh_link
1921// field of the former should point to the latter. I'm not sure who
1922// started this, but the GNU linker does it, and some tools depend
1923// upon it.
1924
1925void
1926Layout::link_stabs_sections()
1927{
1928 if (!this->have_stabstr_section_)
1929 return;
1930
1931 for (Section_list::iterator p = this->section_list_.begin();
1932 p != this->section_list_.end();
1933 ++p)
1934 {
1935 if ((*p)->type() != elfcpp::SHT_STRTAB)
1936 continue;
1937
1938 const char* name = (*p)->name();
1939 if (strncmp(name, ".stab", 5) != 0)
1940 continue;
1941
1942 size_t len = strlen(name);
1943 if (strcmp(name + len - 3, "str") != 0)
1944 continue;
1945
1946 std::string stab_name(name, len - 3);
1947 Output_section* stab_sec;
1948 stab_sec = this->find_output_section(stab_name.c_str());
1949 if (stab_sec != NULL)
1950 stab_sec->set_link_section(*p);
1951 }
1952}
1953
3ce2c28e
ILT
1954// Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
1955// for the next run of incremental linking to check what has changed.
1956
1957void
1958Layout::create_incremental_info_sections()
1959{
1960 gold_assert(this->incremental_inputs_ != NULL);
1961
1962 // Add the .gnu_incremental_inputs section.
1963 const char *incremental_inputs_name =
1964 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
1965 Output_section* inputs_os =
1966 this->make_output_section(incremental_inputs_name,
1967 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0);
1968 Output_section_data* posd =
1969 this->incremental_inputs_->create_incremental_inputs_section_data();
1970 inputs_os->add_output_section_data(posd);
1971
1972 // Add the .gnu_incremental_strtab section.
1973 const char *incremental_strtab_name =
1974 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
1975 Output_section* strtab_os = this->make_output_section(incremental_strtab_name,
1976 elfcpp::SHT_STRTAB,
1977 0);
1978 Output_data_strtab* strtab_data =
1979 new Output_data_strtab(this->incremental_inputs_->get_stringpool());
1980 strtab_os->add_output_section_data(strtab_data);
1981
1982 inputs_os->set_link_section(strtab_data);
1983}
1984
75f65a3e
ILT
1985// Return whether SEG1 should be before SEG2 in the output file. This
1986// is based entirely on the segment type and flags. When this is
1987// called the segment addresses has normally not yet been set.
1988
1989bool
1990Layout::segment_precedes(const Output_segment* seg1,
1991 const Output_segment* seg2)
1992{
1993 elfcpp::Elf_Word type1 = seg1->type();
1994 elfcpp::Elf_Word type2 = seg2->type();
1995
1996 // The single PT_PHDR segment is required to precede any loadable
1997 // segment. We simply make it always first.
1998 if (type1 == elfcpp::PT_PHDR)
1999 {
a3ad94ed 2000 gold_assert(type2 != elfcpp::PT_PHDR);
75f65a3e
ILT
2001 return true;
2002 }
2003 if (type2 == elfcpp::PT_PHDR)
2004 return false;
2005
2006 // The single PT_INTERP segment is required to precede any loadable
2007 // segment. We simply make it always second.
2008 if (type1 == elfcpp::PT_INTERP)
2009 {
a3ad94ed 2010 gold_assert(type2 != elfcpp::PT_INTERP);
75f65a3e
ILT
2011 return true;
2012 }
2013 if (type2 == elfcpp::PT_INTERP)
2014 return false;
2015
2016 // We then put PT_LOAD segments before any other segments.
2017 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2018 return true;
2019 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2020 return false;
2021
9f1d377b
ILT
2022 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2023 // segment, because that is where the dynamic linker expects to find
2024 // it (this is just for efficiency; other positions would also work
2025 // correctly).
2026 if (type1 == elfcpp::PT_TLS
2027 && type2 != elfcpp::PT_TLS
2028 && type2 != elfcpp::PT_GNU_RELRO)
2029 return false;
2030 if (type2 == elfcpp::PT_TLS
2031 && type1 != elfcpp::PT_TLS
2032 && type1 != elfcpp::PT_GNU_RELRO)
2033 return true;
2034
2035 // We put the PT_GNU_RELRO segment last, because that is where the
2036 // dynamic linker expects to find it (as with PT_TLS, this is just
2037 // for efficiency).
2038 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
92e059d8 2039 return false;
9f1d377b 2040 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
92e059d8
ILT
2041 return true;
2042
75f65a3e
ILT
2043 const elfcpp::Elf_Word flags1 = seg1->flags();
2044 const elfcpp::Elf_Word flags2 = seg2->flags();
2045
2046 // The order of non-PT_LOAD segments is unimportant. We simply sort
2047 // by the numeric segment type and flags values. There should not
2048 // be more than one segment with the same type and flags.
2049 if (type1 != elfcpp::PT_LOAD)
2050 {
2051 if (type1 != type2)
2052 return type1 < type2;
a3ad94ed 2053 gold_assert(flags1 != flags2);
75f65a3e
ILT
2054 return flags1 < flags2;
2055 }
2056
a445fddf
ILT
2057 // If the addresses are set already, sort by load address.
2058 if (seg1->are_addresses_set())
2059 {
2060 if (!seg2->are_addresses_set())
2061 return true;
2062
2063 unsigned int section_count1 = seg1->output_section_count();
2064 unsigned int section_count2 = seg2->output_section_count();
2065 if (section_count1 == 0 && section_count2 > 0)
2066 return true;
2067 if (section_count1 > 0 && section_count2 == 0)
2068 return false;
2069
2070 uint64_t paddr1 = seg1->first_section_load_address();
2071 uint64_t paddr2 = seg2->first_section_load_address();
2072 if (paddr1 != paddr2)
2073 return paddr1 < paddr2;
2074 }
2075 else if (seg2->are_addresses_set())
2076 return false;
2077
8a5e3e08
ILT
2078 // A segment which holds large data comes after a segment which does
2079 // not hold large data.
2080 if (seg1->is_large_data_segment())
2081 {
2082 if (!seg2->is_large_data_segment())
2083 return false;
2084 }
2085 else if (seg2->is_large_data_segment())
2086 return true;
2087
2088 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2089 // segments come before writable segments. Then writable segments
2090 // with data come before writable segments without data. Then
2091 // executable segments come before non-executable segments. Then
2092 // the unlikely case of a non-readable segment comes before the
2093 // normal case of a readable segment. If there are multiple
2094 // segments with the same type and flags, we require that the
2095 // address be set, and we sort by virtual address and then physical
2096 // address.
75f65a3e
ILT
2097 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2098 return (flags1 & elfcpp::PF_W) == 0;
756ac4a8
ILT
2099 if ((flags1 & elfcpp::PF_W) != 0
2100 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2101 return seg1->has_any_data_sections();
75f65a3e
ILT
2102 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2103 return (flags1 & elfcpp::PF_X) != 0;
2104 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2105 return (flags1 & elfcpp::PF_R) == 0;
2106
a445fddf
ILT
2107 // We shouldn't get here--we shouldn't create segments which we
2108 // can't distinguish.
2109 gold_unreachable();
75f65a3e
ILT
2110}
2111
8a5e3e08
ILT
2112// Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2113
2114static off_t
2115align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2116{
2117 uint64_t unsigned_off = off;
2118 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2119 | (addr & (abi_pagesize - 1)));
2120 if (aligned_off < unsigned_off)
2121 aligned_off += abi_pagesize;
2122 return aligned_off;
2123}
2124
ead1e424
ILT
2125// Set the file offsets of all the segments, and all the sections they
2126// contain. They have all been created. LOAD_SEG must be be laid out
2127// first. Return the offset of the data to follow.
75f65a3e
ILT
2128
2129off_t
ead1e424
ILT
2130Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2131 unsigned int *pshndx)
75f65a3e
ILT
2132{
2133 // Sort them into the final order.
54dc6425
ILT
2134 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2135 Layout::Compare_segments());
2136
75f65a3e
ILT
2137 // Find the PT_LOAD segments, and set their addresses and offsets
2138 // and their section's addresses and offsets.
0c5e9c22 2139 uint64_t addr;
e55bde5e
ILT
2140 if (parameters->options().user_set_Ttext())
2141 addr = parameters->options().Ttext();
8851ecca 2142 else if (parameters->options().shared())
a445fddf 2143 addr = 0;
0c5e9c22
ILT
2144 else
2145 addr = target->default_text_segment_address();
75f65a3e 2146 off_t off = 0;
a445fddf
ILT
2147
2148 // If LOAD_SEG is NULL, then the file header and segment headers
2149 // will not be loadable. But they still need to be at offset 0 in
2150 // the file. Set their offsets now.
2151 if (load_seg == NULL)
2152 {
2153 for (Data_list::iterator p = this->special_output_list_.begin();
2154 p != this->special_output_list_.end();
2155 ++p)
2156 {
2157 off = align_address(off, (*p)->addralign());
2158 (*p)->set_address_and_file_offset(0, off);
2159 off += (*p)->data_size();
2160 }
2161 }
2162
34810851
ILT
2163 const bool check_sections = parameters->options().check_sections();
2164 Output_segment* last_load_segment = NULL;
2165
75f65a3e
ILT
2166 bool was_readonly = false;
2167 for (Segment_list::iterator p = this->segment_list_.begin();
2168 p != this->segment_list_.end();
2169 ++p)
2170 {
2171 if ((*p)->type() == elfcpp::PT_LOAD)
2172 {
2173 if (load_seg != NULL && load_seg != *p)
a3ad94ed 2174 gold_unreachable();
75f65a3e
ILT
2175 load_seg = NULL;
2176
756ac4a8
ILT
2177 bool are_addresses_set = (*p)->are_addresses_set();
2178 if (are_addresses_set)
2179 {
2180 // When it comes to setting file offsets, we care about
2181 // the physical address.
2182 addr = (*p)->paddr();
2183 }
e55bde5e 2184 else if (parameters->options().user_set_Tdata()
756ac4a8 2185 && ((*p)->flags() & elfcpp::PF_W) != 0
e55bde5e 2186 && (!parameters->options().user_set_Tbss()
756ac4a8
ILT
2187 || (*p)->has_any_data_sections()))
2188 {
e55bde5e 2189 addr = parameters->options().Tdata();
756ac4a8
ILT
2190 are_addresses_set = true;
2191 }
e55bde5e 2192 else if (parameters->options().user_set_Tbss()
756ac4a8
ILT
2193 && ((*p)->flags() & elfcpp::PF_W) != 0
2194 && !(*p)->has_any_data_sections())
2195 {
e55bde5e 2196 addr = parameters->options().Tbss();
756ac4a8
ILT
2197 are_addresses_set = true;
2198 }
2199
75f65a3e
ILT
2200 uint64_t orig_addr = addr;
2201 uint64_t orig_off = off;
2202
a445fddf 2203 uint64_t aligned_addr = 0;
75f65a3e 2204 uint64_t abi_pagesize = target->abi_pagesize();
af6156ef 2205 uint64_t common_pagesize = target->common_pagesize();
0496d5e5 2206
af6156ef
ILT
2207 if (!parameters->options().nmagic()
2208 && !parameters->options().omagic())
2209 (*p)->set_minimum_p_align(common_pagesize);
0496d5e5 2210
8a5e3e08 2211 if (!are_addresses_set)
a445fddf
ILT
2212 {
2213 // If the last segment was readonly, and this one is
2214 // not, then skip the address forward one page,
2215 // maintaining the same position within the page. This
2216 // lets us store both segments overlapping on a single
2217 // page in the file, but the loader will put them on
2218 // different pages in memory.
2219
2220 addr = align_address(addr, (*p)->maximum_alignment());
75f65a3e 2221 aligned_addr = addr;
a445fddf
ILT
2222
2223 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2224 {
2225 if ((addr & (abi_pagesize - 1)) != 0)
2226 addr = addr + abi_pagesize;
2227 }
2228
2229 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
75f65a3e
ILT
2230 }
2231
8a5e3e08
ILT
2232 if (!parameters->options().nmagic()
2233 && !parameters->options().omagic())
2234 off = align_file_offset(off, addr, abi_pagesize);
2235
ead1e424 2236 unsigned int shndx_hold = *pshndx;
96a2b4e4
ILT
2237 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2238 &off, pshndx);
75f65a3e
ILT
2239
2240 // Now that we know the size of this segment, we may be able
2241 // to save a page in memory, at the cost of wasting some
2242 // file space, by instead aligning to the start of a new
2243 // page. Here we use the real machine page size rather than
2244 // the ABI mandated page size.
2245
a445fddf 2246 if (!are_addresses_set && aligned_addr != addr)
75f65a3e 2247 {
75f65a3e
ILT
2248 uint64_t first_off = (common_pagesize
2249 - (aligned_addr
2250 & (common_pagesize - 1)));
2251 uint64_t last_off = new_addr & (common_pagesize - 1);
2252 if (first_off > 0
2253 && last_off > 0
2254 && ((aligned_addr & ~ (common_pagesize - 1))
2255 != (new_addr & ~ (common_pagesize - 1)))
2256 && first_off + last_off <= common_pagesize)
2257 {
ead1e424
ILT
2258 *pshndx = shndx_hold;
2259 addr = align_address(aligned_addr, common_pagesize);
a445fddf 2260 addr = align_address(addr, (*p)->maximum_alignment());
75f65a3e 2261 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
8a5e3e08 2262 off = align_file_offset(off, addr, abi_pagesize);
96a2b4e4
ILT
2263 new_addr = (*p)->set_section_addresses(this, true, addr,
2264 &off, pshndx);
75f65a3e
ILT
2265 }
2266 }
2267
2268 addr = new_addr;
2269
2270 if (((*p)->flags() & elfcpp::PF_W) == 0)
2271 was_readonly = true;
34810851
ILT
2272
2273 // Implement --check-sections. We know that the segments
2274 // are sorted by LMA.
2275 if (check_sections && last_load_segment != NULL)
2276 {
2277 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2278 if (last_load_segment->paddr() + last_load_segment->memsz()
2279 > (*p)->paddr())
2280 {
2281 unsigned long long lb1 = last_load_segment->paddr();
2282 unsigned long long le1 = lb1 + last_load_segment->memsz();
2283 unsigned long long lb2 = (*p)->paddr();
2284 unsigned long long le2 = lb2 + (*p)->memsz();
2285 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2286 "[0x%llx -> 0x%llx]"),
2287 lb1, le1, lb2, le2);
2288 }
2289 }
2290 last_load_segment = *p;
75f65a3e
ILT
2291 }
2292 }
2293
2294 // Handle the non-PT_LOAD segments, setting their offsets from their
2295 // section's offsets.
2296 for (Segment_list::iterator p = this->segment_list_.begin();
2297 p != this->segment_list_.end();
2298 ++p)
2299 {
2300 if ((*p)->type() != elfcpp::PT_LOAD)
2301 (*p)->set_offset();
2302 }
2303
7bf1f802
ILT
2304 // Set the TLS offsets for each section in the PT_TLS segment.
2305 if (this->tls_segment_ != NULL)
2306 this->tls_segment_->set_tls_offsets();
2307
75f65a3e
ILT
2308 return off;
2309}
2310
6a74a719
ILT
2311// Set the offsets of all the allocated sections when doing a
2312// relocatable link. This does the same jobs as set_segment_offsets,
2313// only for a relocatable link.
2314
2315off_t
2316Layout::set_relocatable_section_offsets(Output_data* file_header,
2317 unsigned int *pshndx)
2318{
2319 off_t off = 0;
2320
2321 file_header->set_address_and_file_offset(0, 0);
2322 off += file_header->data_size();
2323
2324 for (Section_list::iterator p = this->section_list_.begin();
2325 p != this->section_list_.end();
2326 ++p)
2327 {
2328 // We skip unallocated sections here, except that group sections
2329 // have to come first.
2330 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2331 && (*p)->type() != elfcpp::SHT_GROUP)
2332 continue;
2333
2334 off = align_address(off, (*p)->addralign());
2335
2336 // The linker script might have set the address.
2337 if (!(*p)->is_address_valid())
2338 (*p)->set_address(0);
2339 (*p)->set_file_offset(off);
2340 (*p)->finalize_data_size();
2341 off += (*p)->data_size();
2342
2343 (*p)->set_out_shndx(*pshndx);
2344 ++*pshndx;
2345 }
2346
2347 return off;
2348}
2349
75f65a3e
ILT
2350// Set the file offset of all the sections not associated with a
2351// segment.
2352
2353off_t
9a0910c3 2354Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
75f65a3e 2355{
a3ad94ed
ILT
2356 for (Section_list::iterator p = this->unattached_section_list_.begin();
2357 p != this->unattached_section_list_.end();
75f65a3e
ILT
2358 ++p)
2359 {
27bc2bce
ILT
2360 // The symtab section is handled in create_symtab_sections.
2361 if (*p == this->symtab_section_)
61ba1cf9 2362 continue;
27bc2bce 2363
a9a60db6
ILT
2364 // If we've already set the data size, don't set it again.
2365 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2366 continue;
2367
96803768
ILT
2368 if (pass == BEFORE_INPUT_SECTIONS_PASS
2369 && (*p)->requires_postprocessing())
17a1d0a9
ILT
2370 {
2371 (*p)->create_postprocessing_buffer();
2372 this->any_postprocessing_sections_ = true;
2373 }
96803768 2374
9a0910c3
ILT
2375 if (pass == BEFORE_INPUT_SECTIONS_PASS
2376 && (*p)->after_input_sections())
2377 continue;
17a1d0a9 2378 else if (pass == POSTPROCESSING_SECTIONS_PASS
9a0910c3
ILT
2379 && (!(*p)->after_input_sections()
2380 || (*p)->type() == elfcpp::SHT_STRTAB))
2381 continue;
17a1d0a9 2382 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
9a0910c3
ILT
2383 && (!(*p)->after_input_sections()
2384 || (*p)->type() != elfcpp::SHT_STRTAB))
2385 continue;
27bc2bce 2386
ead1e424 2387 off = align_address(off, (*p)->addralign());
27bc2bce
ILT
2388 (*p)->set_file_offset(off);
2389 (*p)->finalize_data_size();
75f65a3e 2390 off += (*p)->data_size();
96803768
ILT
2391
2392 // At this point the name must be set.
17a1d0a9 2393 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
96803768 2394 this->namepool_.add((*p)->name(), false, NULL);
75f65a3e
ILT
2395 }
2396 return off;
2397}
2398
86887060
ILT
2399// Set the section indexes of all the sections not associated with a
2400// segment.
2401
2402unsigned int
2403Layout::set_section_indexes(unsigned int shndx)
2404{
2405 for (Section_list::iterator p = this->unattached_section_list_.begin();
2406 p != this->unattached_section_list_.end();
2407 ++p)
2408 {
d491d34e
ILT
2409 if (!(*p)->has_out_shndx())
2410 {
2411 (*p)->set_out_shndx(shndx);
2412 ++shndx;
2413 }
86887060
ILT
2414 }
2415 return shndx;
2416}
2417
a445fddf
ILT
2418// Set the section addresses according to the linker script. This is
2419// only called when we see a SECTIONS clause. This returns the
2420// program segment which should hold the file header and segment
2421// headers, if any. It will return NULL if they should not be in a
2422// segment.
2423
2424Output_segment*
2425Layout::set_section_addresses_from_script(Symbol_table* symtab)
20e6d0d6
DK
2426{
2427 Script_sections* ss = this->script_options_->script_sections();
2428 gold_assert(ss->saw_sections_clause());
2429 return this->script_options_->set_section_addresses(symtab, this);
2430}
2431
2432// Place the orphan sections in the linker script.
2433
2434void
2435Layout::place_orphan_sections_in_script()
a445fddf
ILT
2436{
2437 Script_sections* ss = this->script_options_->script_sections();
2438 gold_assert(ss->saw_sections_clause());
2439
2440 // Place each orphaned output section in the script.
2441 for (Section_list::iterator p = this->section_list_.begin();
2442 p != this->section_list_.end();
2443 ++p)
2444 {
2445 if (!(*p)->found_in_sections_clause())
2446 ss->place_orphan(*p);
2447 }
a445fddf
ILT
2448}
2449
7bf1f802
ILT
2450// Count the local symbols in the regular symbol table and the dynamic
2451// symbol table, and build the respective string pools.
2452
2453void
17a1d0a9
ILT
2454Layout::count_local_symbols(const Task* task,
2455 const Input_objects* input_objects)
7bf1f802 2456{
6d013333
ILT
2457 // First, figure out an upper bound on the number of symbols we'll
2458 // be inserting into each pool. This helps us create the pools with
2459 // the right size, to avoid unnecessary hashtable resizing.
2460 unsigned int symbol_count = 0;
2461 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2462 p != input_objects->relobj_end();
2463 ++p)
2464 symbol_count += (*p)->local_symbol_count();
2465
2466 // Go from "upper bound" to "estimate." We overcount for two
2467 // reasons: we double-count symbols that occur in more than one
2468 // object file, and we count symbols that are dropped from the
2469 // output. Add it all together and assume we overcount by 100%.
2470 symbol_count /= 2;
2471
2472 // We assume all symbols will go into both the sympool and dynpool.
2473 this->sympool_.reserve(symbol_count);
2474 this->dynpool_.reserve(symbol_count);
2475
7bf1f802
ILT
2476 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2477 p != input_objects->relobj_end();
2478 ++p)
2479 {
17a1d0a9 2480 Task_lock_obj<Object> tlo(task, *p);
7bf1f802
ILT
2481 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2482 }
2483}
2484
b8e6aad9
ILT
2485// Create the symbol table sections. Here we also set the final
2486// values of the symbols. At this point all the loadable sections are
d491d34e 2487// fully laid out. SHNUM is the number of sections so far.
75f65a3e
ILT
2488
2489void
9025d29d 2490Layout::create_symtab_sections(const Input_objects* input_objects,
75f65a3e 2491 Symbol_table* symtab,
d491d34e 2492 unsigned int shnum,
16649710 2493 off_t* poff)
75f65a3e 2494{
61ba1cf9
ILT
2495 int symsize;
2496 unsigned int align;
8851ecca 2497 if (parameters->target().get_size() == 32)
61ba1cf9
ILT
2498 {
2499 symsize = elfcpp::Elf_sizes<32>::sym_size;
2500 align = 4;
2501 }
8851ecca 2502 else if (parameters->target().get_size() == 64)
61ba1cf9
ILT
2503 {
2504 symsize = elfcpp::Elf_sizes<64>::sym_size;
2505 align = 8;
2506 }
2507 else
a3ad94ed 2508 gold_unreachable();
61ba1cf9
ILT
2509
2510 off_t off = *poff;
ead1e424 2511 off = align_address(off, align);
61ba1cf9
ILT
2512 off_t startoff = off;
2513
2514 // Save space for the dummy symbol at the start of the section. We
2515 // never bother to write this out--it will just be left as zero.
2516 off += symsize;
c06b7b0b 2517 unsigned int local_symbol_index = 1;
61ba1cf9 2518
a3ad94ed
ILT
2519 // Add STT_SECTION symbols for each Output section which needs one.
2520 for (Section_list::iterator p = this->section_list_.begin();
2521 p != this->section_list_.end();
2522 ++p)
2523 {
2524 if (!(*p)->needs_symtab_index())
2525 (*p)->set_symtab_index(-1U);
2526 else
2527 {
2528 (*p)->set_symtab_index(local_symbol_index);
2529 ++local_symbol_index;
2530 off += symsize;
2531 }
2532 }
2533
f6ce93d6
ILT
2534 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2535 p != input_objects->relobj_end();
75f65a3e
ILT
2536 ++p)
2537 {
c06b7b0b 2538 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
ef15dade 2539 off, symtab);
c06b7b0b
ILT
2540 off += (index - local_symbol_index) * symsize;
2541 local_symbol_index = index;
75f65a3e
ILT
2542 }
2543
c06b7b0b 2544 unsigned int local_symcount = local_symbol_index;
75aea3d0 2545 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
61ba1cf9 2546
16649710
ILT
2547 off_t dynoff;
2548 size_t dyn_global_index;
2549 size_t dyncount;
2550 if (this->dynsym_section_ == NULL)
2551 {
2552 dynoff = 0;
2553 dyn_global_index = 0;
2554 dyncount = 0;
2555 }
2556 else
2557 {
2558 dyn_global_index = this->dynsym_section_->info();
2559 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2560 dynoff = this->dynsym_section_->offset() + locsize;
2561 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
f5c3f225 2562 gold_assert(static_cast<off_t>(dyncount * symsize)
16649710
ILT
2563 == this->dynsym_section_->data_size() - locsize);
2564 }
2565
55a93433
ILT
2566 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2567 &this->sympool_, &local_symcount);
75f65a3e 2568
8851ecca 2569 if (!parameters->options().strip_all())
9e2dcb77
ILT
2570 {
2571 this->sympool_.set_string_offsets();
61ba1cf9 2572
cfd73a4e 2573 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
9e2dcb77
ILT
2574 Output_section* osymtab = this->make_output_section(symtab_name,
2575 elfcpp::SHT_SYMTAB,
2576 0);
2577 this->symtab_section_ = osymtab;
a3ad94ed 2578
27bc2bce 2579 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
7d9e3d98
ILT
2580 align,
2581 "** symtab");
9e2dcb77 2582 osymtab->add_output_section_data(pos);
61ba1cf9 2583
d491d34e
ILT
2584 // We generate a .symtab_shndx section if we have more than
2585 // SHN_LORESERVE sections. Technically it is possible that we
2586 // don't need one, because it is possible that there are no
2587 // symbols in any of sections with indexes larger than
2588 // SHN_LORESERVE. That is probably unusual, though, and it is
2589 // easier to always create one than to compute section indexes
2590 // twice (once here, once when writing out the symbols).
2591 if (shnum >= elfcpp::SHN_LORESERVE)
2592 {
2593 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2594 false, NULL);
2595 Output_section* osymtab_xindex =
2596 this->make_output_section(symtab_xindex_name,
2597 elfcpp::SHT_SYMTAB_SHNDX, 0);
2598
2599 size_t symcount = (off - startoff) / symsize;
2600 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2601
2602 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2603
2604 osymtab_xindex->set_link_section(osymtab);
2605 osymtab_xindex->set_addralign(4);
2606 osymtab_xindex->set_entsize(4);
2607
2608 osymtab_xindex->set_after_input_sections();
2609
2610 // This tells the driver code to wait until the symbol table
2611 // has written out before writing out the postprocessing
2612 // sections, including the .symtab_shndx section.
2613 this->any_postprocessing_sections_ = true;
2614 }
2615
cfd73a4e 2616 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
9e2dcb77
ILT
2617 Output_section* ostrtab = this->make_output_section(strtab_name,
2618 elfcpp::SHT_STRTAB,
2619 0);
a3ad94ed 2620
9e2dcb77
ILT
2621 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2622 ostrtab->add_output_section_data(pstr);
61ba1cf9 2623
27bc2bce
ILT
2624 osymtab->set_file_offset(startoff);
2625 osymtab->finalize_data_size();
9e2dcb77
ILT
2626 osymtab->set_link_section(ostrtab);
2627 osymtab->set_info(local_symcount);
2628 osymtab->set_entsize(symsize);
61ba1cf9 2629
9e2dcb77
ILT
2630 *poff = off;
2631 }
75f65a3e
ILT
2632}
2633
2634// Create the .shstrtab section, which holds the names of the
2635// sections. At the time this is called, we have created all the
2636// output sections except .shstrtab itself.
2637
2638Output_section*
2639Layout::create_shstrtab()
2640{
2641 // FIXME: We don't need to create a .shstrtab section if we are
2642 // stripping everything.
2643
cfd73a4e 2644 const char* name = this->namepool_.add(".shstrtab", false, NULL);
75f65a3e 2645
a3ad94ed 2646 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
75f65a3e 2647
27bc2bce
ILT
2648 // We can't write out this section until we've set all the section
2649 // names, and we don't set the names of compressed output sections
2650 // until relocations are complete.
2651 os->set_after_input_sections();
2652
a3ad94ed
ILT
2653 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2654 os->add_output_section_data(posd);
75f65a3e
ILT
2655
2656 return os;
2657}
2658
2659// Create the section headers. SIZE is 32 or 64. OFF is the file
2660// offset.
2661
27bc2bce 2662void
d491d34e 2663Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
75f65a3e
ILT
2664{
2665 Output_section_headers* oshdrs;
9025d29d 2666 oshdrs = new Output_section_headers(this,
16649710 2667 &this->segment_list_,
6a74a719 2668 &this->section_list_,
16649710 2669 &this->unattached_section_list_,
d491d34e
ILT
2670 &this->namepool_,
2671 shstrtab_section);
ead1e424 2672 off_t off = align_address(*poff, oshdrs->addralign());
27bc2bce 2673 oshdrs->set_address_and_file_offset(0, off);
61ba1cf9
ILT
2674 off += oshdrs->data_size();
2675 *poff = off;
27bc2bce 2676 this->section_headers_ = oshdrs;
54dc6425
ILT
2677}
2678
d491d34e
ILT
2679// Count the allocated sections.
2680
2681size_t
2682Layout::allocated_output_section_count() const
2683{
2684 size_t section_count = 0;
2685 for (Segment_list::const_iterator p = this->segment_list_.begin();
2686 p != this->segment_list_.end();
2687 ++p)
2688 section_count += (*p)->output_section_count();
2689 return section_count;
2690}
2691
dbe717ef
ILT
2692// Create the dynamic symbol table.
2693
2694void
7bf1f802 2695Layout::create_dynamic_symtab(const Input_objects* input_objects,
9b07f471 2696 Symbol_table* symtab,
14b31740
ILT
2697 Output_section **pdynstr,
2698 unsigned int* plocal_dynamic_count,
2699 std::vector<Symbol*>* pdynamic_symbols,
2700 Versions* pversions)
dbe717ef 2701{
a3ad94ed
ILT
2702 // Count all the symbols in the dynamic symbol table, and set the
2703 // dynamic symbol indexes.
dbe717ef 2704
a3ad94ed
ILT
2705 // Skip symbol 0, which is always all zeroes.
2706 unsigned int index = 1;
dbe717ef 2707
a3ad94ed
ILT
2708 // Add STT_SECTION symbols for each Output section which needs one.
2709 for (Section_list::iterator p = this->section_list_.begin();
2710 p != this->section_list_.end();
2711 ++p)
2712 {
2713 if (!(*p)->needs_dynsym_index())
2714 (*p)->set_dynsym_index(-1U);
2715 else
2716 {
2717 (*p)->set_dynsym_index(index);
2718 ++index;
2719 }
2720 }
2721
7bf1f802
ILT
2722 // Count the local symbols that need to go in the dynamic symbol table,
2723 // and set the dynamic symbol indexes.
2724 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2725 p != input_objects->relobj_end();
2726 ++p)
2727 {
2728 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2729 index = new_index;
2730 }
a3ad94ed
ILT
2731
2732 unsigned int local_symcount = index;
14b31740 2733 *plocal_dynamic_count = local_symcount;
a3ad94ed 2734
9b07f471 2735 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
35cdfc9a 2736 &this->dynpool_, pversions);
a3ad94ed
ILT
2737
2738 int symsize;
2739 unsigned int align;
8851ecca 2740 const int size = parameters->target().get_size();
a3ad94ed
ILT
2741 if (size == 32)
2742 {
2743 symsize = elfcpp::Elf_sizes<32>::sym_size;
2744 align = 4;
2745 }
2746 else if (size == 64)
2747 {
2748 symsize = elfcpp::Elf_sizes<64>::sym_size;
2749 align = 8;
2750 }
2751 else
2752 gold_unreachable();
2753
14b31740
ILT
2754 // Create the dynamic symbol table section.
2755
3802b2dd
ILT
2756 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2757 elfcpp::SHT_DYNSYM,
2758 elfcpp::SHF_ALLOC,
2759 false);
a3ad94ed 2760
27bc2bce 2761 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
7d9e3d98
ILT
2762 align,
2763 "** dynsym");
a3ad94ed
ILT
2764 dynsym->add_output_section_data(odata);
2765
2766 dynsym->set_info(local_symcount);
2767 dynsym->set_entsize(symsize);
2768 dynsym->set_addralign(align);
2769
2770 this->dynsym_section_ = dynsym;
2771
16649710 2772 Output_data_dynamic* const odyn = this->dynamic_data_;
a3ad94ed
ILT
2773 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2774 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2775
d491d34e
ILT
2776 // If there are more than SHN_LORESERVE allocated sections, we
2777 // create a .dynsym_shndx section. It is possible that we don't
2778 // need one, because it is possible that there are no dynamic
2779 // symbols in any of the sections with indexes larger than
2780 // SHN_LORESERVE. This is probably unusual, though, and at this
2781 // time we don't know the actual section indexes so it is
2782 // inconvenient to check.
2783 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2784 {
2785 Output_section* dynsym_xindex =
2786 this->choose_output_section(NULL, ".dynsym_shndx",
2787 elfcpp::SHT_SYMTAB_SHNDX,
2788 elfcpp::SHF_ALLOC,
2789 false);
2790
2791 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2792
2793 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2794
2795 dynsym_xindex->set_link_section(dynsym);
2796 dynsym_xindex->set_addralign(4);
2797 dynsym_xindex->set_entsize(4);
2798
2799 dynsym_xindex->set_after_input_sections();
2800
2801 // This tells the driver code to wait until the symbol table has
2802 // written out before writing out the postprocessing sections,
2803 // including the .dynsym_shndx section.
2804 this->any_postprocessing_sections_ = true;
2805 }
2806
14b31740
ILT
2807 // Create the dynamic string table section.
2808
3802b2dd
ILT
2809 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2810 elfcpp::SHT_STRTAB,
2811 elfcpp::SHF_ALLOC,
2812 false);
a3ad94ed
ILT
2813
2814 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2815 dynstr->add_output_section_data(strdata);
2816
16649710
ILT
2817 dynsym->set_link_section(dynstr);
2818 this->dynamic_section_->set_link_section(dynstr);
2819
a3ad94ed
ILT
2820 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2821 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2822
14b31740
ILT
2823 *pdynstr = dynstr;
2824
2825 // Create the hash tables.
2826
13670ee6
ILT
2827 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2828 || strcmp(parameters->options().hash_style(), "both") == 0)
2829 {
2830 unsigned char* phash;
2831 unsigned int hashlen;
2832 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2833 &phash, &hashlen);
2834
2835 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2836 elfcpp::SHT_HASH,
2837 elfcpp::SHF_ALLOC,
2838 false);
2839
2840 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2841 hashlen,
7d9e3d98
ILT
2842 align,
2843 "** hash");
13670ee6
ILT
2844 hashsec->add_output_section_data(hashdata);
2845
2846 hashsec->set_link_section(dynsym);
2847 hashsec->set_entsize(4);
a3ad94ed 2848
13670ee6
ILT
2849 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2850 }
2851
2852 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2853 || strcmp(parameters->options().hash_style(), "both") == 0)
2854 {
2855 unsigned char* phash;
2856 unsigned int hashlen;
2857 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2858 &phash, &hashlen);
a3ad94ed 2859
13670ee6
ILT
2860 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2861 elfcpp::SHT_GNU_HASH,
2862 elfcpp::SHF_ALLOC,
2863 false);
a3ad94ed 2864
13670ee6
ILT
2865 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2866 hashlen,
7d9e3d98
ILT
2867 align,
2868 "** hash");
13670ee6 2869 hashsec->add_output_section_data(hashdata);
a3ad94ed 2870
13670ee6
ILT
2871 hashsec->set_link_section(dynsym);
2872 hashsec->set_entsize(4);
a3ad94ed 2873
13670ee6
ILT
2874 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2875 }
dbe717ef
ILT
2876}
2877
7bf1f802
ILT
2878// Assign offsets to each local portion of the dynamic symbol table.
2879
2880void
2881Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2882{
2883 Output_section* dynsym = this->dynsym_section_;
2884 gold_assert(dynsym != NULL);
2885
2886 off_t off = dynsym->offset();
2887
2888 // Skip the dummy symbol at the start of the section.
2889 off += dynsym->entsize();
2890
2891 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2892 p != input_objects->relobj_end();
2893 ++p)
2894 {
2895 unsigned int count = (*p)->set_local_dynsym_offset(off);
2896 off += count * dynsym->entsize();
2897 }
2898}
2899
14b31740
ILT
2900// Create the version sections.
2901
2902void
9025d29d 2903Layout::create_version_sections(const Versions* versions,
46fe1623 2904 const Symbol_table* symtab,
14b31740
ILT
2905 unsigned int local_symcount,
2906 const std::vector<Symbol*>& dynamic_symbols,
2907 const Output_section* dynstr)
2908{
2909 if (!versions->any_defs() && !versions->any_needs())
2910 return;
2911
8851ecca 2912 switch (parameters->size_and_endianness())
14b31740 2913 {
193a53d9 2914#ifdef HAVE_TARGET_32_LITTLE
8851ecca 2915 case Parameters::TARGET_32_LITTLE:
7d1a9ebb
ILT
2916 this->sized_create_version_sections<32, false>(versions, symtab,
2917 local_symcount,
2918 dynamic_symbols, dynstr);
8851ecca 2919 break;
193a53d9 2920#endif
8851ecca
ILT
2921#ifdef HAVE_TARGET_32_BIG
2922 case Parameters::TARGET_32_BIG:
7d1a9ebb
ILT
2923 this->sized_create_version_sections<32, true>(versions, symtab,
2924 local_symcount,
2925 dynamic_symbols, dynstr);
8851ecca 2926 break;
193a53d9 2927#endif
193a53d9 2928#ifdef HAVE_TARGET_64_LITTLE
8851ecca 2929 case Parameters::TARGET_64_LITTLE:
7d1a9ebb
ILT
2930 this->sized_create_version_sections<64, false>(versions, symtab,
2931 local_symcount,
2932 dynamic_symbols, dynstr);
8851ecca 2933 break;
193a53d9 2934#endif
8851ecca
ILT
2935#ifdef HAVE_TARGET_64_BIG
2936 case Parameters::TARGET_64_BIG:
7d1a9ebb
ILT
2937 this->sized_create_version_sections<64, true>(versions, symtab,
2938 local_symcount,
2939 dynamic_symbols, dynstr);
8851ecca
ILT
2940 break;
2941#endif
2942 default:
2943 gold_unreachable();
14b31740 2944 }
14b31740
ILT
2945}
2946
2947// Create the version sections, sized version.
2948
2949template<int size, bool big_endian>
2950void
2951Layout::sized_create_version_sections(
2952 const Versions* versions,
46fe1623 2953 const Symbol_table* symtab,
14b31740
ILT
2954 unsigned int local_symcount,
2955 const std::vector<Symbol*>& dynamic_symbols,
7d1a9ebb 2956 const Output_section* dynstr)
14b31740 2957{
3802b2dd
ILT
2958 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2959 elfcpp::SHT_GNU_versym,
2960 elfcpp::SHF_ALLOC,
2961 false);
14b31740
ILT
2962
2963 unsigned char* vbuf;
2964 unsigned int vsize;
7d1a9ebb
ILT
2965 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2966 local_symcount,
2967 dynamic_symbols,
2968 &vbuf, &vsize);
14b31740 2969
7d9e3d98
ILT
2970 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
2971 "** versions");
14b31740
ILT
2972
2973 vsec->add_output_section_data(vdata);
2974 vsec->set_entsize(2);
2975 vsec->set_link_section(this->dynsym_section_);
2976
2977 Output_data_dynamic* const odyn = this->dynamic_data_;
2978 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2979
2980 if (versions->any_defs())
2981 {
3802b2dd
ILT
2982 Output_section* vdsec;
2983 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
2984 elfcpp::SHT_GNU_verdef,
2985 elfcpp::SHF_ALLOC,
2986 false);
14b31740
ILT
2987
2988 unsigned char* vdbuf;
2989 unsigned int vdsize;
2990 unsigned int vdentries;
7d1a9ebb
ILT
2991 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
2992 &vdsize, &vdentries);
14b31740 2993
7d9e3d98
ILT
2994 Output_section_data* vddata =
2995 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
14b31740
ILT
2996
2997 vdsec->add_output_section_data(vddata);
2998 vdsec->set_link_section(dynstr);
2999 vdsec->set_info(vdentries);
3000
3001 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3002 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3003 }
3004
3005 if (versions->any_needs())
3006 {
14b31740 3007 Output_section* vnsec;
3802b2dd
ILT
3008 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3009 elfcpp::SHT_GNU_verneed,
3010 elfcpp::SHF_ALLOC,
3011 false);
14b31740
ILT
3012
3013 unsigned char* vnbuf;
3014 unsigned int vnsize;
3015 unsigned int vnentries;
7d1a9ebb
ILT
3016 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3017 &vnbuf, &vnsize,
3018 &vnentries);
14b31740 3019
7d9e3d98
ILT
3020 Output_section_data* vndata =
3021 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
14b31740
ILT
3022
3023 vnsec->add_output_section_data(vndata);
3024 vnsec->set_link_section(dynstr);
3025 vnsec->set_info(vnentries);
3026
3027 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3028 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3029 }
3030}
3031
dbe717ef
ILT
3032// Create the .interp section and PT_INTERP segment.
3033
3034void
3035Layout::create_interp(const Target* target)
3036{
e55bde5e 3037 const char* interp = parameters->options().dynamic_linker();
dbe717ef
ILT
3038 if (interp == NULL)
3039 {
3040 interp = target->dynamic_linker();
a3ad94ed 3041 gold_assert(interp != NULL);
dbe717ef
ILT
3042 }
3043
3044 size_t len = strlen(interp) + 1;
3045
3046 Output_section_data* odata = new Output_data_const(interp, len, 1);
3047
3802b2dd
ILT
3048 Output_section* osec = this->choose_output_section(NULL, ".interp",
3049 elfcpp::SHT_PROGBITS,
3050 elfcpp::SHF_ALLOC,
3051 false);
dbe717ef
ILT
3052 osec->add_output_section_data(odata);
3053
1c4f3631
ILT
3054 if (!this->script_options_->saw_phdrs_clause())
3055 {
3056 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3057 elfcpp::PF_R);
01676dcd 3058 oseg->add_output_section(osec, elfcpp::PF_R);
1c4f3631 3059 }
dbe717ef
ILT
3060}
3061
a3ad94ed
ILT
3062// Finish the .dynamic section and PT_DYNAMIC segment.
3063
3064void
3065Layout::finish_dynamic_section(const Input_objects* input_objects,
16649710 3066 const Symbol_table* symtab)
a3ad94ed 3067{
1c4f3631
ILT
3068 if (!this->script_options_->saw_phdrs_clause())
3069 {
3070 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3071 (elfcpp::PF_R
3072 | elfcpp::PF_W));
01676dcd
ILT
3073 oseg->add_output_section(this->dynamic_section_,
3074 elfcpp::PF_R | elfcpp::PF_W);
1c4f3631 3075 }
a3ad94ed 3076
16649710
ILT
3077 Output_data_dynamic* const odyn = this->dynamic_data_;
3078
a3ad94ed
ILT
3079 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3080 p != input_objects->dynobj_end();
3081 ++p)
3082 {
3083 // FIXME: Handle --as-needed.
3084 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3085 }
3086
8851ecca 3087 if (parameters->options().shared())
fced7afd 3088 {
e55bde5e 3089 const char* soname = parameters->options().soname();
fced7afd
ILT
3090 if (soname != NULL)
3091 odyn->add_string(elfcpp::DT_SONAME, soname);
3092 }
3093
a3ad94ed
ILT
3094 // FIXME: Support --init and --fini.
3095 Symbol* sym = symtab->lookup("_init");
14b31740 3096 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
3097 odyn->add_symbol(elfcpp::DT_INIT, sym);
3098
3099 sym = symtab->lookup("_fini");
14b31740 3100 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
3101 odyn->add_symbol(elfcpp::DT_FINI, sym);
3102
3103 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
41f542e7
ILT
3104
3105 // Add a DT_RPATH entry if needed.
e55bde5e 3106 const General_options::Dir_list& rpath(parameters->options().rpath());
41f542e7
ILT
3107 if (!rpath.empty())
3108 {
3109 std::string rpath_val;
3110 for (General_options::Dir_list::const_iterator p = rpath.begin();
3111 p != rpath.end();
3112 ++p)
3113 {
3114 if (rpath_val.empty())
ad2d6943 3115 rpath_val = p->name();
41f542e7
ILT
3116 else
3117 {
3118 // Eliminate duplicates.
3119 General_options::Dir_list::const_iterator q;
3120 for (q = rpath.begin(); q != p; ++q)
ad2d6943 3121 if (q->name() == p->name())
41f542e7
ILT
3122 break;
3123 if (q == p)
3124 {
3125 rpath_val += ':';
ad2d6943 3126 rpath_val += p->name();
41f542e7
ILT
3127 }
3128 }
3129 }
3130
3131 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
7c414435
DM
3132 if (parameters->options().enable_new_dtags())
3133 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
41f542e7 3134 }
4f4c5f80
ILT
3135
3136 // Look for text segments that have dynamic relocations.
3137 bool have_textrel = false;
4e8fe71f 3138 if (!this->script_options_->saw_sections_clause())
4f4c5f80 3139 {
4e8fe71f
ILT
3140 for (Segment_list::const_iterator p = this->segment_list_.begin();
3141 p != this->segment_list_.end();
3142 ++p)
3143 {
3144 if (((*p)->flags() & elfcpp::PF_W) == 0
3145 && (*p)->dynamic_reloc_count() > 0)
3146 {
3147 have_textrel = true;
3148 break;
3149 }
3150 }
3151 }
3152 else
3153 {
3154 // We don't know the section -> segment mapping, so we are
3155 // conservative and just look for readonly sections with
3156 // relocations. If those sections wind up in writable segments,
3157 // then we have created an unnecessary DT_TEXTREL entry.
3158 for (Section_list::const_iterator p = this->section_list_.begin();
3159 p != this->section_list_.end();
3160 ++p)
3161 {
3162 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3163 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3164 && ((*p)->dynamic_reloc_count() > 0))
3165 {
3166 have_textrel = true;
3167 break;
3168 }
3169 }
4f4c5f80
ILT
3170 }
3171
3172 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3173 // post-link tools can easily modify these flags if desired.
3174 unsigned int flags = 0;
3175 if (have_textrel)
6a41d30b
ILT
3176 {
3177 // Add a DT_TEXTREL for compatibility with older loaders.
3178 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3179 flags |= elfcpp::DF_TEXTREL;
3180 }
8851ecca 3181 if (parameters->options().shared() && this->has_static_tls())
535890bb 3182 flags |= elfcpp::DF_STATIC_TLS;
7be8330a
CD
3183 if (parameters->options().origin())
3184 flags |= elfcpp::DF_ORIGIN;
e1c74d60
ILT
3185 if (parameters->options().now())
3186 flags |= elfcpp::DF_BIND_NOW;
4f4c5f80 3187 odyn->add_constant(elfcpp::DT_FLAGS, flags);
7c414435
DM
3188
3189 flags = 0;
3190 if (parameters->options().initfirst())
3191 flags |= elfcpp::DF_1_INITFIRST;
3192 if (parameters->options().interpose())
3193 flags |= elfcpp::DF_1_INTERPOSE;
3194 if (parameters->options().loadfltr())
3195 flags |= elfcpp::DF_1_LOADFLTR;
3196 if (parameters->options().nodefaultlib())
3197 flags |= elfcpp::DF_1_NODEFLIB;
3198 if (parameters->options().nodelete())
3199 flags |= elfcpp::DF_1_NODELETE;
3200 if (parameters->options().nodlopen())
3201 flags |= elfcpp::DF_1_NOOPEN;
3202 if (parameters->options().nodump())
3203 flags |= elfcpp::DF_1_NODUMP;
3204 if (!parameters->options().shared())
3205 flags &= ~(elfcpp::DF_1_INITFIRST
3206 | elfcpp::DF_1_NODELETE
3207 | elfcpp::DF_1_NOOPEN);
7be8330a
CD
3208 if (parameters->options().origin())
3209 flags |= elfcpp::DF_1_ORIGIN;
e1c74d60
ILT
3210 if (parameters->options().now())
3211 flags |= elfcpp::DF_1_NOW;
7c414435
DM
3212 if (flags)
3213 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
a3ad94ed
ILT
3214}
3215
dff16297
ILT
3216// The mapping of input section name prefixes to output section names.
3217// In some cases one prefix is itself a prefix of another prefix; in
3218// such a case the longer prefix must come first. These prefixes are
3219// based on the GNU linker default ELF linker script.
a2fb1b05 3220
ead1e424 3221#define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
dff16297 3222const Layout::Section_name_mapping Layout::section_name_mapping[] =
a2fb1b05 3223{
dff16297
ILT
3224 MAPPING_INIT(".text.", ".text"),
3225 MAPPING_INIT(".ctors.", ".ctors"),
3226 MAPPING_INIT(".dtors.", ".dtors"),
3227 MAPPING_INIT(".rodata.", ".rodata"),
3228 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3229 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3230 MAPPING_INIT(".data.", ".data"),
3231 MAPPING_INIT(".bss.", ".bss"),
3232 MAPPING_INIT(".tdata.", ".tdata"),
3233 MAPPING_INIT(".tbss.", ".tbss"),
3234 MAPPING_INIT(".init_array.", ".init_array"),
3235 MAPPING_INIT(".fini_array.", ".fini_array"),
3236 MAPPING_INIT(".sdata.", ".sdata"),
3237 MAPPING_INIT(".sbss.", ".sbss"),
3238 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3239 // differently depending on whether it is creating a shared library.
3240 MAPPING_INIT(".sdata2.", ".sdata"),
3241 MAPPING_INIT(".sbss2.", ".sbss"),
3242 MAPPING_INIT(".lrodata.", ".lrodata"),
3243 MAPPING_INIT(".ldata.", ".ldata"),
3244 MAPPING_INIT(".lbss.", ".lbss"),
3245 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3246 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3247 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3248 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3249 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3250 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3251 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3252 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3253 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3254 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3255 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3256 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3257 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3258 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3259 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3260 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3261 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
1dcd334d
DK
3262 MAPPING_INIT(".ARM.extab.", ".ARM.extab"),
3263 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3264 MAPPING_INIT(".ARM.exidx.", ".ARM.exidx"),
3265 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
a2fb1b05
ILT
3266};
3267#undef MAPPING_INIT
3268
dff16297
ILT
3269const int Layout::section_name_mapping_count =
3270 (sizeof(Layout::section_name_mapping)
3271 / sizeof(Layout::section_name_mapping[0]));
a2fb1b05 3272
ead1e424
ILT
3273// Choose the output section name to use given an input section name.
3274// Set *PLEN to the length of the name. *PLEN is initialized to the
3275// length of NAME.
3276
3277const char*
3278Layout::output_section_name(const char* name, size_t* plen)
3279{
af4a8a83
ILT
3280 // gcc 4.3 generates the following sorts of section names when it
3281 // needs a section name specific to a function:
3282 // .text.FN
3283 // .rodata.FN
3284 // .sdata2.FN
3285 // .data.FN
3286 // .data.rel.FN
3287 // .data.rel.local.FN
3288 // .data.rel.ro.FN
3289 // .data.rel.ro.local.FN
3290 // .sdata.FN
3291 // .bss.FN
3292 // .sbss.FN
3293 // .tdata.FN
3294 // .tbss.FN
3295
3296 // The GNU linker maps all of those to the part before the .FN,
3297 // except that .data.rel.local.FN is mapped to .data, and
3298 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3299 // beginning with .data.rel.ro.local are grouped together.
3300
3301 // For an anonymous namespace, the string FN can contain a '.'.
3302
3303 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3304 // GNU linker maps to .rodata.
3305
dff16297
ILT
3306 // The .data.rel.ro sections are used with -z relro. The sections
3307 // are recognized by name. We use the same names that the GNU
3308 // linker does for these sections.
af4a8a83 3309
dff16297
ILT
3310 // It is hard to handle this in a principled way, so we don't even
3311 // try. We use a table of mappings. If the input section name is
3312 // not found in the table, we simply use it as the output section
3313 // name.
af4a8a83 3314
dff16297
ILT
3315 const Section_name_mapping* psnm = section_name_mapping;
3316 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
ead1e424 3317 {
dff16297
ILT
3318 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3319 {
3320 *plen = psnm->tolen;
3321 return psnm->to;
3322 }
ead1e424
ILT
3323 }
3324
ead1e424
ILT
3325 return name;
3326}
3327
8a4c0b0d
ILT
3328// Check if a comdat group or .gnu.linkonce section with the given
3329// NAME is selected for the link. If there is already a section,
1ef4d87f
ILT
3330// *KEPT_SECTION is set to point to the existing section and the
3331// function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3332// IS_GROUP_NAME are recorded for this NAME in the layout object,
3333// *KEPT_SECTION is set to the internal copy and the function returns
3334// true.
a2fb1b05
ILT
3335
3336bool
e55bde5e 3337Layout::find_or_add_kept_section(const std::string& name,
1ef4d87f
ILT
3338 Relobj* object,
3339 unsigned int shndx,
3340 bool is_comdat,
3341 bool is_group_name,
8a4c0b0d 3342 Kept_section** kept_section)
a2fb1b05 3343{
e55bde5e
ILT
3344 // It's normal to see a couple of entries here, for the x86 thunk
3345 // sections. If we see more than a few, we're linking a C++
3346 // program, and we resize to get more space to minimize rehashing.
3347 if (this->signatures_.size() > 4
3348 && !this->resized_signatures_)
3349 {
3350 reserve_unordered_map(&this->signatures_,
3351 this->number_of_input_files_ * 64);
3352 this->resized_signatures_ = true;
3353 }
3354
1ef4d87f
ILT
3355 Kept_section candidate;
3356 std::pair<Signatures::iterator, bool> ins =
3357 this->signatures_.insert(std::make_pair(name, candidate));
a2fb1b05 3358
1ef4d87f 3359 if (kept_section != NULL)
8a4c0b0d 3360 *kept_section = &ins.first->second;
a2fb1b05
ILT
3361 if (ins.second)
3362 {
3363 // This is the first time we've seen this signature.
1ef4d87f
ILT
3364 ins.first->second.set_object(object);
3365 ins.first->second.set_shndx(shndx);
3366 if (is_comdat)
3367 ins.first->second.set_is_comdat();
3368 if (is_group_name)
3369 ins.first->second.set_is_group_name();
a2fb1b05
ILT
3370 return true;
3371 }
3372
1ef4d87f
ILT
3373 // We have already seen this signature.
3374
3375 if (ins.first->second.is_group_name())
a2fb1b05
ILT
3376 {
3377 // We've already seen a real section group with this signature.
1ef4d87f
ILT
3378 // If the kept group is from a plugin object, and we're in the
3379 // replacement phase, accept the new one as a replacement.
3380 if (ins.first->second.object() == NULL
2756a258
CC
3381 && parameters->options().plugins()->in_replacement_phase())
3382 {
1ef4d87f
ILT
3383 ins.first->second.set_object(object);
3384 ins.first->second.set_shndx(shndx);
2756a258
CC
3385 return true;
3386 }
a2fb1b05
ILT
3387 return false;
3388 }
1ef4d87f 3389 else if (is_group_name)
a2fb1b05
ILT
3390 {
3391 // This is a real section group, and we've already seen a
a0fa0c07 3392 // linkonce section with this signature. Record that we've seen
a2fb1b05 3393 // a section group, and don't include this section group.
1ef4d87f 3394 ins.first->second.set_is_group_name();
a2fb1b05
ILT
3395 return false;
3396 }
3397 else
3398 {
3399 // We've already seen a linkonce section and this is a linkonce
3400 // section. These don't block each other--this may be the same
3401 // symbol name with different section types.
3402 return true;
3403 }
3404}
3405
a445fddf
ILT
3406// Store the allocated sections into the section list.
3407
3408void
3409Layout::get_allocated_sections(Section_list* section_list) const
3410{
3411 for (Section_list::const_iterator p = this->section_list_.begin();
3412 p != this->section_list_.end();
3413 ++p)
3414 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3415 section_list->push_back(*p);
3416}
3417
3418// Create an output segment.
3419
3420Output_segment*
3421Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3422{
8851ecca 3423 gold_assert(!parameters->options().relocatable());
a445fddf
ILT
3424 Output_segment* oseg = new Output_segment(type, flags);
3425 this->segment_list_.push_back(oseg);
2d924fd9
ILT
3426
3427 if (type == elfcpp::PT_TLS)
3428 this->tls_segment_ = oseg;
3429 else if (type == elfcpp::PT_GNU_RELRO)
3430 this->relro_segment_ = oseg;
3431
a445fddf
ILT
3432 return oseg;
3433}
3434
730cdc88
ILT
3435// Write out the Output_sections. Most won't have anything to write,
3436// since most of the data will come from input sections which are
3437// handled elsewhere. But some Output_sections do have Output_data.
3438
3439void
3440Layout::write_output_sections(Output_file* of) const
3441{
3442 for (Section_list::const_iterator p = this->section_list_.begin();
3443 p != this->section_list_.end();
3444 ++p)
3445 {
3446 if (!(*p)->after_input_sections())
3447 (*p)->write(of);
3448 }
3449}
3450
61ba1cf9
ILT
3451// Write out data not associated with a section or the symbol table.
3452
3453void
9025d29d 3454Layout::write_data(const Symbol_table* symtab, Output_file* of) const
61ba1cf9 3455{
8851ecca 3456 if (!parameters->options().strip_all())
a3ad94ed 3457 {
9e2dcb77
ILT
3458 const Output_section* symtab_section = this->symtab_section_;
3459 for (Section_list::const_iterator p = this->section_list_.begin();
3460 p != this->section_list_.end();
3461 ++p)
a3ad94ed 3462 {
9e2dcb77
ILT
3463 if ((*p)->needs_symtab_index())
3464 {
3465 gold_assert(symtab_section != NULL);
3466 unsigned int index = (*p)->symtab_index();
3467 gold_assert(index > 0 && index != -1U);
3468 off_t off = (symtab_section->offset()
3469 + index * symtab_section->entsize());
d491d34e 3470 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
9e2dcb77 3471 }
a3ad94ed
ILT
3472 }
3473 }
3474
3475 const Output_section* dynsym_section = this->dynsym_section_;
3476 for (Section_list::const_iterator p = this->section_list_.begin();
3477 p != this->section_list_.end();
3478 ++p)
3479 {
3480 if ((*p)->needs_dynsym_index())
3481 {
3482 gold_assert(dynsym_section != NULL);
3483 unsigned int index = (*p)->dynsym_index();
3484 gold_assert(index > 0 && index != -1U);
3485 off_t off = (dynsym_section->offset()
3486 + index * dynsym_section->entsize());
d491d34e 3487 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
a3ad94ed
ILT
3488 }
3489 }
3490
a3ad94ed 3491 // Write out the Output_data which are not in an Output_section.
61ba1cf9
ILT
3492 for (Data_list::const_iterator p = this->special_output_list_.begin();
3493 p != this->special_output_list_.end();
3494 ++p)
3495 (*p)->write(of);
3496}
3497
730cdc88
ILT
3498// Write out the Output_sections which can only be written after the
3499// input sections are complete.
3500
3501void
27bc2bce 3502Layout::write_sections_after_input_sections(Output_file* of)
730cdc88 3503{
27bc2bce 3504 // Determine the final section offsets, and thus the final output
9a0910c3
ILT
3505 // file size. Note we finalize the .shstrab last, to allow the
3506 // after_input_section sections to modify their section-names before
3507 // writing.
17a1d0a9 3508 if (this->any_postprocessing_sections_)
27bc2bce 3509 {
17a1d0a9
ILT
3510 off_t off = this->output_file_size_;
3511 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
8a4c0b0d 3512
17a1d0a9
ILT
3513 // Now that we've finalized the names, we can finalize the shstrab.
3514 off =
3515 this->set_section_offsets(off,
3516 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3517
3518 if (off > this->output_file_size_)
3519 {
3520 of->resize(off);
3521 this->output_file_size_ = off;
3522 }
27bc2bce
ILT
3523 }
3524
730cdc88
ILT
3525 for (Section_list::const_iterator p = this->section_list_.begin();
3526 p != this->section_list_.end();
3527 ++p)
3528 {
3529 if ((*p)->after_input_sections())
3530 (*p)->write(of);
3531 }
27bc2bce 3532
27bc2bce 3533 this->section_headers_->write(of);
730cdc88
ILT
3534}
3535
8ed814a9
ILT
3536// If the build ID requires computing a checksum, do so here, and
3537// write it out. We compute a checksum over the entire file because
3538// that is simplest.
3539
3540void
3541Layout::write_build_id(Output_file* of) const
3542{
3543 if (this->build_id_note_ == NULL)
3544 return;
3545
3546 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3547
3548 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3549 this->build_id_note_->data_size());
3550
3551 const char* style = parameters->options().build_id();
3552 if (strcmp(style, "sha1") == 0)
3553 {
3554 sha1_ctx ctx;
3555 sha1_init_ctx(&ctx);
3556 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3557 sha1_finish_ctx(&ctx, ov);
3558 }
3559 else if (strcmp(style, "md5") == 0)
3560 {
3561 md5_ctx ctx;
3562 md5_init_ctx(&ctx);
3563 md5_process_bytes(iv, this->output_file_size_, &ctx);
3564 md5_finish_ctx(&ctx, ov);
3565 }
3566 else
3567 gold_unreachable();
3568
3569 of->write_output_view(this->build_id_note_->offset(),
3570 this->build_id_note_->data_size(),
3571 ov);
3572
3573 of->free_input_view(0, this->output_file_size_, iv);
3574}
3575
516cb3d0
ILT
3576// Write out a binary file. This is called after the link is
3577// complete. IN is the temporary output file we used to generate the
3578// ELF code. We simply walk through the segments, read them from
3579// their file offset in IN, and write them to their load address in
3580// the output file. FIXME: with a bit more work, we could support
3581// S-records and/or Intel hex format here.
3582
3583void
3584Layout::write_binary(Output_file* in) const
3585{
e55bde5e 3586 gold_assert(parameters->options().oformat_enum()
bc644c6c 3587 == General_options::OBJECT_FORMAT_BINARY);
516cb3d0
ILT
3588
3589 // Get the size of the binary file.
3590 uint64_t max_load_address = 0;
3591 for (Segment_list::const_iterator p = this->segment_list_.begin();
3592 p != this->segment_list_.end();
3593 ++p)
3594 {
3595 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3596 {
3597 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3598 if (max_paddr > max_load_address)
3599 max_load_address = max_paddr;
3600 }
3601 }
3602
8851ecca 3603 Output_file out(parameters->options().output_file_name());
516cb3d0
ILT
3604 out.open(max_load_address);
3605
3606 for (Segment_list::const_iterator p = this->segment_list_.begin();
3607 p != this->segment_list_.end();
3608 ++p)
3609 {
3610 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3611 {
3612 const unsigned char* vin = in->get_input_view((*p)->offset(),
3613 (*p)->filesz());
3614 unsigned char* vout = out.get_output_view((*p)->paddr(),
3615 (*p)->filesz());
3616 memcpy(vout, vin, (*p)->filesz());
3617 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3618 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3619 }
3620 }
3621
3622 out.close();
3623}
3624
7d9e3d98
ILT
3625// Print the output sections to the map file.
3626
3627void
3628Layout::print_to_mapfile(Mapfile* mapfile) const
3629{
3630 for (Segment_list::const_iterator p = this->segment_list_.begin();
3631 p != this->segment_list_.end();
3632 ++p)
3633 (*p)->print_sections_to_mapfile(mapfile);
3634}
3635
ad8f37d1
ILT
3636// Print statistical information to stderr. This is used for --stats.
3637
3638void
3639Layout::print_stats() const
3640{
3641 this->namepool_.print_stats("section name pool");
3642 this->sympool_.print_stats("output symbol name pool");
3643 this->dynpool_.print_stats("dynamic name pool");
38c5e8b4
ILT
3644
3645 for (Section_list::const_iterator p = this->section_list_.begin();
3646 p != this->section_list_.end();
3647 ++p)
3648 (*p)->print_merge_stats();
ad8f37d1
ILT
3649}
3650
730cdc88
ILT
3651// Write_sections_task methods.
3652
3653// We can always run this task.
3654
17a1d0a9
ILT
3655Task_token*
3656Write_sections_task::is_runnable()
730cdc88 3657{
17a1d0a9 3658 return NULL;
730cdc88
ILT
3659}
3660
3661// We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3662// when finished.
3663
17a1d0a9
ILT
3664void
3665Write_sections_task::locks(Task_locker* tl)
730cdc88 3666{
17a1d0a9
ILT
3667 tl->add(this, this->output_sections_blocker_);
3668 tl->add(this, this->final_blocker_);
730cdc88
ILT
3669}
3670
3671// Run the task--write out the data.
3672
3673void
3674Write_sections_task::run(Workqueue*)
3675{
3676 this->layout_->write_output_sections(this->of_);
3677}
3678
61ba1cf9
ILT
3679// Write_data_task methods.
3680
3681// We can always run this task.
3682
17a1d0a9
ILT
3683Task_token*
3684Write_data_task::is_runnable()
61ba1cf9 3685{
17a1d0a9 3686 return NULL;
61ba1cf9
ILT
3687}
3688
3689// We need to unlock FINAL_BLOCKER when finished.
3690
17a1d0a9
ILT
3691void
3692Write_data_task::locks(Task_locker* tl)
61ba1cf9 3693{
17a1d0a9 3694 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
3695}
3696
3697// Run the task--write out the data.
3698
3699void
3700Write_data_task::run(Workqueue*)
3701{
9025d29d 3702 this->layout_->write_data(this->symtab_, this->of_);
61ba1cf9
ILT
3703}
3704
3705// Write_symbols_task methods.
3706
3707// We can always run this task.
3708
17a1d0a9
ILT
3709Task_token*
3710Write_symbols_task::is_runnable()
61ba1cf9 3711{
17a1d0a9 3712 return NULL;
61ba1cf9
ILT
3713}
3714
3715// We need to unlock FINAL_BLOCKER when finished.
3716
17a1d0a9
ILT
3717void
3718Write_symbols_task::locks(Task_locker* tl)
61ba1cf9 3719{
17a1d0a9 3720 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
3721}
3722
3723// Run the task--write out the symbols.
3724
3725void
3726Write_symbols_task::run(Workqueue*)
3727{
fd9d194f
ILT
3728 this->symtab_->write_globals(this->sympool_, this->dynpool_,
3729 this->layout_->symtab_xindex(),
d491d34e 3730 this->layout_->dynsym_xindex(), this->of_);
61ba1cf9
ILT
3731}
3732
730cdc88
ILT
3733// Write_after_input_sections_task methods.
3734
3735// We can only run this task after the input sections have completed.
3736
17a1d0a9
ILT
3737Task_token*
3738Write_after_input_sections_task::is_runnable()
730cdc88
ILT
3739{
3740 if (this->input_sections_blocker_->is_blocked())
17a1d0a9
ILT
3741 return this->input_sections_blocker_;
3742 return NULL;
730cdc88
ILT
3743}
3744
3745// We need to unlock FINAL_BLOCKER when finished.
3746
17a1d0a9
ILT
3747void
3748Write_after_input_sections_task::locks(Task_locker* tl)
730cdc88 3749{
17a1d0a9 3750 tl->add(this, this->final_blocker_);
730cdc88
ILT
3751}
3752
3753// Run the task.
3754
3755void
3756Write_after_input_sections_task::run(Workqueue*)
3757{
3758 this->layout_->write_sections_after_input_sections(this->of_);
3759}
3760
92e059d8 3761// Close_task_runner methods.
61ba1cf9
ILT
3762
3763// Run the task--close the file.
3764
3765void
17a1d0a9 3766Close_task_runner::run(Workqueue*, const Task*)
61ba1cf9 3767{
8ed814a9
ILT
3768 // If we need to compute a checksum for the BUILD if, we do so here.
3769 this->layout_->write_build_id(this->of_);
3770
516cb3d0 3771 // If we've been asked to create a binary file, we do so here.
7cc619c3 3772 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
516cb3d0
ILT
3773 this->layout_->write_binary(this->of_);
3774
61ba1cf9
ILT
3775 this->of_->close();
3776}
3777
a2fb1b05
ILT
3778// Instantiate the templates we need. We could use the configure
3779// script to restrict this to only the ones for implemented targets.
3780
193a53d9 3781#ifdef HAVE_TARGET_32_LITTLE
a2fb1b05
ILT
3782template
3783Output_section*
730cdc88
ILT
3784Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3785 const char* name,
3786 const elfcpp::Shdr<32, false>& shdr,
3787 unsigned int, unsigned int, off_t*);
193a53d9 3788#endif
a2fb1b05 3789
193a53d9 3790#ifdef HAVE_TARGET_32_BIG
a2fb1b05
ILT
3791template
3792Output_section*
730cdc88
ILT
3793Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3794 const char* name,
3795 const elfcpp::Shdr<32, true>& shdr,
3796 unsigned int, unsigned int, off_t*);
193a53d9 3797#endif
a2fb1b05 3798
193a53d9 3799#ifdef HAVE_TARGET_64_LITTLE
a2fb1b05
ILT
3800template
3801Output_section*
730cdc88
ILT
3802Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3803 const char* name,
3804 const elfcpp::Shdr<64, false>& shdr,
3805 unsigned int, unsigned int, off_t*);
193a53d9 3806#endif
a2fb1b05 3807
193a53d9 3808#ifdef HAVE_TARGET_64_BIG
a2fb1b05
ILT
3809template
3810Output_section*
730cdc88
ILT
3811Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3812 const char* name,
3813 const elfcpp::Shdr<64, true>& shdr,
3814 unsigned int, unsigned int, off_t*);
193a53d9 3815#endif
a2fb1b05 3816
6a74a719
ILT
3817#ifdef HAVE_TARGET_32_LITTLE
3818template
3819Output_section*
3820Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3821 unsigned int reloc_shndx,
3822 const elfcpp::Shdr<32, false>& shdr,
3823 Output_section* data_section,
3824 Relocatable_relocs* rr);
3825#endif
3826
3827#ifdef HAVE_TARGET_32_BIG
3828template
3829Output_section*
3830Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3831 unsigned int reloc_shndx,
3832 const elfcpp::Shdr<32, true>& shdr,
3833 Output_section* data_section,
3834 Relocatable_relocs* rr);
3835#endif
3836
3837#ifdef HAVE_TARGET_64_LITTLE
3838template
3839Output_section*
3840Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3841 unsigned int reloc_shndx,
3842 const elfcpp::Shdr<64, false>& shdr,
3843 Output_section* data_section,
3844 Relocatable_relocs* rr);
3845#endif
3846
3847#ifdef HAVE_TARGET_64_BIG
3848template
3849Output_section*
3850Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3851 unsigned int reloc_shndx,
3852 const elfcpp::Shdr<64, true>& shdr,
3853 Output_section* data_section,
3854 Relocatable_relocs* rr);
3855#endif
3856
3857#ifdef HAVE_TARGET_32_LITTLE
3858template
3859void
3860Layout::layout_group<32, false>(Symbol_table* symtab,
3861 Sized_relobj<32, false>* object,
3862 unsigned int,
3863 const char* group_section_name,
3864 const char* signature,
3865 const elfcpp::Shdr<32, false>& shdr,
8825ac63
ILT
3866 elfcpp::Elf_Word flags,
3867 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3868#endif
3869
3870#ifdef HAVE_TARGET_32_BIG
3871template
3872void
3873Layout::layout_group<32, true>(Symbol_table* symtab,
3874 Sized_relobj<32, true>* object,
3875 unsigned int,
3876 const char* group_section_name,
3877 const char* signature,
3878 const elfcpp::Shdr<32, true>& shdr,
8825ac63
ILT
3879 elfcpp::Elf_Word flags,
3880 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3881#endif
3882
3883#ifdef HAVE_TARGET_64_LITTLE
3884template
3885void
3886Layout::layout_group<64, false>(Symbol_table* symtab,
3887 Sized_relobj<64, false>* object,
3888 unsigned int,
3889 const char* group_section_name,
3890 const char* signature,
3891 const elfcpp::Shdr<64, false>& shdr,
8825ac63
ILT
3892 elfcpp::Elf_Word flags,
3893 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3894#endif
3895
3896#ifdef HAVE_TARGET_64_BIG
3897template
3898void
3899Layout::layout_group<64, true>(Symbol_table* symtab,
3900 Sized_relobj<64, true>* object,
3901 unsigned int,
3902 const char* group_section_name,
3903 const char* signature,
3904 const elfcpp::Shdr<64, true>& shdr,
8825ac63
ILT
3905 elfcpp::Elf_Word flags,
3906 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3907#endif
3908
730cdc88
ILT
3909#ifdef HAVE_TARGET_32_LITTLE
3910template
3911Output_section*
3912Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3913 const unsigned char* symbols,
3914 off_t symbols_size,
3915 const unsigned char* symbol_names,
3916 off_t symbol_names_size,
3917 unsigned int shndx,
3918 const elfcpp::Shdr<32, false>& shdr,
3919 unsigned int reloc_shndx,
3920 unsigned int reloc_type,
3921 off_t* off);
3922#endif
3923
3924#ifdef HAVE_TARGET_32_BIG
3925template
3926Output_section*
3927Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3928 const unsigned char* symbols,
3929 off_t symbols_size,
3930 const unsigned char* symbol_names,
3931 off_t symbol_names_size,
3932 unsigned int shndx,
3933 const elfcpp::Shdr<32, true>& shdr,
3934 unsigned int reloc_shndx,
3935 unsigned int reloc_type,
3936 off_t* off);
3937#endif
3938
3939#ifdef HAVE_TARGET_64_LITTLE
3940template
3941Output_section*
3942Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3943 const unsigned char* symbols,
3944 off_t symbols_size,
3945 const unsigned char* symbol_names,
3946 off_t symbol_names_size,
3947 unsigned int shndx,
3948 const elfcpp::Shdr<64, false>& shdr,
3949 unsigned int reloc_shndx,
3950 unsigned int reloc_type,
3951 off_t* off);
3952#endif
3953
3954#ifdef HAVE_TARGET_64_BIG
3955template
3956Output_section*
3957Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
3958 const unsigned char* symbols,
3959 off_t symbols_size,
3960 const unsigned char* symbol_names,
3961 off_t symbol_names_size,
3962 unsigned int shndx,
3963 const elfcpp::Shdr<64, true>& shdr,
3964 unsigned int reloc_shndx,
3965 unsigned int reloc_type,
3966 off_t* off);
3967#endif
a2fb1b05
ILT
3968
3969} // End namespace gold.
This page took 0.33494 seconds and 4 git commands to generate.