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