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