]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gold/layout.cc
opcodes/
[thirdparty/binutils-gdb.git] / gold / layout.cc
CommitLineData
a2fb1b05
ILT
1// layout.cc -- lay out output file sections for gold
2
6d03d481 3// Copyright 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6cb15b7f
ILT
4// Written by Ian Lance Taylor <iant@google.com>.
5
6// This file is part of gold.
7
8// This program is free software; you can redistribute it and/or modify
9// it under the terms of the GNU General Public License as published by
10// the Free Software Foundation; either version 3 of the License, or
11// (at your option) any later version.
12
13// This program is distributed in the hope that it will be useful,
14// but WITHOUT ANY WARRANTY; without even the implied warranty of
15// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16// GNU General Public License for more details.
17
18// You should have received a copy of the GNU General Public License
19// along with this program; if not, write to the Free Software
20// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21// MA 02110-1301, USA.
22
a2fb1b05
ILT
23#include "gold.h"
24
8ed814a9 25#include <cerrno>
a2fb1b05 26#include <cstring>
54dc6425 27#include <algorithm>
a2fb1b05
ILT
28#include <iostream>
29#include <utility>
8ed814a9
ILT
30#include <fcntl.h>
31#include <unistd.h>
32#include "libiberty.h"
33#include "md5.h"
34#include "sha1.h"
a2fb1b05 35
7e1edb90 36#include "parameters.h"
14144f39 37#include "options.h"
7d9e3d98 38#include "mapfile.h"
a445fddf
ILT
39#include "script.h"
40#include "script-sections.h"
a2fb1b05 41#include "output.h"
f6ce93d6 42#include "symtab.h"
a3ad94ed 43#include "dynobj.h"
3151305a 44#include "ehframe.h"
96803768 45#include "compressed_output.h"
62b01cb5 46#include "reduced_debug_output.h"
6a74a719 47#include "reloc.h"
2a00e4fb 48#include "descriptors.h"
a2fb1b05 49#include "layout.h"
2756a258 50#include "plugin.h"
a2fb1b05
ILT
51
52namespace gold
53{
54
92e059d8 55// Layout_task_runner methods.
a2fb1b05
ILT
56
57// Lay out the sections. This is called after all the input objects
58// have been read.
59
60void
17a1d0a9 61Layout_task_runner::run(Workqueue* workqueue, const Task* task)
a2fb1b05 62{
12e14209 63 off_t file_size = this->layout_->finalize(this->input_objects_,
17a1d0a9 64 this->symtab_,
8851ecca 65 this->target_,
17a1d0a9 66 task);
61ba1cf9
ILT
67
68 // Now we know the final size of the output file and we know where
69 // each piece of information goes.
7d9e3d98
ILT
70
71 if (this->mapfile_ != NULL)
72 {
73 this->mapfile_->print_discarded_sections(this->input_objects_);
74 this->layout_->print_to_mapfile(this->mapfile_);
75 }
76
8851ecca 77 Output_file* of = new Output_file(parameters->options().output_file_name());
7cc619c3 78 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
516cb3d0 79 of->set_is_temporary();
61ba1cf9
ILT
80 of->open(file_size);
81
82 // Queue up the final set of tasks.
83 gold::queue_final_tasks(this->options_, this->input_objects_,
12e14209 84 this->symtab_, this->layout_, workqueue, of);
a2fb1b05
ILT
85}
86
87// Layout methods.
88
e5756efb 89Layout::Layout(const General_options& options, Script_options* script_options)
d491d34e
ILT
90 : options_(options),
91 script_options_(script_options),
92 namepool_(),
93 sympool_(),
94 dynpool_(),
95 signatures_(),
96 section_name_map_(),
97 segment_list_(),
98 section_list_(),
99 unattached_section_list_(),
100 sections_are_attached_(false),
101 special_output_list_(),
102 section_headers_(NULL),
103 tls_segment_(NULL),
9f1d377b 104 relro_segment_(NULL),
d491d34e
ILT
105 symtab_section_(NULL),
106 symtab_xindex_(NULL),
107 dynsym_section_(NULL),
108 dynsym_xindex_(NULL),
109 dynamic_section_(NULL),
110 dynamic_data_(NULL),
111 eh_frame_section_(NULL),
112 eh_frame_data_(NULL),
113 added_eh_frame_data_(false),
114 eh_frame_hdr_section_(NULL),
115 build_id_note_(NULL),
62b01cb5
ILT
116 debug_abbrev_(NULL),
117 debug_info_(NULL),
d491d34e
ILT
118 group_signatures_(),
119 output_file_size_(-1),
35cdfc9a
ILT
120 input_requires_executable_stack_(false),
121 input_with_gnu_stack_note_(false),
535890bb 122 input_without_gnu_stack_note_(false),
17a1d0a9
ILT
123 has_static_tls_(false),
124 any_postprocessing_sections_(false)
54dc6425
ILT
125{
126 // Make space for more than enough segments for a typical file.
127 // This is just for efficiency--it's OK if we wind up needing more.
a3ad94ed
ILT
128 this->segment_list_.reserve(12);
129
27bc2bce
ILT
130 // We expect two unattached Output_data objects: the file header and
131 // the segment headers.
132 this->special_output_list_.reserve(2);
54dc6425
ILT
133}
134
a2fb1b05
ILT
135// Hash a key we use to look up an output section mapping.
136
137size_t
138Layout::Hash_key::operator()(const Layout::Key& k) const
139{
f0641a0b 140 return k.first + k.second.first + k.second.second;
a2fb1b05
ILT
141}
142
02d2ba74
ILT
143// Returns whether the given section is in the list of
144// debug-sections-used-by-some-version-of-gdb. Currently,
145// we've checked versions of gdb up to and including 6.7.1.
146
147static const char* gdb_sections[] =
148{ ".debug_abbrev",
149 // ".debug_aranges", // not used by gdb as of 6.7.1
150 ".debug_frame",
151 ".debug_info",
152 ".debug_line",
153 ".debug_loc",
154 ".debug_macinfo",
155 // ".debug_pubnames", // not used by gdb as of 6.7.1
156 ".debug_ranges",
157 ".debug_str",
158};
159
62b01cb5
ILT
160static const char* lines_only_debug_sections[] =
161{ ".debug_abbrev",
162 // ".debug_aranges", // not used by gdb as of 6.7.1
163 // ".debug_frame",
164 ".debug_info",
165 ".debug_line",
166 // ".debug_loc",
167 // ".debug_macinfo",
168 // ".debug_pubnames", // not used by gdb as of 6.7.1
169 // ".debug_ranges",
170 ".debug_str",
171};
172
02d2ba74
ILT
173static inline bool
174is_gdb_debug_section(const char* str)
175{
176 // We can do this faster: binary search or a hashtable. But why bother?
177 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
178 if (strcmp(str, gdb_sections[i]) == 0)
179 return true;
180 return false;
181}
182
62b01cb5
ILT
183static inline bool
184is_lines_only_debug_section(const char* str)
185{
186 // We can do this faster: binary search or a hashtable. But why bother?
187 for (size_t i = 0;
188 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
189 ++i)
190 if (strcmp(str, lines_only_debug_sections[i]) == 0)
191 return true;
192 return false;
193}
194
a2fb1b05
ILT
195// Whether to include this section in the link.
196
197template<int size, bool big_endian>
198bool
730cdc88 199Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
a2fb1b05
ILT
200 const elfcpp::Shdr<size, big_endian>& shdr)
201{
fd06b4aa
CC
202 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
203 return false;
204
a2fb1b05
ILT
205 switch (shdr.get_sh_type())
206 {
207 case elfcpp::SHT_NULL:
208 case elfcpp::SHT_SYMTAB:
209 case elfcpp::SHT_DYNSYM:
a2fb1b05
ILT
210 case elfcpp::SHT_HASH:
211 case elfcpp::SHT_DYNAMIC:
212 case elfcpp::SHT_SYMTAB_SHNDX:
213 return false;
214
5cb66f97
ILT
215 case elfcpp::SHT_STRTAB:
216 // Discard the sections which have special meanings in the ELF
217 // ABI. Keep others (e.g., .stabstr). We could also do this by
218 // checking the sh_link fields of the appropriate sections.
219 return (strcmp(name, ".dynstr") != 0
220 && strcmp(name, ".strtab") != 0
221 && strcmp(name, ".shstrtab") != 0);
222
a2fb1b05
ILT
223 case elfcpp::SHT_RELA:
224 case elfcpp::SHT_REL:
225 case elfcpp::SHT_GROUP:
7019cd25
ILT
226 // If we are emitting relocations these should be handled
227 // elsewhere.
8851ecca
ILT
228 gold_assert(!parameters->options().relocatable()
229 && !parameters->options().emit_relocs());
6a74a719 230 return false;
a2fb1b05 231
9e2dcb77 232 case elfcpp::SHT_PROGBITS:
8851ecca 233 if (parameters->options().strip_debug()
9e2dcb77
ILT
234 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
235 {
e94cf127 236 if (is_debug_info_section(name))
9e2dcb77
ILT
237 return false;
238 }
62b01cb5
ILT
239 if (parameters->options().strip_debug_non_line()
240 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
241 {
242 // Debugging sections can only be recognized by name.
243 if (is_prefix_of(".debug", name)
244 && !is_lines_only_debug_section(name))
245 return false;
246 }
8851ecca 247 if (parameters->options().strip_debug_gdb()
02d2ba74
ILT
248 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
249 {
250 // Debugging sections can only be recognized by name.
251 if (is_prefix_of(".debug", name)
252 && !is_gdb_debug_section(name))
253 return false;
254 }
fd06b4aa
CC
255 if (parameters->options().strip_lto_sections()
256 && !parameters->options().relocatable()
257 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
258 {
259 // Ignore LTO sections containing intermediate code.
260 if (is_prefix_of(".gnu.lto_", name))
261 return false;
262 }
9e2dcb77
ILT
263 return true;
264
a2fb1b05 265 default:
a2fb1b05
ILT
266 return true;
267 }
268}
269
ead1e424 270// Return an output section named NAME, or NULL if there is none.
a2fb1b05 271
a2fb1b05 272Output_section*
ead1e424 273Layout::find_output_section(const char* name) const
a2fb1b05 274{
a445fddf
ILT
275 for (Section_list::const_iterator p = this->section_list_.begin();
276 p != this->section_list_.end();
ead1e424 277 ++p)
a445fddf
ILT
278 if (strcmp((*p)->name(), name) == 0)
279 return *p;
ead1e424
ILT
280 return NULL;
281}
a2fb1b05 282
ead1e424
ILT
283// Return an output segment of type TYPE, with segment flags SET set
284// and segment flags CLEAR clear. Return NULL if there is none.
a2fb1b05 285
ead1e424
ILT
286Output_segment*
287Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
288 elfcpp::Elf_Word clear) const
289{
290 for (Segment_list::const_iterator p = this->segment_list_.begin();
291 p != this->segment_list_.end();
292 ++p)
293 if (static_cast<elfcpp::PT>((*p)->type()) == type
294 && ((*p)->flags() & set) == set
295 && ((*p)->flags() & clear) == 0)
296 return *p;
297 return NULL;
298}
a2fb1b05 299
ead1e424 300// Return the output section to use for section NAME with type TYPE
a445fddf
ILT
301// and section flags FLAGS. NAME must be canonicalized in the string
302// pool, and NAME_KEY is the key.
a2fb1b05 303
ead1e424 304Output_section*
f0641a0b
ILT
305Layout::get_output_section(const char* name, Stringpool::Key name_key,
306 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
ead1e424 307{
154e0e9a
ILT
308 elfcpp::Elf_Xword lookup_flags = flags;
309
310 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
311 // read-write with read-only sections. Some other ELF linkers do
312 // not do this. FIXME: Perhaps there should be an option
313 // controlling this.
314 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
315
316 const Key key(name_key, std::make_pair(type, lookup_flags));
a2fb1b05
ILT
317 const std::pair<Key, Output_section*> v(key, NULL);
318 std::pair<Section_name_map::iterator, bool> ins(
319 this->section_name_map_.insert(v));
320
a2fb1b05 321 if (!ins.second)
ead1e424 322 return ins.first->second;
a2fb1b05
ILT
323 else
324 {
325 // This is the first time we've seen this name/type/flags
4e2b1697
ILT
326 // combination. For compatibility with the GNU linker, we
327 // combine sections with contents and zero flags with sections
328 // with non-zero flags. This is a workaround for cases where
329 // assembler code forgets to set section flags. FIXME: Perhaps
330 // there should be an option to control this.
15cf077e 331 Output_section* os = NULL;
4e2b1697
ILT
332
333 if (type == elfcpp::SHT_PROGBITS)
15cf077e 334 {
4e2b1697
ILT
335 if (flags == 0)
336 {
337 Output_section* same_name = this->find_output_section(name);
338 if (same_name != NULL
339 && same_name->type() == elfcpp::SHT_PROGBITS
340 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
341 os = same_name;
342 }
343 else if ((flags & elfcpp::SHF_TLS) == 0)
344 {
345 elfcpp::Elf_Xword zero_flags = 0;
346 const Key zero_key(name_key, std::make_pair(type, zero_flags));
347 Section_name_map::iterator p =
348 this->section_name_map_.find(zero_key);
349 if (p != this->section_name_map_.end())
154e0e9a 350 os = p->second;
4e2b1697 351 }
15cf077e 352 }
4e2b1697 353
15cf077e
ILT
354 if (os == NULL)
355 os = this->make_output_section(name, type, flags);
a2fb1b05 356 ins.first->second = os;
ead1e424 357 return os;
a2fb1b05 358 }
ead1e424
ILT
359}
360
a445fddf
ILT
361// Pick the output section to use for section NAME, in input file
362// RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
154e0e9a
ILT
363// linker created section. IS_INPUT_SECTION is true if we are
364// choosing an output section for an input section found in a input
365// file. This will return NULL if the input section should be
366// discarded.
a445fddf
ILT
367
368Output_section*
369Layout::choose_output_section(const Relobj* relobj, const char* name,
370 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
154e0e9a 371 bool is_input_section)
a445fddf 372{
154e0e9a
ILT
373 // We should not see any input sections after we have attached
374 // sections to segments.
375 gold_assert(!is_input_section || !this->sections_are_attached_);
376
377 // Some flags in the input section should not be automatically
378 // copied to the output section.
a445fddf
ILT
379 flags &= ~ (elfcpp::SHF_INFO_LINK
380 | elfcpp::SHF_LINK_ORDER
381 | elfcpp::SHF_GROUP
382 | elfcpp::SHF_MERGE
383 | elfcpp::SHF_STRINGS);
384
385 if (this->script_options_->saw_sections_clause())
386 {
387 // We are using a SECTIONS clause, so the output section is
388 // chosen based only on the name.
389
390 Script_sections* ss = this->script_options_->script_sections();
391 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
392 Output_section** output_section_slot;
393 name = ss->output_section_name(file_name, name, &output_section_slot);
394 if (name == NULL)
395 {
396 // The SECTIONS clause says to discard this input section.
397 return NULL;
398 }
399
400 // If this is an orphan section--one not mentioned in the linker
401 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
402 // default processing below.
403
404 if (output_section_slot != NULL)
405 {
406 if (*output_section_slot != NULL)
154e0e9a 407 return *output_section_slot;
a445fddf
ILT
408
409 // We don't put sections found in the linker script into
410 // SECTION_NAME_MAP_. That keeps us from getting confused
411 // if an orphan section is mapped to a section with the same
412 // name as one in the linker script.
413
414 name = this->namepool_.add(name, false, NULL);
415
416 Output_section* os = this->make_output_section(name, type, flags);
417 os->set_found_in_sections_clause();
418 *output_section_slot = os;
419 return os;
420 }
421 }
422
423 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
424
425 // Turn NAME from the name of the input section into the name of the
426 // output section.
427
428 size_t len = strlen(name);
401a9a73
CC
429 if (is_input_section
430 && !this->script_options_->saw_sections_clause()
431 && !parameters->options().relocatable())
a445fddf
ILT
432 name = Layout::output_section_name(name, &len);
433
434 Stringpool::Key name_key;
435 name = this->namepool_.add_with_length(name, len, true, &name_key);
436
437 // Find or make the output section. The output section is selected
438 // based on the section name, type, and flags.
439 return this->get_output_section(name, name_key, type, flags);
440}
441
ead1e424 442// Return the output section to use for input section SHNDX, with name
730cdc88
ILT
443// NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
444// index of a relocation section which applies to this section, or 0
445// if none, or -1U if more than one. RELOC_TYPE is the type of the
446// relocation section if there is one. Set *OFF to the offset of this
447// input section without the output section. Return NULL if the
448// section should be discarded. Set *OFF to -1 if the section
449// contents should not be written directly to the output file, but
450// will instead receive special handling.
ead1e424
ILT
451
452template<int size, bool big_endian>
453Output_section*
730cdc88
ILT
454Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
455 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
456 unsigned int reloc_shndx, unsigned int, off_t* off)
ead1e424 457{
ef9beddf
ILT
458 *off = 0;
459
ead1e424
ILT
460 if (!this->include_section(object, name, shdr))
461 return NULL;
462
6a74a719
ILT
463 Output_section* os;
464
465 // In a relocatable link a grouped section must not be combined with
466 // any other sections.
8851ecca 467 if (parameters->options().relocatable()
6a74a719
ILT
468 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
469 {
470 name = this->namepool_.add(name, true, NULL);
471 os = this->make_output_section(name, shdr.get_sh_type(),
472 shdr.get_sh_flags());
473 }
474 else
475 {
476 os = this->choose_output_section(object, name, shdr.get_sh_type(),
477 shdr.get_sh_flags(), true);
478 if (os == NULL)
479 return NULL;
480 }
a2fb1b05 481
2fd32231
ILT
482 // By default the GNU linker sorts input sections whose names match
483 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
484 // are sorted by name. This is used to implement constructor
485 // priority ordering. We are compatible.
486 if (!this->script_options_->saw_sections_clause()
487 && (is_prefix_of(".ctors.", name)
488 || is_prefix_of(".dtors.", name)
489 || is_prefix_of(".init_array.", name)
490 || is_prefix_of(".fini_array.", name)))
491 os->set_must_sort_attached_input_sections();
492
a2fb1b05
ILT
493 // FIXME: Handle SHF_LINK_ORDER somewhere.
494
a445fddf
ILT
495 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
496 this->script_options_->saw_sections_clause());
a2fb1b05
ILT
497
498 return os;
499}
500
6a74a719
ILT
501// Handle a relocation section when doing a relocatable link.
502
503template<int size, bool big_endian>
504Output_section*
505Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
506 unsigned int,
507 const elfcpp::Shdr<size, big_endian>& shdr,
508 Output_section* data_section,
509 Relocatable_relocs* rr)
510{
8851ecca
ILT
511 gold_assert(parameters->options().relocatable()
512 || parameters->options().emit_relocs());
6a74a719
ILT
513
514 int sh_type = shdr.get_sh_type();
515
516 std::string name;
517 if (sh_type == elfcpp::SHT_REL)
518 name = ".rel";
519 else if (sh_type == elfcpp::SHT_RELA)
520 name = ".rela";
521 else
522 gold_unreachable();
523 name += data_section->name();
524
525 Output_section* os = this->choose_output_section(object, name.c_str(),
526 sh_type,
527 shdr.get_sh_flags(),
528 false);
529
530 os->set_should_link_to_symtab();
531 os->set_info_section(data_section);
532
533 Output_section_data* posd;
534 if (sh_type == elfcpp::SHT_REL)
535 {
536 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
537 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
538 size,
539 big_endian>(rr);
540 }
541 else if (sh_type == elfcpp::SHT_RELA)
542 {
543 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
544 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
545 size,
546 big_endian>(rr);
547 }
548 else
549 gold_unreachable();
550
551 os->add_output_section_data(posd);
552 rr->set_output_data(posd);
553
554 return os;
555}
556
557// Handle a group section when doing a relocatable link.
558
559template<int size, bool big_endian>
560void
561Layout::layout_group(Symbol_table* symtab,
562 Sized_relobj<size, big_endian>* object,
563 unsigned int,
564 const char* group_section_name,
565 const char* signature,
566 const elfcpp::Shdr<size, big_endian>& shdr,
8825ac63
ILT
567 elfcpp::Elf_Word flags,
568 std::vector<unsigned int>* shndxes)
6a74a719 569{
8851ecca 570 gold_assert(parameters->options().relocatable());
6a74a719
ILT
571 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
572 group_section_name = this->namepool_.add(group_section_name, true, NULL);
573 Output_section* os = this->make_output_section(group_section_name,
574 elfcpp::SHT_GROUP,
575 shdr.get_sh_flags());
576
577 // We need to find a symbol with the signature in the symbol table.
755ab8af 578 // If we don't find one now, we need to look again later.
6a74a719 579 Symbol* sym = symtab->lookup(signature, NULL);
755ab8af
ILT
580 if (sym != NULL)
581 os->set_info_symndx(sym);
582 else
583 {
584 // We will wind up using a symbol whose name is the signature.
585 // So just put the signature in the symbol name pool to save it.
586 signature = symtab->canonicalize_name(signature);
587 this->group_signatures_.push_back(Group_signature(os, signature));
588 }
6a74a719
ILT
589
590 os->set_should_link_to_symtab();
6a74a719
ILT
591 os->set_entsize(4);
592
593 section_size_type entry_count =
594 convert_to_section_size_type(shdr.get_sh_size() / 4);
595 Output_section_data* posd =
8825ac63
ILT
596 new Output_data_group<size, big_endian>(object, entry_count, flags,
597 shndxes);
6a74a719
ILT
598 os->add_output_section_data(posd);
599}
600
730cdc88
ILT
601// Special GNU handling of sections name .eh_frame. They will
602// normally hold exception frame data as defined by the C++ ABI
603// (http://codesourcery.com/cxx-abi/).
3151305a
ILT
604
605template<int size, bool big_endian>
730cdc88
ILT
606Output_section*
607Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
608 const unsigned char* symbols,
609 off_t symbols_size,
610 const unsigned char* symbol_names,
611 off_t symbol_names_size,
3151305a 612 unsigned int shndx,
3151305a 613 const elfcpp::Shdr<size, big_endian>& shdr,
730cdc88
ILT
614 unsigned int reloc_shndx, unsigned int reloc_type,
615 off_t* off)
3151305a 616{
730cdc88 617 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
1650c4ff 618 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
730cdc88 619
a445fddf
ILT
620 const char* const name = ".eh_frame";
621 Output_section* os = this->choose_output_section(object,
622 name,
623 elfcpp::SHT_PROGBITS,
624 elfcpp::SHF_ALLOC,
625 false);
626 if (os == NULL)
627 return NULL;
730cdc88 628
3151305a
ILT
629 if (this->eh_frame_section_ == NULL)
630 {
631 this->eh_frame_section_ = os;
730cdc88 632 this->eh_frame_data_ = new Eh_frame();
3151305a 633
45aa233b 634 if (this->options_.eh_frame_hdr())
3151305a 635 {
3151305a 636 Output_section* hdr_os =
a445fddf
ILT
637 this->choose_output_section(NULL,
638 ".eh_frame_hdr",
639 elfcpp::SHT_PROGBITS,
640 elfcpp::SHF_ALLOC,
641 false);
3151305a 642
a445fddf
ILT
643 if (hdr_os != NULL)
644 {
645 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
646 this->eh_frame_data_);
647 hdr_os->add_output_section_data(hdr_posd);
3151305a 648
a445fddf 649 hdr_os->set_after_input_sections();
730cdc88 650
1c4f3631
ILT
651 if (!this->script_options_->saw_phdrs_clause())
652 {
653 Output_segment* hdr_oseg;
654 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
655 elfcpp::PF_R);
656 hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
657 }
730cdc88 658
a445fddf
ILT
659 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
660 }
3151305a
ILT
661 }
662 }
663
664 gold_assert(this->eh_frame_section_ == os);
665
730cdc88
ILT
666 if (this->eh_frame_data_->add_ehframe_input_section(object,
667 symbols,
668 symbols_size,
669 symbol_names,
670 symbol_names_size,
671 shndx,
672 reloc_shndx,
673 reloc_type))
2c38906f 674 {
154e0e9a
ILT
675 os->update_flags_for_input_section(shdr.get_sh_flags());
676
2c38906f
ILT
677 // We found a .eh_frame section we are going to optimize, so now
678 // we can add the set of optimized sections to the output
679 // section. We need to postpone adding this until we've found a
680 // section we can optimize so that the .eh_frame section in
681 // crtbegin.o winds up at the start of the output section.
682 if (!this->added_eh_frame_data_)
683 {
684 os->add_output_section_data(this->eh_frame_data_);
685 this->added_eh_frame_data_ = true;
686 }
687 *off = -1;
688 }
730cdc88
ILT
689 else
690 {
691 // We couldn't handle this .eh_frame section for some reason.
692 // Add it as a normal section.
a445fddf
ILT
693 bool saw_sections_clause = this->script_options_->saw_sections_clause();
694 *off = os->add_input_section(object, shndx, name, shdr, reloc_shndx,
695 saw_sections_clause);
730cdc88
ILT
696 }
697
698 return os;
3151305a
ILT
699}
700
9f1d377b
ILT
701// Add POSD to an output section using NAME, TYPE, and FLAGS. Return
702// the output section.
ead1e424 703
9f1d377b 704Output_section*
ead1e424
ILT
705Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
706 elfcpp::Elf_Xword flags,
707 Output_section_data* posd)
708{
a445fddf
ILT
709 Output_section* os = this->choose_output_section(NULL, name, type, flags,
710 false);
711 if (os != NULL)
712 os->add_output_section_data(posd);
9f1d377b 713 return os;
ead1e424
ILT
714}
715
a2fb1b05
ILT
716// Map section flags to segment flags.
717
718elfcpp::Elf_Word
719Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
720{
721 elfcpp::Elf_Word ret = elfcpp::PF_R;
722 if ((flags & elfcpp::SHF_WRITE) != 0)
723 ret |= elfcpp::PF_W;
724 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
725 ret |= elfcpp::PF_X;
726 return ret;
727}
728
96803768
ILT
729// Sometimes we compress sections. This is typically done for
730// sections that are not part of normal program execution (such as
731// .debug_* sections), and where the readers of these sections know
732// how to deal with compressed sections. (To make it easier for them,
733// we will rename the ouput section in such cases from .foo to
734// .foo.zlib.nnnn, where nnnn is the uncompressed size.) This routine
735// doesn't say for certain whether we'll compress -- it depends on
736// commandline options as well -- just whether this section is a
737// candidate for compression.
738
739static bool
740is_compressible_debug_section(const char* secname)
741{
742 return (strncmp(secname, ".debug", sizeof(".debug") - 1) == 0);
743}
744
a2fb1b05
ILT
745// Make a new Output_section, and attach it to segments as
746// appropriate.
747
748Output_section*
749Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
750 elfcpp::Elf_Xword flags)
751{
96803768
ILT
752 Output_section* os;
753 if ((flags & elfcpp::SHF_ALLOC) == 0
ee1fe73e 754 && strcmp(this->options_.compress_debug_sections(), "none") != 0
96803768
ILT
755 && is_compressible_debug_section(name))
756 os = new Output_compressed_section(&this->options_, name, type, flags);
62b01cb5
ILT
757
758 else if ((flags & elfcpp::SHF_ALLOC) == 0
759 && this->options_.strip_debug_non_line()
760 && strcmp(".debug_abbrev", name) == 0)
761 {
762 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
763 name, type, flags);
764 if (this->debug_info_)
765 this->debug_info_->set_abbreviations(this->debug_abbrev_);
766 }
767 else if ((flags & elfcpp::SHF_ALLOC) == 0
768 && this->options_.strip_debug_non_line()
769 && strcmp(".debug_info", name) == 0)
770 {
771 os = this->debug_info_ = new Output_reduced_debug_info_section(
772 name, type, flags);
773 if (this->debug_abbrev_)
774 this->debug_info_->set_abbreviations(this->debug_abbrev_);
775 }
776 else
96803768
ILT
777 os = new Output_section(name, type, flags);
778
a3ad94ed 779 this->section_list_.push_back(os);
a2fb1b05 780
2fd32231
ILT
781 // The GNU linker by default sorts some sections by priority, so we
782 // do the same. We need to know that this might happen before we
783 // attach any input sections.
784 if (!this->script_options_->saw_sections_clause()
785 && (strcmp(name, ".ctors") == 0
786 || strcmp(name, ".dtors") == 0
787 || strcmp(name, ".init_array") == 0
788 || strcmp(name, ".fini_array") == 0))
789 os->set_may_sort_attached_input_sections();
790
9f1d377b
ILT
791 // With -z relro, we have to recognize the special sections by name.
792 // There is no other way.
793 if (!this->script_options_->saw_sections_clause()
794 && parameters->options().relro()
795 && type == elfcpp::SHT_PROGBITS
796 && (flags & elfcpp::SHF_ALLOC) != 0
797 && (flags & elfcpp::SHF_WRITE) != 0)
798 {
799 if (strcmp(name, ".data.rel.ro") == 0)
800 os->set_is_relro();
801 else if (strcmp(name, ".data.rel.ro.local") == 0)
802 {
803 os->set_is_relro();
804 os->set_is_relro_local();
805 }
806 }
807
154e0e9a
ILT
808 // If we have already attached the sections to segments, then we
809 // need to attach this one now. This happens for sections created
810 // directly by the linker.
811 if (this->sections_are_attached_)
812 this->attach_section_to_segment(os);
813
4e2b1697
ILT
814 return os;
815}
a445fddf 816
154e0e9a
ILT
817// Attach output sections to segments. This is called after we have
818// seen all the input sections.
819
820void
821Layout::attach_sections_to_segments()
822{
823 for (Section_list::iterator p = this->section_list_.begin();
824 p != this->section_list_.end();
825 ++p)
826 this->attach_section_to_segment(*p);
827
828 this->sections_are_attached_ = true;
829}
830
831// Attach an output section to a segment.
832
833void
834Layout::attach_section_to_segment(Output_section* os)
835{
836 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
837 this->unattached_section_list_.push_back(os);
838 else
839 this->attach_allocated_section_to_segment(os);
840}
841
4e2b1697 842// Attach an allocated output section to a segment.
1c4f3631 843
4e2b1697 844void
154e0e9a 845Layout::attach_allocated_section_to_segment(Output_section* os)
4e2b1697 846{
154e0e9a 847 elfcpp::Elf_Xword flags = os->flags();
4e2b1697 848 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
a2fb1b05 849
4e2b1697
ILT
850 if (parameters->options().relocatable())
851 return;
a2fb1b05 852
4e2b1697
ILT
853 // If we have a SECTIONS clause, we can't handle the attachment to
854 // segments until after we've seen all the sections.
855 if (this->script_options_->saw_sections_clause())
856 return;
a2fb1b05 857
4e2b1697 858 gold_assert(!this->script_options_->saw_phdrs_clause());
756ac4a8 859
4e2b1697 860 // This output section goes into a PT_LOAD segment.
a2fb1b05 861
4e2b1697 862 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
a2fb1b05 863
4e2b1697
ILT
864 // In general the only thing we really care about for PT_LOAD
865 // segments is whether or not they are writable, so that is how we
866 // search for them. People who need segments sorted on some other
867 // basis will have to use a linker script.
a2fb1b05 868
4e2b1697
ILT
869 Segment_list::const_iterator p;
870 for (p = this->segment_list_.begin();
871 p != this->segment_list_.end();
872 ++p)
873 {
874 if ((*p)->type() == elfcpp::PT_LOAD
af6156ef
ILT
875 && (parameters->options().omagic()
876 || ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W)))
4e2b1697
ILT
877 {
878 // If -Tbss was specified, we need to separate the data
879 // and BSS segments.
880 if (this->options_.user_set_Tbss())
881 {
882 if ((os->type() == elfcpp::SHT_NOBITS)
883 == (*p)->has_any_data_sections())
884 continue;
885 }
886
887 (*p)->add_output_section(os, seg_flags);
888 break;
889 }
890 }
54dc6425 891
4e2b1697
ILT
892 if (p == this->segment_list_.end())
893 {
894 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
895 seg_flags);
896 oseg->add_output_section(os, seg_flags);
a2fb1b05
ILT
897 }
898
4e2b1697
ILT
899 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
900 // segment.
901 if (os->type() == elfcpp::SHT_NOTE)
902 {
903 // See if we already have an equivalent PT_NOTE segment.
904 for (p = this->segment_list_.begin();
905 p != segment_list_.end();
906 ++p)
907 {
908 if ((*p)->type() == elfcpp::PT_NOTE
909 && (((*p)->flags() & elfcpp::PF_W)
910 == (seg_flags & elfcpp::PF_W)))
911 {
912 (*p)->add_output_section(os, seg_flags);
913 break;
914 }
915 }
916
917 if (p == this->segment_list_.end())
918 {
919 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
920 seg_flags);
921 oseg->add_output_section(os, seg_flags);
922 }
923 }
924
925 // If we see a loadable SHF_TLS section, we create a PT_TLS
926 // segment. There can only be one such segment.
927 if ((flags & elfcpp::SHF_TLS) != 0)
928 {
929 if (this->tls_segment_ == NULL)
2d924fd9 930 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
4e2b1697
ILT
931 this->tls_segment_->add_output_section(os, seg_flags);
932 }
9f1d377b
ILT
933
934 // If -z relro is in effect, and we see a relro section, we create a
935 // PT_GNU_RELRO segment. There can only be one such segment.
936 if (os->is_relro() && parameters->options().relro())
937 {
938 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
939 if (this->relro_segment_ == NULL)
2d924fd9 940 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
9f1d377b
ILT
941 this->relro_segment_->add_output_section(os, seg_flags);
942 }
a2fb1b05
ILT
943}
944
919ed24c
ILT
945// Make an output section for a script.
946
947Output_section*
948Layout::make_output_section_for_script(const char* name)
949{
950 name = this->namepool_.add(name, false, NULL);
951 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
952 elfcpp::SHF_ALLOC);
953 os->set_found_in_sections_clause();
954 return os;
955}
956
3802b2dd
ILT
957// Return the number of segments we expect to see.
958
959size_t
960Layout::expected_segment_count() const
961{
962 size_t ret = this->segment_list_.size();
963
964 // If we didn't see a SECTIONS clause in a linker script, we should
965 // already have the complete list of segments. Otherwise we ask the
966 // SECTIONS clause how many segments it expects, and add in the ones
967 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
968
969 if (!this->script_options_->saw_sections_clause())
970 return ret;
971 else
972 {
973 const Script_sections* ss = this->script_options_->script_sections();
974 return ret + ss->expected_segment_count(this);
975 }
976}
977
35cdfc9a
ILT
978// Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
979// is whether we saw a .note.GNU-stack section in the object file.
980// GNU_STACK_FLAGS is the section flags. The flags give the
981// protection required for stack memory. We record this in an
982// executable as a PT_GNU_STACK segment. If an object file does not
983// have a .note.GNU-stack segment, we must assume that it is an old
984// object. On some targets that will force an executable stack.
985
986void
987Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
988{
989 if (!seen_gnu_stack)
990 this->input_without_gnu_stack_note_ = true;
991 else
992 {
993 this->input_with_gnu_stack_note_ = true;
994 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
995 this->input_requires_executable_stack_ = true;
996 }
997}
998
a3ad94ed
ILT
999// Create the dynamic sections which are needed before we read the
1000// relocs.
1001
1002void
9b07f471 1003Layout::create_initial_dynamic_sections(Symbol_table* symtab)
a3ad94ed 1004{
436ca963 1005 if (parameters->doing_static_link())
a3ad94ed
ILT
1006 return;
1007
3802b2dd
ILT
1008 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1009 elfcpp::SHT_DYNAMIC,
1010 (elfcpp::SHF_ALLOC
1011 | elfcpp::SHF_WRITE),
1012 false);
9f1d377b 1013 this->dynamic_section_->set_is_relro();
a3ad94ed 1014
9b07f471 1015 symtab->define_in_output_data("_DYNAMIC", NULL, this->dynamic_section_, 0, 0,
a3ad94ed
ILT
1016 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1017 elfcpp::STV_HIDDEN, 0, false, false);
16649710 1018
9025d29d 1019 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
16649710
ILT
1020
1021 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
a3ad94ed
ILT
1022}
1023
bfd58944
ILT
1024// For each output section whose name can be represented as C symbol,
1025// define __start and __stop symbols for the section. This is a GNU
1026// extension.
1027
1028void
9b07f471 1029Layout::define_section_symbols(Symbol_table* symtab)
bfd58944
ILT
1030{
1031 for (Section_list::const_iterator p = this->section_list_.begin();
1032 p != this->section_list_.end();
1033 ++p)
1034 {
1035 const char* const name = (*p)->name();
1036 if (name[strspn(name,
1037 ("0123456789"
1038 "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
1039 "abcdefghijklmnopqrstuvwxyz"
1040 "_"))]
1041 == '\0')
1042 {
1043 const std::string name_string(name);
1044 const std::string start_name("__start_" + name_string);
1045 const std::string stop_name("__stop_" + name_string);
1046
9b07f471 1047 symtab->define_in_output_data(start_name.c_str(),
bfd58944
ILT
1048 NULL, // version
1049 *p,
1050 0, // value
1051 0, // symsize
1052 elfcpp::STT_NOTYPE,
1053 elfcpp::STB_GLOBAL,
1054 elfcpp::STV_DEFAULT,
1055 0, // nonvis
1056 false, // offset_is_from_end
a445fddf 1057 true); // only_if_ref
bfd58944 1058
9b07f471 1059 symtab->define_in_output_data(stop_name.c_str(),
bfd58944
ILT
1060 NULL, // version
1061 *p,
1062 0, // value
1063 0, // symsize
1064 elfcpp::STT_NOTYPE,
1065 elfcpp::STB_GLOBAL,
1066 elfcpp::STV_DEFAULT,
1067 0, // nonvis
1068 true, // offset_is_from_end
a445fddf 1069 true); // only_if_ref
bfd58944
ILT
1070 }
1071 }
1072}
1073
755ab8af
ILT
1074// Define symbols for group signatures.
1075
1076void
1077Layout::define_group_signatures(Symbol_table* symtab)
1078{
1079 for (Group_signatures::iterator p = this->group_signatures_.begin();
1080 p != this->group_signatures_.end();
1081 ++p)
1082 {
1083 Symbol* sym = symtab->lookup(p->signature, NULL);
1084 if (sym != NULL)
1085 p->section->set_info_symndx(sym);
1086 else
1087 {
1088 // Force the name of the group section to the group
1089 // signature, and use the group's section symbol as the
1090 // signature symbol.
1091 if (strcmp(p->section->name(), p->signature) != 0)
1092 {
1093 const char* name = this->namepool_.add(p->signature,
1094 true, NULL);
1095 p->section->set_name(name);
1096 }
1097 p->section->set_needs_symtab_index();
1098 p->section->set_info_section_symndx(p->section);
1099 }
1100 }
1101
1102 this->group_signatures_.clear();
1103}
1104
75f65a3e
ILT
1105// Find the first read-only PT_LOAD segment, creating one if
1106// necessary.
54dc6425 1107
75f65a3e
ILT
1108Output_segment*
1109Layout::find_first_load_seg()
54dc6425 1110{
75f65a3e
ILT
1111 for (Segment_list::const_iterator p = this->segment_list_.begin();
1112 p != this->segment_list_.end();
1113 ++p)
1114 {
1115 if ((*p)->type() == elfcpp::PT_LOAD
1116 && ((*p)->flags() & elfcpp::PF_R) != 0
af6156ef
ILT
1117 && (parameters->options().omagic()
1118 || ((*p)->flags() & elfcpp::PF_W) == 0))
75f65a3e
ILT
1119 return *p;
1120 }
1121
1c4f3631
ILT
1122 gold_assert(!this->script_options_->saw_phdrs_clause());
1123
3802b2dd
ILT
1124 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1125 elfcpp::PF_R);
75f65a3e 1126 return load_seg;
54dc6425
ILT
1127}
1128
1129// Finalize the layout. When this is called, we have created all the
1130// output sections and all the output segments which are based on
1131// input sections. We have several things to do, and we have to do
1132// them in the right order, so that we get the right results correctly
1133// and efficiently.
1134
1135// 1) Finalize the list of output segments and create the segment
1136// table header.
1137
1138// 2) Finalize the dynamic symbol table and associated sections.
1139
1140// 3) Determine the final file offset of all the output segments.
1141
1142// 4) Determine the final file offset of all the SHF_ALLOC output
1143// sections.
1144
75f65a3e
ILT
1145// 5) Create the symbol table sections and the section name table
1146// section.
1147
1148// 6) Finalize the symbol table: set symbol values to their final
54dc6425
ILT
1149// value and make a final determination of which symbols are going
1150// into the output symbol table.
1151
54dc6425
ILT
1152// 7) Create the section table header.
1153
1154// 8) Determine the final file offset of all the output sections which
1155// are not SHF_ALLOC, including the section table header.
1156
1157// 9) Finalize the ELF file header.
1158
75f65a3e
ILT
1159// This function returns the size of the output file.
1160
1161off_t
17a1d0a9 1162Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
8851ecca 1163 Target* target, const Task* task)
54dc6425 1164{
7e1edb90 1165 target->finalize_sections(this);
5a6f7e2d 1166
17a1d0a9 1167 this->count_local_symbols(task, input_objects);
7bf1f802 1168
35cdfc9a
ILT
1169 this->create_gold_note();
1170 this->create_executable_stack_info(target);
8ed814a9 1171 this->create_build_id();
4f211c8b 1172
3802b2dd 1173 Output_segment* phdr_seg = NULL;
8851ecca 1174 if (!parameters->options().relocatable() && !parameters->doing_static_link())
54dc6425 1175 {
dbe717ef
ILT
1176 // There was a dynamic object in the link. We need to create
1177 // some information for the dynamic linker.
1178
3802b2dd
ILT
1179 // Create the PT_PHDR segment which will hold the program
1180 // headers.
1c4f3631
ILT
1181 if (!this->script_options_->saw_phdrs_clause())
1182 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
3802b2dd 1183
14b31740
ILT
1184 // Create the dynamic symbol table, including the hash table.
1185 Output_section* dynstr;
1186 std::vector<Symbol*> dynamic_symbols;
1187 unsigned int local_dynamic_count;
a5dc0706
ILT
1188 Versions versions(*this->script_options()->version_script_info(),
1189 &this->dynpool_);
9b07f471 1190 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
14b31740
ILT
1191 &local_dynamic_count, &dynamic_symbols,
1192 &versions);
dbe717ef
ILT
1193
1194 // Create the .interp section to hold the name of the
1195 // interpreter, and put it in a PT_INTERP segment.
8851ecca 1196 if (!parameters->options().shared())
96f2030e 1197 this->create_interp(target);
a3ad94ed
ILT
1198
1199 // Finish the .dynamic section to hold the dynamic data, and put
1200 // it in a PT_DYNAMIC segment.
16649710 1201 this->finish_dynamic_section(input_objects, symtab);
14b31740
ILT
1202
1203 // We should have added everything we need to the dynamic string
1204 // table.
1205 this->dynpool_.set_string_offsets();
1206
1207 // Create the version sections. We can't do this until the
1208 // dynamic string table is complete.
46fe1623 1209 this->create_version_sections(&versions, symtab, local_dynamic_count,
14b31740 1210 dynamic_symbols, dynstr);
54dc6425
ILT
1211 }
1212
a445fddf
ILT
1213 // If there is a SECTIONS clause, put all the input sections into
1214 // the required order.
1215 Output_segment* load_seg;
88dd47ac 1216 if (this->script_options_->saw_sections_clause())
a445fddf 1217 load_seg = this->set_section_addresses_from_script(symtab);
8851ecca 1218 else if (parameters->options().relocatable())
88dd47ac 1219 load_seg = NULL;
a445fddf
ILT
1220 else
1221 load_seg = this->find_first_load_seg();
54dc6425 1222
7cc619c3 1223 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
516cb3d0
ILT
1224 load_seg = NULL;
1225
3802b2dd 1226 gold_assert(phdr_seg == NULL || load_seg != NULL);
75f65a3e
ILT
1227
1228 // Lay out the segment headers.
75f65a3e 1229 Output_segment_headers* segment_headers;
8851ecca 1230 if (parameters->options().relocatable())
6a74a719
ILT
1231 segment_headers = NULL;
1232 else
1233 {
1234 segment_headers = new Output_segment_headers(this->segment_list_);
1235 if (load_seg != NULL)
1236 load_seg->add_initial_output_data(segment_headers);
1237 if (phdr_seg != NULL)
1238 phdr_seg->add_initial_output_data(segment_headers);
1239 }
75f65a3e
ILT
1240
1241 // Lay out the file header.
1242 Output_file_header* file_header;
d391083d 1243 file_header = new Output_file_header(target, symtab, segment_headers,
a5dc0706 1244 this->options_.entry());
a445fddf
ILT
1245 if (load_seg != NULL)
1246 load_seg->add_initial_output_data(file_header);
1247
61ba1cf9 1248 this->special_output_list_.push_back(file_header);
6a74a719
ILT
1249 if (segment_headers != NULL)
1250 this->special_output_list_.push_back(segment_headers);
75f65a3e 1251
6a74a719 1252 if (this->script_options_->saw_phdrs_clause()
8851ecca 1253 && !parameters->options().relocatable())
1c4f3631
ILT
1254 {
1255 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1256 // clause in a linker script.
1257 Script_sections* ss = this->script_options_->script_sections();
1258 ss->put_headers_in_phdrs(file_header, segment_headers);
1259 }
1260
ead1e424 1261 // We set the output section indexes in set_segment_offsets and
27bc2bce 1262 // set_section_indexes.
ead1e424
ILT
1263 unsigned int shndx = 1;
1264
1265 // Set the file offsets of all the segments, and all the sections
1266 // they contain.
6a74a719 1267 off_t off;
8851ecca 1268 if (!parameters->options().relocatable())
6a74a719
ILT
1269 off = this->set_segment_offsets(target, load_seg, &shndx);
1270 else
1271 off = this->set_relocatable_section_offsets(file_header, &shndx);
75f65a3e 1272
a9a60db6
ILT
1273 // Set the file offsets of all the non-data sections we've seen so
1274 // far which don't have to wait for the input sections. We need
1275 // this in order to finalize local symbols in non-allocated
1276 // sections.
1277 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1278
d491d34e
ILT
1279 // Set the section indexes of all unallocated sections seen so far,
1280 // in case any of them are somehow referenced by a symbol.
1281 shndx = this->set_section_indexes(shndx);
1282
75f65a3e 1283 // Create the symbol table sections.
d491d34e 1284 this->create_symtab_sections(input_objects, symtab, shndx, &off);
7bf1f802
ILT
1285 if (!parameters->doing_static_link())
1286 this->assign_local_dynsym_offsets(input_objects);
75f65a3e 1287
e5756efb
ILT
1288 // Process any symbol assignments from a linker script. This must
1289 // be called after the symbol table has been finalized.
1290 this->script_options_->finalize_symbols(symtab, this);
1291
75f65a3e
ILT
1292 // Create the .shstrtab section.
1293 Output_section* shstrtab_section = this->create_shstrtab();
1294
a9a60db6
ILT
1295 // Set the file offsets of the rest of the non-data sections which
1296 // don't have to wait for the input sections.
9a0910c3 1297 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
86887060 1298
d491d34e
ILT
1299 // Now that all sections have been created, set the section indexes
1300 // for any sections which haven't been done yet.
86887060 1301 shndx = this->set_section_indexes(shndx);
ead1e424 1302
75f65a3e 1303 // Create the section table header.
d491d34e 1304 this->create_shdrs(shstrtab_section, &off);
75f65a3e 1305
17a1d0a9
ILT
1306 // If there are no sections which require postprocessing, we can
1307 // handle the section names now, and avoid a resize later.
1308 if (!this->any_postprocessing_sections_)
1309 off = this->set_section_offsets(off,
1310 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1311
27bc2bce 1312 file_header->set_section_info(this->section_headers_, shstrtab_section);
75f65a3e 1313
27bc2bce
ILT
1314 // Now we know exactly where everything goes in the output file
1315 // (except for non-allocated sections which require postprocessing).
a3ad94ed 1316 Output_data::layout_complete();
75f65a3e 1317
e44fcf3b
ILT
1318 this->output_file_size_ = off;
1319
75f65a3e
ILT
1320 return off;
1321}
1322
8ed814a9
ILT
1323// Create a note header following the format defined in the ELF ABI.
1324// NAME is the name, NOTE_TYPE is the type, DESCSZ is the size of the
1325// descriptor. ALLOCATE is true if the section should be allocated in
1326// memory. This returns the new note section. It sets
1327// *TRAILING_PADDING to the number of trailing zero bytes required.
4f211c8b 1328
8ed814a9 1329Output_section*
ef4ab7a8
PP
1330Layout::create_note(const char* name, int note_type,
1331 const char* section_name, size_t descsz,
8ed814a9 1332 bool allocate, size_t* trailing_padding)
4f211c8b 1333{
e2305dc0
ILT
1334 // Authorities all agree that the values in a .note field should
1335 // be aligned on 4-byte boundaries for 32-bit binaries. However,
1336 // they differ on what the alignment is for 64-bit binaries.
1337 // The GABI says unambiguously they take 8-byte alignment:
1338 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
1339 // Other documentation says alignment should always be 4 bytes:
1340 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
1341 // GNU ld and GNU readelf both support the latter (at least as of
1342 // version 2.16.91), and glibc always generates the latter for
1343 // .note.ABI-tag (as of version 1.6), so that's the one we go with
1344 // here.
35cdfc9a 1345#ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
8851ecca 1346 const int size = parameters->target().get_size();
e2305dc0
ILT
1347#else
1348 const int size = 32;
1349#endif
4f211c8b
ILT
1350
1351 // The contents of the .note section.
4f211c8b
ILT
1352 size_t namesz = strlen(name) + 1;
1353 size_t aligned_namesz = align_address(namesz, size / 8);
4f211c8b 1354 size_t aligned_descsz = align_address(descsz, size / 8);
4f211c8b 1355
8ed814a9 1356 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
4f211c8b 1357
8ed814a9
ILT
1358 unsigned char* buffer = new unsigned char[notehdrsz];
1359 memset(buffer, 0, notehdrsz);
4f211c8b 1360
8851ecca 1361 bool is_big_endian = parameters->target().is_big_endian();
4f211c8b
ILT
1362
1363 if (size == 32)
1364 {
1365 if (!is_big_endian)
1366 {
1367 elfcpp::Swap<32, false>::writeval(buffer, namesz);
1368 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
1369 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
1370 }
1371 else
1372 {
1373 elfcpp::Swap<32, true>::writeval(buffer, namesz);
1374 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
1375 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
1376 }
1377 }
1378 else if (size == 64)
1379 {
1380 if (!is_big_endian)
1381 {
1382 elfcpp::Swap<64, false>::writeval(buffer, namesz);
1383 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
1384 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
1385 }
1386 else
1387 {
1388 elfcpp::Swap<64, true>::writeval(buffer, namesz);
1389 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
1390 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
1391 }
1392 }
1393 else
1394 gold_unreachable();
1395
1396 memcpy(buffer + 3 * (size / 8), name, namesz);
4f211c8b 1397
ef4ab7a8 1398 const char *note_name = this->namepool_.add(section_name, false, NULL);
8ed814a9
ILT
1399 elfcpp::Elf_Xword flags = 0;
1400 if (allocate)
1401 flags = elfcpp::SHF_ALLOC;
4f211c8b
ILT
1402 Output_section* os = this->make_output_section(note_name,
1403 elfcpp::SHT_NOTE,
8ed814a9
ILT
1404 flags);
1405 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
7d9e3d98
ILT
1406 size / 8,
1407 "** note header");
8ed814a9
ILT
1408 os->add_output_section_data(posd);
1409
1410 *trailing_padding = aligned_descsz - descsz;
1411
1412 return os;
1413}
1414
1415// For an executable or shared library, create a note to record the
1416// version of gold used to create the binary.
1417
1418void
1419Layout::create_gold_note()
1420{
1421 if (parameters->options().relocatable())
1422 return;
1423
1424 std::string desc = std::string("gold ") + gold::get_version_string();
1425
1426 size_t trailing_padding;
1427 Output_section *os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
ef4ab7a8
PP
1428 ".note.gnu.gold-version", desc.size(),
1429 false, &trailing_padding);
8ed814a9
ILT
1430
1431 Output_section_data* posd = new Output_data_const(desc, 4);
4f211c8b 1432 os->add_output_section_data(posd);
8ed814a9
ILT
1433
1434 if (trailing_padding > 0)
1435 {
7d9e3d98 1436 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
1437 os->add_output_section_data(posd);
1438 }
4f211c8b
ILT
1439}
1440
35cdfc9a
ILT
1441// Record whether the stack should be executable. This can be set
1442// from the command line using the -z execstack or -z noexecstack
1443// options. Otherwise, if any input file has a .note.GNU-stack
1444// section with the SHF_EXECINSTR flag set, the stack should be
1445// executable. Otherwise, if at least one input file a
1446// .note.GNU-stack section, and some input file has no .note.GNU-stack
1447// section, we use the target default for whether the stack should be
1448// executable. Otherwise, we don't generate a stack note. When
1449// generating a object file, we create a .note.GNU-stack section with
1450// the appropriate marking. When generating an executable or shared
1451// library, we create a PT_GNU_STACK segment.
1452
1453void
1454Layout::create_executable_stack_info(const Target* target)
1455{
1456 bool is_stack_executable;
1457 if (this->options_.is_execstack_set())
1458 is_stack_executable = this->options_.is_stack_executable();
1459 else if (!this->input_with_gnu_stack_note_)
1460 return;
1461 else
1462 {
1463 if (this->input_requires_executable_stack_)
1464 is_stack_executable = true;
1465 else if (this->input_without_gnu_stack_note_)
1466 is_stack_executable = target->is_default_stack_executable();
1467 else
1468 is_stack_executable = false;
1469 }
1470
8851ecca 1471 if (parameters->options().relocatable())
35cdfc9a
ILT
1472 {
1473 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
1474 elfcpp::Elf_Xword flags = 0;
1475 if (is_stack_executable)
1476 flags |= elfcpp::SHF_EXECINSTR;
1477 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags);
1478 }
1479 else
1480 {
1c4f3631
ILT
1481 if (this->script_options_->saw_phdrs_clause())
1482 return;
35cdfc9a
ILT
1483 int flags = elfcpp::PF_R | elfcpp::PF_W;
1484 if (is_stack_executable)
1485 flags |= elfcpp::PF_X;
3802b2dd 1486 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
35cdfc9a
ILT
1487 }
1488}
1489
8ed814a9
ILT
1490// If --build-id was used, set up the build ID note.
1491
1492void
1493Layout::create_build_id()
1494{
1495 if (!parameters->options().user_set_build_id())
1496 return;
1497
1498 const char* style = parameters->options().build_id();
1499 if (strcmp(style, "none") == 0)
1500 return;
1501
1502 // Set DESCSZ to the size of the note descriptor. When possible,
1503 // set DESC to the note descriptor contents.
1504 size_t descsz;
1505 std::string desc;
1506 if (strcmp(style, "md5") == 0)
1507 descsz = 128 / 8;
1508 else if (strcmp(style, "sha1") == 0)
1509 descsz = 160 / 8;
1510 else if (strcmp(style, "uuid") == 0)
1511 {
1512 const size_t uuidsz = 128 / 8;
1513
1514 char buffer[uuidsz];
1515 memset(buffer, 0, uuidsz);
1516
2a00e4fb 1517 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
8ed814a9
ILT
1518 if (descriptor < 0)
1519 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
1520 strerror(errno));
1521 else
1522 {
1523 ssize_t got = ::read(descriptor, buffer, uuidsz);
2a00e4fb 1524 release_descriptor(descriptor, true);
8ed814a9
ILT
1525 if (got < 0)
1526 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
1527 else if (static_cast<size_t>(got) != uuidsz)
1528 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
1529 uuidsz, got);
1530 }
1531
1532 desc.assign(buffer, uuidsz);
1533 descsz = uuidsz;
1534 }
1535 else if (strncmp(style, "0x", 2) == 0)
1536 {
1537 hex_init();
1538 const char* p = style + 2;
1539 while (*p != '\0')
1540 {
1541 if (hex_p(p[0]) && hex_p(p[1]))
1542 {
1543 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
1544 desc += c;
1545 p += 2;
1546 }
1547 else if (*p == '-' || *p == ':')
1548 ++p;
1549 else
1550 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
1551 style);
1552 }
1553 descsz = desc.size();
1554 }
1555 else
1556 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
1557
1558 // Create the note.
1559 size_t trailing_padding;
1560 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
ef4ab7a8
PP
1561 ".note.gnu.build-id", descsz, true,
1562 &trailing_padding);
8ed814a9
ILT
1563
1564 if (!desc.empty())
1565 {
1566 // We know the value already, so we fill it in now.
1567 gold_assert(desc.size() == descsz);
1568
1569 Output_section_data* posd = new Output_data_const(desc, 4);
1570 os->add_output_section_data(posd);
1571
1572 if (trailing_padding != 0)
1573 {
7d9e3d98 1574 posd = new Output_data_zero_fill(trailing_padding, 0);
8ed814a9
ILT
1575 os->add_output_section_data(posd);
1576 }
1577 }
1578 else
1579 {
1580 // We need to compute a checksum after we have completed the
1581 // link.
1582 gold_assert(trailing_padding == 0);
7d9e3d98 1583 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
8ed814a9
ILT
1584 os->add_output_section_data(this->build_id_note_);
1585 os->set_after_input_sections();
1586 }
1587}
1588
75f65a3e
ILT
1589// Return whether SEG1 should be before SEG2 in the output file. This
1590// is based entirely on the segment type and flags. When this is
1591// called the segment addresses has normally not yet been set.
1592
1593bool
1594Layout::segment_precedes(const Output_segment* seg1,
1595 const Output_segment* seg2)
1596{
1597 elfcpp::Elf_Word type1 = seg1->type();
1598 elfcpp::Elf_Word type2 = seg2->type();
1599
1600 // The single PT_PHDR segment is required to precede any loadable
1601 // segment. We simply make it always first.
1602 if (type1 == elfcpp::PT_PHDR)
1603 {
a3ad94ed 1604 gold_assert(type2 != elfcpp::PT_PHDR);
75f65a3e
ILT
1605 return true;
1606 }
1607 if (type2 == elfcpp::PT_PHDR)
1608 return false;
1609
1610 // The single PT_INTERP segment is required to precede any loadable
1611 // segment. We simply make it always second.
1612 if (type1 == elfcpp::PT_INTERP)
1613 {
a3ad94ed 1614 gold_assert(type2 != elfcpp::PT_INTERP);
75f65a3e
ILT
1615 return true;
1616 }
1617 if (type2 == elfcpp::PT_INTERP)
1618 return false;
1619
1620 // We then put PT_LOAD segments before any other segments.
1621 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
1622 return true;
1623 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
1624 return false;
1625
9f1d377b
ILT
1626 // We put the PT_TLS segment last except for the PT_GNU_RELRO
1627 // segment, because that is where the dynamic linker expects to find
1628 // it (this is just for efficiency; other positions would also work
1629 // correctly).
1630 if (type1 == elfcpp::PT_TLS
1631 && type2 != elfcpp::PT_TLS
1632 && type2 != elfcpp::PT_GNU_RELRO)
1633 return false;
1634 if (type2 == elfcpp::PT_TLS
1635 && type1 != elfcpp::PT_TLS
1636 && type1 != elfcpp::PT_GNU_RELRO)
1637 return true;
1638
1639 // We put the PT_GNU_RELRO segment last, because that is where the
1640 // dynamic linker expects to find it (as with PT_TLS, this is just
1641 // for efficiency).
1642 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
92e059d8 1643 return false;
9f1d377b 1644 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
92e059d8
ILT
1645 return true;
1646
75f65a3e
ILT
1647 const elfcpp::Elf_Word flags1 = seg1->flags();
1648 const elfcpp::Elf_Word flags2 = seg2->flags();
1649
1650 // The order of non-PT_LOAD segments is unimportant. We simply sort
1651 // by the numeric segment type and flags values. There should not
1652 // be more than one segment with the same type and flags.
1653 if (type1 != elfcpp::PT_LOAD)
1654 {
1655 if (type1 != type2)
1656 return type1 < type2;
a3ad94ed 1657 gold_assert(flags1 != flags2);
75f65a3e
ILT
1658 return flags1 < flags2;
1659 }
1660
a445fddf
ILT
1661 // If the addresses are set already, sort by load address.
1662 if (seg1->are_addresses_set())
1663 {
1664 if (!seg2->are_addresses_set())
1665 return true;
1666
1667 unsigned int section_count1 = seg1->output_section_count();
1668 unsigned int section_count2 = seg2->output_section_count();
1669 if (section_count1 == 0 && section_count2 > 0)
1670 return true;
1671 if (section_count1 > 0 && section_count2 == 0)
1672 return false;
1673
1674 uint64_t paddr1 = seg1->first_section_load_address();
1675 uint64_t paddr2 = seg2->first_section_load_address();
1676 if (paddr1 != paddr2)
1677 return paddr1 < paddr2;
1678 }
1679 else if (seg2->are_addresses_set())
1680 return false;
1681
75f65a3e 1682 // We sort PT_LOAD segments based on the flags. Readonly segments
756ac4a8
ILT
1683 // come before writable segments. Then writable segments with data
1684 // come before writable segments without data. Then executable
1685 // segments come before non-executable segments. Then the unlikely
1686 // case of a non-readable segment comes before the normal case of a
1687 // readable segment. If there are multiple segments with the same
1688 // type and flags, we require that the address be set, and we sort
1689 // by virtual address and then physical address.
75f65a3e
ILT
1690 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
1691 return (flags1 & elfcpp::PF_W) == 0;
756ac4a8
ILT
1692 if ((flags1 & elfcpp::PF_W) != 0
1693 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
1694 return seg1->has_any_data_sections();
75f65a3e
ILT
1695 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
1696 return (flags1 & elfcpp::PF_X) != 0;
1697 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
1698 return (flags1 & elfcpp::PF_R) == 0;
1699
a445fddf
ILT
1700 // We shouldn't get here--we shouldn't create segments which we
1701 // can't distinguish.
1702 gold_unreachable();
75f65a3e
ILT
1703}
1704
ead1e424
ILT
1705// Set the file offsets of all the segments, and all the sections they
1706// contain. They have all been created. LOAD_SEG must be be laid out
1707// first. Return the offset of the data to follow.
75f65a3e
ILT
1708
1709off_t
ead1e424
ILT
1710Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
1711 unsigned int *pshndx)
75f65a3e
ILT
1712{
1713 // Sort them into the final order.
54dc6425
ILT
1714 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
1715 Layout::Compare_segments());
1716
75f65a3e
ILT
1717 // Find the PT_LOAD segments, and set their addresses and offsets
1718 // and their section's addresses and offsets.
0c5e9c22 1719 uint64_t addr;
45aa233b
ILT
1720 if (this->options_.user_set_Ttext())
1721 addr = this->options_.Ttext();
8851ecca 1722 else if (parameters->options().shared())
a445fddf 1723 addr = 0;
0c5e9c22
ILT
1724 else
1725 addr = target->default_text_segment_address();
75f65a3e 1726 off_t off = 0;
a445fddf
ILT
1727
1728 // If LOAD_SEG is NULL, then the file header and segment headers
1729 // will not be loadable. But they still need to be at offset 0 in
1730 // the file. Set their offsets now.
1731 if (load_seg == NULL)
1732 {
1733 for (Data_list::iterator p = this->special_output_list_.begin();
1734 p != this->special_output_list_.end();
1735 ++p)
1736 {
1737 off = align_address(off, (*p)->addralign());
1738 (*p)->set_address_and_file_offset(0, off);
1739 off += (*p)->data_size();
1740 }
1741 }
1742
34810851
ILT
1743 const bool check_sections = parameters->options().check_sections();
1744 Output_segment* last_load_segment = NULL;
1745
75f65a3e
ILT
1746 bool was_readonly = false;
1747 for (Segment_list::iterator p = this->segment_list_.begin();
1748 p != this->segment_list_.end();
1749 ++p)
1750 {
1751 if ((*p)->type() == elfcpp::PT_LOAD)
1752 {
1753 if (load_seg != NULL && load_seg != *p)
a3ad94ed 1754 gold_unreachable();
75f65a3e
ILT
1755 load_seg = NULL;
1756
756ac4a8
ILT
1757 bool are_addresses_set = (*p)->are_addresses_set();
1758 if (are_addresses_set)
1759 {
1760 // When it comes to setting file offsets, we care about
1761 // the physical address.
1762 addr = (*p)->paddr();
1763 }
45aa233b 1764 else if (this->options_.user_set_Tdata()
756ac4a8 1765 && ((*p)->flags() & elfcpp::PF_W) != 0
45aa233b 1766 && (!this->options_.user_set_Tbss()
756ac4a8
ILT
1767 || (*p)->has_any_data_sections()))
1768 {
45aa233b 1769 addr = this->options_.Tdata();
756ac4a8
ILT
1770 are_addresses_set = true;
1771 }
45aa233b 1772 else if (this->options_.user_set_Tbss()
756ac4a8
ILT
1773 && ((*p)->flags() & elfcpp::PF_W) != 0
1774 && !(*p)->has_any_data_sections())
1775 {
45aa233b 1776 addr = this->options_.Tbss();
756ac4a8
ILT
1777 are_addresses_set = true;
1778 }
1779
75f65a3e
ILT
1780 uint64_t orig_addr = addr;
1781 uint64_t orig_off = off;
1782
a445fddf 1783 uint64_t aligned_addr = 0;
75f65a3e 1784 uint64_t abi_pagesize = target->abi_pagesize();
af6156ef 1785 uint64_t common_pagesize = target->common_pagesize();
0496d5e5 1786
af6156ef
ILT
1787 if (!parameters->options().nmagic()
1788 && !parameters->options().omagic())
1789 (*p)->set_minimum_p_align(common_pagesize);
0496d5e5 1790
a445fddf 1791 if (are_addresses_set)
75f65a3e 1792 {
af6156ef
ILT
1793 if (!parameters->options().nmagic()
1794 && !parameters->options().omagic())
1795 {
1796 // Adjust the file offset to the same address modulo
1797 // the page size.
1798 uint64_t unsigned_off = off;
1799 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
1800 | (addr & (abi_pagesize - 1)));
1801 if (aligned_off < unsigned_off)
1802 aligned_off += abi_pagesize;
1803 off = aligned_off;
1804 }
a445fddf
ILT
1805 }
1806 else
1807 {
1808 // If the last segment was readonly, and this one is
1809 // not, then skip the address forward one page,
1810 // maintaining the same position within the page. This
1811 // lets us store both segments overlapping on a single
1812 // page in the file, but the loader will put them on
1813 // different pages in memory.
1814
1815 addr = align_address(addr, (*p)->maximum_alignment());
75f65a3e 1816 aligned_addr = addr;
a445fddf
ILT
1817
1818 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
1819 {
1820 if ((addr & (abi_pagesize - 1)) != 0)
1821 addr = addr + abi_pagesize;
1822 }
1823
1824 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
75f65a3e
ILT
1825 }
1826
ead1e424 1827 unsigned int shndx_hold = *pshndx;
96a2b4e4
ILT
1828 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
1829 &off, pshndx);
75f65a3e
ILT
1830
1831 // Now that we know the size of this segment, we may be able
1832 // to save a page in memory, at the cost of wasting some
1833 // file space, by instead aligning to the start of a new
1834 // page. Here we use the real machine page size rather than
1835 // the ABI mandated page size.
1836
a445fddf 1837 if (!are_addresses_set && aligned_addr != addr)
75f65a3e 1838 {
75f65a3e
ILT
1839 uint64_t first_off = (common_pagesize
1840 - (aligned_addr
1841 & (common_pagesize - 1)));
1842 uint64_t last_off = new_addr & (common_pagesize - 1);
1843 if (first_off > 0
1844 && last_off > 0
1845 && ((aligned_addr & ~ (common_pagesize - 1))
1846 != (new_addr & ~ (common_pagesize - 1)))
1847 && first_off + last_off <= common_pagesize)
1848 {
ead1e424
ILT
1849 *pshndx = shndx_hold;
1850 addr = align_address(aligned_addr, common_pagesize);
a445fddf 1851 addr = align_address(addr, (*p)->maximum_alignment());
75f65a3e 1852 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
96a2b4e4
ILT
1853 new_addr = (*p)->set_section_addresses(this, true, addr,
1854 &off, pshndx);
75f65a3e
ILT
1855 }
1856 }
1857
1858 addr = new_addr;
1859
1860 if (((*p)->flags() & elfcpp::PF_W) == 0)
1861 was_readonly = true;
34810851
ILT
1862
1863 // Implement --check-sections. We know that the segments
1864 // are sorted by LMA.
1865 if (check_sections && last_load_segment != NULL)
1866 {
1867 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
1868 if (last_load_segment->paddr() + last_load_segment->memsz()
1869 > (*p)->paddr())
1870 {
1871 unsigned long long lb1 = last_load_segment->paddr();
1872 unsigned long long le1 = lb1 + last_load_segment->memsz();
1873 unsigned long long lb2 = (*p)->paddr();
1874 unsigned long long le2 = lb2 + (*p)->memsz();
1875 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
1876 "[0x%llx -> 0x%llx]"),
1877 lb1, le1, lb2, le2);
1878 }
1879 }
1880 last_load_segment = *p;
75f65a3e
ILT
1881 }
1882 }
1883
1884 // Handle the non-PT_LOAD segments, setting their offsets from their
1885 // section's offsets.
1886 for (Segment_list::iterator p = this->segment_list_.begin();
1887 p != this->segment_list_.end();
1888 ++p)
1889 {
1890 if ((*p)->type() != elfcpp::PT_LOAD)
1891 (*p)->set_offset();
1892 }
1893
7bf1f802
ILT
1894 // Set the TLS offsets for each section in the PT_TLS segment.
1895 if (this->tls_segment_ != NULL)
1896 this->tls_segment_->set_tls_offsets();
1897
75f65a3e
ILT
1898 return off;
1899}
1900
6a74a719
ILT
1901// Set the offsets of all the allocated sections when doing a
1902// relocatable link. This does the same jobs as set_segment_offsets,
1903// only for a relocatable link.
1904
1905off_t
1906Layout::set_relocatable_section_offsets(Output_data* file_header,
1907 unsigned int *pshndx)
1908{
1909 off_t off = 0;
1910
1911 file_header->set_address_and_file_offset(0, 0);
1912 off += file_header->data_size();
1913
1914 for (Section_list::iterator p = this->section_list_.begin();
1915 p != this->section_list_.end();
1916 ++p)
1917 {
1918 // We skip unallocated sections here, except that group sections
1919 // have to come first.
1920 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
1921 && (*p)->type() != elfcpp::SHT_GROUP)
1922 continue;
1923
1924 off = align_address(off, (*p)->addralign());
1925
1926 // The linker script might have set the address.
1927 if (!(*p)->is_address_valid())
1928 (*p)->set_address(0);
1929 (*p)->set_file_offset(off);
1930 (*p)->finalize_data_size();
1931 off += (*p)->data_size();
1932
1933 (*p)->set_out_shndx(*pshndx);
1934 ++*pshndx;
1935 }
1936
1937 return off;
1938}
1939
75f65a3e
ILT
1940// Set the file offset of all the sections not associated with a
1941// segment.
1942
1943off_t
9a0910c3 1944Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
75f65a3e 1945{
a3ad94ed
ILT
1946 for (Section_list::iterator p = this->unattached_section_list_.begin();
1947 p != this->unattached_section_list_.end();
75f65a3e
ILT
1948 ++p)
1949 {
27bc2bce
ILT
1950 // The symtab section is handled in create_symtab_sections.
1951 if (*p == this->symtab_section_)
61ba1cf9 1952 continue;
27bc2bce 1953
a9a60db6
ILT
1954 // If we've already set the data size, don't set it again.
1955 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
1956 continue;
1957
96803768
ILT
1958 if (pass == BEFORE_INPUT_SECTIONS_PASS
1959 && (*p)->requires_postprocessing())
17a1d0a9
ILT
1960 {
1961 (*p)->create_postprocessing_buffer();
1962 this->any_postprocessing_sections_ = true;
1963 }
96803768 1964
9a0910c3
ILT
1965 if (pass == BEFORE_INPUT_SECTIONS_PASS
1966 && (*p)->after_input_sections())
1967 continue;
17a1d0a9 1968 else if (pass == POSTPROCESSING_SECTIONS_PASS
9a0910c3
ILT
1969 && (!(*p)->after_input_sections()
1970 || (*p)->type() == elfcpp::SHT_STRTAB))
1971 continue;
17a1d0a9 1972 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
9a0910c3
ILT
1973 && (!(*p)->after_input_sections()
1974 || (*p)->type() != elfcpp::SHT_STRTAB))
1975 continue;
27bc2bce 1976
ead1e424 1977 off = align_address(off, (*p)->addralign());
27bc2bce
ILT
1978 (*p)->set_file_offset(off);
1979 (*p)->finalize_data_size();
75f65a3e 1980 off += (*p)->data_size();
96803768
ILT
1981
1982 // At this point the name must be set.
17a1d0a9 1983 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
96803768 1984 this->namepool_.add((*p)->name(), false, NULL);
75f65a3e
ILT
1985 }
1986 return off;
1987}
1988
86887060
ILT
1989// Set the section indexes of all the sections not associated with a
1990// segment.
1991
1992unsigned int
1993Layout::set_section_indexes(unsigned int shndx)
1994{
1995 for (Section_list::iterator p = this->unattached_section_list_.begin();
1996 p != this->unattached_section_list_.end();
1997 ++p)
1998 {
d491d34e
ILT
1999 if (!(*p)->has_out_shndx())
2000 {
2001 (*p)->set_out_shndx(shndx);
2002 ++shndx;
2003 }
86887060
ILT
2004 }
2005 return shndx;
2006}
2007
a445fddf
ILT
2008// Set the section addresses according to the linker script. This is
2009// only called when we see a SECTIONS clause. This returns the
2010// program segment which should hold the file header and segment
2011// headers, if any. It will return NULL if they should not be in a
2012// segment.
2013
2014Output_segment*
2015Layout::set_section_addresses_from_script(Symbol_table* symtab)
2016{
2017 Script_sections* ss = this->script_options_->script_sections();
2018 gold_assert(ss->saw_sections_clause());
2019
2020 // Place each orphaned output section in the script.
2021 for (Section_list::iterator p = this->section_list_.begin();
2022 p != this->section_list_.end();
2023 ++p)
2024 {
2025 if (!(*p)->found_in_sections_clause())
2026 ss->place_orphan(*p);
2027 }
2028
2029 return this->script_options_->set_section_addresses(symtab, this);
2030}
2031
7bf1f802
ILT
2032// Count the local symbols in the regular symbol table and the dynamic
2033// symbol table, and build the respective string pools.
2034
2035void
17a1d0a9
ILT
2036Layout::count_local_symbols(const Task* task,
2037 const Input_objects* input_objects)
7bf1f802 2038{
6d013333
ILT
2039 // First, figure out an upper bound on the number of symbols we'll
2040 // be inserting into each pool. This helps us create the pools with
2041 // the right size, to avoid unnecessary hashtable resizing.
2042 unsigned int symbol_count = 0;
2043 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2044 p != input_objects->relobj_end();
2045 ++p)
2046 symbol_count += (*p)->local_symbol_count();
2047
2048 // Go from "upper bound" to "estimate." We overcount for two
2049 // reasons: we double-count symbols that occur in more than one
2050 // object file, and we count symbols that are dropped from the
2051 // output. Add it all together and assume we overcount by 100%.
2052 symbol_count /= 2;
2053
2054 // We assume all symbols will go into both the sympool and dynpool.
2055 this->sympool_.reserve(symbol_count);
2056 this->dynpool_.reserve(symbol_count);
2057
7bf1f802
ILT
2058 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2059 p != input_objects->relobj_end();
2060 ++p)
2061 {
17a1d0a9 2062 Task_lock_obj<Object> tlo(task, *p);
7bf1f802
ILT
2063 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2064 }
2065}
2066
b8e6aad9
ILT
2067// Create the symbol table sections. Here we also set the final
2068// values of the symbols. At this point all the loadable sections are
d491d34e 2069// fully laid out. SHNUM is the number of sections so far.
75f65a3e
ILT
2070
2071void
9025d29d 2072Layout::create_symtab_sections(const Input_objects* input_objects,
75f65a3e 2073 Symbol_table* symtab,
d491d34e 2074 unsigned int shnum,
16649710 2075 off_t* poff)
75f65a3e 2076{
61ba1cf9
ILT
2077 int symsize;
2078 unsigned int align;
8851ecca 2079 if (parameters->target().get_size() == 32)
61ba1cf9
ILT
2080 {
2081 symsize = elfcpp::Elf_sizes<32>::sym_size;
2082 align = 4;
2083 }
8851ecca 2084 else if (parameters->target().get_size() == 64)
61ba1cf9
ILT
2085 {
2086 symsize = elfcpp::Elf_sizes<64>::sym_size;
2087 align = 8;
2088 }
2089 else
a3ad94ed 2090 gold_unreachable();
61ba1cf9
ILT
2091
2092 off_t off = *poff;
ead1e424 2093 off = align_address(off, align);
61ba1cf9
ILT
2094 off_t startoff = off;
2095
2096 // Save space for the dummy symbol at the start of the section. We
2097 // never bother to write this out--it will just be left as zero.
2098 off += symsize;
c06b7b0b 2099 unsigned int local_symbol_index = 1;
61ba1cf9 2100
a3ad94ed
ILT
2101 // Add STT_SECTION symbols for each Output section which needs one.
2102 for (Section_list::iterator p = this->section_list_.begin();
2103 p != this->section_list_.end();
2104 ++p)
2105 {
2106 if (!(*p)->needs_symtab_index())
2107 (*p)->set_symtab_index(-1U);
2108 else
2109 {
2110 (*p)->set_symtab_index(local_symbol_index);
2111 ++local_symbol_index;
2112 off += symsize;
2113 }
2114 }
2115
f6ce93d6
ILT
2116 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2117 p != input_objects->relobj_end();
75f65a3e
ILT
2118 ++p)
2119 {
c06b7b0b 2120 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
7bf1f802 2121 off);
c06b7b0b
ILT
2122 off += (index - local_symbol_index) * symsize;
2123 local_symbol_index = index;
75f65a3e
ILT
2124 }
2125
c06b7b0b 2126 unsigned int local_symcount = local_symbol_index;
a3ad94ed 2127 gold_assert(local_symcount * symsize == off - startoff);
61ba1cf9 2128
16649710
ILT
2129 off_t dynoff;
2130 size_t dyn_global_index;
2131 size_t dyncount;
2132 if (this->dynsym_section_ == NULL)
2133 {
2134 dynoff = 0;
2135 dyn_global_index = 0;
2136 dyncount = 0;
2137 }
2138 else
2139 {
2140 dyn_global_index = this->dynsym_section_->info();
2141 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2142 dynoff = this->dynsym_section_->offset() + locsize;
2143 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
f5c3f225 2144 gold_assert(static_cast<off_t>(dyncount * symsize)
16649710
ILT
2145 == this->dynsym_section_->data_size() - locsize);
2146 }
2147
55a93433
ILT
2148 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2149 &this->sympool_, &local_symcount);
75f65a3e 2150
8851ecca 2151 if (!parameters->options().strip_all())
9e2dcb77
ILT
2152 {
2153 this->sympool_.set_string_offsets();
61ba1cf9 2154
cfd73a4e 2155 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
9e2dcb77
ILT
2156 Output_section* osymtab = this->make_output_section(symtab_name,
2157 elfcpp::SHT_SYMTAB,
2158 0);
2159 this->symtab_section_ = osymtab;
a3ad94ed 2160
27bc2bce 2161 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
7d9e3d98
ILT
2162 align,
2163 "** symtab");
9e2dcb77 2164 osymtab->add_output_section_data(pos);
61ba1cf9 2165
d491d34e
ILT
2166 // We generate a .symtab_shndx section if we have more than
2167 // SHN_LORESERVE sections. Technically it is possible that we
2168 // don't need one, because it is possible that there are no
2169 // symbols in any of sections with indexes larger than
2170 // SHN_LORESERVE. That is probably unusual, though, and it is
2171 // easier to always create one than to compute section indexes
2172 // twice (once here, once when writing out the symbols).
2173 if (shnum >= elfcpp::SHN_LORESERVE)
2174 {
2175 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
2176 false, NULL);
2177 Output_section* osymtab_xindex =
2178 this->make_output_section(symtab_xindex_name,
2179 elfcpp::SHT_SYMTAB_SHNDX, 0);
2180
2181 size_t symcount = (off - startoff) / symsize;
2182 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
2183
2184 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
2185
2186 osymtab_xindex->set_link_section(osymtab);
2187 osymtab_xindex->set_addralign(4);
2188 osymtab_xindex->set_entsize(4);
2189
2190 osymtab_xindex->set_after_input_sections();
2191
2192 // This tells the driver code to wait until the symbol table
2193 // has written out before writing out the postprocessing
2194 // sections, including the .symtab_shndx section.
2195 this->any_postprocessing_sections_ = true;
2196 }
2197
cfd73a4e 2198 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
9e2dcb77
ILT
2199 Output_section* ostrtab = this->make_output_section(strtab_name,
2200 elfcpp::SHT_STRTAB,
2201 0);
a3ad94ed 2202
9e2dcb77
ILT
2203 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
2204 ostrtab->add_output_section_data(pstr);
61ba1cf9 2205
27bc2bce
ILT
2206 osymtab->set_file_offset(startoff);
2207 osymtab->finalize_data_size();
9e2dcb77
ILT
2208 osymtab->set_link_section(ostrtab);
2209 osymtab->set_info(local_symcount);
2210 osymtab->set_entsize(symsize);
61ba1cf9 2211
9e2dcb77
ILT
2212 *poff = off;
2213 }
75f65a3e
ILT
2214}
2215
2216// Create the .shstrtab section, which holds the names of the
2217// sections. At the time this is called, we have created all the
2218// output sections except .shstrtab itself.
2219
2220Output_section*
2221Layout::create_shstrtab()
2222{
2223 // FIXME: We don't need to create a .shstrtab section if we are
2224 // stripping everything.
2225
cfd73a4e 2226 const char* name = this->namepool_.add(".shstrtab", false, NULL);
75f65a3e 2227
a3ad94ed 2228 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
75f65a3e 2229
27bc2bce
ILT
2230 // We can't write out this section until we've set all the section
2231 // names, and we don't set the names of compressed output sections
2232 // until relocations are complete.
2233 os->set_after_input_sections();
2234
a3ad94ed
ILT
2235 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
2236 os->add_output_section_data(posd);
75f65a3e
ILT
2237
2238 return os;
2239}
2240
2241// Create the section headers. SIZE is 32 or 64. OFF is the file
2242// offset.
2243
27bc2bce 2244void
d491d34e 2245Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
75f65a3e
ILT
2246{
2247 Output_section_headers* oshdrs;
9025d29d 2248 oshdrs = new Output_section_headers(this,
16649710 2249 &this->segment_list_,
6a74a719 2250 &this->section_list_,
16649710 2251 &this->unattached_section_list_,
d491d34e
ILT
2252 &this->namepool_,
2253 shstrtab_section);
ead1e424 2254 off_t off = align_address(*poff, oshdrs->addralign());
27bc2bce 2255 oshdrs->set_address_and_file_offset(0, off);
61ba1cf9
ILT
2256 off += oshdrs->data_size();
2257 *poff = off;
27bc2bce 2258 this->section_headers_ = oshdrs;
54dc6425
ILT
2259}
2260
d491d34e
ILT
2261// Count the allocated sections.
2262
2263size_t
2264Layout::allocated_output_section_count() const
2265{
2266 size_t section_count = 0;
2267 for (Segment_list::const_iterator p = this->segment_list_.begin();
2268 p != this->segment_list_.end();
2269 ++p)
2270 section_count += (*p)->output_section_count();
2271 return section_count;
2272}
2273
dbe717ef
ILT
2274// Create the dynamic symbol table.
2275
2276void
7bf1f802 2277Layout::create_dynamic_symtab(const Input_objects* input_objects,
9b07f471 2278 Symbol_table* symtab,
14b31740
ILT
2279 Output_section **pdynstr,
2280 unsigned int* plocal_dynamic_count,
2281 std::vector<Symbol*>* pdynamic_symbols,
2282 Versions* pversions)
dbe717ef 2283{
a3ad94ed
ILT
2284 // Count all the symbols in the dynamic symbol table, and set the
2285 // dynamic symbol indexes.
dbe717ef 2286
a3ad94ed
ILT
2287 // Skip symbol 0, which is always all zeroes.
2288 unsigned int index = 1;
dbe717ef 2289
a3ad94ed
ILT
2290 // Add STT_SECTION symbols for each Output section which needs one.
2291 for (Section_list::iterator p = this->section_list_.begin();
2292 p != this->section_list_.end();
2293 ++p)
2294 {
2295 if (!(*p)->needs_dynsym_index())
2296 (*p)->set_dynsym_index(-1U);
2297 else
2298 {
2299 (*p)->set_dynsym_index(index);
2300 ++index;
2301 }
2302 }
2303
7bf1f802
ILT
2304 // Count the local symbols that need to go in the dynamic symbol table,
2305 // and set the dynamic symbol indexes.
2306 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2307 p != input_objects->relobj_end();
2308 ++p)
2309 {
2310 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
2311 index = new_index;
2312 }
a3ad94ed
ILT
2313
2314 unsigned int local_symcount = index;
14b31740 2315 *plocal_dynamic_count = local_symcount;
a3ad94ed 2316
9b07f471 2317 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
35cdfc9a 2318 &this->dynpool_, pversions);
a3ad94ed
ILT
2319
2320 int symsize;
2321 unsigned int align;
8851ecca 2322 const int size = parameters->target().get_size();
a3ad94ed
ILT
2323 if (size == 32)
2324 {
2325 symsize = elfcpp::Elf_sizes<32>::sym_size;
2326 align = 4;
2327 }
2328 else if (size == 64)
2329 {
2330 symsize = elfcpp::Elf_sizes<64>::sym_size;
2331 align = 8;
2332 }
2333 else
2334 gold_unreachable();
2335
14b31740
ILT
2336 // Create the dynamic symbol table section.
2337
3802b2dd
ILT
2338 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
2339 elfcpp::SHT_DYNSYM,
2340 elfcpp::SHF_ALLOC,
2341 false);
a3ad94ed 2342
27bc2bce 2343 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
7d9e3d98
ILT
2344 align,
2345 "** dynsym");
a3ad94ed
ILT
2346 dynsym->add_output_section_data(odata);
2347
2348 dynsym->set_info(local_symcount);
2349 dynsym->set_entsize(symsize);
2350 dynsym->set_addralign(align);
2351
2352 this->dynsym_section_ = dynsym;
2353
16649710 2354 Output_data_dynamic* const odyn = this->dynamic_data_;
a3ad94ed
ILT
2355 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
2356 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
2357
d491d34e
ILT
2358 // If there are more than SHN_LORESERVE allocated sections, we
2359 // create a .dynsym_shndx section. It is possible that we don't
2360 // need one, because it is possible that there are no dynamic
2361 // symbols in any of the sections with indexes larger than
2362 // SHN_LORESERVE. This is probably unusual, though, and at this
2363 // time we don't know the actual section indexes so it is
2364 // inconvenient to check.
2365 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
2366 {
2367 Output_section* dynsym_xindex =
2368 this->choose_output_section(NULL, ".dynsym_shndx",
2369 elfcpp::SHT_SYMTAB_SHNDX,
2370 elfcpp::SHF_ALLOC,
2371 false);
2372
2373 this->dynsym_xindex_ = new Output_symtab_xindex(index);
2374
2375 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
2376
2377 dynsym_xindex->set_link_section(dynsym);
2378 dynsym_xindex->set_addralign(4);
2379 dynsym_xindex->set_entsize(4);
2380
2381 dynsym_xindex->set_after_input_sections();
2382
2383 // This tells the driver code to wait until the symbol table has
2384 // written out before writing out the postprocessing sections,
2385 // including the .dynsym_shndx section.
2386 this->any_postprocessing_sections_ = true;
2387 }
2388
14b31740
ILT
2389 // Create the dynamic string table section.
2390
3802b2dd
ILT
2391 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
2392 elfcpp::SHT_STRTAB,
2393 elfcpp::SHF_ALLOC,
2394 false);
a3ad94ed
ILT
2395
2396 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
2397 dynstr->add_output_section_data(strdata);
2398
16649710
ILT
2399 dynsym->set_link_section(dynstr);
2400 this->dynamic_section_->set_link_section(dynstr);
2401
a3ad94ed
ILT
2402 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
2403 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
2404
14b31740
ILT
2405 *pdynstr = dynstr;
2406
2407 // Create the hash tables.
2408
13670ee6
ILT
2409 if (strcmp(parameters->options().hash_style(), "sysv") == 0
2410 || strcmp(parameters->options().hash_style(), "both") == 0)
2411 {
2412 unsigned char* phash;
2413 unsigned int hashlen;
2414 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
2415 &phash, &hashlen);
2416
2417 Output_section* hashsec = this->choose_output_section(NULL, ".hash",
2418 elfcpp::SHT_HASH,
2419 elfcpp::SHF_ALLOC,
2420 false);
2421
2422 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2423 hashlen,
7d9e3d98
ILT
2424 align,
2425 "** hash");
13670ee6
ILT
2426 hashsec->add_output_section_data(hashdata);
2427
2428 hashsec->set_link_section(dynsym);
2429 hashsec->set_entsize(4);
a3ad94ed 2430
13670ee6
ILT
2431 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
2432 }
2433
2434 if (strcmp(parameters->options().hash_style(), "gnu") == 0
2435 || strcmp(parameters->options().hash_style(), "both") == 0)
2436 {
2437 unsigned char* phash;
2438 unsigned int hashlen;
2439 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
2440 &phash, &hashlen);
a3ad94ed 2441
13670ee6
ILT
2442 Output_section* hashsec = this->choose_output_section(NULL, ".gnu.hash",
2443 elfcpp::SHT_GNU_HASH,
2444 elfcpp::SHF_ALLOC,
2445 false);
a3ad94ed 2446
13670ee6
ILT
2447 Output_section_data* hashdata = new Output_data_const_buffer(phash,
2448 hashlen,
7d9e3d98
ILT
2449 align,
2450 "** hash");
13670ee6 2451 hashsec->add_output_section_data(hashdata);
a3ad94ed 2452
13670ee6
ILT
2453 hashsec->set_link_section(dynsym);
2454 hashsec->set_entsize(4);
a3ad94ed 2455
13670ee6
ILT
2456 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
2457 }
dbe717ef
ILT
2458}
2459
7bf1f802
ILT
2460// Assign offsets to each local portion of the dynamic symbol table.
2461
2462void
2463Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
2464{
2465 Output_section* dynsym = this->dynsym_section_;
2466 gold_assert(dynsym != NULL);
2467
2468 off_t off = dynsym->offset();
2469
2470 // Skip the dummy symbol at the start of the section.
2471 off += dynsym->entsize();
2472
2473 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2474 p != input_objects->relobj_end();
2475 ++p)
2476 {
2477 unsigned int count = (*p)->set_local_dynsym_offset(off);
2478 off += count * dynsym->entsize();
2479 }
2480}
2481
14b31740
ILT
2482// Create the version sections.
2483
2484void
9025d29d 2485Layout::create_version_sections(const Versions* versions,
46fe1623 2486 const Symbol_table* symtab,
14b31740
ILT
2487 unsigned int local_symcount,
2488 const std::vector<Symbol*>& dynamic_symbols,
2489 const Output_section* dynstr)
2490{
2491 if (!versions->any_defs() && !versions->any_needs())
2492 return;
2493
8851ecca 2494 switch (parameters->size_and_endianness())
14b31740 2495 {
193a53d9 2496#ifdef HAVE_TARGET_32_LITTLE
8851ecca 2497 case Parameters::TARGET_32_LITTLE:
7d1a9ebb
ILT
2498 this->sized_create_version_sections<32, false>(versions, symtab,
2499 local_symcount,
2500 dynamic_symbols, dynstr);
8851ecca 2501 break;
193a53d9 2502#endif
8851ecca
ILT
2503#ifdef HAVE_TARGET_32_BIG
2504 case Parameters::TARGET_32_BIG:
7d1a9ebb
ILT
2505 this->sized_create_version_sections<32, true>(versions, symtab,
2506 local_symcount,
2507 dynamic_symbols, dynstr);
8851ecca 2508 break;
193a53d9 2509#endif
193a53d9 2510#ifdef HAVE_TARGET_64_LITTLE
8851ecca 2511 case Parameters::TARGET_64_LITTLE:
7d1a9ebb
ILT
2512 this->sized_create_version_sections<64, false>(versions, symtab,
2513 local_symcount,
2514 dynamic_symbols, dynstr);
8851ecca 2515 break;
193a53d9 2516#endif
8851ecca
ILT
2517#ifdef HAVE_TARGET_64_BIG
2518 case Parameters::TARGET_64_BIG:
7d1a9ebb
ILT
2519 this->sized_create_version_sections<64, true>(versions, symtab,
2520 local_symcount,
2521 dynamic_symbols, dynstr);
8851ecca
ILT
2522 break;
2523#endif
2524 default:
2525 gold_unreachable();
14b31740 2526 }
14b31740
ILT
2527}
2528
2529// Create the version sections, sized version.
2530
2531template<int size, bool big_endian>
2532void
2533Layout::sized_create_version_sections(
2534 const Versions* versions,
46fe1623 2535 const Symbol_table* symtab,
14b31740
ILT
2536 unsigned int local_symcount,
2537 const std::vector<Symbol*>& dynamic_symbols,
7d1a9ebb 2538 const Output_section* dynstr)
14b31740 2539{
3802b2dd
ILT
2540 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
2541 elfcpp::SHT_GNU_versym,
2542 elfcpp::SHF_ALLOC,
2543 false);
14b31740
ILT
2544
2545 unsigned char* vbuf;
2546 unsigned int vsize;
7d1a9ebb
ILT
2547 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
2548 local_symcount,
2549 dynamic_symbols,
2550 &vbuf, &vsize);
14b31740 2551
7d9e3d98
ILT
2552 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
2553 "** versions");
14b31740
ILT
2554
2555 vsec->add_output_section_data(vdata);
2556 vsec->set_entsize(2);
2557 vsec->set_link_section(this->dynsym_section_);
2558
2559 Output_data_dynamic* const odyn = this->dynamic_data_;
2560 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
2561
2562 if (versions->any_defs())
2563 {
3802b2dd
ILT
2564 Output_section* vdsec;
2565 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
2566 elfcpp::SHT_GNU_verdef,
2567 elfcpp::SHF_ALLOC,
2568 false);
14b31740
ILT
2569
2570 unsigned char* vdbuf;
2571 unsigned int vdsize;
2572 unsigned int vdentries;
7d1a9ebb
ILT
2573 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
2574 &vdsize, &vdentries);
14b31740 2575
7d9e3d98
ILT
2576 Output_section_data* vddata =
2577 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
14b31740
ILT
2578
2579 vdsec->add_output_section_data(vddata);
2580 vdsec->set_link_section(dynstr);
2581 vdsec->set_info(vdentries);
2582
2583 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
2584 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
2585 }
2586
2587 if (versions->any_needs())
2588 {
14b31740 2589 Output_section* vnsec;
3802b2dd
ILT
2590 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
2591 elfcpp::SHT_GNU_verneed,
2592 elfcpp::SHF_ALLOC,
2593 false);
14b31740
ILT
2594
2595 unsigned char* vnbuf;
2596 unsigned int vnsize;
2597 unsigned int vnentries;
7d1a9ebb
ILT
2598 versions->need_section_contents<size, big_endian>(&this->dynpool_,
2599 &vnbuf, &vnsize,
2600 &vnentries);
14b31740 2601
7d9e3d98
ILT
2602 Output_section_data* vndata =
2603 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
14b31740
ILT
2604
2605 vnsec->add_output_section_data(vndata);
2606 vnsec->set_link_section(dynstr);
2607 vnsec->set_info(vnentries);
2608
2609 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
2610 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
2611 }
2612}
2613
dbe717ef
ILT
2614// Create the .interp section and PT_INTERP segment.
2615
2616void
2617Layout::create_interp(const Target* target)
2618{
2619 const char* interp = this->options_.dynamic_linker();
2620 if (interp == NULL)
2621 {
2622 interp = target->dynamic_linker();
a3ad94ed 2623 gold_assert(interp != NULL);
dbe717ef
ILT
2624 }
2625
2626 size_t len = strlen(interp) + 1;
2627
2628 Output_section_data* odata = new Output_data_const(interp, len, 1);
2629
3802b2dd
ILT
2630 Output_section* osec = this->choose_output_section(NULL, ".interp",
2631 elfcpp::SHT_PROGBITS,
2632 elfcpp::SHF_ALLOC,
2633 false);
dbe717ef
ILT
2634 osec->add_output_section_data(odata);
2635
1c4f3631
ILT
2636 if (!this->script_options_->saw_phdrs_clause())
2637 {
2638 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
2639 elfcpp::PF_R);
01676dcd 2640 oseg->add_output_section(osec, elfcpp::PF_R);
1c4f3631 2641 }
dbe717ef
ILT
2642}
2643
a3ad94ed
ILT
2644// Finish the .dynamic section and PT_DYNAMIC segment.
2645
2646void
2647Layout::finish_dynamic_section(const Input_objects* input_objects,
16649710 2648 const Symbol_table* symtab)
a3ad94ed 2649{
1c4f3631
ILT
2650 if (!this->script_options_->saw_phdrs_clause())
2651 {
2652 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
2653 (elfcpp::PF_R
2654 | elfcpp::PF_W));
01676dcd
ILT
2655 oseg->add_output_section(this->dynamic_section_,
2656 elfcpp::PF_R | elfcpp::PF_W);
1c4f3631 2657 }
a3ad94ed 2658
16649710
ILT
2659 Output_data_dynamic* const odyn = this->dynamic_data_;
2660
a3ad94ed
ILT
2661 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
2662 p != input_objects->dynobj_end();
2663 ++p)
2664 {
2665 // FIXME: Handle --as-needed.
2666 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
2667 }
2668
8851ecca 2669 if (parameters->options().shared())
fced7afd
ILT
2670 {
2671 const char* soname = this->options_.soname();
2672 if (soname != NULL)
2673 odyn->add_string(elfcpp::DT_SONAME, soname);
2674 }
2675
a3ad94ed
ILT
2676 // FIXME: Support --init and --fini.
2677 Symbol* sym = symtab->lookup("_init");
14b31740 2678 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
2679 odyn->add_symbol(elfcpp::DT_INIT, sym);
2680
2681 sym = symtab->lookup("_fini");
14b31740 2682 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
a3ad94ed
ILT
2683 odyn->add_symbol(elfcpp::DT_FINI, sym);
2684
2685 // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
41f542e7
ILT
2686
2687 // Add a DT_RPATH entry if needed.
2688 const General_options::Dir_list& rpath(this->options_.rpath());
2689 if (!rpath.empty())
2690 {
2691 std::string rpath_val;
2692 for (General_options::Dir_list::const_iterator p = rpath.begin();
2693 p != rpath.end();
2694 ++p)
2695 {
2696 if (rpath_val.empty())
ad2d6943 2697 rpath_val = p->name();
41f542e7
ILT
2698 else
2699 {
2700 // Eliminate duplicates.
2701 General_options::Dir_list::const_iterator q;
2702 for (q = rpath.begin(); q != p; ++q)
ad2d6943 2703 if (q->name() == p->name())
41f542e7
ILT
2704 break;
2705 if (q == p)
2706 {
2707 rpath_val += ':';
ad2d6943 2708 rpath_val += p->name();
41f542e7
ILT
2709 }
2710 }
2711 }
2712
2713 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
7c414435
DM
2714 if (parameters->options().enable_new_dtags())
2715 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
41f542e7 2716 }
4f4c5f80
ILT
2717
2718 // Look for text segments that have dynamic relocations.
2719 bool have_textrel = false;
4e8fe71f 2720 if (!this->script_options_->saw_sections_clause())
4f4c5f80 2721 {
4e8fe71f
ILT
2722 for (Segment_list::const_iterator p = this->segment_list_.begin();
2723 p != this->segment_list_.end();
2724 ++p)
2725 {
2726 if (((*p)->flags() & elfcpp::PF_W) == 0
2727 && (*p)->dynamic_reloc_count() > 0)
2728 {
2729 have_textrel = true;
2730 break;
2731 }
2732 }
2733 }
2734 else
2735 {
2736 // We don't know the section -> segment mapping, so we are
2737 // conservative and just look for readonly sections with
2738 // relocations. If those sections wind up in writable segments,
2739 // then we have created an unnecessary DT_TEXTREL entry.
2740 for (Section_list::const_iterator p = this->section_list_.begin();
2741 p != this->section_list_.end();
2742 ++p)
2743 {
2744 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
2745 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
2746 && ((*p)->dynamic_reloc_count() > 0))
2747 {
2748 have_textrel = true;
2749 break;
2750 }
2751 }
4f4c5f80
ILT
2752 }
2753
2754 // Add a DT_FLAGS entry. We add it even if no flags are set so that
2755 // post-link tools can easily modify these flags if desired.
2756 unsigned int flags = 0;
2757 if (have_textrel)
6a41d30b
ILT
2758 {
2759 // Add a DT_TEXTREL for compatibility with older loaders.
2760 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
2761 flags |= elfcpp::DF_TEXTREL;
2762 }
8851ecca 2763 if (parameters->options().shared() && this->has_static_tls())
535890bb 2764 flags |= elfcpp::DF_STATIC_TLS;
7be8330a
CD
2765 if (parameters->options().origin())
2766 flags |= elfcpp::DF_ORIGIN;
4f4c5f80 2767 odyn->add_constant(elfcpp::DT_FLAGS, flags);
7c414435
DM
2768
2769 flags = 0;
2770 if (parameters->options().initfirst())
2771 flags |= elfcpp::DF_1_INITFIRST;
2772 if (parameters->options().interpose())
2773 flags |= elfcpp::DF_1_INTERPOSE;
2774 if (parameters->options().loadfltr())
2775 flags |= elfcpp::DF_1_LOADFLTR;
2776 if (parameters->options().nodefaultlib())
2777 flags |= elfcpp::DF_1_NODEFLIB;
2778 if (parameters->options().nodelete())
2779 flags |= elfcpp::DF_1_NODELETE;
2780 if (parameters->options().nodlopen())
2781 flags |= elfcpp::DF_1_NOOPEN;
2782 if (parameters->options().nodump())
2783 flags |= elfcpp::DF_1_NODUMP;
2784 if (!parameters->options().shared())
2785 flags &= ~(elfcpp::DF_1_INITFIRST
2786 | elfcpp::DF_1_NODELETE
2787 | elfcpp::DF_1_NOOPEN);
7be8330a
CD
2788 if (parameters->options().origin())
2789 flags |= elfcpp::DF_1_ORIGIN;
7c414435
DM
2790 if (flags)
2791 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
a3ad94ed
ILT
2792}
2793
a2fb1b05
ILT
2794// The mapping of .gnu.linkonce section names to real section names.
2795
ead1e424 2796#define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
a2fb1b05
ILT
2797const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
2798{
9f1d377b
ILT
2799 MAPPING_INIT("d.rel.ro.local", ".data.rel.ro.local"), // Before "d.rel.ro".
2800 MAPPING_INIT("d.rel.ro", ".data.rel.ro"), // Before "d".
a2fb1b05
ILT
2801 MAPPING_INIT("t", ".text"),
2802 MAPPING_INIT("r", ".rodata"),
2803 MAPPING_INIT("d", ".data"),
2804 MAPPING_INIT("b", ".bss"),
2805 MAPPING_INIT("s", ".sdata"),
2806 MAPPING_INIT("sb", ".sbss"),
2807 MAPPING_INIT("s2", ".sdata2"),
2808 MAPPING_INIT("sb2", ".sbss2"),
2809 MAPPING_INIT("wi", ".debug_info"),
2810 MAPPING_INIT("td", ".tdata"),
2811 MAPPING_INIT("tb", ".tbss"),
2812 MAPPING_INIT("lr", ".lrodata"),
2813 MAPPING_INIT("l", ".ldata"),
2814 MAPPING_INIT("lb", ".lbss"),
2815};
2816#undef MAPPING_INIT
2817
2818const int Layout::linkonce_mapping_count =
2819 sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
2820
2821// Return the name of the output section to use for a .gnu.linkonce
2822// section. This is based on the default ELF linker script of the old
2823// GNU linker. For example, we map a name like ".gnu.linkonce.t.foo"
ead1e424
ILT
2824// to ".text". Set *PLEN to the length of the name. *PLEN is
2825// initialized to the length of NAME.
a2fb1b05
ILT
2826
2827const char*
ead1e424 2828Layout::linkonce_output_name(const char* name, size_t *plen)
a2fb1b05
ILT
2829{
2830 const char* s = name + sizeof(".gnu.linkonce") - 1;
2831 if (*s != '.')
2832 return name;
2833 ++s;
2834 const Linkonce_mapping* plm = linkonce_mapping;
2835 for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
2836 {
2837 if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
ead1e424
ILT
2838 {
2839 *plen = plm->tolen;
2840 return plm->to;
2841 }
a2fb1b05
ILT
2842 }
2843 return name;
2844}
2845
ead1e424
ILT
2846// Choose the output section name to use given an input section name.
2847// Set *PLEN to the length of the name. *PLEN is initialized to the
2848// length of NAME.
2849
2850const char*
2851Layout::output_section_name(const char* name, size_t* plen)
2852{
2853 if (Layout::is_linkonce(name))
2854 {
2855 // .gnu.linkonce sections are laid out as though they were named
2856 // for the sections are placed into.
2857 return Layout::linkonce_output_name(name, plen);
2858 }
2859
af4a8a83
ILT
2860 // gcc 4.3 generates the following sorts of section names when it
2861 // needs a section name specific to a function:
2862 // .text.FN
2863 // .rodata.FN
2864 // .sdata2.FN
2865 // .data.FN
2866 // .data.rel.FN
2867 // .data.rel.local.FN
2868 // .data.rel.ro.FN
2869 // .data.rel.ro.local.FN
2870 // .sdata.FN
2871 // .bss.FN
2872 // .sbss.FN
2873 // .tdata.FN
2874 // .tbss.FN
2875
2876 // The GNU linker maps all of those to the part before the .FN,
2877 // except that .data.rel.local.FN is mapped to .data, and
2878 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
2879 // beginning with .data.rel.ro.local are grouped together.
2880
2881 // For an anonymous namespace, the string FN can contain a '.'.
2882
2883 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
2884 // GNU linker maps to .rodata.
2885
2886 // The .data.rel.ro sections enable a security feature triggered by
2887 // the -z relro option. Section which need to be relocated at
2888 // program startup time but which may be readonly after startup are
2889 // grouped into .data.rel.ro. They are then put into a PT_GNU_RELRO
2890 // segment. The dynamic linker will make that segment writable,
2891 // perform relocations, and then make it read-only. FIXME: We do
2892 // not yet implement this optimization.
2893
2894 // It is hard to handle this in a principled way.
2895
2896 // These are the rules we follow:
2897
2898 // If the section name has no initial '.', or no dot other than an
2899 // initial '.', we use the name unchanged (i.e., "mysection" and
2900 // ".text" are unchanged).
2901
41105937
PP
2902 // If the name starts with '.note', we keep it unchanged (e.g. to
2903 // avoid truncating '.note.ABI-tag' to '.note').
2904
9f1d377b
ILT
2905 // If the name starts with ".data.rel.ro.local" we use
2906 // ".data.rel.ro.local".
2907
af4a8a83
ILT
2908 // If the name starts with ".data.rel.ro" we use ".data.rel.ro".
2909
2910 // Otherwise, we drop the second '.' and everything that comes after
2911 // it (i.e., ".text.XXX" becomes ".text").
ead1e424
ILT
2912
2913 const char* s = name;
af4a8a83
ILT
2914 if (*s != '.')
2915 return name;
2916 ++s;
ead1e424
ILT
2917 const char* sdot = strchr(s, '.');
2918 if (sdot == NULL)
2919 return name;
41105937
PP
2920 if (strncmp(name, ".note.", 6) == 0)
2921 return name;
ead1e424 2922
9f1d377b
ILT
2923 const char* const data_rel_ro_local = ".data.rel.ro.local";
2924 if (strncmp(name, data_rel_ro_local, strlen(data_rel_ro_local)) == 0)
2925 {
2926 *plen = strlen(data_rel_ro_local);
2927 return data_rel_ro_local;
2928 }
2929
af4a8a83
ILT
2930 const char* const data_rel_ro = ".data.rel.ro";
2931 if (strncmp(name, data_rel_ro, strlen(data_rel_ro)) == 0)
ead1e424 2932 {
af4a8a83
ILT
2933 *plen = strlen(data_rel_ro);
2934 return data_rel_ro;
ead1e424
ILT
2935 }
2936
ead1e424
ILT
2937 *plen = sdot - name;
2938 return name;
2939}
2940
8a4c0b0d
ILT
2941// Check if a comdat group or .gnu.linkonce section with the given
2942// NAME is selected for the link. If there is already a section,
2943// *KEPT_SECTION is set to point to the signature and the function
2944// returns false. Otherwise, the CANDIDATE signature is recorded for
2945// this NAME in the layout object, *KEPT_SECTION is set to the
2946// internal copy and the function return false. In some cases, with
2947// CANDIDATE->GROUP_ being false, KEPT_SECTION can point back to
2948// CANDIDATE.
a2fb1b05
ILT
2949
2950bool
8a4c0b0d
ILT
2951Layout::find_or_add_kept_section(const std::string name,
2952 Kept_section* candidate,
2953 Kept_section** kept_section)
a2fb1b05 2954{
a2fb1b05 2955 std::pair<Signatures::iterator, bool> ins(
8a4c0b0d 2956 this->signatures_.insert(std::make_pair(name, *candidate)));
a2fb1b05 2957
8a4c0b0d
ILT
2958 if (kept_section)
2959 *kept_section = &ins.first->second;
a2fb1b05
ILT
2960 if (ins.second)
2961 {
2962 // This is the first time we've seen this signature.
2963 return true;
2964 }
2965
8a4c0b0d 2966 if (ins.first->second.is_group)
a2fb1b05
ILT
2967 {
2968 // We've already seen a real section group with this signature.
2756a258
CC
2969 // If the kept group is from a plugin object, and we're in
2970 // the replacement phase, accept the new one as a replacement.
8a4c0b0d 2971 if (ins.first->second.object == NULL
2756a258
CC
2972 && parameters->options().plugins()->in_replacement_phase())
2973 {
8a4c0b0d 2974 ins.first->second = *candidate;
2756a258
CC
2975 return true;
2976 }
a2fb1b05
ILT
2977 return false;
2978 }
8a4c0b0d 2979 else if (candidate->is_group)
a2fb1b05
ILT
2980 {
2981 // This is a real section group, and we've already seen a
a0fa0c07 2982 // linkonce section with this signature. Record that we've seen
a2fb1b05 2983 // a section group, and don't include this section group.
8a4c0b0d 2984 ins.first->second.is_group = true;
a2fb1b05
ILT
2985 return false;
2986 }
2987 else
2988 {
2989 // We've already seen a linkonce section and this is a linkonce
2990 // section. These don't block each other--this may be the same
2991 // symbol name with different section types.
8a4c0b0d 2992 *kept_section = candidate;
a2fb1b05
ILT
2993 return true;
2994 }
2995}
2996
e94cf127
CC
2997// Find the given comdat signature, and return the object and section
2998// index of the kept group.
2999Relobj*
3000Layout::find_kept_object(const std::string& signature,
3001 unsigned int* pshndx) const
3002{
3003 Signatures::const_iterator p = this->signatures_.find(signature);
3004 if (p == this->signatures_.end())
3005 return NULL;
3006 if (pshndx != NULL)
8a4c0b0d
ILT
3007 *pshndx = p->second.shndx;
3008 return p->second.object;
e94cf127
CC
3009}
3010
a445fddf
ILT
3011// Store the allocated sections into the section list.
3012
3013void
3014Layout::get_allocated_sections(Section_list* section_list) const
3015{
3016 for (Section_list::const_iterator p = this->section_list_.begin();
3017 p != this->section_list_.end();
3018 ++p)
3019 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
3020 section_list->push_back(*p);
3021}
3022
3023// Create an output segment.
3024
3025Output_segment*
3026Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
3027{
8851ecca 3028 gold_assert(!parameters->options().relocatable());
a445fddf
ILT
3029 Output_segment* oseg = new Output_segment(type, flags);
3030 this->segment_list_.push_back(oseg);
2d924fd9
ILT
3031
3032 if (type == elfcpp::PT_TLS)
3033 this->tls_segment_ = oseg;
3034 else if (type == elfcpp::PT_GNU_RELRO)
3035 this->relro_segment_ = oseg;
3036
a445fddf
ILT
3037 return oseg;
3038}
3039
730cdc88
ILT
3040// Write out the Output_sections. Most won't have anything to write,
3041// since most of the data will come from input sections which are
3042// handled elsewhere. But some Output_sections do have Output_data.
3043
3044void
3045Layout::write_output_sections(Output_file* of) const
3046{
3047 for (Section_list::const_iterator p = this->section_list_.begin();
3048 p != this->section_list_.end();
3049 ++p)
3050 {
3051 if (!(*p)->after_input_sections())
3052 (*p)->write(of);
3053 }
3054}
3055
61ba1cf9
ILT
3056// Write out data not associated with a section or the symbol table.
3057
3058void
9025d29d 3059Layout::write_data(const Symbol_table* symtab, Output_file* of) const
61ba1cf9 3060{
8851ecca 3061 if (!parameters->options().strip_all())
a3ad94ed 3062 {
9e2dcb77
ILT
3063 const Output_section* symtab_section = this->symtab_section_;
3064 for (Section_list::const_iterator p = this->section_list_.begin();
3065 p != this->section_list_.end();
3066 ++p)
a3ad94ed 3067 {
9e2dcb77
ILT
3068 if ((*p)->needs_symtab_index())
3069 {
3070 gold_assert(symtab_section != NULL);
3071 unsigned int index = (*p)->symtab_index();
3072 gold_assert(index > 0 && index != -1U);
3073 off_t off = (symtab_section->offset()
3074 + index * symtab_section->entsize());
d491d34e 3075 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
9e2dcb77 3076 }
a3ad94ed
ILT
3077 }
3078 }
3079
3080 const Output_section* dynsym_section = this->dynsym_section_;
3081 for (Section_list::const_iterator p = this->section_list_.begin();
3082 p != this->section_list_.end();
3083 ++p)
3084 {
3085 if ((*p)->needs_dynsym_index())
3086 {
3087 gold_assert(dynsym_section != NULL);
3088 unsigned int index = (*p)->dynsym_index();
3089 gold_assert(index > 0 && index != -1U);
3090 off_t off = (dynsym_section->offset()
3091 + index * dynsym_section->entsize());
d491d34e 3092 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
a3ad94ed
ILT
3093 }
3094 }
3095
a3ad94ed 3096 // Write out the Output_data which are not in an Output_section.
61ba1cf9
ILT
3097 for (Data_list::const_iterator p = this->special_output_list_.begin();
3098 p != this->special_output_list_.end();
3099 ++p)
3100 (*p)->write(of);
3101}
3102
730cdc88
ILT
3103// Write out the Output_sections which can only be written after the
3104// input sections are complete.
3105
3106void
27bc2bce 3107Layout::write_sections_after_input_sections(Output_file* of)
730cdc88 3108{
27bc2bce 3109 // Determine the final section offsets, and thus the final output
9a0910c3
ILT
3110 // file size. Note we finalize the .shstrab last, to allow the
3111 // after_input_section sections to modify their section-names before
3112 // writing.
17a1d0a9 3113 if (this->any_postprocessing_sections_)
27bc2bce 3114 {
17a1d0a9
ILT
3115 off_t off = this->output_file_size_;
3116 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
8a4c0b0d 3117
17a1d0a9
ILT
3118 // Now that we've finalized the names, we can finalize the shstrab.
3119 off =
3120 this->set_section_offsets(off,
3121 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
3122
3123 if (off > this->output_file_size_)
3124 {
3125 of->resize(off);
3126 this->output_file_size_ = off;
3127 }
27bc2bce
ILT
3128 }
3129
730cdc88
ILT
3130 for (Section_list::const_iterator p = this->section_list_.begin();
3131 p != this->section_list_.end();
3132 ++p)
3133 {
3134 if ((*p)->after_input_sections())
3135 (*p)->write(of);
3136 }
27bc2bce 3137
27bc2bce 3138 this->section_headers_->write(of);
730cdc88
ILT
3139}
3140
8ed814a9
ILT
3141// If the build ID requires computing a checksum, do so here, and
3142// write it out. We compute a checksum over the entire file because
3143// that is simplest.
3144
3145void
3146Layout::write_build_id(Output_file* of) const
3147{
3148 if (this->build_id_note_ == NULL)
3149 return;
3150
3151 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
3152
3153 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
3154 this->build_id_note_->data_size());
3155
3156 const char* style = parameters->options().build_id();
3157 if (strcmp(style, "sha1") == 0)
3158 {
3159 sha1_ctx ctx;
3160 sha1_init_ctx(&ctx);
3161 sha1_process_bytes(iv, this->output_file_size_, &ctx);
3162 sha1_finish_ctx(&ctx, ov);
3163 }
3164 else if (strcmp(style, "md5") == 0)
3165 {
3166 md5_ctx ctx;
3167 md5_init_ctx(&ctx);
3168 md5_process_bytes(iv, this->output_file_size_, &ctx);
3169 md5_finish_ctx(&ctx, ov);
3170 }
3171 else
3172 gold_unreachable();
3173
3174 of->write_output_view(this->build_id_note_->offset(),
3175 this->build_id_note_->data_size(),
3176 ov);
3177
3178 of->free_input_view(0, this->output_file_size_, iv);
3179}
3180
516cb3d0
ILT
3181// Write out a binary file. This is called after the link is
3182// complete. IN is the temporary output file we used to generate the
3183// ELF code. We simply walk through the segments, read them from
3184// their file offset in IN, and write them to their load address in
3185// the output file. FIXME: with a bit more work, we could support
3186// S-records and/or Intel hex format here.
3187
3188void
3189Layout::write_binary(Output_file* in) const
3190{
7cc619c3 3191 gold_assert(this->options_.oformat_enum()
bc644c6c 3192 == General_options::OBJECT_FORMAT_BINARY);
516cb3d0
ILT
3193
3194 // Get the size of the binary file.
3195 uint64_t max_load_address = 0;
3196 for (Segment_list::const_iterator p = this->segment_list_.begin();
3197 p != this->segment_list_.end();
3198 ++p)
3199 {
3200 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3201 {
3202 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
3203 if (max_paddr > max_load_address)
3204 max_load_address = max_paddr;
3205 }
3206 }
3207
8851ecca 3208 Output_file out(parameters->options().output_file_name());
516cb3d0
ILT
3209 out.open(max_load_address);
3210
3211 for (Segment_list::const_iterator p = this->segment_list_.begin();
3212 p != this->segment_list_.end();
3213 ++p)
3214 {
3215 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
3216 {
3217 const unsigned char* vin = in->get_input_view((*p)->offset(),
3218 (*p)->filesz());
3219 unsigned char* vout = out.get_output_view((*p)->paddr(),
3220 (*p)->filesz());
3221 memcpy(vout, vin, (*p)->filesz());
3222 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
3223 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
3224 }
3225 }
3226
3227 out.close();
3228}
3229
7d9e3d98
ILT
3230// Print the output sections to the map file.
3231
3232void
3233Layout::print_to_mapfile(Mapfile* mapfile) const
3234{
3235 for (Segment_list::const_iterator p = this->segment_list_.begin();
3236 p != this->segment_list_.end();
3237 ++p)
3238 (*p)->print_sections_to_mapfile(mapfile);
3239}
3240
ad8f37d1
ILT
3241// Print statistical information to stderr. This is used for --stats.
3242
3243void
3244Layout::print_stats() const
3245{
3246 this->namepool_.print_stats("section name pool");
3247 this->sympool_.print_stats("output symbol name pool");
3248 this->dynpool_.print_stats("dynamic name pool");
38c5e8b4
ILT
3249
3250 for (Section_list::const_iterator p = this->section_list_.begin();
3251 p != this->section_list_.end();
3252 ++p)
3253 (*p)->print_merge_stats();
ad8f37d1
ILT
3254}
3255
730cdc88
ILT
3256// Write_sections_task methods.
3257
3258// We can always run this task.
3259
17a1d0a9
ILT
3260Task_token*
3261Write_sections_task::is_runnable()
730cdc88 3262{
17a1d0a9 3263 return NULL;
730cdc88
ILT
3264}
3265
3266// We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
3267// when finished.
3268
17a1d0a9
ILT
3269void
3270Write_sections_task::locks(Task_locker* tl)
730cdc88 3271{
17a1d0a9
ILT
3272 tl->add(this, this->output_sections_blocker_);
3273 tl->add(this, this->final_blocker_);
730cdc88
ILT
3274}
3275
3276// Run the task--write out the data.
3277
3278void
3279Write_sections_task::run(Workqueue*)
3280{
3281 this->layout_->write_output_sections(this->of_);
3282}
3283
61ba1cf9
ILT
3284// Write_data_task methods.
3285
3286// We can always run this task.
3287
17a1d0a9
ILT
3288Task_token*
3289Write_data_task::is_runnable()
61ba1cf9 3290{
17a1d0a9 3291 return NULL;
61ba1cf9
ILT
3292}
3293
3294// We need to unlock FINAL_BLOCKER when finished.
3295
17a1d0a9
ILT
3296void
3297Write_data_task::locks(Task_locker* tl)
61ba1cf9 3298{
17a1d0a9 3299 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
3300}
3301
3302// Run the task--write out the data.
3303
3304void
3305Write_data_task::run(Workqueue*)
3306{
9025d29d 3307 this->layout_->write_data(this->symtab_, this->of_);
61ba1cf9
ILT
3308}
3309
3310// Write_symbols_task methods.
3311
3312// We can always run this task.
3313
17a1d0a9
ILT
3314Task_token*
3315Write_symbols_task::is_runnable()
61ba1cf9 3316{
17a1d0a9 3317 return NULL;
61ba1cf9
ILT
3318}
3319
3320// We need to unlock FINAL_BLOCKER when finished.
3321
17a1d0a9
ILT
3322void
3323Write_symbols_task::locks(Task_locker* tl)
61ba1cf9 3324{
17a1d0a9 3325 tl->add(this, this->final_blocker_);
61ba1cf9
ILT
3326}
3327
3328// Run the task--write out the symbols.
3329
3330void
3331Write_symbols_task::run(Workqueue*)
3332{
fd9d194f
ILT
3333 this->symtab_->write_globals(this->sympool_, this->dynpool_,
3334 this->layout_->symtab_xindex(),
d491d34e 3335 this->layout_->dynsym_xindex(), this->of_);
61ba1cf9
ILT
3336}
3337
730cdc88
ILT
3338// Write_after_input_sections_task methods.
3339
3340// We can only run this task after the input sections have completed.
3341
17a1d0a9
ILT
3342Task_token*
3343Write_after_input_sections_task::is_runnable()
730cdc88
ILT
3344{
3345 if (this->input_sections_blocker_->is_blocked())
17a1d0a9
ILT
3346 return this->input_sections_blocker_;
3347 return NULL;
730cdc88
ILT
3348}
3349
3350// We need to unlock FINAL_BLOCKER when finished.
3351
17a1d0a9
ILT
3352void
3353Write_after_input_sections_task::locks(Task_locker* tl)
730cdc88 3354{
17a1d0a9 3355 tl->add(this, this->final_blocker_);
730cdc88
ILT
3356}
3357
3358// Run the task.
3359
3360void
3361Write_after_input_sections_task::run(Workqueue*)
3362{
3363 this->layout_->write_sections_after_input_sections(this->of_);
3364}
3365
92e059d8 3366// Close_task_runner methods.
61ba1cf9
ILT
3367
3368// Run the task--close the file.
3369
3370void
17a1d0a9 3371Close_task_runner::run(Workqueue*, const Task*)
61ba1cf9 3372{
8ed814a9
ILT
3373 // If we need to compute a checksum for the BUILD if, we do so here.
3374 this->layout_->write_build_id(this->of_);
3375
516cb3d0 3376 // If we've been asked to create a binary file, we do so here.
7cc619c3 3377 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
516cb3d0
ILT
3378 this->layout_->write_binary(this->of_);
3379
61ba1cf9
ILT
3380 this->of_->close();
3381}
3382
a2fb1b05
ILT
3383// Instantiate the templates we need. We could use the configure
3384// script to restrict this to only the ones for implemented targets.
3385
193a53d9 3386#ifdef HAVE_TARGET_32_LITTLE
a2fb1b05
ILT
3387template
3388Output_section*
730cdc88
ILT
3389Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
3390 const char* name,
3391 const elfcpp::Shdr<32, false>& shdr,
3392 unsigned int, unsigned int, off_t*);
193a53d9 3393#endif
a2fb1b05 3394
193a53d9 3395#ifdef HAVE_TARGET_32_BIG
a2fb1b05
ILT
3396template
3397Output_section*
730cdc88
ILT
3398Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
3399 const char* name,
3400 const elfcpp::Shdr<32, true>& shdr,
3401 unsigned int, unsigned int, off_t*);
193a53d9 3402#endif
a2fb1b05 3403
193a53d9 3404#ifdef HAVE_TARGET_64_LITTLE
a2fb1b05
ILT
3405template
3406Output_section*
730cdc88
ILT
3407Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
3408 const char* name,
3409 const elfcpp::Shdr<64, false>& shdr,
3410 unsigned int, unsigned int, off_t*);
193a53d9 3411#endif
a2fb1b05 3412
193a53d9 3413#ifdef HAVE_TARGET_64_BIG
a2fb1b05
ILT
3414template
3415Output_section*
730cdc88
ILT
3416Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
3417 const char* name,
3418 const elfcpp::Shdr<64, true>& shdr,
3419 unsigned int, unsigned int, off_t*);
193a53d9 3420#endif
a2fb1b05 3421
6a74a719
ILT
3422#ifdef HAVE_TARGET_32_LITTLE
3423template
3424Output_section*
3425Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
3426 unsigned int reloc_shndx,
3427 const elfcpp::Shdr<32, false>& shdr,
3428 Output_section* data_section,
3429 Relocatable_relocs* rr);
3430#endif
3431
3432#ifdef HAVE_TARGET_32_BIG
3433template
3434Output_section*
3435Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
3436 unsigned int reloc_shndx,
3437 const elfcpp::Shdr<32, true>& shdr,
3438 Output_section* data_section,
3439 Relocatable_relocs* rr);
3440#endif
3441
3442#ifdef HAVE_TARGET_64_LITTLE
3443template
3444Output_section*
3445Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
3446 unsigned int reloc_shndx,
3447 const elfcpp::Shdr<64, false>& shdr,
3448 Output_section* data_section,
3449 Relocatable_relocs* rr);
3450#endif
3451
3452#ifdef HAVE_TARGET_64_BIG
3453template
3454Output_section*
3455Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
3456 unsigned int reloc_shndx,
3457 const elfcpp::Shdr<64, true>& shdr,
3458 Output_section* data_section,
3459 Relocatable_relocs* rr);
3460#endif
3461
3462#ifdef HAVE_TARGET_32_LITTLE
3463template
3464void
3465Layout::layout_group<32, false>(Symbol_table* symtab,
3466 Sized_relobj<32, false>* object,
3467 unsigned int,
3468 const char* group_section_name,
3469 const char* signature,
3470 const elfcpp::Shdr<32, false>& shdr,
8825ac63
ILT
3471 elfcpp::Elf_Word flags,
3472 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3473#endif
3474
3475#ifdef HAVE_TARGET_32_BIG
3476template
3477void
3478Layout::layout_group<32, true>(Symbol_table* symtab,
3479 Sized_relobj<32, true>* object,
3480 unsigned int,
3481 const char* group_section_name,
3482 const char* signature,
3483 const elfcpp::Shdr<32, true>& shdr,
8825ac63
ILT
3484 elfcpp::Elf_Word flags,
3485 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3486#endif
3487
3488#ifdef HAVE_TARGET_64_LITTLE
3489template
3490void
3491Layout::layout_group<64, false>(Symbol_table* symtab,
3492 Sized_relobj<64, false>* object,
3493 unsigned int,
3494 const char* group_section_name,
3495 const char* signature,
3496 const elfcpp::Shdr<64, false>& shdr,
8825ac63
ILT
3497 elfcpp::Elf_Word flags,
3498 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3499#endif
3500
3501#ifdef HAVE_TARGET_64_BIG
3502template
3503void
3504Layout::layout_group<64, true>(Symbol_table* symtab,
3505 Sized_relobj<64, true>* object,
3506 unsigned int,
3507 const char* group_section_name,
3508 const char* signature,
3509 const elfcpp::Shdr<64, true>& shdr,
8825ac63
ILT
3510 elfcpp::Elf_Word flags,
3511 std::vector<unsigned int>* shndxes);
6a74a719
ILT
3512#endif
3513
730cdc88
ILT
3514#ifdef HAVE_TARGET_32_LITTLE
3515template
3516Output_section*
3517Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
3518 const unsigned char* symbols,
3519 off_t symbols_size,
3520 const unsigned char* symbol_names,
3521 off_t symbol_names_size,
3522 unsigned int shndx,
3523 const elfcpp::Shdr<32, false>& shdr,
3524 unsigned int reloc_shndx,
3525 unsigned int reloc_type,
3526 off_t* off);
3527#endif
3528
3529#ifdef HAVE_TARGET_32_BIG
3530template
3531Output_section*
3532Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
3533 const unsigned char* symbols,
3534 off_t symbols_size,
3535 const unsigned char* symbol_names,
3536 off_t symbol_names_size,
3537 unsigned int shndx,
3538 const elfcpp::Shdr<32, true>& shdr,
3539 unsigned int reloc_shndx,
3540 unsigned int reloc_type,
3541 off_t* off);
3542#endif
3543
3544#ifdef HAVE_TARGET_64_LITTLE
3545template
3546Output_section*
3547Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
3548 const unsigned char* symbols,
3549 off_t symbols_size,
3550 const unsigned char* symbol_names,
3551 off_t symbol_names_size,
3552 unsigned int shndx,
3553 const elfcpp::Shdr<64, false>& shdr,
3554 unsigned int reloc_shndx,
3555 unsigned int reloc_type,
3556 off_t* off);
3557#endif
3558
3559#ifdef HAVE_TARGET_64_BIG
3560template
3561Output_section*
3562Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
3563 const unsigned char* symbols,
3564 off_t symbols_size,
3565 const unsigned char* symbol_names,
3566 off_t symbol_names_size,
3567 unsigned int shndx,
3568 const elfcpp::Shdr<64, true>& shdr,
3569 unsigned int reloc_shndx,
3570 unsigned int reloc_type,
3571 off_t* off);
3572#endif
a2fb1b05
ILT
3573
3574} // End namespace gold.