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