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