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