Support size relocation only for ELF
[deliverable/binutils-gdb.git] / gold / layout.cc
CommitLineData
a2fb1b05
ILT
1// layout.cc -- lay out output file sections for gold
2
2e702c99
RM
3// Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2012
4// Free Software Foundation, Inc.
6cb15b7f
ILT
5// Written by Ian Lance Taylor <iant@google.com>.
6
7// This file is part of gold.
8
9// This program is free software; you can redistribute it and/or modify
10// it under the terms of the GNU General Public License as published by
11// the Free Software Foundation; either version 3 of the License, or
12// (at your option) any later version.
13
14// This program is distributed in the hope that it will be useful,
15// but WITHOUT ANY WARRANTY; without even the implied warranty of
16// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17// GNU General Public License for more details.
18
19// You should have received a copy of the GNU General Public License
20// along with this program; if not, write to the Free Software
21// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
22// MA 02110-1301, USA.
23
a2fb1b05
ILT
24#include "gold.h"
25
8ed814a9 26#include <cerrno>
a2fb1b05 27#include <cstring>
54dc6425 28#include <algorithm>
a2fb1b05 29#include <iostream>
6e9ba2ca 30#include <fstream>
a2fb1b05 31#include <utility>
8ed814a9 32#include <fcntl.h>
6e9ba2ca 33#include <fnmatch.h>
8ed814a9
ILT
34#include <unistd.h>
35#include "libiberty.h"
36#include "md5.h"
37#include "sha1.h"
a2fb1b05 38
7e1edb90 39#include "parameters.h"
14144f39 40#include "options.h"
7d9e3d98 41#include "mapfile.h"
a445fddf
ILT
42#include "script.h"
43#include "script-sections.h"
a2fb1b05 44#include "output.h"
f6ce93d6 45#include "symtab.h"
a3ad94ed 46#include "dynobj.h"
3151305a 47#include "ehframe.h"
c1027032 48#include "gdb-index.h"
96803768 49#include "compressed_output.h"
62b01cb5 50#include "reduced_debug_output.h"
487b39df 51#include "object.h"
6a74a719 52#include "reloc.h"
2a00e4fb 53#include "descriptors.h"
2756a258 54#include "plugin.h"
3ce2c28e
ILT
55#include "incremental.h"
56#include "layout.h"
a2fb1b05
ILT
57
58namespace gold
59{
60
cdc29364
CC
61// Class Free_list.
62
63// The total number of free lists used.
64unsigned int Free_list::num_lists = 0;
65// The total number of free list nodes used.
66unsigned int Free_list::num_nodes = 0;
67// The total number of calls to Free_list::remove.
68unsigned int Free_list::num_removes = 0;
69// The total number of nodes visited during calls to Free_list::remove.
70unsigned int Free_list::num_remove_visits = 0;
71// The total number of calls to Free_list::allocate.
72unsigned int Free_list::num_allocates = 0;
73// The total number of nodes visited during calls to Free_list::allocate.
74unsigned int Free_list::num_allocate_visits = 0;
75
76// Initialize the free list. Creates a single free list node that
77// describes the entire region of length LEN. If EXTEND is true,
78// allocate() is allowed to extend the region beyond its initial
79// length.
80
81void
82Free_list::init(off_t len, bool extend)
83{
84 this->list_.push_front(Free_list_node(0, len));
85 this->last_remove_ = this->list_.begin();
86 this->extend_ = extend;
87 this->length_ = len;
88 ++Free_list::num_lists;
89 ++Free_list::num_nodes;
90}
91
92// Remove a chunk from the free list. Because we start with a single
93// node that covers the entire section, and remove chunks from it one
94// at a time, we do not need to coalesce chunks or handle cases that
95// span more than one free node. We expect to remove chunks from the
96// free list in order, and we expect to have only a few chunks of free
97// space left (corresponding to files that have changed since the last
98// incremental link), so a simple linear list should provide sufficient
99// performance.
100
101void
102Free_list::remove(off_t start, off_t end)
103{
104 if (start == end)
105 return;
106 gold_assert(start < end);
107
108 ++Free_list::num_removes;
109
110 Iterator p = this->last_remove_;
111 if (p->start_ > start)
112 p = this->list_.begin();
113
114 for (; p != this->list_.end(); ++p)
115 {
116 ++Free_list::num_remove_visits;
117 // Find a node that wholly contains the indicated region.
118 if (p->start_ <= start && p->end_ >= end)
119 {
120 // Case 1: the indicated region spans the whole node.
121 // Add some fuzz to avoid creating tiny free chunks.
122 if (p->start_ + 3 >= start && p->end_ <= end + 3)
123 p = this->list_.erase(p);
124 // Case 2: remove a chunk from the start of the node.
125 else if (p->start_ + 3 >= start)
126 p->start_ = end;
127 // Case 3: remove a chunk from the end of the node.
128 else if (p->end_ <= end + 3)
129 p->end_ = start;
130 // Case 4: remove a chunk from the middle, and split
131 // the node into two.
132 else
133 {
134 Free_list_node newnode(p->start_, start);
135 p->start_ = end;
136 this->list_.insert(p, newnode);
137 ++Free_list::num_nodes;
138 }
139 this->last_remove_ = p;
140 return;
141 }
142 }
143
144 // Did not find a node containing the given chunk. This could happen
145 // because a small chunk was already removed due to the fuzz.
146 gold_debug(DEBUG_INCREMENTAL,
147 "Free_list::remove(%d,%d) not found",
148 static_cast<int>(start), static_cast<int>(end));
149}
150
151// Allocate a chunk of size LEN from the free list. Returns -1ULL
152// if a sufficiently large chunk of free space is not found.
153// We use a simple first-fit algorithm.
154
155off_t
156Free_list::allocate(off_t len, uint64_t align, off_t minoff)
157{
158 gold_debug(DEBUG_INCREMENTAL,
2e702c99
RM
159 "Free_list::allocate(%08lx, %d, %08lx)",
160 static_cast<long>(len), static_cast<int>(align),
161 static_cast<long>(minoff));
cdc29364
CC
162 if (len == 0)
163 return align_address(minoff, align);
164
165 ++Free_list::num_allocates;
166
8ea8cd50
CC
167 // We usually want to drop free chunks smaller than 4 bytes.
168 // If we need to guarantee a minimum hole size, though, we need
169 // to keep track of all free chunks.
170 const int fuzz = this->min_hole_ > 0 ? 0 : 3;
171
cdc29364
CC
172 for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
173 {
174 ++Free_list::num_allocate_visits;
175 off_t start = p->start_ > minoff ? p->start_ : minoff;
176 start = align_address(start, align);
177 off_t end = start + len;
9fbd3822
CC
178 if (end > p->end_ && p->end_ == this->length_ && this->extend_)
179 {
180 this->length_ = end;
181 p->end_ = end;
182 }
8ea8cd50 183 if (end == p->end_ || (end <= p->end_ - this->min_hole_))
cdc29364 184 {
8ea8cd50 185 if (p->start_ + fuzz >= start && p->end_ <= end + fuzz)
cdc29364 186 this->list_.erase(p);
8ea8cd50 187 else if (p->start_ + fuzz >= start)
cdc29364 188 p->start_ = end;
8ea8cd50 189 else if (p->end_ <= end + fuzz)
cdc29364
CC
190 p->end_ = start;
191 else
192 {
193 Free_list_node newnode(p->start_, start);
194 p->start_ = end;
195 this->list_.insert(p, newnode);
196 ++Free_list::num_nodes;
197 }
198 return start;
199 }
200 }
9fbd3822
CC
201 if (this->extend_)
202 {
203 off_t start = align_address(this->length_, align);
204 this->length_ = start + len;
205 return start;
206 }
cdc29364
CC
207 return -1;
208}
209
210// Dump the free list (for debugging).
211void
212Free_list::dump()
213{
214 gold_info("Free list:\n start end length\n");
215 for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
216 gold_info(" %08lx %08lx %08lx", static_cast<long>(p->start_),
217 static_cast<long>(p->end_),
218 static_cast<long>(p->end_ - p->start_));
219}
220
221// Print the statistics for the free lists.
222void
223Free_list::print_stats()
224{
225 fprintf(stderr, _("%s: total free lists: %u\n"),
2e702c99 226 program_name, Free_list::num_lists);
cdc29364 227 fprintf(stderr, _("%s: total free list nodes: %u\n"),
2e702c99 228 program_name, Free_list::num_nodes);
cdc29364 229 fprintf(stderr, _("%s: calls to Free_list::remove: %u\n"),
2e702c99 230 program_name, Free_list::num_removes);
cdc29364 231 fprintf(stderr, _("%s: nodes visited: %u\n"),
2e702c99 232 program_name, Free_list::num_remove_visits);
cdc29364 233 fprintf(stderr, _("%s: calls to Free_list::allocate: %u\n"),
2e702c99 234 program_name, Free_list::num_allocates);
cdc29364 235 fprintf(stderr, _("%s: nodes visited: %u\n"),
2e702c99 236 program_name, Free_list::num_allocate_visits);
cdc29364
CC
237}
238
20e6d0d6
DK
239// Layout::Relaxation_debug_check methods.
240
241// Check that sections and special data are in reset states.
242// We do not save states for Output_sections and special Output_data.
243// So we check that they have not assigned any addresses or offsets.
244// clean_up_after_relaxation simply resets their addresses and offsets.
245void
246Layout::Relaxation_debug_check::check_output_data_for_reset_values(
247 const Layout::Section_list& sections,
248 const Layout::Data_list& special_outputs)
249{
250 for(Layout::Section_list::const_iterator p = sections.begin();
251 p != sections.end();
252 ++p)
253 gold_assert((*p)->address_and_file_offset_have_reset_values());
254
255 for(Layout::Data_list::const_iterator p = special_outputs.begin();
256 p != special_outputs.end();
257 ++p)
258 gold_assert((*p)->address_and_file_offset_have_reset_values());
259}
2e702c99 260
20e6d0d6
DK
261// Save information of SECTIONS for checking later.
262
263void
264Layout::Relaxation_debug_check::read_sections(
265 const Layout::Section_list& sections)
266{
267 for(Layout::Section_list::const_iterator p = sections.begin();
268 p != sections.end();
269 ++p)
270 {
271 Output_section* os = *p;
272 Section_info info;
273 info.output_section = os;
274 info.address = os->is_address_valid() ? os->address() : 0;
275 info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
276 info.offset = os->is_offset_valid()? os->offset() : -1 ;
277 this->section_infos_.push_back(info);
278 }
279}
280
281// Verify SECTIONS using previously recorded information.
282
283void
284Layout::Relaxation_debug_check::verify_sections(
285 const Layout::Section_list& sections)
286{
287 size_t i = 0;
288 for(Layout::Section_list::const_iterator p = sections.begin();
289 p != sections.end();
290 ++p, ++i)
291 {
292 Output_section* os = *p;
293 uint64_t address = os->is_address_valid() ? os->address() : 0;
294 off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
295 off_t offset = os->is_offset_valid()? os->offset() : -1 ;
296
297 if (i >= this->section_infos_.size())
298 {
299 gold_fatal("Section_info of %s missing.\n", os->name());
300 }
301 const Section_info& info = this->section_infos_[i];
302 if (os != info.output_section)
303 gold_fatal("Section order changed. Expecting %s but see %s\n",
304 info.output_section->name(), os->name());
305 if (address != info.address
306 || data_size != info.data_size
307 || offset != info.offset)
308 gold_fatal("Section %s changed.\n", os->name());
309 }
310}
311
92e059d8 312// Layout_task_runner methods.
a2fb1b05
ILT
313
314// Lay out the sections. This is called after all the input objects
315// have been read.
316
317void
17a1d0a9 318Layout_task_runner::run(Workqueue* workqueue, const Task* task)
a2fb1b05 319{
94a3fc8b
CC
320 Layout* layout = this->layout_;
321 off_t file_size = layout->finalize(this->input_objects_,
322 this->symtab_,
2e702c99 323 this->target_,
94a3fc8b 324 task);
61ba1cf9
ILT
325
326 // Now we know the final size of the output file and we know where
327 // each piece of information goes.
7d9e3d98
ILT
328
329 if (this->mapfile_ != NULL)
330 {
331 this->mapfile_->print_discarded_sections(this->input_objects_);
94a3fc8b 332 layout->print_to_mapfile(this->mapfile_);
7d9e3d98
ILT
333 }
334
cdc29364 335 Output_file* of;
94a3fc8b 336 if (layout->incremental_base() == NULL)
cdc29364
CC
337 {
338 of = new Output_file(parameters->options().output_file_name());
339 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
340 of->set_is_temporary();
341 of->open(file_size);
342 }
343 else
344 {
94a3fc8b
CC
345 of = layout->incremental_base()->output_file();
346
347 // Apply the incremental relocations for symbols whose values
348 // have changed. We do this before we resize the file and start
349 // writing anything else to it, so that we can read the old
350 // incremental information from the file before (possibly)
351 // overwriting it.
352 if (parameters->incremental_update())
2e702c99
RM
353 layout->incremental_base()->apply_incremental_relocs(this->symtab_,
354 this->layout_,
94a3fc8b
CC
355 of);
356
cdc29364
CC
357 of->resize(file_size);
358 }
61ba1cf9
ILT
359
360 // Queue up the final set of tasks.
361 gold::queue_final_tasks(this->options_, this->input_objects_,
94a3fc8b 362 this->symtab_, layout, workqueue, of);
a2fb1b05
ILT
363}
364
365// Layout methods.
366
2ea97941 367Layout::Layout(int number_of_input_files, Script_options* script_options)
e55bde5e 368 : number_of_input_files_(number_of_input_files),
2ea97941 369 script_options_(script_options),
d491d34e
ILT
370 namepool_(),
371 sympool_(),
372 dynpool_(),
373 signatures_(),
374 section_name_map_(),
375 segment_list_(),
376 section_list_(),
377 unattached_section_list_(),
d491d34e
ILT
378 special_output_list_(),
379 section_headers_(NULL),
380 tls_segment_(NULL),
9f1d377b 381 relro_segment_(NULL),
10b4f102 382 interp_segment_(NULL),
1a2dff53 383 increase_relro_(0),
d491d34e
ILT
384 symtab_section_(NULL),
385 symtab_xindex_(NULL),
386 dynsym_section_(NULL),
387 dynsym_xindex_(NULL),
388 dynamic_section_(NULL),
f0ba79e2 389 dynamic_symbol_(NULL),
d491d34e
ILT
390 dynamic_data_(NULL),
391 eh_frame_section_(NULL),
392 eh_frame_data_(NULL),
393 added_eh_frame_data_(false),
394 eh_frame_hdr_section_(NULL),
c1027032 395 gdb_index_data_(NULL),
d491d34e 396 build_id_note_(NULL),
62b01cb5
ILT
397 debug_abbrev_(NULL),
398 debug_info_(NULL),
d491d34e
ILT
399 group_signatures_(),
400 output_file_size_(-1),
d7bb5745 401 have_added_input_section_(false),
e55bde5e 402 sections_are_attached_(false),
35cdfc9a
ILT
403 input_requires_executable_stack_(false),
404 input_with_gnu_stack_note_(false),
535890bb 405 input_without_gnu_stack_note_(false),
17a1d0a9 406 has_static_tls_(false),
e55bde5e 407 any_postprocessing_sections_(false),
3ce2c28e 408 resized_signatures_(false),
1518dc8f 409 have_stabstr_section_(false),
e9552f7e 410 section_ordering_specified_(false),
16164a6b 411 unique_segment_for_sections_specified_(false),
20e6d0d6
DK
412 incremental_inputs_(NULL),
413 record_output_section_data_from_script_(false),
414 script_output_section_data_list_(),
415 segment_states_(NULL),
cdc29364 416 relaxation_debug_check_(NULL),
f0558624 417 section_order_map_(),
16164a6b 418 section_segment_map_(),
e9552f7e
ST
419 input_section_position_(),
420 input_section_glob_(),
cdc29364
CC
421 incremental_base_(NULL),
422 free_list_()
54dc6425
ILT
423{
424 // Make space for more than enough segments for a typical file.
425 // This is just for efficiency--it's OK if we wind up needing more.
a3ad94ed
ILT
426 this->segment_list_.reserve(12);
427
27bc2bce
ILT
428 // We expect two unattached Output_data objects: the file header and
429 // the segment headers.
430 this->special_output_list_.reserve(2);
3ce2c28e
ILT
431
432 // Initialize structure needed for an incremental build.
8c21d9d3 433 if (parameters->incremental())
3ce2c28e 434 this->incremental_inputs_ = new Incremental_inputs;
f7c8a183
ILT
435
436 // The section name pool is worth optimizing in all cases, because
437 // it is small, but there are often overlaps due to .rel sections.
438 this->namepool_.set_optimize();
54dc6425
ILT
439}
440
cdc29364
CC
441// For incremental links, record the base file to be modified.
442
443void
444Layout::set_incremental_base(Incremental_binary* base)
445{
446 this->incremental_base_ = base;
447 this->free_list_.init(base->output_file()->filesize(), true);
448}
449
a2fb1b05
ILT
450// Hash a key we use to look up an output section mapping.
451
452size_t
453Layout::Hash_key::operator()(const Layout::Key& k) const
454{
f0641a0b 455 return k.first + k.second.first + k.second.second;
a2fb1b05
ILT
456}
457
fb1b895d
CC
458// These are the debug sections that are actually used by gdb.
459// Currently, we've checked versions of gdb up to and including 7.4.
460// We only check the part of the name that follows ".debug_" or
461// ".zdebug_".
02d2ba74
ILT
462
463static const char* gdb_sections[] =
fb1b895d
CC
464{
465 "abbrev",
466 "addr", // Fission extension
467 // "aranges", // not used by gdb as of 7.4
468 "frame",
469 "info",
470 "types",
471 "line",
472 "loc",
473 "macinfo",
474 "macro",
475 // "pubnames", // not used by gdb as of 7.4
476 // "pubtypes", // not used by gdb as of 7.4
477 "ranges",
478 "str",
02d2ba74
ILT
479};
480
fb1b895d
CC
481// This is the minimum set of sections needed for line numbers.
482
62b01cb5 483static const char* lines_only_debug_sections[] =
fb1b895d
CC
484{
485 "abbrev",
486 // "addr", // Fission extension
487 // "aranges", // not used by gdb as of 7.4
488 // "frame",
489 "info",
490 // "types",
491 "line",
492 // "loc",
493 // "macinfo",
494 // "macro",
495 // "pubnames", // not used by gdb as of 7.4
496 // "pubtypes", // not used by gdb as of 7.4
497 // "ranges",
498 "str",
499};
500
501// These sections are the DWARF fast-lookup tables, and are not needed
502// when building a .gdb_index section.
503
504static const char* gdb_fast_lookup_sections[] =
505{
506 "aranges",
507 "pubnames",
508 "pubtypes",
62b01cb5
ILT
509};
510
fb1b895d
CC
511// Returns whether the given debug section is in the list of
512// debug-sections-used-by-some-version-of-gdb. SUFFIX is the
513// portion of the name following ".debug_" or ".zdebug_".
514
02d2ba74 515static inline bool
fb1b895d 516is_gdb_debug_section(const char* suffix)
02d2ba74
ILT
517{
518 // We can do this faster: binary search or a hashtable. But why bother?
519 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
fb1b895d 520 if (strcmp(suffix, gdb_sections[i]) == 0)
02d2ba74
ILT
521 return true;
522 return false;
523}
524
fb1b895d
CC
525// Returns whether the given section is needed for lines-only debugging.
526
62b01cb5 527static inline bool
fb1b895d 528is_lines_only_debug_section(const char* suffix)
62b01cb5
ILT
529{
530 // We can do this faster: binary search or a hashtable. But why bother?
531 for (size_t i = 0;
532 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
533 ++i)
fb1b895d
CC
534 if (strcmp(suffix, lines_only_debug_sections[i]) == 0)
535 return true;
536 return false;
537}
538
539// Returns whether the given section is a fast-lookup section that
540// will not be needed when building a .gdb_index section.
541
542static inline bool
543is_gdb_fast_lookup_section(const char* suffix)
544{
545 // We can do this faster: binary search or a hashtable. But why bother?
546 for (size_t i = 0;
547 i < sizeof(gdb_fast_lookup_sections)/sizeof(*gdb_fast_lookup_sections);
548 ++i)
549 if (strcmp(suffix, gdb_fast_lookup_sections[i]) == 0)
62b01cb5
ILT
550 return true;
551 return false;
552}
553
6fc6ea19
CC
554// Sometimes we compress sections. This is typically done for
555// sections that are not part of normal program execution (such as
556// .debug_* sections), and where the readers of these sections know
557// how to deal with compressed sections. This routine doesn't say for
558// certain whether we'll compress -- it depends on commandline options
559// as well -- just whether this section is a candidate for compression.
560// (The Output_compressed_section class decides whether to compress
561// a given section, and picks the name of the compressed section.)
562
563static bool
564is_compressible_debug_section(const char* secname)
565{
566 return (is_prefix_of(".debug", secname));
567}
568
569// We may see compressed debug sections in input files. Return TRUE
570// if this is the name of a compressed debug section.
571
572bool
573is_compressed_debug_section(const char* secname)
574{
575 return (is_prefix_of(".zdebug", secname));
576}
577
a2fb1b05
ILT
578// Whether to include this section in the link.
579
580template<int size, bool big_endian>
581bool
6fa2a40b 582Layout::include_section(Sized_relobj_file<size, big_endian>*, const char* name,
a2fb1b05
ILT
583 const elfcpp::Shdr<size, big_endian>& shdr)
584{
ae034989
ST
585 if (!parameters->options().relocatable()
586 && (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE))
fd06b4aa
CC
587 return false;
588
a2fb1b05
ILT
589 switch (shdr.get_sh_type())
590 {
591 case elfcpp::SHT_NULL:
592 case elfcpp::SHT_SYMTAB:
593 case elfcpp::SHT_DYNSYM:
a2fb1b05
ILT
594 case elfcpp::SHT_HASH:
595 case elfcpp::SHT_DYNAMIC:
596 case elfcpp::SHT_SYMTAB_SHNDX:
597 return false;
598
5cb66f97
ILT
599 case elfcpp::SHT_STRTAB:
600 // Discard the sections which have special meanings in the ELF
601 // ABI. Keep others (e.g., .stabstr). We could also do this by
602 // checking the sh_link fields of the appropriate sections.
603 return (strcmp(name, ".dynstr") != 0
604 && strcmp(name, ".strtab") != 0
605 && strcmp(name, ".shstrtab") != 0);
606
a2fb1b05
ILT
607 case elfcpp::SHT_RELA:
608 case elfcpp::SHT_REL:
609 case elfcpp::SHT_GROUP:
7019cd25
ILT
610 // If we are emitting relocations these should be handled
611 // elsewhere.
1e2bee4f 612 gold_assert(!parameters->options().relocatable());
6a74a719 613 return false;
a2fb1b05 614
9e2dcb77 615 case elfcpp::SHT_PROGBITS:
8851ecca 616 if (parameters->options().strip_debug()
9e2dcb77
ILT
617 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
618 {
e94cf127 619 if (is_debug_info_section(name))
9e2dcb77
ILT
620 return false;
621 }
62b01cb5
ILT
622 if (parameters->options().strip_debug_non_line()
623 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
624 {
625 // Debugging sections can only be recognized by name.
fb1b895d
CC
626 if (is_prefix_of(".debug_", name)
627 && !is_lines_only_debug_section(name + 7))
628 return false;
629 if (is_prefix_of(".zdebug_", name)
630 && !is_lines_only_debug_section(name + 8))
62b01cb5
ILT
631 return false;
632 }
8851ecca 633 if (parameters->options().strip_debug_gdb()
02d2ba74
ILT
634 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
635 {
636 // Debugging sections can only be recognized by name.
fb1b895d
CC
637 if (is_prefix_of(".debug_", name)
638 && !is_gdb_debug_section(name + 7))
639 return false;
640 if (is_prefix_of(".zdebug_", name)
641 && !is_gdb_debug_section(name + 8))
642 return false;
643 }
644 if (parameters->options().gdb_index()
645 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
646 {
647 // When building .gdb_index, we can strip .debug_pubnames,
648 // .debug_pubtypes, and .debug_aranges sections.
649 if (is_prefix_of(".debug_", name)
650 && is_gdb_fast_lookup_section(name + 7))
651 return false;
652 if (is_prefix_of(".zdebug_", name)
653 && is_gdb_fast_lookup_section(name + 8))
02d2ba74
ILT
654 return false;
655 }
fd06b4aa 656 if (parameters->options().strip_lto_sections()
2e702c99
RM
657 && !parameters->options().relocatable()
658 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
659 {
660 // Ignore LTO sections containing intermediate code.
661 if (is_prefix_of(".gnu.lto_", name))
662 return false;
663 }
6b7dd3f3
ILT
664 // The GNU linker strips .gnu_debuglink sections, so we do too.
665 // This is a feature used to keep debugging information in
666 // separate files.
667 if (strcmp(name, ".gnu_debuglink") == 0)
668 return false;
9e2dcb77
ILT
669 return true;
670
a2fb1b05 671 default:
a2fb1b05
ILT
672 return true;
673 }
674}
675
ead1e424 676// Return an output section named NAME, or NULL if there is none.
a2fb1b05 677
a2fb1b05 678Output_section*
ead1e424 679Layout::find_output_section(const char* name) const
a2fb1b05 680{
a445fddf
ILT
681 for (Section_list::const_iterator p = this->section_list_.begin();
682 p != this->section_list_.end();
ead1e424 683 ++p)
a445fddf
ILT
684 if (strcmp((*p)->name(), name) == 0)
685 return *p;
ead1e424
ILT
686 return NULL;
687}
a2fb1b05 688
ead1e424
ILT
689// Return an output segment of type TYPE, with segment flags SET set
690// and segment flags CLEAR clear. Return NULL if there is none.
a2fb1b05 691
ead1e424
ILT
692Output_segment*
693Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
694 elfcpp::Elf_Word clear) const
695{
696 for (Segment_list::const_iterator p = this->segment_list_.begin();
697 p != this->segment_list_.end();
698 ++p)
699 if (static_cast<elfcpp::PT>((*p)->type()) == type
700 && ((*p)->flags() & set) == set
701 && ((*p)->flags() & clear) == 0)
702 return *p;
703 return NULL;
704}
a2fb1b05 705
487b39df
ILT
706// When we put a .ctors or .dtors section with more than one word into
707// a .init_array or .fini_array section, we need to reverse the words
708// in the .ctors/.dtors section. This is because .init_array executes
709// constructors front to back, where .ctors executes them back to
710// front, and vice-versa for .fini_array/.dtors. Although we do want
711// to remap .ctors/.dtors into .init_array/.fini_array because it can
712// be more efficient, we don't want to change the order in which
713// constructors/destructors are run. This set just keeps track of
714// these sections which need to be reversed. It is only changed by
715// Layout::layout. It should be a private member of Layout, but that
716// would require layout.h to #include object.h to get the definition
717// of Section_id.
718static Unordered_set<Section_id, Section_id_hash> ctors_sections_in_init_array;
719
720// Return whether OBJECT/SHNDX is a .ctors/.dtors section mapped to a
721// .init_array/.fini_array section.
722
723bool
724Layout::is_ctors_in_init_array(Relobj* relobj, unsigned int shndx) const
725{
726 return (ctors_sections_in_init_array.find(Section_id(relobj, shndx))
727 != ctors_sections_in_init_array.end());
728}
729
ead1e424 730// Return the output section to use for section NAME with type TYPE
a445fddf 731// and section flags FLAGS. NAME must be canonicalized in the string
10b4f102
ILT
732// pool, and NAME_KEY is the key. ORDER is where this should appear
733// in the output sections. IS_RELRO is true for a relro section.
a2fb1b05 734
ead1e424 735Output_section*
f0641a0b 736Layout::get_output_section(const char* name, Stringpool::Key name_key,
f5c870d2 737 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
22f0da72 738 Output_section_order order, bool is_relro)
ead1e424 739{
5393d741
ILT
740 elfcpp::Elf_Word lookup_type = type;
741
742 // For lookup purposes, treat INIT_ARRAY, FINI_ARRAY, and
743 // PREINIT_ARRAY like PROGBITS. This ensures that we combine
744 // .init_array, .fini_array, and .preinit_array sections by name
745 // whatever their type in the input file. We do this because the
746 // types are not always right in the input files.
747 if (lookup_type == elfcpp::SHT_INIT_ARRAY
748 || lookup_type == elfcpp::SHT_FINI_ARRAY
749 || lookup_type == elfcpp::SHT_PREINIT_ARRAY)
750 lookup_type = elfcpp::SHT_PROGBITS;
751
154e0e9a
ILT
752 elfcpp::Elf_Xword lookup_flags = flags;
753
754 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
755 // read-write with read-only sections. Some other ELF linkers do
756 // not do this. FIXME: Perhaps there should be an option
757 // controlling this.
758 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
759
5393d741 760 const Key key(name_key, std::make_pair(lookup_type, lookup_flags));
a2fb1b05
ILT
761 const std::pair<Key, Output_section*> v(key, NULL);
762 std::pair<Section_name_map::iterator, bool> ins(
763 this->section_name_map_.insert(v));
764
a2fb1b05 765 if (!ins.second)
ead1e424 766 return ins.first->second;
a2fb1b05
ILT
767 else
768 {
769 // This is the first time we've seen this name/type/flags
4e2b1697
ILT
770 // combination. For compatibility with the GNU linker, we
771 // combine sections with contents and zero flags with sections
772 // with non-zero flags. This is a workaround for cases where
773 // assembler code forgets to set section flags. FIXME: Perhaps
774 // there should be an option to control this.
15cf077e 775 Output_section* os = NULL;
4e2b1697 776
5393d741 777 if (lookup_type == elfcpp::SHT_PROGBITS)
15cf077e 778 {
2e702c99
RM
779 if (flags == 0)
780 {
781 Output_section* same_name = this->find_output_section(name);
782 if (same_name != NULL
783 && (same_name->type() == elfcpp::SHT_PROGBITS
5393d741
ILT
784 || same_name->type() == elfcpp::SHT_INIT_ARRAY
785 || same_name->type() == elfcpp::SHT_FINI_ARRAY
786 || same_name->type() == elfcpp::SHT_PREINIT_ARRAY)
2e702c99
RM
787 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
788 os = same_name;
789 }
790 else if ((flags & elfcpp::SHF_TLS) == 0)
791 {
792 elfcpp::Elf_Xword zero_flags = 0;
793 const Key zero_key(name_key, std::make_pair(lookup_type,
5393d741 794 zero_flags));
2e702c99
RM
795 Section_name_map::iterator p =
796 this->section_name_map_.find(zero_key);
797 if (p != this->section_name_map_.end())
154e0e9a 798 os = p->second;
2e702c99 799 }
15cf077e 800 }
4e2b1697 801
15cf077e 802 if (os == NULL)
22f0da72
ILT
803 os = this->make_output_section(name, type, flags, order, is_relro);
804
a2fb1b05 805 ins.first->second = os;
ead1e424 806 return os;
a2fb1b05 807 }
ead1e424
ILT
808}
809
b9b2ae8b
NC
810// Returns TRUE iff NAME (an input section from RELOBJ) will
811// be mapped to an output section that should be KEPT.
812
813bool
814Layout::keep_input_section(const Relobj* relobj, const char* name)
815{
816 if (! this->script_options_->saw_sections_clause())
817 return false;
818
819 Script_sections* ss = this->script_options_->script_sections();
820 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
821 Output_section** output_section_slot;
822 Script_sections::Section_type script_section_type;
823 bool keep;
824
825 name = ss->output_section_name(file_name, name, &output_section_slot,
826 &script_section_type, &keep);
827 return name != NULL && keep;
828}
829
16164a6b
ST
830// Clear the input section flags that should not be copied to the
831// output section.
832
833elfcpp::Elf_Xword
834Layout::get_output_section_flags(elfcpp::Elf_Xword input_section_flags)
835{
836 // Some flags in the input section should not be automatically
837 // copied to the output section.
838 input_section_flags &= ~ (elfcpp::SHF_INFO_LINK
839 | elfcpp::SHF_GROUP
840 | elfcpp::SHF_MERGE
841 | elfcpp::SHF_STRINGS);
842
843 // We only clear the SHF_LINK_ORDER flag in for
844 // a non-relocatable link.
845 if (!parameters->options().relocatable())
846 input_section_flags &= ~elfcpp::SHF_LINK_ORDER;
847
848 return input_section_flags;
849}
850
a445fddf
ILT
851// Pick the output section to use for section NAME, in input file
852// RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
154e0e9a
ILT
853// linker created section. IS_INPUT_SECTION is true if we are
854// choosing an output section for an input section found in a input
10b4f102
ILT
855// file. ORDER is where this section should appear in the output
856// sections. IS_RELRO is true for a relro section. This will return
857// NULL if the input section should be discarded.
a445fddf
ILT
858
859Output_section*
860Layout::choose_output_section(const Relobj* relobj, const char* name,
861 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
22f0da72
ILT
862 bool is_input_section, Output_section_order order,
863 bool is_relro)
a445fddf 864{
154e0e9a
ILT
865 // We should not see any input sections after we have attached
866 // sections to segments.
867 gold_assert(!is_input_section || !this->sections_are_attached_);
868
16164a6b 869 flags = this->get_output_section_flags(flags);
c9484ea5 870
a445fddf
ILT
871 if (this->script_options_->saw_sections_clause())
872 {
873 // We are using a SECTIONS clause, so the output section is
874 // chosen based only on the name.
875
876 Script_sections* ss = this->script_options_->script_sections();
877 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
878 Output_section** output_section_slot;
1e5d2fb1 879 Script_sections::Section_type script_section_type;
7f8cd844 880 const char* orig_name = name;
b9b2ae8b 881 bool keep;
1e5d2fb1 882 name = ss->output_section_name(file_name, name, &output_section_slot,
b9b2ae8b
NC
883 &script_section_type, &keep);
884
a445fddf
ILT
885 if (name == NULL)
886 {
7f8cd844
NC
887 gold_debug(DEBUG_SCRIPT, _("Unable to create output section '%s' "
888 "because it is not allowed by the "
889 "SECTIONS clause of the linker script"),
890 orig_name);
a445fddf
ILT
891 // The SECTIONS clause says to discard this input section.
892 return NULL;
893 }
894
1e5d2fb1
DK
895 // We can only handle script section types ST_NONE and ST_NOLOAD.
896 switch (script_section_type)
897 {
898 case Script_sections::ST_NONE:
899 break;
900 case Script_sections::ST_NOLOAD:
901 flags &= elfcpp::SHF_ALLOC;
902 break;
903 default:
904 gold_unreachable();
905 }
906
a445fddf
ILT
907 // If this is an orphan section--one not mentioned in the linker
908 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
909 // default processing below.
910
911 if (output_section_slot != NULL)
912 {
913 if (*output_section_slot != NULL)
9c547ec3
ILT
914 {
915 (*output_section_slot)->update_flags_for_input_section(flags);
916 return *output_section_slot;
917 }
a445fddf
ILT
918
919 // We don't put sections found in the linker script into
920 // SECTION_NAME_MAP_. That keeps us from getting confused
921 // if an orphan section is mapped to a section with the same
922 // name as one in the linker script.
923
924 name = this->namepool_.add(name, false, NULL);
925
22f0da72
ILT
926 Output_section* os = this->make_output_section(name, type, flags,
927 order, is_relro);
928
a445fddf 929 os->set_found_in_sections_clause();
1e5d2fb1
DK
930
931 // Special handling for NOLOAD sections.
932 if (script_section_type == Script_sections::ST_NOLOAD)
933 {
934 os->set_is_noload();
935
936 // The constructor of Output_section sets addresses of non-ALLOC
937 // sections to 0 by default. We don't want that for NOLOAD
938 // sections even if they have no SHF_ALLOC flag.
939 if ((os->flags() & elfcpp::SHF_ALLOC) == 0
940 && os->is_address_valid())
941 {
942 gold_assert(os->address() == 0
943 && !os->is_offset_valid()
944 && !os->is_data_size_valid());
945 os->reset_address_and_file_offset();
946 }
947 }
948
a445fddf
ILT
949 *output_section_slot = os;
950 return os;
951 }
952 }
953
954 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
955
6fc6ea19
CC
956 size_t len = strlen(name);
957 char* uncompressed_name = NULL;
958
959 // Compressed debug sections should be mapped to the corresponding
960 // uncompressed section.
961 if (is_compressed_debug_section(name))
962 {
963 uncompressed_name = new char[len];
964 uncompressed_name[0] = '.';
965 gold_assert(name[0] == '.' && name[1] == 'z');
966 strncpy(&uncompressed_name[1], &name[2], len - 2);
967 uncompressed_name[len - 1] = '\0';
968 len -= 1;
969 name = uncompressed_name;
970 }
971
a445fddf
ILT
972 // Turn NAME from the name of the input section into the name of the
973 // output section.
401a9a73
CC
974 if (is_input_section
975 && !this->script_options_->saw_sections_clause()
976 && !parameters->options().relocatable())
921b5322
AM
977 {
978 const char *orig_name = name;
979 name = parameters->target().output_section_name(relobj, name, &len);
980 if (name == NULL)
981 name = Layout::output_section_name(relobj, orig_name, &len);
982 }
a445fddf
ILT
983
984 Stringpool::Key name_key;
985 name = this->namepool_.add_with_length(name, len, true, &name_key);
986
6fc6ea19
CC
987 if (uncompressed_name != NULL)
988 delete[] uncompressed_name;
989
a445fddf
ILT
990 // Find or make the output section. The output section is selected
991 // based on the section name, type, and flags.
22f0da72 992 return this->get_output_section(name, name_key, type, flags, order, is_relro);
a445fddf
ILT
993}
994
cdc29364
CC
995// For incremental links, record the initial fixed layout of a section
996// from the base file, and return a pointer to the Output_section.
997
998template<int size, bool big_endian>
999Output_section*
1000Layout::init_fixed_output_section(const char* name,
1001 elfcpp::Shdr<size, big_endian>& shdr)
1002{
1003 unsigned int sh_type = shdr.get_sh_type();
1004
aa06ae28
CC
1005 // We preserve the layout of PROGBITS, NOBITS, INIT_ARRAY, FINI_ARRAY,
1006 // PRE_INIT_ARRAY, and NOTE sections.
cdc29364 1007 // All others will be created from scratch and reallocated.
aa06ae28 1008 if (!can_incremental_update(sh_type))
cdc29364
CC
1009 return NULL;
1010
c1027032
CC
1011 // If we're generating a .gdb_index section, we need to regenerate
1012 // it from scratch.
1013 if (parameters->options().gdb_index()
1014 && sh_type == elfcpp::SHT_PROGBITS
1015 && strcmp(name, ".gdb_index") == 0)
1016 return NULL;
1017
cdc29364
CC
1018 typename elfcpp::Elf_types<size>::Elf_Addr sh_addr = shdr.get_sh_addr();
1019 typename elfcpp::Elf_types<size>::Elf_Off sh_offset = shdr.get_sh_offset();
1020 typename elfcpp::Elf_types<size>::Elf_WXword sh_size = shdr.get_sh_size();
1021 typename elfcpp::Elf_types<size>::Elf_WXword sh_flags = shdr.get_sh_flags();
1022 typename elfcpp::Elf_types<size>::Elf_WXword sh_addralign =
1023 shdr.get_sh_addralign();
1024
1025 // Make the output section.
1026 Stringpool::Key name_key;
1027 name = this->namepool_.add(name, true, &name_key);
1028 Output_section* os = this->get_output_section(name, name_key, sh_type,
2e702c99 1029 sh_flags, ORDER_INVALID, false);
cdc29364
CC
1030 os->set_fixed_layout(sh_addr, sh_offset, sh_size, sh_addralign);
1031 if (sh_type != elfcpp::SHT_NOBITS)
1032 this->free_list_.remove(sh_offset, sh_offset + sh_size);
1033 return os;
1034}
1035
edcac0c1
ILT
1036// Return the index by which an input section should be ordered. This
1037// is used to sort some .text sections, for compatibility with GNU ld.
1038
1039int
1040Layout::special_ordering_of_input_section(const char* name)
1041{
1042 // The GNU linker has some special handling for some sections that
1043 // wind up in the .text section. Sections that start with these
1044 // prefixes must appear first, and must appear in the order listed
1045 // here.
1046 static const char* const text_section_sort[] =
1047 {
1048 ".text.unlikely",
1049 ".text.exit",
1050 ".text.startup",
1051 ".text.hot"
1052 };
1053
1054 for (size_t i = 0;
1055 i < sizeof(text_section_sort) / sizeof(text_section_sort[0]);
1056 i++)
1057 if (is_prefix_of(text_section_sort[i], name))
1058 return i;
1059
1060 return -1;
1061}
1062
ead1e424 1063// Return the output section to use for input section SHNDX, with name
730cdc88
ILT
1064// NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
1065// index of a relocation section which applies to this section, or 0
1066// if none, or -1U if more than one. RELOC_TYPE is the type of the
1067// relocation section if there is one. Set *OFF to the offset of this
1068// input section without the output section. Return NULL if the
1069// section should be discarded. Set *OFF to -1 if the section
1070// contents should not be written directly to the output file, but
1071// will instead receive special handling.
ead1e424
ILT
1072
1073template<int size, bool big_endian>
1074Output_section*
6fa2a40b 1075Layout::layout(Sized_relobj_file<size, big_endian>* object, unsigned int shndx,
730cdc88
ILT
1076 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
1077 unsigned int reloc_shndx, unsigned int, off_t* off)
ead1e424 1078{
ef9beddf
ILT
1079 *off = 0;
1080
ead1e424
ILT
1081 if (!this->include_section(object, name, shdr))
1082 return NULL;
1083
2a0ff005 1084 elfcpp::Elf_Word sh_type = shdr.get_sh_type();
2a0ff005 1085
6a74a719
ILT
1086 // In a relocatable link a grouped section must not be combined with
1087 // any other sections.
5393d741 1088 Output_section* os;
8851ecca 1089 if (parameters->options().relocatable()
6a74a719
ILT
1090 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
1091 {
1092 name = this->namepool_.add(name, true, NULL);
22f0da72
ILT
1093 os = this->make_output_section(name, sh_type, shdr.get_sh_flags(),
1094 ORDER_INVALID, false);
6a74a719
ILT
1095 }
1096 else
1097 {
16164a6b
ST
1098 // Plugins can choose to place one or more subsets of sections in
1099 // unique segments and this is done by mapping these section subsets
1100 // to unique output sections. Check if this section needs to be
1101 // remapped to a unique output section.
1102 Section_segment_map::iterator it
1103 = this->section_segment_map_.find(Const_section_id(object, shndx));
1104 if (it == this->section_segment_map_.end())
1105 {
1106 os = this->choose_output_section(object, name, sh_type,
1107 shdr.get_sh_flags(), true,
1108 ORDER_INVALID, false);
1109 }
1110 else
1111 {
1112 // We know the name of the output section, directly call
1113 // get_output_section here by-passing choose_output_section.
1114 elfcpp::Elf_Xword flags
1115 = this->get_output_section_flags(shdr.get_sh_flags());
1116
1117 const char* os_name = it->second->name;
1118 Stringpool::Key name_key;
1119 os_name = this->namepool_.add(os_name, true, &name_key);
1120 os = this->get_output_section(os_name, name_key, sh_type, flags,
1121 ORDER_INVALID, false);
1122 if (!os->is_unique_segment())
1123 {
1124 os->set_is_unique_segment();
1125 os->set_extra_segment_flags(it->second->flags);
1126 os->set_segment_alignment(it->second->align);
1127 }
1128 }
6a74a719
ILT
1129 if (os == NULL)
1130 return NULL;
1131 }
a2fb1b05 1132
2fd32231 1133 // By default the GNU linker sorts input sections whose names match
487b39df
ILT
1134 // .ctors.*, .dtors.*, .init_array.*, or .fini_array.*. The
1135 // sections are sorted by name. This is used to implement
1136 // constructor priority ordering. We are compatible. When we put
1137 // .ctor sections in .init_array and .dtor sections in .fini_array,
1138 // we must also sort plain .ctor and .dtor sections.
2fd32231 1139 if (!this->script_options_->saw_sections_clause()
5393d741 1140 && !parameters->options().relocatable()
2fd32231
ILT
1141 && (is_prefix_of(".ctors.", name)
1142 || is_prefix_of(".dtors.", name)
1143 || is_prefix_of(".init_array.", name)
5393d741
ILT
1144 || is_prefix_of(".fini_array.", name)
1145 || (parameters->options().ctors_in_init_array()
1146 && (strcmp(name, ".ctors") == 0
1147 || strcmp(name, ".dtors") == 0))))
2fd32231
ILT
1148 os->set_must_sort_attached_input_sections();
1149
edcac0c1
ILT
1150 // By default the GNU linker sorts some special text sections ahead
1151 // of others. We are compatible.
1152 if (!this->script_options_->saw_sections_clause()
7c381248 1153 && !this->is_section_ordering_specified()
edcac0c1
ILT
1154 && !parameters->options().relocatable()
1155 && Layout::special_ordering_of_input_section(name) >= 0)
1156 os->set_must_sort_attached_input_sections();
1157
487b39df
ILT
1158 // If this is a .ctors or .ctors.* section being mapped to a
1159 // .init_array section, or a .dtors or .dtors.* section being mapped
1160 // to a .fini_array section, we will need to reverse the words if
1161 // there is more than one. Record this section for later. See
1162 // ctors_sections_in_init_array above.
1163 if (!this->script_options_->saw_sections_clause()
1164 && !parameters->options().relocatable()
1165 && shdr.get_sh_size() > size / 8
1166 && (((strcmp(name, ".ctors") == 0
1167 || is_prefix_of(".ctors.", name))
1168 && strcmp(os->name(), ".init_array") == 0)
1169 || ((strcmp(name, ".dtors") == 0
1170 || is_prefix_of(".dtors.", name))
1171 && strcmp(os->name(), ".fini_array") == 0)))
1172 ctors_sections_in_init_array.insert(Section_id(object, shndx));
1173
a2fb1b05
ILT
1174 // FIXME: Handle SHF_LINK_ORDER somewhere.
1175
5b7b7d6e
ILT
1176 elfcpp::Elf_Xword orig_flags = os->flags();
1177
6e9ba2ca 1178 *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
a445fddf 1179 this->script_options_->saw_sections_clause());
5b7b7d6e
ILT
1180
1181 // If the flags changed, we may have to change the order.
1182 if ((orig_flags & elfcpp::SHF_ALLOC) != 0)
1183 {
1184 orig_flags &= (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
1185 elfcpp::Elf_Xword new_flags =
1186 os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
1187 if (orig_flags != new_flags)
1188 os->set_order(this->default_section_order(os, false));
1189 }
1190
d7bb5745 1191 this->have_added_input_section_ = true;
a2fb1b05
ILT
1192
1193 return os;
1194}
1195
16164a6b
ST
1196// Maps section SECN to SEGMENT s.
1197void
1198Layout::insert_section_segment_map(Const_section_id secn,
1199 Unique_segment_info *s)
1200{
1201 gold_assert(this->unique_segment_for_sections_specified_);
1202 this->section_segment_map_[secn] = s;
1203}
1204
6a74a719
ILT
1205// Handle a relocation section when doing a relocatable link.
1206
1207template<int size, bool big_endian>
1208Output_section*
6fa2a40b 1209Layout::layout_reloc(Sized_relobj_file<size, big_endian>* object,
6a74a719
ILT
1210 unsigned int,
1211 const elfcpp::Shdr<size, big_endian>& shdr,
1212 Output_section* data_section,
1213 Relocatable_relocs* rr)
1214{
8851ecca
ILT
1215 gold_assert(parameters->options().relocatable()
1216 || parameters->options().emit_relocs());
6a74a719
ILT
1217
1218 int sh_type = shdr.get_sh_type();
1219
1220 std::string name;
1221 if (sh_type == elfcpp::SHT_REL)
1222 name = ".rel";
1223 else if (sh_type == elfcpp::SHT_RELA)
1224 name = ".rela";
1225 else
1226 gold_unreachable();
1227 name += data_section->name();
1228
bd288ea2
ILT
1229 // In a relocatable link relocs for a grouped section must not be
1230 // combined with other reloc sections.
1231 Output_section* os;
1232 if (!parameters->options().relocatable()
1233 || (data_section->flags() & elfcpp::SHF_GROUP) == 0)
1234 os = this->choose_output_section(object, name.c_str(), sh_type,
22f0da72
ILT
1235 shdr.get_sh_flags(), false,
1236 ORDER_INVALID, false);
bd288ea2
ILT
1237 else
1238 {
1239 const char* n = this->namepool_.add(name.c_str(), true, NULL);
1240 os = this->make_output_section(n, sh_type, shdr.get_sh_flags(),
22f0da72 1241 ORDER_INVALID, false);
bd288ea2 1242 }
6a74a719
ILT
1243
1244 os->set_should_link_to_symtab();
1245 os->set_info_section(data_section);
1246
1247 Output_section_data* posd;
1248 if (sh_type == elfcpp::SHT_REL)
1249 {
1250 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
1251 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
1252 size,
1253 big_endian>(rr);
1254 }
1255 else if (sh_type == elfcpp::SHT_RELA)
1256 {
1257 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
1258 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
1259 size,
1260 big_endian>(rr);
1261 }
1262 else
1263 gold_unreachable();
1264
1265 os->add_output_section_data(posd);
1266 rr->set_output_data(posd);
1267
1268 return os;
1269}
1270
1271// Handle a group section when doing a relocatable link.
1272
1273template<int size, bool big_endian>
1274void
1275Layout::layout_group(Symbol_table* symtab,
6fa2a40b 1276 Sized_relobj_file<size, big_endian>* object,
6a74a719
ILT
1277 unsigned int,
1278 const char* group_section_name,
1279 const char* signature,
1280 const elfcpp::Shdr<size, big_endian>& shdr,
8825ac63
ILT
1281 elfcpp::Elf_Word flags,
1282 std::vector<unsigned int>* shndxes)
6a74a719 1283{
8851ecca 1284 gold_assert(parameters->options().relocatable());
6a74a719
ILT
1285 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
1286 group_section_name = this->namepool_.add(group_section_name, true, NULL);
1287 Output_section* os = this->make_output_section(group_section_name,
1288 elfcpp::SHT_GROUP,
f5c870d2 1289 shdr.get_sh_flags(),
22f0da72 1290 ORDER_INVALID, false);
6a74a719
ILT
1291
1292 // We need to find a symbol with the signature in the symbol table.
755ab8af 1293 // If we don't find one now, we need to look again later.
6a74a719 1294 Symbol* sym = symtab->lookup(signature, NULL);
755ab8af
ILT
1295 if (sym != NULL)
1296 os->set_info_symndx(sym);
1297 else
1298 {
e55bde5e
ILT
1299 // Reserve some space to minimize reallocations.
1300 if (this->group_signatures_.empty())
1301 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
1302
755ab8af
ILT
1303 // We will wind up using a symbol whose name is the signature.
1304 // So just put the signature in the symbol name pool to save it.
1305 signature = symtab->canonicalize_name(signature);
1306 this->group_signatures_.push_back(Group_signature(os, signature));
1307 }
6a74a719
ILT
1308
1309 os->set_should_link_to_symtab();
6a74a719
ILT
1310 os->set_entsize(4);
1311
1312 section_size_type entry_count =
1313 convert_to_section_size_type(shdr.get_sh_size() / 4);
1314 Output_section_data* posd =
8825ac63
ILT
1315 new Output_data_group<size, big_endian>(object, entry_count, flags,
1316 shndxes);
6a74a719
ILT
1317 os->add_output_section_data(posd);
1318}
1319
730cdc88
ILT
1320// Special GNU handling of sections name .eh_frame. They will
1321// normally hold exception frame data as defined by the C++ ABI
1322// (http://codesourcery.com/cxx-abi/).
3151305a
ILT
1323
1324template<int size, bool big_endian>
730cdc88 1325Output_section*
6fa2a40b 1326Layout::layout_eh_frame(Sized_relobj_file<size, big_endian>* object,
730cdc88
ILT
1327 const unsigned char* symbols,
1328 off_t symbols_size,
1329 const unsigned char* symbol_names,
1330 off_t symbol_names_size,
3151305a 1331 unsigned int shndx,
3151305a 1332 const elfcpp::Shdr<size, big_endian>& shdr,
730cdc88
ILT
1333 unsigned int reloc_shndx, unsigned int reloc_type,
1334 off_t* off)
3151305a 1335{
4d5e4e62
ILT
1336 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS
1337 || shdr.get_sh_type() == elfcpp::SHT_X86_64_UNWIND);
1650c4ff 1338 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
730cdc88 1339
07a60597 1340 Output_section* os = this->make_eh_frame_section(object);
a445fddf
ILT
1341 if (os == NULL)
1342 return NULL;
730cdc88 1343
3151305a
ILT
1344 gold_assert(this->eh_frame_section_ == os);
1345
911a5072
ILT
1346 elfcpp::Elf_Xword orig_flags = os->flags();
1347
cdc29364
CC
1348 if (!parameters->incremental()
1349 && this->eh_frame_data_->add_ehframe_input_section(object,
1350 symbols,
1351 symbols_size,
1352 symbol_names,
1353 symbol_names_size,
1354 shndx,
1355 reloc_shndx,
1356 reloc_type))
2c38906f 1357 {
154e0e9a
ILT
1358 os->update_flags_for_input_section(shdr.get_sh_flags());
1359
3bb951e5 1360 // A writable .eh_frame section is a RELRO section.
911a5072
ILT
1361 if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
1362 != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
1363 {
1364 os->set_is_relro();
1365 os->set_order(ORDER_RELRO);
1366 }
3bb951e5 1367
2c38906f
ILT
1368 // We found a .eh_frame section we are going to optimize, so now
1369 // we can add the set of optimized sections to the output
1370 // section. We need to postpone adding this until we've found a
1371 // section we can optimize so that the .eh_frame section in
1372 // crtbegin.o winds up at the start of the output section.
1373 if (!this->added_eh_frame_data_)
1374 {
1375 os->add_output_section_data(this->eh_frame_data_);
1376 this->added_eh_frame_data_ = true;
1377 }
1378 *off = -1;
1379 }
730cdc88
ILT
1380 else
1381 {
1382 // We couldn't handle this .eh_frame section for some reason.
1383 // Add it as a normal section.
a445fddf 1384 bool saw_sections_clause = this->script_options_->saw_sections_clause();
07a60597
ILT
1385 *off = os->add_input_section(this, object, shndx, ".eh_frame", shdr,
1386 reloc_shndx, saw_sections_clause);
d7bb5745 1387 this->have_added_input_section_ = true;
911a5072
ILT
1388
1389 if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
1390 != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
1391 os->set_order(this->default_section_order(os, false));
730cdc88
ILT
1392 }
1393
1394 return os;
3151305a
ILT
1395}
1396
07a60597
ILT
1397// Create and return the magic .eh_frame section. Create
1398// .eh_frame_hdr also if appropriate. OBJECT is the object with the
1399// input .eh_frame section; it may be NULL.
1400
1401Output_section*
1402Layout::make_eh_frame_section(const Relobj* object)
1403{
1404 // FIXME: On x86_64, this could use SHT_X86_64_UNWIND rather than
1405 // SHT_PROGBITS.
1406 Output_section* os = this->choose_output_section(object, ".eh_frame",
1407 elfcpp::SHT_PROGBITS,
1408 elfcpp::SHF_ALLOC, false,
1409 ORDER_EHFRAME, false);
1410 if (os == NULL)
1411 return NULL;
1412
1413 if (this->eh_frame_section_ == NULL)
1414 {
1415 this->eh_frame_section_ = os;
1416 this->eh_frame_data_ = new Eh_frame();
1417
1418 // For incremental linking, we do not optimize .eh_frame sections
1419 // or create a .eh_frame_hdr section.
1420 if (parameters->options().eh_frame_hdr() && !parameters->incremental())
1421 {
1422 Output_section* hdr_os =
1423 this->choose_output_section(NULL, ".eh_frame_hdr",
1424 elfcpp::SHT_PROGBITS,
1425 elfcpp::SHF_ALLOC, false,
1426 ORDER_EHFRAME, false);
1427
1428 if (hdr_os != NULL)
1429 {
1430 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
1431 this->eh_frame_data_);
1432 hdr_os->add_output_section_data(hdr_posd);
1433
1434 hdr_os->set_after_input_sections();
1435
1436 if (!this->script_options_->saw_phdrs_clause())
1437 {
1438 Output_segment* hdr_oseg;
1439 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
1440 elfcpp::PF_R);
1441 hdr_oseg->add_output_section_to_nonload(hdr_os,
1442 elfcpp::PF_R);
1443 }
1444
1445 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
1446 }
1447 }
1448 }
1449
1450 return os;
1451}
1452
1453// Add an exception frame for a PLT. This is called from target code.
1454
1455void
1456Layout::add_eh_frame_for_plt(Output_data* plt, const unsigned char* cie_data,
1457 size_t cie_length, const unsigned char* fde_data,
1458 size_t fde_length)
1459{
1460 if (parameters->incremental())
1461 {
1462 // FIXME: Maybe this could work some day....
1463 return;
1464 }
1465 Output_section* os = this->make_eh_frame_section(NULL);
1466 if (os == NULL)
1467 return;
1468 this->eh_frame_data_->add_ehframe_for_plt(plt, cie_data, cie_length,
1469 fde_data, fde_length);
1470 if (!this->added_eh_frame_data_)
1471 {
1472 os->add_output_section_data(this->eh_frame_data_);
1473 this->added_eh_frame_data_ = true;
1474 }
1475}
1476
c1027032
CC
1477// Scan a .debug_info or .debug_types section, and add summary
1478// information to the .gdb_index section.
1479
1480template<int size, bool big_endian>
1481void
1482Layout::add_to_gdb_index(bool is_type_unit,
1483 Sized_relobj<size, big_endian>* object,
1484 const unsigned char* symbols,
1485 off_t symbols_size,
1486 unsigned int shndx,
1487 unsigned int reloc_shndx,
1488 unsigned int reloc_type)
1489{
1490 if (this->gdb_index_data_ == NULL)
1491 {
1492 Output_section* os = this->choose_output_section(NULL, ".gdb_index",
1493 elfcpp::SHT_PROGBITS, 0,
1494 false, ORDER_INVALID,
1495 false);
1496 if (os == NULL)
2e702c99 1497 return;
c1027032
CC
1498
1499 this->gdb_index_data_ = new Gdb_index(os);
1500 os->add_output_section_data(this->gdb_index_data_);
1501 os->set_after_input_sections();
1502 }
1503
1504 this->gdb_index_data_->scan_debug_info(is_type_unit, object, symbols,
1505 symbols_size, shndx, reloc_shndx,
1506 reloc_type);
1507}
1508
9f1d377b
ILT
1509// Add POSD to an output section using NAME, TYPE, and FLAGS. Return
1510// the output section.
ead1e424 1511
9f1d377b 1512Output_section*
ead1e424
ILT
1513Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
1514 elfcpp::Elf_Xword flags,
f5c870d2 1515 Output_section_data* posd,
22f0da72 1516 Output_section_order order, bool is_relro)
ead1e424 1517{
a445fddf 1518 Output_section* os = this->choose_output_section(NULL, name, type, flags,
22f0da72 1519 false, order, is_relro);
a445fddf
ILT
1520 if (os != NULL)
1521 os->add_output_section_data(posd);
9f1d377b 1522 return os;
ead1e424
ILT
1523}
1524
a2fb1b05
ILT
1525// Map section flags to segment flags.
1526
1527elfcpp::Elf_Word
1528Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
1529{
1530 elfcpp::Elf_Word ret = elfcpp::PF_R;
1531 if ((flags & elfcpp::SHF_WRITE) != 0)
1532 ret |= elfcpp::PF_W;
1533 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
1534 ret |= elfcpp::PF_X;
1535 return ret;
1536}
1537
1538// Make a new Output_section, and attach it to segments as
22f0da72
ILT
1539// appropriate. ORDER is the order in which this section should
1540// appear in the output segment. IS_RELRO is true if this is a relro
1541// (read-only after relocations) section.
a2fb1b05
ILT
1542
1543Output_section*
1544Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
22f0da72
ILT
1545 elfcpp::Elf_Xword flags,
1546 Output_section_order order, bool is_relro)
a2fb1b05 1547{
96803768
ILT
1548 Output_section* os;
1549 if ((flags & elfcpp::SHF_ALLOC) == 0
e55bde5e 1550 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
96803768 1551 && is_compressible_debug_section(name))
e55bde5e
ILT
1552 os = new Output_compressed_section(&parameters->options(), name, type,
1553 flags);
62b01cb5 1554 else if ((flags & elfcpp::SHF_ALLOC) == 0
2e702c99
RM
1555 && parameters->options().strip_debug_non_line()
1556 && strcmp(".debug_abbrev", name) == 0)
62b01cb5
ILT
1557 {
1558 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
2e702c99 1559 name, type, flags);
62b01cb5 1560 if (this->debug_info_)
2e702c99 1561 this->debug_info_->set_abbreviations(this->debug_abbrev_);
62b01cb5
ILT
1562 }
1563 else if ((flags & elfcpp::SHF_ALLOC) == 0
2e702c99
RM
1564 && parameters->options().strip_debug_non_line()
1565 && strcmp(".debug_info", name) == 0)
62b01cb5
ILT
1566 {
1567 os = this->debug_info_ = new Output_reduced_debug_info_section(
2e702c99 1568 name, type, flags);
62b01cb5 1569 if (this->debug_abbrev_)
2e702c99 1570 this->debug_info_->set_abbreviations(this->debug_abbrev_);
62b01cb5 1571 }
09ec0418 1572 else
c0a62865 1573 {
5393d741
ILT
1574 // Sometimes .init_array*, .preinit_array* and .fini_array* do
1575 // not have correct section types. Force them here.
1576 if (type == elfcpp::SHT_PROGBITS)
1577 {
1578 if (is_prefix_of(".init_array", name))
1579 type = elfcpp::SHT_INIT_ARRAY;
1580 else if (is_prefix_of(".preinit_array", name))
1581 type = elfcpp::SHT_PREINIT_ARRAY;
1582 else if (is_prefix_of(".fini_array", name))
1583 type = elfcpp::SHT_FINI_ARRAY;
1584 }
1585
c0a62865
DK
1586 // FIXME: const_cast is ugly.
1587 Target* target = const_cast<Target*>(&parameters->target());
1588 os = target->make_output_section(name, type, flags);
1589 }
96803768 1590
22f0da72
ILT
1591 // With -z relro, we have to recognize the special sections by name.
1592 // There is no other way.
1593 bool is_relro_local = false;
1594 if (!this->script_options_->saw_sections_clause()
1595 && parameters->options().relro()
22f0da72
ILT
1596 && (flags & elfcpp::SHF_ALLOC) != 0
1597 && (flags & elfcpp::SHF_WRITE) != 0)
1598 {
14dc9ef7 1599 if (type == elfcpp::SHT_PROGBITS)
22f0da72 1600 {
1007b503
CC
1601 if ((flags & elfcpp::SHF_TLS) != 0)
1602 is_relro = true;
1603 else if (strcmp(name, ".data.rel.ro") == 0)
14dc9ef7
ILT
1604 is_relro = true;
1605 else if (strcmp(name, ".data.rel.ro.local") == 0)
1606 {
1607 is_relro = true;
1608 is_relro_local = true;
1609 }
1610 else if (strcmp(name, ".ctors") == 0
1611 || strcmp(name, ".dtors") == 0
1612 || strcmp(name, ".jcr") == 0)
1613 is_relro = true;
22f0da72
ILT
1614 }
1615 else if (type == elfcpp::SHT_INIT_ARRAY
1616 || type == elfcpp::SHT_FINI_ARRAY
1617 || type == elfcpp::SHT_PREINIT_ARRAY)
1618 is_relro = true;
22f0da72
ILT
1619 }
1620
1a2dff53
ILT
1621 if (is_relro)
1622 os->set_is_relro();
22f0da72
ILT
1623
1624 if (order == ORDER_INVALID && (flags & elfcpp::SHF_ALLOC) != 0)
1625 order = this->default_section_order(os, is_relro_local);
1626
1627 os->set_order(order);
f5c870d2 1628
8a5e3e08
ILT
1629 parameters->target().new_output_section(os);
1630
a3ad94ed 1631 this->section_list_.push_back(os);
a2fb1b05 1632
2fd32231
ILT
1633 // The GNU linker by default sorts some sections by priority, so we
1634 // do the same. We need to know that this might happen before we
1635 // attach any input sections.
1636 if (!this->script_options_->saw_sections_clause()
5393d741
ILT
1637 && !parameters->options().relocatable()
1638 && (strcmp(name, ".init_array") == 0
1639 || strcmp(name, ".fini_array") == 0
1640 || (!parameters->options().ctors_in_init_array()
1641 && (strcmp(name, ".ctors") == 0
1642 || strcmp(name, ".dtors") == 0))))
2fd32231
ILT
1643 os->set_may_sort_attached_input_sections();
1644
edcac0c1
ILT
1645 // The GNU linker by default sorts .text.{unlikely,exit,startup,hot}
1646 // sections before other .text sections. We are compatible. We
1647 // need to know that this might happen before we attach any input
1648 // sections.
1649 if (!this->script_options_->saw_sections_clause()
7c381248 1650 && !this->is_section_ordering_specified()
edcac0c1
ILT
1651 && !parameters->options().relocatable()
1652 && strcmp(name, ".text") == 0)
1653 os->set_may_sort_attached_input_sections();
1654
1518dc8f
ILT
1655 // Check for .stab*str sections, as .stab* sections need to link to
1656 // them.
1657 if (type == elfcpp::SHT_STRTAB
1658 && !this->have_stabstr_section_
1659 && strncmp(name, ".stab", 5) == 0
1660 && strcmp(name + strlen(name) - 3, "str") == 0)
1661 this->have_stabstr_section_ = true;
1662
9fbd3822
CC
1663 // During a full incremental link, we add patch space to most
1664 // PROGBITS and NOBITS sections. Flag those that may be
1665 // arbitrarily padded.
1666 if ((type == elfcpp::SHT_PROGBITS || type == elfcpp::SHT_NOBITS)
1667 && order != ORDER_INTERP
1668 && order != ORDER_INIT
1669 && order != ORDER_PLT
1670 && order != ORDER_FINI
1671 && order != ORDER_RELRO_LAST
1672 && order != ORDER_NON_RELRO_FIRST
aa06ae28 1673 && strcmp(name, ".eh_frame") != 0
9fbd3822
CC
1674 && strcmp(name, ".ctors") != 0
1675 && strcmp(name, ".dtors") != 0
1676 && strcmp(name, ".jcr") != 0)
8ea8cd50
CC
1677 {
1678 os->set_is_patch_space_allowed();
1679
1680 // Certain sections require "holes" to be filled with
1681 // specific fill patterns. These fill patterns may have
1682 // a minimum size, so we must prevent allocations from the
1683 // free list that leave a hole smaller than the minimum.
1684 if (strcmp(name, ".debug_info") == 0)
2e702c99 1685 os->set_free_space_fill(new Output_fill_debug_info(false));
8ea8cd50 1686 else if (strcmp(name, ".debug_types") == 0)
2e702c99 1687 os->set_free_space_fill(new Output_fill_debug_info(true));
8ea8cd50 1688 else if (strcmp(name, ".debug_line") == 0)
2e702c99 1689 os->set_free_space_fill(new Output_fill_debug_line());
8ea8cd50 1690 }
9fbd3822 1691
154e0e9a
ILT
1692 // If we have already attached the sections to segments, then we
1693 // need to attach this one now. This happens for sections created
1694 // directly by the linker.
1695 if (this->sections_are_attached_)
2e702c99 1696 this->attach_section_to_segment(&parameters->target(), os);
154e0e9a 1697
4e2b1697
ILT
1698 return os;
1699}
a445fddf 1700
22f0da72
ILT
1701// Return the default order in which a section should be placed in an
1702// output segment. This function captures a lot of the ideas in
1703// ld/scripttempl/elf.sc in the GNU linker. Note that the order of a
1704// linker created section is normally set when the section is created;
1705// this function is used for input sections.
1706
1707Output_section_order
1708Layout::default_section_order(Output_section* os, bool is_relro_local)
1709{
1710 gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
1711 bool is_write = (os->flags() & elfcpp::SHF_WRITE) != 0;
1712 bool is_execinstr = (os->flags() & elfcpp::SHF_EXECINSTR) != 0;
1713 bool is_bss = false;
1714
1715 switch (os->type())
1716 {
1717 default:
1718 case elfcpp::SHT_PROGBITS:
1719 break;
1720 case elfcpp::SHT_NOBITS:
1721 is_bss = true;
1722 break;
1723 case elfcpp::SHT_RELA:
1724 case elfcpp::SHT_REL:
1725 if (!is_write)
1726 return ORDER_DYNAMIC_RELOCS;
1727 break;
1728 case elfcpp::SHT_HASH:
1729 case elfcpp::SHT_DYNAMIC:
1730 case elfcpp::SHT_SHLIB:
1731 case elfcpp::SHT_DYNSYM:
1732 case elfcpp::SHT_GNU_HASH:
1733 case elfcpp::SHT_GNU_verdef:
1734 case elfcpp::SHT_GNU_verneed:
1735 case elfcpp::SHT_GNU_versym:
1736 if (!is_write)
1737 return ORDER_DYNAMIC_LINKER;
1738 break;
1739 case elfcpp::SHT_NOTE:
1740 return is_write ? ORDER_RW_NOTE : ORDER_RO_NOTE;
1741 }
1742
1743 if ((os->flags() & elfcpp::SHF_TLS) != 0)
1744 return is_bss ? ORDER_TLS_BSS : ORDER_TLS_DATA;
1745
1746 if (!is_bss && !is_write)
1747 {
1748 if (is_execinstr)
1749 {
1750 if (strcmp(os->name(), ".init") == 0)
1751 return ORDER_INIT;
1752 else if (strcmp(os->name(), ".fini") == 0)
1753 return ORDER_FINI;
1754 }
1755 return is_execinstr ? ORDER_TEXT : ORDER_READONLY;
1756 }
1757
1758 if (os->is_relro())
1759 return is_relro_local ? ORDER_RELRO_LOCAL : ORDER_RELRO;
1760
1761 if (os->is_small_section())
1762 return is_bss ? ORDER_SMALL_BSS : ORDER_SMALL_DATA;
1763 if (os->is_large_section())
1764 return is_bss ? ORDER_LARGE_BSS : ORDER_LARGE_DATA;
1765
1766 return is_bss ? ORDER_BSS : ORDER_DATA;
1767}
1768
154e0e9a
ILT
1769// Attach output sections to segments. This is called after we have
1770// seen all the input sections.
1771
1772void
2e702c99 1773Layout::attach_sections_to_segments(const Target* target)
154e0e9a
ILT
1774{
1775 for (Section_list::iterator p = this->section_list_.begin();
1776 p != this->section_list_.end();
1777 ++p)
2e702c99 1778 this->attach_section_to_segment(target, *p);
154e0e9a
ILT
1779
1780 this->sections_are_attached_ = true;
1781}
1782
1783// Attach an output section to a segment.
1784
1785void
2e702c99 1786Layout::attach_section_to_segment(const Target* target, Output_section* os)
154e0e9a
ILT
1787{
1788 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1789 this->unattached_section_list_.push_back(os);
1790 else
2e702c99 1791 this->attach_allocated_section_to_segment(target, os);
154e0e9a
ILT
1792}
1793
4e2b1697 1794// Attach an allocated output section to a segment.
1c4f3631 1795
4e2b1697 1796void
2e702c99
RM
1797Layout::attach_allocated_section_to_segment(const Target* target,
1798 Output_section* os)
4e2b1697 1799{
154e0e9a 1800 elfcpp::Elf_Xword flags = os->flags();
4e2b1697 1801 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
a2fb1b05 1802
4e2b1697
ILT
1803 if (parameters->options().relocatable())
1804 return;
a2fb1b05 1805
4e2b1697
ILT
1806 // If we have a SECTIONS clause, we can't handle the attachment to
1807 // segments until after we've seen all the sections.
1808 if (this->script_options_->saw_sections_clause())
1809 return;
a2fb1b05 1810
4e2b1697 1811 gold_assert(!this->script_options_->saw_phdrs_clause());
756ac4a8 1812
4e2b1697 1813 // This output section goes into a PT_LOAD segment.
a2fb1b05 1814
4e2b1697 1815 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
a2fb1b05 1816
16164a6b
ST
1817 // If this output section's segment has extra flags that need to be set,
1818 // coming from a linker plugin, do that.
1819 seg_flags |= os->extra_segment_flags();
1820
a192ba05
ILT
1821 // Check for --section-start.
1822 uint64_t addr;
1823 bool is_address_set = parameters->options().section_start(os->name(), &addr);
f5c870d2 1824
4e2b1697 1825 // In general the only thing we really care about for PT_LOAD
0f72bf6f
RÁE
1826 // segments is whether or not they are writable or executable,
1827 // so that is how we search for them.
1828 // Large data sections also go into their own PT_LOAD segment.
1829 // People who need segments sorted on some other basis will
1830 // have to use a linker script.
a2fb1b05 1831
4e2b1697 1832 Segment_list::const_iterator p;
16164a6b 1833 if (!os->is_unique_segment())
4e2b1697 1834 {
16164a6b
ST
1835 for (p = this->segment_list_.begin();
1836 p != this->segment_list_.end();
1837 ++p)
a192ba05 1838 {
16164a6b
ST
1839 if ((*p)->type() != elfcpp::PT_LOAD)
1840 continue;
1841 if ((*p)->is_unique_segment())
1842 continue;
1843 if (!parameters->options().omagic()
1844 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1845 continue;
1846 if ((target->isolate_execinstr() || parameters->options().rosegment())
1847 && ((*p)->flags() & elfcpp::PF_X) != (seg_flags & elfcpp::PF_X))
1848 continue;
1849 // If -Tbss was specified, we need to separate the data and BSS
1850 // segments.
1851 if (parameters->options().user_set_Tbss())
1852 {
1853 if ((os->type() == elfcpp::SHT_NOBITS)
1854 == (*p)->has_any_data_sections())
1855 continue;
1856 }
1857 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1858 continue;
1859
1860 if (is_address_set)
1861 {
1862 if ((*p)->are_addresses_set())
1863 continue;
1864
1865 (*p)->add_initial_output_data(os);
1866 (*p)->update_flags_for_output_section(seg_flags);
1867 (*p)->set_addresses(addr, addr);
1868 break;
1869 }
1870
1871 (*p)->add_output_section_to_load(this, os, seg_flags);
1872 break;
1873 }
1874 }
1875
1876 if (p == this->segment_list_.end()
1877 || os->is_unique_segment())
4e2b1697
ILT
1878 {
1879 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
2e702c99 1880 seg_flags);
8a5e3e08
ILT
1881 if (os->is_large_data_section())
1882 oseg->set_is_large_data_segment();
22f0da72 1883 oseg->add_output_section_to_load(this, os, seg_flags);
a192ba05
ILT
1884 if (is_address_set)
1885 oseg->set_addresses(addr, addr);
16164a6b
ST
1886 // Check if segment should be marked unique. For segments marked
1887 // unique by linker plugins, set the new alignment if specified.
1888 if (os->is_unique_segment())
1889 {
1890 oseg->set_is_unique_segment();
1891 if (os->segment_alignment() != 0)
1892 oseg->set_minimum_p_align(os->segment_alignment());
1893 }
a2fb1b05
ILT
1894 }
1895
4e2b1697
ILT
1896 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1897 // segment.
1898 if (os->type() == elfcpp::SHT_NOTE)
1899 {
1900 // See if we already have an equivalent PT_NOTE segment.
1901 for (p = this->segment_list_.begin();
2e702c99
RM
1902 p != segment_list_.end();
1903 ++p)
1904 {
1905 if ((*p)->type() == elfcpp::PT_NOTE
1906 && (((*p)->flags() & elfcpp::PF_W)
1907 == (seg_flags & elfcpp::PF_W)))
1908 {
1909 (*p)->add_output_section_to_nonload(os, seg_flags);
1910 break;
1911 }
1912 }
4e2b1697
ILT
1913
1914 if (p == this->segment_list_.end())
2e702c99
RM
1915 {
1916 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1917 seg_flags);
1918 oseg->add_output_section_to_nonload(os, seg_flags);
1919 }
4e2b1697
ILT
1920 }
1921
1922 // If we see a loadable SHF_TLS section, we create a PT_TLS
1923 // segment. There can only be one such segment.
1924 if ((flags & elfcpp::SHF_TLS) != 0)
1925 {
1926 if (this->tls_segment_ == NULL)
2d924fd9 1927 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
22f0da72 1928 this->tls_segment_->add_output_section_to_nonload(os, seg_flags);
4e2b1697 1929 }
9f1d377b
ILT
1930
1931 // If -z relro is in effect, and we see a relro section, we create a
1932 // PT_GNU_RELRO segment. There can only be one such segment.
1933 if (os->is_relro() && parameters->options().relro())
1934 {
1935 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1936 if (this->relro_segment_ == NULL)
2d924fd9 1937 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
22f0da72 1938 this->relro_segment_->add_output_section_to_nonload(os, seg_flags);
9f1d377b 1939 }
10b4f102 1940
e1f74f98
ILT
1941 // If we see a section named .interp, put it into a PT_INTERP
1942 // segment. This seems broken to me, but this is what GNU ld does,
1943 // and glibc expects it.
10b4f102 1944 if (strcmp(os->name(), ".interp") == 0
e1f74f98 1945 && !this->script_options_->saw_phdrs_clause())
10b4f102
ILT
1946 {
1947 if (this->interp_segment_ == NULL)
1948 this->make_output_segment(elfcpp::PT_INTERP, seg_flags);
e1f74f98
ILT
1949 else
1950 gold_warning(_("multiple '.interp' sections in input files "
1951 "may cause confusing PT_INTERP segment"));
10b4f102
ILT
1952 this->interp_segment_->add_output_section_to_nonload(os, seg_flags);
1953 }
a2fb1b05
ILT
1954}
1955
919ed24c
ILT
1956// Make an output section for a script.
1957
1958Output_section*
1e5d2fb1
DK
1959Layout::make_output_section_for_script(
1960 const char* name,
1961 Script_sections::Section_type section_type)
919ed24c
ILT
1962{
1963 name = this->namepool_.add(name, false, NULL);
1e5d2fb1
DK
1964 elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
1965 if (section_type == Script_sections::ST_NOLOAD)
1966 sh_flags = 0;
919ed24c 1967 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
22f0da72
ILT
1968 sh_flags, ORDER_INVALID,
1969 false);
919ed24c 1970 os->set_found_in_sections_clause();
1e5d2fb1
DK
1971 if (section_type == Script_sections::ST_NOLOAD)
1972 os->set_is_noload();
919ed24c
ILT
1973 return os;
1974}
1975
3802b2dd
ILT
1976// Return the number of segments we expect to see.
1977
1978size_t
1979Layout::expected_segment_count() const
1980{
1981 size_t ret = this->segment_list_.size();
1982
1983 // If we didn't see a SECTIONS clause in a linker script, we should
1984 // already have the complete list of segments. Otherwise we ask the
1985 // SECTIONS clause how many segments it expects, and add in the ones
1986 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1987
1988 if (!this->script_options_->saw_sections_clause())
1989 return ret;
1990 else
1991 {
1992 const Script_sections* ss = this->script_options_->script_sections();
1993 return ret + ss->expected_segment_count(this);
1994 }
1995}
1996
35cdfc9a
ILT
1997// Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1998// is whether we saw a .note.GNU-stack section in the object file.
1999// GNU_STACK_FLAGS is the section flags. The flags give the
2000// protection required for stack memory. We record this in an
2001// executable as a PT_GNU_STACK segment. If an object file does not
2002// have a .note.GNU-stack segment, we must assume that it is an old
2003// object. On some targets that will force an executable stack.
2004
2005void
83e17bd5
CC
2006Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags,
2007 const Object* obj)
35cdfc9a
ILT
2008{
2009 if (!seen_gnu_stack)
83e17bd5
CC
2010 {
2011 this->input_without_gnu_stack_note_ = true;
2012 if (parameters->options().warn_execstack()
2013 && parameters->target().is_default_stack_executable())
2014 gold_warning(_("%s: missing .note.GNU-stack section"
2015 " implies executable stack"),
2016 obj->name().c_str());
2017 }
35cdfc9a
ILT
2018 else
2019 {
2020 this->input_with_gnu_stack_note_ = true;
2021 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
83e17bd5
CC
2022 {
2023 this->input_requires_executable_stack_ = true;
2024 if (parameters->options().warn_execstack()
2025 || parameters->options().is_stack_executable())
2026 gold_warning(_("%s: requires executable stack"),
2027 obj->name().c_str());
2028 }
35cdfc9a
ILT
2029 }
2030}
2031
9c547ec3
ILT
2032// Create automatic note sections.
2033
2034void
2035Layout::create_notes()
2036{
2037 this->create_gold_note();
2038 this->create_executable_stack_info();
2039 this->create_build_id();
2040}
2041
a3ad94ed
ILT
2042// Create the dynamic sections which are needed before we read the
2043// relocs.
2044
2045void
9b07f471 2046Layout::create_initial_dynamic_sections(Symbol_table* symtab)
a3ad94ed 2047{
436ca963 2048 if (parameters->doing_static_link())
a3ad94ed
ILT
2049 return;
2050
3802b2dd
ILT
2051 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
2052 elfcpp::SHT_DYNAMIC,
2053 (elfcpp::SHF_ALLOC
2054 | elfcpp::SHF_WRITE),
22f0da72
ILT
2055 false, ORDER_RELRO,
2056 true);
a3ad94ed 2057
6daf5215
ILT
2058 // A linker script may discard .dynamic, so check for NULL.
2059 if (this->dynamic_section_ != NULL)
2060 {
2061 this->dynamic_symbol_ =
2062 symtab->define_in_output_data("_DYNAMIC", NULL,
2063 Symbol_table::PREDEFINED,
2064 this->dynamic_section_, 0, 0,
2065 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
2066 elfcpp::STV_HIDDEN, 0, false, false);
16649710 2067
6daf5215 2068 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
16649710 2069
6daf5215
ILT
2070 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
2071 }
a3ad94ed
ILT
2072}
2073
bfd58944
ILT
2074// For each output section whose name can be represented as C symbol,
2075// define __start and __stop symbols for the section. This is a GNU
2076// extension.
2077
2078void
9b07f471 2079Layout::define_section_symbols(Symbol_table* symtab)
bfd58944
ILT
2080{
2081 for (Section_list::const_iterator p = this->section_list_.begin();
2082 p != this->section_list_.end();
2083 ++p)
2084 {
2085 const char* const name = (*p)->name();
f1ec9ded 2086 if (is_cident(name))
bfd58944
ILT
2087 {
2088 const std::string name_string(name);
f1ec9ded 2089 const std::string start_name(cident_section_start_prefix
2e702c99 2090 + name_string);
f1ec9ded 2091 const std::string stop_name(cident_section_stop_prefix
2e702c99 2092 + name_string);
bfd58944 2093
9b07f471 2094 symtab->define_in_output_data(start_name.c_str(),
bfd58944 2095 NULL, // version
99fff23b 2096 Symbol_table::PREDEFINED,
bfd58944
ILT
2097 *p,
2098 0, // value
2099 0, // symsize
2100 elfcpp::STT_NOTYPE,
2101 elfcpp::STB_GLOBAL,
2102 elfcpp::STV_DEFAULT,
2103 0, // nonvis
2104 false, // offset_is_from_end
a445fddf 2105 true); // only_if_ref
bfd58944 2106
9b07f471 2107 symtab->define_in_output_data(stop_name.c_str(),
bfd58944 2108 NULL, // version
99fff23b 2109 Symbol_table::PREDEFINED,
bfd58944
ILT
2110 *p,
2111 0, // value
2112 0, // symsize
2113 elfcpp::STT_NOTYPE,
2114 elfcpp::STB_GLOBAL,
2115 elfcpp::STV_DEFAULT,
2116 0, // nonvis
2117 true, // offset_is_from_end
a445fddf 2118 true); // only_if_ref
bfd58944
ILT
2119 }
2120 }
2121}
2122
755ab8af
ILT
2123// Define symbols for group signatures.
2124
2125void
2126Layout::define_group_signatures(Symbol_table* symtab)
2127{
2128 for (Group_signatures::iterator p = this->group_signatures_.begin();
2129 p != this->group_signatures_.end();
2130 ++p)
2131 {
2132 Symbol* sym = symtab->lookup(p->signature, NULL);
2133 if (sym != NULL)
2134 p->section->set_info_symndx(sym);
2135 else
2136 {
2137 // Force the name of the group section to the group
2138 // signature, and use the group's section symbol as the
2139 // signature symbol.
2140 if (strcmp(p->section->name(), p->signature) != 0)
2141 {
2142 const char* name = this->namepool_.add(p->signature,
2143 true, NULL);
2144 p->section->set_name(name);
2145 }
2146 p->section->set_needs_symtab_index();
2147 p->section->set_info_section_symndx(p->section);
2148 }
2149 }
2150
2151 this->group_signatures_.clear();
2152}
2153
75f65a3e
ILT
2154// Find the first read-only PT_LOAD segment, creating one if
2155// necessary.
54dc6425 2156
75f65a3e 2157Output_segment*
2e702c99 2158Layout::find_first_load_seg(const Target* target)
54dc6425 2159{
0f72bf6f 2160 Output_segment* best = NULL;
75f65a3e
ILT
2161 for (Segment_list::const_iterator p = this->segment_list_.begin();
2162 p != this->segment_list_.end();
2163 ++p)
2164 {
2165 if ((*p)->type() == elfcpp::PT_LOAD
2166 && ((*p)->flags() & elfcpp::PF_R) != 0
af6156ef 2167 && (parameters->options().omagic()
2e702c99
RM
2168 || ((*p)->flags() & elfcpp::PF_W) == 0)
2169 && (!target->isolate_execinstr()
2170 || ((*p)->flags() & elfcpp::PF_X) == 0))
2171 {
2172 if (best == NULL || this->segment_precedes(*p, best))
2173 best = *p;
2174 }
75f65a3e 2175 }
0f72bf6f
RÁE
2176 if (best != NULL)
2177 return best;
75f65a3e 2178
1c4f3631
ILT
2179 gold_assert(!this->script_options_->saw_phdrs_clause());
2180
3802b2dd
ILT
2181 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
2182 elfcpp::PF_R);
75f65a3e 2183 return load_seg;
54dc6425
ILT
2184}
2185
20e6d0d6
DK
2186// Save states of all current output segments. Store saved states
2187// in SEGMENT_STATES.
2188
2189void
2190Layout::save_segments(Segment_states* segment_states)
2191{
2192 for (Segment_list::const_iterator p = this->segment_list_.begin();
2193 p != this->segment_list_.end();
2194 ++p)
2195 {
2196 Output_segment* segment = *p;
2197 // Shallow copy.
2198 Output_segment* copy = new Output_segment(*segment);
2199 (*segment_states)[segment] = copy;
2200 }
2201}
2202
2203// Restore states of output segments and delete any segment not found in
2204// SEGMENT_STATES.
2205
2206void
2207Layout::restore_segments(const Segment_states* segment_states)
2208{
2209 // Go through the segment list and remove any segment added in the
2210 // relaxation loop.
2211 this->tls_segment_ = NULL;
2212 this->relro_segment_ = NULL;
2213 Segment_list::iterator list_iter = this->segment_list_.begin();
2214 while (list_iter != this->segment_list_.end())
2215 {
2216 Output_segment* segment = *list_iter;
2217 Segment_states::const_iterator states_iter =
2218 segment_states->find(segment);
2219 if (states_iter != segment_states->end())
2220 {
2221 const Output_segment* copy = states_iter->second;
2222 // Shallow copy to restore states.
2223 *segment = *copy;
2224
2225 // Also fix up TLS and RELRO segment pointers as appropriate.
2226 if (segment->type() == elfcpp::PT_TLS)
2227 this->tls_segment_ = segment;
2228 else if (segment->type() == elfcpp::PT_GNU_RELRO)
2229 this->relro_segment_ = segment;
2230
2231 ++list_iter;
2e702c99 2232 }
20e6d0d6
DK
2233 else
2234 {
2e702c99 2235 list_iter = this->segment_list_.erase(list_iter);
20e6d0d6
DK
2236 // This is a segment created during section layout. It should be
2237 // safe to remove it since we should have removed all pointers to it.
2238 delete segment;
2239 }
2240 }
2241}
2242
2243// Clean up after relaxation so that sections can be laid out again.
2244
2245void
2246Layout::clean_up_after_relaxation()
2247{
2248 // Restore the segments to point state just prior to the relaxation loop.
2249 Script_sections* script_section = this->script_options_->script_sections();
2250 script_section->release_segments();
2251 this->restore_segments(this->segment_states_);
2252
2253 // Reset section addresses and file offsets
2254 for (Section_list::iterator p = this->section_list_.begin();
2255 p != this->section_list_.end();
2256 ++p)
2257 {
20e6d0d6 2258 (*p)->restore_states();
8923b24c
DK
2259
2260 // If an input section changes size because of relaxation,
2261 // we need to adjust the section offsets of all input sections.
2262 // after such a section.
2263 if ((*p)->section_offsets_need_adjustment())
2264 (*p)->adjust_section_offsets();
2265
2266 (*p)->reset_address_and_file_offset();
20e6d0d6 2267 }
2e702c99 2268
20e6d0d6
DK
2269 // Reset special output object address and file offsets.
2270 for (Data_list::iterator p = this->special_output_list_.begin();
2271 p != this->special_output_list_.end();
2272 ++p)
2273 (*p)->reset_address_and_file_offset();
2274
2275 // A linker script may have created some output section data objects.
2276 // They are useless now.
2277 for (Output_section_data_list::const_iterator p =
2278 this->script_output_section_data_list_.begin();
2279 p != this->script_output_section_data_list_.end();
2280 ++p)
2281 delete *p;
2e702c99 2282 this->script_output_section_data_list_.clear();
20e6d0d6
DK
2283}
2284
2285// Prepare for relaxation.
2286
2287void
2288Layout::prepare_for_relaxation()
2289{
2290 // Create an relaxation debug check if in debugging mode.
2291 if (is_debugging_enabled(DEBUG_RELAXATION))
2292 this->relaxation_debug_check_ = new Relaxation_debug_check();
2293
2294 // Save segment states.
2295 this->segment_states_ = new Segment_states();
2296 this->save_segments(this->segment_states_);
2297
2298 for(Section_list::const_iterator p = this->section_list_.begin();
2299 p != this->section_list_.end();
2300 ++p)
2301 (*p)->save_states();
2302
2303 if (is_debugging_enabled(DEBUG_RELAXATION))
2304 this->relaxation_debug_check_->check_output_data_for_reset_values(
2e702c99 2305 this->section_list_, this->special_output_list_);
20e6d0d6
DK
2306
2307 // Also enable recording of output section data from scripts.
2308 this->record_output_section_data_from_script_ = true;
2309}
2310
2311// Relaxation loop body: If target has no relaxation, this runs only once
2312// Otherwise, the target relaxation hook is called at the end of
2313// each iteration. If the hook returns true, it means re-layout of
2e702c99 2314// section is required.
20e6d0d6
DK
2315//
2316// The number of segments created by a linking script without a PHDRS
2317// clause may be affected by section sizes and alignments. There is
2318// a remote chance that relaxation causes different number of PT_LOAD
2319// segments are created and sections are attached to different segments.
2320// Therefore, we always throw away all segments created during section
2321// layout. In order to be able to restart the section layout, we keep
2322// a copy of the segment list right before the relaxation loop and use
2323// that to restore the segments.
2e702c99
RM
2324//
2325// PASS is the current relaxation pass number.
20e6d0d6
DK
2326// SYMTAB is a symbol table.
2327// PLOAD_SEG is the address of a pointer for the load segment.
2328// PHDR_SEG is a pointer to the PHDR segment.
2329// SEGMENT_HEADERS points to the output segment header.
2330// FILE_HEADER points to the output file header.
2331// PSHNDX is the address to store the output section index.
2332
2333off_t inline
2334Layout::relaxation_loop_body(
2335 int pass,
2336 Target* target,
2337 Symbol_table* symtab,
2338 Output_segment** pload_seg,
2339 Output_segment* phdr_seg,
2340 Output_segment_headers* segment_headers,
2341 Output_file_header* file_header,
2342 unsigned int* pshndx)
2343{
2344 // If this is not the first iteration, we need to clean up after
2345 // relaxation so that we can lay out the sections again.
2346 if (pass != 0)
2347 this->clean_up_after_relaxation();
2348
2349 // If there is a SECTIONS clause, put all the input sections into
2350 // the required order.
2351 Output_segment* load_seg;
2352 if (this->script_options_->saw_sections_clause())
2353 load_seg = this->set_section_addresses_from_script(symtab);
2354 else if (parameters->options().relocatable())
2355 load_seg = NULL;
2356 else
2e702c99 2357 load_seg = this->find_first_load_seg(target);
20e6d0d6
DK
2358
2359 if (parameters->options().oformat_enum()
2360 != General_options::OBJECT_FORMAT_ELF)
2361 load_seg = NULL;
2362
403a15dd
ILT
2363 // If the user set the address of the text segment, that may not be
2364 // compatible with putting the segment headers and file headers into
2365 // that segment.
d12a5ea8 2366 if (parameters->options().user_set_Ttext()
a1373b60 2367 && parameters->options().Ttext() % target->abi_pagesize() != 0)
d12a5ea8
ILT
2368 {
2369 load_seg = NULL;
2370 phdr_seg = NULL;
2371 }
403a15dd 2372
68b6574b
ILT
2373 gold_assert(phdr_seg == NULL
2374 || load_seg != NULL
2375 || this->script_options_->saw_sections_clause());
20e6d0d6 2376
a192ba05 2377 // If the address of the load segment we found has been set by
1e3811b0
ILT
2378 // --section-start rather than by a script, then adjust the VMA and
2379 // LMA downward if possible to include the file and section headers.
2380 uint64_t header_gap = 0;
a192ba05
ILT
2381 if (load_seg != NULL
2382 && load_seg->are_addresses_set()
1e3811b0
ILT
2383 && !this->script_options_->saw_sections_clause()
2384 && !parameters->options().relocatable())
2385 {
2386 file_header->finalize_data_size();
2387 segment_headers->finalize_data_size();
2388 size_t sizeof_headers = (file_header->data_size()
2389 + segment_headers->data_size());
2390 const uint64_t abi_pagesize = target->abi_pagesize();
2391 uint64_t hdr_paddr = load_seg->paddr() - sizeof_headers;
2392 hdr_paddr &= ~(abi_pagesize - 1);
2393 uint64_t subtract = load_seg->paddr() - hdr_paddr;
2394 if (load_seg->paddr() < subtract || load_seg->vaddr() < subtract)
2395 load_seg = NULL;
2396 else
2397 {
2398 load_seg->set_addresses(load_seg->vaddr() - subtract,
2399 load_seg->paddr() - subtract);
2400 header_gap = subtract - sizeof_headers;
2401 }
2402 }
a192ba05 2403
20e6d0d6
DK
2404 // Lay out the segment headers.
2405 if (!parameters->options().relocatable())
2406 {
2407 gold_assert(segment_headers != NULL);
1e3811b0
ILT
2408 if (header_gap != 0 && load_seg != NULL)
2409 {
2410 Output_data_zero_fill* z = new Output_data_zero_fill(header_gap, 1);
2411 load_seg->add_initial_output_data(z);
2412 }
20e6d0d6 2413 if (load_seg != NULL)
2e702c99 2414 load_seg->add_initial_output_data(segment_headers);
20e6d0d6 2415 if (phdr_seg != NULL)
2e702c99 2416 phdr_seg->add_initial_output_data(segment_headers);
20e6d0d6
DK
2417 }
2418
2419 // Lay out the file header.
2420 if (load_seg != NULL)
2421 load_seg->add_initial_output_data(file_header);
2422
2423 if (this->script_options_->saw_phdrs_clause()
2424 && !parameters->options().relocatable())
2425 {
2426 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
2427 // clause in a linker script.
2428 Script_sections* ss = this->script_options_->script_sections();
2429 ss->put_headers_in_phdrs(file_header, segment_headers);
2430 }
2431
2432 // We set the output section indexes in set_segment_offsets and
2433 // set_section_indexes.
2434 *pshndx = 1;
2435
2436 // Set the file offsets of all the segments, and all the sections
2437 // they contain.
2438 off_t off;
2439 if (!parameters->options().relocatable())
2440 off = this->set_segment_offsets(target, load_seg, pshndx);
2441 else
2442 off = this->set_relocatable_section_offsets(file_header, pshndx);
2443
2444 // Verify that the dummy relaxation does not change anything.
2445 if (is_debugging_enabled(DEBUG_RELAXATION))
2446 {
2447 if (pass == 0)
2448 this->relaxation_debug_check_->read_sections(this->section_list_);
2449 else
2450 this->relaxation_debug_check_->verify_sections(this->section_list_);
2451 }
2452
2453 *pload_seg = load_seg;
2454 return off;
2455}
2456
6e9ba2ca
ST
2457// Search the list of patterns and find the postion of the given section
2458// name in the output section. If the section name matches a glob
2459// pattern and a non-glob name, then the non-glob position takes
2460// precedence. Return 0 if no match is found.
2461
2462unsigned int
2463Layout::find_section_order_index(const std::string& section_name)
2464{
2465 Unordered_map<std::string, unsigned int>::iterator map_it;
2466 map_it = this->input_section_position_.find(section_name);
2467 if (map_it != this->input_section_position_.end())
2468 return map_it->second;
2469
2470 // Absolute match failed. Linear search the glob patterns.
2471 std::vector<std::string>::iterator it;
2472 for (it = this->input_section_glob_.begin();
2473 it != this->input_section_glob_.end();
2474 ++it)
2475 {
2476 if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
2e702c99
RM
2477 {
2478 map_it = this->input_section_position_.find(*it);
2479 gold_assert(map_it != this->input_section_position_.end());
2480 return map_it->second;
2481 }
6e9ba2ca
ST
2482 }
2483 return 0;
2484}
2485
2486// Read the sequence of input sections from the file specified with
e9552f7e 2487// option --section-ordering-file.
6e9ba2ca
ST
2488
2489void
2490Layout::read_layout_from_file()
2491{
2492 const char* filename = parameters->options().section_ordering_file();
2493 std::ifstream in;
2494 std::string line;
2495
2496 in.open(filename);
2497 if (!in)
2498 gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
2e702c99 2499 filename, strerror(errno));
6e9ba2ca
ST
2500
2501 std::getline(in, line); // this chops off the trailing \n, if any
2502 unsigned int position = 1;
e9552f7e 2503 this->set_section_ordering_specified();
6e9ba2ca
ST
2504
2505 while (in)
2506 {
2507 if (!line.empty() && line[line.length() - 1] == '\r') // Windows
2e702c99 2508 line.resize(line.length() - 1);
6e9ba2ca
ST
2509 // Ignore comments, beginning with '#'
2510 if (line[0] == '#')
2e702c99
RM
2511 {
2512 std::getline(in, line);
2513 continue;
2514 }
6e9ba2ca
ST
2515 this->input_section_position_[line] = position;
2516 // Store all glob patterns in a vector.
2517 if (is_wildcard_string(line.c_str()))
2e702c99 2518 this->input_section_glob_.push_back(line);
6e9ba2ca
ST
2519 position++;
2520 std::getline(in, line);
2521 }
2522}
2523
54dc6425
ILT
2524// Finalize the layout. When this is called, we have created all the
2525// output sections and all the output segments which are based on
2526// input sections. We have several things to do, and we have to do
2527// them in the right order, so that we get the right results correctly
2528// and efficiently.
2529
2530// 1) Finalize the list of output segments and create the segment
2531// table header.
2532
2533// 2) Finalize the dynamic symbol table and associated sections.
2534
2535// 3) Determine the final file offset of all the output segments.
2536
2537// 4) Determine the final file offset of all the SHF_ALLOC output
2538// sections.
2539
75f65a3e
ILT
2540// 5) Create the symbol table sections and the section name table
2541// section.
2542
2543// 6) Finalize the symbol table: set symbol values to their final
54dc6425
ILT
2544// value and make a final determination of which symbols are going
2545// into the output symbol table.
2546
54dc6425
ILT
2547// 7) Create the section table header.
2548
2549// 8) Determine the final file offset of all the output sections which
2550// are not SHF_ALLOC, including the section table header.
2551
2552// 9) Finalize the ELF file header.
2553
75f65a3e
ILT
2554// This function returns the size of the output file.
2555
2556off_t
17a1d0a9 2557Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
8851ecca 2558 Target* target, const Task* task)
54dc6425 2559{
f59f41f3 2560 target->finalize_sections(this, input_objects, symtab);
5a6f7e2d 2561
17a1d0a9 2562 this->count_local_symbols(task, input_objects);
7bf1f802 2563
1518dc8f 2564 this->link_stabs_sections();
4f211c8b 2565
3802b2dd 2566 Output_segment* phdr_seg = NULL;
8851ecca 2567 if (!parameters->options().relocatable() && !parameters->doing_static_link())
54dc6425 2568 {
dbe717ef
ILT
2569 // There was a dynamic object in the link. We need to create
2570 // some information for the dynamic linker.
2571
3802b2dd
ILT
2572 // Create the PT_PHDR segment which will hold the program
2573 // headers.
1c4f3631
ILT
2574 if (!this->script_options_->saw_phdrs_clause())
2575 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
3802b2dd 2576
14b31740
ILT
2577 // Create the dynamic symbol table, including the hash table.
2578 Output_section* dynstr;
2579 std::vector<Symbol*> dynamic_symbols;
2580 unsigned int local_dynamic_count;
a5dc0706 2581 Versions versions(*this->script_options()->version_script_info(),
2e702c99 2582 &this->dynpool_);
9b07f471 2583 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
14b31740
ILT
2584 &local_dynamic_count, &dynamic_symbols,
2585 &versions);
dbe717ef
ILT
2586
2587 // Create the .interp section to hold the name of the
e1f74f98
ILT
2588 // interpreter, and put it in a PT_INTERP segment. Don't do it
2589 // if we saw a .interp section in an input file.
2590 if ((!parameters->options().shared()
2591 || parameters->options().dynamic_linker() != NULL)
2592 && this->interp_segment_ == NULL)
2e702c99 2593 this->create_interp(target);
a3ad94ed
ILT
2594
2595 // Finish the .dynamic section to hold the dynamic data, and put
2596 // it in a PT_DYNAMIC segment.
16649710 2597 this->finish_dynamic_section(input_objects, symtab);
14b31740
ILT
2598
2599 // We should have added everything we need to the dynamic string
2600 // table.
2601 this->dynpool_.set_string_offsets();
2602
2603 // Create the version sections. We can't do this until the
2604 // dynamic string table is complete.
46fe1623 2605 this->create_version_sections(&versions, symtab, local_dynamic_count,
14b31740 2606 dynamic_symbols, dynstr);
f0ba79e2
ILT
2607
2608 // Set the size of the _DYNAMIC symbol. We can't do this until
2609 // after we call create_version_sections.
2610 this->set_dynamic_symbol_size(symtab);
54dc6425 2611 }
2e702c99 2612
20e6d0d6
DK
2613 // Create segment headers.
2614 Output_segment_headers* segment_headers =
2615 (parameters->options().relocatable()
2616 ? NULL
2617 : new Output_segment_headers(this->segment_list_));
75f65a3e
ILT
2618
2619 // Lay out the file header.
a10ae760
ILT
2620 Output_file_header* file_header = new Output_file_header(target, symtab,
2621 segment_headers);
a445fddf 2622
61ba1cf9 2623 this->special_output_list_.push_back(file_header);
6a74a719
ILT
2624 if (segment_headers != NULL)
2625 this->special_output_list_.push_back(segment_headers);
75f65a3e 2626
20e6d0d6
DK
2627 // Find approriate places for orphan output sections if we are using
2628 // a linker script.
2629 if (this->script_options_->saw_sections_clause())
2630 this->place_orphan_sections_in_script();
2e702c99 2631
20e6d0d6
DK
2632 Output_segment* load_seg;
2633 off_t off;
2634 unsigned int shndx;
2635 int pass = 0;
2636
2637 // Take a snapshot of the section layout as needed.
2638 if (target->may_relax())
2639 this->prepare_for_relaxation();
2e702c99 2640
20e6d0d6
DK
2641 // Run the relaxation loop to lay out sections.
2642 do
1c4f3631 2643 {
20e6d0d6
DK
2644 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
2645 phdr_seg, segment_headers, file_header,
2646 &shndx);
2647 pass++;
1c4f3631 2648 }
c0a62865 2649 while (target->may_relax()
f625ae50 2650 && target->relax(pass, input_objects, symtab, this, task));
75f65a3e 2651
eabc84f4
RM
2652 // If there is a load segment that contains the file and program headers,
2653 // provide a symbol __ehdr_start pointing there.
2654 // A program can use this to examine itself robustly.
2655 if (load_seg != NULL)
2656 symtab->define_in_output_segment("__ehdr_start", NULL,
2657 Symbol_table::PREDEFINED, load_seg, 0, 0,
2658 elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
2659 elfcpp::STV_DEFAULT, 0,
2660 Symbol::SEGMENT_START, true);
2661
a9a60db6
ILT
2662 // Set the file offsets of all the non-data sections we've seen so
2663 // far which don't have to wait for the input sections. We need
2664 // this in order to finalize local symbols in non-allocated
2665 // sections.
2666 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
2667
d491d34e
ILT
2668 // Set the section indexes of all unallocated sections seen so far,
2669 // in case any of them are somehow referenced by a symbol.
2670 shndx = this->set_section_indexes(shndx);
2671
75f65a3e 2672 // Create the symbol table sections.
d491d34e 2673 this->create_symtab_sections(input_objects, symtab, shndx, &off);
7bf1f802
ILT
2674 if (!parameters->doing_static_link())
2675 this->assign_local_dynsym_offsets(input_objects);
75f65a3e 2676
e5756efb
ILT
2677 // Process any symbol assignments from a linker script. This must
2678 // be called after the symbol table has been finalized.
2679 this->script_options_->finalize_symbols(symtab, this);
2680
09ec0418
CC
2681 // Create the incremental inputs sections.
2682 if (this->incremental_inputs_)
2683 {
2684 this->incremental_inputs_->finalize();
2685 this->create_incremental_info_sections(symtab);
2686 }
2687
75f65a3e
ILT
2688 // Create the .shstrtab section.
2689 Output_section* shstrtab_section = this->create_shstrtab();
2690
a9a60db6
ILT
2691 // Set the file offsets of the rest of the non-data sections which
2692 // don't have to wait for the input sections.
9a0910c3 2693 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
86887060 2694
d491d34e
ILT
2695 // Now that all sections have been created, set the section indexes
2696 // for any sections which haven't been done yet.
86887060 2697 shndx = this->set_section_indexes(shndx);
ead1e424 2698
75f65a3e 2699 // Create the section table header.
d491d34e 2700 this->create_shdrs(shstrtab_section, &off);
75f65a3e 2701
17a1d0a9
ILT
2702 // If there are no sections which require postprocessing, we can
2703 // handle the section names now, and avoid a resize later.
2704 if (!this->any_postprocessing_sections_)
09ec0418
CC
2705 {
2706 off = this->set_section_offsets(off,
2707 POSTPROCESSING_SECTIONS_PASS);
2708 off =
2709 this->set_section_offsets(off,
17a1d0a9 2710 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
09ec0418 2711 }
17a1d0a9 2712
27bc2bce 2713 file_header->set_section_info(this->section_headers_, shstrtab_section);
75f65a3e 2714
27bc2bce
ILT
2715 // Now we know exactly where everything goes in the output file
2716 // (except for non-allocated sections which require postprocessing).
a3ad94ed 2717 Output_data::layout_complete();
75f65a3e 2718
e44fcf3b
ILT
2719 this->output_file_size_ = off;
2720
75f65a3e
ILT
2721 return off;
2722}
2723
8ed814a9 2724// Create a note header following the format defined in the ELF ABI.
ec3f783e
ILT
2725// NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
2726// of the section to create, DESCSZ is the size of the descriptor.
2727// ALLOCATE is true if the section should be allocated in memory.
2728// This returns the new note section. It sets *TRAILING_PADDING to
2729// the number of trailing zero bytes required.
4f211c8b 2730
8ed814a9 2731Output_section*
ef4ab7a8
PP
2732Layout::create_note(const char* name, int note_type,
2733 const char* section_name, size_t descsz,
8ed814a9 2734 bool allocate, size_t* trailing_padding)
4f211c8b 2735{
e2305dc0
ILT
2736 // Authorities all agree that the values in a .note field should
2737 // be aligned on 4-byte boundaries for 32-bit binaries. However,
2738 // they differ on what the alignment is for 64-bit binaries.
2739 // The GABI says unambiguously they take 8-byte alignment:
2740 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
2741 // Other documentation says alignment should always be 4 bytes:
2742 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
2743 // GNU ld and GNU readelf both support the latter (at least as of
2744 // version 2.16.91), and glibc always generates the latter for
2745 // .note.ABI-tag (as of version 1.6), so that's the one we go with
2746 // here.
35cdfc9a 2747#ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
8851ecca 2748 const int size = parameters->target().get_size();
e2305dc0
ILT
2749#else
2750 const int size = 32;
2751#endif
4f211c8b
ILT
2752
2753 // The contents of the .note section.
4f211c8b
ILT
2754 size_t namesz = strlen(name) + 1;
2755 size_t aligned_namesz = align_address(namesz, size / 8);
4f211c8b 2756 size_t aligned_descsz = align_address(descsz, size / 8);
4f211c8b 2757
8ed814a9 2758 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
4f211c8b 2759
8ed814a9
ILT
2760 unsigned char* buffer = new unsigned char[notehdrsz];
2761 memset(buffer, 0, notehdrsz);
4f211c8b 2762
8851ecca 2763 bool is_big_endian = parameters->target().is_big_endian();
4f211c8b
ILT
2764
2765 if (size == 32)
2766 {
2767 if (!is_big_endian)
2768 {
2769 elfcpp::Swap<32, false>::writeval(buffer, namesz);
2770 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
2771 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
2772 }
2773 else
2774 {
2775 elfcpp::Swap<32, true>::writeval(buffer, namesz);
2776 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
2777 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
2778 }
2779 }
2780 else if (size == 64)
2781 {
2782 if (!is_big_endian)
2783 {
2784 elfcpp::Swap<64, false>::writeval(buffer, namesz);
2785 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
2786 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
2787 }
2788 else
2789 {
2790 elfcpp::Swap<64, true>::writeval(buffer, namesz);
2791 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
2792 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
2793 }
2794 }
2795 else
2796 gold_unreachable();
2797
2798 memcpy(buffer + 3 * (size / 8), name, namesz);
4f211c8b 2799
8ed814a9 2800 elfcpp::Elf_Xword flags = 0;
22f0da72 2801 Output_section_order order = ORDER_INVALID;
8ed814a9 2802 if (allocate)
22f0da72
ILT
2803 {
2804 flags = elfcpp::SHF_ALLOC;
2805 order = ORDER_RO_NOTE;
2806 }
ec3f783e
ILT
2807 Output_section* os = this->choose_output_section(NULL, section_name,
2808 elfcpp::SHT_NOTE,
22f0da72 2809 flags, false, order, false);
9c547ec3
ILT
2810 if (os == NULL)
2811 return NULL;
2812
8ed814a9 2813 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
7d9e3d98
ILT
2814 size / 8,
2815 "** note header");
8ed814a9
ILT
2816 os->add_output_section_data(posd);
2817
2818 *trailing_padding = aligned_descsz - descsz;
2819
2820 return os;
2821}
2822
2823// For an executable or shared library, create a note to record the
2824// version of gold used to create the binary.
2825
2826void
2827Layout::create_gold_note()
2828{
cdc29364
CC
2829 if (parameters->options().relocatable()
2830 || parameters->incremental_update())
8ed814a9
ILT
2831 return;
2832
2833 std::string desc = std::string("gold ") + gold::get_version_string();
2834
2835 size_t trailing_padding;
ca09d69a 2836 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
ef4ab7a8
PP
2837 ".note.gnu.gold-version", desc.size(),
2838 false, &trailing_padding);
9c547ec3
ILT
2839 if (os == NULL)
2840 return;
8ed814a9
ILT
2841
2842 Output_section_data* posd = new Output_data_const(desc, 4);
4f211c8b 2843 os->add_output_section_data(posd);
8ed814a9
ILT
2844
2845 if (trailing_padding > 0)
2846 {
7d9e3d98 2847 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
2848 os->add_output_section_data(posd);
2849 }
4f211c8b
ILT
2850}
2851
35cdfc9a
ILT
2852// Record whether the stack should be executable. This can be set
2853// from the command line using the -z execstack or -z noexecstack
2854// options. Otherwise, if any input file has a .note.GNU-stack
2855// section with the SHF_EXECINSTR flag set, the stack should be
2856// executable. Otherwise, if at least one input file a
2857// .note.GNU-stack section, and some input file has no .note.GNU-stack
2858// section, we use the target default for whether the stack should be
2859// executable. Otherwise, we don't generate a stack note. When
2860// generating a object file, we create a .note.GNU-stack section with
2861// the appropriate marking. When generating an executable or shared
2862// library, we create a PT_GNU_STACK segment.
2863
2864void
9c547ec3 2865Layout::create_executable_stack_info()
35cdfc9a
ILT
2866{
2867 bool is_stack_executable;
e55bde5e
ILT
2868 if (parameters->options().is_execstack_set())
2869 is_stack_executable = parameters->options().is_stack_executable();
35cdfc9a
ILT
2870 else if (!this->input_with_gnu_stack_note_)
2871 return;
2872 else
2873 {
2874 if (this->input_requires_executable_stack_)
2875 is_stack_executable = true;
2876 else if (this->input_without_gnu_stack_note_)
9c547ec3
ILT
2877 is_stack_executable =
2878 parameters->target().is_default_stack_executable();
35cdfc9a
ILT
2879 else
2880 is_stack_executable = false;
2881 }
2882
8851ecca 2883 if (parameters->options().relocatable())
35cdfc9a
ILT
2884 {
2885 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
2886 elfcpp::Elf_Xword flags = 0;
2887 if (is_stack_executable)
2888 flags |= elfcpp::SHF_EXECINSTR;
22f0da72
ILT
2889 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags,
2890 ORDER_INVALID, false);
35cdfc9a
ILT
2891 }
2892 else
2893 {
1c4f3631
ILT
2894 if (this->script_options_->saw_phdrs_clause())
2895 return;
35cdfc9a
ILT
2896 int flags = elfcpp::PF_R | elfcpp::PF_W;
2897 if (is_stack_executable)
2898 flags |= elfcpp::PF_X;
3802b2dd 2899 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
35cdfc9a
ILT
2900 }
2901}
2902
8ed814a9
ILT
2903// If --build-id was used, set up the build ID note.
2904
2905void
2906Layout::create_build_id()
2907{
2908 if (!parameters->options().user_set_build_id())
2909 return;
2910
2911 const char* style = parameters->options().build_id();
2912 if (strcmp(style, "none") == 0)
2913 return;
2914
2915 // Set DESCSZ to the size of the note descriptor. When possible,
2916 // set DESC to the note descriptor contents.
2917 size_t descsz;
2918 std::string desc;
2919 if (strcmp(style, "md5") == 0)
2920 descsz = 128 / 8;
2921 else if (strcmp(style, "sha1") == 0)
2922 descsz = 160 / 8;
2923 else if (strcmp(style, "uuid") == 0)
2924 {
2925 const size_t uuidsz = 128 / 8;
2926
2927 char buffer[uuidsz];
2928 memset(buffer, 0, uuidsz);
2929
2a00e4fb 2930 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
8ed814a9
ILT
2931 if (descriptor < 0)
2932 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
2933 strerror(errno));
2934 else
2935 {
2936 ssize_t got = ::read(descriptor, buffer, uuidsz);
2a00e4fb 2937 release_descriptor(descriptor, true);
8ed814a9
ILT
2938 if (got < 0)
2939 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
2940 else if (static_cast<size_t>(got) != uuidsz)
2941 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
2942 uuidsz, got);
2943 }
2944
2945 desc.assign(buffer, uuidsz);
2946 descsz = uuidsz;
2947 }
2948 else if (strncmp(style, "0x", 2) == 0)
2949 {
2950 hex_init();
2951 const char* p = style + 2;
2952 while (*p != '\0')
2953 {
2954 if (hex_p(p[0]) && hex_p(p[1]))
2955 {
2956 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
2957 desc += c;
2958 p += 2;
2959 }
2960 else if (*p == '-' || *p == ':')
2961 ++p;
2962 else
2963 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
2964 style);
2965 }
2966 descsz = desc.size();
2967 }
2968 else
2969 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
2970
2971 // Create the note.
2972 size_t trailing_padding;
2973 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
ef4ab7a8
PP
2974 ".note.gnu.build-id", descsz, true,
2975 &trailing_padding);
9c547ec3
ILT
2976 if (os == NULL)
2977 return;
8ed814a9
ILT
2978
2979 if (!desc.empty())
2980 {
2981 // We know the value already, so we fill it in now.
2982 gold_assert(desc.size() == descsz);
2983
2984 Output_section_data* posd = new Output_data_const(desc, 4);
2985 os->add_output_section_data(posd);
2986
2987 if (trailing_padding != 0)
2988 {
7d9e3d98 2989 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
2990 os->add_output_section_data(posd);
2991 }
2992 }
2993 else
2994 {
2995 // We need to compute a checksum after we have completed the
2996 // link.
2997 gold_assert(trailing_padding == 0);
7d9e3d98 2998 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
8ed814a9 2999 os->add_output_section_data(this->build_id_note_);
8ed814a9
ILT
3000 }
3001}
3002
1518dc8f
ILT
3003// If we have both .stabXX and .stabXXstr sections, then the sh_link
3004// field of the former should point to the latter. I'm not sure who
3005// started this, but the GNU linker does it, and some tools depend
3006// upon it.
3007
3008void
3009Layout::link_stabs_sections()
3010{
3011 if (!this->have_stabstr_section_)
3012 return;
3013
3014 for (Section_list::iterator p = this->section_list_.begin();
3015 p != this->section_list_.end();
3016 ++p)
3017 {
3018 if ((*p)->type() != elfcpp::SHT_STRTAB)
3019 continue;
3020
3021 const char* name = (*p)->name();
3022 if (strncmp(name, ".stab", 5) != 0)
3023 continue;
3024
3025 size_t len = strlen(name);
3026 if (strcmp(name + len - 3, "str") != 0)
3027 continue;
3028
3029 std::string stab_name(name, len - 3);
3030 Output_section* stab_sec;
3031 stab_sec = this->find_output_section(stab_name.c_str());
3032 if (stab_sec != NULL)
3033 stab_sec->set_link_section(*p);
3034 }
3035}
3036
09ec0418 3037// Create .gnu_incremental_inputs and related sections needed
3ce2c28e
ILT
3038// for the next run of incremental linking to check what has changed.
3039
3040void
09ec0418 3041Layout::create_incremental_info_sections(Symbol_table* symtab)
3ce2c28e 3042{
09ec0418
CC
3043 Incremental_inputs* incr = this->incremental_inputs_;
3044
3045 gold_assert(incr != NULL);
3046
3047 // Create the .gnu_incremental_inputs, _symtab, and _relocs input sections.
3048 incr->create_data_sections(symtab);
3ce2c28e
ILT
3049
3050 // Add the .gnu_incremental_inputs section.
ca09d69a 3051 const char* incremental_inputs_name =
3ce2c28e 3052 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
09ec0418 3053 Output_section* incremental_inputs_os =
3ce2c28e 3054 this->make_output_section(incremental_inputs_name,
f5c870d2 3055 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
22f0da72 3056 ORDER_INVALID, false);
09ec0418
CC
3057 incremental_inputs_os->add_output_section_data(incr->inputs_section());
3058
3059 // Add the .gnu_incremental_symtab section.
ca09d69a 3060 const char* incremental_symtab_name =
09ec0418
CC
3061 this->namepool_.add(".gnu_incremental_symtab", false, NULL);
3062 Output_section* incremental_symtab_os =
3063 this->make_output_section(incremental_symtab_name,
3064 elfcpp::SHT_GNU_INCREMENTAL_SYMTAB, 0,
3065 ORDER_INVALID, false);
3066 incremental_symtab_os->add_output_section_data(incr->symtab_section());
3067 incremental_symtab_os->set_entsize(4);
3068
3069 // Add the .gnu_incremental_relocs section.
ca09d69a 3070 const char* incremental_relocs_name =
09ec0418
CC
3071 this->namepool_.add(".gnu_incremental_relocs", false, NULL);
3072 Output_section* incremental_relocs_os =
3073 this->make_output_section(incremental_relocs_name,
3074 elfcpp::SHT_GNU_INCREMENTAL_RELOCS, 0,
3075 ORDER_INVALID, false);
3076 incremental_relocs_os->add_output_section_data(incr->relocs_section());
3077 incremental_relocs_os->set_entsize(incr->relocs_entsize());
3078
0e70b911 3079 // Add the .gnu_incremental_got_plt section.
ca09d69a 3080 const char* incremental_got_plt_name =
0e70b911
CC
3081 this->namepool_.add(".gnu_incremental_got_plt", false, NULL);
3082 Output_section* incremental_got_plt_os =
3083 this->make_output_section(incremental_got_plt_name,
3084 elfcpp::SHT_GNU_INCREMENTAL_GOT_PLT, 0,
3085 ORDER_INVALID, false);
3086 incremental_got_plt_os->add_output_section_data(incr->got_plt_section());
3087
3ce2c28e 3088 // Add the .gnu_incremental_strtab section.
ca09d69a 3089 const char* incremental_strtab_name =
3ce2c28e 3090 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
09ec0418 3091 Output_section* incremental_strtab_os = this->make_output_section(incremental_strtab_name,
2e702c99
RM
3092 elfcpp::SHT_STRTAB, 0,
3093 ORDER_INVALID, false);
3ce2c28e 3094 Output_data_strtab* strtab_data =
09ec0418
CC
3095 new Output_data_strtab(incr->get_stringpool());
3096 incremental_strtab_os->add_output_section_data(strtab_data);
3097
3098 incremental_inputs_os->set_after_input_sections();
3099 incremental_symtab_os->set_after_input_sections();
3100 incremental_relocs_os->set_after_input_sections();
0e70b911 3101 incremental_got_plt_os->set_after_input_sections();
09ec0418
CC
3102
3103 incremental_inputs_os->set_link_section(incremental_strtab_os);
3104 incremental_symtab_os->set_link_section(incremental_inputs_os);
3105 incremental_relocs_os->set_link_section(incremental_inputs_os);
0e70b911 3106 incremental_got_plt_os->set_link_section(incremental_inputs_os);
3ce2c28e
ILT
3107}
3108
75f65a3e
ILT
3109// Return whether SEG1 should be before SEG2 in the output file. This
3110// is based entirely on the segment type and flags. When this is
aecf301f 3111// called the segment addresses have normally not yet been set.
75f65a3e
ILT
3112
3113bool
3114Layout::segment_precedes(const Output_segment* seg1,
3115 const Output_segment* seg2)
3116{
3117 elfcpp::Elf_Word type1 = seg1->type();
3118 elfcpp::Elf_Word type2 = seg2->type();
3119
3120 // The single PT_PHDR segment is required to precede any loadable
3121 // segment. We simply make it always first.
3122 if (type1 == elfcpp::PT_PHDR)
3123 {
a3ad94ed 3124 gold_assert(type2 != elfcpp::PT_PHDR);
75f65a3e
ILT
3125 return true;
3126 }
3127 if (type2 == elfcpp::PT_PHDR)
3128 return false;
3129
3130 // The single PT_INTERP segment is required to precede any loadable
3131 // segment. We simply make it always second.
3132 if (type1 == elfcpp::PT_INTERP)
3133 {
a3ad94ed 3134 gold_assert(type2 != elfcpp::PT_INTERP);
75f65a3e
ILT
3135 return true;
3136 }
3137 if (type2 == elfcpp::PT_INTERP)
3138 return false;
3139
3140 // We then put PT_LOAD segments before any other segments.
3141 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
3142 return true;
3143 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
3144 return false;
3145
9f1d377b
ILT
3146 // We put the PT_TLS segment last except for the PT_GNU_RELRO
3147 // segment, because that is where the dynamic linker expects to find
3148 // it (this is just for efficiency; other positions would also work
3149 // correctly).
3150 if (type1 == elfcpp::PT_TLS
3151 && type2 != elfcpp::PT_TLS
3152 && type2 != elfcpp::PT_GNU_RELRO)
3153 return false;
3154 if (type2 == elfcpp::PT_TLS
3155 && type1 != elfcpp::PT_TLS
3156 && type1 != elfcpp::PT_GNU_RELRO)
3157 return true;
3158
3159 // We put the PT_GNU_RELRO segment last, because that is where the
3160 // dynamic linker expects to find it (as with PT_TLS, this is just
3161 // for efficiency).
3162 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
92e059d8 3163 return false;
9f1d377b 3164 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
92e059d8
ILT
3165 return true;
3166
75f65a3e
ILT
3167 const elfcpp::Elf_Word flags1 = seg1->flags();
3168 const elfcpp::Elf_Word flags2 = seg2->flags();
3169
3170 // The order of non-PT_LOAD segments is unimportant. We simply sort
3171 // by the numeric segment type and flags values. There should not
3172 // be more than one segment with the same type and flags.
3173 if (type1 != elfcpp::PT_LOAD)
3174 {
3175 if (type1 != type2)
3176 return type1 < type2;
a3ad94ed 3177 gold_assert(flags1 != flags2);
75f65a3e
ILT
3178 return flags1 < flags2;
3179 }
3180
a445fddf
ILT
3181 // If the addresses are set already, sort by load address.
3182 if (seg1->are_addresses_set())
3183 {
3184 if (!seg2->are_addresses_set())
3185 return true;
3186
3187 unsigned int section_count1 = seg1->output_section_count();
3188 unsigned int section_count2 = seg2->output_section_count();
3189 if (section_count1 == 0 && section_count2 > 0)
3190 return true;
3191 if (section_count1 > 0 && section_count2 == 0)
3192 return false;
3193
b8fa8750
NC
3194 uint64_t paddr1 = (seg1->are_addresses_set()
3195 ? seg1->paddr()
3196 : seg1->first_section_load_address());
3197 uint64_t paddr2 = (seg2->are_addresses_set()
3198 ? seg2->paddr()
3199 : seg2->first_section_load_address());
3200
a445fddf
ILT
3201 if (paddr1 != paddr2)
3202 return paddr1 < paddr2;
3203 }
3204 else if (seg2->are_addresses_set())
3205 return false;
3206
8a5e3e08
ILT
3207 // A segment which holds large data comes after a segment which does
3208 // not hold large data.
3209 if (seg1->is_large_data_segment())
3210 {
3211 if (!seg2->is_large_data_segment())
3212 return false;
3213 }
3214 else if (seg2->is_large_data_segment())
3215 return true;
3216
3217 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
3218 // segments come before writable segments. Then writable segments
3219 // with data come before writable segments without data. Then
3220 // executable segments come before non-executable segments. Then
3221 // the unlikely case of a non-readable segment comes before the
3222 // normal case of a readable segment. If there are multiple
3223 // segments with the same type and flags, we require that the
3224 // address be set, and we sort by virtual address and then physical
3225 // address.
75f65a3e
ILT
3226 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
3227 return (flags1 & elfcpp::PF_W) == 0;
756ac4a8
ILT
3228 if ((flags1 & elfcpp::PF_W) != 0
3229 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
3230 return seg1->has_any_data_sections();
75f65a3e
ILT
3231 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
3232 return (flags1 & elfcpp::PF_X) != 0;
3233 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
3234 return (flags1 & elfcpp::PF_R) == 0;
3235
a445fddf 3236 // We shouldn't get here--we shouldn't create segments which we
aecf301f 3237 // can't distinguish. Unless of course we are using a weird linker
16164a6b
ST
3238 // script or overlapping --section-start options. We could also get
3239 // here if plugins want unique segments for subsets of sections.
ea0d8c47 3240 gold_assert(this->script_options_->saw_phdrs_clause()
16164a6b
ST
3241 || parameters->options().any_section_start()
3242 || this->is_unique_segment_for_sections_specified());
aecf301f 3243 return false;
75f65a3e
ILT
3244}
3245
8a5e3e08
ILT
3246// Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
3247
3248static off_t
3249align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
3250{
3251 uint64_t unsigned_off = off;
3252 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
3253 | (addr & (abi_pagesize - 1)));
3254 if (aligned_off < unsigned_off)
3255 aligned_off += abi_pagesize;
3256 return aligned_off;
3257}
3258
ead1e424
ILT
3259// Set the file offsets of all the segments, and all the sections they
3260// contain. They have all been created. LOAD_SEG must be be laid out
3261// first. Return the offset of the data to follow.
75f65a3e
ILT
3262
3263off_t
ead1e424 3264Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
ca09d69a 3265 unsigned int* pshndx)
75f65a3e 3266{
aecf301f
ILT
3267 // Sort them into the final order. We use a stable sort so that we
3268 // don't randomize the order of indistinguishable segments created
3269 // by linker scripts.
3270 std::stable_sort(this->segment_list_.begin(), this->segment_list_.end(),
3271 Layout::Compare_segments(this));
54dc6425 3272
75f65a3e
ILT
3273 // Find the PT_LOAD segments, and set their addresses and offsets
3274 // and their section's addresses and offsets.
2e702c99 3275 uint64_t start_addr;
e55bde5e 3276 if (parameters->options().user_set_Ttext())
2e702c99 3277 start_addr = parameters->options().Ttext();
374ad285 3278 else if (parameters->options().output_is_position_independent())
2e702c99 3279 start_addr = 0;
0c5e9c22 3280 else
2e702c99
RM
3281 start_addr = target->default_text_segment_address();
3282
3283 uint64_t addr = start_addr;
75f65a3e 3284 off_t off = 0;
a445fddf
ILT
3285
3286 // If LOAD_SEG is NULL, then the file header and segment headers
3287 // will not be loadable. But they still need to be at offset 0 in
3288 // the file. Set their offsets now.
3289 if (load_seg == NULL)
3290 {
3291 for (Data_list::iterator p = this->special_output_list_.begin();
3292 p != this->special_output_list_.end();
3293 ++p)
3294 {
3295 off = align_address(off, (*p)->addralign());
3296 (*p)->set_address_and_file_offset(0, off);
3297 off += (*p)->data_size();
3298 }
3299 }
3300
1a2dff53
ILT
3301 unsigned int increase_relro = this->increase_relro_;
3302 if (this->script_options_->saw_sections_clause())
3303 increase_relro = 0;
3304
34810851
ILT
3305 const bool check_sections = parameters->options().check_sections();
3306 Output_segment* last_load_segment = NULL;
3307
2e702c99
RM
3308 unsigned int shndx_begin = *pshndx;
3309 unsigned int shndx_load_seg = *pshndx;
3310
75f65a3e
ILT
3311 for (Segment_list::iterator p = this->segment_list_.begin();
3312 p != this->segment_list_.end();
3313 ++p)
3314 {
3315 if ((*p)->type() == elfcpp::PT_LOAD)
3316 {
2e702c99
RM
3317 if (target->isolate_execinstr())
3318 {
3319 // When we hit the segment that should contain the
3320 // file headers, reset the file offset so we place
3321 // it and subsequent segments appropriately.
3322 // We'll fix up the preceding segments below.
3323 if (load_seg == *p)
3324 {
3325 if (off == 0)
3326 load_seg = NULL;
3327 else
3328 {
3329 off = 0;
3330 shndx_load_seg = *pshndx;
3331 }
3332 }
3333 }
3334 else
3335 {
3336 // Verify that the file headers fall into the first segment.
3337 if (load_seg != NULL && load_seg != *p)
3338 gold_unreachable();
3339 load_seg = NULL;
3340 }
75f65a3e 3341
756ac4a8
ILT
3342 bool are_addresses_set = (*p)->are_addresses_set();
3343 if (are_addresses_set)
3344 {
3345 // When it comes to setting file offsets, we care about
3346 // the physical address.
3347 addr = (*p)->paddr();
3348 }
9590bf25
CC
3349 else if (parameters->options().user_set_Ttext()
3350 && ((*p)->flags() & elfcpp::PF_W) == 0)
3351 {
3352 are_addresses_set = true;
3353 }
e55bde5e 3354 else if (parameters->options().user_set_Tdata()
756ac4a8 3355 && ((*p)->flags() & elfcpp::PF_W) != 0
e55bde5e 3356 && (!parameters->options().user_set_Tbss()
756ac4a8
ILT
3357 || (*p)->has_any_data_sections()))
3358 {
e55bde5e 3359 addr = parameters->options().Tdata();
756ac4a8
ILT
3360 are_addresses_set = true;
3361 }
e55bde5e 3362 else if (parameters->options().user_set_Tbss()
756ac4a8
ILT
3363 && ((*p)->flags() & elfcpp::PF_W) != 0
3364 && !(*p)->has_any_data_sections())
3365 {
e55bde5e 3366 addr = parameters->options().Tbss();
756ac4a8
ILT
3367 are_addresses_set = true;
3368 }
3369
75f65a3e
ILT
3370 uint64_t orig_addr = addr;
3371 uint64_t orig_off = off;
3372
a445fddf 3373 uint64_t aligned_addr = 0;
75f65a3e 3374 uint64_t abi_pagesize = target->abi_pagesize();
af6156ef 3375 uint64_t common_pagesize = target->common_pagesize();
0496d5e5 3376
af6156ef
ILT
3377 if (!parameters->options().nmagic()
3378 && !parameters->options().omagic())
a1373b60 3379 (*p)->set_minimum_p_align(abi_pagesize);
0496d5e5 3380
8a5e3e08 3381 if (!are_addresses_set)
a445fddf 3382 {
a6577478
RÁE
3383 // Skip the address forward one page, maintaining the same
3384 // position within the page. This lets us store both segments
3385 // overlapping on a single page in the file, but the loader will
3386 // put them on different pages in memory. We will revisit this
3387 // decision once we know the size of the segment.
a445fddf
ILT
3388
3389 addr = align_address(addr, (*p)->maximum_alignment());
75f65a3e 3390 aligned_addr = addr;
a445fddf 3391
2e702c99
RM
3392 if (load_seg == *p)
3393 {
3394 // This is the segment that will contain the file
3395 // headers, so its offset will have to be exactly zero.
3396 gold_assert(orig_off == 0);
3397
3398 // If the target wants a fixed minimum distance from the
3399 // text segment to the read-only segment, move up now.
3400 uint64_t min_addr = start_addr + target->rosegment_gap();
3401 if (addr < min_addr)
3402 addr = min_addr;
3403
3404 // But this is not the first segment! To make its
3405 // address congruent with its offset, that address better
3406 // be aligned to the ABI-mandated page size.
3407 addr = align_address(addr, abi_pagesize);
3408 aligned_addr = addr;
3409 }
3410 else
3411 {
3412 if ((addr & (abi_pagesize - 1)) != 0)
3413 addr = addr + abi_pagesize;
a445fddf 3414
2e702c99
RM
3415 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
3416 }
75f65a3e
ILT
3417 }
3418
8a5e3e08
ILT
3419 if (!parameters->options().nmagic()
3420 && !parameters->options().omagic())
3421 off = align_file_offset(off, addr, abi_pagesize);
2e702c99 3422 else
661be1e2
ILT
3423 {
3424 // This is -N or -n with a section script which prevents
3425 // us from using a load segment. We need to ensure that
3426 // the file offset is aligned to the alignment of the
3427 // segment. This is because the linker script
3428 // implicitly assumed a zero offset. If we don't align
3429 // here, then the alignment of the sections in the
3430 // linker script may not match the alignment of the
3431 // sections in the set_section_addresses call below,
3432 // causing an error about dot moving backward.
3433 off = align_address(off, (*p)->maximum_alignment());
3434 }
8a5e3e08 3435
ead1e424 3436 unsigned int shndx_hold = *pshndx;
fc497986 3437 bool has_relro = false;
96a2b4e4 3438 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
fd064a5b 3439 &increase_relro,
fc497986 3440 &has_relro,
2e702c99 3441 &off, pshndx);
75f65a3e
ILT
3442
3443 // Now that we know the size of this segment, we may be able
3444 // to save a page in memory, at the cost of wasting some
3445 // file space, by instead aligning to the start of a new
3446 // page. Here we use the real machine page size rather than
fc497986
CC
3447 // the ABI mandated page size. If the segment has been
3448 // aligned so that the relro data ends at a page boundary,
3449 // we do not try to realign it.
75f65a3e 3450
cdc29364
CC
3451 if (!are_addresses_set
3452 && !has_relro
3453 && aligned_addr != addr
fb0e076f 3454 && !parameters->incremental())
75f65a3e 3455 {
75f65a3e
ILT
3456 uint64_t first_off = (common_pagesize
3457 - (aligned_addr
3458 & (common_pagesize - 1)));
3459 uint64_t last_off = new_addr & (common_pagesize - 1);
3460 if (first_off > 0
3461 && last_off > 0
3462 && ((aligned_addr & ~ (common_pagesize - 1))
3463 != (new_addr & ~ (common_pagesize - 1)))
3464 && first_off + last_off <= common_pagesize)
3465 {
ead1e424
ILT
3466 *pshndx = shndx_hold;
3467 addr = align_address(aligned_addr, common_pagesize);
a445fddf 3468 addr = align_address(addr, (*p)->maximum_alignment());
815a1205
AM
3469 if ((addr & (abi_pagesize - 1)) != 0)
3470 addr = addr + abi_pagesize;
75f65a3e 3471 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
8a5e3e08 3472 off = align_file_offset(off, addr, abi_pagesize);
3bb951e5
ILT
3473
3474 increase_relro = this->increase_relro_;
3475 if (this->script_options_->saw_sections_clause())
3476 increase_relro = 0;
3477 has_relro = false;
3478
96a2b4e4 3479 new_addr = (*p)->set_section_addresses(this, true, addr,
fd064a5b 3480 &increase_relro,
fc497986 3481 &has_relro,
2e702c99 3482 &off, pshndx);
75f65a3e
ILT
3483 }
3484 }
3485
3486 addr = new_addr;
3487
34810851
ILT
3488 // Implement --check-sections. We know that the segments
3489 // are sorted by LMA.
3490 if (check_sections && last_load_segment != NULL)
3491 {
3492 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
3493 if (last_load_segment->paddr() + last_load_segment->memsz()
3494 > (*p)->paddr())
3495 {
3496 unsigned long long lb1 = last_load_segment->paddr();
3497 unsigned long long le1 = lb1 + last_load_segment->memsz();
3498 unsigned long long lb2 = (*p)->paddr();
3499 unsigned long long le2 = lb2 + (*p)->memsz();
3500 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
3501 "[0x%llx -> 0x%llx]"),
3502 lb1, le1, lb2, le2);
3503 }
3504 }
3505 last_load_segment = *p;
75f65a3e
ILT
3506 }
3507 }
3508
2e702c99
RM
3509 if (load_seg != NULL && target->isolate_execinstr())
3510 {
3511 // Process the early segments again, setting their file offsets
3512 // so they land after the segments starting at LOAD_SEG.
3513 off = align_file_offset(off, 0, target->abi_pagesize());
3514
3515 for (Segment_list::iterator p = this->segment_list_.begin();
3516 *p != load_seg;
3517 ++p)
3518 {
3519 if ((*p)->type() == elfcpp::PT_LOAD)
3520 {
3521 // We repeat the whole job of assigning addresses and
3522 // offsets, but we really only want to change the offsets and
3523 // must ensure that the addresses all come out the same as
3524 // they did the first time through.
3525 bool has_relro = false;
3526 const uint64_t old_addr = (*p)->vaddr();
3527 const uint64_t old_end = old_addr + (*p)->memsz();
3528 uint64_t new_addr = (*p)->set_section_addresses(this, true,
3529 old_addr,
3530 &increase_relro,
3531 &has_relro,
3532 &off,
3533 &shndx_begin);
3534 gold_assert(new_addr == old_end);
3535 }
3536 }
3537
3538 gold_assert(shndx_begin == shndx_load_seg);
3539 }
3540
75f65a3e
ILT
3541 // Handle the non-PT_LOAD segments, setting their offsets from their
3542 // section's offsets.
3543 for (Segment_list::iterator p = this->segment_list_.begin();
3544 p != this->segment_list_.end();
3545 ++p)
3546 {
3547 if ((*p)->type() != elfcpp::PT_LOAD)
1a2dff53
ILT
3548 (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
3549 ? increase_relro
3550 : 0);
75f65a3e
ILT
3551 }
3552
7bf1f802
ILT
3553 // Set the TLS offsets for each section in the PT_TLS segment.
3554 if (this->tls_segment_ != NULL)
3555 this->tls_segment_->set_tls_offsets();
3556
75f65a3e
ILT
3557 return off;
3558}
3559
6a74a719
ILT
3560// Set the offsets of all the allocated sections when doing a
3561// relocatable link. This does the same jobs as set_segment_offsets,
3562// only for a relocatable link.
3563
3564off_t
3565Layout::set_relocatable_section_offsets(Output_data* file_header,
ca09d69a 3566 unsigned int* pshndx)
6a74a719
ILT
3567{
3568 off_t off = 0;
3569
3570 file_header->set_address_and_file_offset(0, 0);
3571 off += file_header->data_size();
3572
3573 for (Section_list::iterator p = this->section_list_.begin();
3574 p != this->section_list_.end();
3575 ++p)
3576 {
3577 // We skip unallocated sections here, except that group sections
3578 // have to come first.
3579 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
3580 && (*p)->type() != elfcpp::SHT_GROUP)
3581 continue;
3582
3583 off = align_address(off, (*p)->addralign());
3584
3585 // The linker script might have set the address.
3586 if (!(*p)->is_address_valid())
3587 (*p)->set_address(0);
3588 (*p)->set_file_offset(off);
3589 (*p)->finalize_data_size();
3590 off += (*p)->data_size();
3591
3592 (*p)->set_out_shndx(*pshndx);
3593 ++*pshndx;
3594 }
3595
3596 return off;
3597}
3598
75f65a3e
ILT
3599// Set the file offset of all the sections not associated with a
3600// segment.
3601
3602off_t
9a0910c3 3603Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
75f65a3e 3604{
cdc29364
CC
3605 off_t startoff = off;
3606 off_t maxoff = off;
3607
a3ad94ed
ILT
3608 for (Section_list::iterator p = this->unattached_section_list_.begin();
3609 p != this->unattached_section_list_.end();
75f65a3e
ILT
3610 ++p)
3611 {
27bc2bce
ILT
3612 // The symtab section is handled in create_symtab_sections.
3613 if (*p == this->symtab_section_)
61ba1cf9 3614 continue;
27bc2bce 3615
a9a60db6
ILT
3616 // If we've already set the data size, don't set it again.
3617 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
3618 continue;
3619
96803768
ILT
3620 if (pass == BEFORE_INPUT_SECTIONS_PASS
3621 && (*p)->requires_postprocessing())
17a1d0a9
ILT
3622 {
3623 (*p)->create_postprocessing_buffer();
3624 this->any_postprocessing_sections_ = true;
3625 }
96803768 3626
9a0910c3 3627 if (pass == BEFORE_INPUT_SECTIONS_PASS
2e702c99
RM
3628 && (*p)->after_input_sections())
3629 continue;
17a1d0a9 3630 else if (pass == POSTPROCESSING_SECTIONS_PASS
2e702c99
RM
3631 && (!(*p)->after_input_sections()
3632 || (*p)->type() == elfcpp::SHT_STRTAB))
3633 continue;
17a1d0a9 3634 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2e702c99
RM
3635 && (!(*p)->after_input_sections()
3636 || (*p)->type() != elfcpp::SHT_STRTAB))
3637 continue;
27bc2bce 3638
cdc29364
CC
3639 if (!parameters->incremental_update())
3640 {
3641 off = align_address(off, (*p)->addralign());
3642 (*p)->set_file_offset(off);
3643 (*p)->finalize_data_size();
3644 }
3645 else
3646 {
3647 // Incremental update: allocate file space from free list.
3648 (*p)->pre_finalize_data_size();
3649 off_t current_size = (*p)->current_data_size();
3650 off = this->allocate(current_size, (*p)->addralign(), startoff);
3651 if (off == -1)
3652 {
3653 if (is_debugging_enabled(DEBUG_INCREMENTAL))
2e702c99 3654 this->free_list_.dump();
cdc29364 3655 gold_assert((*p)->output_section() != NULL);
e6455dfb
CC
3656 gold_fallback(_("out of patch space for section %s; "
3657 "relink with --incremental-full"),
3658 (*p)->output_section()->name());
cdc29364
CC
3659 }
3660 (*p)->set_file_offset(off);
3661 (*p)->finalize_data_size();
3662 if ((*p)->data_size() > current_size)
3663 {
3664 gold_assert((*p)->output_section() != NULL);
e6455dfb
CC
3665 gold_fallback(_("%s: section changed size; "
3666 "relink with --incremental-full"),
3667 (*p)->output_section()->name());
cdc29364
CC
3668 }
3669 gold_debug(DEBUG_INCREMENTAL,
3670 "set_section_offsets: %08lx %08lx %s",
3671 static_cast<long>(off),
3672 static_cast<long>((*p)->data_size()),
3673 ((*p)->output_section() != NULL
3674 ? (*p)->output_section()->name() : "(special)"));
3675 }
3676
75f65a3e 3677 off += (*p)->data_size();
cdc29364 3678 if (off > maxoff)
2e702c99 3679 maxoff = off;
96803768
ILT
3680
3681 // At this point the name must be set.
17a1d0a9 3682 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
96803768 3683 this->namepool_.add((*p)->name(), false, NULL);
75f65a3e 3684 }
cdc29364 3685 return maxoff;
75f65a3e
ILT
3686}
3687
86887060
ILT
3688// Set the section indexes of all the sections not associated with a
3689// segment.
3690
3691unsigned int
3692Layout::set_section_indexes(unsigned int shndx)
3693{
3694 for (Section_list::iterator p = this->unattached_section_list_.begin();
3695 p != this->unattached_section_list_.end();
3696 ++p)
3697 {
d491d34e
ILT
3698 if (!(*p)->has_out_shndx())
3699 {
3700 (*p)->set_out_shndx(shndx);
3701 ++shndx;
3702 }
86887060
ILT
3703 }
3704 return shndx;
3705}
3706
a445fddf
ILT
3707// Set the section addresses according to the linker script. This is
3708// only called when we see a SECTIONS clause. This returns the
3709// program segment which should hold the file header and segment
3710// headers, if any. It will return NULL if they should not be in a
3711// segment.
3712
3713Output_segment*
3714Layout::set_section_addresses_from_script(Symbol_table* symtab)
20e6d0d6
DK
3715{
3716 Script_sections* ss = this->script_options_->script_sections();
3717 gold_assert(ss->saw_sections_clause());
3718 return this->script_options_->set_section_addresses(symtab, this);
3719}
3720
3721// Place the orphan sections in the linker script.
3722
3723void
3724Layout::place_orphan_sections_in_script()
a445fddf
ILT
3725{
3726 Script_sections* ss = this->script_options_->script_sections();
3727 gold_assert(ss->saw_sections_clause());
3728
3729 // Place each orphaned output section in the script.
3730 for (Section_list::iterator p = this->section_list_.begin();
3731 p != this->section_list_.end();
3732 ++p)
3733 {
3734 if (!(*p)->found_in_sections_clause())
3735 ss->place_orphan(*p);
3736 }
a445fddf
ILT
3737}
3738
7bf1f802
ILT
3739// Count the local symbols in the regular symbol table and the dynamic
3740// symbol table, and build the respective string pools.
3741
3742void
17a1d0a9
ILT
3743Layout::count_local_symbols(const Task* task,
3744 const Input_objects* input_objects)
7bf1f802 3745{
6d013333
ILT
3746 // First, figure out an upper bound on the number of symbols we'll
3747 // be inserting into each pool. This helps us create the pools with
3748 // the right size, to avoid unnecessary hashtable resizing.
3749 unsigned int symbol_count = 0;
3750 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3751 p != input_objects->relobj_end();
3752 ++p)
3753 symbol_count += (*p)->local_symbol_count();
3754
3755 // Go from "upper bound" to "estimate." We overcount for two
3756 // reasons: we double-count symbols that occur in more than one
3757 // object file, and we count symbols that are dropped from the
3758 // output. Add it all together and assume we overcount by 100%.
3759 symbol_count /= 2;
3760
3761 // We assume all symbols will go into both the sympool and dynpool.
3762 this->sympool_.reserve(symbol_count);
3763 this->dynpool_.reserve(symbol_count);
3764
7bf1f802
ILT
3765 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3766 p != input_objects->relobj_end();
3767 ++p)
3768 {
17a1d0a9 3769 Task_lock_obj<Object> tlo(task, *p);
7bf1f802
ILT
3770 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
3771 }
3772}
3773
b8e6aad9
ILT
3774// Create the symbol table sections. Here we also set the final
3775// values of the symbols. At this point all the loadable sections are
d491d34e 3776// fully laid out. SHNUM is the number of sections so far.
75f65a3e
ILT
3777
3778void
9025d29d 3779Layout::create_symtab_sections(const Input_objects* input_objects,
75f65a3e 3780 Symbol_table* symtab,
d491d34e 3781 unsigned int shnum,
16649710 3782 off_t* poff)
75f65a3e 3783{
61ba1cf9
ILT
3784 int symsize;
3785 unsigned int align;
8851ecca 3786 if (parameters->target().get_size() == 32)
61ba1cf9
ILT
3787 {
3788 symsize = elfcpp::Elf_sizes<32>::sym_size;
3789 align = 4;
3790 }
8851ecca 3791 else if (parameters->target().get_size() == 64)
61ba1cf9
ILT
3792 {
3793 symsize = elfcpp::Elf_sizes<64>::sym_size;
3794 align = 8;
3795 }
3796 else
a3ad94ed 3797 gold_unreachable();
61ba1cf9 3798
cdc29364
CC
3799 // Compute file offsets relative to the start of the symtab section.
3800 off_t off = 0;
61ba1cf9
ILT
3801
3802 // Save space for the dummy symbol at the start of the section. We
3803 // never bother to write this out--it will just be left as zero.
3804 off += symsize;
c06b7b0b 3805 unsigned int local_symbol_index = 1;
61ba1cf9 3806
a3ad94ed
ILT
3807 // Add STT_SECTION symbols for each Output section which needs one.
3808 for (Section_list::iterator p = this->section_list_.begin();
3809 p != this->section_list_.end();
3810 ++p)
3811 {
3812 if (!(*p)->needs_symtab_index())
3813 (*p)->set_symtab_index(-1U);
3814 else
3815 {
3816 (*p)->set_symtab_index(local_symbol_index);
3817 ++local_symbol_index;
3818 off += symsize;
3819 }
3820 }
3821
f6ce93d6
ILT
3822 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3823 p != input_objects->relobj_end();
75f65a3e
ILT
3824 ++p)
3825 {
c06b7b0b 3826 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2e702c99 3827 off, symtab);
c06b7b0b
ILT
3828 off += (index - local_symbol_index) * symsize;
3829 local_symbol_index = index;
75f65a3e
ILT
3830 }
3831
c06b7b0b 3832 unsigned int local_symcount = local_symbol_index;
cdc29364 3833 gold_assert(static_cast<off_t>(local_symcount * symsize) == off);
61ba1cf9 3834
16649710
ILT
3835 off_t dynoff;
3836 size_t dyn_global_index;
3837 size_t dyncount;
3838 if (this->dynsym_section_ == NULL)
3839 {
3840 dynoff = 0;
3841 dyn_global_index = 0;
3842 dyncount = 0;
3843 }
3844 else
3845 {
3846 dyn_global_index = this->dynsym_section_->info();
3847 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
3848 dynoff = this->dynsym_section_->offset() + locsize;
3849 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
f5c3f225 3850 gold_assert(static_cast<off_t>(dyncount * symsize)
16649710
ILT
3851 == this->dynsym_section_->data_size() - locsize);
3852 }
3853
cdc29364 3854 off_t global_off = off;
55a93433
ILT
3855 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
3856 &this->sympool_, &local_symcount);
75f65a3e 3857
8851ecca 3858 if (!parameters->options().strip_all())
9e2dcb77
ILT
3859 {
3860 this->sympool_.set_string_offsets();
61ba1cf9 3861
cfd73a4e 3862 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
9e2dcb77
ILT
3863 Output_section* osymtab = this->make_output_section(symtab_name,
3864 elfcpp::SHT_SYMTAB,
22f0da72
ILT
3865 0, ORDER_INVALID,
3866 false);
9e2dcb77 3867 this->symtab_section_ = osymtab;
a3ad94ed 3868
cdc29364 3869 Output_section_data* pos = new Output_data_fixed_space(off, align,
7d9e3d98 3870 "** symtab");
9e2dcb77 3871 osymtab->add_output_section_data(pos);
61ba1cf9 3872
d491d34e
ILT
3873 // We generate a .symtab_shndx section if we have more than
3874 // SHN_LORESERVE sections. Technically it is possible that we
3875 // don't need one, because it is possible that there are no
3876 // symbols in any of sections with indexes larger than
3877 // SHN_LORESERVE. That is probably unusual, though, and it is
3878 // easier to always create one than to compute section indexes
3879 // twice (once here, once when writing out the symbols).
3880 if (shnum >= elfcpp::SHN_LORESERVE)
3881 {
3882 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
3883 false, NULL);
3884 Output_section* osymtab_xindex =
3885 this->make_output_section(symtab_xindex_name,
22f0da72
ILT
3886 elfcpp::SHT_SYMTAB_SHNDX, 0,
3887 ORDER_INVALID, false);
d491d34e 3888
cdc29364 3889 size_t symcount = off / symsize;
d491d34e
ILT
3890 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
3891
3892 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
3893
3894 osymtab_xindex->set_link_section(osymtab);
3895 osymtab_xindex->set_addralign(4);
3896 osymtab_xindex->set_entsize(4);
3897
3898 osymtab_xindex->set_after_input_sections();
3899
3900 // This tells the driver code to wait until the symbol table
3901 // has written out before writing out the postprocessing
3902 // sections, including the .symtab_shndx section.
3903 this->any_postprocessing_sections_ = true;
3904 }
3905
cfd73a4e 3906 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
9e2dcb77
ILT
3907 Output_section* ostrtab = this->make_output_section(strtab_name,
3908 elfcpp::SHT_STRTAB,
22f0da72
ILT
3909 0, ORDER_INVALID,
3910 false);
a3ad94ed 3911
9e2dcb77
ILT
3912 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
3913 ostrtab->add_output_section_data(pstr);
61ba1cf9 3914
cdc29364
CC
3915 off_t symtab_off;
3916 if (!parameters->incremental_update())
3917 symtab_off = align_address(*poff, align);
3918 else
3919 {
3920 symtab_off = this->allocate(off, align, *poff);
2e702c99 3921 if (off == -1)
e6455dfb
CC
3922 gold_fallback(_("out of patch space for symbol table; "
3923 "relink with --incremental-full"));
cdc29364
CC
3924 gold_debug(DEBUG_INCREMENTAL,
3925 "create_symtab_sections: %08lx %08lx .symtab",
3926 static_cast<long>(symtab_off),
3927 static_cast<long>(off));
3928 }
3929
3930 symtab->set_file_offset(symtab_off + global_off);
3931 osymtab->set_file_offset(symtab_off);
27bc2bce 3932 osymtab->finalize_data_size();
9e2dcb77
ILT
3933 osymtab->set_link_section(ostrtab);
3934 osymtab->set_info(local_symcount);
3935 osymtab->set_entsize(symsize);
61ba1cf9 3936
cdc29364
CC
3937 if (symtab_off + off > *poff)
3938 *poff = symtab_off + off;
9e2dcb77 3939 }
75f65a3e
ILT
3940}
3941
3942// Create the .shstrtab section, which holds the names of the
3943// sections. At the time this is called, we have created all the
3944// output sections except .shstrtab itself.
3945
3946Output_section*
3947Layout::create_shstrtab()
3948{
3949 // FIXME: We don't need to create a .shstrtab section if we are
3950 // stripping everything.
3951
cfd73a4e 3952 const char* name = this->namepool_.add(".shstrtab", false, NULL);
75f65a3e 3953
f5c870d2 3954 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
22f0da72 3955 ORDER_INVALID, false);
75f65a3e 3956
0e0d5469
ILT
3957 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
3958 {
3959 // We can't write out this section until we've set all the
3960 // section names, and we don't set the names of compressed
3961 // output sections until relocations are complete. FIXME: With
3962 // the current names we use, this is unnecessary.
3963 os->set_after_input_sections();
3964 }
27bc2bce 3965
a3ad94ed
ILT
3966 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
3967 os->add_output_section_data(posd);
75f65a3e
ILT
3968
3969 return os;
3970}
3971
3972// Create the section headers. SIZE is 32 or 64. OFF is the file
3973// offset.
3974
27bc2bce 3975void
d491d34e 3976Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
75f65a3e
ILT
3977{
3978 Output_section_headers* oshdrs;
9025d29d 3979 oshdrs = new Output_section_headers(this,
16649710 3980 &this->segment_list_,
6a74a719 3981 &this->section_list_,
16649710 3982 &this->unattached_section_list_,
d491d34e
ILT
3983 &this->namepool_,
3984 shstrtab_section);
cdc29364
CC
3985 off_t off;
3986 if (!parameters->incremental_update())
3987 off = align_address(*poff, oshdrs->addralign());
3988 else
3989 {
3990 oshdrs->pre_finalize_data_size();
3991 off = this->allocate(oshdrs->data_size(), oshdrs->addralign(), *poff);
3992 if (off == -1)
e6455dfb
CC
3993 gold_fallback(_("out of patch space for section header table; "
3994 "relink with --incremental-full"));
cdc29364
CC
3995 gold_debug(DEBUG_INCREMENTAL,
3996 "create_shdrs: %08lx %08lx (section header table)",
3997 static_cast<long>(off),
3998 static_cast<long>(off + oshdrs->data_size()));
3999 }
27bc2bce 4000 oshdrs->set_address_and_file_offset(0, off);
61ba1cf9 4001 off += oshdrs->data_size();
cdc29364
CC
4002 if (off > *poff)
4003 *poff = off;
27bc2bce 4004 this->section_headers_ = oshdrs;
54dc6425
ILT
4005}
4006
d491d34e
ILT
4007// Count the allocated sections.
4008
4009size_t
4010Layout::allocated_output_section_count() const
4011{
4012 size_t section_count = 0;
4013 for (Segment_list::const_iterator p = this->segment_list_.begin();
4014 p != this->segment_list_.end();
4015 ++p)
4016 section_count += (*p)->output_section_count();
4017 return section_count;
4018}
4019
dbe717ef
ILT
4020// Create the dynamic symbol table.
4021
4022void
7bf1f802 4023Layout::create_dynamic_symtab(const Input_objects* input_objects,
2e702c99 4024 Symbol_table* symtab,
ca09d69a 4025 Output_section** pdynstr,
14b31740
ILT
4026 unsigned int* plocal_dynamic_count,
4027 std::vector<Symbol*>* pdynamic_symbols,
4028 Versions* pversions)
dbe717ef 4029{
a3ad94ed
ILT
4030 // Count all the symbols in the dynamic symbol table, and set the
4031 // dynamic symbol indexes.
dbe717ef 4032
a3ad94ed
ILT
4033 // Skip symbol 0, which is always all zeroes.
4034 unsigned int index = 1;
dbe717ef 4035
a3ad94ed
ILT
4036 // Add STT_SECTION symbols for each Output section which needs one.
4037 for (Section_list::iterator p = this->section_list_.begin();
4038 p != this->section_list_.end();
4039 ++p)
4040 {
4041 if (!(*p)->needs_dynsym_index())
4042 (*p)->set_dynsym_index(-1U);
4043 else
4044 {
4045 (*p)->set_dynsym_index(index);
4046 ++index;
4047 }
4048 }
4049
7bf1f802
ILT
4050 // Count the local symbols that need to go in the dynamic symbol table,
4051 // and set the dynamic symbol indexes.
4052 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4053 p != input_objects->relobj_end();
4054 ++p)
4055 {
4056 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
4057 index = new_index;
4058 }
a3ad94ed
ILT
4059
4060 unsigned int local_symcount = index;
14b31740 4061 *plocal_dynamic_count = local_symcount;
a3ad94ed 4062
9b07f471 4063 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
35cdfc9a 4064 &this->dynpool_, pversions);
a3ad94ed
ILT
4065
4066 int symsize;
4067 unsigned int align;
8851ecca 4068 const int size = parameters->target().get_size();
a3ad94ed
ILT
4069 if (size == 32)
4070 {
4071 symsize = elfcpp::Elf_sizes<32>::sym_size;
4072 align = 4;
4073 }
4074 else if (size == 64)
4075 {
4076 symsize = elfcpp::Elf_sizes<64>::sym_size;
4077 align = 8;
4078 }
4079 else
4080 gold_unreachable();
4081
14b31740
ILT
4082 // Create the dynamic symbol table section.
4083
3802b2dd
ILT
4084 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
4085 elfcpp::SHT_DYNSYM,
4086 elfcpp::SHF_ALLOC,
22f0da72
ILT
4087 false,
4088 ORDER_DYNAMIC_LINKER,
4089 false);
a3ad94ed 4090
6daf5215
ILT
4091 // Check for NULL as a linker script may discard .dynsym.
4092 if (dynsym != NULL)
4093 {
4094 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
4095 align,
4096 "** dynsym");
4097 dynsym->add_output_section_data(odata);
a3ad94ed 4098
6daf5215
ILT
4099 dynsym->set_info(local_symcount);
4100 dynsym->set_entsize(symsize);
4101 dynsym->set_addralign(align);
a3ad94ed 4102
6daf5215
ILT
4103 this->dynsym_section_ = dynsym;
4104 }
a3ad94ed 4105
16649710 4106 Output_data_dynamic* const odyn = this->dynamic_data_;
6daf5215
ILT
4107 if (odyn != NULL)
4108 {
4109 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
4110 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
4111 }
a3ad94ed 4112
d491d34e
ILT
4113 // If there are more than SHN_LORESERVE allocated sections, we
4114 // create a .dynsym_shndx section. It is possible that we don't
4115 // need one, because it is possible that there are no dynamic
4116 // symbols in any of the sections with indexes larger than
4117 // SHN_LORESERVE. This is probably unusual, though, and at this
4118 // time we don't know the actual section indexes so it is
4119 // inconvenient to check.
4120 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
4121 {
2ea97941 4122 Output_section* dynsym_xindex =
d491d34e
ILT
4123 this->choose_output_section(NULL, ".dynsym_shndx",
4124 elfcpp::SHT_SYMTAB_SHNDX,
4125 elfcpp::SHF_ALLOC,
22f0da72 4126 false, ORDER_DYNAMIC_LINKER, false);
d491d34e 4127
6daf5215
ILT
4128 if (dynsym_xindex != NULL)
4129 {
4130 this->dynsym_xindex_ = new Output_symtab_xindex(index);
d491d34e 4131
6daf5215 4132 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
d491d34e 4133
6daf5215
ILT
4134 dynsym_xindex->set_link_section(dynsym);
4135 dynsym_xindex->set_addralign(4);
4136 dynsym_xindex->set_entsize(4);
d491d34e 4137
6daf5215 4138 dynsym_xindex->set_after_input_sections();
d491d34e 4139
6daf5215
ILT
4140 // This tells the driver code to wait until the symbol table
4141 // has written out before writing out the postprocessing
4142 // sections, including the .dynsym_shndx section.
4143 this->any_postprocessing_sections_ = true;
4144 }
d491d34e
ILT
4145 }
4146
14b31740
ILT
4147 // Create the dynamic string table section.
4148
3802b2dd
ILT
4149 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
4150 elfcpp::SHT_STRTAB,
4151 elfcpp::SHF_ALLOC,
22f0da72
ILT
4152 false,
4153 ORDER_DYNAMIC_LINKER,
4154 false);
a3ad94ed 4155
6daf5215
ILT
4156 if (dynstr != NULL)
4157 {
4158 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
4159 dynstr->add_output_section_data(strdata);
a3ad94ed 4160
6daf5215
ILT
4161 if (dynsym != NULL)
4162 dynsym->set_link_section(dynstr);
4163 if (this->dynamic_section_ != NULL)
4164 this->dynamic_section_->set_link_section(dynstr);
16649710 4165
6daf5215
ILT
4166 if (odyn != NULL)
4167 {
4168 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
4169 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
4170 }
a3ad94ed 4171
6daf5215
ILT
4172 *pdynstr = dynstr;
4173 }
14b31740
ILT
4174
4175 // Create the hash tables.
4176
13670ee6
ILT
4177 if (strcmp(parameters->options().hash_style(), "sysv") == 0
4178 || strcmp(parameters->options().hash_style(), "both") == 0)
4179 {
4180 unsigned char* phash;
4181 unsigned int hashlen;
4182 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
4183 &phash, &hashlen);
4184
22f0da72
ILT
4185 Output_section* hashsec =
4186 this->choose_output_section(NULL, ".hash", elfcpp::SHT_HASH,
4187 elfcpp::SHF_ALLOC, false,
4188 ORDER_DYNAMIC_LINKER, false);
13670ee6
ILT
4189
4190 Output_section_data* hashdata = new Output_data_const_buffer(phash,
4191 hashlen,
7d9e3d98
ILT
4192 align,
4193 "** hash");
6daf5215
ILT
4194 if (hashsec != NULL && hashdata != NULL)
4195 hashsec->add_output_section_data(hashdata);
13670ee6 4196
6daf5215
ILT
4197 if (hashsec != NULL)
4198 {
4199 if (dynsym != NULL)
4200 hashsec->set_link_section(dynsym);
4201 hashsec->set_entsize(4);
4202 }
a3ad94ed 4203
6daf5215
ILT
4204 if (odyn != NULL)
4205 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
13670ee6
ILT
4206 }
4207
4208 if (strcmp(parameters->options().hash_style(), "gnu") == 0
4209 || strcmp(parameters->options().hash_style(), "both") == 0)
4210 {
4211 unsigned char* phash;
4212 unsigned int hashlen;
4213 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
4214 &phash, &hashlen);
a3ad94ed 4215
22f0da72
ILT
4216 Output_section* hashsec =
4217 this->choose_output_section(NULL, ".gnu.hash", elfcpp::SHT_GNU_HASH,
4218 elfcpp::SHF_ALLOC, false,
4219 ORDER_DYNAMIC_LINKER, false);
a3ad94ed 4220
13670ee6
ILT
4221 Output_section_data* hashdata = new Output_data_const_buffer(phash,
4222 hashlen,
7d9e3d98
ILT
4223 align,
4224 "** hash");
6daf5215
ILT
4225 if (hashsec != NULL && hashdata != NULL)
4226 hashsec->add_output_section_data(hashdata);
a3ad94ed 4227
6daf5215
ILT
4228 if (hashsec != NULL)
4229 {
4230 if (dynsym != NULL)
4231 hashsec->set_link_section(dynsym);
1b81fb71 4232
6daf5215
ILT
4233 // For a 64-bit target, the entries in .gnu.hash do not have
4234 // a uniform size, so we only set the entry size for a
4235 // 32-bit target.
4236 if (parameters->target().get_size() == 32)
4237 hashsec->set_entsize(4);
a3ad94ed 4238
6daf5215
ILT
4239 if (odyn != NULL)
4240 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
4241 }
13670ee6 4242 }
dbe717ef
ILT
4243}
4244
7bf1f802
ILT
4245// Assign offsets to each local portion of the dynamic symbol table.
4246
4247void
4248Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
4249{
4250 Output_section* dynsym = this->dynsym_section_;
6daf5215
ILT
4251 if (dynsym == NULL)
4252 return;
7bf1f802
ILT
4253
4254 off_t off = dynsym->offset();
4255
4256 // Skip the dummy symbol at the start of the section.
4257 off += dynsym->entsize();
4258
4259 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4260 p != input_objects->relobj_end();
4261 ++p)
4262 {
4263 unsigned int count = (*p)->set_local_dynsym_offset(off);
4264 off += count * dynsym->entsize();
4265 }
4266}
4267
14b31740
ILT
4268// Create the version sections.
4269
4270void
9025d29d 4271Layout::create_version_sections(const Versions* versions,
46fe1623 4272 const Symbol_table* symtab,
14b31740
ILT
4273 unsigned int local_symcount,
4274 const std::vector<Symbol*>& dynamic_symbols,
4275 const Output_section* dynstr)
4276{
4277 if (!versions->any_defs() && !versions->any_needs())
4278 return;
4279
8851ecca 4280 switch (parameters->size_and_endianness())
14b31740 4281 {
193a53d9 4282#ifdef HAVE_TARGET_32_LITTLE
8851ecca 4283 case Parameters::TARGET_32_LITTLE:
7d1a9ebb
ILT
4284 this->sized_create_version_sections<32, false>(versions, symtab,
4285 local_symcount,
4286 dynamic_symbols, dynstr);
8851ecca 4287 break;
193a53d9 4288#endif
8851ecca
ILT
4289#ifdef HAVE_TARGET_32_BIG
4290 case Parameters::TARGET_32_BIG:
7d1a9ebb
ILT
4291 this->sized_create_version_sections<32, true>(versions, symtab,
4292 local_symcount,
4293 dynamic_symbols, dynstr);
8851ecca 4294 break;
193a53d9 4295#endif
193a53d9 4296#ifdef HAVE_TARGET_64_LITTLE
8851ecca 4297 case Parameters::TARGET_64_LITTLE:
7d1a9ebb
ILT
4298 this->sized_create_version_sections<64, false>(versions, symtab,
4299 local_symcount,
4300 dynamic_symbols, dynstr);
8851ecca 4301 break;
193a53d9 4302#endif
8851ecca
ILT
4303#ifdef HAVE_TARGET_64_BIG
4304 case Parameters::TARGET_64_BIG:
7d1a9ebb
ILT
4305 this->sized_create_version_sections<64, true>(versions, symtab,
4306 local_symcount,
4307 dynamic_symbols, dynstr);
8851ecca
ILT
4308 break;
4309#endif
4310 default:
4311 gold_unreachable();
14b31740 4312 }
14b31740
ILT
4313}
4314
4315// Create the version sections, sized version.
4316
4317template<int size, bool big_endian>
4318void
4319Layout::sized_create_version_sections(
4320 const Versions* versions,
46fe1623 4321 const Symbol_table* symtab,
14b31740
ILT
4322 unsigned int local_symcount,
4323 const std::vector<Symbol*>& dynamic_symbols,
7d1a9ebb 4324 const Output_section* dynstr)
14b31740 4325{
3802b2dd
ILT
4326 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
4327 elfcpp::SHT_GNU_versym,
4328 elfcpp::SHF_ALLOC,
22f0da72
ILT
4329 false,
4330 ORDER_DYNAMIC_LINKER,
4331 false);
14b31740 4332
6daf5215
ILT
4333 // Check for NULL since a linker script may discard this section.
4334 if (vsec != NULL)
4335 {
4336 unsigned char* vbuf;
4337 unsigned int vsize;
4338 versions->symbol_section_contents<size, big_endian>(symtab,
4339 &this->dynpool_,
4340 local_symcount,
4341 dynamic_symbols,
4342 &vbuf, &vsize);
4343
4344 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
4345 "** versions");
4346
4347 vsec->add_output_section_data(vdata);
4348 vsec->set_entsize(2);
4349 vsec->set_link_section(this->dynsym_section_);
4350 }
14b31740
ILT
4351
4352 Output_data_dynamic* const odyn = this->dynamic_data_;
6daf5215
ILT
4353 if (odyn != NULL && vsec != NULL)
4354 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
14b31740
ILT
4355
4356 if (versions->any_defs())
4357 {
3802b2dd 4358 Output_section* vdsec;
6daf5215
ILT
4359 vdsec = this->choose_output_section(NULL, ".gnu.version_d",
4360 elfcpp::SHT_GNU_verdef,
4361 elfcpp::SHF_ALLOC,
4362 false, ORDER_DYNAMIC_LINKER, false);
4363
4364 if (vdsec != NULL)
4365 {
4366 unsigned char* vdbuf;
4367 unsigned int vdsize;
4368 unsigned int vdentries;
4369 versions->def_section_contents<size, big_endian>(&this->dynpool_,
4370 &vdbuf, &vdsize,
4371 &vdentries);
4372
4373 Output_section_data* vddata =
4374 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
4375
4376 vdsec->add_output_section_data(vddata);
4377 vdsec->set_link_section(dynstr);
4378 vdsec->set_info(vdentries);
4379
4380 if (odyn != NULL)
4381 {
4382 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
4383 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
4384 }
4385 }
14b31740
ILT
4386 }
4387
4388 if (versions->any_needs())
4389 {
14b31740 4390 Output_section* vnsec;
3802b2dd
ILT
4391 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
4392 elfcpp::SHT_GNU_verneed,
4393 elfcpp::SHF_ALLOC,
22f0da72 4394 false, ORDER_DYNAMIC_LINKER, false);
14b31740 4395
6daf5215
ILT
4396 if (vnsec != NULL)
4397 {
4398 unsigned char* vnbuf;
4399 unsigned int vnsize;
4400 unsigned int vnentries;
4401 versions->need_section_contents<size, big_endian>(&this->dynpool_,
4402 &vnbuf, &vnsize,
4403 &vnentries);
14b31740 4404
6daf5215
ILT
4405 Output_section_data* vndata =
4406 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
14b31740 4407
6daf5215
ILT
4408 vnsec->add_output_section_data(vndata);
4409 vnsec->set_link_section(dynstr);
4410 vnsec->set_info(vnentries);
14b31740 4411
6daf5215
ILT
4412 if (odyn != NULL)
4413 {
4414 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
4415 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
4416 }
4417 }
14b31740
ILT
4418 }
4419}
4420
dbe717ef
ILT
4421// Create the .interp section and PT_INTERP segment.
4422
4423void
4424Layout::create_interp(const Target* target)
4425{
10b4f102
ILT
4426 gold_assert(this->interp_segment_ == NULL);
4427
e55bde5e 4428 const char* interp = parameters->options().dynamic_linker();
dbe717ef
ILT
4429 if (interp == NULL)
4430 {
4431 interp = target->dynamic_linker();
a3ad94ed 4432 gold_assert(interp != NULL);
dbe717ef
ILT
4433 }
4434
4435 size_t len = strlen(interp) + 1;
4436
4437 Output_section_data* odata = new Output_data_const(interp, len, 1);
4438
e1f74f98
ILT
4439 Output_section* osec = this->choose_output_section(NULL, ".interp",
4440 elfcpp::SHT_PROGBITS,
4441 elfcpp::SHF_ALLOC,
4442 false, ORDER_INTERP,
4443 false);
6daf5215
ILT
4444 if (osec != NULL)
4445 osec->add_output_section_data(odata);
dbe717ef
ILT
4446}
4447
ea715a34
ILT
4448// Add dynamic tags for the PLT and the dynamic relocs. This is
4449// called by the target-specific code. This does nothing if not doing
4450// a dynamic link.
4451
4452// USE_REL is true for REL relocs rather than RELA relocs.
4453
4454// If PLT_GOT is not NULL, then DT_PLTGOT points to it.
4455
4456// If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
e291e7b9
ILT
4457// and we also set DT_PLTREL. We use PLT_REL's output section, since
4458// some targets have multiple reloc sections in PLT_REL.
ea715a34
ILT
4459
4460// If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
67181c72
ILT
4461// DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT. Again we use the output
4462// section.
ea715a34
ILT
4463
4464// If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
4465// executable.
4466
4467void
4468Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
4469 const Output_data* plt_rel,
3a44184e 4470 const Output_data_reloc_generic* dyn_rel,
612a8d3d 4471 bool add_debug, bool dynrel_includes_plt)
ea715a34
ILT
4472{
4473 Output_data_dynamic* odyn = this->dynamic_data_;
4474 if (odyn == NULL)
4475 return;
4476
4477 if (plt_got != NULL && plt_got->output_section() != NULL)
4478 odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
4479
4480 if (plt_rel != NULL && plt_rel->output_section() != NULL)
4481 {
e291e7b9
ILT
4482 odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
4483 odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
ea715a34
ILT
4484 odyn->add_constant(elfcpp::DT_PLTREL,
4485 use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
4486 }
4487
82435b3b
ILT
4488 if ((dyn_rel != NULL && dyn_rel->output_section() != NULL)
4489 || (dynrel_includes_plt
4490 && plt_rel != NULL
4491 && plt_rel->output_section() != NULL))
ea715a34 4492 {
82435b3b
ILT
4493 bool have_dyn_rel = dyn_rel != NULL && dyn_rel->output_section() != NULL;
4494 bool have_plt_rel = plt_rel != NULL && plt_rel->output_section() != NULL;
ea715a34 4495 odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
82435b3b
ILT
4496 (have_dyn_rel
4497 ? dyn_rel->output_section()
4498 : plt_rel->output_section()));
4499 elfcpp::DT size_tag = use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ;
4500 if (have_dyn_rel && have_plt_rel && dynrel_includes_plt)
4501 odyn->add_section_size(size_tag,
67181c72
ILT
4502 dyn_rel->output_section(),
4503 plt_rel->output_section());
82435b3b
ILT
4504 else if (have_dyn_rel)
4505 odyn->add_section_size(size_tag, dyn_rel->output_section());
612a8d3d 4506 else
82435b3b 4507 odyn->add_section_size(size_tag, plt_rel->output_section());
ea715a34
ILT
4508 const int size = parameters->target().get_size();
4509 elfcpp::DT rel_tag;
4510 int rel_size;
4511 if (use_rel)
4512 {
4513 rel_tag = elfcpp::DT_RELENT;
4514 if (size == 32)
4515 rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
4516 else if (size == 64)
4517 rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
4518 else
4519 gold_unreachable();
4520 }
4521 else
4522 {
4523 rel_tag = elfcpp::DT_RELAENT;
4524 if (size == 32)
4525 rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
4526 else if (size == 64)
4527 rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
4528 else
4529 gold_unreachable();
4530 }
4531 odyn->add_constant(rel_tag, rel_size);
3a44184e 4532
82435b3b 4533 if (parameters->options().combreloc() && have_dyn_rel)
3a44184e
ILT
4534 {
4535 size_t c = dyn_rel->relative_reloc_count();
4536 if (c > 0)
4537 odyn->add_constant((use_rel
4538 ? elfcpp::DT_RELCOUNT
4539 : elfcpp::DT_RELACOUNT),
4540 c);
4541 }
ea715a34
ILT
4542 }
4543
4544 if (add_debug && !parameters->options().shared())
4545 {
4546 // The value of the DT_DEBUG tag is filled in by the dynamic
4547 // linker at run time, and used by the debugger.
4548 odyn->add_constant(elfcpp::DT_DEBUG, 0);
4549 }
4550}
4551
a3ad94ed
ILT
4552// Finish the .dynamic section and PT_DYNAMIC segment.
4553
4554void
4555Layout::finish_dynamic_section(const Input_objects* input_objects,
16649710 4556 const Symbol_table* symtab)
a3ad94ed 4557{
6daf5215
ILT
4558 if (!this->script_options_->saw_phdrs_clause()
4559 && this->dynamic_section_ != NULL)
1c4f3631
ILT
4560 {
4561 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
4562 (elfcpp::PF_R
4563 | elfcpp::PF_W));
22f0da72
ILT
4564 oseg->add_output_section_to_nonload(this->dynamic_section_,
4565 elfcpp::PF_R | elfcpp::PF_W);
1c4f3631 4566 }
a3ad94ed 4567
16649710 4568 Output_data_dynamic* const odyn = this->dynamic_data_;
6daf5215
ILT
4569 if (odyn == NULL)
4570 return;
16649710 4571
a3ad94ed
ILT
4572 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
4573 p != input_objects->dynobj_end();
4574 ++p)
4575 {
0f1c85a6 4576 if (!(*p)->is_needed() && (*p)->as_needed())
594c8e5e
ILT
4577 {
4578 // This dynamic object was linked with --as-needed, but it
4579 // is not needed.
4580 continue;
4581 }
4582
a3ad94ed
ILT
4583 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
4584 }
4585
8851ecca 4586 if (parameters->options().shared())
fced7afd 4587 {
e55bde5e 4588 const char* soname = parameters->options().soname();
fced7afd
ILT
4589 if (soname != NULL)
4590 odyn->add_string(elfcpp::DT_SONAME, soname);
4591 }
4592
c6585162 4593 Symbol* sym = symtab->lookup(parameters->options().init());
14b31740 4594 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
4595 odyn->add_symbol(elfcpp::DT_INIT, sym);
4596
c6585162 4597 sym = symtab->lookup(parameters->options().fini());
14b31740 4598 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
4599 odyn->add_symbol(elfcpp::DT_FINI, sym);
4600
f15f61a7
DK
4601 // Look for .init_array, .preinit_array and .fini_array by checking
4602 // section types.
4603 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
4604 p != this->section_list_.end();
4605 ++p)
4606 switch((*p)->type())
4607 {
4608 case elfcpp::SHT_FINI_ARRAY:
4609 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
2e702c99 4610 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
f15f61a7
DK
4611 break;
4612 case elfcpp::SHT_INIT_ARRAY:
4613 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
2e702c99 4614 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
f15f61a7
DK
4615 break;
4616 case elfcpp::SHT_PREINIT_ARRAY:
4617 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
2e702c99 4618 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
f15f61a7
DK
4619 break;
4620 default:
4621 break;
4622 }
2e702c99 4623
41f542e7 4624 // Add a DT_RPATH entry if needed.
e55bde5e 4625 const General_options::Dir_list& rpath(parameters->options().rpath());
41f542e7
ILT
4626 if (!rpath.empty())
4627 {
4628 std::string rpath_val;
4629 for (General_options::Dir_list::const_iterator p = rpath.begin();
2e702c99
RM
4630 p != rpath.end();
4631 ++p)
4632 {
4633 if (rpath_val.empty())
4634 rpath_val = p->name();
4635 else
4636 {
4637 // Eliminate duplicates.
4638 General_options::Dir_list::const_iterator q;
4639 for (q = rpath.begin(); q != p; ++q)
ad2d6943 4640 if (q->name() == p->name())
2e702c99
RM
4641 break;
4642 if (q == p)
4643 {
4644 rpath_val += ':';
4645 rpath_val += p->name();
4646 }
4647 }
4648 }
41f542e7
ILT
4649
4650 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
7c414435
DM
4651 if (parameters->options().enable_new_dtags())
4652 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
41f542e7 4653 }
4f4c5f80
ILT
4654
4655 // Look for text segments that have dynamic relocations.
4656 bool have_textrel = false;
4e8fe71f 4657 if (!this->script_options_->saw_sections_clause())
4f4c5f80 4658 {
4e8fe71f 4659 for (Segment_list::const_iterator p = this->segment_list_.begin();
2e702c99
RM
4660 p != this->segment_list_.end();
4661 ++p)
4662 {
4663 if ((*p)->type() == elfcpp::PT_LOAD
766f91bb 4664 && ((*p)->flags() & elfcpp::PF_W) == 0
2e702c99
RM
4665 && (*p)->has_dynamic_reloc())
4666 {
4667 have_textrel = true;
4668 break;
4669 }
4670 }
4e8fe71f
ILT
4671 }
4672 else
4673 {
4674 // We don't know the section -> segment mapping, so we are
4675 // conservative and just look for readonly sections with
4676 // relocations. If those sections wind up in writable segments,
4677 // then we have created an unnecessary DT_TEXTREL entry.
4678 for (Section_list::const_iterator p = this->section_list_.begin();
2e702c99
RM
4679 p != this->section_list_.end();
4680 ++p)
4681 {
4682 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
4683 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
4684 && (*p)->has_dynamic_reloc())
4685 {
4686 have_textrel = true;
4687 break;
4688 }
4689 }
4f4c5f80
ILT
4690 }
4691
886288f1
ILT
4692 if (parameters->options().filter() != NULL)
4693 odyn->add_string(elfcpp::DT_FILTER, parameters->options().filter());
4694 if (parameters->options().any_auxiliary())
4695 {
4696 for (options::String_set::const_iterator p =
4697 parameters->options().auxiliary_begin();
4698 p != parameters->options().auxiliary_end();
4699 ++p)
4700 odyn->add_string(elfcpp::DT_AUXILIARY, *p);
4701 }
4702
4703 // Add a DT_FLAGS entry if necessary.
4f4c5f80
ILT
4704 unsigned int flags = 0;
4705 if (have_textrel)
6a41d30b
ILT
4706 {
4707 // Add a DT_TEXTREL for compatibility with older loaders.
4708 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
4709 flags |= elfcpp::DF_TEXTREL;
b9674e17 4710
ffeef7df
ILT
4711 if (parameters->options().text())
4712 gold_error(_("read-only segment has dynamic relocations"));
4713 else if (parameters->options().warn_shared_textrel()
4714 && parameters->options().shared())
b9674e17 4715 gold_warning(_("shared library text segment is not shareable"));
6a41d30b 4716 }
8851ecca 4717 if (parameters->options().shared() && this->has_static_tls())
535890bb 4718 flags |= elfcpp::DF_STATIC_TLS;
7be8330a
CD
4719 if (parameters->options().origin())
4720 flags |= elfcpp::DF_ORIGIN;
f15f61a7
DK
4721 if (parameters->options().Bsymbolic())
4722 {
4723 flags |= elfcpp::DF_SYMBOLIC;
4724 // Add DT_SYMBOLIC for compatibility with older loaders.
4725 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
4726 }
e1c74d60
ILT
4727 if (parameters->options().now())
4728 flags |= elfcpp::DF_BIND_NOW;
0d212c3a
ILT
4729 if (flags != 0)
4730 odyn->add_constant(elfcpp::DT_FLAGS, flags);
7c414435
DM
4731
4732 flags = 0;
4733 if (parameters->options().initfirst())
4734 flags |= elfcpp::DF_1_INITFIRST;
4735 if (parameters->options().interpose())
4736 flags |= elfcpp::DF_1_INTERPOSE;
4737 if (parameters->options().loadfltr())
4738 flags |= elfcpp::DF_1_LOADFLTR;
4739 if (parameters->options().nodefaultlib())
4740 flags |= elfcpp::DF_1_NODEFLIB;
4741 if (parameters->options().nodelete())
4742 flags |= elfcpp::DF_1_NODELETE;
4743 if (parameters->options().nodlopen())
4744 flags |= elfcpp::DF_1_NOOPEN;
4745 if (parameters->options().nodump())
4746 flags |= elfcpp::DF_1_NODUMP;
4747 if (!parameters->options().shared())
4748 flags &= ~(elfcpp::DF_1_INITFIRST
4749 | elfcpp::DF_1_NODELETE
4750 | elfcpp::DF_1_NOOPEN);
7be8330a
CD
4751 if (parameters->options().origin())
4752 flags |= elfcpp::DF_1_ORIGIN;
e1c74d60
ILT
4753 if (parameters->options().now())
4754 flags |= elfcpp::DF_1_NOW;
e2153196
ILT
4755 if (parameters->options().Bgroup())
4756 flags |= elfcpp::DF_1_GROUP;
0d212c3a 4757 if (flags != 0)
7c414435 4758 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
a3ad94ed
ILT
4759}
4760
f0ba79e2
ILT
4761// Set the size of the _DYNAMIC symbol table to be the size of the
4762// dynamic data.
4763
4764void
4765Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
4766{
4767 Output_data_dynamic* const odyn = this->dynamic_data_;
6daf5215
ILT
4768 if (odyn == NULL)
4769 return;
f0ba79e2 4770 odyn->finalize_data_size();
6daf5215
ILT
4771 if (this->dynamic_symbol_ == NULL)
4772 return;
f0ba79e2
ILT
4773 off_t data_size = odyn->data_size();
4774 const int size = parameters->target().get_size();
4775 if (size == 32)
4776 symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
4777 else if (size == 64)
4778 symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
4779 else
4780 gold_unreachable();
4781}
4782
dff16297
ILT
4783// The mapping of input section name prefixes to output section names.
4784// In some cases one prefix is itself a prefix of another prefix; in
4785// such a case the longer prefix must come first. These prefixes are
4786// based on the GNU linker default ELF linker script.
a2fb1b05 4787
ead1e424 4788#define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
1be75daa 4789#define MAPPING_INIT_EXACT(f, t) { f, 0, t, sizeof(t) - 1 }
dff16297 4790const Layout::Section_name_mapping Layout::section_name_mapping[] =
a2fb1b05 4791{
dff16297 4792 MAPPING_INIT(".text.", ".text"),
dff16297 4793 MAPPING_INIT(".rodata.", ".rodata"),
9b689de0 4794 MAPPING_INIT(".data.rel.ro.local.", ".data.rel.ro.local"),
1be75daa 4795 MAPPING_INIT_EXACT(".data.rel.ro.local", ".data.rel.ro.local"),
9b689de0 4796 MAPPING_INIT(".data.rel.ro.", ".data.rel.ro"),
1be75daa 4797 MAPPING_INIT_EXACT(".data.rel.ro", ".data.rel.ro"),
dff16297
ILT
4798 MAPPING_INIT(".data.", ".data"),
4799 MAPPING_INIT(".bss.", ".bss"),
4800 MAPPING_INIT(".tdata.", ".tdata"),
4801 MAPPING_INIT(".tbss.", ".tbss"),
4802 MAPPING_INIT(".init_array.", ".init_array"),
4803 MAPPING_INIT(".fini_array.", ".fini_array"),
4804 MAPPING_INIT(".sdata.", ".sdata"),
4805 MAPPING_INIT(".sbss.", ".sbss"),
4806 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
4807 // differently depending on whether it is creating a shared library.
4808 MAPPING_INIT(".sdata2.", ".sdata"),
4809 MAPPING_INIT(".sbss2.", ".sbss"),
4810 MAPPING_INIT(".lrodata.", ".lrodata"),
4811 MAPPING_INIT(".ldata.", ".ldata"),
4812 MAPPING_INIT(".lbss.", ".lbss"),
4813 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
4814 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
4815 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
4816 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
4817 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
4818 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
4819 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
4820 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
4821 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
4822 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
4823 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
4824 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
4825 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
4826 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
4827 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
4828 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
4829 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
4a54abbb 4830 MAPPING_INIT(".ARM.extab", ".ARM.extab"),
1dcd334d 4831 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
4a54abbb 4832 MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
1dcd334d 4833 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
a2fb1b05
ILT
4834};
4835#undef MAPPING_INIT
1be75daa 4836#undef MAPPING_INIT_EXACT
a2fb1b05 4837
dff16297
ILT
4838const int Layout::section_name_mapping_count =
4839 (sizeof(Layout::section_name_mapping)
4840 / sizeof(Layout::section_name_mapping[0]));
a2fb1b05 4841
ead1e424
ILT
4842// Choose the output section name to use given an input section name.
4843// Set *PLEN to the length of the name. *PLEN is initialized to the
4844// length of NAME.
4845
4846const char*
5393d741
ILT
4847Layout::output_section_name(const Relobj* relobj, const char* name,
4848 size_t* plen)
ead1e424 4849{
af4a8a83
ILT
4850 // gcc 4.3 generates the following sorts of section names when it
4851 // needs a section name specific to a function:
4852 // .text.FN
4853 // .rodata.FN
4854 // .sdata2.FN
4855 // .data.FN
4856 // .data.rel.FN
4857 // .data.rel.local.FN
4858 // .data.rel.ro.FN
4859 // .data.rel.ro.local.FN
4860 // .sdata.FN
4861 // .bss.FN
4862 // .sbss.FN
4863 // .tdata.FN
4864 // .tbss.FN
4865
4866 // The GNU linker maps all of those to the part before the .FN,
4867 // except that .data.rel.local.FN is mapped to .data, and
4868 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
4869 // beginning with .data.rel.ro.local are grouped together.
4870
4871 // For an anonymous namespace, the string FN can contain a '.'.
4872
4873 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
4874 // GNU linker maps to .rodata.
4875
dff16297
ILT
4876 // The .data.rel.ro sections are used with -z relro. The sections
4877 // are recognized by name. We use the same names that the GNU
4878 // linker does for these sections.
af4a8a83 4879
dff16297
ILT
4880 // It is hard to handle this in a principled way, so we don't even
4881 // try. We use a table of mappings. If the input section name is
4882 // not found in the table, we simply use it as the output section
4883 // name.
af4a8a83 4884
dff16297
ILT
4885 const Section_name_mapping* psnm = section_name_mapping;
4886 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
ead1e424 4887 {
1be75daa 4888 if (psnm->fromlen > 0)
dff16297 4889 {
1be75daa
CC
4890 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
4891 {
4892 *plen = psnm->tolen;
4893 return psnm->to;
4894 }
4895 }
4896 else
4897 {
4898 if (strcmp(name, psnm->from) == 0)
4899 {
4900 *plen = psnm->tolen;
4901 return psnm->to;
4902 }
dff16297 4903 }
ead1e424
ILT
4904 }
4905
5393d741
ILT
4906 // As an additional complication, .ctors sections are output in
4907 // either .ctors or .init_array sections, and .dtors sections are
4908 // output in either .dtors or .fini_array sections.
4909 if (is_prefix_of(".ctors.", name) || is_prefix_of(".dtors.", name))
4910 {
4911 if (parameters->options().ctors_in_init_array())
4912 {
4913 *plen = 11;
4914 return name[1] == 'c' ? ".init_array" : ".fini_array";
4915 }
4916 else
4917 {
4918 *plen = 6;
4919 return name[1] == 'c' ? ".ctors" : ".dtors";
4920 }
4921 }
4922 if (parameters->options().ctors_in_init_array()
4923 && (strcmp(name, ".ctors") == 0 || strcmp(name, ".dtors") == 0))
4924 {
4925 // To make .init_array/.fini_array work with gcc we must exclude
4926 // .ctors and .dtors sections from the crtbegin and crtend
4927 // files.
4928 if (relobj == NULL
4929 || (!Layout::match_file_name(relobj, "crtbegin")
4930 && !Layout::match_file_name(relobj, "crtend")))
4931 {
4932 *plen = 11;
4933 return name[1] == 'c' ? ".init_array" : ".fini_array";
4934 }
4935 }
4936
ead1e424
ILT
4937 return name;
4938}
4939
5393d741
ILT
4940// Return true if RELOBJ is an input file whose base name matches
4941// FILE_NAME. The base name must have an extension of ".o", and must
4942// be exactly FILE_NAME.o or FILE_NAME, one character, ".o". This is
4943// to match crtbegin.o as well as crtbeginS.o without getting confused
4944// by other possibilities. Overall matching the file name this way is
4945// a dreadful hack, but the GNU linker does it in order to better
4946// support gcc, and we need to be compatible.
4947
4948bool
4949Layout::match_file_name(const Relobj* relobj, const char* match)
4950{
4951 const std::string& file_name(relobj->name());
4952 const char* base_name = lbasename(file_name.c_str());
4953 size_t match_len = strlen(match);
4954 if (strncmp(base_name, match, match_len) != 0)
4955 return false;
4956 size_t base_len = strlen(base_name);
4957 if (base_len != match_len + 2 && base_len != match_len + 3)
4958 return false;
4959 return memcmp(base_name + base_len - 2, ".o", 2) == 0;
4960}
4961
8a4c0b0d
ILT
4962// Check if a comdat group or .gnu.linkonce section with the given
4963// NAME is selected for the link. If there is already a section,
1ef4d87f
ILT
4964// *KEPT_SECTION is set to point to the existing section and the
4965// function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
4966// IS_GROUP_NAME are recorded for this NAME in the layout object,
4967// *KEPT_SECTION is set to the internal copy and the function returns
4968// true.
a2fb1b05
ILT
4969
4970bool
e55bde5e 4971Layout::find_or_add_kept_section(const std::string& name,
1ef4d87f
ILT
4972 Relobj* object,
4973 unsigned int shndx,
4974 bool is_comdat,
4975 bool is_group_name,
2e702c99 4976 Kept_section** kept_section)
a2fb1b05 4977{
e55bde5e
ILT
4978 // It's normal to see a couple of entries here, for the x86 thunk
4979 // sections. If we see more than a few, we're linking a C++
4980 // program, and we resize to get more space to minimize rehashing.
4981 if (this->signatures_.size() > 4
4982 && !this->resized_signatures_)
4983 {
4984 reserve_unordered_map(&this->signatures_,
4985 this->number_of_input_files_ * 64);
4986 this->resized_signatures_ = true;
4987 }
4988
1ef4d87f
ILT
4989 Kept_section candidate;
4990 std::pair<Signatures::iterator, bool> ins =
4991 this->signatures_.insert(std::make_pair(name, candidate));
a2fb1b05 4992
1ef4d87f 4993 if (kept_section != NULL)
8a4c0b0d 4994 *kept_section = &ins.first->second;
a2fb1b05
ILT
4995 if (ins.second)
4996 {
4997 // This is the first time we've seen this signature.
1ef4d87f
ILT
4998 ins.first->second.set_object(object);
4999 ins.first->second.set_shndx(shndx);
5000 if (is_comdat)
5001 ins.first->second.set_is_comdat();
5002 if (is_group_name)
5003 ins.first->second.set_is_group_name();
a2fb1b05
ILT
5004 return true;
5005 }
5006
1ef4d87f
ILT
5007 // We have already seen this signature.
5008
5009 if (ins.first->second.is_group_name())
a2fb1b05
ILT
5010 {
5011 // We've already seen a real section group with this signature.
1ef4d87f
ILT
5012 // If the kept group is from a plugin object, and we're in the
5013 // replacement phase, accept the new one as a replacement.
5014 if (ins.first->second.object() == NULL
2e702c99
RM
5015 && parameters->options().plugins()->in_replacement_phase())
5016 {
1ef4d87f
ILT
5017 ins.first->second.set_object(object);
5018 ins.first->second.set_shndx(shndx);
2e702c99
RM
5019 return true;
5020 }
a2fb1b05
ILT
5021 return false;
5022 }
1ef4d87f 5023 else if (is_group_name)
a2fb1b05
ILT
5024 {
5025 // This is a real section group, and we've already seen a
a0fa0c07 5026 // linkonce section with this signature. Record that we've seen
a2fb1b05 5027 // a section group, and don't include this section group.
1ef4d87f 5028 ins.first->second.set_is_group_name();
a2fb1b05
ILT
5029 return false;
5030 }
5031 else
5032 {
5033 // We've already seen a linkonce section and this is a linkonce
5034 // section. These don't block each other--this may be the same
5035 // symbol name with different section types.
5036 return true;
5037 }
5038}
5039
a445fddf
ILT
5040// Store the allocated sections into the section list.
5041
5042void
2ea97941 5043Layout::get_allocated_sections(Section_list* section_list) const
a445fddf
ILT
5044{
5045 for (Section_list::const_iterator p = this->section_list_.begin();
5046 p != this->section_list_.end();
5047 ++p)
5048 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
2ea97941 5049 section_list->push_back(*p);
a445fddf
ILT
5050}
5051
ec661b9d
AM
5052// Store the executable sections into the section list.
5053
5054void
5055Layout::get_executable_sections(Section_list* section_list) const
5056{
5057 for (Section_list::const_iterator p = this->section_list_.begin();
5058 p != this->section_list_.end();
5059 ++p)
5060 if (((*p)->flags() & (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
5061 == (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
5062 section_list->push_back(*p);
5063}
5064
a445fddf
ILT
5065// Create an output segment.
5066
5067Output_segment*
5068Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
5069{
8851ecca 5070 gold_assert(!parameters->options().relocatable());
a445fddf
ILT
5071 Output_segment* oseg = new Output_segment(type, flags);
5072 this->segment_list_.push_back(oseg);
2d924fd9
ILT
5073
5074 if (type == elfcpp::PT_TLS)
5075 this->tls_segment_ = oseg;
5076 else if (type == elfcpp::PT_GNU_RELRO)
5077 this->relro_segment_ = oseg;
10b4f102
ILT
5078 else if (type == elfcpp::PT_INTERP)
5079 this->interp_segment_ = oseg;
2d924fd9 5080
a445fddf
ILT
5081 return oseg;
5082}
5083
bec5b579
CC
5084// Return the file offset of the normal symbol table.
5085
5086off_t
5087Layout::symtab_section_offset() const
5088{
5089 if (this->symtab_section_ != NULL)
5090 return this->symtab_section_->offset();
5091 return 0;
5092}
5093
886f533a
ILT
5094// Return the section index of the normal symbol table. It may have
5095// been stripped by the -s/--strip-all option.
5096
5097unsigned int
5098Layout::symtab_section_shndx() const
5099{
5100 if (this->symtab_section_ != NULL)
5101 return this->symtab_section_->out_shndx();
5102 return 0;
5103}
5104
730cdc88
ILT
5105// Write out the Output_sections. Most won't have anything to write,
5106// since most of the data will come from input sections which are
5107// handled elsewhere. But some Output_sections do have Output_data.
5108
5109void
5110Layout::write_output_sections(Output_file* of) const
5111{
5112 for (Section_list::const_iterator p = this->section_list_.begin();
5113 p != this->section_list_.end();
5114 ++p)
5115 {
5116 if (!(*p)->after_input_sections())
5117 (*p)->write(of);
5118 }
5119}
5120
61ba1cf9
ILT
5121// Write out data not associated with a section or the symbol table.
5122
5123void
9025d29d 5124Layout::write_data(const Symbol_table* symtab, Output_file* of) const
61ba1cf9 5125{
8851ecca 5126 if (!parameters->options().strip_all())
a3ad94ed 5127 {
2ea97941 5128 const Output_section* symtab_section = this->symtab_section_;
9e2dcb77
ILT
5129 for (Section_list::const_iterator p = this->section_list_.begin();
5130 p != this->section_list_.end();
5131 ++p)
a3ad94ed 5132 {
9e2dcb77
ILT
5133 if ((*p)->needs_symtab_index())
5134 {
2ea97941 5135 gold_assert(symtab_section != NULL);
9e2dcb77
ILT
5136 unsigned int index = (*p)->symtab_index();
5137 gold_assert(index > 0 && index != -1U);
2ea97941
ILT
5138 off_t off = (symtab_section->offset()
5139 + index * symtab_section->entsize());
d491d34e 5140 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
9e2dcb77 5141 }
a3ad94ed
ILT
5142 }
5143 }
5144
2ea97941 5145 const Output_section* dynsym_section = this->dynsym_section_;
a3ad94ed
ILT
5146 for (Section_list::const_iterator p = this->section_list_.begin();
5147 p != this->section_list_.end();
5148 ++p)
5149 {
5150 if ((*p)->needs_dynsym_index())
5151 {
2ea97941 5152 gold_assert(dynsym_section != NULL);
a3ad94ed
ILT
5153 unsigned int index = (*p)->dynsym_index();
5154 gold_assert(index > 0 && index != -1U);
2ea97941
ILT
5155 off_t off = (dynsym_section->offset()
5156 + index * dynsym_section->entsize());
d491d34e 5157 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
a3ad94ed
ILT
5158 }
5159 }
5160
a3ad94ed 5161 // Write out the Output_data which are not in an Output_section.
61ba1cf9
ILT
5162 for (Data_list::const_iterator p = this->special_output_list_.begin();
5163 p != this->special_output_list_.end();
5164 ++p)
5165 (*p)->write(of);
5166}
5167
730cdc88
ILT
5168// Write out the Output_sections which can only be written after the
5169// input sections are complete.
5170
5171void
27bc2bce 5172Layout::write_sections_after_input_sections(Output_file* of)
730cdc88 5173{
27bc2bce 5174 // Determine the final section offsets, and thus the final output
9a0910c3
ILT
5175 // file size. Note we finalize the .shstrab last, to allow the
5176 // after_input_section sections to modify their section-names before
5177 // writing.
17a1d0a9 5178 if (this->any_postprocessing_sections_)
27bc2bce 5179 {
17a1d0a9
ILT
5180 off_t off = this->output_file_size_;
5181 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
8a4c0b0d 5182
17a1d0a9
ILT
5183 // Now that we've finalized the names, we can finalize the shstrab.
5184 off =
5185 this->set_section_offsets(off,
5186 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
5187
5188 if (off > this->output_file_size_)
5189 {
5190 of->resize(off);
5191 this->output_file_size_ = off;
5192 }
27bc2bce
ILT
5193 }
5194
730cdc88
ILT
5195 for (Section_list::const_iterator p = this->section_list_.begin();
5196 p != this->section_list_.end();
5197 ++p)
5198 {
5199 if ((*p)->after_input_sections())
5200 (*p)->write(of);
5201 }
27bc2bce 5202
27bc2bce 5203 this->section_headers_->write(of);
730cdc88
ILT
5204}
5205
8ed814a9
ILT
5206// If the build ID requires computing a checksum, do so here, and
5207// write it out. We compute a checksum over the entire file because
5208// that is simplest.
5209
5210void
5211Layout::write_build_id(Output_file* of) const
5212{
5213 if (this->build_id_note_ == NULL)
5214 return;
5215
5216 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
5217
5218 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
5219 this->build_id_note_->data_size());
5220
5221 const char* style = parameters->options().build_id();
5222 if (strcmp(style, "sha1") == 0)
5223 {
5224 sha1_ctx ctx;
5225 sha1_init_ctx(&ctx);
5226 sha1_process_bytes(iv, this->output_file_size_, &ctx);
5227 sha1_finish_ctx(&ctx, ov);
5228 }
5229 else if (strcmp(style, "md5") == 0)
5230 {
5231 md5_ctx ctx;
5232 md5_init_ctx(&ctx);
5233 md5_process_bytes(iv, this->output_file_size_, &ctx);
5234 md5_finish_ctx(&ctx, ov);
5235 }
5236 else
5237 gold_unreachable();
5238
5239 of->write_output_view(this->build_id_note_->offset(),
5240 this->build_id_note_->data_size(),
5241 ov);
5242
5243 of->free_input_view(0, this->output_file_size_, iv);
5244}
5245
516cb3d0
ILT
5246// Write out a binary file. This is called after the link is
5247// complete. IN is the temporary output file we used to generate the
5248// ELF code. We simply walk through the segments, read them from
5249// their file offset in IN, and write them to their load address in
5250// the output file. FIXME: with a bit more work, we could support
5251// S-records and/or Intel hex format here.
5252
5253void
5254Layout::write_binary(Output_file* in) const
5255{
e55bde5e 5256 gold_assert(parameters->options().oformat_enum()
bc644c6c 5257 == General_options::OBJECT_FORMAT_BINARY);
516cb3d0
ILT
5258
5259 // Get the size of the binary file.
5260 uint64_t max_load_address = 0;
5261 for (Segment_list::const_iterator p = this->segment_list_.begin();
5262 p != this->segment_list_.end();
5263 ++p)
5264 {
5265 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
5266 {
5267 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
5268 if (max_paddr > max_load_address)
5269 max_load_address = max_paddr;
5270 }
5271 }
5272
8851ecca 5273 Output_file out(parameters->options().output_file_name());
516cb3d0
ILT
5274 out.open(max_load_address);
5275
5276 for (Segment_list::const_iterator p = this->segment_list_.begin();
5277 p != this->segment_list_.end();
5278 ++p)
5279 {
5280 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
5281 {
5282 const unsigned char* vin = in->get_input_view((*p)->offset(),
5283 (*p)->filesz());
5284 unsigned char* vout = out.get_output_view((*p)->paddr(),
5285 (*p)->filesz());
5286 memcpy(vout, vin, (*p)->filesz());
5287 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
5288 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
5289 }
5290 }
5291
5292 out.close();
5293}
5294
7d9e3d98
ILT
5295// Print the output sections to the map file.
5296
5297void
5298Layout::print_to_mapfile(Mapfile* mapfile) const
5299{
5300 for (Segment_list::const_iterator p = this->segment_list_.begin();
5301 p != this->segment_list_.end();
5302 ++p)
5303 (*p)->print_sections_to_mapfile(mapfile);
5304}
5305
ad8f37d1
ILT
5306// Print statistical information to stderr. This is used for --stats.
5307
5308void
5309Layout::print_stats() const
5310{
5311 this->namepool_.print_stats("section name pool");
5312 this->sympool_.print_stats("output symbol name pool");
5313 this->dynpool_.print_stats("dynamic name pool");
38c5e8b4
ILT
5314
5315 for (Section_list::const_iterator p = this->section_list_.begin();
5316 p != this->section_list_.end();
5317 ++p)
5318 (*p)->print_merge_stats();
ad8f37d1
ILT
5319}
5320
730cdc88
ILT
5321// Write_sections_task methods.
5322
5323// We can always run this task.
5324
17a1d0a9
ILT
5325Task_token*
5326Write_sections_task::is_runnable()
730cdc88 5327{
17a1d0a9 5328 return NULL;
730cdc88
ILT
5329}
5330
5331// We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
5332// when finished.
5333
17a1d0a9
ILT
5334void
5335Write_sections_task::locks(Task_locker* tl)
730cdc88 5336{
17a1d0a9
ILT
5337 tl->add(this, this->output_sections_blocker_);
5338 tl->add(this, this->final_blocker_);
730cdc88
ILT
5339}
5340
5341// Run the task--write out the data.
5342
5343void
5344Write_sections_task::run(Workqueue*)
5345{
5346 this->layout_->write_output_sections(this->of_);
5347}
5348
61ba1cf9
ILT
5349// Write_data_task methods.
5350
5351// We can always run this task.
5352
17a1d0a9
ILT
5353Task_token*
5354Write_data_task::is_runnable()
61ba1cf9 5355{
17a1d0a9 5356 return NULL;
61ba1cf9
ILT
5357}
5358
5359// We need to unlock FINAL_BLOCKER when finished.
5360
17a1d0a9
ILT
5361void
5362Write_data_task::locks(Task_locker* tl)
61ba1cf9 5363{
17a1d0a9 5364 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
5365}
5366
5367// Run the task--write out the data.
5368
5369void
5370Write_data_task::run(Workqueue*)
5371{
9025d29d 5372 this->layout_->write_data(this->symtab_, this->of_);
61ba1cf9
ILT
5373}
5374
5375// Write_symbols_task methods.
5376
5377// We can always run this task.
5378
17a1d0a9
ILT
5379Task_token*
5380Write_symbols_task::is_runnable()
61ba1cf9 5381{
17a1d0a9 5382 return NULL;
61ba1cf9
ILT
5383}
5384
5385// We need to unlock FINAL_BLOCKER when finished.
5386
17a1d0a9
ILT
5387void
5388Write_symbols_task::locks(Task_locker* tl)
61ba1cf9 5389{
17a1d0a9 5390 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
5391}
5392
5393// Run the task--write out the symbols.
5394
5395void
5396Write_symbols_task::run(Workqueue*)
5397{
fd9d194f
ILT
5398 this->symtab_->write_globals(this->sympool_, this->dynpool_,
5399 this->layout_->symtab_xindex(),
d491d34e 5400 this->layout_->dynsym_xindex(), this->of_);
61ba1cf9
ILT
5401}
5402
730cdc88
ILT
5403// Write_after_input_sections_task methods.
5404
5405// We can only run this task after the input sections have completed.
5406
17a1d0a9
ILT
5407Task_token*
5408Write_after_input_sections_task::is_runnable()
730cdc88
ILT
5409{
5410 if (this->input_sections_blocker_->is_blocked())
17a1d0a9
ILT
5411 return this->input_sections_blocker_;
5412 return NULL;
730cdc88
ILT
5413}
5414
5415// We need to unlock FINAL_BLOCKER when finished.
5416
17a1d0a9
ILT
5417void
5418Write_after_input_sections_task::locks(Task_locker* tl)
730cdc88 5419{
17a1d0a9 5420 tl->add(this, this->final_blocker_);
730cdc88
ILT
5421}
5422
5423// Run the task.
5424
5425void
5426Write_after_input_sections_task::run(Workqueue*)
5427{
5428 this->layout_->write_sections_after_input_sections(this->of_);
5429}
5430
92e059d8 5431// Close_task_runner methods.
61ba1cf9
ILT
5432
5433// Run the task--close the file.
5434
5435void
17a1d0a9 5436Close_task_runner::run(Workqueue*, const Task*)
61ba1cf9 5437{
8ed814a9
ILT
5438 // If we need to compute a checksum for the BUILD if, we do so here.
5439 this->layout_->write_build_id(this->of_);
5440
516cb3d0 5441 // If we've been asked to create a binary file, we do so here.
7cc619c3 5442 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
516cb3d0
ILT
5443 this->layout_->write_binary(this->of_);
5444
61ba1cf9
ILT
5445 this->of_->close();
5446}
5447
a2fb1b05
ILT
5448// Instantiate the templates we need. We could use the configure
5449// script to restrict this to only the ones for implemented targets.
5450
193a53d9 5451#ifdef HAVE_TARGET_32_LITTLE
a2fb1b05 5452template
cdc29364
CC
5453Output_section*
5454Layout::init_fixed_output_section<32, false>(
5455 const char* name,
5456 elfcpp::Shdr<32, false>& shdr);
5457#endif
5458
5459#ifdef HAVE_TARGET_32_BIG
5460template
5461Output_section*
5462Layout::init_fixed_output_section<32, true>(
5463 const char* name,
5464 elfcpp::Shdr<32, true>& shdr);
5465#endif
5466
5467#ifdef HAVE_TARGET_64_LITTLE
5468template
5469Output_section*
5470Layout::init_fixed_output_section<64, false>(
5471 const char* name,
5472 elfcpp::Shdr<64, false>& shdr);
5473#endif
5474
5475#ifdef HAVE_TARGET_64_BIG
5476template
5477Output_section*
5478Layout::init_fixed_output_section<64, true>(
5479 const char* name,
5480 elfcpp::Shdr<64, true>& shdr);
5481#endif
5482
5483#ifdef HAVE_TARGET_32_LITTLE
5484template
a2fb1b05 5485Output_section*
6fa2a40b
CC
5486Layout::layout<32, false>(Sized_relobj_file<32, false>* object,
5487 unsigned int shndx,
730cdc88
ILT
5488 const char* name,
5489 const elfcpp::Shdr<32, false>& shdr,
5490 unsigned int, unsigned int, off_t*);
193a53d9 5491#endif
a2fb1b05 5492
193a53d9 5493#ifdef HAVE_TARGET_32_BIG
a2fb1b05
ILT
5494template
5495Output_section*
6fa2a40b
CC
5496Layout::layout<32, true>(Sized_relobj_file<32, true>* object,
5497 unsigned int shndx,
730cdc88
ILT
5498 const char* name,
5499 const elfcpp::Shdr<32, true>& shdr,
5500 unsigned int, unsigned int, off_t*);
193a53d9 5501#endif
a2fb1b05 5502
193a53d9 5503#ifdef HAVE_TARGET_64_LITTLE
a2fb1b05
ILT
5504template
5505Output_section*
6fa2a40b
CC
5506Layout::layout<64, false>(Sized_relobj_file<64, false>* object,
5507 unsigned int shndx,
730cdc88
ILT
5508 const char* name,
5509 const elfcpp::Shdr<64, false>& shdr,
5510 unsigned int, unsigned int, off_t*);
193a53d9 5511#endif
a2fb1b05 5512
193a53d9 5513#ifdef HAVE_TARGET_64_BIG
a2fb1b05
ILT
5514template
5515Output_section*
6fa2a40b
CC
5516Layout::layout<64, true>(Sized_relobj_file<64, true>* object,
5517 unsigned int shndx,
730cdc88
ILT
5518 const char* name,
5519 const elfcpp::Shdr<64, true>& shdr,
5520 unsigned int, unsigned int, off_t*);
193a53d9 5521#endif
a2fb1b05 5522
6a74a719
ILT
5523#ifdef HAVE_TARGET_32_LITTLE
5524template
5525Output_section*
6fa2a40b 5526Layout::layout_reloc<32, false>(Sized_relobj_file<32, false>* object,
6a74a719
ILT
5527 unsigned int reloc_shndx,
5528 const elfcpp::Shdr<32, false>& shdr,
5529 Output_section* data_section,
5530 Relocatable_relocs* rr);
5531#endif
5532
5533#ifdef HAVE_TARGET_32_BIG
5534template
5535Output_section*
6fa2a40b 5536Layout::layout_reloc<32, true>(Sized_relobj_file<32, true>* object,
6a74a719
ILT
5537 unsigned int reloc_shndx,
5538 const elfcpp::Shdr<32, true>& shdr,
5539 Output_section* data_section,
5540 Relocatable_relocs* rr);
5541#endif
5542
5543#ifdef HAVE_TARGET_64_LITTLE
5544template
5545Output_section*
6fa2a40b 5546Layout::layout_reloc<64, false>(Sized_relobj_file<64, false>* object,
6a74a719
ILT
5547 unsigned int reloc_shndx,
5548 const elfcpp::Shdr<64, false>& shdr,
5549 Output_section* data_section,
5550 Relocatable_relocs* rr);
5551#endif
5552
5553#ifdef HAVE_TARGET_64_BIG
5554template
5555Output_section*
6fa2a40b 5556Layout::layout_reloc<64, true>(Sized_relobj_file<64, true>* object,
6a74a719
ILT
5557 unsigned int reloc_shndx,
5558 const elfcpp::Shdr<64, true>& shdr,
5559 Output_section* data_section,
5560 Relocatable_relocs* rr);
5561#endif
5562
5563#ifdef HAVE_TARGET_32_LITTLE
5564template
5565void
5566Layout::layout_group<32, false>(Symbol_table* symtab,
6fa2a40b 5567 Sized_relobj_file<32, false>* object,
6a74a719
ILT
5568 unsigned int,
5569 const char* group_section_name,
5570 const char* signature,
5571 const elfcpp::Shdr<32, false>& shdr,
8825ac63
ILT
5572 elfcpp::Elf_Word flags,
5573 std::vector<unsigned int>* shndxes);
6a74a719
ILT
5574#endif
5575
5576#ifdef HAVE_TARGET_32_BIG
5577template
5578void
5579Layout::layout_group<32, true>(Symbol_table* symtab,
6fa2a40b 5580 Sized_relobj_file<32, true>* object,
6a74a719
ILT
5581 unsigned int,
5582 const char* group_section_name,
5583 const char* signature,
5584 const elfcpp::Shdr<32, true>& shdr,
8825ac63
ILT
5585 elfcpp::Elf_Word flags,
5586 std::vector<unsigned int>* shndxes);
6a74a719
ILT
5587#endif
5588
5589#ifdef HAVE_TARGET_64_LITTLE
5590template
5591void
5592Layout::layout_group<64, false>(Symbol_table* symtab,
6fa2a40b 5593 Sized_relobj_file<64, false>* object,
6a74a719
ILT
5594 unsigned int,
5595 const char* group_section_name,
5596 const char* signature,
5597 const elfcpp::Shdr<64, false>& shdr,
8825ac63
ILT
5598 elfcpp::Elf_Word flags,
5599 std::vector<unsigned int>* shndxes);
6a74a719
ILT
5600#endif
5601
5602#ifdef HAVE_TARGET_64_BIG
5603template
5604void
5605Layout::layout_group<64, true>(Symbol_table* symtab,
6fa2a40b 5606 Sized_relobj_file<64, true>* object,
6a74a719
ILT
5607 unsigned int,
5608 const char* group_section_name,
5609 const char* signature,
5610 const elfcpp::Shdr<64, true>& shdr,
8825ac63
ILT
5611 elfcpp::Elf_Word flags,
5612 std::vector<unsigned int>* shndxes);
6a74a719
ILT
5613#endif
5614
730cdc88
ILT
5615#ifdef HAVE_TARGET_32_LITTLE
5616template
5617Output_section*
6fa2a40b 5618Layout::layout_eh_frame<32, false>(Sized_relobj_file<32, false>* object,
730cdc88
ILT
5619 const unsigned char* symbols,
5620 off_t symbols_size,
5621 const unsigned char* symbol_names,
5622 off_t symbol_names_size,
5623 unsigned int shndx,
5624 const elfcpp::Shdr<32, false>& shdr,
5625 unsigned int reloc_shndx,
5626 unsigned int reloc_type,
5627 off_t* off);
5628#endif
5629
5630#ifdef HAVE_TARGET_32_BIG
5631template
5632Output_section*
6fa2a40b
CC
5633Layout::layout_eh_frame<32, true>(Sized_relobj_file<32, true>* object,
5634 const unsigned char* symbols,
5635 off_t symbols_size,
730cdc88
ILT
5636 const unsigned char* symbol_names,
5637 off_t symbol_names_size,
5638 unsigned int shndx,
5639 const elfcpp::Shdr<32, true>& shdr,
5640 unsigned int reloc_shndx,
5641 unsigned int reloc_type,
5642 off_t* off);
5643#endif
5644
5645#ifdef HAVE_TARGET_64_LITTLE
5646template
5647Output_section*
6fa2a40b 5648Layout::layout_eh_frame<64, false>(Sized_relobj_file<64, false>* object,
730cdc88
ILT
5649 const unsigned char* symbols,
5650 off_t symbols_size,
5651 const unsigned char* symbol_names,
5652 off_t symbol_names_size,
5653 unsigned int shndx,
5654 const elfcpp::Shdr<64, false>& shdr,
5655 unsigned int reloc_shndx,
5656 unsigned int reloc_type,
5657 off_t* off);
5658#endif
5659
5660#ifdef HAVE_TARGET_64_BIG
5661template
5662Output_section*
6fa2a40b
CC
5663Layout::layout_eh_frame<64, true>(Sized_relobj_file<64, true>* object,
5664 const unsigned char* symbols,
5665 off_t symbols_size,
730cdc88
ILT
5666 const unsigned char* symbol_names,
5667 off_t symbol_names_size,
5668 unsigned int shndx,
5669 const elfcpp::Shdr<64, true>& shdr,
5670 unsigned int reloc_shndx,
5671 unsigned int reloc_type,
5672 off_t* off);
5673#endif
a2fb1b05 5674
c1027032
CC
5675#ifdef HAVE_TARGET_32_LITTLE
5676template
5677void
5678Layout::add_to_gdb_index(bool is_type_unit,
5679 Sized_relobj<32, false>* object,
5680 const unsigned char* symbols,
5681 off_t symbols_size,
5682 unsigned int shndx,
5683 unsigned int reloc_shndx,
5684 unsigned int reloc_type);
5685#endif
5686
5687#ifdef HAVE_TARGET_32_BIG
5688template
5689void
5690Layout::add_to_gdb_index(bool is_type_unit,
5691 Sized_relobj<32, true>* object,
5692 const unsigned char* symbols,
5693 off_t symbols_size,
5694 unsigned int shndx,
5695 unsigned int reloc_shndx,
5696 unsigned int reloc_type);
5697#endif
5698
5699#ifdef HAVE_TARGET_64_LITTLE
5700template
5701void
5702Layout::add_to_gdb_index(bool is_type_unit,
5703 Sized_relobj<64, false>* object,
5704 const unsigned char* symbols,
5705 off_t symbols_size,
5706 unsigned int shndx,
5707 unsigned int reloc_shndx,
5708 unsigned int reloc_type);
5709#endif
5710
5711#ifdef HAVE_TARGET_64_BIG
5712template
5713void
5714Layout::add_to_gdb_index(bool is_type_unit,
5715 Sized_relobj<64, true>* object,
5716 const unsigned char* symbols,
5717 off_t symbols_size,
5718 unsigned int shndx,
5719 unsigned int reloc_shndx,
5720 unsigned int reloc_type);
5721#endif
5722
a2fb1b05 5723} // End namespace gold.
This page took 0.631978 seconds and 4 git commands to generate.