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