Fix ChangeLog typo.
[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
c0a62865
DK
873 {
874 // FIXME: const_cast is ugly.
875 Target* target = const_cast<Target*>(&parameters->target());
876 os = target->make_output_section(name, type, flags);
877 }
96803768 878
8a5e3e08
ILT
879 parameters->target().new_output_section(os);
880
a3ad94ed 881 this->section_list_.push_back(os);
a2fb1b05 882
2fd32231
ILT
883 // The GNU linker by default sorts some sections by priority, so we
884 // do the same. We need to know that this might happen before we
885 // attach any input sections.
886 if (!this->script_options_->saw_sections_clause()
887 && (strcmp(name, ".ctors") == 0
888 || strcmp(name, ".dtors") == 0
889 || strcmp(name, ".init_array") == 0
890 || strcmp(name, ".fini_array") == 0))
891 os->set_may_sort_attached_input_sections();
892
9f1d377b
ILT
893 // With -z relro, we have to recognize the special sections by name.
894 // There is no other way.
895 if (!this->script_options_->saw_sections_clause()
896 && parameters->options().relro()
897 && type == elfcpp::SHT_PROGBITS
898 && (flags & elfcpp::SHF_ALLOC) != 0
899 && (flags & elfcpp::SHF_WRITE) != 0)
900 {
901 if (strcmp(name, ".data.rel.ro") == 0)
902 os->set_is_relro();
903 else if (strcmp(name, ".data.rel.ro.local") == 0)
904 {
905 os->set_is_relro();
906 os->set_is_relro_local();
907 }
908 }
909
1518dc8f
ILT
910 // Check for .stab*str sections, as .stab* sections need to link to
911 // them.
912 if (type == elfcpp::SHT_STRTAB
913 && !this->have_stabstr_section_
914 && strncmp(name, ".stab", 5) == 0
915 && strcmp(name + strlen(name) - 3, "str") == 0)
916 this->have_stabstr_section_ = true;
917
154e0e9a
ILT
918 // If we have already attached the sections to segments, then we
919 // need to attach this one now. This happens for sections created
920 // directly by the linker.
921 if (this->sections_are_attached_)
922 this->attach_section_to_segment(os);
923
4e2b1697
ILT
924 return os;
925}
a445fddf 926
154e0e9a
ILT
927// Attach output sections to segments. This is called after we have
928// seen all the input sections.
929
930void
931Layout::attach_sections_to_segments()
932{
933 for (Section_list::iterator p = this->section_list_.begin();
934 p != this->section_list_.end();
935 ++p)
936 this->attach_section_to_segment(*p);
937
938 this->sections_are_attached_ = true;
939}
940
941// Attach an output section to a segment.
942
943void
944Layout::attach_section_to_segment(Output_section* os)
945{
946 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
947 this->unattached_section_list_.push_back(os);
948 else
949 this->attach_allocated_section_to_segment(os);
950}
951
4e2b1697 952// Attach an allocated output section to a segment.
1c4f3631 953
4e2b1697 954void
154e0e9a 955Layout::attach_allocated_section_to_segment(Output_section* os)
4e2b1697 956{
154e0e9a 957 elfcpp::Elf_Xword flags = os->flags();
4e2b1697 958 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
a2fb1b05 959
4e2b1697
ILT
960 if (parameters->options().relocatable())
961 return;
a2fb1b05 962
4e2b1697
ILT
963 // If we have a SECTIONS clause, we can't handle the attachment to
964 // segments until after we've seen all the sections.
965 if (this->script_options_->saw_sections_clause())
966 return;
a2fb1b05 967
4e2b1697 968 gold_assert(!this->script_options_->saw_phdrs_clause());
756ac4a8 969
4e2b1697 970 // This output section goes into a PT_LOAD segment.
a2fb1b05 971
4e2b1697 972 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
a2fb1b05 973
4e2b1697
ILT
974 // In general the only thing we really care about for PT_LOAD
975 // segments is whether or not they are writable, so that is how we
8a5e3e08
ILT
976 // search for them. Large data sections also go into their own
977 // PT_LOAD segment. People who need segments sorted on some other
4e2b1697 978 // basis will have to use a linker script.
a2fb1b05 979
4e2b1697
ILT
980 Segment_list::const_iterator p;
981 for (p = this->segment_list_.begin();
982 p != this->segment_list_.end();
983 ++p)
984 {
8a5e3e08
ILT
985 if ((*p)->type() != elfcpp::PT_LOAD)
986 continue;
987 if (!parameters->options().omagic()
988 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
989 continue;
990 // If -Tbss was specified, we need to separate the data and BSS
991 // segments.
992 if (parameters->options().user_set_Tbss())
993 {
994 if ((os->type() == elfcpp::SHT_NOBITS)
995 == (*p)->has_any_data_sections())
996 continue;
997 }
998 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
999 continue;
4e2b1697 1000
8a5e3e08
ILT
1001 (*p)->add_output_section(os, seg_flags);
1002 break;
4e2b1697 1003 }
54dc6425 1004
4e2b1697
ILT
1005 if (p == this->segment_list_.end())
1006 {
1007 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1008 seg_flags);
8a5e3e08
ILT
1009 if (os->is_large_data_section())
1010 oseg->set_is_large_data_segment();
4e2b1697 1011 oseg->add_output_section(os, seg_flags);
a2fb1b05
ILT
1012 }
1013
4e2b1697
ILT
1014 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1015 // segment.
1016 if (os->type() == elfcpp::SHT_NOTE)
1017 {
1018 // See if we already have an equivalent PT_NOTE segment.
1019 for (p = this->segment_list_.begin();
1020 p != segment_list_.end();
1021 ++p)
1022 {
1023 if ((*p)->type() == elfcpp::PT_NOTE
1024 && (((*p)->flags() & elfcpp::PF_W)
1025 == (seg_flags & elfcpp::PF_W)))
1026 {
1027 (*p)->add_output_section(os, seg_flags);
1028 break;
1029 }
1030 }
1031
1032 if (p == this->segment_list_.end())
1033 {
1034 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1035 seg_flags);
1036 oseg->add_output_section(os, seg_flags);
1037 }
1038 }
1039
1040 // If we see a loadable SHF_TLS section, we create a PT_TLS
1041 // segment. There can only be one such segment.
1042 if ((flags & elfcpp::SHF_TLS) != 0)
1043 {
1044 if (this->tls_segment_ == NULL)
2d924fd9 1045 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
4e2b1697
ILT
1046 this->tls_segment_->add_output_section(os, seg_flags);
1047 }
9f1d377b
ILT
1048
1049 // If -z relro is in effect, and we see a relro section, we create a
1050 // PT_GNU_RELRO segment. There can only be one such segment.
1051 if (os->is_relro() && parameters->options().relro())
1052 {
1053 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1054 if (this->relro_segment_ == NULL)
2d924fd9 1055 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
9f1d377b
ILT
1056 this->relro_segment_->add_output_section(os, seg_flags);
1057 }
a2fb1b05
ILT
1058}
1059
919ed24c
ILT
1060// Make an output section for a script.
1061
1062Output_section*
1063Layout::make_output_section_for_script(const char* name)
1064{
1065 name = this->namepool_.add(name, false, NULL);
1066 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1067 elfcpp::SHF_ALLOC);
1068 os->set_found_in_sections_clause();
1069 return os;
1070}
1071
3802b2dd
ILT
1072// Return the number of segments we expect to see.
1073
1074size_t
1075Layout::expected_segment_count() const
1076{
1077 size_t ret = this->segment_list_.size();
1078
1079 // If we didn't see a SECTIONS clause in a linker script, we should
1080 // already have the complete list of segments. Otherwise we ask the
1081 // SECTIONS clause how many segments it expects, and add in the ones
1082 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1083
1084 if (!this->script_options_->saw_sections_clause())
1085 return ret;
1086 else
1087 {
1088 const Script_sections* ss = this->script_options_->script_sections();
1089 return ret + ss->expected_segment_count(this);
1090 }
1091}
1092
35cdfc9a
ILT
1093// Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1094// is whether we saw a .note.GNU-stack section in the object file.
1095// GNU_STACK_FLAGS is the section flags. The flags give the
1096// protection required for stack memory. We record this in an
1097// executable as a PT_GNU_STACK segment. If an object file does not
1098// have a .note.GNU-stack segment, we must assume that it is an old
1099// object. On some targets that will force an executable stack.
1100
1101void
1102Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1103{
1104 if (!seen_gnu_stack)
1105 this->input_without_gnu_stack_note_ = true;
1106 else
1107 {
1108 this->input_with_gnu_stack_note_ = true;
1109 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1110 this->input_requires_executable_stack_ = true;
1111 }
1112}
1113
9c547ec3
ILT
1114// Create automatic note sections.
1115
1116void
1117Layout::create_notes()
1118{
1119 this->create_gold_note();
1120 this->create_executable_stack_info();
1121 this->create_build_id();
1122}
1123
a3ad94ed
ILT
1124// Create the dynamic sections which are needed before we read the
1125// relocs.
1126
1127void
9b07f471 1128Layout::create_initial_dynamic_sections(Symbol_table* symtab)
a3ad94ed 1129{
436ca963 1130 if (parameters->doing_static_link())
a3ad94ed
ILT
1131 return;
1132
3802b2dd
ILT
1133 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1134 elfcpp::SHT_DYNAMIC,
1135 (elfcpp::SHF_ALLOC
1136 | elfcpp::SHF_WRITE),
1137 false);
9f1d377b 1138 this->dynamic_section_->set_is_relro();
a3ad94ed 1139
9b07f471 1140 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
a3ad94ed
ILT
1141 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1142 elfcpp::STV_HIDDEN, 0, false, false);
16649710 1143
9025d29d 1144 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
16649710
ILT
1145
1146 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
a3ad94ed
ILT
1147}
1148
bfd58944
ILT
1149// For each output section whose name can be represented as C symbol,
1150// define __start and __stop symbols for the section. This is a GNU
1151// extension.
1152
1153void
9b07f471 1154Layout::define_section_symbols(Symbol_table* symtab)
bfd58944
ILT
1155{
1156 for (Section_list::const_iterator p = this->section_list_.begin();
1157 p != this->section_list_.end();
1158 ++p)
1159 {
1160 const char* const name = (*p)->name();
1161 if (name[strspn(name,
1162 ("0123456789"
1163 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1164 "abcdefghijklmnopqrstuvwxyz"
1165 "_"))]
1166 == '\0')
1167 {
1168 const std::string name_string(name);
1169 const std::string start_name("__start_" + name_string);
1170 const std::string stop_name("__stop_" + name_string);
1171
9b07f471 1172 symtab->define_in_output_data(start_name.c_str(),
bfd58944
ILT
1173 NULL, // version
1174 *p,
1175 0, // value
1176 0, // symsize
1177 elfcpp::STT_NOTYPE,
1178 elfcpp::STB_GLOBAL,
1179 elfcpp::STV_DEFAULT,
1180 0, // nonvis
1181 false, // offset_is_from_end
a445fddf 1182 true); // only_if_ref
bfd58944 1183
9b07f471 1184 symtab->define_in_output_data(stop_name.c_str(),
bfd58944
ILT
1185 NULL, // version
1186 *p,
1187 0, // value
1188 0, // symsize
1189 elfcpp::STT_NOTYPE,
1190 elfcpp::STB_GLOBAL,
1191 elfcpp::STV_DEFAULT,
1192 0, // nonvis
1193 true, // offset_is_from_end
a445fddf 1194 true); // only_if_ref
bfd58944
ILT
1195 }
1196 }
1197}
1198
755ab8af
ILT
1199// Define symbols for group signatures.
1200
1201void
1202Layout::define_group_signatures(Symbol_table* symtab)
1203{
1204 for (Group_signatures::iterator p = this->group_signatures_.begin();
1205 p != this->group_signatures_.end();
1206 ++p)
1207 {
1208 Symbol* sym = symtab->lookup(p->signature, NULL);
1209 if (sym != NULL)
1210 p->section->set_info_symndx(sym);
1211 else
1212 {
1213 // Force the name of the group section to the group
1214 // signature, and use the group's section symbol as the
1215 // signature symbol.
1216 if (strcmp(p->section->name(), p->signature) != 0)
1217 {
1218 const char* name = this->namepool_.add(p->signature,
1219 true, NULL);
1220 p->section->set_name(name);
1221 }
1222 p->section->set_needs_symtab_index();
1223 p->section->set_info_section_symndx(p->section);
1224 }
1225 }
1226
1227 this->group_signatures_.clear();
1228}
1229
75f65a3e
ILT
1230// Find the first read-only PT_LOAD segment, creating one if
1231// necessary.
54dc6425 1232
75f65a3e
ILT
1233Output_segment*
1234Layout::find_first_load_seg()
54dc6425 1235{
75f65a3e
ILT
1236 for (Segment_list::const_iterator p = this->segment_list_.begin();
1237 p != this->segment_list_.end();
1238 ++p)
1239 {
1240 if ((*p)->type() == elfcpp::PT_LOAD
1241 && ((*p)->flags() & elfcpp::PF_R) != 0
af6156ef
ILT
1242 && (parameters->options().omagic()
1243 || ((*p)->flags() & elfcpp::PF_W) == 0))
75f65a3e
ILT
1244 return *p;
1245 }
1246
1c4f3631
ILT
1247 gold_assert(!this->script_options_->saw_phdrs_clause());
1248
3802b2dd
ILT
1249 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1250 elfcpp::PF_R);
75f65a3e 1251 return load_seg;
54dc6425
ILT
1252}
1253
20e6d0d6
DK
1254// Save states of all current output segments. Store saved states
1255// in SEGMENT_STATES.
1256
1257void
1258Layout::save_segments(Segment_states* segment_states)
1259{
1260 for (Segment_list::const_iterator p = this->segment_list_.begin();
1261 p != this->segment_list_.end();
1262 ++p)
1263 {
1264 Output_segment* segment = *p;
1265 // Shallow copy.
1266 Output_segment* copy = new Output_segment(*segment);
1267 (*segment_states)[segment] = copy;
1268 }
1269}
1270
1271// Restore states of output segments and delete any segment not found in
1272// SEGMENT_STATES.
1273
1274void
1275Layout::restore_segments(const Segment_states* segment_states)
1276{
1277 // Go through the segment list and remove any segment added in the
1278 // relaxation loop.
1279 this->tls_segment_ = NULL;
1280 this->relro_segment_ = NULL;
1281 Segment_list::iterator list_iter = this->segment_list_.begin();
1282 while (list_iter != this->segment_list_.end())
1283 {
1284 Output_segment* segment = *list_iter;
1285 Segment_states::const_iterator states_iter =
1286 segment_states->find(segment);
1287 if (states_iter != segment_states->end())
1288 {
1289 const Output_segment* copy = states_iter->second;
1290 // Shallow copy to restore states.
1291 *segment = *copy;
1292
1293 // Also fix up TLS and RELRO segment pointers as appropriate.
1294 if (segment->type() == elfcpp::PT_TLS)
1295 this->tls_segment_ = segment;
1296 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1297 this->relro_segment_ = segment;
1298
1299 ++list_iter;
1300 }
1301 else
1302 {
1303 list_iter = this->segment_list_.erase(list_iter);
1304 // This is a segment created during section layout. It should be
1305 // safe to remove it since we should have removed all pointers to it.
1306 delete segment;
1307 }
1308 }
1309}
1310
1311// Clean up after relaxation so that sections can be laid out again.
1312
1313void
1314Layout::clean_up_after_relaxation()
1315{
1316 // Restore the segments to point state just prior to the relaxation loop.
1317 Script_sections* script_section = this->script_options_->script_sections();
1318 script_section->release_segments();
1319 this->restore_segments(this->segment_states_);
1320
1321 // Reset section addresses and file offsets
1322 for (Section_list::iterator p = this->section_list_.begin();
1323 p != this->section_list_.end();
1324 ++p)
1325 {
1326 (*p)->reset_address_and_file_offset();
1327 (*p)->restore_states();
1328 }
1329
1330 // Reset special output object address and file offsets.
1331 for (Data_list::iterator p = this->special_output_list_.begin();
1332 p != this->special_output_list_.end();
1333 ++p)
1334 (*p)->reset_address_and_file_offset();
1335
1336 // A linker script may have created some output section data objects.
1337 // They are useless now.
1338 for (Output_section_data_list::const_iterator p =
1339 this->script_output_section_data_list_.begin();
1340 p != this->script_output_section_data_list_.end();
1341 ++p)
1342 delete *p;
1343 this->script_output_section_data_list_.clear();
1344}
1345
1346// Prepare for relaxation.
1347
1348void
1349Layout::prepare_for_relaxation()
1350{
1351 // Create an relaxation debug check if in debugging mode.
1352 if (is_debugging_enabled(DEBUG_RELAXATION))
1353 this->relaxation_debug_check_ = new Relaxation_debug_check();
1354
1355 // Save segment states.
1356 this->segment_states_ = new Segment_states();
1357 this->save_segments(this->segment_states_);
1358
1359 for(Section_list::const_iterator p = this->section_list_.begin();
1360 p != this->section_list_.end();
1361 ++p)
1362 (*p)->save_states();
1363
1364 if (is_debugging_enabled(DEBUG_RELAXATION))
1365 this->relaxation_debug_check_->check_output_data_for_reset_values(
1366 this->section_list_, this->special_output_list_);
1367
1368 // Also enable recording of output section data from scripts.
1369 this->record_output_section_data_from_script_ = true;
1370}
1371
1372// Relaxation loop body: If target has no relaxation, this runs only once
1373// Otherwise, the target relaxation hook is called at the end of
1374// each iteration. If the hook returns true, it means re-layout of
1375// section is required.
1376//
1377// The number of segments created by a linking script without a PHDRS
1378// clause may be affected by section sizes and alignments. There is
1379// a remote chance that relaxation causes different number of PT_LOAD
1380// segments are created and sections are attached to different segments.
1381// Therefore, we always throw away all segments created during section
1382// layout. In order to be able to restart the section layout, we keep
1383// a copy of the segment list right before the relaxation loop and use
1384// that to restore the segments.
1385//
1386// PASS is the current relaxation pass number.
1387// SYMTAB is a symbol table.
1388// PLOAD_SEG is the address of a pointer for the load segment.
1389// PHDR_SEG is a pointer to the PHDR segment.
1390// SEGMENT_HEADERS points to the output segment header.
1391// FILE_HEADER points to the output file header.
1392// PSHNDX is the address to store the output section index.
1393
1394off_t inline
1395Layout::relaxation_loop_body(
1396 int pass,
1397 Target* target,
1398 Symbol_table* symtab,
1399 Output_segment** pload_seg,
1400 Output_segment* phdr_seg,
1401 Output_segment_headers* segment_headers,
1402 Output_file_header* file_header,
1403 unsigned int* pshndx)
1404{
1405 // If this is not the first iteration, we need to clean up after
1406 // relaxation so that we can lay out the sections again.
1407 if (pass != 0)
1408 this->clean_up_after_relaxation();
1409
1410 // If there is a SECTIONS clause, put all the input sections into
1411 // the required order.
1412 Output_segment* load_seg;
1413 if (this->script_options_->saw_sections_clause())
1414 load_seg = this->set_section_addresses_from_script(symtab);
1415 else if (parameters->options().relocatable())
1416 load_seg = NULL;
1417 else
1418 load_seg = this->find_first_load_seg();
1419
1420 if (parameters->options().oformat_enum()
1421 != General_options::OBJECT_FORMAT_ELF)
1422 load_seg = NULL;
1423
68b6574b
ILT
1424 gold_assert(phdr_seg == NULL
1425 || load_seg != NULL
1426 || this->script_options_->saw_sections_clause());
20e6d0d6
DK
1427
1428 // Lay out the segment headers.
1429 if (!parameters->options().relocatable())
1430 {
1431 gold_assert(segment_headers != NULL);
1432 if (load_seg != NULL)
1433 load_seg->add_initial_output_data(segment_headers);
1434 if (phdr_seg != NULL)
1435 phdr_seg->add_initial_output_data(segment_headers);
1436 }
1437
1438 // Lay out the file header.
1439 if (load_seg != NULL)
1440 load_seg->add_initial_output_data(file_header);
1441
1442 if (this->script_options_->saw_phdrs_clause()
1443 && !parameters->options().relocatable())
1444 {
1445 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1446 // clause in a linker script.
1447 Script_sections* ss = this->script_options_->script_sections();
1448 ss->put_headers_in_phdrs(file_header, segment_headers);
1449 }
1450
1451 // We set the output section indexes in set_segment_offsets and
1452 // set_section_indexes.
1453 *pshndx = 1;
1454
1455 // Set the file offsets of all the segments, and all the sections
1456 // they contain.
1457 off_t off;
1458 if (!parameters->options().relocatable())
1459 off = this->set_segment_offsets(target, load_seg, pshndx);
1460 else
1461 off = this->set_relocatable_section_offsets(file_header, pshndx);
1462
1463 // Verify that the dummy relaxation does not change anything.
1464 if (is_debugging_enabled(DEBUG_RELAXATION))
1465 {
1466 if (pass == 0)
1467 this->relaxation_debug_check_->read_sections(this->section_list_);
1468 else
1469 this->relaxation_debug_check_->verify_sections(this->section_list_);
1470 }
1471
1472 *pload_seg = load_seg;
1473 return off;
1474}
1475
54dc6425
ILT
1476// Finalize the layout. When this is called, we have created all the
1477// output sections and all the output segments which are based on
1478// input sections. We have several things to do, and we have to do
1479// them in the right order, so that we get the right results correctly
1480// and efficiently.
1481
1482// 1) Finalize the list of output segments and create the segment
1483// table header.
1484
1485// 2) Finalize the dynamic symbol table and associated sections.
1486
1487// 3) Determine the final file offset of all the output segments.
1488
1489// 4) Determine the final file offset of all the SHF_ALLOC output
1490// sections.
1491
75f65a3e
ILT
1492// 5) Create the symbol table sections and the section name table
1493// section.
1494
1495// 6) Finalize the symbol table: set symbol values to their final
54dc6425
ILT
1496// value and make a final determination of which symbols are going
1497// into the output symbol table.
1498
54dc6425
ILT
1499// 7) Create the section table header.
1500
1501// 8) Determine the final file offset of all the output sections which
1502// are not SHF_ALLOC, including the section table header.
1503
1504// 9) Finalize the ELF file header.
1505
75f65a3e
ILT
1506// This function returns the size of the output file.
1507
1508off_t
17a1d0a9 1509Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
8851ecca 1510 Target* target, const Task* task)
54dc6425 1511{
d5b40221 1512 target->finalize_sections(this, input_objects);
5a6f7e2d 1513
17a1d0a9 1514 this->count_local_symbols(task, input_objects);
7bf1f802 1515
1518dc8f 1516 this->link_stabs_sections();
4f211c8b 1517
3802b2dd 1518 Output_segment* phdr_seg = NULL;
8851ecca 1519 if (!parameters->options().relocatable() && !parameters->doing_static_link())
54dc6425 1520 {
dbe717ef
ILT
1521 // There was a dynamic object in the link. We need to create
1522 // some information for the dynamic linker.
1523
3802b2dd
ILT
1524 // Create the PT_PHDR segment which will hold the program
1525 // headers.
1c4f3631
ILT
1526 if (!this->script_options_->saw_phdrs_clause())
1527 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
3802b2dd 1528
14b31740
ILT
1529 // Create the dynamic symbol table, including the hash table.
1530 Output_section* dynstr;
1531 std::vector<Symbol*> dynamic_symbols;
1532 unsigned int local_dynamic_count;
a5dc0706
ILT
1533 Versions versions(*this->script_options()->version_script_info(),
1534 &this->dynpool_);
9b07f471 1535 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
14b31740
ILT
1536 &local_dynamic_count, &dynamic_symbols,
1537 &versions);
dbe717ef
ILT
1538
1539 // Create the .interp section to hold the name of the
1540 // interpreter, and put it in a PT_INTERP segment.
8851ecca 1541 if (!parameters->options().shared())
96f2030e 1542 this->create_interp(target);
a3ad94ed
ILT
1543
1544 // Finish the .dynamic section to hold the dynamic data, and put
1545 // it in a PT_DYNAMIC segment.
16649710 1546 this->finish_dynamic_section(input_objects, symtab);
14b31740
ILT
1547
1548 // We should have added everything we need to the dynamic string
1549 // table.
1550 this->dynpool_.set_string_offsets();
1551
1552 // Create the version sections. We can't do this until the
1553 // dynamic string table is complete.
46fe1623 1554 this->create_version_sections(&versions, symtab, local_dynamic_count,
14b31740 1555 dynamic_symbols, dynstr);
54dc6425 1556 }
3ce2c28e
ILT
1557
1558 if (this->incremental_inputs_)
1559 {
1560 this->incremental_inputs_->finalize();
1561 this->create_incremental_info_sections();
1562 }
54dc6425 1563
20e6d0d6
DK
1564 // Create segment headers.
1565 Output_segment_headers* segment_headers =
1566 (parameters->options().relocatable()
1567 ? NULL
1568 : new Output_segment_headers(this->segment_list_));
75f65a3e
ILT
1569
1570 // Lay out the file header.
20e6d0d6
DK
1571 Output_file_header* file_header
1572 = new Output_file_header(target, symtab, segment_headers,
1573 parameters->options().entry());
a445fddf 1574
61ba1cf9 1575 this->special_output_list_.push_back(file_header);
6a74a719
ILT
1576 if (segment_headers != NULL)
1577 this->special_output_list_.push_back(segment_headers);
75f65a3e 1578
20e6d0d6
DK
1579 // Find approriate places for orphan output sections if we are using
1580 // a linker script.
1581 if (this->script_options_->saw_sections_clause())
1582 this->place_orphan_sections_in_script();
1583
1584 Output_segment* load_seg;
1585 off_t off;
1586 unsigned int shndx;
1587 int pass = 0;
1588
1589 // Take a snapshot of the section layout as needed.
1590 if (target->may_relax())
1591 this->prepare_for_relaxation();
1592
1593 // Run the relaxation loop to lay out sections.
1594 do
1c4f3631 1595 {
20e6d0d6
DK
1596 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1597 phdr_seg, segment_headers, file_header,
1598 &shndx);
1599 pass++;
1c4f3631 1600 }
c0a62865
DK
1601 while (target->may_relax()
1602 && target->relax(pass, input_objects, symtab, this));
75f65a3e 1603
a9a60db6
ILT
1604 // Set the file offsets of all the non-data sections we've seen so
1605 // far which don't have to wait for the input sections. We need
1606 // this in order to finalize local symbols in non-allocated
1607 // sections.
1608 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1609
d491d34e
ILT
1610 // Set the section indexes of all unallocated sections seen so far,
1611 // in case any of them are somehow referenced by a symbol.
1612 shndx = this->set_section_indexes(shndx);
1613
75f65a3e 1614 // Create the symbol table sections.
d491d34e 1615 this->create_symtab_sections(input_objects, symtab, shndx, &off);
7bf1f802
ILT
1616 if (!parameters->doing_static_link())
1617 this->assign_local_dynsym_offsets(input_objects);
75f65a3e 1618
e5756efb
ILT
1619 // Process any symbol assignments from a linker script. This must
1620 // be called after the symbol table has been finalized.
1621 this->script_options_->finalize_symbols(symtab, this);
1622
75f65a3e
ILT
1623 // Create the .shstrtab section.
1624 Output_section* shstrtab_section = this->create_shstrtab();
1625
a9a60db6
ILT
1626 // Set the file offsets of the rest of the non-data sections which
1627 // don't have to wait for the input sections.
9a0910c3 1628 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
86887060 1629
d491d34e
ILT
1630 // Now that all sections have been created, set the section indexes
1631 // for any sections which haven't been done yet.
86887060 1632 shndx = this->set_section_indexes(shndx);
ead1e424 1633
75f65a3e 1634 // Create the section table header.
d491d34e 1635 this->create_shdrs(shstrtab_section, &off);
75f65a3e 1636
17a1d0a9
ILT
1637 // If there are no sections which require postprocessing, we can
1638 // handle the section names now, and avoid a resize later.
1639 if (!this->any_postprocessing_sections_)
1640 off = this->set_section_offsets(off,
1641 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1642
27bc2bce 1643 file_header->set_section_info(this->section_headers_, shstrtab_section);
75f65a3e 1644
27bc2bce
ILT
1645 // Now we know exactly where everything goes in the output file
1646 // (except for non-allocated sections which require postprocessing).
a3ad94ed 1647 Output_data::layout_complete();
75f65a3e 1648
e44fcf3b
ILT
1649 this->output_file_size_ = off;
1650
75f65a3e
ILT
1651 return off;
1652}
1653
8ed814a9 1654// Create a note header following the format defined in the ELF ABI.
ec3f783e
ILT
1655// NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1656// of the section to create, DESCSZ is the size of the descriptor.
1657// ALLOCATE is true if the section should be allocated in memory.
1658// This returns the new note section. It sets *TRAILING_PADDING to
1659// the number of trailing zero bytes required.
4f211c8b 1660
8ed814a9 1661Output_section*
ef4ab7a8
PP
1662Layout::create_note(const char* name, int note_type,
1663 const char* section_name, size_t descsz,
8ed814a9 1664 bool allocate, size_t* trailing_padding)
4f211c8b 1665{
e2305dc0
ILT
1666 // Authorities all agree that the values in a .note field should
1667 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1668 // they differ on what the alignment is for 64-bit binaries.
1669 // The GABI says unambiguously they take 8-byte alignment:
1670 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1671 // Other documentation says alignment should always be 4 bytes:
1672 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1673 // GNU ld and GNU readelf both support the latter (at least as of
1674 // version 2.16.91), and glibc always generates the latter for
1675 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1676 // here.
35cdfc9a 1677#ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
8851ecca 1678 const int size = parameters->target().get_size();
e2305dc0
ILT
1679#else
1680 const int size = 32;
1681#endif
4f211c8b
ILT
1682
1683 // The contents of the .note section.
4f211c8b
ILT
1684 size_t namesz = strlen(name) + 1;
1685 size_t aligned_namesz = align_address(namesz, size / 8);
4f211c8b 1686 size_t aligned_descsz = align_address(descsz, size / 8);
4f211c8b 1687
8ed814a9 1688 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
4f211c8b 1689
8ed814a9
ILT
1690 unsigned char* buffer = new unsigned char[notehdrsz];
1691 memset(buffer, 0, notehdrsz);
4f211c8b 1692
8851ecca 1693 bool is_big_endian = parameters->target().is_big_endian();
4f211c8b
ILT
1694
1695 if (size == 32)
1696 {
1697 if (!is_big_endian)
1698 {
1699 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1700 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1701 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1702 }
1703 else
1704 {
1705 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1706 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1707 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1708 }
1709 }
1710 else if (size == 64)
1711 {
1712 if (!is_big_endian)
1713 {
1714 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1715 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1716 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1717 }
1718 else
1719 {
1720 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1721 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1722 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1723 }
1724 }
1725 else
1726 gold_unreachable();
1727
1728 memcpy(buffer + 3 * (size / 8), name, namesz);
4f211c8b 1729
8ed814a9
ILT
1730 elfcpp::Elf_Xword flags = 0;
1731 if (allocate)
1732 flags = elfcpp::SHF_ALLOC;
ec3f783e
ILT
1733 Output_section* os = this->choose_output_section(NULL, section_name,
1734 elfcpp::SHT_NOTE,
1735 flags, false);
9c547ec3
ILT
1736 if (os == NULL)
1737 return NULL;
1738
8ed814a9 1739 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
7d9e3d98
ILT
1740 size / 8,
1741 "** note header");
8ed814a9
ILT
1742 os->add_output_section_data(posd);
1743
1744 *trailing_padding = aligned_descsz - descsz;
1745
1746 return os;
1747}
1748
1749// For an executable or shared library, create a note to record the
1750// version of gold used to create the binary.
1751
1752void
1753Layout::create_gold_note()
1754{
1755 if (parameters->options().relocatable())
1756 return;
1757
1758 std::string desc = std::string("gold ") + gold::get_version_string();
1759
1760 size_t trailing_padding;
1761 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
ef4ab7a8
PP
1762 ".note.gnu.gold-version", desc.size(),
1763 false, &trailing_padding);
9c547ec3
ILT
1764 if (os == NULL)
1765 return;
8ed814a9
ILT
1766
1767 Output_section_data* posd = new Output_data_const(desc, 4);
4f211c8b 1768 os->add_output_section_data(posd);
8ed814a9
ILT
1769
1770 if (trailing_padding > 0)
1771 {
7d9e3d98 1772 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
1773 os->add_output_section_data(posd);
1774 }
4f211c8b
ILT
1775}
1776
35cdfc9a
ILT
1777// Record whether the stack should be executable. This can be set
1778// from the command line using the -z execstack or -z noexecstack
1779// options. Otherwise, if any input file has a .note.GNU-stack
1780// section with the SHF_EXECINSTR flag set, the stack should be
1781// executable. Otherwise, if at least one input file a
1782// .note.GNU-stack section, and some input file has no .note.GNU-stack
1783// section, we use the target default for whether the stack should be
1784// executable. Otherwise, we don't generate a stack note. When
1785// generating a object file, we create a .note.GNU-stack section with
1786// the appropriate marking. When generating an executable or shared
1787// library, we create a PT_GNU_STACK segment.
1788
1789void
9c547ec3 1790Layout::create_executable_stack_info()
35cdfc9a
ILT
1791{
1792 bool is_stack_executable;
e55bde5e
ILT
1793 if (parameters->options().is_execstack_set())
1794 is_stack_executable = parameters->options().is_stack_executable();
35cdfc9a
ILT
1795 else if (!this->input_with_gnu_stack_note_)
1796 return;
1797 else
1798 {
1799 if (this->input_requires_executable_stack_)
1800 is_stack_executable = true;
1801 else if (this->input_without_gnu_stack_note_)
9c547ec3
ILT
1802 is_stack_executable =
1803 parameters->target().is_default_stack_executable();
35cdfc9a
ILT
1804 else
1805 is_stack_executable = false;
1806 }
1807
8851ecca 1808 if (parameters->options().relocatable())
35cdfc9a
ILT
1809 {
1810 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1811 elfcpp::Elf_Xword flags = 0;
1812 if (is_stack_executable)
1813 flags |= elfcpp::SHF_EXECINSTR;
1814 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1815 }
1816 else
1817 {
1c4f3631
ILT
1818 if (this->script_options_->saw_phdrs_clause())
1819 return;
35cdfc9a
ILT
1820 int flags = elfcpp::PF_R | elfcpp::PF_W;
1821 if (is_stack_executable)
1822 flags |= elfcpp::PF_X;
3802b2dd 1823 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
35cdfc9a
ILT
1824 }
1825}
1826
8ed814a9
ILT
1827// If --build-id was used, set up the build ID note.
1828
1829void
1830Layout::create_build_id()
1831{
1832 if (!parameters->options().user_set_build_id())
1833 return;
1834
1835 const char* style = parameters->options().build_id();
1836 if (strcmp(style, "none") == 0)
1837 return;
1838
1839 // Set DESCSZ to the size of the note descriptor. When possible,
1840 // set DESC to the note descriptor contents.
1841 size_t descsz;
1842 std::string desc;
1843 if (strcmp(style, "md5") == 0)
1844 descsz = 128 / 8;
1845 else if (strcmp(style, "sha1") == 0)
1846 descsz = 160 / 8;
1847 else if (strcmp(style, "uuid") == 0)
1848 {
1849 const size_t uuidsz = 128 / 8;
1850
1851 char buffer[uuidsz];
1852 memset(buffer, 0, uuidsz);
1853
2a00e4fb 1854 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
8ed814a9
ILT
1855 if (descriptor < 0)
1856 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1857 strerror(errno));
1858 else
1859 {
1860 ssize_t got = ::read(descriptor, buffer, uuidsz);
2a00e4fb 1861 release_descriptor(descriptor, true);
8ed814a9
ILT
1862 if (got < 0)
1863 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1864 else if (static_cast<size_t>(got) != uuidsz)
1865 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1866 uuidsz, got);
1867 }
1868
1869 desc.assign(buffer, uuidsz);
1870 descsz = uuidsz;
1871 }
1872 else if (strncmp(style, "0x", 2) == 0)
1873 {
1874 hex_init();
1875 const char* p = style + 2;
1876 while (*p != '\0')
1877 {
1878 if (hex_p(p[0]) && hex_p(p[1]))
1879 {
1880 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1881 desc += c;
1882 p += 2;
1883 }
1884 else if (*p == '-' || *p == ':')
1885 ++p;
1886 else
1887 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1888 style);
1889 }
1890 descsz = desc.size();
1891 }
1892 else
1893 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1894
1895 // Create the note.
1896 size_t trailing_padding;
1897 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
ef4ab7a8
PP
1898 ".note.gnu.build-id", descsz, true,
1899 &trailing_padding);
9c547ec3
ILT
1900 if (os == NULL)
1901 return;
8ed814a9
ILT
1902
1903 if (!desc.empty())
1904 {
1905 // We know the value already, so we fill it in now.
1906 gold_assert(desc.size() == descsz);
1907
1908 Output_section_data* posd = new Output_data_const(desc, 4);
1909 os->add_output_section_data(posd);
1910
1911 if (trailing_padding != 0)
1912 {
7d9e3d98 1913 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
1914 os->add_output_section_data(posd);
1915 }
1916 }
1917 else
1918 {
1919 // We need to compute a checksum after we have completed the
1920 // link.
1921 gold_assert(trailing_padding == 0);
7d9e3d98 1922 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
8ed814a9 1923 os->add_output_section_data(this->build_id_note_);
8ed814a9
ILT
1924 }
1925}
1926
1518dc8f
ILT
1927// If we have both .stabXX and .stabXXstr sections, then the sh_link
1928// field of the former should point to the latter. I'm not sure who
1929// started this, but the GNU linker does it, and some tools depend
1930// upon it.
1931
1932void
1933Layout::link_stabs_sections()
1934{
1935 if (!this->have_stabstr_section_)
1936 return;
1937
1938 for (Section_list::iterator p = this->section_list_.begin();
1939 p != this->section_list_.end();
1940 ++p)
1941 {
1942 if ((*p)->type() != elfcpp::SHT_STRTAB)
1943 continue;
1944
1945 const char* name = (*p)->name();
1946 if (strncmp(name, ".stab", 5) != 0)
1947 continue;
1948
1949 size_t len = strlen(name);
1950 if (strcmp(name + len - 3, "str") != 0)
1951 continue;
1952
1953 std::string stab_name(name, len - 3);
1954 Output_section* stab_sec;
1955 stab_sec = this->find_output_section(stab_name.c_str());
1956 if (stab_sec != NULL)
1957 stab_sec->set_link_section(*p);
1958 }
1959}
1960
3ce2c28e
ILT
1961// Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
1962// for the next run of incremental linking to check what has changed.
1963
1964void
1965Layout::create_incremental_info_sections()
1966{
1967 gold_assert(this->incremental_inputs_ != NULL);
1968
1969 // Add the .gnu_incremental_inputs section.
1970 const char *incremental_inputs_name =
1971 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
1972 Output_section* inputs_os =
1973 this->make_output_section(incremental_inputs_name,
1974 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0);
1975 Output_section_data* posd =
1976 this->incremental_inputs_->create_incremental_inputs_section_data();
1977 inputs_os->add_output_section_data(posd);
1978
1979 // Add the .gnu_incremental_strtab section.
1980 const char *incremental_strtab_name =
1981 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
1982 Output_section* strtab_os = this->make_output_section(incremental_strtab_name,
1983 elfcpp::SHT_STRTAB,
1984 0);
1985 Output_data_strtab* strtab_data =
1986 new Output_data_strtab(this->incremental_inputs_->get_stringpool());
1987 strtab_os->add_output_section_data(strtab_data);
1988
1989 inputs_os->set_link_section(strtab_data);
1990}
1991
75f65a3e
ILT
1992// Return whether SEG1 should be before SEG2 in the output file. This
1993// is based entirely on the segment type and flags. When this is
1994// called the segment addresses has normally not yet been set.
1995
1996bool
1997Layout::segment_precedes(const Output_segment* seg1,
1998 const Output_segment* seg2)
1999{
2000 elfcpp::Elf_Word type1 = seg1->type();
2001 elfcpp::Elf_Word type2 = seg2->type();
2002
2003 // The single PT_PHDR segment is required to precede any loadable
2004 // segment. We simply make it always first.
2005 if (type1 == elfcpp::PT_PHDR)
2006 {
a3ad94ed 2007 gold_assert(type2 != elfcpp::PT_PHDR);
75f65a3e
ILT
2008 return true;
2009 }
2010 if (type2 == elfcpp::PT_PHDR)
2011 return false;
2012
2013 // The single PT_INTERP segment is required to precede any loadable
2014 // segment. We simply make it always second.
2015 if (type1 == elfcpp::PT_INTERP)
2016 {
a3ad94ed 2017 gold_assert(type2 != elfcpp::PT_INTERP);
75f65a3e
ILT
2018 return true;
2019 }
2020 if (type2 == elfcpp::PT_INTERP)
2021 return false;
2022
2023 // We then put PT_LOAD segments before any other segments.
2024 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2025 return true;
2026 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2027 return false;
2028
9f1d377b
ILT
2029 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2030 // segment, because that is where the dynamic linker expects to find
2031 // it (this is just for efficiency; other positions would also work
2032 // correctly).
2033 if (type1 == elfcpp::PT_TLS
2034 && type2 != elfcpp::PT_TLS
2035 && type2 != elfcpp::PT_GNU_RELRO)
2036 return false;
2037 if (type2 == elfcpp::PT_TLS
2038 && type1 != elfcpp::PT_TLS
2039 && type1 != elfcpp::PT_GNU_RELRO)
2040 return true;
2041
2042 // We put the PT_GNU_RELRO segment last, because that is where the
2043 // dynamic linker expects to find it (as with PT_TLS, this is just
2044 // for efficiency).
2045 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
92e059d8 2046 return false;
9f1d377b 2047 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
92e059d8
ILT
2048 return true;
2049
75f65a3e
ILT
2050 const elfcpp::Elf_Word flags1 = seg1->flags();
2051 const elfcpp::Elf_Word flags2 = seg2->flags();
2052
2053 // The order of non-PT_LOAD segments is unimportant. We simply sort
2054 // by the numeric segment type and flags values. There should not
2055 // be more than one segment with the same type and flags.
2056 if (type1 != elfcpp::PT_LOAD)
2057 {
2058 if (type1 != type2)
2059 return type1 < type2;
a3ad94ed 2060 gold_assert(flags1 != flags2);
75f65a3e
ILT
2061 return flags1 < flags2;
2062 }
2063
a445fddf
ILT
2064 // If the addresses are set already, sort by load address.
2065 if (seg1->are_addresses_set())
2066 {
2067 if (!seg2->are_addresses_set())
2068 return true;
2069
2070 unsigned int section_count1 = seg1->output_section_count();
2071 unsigned int section_count2 = seg2->output_section_count();
2072 if (section_count1 == 0 && section_count2 > 0)
2073 return true;
2074 if (section_count1 > 0 && section_count2 == 0)
2075 return false;
2076
2077 uint64_t paddr1 = seg1->first_section_load_address();
2078 uint64_t paddr2 = seg2->first_section_load_address();
2079 if (paddr1 != paddr2)
2080 return paddr1 < paddr2;
2081 }
2082 else if (seg2->are_addresses_set())
2083 return false;
2084
8a5e3e08
ILT
2085 // A segment which holds large data comes after a segment which does
2086 // not hold large data.
2087 if (seg1->is_large_data_segment())
2088 {
2089 if (!seg2->is_large_data_segment())
2090 return false;
2091 }
2092 else if (seg2->is_large_data_segment())
2093 return true;
2094
2095 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2096 // segments come before writable segments. Then writable segments
2097 // with data come before writable segments without data. Then
2098 // executable segments come before non-executable segments. Then
2099 // the unlikely case of a non-readable segment comes before the
2100 // normal case of a readable segment. If there are multiple
2101 // segments with the same type and flags, we require that the
2102 // address be set, and we sort by virtual address and then physical
2103 // address.
75f65a3e
ILT
2104 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2105 return (flags1 & elfcpp::PF_W) == 0;
756ac4a8
ILT
2106 if ((flags1 & elfcpp::PF_W) != 0
2107 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2108 return seg1->has_any_data_sections();
75f65a3e
ILT
2109 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2110 return (flags1 & elfcpp::PF_X) != 0;
2111 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2112 return (flags1 & elfcpp::PF_R) == 0;
2113
a445fddf
ILT
2114 // We shouldn't get here--we shouldn't create segments which we
2115 // can't distinguish.
2116 gold_unreachable();
75f65a3e
ILT
2117}
2118
8a5e3e08
ILT
2119// Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2120
2121static off_t
2122align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2123{
2124 uint64_t unsigned_off = off;
2125 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2126 | (addr & (abi_pagesize - 1)));
2127 if (aligned_off < unsigned_off)
2128 aligned_off += abi_pagesize;
2129 return aligned_off;
2130}
2131
ead1e424
ILT
2132// Set the file offsets of all the segments, and all the sections they
2133// contain. They have all been created. LOAD_SEG must be be laid out
2134// first. Return the offset of the data to follow.
75f65a3e
ILT
2135
2136off_t
ead1e424
ILT
2137Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2138 unsigned int *pshndx)
75f65a3e
ILT
2139{
2140 // Sort them into the final order.
54dc6425
ILT
2141 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2142 Layout::Compare_segments());
2143
75f65a3e
ILT
2144 // Find the PT_LOAD segments, and set their addresses and offsets
2145 // and their section's addresses and offsets.
0c5e9c22 2146 uint64_t addr;
e55bde5e
ILT
2147 if (parameters->options().user_set_Ttext())
2148 addr = parameters->options().Ttext();
374ad285 2149 else if (parameters->options().output_is_position_independent())
a445fddf 2150 addr = 0;
0c5e9c22
ILT
2151 else
2152 addr = target->default_text_segment_address();
75f65a3e 2153 off_t off = 0;
a445fddf
ILT
2154
2155 // If LOAD_SEG is NULL, then the file header and segment headers
2156 // will not be loadable. But they still need to be at offset 0 in
2157 // the file. Set their offsets now.
2158 if (load_seg == NULL)
2159 {
2160 for (Data_list::iterator p = this->special_output_list_.begin();
2161 p != this->special_output_list_.end();
2162 ++p)
2163 {
2164 off = align_address(off, (*p)->addralign());
2165 (*p)->set_address_and_file_offset(0, off);
2166 off += (*p)->data_size();
2167 }
2168 }
2169
34810851
ILT
2170 const bool check_sections = parameters->options().check_sections();
2171 Output_segment* last_load_segment = NULL;
2172
75f65a3e
ILT
2173 bool was_readonly = false;
2174 for (Segment_list::iterator p = this->segment_list_.begin();
2175 p != this->segment_list_.end();
2176 ++p)
2177 {
2178 if ((*p)->type() == elfcpp::PT_LOAD)
2179 {
2180 if (load_seg != NULL && load_seg != *p)
a3ad94ed 2181 gold_unreachable();
75f65a3e
ILT
2182 load_seg = NULL;
2183
756ac4a8
ILT
2184 bool are_addresses_set = (*p)->are_addresses_set();
2185 if (are_addresses_set)
2186 {
2187 // When it comes to setting file offsets, we care about
2188 // the physical address.
2189 addr = (*p)->paddr();
2190 }
e55bde5e 2191 else if (parameters->options().user_set_Tdata()
756ac4a8 2192 && ((*p)->flags() & elfcpp::PF_W) != 0
e55bde5e 2193 && (!parameters->options().user_set_Tbss()
756ac4a8
ILT
2194 || (*p)->has_any_data_sections()))
2195 {
e55bde5e 2196 addr = parameters->options().Tdata();
756ac4a8
ILT
2197 are_addresses_set = true;
2198 }
e55bde5e 2199 else if (parameters->options().user_set_Tbss()
756ac4a8
ILT
2200 && ((*p)->flags() & elfcpp::PF_W) != 0
2201 && !(*p)->has_any_data_sections())
2202 {
e55bde5e 2203 addr = parameters->options().Tbss();
756ac4a8
ILT
2204 are_addresses_set = true;
2205 }
2206
75f65a3e
ILT
2207 uint64_t orig_addr = addr;
2208 uint64_t orig_off = off;
2209
a445fddf 2210 uint64_t aligned_addr = 0;
75f65a3e 2211 uint64_t abi_pagesize = target->abi_pagesize();
af6156ef 2212 uint64_t common_pagesize = target->common_pagesize();
0496d5e5 2213
af6156ef
ILT
2214 if (!parameters->options().nmagic()
2215 && !parameters->options().omagic())
2216 (*p)->set_minimum_p_align(common_pagesize);
0496d5e5 2217
8a5e3e08 2218 if (!are_addresses_set)
a445fddf
ILT
2219 {
2220 // If the last segment was readonly, and this one is
2221 // not, then skip the address forward one page,
2222 // maintaining the same position within the page. This
2223 // lets us store both segments overlapping on a single
2224 // page in the file, but the loader will put them on
2225 // different pages in memory.
2226
2227 addr = align_address(addr, (*p)->maximum_alignment());
75f65a3e 2228 aligned_addr = addr;
a445fddf
ILT
2229
2230 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2231 {
2232 if ((addr & (abi_pagesize - 1)) != 0)
2233 addr = addr + abi_pagesize;
2234 }
2235
2236 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
75f65a3e
ILT
2237 }
2238
8a5e3e08
ILT
2239 if (!parameters->options().nmagic()
2240 && !parameters->options().omagic())
2241 off = align_file_offset(off, addr, abi_pagesize);
661be1e2
ILT
2242 else if (load_seg == NULL)
2243 {
2244 // This is -N or -n with a section script which prevents
2245 // us from using a load segment. We need to ensure that
2246 // the file offset is aligned to the alignment of the
2247 // segment. This is because the linker script
2248 // implicitly assumed a zero offset. If we don't align
2249 // here, then the alignment of the sections in the
2250 // linker script may not match the alignment of the
2251 // sections in the set_section_addresses call below,
2252 // causing an error about dot moving backward.
2253 off = align_address(off, (*p)->maximum_alignment());
2254 }
8a5e3e08 2255
ead1e424 2256 unsigned int shndx_hold = *pshndx;
96a2b4e4
ILT
2257 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2258 &off, pshndx);
75f65a3e
ILT
2259
2260 // Now that we know the size of this segment, we may be able
2261 // to save a page in memory, at the cost of wasting some
2262 // file space, by instead aligning to the start of a new
2263 // page. Here we use the real machine page size rather than
2264 // the ABI mandated page size.
2265
a445fddf 2266 if (!are_addresses_set && aligned_addr != addr)
75f65a3e 2267 {
75f65a3e
ILT
2268 uint64_t first_off = (common_pagesize
2269 - (aligned_addr
2270 & (common_pagesize - 1)));
2271 uint64_t last_off = new_addr & (common_pagesize - 1);
2272 if (first_off > 0
2273 && last_off > 0
2274 && ((aligned_addr & ~ (common_pagesize - 1))
2275 != (new_addr & ~ (common_pagesize - 1)))
2276 && first_off + last_off <= common_pagesize)
2277 {
ead1e424
ILT
2278 *pshndx = shndx_hold;
2279 addr = align_address(aligned_addr, common_pagesize);
a445fddf 2280 addr = align_address(addr, (*p)->maximum_alignment());
75f65a3e 2281 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
8a5e3e08 2282 off = align_file_offset(off, addr, abi_pagesize);
96a2b4e4
ILT
2283 new_addr = (*p)->set_section_addresses(this, true, addr,
2284 &off, pshndx);
75f65a3e
ILT
2285 }
2286 }
2287
2288 addr = new_addr;
2289
2290 if (((*p)->flags() & elfcpp::PF_W) == 0)
2291 was_readonly = true;
34810851
ILT
2292
2293 // Implement --check-sections. We know that the segments
2294 // are sorted by LMA.
2295 if (check_sections && last_load_segment != NULL)
2296 {
2297 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2298 if (last_load_segment->paddr() + last_load_segment->memsz()
2299 > (*p)->paddr())
2300 {
2301 unsigned long long lb1 = last_load_segment->paddr();
2302 unsigned long long le1 = lb1 + last_load_segment->memsz();
2303 unsigned long long lb2 = (*p)->paddr();
2304 unsigned long long le2 = lb2 + (*p)->memsz();
2305 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2306 "[0x%llx -> 0x%llx]"),
2307 lb1, le1, lb2, le2);
2308 }
2309 }
2310 last_load_segment = *p;
75f65a3e
ILT
2311 }
2312 }
2313
2314 // Handle the non-PT_LOAD segments, setting their offsets from their
2315 // section's offsets.
2316 for (Segment_list::iterator p = this->segment_list_.begin();
2317 p != this->segment_list_.end();
2318 ++p)
2319 {
2320 if ((*p)->type() != elfcpp::PT_LOAD)
2321 (*p)->set_offset();
2322 }
2323
7bf1f802
ILT
2324 // Set the TLS offsets for each section in the PT_TLS segment.
2325 if (this->tls_segment_ != NULL)
2326 this->tls_segment_->set_tls_offsets();
2327
75f65a3e
ILT
2328 return off;
2329}
2330
6a74a719
ILT
2331// Set the offsets of all the allocated sections when doing a
2332// relocatable link. This does the same jobs as set_segment_offsets,
2333// only for a relocatable link.
2334
2335off_t
2336Layout::set_relocatable_section_offsets(Output_data* file_header,
2337 unsigned int *pshndx)
2338{
2339 off_t off = 0;
2340
2341 file_header->set_address_and_file_offset(0, 0);
2342 off += file_header->data_size();
2343
2344 for (Section_list::iterator p = this->section_list_.begin();
2345 p != this->section_list_.end();
2346 ++p)
2347 {
2348 // We skip unallocated sections here, except that group sections
2349 // have to come first.
2350 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2351 && (*p)->type() != elfcpp::SHT_GROUP)
2352 continue;
2353
2354 off = align_address(off, (*p)->addralign());
2355
2356 // The linker script might have set the address.
2357 if (!(*p)->is_address_valid())
2358 (*p)->set_address(0);
2359 (*p)->set_file_offset(off);
2360 (*p)->finalize_data_size();
2361 off += (*p)->data_size();
2362
2363 (*p)->set_out_shndx(*pshndx);
2364 ++*pshndx;
2365 }
2366
2367 return off;
2368}
2369
75f65a3e
ILT
2370// Set the file offset of all the sections not associated with a
2371// segment.
2372
2373off_t
9a0910c3 2374Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
75f65a3e 2375{
a3ad94ed
ILT
2376 for (Section_list::iterator p = this->unattached_section_list_.begin();
2377 p != this->unattached_section_list_.end();
75f65a3e
ILT
2378 ++p)
2379 {
27bc2bce
ILT
2380 // The symtab section is handled in create_symtab_sections.
2381 if (*p == this->symtab_section_)
61ba1cf9 2382 continue;
27bc2bce 2383
a9a60db6
ILT
2384 // If we've already set the data size, don't set it again.
2385 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2386 continue;
2387
96803768
ILT
2388 if (pass == BEFORE_INPUT_SECTIONS_PASS
2389 && (*p)->requires_postprocessing())
17a1d0a9
ILT
2390 {
2391 (*p)->create_postprocessing_buffer();
2392 this->any_postprocessing_sections_ = true;
2393 }
96803768 2394
9a0910c3
ILT
2395 if (pass == BEFORE_INPUT_SECTIONS_PASS
2396 && (*p)->after_input_sections())
2397 continue;
17a1d0a9 2398 else if (pass == POSTPROCESSING_SECTIONS_PASS
9a0910c3
ILT
2399 && (!(*p)->after_input_sections()
2400 || (*p)->type() == elfcpp::SHT_STRTAB))
2401 continue;
17a1d0a9 2402 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
9a0910c3
ILT
2403 && (!(*p)->after_input_sections()
2404 || (*p)->type() != elfcpp::SHT_STRTAB))
2405 continue;
27bc2bce 2406
ead1e424 2407 off = align_address(off, (*p)->addralign());
27bc2bce
ILT
2408 (*p)->set_file_offset(off);
2409 (*p)->finalize_data_size();
75f65a3e 2410 off += (*p)->data_size();
96803768
ILT
2411
2412 // At this point the name must be set.
17a1d0a9 2413 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
96803768 2414 this->namepool_.add((*p)->name(), false, NULL);
75f65a3e
ILT
2415 }
2416 return off;
2417}
2418
86887060
ILT
2419// Set the section indexes of all the sections not associated with a
2420// segment.
2421
2422unsigned int
2423Layout::set_section_indexes(unsigned int shndx)
2424{
2425 for (Section_list::iterator p = this->unattached_section_list_.begin();
2426 p != this->unattached_section_list_.end();
2427 ++p)
2428 {
d491d34e
ILT
2429 if (!(*p)->has_out_shndx())
2430 {
2431 (*p)->set_out_shndx(shndx);
2432 ++shndx;
2433 }
86887060
ILT
2434 }
2435 return shndx;
2436}
2437
a445fddf
ILT
2438// Set the section addresses according to the linker script. This is
2439// only called when we see a SECTIONS clause. This returns the
2440// program segment which should hold the file header and segment
2441// headers, if any. It will return NULL if they should not be in a
2442// segment.
2443
2444Output_segment*
2445Layout::set_section_addresses_from_script(Symbol_table* symtab)
20e6d0d6
DK
2446{
2447 Script_sections* ss = this->script_options_->script_sections();
2448 gold_assert(ss->saw_sections_clause());
2449 return this->script_options_->set_section_addresses(symtab, this);
2450}
2451
2452// Place the orphan sections in the linker script.
2453
2454void
2455Layout::place_orphan_sections_in_script()
a445fddf
ILT
2456{
2457 Script_sections* ss = this->script_options_->script_sections();
2458 gold_assert(ss->saw_sections_clause());
2459
2460 // Place each orphaned output section in the script.
2461 for (Section_list::iterator p = this->section_list_.begin();
2462 p != this->section_list_.end();
2463 ++p)
2464 {
2465 if (!(*p)->found_in_sections_clause())
2466 ss->place_orphan(*p);
2467 }
a445fddf
ILT
2468}
2469
7bf1f802
ILT
2470// Count the local symbols in the regular symbol table and the dynamic
2471// symbol table, and build the respective string pools.
2472
2473void
17a1d0a9
ILT
2474Layout::count_local_symbols(const Task* task,
2475 const Input_objects* input_objects)
7bf1f802 2476{
6d013333
ILT
2477 // First, figure out an upper bound on the number of symbols we'll
2478 // be inserting into each pool. This helps us create the pools with
2479 // the right size, to avoid unnecessary hashtable resizing.
2480 unsigned int symbol_count = 0;
2481 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2482 p != input_objects->relobj_end();
2483 ++p)
2484 symbol_count += (*p)->local_symbol_count();
2485
2486 // Go from "upper bound" to "estimate." We overcount for two
2487 // reasons: we double-count symbols that occur in more than one
2488 // object file, and we count symbols that are dropped from the
2489 // output. Add it all together and assume we overcount by 100%.
2490 symbol_count /= 2;
2491
2492 // We assume all symbols will go into both the sympool and dynpool.
2493 this->sympool_.reserve(symbol_count);
2494 this->dynpool_.reserve(symbol_count);
2495
7bf1f802
ILT
2496 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2497 p != input_objects->relobj_end();
2498 ++p)
2499 {
17a1d0a9 2500 Task_lock_obj<Object> tlo(task, *p);
7bf1f802
ILT
2501 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2502 }
2503}
2504
b8e6aad9
ILT
2505// Create the symbol table sections. Here we also set the final
2506// values of the symbols. At this point all the loadable sections are
d491d34e 2507// fully laid out. SHNUM is the number of sections so far.
75f65a3e
ILT
2508
2509void
9025d29d 2510Layout::create_symtab_sections(const Input_objects* input_objects,
75f65a3e 2511 Symbol_table* symtab,
d491d34e 2512 unsigned int shnum,
16649710 2513 off_t* poff)
75f65a3e 2514{
61ba1cf9
ILT
2515 int symsize;
2516 unsigned int align;
8851ecca 2517 if (parameters->target().get_size() == 32)
61ba1cf9
ILT
2518 {
2519 symsize = elfcpp::Elf_sizes<32>::sym_size;
2520 align = 4;
2521 }
8851ecca 2522 else if (parameters->target().get_size() == 64)
61ba1cf9
ILT
2523 {
2524 symsize = elfcpp::Elf_sizes<64>::sym_size;
2525 align = 8;
2526 }
2527 else
a3ad94ed 2528 gold_unreachable();
61ba1cf9
ILT
2529
2530 off_t off = *poff;
ead1e424 2531 off = align_address(off, align);
61ba1cf9
ILT
2532 off_t startoff = off;
2533
2534 // Save space for the dummy symbol at the start of the section. We
2535 // never bother to write this out--it will just be left as zero.
2536 off += symsize;
c06b7b0b 2537 unsigned int local_symbol_index = 1;
61ba1cf9 2538
a3ad94ed
ILT
2539 // Add STT_SECTION symbols for each Output section which needs one.
2540 for (Section_list::iterator p = this->section_list_.begin();
2541 p != this->section_list_.end();
2542 ++p)
2543 {
2544 if (!(*p)->needs_symtab_index())
2545 (*p)->set_symtab_index(-1U);
2546 else
2547 {
2548 (*p)->set_symtab_index(local_symbol_index);
2549 ++local_symbol_index;
2550 off += symsize;
2551 }
2552 }
2553
f6ce93d6
ILT
2554 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2555 p != input_objects->relobj_end();
75f65a3e
ILT
2556 ++p)
2557 {
c06b7b0b 2558 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
ef15dade 2559 off, symtab);
c06b7b0b
ILT
2560 off += (index - local_symbol_index) * symsize;
2561 local_symbol_index = index;
75f65a3e
ILT
2562 }
2563
c06b7b0b 2564 unsigned int local_symcount = local_symbol_index;
75aea3d0 2565 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
61ba1cf9 2566
16649710
ILT
2567 off_t dynoff;
2568 size_t dyn_global_index;
2569 size_t dyncount;
2570 if (this->dynsym_section_ == NULL)
2571 {
2572 dynoff = 0;
2573 dyn_global_index = 0;
2574 dyncount = 0;
2575 }
2576 else
2577 {
2578 dyn_global_index = this->dynsym_section_->info();
2579 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2580 dynoff = this->dynsym_section_->offset() + locsize;
2581 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
f5c3f225 2582 gold_assert(static_cast<off_t>(dyncount * symsize)
16649710
ILT
2583 == this->dynsym_section_->data_size() - locsize);
2584 }
2585
55a93433
ILT
2586 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2587 &this->sympool_, &local_symcount);
75f65a3e 2588
8851ecca 2589 if (!parameters->options().strip_all())
9e2dcb77
ILT
2590 {
2591 this->sympool_.set_string_offsets();
61ba1cf9 2592
cfd73a4e 2593 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
9e2dcb77
ILT
2594 Output_section* osymtab = this->make_output_section(symtab_name,
2595 elfcpp::SHT_SYMTAB,
2596 0);
2597 this->symtab_section_ = osymtab;
a3ad94ed 2598
27bc2bce 2599 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
7d9e3d98
ILT
2600 align,
2601 "** symtab");
9e2dcb77 2602 osymtab->add_output_section_data(pos);
61ba1cf9 2603
d491d34e
ILT
2604 // We generate a .symtab_shndx section if we have more than
2605 // SHN_LORESERVE sections. Technically it is possible that we
2606 // don't need one, because it is possible that there are no
2607 // symbols in any of sections with indexes larger than
2608 // SHN_LORESERVE. That is probably unusual, though, and it is
2609 // easier to always create one than to compute section indexes
2610 // twice (once here, once when writing out the symbols).
2611 if (shnum >= elfcpp::SHN_LORESERVE)
2612 {
2613 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2614 false, NULL);
2615 Output_section* osymtab_xindex =
2616 this->make_output_section(symtab_xindex_name,
2617 elfcpp::SHT_SYMTAB_SHNDX, 0);
2618
2619 size_t symcount = (off - startoff) / symsize;
2620 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2621
2622 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2623
2624 osymtab_xindex->set_link_section(osymtab);
2625 osymtab_xindex->set_addralign(4);
2626 osymtab_xindex->set_entsize(4);
2627
2628 osymtab_xindex->set_after_input_sections();
2629
2630 // This tells the driver code to wait until the symbol table
2631 // has written out before writing out the postprocessing
2632 // sections, including the .symtab_shndx section.
2633 this->any_postprocessing_sections_ = true;
2634 }
2635
cfd73a4e 2636 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
9e2dcb77
ILT
2637 Output_section* ostrtab = this->make_output_section(strtab_name,
2638 elfcpp::SHT_STRTAB,
2639 0);
a3ad94ed 2640
9e2dcb77
ILT
2641 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2642 ostrtab->add_output_section_data(pstr);
61ba1cf9 2643
27bc2bce
ILT
2644 osymtab->set_file_offset(startoff);
2645 osymtab->finalize_data_size();
9e2dcb77
ILT
2646 osymtab->set_link_section(ostrtab);
2647 osymtab->set_info(local_symcount);
2648 osymtab->set_entsize(symsize);
61ba1cf9 2649
9e2dcb77
ILT
2650 *poff = off;
2651 }
75f65a3e
ILT
2652}
2653
2654// Create the .shstrtab section, which holds the names of the
2655// sections. At the time this is called, we have created all the
2656// output sections except .shstrtab itself.
2657
2658Output_section*
2659Layout::create_shstrtab()
2660{
2661 // FIXME: We don't need to create a .shstrtab section if we are
2662 // stripping everything.
2663
cfd73a4e 2664 const char* name = this->namepool_.add(".shstrtab", false, NULL);
75f65a3e 2665
a3ad94ed 2666 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
75f65a3e 2667
27bc2bce
ILT
2668 // We can't write out this section until we've set all the section
2669 // names, and we don't set the names of compressed output sections
2670 // until relocations are complete.
2671 os->set_after_input_sections();
2672
a3ad94ed
ILT
2673 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2674 os->add_output_section_data(posd);
75f65a3e
ILT
2675
2676 return os;
2677}
2678
2679// Create the section headers. SIZE is 32 or 64. OFF is the file
2680// offset.
2681
27bc2bce 2682void
d491d34e 2683Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
75f65a3e
ILT
2684{
2685 Output_section_headers* oshdrs;
9025d29d 2686 oshdrs = new Output_section_headers(this,
16649710 2687 &this->segment_list_,
6a74a719 2688 &this->section_list_,
16649710 2689 &this->unattached_section_list_,
d491d34e
ILT
2690 &this->namepool_,
2691 shstrtab_section);
ead1e424 2692 off_t off = align_address(*poff, oshdrs->addralign());
27bc2bce 2693 oshdrs->set_address_and_file_offset(0, off);
61ba1cf9
ILT
2694 off += oshdrs->data_size();
2695 *poff = off;
27bc2bce 2696 this->section_headers_ = oshdrs;
54dc6425
ILT
2697}
2698
d491d34e
ILT
2699// Count the allocated sections.
2700
2701size_t
2702Layout::allocated_output_section_count() const
2703{
2704 size_t section_count = 0;
2705 for (Segment_list::const_iterator p = this->segment_list_.begin();
2706 p != this->segment_list_.end();
2707 ++p)
2708 section_count += (*p)->output_section_count();
2709 return section_count;
2710}
2711
dbe717ef
ILT
2712// Create the dynamic symbol table.
2713
2714void
7bf1f802 2715Layout::create_dynamic_symtab(const Input_objects* input_objects,
9b07f471 2716 Symbol_table* symtab,
14b31740
ILT
2717 Output_section **pdynstr,
2718 unsigned int* plocal_dynamic_count,
2719 std::vector<Symbol*>* pdynamic_symbols,
2720 Versions* pversions)
dbe717ef 2721{
a3ad94ed
ILT
2722 // Count all the symbols in the dynamic symbol table, and set the
2723 // dynamic symbol indexes.
dbe717ef 2724
a3ad94ed
ILT
2725 // Skip symbol 0, which is always all zeroes.
2726 unsigned int index = 1;
dbe717ef 2727
a3ad94ed
ILT
2728 // Add STT_SECTION symbols for each Output section which needs one.
2729 for (Section_list::iterator p = this->section_list_.begin();
2730 p != this->section_list_.end();
2731 ++p)
2732 {
2733 if (!(*p)->needs_dynsym_index())
2734 (*p)->set_dynsym_index(-1U);
2735 else
2736 {
2737 (*p)->set_dynsym_index(index);
2738 ++index;
2739 }
2740 }
2741
7bf1f802
ILT
2742 // Count the local symbols that need to go in the dynamic symbol table,
2743 // and set the dynamic symbol indexes.
2744 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2745 p != input_objects->relobj_end();
2746 ++p)
2747 {
2748 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2749 index = new_index;
2750 }
a3ad94ed
ILT
2751
2752 unsigned int local_symcount = index;
14b31740 2753 *plocal_dynamic_count = local_symcount;
a3ad94ed 2754
9b07f471 2755 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
35cdfc9a 2756 &this->dynpool_, pversions);
a3ad94ed
ILT
2757
2758 int symsize;
2759 unsigned int align;
8851ecca 2760 const int size = parameters->target().get_size();
a3ad94ed
ILT
2761 if (size == 32)
2762 {
2763 symsize = elfcpp::Elf_sizes<32>::sym_size;
2764 align = 4;
2765 }
2766 else if (size == 64)
2767 {
2768 symsize = elfcpp::Elf_sizes<64>::sym_size;
2769 align = 8;
2770 }
2771 else
2772 gold_unreachable();
2773
14b31740
ILT
2774 // Create the dynamic symbol table section.
2775
3802b2dd
ILT
2776 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2777 elfcpp::SHT_DYNSYM,
2778 elfcpp::SHF_ALLOC,
2779 false);
a3ad94ed 2780
27bc2bce 2781 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
7d9e3d98
ILT
2782 align,
2783 "** dynsym");
a3ad94ed
ILT
2784 dynsym->add_output_section_data(odata);
2785
2786 dynsym->set_info(local_symcount);
2787 dynsym->set_entsize(symsize);
2788 dynsym->set_addralign(align);
2789
2790 this->dynsym_section_ = dynsym;
2791
16649710 2792 Output_data_dynamic* const odyn = this->dynamic_data_;
a3ad94ed
ILT
2793 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2794 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2795
d491d34e
ILT
2796 // If there are more than SHN_LORESERVE allocated sections, we
2797 // create a .dynsym_shndx section. It is possible that we don't
2798 // need one, because it is possible that there are no dynamic
2799 // symbols in any of the sections with indexes larger than
2800 // SHN_LORESERVE. This is probably unusual, though, and at this
2801 // time we don't know the actual section indexes so it is
2802 // inconvenient to check.
2803 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2804 {
2805 Output_section* dynsym_xindex =
2806 this->choose_output_section(NULL, ".dynsym_shndx",
2807 elfcpp::SHT_SYMTAB_SHNDX,
2808 elfcpp::SHF_ALLOC,
2809 false);
2810
2811 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2812
2813 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2814
2815 dynsym_xindex->set_link_section(dynsym);
2816 dynsym_xindex->set_addralign(4);
2817 dynsym_xindex->set_entsize(4);
2818
2819 dynsym_xindex->set_after_input_sections();
2820
2821 // This tells the driver code to wait until the symbol table has
2822 // written out before writing out the postprocessing sections,
2823 // including the .dynsym_shndx section.
2824 this->any_postprocessing_sections_ = true;
2825 }
2826
14b31740
ILT
2827 // Create the dynamic string table section.
2828
3802b2dd
ILT
2829 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2830 elfcpp::SHT_STRTAB,
2831 elfcpp::SHF_ALLOC,
2832 false);
a3ad94ed
ILT
2833
2834 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2835 dynstr->add_output_section_data(strdata);
2836
16649710
ILT
2837 dynsym->set_link_section(dynstr);
2838 this->dynamic_section_->set_link_section(dynstr);
2839
a3ad94ed
ILT
2840 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2841 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2842
14b31740
ILT
2843 *pdynstr = dynstr;
2844
2845 // Create the hash tables.
2846
13670ee6
ILT
2847 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2848 || strcmp(parameters->options().hash_style(), "both") == 0)
2849 {
2850 unsigned char* phash;
2851 unsigned int hashlen;
2852 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2853 &phash, &hashlen);
2854
2855 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2856 elfcpp::SHT_HASH,
2857 elfcpp::SHF_ALLOC,
2858 false);
2859
2860 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2861 hashlen,
7d9e3d98
ILT
2862 align,
2863 "** hash");
13670ee6
ILT
2864 hashsec->add_output_section_data(hashdata);
2865
2866 hashsec->set_link_section(dynsym);
2867 hashsec->set_entsize(4);
a3ad94ed 2868
13670ee6
ILT
2869 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2870 }
2871
2872 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2873 || strcmp(parameters->options().hash_style(), "both") == 0)
2874 {
2875 unsigned char* phash;
2876 unsigned int hashlen;
2877 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2878 &phash, &hashlen);
a3ad94ed 2879
13670ee6
ILT
2880 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2881 elfcpp::SHT_GNU_HASH,
2882 elfcpp::SHF_ALLOC,
2883 false);
a3ad94ed 2884
13670ee6
ILT
2885 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2886 hashlen,
7d9e3d98
ILT
2887 align,
2888 "** hash");
13670ee6 2889 hashsec->add_output_section_data(hashdata);
a3ad94ed 2890
13670ee6
ILT
2891 hashsec->set_link_section(dynsym);
2892 hashsec->set_entsize(4);
a3ad94ed 2893
13670ee6
ILT
2894 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2895 }
dbe717ef
ILT
2896}
2897
7bf1f802
ILT
2898// Assign offsets to each local portion of the dynamic symbol table.
2899
2900void
2901Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2902{
2903 Output_section* dynsym = this->dynsym_section_;
2904 gold_assert(dynsym != NULL);
2905
2906 off_t off = dynsym->offset();
2907
2908 // Skip the dummy symbol at the start of the section.
2909 off += dynsym->entsize();
2910
2911 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2912 p != input_objects->relobj_end();
2913 ++p)
2914 {
2915 unsigned int count = (*p)->set_local_dynsym_offset(off);
2916 off += count * dynsym->entsize();
2917 }
2918}
2919
14b31740
ILT
2920// Create the version sections.
2921
2922void
9025d29d 2923Layout::create_version_sections(const Versions* versions,
46fe1623 2924 const Symbol_table* symtab,
14b31740
ILT
2925 unsigned int local_symcount,
2926 const std::vector<Symbol*>& dynamic_symbols,
2927 const Output_section* dynstr)
2928{
2929 if (!versions->any_defs() && !versions->any_needs())
2930 return;
2931
8851ecca 2932 switch (parameters->size_and_endianness())
14b31740 2933 {
193a53d9 2934#ifdef HAVE_TARGET_32_LITTLE
8851ecca 2935 case Parameters::TARGET_32_LITTLE:
7d1a9ebb
ILT
2936 this->sized_create_version_sections<32, false>(versions, symtab,
2937 local_symcount,
2938 dynamic_symbols, dynstr);
8851ecca 2939 break;
193a53d9 2940#endif
8851ecca
ILT
2941#ifdef HAVE_TARGET_32_BIG
2942 case Parameters::TARGET_32_BIG:
7d1a9ebb
ILT
2943 this->sized_create_version_sections<32, true>(versions, symtab,
2944 local_symcount,
2945 dynamic_symbols, dynstr);
8851ecca 2946 break;
193a53d9 2947#endif
193a53d9 2948#ifdef HAVE_TARGET_64_LITTLE
8851ecca 2949 case Parameters::TARGET_64_LITTLE:
7d1a9ebb
ILT
2950 this->sized_create_version_sections<64, false>(versions, symtab,
2951 local_symcount,
2952 dynamic_symbols, dynstr);
8851ecca 2953 break;
193a53d9 2954#endif
8851ecca
ILT
2955#ifdef HAVE_TARGET_64_BIG
2956 case Parameters::TARGET_64_BIG:
7d1a9ebb
ILT
2957 this->sized_create_version_sections<64, true>(versions, symtab,
2958 local_symcount,
2959 dynamic_symbols, dynstr);
8851ecca
ILT
2960 break;
2961#endif
2962 default:
2963 gold_unreachable();
14b31740 2964 }
14b31740
ILT
2965}
2966
2967// Create the version sections, sized version.
2968
2969template<int size, bool big_endian>
2970void
2971Layout::sized_create_version_sections(
2972 const Versions* versions,
46fe1623 2973 const Symbol_table* symtab,
14b31740
ILT
2974 unsigned int local_symcount,
2975 const std::vector<Symbol*>& dynamic_symbols,
7d1a9ebb 2976 const Output_section* dynstr)
14b31740 2977{
3802b2dd
ILT
2978 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2979 elfcpp::SHT_GNU_versym,
2980 elfcpp::SHF_ALLOC,
2981 false);
14b31740
ILT
2982
2983 unsigned char* vbuf;
2984 unsigned int vsize;
7d1a9ebb
ILT
2985 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2986 local_symcount,
2987 dynamic_symbols,
2988 &vbuf, &vsize);
14b31740 2989
7d9e3d98
ILT
2990 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
2991 "** versions");
14b31740
ILT
2992
2993 vsec->add_output_section_data(vdata);
2994 vsec->set_entsize(2);
2995 vsec->set_link_section(this->dynsym_section_);
2996
2997 Output_data_dynamic* const odyn = this->dynamic_data_;
2998 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2999
3000 if (versions->any_defs())
3001 {
3802b2dd
ILT
3002 Output_section* vdsec;
3003 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3004 elfcpp::SHT_GNU_verdef,
3005 elfcpp::SHF_ALLOC,
3006 false);
14b31740
ILT
3007
3008 unsigned char* vdbuf;
3009 unsigned int vdsize;
3010 unsigned int vdentries;
7d1a9ebb
ILT
3011 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3012 &vdsize, &vdentries);
14b31740 3013
7d9e3d98
ILT
3014 Output_section_data* vddata =
3015 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
14b31740
ILT
3016
3017 vdsec->add_output_section_data(vddata);
3018 vdsec->set_link_section(dynstr);
3019 vdsec->set_info(vdentries);
3020
3021 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3022 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3023 }
3024
3025 if (versions->any_needs())
3026 {
14b31740 3027 Output_section* vnsec;
3802b2dd
ILT
3028 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3029 elfcpp::SHT_GNU_verneed,
3030 elfcpp::SHF_ALLOC,
3031 false);
14b31740
ILT
3032
3033 unsigned char* vnbuf;
3034 unsigned int vnsize;
3035 unsigned int vnentries;
7d1a9ebb
ILT
3036 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3037 &vnbuf, &vnsize,
3038 &vnentries);
14b31740 3039
7d9e3d98
ILT
3040 Output_section_data* vndata =
3041 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
14b31740
ILT
3042
3043 vnsec->add_output_section_data(vndata);
3044 vnsec->set_link_section(dynstr);
3045 vnsec->set_info(vnentries);
3046
3047 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3048 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3049 }
3050}
3051
dbe717ef
ILT
3052// Create the .interp section and PT_INTERP segment.
3053
3054void
3055Layout::create_interp(const Target* target)
3056{
e55bde5e 3057 const char* interp = parameters->options().dynamic_linker();
dbe717ef
ILT
3058 if (interp == NULL)
3059 {
3060 interp = target->dynamic_linker();
a3ad94ed 3061 gold_assert(interp != NULL);
dbe717ef
ILT
3062 }
3063
3064 size_t len = strlen(interp) + 1;
3065
3066 Output_section_data* odata = new Output_data_const(interp, len, 1);
3067
3802b2dd
ILT
3068 Output_section* osec = this->choose_output_section(NULL, ".interp",
3069 elfcpp::SHT_PROGBITS,
3070 elfcpp::SHF_ALLOC,
3071 false);
dbe717ef
ILT
3072 osec->add_output_section_data(odata);
3073
1c4f3631
ILT
3074 if (!this->script_options_->saw_phdrs_clause())
3075 {
3076 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3077 elfcpp::PF_R);
01676dcd 3078 oseg->add_output_section(osec, elfcpp::PF_R);
1c4f3631 3079 }
dbe717ef
ILT
3080}
3081
a3ad94ed
ILT
3082// Finish the .dynamic section and PT_DYNAMIC segment.
3083
3084void
3085Layout::finish_dynamic_section(const Input_objects* input_objects,
16649710 3086 const Symbol_table* symtab)
a3ad94ed 3087{
1c4f3631
ILT
3088 if (!this->script_options_->saw_phdrs_clause())
3089 {
3090 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3091 (elfcpp::PF_R
3092 | elfcpp::PF_W));
01676dcd
ILT
3093 oseg->add_output_section(this->dynamic_section_,
3094 elfcpp::PF_R | elfcpp::PF_W);
1c4f3631 3095 }
a3ad94ed 3096
16649710
ILT
3097 Output_data_dynamic* const odyn = this->dynamic_data_;
3098
a3ad94ed
ILT
3099 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3100 p != input_objects->dynobj_end();
3101 ++p)
3102 {
3103 // FIXME: Handle --as-needed.
3104 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3105 }
3106
8851ecca 3107 if (parameters->options().shared())
fced7afd 3108 {
e55bde5e 3109 const char* soname = parameters->options().soname();
fced7afd
ILT
3110 if (soname != NULL)
3111 odyn->add_string(elfcpp::DT_SONAME, soname);
3112 }
3113
c6585162 3114 Symbol* sym = symtab->lookup(parameters->options().init());
14b31740 3115 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
3116 odyn->add_symbol(elfcpp::DT_INIT, sym);
3117
c6585162 3118 sym = symtab->lookup(parameters->options().fini());
14b31740 3119 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
3120 odyn->add_symbol(elfcpp::DT_FINI, sym);
3121
f15f61a7
DK
3122 // Look for .init_array, .preinit_array and .fini_array by checking
3123 // section types.
3124 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3125 p != this->section_list_.end();
3126 ++p)
3127 switch((*p)->type())
3128 {
3129 case elfcpp::SHT_FINI_ARRAY:
3130 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3131 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3132 break;
3133 case elfcpp::SHT_INIT_ARRAY:
3134 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3135 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3136 break;
3137 case elfcpp::SHT_PREINIT_ARRAY:
3138 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3139 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3140 break;
3141 default:
3142 break;
3143 }
3144
41f542e7 3145 // Add a DT_RPATH entry if needed.
e55bde5e 3146 const General_options::Dir_list& rpath(parameters->options().rpath());
41f542e7
ILT
3147 if (!rpath.empty())
3148 {
3149 std::string rpath_val;
3150 for (General_options::Dir_list::const_iterator p = rpath.begin();
3151 p != rpath.end();
3152 ++p)
3153 {
3154 if (rpath_val.empty())
ad2d6943 3155 rpath_val = p->name();
41f542e7
ILT
3156 else
3157 {
3158 // Eliminate duplicates.
3159 General_options::Dir_list::const_iterator q;
3160 for (q = rpath.begin(); q != p; ++q)
ad2d6943 3161 if (q->name() == p->name())
41f542e7
ILT
3162 break;
3163 if (q == p)
3164 {
3165 rpath_val += ':';
ad2d6943 3166 rpath_val += p->name();
41f542e7
ILT
3167 }
3168 }
3169 }
3170
3171 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
7c414435
DM
3172 if (parameters->options().enable_new_dtags())
3173 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
41f542e7 3174 }
4f4c5f80
ILT
3175
3176 // Look for text segments that have dynamic relocations.
3177 bool have_textrel = false;
4e8fe71f 3178 if (!this->script_options_->saw_sections_clause())
4f4c5f80 3179 {
4e8fe71f
ILT
3180 for (Segment_list::const_iterator p = this->segment_list_.begin();
3181 p != this->segment_list_.end();
3182 ++p)
3183 {
3184 if (((*p)->flags() & elfcpp::PF_W) == 0
3185 && (*p)->dynamic_reloc_count() > 0)
3186 {
3187 have_textrel = true;
3188 break;
3189 }
3190 }
3191 }
3192 else
3193 {
3194 // We don't know the section -> segment mapping, so we are
3195 // conservative and just look for readonly sections with
3196 // relocations. If those sections wind up in writable segments,
3197 // then we have created an unnecessary DT_TEXTREL entry.
3198 for (Section_list::const_iterator p = this->section_list_.begin();
3199 p != this->section_list_.end();
3200 ++p)
3201 {
3202 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3203 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3204 && ((*p)->dynamic_reloc_count() > 0))
3205 {
3206 have_textrel = true;
3207 break;
3208 }
3209 }
4f4c5f80
ILT
3210 }
3211
3212 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3213 // post-link tools can easily modify these flags if desired.
3214 unsigned int flags = 0;
3215 if (have_textrel)
6a41d30b
ILT
3216 {
3217 // Add a DT_TEXTREL for compatibility with older loaders.
3218 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3219 flags |= elfcpp::DF_TEXTREL;
3220 }
8851ecca 3221 if (parameters->options().shared() && this->has_static_tls())
535890bb 3222 flags |= elfcpp::DF_STATIC_TLS;
7be8330a
CD
3223 if (parameters->options().origin())
3224 flags |= elfcpp::DF_ORIGIN;
f15f61a7
DK
3225 if (parameters->options().Bsymbolic())
3226 {
3227 flags |= elfcpp::DF_SYMBOLIC;
3228 // Add DT_SYMBOLIC for compatibility with older loaders.
3229 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3230 }
e1c74d60
ILT
3231 if (parameters->options().now())
3232 flags |= elfcpp::DF_BIND_NOW;
4f4c5f80 3233 odyn->add_constant(elfcpp::DT_FLAGS, flags);
7c414435
DM
3234
3235 flags = 0;
3236 if (parameters->options().initfirst())
3237 flags |= elfcpp::DF_1_INITFIRST;
3238 if (parameters->options().interpose())
3239 flags |= elfcpp::DF_1_INTERPOSE;
3240 if (parameters->options().loadfltr())
3241 flags |= elfcpp::DF_1_LOADFLTR;
3242 if (parameters->options().nodefaultlib())
3243 flags |= elfcpp::DF_1_NODEFLIB;
3244 if (parameters->options().nodelete())
3245 flags |= elfcpp::DF_1_NODELETE;
3246 if (parameters->options().nodlopen())
3247 flags |= elfcpp::DF_1_NOOPEN;
3248 if (parameters->options().nodump())
3249 flags |= elfcpp::DF_1_NODUMP;
3250 if (!parameters->options().shared())
3251 flags &= ~(elfcpp::DF_1_INITFIRST
3252 | elfcpp::DF_1_NODELETE
3253 | elfcpp::DF_1_NOOPEN);
7be8330a
CD
3254 if (parameters->options().origin())
3255 flags |= elfcpp::DF_1_ORIGIN;
e1c74d60
ILT
3256 if (parameters->options().now())
3257 flags |= elfcpp::DF_1_NOW;
7c414435
DM
3258 if (flags)
3259 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
a3ad94ed
ILT
3260}
3261
dff16297
ILT
3262// The mapping of input section name prefixes to output section names.
3263// In some cases one prefix is itself a prefix of another prefix; in
3264// such a case the longer prefix must come first. These prefixes are
3265// based on the GNU linker default ELF linker script.
a2fb1b05 3266
ead1e424 3267#define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
dff16297 3268const Layout::Section_name_mapping Layout::section_name_mapping[] =
a2fb1b05 3269{
dff16297
ILT
3270 MAPPING_INIT(".text.", ".text"),
3271 MAPPING_INIT(".ctors.", ".ctors"),
3272 MAPPING_INIT(".dtors.", ".dtors"),
3273 MAPPING_INIT(".rodata.", ".rodata"),
3274 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3275 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3276 MAPPING_INIT(".data.", ".data"),
3277 MAPPING_INIT(".bss.", ".bss"),
3278 MAPPING_INIT(".tdata.", ".tdata"),
3279 MAPPING_INIT(".tbss.", ".tbss"),
3280 MAPPING_INIT(".init_array.", ".init_array"),
3281 MAPPING_INIT(".fini_array.", ".fini_array"),
3282 MAPPING_INIT(".sdata.", ".sdata"),
3283 MAPPING_INIT(".sbss.", ".sbss"),
3284 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3285 // differently depending on whether it is creating a shared library.
3286 MAPPING_INIT(".sdata2.", ".sdata"),
3287 MAPPING_INIT(".sbss2.", ".sbss"),
3288 MAPPING_INIT(".lrodata.", ".lrodata"),
3289 MAPPING_INIT(".ldata.", ".ldata"),
3290 MAPPING_INIT(".lbss.", ".lbss"),
3291 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3292 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3293 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3294 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3295 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3296 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3297 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3298 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3299 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3300 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3301 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3302 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3303 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3304 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3305 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3306 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3307 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
1dcd334d
DK
3308 MAPPING_INIT(".ARM.extab.", ".ARM.extab"),
3309 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3310 MAPPING_INIT(".ARM.exidx.", ".ARM.exidx"),
3311 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
a2fb1b05
ILT
3312};
3313#undef MAPPING_INIT
3314
dff16297
ILT
3315const int Layout::section_name_mapping_count =
3316 (sizeof(Layout::section_name_mapping)
3317 / sizeof(Layout::section_name_mapping[0]));
a2fb1b05 3318
ead1e424
ILT
3319// Choose the output section name to use given an input section name.
3320// Set *PLEN to the length of the name. *PLEN is initialized to the
3321// length of NAME.
3322
3323const char*
3324Layout::output_section_name(const char* name, size_t* plen)
3325{
af4a8a83
ILT
3326 // gcc 4.3 generates the following sorts of section names when it
3327 // needs a section name specific to a function:
3328 // .text.FN
3329 // .rodata.FN
3330 // .sdata2.FN
3331 // .data.FN
3332 // .data.rel.FN
3333 // .data.rel.local.FN
3334 // .data.rel.ro.FN
3335 // .data.rel.ro.local.FN
3336 // .sdata.FN
3337 // .bss.FN
3338 // .sbss.FN
3339 // .tdata.FN
3340 // .tbss.FN
3341
3342 // The GNU linker maps all of those to the part before the .FN,
3343 // except that .data.rel.local.FN is mapped to .data, and
3344 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3345 // beginning with .data.rel.ro.local are grouped together.
3346
3347 // For an anonymous namespace, the string FN can contain a '.'.
3348
3349 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3350 // GNU linker maps to .rodata.
3351
dff16297
ILT
3352 // The .data.rel.ro sections are used with -z relro. The sections
3353 // are recognized by name. We use the same names that the GNU
3354 // linker does for these sections.
af4a8a83 3355
dff16297
ILT
3356 // It is hard to handle this in a principled way, so we don't even
3357 // try. We use a table of mappings. If the input section name is
3358 // not found in the table, we simply use it as the output section
3359 // name.
af4a8a83 3360
dff16297
ILT
3361 const Section_name_mapping* psnm = section_name_mapping;
3362 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
ead1e424 3363 {
dff16297
ILT
3364 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3365 {
3366 *plen = psnm->tolen;
3367 return psnm->to;
3368 }
ead1e424
ILT
3369 }
3370
ead1e424
ILT
3371 return name;
3372}
3373
8a4c0b0d
ILT
3374// Check if a comdat group or .gnu.linkonce section with the given
3375// NAME is selected for the link. If there is already a section,
1ef4d87f
ILT
3376// *KEPT_SECTION is set to point to the existing section and the
3377// function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3378// IS_GROUP_NAME are recorded for this NAME in the layout object,
3379// *KEPT_SECTION is set to the internal copy and the function returns
3380// true.
a2fb1b05
ILT
3381
3382bool
e55bde5e 3383Layout::find_or_add_kept_section(const std::string& name,
1ef4d87f
ILT
3384 Relobj* object,
3385 unsigned int shndx,
3386 bool is_comdat,
3387 bool is_group_name,
8a4c0b0d 3388 Kept_section** kept_section)
a2fb1b05 3389{
e55bde5e
ILT
3390 // It's normal to see a couple of entries here, for the x86 thunk
3391 // sections. If we see more than a few, we're linking a C++
3392 // program, and we resize to get more space to minimize rehashing.
3393 if (this->signatures_.size() > 4
3394 && !this->resized_signatures_)
3395 {
3396 reserve_unordered_map(&this->signatures_,
3397 this->number_of_input_files_ * 64);
3398 this->resized_signatures_ = true;
3399 }
3400
1ef4d87f
ILT
3401 Kept_section candidate;
3402 std::pair<Signatures::iterator, bool> ins =
3403 this->signatures_.insert(std::make_pair(name, candidate));
a2fb1b05 3404
1ef4d87f 3405 if (kept_section != NULL)
8a4c0b0d 3406 *kept_section = &ins.first->second;
a2fb1b05
ILT
3407 if (ins.second)
3408 {
3409 // This is the first time we've seen this signature.
1ef4d87f
ILT
3410 ins.first->second.set_object(object);
3411 ins.first->second.set_shndx(shndx);
3412 if (is_comdat)
3413 ins.first->second.set_is_comdat();
3414 if (is_group_name)
3415 ins.first->second.set_is_group_name();
a2fb1b05
ILT
3416 return true;
3417 }
3418
1ef4d87f
ILT
3419 // We have already seen this signature.
3420
3421 if (ins.first->second.is_group_name())
a2fb1b05
ILT
3422 {
3423 // We've already seen a real section group with this signature.
1ef4d87f
ILT
3424 // If the kept group is from a plugin object, and we're in the
3425 // replacement phase, accept the new one as a replacement.
3426 if (ins.first->second.object() == NULL
2756a258
CC
3427 && parameters->options().plugins()->in_replacement_phase())
3428 {
1ef4d87f
ILT
3429 ins.first->second.set_object(object);
3430 ins.first->second.set_shndx(shndx);
2756a258
CC
3431 return true;
3432 }
a2fb1b05
ILT
3433 return false;
3434 }
1ef4d87f 3435 else if (is_group_name)
a2fb1b05
ILT
3436 {
3437 // This is a real section group, and we've already seen a
a0fa0c07 3438 // linkonce section with this signature. Record that we've seen
a2fb1b05 3439 // a section group, and don't include this section group.
1ef4d87f 3440 ins.first->second.set_is_group_name();
a2fb1b05
ILT
3441 return false;
3442 }
3443 else
3444 {
3445 // We've already seen a linkonce section and this is a linkonce
3446 // section. These don't block each other--this may be the same
3447 // symbol name with different section types.
3448 return true;
3449 }
3450}
3451
a445fddf
ILT
3452// Store the allocated sections into the section list.
3453
3454void
3455Layout::get_allocated_sections(Section_list* section_list) const
3456{
3457 for (Section_list::const_iterator p = this->section_list_.begin();
3458 p != this->section_list_.end();
3459 ++p)
3460 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3461 section_list->push_back(*p);
3462}
3463
3464// Create an output segment.
3465
3466Output_segment*
3467Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3468{
8851ecca 3469 gold_assert(!parameters->options().relocatable());
a445fddf
ILT
3470 Output_segment* oseg = new Output_segment(type, flags);
3471 this->segment_list_.push_back(oseg);
2d924fd9
ILT
3472
3473 if (type == elfcpp::PT_TLS)
3474 this->tls_segment_ = oseg;
3475 else if (type == elfcpp::PT_GNU_RELRO)
3476 this->relro_segment_ = oseg;
3477
a445fddf
ILT
3478 return oseg;
3479}
3480
730cdc88
ILT
3481// Write out the Output_sections. Most won't have anything to write,
3482// since most of the data will come from input sections which are
3483// handled elsewhere. But some Output_sections do have Output_data.
3484
3485void
3486Layout::write_output_sections(Output_file* of) const
3487{
3488 for (Section_list::const_iterator p = this->section_list_.begin();
3489 p != this->section_list_.end();
3490 ++p)
3491 {
3492 if (!(*p)->after_input_sections())
3493 (*p)->write(of);
3494 }
3495}
3496
61ba1cf9
ILT
3497// Write out data not associated with a section or the symbol table.
3498
3499void
9025d29d 3500Layout::write_data(const Symbol_table* symtab, Output_file* of) const
61ba1cf9 3501{
8851ecca 3502 if (!parameters->options().strip_all())
a3ad94ed 3503 {
9e2dcb77
ILT
3504 const Output_section* symtab_section = this->symtab_section_;
3505 for (Section_list::const_iterator p = this->section_list_.begin();
3506 p != this->section_list_.end();
3507 ++p)
a3ad94ed 3508 {
9e2dcb77
ILT
3509 if ((*p)->needs_symtab_index())
3510 {
3511 gold_assert(symtab_section != NULL);
3512 unsigned int index = (*p)->symtab_index();
3513 gold_assert(index > 0 && index != -1U);
3514 off_t off = (symtab_section->offset()
3515 + index * symtab_section->entsize());
d491d34e 3516 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
9e2dcb77 3517 }
a3ad94ed
ILT
3518 }
3519 }
3520
3521 const Output_section* dynsym_section = this->dynsym_section_;
3522 for (Section_list::const_iterator p = this->section_list_.begin();
3523 p != this->section_list_.end();
3524 ++p)
3525 {
3526 if ((*p)->needs_dynsym_index())
3527 {
3528 gold_assert(dynsym_section != NULL);
3529 unsigned int index = (*p)->dynsym_index();
3530 gold_assert(index > 0 && index != -1U);
3531 off_t off = (dynsym_section->offset()
3532 + index * dynsym_section->entsize());
d491d34e 3533 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
a3ad94ed
ILT
3534 }
3535 }
3536
a3ad94ed 3537 // Write out the Output_data which are not in an Output_section.
61ba1cf9
ILT
3538 for (Data_list::const_iterator p = this->special_output_list_.begin();
3539 p != this->special_output_list_.end();
3540 ++p)
3541 (*p)->write(of);
3542}
3543
730cdc88
ILT
3544// Write out the Output_sections which can only be written after the
3545// input sections are complete.
3546
3547void
27bc2bce 3548Layout::write_sections_after_input_sections(Output_file* of)
730cdc88 3549{
27bc2bce 3550 // Determine the final section offsets, and thus the final output
9a0910c3
ILT
3551 // file size. Note we finalize the .shstrab last, to allow the
3552 // after_input_section sections to modify their section-names before
3553 // writing.
17a1d0a9 3554 if (this->any_postprocessing_sections_)
27bc2bce 3555 {
17a1d0a9
ILT
3556 off_t off = this->output_file_size_;
3557 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
8a4c0b0d 3558
17a1d0a9
ILT
3559 // Now that we've finalized the names, we can finalize the shstrab.
3560 off =
3561 this->set_section_offsets(off,
3562 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3563
3564 if (off > this->output_file_size_)
3565 {
3566 of->resize(off);
3567 this->output_file_size_ = off;
3568 }
27bc2bce
ILT
3569 }
3570
730cdc88
ILT
3571 for (Section_list::const_iterator p = this->section_list_.begin();
3572 p != this->section_list_.end();
3573 ++p)
3574 {
3575 if ((*p)->after_input_sections())
3576 (*p)->write(of);
3577 }
27bc2bce 3578
27bc2bce 3579 this->section_headers_->write(of);
730cdc88
ILT
3580}
3581
8ed814a9
ILT
3582// If the build ID requires computing a checksum, do so here, and
3583// write it out. We compute a checksum over the entire file because
3584// that is simplest.
3585
3586void
3587Layout::write_build_id(Output_file* of) const
3588{
3589 if (this->build_id_note_ == NULL)
3590 return;
3591
3592 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3593
3594 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3595 this->build_id_note_->data_size());
3596
3597 const char* style = parameters->options().build_id();
3598 if (strcmp(style, "sha1") == 0)
3599 {
3600 sha1_ctx ctx;
3601 sha1_init_ctx(&ctx);
3602 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3603 sha1_finish_ctx(&ctx, ov);
3604 }
3605 else if (strcmp(style, "md5") == 0)
3606 {
3607 md5_ctx ctx;
3608 md5_init_ctx(&ctx);
3609 md5_process_bytes(iv, this->output_file_size_, &ctx);
3610 md5_finish_ctx(&ctx, ov);
3611 }
3612 else
3613 gold_unreachable();
3614
3615 of->write_output_view(this->build_id_note_->offset(),
3616 this->build_id_note_->data_size(),
3617 ov);
3618
3619 of->free_input_view(0, this->output_file_size_, iv);
3620}
3621
516cb3d0
ILT
3622// Write out a binary file. This is called after the link is
3623// complete. IN is the temporary output file we used to generate the
3624// ELF code. We simply walk through the segments, read them from
3625// their file offset in IN, and write them to their load address in
3626// the output file. FIXME: with a bit more work, we could support
3627// S-records and/or Intel hex format here.
3628
3629void
3630Layout::write_binary(Output_file* in) const
3631{
e55bde5e 3632 gold_assert(parameters->options().oformat_enum()
bc644c6c 3633 == General_options::OBJECT_FORMAT_BINARY);
516cb3d0
ILT
3634
3635 // Get the size of the binary file.
3636 uint64_t max_load_address = 0;
3637 for (Segment_list::const_iterator p = this->segment_list_.begin();
3638 p != this->segment_list_.end();
3639 ++p)
3640 {
3641 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3642 {
3643 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3644 if (max_paddr > max_load_address)
3645 max_load_address = max_paddr;
3646 }
3647 }
3648
8851ecca 3649 Output_file out(parameters->options().output_file_name());
516cb3d0
ILT
3650 out.open(max_load_address);
3651
3652 for (Segment_list::const_iterator p = this->segment_list_.begin();
3653 p != this->segment_list_.end();
3654 ++p)
3655 {
3656 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3657 {
3658 const unsigned char* vin = in->get_input_view((*p)->offset(),
3659 (*p)->filesz());
3660 unsigned char* vout = out.get_output_view((*p)->paddr(),
3661 (*p)->filesz());
3662 memcpy(vout, vin, (*p)->filesz());
3663 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3664 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3665 }
3666 }
3667
3668 out.close();
3669}
3670
7d9e3d98
ILT
3671// Print the output sections to the map file.
3672
3673void
3674Layout::print_to_mapfile(Mapfile* mapfile) const
3675{
3676 for (Segment_list::const_iterator p = this->segment_list_.begin();
3677 p != this->segment_list_.end();
3678 ++p)
3679 (*p)->print_sections_to_mapfile(mapfile);
3680}
3681
ad8f37d1
ILT
3682// Print statistical information to stderr. This is used for --stats.
3683
3684void
3685Layout::print_stats() const
3686{
3687 this->namepool_.print_stats("section name pool");
3688 this->sympool_.print_stats("output symbol name pool");
3689 this->dynpool_.print_stats("dynamic name pool");
38c5e8b4
ILT
3690
3691 for (Section_list::const_iterator p = this->section_list_.begin();
3692 p != this->section_list_.end();
3693 ++p)
3694 (*p)->print_merge_stats();
ad8f37d1
ILT
3695}
3696
730cdc88
ILT
3697// Write_sections_task methods.
3698
3699// We can always run this task.
3700
17a1d0a9
ILT
3701Task_token*
3702Write_sections_task::is_runnable()
730cdc88 3703{
17a1d0a9 3704 return NULL;
730cdc88
ILT
3705}
3706
3707// We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3708// when finished.
3709
17a1d0a9
ILT
3710void
3711Write_sections_task::locks(Task_locker* tl)
730cdc88 3712{
17a1d0a9
ILT
3713 tl->add(this, this->output_sections_blocker_);
3714 tl->add(this, this->final_blocker_);
730cdc88
ILT
3715}
3716
3717// Run the task--write out the data.
3718
3719void
3720Write_sections_task::run(Workqueue*)
3721{
3722 this->layout_->write_output_sections(this->of_);
3723}
3724
61ba1cf9
ILT
3725// Write_data_task methods.
3726
3727// We can always run this task.
3728
17a1d0a9
ILT
3729Task_token*
3730Write_data_task::is_runnable()
61ba1cf9 3731{
17a1d0a9 3732 return NULL;
61ba1cf9
ILT
3733}
3734
3735// We need to unlock FINAL_BLOCKER when finished.
3736
17a1d0a9
ILT
3737void
3738Write_data_task::locks(Task_locker* tl)
61ba1cf9 3739{
17a1d0a9 3740 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
3741}
3742
3743// Run the task--write out the data.
3744
3745void
3746Write_data_task::run(Workqueue*)
3747{
9025d29d 3748 this->layout_->write_data(this->symtab_, this->of_);
61ba1cf9
ILT
3749}
3750
3751// Write_symbols_task methods.
3752
3753// We can always run this task.
3754
17a1d0a9
ILT
3755Task_token*
3756Write_symbols_task::is_runnable()
61ba1cf9 3757{
17a1d0a9 3758 return NULL;
61ba1cf9
ILT
3759}
3760
3761// We need to unlock FINAL_BLOCKER when finished.
3762
17a1d0a9
ILT
3763void
3764Write_symbols_task::locks(Task_locker* tl)
61ba1cf9 3765{
17a1d0a9 3766 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
3767}
3768
3769// Run the task--write out the symbols.
3770
3771void
3772Write_symbols_task::run(Workqueue*)
3773{
fd9d194f
ILT
3774 this->symtab_->write_globals(this->sympool_, this->dynpool_,
3775 this->layout_->symtab_xindex(),
d491d34e 3776 this->layout_->dynsym_xindex(), this->of_);
61ba1cf9
ILT
3777}
3778
730cdc88
ILT
3779// Write_after_input_sections_task methods.
3780
3781// We can only run this task after the input sections have completed.
3782
17a1d0a9
ILT
3783Task_token*
3784Write_after_input_sections_task::is_runnable()
730cdc88
ILT
3785{
3786 if (this->input_sections_blocker_->is_blocked())
17a1d0a9
ILT
3787 return this->input_sections_blocker_;
3788 return NULL;
730cdc88
ILT
3789}
3790
3791// We need to unlock FINAL_BLOCKER when finished.
3792
17a1d0a9
ILT
3793void
3794Write_after_input_sections_task::locks(Task_locker* tl)
730cdc88 3795{
17a1d0a9 3796 tl->add(this, this->final_blocker_);
730cdc88
ILT
3797}
3798
3799// Run the task.
3800
3801void
3802Write_after_input_sections_task::run(Workqueue*)
3803{
3804 this->layout_->write_sections_after_input_sections(this->of_);
3805}
3806
92e059d8 3807// Close_task_runner methods.
61ba1cf9
ILT
3808
3809// Run the task--close the file.
3810
3811void
17a1d0a9 3812Close_task_runner::run(Workqueue*, const Task*)
61ba1cf9 3813{
8ed814a9
ILT
3814 // If we need to compute a checksum for the BUILD if, we do so here.
3815 this->layout_->write_build_id(this->of_);
3816
516cb3d0 3817 // If we've been asked to create a binary file, we do so here.
7cc619c3 3818 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
516cb3d0
ILT
3819 this->layout_->write_binary(this->of_);
3820
61ba1cf9
ILT
3821 this->of_->close();
3822}
3823
a2fb1b05
ILT
3824// Instantiate the templates we need. We could use the configure
3825// script to restrict this to only the ones for implemented targets.
3826
193a53d9 3827#ifdef HAVE_TARGET_32_LITTLE
a2fb1b05
ILT
3828template
3829Output_section*
730cdc88
ILT
3830Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3831 const char* name,
3832 const elfcpp::Shdr<32, false>& shdr,
3833 unsigned int, unsigned int, off_t*);
193a53d9 3834#endif
a2fb1b05 3835
193a53d9 3836#ifdef HAVE_TARGET_32_BIG
a2fb1b05
ILT
3837template
3838Output_section*
730cdc88
ILT
3839Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3840 const char* name,
3841 const elfcpp::Shdr<32, true>& shdr,
3842 unsigned int, unsigned int, off_t*);
193a53d9 3843#endif
a2fb1b05 3844
193a53d9 3845#ifdef HAVE_TARGET_64_LITTLE
a2fb1b05
ILT
3846template
3847Output_section*
730cdc88
ILT
3848Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3849 const char* name,
3850 const elfcpp::Shdr<64, false>& shdr,
3851 unsigned int, unsigned int, off_t*);
193a53d9 3852#endif
a2fb1b05 3853
193a53d9 3854#ifdef HAVE_TARGET_64_BIG
a2fb1b05
ILT
3855template
3856Output_section*
730cdc88
ILT
3857Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3858 const char* name,
3859 const elfcpp::Shdr<64, true>& shdr,
3860 unsigned int, unsigned int, off_t*);
193a53d9 3861#endif
a2fb1b05 3862
6a74a719
ILT
3863#ifdef HAVE_TARGET_32_LITTLE
3864template
3865Output_section*
3866Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3867 unsigned int reloc_shndx,
3868 const elfcpp::Shdr<32, false>& shdr,
3869 Output_section* data_section,
3870 Relocatable_relocs* rr);
3871#endif
3872
3873#ifdef HAVE_TARGET_32_BIG
3874template
3875Output_section*
3876Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3877 unsigned int reloc_shndx,
3878 const elfcpp::Shdr<32, true>& shdr,
3879 Output_section* data_section,
3880 Relocatable_relocs* rr);
3881#endif
3882
3883#ifdef HAVE_TARGET_64_LITTLE
3884template
3885Output_section*
3886Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3887 unsigned int reloc_shndx,
3888 const elfcpp::Shdr<64, false>& shdr,
3889 Output_section* data_section,
3890 Relocatable_relocs* rr);
3891#endif
3892
3893#ifdef HAVE_TARGET_64_BIG
3894template
3895Output_section*
3896Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3897 unsigned int reloc_shndx,
3898 const elfcpp::Shdr<64, true>& shdr,
3899 Output_section* data_section,
3900 Relocatable_relocs* rr);
3901#endif
3902
3903#ifdef HAVE_TARGET_32_LITTLE
3904template
3905void
3906Layout::layout_group<32, false>(Symbol_table* symtab,
3907 Sized_relobj<32, false>* object,
3908 unsigned int,
3909 const char* group_section_name,
3910 const char* signature,
3911 const elfcpp::Shdr<32, false>& shdr,
8825ac63
ILT
3912 elfcpp::Elf_Word flags,
3913 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3914#endif
3915
3916#ifdef HAVE_TARGET_32_BIG
3917template
3918void
3919Layout::layout_group<32, true>(Symbol_table* symtab,
3920 Sized_relobj<32, true>* object,
3921 unsigned int,
3922 const char* group_section_name,
3923 const char* signature,
3924 const elfcpp::Shdr<32, true>& shdr,
8825ac63
ILT
3925 elfcpp::Elf_Word flags,
3926 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3927#endif
3928
3929#ifdef HAVE_TARGET_64_LITTLE
3930template
3931void
3932Layout::layout_group<64, false>(Symbol_table* symtab,
3933 Sized_relobj<64, false>* object,
3934 unsigned int,
3935 const char* group_section_name,
3936 const char* signature,
3937 const elfcpp::Shdr<64, false>& shdr,
8825ac63
ILT
3938 elfcpp::Elf_Word flags,
3939 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3940#endif
3941
3942#ifdef HAVE_TARGET_64_BIG
3943template
3944void
3945Layout::layout_group<64, true>(Symbol_table* symtab,
3946 Sized_relobj<64, true>* object,
3947 unsigned int,
3948 const char* group_section_name,
3949 const char* signature,
3950 const elfcpp::Shdr<64, true>& shdr,
8825ac63
ILT
3951 elfcpp::Elf_Word flags,
3952 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3953#endif
3954
730cdc88
ILT
3955#ifdef HAVE_TARGET_32_LITTLE
3956template
3957Output_section*
3958Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3959 const unsigned char* symbols,
3960 off_t symbols_size,
3961 const unsigned char* symbol_names,
3962 off_t symbol_names_size,
3963 unsigned int shndx,
3964 const elfcpp::Shdr<32, false>& shdr,
3965 unsigned int reloc_shndx,
3966 unsigned int reloc_type,
3967 off_t* off);
3968#endif
3969
3970#ifdef HAVE_TARGET_32_BIG
3971template
3972Output_section*
3973Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3974 const unsigned char* symbols,
3975 off_t symbols_size,
3976 const unsigned char* symbol_names,
3977 off_t symbol_names_size,
3978 unsigned int shndx,
3979 const elfcpp::Shdr<32, true>& shdr,
3980 unsigned int reloc_shndx,
3981 unsigned int reloc_type,
3982 off_t* off);
3983#endif
3984
3985#ifdef HAVE_TARGET_64_LITTLE
3986template
3987Output_section*
3988Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3989 const unsigned char* symbols,
3990 off_t symbols_size,
3991 const unsigned char* symbol_names,
3992 off_t symbol_names_size,
3993 unsigned int shndx,
3994 const elfcpp::Shdr<64, false>& shdr,
3995 unsigned int reloc_shndx,
3996 unsigned int reloc_type,
3997 off_t* off);
3998#endif
3999
4000#ifdef HAVE_TARGET_64_BIG
4001template
4002Output_section*
4003Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4004 const unsigned char* symbols,
4005 off_t symbols_size,
4006 const unsigned char* symbol_names,
4007 off_t symbol_names_size,
4008 unsigned int shndx,
4009 const elfcpp::Shdr<64, true>& shdr,
4010 unsigned int reloc_shndx,
4011 unsigned int reloc_type,
4012 off_t* off);
4013#endif
a2fb1b05
ILT
4014
4015} // End namespace gold.
This page took 0.423943 seconds and 4 git commands to generate.