* README: Remove claim that MEMORY is not supported.
[deliverable/binutils-gdb.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
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
23 #include "gold.h"
24
25 #include <cerrno>
26 #include <cstring>
27 #include <algorithm>
28 #include <iostream>
29 #include <fstream>
30 #include <utility>
31 #include <fcntl.h>
32 #include <fnmatch.h>
33 #include <unistd.h>
34 #include "libiberty.h"
35 #include "md5.h"
36 #include "sha1.h"
37
38 #include "parameters.h"
39 #include "options.h"
40 #include "mapfile.h"
41 #include "script.h"
42 #include "script-sections.h"
43 #include "output.h"
44 #include "symtab.h"
45 #include "dynobj.h"
46 #include "ehframe.h"
47 #include "compressed_output.h"
48 #include "reduced_debug_output.h"
49 #include "reloc.h"
50 #include "descriptors.h"
51 #include "plugin.h"
52 #include "incremental.h"
53 #include "layout.h"
54
55 namespace gold
56 {
57
58 // Layout::Relaxation_debug_check methods.
59
60 // Check that sections and special data are in reset states.
61 // We do not save states for Output_sections and special Output_data.
62 // So we check that they have not assigned any addresses or offsets.
63 // clean_up_after_relaxation simply resets their addresses and offsets.
64 void
65 Layout::Relaxation_debug_check::check_output_data_for_reset_values(
66 const Layout::Section_list& sections,
67 const Layout::Data_list& special_outputs)
68 {
69 for(Layout::Section_list::const_iterator p = sections.begin();
70 p != sections.end();
71 ++p)
72 gold_assert((*p)->address_and_file_offset_have_reset_values());
73
74 for(Layout::Data_list::const_iterator p = special_outputs.begin();
75 p != special_outputs.end();
76 ++p)
77 gold_assert((*p)->address_and_file_offset_have_reset_values());
78 }
79
80 // Save information of SECTIONS for checking later.
81
82 void
83 Layout::Relaxation_debug_check::read_sections(
84 const Layout::Section_list& sections)
85 {
86 for(Layout::Section_list::const_iterator p = sections.begin();
87 p != sections.end();
88 ++p)
89 {
90 Output_section* os = *p;
91 Section_info info;
92 info.output_section = os;
93 info.address = os->is_address_valid() ? os->address() : 0;
94 info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
95 info.offset = os->is_offset_valid()? os->offset() : -1 ;
96 this->section_infos_.push_back(info);
97 }
98 }
99
100 // Verify SECTIONS using previously recorded information.
101
102 void
103 Layout::Relaxation_debug_check::verify_sections(
104 const Layout::Section_list& sections)
105 {
106 size_t i = 0;
107 for(Layout::Section_list::const_iterator p = sections.begin();
108 p != sections.end();
109 ++p, ++i)
110 {
111 Output_section* os = *p;
112 uint64_t address = os->is_address_valid() ? os->address() : 0;
113 off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
114 off_t offset = os->is_offset_valid()? os->offset() : -1 ;
115
116 if (i >= this->section_infos_.size())
117 {
118 gold_fatal("Section_info of %s missing.\n", os->name());
119 }
120 const Section_info& info = this->section_infos_[i];
121 if (os != info.output_section)
122 gold_fatal("Section order changed. Expecting %s but see %s\n",
123 info.output_section->name(), os->name());
124 if (address != info.address
125 || data_size != info.data_size
126 || offset != info.offset)
127 gold_fatal("Section %s changed.\n", os->name());
128 }
129 }
130
131 // Layout_task_runner methods.
132
133 // Lay out the sections. This is called after all the input objects
134 // have been read.
135
136 void
137 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
138 {
139 off_t file_size = this->layout_->finalize(this->input_objects_,
140 this->symtab_,
141 this->target_,
142 task);
143
144 // Now we know the final size of the output file and we know where
145 // each piece of information goes.
146
147 if (this->mapfile_ != NULL)
148 {
149 this->mapfile_->print_discarded_sections(this->input_objects_);
150 this->layout_->print_to_mapfile(this->mapfile_);
151 }
152
153 Output_file* of = new Output_file(parameters->options().output_file_name());
154 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
155 of->set_is_temporary();
156 of->open(file_size);
157
158 // Queue up the final set of tasks.
159 gold::queue_final_tasks(this->options_, this->input_objects_,
160 this->symtab_, this->layout_, workqueue, of);
161 }
162
163 // Layout methods.
164
165 Layout::Layout(int number_of_input_files, Script_options* script_options)
166 : number_of_input_files_(number_of_input_files),
167 script_options_(script_options),
168 namepool_(),
169 sympool_(),
170 dynpool_(),
171 signatures_(),
172 section_name_map_(),
173 segment_list_(),
174 section_list_(),
175 unattached_section_list_(),
176 special_output_list_(),
177 section_headers_(NULL),
178 tls_segment_(NULL),
179 relro_segment_(NULL),
180 increase_relro_(0),
181 symtab_section_(NULL),
182 symtab_xindex_(NULL),
183 dynsym_section_(NULL),
184 dynsym_xindex_(NULL),
185 dynamic_section_(NULL),
186 dynamic_symbol_(NULL),
187 dynamic_data_(NULL),
188 eh_frame_section_(NULL),
189 eh_frame_data_(NULL),
190 added_eh_frame_data_(false),
191 eh_frame_hdr_section_(NULL),
192 build_id_note_(NULL),
193 debug_abbrev_(NULL),
194 debug_info_(NULL),
195 group_signatures_(),
196 output_file_size_(-1),
197 have_added_input_section_(false),
198 sections_are_attached_(false),
199 input_requires_executable_stack_(false),
200 input_with_gnu_stack_note_(false),
201 input_without_gnu_stack_note_(false),
202 has_static_tls_(false),
203 any_postprocessing_sections_(false),
204 resized_signatures_(false),
205 have_stabstr_section_(false),
206 incremental_inputs_(NULL),
207 record_output_section_data_from_script_(false),
208 script_output_section_data_list_(),
209 segment_states_(NULL),
210 relaxation_debug_check_(NULL)
211 {
212 // Make space for more than enough segments for a typical file.
213 // This is just for efficiency--it's OK if we wind up needing more.
214 this->segment_list_.reserve(12);
215
216 // We expect two unattached Output_data objects: the file header and
217 // the segment headers.
218 this->special_output_list_.reserve(2);
219
220 // Initialize structure needed for an incremental build.
221 if (parameters->options().incremental())
222 this->incremental_inputs_ = new Incremental_inputs;
223
224 // The section name pool is worth optimizing in all cases, because
225 // it is small, but there are often overlaps due to .rel sections.
226 this->namepool_.set_optimize();
227 }
228
229 // Hash a key we use to look up an output section mapping.
230
231 size_t
232 Layout::Hash_key::operator()(const Layout::Key& k) const
233 {
234 return k.first + k.second.first + k.second.second;
235 }
236
237 // Returns whether the given section is in the list of
238 // debug-sections-used-by-some-version-of-gdb. Currently,
239 // we've checked versions of gdb up to and including 6.7.1.
240
241 static const char* gdb_sections[] =
242 { ".debug_abbrev",
243 // ".debug_aranges", // not used by gdb as of 6.7.1
244 ".debug_frame",
245 ".debug_info",
246 ".debug_types",
247 ".debug_line",
248 ".debug_loc",
249 ".debug_macinfo",
250 // ".debug_pubnames", // not used by gdb as of 6.7.1
251 ".debug_ranges",
252 ".debug_str",
253 };
254
255 static const char* lines_only_debug_sections[] =
256 { ".debug_abbrev",
257 // ".debug_aranges", // not used by gdb as of 6.7.1
258 // ".debug_frame",
259 ".debug_info",
260 // ".debug_types",
261 ".debug_line",
262 // ".debug_loc",
263 // ".debug_macinfo",
264 // ".debug_pubnames", // not used by gdb as of 6.7.1
265 // ".debug_ranges",
266 ".debug_str",
267 };
268
269 static inline bool
270 is_gdb_debug_section(const char* str)
271 {
272 // We can do this faster: binary search or a hashtable. But why bother?
273 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
274 if (strcmp(str, gdb_sections[i]) == 0)
275 return true;
276 return false;
277 }
278
279 static inline bool
280 is_lines_only_debug_section(const char* str)
281 {
282 // We can do this faster: binary search or a hashtable. But why bother?
283 for (size_t i = 0;
284 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
285 ++i)
286 if (strcmp(str, lines_only_debug_sections[i]) == 0)
287 return true;
288 return false;
289 }
290
291 // Whether to include this section in the link.
292
293 template<int size, bool big_endian>
294 bool
295 Layout::include_section(Sized_relobj<size, big_endian>*, const char* name,
296 const elfcpp::Shdr<size, big_endian>& shdr)
297 {
298 if (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE)
299 return false;
300
301 switch (shdr.get_sh_type())
302 {
303 case elfcpp::SHT_NULL:
304 case elfcpp::SHT_SYMTAB:
305 case elfcpp::SHT_DYNSYM:
306 case elfcpp::SHT_HASH:
307 case elfcpp::SHT_DYNAMIC:
308 case elfcpp::SHT_SYMTAB_SHNDX:
309 return false;
310
311 case elfcpp::SHT_STRTAB:
312 // Discard the sections which have special meanings in the ELF
313 // ABI. Keep others (e.g., .stabstr). We could also do this by
314 // checking the sh_link fields of the appropriate sections.
315 return (strcmp(name, ".dynstr") != 0
316 && strcmp(name, ".strtab") != 0
317 && strcmp(name, ".shstrtab") != 0);
318
319 case elfcpp::SHT_RELA:
320 case elfcpp::SHT_REL:
321 case elfcpp::SHT_GROUP:
322 // If we are emitting relocations these should be handled
323 // elsewhere.
324 gold_assert(!parameters->options().relocatable()
325 && !parameters->options().emit_relocs());
326 return false;
327
328 case elfcpp::SHT_PROGBITS:
329 if (parameters->options().strip_debug()
330 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
331 {
332 if (is_debug_info_section(name))
333 return false;
334 }
335 if (parameters->options().strip_debug_non_line()
336 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
337 {
338 // Debugging sections can only be recognized by name.
339 if (is_prefix_of(".debug", name)
340 && !is_lines_only_debug_section(name))
341 return false;
342 }
343 if (parameters->options().strip_debug_gdb()
344 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
345 {
346 // Debugging sections can only be recognized by name.
347 if (is_prefix_of(".debug", name)
348 && !is_gdb_debug_section(name))
349 return false;
350 }
351 if (parameters->options().strip_lto_sections()
352 && !parameters->options().relocatable()
353 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
354 {
355 // Ignore LTO sections containing intermediate code.
356 if (is_prefix_of(".gnu.lto_", name))
357 return false;
358 }
359 // The GNU linker strips .gnu_debuglink sections, so we do too.
360 // This is a feature used to keep debugging information in
361 // separate files.
362 if (strcmp(name, ".gnu_debuglink") == 0)
363 return false;
364 return true;
365
366 default:
367 return true;
368 }
369 }
370
371 // Return an output section named NAME, or NULL if there is none.
372
373 Output_section*
374 Layout::find_output_section(const char* name) const
375 {
376 for (Section_list::const_iterator p = this->section_list_.begin();
377 p != this->section_list_.end();
378 ++p)
379 if (strcmp((*p)->name(), name) == 0)
380 return *p;
381 return NULL;
382 }
383
384 // Return an output segment of type TYPE, with segment flags SET set
385 // and segment flags CLEAR clear. Return NULL if there is none.
386
387 Output_segment*
388 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
389 elfcpp::Elf_Word clear) const
390 {
391 for (Segment_list::const_iterator p = this->segment_list_.begin();
392 p != this->segment_list_.end();
393 ++p)
394 if (static_cast<elfcpp::PT>((*p)->type()) == type
395 && ((*p)->flags() & set) == set
396 && ((*p)->flags() & clear) == 0)
397 return *p;
398 return NULL;
399 }
400
401 // Return the output section to use for section NAME with type TYPE
402 // and section flags FLAGS. NAME must be canonicalized in the string
403 // pool, and NAME_KEY is the key. IS_INTERP is true if this is the
404 // .interp section. IS_DYNAMIC_LINKER_SECTION is true if this section
405 // is used by the dynamic linker. IS_RELRO is true for a relro
406 // section. IS_LAST_RELRO is true for the last relro section.
407 // IS_FIRST_NON_RELRO is true for the first non-relro section.
408
409 Output_section*
410 Layout::get_output_section(const char* name, Stringpool::Key name_key,
411 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
412 Output_section_order order, bool is_relro)
413 {
414 elfcpp::Elf_Xword lookup_flags = flags;
415
416 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
417 // read-write with read-only sections. Some other ELF linkers do
418 // not do this. FIXME: Perhaps there should be an option
419 // controlling this.
420 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
421
422 const Key key(name_key, std::make_pair(type, lookup_flags));
423 const std::pair<Key, Output_section*> v(key, NULL);
424 std::pair<Section_name_map::iterator, bool> ins(
425 this->section_name_map_.insert(v));
426
427 if (!ins.second)
428 return ins.first->second;
429 else
430 {
431 // This is the first time we've seen this name/type/flags
432 // combination. For compatibility with the GNU linker, we
433 // combine sections with contents and zero flags with sections
434 // with non-zero flags. This is a workaround for cases where
435 // assembler code forgets to set section flags. FIXME: Perhaps
436 // there should be an option to control this.
437 Output_section* os = NULL;
438
439 if (type == elfcpp::SHT_PROGBITS)
440 {
441 if (flags == 0)
442 {
443 Output_section* same_name = this->find_output_section(name);
444 if (same_name != NULL
445 && same_name->type() == elfcpp::SHT_PROGBITS
446 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
447 os = same_name;
448 }
449 else if ((flags & elfcpp::SHF_TLS) == 0)
450 {
451 elfcpp::Elf_Xword zero_flags = 0;
452 const Key zero_key(name_key, std::make_pair(type, zero_flags));
453 Section_name_map::iterator p =
454 this->section_name_map_.find(zero_key);
455 if (p != this->section_name_map_.end())
456 os = p->second;
457 }
458 }
459
460 if (os == NULL)
461 os = this->make_output_section(name, type, flags, order, is_relro);
462
463 ins.first->second = os;
464 return os;
465 }
466 }
467
468 // Pick the output section to use for section NAME, in input file
469 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
470 // linker created section. IS_INPUT_SECTION is true if we are
471 // choosing an output section for an input section found in a input
472 // file. IS_INTERP is true if this is the .interp section.
473 // IS_DYNAMIC_LINKER_SECTION is true if this section is used by the
474 // dynamic linker. IS_RELRO is true for a relro section.
475 // IS_LAST_RELRO is true for the last relro section.
476 // IS_FIRST_NON_RELRO is true for the first non-relro section. This
477 // will return NULL if the input section should be discarded.
478
479 Output_section*
480 Layout::choose_output_section(const Relobj* relobj, const char* name,
481 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
482 bool is_input_section, Output_section_order order,
483 bool is_relro)
484 {
485 // We should not see any input sections after we have attached
486 // sections to segments.
487 gold_assert(!is_input_section || !this->sections_are_attached_);
488
489 // Some flags in the input section should not be automatically
490 // copied to the output section.
491 flags &= ~ (elfcpp::SHF_INFO_LINK
492 | elfcpp::SHF_LINK_ORDER
493 | elfcpp::SHF_GROUP
494 | elfcpp::SHF_MERGE
495 | elfcpp::SHF_STRINGS);
496
497 if (this->script_options_->saw_sections_clause())
498 {
499 // We are using a SECTIONS clause, so the output section is
500 // chosen based only on the name.
501
502 Script_sections* ss = this->script_options_->script_sections();
503 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
504 Output_section** output_section_slot;
505 Script_sections::Section_type script_section_type;
506 const char* orig_name = name;
507 name = ss->output_section_name(file_name, name, &output_section_slot,
508 &script_section_type);
509 if (name == NULL)
510 {
511 gold_debug(DEBUG_SCRIPT, _("Unable to create output section '%s' "
512 "because it is not allowed by the "
513 "SECTIONS clause of the linker script"),
514 orig_name);
515 // The SECTIONS clause says to discard this input section.
516 return NULL;
517 }
518
519 // We can only handle script section types ST_NONE and ST_NOLOAD.
520 switch (script_section_type)
521 {
522 case Script_sections::ST_NONE:
523 break;
524 case Script_sections::ST_NOLOAD:
525 flags &= elfcpp::SHF_ALLOC;
526 break;
527 default:
528 gold_unreachable();
529 }
530
531 // If this is an orphan section--one not mentioned in the linker
532 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
533 // default processing below.
534
535 if (output_section_slot != NULL)
536 {
537 if (*output_section_slot != NULL)
538 {
539 (*output_section_slot)->update_flags_for_input_section(flags);
540 return *output_section_slot;
541 }
542
543 // We don't put sections found in the linker script into
544 // SECTION_NAME_MAP_. That keeps us from getting confused
545 // if an orphan section is mapped to a section with the same
546 // name as one in the linker script.
547
548 name = this->namepool_.add(name, false, NULL);
549
550 Output_section* os = this->make_output_section(name, type, flags,
551 order, is_relro);
552
553 os->set_found_in_sections_clause();
554
555 // Special handling for NOLOAD sections.
556 if (script_section_type == Script_sections::ST_NOLOAD)
557 {
558 os->set_is_noload();
559
560 // The constructor of Output_section sets addresses of non-ALLOC
561 // sections to 0 by default. We don't want that for NOLOAD
562 // sections even if they have no SHF_ALLOC flag.
563 if ((os->flags() & elfcpp::SHF_ALLOC) == 0
564 && os->is_address_valid())
565 {
566 gold_assert(os->address() == 0
567 && !os->is_offset_valid()
568 && !os->is_data_size_valid());
569 os->reset_address_and_file_offset();
570 }
571 }
572
573 *output_section_slot = os;
574 return os;
575 }
576 }
577
578 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
579
580 // Turn NAME from the name of the input section into the name of the
581 // output section.
582
583 size_t len = strlen(name);
584 if (is_input_section
585 && !this->script_options_->saw_sections_clause()
586 && !parameters->options().relocatable())
587 name = Layout::output_section_name(name, &len);
588
589 Stringpool::Key name_key;
590 name = this->namepool_.add_with_length(name, len, true, &name_key);
591
592 // Find or make the output section. The output section is selected
593 // based on the section name, type, and flags.
594 return this->get_output_section(name, name_key, type, flags, order, is_relro);
595 }
596
597 // Return the output section to use for input section SHNDX, with name
598 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
599 // index of a relocation section which applies to this section, or 0
600 // if none, or -1U if more than one. RELOC_TYPE is the type of the
601 // relocation section if there is one. Set *OFF to the offset of this
602 // input section without the output section. Return NULL if the
603 // section should be discarded. Set *OFF to -1 if the section
604 // contents should not be written directly to the output file, but
605 // will instead receive special handling.
606
607 template<int size, bool big_endian>
608 Output_section*
609 Layout::layout(Sized_relobj<size, big_endian>* object, unsigned int shndx,
610 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
611 unsigned int reloc_shndx, unsigned int, off_t* off)
612 {
613 *off = 0;
614
615 if (!this->include_section(object, name, shdr))
616 return NULL;
617
618 Output_section* os;
619
620 // Sometimes .init_array*, .preinit_array* and .fini_array* do not have
621 // correct section types. Force them here.
622 elfcpp::Elf_Word sh_type = shdr.get_sh_type();
623 if (sh_type == elfcpp::SHT_PROGBITS)
624 {
625 static const char init_array_prefix[] = ".init_array";
626 static const char preinit_array_prefix[] = ".preinit_array";
627 static const char fini_array_prefix[] = ".fini_array";
628 static size_t init_array_prefix_size = sizeof(init_array_prefix) - 1;
629 static size_t preinit_array_prefix_size =
630 sizeof(preinit_array_prefix) - 1;
631 static size_t fini_array_prefix_size = sizeof(fini_array_prefix) - 1;
632
633 if (strncmp(name, init_array_prefix, init_array_prefix_size) == 0)
634 sh_type = elfcpp::SHT_INIT_ARRAY;
635 else if (strncmp(name, preinit_array_prefix, preinit_array_prefix_size)
636 == 0)
637 sh_type = elfcpp::SHT_PREINIT_ARRAY;
638 else if (strncmp(name, fini_array_prefix, fini_array_prefix_size) == 0)
639 sh_type = elfcpp::SHT_FINI_ARRAY;
640 }
641
642 // In a relocatable link a grouped section must not be combined with
643 // any other sections.
644 if (parameters->options().relocatable()
645 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
646 {
647 name = this->namepool_.add(name, true, NULL);
648 os = this->make_output_section(name, sh_type, shdr.get_sh_flags(),
649 ORDER_INVALID, false);
650 }
651 else
652 {
653 os = this->choose_output_section(object, name, sh_type,
654 shdr.get_sh_flags(), true,
655 ORDER_INVALID, false);
656 if (os == NULL)
657 return NULL;
658 }
659
660 // By default the GNU linker sorts input sections whose names match
661 // .ctor.*, .dtor.*, .init_array.*, or .fini_array.*. The sections
662 // are sorted by name. This is used to implement constructor
663 // priority ordering. We are compatible.
664 if (!this->script_options_->saw_sections_clause()
665 && (is_prefix_of(".ctors.", name)
666 || is_prefix_of(".dtors.", name)
667 || is_prefix_of(".init_array.", name)
668 || is_prefix_of(".fini_array.", name)))
669 os->set_must_sort_attached_input_sections();
670
671 // FIXME: Handle SHF_LINK_ORDER somewhere.
672
673 *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
674 this->script_options_->saw_sections_clause());
675 this->have_added_input_section_ = true;
676
677 return os;
678 }
679
680 // Handle a relocation section when doing a relocatable link.
681
682 template<int size, bool big_endian>
683 Output_section*
684 Layout::layout_reloc(Sized_relobj<size, big_endian>* object,
685 unsigned int,
686 const elfcpp::Shdr<size, big_endian>& shdr,
687 Output_section* data_section,
688 Relocatable_relocs* rr)
689 {
690 gold_assert(parameters->options().relocatable()
691 || parameters->options().emit_relocs());
692
693 int sh_type = shdr.get_sh_type();
694
695 std::string name;
696 if (sh_type == elfcpp::SHT_REL)
697 name = ".rel";
698 else if (sh_type == elfcpp::SHT_RELA)
699 name = ".rela";
700 else
701 gold_unreachable();
702 name += data_section->name();
703
704 // In a relocatable link relocs for a grouped section must not be
705 // combined with other reloc sections.
706 Output_section* os;
707 if (!parameters->options().relocatable()
708 || (data_section->flags() & elfcpp::SHF_GROUP) == 0)
709 os = this->choose_output_section(object, name.c_str(), sh_type,
710 shdr.get_sh_flags(), false,
711 ORDER_INVALID, false);
712 else
713 {
714 const char* n = this->namepool_.add(name.c_str(), true, NULL);
715 os = this->make_output_section(n, sh_type, shdr.get_sh_flags(),
716 ORDER_INVALID, false);
717 }
718
719 os->set_should_link_to_symtab();
720 os->set_info_section(data_section);
721
722 Output_section_data* posd;
723 if (sh_type == elfcpp::SHT_REL)
724 {
725 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
726 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
727 size,
728 big_endian>(rr);
729 }
730 else if (sh_type == elfcpp::SHT_RELA)
731 {
732 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
733 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
734 size,
735 big_endian>(rr);
736 }
737 else
738 gold_unreachable();
739
740 os->add_output_section_data(posd);
741 rr->set_output_data(posd);
742
743 return os;
744 }
745
746 // Handle a group section when doing a relocatable link.
747
748 template<int size, bool big_endian>
749 void
750 Layout::layout_group(Symbol_table* symtab,
751 Sized_relobj<size, big_endian>* object,
752 unsigned int,
753 const char* group_section_name,
754 const char* signature,
755 const elfcpp::Shdr<size, big_endian>& shdr,
756 elfcpp::Elf_Word flags,
757 std::vector<unsigned int>* shndxes)
758 {
759 gold_assert(parameters->options().relocatable());
760 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
761 group_section_name = this->namepool_.add(group_section_name, true, NULL);
762 Output_section* os = this->make_output_section(group_section_name,
763 elfcpp::SHT_GROUP,
764 shdr.get_sh_flags(),
765 ORDER_INVALID, false);
766
767 // We need to find a symbol with the signature in the symbol table.
768 // If we don't find one now, we need to look again later.
769 Symbol* sym = symtab->lookup(signature, NULL);
770 if (sym != NULL)
771 os->set_info_symndx(sym);
772 else
773 {
774 // Reserve some space to minimize reallocations.
775 if (this->group_signatures_.empty())
776 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
777
778 // We will wind up using a symbol whose name is the signature.
779 // So just put the signature in the symbol name pool to save it.
780 signature = symtab->canonicalize_name(signature);
781 this->group_signatures_.push_back(Group_signature(os, signature));
782 }
783
784 os->set_should_link_to_symtab();
785 os->set_entsize(4);
786
787 section_size_type entry_count =
788 convert_to_section_size_type(shdr.get_sh_size() / 4);
789 Output_section_data* posd =
790 new Output_data_group<size, big_endian>(object, entry_count, flags,
791 shndxes);
792 os->add_output_section_data(posd);
793 }
794
795 // Special GNU handling of sections name .eh_frame. They will
796 // normally hold exception frame data as defined by the C++ ABI
797 // (http://codesourcery.com/cxx-abi/).
798
799 template<int size, bool big_endian>
800 Output_section*
801 Layout::layout_eh_frame(Sized_relobj<size, big_endian>* object,
802 const unsigned char* symbols,
803 off_t symbols_size,
804 const unsigned char* symbol_names,
805 off_t symbol_names_size,
806 unsigned int shndx,
807 const elfcpp::Shdr<size, big_endian>& shdr,
808 unsigned int reloc_shndx, unsigned int reloc_type,
809 off_t* off)
810 {
811 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS);
812 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
813
814 const char* const name = ".eh_frame";
815 Output_section* os = this->choose_output_section(object, name,
816 elfcpp::SHT_PROGBITS,
817 elfcpp::SHF_ALLOC, false,
818 ORDER_EHFRAME, false);
819 if (os == NULL)
820 return NULL;
821
822 if (this->eh_frame_section_ == NULL)
823 {
824 this->eh_frame_section_ = os;
825 this->eh_frame_data_ = new Eh_frame();
826
827 if (parameters->options().eh_frame_hdr())
828 {
829 Output_section* hdr_os =
830 this->choose_output_section(NULL, ".eh_frame_hdr",
831 elfcpp::SHT_PROGBITS,
832 elfcpp::SHF_ALLOC, false,
833 ORDER_EHFRAME, false);
834
835 if (hdr_os != NULL)
836 {
837 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
838 this->eh_frame_data_);
839 hdr_os->add_output_section_data(hdr_posd);
840
841 hdr_os->set_after_input_sections();
842
843 if (!this->script_options_->saw_phdrs_clause())
844 {
845 Output_segment* hdr_oseg;
846 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
847 elfcpp::PF_R);
848 hdr_oseg->add_output_section_to_nonload(hdr_os,
849 elfcpp::PF_R);
850 }
851
852 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
853 }
854 }
855 }
856
857 gold_assert(this->eh_frame_section_ == os);
858
859 if (this->eh_frame_data_->add_ehframe_input_section(object,
860 symbols,
861 symbols_size,
862 symbol_names,
863 symbol_names_size,
864 shndx,
865 reloc_shndx,
866 reloc_type))
867 {
868 os->update_flags_for_input_section(shdr.get_sh_flags());
869
870 // We found a .eh_frame section we are going to optimize, so now
871 // we can add the set of optimized sections to the output
872 // section. We need to postpone adding this until we've found a
873 // section we can optimize so that the .eh_frame section in
874 // crtbegin.o winds up at the start of the output section.
875 if (!this->added_eh_frame_data_)
876 {
877 os->add_output_section_data(this->eh_frame_data_);
878 this->added_eh_frame_data_ = true;
879 }
880 *off = -1;
881 }
882 else
883 {
884 // We couldn't handle this .eh_frame section for some reason.
885 // Add it as a normal section.
886 bool saw_sections_clause = this->script_options_->saw_sections_clause();
887 *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
888 saw_sections_clause);
889 this->have_added_input_section_ = true;
890 }
891
892 return os;
893 }
894
895 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
896 // the output section.
897
898 Output_section*
899 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
900 elfcpp::Elf_Xword flags,
901 Output_section_data* posd,
902 Output_section_order order, bool is_relro)
903 {
904 Output_section* os = this->choose_output_section(NULL, name, type, flags,
905 false, order, is_relro);
906 if (os != NULL)
907 os->add_output_section_data(posd);
908 return os;
909 }
910
911 // Map section flags to segment flags.
912
913 elfcpp::Elf_Word
914 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
915 {
916 elfcpp::Elf_Word ret = elfcpp::PF_R;
917 if ((flags & elfcpp::SHF_WRITE) != 0)
918 ret |= elfcpp::PF_W;
919 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
920 ret |= elfcpp::PF_X;
921 return ret;
922 }
923
924 // Sometimes we compress sections. This is typically done for
925 // sections that are not part of normal program execution (such as
926 // .debug_* sections), and where the readers of these sections know
927 // how to deal with compressed sections. This routine doesn't say for
928 // certain whether we'll compress -- it depends on commandline options
929 // as well -- just whether this section is a candidate for compression.
930 // (The Output_compressed_section class decides whether to compress
931 // a given section, and picks the name of the compressed section.)
932
933 static bool
934 is_compressible_debug_section(const char* secname)
935 {
936 return (is_prefix_of(".debug", secname));
937 }
938
939 // We may see compressed debug sections in input files. Return TRUE
940 // if this is the name of a compressed debug section.
941
942 bool
943 is_compressed_debug_section(const char* secname)
944 {
945 return (is_prefix_of(".zdebug", secname));
946 }
947
948 // Make a new Output_section, and attach it to segments as
949 // appropriate. ORDER is the order in which this section should
950 // appear in the output segment. IS_RELRO is true if this is a relro
951 // (read-only after relocations) section.
952
953 Output_section*
954 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
955 elfcpp::Elf_Xword flags,
956 Output_section_order order, bool is_relro)
957 {
958 Output_section* os;
959 if ((flags & elfcpp::SHF_ALLOC) == 0
960 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
961 && is_compressible_debug_section(name))
962 os = new Output_compressed_section(&parameters->options(), name, type,
963 flags);
964 else if ((flags & elfcpp::SHF_ALLOC) == 0
965 && parameters->options().strip_debug_non_line()
966 && strcmp(".debug_abbrev", name) == 0)
967 {
968 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
969 name, type, flags);
970 if (this->debug_info_)
971 this->debug_info_->set_abbreviations(this->debug_abbrev_);
972 }
973 else if ((flags & elfcpp::SHF_ALLOC) == 0
974 && parameters->options().strip_debug_non_line()
975 && strcmp(".debug_info", name) == 0)
976 {
977 os = this->debug_info_ = new Output_reduced_debug_info_section(
978 name, type, flags);
979 if (this->debug_abbrev_)
980 this->debug_info_->set_abbreviations(this->debug_abbrev_);
981 }
982 else
983 {
984 // FIXME: const_cast is ugly.
985 Target* target = const_cast<Target*>(&parameters->target());
986 os = target->make_output_section(name, type, flags);
987 }
988
989 // With -z relro, we have to recognize the special sections by name.
990 // There is no other way.
991 bool is_relro_local = false;
992 if (!this->script_options_->saw_sections_clause()
993 && parameters->options().relro()
994 && type == elfcpp::SHT_PROGBITS
995 && (flags & elfcpp::SHF_ALLOC) != 0
996 && (flags & elfcpp::SHF_WRITE) != 0)
997 {
998 if (strcmp(name, ".data.rel.ro") == 0)
999 is_relro = true;
1000 else if (strcmp(name, ".data.rel.ro.local") == 0)
1001 {
1002 is_relro = true;
1003 is_relro_local = true;
1004 }
1005 else if (type == elfcpp::SHT_INIT_ARRAY
1006 || type == elfcpp::SHT_FINI_ARRAY
1007 || type == elfcpp::SHT_PREINIT_ARRAY)
1008 is_relro = true;
1009 else if (strcmp(name, ".ctors") == 0
1010 || strcmp(name, ".dtors") == 0
1011 || strcmp(name, ".jcr") == 0)
1012 is_relro = true;
1013 }
1014
1015 if (is_relro)
1016 os->set_is_relro();
1017
1018 if (order == ORDER_INVALID && (flags & elfcpp::SHF_ALLOC) != 0)
1019 order = this->default_section_order(os, is_relro_local);
1020
1021 os->set_order(order);
1022
1023 parameters->target().new_output_section(os);
1024
1025 this->section_list_.push_back(os);
1026
1027 // The GNU linker by default sorts some sections by priority, so we
1028 // do the same. We need to know that this might happen before we
1029 // attach any input sections.
1030 if (!this->script_options_->saw_sections_clause()
1031 && (strcmp(name, ".ctors") == 0
1032 || strcmp(name, ".dtors") == 0
1033 || strcmp(name, ".init_array") == 0
1034 || strcmp(name, ".fini_array") == 0))
1035 os->set_may_sort_attached_input_sections();
1036
1037 // Check for .stab*str sections, as .stab* sections need to link to
1038 // them.
1039 if (type == elfcpp::SHT_STRTAB
1040 && !this->have_stabstr_section_
1041 && strncmp(name, ".stab", 5) == 0
1042 && strcmp(name + strlen(name) - 3, "str") == 0)
1043 this->have_stabstr_section_ = true;
1044
1045 // If we have already attached the sections to segments, then we
1046 // need to attach this one now. This happens for sections created
1047 // directly by the linker.
1048 if (this->sections_are_attached_)
1049 this->attach_section_to_segment(os);
1050
1051 return os;
1052 }
1053
1054 // Return the default order in which a section should be placed in an
1055 // output segment. This function captures a lot of the ideas in
1056 // ld/scripttempl/elf.sc in the GNU linker. Note that the order of a
1057 // linker created section is normally set when the section is created;
1058 // this function is used for input sections.
1059
1060 Output_section_order
1061 Layout::default_section_order(Output_section* os, bool is_relro_local)
1062 {
1063 gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
1064 bool is_write = (os->flags() & elfcpp::SHF_WRITE) != 0;
1065 bool is_execinstr = (os->flags() & elfcpp::SHF_EXECINSTR) != 0;
1066 bool is_bss = false;
1067
1068 switch (os->type())
1069 {
1070 default:
1071 case elfcpp::SHT_PROGBITS:
1072 break;
1073 case elfcpp::SHT_NOBITS:
1074 is_bss = true;
1075 break;
1076 case elfcpp::SHT_RELA:
1077 case elfcpp::SHT_REL:
1078 if (!is_write)
1079 return ORDER_DYNAMIC_RELOCS;
1080 break;
1081 case elfcpp::SHT_HASH:
1082 case elfcpp::SHT_DYNAMIC:
1083 case elfcpp::SHT_SHLIB:
1084 case elfcpp::SHT_DYNSYM:
1085 case elfcpp::SHT_GNU_HASH:
1086 case elfcpp::SHT_GNU_verdef:
1087 case elfcpp::SHT_GNU_verneed:
1088 case elfcpp::SHT_GNU_versym:
1089 if (!is_write)
1090 return ORDER_DYNAMIC_LINKER;
1091 break;
1092 case elfcpp::SHT_NOTE:
1093 return is_write ? ORDER_RW_NOTE : ORDER_RO_NOTE;
1094 }
1095
1096 if ((os->flags() & elfcpp::SHF_TLS) != 0)
1097 return is_bss ? ORDER_TLS_BSS : ORDER_TLS_DATA;
1098
1099 if (!is_bss && !is_write)
1100 {
1101 if (is_execinstr)
1102 {
1103 if (strcmp(os->name(), ".init") == 0)
1104 return ORDER_INIT;
1105 else if (strcmp(os->name(), ".fini") == 0)
1106 return ORDER_FINI;
1107 }
1108 return is_execinstr ? ORDER_TEXT : ORDER_READONLY;
1109 }
1110
1111 if (os->is_relro())
1112 return is_relro_local ? ORDER_RELRO_LOCAL : ORDER_RELRO;
1113
1114 if (os->is_small_section())
1115 return is_bss ? ORDER_SMALL_BSS : ORDER_SMALL_DATA;
1116 if (os->is_large_section())
1117 return is_bss ? ORDER_LARGE_BSS : ORDER_LARGE_DATA;
1118
1119 return is_bss ? ORDER_BSS : ORDER_DATA;
1120 }
1121
1122 // Attach output sections to segments. This is called after we have
1123 // seen all the input sections.
1124
1125 void
1126 Layout::attach_sections_to_segments()
1127 {
1128 for (Section_list::iterator p = this->section_list_.begin();
1129 p != this->section_list_.end();
1130 ++p)
1131 this->attach_section_to_segment(*p);
1132
1133 this->sections_are_attached_ = true;
1134 }
1135
1136 // Attach an output section to a segment.
1137
1138 void
1139 Layout::attach_section_to_segment(Output_section* os)
1140 {
1141 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1142 this->unattached_section_list_.push_back(os);
1143 else
1144 this->attach_allocated_section_to_segment(os);
1145 }
1146
1147 // Attach an allocated output section to a segment.
1148
1149 void
1150 Layout::attach_allocated_section_to_segment(Output_section* os)
1151 {
1152 elfcpp::Elf_Xword flags = os->flags();
1153 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
1154
1155 if (parameters->options().relocatable())
1156 return;
1157
1158 // If we have a SECTIONS clause, we can't handle the attachment to
1159 // segments until after we've seen all the sections.
1160 if (this->script_options_->saw_sections_clause())
1161 return;
1162
1163 gold_assert(!this->script_options_->saw_phdrs_clause());
1164
1165 // This output section goes into a PT_LOAD segment.
1166
1167 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
1168
1169 // Check for --section-start.
1170 uint64_t addr;
1171 bool is_address_set = parameters->options().section_start(os->name(), &addr);
1172
1173 // In general the only thing we really care about for PT_LOAD
1174 // segments is whether or not they are writable, so that is how we
1175 // search for them. Large data sections also go into their own
1176 // PT_LOAD segment. People who need segments sorted on some other
1177 // basis will have to use a linker script.
1178
1179 Segment_list::const_iterator p;
1180 for (p = this->segment_list_.begin();
1181 p != this->segment_list_.end();
1182 ++p)
1183 {
1184 if ((*p)->type() != elfcpp::PT_LOAD)
1185 continue;
1186 if (!parameters->options().omagic()
1187 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1188 continue;
1189 // If -Tbss was specified, we need to separate the data and BSS
1190 // segments.
1191 if (parameters->options().user_set_Tbss())
1192 {
1193 if ((os->type() == elfcpp::SHT_NOBITS)
1194 == (*p)->has_any_data_sections())
1195 continue;
1196 }
1197 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1198 continue;
1199
1200 if (is_address_set)
1201 {
1202 if ((*p)->are_addresses_set())
1203 continue;
1204
1205 (*p)->add_initial_output_data(os);
1206 (*p)->update_flags_for_output_section(seg_flags);
1207 (*p)->set_addresses(addr, addr);
1208 break;
1209 }
1210
1211 (*p)->add_output_section_to_load(this, os, seg_flags);
1212 break;
1213 }
1214
1215 if (p == this->segment_list_.end())
1216 {
1217 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1218 seg_flags);
1219 if (os->is_large_data_section())
1220 oseg->set_is_large_data_segment();
1221 oseg->add_output_section_to_load(this, os, seg_flags);
1222 if (is_address_set)
1223 oseg->set_addresses(addr, addr);
1224 }
1225
1226 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
1227 // segment.
1228 if (os->type() == elfcpp::SHT_NOTE)
1229 {
1230 // See if we already have an equivalent PT_NOTE segment.
1231 for (p = this->segment_list_.begin();
1232 p != segment_list_.end();
1233 ++p)
1234 {
1235 if ((*p)->type() == elfcpp::PT_NOTE
1236 && (((*p)->flags() & elfcpp::PF_W)
1237 == (seg_flags & elfcpp::PF_W)))
1238 {
1239 (*p)->add_output_section_to_nonload(os, seg_flags);
1240 break;
1241 }
1242 }
1243
1244 if (p == this->segment_list_.end())
1245 {
1246 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
1247 seg_flags);
1248 oseg->add_output_section_to_nonload(os, seg_flags);
1249 }
1250 }
1251
1252 // If we see a loadable SHF_TLS section, we create a PT_TLS
1253 // segment. There can only be one such segment.
1254 if ((flags & elfcpp::SHF_TLS) != 0)
1255 {
1256 if (this->tls_segment_ == NULL)
1257 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
1258 this->tls_segment_->add_output_section_to_nonload(os, seg_flags);
1259 }
1260
1261 // If -z relro is in effect, and we see a relro section, we create a
1262 // PT_GNU_RELRO segment. There can only be one such segment.
1263 if (os->is_relro() && parameters->options().relro())
1264 {
1265 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
1266 if (this->relro_segment_ == NULL)
1267 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
1268 this->relro_segment_->add_output_section_to_nonload(os, seg_flags);
1269 }
1270 }
1271
1272 // Make an output section for a script.
1273
1274 Output_section*
1275 Layout::make_output_section_for_script(
1276 const char* name,
1277 Script_sections::Section_type section_type)
1278 {
1279 name = this->namepool_.add(name, false, NULL);
1280 elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
1281 if (section_type == Script_sections::ST_NOLOAD)
1282 sh_flags = 0;
1283 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
1284 sh_flags, ORDER_INVALID,
1285 false);
1286 os->set_found_in_sections_clause();
1287 if (section_type == Script_sections::ST_NOLOAD)
1288 os->set_is_noload();
1289 return os;
1290 }
1291
1292 // Return the number of segments we expect to see.
1293
1294 size_t
1295 Layout::expected_segment_count() const
1296 {
1297 size_t ret = this->segment_list_.size();
1298
1299 // If we didn't see a SECTIONS clause in a linker script, we should
1300 // already have the complete list of segments. Otherwise we ask the
1301 // SECTIONS clause how many segments it expects, and add in the ones
1302 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
1303
1304 if (!this->script_options_->saw_sections_clause())
1305 return ret;
1306 else
1307 {
1308 const Script_sections* ss = this->script_options_->script_sections();
1309 return ret + ss->expected_segment_count(this);
1310 }
1311 }
1312
1313 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
1314 // is whether we saw a .note.GNU-stack section in the object file.
1315 // GNU_STACK_FLAGS is the section flags. The flags give the
1316 // protection required for stack memory. We record this in an
1317 // executable as a PT_GNU_STACK segment. If an object file does not
1318 // have a .note.GNU-stack segment, we must assume that it is an old
1319 // object. On some targets that will force an executable stack.
1320
1321 void
1322 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags)
1323 {
1324 if (!seen_gnu_stack)
1325 this->input_without_gnu_stack_note_ = true;
1326 else
1327 {
1328 this->input_with_gnu_stack_note_ = true;
1329 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
1330 this->input_requires_executable_stack_ = true;
1331 }
1332 }
1333
1334 // Create automatic note sections.
1335
1336 void
1337 Layout::create_notes()
1338 {
1339 this->create_gold_note();
1340 this->create_executable_stack_info();
1341 this->create_build_id();
1342 }
1343
1344 // Create the dynamic sections which are needed before we read the
1345 // relocs.
1346
1347 void
1348 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
1349 {
1350 if (parameters->doing_static_link())
1351 return;
1352
1353 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
1354 elfcpp::SHT_DYNAMIC,
1355 (elfcpp::SHF_ALLOC
1356 | elfcpp::SHF_WRITE),
1357 false, ORDER_RELRO,
1358 true);
1359
1360 this->dynamic_symbol_ =
1361 symtab->define_in_output_data("_DYNAMIC", NULL, Symbol_table::PREDEFINED,
1362 this->dynamic_section_, 0, 0,
1363 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
1364 elfcpp::STV_HIDDEN, 0, false, false);
1365
1366 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
1367
1368 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
1369 }
1370
1371 // For each output section whose name can be represented as C symbol,
1372 // define __start and __stop symbols for the section. This is a GNU
1373 // extension.
1374
1375 void
1376 Layout::define_section_symbols(Symbol_table* symtab)
1377 {
1378 for (Section_list::const_iterator p = this->section_list_.begin();
1379 p != this->section_list_.end();
1380 ++p)
1381 {
1382 const char* const name = (*p)->name();
1383 if (is_cident(name))
1384 {
1385 const std::string name_string(name);
1386 const std::string start_name(cident_section_start_prefix
1387 + name_string);
1388 const std::string stop_name(cident_section_stop_prefix
1389 + name_string);
1390
1391 symtab->define_in_output_data(start_name.c_str(),
1392 NULL, // version
1393 Symbol_table::PREDEFINED,
1394 *p,
1395 0, // value
1396 0, // symsize
1397 elfcpp::STT_NOTYPE,
1398 elfcpp::STB_GLOBAL,
1399 elfcpp::STV_DEFAULT,
1400 0, // nonvis
1401 false, // offset_is_from_end
1402 true); // only_if_ref
1403
1404 symtab->define_in_output_data(stop_name.c_str(),
1405 NULL, // version
1406 Symbol_table::PREDEFINED,
1407 *p,
1408 0, // value
1409 0, // symsize
1410 elfcpp::STT_NOTYPE,
1411 elfcpp::STB_GLOBAL,
1412 elfcpp::STV_DEFAULT,
1413 0, // nonvis
1414 true, // offset_is_from_end
1415 true); // only_if_ref
1416 }
1417 }
1418 }
1419
1420 // Define symbols for group signatures.
1421
1422 void
1423 Layout::define_group_signatures(Symbol_table* symtab)
1424 {
1425 for (Group_signatures::iterator p = this->group_signatures_.begin();
1426 p != this->group_signatures_.end();
1427 ++p)
1428 {
1429 Symbol* sym = symtab->lookup(p->signature, NULL);
1430 if (sym != NULL)
1431 p->section->set_info_symndx(sym);
1432 else
1433 {
1434 // Force the name of the group section to the group
1435 // signature, and use the group's section symbol as the
1436 // signature symbol.
1437 if (strcmp(p->section->name(), p->signature) != 0)
1438 {
1439 const char* name = this->namepool_.add(p->signature,
1440 true, NULL);
1441 p->section->set_name(name);
1442 }
1443 p->section->set_needs_symtab_index();
1444 p->section->set_info_section_symndx(p->section);
1445 }
1446 }
1447
1448 this->group_signatures_.clear();
1449 }
1450
1451 // Find the first read-only PT_LOAD segment, creating one if
1452 // necessary.
1453
1454 Output_segment*
1455 Layout::find_first_load_seg()
1456 {
1457 for (Segment_list::const_iterator p = this->segment_list_.begin();
1458 p != this->segment_list_.end();
1459 ++p)
1460 {
1461 if ((*p)->type() == elfcpp::PT_LOAD
1462 && ((*p)->flags() & elfcpp::PF_R) != 0
1463 && (parameters->options().omagic()
1464 || ((*p)->flags() & elfcpp::PF_W) == 0))
1465 return *p;
1466 }
1467
1468 gold_assert(!this->script_options_->saw_phdrs_clause());
1469
1470 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
1471 elfcpp::PF_R);
1472 return load_seg;
1473 }
1474
1475 // Save states of all current output segments. Store saved states
1476 // in SEGMENT_STATES.
1477
1478 void
1479 Layout::save_segments(Segment_states* segment_states)
1480 {
1481 for (Segment_list::const_iterator p = this->segment_list_.begin();
1482 p != this->segment_list_.end();
1483 ++p)
1484 {
1485 Output_segment* segment = *p;
1486 // Shallow copy.
1487 Output_segment* copy = new Output_segment(*segment);
1488 (*segment_states)[segment] = copy;
1489 }
1490 }
1491
1492 // Restore states of output segments and delete any segment not found in
1493 // SEGMENT_STATES.
1494
1495 void
1496 Layout::restore_segments(const Segment_states* segment_states)
1497 {
1498 // Go through the segment list and remove any segment added in the
1499 // relaxation loop.
1500 this->tls_segment_ = NULL;
1501 this->relro_segment_ = NULL;
1502 Segment_list::iterator list_iter = this->segment_list_.begin();
1503 while (list_iter != this->segment_list_.end())
1504 {
1505 Output_segment* segment = *list_iter;
1506 Segment_states::const_iterator states_iter =
1507 segment_states->find(segment);
1508 if (states_iter != segment_states->end())
1509 {
1510 const Output_segment* copy = states_iter->second;
1511 // Shallow copy to restore states.
1512 *segment = *copy;
1513
1514 // Also fix up TLS and RELRO segment pointers as appropriate.
1515 if (segment->type() == elfcpp::PT_TLS)
1516 this->tls_segment_ = segment;
1517 else if (segment->type() == elfcpp::PT_GNU_RELRO)
1518 this->relro_segment_ = segment;
1519
1520 ++list_iter;
1521 }
1522 else
1523 {
1524 list_iter = this->segment_list_.erase(list_iter);
1525 // This is a segment created during section layout. It should be
1526 // safe to remove it since we should have removed all pointers to it.
1527 delete segment;
1528 }
1529 }
1530 }
1531
1532 // Clean up after relaxation so that sections can be laid out again.
1533
1534 void
1535 Layout::clean_up_after_relaxation()
1536 {
1537 // Restore the segments to point state just prior to the relaxation loop.
1538 Script_sections* script_section = this->script_options_->script_sections();
1539 script_section->release_segments();
1540 this->restore_segments(this->segment_states_);
1541
1542 // Reset section addresses and file offsets
1543 for (Section_list::iterator p = this->section_list_.begin();
1544 p != this->section_list_.end();
1545 ++p)
1546 {
1547 (*p)->restore_states();
1548
1549 // If an input section changes size because of relaxation,
1550 // we need to adjust the section offsets of all input sections.
1551 // after such a section.
1552 if ((*p)->section_offsets_need_adjustment())
1553 (*p)->adjust_section_offsets();
1554
1555 (*p)->reset_address_and_file_offset();
1556 }
1557
1558 // Reset special output object address and file offsets.
1559 for (Data_list::iterator p = this->special_output_list_.begin();
1560 p != this->special_output_list_.end();
1561 ++p)
1562 (*p)->reset_address_and_file_offset();
1563
1564 // A linker script may have created some output section data objects.
1565 // They are useless now.
1566 for (Output_section_data_list::const_iterator p =
1567 this->script_output_section_data_list_.begin();
1568 p != this->script_output_section_data_list_.end();
1569 ++p)
1570 delete *p;
1571 this->script_output_section_data_list_.clear();
1572 }
1573
1574 // Prepare for relaxation.
1575
1576 void
1577 Layout::prepare_for_relaxation()
1578 {
1579 // Create an relaxation debug check if in debugging mode.
1580 if (is_debugging_enabled(DEBUG_RELAXATION))
1581 this->relaxation_debug_check_ = new Relaxation_debug_check();
1582
1583 // Save segment states.
1584 this->segment_states_ = new Segment_states();
1585 this->save_segments(this->segment_states_);
1586
1587 for(Section_list::const_iterator p = this->section_list_.begin();
1588 p != this->section_list_.end();
1589 ++p)
1590 (*p)->save_states();
1591
1592 if (is_debugging_enabled(DEBUG_RELAXATION))
1593 this->relaxation_debug_check_->check_output_data_for_reset_values(
1594 this->section_list_, this->special_output_list_);
1595
1596 // Also enable recording of output section data from scripts.
1597 this->record_output_section_data_from_script_ = true;
1598 }
1599
1600 // Relaxation loop body: If target has no relaxation, this runs only once
1601 // Otherwise, the target relaxation hook is called at the end of
1602 // each iteration. If the hook returns true, it means re-layout of
1603 // section is required.
1604 //
1605 // The number of segments created by a linking script without a PHDRS
1606 // clause may be affected by section sizes and alignments. There is
1607 // a remote chance that relaxation causes different number of PT_LOAD
1608 // segments are created and sections are attached to different segments.
1609 // Therefore, we always throw away all segments created during section
1610 // layout. In order to be able to restart the section layout, we keep
1611 // a copy of the segment list right before the relaxation loop and use
1612 // that to restore the segments.
1613 //
1614 // PASS is the current relaxation pass number.
1615 // SYMTAB is a symbol table.
1616 // PLOAD_SEG is the address of a pointer for the load segment.
1617 // PHDR_SEG is a pointer to the PHDR segment.
1618 // SEGMENT_HEADERS points to the output segment header.
1619 // FILE_HEADER points to the output file header.
1620 // PSHNDX is the address to store the output section index.
1621
1622 off_t inline
1623 Layout::relaxation_loop_body(
1624 int pass,
1625 Target* target,
1626 Symbol_table* symtab,
1627 Output_segment** pload_seg,
1628 Output_segment* phdr_seg,
1629 Output_segment_headers* segment_headers,
1630 Output_file_header* file_header,
1631 unsigned int* pshndx)
1632 {
1633 // If this is not the first iteration, we need to clean up after
1634 // relaxation so that we can lay out the sections again.
1635 if (pass != 0)
1636 this->clean_up_after_relaxation();
1637
1638 // If there is a SECTIONS clause, put all the input sections into
1639 // the required order.
1640 Output_segment* load_seg;
1641 if (this->script_options_->saw_sections_clause())
1642 load_seg = this->set_section_addresses_from_script(symtab);
1643 else if (parameters->options().relocatable())
1644 load_seg = NULL;
1645 else
1646 load_seg = this->find_first_load_seg();
1647
1648 if (parameters->options().oformat_enum()
1649 != General_options::OBJECT_FORMAT_ELF)
1650 load_seg = NULL;
1651
1652 // If the user set the address of the text segment, that may not be
1653 // compatible with putting the segment headers and file headers into
1654 // that segment.
1655 if (parameters->options().user_set_Ttext())
1656 load_seg = NULL;
1657
1658 gold_assert(phdr_seg == NULL
1659 || load_seg != NULL
1660 || this->script_options_->saw_sections_clause());
1661
1662 // If the address of the load segment we found has been set by
1663 // --section-start rather than by a script, then adjust the VMA and
1664 // LMA downward if possible to include the file and section headers.
1665 uint64_t header_gap = 0;
1666 if (load_seg != NULL
1667 && load_seg->are_addresses_set()
1668 && !this->script_options_->saw_sections_clause()
1669 && !parameters->options().relocatable())
1670 {
1671 file_header->finalize_data_size();
1672 segment_headers->finalize_data_size();
1673 size_t sizeof_headers = (file_header->data_size()
1674 + segment_headers->data_size());
1675 const uint64_t abi_pagesize = target->abi_pagesize();
1676 uint64_t hdr_paddr = load_seg->paddr() - sizeof_headers;
1677 hdr_paddr &= ~(abi_pagesize - 1);
1678 uint64_t subtract = load_seg->paddr() - hdr_paddr;
1679 if (load_seg->paddr() < subtract || load_seg->vaddr() < subtract)
1680 load_seg = NULL;
1681 else
1682 {
1683 load_seg->set_addresses(load_seg->vaddr() - subtract,
1684 load_seg->paddr() - subtract);
1685 header_gap = subtract - sizeof_headers;
1686 }
1687 }
1688
1689 // Lay out the segment headers.
1690 if (!parameters->options().relocatable())
1691 {
1692 gold_assert(segment_headers != NULL);
1693 if (header_gap != 0 && load_seg != NULL)
1694 {
1695 Output_data_zero_fill* z = new Output_data_zero_fill(header_gap, 1);
1696 load_seg->add_initial_output_data(z);
1697 }
1698 if (load_seg != NULL)
1699 load_seg->add_initial_output_data(segment_headers);
1700 if (phdr_seg != NULL)
1701 phdr_seg->add_initial_output_data(segment_headers);
1702 }
1703
1704 // Lay out the file header.
1705 if (load_seg != NULL)
1706 load_seg->add_initial_output_data(file_header);
1707
1708 if (this->script_options_->saw_phdrs_clause()
1709 && !parameters->options().relocatable())
1710 {
1711 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
1712 // clause in a linker script.
1713 Script_sections* ss = this->script_options_->script_sections();
1714 ss->put_headers_in_phdrs(file_header, segment_headers);
1715 }
1716
1717 // We set the output section indexes in set_segment_offsets and
1718 // set_section_indexes.
1719 *pshndx = 1;
1720
1721 // Set the file offsets of all the segments, and all the sections
1722 // they contain.
1723 off_t off;
1724 if (!parameters->options().relocatable())
1725 off = this->set_segment_offsets(target, load_seg, pshndx);
1726 else
1727 off = this->set_relocatable_section_offsets(file_header, pshndx);
1728
1729 // Verify that the dummy relaxation does not change anything.
1730 if (is_debugging_enabled(DEBUG_RELAXATION))
1731 {
1732 if (pass == 0)
1733 this->relaxation_debug_check_->read_sections(this->section_list_);
1734 else
1735 this->relaxation_debug_check_->verify_sections(this->section_list_);
1736 }
1737
1738 *pload_seg = load_seg;
1739 return off;
1740 }
1741
1742 // Search the list of patterns and find the postion of the given section
1743 // name in the output section. If the section name matches a glob
1744 // pattern and a non-glob name, then the non-glob position takes
1745 // precedence. Return 0 if no match is found.
1746
1747 unsigned int
1748 Layout::find_section_order_index(const std::string& section_name)
1749 {
1750 Unordered_map<std::string, unsigned int>::iterator map_it;
1751 map_it = this->input_section_position_.find(section_name);
1752 if (map_it != this->input_section_position_.end())
1753 return map_it->second;
1754
1755 // Absolute match failed. Linear search the glob patterns.
1756 std::vector<std::string>::iterator it;
1757 for (it = this->input_section_glob_.begin();
1758 it != this->input_section_glob_.end();
1759 ++it)
1760 {
1761 if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
1762 {
1763 map_it = this->input_section_position_.find(*it);
1764 gold_assert(map_it != this->input_section_position_.end());
1765 return map_it->second;
1766 }
1767 }
1768 return 0;
1769 }
1770
1771 // Read the sequence of input sections from the file specified with
1772 // --section-ordering-file.
1773
1774 void
1775 Layout::read_layout_from_file()
1776 {
1777 const char* filename = parameters->options().section_ordering_file();
1778 std::ifstream in;
1779 std::string line;
1780
1781 in.open(filename);
1782 if (!in)
1783 gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
1784 filename, strerror(errno));
1785
1786 std::getline(in, line); // this chops off the trailing \n, if any
1787 unsigned int position = 1;
1788
1789 while (in)
1790 {
1791 if (!line.empty() && line[line.length() - 1] == '\r') // Windows
1792 line.resize(line.length() - 1);
1793 // Ignore comments, beginning with '#'
1794 if (line[0] == '#')
1795 {
1796 std::getline(in, line);
1797 continue;
1798 }
1799 this->input_section_position_[line] = position;
1800 // Store all glob patterns in a vector.
1801 if (is_wildcard_string(line.c_str()))
1802 this->input_section_glob_.push_back(line);
1803 position++;
1804 std::getline(in, line);
1805 }
1806 }
1807
1808 // Finalize the layout. When this is called, we have created all the
1809 // output sections and all the output segments which are based on
1810 // input sections. We have several things to do, and we have to do
1811 // them in the right order, so that we get the right results correctly
1812 // and efficiently.
1813
1814 // 1) Finalize the list of output segments and create the segment
1815 // table header.
1816
1817 // 2) Finalize the dynamic symbol table and associated sections.
1818
1819 // 3) Determine the final file offset of all the output segments.
1820
1821 // 4) Determine the final file offset of all the SHF_ALLOC output
1822 // sections.
1823
1824 // 5) Create the symbol table sections and the section name table
1825 // section.
1826
1827 // 6) Finalize the symbol table: set symbol values to their final
1828 // value and make a final determination of which symbols are going
1829 // into the output symbol table.
1830
1831 // 7) Create the section table header.
1832
1833 // 8) Determine the final file offset of all the output sections which
1834 // are not SHF_ALLOC, including the section table header.
1835
1836 // 9) Finalize the ELF file header.
1837
1838 // This function returns the size of the output file.
1839
1840 off_t
1841 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
1842 Target* target, const Task* task)
1843 {
1844 target->finalize_sections(this, input_objects, symtab);
1845
1846 this->count_local_symbols(task, input_objects);
1847
1848 this->link_stabs_sections();
1849
1850 Output_segment* phdr_seg = NULL;
1851 if (!parameters->options().relocatable() && !parameters->doing_static_link())
1852 {
1853 // There was a dynamic object in the link. We need to create
1854 // some information for the dynamic linker.
1855
1856 // Create the PT_PHDR segment which will hold the program
1857 // headers.
1858 if (!this->script_options_->saw_phdrs_clause())
1859 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
1860
1861 // Create the dynamic symbol table, including the hash table.
1862 Output_section* dynstr;
1863 std::vector<Symbol*> dynamic_symbols;
1864 unsigned int local_dynamic_count;
1865 Versions versions(*this->script_options()->version_script_info(),
1866 &this->dynpool_);
1867 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
1868 &local_dynamic_count, &dynamic_symbols,
1869 &versions);
1870
1871 // Create the .interp section to hold the name of the
1872 // interpreter, and put it in a PT_INTERP segment.
1873 if (!parameters->options().shared())
1874 this->create_interp(target);
1875
1876 // Finish the .dynamic section to hold the dynamic data, and put
1877 // it in a PT_DYNAMIC segment.
1878 this->finish_dynamic_section(input_objects, symtab);
1879
1880 // We should have added everything we need to the dynamic string
1881 // table.
1882 this->dynpool_.set_string_offsets();
1883
1884 // Create the version sections. We can't do this until the
1885 // dynamic string table is complete.
1886 this->create_version_sections(&versions, symtab, local_dynamic_count,
1887 dynamic_symbols, dynstr);
1888
1889 // Set the size of the _DYNAMIC symbol. We can't do this until
1890 // after we call create_version_sections.
1891 this->set_dynamic_symbol_size(symtab);
1892 }
1893
1894 // Create segment headers.
1895 Output_segment_headers* segment_headers =
1896 (parameters->options().relocatable()
1897 ? NULL
1898 : new Output_segment_headers(this->segment_list_));
1899
1900 // Lay out the file header.
1901 Output_file_header* file_header
1902 = new Output_file_header(target, symtab, segment_headers,
1903 parameters->options().entry());
1904
1905 this->special_output_list_.push_back(file_header);
1906 if (segment_headers != NULL)
1907 this->special_output_list_.push_back(segment_headers);
1908
1909 // Find approriate places for orphan output sections if we are using
1910 // a linker script.
1911 if (this->script_options_->saw_sections_clause())
1912 this->place_orphan_sections_in_script();
1913
1914 Output_segment* load_seg;
1915 off_t off;
1916 unsigned int shndx;
1917 int pass = 0;
1918
1919 // Take a snapshot of the section layout as needed.
1920 if (target->may_relax())
1921 this->prepare_for_relaxation();
1922
1923 // Run the relaxation loop to lay out sections.
1924 do
1925 {
1926 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
1927 phdr_seg, segment_headers, file_header,
1928 &shndx);
1929 pass++;
1930 }
1931 while (target->may_relax()
1932 && target->relax(pass, input_objects, symtab, this));
1933
1934 // Set the file offsets of all the non-data sections we've seen so
1935 // far which don't have to wait for the input sections. We need
1936 // this in order to finalize local symbols in non-allocated
1937 // sections.
1938 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1939
1940 // Set the section indexes of all unallocated sections seen so far,
1941 // in case any of them are somehow referenced by a symbol.
1942 shndx = this->set_section_indexes(shndx);
1943
1944 // Create the symbol table sections.
1945 this->create_symtab_sections(input_objects, symtab, shndx, &off);
1946 if (!parameters->doing_static_link())
1947 this->assign_local_dynsym_offsets(input_objects);
1948
1949 // Process any symbol assignments from a linker script. This must
1950 // be called after the symbol table has been finalized.
1951 this->script_options_->finalize_symbols(symtab, this);
1952
1953 // Create the incremental inputs sections.
1954 if (this->incremental_inputs_)
1955 {
1956 this->incremental_inputs_->finalize();
1957 this->create_incremental_info_sections(symtab);
1958 }
1959
1960 // Create the .shstrtab section.
1961 Output_section* shstrtab_section = this->create_shstrtab();
1962
1963 // Set the file offsets of the rest of the non-data sections which
1964 // don't have to wait for the input sections.
1965 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
1966
1967 // Now that all sections have been created, set the section indexes
1968 // for any sections which haven't been done yet.
1969 shndx = this->set_section_indexes(shndx);
1970
1971 // Create the section table header.
1972 this->create_shdrs(shstrtab_section, &off);
1973
1974 // If there are no sections which require postprocessing, we can
1975 // handle the section names now, and avoid a resize later.
1976 if (!this->any_postprocessing_sections_)
1977 {
1978 off = this->set_section_offsets(off,
1979 POSTPROCESSING_SECTIONS_PASS);
1980 off =
1981 this->set_section_offsets(off,
1982 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
1983 }
1984
1985 file_header->set_section_info(this->section_headers_, shstrtab_section);
1986
1987 // Now we know exactly where everything goes in the output file
1988 // (except for non-allocated sections which require postprocessing).
1989 Output_data::layout_complete();
1990
1991 this->output_file_size_ = off;
1992
1993 return off;
1994 }
1995
1996 // Create a note header following the format defined in the ELF ABI.
1997 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
1998 // of the section to create, DESCSZ is the size of the descriptor.
1999 // ALLOCATE is true if the section should be allocated in memory.
2000 // This returns the new note section. It sets *TRAILING_PADDING to
2001 // the number of trailing zero bytes required.
2002
2003 Output_section*
2004 Layout::create_note(const char* name, int note_type,
2005 const char* section_name, size_t descsz,
2006 bool allocate, size_t* trailing_padding)
2007 {
2008 // Authorities all agree that the values in a .note field should
2009 // be aligned on 4-byte boundaries for 32-bit binaries. However,
2010 // they differ on what the alignment is for 64-bit binaries.
2011 // The GABI says unambiguously they take 8-byte alignment:
2012 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
2013 // Other documentation says alignment should always be 4 bytes:
2014 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
2015 // GNU ld and GNU readelf both support the latter (at least as of
2016 // version 2.16.91), and glibc always generates the latter for
2017 // .note.ABI-tag (as of version 1.6), so that's the one we go with
2018 // here.
2019 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
2020 const int size = parameters->target().get_size();
2021 #else
2022 const int size = 32;
2023 #endif
2024
2025 // The contents of the .note section.
2026 size_t namesz = strlen(name) + 1;
2027 size_t aligned_namesz = align_address(namesz, size / 8);
2028 size_t aligned_descsz = align_address(descsz, size / 8);
2029
2030 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
2031
2032 unsigned char* buffer = new unsigned char[notehdrsz];
2033 memset(buffer, 0, notehdrsz);
2034
2035 bool is_big_endian = parameters->target().is_big_endian();
2036
2037 if (size == 32)
2038 {
2039 if (!is_big_endian)
2040 {
2041 elfcpp::Swap<32, false>::writeval(buffer, namesz);
2042 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
2043 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
2044 }
2045 else
2046 {
2047 elfcpp::Swap<32, true>::writeval(buffer, namesz);
2048 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
2049 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
2050 }
2051 }
2052 else if (size == 64)
2053 {
2054 if (!is_big_endian)
2055 {
2056 elfcpp::Swap<64, false>::writeval(buffer, namesz);
2057 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
2058 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
2059 }
2060 else
2061 {
2062 elfcpp::Swap<64, true>::writeval(buffer, namesz);
2063 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
2064 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
2065 }
2066 }
2067 else
2068 gold_unreachable();
2069
2070 memcpy(buffer + 3 * (size / 8), name, namesz);
2071
2072 elfcpp::Elf_Xword flags = 0;
2073 Output_section_order order = ORDER_INVALID;
2074 if (allocate)
2075 {
2076 flags = elfcpp::SHF_ALLOC;
2077 order = ORDER_RO_NOTE;
2078 }
2079 Output_section* os = this->choose_output_section(NULL, section_name,
2080 elfcpp::SHT_NOTE,
2081 flags, false, order, false);
2082 if (os == NULL)
2083 return NULL;
2084
2085 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
2086 size / 8,
2087 "** note header");
2088 os->add_output_section_data(posd);
2089
2090 *trailing_padding = aligned_descsz - descsz;
2091
2092 return os;
2093 }
2094
2095 // For an executable or shared library, create a note to record the
2096 // version of gold used to create the binary.
2097
2098 void
2099 Layout::create_gold_note()
2100 {
2101 if (parameters->options().relocatable())
2102 return;
2103
2104 std::string desc = std::string("gold ") + gold::get_version_string();
2105
2106 size_t trailing_padding;
2107 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
2108 ".note.gnu.gold-version", desc.size(),
2109 false, &trailing_padding);
2110 if (os == NULL)
2111 return;
2112
2113 Output_section_data* posd = new Output_data_const(desc, 4);
2114 os->add_output_section_data(posd);
2115
2116 if (trailing_padding > 0)
2117 {
2118 posd = new Output_data_zero_fill(trailing_padding, 0);
2119 os->add_output_section_data(posd);
2120 }
2121 }
2122
2123 // Record whether the stack should be executable. This can be set
2124 // from the command line using the -z execstack or -z noexecstack
2125 // options. Otherwise, if any input file has a .note.GNU-stack
2126 // section with the SHF_EXECINSTR flag set, the stack should be
2127 // executable. Otherwise, if at least one input file a
2128 // .note.GNU-stack section, and some input file has no .note.GNU-stack
2129 // section, we use the target default for whether the stack should be
2130 // executable. Otherwise, we don't generate a stack note. When
2131 // generating a object file, we create a .note.GNU-stack section with
2132 // the appropriate marking. When generating an executable or shared
2133 // library, we create a PT_GNU_STACK segment.
2134
2135 void
2136 Layout::create_executable_stack_info()
2137 {
2138 bool is_stack_executable;
2139 if (parameters->options().is_execstack_set())
2140 is_stack_executable = parameters->options().is_stack_executable();
2141 else if (!this->input_with_gnu_stack_note_)
2142 return;
2143 else
2144 {
2145 if (this->input_requires_executable_stack_)
2146 is_stack_executable = true;
2147 else if (this->input_without_gnu_stack_note_)
2148 is_stack_executable =
2149 parameters->target().is_default_stack_executable();
2150 else
2151 is_stack_executable = false;
2152 }
2153
2154 if (parameters->options().relocatable())
2155 {
2156 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
2157 elfcpp::Elf_Xword flags = 0;
2158 if (is_stack_executable)
2159 flags |= elfcpp::SHF_EXECINSTR;
2160 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags,
2161 ORDER_INVALID, false);
2162 }
2163 else
2164 {
2165 if (this->script_options_->saw_phdrs_clause())
2166 return;
2167 int flags = elfcpp::PF_R | elfcpp::PF_W;
2168 if (is_stack_executable)
2169 flags |= elfcpp::PF_X;
2170 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
2171 }
2172 }
2173
2174 // If --build-id was used, set up the build ID note.
2175
2176 void
2177 Layout::create_build_id()
2178 {
2179 if (!parameters->options().user_set_build_id())
2180 return;
2181
2182 const char* style = parameters->options().build_id();
2183 if (strcmp(style, "none") == 0)
2184 return;
2185
2186 // Set DESCSZ to the size of the note descriptor. When possible,
2187 // set DESC to the note descriptor contents.
2188 size_t descsz;
2189 std::string desc;
2190 if (strcmp(style, "md5") == 0)
2191 descsz = 128 / 8;
2192 else if (strcmp(style, "sha1") == 0)
2193 descsz = 160 / 8;
2194 else if (strcmp(style, "uuid") == 0)
2195 {
2196 const size_t uuidsz = 128 / 8;
2197
2198 char buffer[uuidsz];
2199 memset(buffer, 0, uuidsz);
2200
2201 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
2202 if (descriptor < 0)
2203 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
2204 strerror(errno));
2205 else
2206 {
2207 ssize_t got = ::read(descriptor, buffer, uuidsz);
2208 release_descriptor(descriptor, true);
2209 if (got < 0)
2210 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
2211 else if (static_cast<size_t>(got) != uuidsz)
2212 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
2213 uuidsz, got);
2214 }
2215
2216 desc.assign(buffer, uuidsz);
2217 descsz = uuidsz;
2218 }
2219 else if (strncmp(style, "0x", 2) == 0)
2220 {
2221 hex_init();
2222 const char* p = style + 2;
2223 while (*p != '\0')
2224 {
2225 if (hex_p(p[0]) && hex_p(p[1]))
2226 {
2227 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
2228 desc += c;
2229 p += 2;
2230 }
2231 else if (*p == '-' || *p == ':')
2232 ++p;
2233 else
2234 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
2235 style);
2236 }
2237 descsz = desc.size();
2238 }
2239 else
2240 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
2241
2242 // Create the note.
2243 size_t trailing_padding;
2244 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
2245 ".note.gnu.build-id", descsz, true,
2246 &trailing_padding);
2247 if (os == NULL)
2248 return;
2249
2250 if (!desc.empty())
2251 {
2252 // We know the value already, so we fill it in now.
2253 gold_assert(desc.size() == descsz);
2254
2255 Output_section_data* posd = new Output_data_const(desc, 4);
2256 os->add_output_section_data(posd);
2257
2258 if (trailing_padding != 0)
2259 {
2260 posd = new Output_data_zero_fill(trailing_padding, 0);
2261 os->add_output_section_data(posd);
2262 }
2263 }
2264 else
2265 {
2266 // We need to compute a checksum after we have completed the
2267 // link.
2268 gold_assert(trailing_padding == 0);
2269 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
2270 os->add_output_section_data(this->build_id_note_);
2271 }
2272 }
2273
2274 // If we have both .stabXX and .stabXXstr sections, then the sh_link
2275 // field of the former should point to the latter. I'm not sure who
2276 // started this, but the GNU linker does it, and some tools depend
2277 // upon it.
2278
2279 void
2280 Layout::link_stabs_sections()
2281 {
2282 if (!this->have_stabstr_section_)
2283 return;
2284
2285 for (Section_list::iterator p = this->section_list_.begin();
2286 p != this->section_list_.end();
2287 ++p)
2288 {
2289 if ((*p)->type() != elfcpp::SHT_STRTAB)
2290 continue;
2291
2292 const char* name = (*p)->name();
2293 if (strncmp(name, ".stab", 5) != 0)
2294 continue;
2295
2296 size_t len = strlen(name);
2297 if (strcmp(name + len - 3, "str") != 0)
2298 continue;
2299
2300 std::string stab_name(name, len - 3);
2301 Output_section* stab_sec;
2302 stab_sec = this->find_output_section(stab_name.c_str());
2303 if (stab_sec != NULL)
2304 stab_sec->set_link_section(*p);
2305 }
2306 }
2307
2308 // Create .gnu_incremental_inputs and related sections needed
2309 // for the next run of incremental linking to check what has changed.
2310
2311 void
2312 Layout::create_incremental_info_sections(Symbol_table* symtab)
2313 {
2314 Incremental_inputs* incr = this->incremental_inputs_;
2315
2316 gold_assert(incr != NULL);
2317
2318 // Create the .gnu_incremental_inputs, _symtab, and _relocs input sections.
2319 incr->create_data_sections(symtab);
2320
2321 // Add the .gnu_incremental_inputs section.
2322 const char* incremental_inputs_name =
2323 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
2324 Output_section* incremental_inputs_os =
2325 this->make_output_section(incremental_inputs_name,
2326 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
2327 ORDER_INVALID, false);
2328 incremental_inputs_os->add_output_section_data(incr->inputs_section());
2329
2330 // Add the .gnu_incremental_symtab section.
2331 const char* incremental_symtab_name =
2332 this->namepool_.add(".gnu_incremental_symtab", false, NULL);
2333 Output_section* incremental_symtab_os =
2334 this->make_output_section(incremental_symtab_name,
2335 elfcpp::SHT_GNU_INCREMENTAL_SYMTAB, 0,
2336 ORDER_INVALID, false);
2337 incremental_symtab_os->add_output_section_data(incr->symtab_section());
2338 incremental_symtab_os->set_entsize(4);
2339
2340 // Add the .gnu_incremental_relocs section.
2341 const char* incremental_relocs_name =
2342 this->namepool_.add(".gnu_incremental_relocs", false, NULL);
2343 Output_section* incremental_relocs_os =
2344 this->make_output_section(incremental_relocs_name,
2345 elfcpp::SHT_GNU_INCREMENTAL_RELOCS, 0,
2346 ORDER_INVALID, false);
2347 incremental_relocs_os->add_output_section_data(incr->relocs_section());
2348 incremental_relocs_os->set_entsize(incr->relocs_entsize());
2349
2350 // Add the .gnu_incremental_got_plt section.
2351 const char* incremental_got_plt_name =
2352 this->namepool_.add(".gnu_incremental_got_plt", false, NULL);
2353 Output_section* incremental_got_plt_os =
2354 this->make_output_section(incremental_got_plt_name,
2355 elfcpp::SHT_GNU_INCREMENTAL_GOT_PLT, 0,
2356 ORDER_INVALID, false);
2357 incremental_got_plt_os->add_output_section_data(incr->got_plt_section());
2358
2359 // Add the .gnu_incremental_strtab section.
2360 const char* incremental_strtab_name =
2361 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
2362 Output_section* incremental_strtab_os = this->make_output_section(incremental_strtab_name,
2363 elfcpp::SHT_STRTAB, 0,
2364 ORDER_INVALID, false);
2365 Output_data_strtab* strtab_data =
2366 new Output_data_strtab(incr->get_stringpool());
2367 incremental_strtab_os->add_output_section_data(strtab_data);
2368
2369 incremental_inputs_os->set_after_input_sections();
2370 incremental_symtab_os->set_after_input_sections();
2371 incremental_relocs_os->set_after_input_sections();
2372 incremental_got_plt_os->set_after_input_sections();
2373
2374 incremental_inputs_os->set_link_section(incremental_strtab_os);
2375 incremental_symtab_os->set_link_section(incremental_inputs_os);
2376 incremental_relocs_os->set_link_section(incremental_inputs_os);
2377 incremental_got_plt_os->set_link_section(incremental_inputs_os);
2378 }
2379
2380 // Return whether SEG1 should be before SEG2 in the output file. This
2381 // is based entirely on the segment type and flags. When this is
2382 // called the segment addresses has normally not yet been set.
2383
2384 bool
2385 Layout::segment_precedes(const Output_segment* seg1,
2386 const Output_segment* seg2)
2387 {
2388 elfcpp::Elf_Word type1 = seg1->type();
2389 elfcpp::Elf_Word type2 = seg2->type();
2390
2391 // The single PT_PHDR segment is required to precede any loadable
2392 // segment. We simply make it always first.
2393 if (type1 == elfcpp::PT_PHDR)
2394 {
2395 gold_assert(type2 != elfcpp::PT_PHDR);
2396 return true;
2397 }
2398 if (type2 == elfcpp::PT_PHDR)
2399 return false;
2400
2401 // The single PT_INTERP segment is required to precede any loadable
2402 // segment. We simply make it always second.
2403 if (type1 == elfcpp::PT_INTERP)
2404 {
2405 gold_assert(type2 != elfcpp::PT_INTERP);
2406 return true;
2407 }
2408 if (type2 == elfcpp::PT_INTERP)
2409 return false;
2410
2411 // We then put PT_LOAD segments before any other segments.
2412 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
2413 return true;
2414 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
2415 return false;
2416
2417 // We put the PT_TLS segment last except for the PT_GNU_RELRO
2418 // segment, because that is where the dynamic linker expects to find
2419 // it (this is just for efficiency; other positions would also work
2420 // correctly).
2421 if (type1 == elfcpp::PT_TLS
2422 && type2 != elfcpp::PT_TLS
2423 && type2 != elfcpp::PT_GNU_RELRO)
2424 return false;
2425 if (type2 == elfcpp::PT_TLS
2426 && type1 != elfcpp::PT_TLS
2427 && type1 != elfcpp::PT_GNU_RELRO)
2428 return true;
2429
2430 // We put the PT_GNU_RELRO segment last, because that is where the
2431 // dynamic linker expects to find it (as with PT_TLS, this is just
2432 // for efficiency).
2433 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
2434 return false;
2435 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
2436 return true;
2437
2438 const elfcpp::Elf_Word flags1 = seg1->flags();
2439 const elfcpp::Elf_Word flags2 = seg2->flags();
2440
2441 // The order of non-PT_LOAD segments is unimportant. We simply sort
2442 // by the numeric segment type and flags values. There should not
2443 // be more than one segment with the same type and flags.
2444 if (type1 != elfcpp::PT_LOAD)
2445 {
2446 if (type1 != type2)
2447 return type1 < type2;
2448 gold_assert(flags1 != flags2);
2449 return flags1 < flags2;
2450 }
2451
2452 // If the addresses are set already, sort by load address.
2453 if (seg1->are_addresses_set())
2454 {
2455 if (!seg2->are_addresses_set())
2456 return true;
2457
2458 unsigned int section_count1 = seg1->output_section_count();
2459 unsigned int section_count2 = seg2->output_section_count();
2460 if (section_count1 == 0 && section_count2 > 0)
2461 return true;
2462 if (section_count1 > 0 && section_count2 == 0)
2463 return false;
2464
2465 uint64_t paddr1 = (seg1->are_addresses_set()
2466 ? seg1->paddr()
2467 : seg1->first_section_load_address());
2468 uint64_t paddr2 = (seg2->are_addresses_set()
2469 ? seg2->paddr()
2470 : seg2->first_section_load_address());
2471
2472 if (paddr1 != paddr2)
2473 return paddr1 < paddr2;
2474 }
2475 else if (seg2->are_addresses_set())
2476 return false;
2477
2478 // A segment which holds large data comes after a segment which does
2479 // not hold large data.
2480 if (seg1->is_large_data_segment())
2481 {
2482 if (!seg2->is_large_data_segment())
2483 return false;
2484 }
2485 else if (seg2->is_large_data_segment())
2486 return true;
2487
2488 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
2489 // segments come before writable segments. Then writable segments
2490 // with data come before writable segments without data. Then
2491 // executable segments come before non-executable segments. Then
2492 // the unlikely case of a non-readable segment comes before the
2493 // normal case of a readable segment. If there are multiple
2494 // segments with the same type and flags, we require that the
2495 // address be set, and we sort by virtual address and then physical
2496 // address.
2497 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
2498 return (flags1 & elfcpp::PF_W) == 0;
2499 if ((flags1 & elfcpp::PF_W) != 0
2500 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
2501 return seg1->has_any_data_sections();
2502 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
2503 return (flags1 & elfcpp::PF_X) != 0;
2504 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
2505 return (flags1 & elfcpp::PF_R) == 0;
2506
2507 // We shouldn't get here--we shouldn't create segments which we
2508 // can't distinguish.
2509 gold_unreachable();
2510 }
2511
2512 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
2513
2514 static off_t
2515 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
2516 {
2517 uint64_t unsigned_off = off;
2518 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
2519 | (addr & (abi_pagesize - 1)));
2520 if (aligned_off < unsigned_off)
2521 aligned_off += abi_pagesize;
2522 return aligned_off;
2523 }
2524
2525 // Set the file offsets of all the segments, and all the sections they
2526 // contain. They have all been created. LOAD_SEG must be be laid out
2527 // first. Return the offset of the data to follow.
2528
2529 off_t
2530 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
2531 unsigned int* pshndx)
2532 {
2533 // Sort them into the final order.
2534 std::sort(this->segment_list_.begin(), this->segment_list_.end(),
2535 Layout::Compare_segments());
2536
2537 // Find the PT_LOAD segments, and set their addresses and offsets
2538 // and their section's addresses and offsets.
2539 uint64_t addr;
2540 if (parameters->options().user_set_Ttext())
2541 addr = parameters->options().Ttext();
2542 else if (parameters->options().output_is_position_independent())
2543 addr = 0;
2544 else
2545 addr = target->default_text_segment_address();
2546 off_t off = 0;
2547
2548 // If LOAD_SEG is NULL, then the file header and segment headers
2549 // will not be loadable. But they still need to be at offset 0 in
2550 // the file. Set their offsets now.
2551 if (load_seg == NULL)
2552 {
2553 for (Data_list::iterator p = this->special_output_list_.begin();
2554 p != this->special_output_list_.end();
2555 ++p)
2556 {
2557 off = align_address(off, (*p)->addralign());
2558 (*p)->set_address_and_file_offset(0, off);
2559 off += (*p)->data_size();
2560 }
2561 }
2562
2563 unsigned int increase_relro = this->increase_relro_;
2564 if (this->script_options_->saw_sections_clause())
2565 increase_relro = 0;
2566
2567 const bool check_sections = parameters->options().check_sections();
2568 Output_segment* last_load_segment = NULL;
2569
2570 bool was_readonly = false;
2571 for (Segment_list::iterator p = this->segment_list_.begin();
2572 p != this->segment_list_.end();
2573 ++p)
2574 {
2575 if ((*p)->type() == elfcpp::PT_LOAD)
2576 {
2577 if (load_seg != NULL && load_seg != *p)
2578 gold_unreachable();
2579 load_seg = NULL;
2580
2581 bool are_addresses_set = (*p)->are_addresses_set();
2582 if (are_addresses_set)
2583 {
2584 // When it comes to setting file offsets, we care about
2585 // the physical address.
2586 addr = (*p)->paddr();
2587 }
2588 else if (parameters->options().user_set_Tdata()
2589 && ((*p)->flags() & elfcpp::PF_W) != 0
2590 && (!parameters->options().user_set_Tbss()
2591 || (*p)->has_any_data_sections()))
2592 {
2593 addr = parameters->options().Tdata();
2594 are_addresses_set = true;
2595 }
2596 else if (parameters->options().user_set_Tbss()
2597 && ((*p)->flags() & elfcpp::PF_W) != 0
2598 && !(*p)->has_any_data_sections())
2599 {
2600 addr = parameters->options().Tbss();
2601 are_addresses_set = true;
2602 }
2603
2604 uint64_t orig_addr = addr;
2605 uint64_t orig_off = off;
2606
2607 uint64_t aligned_addr = 0;
2608 uint64_t abi_pagesize = target->abi_pagesize();
2609 uint64_t common_pagesize = target->common_pagesize();
2610
2611 if (!parameters->options().nmagic()
2612 && !parameters->options().omagic())
2613 (*p)->set_minimum_p_align(common_pagesize);
2614
2615 if (!are_addresses_set)
2616 {
2617 // If the last segment was readonly, and this one is
2618 // not, then skip the address forward one page,
2619 // maintaining the same position within the page. This
2620 // lets us store both segments overlapping on a single
2621 // page in the file, but the loader will put them on
2622 // different pages in memory.
2623
2624 addr = align_address(addr, (*p)->maximum_alignment());
2625 aligned_addr = addr;
2626
2627 if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
2628 {
2629 if ((addr & (abi_pagesize - 1)) != 0)
2630 addr = addr + abi_pagesize;
2631 }
2632
2633 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2634 }
2635
2636 if (!parameters->options().nmagic()
2637 && !parameters->options().omagic())
2638 off = align_file_offset(off, addr, abi_pagesize);
2639 else if (load_seg == NULL)
2640 {
2641 // This is -N or -n with a section script which prevents
2642 // us from using a load segment. We need to ensure that
2643 // the file offset is aligned to the alignment of the
2644 // segment. This is because the linker script
2645 // implicitly assumed a zero offset. If we don't align
2646 // here, then the alignment of the sections in the
2647 // linker script may not match the alignment of the
2648 // sections in the set_section_addresses call below,
2649 // causing an error about dot moving backward.
2650 off = align_address(off, (*p)->maximum_alignment());
2651 }
2652
2653 unsigned int shndx_hold = *pshndx;
2654 uint64_t new_addr = (*p)->set_section_addresses(this, false, addr,
2655 increase_relro,
2656 &off, pshndx);
2657
2658 // Now that we know the size of this segment, we may be able
2659 // to save a page in memory, at the cost of wasting some
2660 // file space, by instead aligning to the start of a new
2661 // page. Here we use the real machine page size rather than
2662 // the ABI mandated page size.
2663
2664 if (!are_addresses_set && aligned_addr != addr)
2665 {
2666 uint64_t first_off = (common_pagesize
2667 - (aligned_addr
2668 & (common_pagesize - 1)));
2669 uint64_t last_off = new_addr & (common_pagesize - 1);
2670 if (first_off > 0
2671 && last_off > 0
2672 && ((aligned_addr & ~ (common_pagesize - 1))
2673 != (new_addr & ~ (common_pagesize - 1)))
2674 && first_off + last_off <= common_pagesize)
2675 {
2676 *pshndx = shndx_hold;
2677 addr = align_address(aligned_addr, common_pagesize);
2678 addr = align_address(addr, (*p)->maximum_alignment());
2679 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
2680 off = align_file_offset(off, addr, abi_pagesize);
2681 new_addr = (*p)->set_section_addresses(this, true, addr,
2682 increase_relro,
2683 &off, pshndx);
2684 }
2685 }
2686
2687 addr = new_addr;
2688
2689 if (((*p)->flags() & elfcpp::PF_W) == 0)
2690 was_readonly = true;
2691
2692 // Implement --check-sections. We know that the segments
2693 // are sorted by LMA.
2694 if (check_sections && last_load_segment != NULL)
2695 {
2696 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
2697 if (last_load_segment->paddr() + last_load_segment->memsz()
2698 > (*p)->paddr())
2699 {
2700 unsigned long long lb1 = last_load_segment->paddr();
2701 unsigned long long le1 = lb1 + last_load_segment->memsz();
2702 unsigned long long lb2 = (*p)->paddr();
2703 unsigned long long le2 = lb2 + (*p)->memsz();
2704 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
2705 "[0x%llx -> 0x%llx]"),
2706 lb1, le1, lb2, le2);
2707 }
2708 }
2709 last_load_segment = *p;
2710 }
2711 }
2712
2713 // Handle the non-PT_LOAD segments, setting their offsets from their
2714 // section's offsets.
2715 for (Segment_list::iterator p = this->segment_list_.begin();
2716 p != this->segment_list_.end();
2717 ++p)
2718 {
2719 if ((*p)->type() != elfcpp::PT_LOAD)
2720 (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
2721 ? increase_relro
2722 : 0);
2723 }
2724
2725 // Set the TLS offsets for each section in the PT_TLS segment.
2726 if (this->tls_segment_ != NULL)
2727 this->tls_segment_->set_tls_offsets();
2728
2729 return off;
2730 }
2731
2732 // Set the offsets of all the allocated sections when doing a
2733 // relocatable link. This does the same jobs as set_segment_offsets,
2734 // only for a relocatable link.
2735
2736 off_t
2737 Layout::set_relocatable_section_offsets(Output_data* file_header,
2738 unsigned int* pshndx)
2739 {
2740 off_t off = 0;
2741
2742 file_header->set_address_and_file_offset(0, 0);
2743 off += file_header->data_size();
2744
2745 for (Section_list::iterator p = this->section_list_.begin();
2746 p != this->section_list_.end();
2747 ++p)
2748 {
2749 // We skip unallocated sections here, except that group sections
2750 // have to come first.
2751 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
2752 && (*p)->type() != elfcpp::SHT_GROUP)
2753 continue;
2754
2755 off = align_address(off, (*p)->addralign());
2756
2757 // The linker script might have set the address.
2758 if (!(*p)->is_address_valid())
2759 (*p)->set_address(0);
2760 (*p)->set_file_offset(off);
2761 (*p)->finalize_data_size();
2762 off += (*p)->data_size();
2763
2764 (*p)->set_out_shndx(*pshndx);
2765 ++*pshndx;
2766 }
2767
2768 return off;
2769 }
2770
2771 // Set the file offset of all the sections not associated with a
2772 // segment.
2773
2774 off_t
2775 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
2776 {
2777 for (Section_list::iterator p = this->unattached_section_list_.begin();
2778 p != this->unattached_section_list_.end();
2779 ++p)
2780 {
2781 // The symtab section is handled in create_symtab_sections.
2782 if (*p == this->symtab_section_)
2783 continue;
2784
2785 // If we've already set the data size, don't set it again.
2786 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
2787 continue;
2788
2789 if (pass == BEFORE_INPUT_SECTIONS_PASS
2790 && (*p)->requires_postprocessing())
2791 {
2792 (*p)->create_postprocessing_buffer();
2793 this->any_postprocessing_sections_ = true;
2794 }
2795
2796 if (pass == BEFORE_INPUT_SECTIONS_PASS
2797 && (*p)->after_input_sections())
2798 continue;
2799 else if (pass == POSTPROCESSING_SECTIONS_PASS
2800 && (!(*p)->after_input_sections()
2801 || (*p)->type() == elfcpp::SHT_STRTAB))
2802 continue;
2803 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
2804 && (!(*p)->after_input_sections()
2805 || (*p)->type() != elfcpp::SHT_STRTAB))
2806 continue;
2807
2808 off = align_address(off, (*p)->addralign());
2809 (*p)->set_file_offset(off);
2810 (*p)->finalize_data_size();
2811 off += (*p)->data_size();
2812
2813 // At this point the name must be set.
2814 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
2815 this->namepool_.add((*p)->name(), false, NULL);
2816 }
2817 return off;
2818 }
2819
2820 // Set the section indexes of all the sections not associated with a
2821 // segment.
2822
2823 unsigned int
2824 Layout::set_section_indexes(unsigned int shndx)
2825 {
2826 for (Section_list::iterator p = this->unattached_section_list_.begin();
2827 p != this->unattached_section_list_.end();
2828 ++p)
2829 {
2830 if (!(*p)->has_out_shndx())
2831 {
2832 (*p)->set_out_shndx(shndx);
2833 ++shndx;
2834 }
2835 }
2836 return shndx;
2837 }
2838
2839 // Set the section addresses according to the linker script. This is
2840 // only called when we see a SECTIONS clause. This returns the
2841 // program segment which should hold the file header and segment
2842 // headers, if any. It will return NULL if they should not be in a
2843 // segment.
2844
2845 Output_segment*
2846 Layout::set_section_addresses_from_script(Symbol_table* symtab)
2847 {
2848 Script_sections* ss = this->script_options_->script_sections();
2849 gold_assert(ss->saw_sections_clause());
2850 return this->script_options_->set_section_addresses(symtab, this);
2851 }
2852
2853 // Place the orphan sections in the linker script.
2854
2855 void
2856 Layout::place_orphan_sections_in_script()
2857 {
2858 Script_sections* ss = this->script_options_->script_sections();
2859 gold_assert(ss->saw_sections_clause());
2860
2861 // Place each orphaned output section in the script.
2862 for (Section_list::iterator p = this->section_list_.begin();
2863 p != this->section_list_.end();
2864 ++p)
2865 {
2866 if (!(*p)->found_in_sections_clause())
2867 ss->place_orphan(*p);
2868 }
2869 }
2870
2871 // Count the local symbols in the regular symbol table and the dynamic
2872 // symbol table, and build the respective string pools.
2873
2874 void
2875 Layout::count_local_symbols(const Task* task,
2876 const Input_objects* input_objects)
2877 {
2878 // First, figure out an upper bound on the number of symbols we'll
2879 // be inserting into each pool. This helps us create the pools with
2880 // the right size, to avoid unnecessary hashtable resizing.
2881 unsigned int symbol_count = 0;
2882 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2883 p != input_objects->relobj_end();
2884 ++p)
2885 symbol_count += (*p)->local_symbol_count();
2886
2887 // Go from "upper bound" to "estimate." We overcount for two
2888 // reasons: we double-count symbols that occur in more than one
2889 // object file, and we count symbols that are dropped from the
2890 // output. Add it all together and assume we overcount by 100%.
2891 symbol_count /= 2;
2892
2893 // We assume all symbols will go into both the sympool and dynpool.
2894 this->sympool_.reserve(symbol_count);
2895 this->dynpool_.reserve(symbol_count);
2896
2897 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2898 p != input_objects->relobj_end();
2899 ++p)
2900 {
2901 Task_lock_obj<Object> tlo(task, *p);
2902 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
2903 }
2904 }
2905
2906 // Create the symbol table sections. Here we also set the final
2907 // values of the symbols. At this point all the loadable sections are
2908 // fully laid out. SHNUM is the number of sections so far.
2909
2910 void
2911 Layout::create_symtab_sections(const Input_objects* input_objects,
2912 Symbol_table* symtab,
2913 unsigned int shnum,
2914 off_t* poff)
2915 {
2916 int symsize;
2917 unsigned int align;
2918 if (parameters->target().get_size() == 32)
2919 {
2920 symsize = elfcpp::Elf_sizes<32>::sym_size;
2921 align = 4;
2922 }
2923 else if (parameters->target().get_size() == 64)
2924 {
2925 symsize = elfcpp::Elf_sizes<64>::sym_size;
2926 align = 8;
2927 }
2928 else
2929 gold_unreachable();
2930
2931 off_t off = *poff;
2932 off = align_address(off, align);
2933 off_t startoff = off;
2934
2935 // Save space for the dummy symbol at the start of the section. We
2936 // never bother to write this out--it will just be left as zero.
2937 off += symsize;
2938 unsigned int local_symbol_index = 1;
2939
2940 // Add STT_SECTION symbols for each Output section which needs one.
2941 for (Section_list::iterator p = this->section_list_.begin();
2942 p != this->section_list_.end();
2943 ++p)
2944 {
2945 if (!(*p)->needs_symtab_index())
2946 (*p)->set_symtab_index(-1U);
2947 else
2948 {
2949 (*p)->set_symtab_index(local_symbol_index);
2950 ++local_symbol_index;
2951 off += symsize;
2952 }
2953 }
2954
2955 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
2956 p != input_objects->relobj_end();
2957 ++p)
2958 {
2959 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
2960 off, symtab);
2961 off += (index - local_symbol_index) * symsize;
2962 local_symbol_index = index;
2963 }
2964
2965 unsigned int local_symcount = local_symbol_index;
2966 gold_assert(static_cast<off_t>(local_symcount * symsize) == off - startoff);
2967
2968 off_t dynoff;
2969 size_t dyn_global_index;
2970 size_t dyncount;
2971 if (this->dynsym_section_ == NULL)
2972 {
2973 dynoff = 0;
2974 dyn_global_index = 0;
2975 dyncount = 0;
2976 }
2977 else
2978 {
2979 dyn_global_index = this->dynsym_section_->info();
2980 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
2981 dynoff = this->dynsym_section_->offset() + locsize;
2982 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
2983 gold_assert(static_cast<off_t>(dyncount * symsize)
2984 == this->dynsym_section_->data_size() - locsize);
2985 }
2986
2987 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
2988 &this->sympool_, &local_symcount);
2989
2990 if (!parameters->options().strip_all())
2991 {
2992 this->sympool_.set_string_offsets();
2993
2994 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
2995 Output_section* osymtab = this->make_output_section(symtab_name,
2996 elfcpp::SHT_SYMTAB,
2997 0, ORDER_INVALID,
2998 false);
2999 this->symtab_section_ = osymtab;
3000
3001 Output_section_data* pos = new Output_data_fixed_space(off - startoff,
3002 align,
3003 "** symtab");
3004 osymtab->add_output_section_data(pos);
3005
3006 // We generate a .symtab_shndx section if we have more than
3007 // SHN_LORESERVE sections. Technically it is possible that we
3008 // don't need one, because it is possible that there are no
3009 // symbols in any of sections with indexes larger than
3010 // SHN_LORESERVE. That is probably unusual, though, and it is
3011 // easier to always create one than to compute section indexes
3012 // twice (once here, once when writing out the symbols).
3013 if (shnum >= elfcpp::SHN_LORESERVE)
3014 {
3015 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
3016 false, NULL);
3017 Output_section* osymtab_xindex =
3018 this->make_output_section(symtab_xindex_name,
3019 elfcpp::SHT_SYMTAB_SHNDX, 0,
3020 ORDER_INVALID, false);
3021
3022 size_t symcount = (off - startoff) / symsize;
3023 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
3024
3025 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
3026
3027 osymtab_xindex->set_link_section(osymtab);
3028 osymtab_xindex->set_addralign(4);
3029 osymtab_xindex->set_entsize(4);
3030
3031 osymtab_xindex->set_after_input_sections();
3032
3033 // This tells the driver code to wait until the symbol table
3034 // has written out before writing out the postprocessing
3035 // sections, including the .symtab_shndx section.
3036 this->any_postprocessing_sections_ = true;
3037 }
3038
3039 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
3040 Output_section* ostrtab = this->make_output_section(strtab_name,
3041 elfcpp::SHT_STRTAB,
3042 0, ORDER_INVALID,
3043 false);
3044
3045 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
3046 ostrtab->add_output_section_data(pstr);
3047
3048 osymtab->set_file_offset(startoff);
3049 osymtab->finalize_data_size();
3050 osymtab->set_link_section(ostrtab);
3051 osymtab->set_info(local_symcount);
3052 osymtab->set_entsize(symsize);
3053
3054 *poff = off;
3055 }
3056 }
3057
3058 // Create the .shstrtab section, which holds the names of the
3059 // sections. At the time this is called, we have created all the
3060 // output sections except .shstrtab itself.
3061
3062 Output_section*
3063 Layout::create_shstrtab()
3064 {
3065 // FIXME: We don't need to create a .shstrtab section if we are
3066 // stripping everything.
3067
3068 const char* name = this->namepool_.add(".shstrtab", false, NULL);
3069
3070 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
3071 ORDER_INVALID, false);
3072
3073 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
3074 {
3075 // We can't write out this section until we've set all the
3076 // section names, and we don't set the names of compressed
3077 // output sections until relocations are complete. FIXME: With
3078 // the current names we use, this is unnecessary.
3079 os->set_after_input_sections();
3080 }
3081
3082 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
3083 os->add_output_section_data(posd);
3084
3085 return os;
3086 }
3087
3088 // Create the section headers. SIZE is 32 or 64. OFF is the file
3089 // offset.
3090
3091 void
3092 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
3093 {
3094 Output_section_headers* oshdrs;
3095 oshdrs = new Output_section_headers(this,
3096 &this->segment_list_,
3097 &this->section_list_,
3098 &this->unattached_section_list_,
3099 &this->namepool_,
3100 shstrtab_section);
3101 off_t off = align_address(*poff, oshdrs->addralign());
3102 oshdrs->set_address_and_file_offset(0, off);
3103 off += oshdrs->data_size();
3104 *poff = off;
3105 this->section_headers_ = oshdrs;
3106 }
3107
3108 // Count the allocated sections.
3109
3110 size_t
3111 Layout::allocated_output_section_count() const
3112 {
3113 size_t section_count = 0;
3114 for (Segment_list::const_iterator p = this->segment_list_.begin();
3115 p != this->segment_list_.end();
3116 ++p)
3117 section_count += (*p)->output_section_count();
3118 return section_count;
3119 }
3120
3121 // Create the dynamic symbol table.
3122
3123 void
3124 Layout::create_dynamic_symtab(const Input_objects* input_objects,
3125 Symbol_table* symtab,
3126 Output_section** pdynstr,
3127 unsigned int* plocal_dynamic_count,
3128 std::vector<Symbol*>* pdynamic_symbols,
3129 Versions* pversions)
3130 {
3131 // Count all the symbols in the dynamic symbol table, and set the
3132 // dynamic symbol indexes.
3133
3134 // Skip symbol 0, which is always all zeroes.
3135 unsigned int index = 1;
3136
3137 // Add STT_SECTION symbols for each Output section which needs one.
3138 for (Section_list::iterator p = this->section_list_.begin();
3139 p != this->section_list_.end();
3140 ++p)
3141 {
3142 if (!(*p)->needs_dynsym_index())
3143 (*p)->set_dynsym_index(-1U);
3144 else
3145 {
3146 (*p)->set_dynsym_index(index);
3147 ++index;
3148 }
3149 }
3150
3151 // Count the local symbols that need to go in the dynamic symbol table,
3152 // and set the dynamic symbol indexes.
3153 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3154 p != input_objects->relobj_end();
3155 ++p)
3156 {
3157 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
3158 index = new_index;
3159 }
3160
3161 unsigned int local_symcount = index;
3162 *plocal_dynamic_count = local_symcount;
3163
3164 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
3165 &this->dynpool_, pversions);
3166
3167 int symsize;
3168 unsigned int align;
3169 const int size = parameters->target().get_size();
3170 if (size == 32)
3171 {
3172 symsize = elfcpp::Elf_sizes<32>::sym_size;
3173 align = 4;
3174 }
3175 else if (size == 64)
3176 {
3177 symsize = elfcpp::Elf_sizes<64>::sym_size;
3178 align = 8;
3179 }
3180 else
3181 gold_unreachable();
3182
3183 // Create the dynamic symbol table section.
3184
3185 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
3186 elfcpp::SHT_DYNSYM,
3187 elfcpp::SHF_ALLOC,
3188 false,
3189 ORDER_DYNAMIC_LINKER,
3190 false);
3191
3192 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
3193 align,
3194 "** dynsym");
3195 dynsym->add_output_section_data(odata);
3196
3197 dynsym->set_info(local_symcount);
3198 dynsym->set_entsize(symsize);
3199 dynsym->set_addralign(align);
3200
3201 this->dynsym_section_ = dynsym;
3202
3203 Output_data_dynamic* const odyn = this->dynamic_data_;
3204 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
3205 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
3206
3207 // If there are more than SHN_LORESERVE allocated sections, we
3208 // create a .dynsym_shndx section. It is possible that we don't
3209 // need one, because it is possible that there are no dynamic
3210 // symbols in any of the sections with indexes larger than
3211 // SHN_LORESERVE. This is probably unusual, though, and at this
3212 // time we don't know the actual section indexes so it is
3213 // inconvenient to check.
3214 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
3215 {
3216 Output_section* dynsym_xindex =
3217 this->choose_output_section(NULL, ".dynsym_shndx",
3218 elfcpp::SHT_SYMTAB_SHNDX,
3219 elfcpp::SHF_ALLOC,
3220 false, ORDER_DYNAMIC_LINKER, false);
3221
3222 this->dynsym_xindex_ = new Output_symtab_xindex(index);
3223
3224 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
3225
3226 dynsym_xindex->set_link_section(dynsym);
3227 dynsym_xindex->set_addralign(4);
3228 dynsym_xindex->set_entsize(4);
3229
3230 dynsym_xindex->set_after_input_sections();
3231
3232 // This tells the driver code to wait until the symbol table has
3233 // written out before writing out the postprocessing sections,
3234 // including the .dynsym_shndx section.
3235 this->any_postprocessing_sections_ = true;
3236 }
3237
3238 // Create the dynamic string table section.
3239
3240 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
3241 elfcpp::SHT_STRTAB,
3242 elfcpp::SHF_ALLOC,
3243 false,
3244 ORDER_DYNAMIC_LINKER,
3245 false);
3246
3247 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
3248 dynstr->add_output_section_data(strdata);
3249
3250 dynsym->set_link_section(dynstr);
3251 this->dynamic_section_->set_link_section(dynstr);
3252
3253 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
3254 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
3255
3256 *pdynstr = dynstr;
3257
3258 // Create the hash tables.
3259
3260 if (strcmp(parameters->options().hash_style(), "sysv") == 0
3261 || strcmp(parameters->options().hash_style(), "both") == 0)
3262 {
3263 unsigned char* phash;
3264 unsigned int hashlen;
3265 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
3266 &phash, &hashlen);
3267
3268 Output_section* hashsec =
3269 this->choose_output_section(NULL, ".hash", elfcpp::SHT_HASH,
3270 elfcpp::SHF_ALLOC, false,
3271 ORDER_DYNAMIC_LINKER, false);
3272
3273 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3274 hashlen,
3275 align,
3276 "** hash");
3277 hashsec->add_output_section_data(hashdata);
3278
3279 hashsec->set_link_section(dynsym);
3280 hashsec->set_entsize(4);
3281
3282 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
3283 }
3284
3285 if (strcmp(parameters->options().hash_style(), "gnu") == 0
3286 || strcmp(parameters->options().hash_style(), "both") == 0)
3287 {
3288 unsigned char* phash;
3289 unsigned int hashlen;
3290 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
3291 &phash, &hashlen);
3292
3293 Output_section* hashsec =
3294 this->choose_output_section(NULL, ".gnu.hash", elfcpp::SHT_GNU_HASH,
3295 elfcpp::SHF_ALLOC, false,
3296 ORDER_DYNAMIC_LINKER, false);
3297
3298 Output_section_data* hashdata = new Output_data_const_buffer(phash,
3299 hashlen,
3300 align,
3301 "** hash");
3302 hashsec->add_output_section_data(hashdata);
3303
3304 hashsec->set_link_section(dynsym);
3305
3306 // For a 64-bit target, the entries in .gnu.hash do not have a
3307 // uniform size, so we only set the entry size for a 32-bit
3308 // target.
3309 if (parameters->target().get_size() == 32)
3310 hashsec->set_entsize(4);
3311
3312 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
3313 }
3314 }
3315
3316 // Assign offsets to each local portion of the dynamic symbol table.
3317
3318 void
3319 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
3320 {
3321 Output_section* dynsym = this->dynsym_section_;
3322 gold_assert(dynsym != NULL);
3323
3324 off_t off = dynsym->offset();
3325
3326 // Skip the dummy symbol at the start of the section.
3327 off += dynsym->entsize();
3328
3329 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3330 p != input_objects->relobj_end();
3331 ++p)
3332 {
3333 unsigned int count = (*p)->set_local_dynsym_offset(off);
3334 off += count * dynsym->entsize();
3335 }
3336 }
3337
3338 // Create the version sections.
3339
3340 void
3341 Layout::create_version_sections(const Versions* versions,
3342 const Symbol_table* symtab,
3343 unsigned int local_symcount,
3344 const std::vector<Symbol*>& dynamic_symbols,
3345 const Output_section* dynstr)
3346 {
3347 if (!versions->any_defs() && !versions->any_needs())
3348 return;
3349
3350 switch (parameters->size_and_endianness())
3351 {
3352 #ifdef HAVE_TARGET_32_LITTLE
3353 case Parameters::TARGET_32_LITTLE:
3354 this->sized_create_version_sections<32, false>(versions, symtab,
3355 local_symcount,
3356 dynamic_symbols, dynstr);
3357 break;
3358 #endif
3359 #ifdef HAVE_TARGET_32_BIG
3360 case Parameters::TARGET_32_BIG:
3361 this->sized_create_version_sections<32, true>(versions, symtab,
3362 local_symcount,
3363 dynamic_symbols, dynstr);
3364 break;
3365 #endif
3366 #ifdef HAVE_TARGET_64_LITTLE
3367 case Parameters::TARGET_64_LITTLE:
3368 this->sized_create_version_sections<64, false>(versions, symtab,
3369 local_symcount,
3370 dynamic_symbols, dynstr);
3371 break;
3372 #endif
3373 #ifdef HAVE_TARGET_64_BIG
3374 case Parameters::TARGET_64_BIG:
3375 this->sized_create_version_sections<64, true>(versions, symtab,
3376 local_symcount,
3377 dynamic_symbols, dynstr);
3378 break;
3379 #endif
3380 default:
3381 gold_unreachable();
3382 }
3383 }
3384
3385 // Create the version sections, sized version.
3386
3387 template<int size, bool big_endian>
3388 void
3389 Layout::sized_create_version_sections(
3390 const Versions* versions,
3391 const Symbol_table* symtab,
3392 unsigned int local_symcount,
3393 const std::vector<Symbol*>& dynamic_symbols,
3394 const Output_section* dynstr)
3395 {
3396 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
3397 elfcpp::SHT_GNU_versym,
3398 elfcpp::SHF_ALLOC,
3399 false,
3400 ORDER_DYNAMIC_LINKER,
3401 false);
3402
3403 unsigned char* vbuf;
3404 unsigned int vsize;
3405 versions->symbol_section_contents<size, big_endian>(symtab, &this->dynpool_,
3406 local_symcount,
3407 dynamic_symbols,
3408 &vbuf, &vsize);
3409
3410 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
3411 "** versions");
3412
3413 vsec->add_output_section_data(vdata);
3414 vsec->set_entsize(2);
3415 vsec->set_link_section(this->dynsym_section_);
3416
3417 Output_data_dynamic* const odyn = this->dynamic_data_;
3418 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
3419
3420 if (versions->any_defs())
3421 {
3422 Output_section* vdsec;
3423 vdsec= this->choose_output_section(NULL, ".gnu.version_d",
3424 elfcpp::SHT_GNU_verdef,
3425 elfcpp::SHF_ALLOC,
3426 false, ORDER_DYNAMIC_LINKER, false);
3427
3428 unsigned char* vdbuf;
3429 unsigned int vdsize;
3430 unsigned int vdentries;
3431 versions->def_section_contents<size, big_endian>(&this->dynpool_, &vdbuf,
3432 &vdsize, &vdentries);
3433
3434 Output_section_data* vddata =
3435 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
3436
3437 vdsec->add_output_section_data(vddata);
3438 vdsec->set_link_section(dynstr);
3439 vdsec->set_info(vdentries);
3440
3441 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
3442 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
3443 }
3444
3445 if (versions->any_needs())
3446 {
3447 Output_section* vnsec;
3448 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
3449 elfcpp::SHT_GNU_verneed,
3450 elfcpp::SHF_ALLOC,
3451 false, ORDER_DYNAMIC_LINKER, false);
3452
3453 unsigned char* vnbuf;
3454 unsigned int vnsize;
3455 unsigned int vnentries;
3456 versions->need_section_contents<size, big_endian>(&this->dynpool_,
3457 &vnbuf, &vnsize,
3458 &vnentries);
3459
3460 Output_section_data* vndata =
3461 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
3462
3463 vnsec->add_output_section_data(vndata);
3464 vnsec->set_link_section(dynstr);
3465 vnsec->set_info(vnentries);
3466
3467 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
3468 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
3469 }
3470 }
3471
3472 // Create the .interp section and PT_INTERP segment.
3473
3474 void
3475 Layout::create_interp(const Target* target)
3476 {
3477 const char* interp = parameters->options().dynamic_linker();
3478 if (interp == NULL)
3479 {
3480 interp = target->dynamic_linker();
3481 gold_assert(interp != NULL);
3482 }
3483
3484 size_t len = strlen(interp) + 1;
3485
3486 Output_section_data* odata = new Output_data_const(interp, len, 1);
3487
3488 Output_section* osec = this->choose_output_section(NULL, ".interp",
3489 elfcpp::SHT_PROGBITS,
3490 elfcpp::SHF_ALLOC,
3491 false, ORDER_INTERP,
3492 false);
3493 osec->add_output_section_data(odata);
3494
3495 if (!this->script_options_->saw_phdrs_clause())
3496 {
3497 Output_segment* oseg = this->make_output_segment(elfcpp::PT_INTERP,
3498 elfcpp::PF_R);
3499 oseg->add_output_section_to_nonload(osec, elfcpp::PF_R);
3500 }
3501 }
3502
3503 // Add dynamic tags for the PLT and the dynamic relocs. This is
3504 // called by the target-specific code. This does nothing if not doing
3505 // a dynamic link.
3506
3507 // USE_REL is true for REL relocs rather than RELA relocs.
3508
3509 // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
3510
3511 // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
3512 // and we also set DT_PLTREL. We use PLT_REL's output section, since
3513 // some targets have multiple reloc sections in PLT_REL.
3514
3515 // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
3516 // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT.
3517
3518 // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
3519 // executable.
3520
3521 void
3522 Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
3523 const Output_data* plt_rel,
3524 const Output_data_reloc_generic* dyn_rel,
3525 bool add_debug, bool dynrel_includes_plt)
3526 {
3527 Output_data_dynamic* odyn = this->dynamic_data_;
3528 if (odyn == NULL)
3529 return;
3530
3531 if (plt_got != NULL && plt_got->output_section() != NULL)
3532 odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
3533
3534 if (plt_rel != NULL && plt_rel->output_section() != NULL)
3535 {
3536 odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
3537 odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
3538 odyn->add_constant(elfcpp::DT_PLTREL,
3539 use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
3540 }
3541
3542 if (dyn_rel != NULL && dyn_rel->output_section() != NULL)
3543 {
3544 odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
3545 dyn_rel);
3546 if (plt_rel != NULL && dynrel_includes_plt)
3547 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3548 dyn_rel, plt_rel);
3549 else
3550 odyn->add_section_size(use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ,
3551 dyn_rel);
3552 const int size = parameters->target().get_size();
3553 elfcpp::DT rel_tag;
3554 int rel_size;
3555 if (use_rel)
3556 {
3557 rel_tag = elfcpp::DT_RELENT;
3558 if (size == 32)
3559 rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
3560 else if (size == 64)
3561 rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
3562 else
3563 gold_unreachable();
3564 }
3565 else
3566 {
3567 rel_tag = elfcpp::DT_RELAENT;
3568 if (size == 32)
3569 rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
3570 else if (size == 64)
3571 rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
3572 else
3573 gold_unreachable();
3574 }
3575 odyn->add_constant(rel_tag, rel_size);
3576
3577 if (parameters->options().combreloc())
3578 {
3579 size_t c = dyn_rel->relative_reloc_count();
3580 if (c > 0)
3581 odyn->add_constant((use_rel
3582 ? elfcpp::DT_RELCOUNT
3583 : elfcpp::DT_RELACOUNT),
3584 c);
3585 }
3586 }
3587
3588 if (add_debug && !parameters->options().shared())
3589 {
3590 // The value of the DT_DEBUG tag is filled in by the dynamic
3591 // linker at run time, and used by the debugger.
3592 odyn->add_constant(elfcpp::DT_DEBUG, 0);
3593 }
3594 }
3595
3596 // Finish the .dynamic section and PT_DYNAMIC segment.
3597
3598 void
3599 Layout::finish_dynamic_section(const Input_objects* input_objects,
3600 const Symbol_table* symtab)
3601 {
3602 if (!this->script_options_->saw_phdrs_clause())
3603 {
3604 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
3605 (elfcpp::PF_R
3606 | elfcpp::PF_W));
3607 oseg->add_output_section_to_nonload(this->dynamic_section_,
3608 elfcpp::PF_R | elfcpp::PF_W);
3609 }
3610
3611 Output_data_dynamic* const odyn = this->dynamic_data_;
3612
3613 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
3614 p != input_objects->dynobj_end();
3615 ++p)
3616 {
3617 if (!(*p)->is_needed()
3618 && (*p)->input_file()->options().as_needed())
3619 {
3620 // This dynamic object was linked with --as-needed, but it
3621 // is not needed.
3622 continue;
3623 }
3624
3625 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
3626 }
3627
3628 if (parameters->options().shared())
3629 {
3630 const char* soname = parameters->options().soname();
3631 if (soname != NULL)
3632 odyn->add_string(elfcpp::DT_SONAME, soname);
3633 }
3634
3635 Symbol* sym = symtab->lookup(parameters->options().init());
3636 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3637 odyn->add_symbol(elfcpp::DT_INIT, sym);
3638
3639 sym = symtab->lookup(parameters->options().fini());
3640 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
3641 odyn->add_symbol(elfcpp::DT_FINI, sym);
3642
3643 // Look for .init_array, .preinit_array and .fini_array by checking
3644 // section types.
3645 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
3646 p != this->section_list_.end();
3647 ++p)
3648 switch((*p)->type())
3649 {
3650 case elfcpp::SHT_FINI_ARRAY:
3651 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
3652 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
3653 break;
3654 case elfcpp::SHT_INIT_ARRAY:
3655 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
3656 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
3657 break;
3658 case elfcpp::SHT_PREINIT_ARRAY:
3659 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
3660 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
3661 break;
3662 default:
3663 break;
3664 }
3665
3666 // Add a DT_RPATH entry if needed.
3667 const General_options::Dir_list& rpath(parameters->options().rpath());
3668 if (!rpath.empty())
3669 {
3670 std::string rpath_val;
3671 for (General_options::Dir_list::const_iterator p = rpath.begin();
3672 p != rpath.end();
3673 ++p)
3674 {
3675 if (rpath_val.empty())
3676 rpath_val = p->name();
3677 else
3678 {
3679 // Eliminate duplicates.
3680 General_options::Dir_list::const_iterator q;
3681 for (q = rpath.begin(); q != p; ++q)
3682 if (q->name() == p->name())
3683 break;
3684 if (q == p)
3685 {
3686 rpath_val += ':';
3687 rpath_val += p->name();
3688 }
3689 }
3690 }
3691
3692 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
3693 if (parameters->options().enable_new_dtags())
3694 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
3695 }
3696
3697 // Look for text segments that have dynamic relocations.
3698 bool have_textrel = false;
3699 if (!this->script_options_->saw_sections_clause())
3700 {
3701 for (Segment_list::const_iterator p = this->segment_list_.begin();
3702 p != this->segment_list_.end();
3703 ++p)
3704 {
3705 if (((*p)->flags() & elfcpp::PF_W) == 0
3706 && (*p)->has_dynamic_reloc())
3707 {
3708 have_textrel = true;
3709 break;
3710 }
3711 }
3712 }
3713 else
3714 {
3715 // We don't know the section -> segment mapping, so we are
3716 // conservative and just look for readonly sections with
3717 // relocations. If those sections wind up in writable segments,
3718 // then we have created an unnecessary DT_TEXTREL entry.
3719 for (Section_list::const_iterator p = this->section_list_.begin();
3720 p != this->section_list_.end();
3721 ++p)
3722 {
3723 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
3724 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
3725 && ((*p)->has_dynamic_reloc()))
3726 {
3727 have_textrel = true;
3728 break;
3729 }
3730 }
3731 }
3732
3733 // Add a DT_FLAGS entry. We add it even if no flags are set so that
3734 // post-link tools can easily modify these flags if desired.
3735 unsigned int flags = 0;
3736 if (have_textrel)
3737 {
3738 // Add a DT_TEXTREL for compatibility with older loaders.
3739 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
3740 flags |= elfcpp::DF_TEXTREL;
3741
3742 if (parameters->options().text())
3743 gold_error(_("read-only segment has dynamic relocations"));
3744 else if (parameters->options().warn_shared_textrel()
3745 && parameters->options().shared())
3746 gold_warning(_("shared library text segment is not shareable"));
3747 }
3748 if (parameters->options().shared() && this->has_static_tls())
3749 flags |= elfcpp::DF_STATIC_TLS;
3750 if (parameters->options().origin())
3751 flags |= elfcpp::DF_ORIGIN;
3752 if (parameters->options().Bsymbolic())
3753 {
3754 flags |= elfcpp::DF_SYMBOLIC;
3755 // Add DT_SYMBOLIC for compatibility with older loaders.
3756 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
3757 }
3758 if (parameters->options().now())
3759 flags |= elfcpp::DF_BIND_NOW;
3760 odyn->add_constant(elfcpp::DT_FLAGS, flags);
3761
3762 flags = 0;
3763 if (parameters->options().initfirst())
3764 flags |= elfcpp::DF_1_INITFIRST;
3765 if (parameters->options().interpose())
3766 flags |= elfcpp::DF_1_INTERPOSE;
3767 if (parameters->options().loadfltr())
3768 flags |= elfcpp::DF_1_LOADFLTR;
3769 if (parameters->options().nodefaultlib())
3770 flags |= elfcpp::DF_1_NODEFLIB;
3771 if (parameters->options().nodelete())
3772 flags |= elfcpp::DF_1_NODELETE;
3773 if (parameters->options().nodlopen())
3774 flags |= elfcpp::DF_1_NOOPEN;
3775 if (parameters->options().nodump())
3776 flags |= elfcpp::DF_1_NODUMP;
3777 if (!parameters->options().shared())
3778 flags &= ~(elfcpp::DF_1_INITFIRST
3779 | elfcpp::DF_1_NODELETE
3780 | elfcpp::DF_1_NOOPEN);
3781 if (parameters->options().origin())
3782 flags |= elfcpp::DF_1_ORIGIN;
3783 if (parameters->options().now())
3784 flags |= elfcpp::DF_1_NOW;
3785 if (flags)
3786 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
3787 }
3788
3789 // Set the size of the _DYNAMIC symbol table to be the size of the
3790 // dynamic data.
3791
3792 void
3793 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
3794 {
3795 Output_data_dynamic* const odyn = this->dynamic_data_;
3796 odyn->finalize_data_size();
3797 off_t data_size = odyn->data_size();
3798 const int size = parameters->target().get_size();
3799 if (size == 32)
3800 symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
3801 else if (size == 64)
3802 symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
3803 else
3804 gold_unreachable();
3805 }
3806
3807 // The mapping of input section name prefixes to output section names.
3808 // In some cases one prefix is itself a prefix of another prefix; in
3809 // such a case the longer prefix must come first. These prefixes are
3810 // based on the GNU linker default ELF linker script.
3811
3812 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
3813 const Layout::Section_name_mapping Layout::section_name_mapping[] =
3814 {
3815 MAPPING_INIT(".text.", ".text"),
3816 MAPPING_INIT(".ctors.", ".ctors"),
3817 MAPPING_INIT(".dtors.", ".dtors"),
3818 MAPPING_INIT(".rodata.", ".rodata"),
3819 MAPPING_INIT(".data.rel.ro.local", ".data.rel.ro.local"),
3820 MAPPING_INIT(".data.rel.ro", ".data.rel.ro"),
3821 MAPPING_INIT(".data.", ".data"),
3822 MAPPING_INIT(".bss.", ".bss"),
3823 MAPPING_INIT(".tdata.", ".tdata"),
3824 MAPPING_INIT(".tbss.", ".tbss"),
3825 MAPPING_INIT(".init_array.", ".init_array"),
3826 MAPPING_INIT(".fini_array.", ".fini_array"),
3827 MAPPING_INIT(".sdata.", ".sdata"),
3828 MAPPING_INIT(".sbss.", ".sbss"),
3829 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
3830 // differently depending on whether it is creating a shared library.
3831 MAPPING_INIT(".sdata2.", ".sdata"),
3832 MAPPING_INIT(".sbss2.", ".sbss"),
3833 MAPPING_INIT(".lrodata.", ".lrodata"),
3834 MAPPING_INIT(".ldata.", ".ldata"),
3835 MAPPING_INIT(".lbss.", ".lbss"),
3836 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
3837 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
3838 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
3839 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
3840 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
3841 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
3842 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
3843 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
3844 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
3845 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
3846 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
3847 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
3848 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
3849 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
3850 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
3851 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
3852 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
3853 MAPPING_INIT(".ARM.extab", ".ARM.extab"),
3854 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
3855 MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
3856 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
3857 };
3858 #undef MAPPING_INIT
3859
3860 const int Layout::section_name_mapping_count =
3861 (sizeof(Layout::section_name_mapping)
3862 / sizeof(Layout::section_name_mapping[0]));
3863
3864 // Choose the output section name to use given an input section name.
3865 // Set *PLEN to the length of the name. *PLEN is initialized to the
3866 // length of NAME.
3867
3868 const char*
3869 Layout::output_section_name(const char* name, size_t* plen)
3870 {
3871 // gcc 4.3 generates the following sorts of section names when it
3872 // needs a section name specific to a function:
3873 // .text.FN
3874 // .rodata.FN
3875 // .sdata2.FN
3876 // .data.FN
3877 // .data.rel.FN
3878 // .data.rel.local.FN
3879 // .data.rel.ro.FN
3880 // .data.rel.ro.local.FN
3881 // .sdata.FN
3882 // .bss.FN
3883 // .sbss.FN
3884 // .tdata.FN
3885 // .tbss.FN
3886
3887 // The GNU linker maps all of those to the part before the .FN,
3888 // except that .data.rel.local.FN is mapped to .data, and
3889 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
3890 // beginning with .data.rel.ro.local are grouped together.
3891
3892 // For an anonymous namespace, the string FN can contain a '.'.
3893
3894 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
3895 // GNU linker maps to .rodata.
3896
3897 // The .data.rel.ro sections are used with -z relro. The sections
3898 // are recognized by name. We use the same names that the GNU
3899 // linker does for these sections.
3900
3901 // It is hard to handle this in a principled way, so we don't even
3902 // try. We use a table of mappings. If the input section name is
3903 // not found in the table, we simply use it as the output section
3904 // name.
3905
3906 const Section_name_mapping* psnm = section_name_mapping;
3907 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
3908 {
3909 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
3910 {
3911 *plen = psnm->tolen;
3912 return psnm->to;
3913 }
3914 }
3915
3916 // Compressed debug sections should be mapped to the corresponding
3917 // uncompressed section.
3918 if (is_compressed_debug_section(name))
3919 {
3920 size_t len = strlen(name);
3921 char* uncompressed_name = new char[len];
3922 uncompressed_name[0] = '.';
3923 gold_assert(name[0] == '.' && name[1] == 'z');
3924 strncpy(&uncompressed_name[1], &name[2], len - 2);
3925 uncompressed_name[len - 1] = '\0';
3926 *plen = len - 1;
3927 return uncompressed_name;
3928 }
3929
3930 return name;
3931 }
3932
3933 // Check if a comdat group or .gnu.linkonce section with the given
3934 // NAME is selected for the link. If there is already a section,
3935 // *KEPT_SECTION is set to point to the existing section and the
3936 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
3937 // IS_GROUP_NAME are recorded for this NAME in the layout object,
3938 // *KEPT_SECTION is set to the internal copy and the function returns
3939 // true.
3940
3941 bool
3942 Layout::find_or_add_kept_section(const std::string& name,
3943 Relobj* object,
3944 unsigned int shndx,
3945 bool is_comdat,
3946 bool is_group_name,
3947 Kept_section** kept_section)
3948 {
3949 // It's normal to see a couple of entries here, for the x86 thunk
3950 // sections. If we see more than a few, we're linking a C++
3951 // program, and we resize to get more space to minimize rehashing.
3952 if (this->signatures_.size() > 4
3953 && !this->resized_signatures_)
3954 {
3955 reserve_unordered_map(&this->signatures_,
3956 this->number_of_input_files_ * 64);
3957 this->resized_signatures_ = true;
3958 }
3959
3960 Kept_section candidate;
3961 std::pair<Signatures::iterator, bool> ins =
3962 this->signatures_.insert(std::make_pair(name, candidate));
3963
3964 if (kept_section != NULL)
3965 *kept_section = &ins.first->second;
3966 if (ins.second)
3967 {
3968 // This is the first time we've seen this signature.
3969 ins.first->second.set_object(object);
3970 ins.first->second.set_shndx(shndx);
3971 if (is_comdat)
3972 ins.first->second.set_is_comdat();
3973 if (is_group_name)
3974 ins.first->second.set_is_group_name();
3975 return true;
3976 }
3977
3978 // We have already seen this signature.
3979
3980 if (ins.first->second.is_group_name())
3981 {
3982 // We've already seen a real section group with this signature.
3983 // If the kept group is from a plugin object, and we're in the
3984 // replacement phase, accept the new one as a replacement.
3985 if (ins.first->second.object() == NULL
3986 && parameters->options().plugins()->in_replacement_phase())
3987 {
3988 ins.first->second.set_object(object);
3989 ins.first->second.set_shndx(shndx);
3990 return true;
3991 }
3992 return false;
3993 }
3994 else if (is_group_name)
3995 {
3996 // This is a real section group, and we've already seen a
3997 // linkonce section with this signature. Record that we've seen
3998 // a section group, and don't include this section group.
3999 ins.first->second.set_is_group_name();
4000 return false;
4001 }
4002 else
4003 {
4004 // We've already seen a linkonce section and this is a linkonce
4005 // section. These don't block each other--this may be the same
4006 // symbol name with different section types.
4007 return true;
4008 }
4009 }
4010
4011 // Store the allocated sections into the section list.
4012
4013 void
4014 Layout::get_allocated_sections(Section_list* section_list) const
4015 {
4016 for (Section_list::const_iterator p = this->section_list_.begin();
4017 p != this->section_list_.end();
4018 ++p)
4019 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
4020 section_list->push_back(*p);
4021 }
4022
4023 // Create an output segment.
4024
4025 Output_segment*
4026 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
4027 {
4028 gold_assert(!parameters->options().relocatable());
4029 Output_segment* oseg = new Output_segment(type, flags);
4030 this->segment_list_.push_back(oseg);
4031
4032 if (type == elfcpp::PT_TLS)
4033 this->tls_segment_ = oseg;
4034 else if (type == elfcpp::PT_GNU_RELRO)
4035 this->relro_segment_ = oseg;
4036
4037 return oseg;
4038 }
4039
4040 // Write out the Output_sections. Most won't have anything to write,
4041 // since most of the data will come from input sections which are
4042 // handled elsewhere. But some Output_sections do have Output_data.
4043
4044 void
4045 Layout::write_output_sections(Output_file* of) const
4046 {
4047 for (Section_list::const_iterator p = this->section_list_.begin();
4048 p != this->section_list_.end();
4049 ++p)
4050 {
4051 if (!(*p)->after_input_sections())
4052 (*p)->write(of);
4053 }
4054 }
4055
4056 // Write out data not associated with a section or the symbol table.
4057
4058 void
4059 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
4060 {
4061 if (!parameters->options().strip_all())
4062 {
4063 const Output_section* symtab_section = this->symtab_section_;
4064 for (Section_list::const_iterator p = this->section_list_.begin();
4065 p != this->section_list_.end();
4066 ++p)
4067 {
4068 if ((*p)->needs_symtab_index())
4069 {
4070 gold_assert(symtab_section != NULL);
4071 unsigned int index = (*p)->symtab_index();
4072 gold_assert(index > 0 && index != -1U);
4073 off_t off = (symtab_section->offset()
4074 + index * symtab_section->entsize());
4075 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
4076 }
4077 }
4078 }
4079
4080 const Output_section* dynsym_section = this->dynsym_section_;
4081 for (Section_list::const_iterator p = this->section_list_.begin();
4082 p != this->section_list_.end();
4083 ++p)
4084 {
4085 if ((*p)->needs_dynsym_index())
4086 {
4087 gold_assert(dynsym_section != NULL);
4088 unsigned int index = (*p)->dynsym_index();
4089 gold_assert(index > 0 && index != -1U);
4090 off_t off = (dynsym_section->offset()
4091 + index * dynsym_section->entsize());
4092 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
4093 }
4094 }
4095
4096 // Write out the Output_data which are not in an Output_section.
4097 for (Data_list::const_iterator p = this->special_output_list_.begin();
4098 p != this->special_output_list_.end();
4099 ++p)
4100 (*p)->write(of);
4101 }
4102
4103 // Write out the Output_sections which can only be written after the
4104 // input sections are complete.
4105
4106 void
4107 Layout::write_sections_after_input_sections(Output_file* of)
4108 {
4109 // Determine the final section offsets, and thus the final output
4110 // file size. Note we finalize the .shstrab last, to allow the
4111 // after_input_section sections to modify their section-names before
4112 // writing.
4113 if (this->any_postprocessing_sections_)
4114 {
4115 off_t off = this->output_file_size_;
4116 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
4117
4118 // Now that we've finalized the names, we can finalize the shstrab.
4119 off =
4120 this->set_section_offsets(off,
4121 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
4122
4123 if (off > this->output_file_size_)
4124 {
4125 of->resize(off);
4126 this->output_file_size_ = off;
4127 }
4128 }
4129
4130 for (Section_list::const_iterator p = this->section_list_.begin();
4131 p != this->section_list_.end();
4132 ++p)
4133 {
4134 if ((*p)->after_input_sections())
4135 (*p)->write(of);
4136 }
4137
4138 this->section_headers_->write(of);
4139 }
4140
4141 // If the build ID requires computing a checksum, do so here, and
4142 // write it out. We compute a checksum over the entire file because
4143 // that is simplest.
4144
4145 void
4146 Layout::write_build_id(Output_file* of) const
4147 {
4148 if (this->build_id_note_ == NULL)
4149 return;
4150
4151 const unsigned char* iv = of->get_input_view(0, this->output_file_size_);
4152
4153 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
4154 this->build_id_note_->data_size());
4155
4156 const char* style = parameters->options().build_id();
4157 if (strcmp(style, "sha1") == 0)
4158 {
4159 sha1_ctx ctx;
4160 sha1_init_ctx(&ctx);
4161 sha1_process_bytes(iv, this->output_file_size_, &ctx);
4162 sha1_finish_ctx(&ctx, ov);
4163 }
4164 else if (strcmp(style, "md5") == 0)
4165 {
4166 md5_ctx ctx;
4167 md5_init_ctx(&ctx);
4168 md5_process_bytes(iv, this->output_file_size_, &ctx);
4169 md5_finish_ctx(&ctx, ov);
4170 }
4171 else
4172 gold_unreachable();
4173
4174 of->write_output_view(this->build_id_note_->offset(),
4175 this->build_id_note_->data_size(),
4176 ov);
4177
4178 of->free_input_view(0, this->output_file_size_, iv);
4179 }
4180
4181 // Write out a binary file. This is called after the link is
4182 // complete. IN is the temporary output file we used to generate the
4183 // ELF code. We simply walk through the segments, read them from
4184 // their file offset in IN, and write them to their load address in
4185 // the output file. FIXME: with a bit more work, we could support
4186 // S-records and/or Intel hex format here.
4187
4188 void
4189 Layout::write_binary(Output_file* in) const
4190 {
4191 gold_assert(parameters->options().oformat_enum()
4192 == General_options::OBJECT_FORMAT_BINARY);
4193
4194 // Get the size of the binary file.
4195 uint64_t max_load_address = 0;
4196 for (Segment_list::const_iterator p = this->segment_list_.begin();
4197 p != this->segment_list_.end();
4198 ++p)
4199 {
4200 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4201 {
4202 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
4203 if (max_paddr > max_load_address)
4204 max_load_address = max_paddr;
4205 }
4206 }
4207
4208 Output_file out(parameters->options().output_file_name());
4209 out.open(max_load_address);
4210
4211 for (Segment_list::const_iterator p = this->segment_list_.begin();
4212 p != this->segment_list_.end();
4213 ++p)
4214 {
4215 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
4216 {
4217 const unsigned char* vin = in->get_input_view((*p)->offset(),
4218 (*p)->filesz());
4219 unsigned char* vout = out.get_output_view((*p)->paddr(),
4220 (*p)->filesz());
4221 memcpy(vout, vin, (*p)->filesz());
4222 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
4223 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
4224 }
4225 }
4226
4227 out.close();
4228 }
4229
4230 // Print the output sections to the map file.
4231
4232 void
4233 Layout::print_to_mapfile(Mapfile* mapfile) const
4234 {
4235 for (Segment_list::const_iterator p = this->segment_list_.begin();
4236 p != this->segment_list_.end();
4237 ++p)
4238 (*p)->print_sections_to_mapfile(mapfile);
4239 }
4240
4241 // Print statistical information to stderr. This is used for --stats.
4242
4243 void
4244 Layout::print_stats() const
4245 {
4246 this->namepool_.print_stats("section name pool");
4247 this->sympool_.print_stats("output symbol name pool");
4248 this->dynpool_.print_stats("dynamic name pool");
4249
4250 for (Section_list::const_iterator p = this->section_list_.begin();
4251 p != this->section_list_.end();
4252 ++p)
4253 (*p)->print_merge_stats();
4254 }
4255
4256 // Write_sections_task methods.
4257
4258 // We can always run this task.
4259
4260 Task_token*
4261 Write_sections_task::is_runnable()
4262 {
4263 return NULL;
4264 }
4265
4266 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
4267 // when finished.
4268
4269 void
4270 Write_sections_task::locks(Task_locker* tl)
4271 {
4272 tl->add(this, this->output_sections_blocker_);
4273 tl->add(this, this->final_blocker_);
4274 }
4275
4276 // Run the task--write out the data.
4277
4278 void
4279 Write_sections_task::run(Workqueue*)
4280 {
4281 this->layout_->write_output_sections(this->of_);
4282 }
4283
4284 // Write_data_task methods.
4285
4286 // We can always run this task.
4287
4288 Task_token*
4289 Write_data_task::is_runnable()
4290 {
4291 return NULL;
4292 }
4293
4294 // We need to unlock FINAL_BLOCKER when finished.
4295
4296 void
4297 Write_data_task::locks(Task_locker* tl)
4298 {
4299 tl->add(this, this->final_blocker_);
4300 }
4301
4302 // Run the task--write out the data.
4303
4304 void
4305 Write_data_task::run(Workqueue*)
4306 {
4307 this->layout_->write_data(this->symtab_, this->of_);
4308 }
4309
4310 // Write_symbols_task methods.
4311
4312 // We can always run this task.
4313
4314 Task_token*
4315 Write_symbols_task::is_runnable()
4316 {
4317 return NULL;
4318 }
4319
4320 // We need to unlock FINAL_BLOCKER when finished.
4321
4322 void
4323 Write_symbols_task::locks(Task_locker* tl)
4324 {
4325 tl->add(this, this->final_blocker_);
4326 }
4327
4328 // Run the task--write out the symbols.
4329
4330 void
4331 Write_symbols_task::run(Workqueue*)
4332 {
4333 this->symtab_->write_globals(this->sympool_, this->dynpool_,
4334 this->layout_->symtab_xindex(),
4335 this->layout_->dynsym_xindex(), this->of_);
4336 }
4337
4338 // Write_after_input_sections_task methods.
4339
4340 // We can only run this task after the input sections have completed.
4341
4342 Task_token*
4343 Write_after_input_sections_task::is_runnable()
4344 {
4345 if (this->input_sections_blocker_->is_blocked())
4346 return this->input_sections_blocker_;
4347 return NULL;
4348 }
4349
4350 // We need to unlock FINAL_BLOCKER when finished.
4351
4352 void
4353 Write_after_input_sections_task::locks(Task_locker* tl)
4354 {
4355 tl->add(this, this->final_blocker_);
4356 }
4357
4358 // Run the task.
4359
4360 void
4361 Write_after_input_sections_task::run(Workqueue*)
4362 {
4363 this->layout_->write_sections_after_input_sections(this->of_);
4364 }
4365
4366 // Close_task_runner methods.
4367
4368 // Run the task--close the file.
4369
4370 void
4371 Close_task_runner::run(Workqueue*, const Task*)
4372 {
4373 // If we need to compute a checksum for the BUILD if, we do so here.
4374 this->layout_->write_build_id(this->of_);
4375
4376 // If we've been asked to create a binary file, we do so here.
4377 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
4378 this->layout_->write_binary(this->of_);
4379
4380 this->of_->close();
4381 }
4382
4383 // Instantiate the templates we need. We could use the configure
4384 // script to restrict this to only the ones for implemented targets.
4385
4386 #ifdef HAVE_TARGET_32_LITTLE
4387 template
4388 Output_section*
4389 Layout::layout<32, false>(Sized_relobj<32, false>* object, unsigned int shndx,
4390 const char* name,
4391 const elfcpp::Shdr<32, false>& shdr,
4392 unsigned int, unsigned int, off_t*);
4393 #endif
4394
4395 #ifdef HAVE_TARGET_32_BIG
4396 template
4397 Output_section*
4398 Layout::layout<32, true>(Sized_relobj<32, true>* object, unsigned int shndx,
4399 const char* name,
4400 const elfcpp::Shdr<32, true>& shdr,
4401 unsigned int, unsigned int, off_t*);
4402 #endif
4403
4404 #ifdef HAVE_TARGET_64_LITTLE
4405 template
4406 Output_section*
4407 Layout::layout<64, false>(Sized_relobj<64, false>* object, unsigned int shndx,
4408 const char* name,
4409 const elfcpp::Shdr<64, false>& shdr,
4410 unsigned int, unsigned int, off_t*);
4411 #endif
4412
4413 #ifdef HAVE_TARGET_64_BIG
4414 template
4415 Output_section*
4416 Layout::layout<64, true>(Sized_relobj<64, true>* object, unsigned int shndx,
4417 const char* name,
4418 const elfcpp::Shdr<64, true>& shdr,
4419 unsigned int, unsigned int, off_t*);
4420 #endif
4421
4422 #ifdef HAVE_TARGET_32_LITTLE
4423 template
4424 Output_section*
4425 Layout::layout_reloc<32, false>(Sized_relobj<32, false>* object,
4426 unsigned int reloc_shndx,
4427 const elfcpp::Shdr<32, false>& shdr,
4428 Output_section* data_section,
4429 Relocatable_relocs* rr);
4430 #endif
4431
4432 #ifdef HAVE_TARGET_32_BIG
4433 template
4434 Output_section*
4435 Layout::layout_reloc<32, true>(Sized_relobj<32, true>* object,
4436 unsigned int reloc_shndx,
4437 const elfcpp::Shdr<32, true>& shdr,
4438 Output_section* data_section,
4439 Relocatable_relocs* rr);
4440 #endif
4441
4442 #ifdef HAVE_TARGET_64_LITTLE
4443 template
4444 Output_section*
4445 Layout::layout_reloc<64, false>(Sized_relobj<64, false>* object,
4446 unsigned int reloc_shndx,
4447 const elfcpp::Shdr<64, false>& shdr,
4448 Output_section* data_section,
4449 Relocatable_relocs* rr);
4450 #endif
4451
4452 #ifdef HAVE_TARGET_64_BIG
4453 template
4454 Output_section*
4455 Layout::layout_reloc<64, true>(Sized_relobj<64, true>* object,
4456 unsigned int reloc_shndx,
4457 const elfcpp::Shdr<64, true>& shdr,
4458 Output_section* data_section,
4459 Relocatable_relocs* rr);
4460 #endif
4461
4462 #ifdef HAVE_TARGET_32_LITTLE
4463 template
4464 void
4465 Layout::layout_group<32, false>(Symbol_table* symtab,
4466 Sized_relobj<32, false>* object,
4467 unsigned int,
4468 const char* group_section_name,
4469 const char* signature,
4470 const elfcpp::Shdr<32, false>& shdr,
4471 elfcpp::Elf_Word flags,
4472 std::vector<unsigned int>* shndxes);
4473 #endif
4474
4475 #ifdef HAVE_TARGET_32_BIG
4476 template
4477 void
4478 Layout::layout_group<32, true>(Symbol_table* symtab,
4479 Sized_relobj<32, true>* object,
4480 unsigned int,
4481 const char* group_section_name,
4482 const char* signature,
4483 const elfcpp::Shdr<32, true>& shdr,
4484 elfcpp::Elf_Word flags,
4485 std::vector<unsigned int>* shndxes);
4486 #endif
4487
4488 #ifdef HAVE_TARGET_64_LITTLE
4489 template
4490 void
4491 Layout::layout_group<64, false>(Symbol_table* symtab,
4492 Sized_relobj<64, false>* object,
4493 unsigned int,
4494 const char* group_section_name,
4495 const char* signature,
4496 const elfcpp::Shdr<64, false>& shdr,
4497 elfcpp::Elf_Word flags,
4498 std::vector<unsigned int>* shndxes);
4499 #endif
4500
4501 #ifdef HAVE_TARGET_64_BIG
4502 template
4503 void
4504 Layout::layout_group<64, true>(Symbol_table* symtab,
4505 Sized_relobj<64, true>* object,
4506 unsigned int,
4507 const char* group_section_name,
4508 const char* signature,
4509 const elfcpp::Shdr<64, true>& shdr,
4510 elfcpp::Elf_Word flags,
4511 std::vector<unsigned int>* shndxes);
4512 #endif
4513
4514 #ifdef HAVE_TARGET_32_LITTLE
4515 template
4516 Output_section*
4517 Layout::layout_eh_frame<32, false>(Sized_relobj<32, false>* object,
4518 const unsigned char* symbols,
4519 off_t symbols_size,
4520 const unsigned char* symbol_names,
4521 off_t symbol_names_size,
4522 unsigned int shndx,
4523 const elfcpp::Shdr<32, false>& shdr,
4524 unsigned int reloc_shndx,
4525 unsigned int reloc_type,
4526 off_t* off);
4527 #endif
4528
4529 #ifdef HAVE_TARGET_32_BIG
4530 template
4531 Output_section*
4532 Layout::layout_eh_frame<32, true>(Sized_relobj<32, true>* object,
4533 const unsigned char* symbols,
4534 off_t symbols_size,
4535 const unsigned char* symbol_names,
4536 off_t symbol_names_size,
4537 unsigned int shndx,
4538 const elfcpp::Shdr<32, true>& shdr,
4539 unsigned int reloc_shndx,
4540 unsigned int reloc_type,
4541 off_t* off);
4542 #endif
4543
4544 #ifdef HAVE_TARGET_64_LITTLE
4545 template
4546 Output_section*
4547 Layout::layout_eh_frame<64, false>(Sized_relobj<64, false>* object,
4548 const unsigned char* symbols,
4549 off_t symbols_size,
4550 const unsigned char* symbol_names,
4551 off_t symbol_names_size,
4552 unsigned int shndx,
4553 const elfcpp::Shdr<64, false>& shdr,
4554 unsigned int reloc_shndx,
4555 unsigned int reloc_type,
4556 off_t* off);
4557 #endif
4558
4559 #ifdef HAVE_TARGET_64_BIG
4560 template
4561 Output_section*
4562 Layout::layout_eh_frame<64, true>(Sized_relobj<64, true>* object,
4563 const unsigned char* symbols,
4564 off_t symbols_size,
4565 const unsigned char* symbol_names,
4566 off_t symbol_names_size,
4567 unsigned int shndx,
4568 const elfcpp::Shdr<64, true>& shdr,
4569 unsigned int reloc_shndx,
4570 unsigned int reloc_type,
4571 off_t* off);
4572 #endif
4573
4574 } // End namespace gold.
This page took 0.124801 seconds and 5 git commands to generate.