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