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