1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright (C) 2006-2014 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 // __STDC_FORMAT_MACROS is needed to turn on macros in inttypes.h.
29 #define __STDC_FORMAT_MACROS
30 #include <inttypes.h>
31 #include <iostream>
32 #include <fstream>
33 #include <utility>
34 #include <fcntl.h>
35 #include <fnmatch.h>
36 #include <unistd.h>
37 #include "libiberty.h"
38 #include "md5.h"
39 #include "sha1.h"
40
41 #include "parameters.h"
42 #include "options.h"
43 #include "mapfile.h"
44 #include "script.h"
45 #include "script-sections.h"
46 #include "output.h"
47 #include "symtab.h"
48 #include "dynobj.h"
49 #include "ehframe.h"
50 #include "gdb-index.h"
51 #include "compressed_output.h"
52 #include "reduced_debug_output.h"
53 #include "object.h"
54 #include "reloc.h"
55 #include "descriptors.h"
56 #include "plugin.h"
57 #include "incremental.h"
58 #include "layout.h"
59
60 namespace gold
61 {
62
63 // Class Free_list.
64
65 // The total number of free lists used.
66 unsigned int Free_list::num_lists = 0;
67 // The total number of free list nodes used.
68 unsigned int Free_list::num_nodes = 0;
69 // The total number of calls to Free_list::remove.
70 unsigned int Free_list::num_removes = 0;
71 // The total number of nodes visited during calls to Free_list::remove.
72 unsigned int Free_list::num_remove_visits = 0;
73 // The total number of calls to Free_list::allocate.
74 unsigned int Free_list::num_allocates = 0;
75 // The total number of nodes visited during calls to Free_list::allocate.
76 unsigned int Free_list::num_allocate_visits = 0;
77
78 // Initialize the free list. Creates a single free list node that
79 // describes the entire region of length LEN. If EXTEND is true,
80 // allocate() is allowed to extend the region beyond its initial
81 // length.
82
83 void
init(off_t len,bool extend)84 Free_list::init(off_t len, bool extend)
85 {
86 this->list_.push_front(Free_list_node(0, len));
87 this->last_remove_ = this->list_.begin();
88 this->extend_ = extend;
89 this->length_ = len;
90 ++Free_list::num_lists;
91 ++Free_list::num_nodes;
92 }
93
94 // Remove a chunk from the free list. Because we start with a single
95 // node that covers the entire section, and remove chunks from it one
96 // at a time, we do not need to coalesce chunks or handle cases that
97 // span more than one free node. We expect to remove chunks from the
98 // free list in order, and we expect to have only a few chunks of free
99 // space left (corresponding to files that have changed since the last
100 // incremental link), so a simple linear list should provide sufficient
101 // performance.
102
103 void
remove(off_t start,off_t end)104 Free_list::remove(off_t start, off_t end)
105 {
106 if (start == end)
107 return;
108 gold_assert(start < end);
109
110 ++Free_list::num_removes;
111
112 Iterator p = this->last_remove_;
113 if (p->start_ > start)
114 p = this->list_.begin();
115
116 for (; p != this->list_.end(); ++p)
117 {
118 ++Free_list::num_remove_visits;
119 // Find a node that wholly contains the indicated region.
120 if (p->start_ <= start && p->end_ >= end)
121 {
122 // Case 1: the indicated region spans the whole node.
123 // Add some fuzz to avoid creating tiny free chunks.
124 if (p->start_ + 3 >= start && p->end_ <= end + 3)
125 p = this->list_.erase(p);
126 // Case 2: remove a chunk from the start of the node.
127 else if (p->start_ + 3 >= start)
128 p->start_ = end;
129 // Case 3: remove a chunk from the end of the node.
130 else if (p->end_ <= end + 3)
131 p->end_ = start;
132 // Case 4: remove a chunk from the middle, and split
133 // the node into two.
134 else
135 {
136 Free_list_node newnode(p->start_, start);
137 p->start_ = end;
138 this->list_.insert(p, newnode);
139 ++Free_list::num_nodes;
140 }
141 this->last_remove_ = p;
142 return;
143 }
144 }
145
146 // Did not find a node containing the given chunk. This could happen
147 // because a small chunk was already removed due to the fuzz.
148 gold_debug(DEBUG_INCREMENTAL,
149 "Free_list::remove(%d,%d) not found",
150 static_cast<int>(start), static_cast<int>(end));
151 }
152
153 // Allocate a chunk of size LEN from the free list. Returns -1ULL
154 // if a sufficiently large chunk of free space is not found.
155 // We use a simple first-fit algorithm.
156
157 off_t
allocate(off_t len,uint64_t align,off_t minoff)158 Free_list::allocate(off_t len, uint64_t align, off_t minoff)
159 {
160 gold_debug(DEBUG_INCREMENTAL,
161 "Free_list::allocate(%08lx, %d, %08lx)",
162 static_cast<long>(len), static_cast<int>(align),
163 static_cast<long>(minoff));
164 if (len == 0)
165 return align_address(minoff, align);
166
167 ++Free_list::num_allocates;
168
169 // We usually want to drop free chunks smaller than 4 bytes.
170 // If we need to guarantee a minimum hole size, though, we need
171 // to keep track of all free chunks.
172 const int fuzz = this->min_hole_ > 0 ? 0 : 3;
173
174 for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
175 {
176 ++Free_list::num_allocate_visits;
177 off_t start = p->start_ > minoff ? p->start_ : minoff;
178 start = align_address(start, align);
179 off_t end = start + len;
180 if (end > p->end_ && p->end_ == this->length_ && this->extend_)
181 {
182 this->length_ = end;
183 p->end_ = end;
184 }
185 if (end == p->end_ || (end <= p->end_ - this->min_hole_))
186 {
187 if (p->start_ + fuzz >= start && p->end_ <= end + fuzz)
188 this->list_.erase(p);
189 else if (p->start_ + fuzz >= start)
190 p->start_ = end;
191 else if (p->end_ <= end + fuzz)
192 p->end_ = start;
193 else
194 {
195 Free_list_node newnode(p->start_, start);
196 p->start_ = end;
197 this->list_.insert(p, newnode);
198 ++Free_list::num_nodes;
199 }
200 return start;
201 }
202 }
203 if (this->extend_)
204 {
205 off_t start = align_address(this->length_, align);
206 this->length_ = start + len;
207 return start;
208 }
209 return -1;
210 }
211
212 // Dump the free list (for debugging).
213 void
dump()214 Free_list::dump()
215 {
216 gold_info("Free list:\n start end length\n");
217 for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
218 gold_info(" %08lx %08lx %08lx", static_cast<long>(p->start_),
219 static_cast<long>(p->end_),
220 static_cast<long>(p->end_ - p->start_));
221 }
222
223 // Print the statistics for the free lists.
224 void
print_stats()225 Free_list::print_stats()
226 {
227 fprintf(stderr, _("%s: total free lists: %u\n"),
228 program_name, Free_list::num_lists);
229 fprintf(stderr, _("%s: total free list nodes: %u\n"),
230 program_name, Free_list::num_nodes);
231 fprintf(stderr, _("%s: calls to Free_list::remove: %u\n"),
232 program_name, Free_list::num_removes);
233 fprintf(stderr, _("%s: nodes visited: %u\n"),
234 program_name, Free_list::num_remove_visits);
235 fprintf(stderr, _("%s: calls to Free_list::allocate: %u\n"),
236 program_name, Free_list::num_allocates);
237 fprintf(stderr, _("%s: nodes visited: %u\n"),
238 program_name, Free_list::num_allocate_visits);
239 }
240
241 // A Hash_task computes the MD5 checksum of an array of char.
242 // It has a blocker on either side (i.e., the task cannot run until
243 // the first is unblocked, and it unblocks the second after running).
244
245 class Hash_task : public Task
246 {
247 public:
Hash_task(const unsigned char * src,size_t size,unsigned char * dst,Task_token * build_id_blocker,Task_token * final_blocker)248 Hash_task(const unsigned char* src,
249 size_t size,
250 unsigned char* dst,
251 Task_token* build_id_blocker,
252 Task_token* final_blocker)
253 : src_(src), size_(size), dst_(dst), build_id_blocker_(build_id_blocker),
254 final_blocker_(final_blocker)
255 { }
256
257 void
run(Workqueue *)258 run(Workqueue*)
259 { md5_buffer(reinterpret_cast<const char*>(src_), size_, dst_); }
260
261 Task_token*
262 is_runnable();
263
264 // Unblock FINAL_BLOCKER_ when done.
265 void
locks(Task_locker * tl)266 locks(Task_locker* tl)
267 { tl->add(this, this->final_blocker_); }
268
269 std::string
get_name() const270 get_name() const
271 { return "Hash_task"; }
272
273 private:
274 const unsigned char* const src_;
275 const size_t size_;
276 unsigned char* const dst_;
277 Task_token* const build_id_blocker_;
278 Task_token* const final_blocker_;
279 };
280
281 Task_token*
is_runnable()282 Hash_task::is_runnable()
283 {
284 if (this->build_id_blocker_->is_blocked())
285 return this->build_id_blocker_;
286 return NULL;
287 }
288
289 // Layout::Relaxation_debug_check methods.
290
291 // Check that sections and special data are in reset states.
292 // We do not save states for Output_sections and special Output_data.
293 // So we check that they have not assigned any addresses or offsets.
294 // clean_up_after_relaxation simply resets their addresses and offsets.
295 void
check_output_data_for_reset_values(const Layout::Section_list & sections,const Layout::Data_list & special_outputs,const Layout::Data_list & relax_outputs)296 Layout::Relaxation_debug_check::check_output_data_for_reset_values(
297 const Layout::Section_list& sections,
298 const Layout::Data_list& special_outputs,
299 const Layout::Data_list& relax_outputs)
300 {
301 for(Layout::Section_list::const_iterator p = sections.begin();
302 p != sections.end();
303 ++p)
304 gold_assert((*p)->address_and_file_offset_have_reset_values());
305
306 for(Layout::Data_list::const_iterator p = special_outputs.begin();
307 p != special_outputs.end();
308 ++p)
309 gold_assert((*p)->address_and_file_offset_have_reset_values());
310
311 gold_assert(relax_outputs.empty());
312 }
313
314 // Save information of SECTIONS for checking later.
315
316 void
read_sections(const Layout::Section_list & sections)317 Layout::Relaxation_debug_check::read_sections(
318 const Layout::Section_list& sections)
319 {
320 for(Layout::Section_list::const_iterator p = sections.begin();
321 p != sections.end();
322 ++p)
323 {
324 Output_section* os = *p;
325 Section_info info;
326 info.output_section = os;
327 info.address = os->is_address_valid() ? os->address() : 0;
328 info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
329 info.offset = os->is_offset_valid()? os->offset() : -1 ;
330 this->section_infos_.push_back(info);
331 }
332 }
333
334 // Verify SECTIONS using previously recorded information.
335
336 void
verify_sections(const Layout::Section_list & sections)337 Layout::Relaxation_debug_check::verify_sections(
338 const Layout::Section_list& sections)
339 {
340 size_t i = 0;
341 for(Layout::Section_list::const_iterator p = sections.begin();
342 p != sections.end();
343 ++p, ++i)
344 {
345 Output_section* os = *p;
346 uint64_t address = os->is_address_valid() ? os->address() : 0;
347 off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
348 off_t offset = os->is_offset_valid()? os->offset() : -1 ;
349
350 if (i >= this->section_infos_.size())
351 {
352 gold_fatal("Section_info of %s missing.\n", os->name());
353 }
354 const Section_info& info = this->section_infos_[i];
355 if (os != info.output_section)
356 gold_fatal("Section order changed. Expecting %s but see %s\n",
357 info.output_section->name(), os->name());
358 if (address != info.address
359 || data_size != info.data_size
360 || offset != info.offset)
361 gold_fatal("Section %s changed.\n", os->name());
362 }
363 }
364
365 // Layout_task_runner methods.
366
367 // Lay out the sections. This is called after all the input objects
368 // have been read.
369
370 void
run(Workqueue * workqueue,const Task * task)371 Layout_task_runner::run(Workqueue* workqueue, const Task* task)
372 {
373 // See if any of the input definitions violate the One Definition Rule.
374 // TODO: if this is too slow, do this as a task, rather than inline.
375 this->symtab_->detect_odr_violations(task, this->options_.output_file_name());
376
377 Layout* layout = this->layout_;
378 off_t file_size = layout->finalize(this->input_objects_,
379 this->symtab_,
380 this->target_,
381 task);
382
383 // Now we know the final size of the output file and we know where
384 // each piece of information goes.
385
386 if (this->mapfile_ != NULL)
387 {
388 this->mapfile_->print_discarded_sections(this->input_objects_);
389 layout->print_to_mapfile(this->mapfile_);
390 }
391
392 Output_file* of;
393 if (layout->incremental_base() == NULL)
394 {
395 of = new Output_file(parameters->options().output_file_name());
396 if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
397 of->set_is_temporary();
398 of->open(file_size);
399 }
400 else
401 {
402 of = layout->incremental_base()->output_file();
403
404 // Apply the incremental relocations for symbols whose values
405 // have changed. We do this before we resize the file and start
406 // writing anything else to it, so that we can read the old
407 // incremental information from the file before (possibly)
408 // overwriting it.
409 if (parameters->incremental_update())
410 layout->incremental_base()->apply_incremental_relocs(this->symtab_,
411 this->layout_,
412 of);
413
414 of->resize(file_size);
415 }
416
417 // Queue up the final set of tasks.
418 gold::queue_final_tasks(this->options_, this->input_objects_,
419 this->symtab_, layout, workqueue, of);
420 }
421
422 // Layout methods.
423
Layout(int number_of_input_files,Script_options * script_options)424 Layout::Layout(int number_of_input_files, Script_options* script_options)
425 : number_of_input_files_(number_of_input_files),
426 script_options_(script_options),
427 namepool_(),
428 sympool_(),
429 dynpool_(),
430 signatures_(),
431 section_name_map_(),
432 segment_list_(),
433 section_list_(),
434 unattached_section_list_(),
435 special_output_list_(),
436 relax_output_list_(),
437 section_headers_(NULL),
438 tls_segment_(NULL),
439 relro_segment_(NULL),
440 interp_segment_(NULL),
441 increase_relro_(0),
442 symtab_section_(NULL),
443 symtab_xindex_(NULL),
444 dynsym_section_(NULL),
445 dynsym_xindex_(NULL),
446 dynamic_section_(NULL),
447 dynamic_symbol_(NULL),
448 dynamic_data_(NULL),
449 eh_frame_section_(NULL),
450 eh_frame_data_(NULL),
451 added_eh_frame_data_(false),
452 eh_frame_hdr_section_(NULL),
453 gdb_index_data_(NULL),
454 build_id_note_(NULL),
455 array_of_hashes_(NULL),
456 size_of_array_of_hashes_(0),
457 input_view_(NULL),
458 debug_abbrev_(NULL),
459 debug_info_(NULL),
460 group_signatures_(),
461 output_file_size_(-1),
462 have_added_input_section_(false),
463 sections_are_attached_(false),
464 input_requires_executable_stack_(false),
465 input_with_gnu_stack_note_(false),
466 input_without_gnu_stack_note_(false),
467 has_static_tls_(false),
468 any_postprocessing_sections_(false),
469 resized_signatures_(false),
470 have_stabstr_section_(false),
471 section_ordering_specified_(false),
472 unique_segment_for_sections_specified_(false),
473 incremental_inputs_(NULL),
474 record_output_section_data_from_script_(false),
475 script_output_section_data_list_(),
476 segment_states_(NULL),
477 relaxation_debug_check_(NULL),
478 section_order_map_(),
479 section_segment_map_(),
480 input_section_position_(),
481 input_section_glob_(),
482 incremental_base_(NULL),
483 free_list_()
484 {
485 // Make space for more than enough segments for a typical file.
486 // This is just for efficiency--it's OK if we wind up needing more.
487 this->segment_list_.reserve(12);
488
489 // We expect two unattached Output_data objects: the file header and
490 // the segment headers.
491 this->special_output_list_.reserve(2);
492
493 // Initialize structure needed for an incremental build.
494 if (parameters->incremental())
495 this->incremental_inputs_ = new Incremental_inputs;
496
497 // The section name pool is worth optimizing in all cases, because
498 // it is small, but there are often overlaps due to .rel sections.
499 this->namepool_.set_optimize();
500 }
501
502 // For incremental links, record the base file to be modified.
503
504 void
set_incremental_base(Incremental_binary * base)505 Layout::set_incremental_base(Incremental_binary* base)
506 {
507 this->incremental_base_ = base;
508 this->free_list_.init(base->output_file()->filesize(), true);
509 }
510
511 // Hash a key we use to look up an output section mapping.
512
513 size_t
operator ()(const Layout::Key & k) const514 Layout::Hash_key::operator()(const Layout::Key& k) const
515 {
516 return k.first + k.second.first + k.second.second;
517 }
518
519 // These are the debug sections that are actually used by gdb.
520 // Currently, we've checked versions of gdb up to and including 7.4.
521 // We only check the part of the name that follows ".debug_" or
522 // ".zdebug_".
523
524 static const char* gdb_sections[] =
525 {
526 "abbrev",
527 "addr", // Fission extension
528 // "aranges", // not used by gdb as of 7.4
529 "frame",
530 "gdb_scripts",
531 "info",
532 "types",
533 "line",
534 "loc",
535 "macinfo",
536 "macro",
537 // "pubnames", // not used by gdb as of 7.4
538 // "pubtypes", // not used by gdb as of 7.4
539 // "gnu_pubnames", // Fission extension
540 // "gnu_pubtypes", // Fission extension
541 "ranges",
542 "str",
543 "str_offsets",
544 };
545
546 // This is the minimum set of sections needed for line numbers.
547
548 static const char* lines_only_debug_sections[] =
549 {
550 "abbrev",
551 // "addr", // Fission extension
552 // "aranges", // not used by gdb as of 7.4
553 // "frame",
554 // "gdb_scripts",
555 "info",
556 // "types",
557 "line",
558 // "loc",
559 // "macinfo",
560 // "macro",
561 // "pubnames", // not used by gdb as of 7.4
562 // "pubtypes", // not used by gdb as of 7.4
563 // "gnu_pubnames", // Fission extension
564 // "gnu_pubtypes", // Fission extension
565 // "ranges",
566 "str",
567 "str_offsets", // Fission extension
568 };
569
570 // These sections are the DWARF fast-lookup tables, and are not needed
571 // when building a .gdb_index section.
572
573 static const char* gdb_fast_lookup_sections[] =
574 {
575 "aranges",
576 "pubnames",
577 "gnu_pubnames",
578 "pubtypes",
579 "gnu_pubtypes",
580 };
581
582 // Returns whether the given debug section is in the list of
583 // debug-sections-used-by-some-version-of-gdb. SUFFIX is the
584 // portion of the name following ".debug_" or ".zdebug_".
585
586 static inline bool
is_gdb_debug_section(const char * suffix)587 is_gdb_debug_section(const char* suffix)
588 {
589 // We can do this faster: binary search or a hashtable. But why bother?
590 for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
591 if (strcmp(suffix, gdb_sections[i]) == 0)
592 return true;
593 return false;
594 }
595
596 // Returns whether the given section is needed for lines-only debugging.
597
598 static inline bool
is_lines_only_debug_section(const char * suffix)599 is_lines_only_debug_section(const char* suffix)
600 {
601 // We can do this faster: binary search or a hashtable. But why bother?
602 for (size_t i = 0;
603 i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
604 ++i)
605 if (strcmp(suffix, lines_only_debug_sections[i]) == 0)
606 return true;
607 return false;
608 }
609
610 // Returns whether the given section is a fast-lookup section that
611 // will not be needed when building a .gdb_index section.
612
613 static inline bool
is_gdb_fast_lookup_section(const char * suffix)614 is_gdb_fast_lookup_section(const char* suffix)
615 {
616 // We can do this faster: binary search or a hashtable. But why bother?
617 for (size_t i = 0;
618 i < sizeof(gdb_fast_lookup_sections)/sizeof(*gdb_fast_lookup_sections);
619 ++i)
620 if (strcmp(suffix, gdb_fast_lookup_sections[i]) == 0)
621 return true;
622 return false;
623 }
624
625 // Sometimes we compress sections. This is typically done for
626 // sections that are not part of normal program execution (such as
627 // .debug_* sections), and where the readers of these sections know
628 // how to deal with compressed sections. This routine doesn't say for
629 // certain whether we'll compress -- it depends on commandline options
630 // as well -- just whether this section is a candidate for compression.
631 // (The Output_compressed_section class decides whether to compress
632 // a given section, and picks the name of the compressed section.)
633
634 static bool
is_compressible_debug_section(const char * secname)635 is_compressible_debug_section(const char* secname)
636 {
637 return (is_prefix_of(".debug", secname));
638 }
639
640 // We may see compressed debug sections in input files. Return TRUE
641 // if this is the name of a compressed debug section.
642
643 bool
is_compressed_debug_section(const char * secname)644 is_compressed_debug_section(const char* secname)
645 {
646 return (is_prefix_of(".zdebug", secname));
647 }
648
649 // Whether to include this section in the link.
650
651 template<int size, bool big_endian>
652 bool
include_section(Sized_relobj_file<size,big_endian> *,const char * name,const elfcpp::Shdr<size,big_endian> & shdr)653 Layout::include_section(Sized_relobj_file<size, big_endian>*, const char* name,
654 const elfcpp::Shdr<size, big_endian>& shdr)
655 {
656 if (!parameters->options().relocatable()
657 && (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE))
658 return false;
659
660 elfcpp::Elf_Word sh_type = shdr.get_sh_type();
661
662 if ((sh_type >= elfcpp::SHT_LOOS && sh_type <= elfcpp::SHT_HIOS)
663 || (sh_type >= elfcpp::SHT_LOPROC && sh_type <= elfcpp::SHT_HIPROC))
664 return parameters->target().should_include_section(sh_type);
665
666 switch (sh_type)
667 {
668 case elfcpp::SHT_NULL:
669 case elfcpp::SHT_SYMTAB:
670 case elfcpp::SHT_DYNSYM:
671 case elfcpp::SHT_HASH:
672 case elfcpp::SHT_DYNAMIC:
673 case elfcpp::SHT_SYMTAB_SHNDX:
674 return false;
675
676 case elfcpp::SHT_STRTAB:
677 // Discard the sections which have special meanings in the ELF
678 // ABI. Keep others (e.g., .stabstr). We could also do this by
679 // checking the sh_link fields of the appropriate sections.
680 return (strcmp(name, ".dynstr") != 0
681 && strcmp(name, ".strtab") != 0
682 && strcmp(name, ".shstrtab") != 0);
683
684 case elfcpp::SHT_RELA:
685 case elfcpp::SHT_REL:
686 case elfcpp::SHT_GROUP:
687 // If we are emitting relocations these should be handled
688 // elsewhere.
689 gold_assert(!parameters->options().relocatable());
690 return false;
691
692 case elfcpp::SHT_PROGBITS:
693 if (parameters->options().strip_debug()
694 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
695 {
696 if (is_debug_info_section(name))
697 return false;
698 }
699 if (parameters->options().strip_debug_non_line()
700 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
701 {
702 // Debugging sections can only be recognized by name.
703 if (is_prefix_of(".debug_", name)
704 && !is_lines_only_debug_section(name + 7))
705 return false;
706 if (is_prefix_of(".zdebug_", name)
707 && !is_lines_only_debug_section(name + 8))
708 return false;
709 }
710 if (parameters->options().strip_debug_gdb()
711 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
712 {
713 // Debugging sections can only be recognized by name.
714 if (is_prefix_of(".debug_", name)
715 && !is_gdb_debug_section(name + 7))
716 return false;
717 if (is_prefix_of(".zdebug_", name)
718 && !is_gdb_debug_section(name + 8))
719 return false;
720 }
721 if (parameters->options().gdb_index()
722 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
723 {
724 // When building .gdb_index, we can strip .debug_pubnames,
725 // .debug_pubtypes, and .debug_aranges sections.
726 if (is_prefix_of(".debug_", name)
727 && is_gdb_fast_lookup_section(name + 7))
728 return false;
729 if (is_prefix_of(".zdebug_", name)
730 && is_gdb_fast_lookup_section(name + 8))
731 return false;
732 }
733 if (parameters->options().strip_lto_sections()
734 && !parameters->options().relocatable()
735 && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
736 {
737 // Ignore LTO sections containing intermediate code.
738 if (is_prefix_of(".gnu.lto_", name))
739 return false;
740 }
741 // The GNU linker strips .gnu_debuglink sections, so we do too.
742 // This is a feature used to keep debugging information in
743 // separate files.
744 if (strcmp(name, ".gnu_debuglink") == 0)
745 return false;
746 return true;
747
748 default:
749 return true;
750 }
751 }
752
753 // Return an output section named NAME, or NULL if there is none.
754
755 Output_section*
find_output_section(const char * name) const756 Layout::find_output_section(const char* name) const
757 {
758 for (Section_list::const_iterator p = this->section_list_.begin();
759 p != this->section_list_.end();
760 ++p)
761 if (strcmp((*p)->name(), name) == 0)
762 return *p;
763 return NULL;
764 }
765
766 // Return an output segment of type TYPE, with segment flags SET set
767 // and segment flags CLEAR clear. Return NULL if there is none.
768
769 Output_segment*
find_output_segment(elfcpp::PT type,elfcpp::Elf_Word set,elfcpp::Elf_Word clear) const770 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
771 elfcpp::Elf_Word clear) const
772 {
773 for (Segment_list::const_iterator p = this->segment_list_.begin();
774 p != this->segment_list_.end();
775 ++p)
776 if (static_cast<elfcpp::PT>((*p)->type()) == type
777 && ((*p)->flags() & set) == set
778 && ((*p)->flags() & clear) == 0)
779 return *p;
780 return NULL;
781 }
782
783 // When we put a .ctors or .dtors section with more than one word into
784 // a .init_array or .fini_array section, we need to reverse the words
785 // in the .ctors/.dtors section. This is because .init_array executes
786 // constructors front to back, where .ctors executes them back to
787 // front, and vice-versa for .fini_array/.dtors. Although we do want
788 // to remap .ctors/.dtors into .init_array/.fini_array because it can
789 // be more efficient, we don't want to change the order in which
790 // constructors/destructors are run. This set just keeps track of
791 // these sections which need to be reversed. It is only changed by
792 // Layout::layout. It should be a private member of Layout, but that
793 // would require layout.h to #include object.h to get the definition
794 // of Section_id.
795 static Unordered_set<Section_id, Section_id_hash> ctors_sections_in_init_array;
796
797 // Return whether OBJECT/SHNDX is a .ctors/.dtors section mapped to a
798 // .init_array/.fini_array section.
799
800 bool
is_ctors_in_init_array(Relobj * relobj,unsigned int shndx) const801 Layout::is_ctors_in_init_array(Relobj* relobj, unsigned int shndx) const
802 {
803 return (ctors_sections_in_init_array.find(Section_id(relobj, shndx))
804 != ctors_sections_in_init_array.end());
805 }
806
807 // Return the output section to use for section NAME with type TYPE
808 // and section flags FLAGS. NAME must be canonicalized in the string
809 // pool, and NAME_KEY is the key. ORDER is where this should appear
810 // in the output sections. IS_RELRO is true for a relro section.
811
812 Output_section*
get_output_section(const char * name,Stringpool::Key name_key,elfcpp::Elf_Word type,elfcpp::Elf_Xword flags,Output_section_order order,bool is_relro)813 Layout::get_output_section(const char* name, Stringpool::Key name_key,
814 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
815 Output_section_order order, bool is_relro)
816 {
817 elfcpp::Elf_Word lookup_type = type;
818
819 // For lookup purposes, treat INIT_ARRAY, FINI_ARRAY, and
820 // PREINIT_ARRAY like PROGBITS. This ensures that we combine
821 // .init_array, .fini_array, and .preinit_array sections by name
822 // whatever their type in the input file. We do this because the
823 // types are not always right in the input files.
824 if (lookup_type == elfcpp::SHT_INIT_ARRAY
825 || lookup_type == elfcpp::SHT_FINI_ARRAY
826 || lookup_type == elfcpp::SHT_PREINIT_ARRAY)
827 lookup_type = elfcpp::SHT_PROGBITS;
828
829 elfcpp::Elf_Xword lookup_flags = flags;
830
831 // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
832 // read-write with read-only sections. Some other ELF linkers do
833 // not do this. FIXME: Perhaps there should be an option
834 // controlling this.
835 lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
836
837 const Key key(name_key, std::make_pair(lookup_type, lookup_flags));
838 const std::pair<Key, Output_section*> v(key, NULL);
839 std::pair<Section_name_map::iterator, bool> ins(
840 this->section_name_map_.insert(v));
841
842 if (!ins.second)
843 return ins.first->second;
844 else
845 {
846 // This is the first time we've seen this name/type/flags
847 // combination. For compatibility with the GNU linker, we
848 // combine sections with contents and zero flags with sections
849 // with non-zero flags. This is a workaround for cases where
850 // assembler code forgets to set section flags. FIXME: Perhaps
851 // there should be an option to control this.
852 Output_section* os = NULL;
853
854 if (lookup_type == elfcpp::SHT_PROGBITS)
855 {
856 if (flags == 0)
857 {
858 Output_section* same_name = this->find_output_section(name);
859 if (same_name != NULL
860 && (same_name->type() == elfcpp::SHT_PROGBITS
861 || same_name->type() == elfcpp::SHT_INIT_ARRAY
862 || same_name->type() == elfcpp::SHT_FINI_ARRAY
863 || same_name->type() == elfcpp::SHT_PREINIT_ARRAY)
864 && (same_name->flags() & elfcpp::SHF_TLS) == 0)
865 os = same_name;
866 }
867 else if ((flags & elfcpp::SHF_TLS) == 0)
868 {
869 elfcpp::Elf_Xword zero_flags = 0;
870 const Key zero_key(name_key, std::make_pair(lookup_type,
871 zero_flags));
872 Section_name_map::iterator p =
873 this->section_name_map_.find(zero_key);
874 if (p != this->section_name_map_.end())
875 os = p->second;
876 }
877 }
878
879 if (os == NULL)
880 os = this->make_output_section(name, type, flags, order, is_relro);
881
882 ins.first->second = os;
883 return os;
884 }
885 }
886
887 // Returns TRUE iff NAME (an input section from RELOBJ) will
888 // be mapped to an output section that should be KEPT.
889
890 bool
keep_input_section(const Relobj * relobj,const char * name)891 Layout::keep_input_section(const Relobj* relobj, const char* name)
892 {
893 if (! this->script_options_->saw_sections_clause())
894 return false;
895
896 Script_sections* ss = this->script_options_->script_sections();
897 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
898 Output_section** output_section_slot;
899 Script_sections::Section_type script_section_type;
900 bool keep;
901
902 name = ss->output_section_name(file_name, name, &output_section_slot,
903 &script_section_type, &keep);
904 return name != NULL && keep;
905 }
906
907 // Clear the input section flags that should not be copied to the
908 // output section.
909
910 elfcpp::Elf_Xword
get_output_section_flags(elfcpp::Elf_Xword input_section_flags)911 Layout::get_output_section_flags(elfcpp::Elf_Xword input_section_flags)
912 {
913 // Some flags in the input section should not be automatically
914 // copied to the output section.
915 input_section_flags &= ~ (elfcpp::SHF_INFO_LINK
916 | elfcpp::SHF_GROUP
917 | elfcpp::SHF_MERGE
918 | elfcpp::SHF_STRINGS);
919
920 // We only clear the SHF_LINK_ORDER flag in for
921 // a non-relocatable link.
922 if (!parameters->options().relocatable())
923 input_section_flags &= ~elfcpp::SHF_LINK_ORDER;
924
925 return input_section_flags;
926 }
927
928 // Pick the output section to use for section NAME, in input file
929 // RELOBJ, with type TYPE and flags FLAGS. RELOBJ may be NULL for a
930 // linker created section. IS_INPUT_SECTION is true if we are
931 // choosing an output section for an input section found in a input
932 // file. ORDER is where this section should appear in the output
933 // sections. IS_RELRO is true for a relro section. This will return
934 // NULL if the input section should be discarded.
935
936 Output_section*
choose_output_section(const Relobj * relobj,const char * name,elfcpp::Elf_Word type,elfcpp::Elf_Xword flags,bool is_input_section,Output_section_order order,bool is_relro)937 Layout::choose_output_section(const Relobj* relobj, const char* name,
938 elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
939 bool is_input_section, Output_section_order order,
940 bool is_relro)
941 {
942 // We should not see any input sections after we have attached
943 // sections to segments.
944 gold_assert(!is_input_section || !this->sections_are_attached_);
945
946 flags = this->get_output_section_flags(flags);
947
948 if (this->script_options_->saw_sections_clause())
949 {
950 // We are using a SECTIONS clause, so the output section is
951 // chosen based only on the name.
952
953 Script_sections* ss = this->script_options_->script_sections();
954 const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
955 Output_section** output_section_slot;
956 Script_sections::Section_type script_section_type;
957 const char* orig_name = name;
958 bool keep;
959 name = ss->output_section_name(file_name, name, &output_section_slot,
960 &script_section_type, &keep);
961
962 if (name == NULL)
963 {
964 gold_debug(DEBUG_SCRIPT, _("Unable to create output section '%s' "
965 "because it is not allowed by the "
966 "SECTIONS clause of the linker script"),
967 orig_name);
968 // The SECTIONS clause says to discard this input section.
969 return NULL;
970 }
971
972 // We can only handle script section types ST_NONE and ST_NOLOAD.
973 switch (script_section_type)
974 {
975 case Script_sections::ST_NONE:
976 break;
977 case Script_sections::ST_NOLOAD:
978 flags &= elfcpp::SHF_ALLOC;
979 break;
980 default:
981 gold_unreachable();
982 }
983
984 // If this is an orphan section--one not mentioned in the linker
985 // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
986 // default processing below.
987
988 if (output_section_slot != NULL)
989 {
990 if (*output_section_slot != NULL)
991 {
992 (*output_section_slot)->update_flags_for_input_section(flags);
993 return *output_section_slot;
994 }
995
996 // We don't put sections found in the linker script into
997 // SECTION_NAME_MAP_. That keeps us from getting confused
998 // if an orphan section is mapped to a section with the same
999 // name as one in the linker script.
1000
1001 name = this->namepool_.add(name, false, NULL);
1002
1003 Output_section* os = this->make_output_section(name, type, flags,
1004 order, is_relro);
1005
1006 os->set_found_in_sections_clause();
1007
1008 // Special handling for NOLOAD sections.
1009 if (script_section_type == Script_sections::ST_NOLOAD)
1010 {
1011 os->set_is_noload();
1012
1013 // The constructor of Output_section sets addresses of non-ALLOC
1014 // sections to 0 by default. We don't want that for NOLOAD
1015 // sections even if they have no SHF_ALLOC flag.
1016 if ((os->flags() & elfcpp::SHF_ALLOC) == 0
1017 && os->is_address_valid())
1018 {
1019 gold_assert(os->address() == 0
1020 && !os->is_offset_valid()
1021 && !os->is_data_size_valid());
1022 os->reset_address_and_file_offset();
1023 }
1024 }
1025
1026 *output_section_slot = os;
1027 return os;
1028 }
1029 }
1030
1031 // FIXME: Handle SHF_OS_NONCONFORMING somewhere.
1032
1033 size_t len = strlen(name);
1034 char* uncompressed_name = NULL;
1035
1036 // Compressed debug sections should be mapped to the corresponding
1037 // uncompressed section.
1038 if (is_compressed_debug_section(name))
1039 {
1040 uncompressed_name = new char[len];
1041 uncompressed_name[0] = '.';
1042 gold_assert(name[0] == '.' && name[1] == 'z');
1043 strncpy(&uncompressed_name[1], &name[2], len - 2);
1044 uncompressed_name[len - 1] = '\0';
1045 len -= 1;
1046 name = uncompressed_name;
1047 }
1048
1049 // Turn NAME from the name of the input section into the name of the
1050 // output section.
1051 if (is_input_section
1052 && !this->script_options_->saw_sections_clause()
1053 && !parameters->options().relocatable())
1054 {
1055 const char *orig_name = name;
1056 name = parameters->target().output_section_name(relobj, name, &len);
1057 if (name == NULL)
1058 name = Layout::output_section_name(relobj, orig_name, &len);
1059 }
1060
1061 Stringpool::Key name_key;
1062 name = this->namepool_.add_with_length(name, len, true, &name_key);
1063
1064 if (uncompressed_name != NULL)
1065 delete[] uncompressed_name;
1066
1067 // Find or make the output section. The output section is selected
1068 // based on the section name, type, and flags.
1069 return this->get_output_section(name, name_key, type, flags, order, is_relro);
1070 }
1071
1072 // For incremental links, record the initial fixed layout of a section
1073 // from the base file, and return a pointer to the Output_section.
1074
1075 template<int size, bool big_endian>
1076 Output_section*
init_fixed_output_section(const char * name,elfcpp::Shdr<size,big_endian> & shdr)1077 Layout::init_fixed_output_section(const char* name,
1078 elfcpp::Shdr<size, big_endian>& shdr)
1079 {
1080 unsigned int sh_type = shdr.get_sh_type();
1081
1082 // We preserve the layout of PROGBITS, NOBITS, INIT_ARRAY, FINI_ARRAY,
1083 // PRE_INIT_ARRAY, and NOTE sections.
1084 // All others will be created from scratch and reallocated.
1085 if (!can_incremental_update(sh_type))
1086 return NULL;
1087
1088 // If we're generating a .gdb_index section, we need to regenerate
1089 // it from scratch.
1090 if (parameters->options().gdb_index()
1091 && sh_type == elfcpp::SHT_PROGBITS
1092 && strcmp(name, ".gdb_index") == 0)
1093 return NULL;
1094
1095 typename elfcpp::Elf_types<size>::Elf_Addr sh_addr = shdr.get_sh_addr();
1096 typename elfcpp::Elf_types<size>::Elf_Off sh_offset = shdr.get_sh_offset();
1097 typename elfcpp::Elf_types<size>::Elf_WXword sh_size = shdr.get_sh_size();
1098 typename elfcpp::Elf_types<size>::Elf_WXword sh_flags = shdr.get_sh_flags();
1099 typename elfcpp::Elf_types<size>::Elf_WXword sh_addralign =
1100 shdr.get_sh_addralign();
1101
1102 // Make the output section.
1103 Stringpool::Key name_key;
1104 name = this->namepool_.add(name, true, &name_key);
1105 Output_section* os = this->get_output_section(name, name_key, sh_type,
1106 sh_flags, ORDER_INVALID, false);
1107 os->set_fixed_layout(sh_addr, sh_offset, sh_size, sh_addralign);
1108 if (sh_type != elfcpp::SHT_NOBITS)
1109 this->free_list_.remove(sh_offset, sh_offset + sh_size);
1110 return os;
1111 }
1112
1113 // Return the index by which an input section should be ordered. This
1114 // is used to sort some .text sections, for compatibility with GNU ld.
1115
1116 int
special_ordering_of_input_section(const char * name)1117 Layout::special_ordering_of_input_section(const char* name)
1118 {
1119 // The GNU linker has some special handling for some sections that
1120 // wind up in the .text section. Sections that start with these
1121 // prefixes must appear first, and must appear in the order listed
1122 // here.
1123 static const char* const text_section_sort[] =
1124 {
1125 ".text.unlikely",
1126 ".text.exit",
1127 ".text.startup",
1128 ".text.hot"
1129 };
1130
1131 for (size_t i = 0;
1132 i < sizeof(text_section_sort) / sizeof(text_section_sort[0]);
1133 i++)
1134 if (is_prefix_of(text_section_sort[i], name))
1135 return i;
1136
1137 return -1;
1138 }
1139
1140 // Return the output section to use for input section SHNDX, with name
1141 // NAME, with header HEADER, from object OBJECT. RELOC_SHNDX is the
1142 // index of a relocation section which applies to this section, or 0
1143 // if none, or -1U if more than one. RELOC_TYPE is the type of the
1144 // relocation section if there is one. Set *OFF to the offset of this
1145 // input section without the output section. Return NULL if the
1146 // section should be discarded. Set *OFF to -1 if the section
1147 // contents should not be written directly to the output file, but
1148 // will instead receive special handling.
1149
1150 template<int size, bool big_endian>
1151 Output_section*
layout(Sized_relobj_file<size,big_endian> * object,unsigned int shndx,const char * name,const elfcpp::Shdr<size,big_endian> & shdr,unsigned int reloc_shndx,unsigned int,off_t * off)1152 Layout::layout(Sized_relobj_file<size, big_endian>* object, unsigned int shndx,
1153 const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
1154 unsigned int reloc_shndx, unsigned int, off_t* off)
1155 {
1156 *off = 0;
1157
1158 if (!this->include_section(object, name, shdr))
1159 return NULL;
1160
1161 elfcpp::Elf_Word sh_type = shdr.get_sh_type();
1162
1163 // In a relocatable link a grouped section must not be combined with
1164 // any other sections.
1165 Output_section* os;
1166 if (parameters->options().relocatable()
1167 && (shdr.get_sh_flags() & elfcpp::SHF_GROUP) != 0)
1168 {
1169 name = this->namepool_.add(name, true, NULL);
1170 os = this->make_output_section(name, sh_type, shdr.get_sh_flags(),
1171 ORDER_INVALID, false);
1172 }
1173 else
1174 {
1175 // Plugins can choose to place one or more subsets of sections in
1176 // unique segments and this is done by mapping these section subsets
1177 // to unique output sections. Check if this section needs to be
1178 // remapped to a unique output section.
1179 Section_segment_map::iterator it
1180 = this->section_segment_map_.find(Const_section_id(object, shndx));
1181 if (it == this->section_segment_map_.end())
1182 {
1183 os = this->choose_output_section(object, name, sh_type,
1184 shdr.get_sh_flags(), true,
1185 ORDER_INVALID, false);
1186 }
1187 else
1188 {
1189 // We know the name of the output section, directly call
1190 // get_output_section here by-passing choose_output_section.
1191 elfcpp::Elf_Xword flags
1192 = this->get_output_section_flags(shdr.get_sh_flags());
1193
1194 const char* os_name = it->second->name;
1195 Stringpool::Key name_key;
1196 os_name = this->namepool_.add(os_name, true, &name_key);
1197 os = this->get_output_section(os_name, name_key, sh_type, flags,
1198 ORDER_INVALID, false);
1199 if (!os->is_unique_segment())
1200 {
1201 os->set_is_unique_segment();
1202 os->set_extra_segment_flags(it->second->flags);
1203 os->set_segment_alignment(it->second->align);
1204 }
1205 }
1206 if (os == NULL)
1207 return NULL;
1208 }
1209
1210 // By default the GNU linker sorts input sections whose names match
1211 // .ctors.*, .dtors.*, .init_array.*, or .fini_array.*. The
1212 // sections are sorted by name. This is used to implement
1213 // constructor priority ordering. We are compatible. When we put
1214 // .ctor sections in .init_array and .dtor sections in .fini_array,
1215 // we must also sort plain .ctor and .dtor sections.
1216 if (!this->script_options_->saw_sections_clause()
1217 && !parameters->options().relocatable()
1218 && (is_prefix_of(".ctors.", name)
1219 || is_prefix_of(".dtors.", name)
1220 || is_prefix_of(".init_array.", name)
1221 || is_prefix_of(".fini_array.", name)
1222 || (parameters->options().ctors_in_init_array()
1223 && (strcmp(name, ".ctors") == 0
1224 || strcmp(name, ".dtors") == 0))))
1225 os->set_must_sort_attached_input_sections();
1226
1227 // By default the GNU linker sorts some special text sections ahead
1228 // of others. We are compatible.
1229 if (parameters->options().text_reorder()
1230 && !this->script_options_->saw_sections_clause()
1231 && !this->is_section_ordering_specified()
1232 && !parameters->options().relocatable()
1233 && Layout::special_ordering_of_input_section(name) >= 0)
1234 os->set_must_sort_attached_input_sections();
1235
1236 // If this is a .ctors or .ctors.* section being mapped to a
1237 // .init_array section, or a .dtors or .dtors.* section being mapped
1238 // to a .fini_array section, we will need to reverse the words if
1239 // there is more than one. Record this section for later. See
1240 // ctors_sections_in_init_array above.
1241 if (!this->script_options_->saw_sections_clause()
1242 && !parameters->options().relocatable()
1243 && shdr.get_sh_size() > size / 8
1244 && (((strcmp(name, ".ctors") == 0
1245 || is_prefix_of(".ctors.", name))
1246 && strcmp(os->name(), ".init_array") == 0)
1247 || ((strcmp(name, ".dtors") == 0
1248 || is_prefix_of(".dtors.", name))
1249 && strcmp(os->name(), ".fini_array") == 0)))
1250 ctors_sections_in_init_array.insert(Section_id(object, shndx));
1251
1252 // FIXME: Handle SHF_LINK_ORDER somewhere.
1253
1254 elfcpp::Elf_Xword orig_flags = os->flags();
1255
1256 *off = os->add_input_section(this, object, shndx, name, shdr, reloc_shndx,
1257 this->script_options_->saw_sections_clause());
1258
1259 // If the flags changed, we may have to change the order.
1260 if ((orig_flags & elfcpp::SHF_ALLOC) != 0)
1261 {
1262 orig_flags &= (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
1263 elfcpp::Elf_Xword new_flags =
1264 os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);
1265 if (orig_flags != new_flags)
1266 os->set_order(this->default_section_order(os, false));
1267 }
1268
1269 this->have_added_input_section_ = true;
1270
1271 return os;
1272 }
1273
1274 // Maps section SECN to SEGMENT s.
1275 void
insert_section_segment_map(Const_section_id secn,Unique_segment_info * s)1276 Layout::insert_section_segment_map(Const_section_id secn,
1277 Unique_segment_info *s)
1278 {
1279 gold_assert(this->unique_segment_for_sections_specified_);
1280 this->section_segment_map_[secn] = s;
1281 }
1282
1283 // Handle a relocation section when doing a relocatable link.
1284
1285 template<int size, bool big_endian>
1286 Output_section*
layout_reloc(Sized_relobj_file<size,big_endian> * object,unsigned int,const elfcpp::Shdr<size,big_endian> & shdr,Output_section * data_section,Relocatable_relocs * rr)1287 Layout::layout_reloc(Sized_relobj_file<size, big_endian>* object,
1288 unsigned int,
1289 const elfcpp::Shdr<size, big_endian>& shdr,
1290 Output_section* data_section,
1291 Relocatable_relocs* rr)
1292 {
1293 gold_assert(parameters->options().relocatable()
1294 || parameters->options().emit_relocs());
1295
1296 int sh_type = shdr.get_sh_type();
1297
1298 std::string name;
1299 if (sh_type == elfcpp::SHT_REL)
1300 name = ".rel";
1301 else if (sh_type == elfcpp::SHT_RELA)
1302 name = ".rela";
1303 else
1304 gold_unreachable();
1305 name += data_section->name();
1306
1307 // In a relocatable link relocs for a grouped section must not be
1308 // combined with other reloc sections.
1309 Output_section* os;
1310 if (!parameters->options().relocatable()
1311 || (data_section->flags() & elfcpp::SHF_GROUP) == 0)
1312 os = this->choose_output_section(object, name.c_str(), sh_type,
1313 shdr.get_sh_flags(), false,
1314 ORDER_INVALID, false);
1315 else
1316 {
1317 const char* n = this->namepool_.add(name.c_str(), true, NULL);
1318 os = this->make_output_section(n, sh_type, shdr.get_sh_flags(),
1319 ORDER_INVALID, false);
1320 }
1321
1322 os->set_should_link_to_symtab();
1323 os->set_info_section(data_section);
1324
1325 Output_section_data* posd;
1326 if (sh_type == elfcpp::SHT_REL)
1327 {
1328 os->set_entsize(elfcpp::Elf_sizes<size>::rel_size);
1329 posd = new Output_relocatable_relocs<elfcpp::SHT_REL,
1330 size,
1331 big_endian>(rr);
1332 }
1333 else if (sh_type == elfcpp::SHT_RELA)
1334 {
1335 os->set_entsize(elfcpp::Elf_sizes<size>::rela_size);
1336 posd = new Output_relocatable_relocs<elfcpp::SHT_RELA,
1337 size,
1338 big_endian>(rr);
1339 }
1340 else
1341 gold_unreachable();
1342
1343 os->add_output_section_data(posd);
1344 rr->set_output_data(posd);
1345
1346 return os;
1347 }
1348
1349 // Handle a group section when doing a relocatable link.
1350
1351 template<int size, bool big_endian>
1352 void
layout_group(Symbol_table * symtab,Sized_relobj_file<size,big_endian> * object,unsigned int,const char * group_section_name,const char * signature,const elfcpp::Shdr<size,big_endian> & shdr,elfcpp::Elf_Word flags,std::vector<unsigned int> * shndxes)1353 Layout::layout_group(Symbol_table* symtab,
1354 Sized_relobj_file<size, big_endian>* object,
1355 unsigned int,
1356 const char* group_section_name,
1357 const char* signature,
1358 const elfcpp::Shdr<size, big_endian>& shdr,
1359 elfcpp::Elf_Word flags,
1360 std::vector<unsigned int>* shndxes)
1361 {
1362 gold_assert(parameters->options().relocatable());
1363 gold_assert(shdr.get_sh_type() == elfcpp::SHT_GROUP);
1364 group_section_name = this->namepool_.add(group_section_name, true, NULL);
1365 Output_section* os = this->make_output_section(group_section_name,
1366 elfcpp::SHT_GROUP,
1367 shdr.get_sh_flags(),
1368 ORDER_INVALID, false);
1369
1370 // We need to find a symbol with the signature in the symbol table.
1371 // If we don't find one now, we need to look again later.
1372 Symbol* sym = symtab->lookup(signature, NULL);
1373 if (sym != NULL)
1374 os->set_info_symndx(sym);
1375 else
1376 {
1377 // Reserve some space to minimize reallocations.
1378 if (this->group_signatures_.empty())
1379 this->group_signatures_.reserve(this->number_of_input_files_ * 16);
1380
1381 // We will wind up using a symbol whose name is the signature.
1382 // So just put the signature in the symbol name pool to save it.
1383 signature = symtab->canonicalize_name(signature);
1384 this->group_signatures_.push_back(Group_signature(os, signature));
1385 }
1386
1387 os->set_should_link_to_symtab();
1388 os->set_entsize(4);
1389
1390 section_size_type entry_count =
1391 convert_to_section_size_type(shdr.get_sh_size() / 4);
1392 Output_section_data* posd =
1393 new Output_data_group<size, big_endian>(object, entry_count, flags,
1394 shndxes);
1395 os->add_output_section_data(posd);
1396 }
1397
1398 // Special GNU handling of sections name .eh_frame. They will
1399 // normally hold exception frame data as defined by the C++ ABI
1400 // (http://codesourcery.com/cxx-abi/).
1401
1402 template<int size, bool big_endian>
1403 Output_section*
layout_eh_frame(Sized_relobj_file<size,big_endian> * object,const unsigned char * symbols,off_t symbols_size,const unsigned char * symbol_names,off_t symbol_names_size,unsigned int shndx,const elfcpp::Shdr<size,big_endian> & shdr,unsigned int reloc_shndx,unsigned int reloc_type,off_t * off)1404 Layout::layout_eh_frame(Sized_relobj_file<size, big_endian>* object,
1405 const unsigned char* symbols,
1406 off_t symbols_size,
1407 const unsigned char* symbol_names,
1408 off_t symbol_names_size,
1409 unsigned int shndx,
1410 const elfcpp::Shdr<size, big_endian>& shdr,
1411 unsigned int reloc_shndx, unsigned int reloc_type,
1412 off_t* off)
1413 {
1414 gold_assert(shdr.get_sh_type() == elfcpp::SHT_PROGBITS
1415 || shdr.get_sh_type() == elfcpp::SHT_X86_64_UNWIND);
1416 gold_assert((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
1417
1418 Output_section* os = this->make_eh_frame_section(object);
1419 if (os == NULL)
1420 return NULL;
1421
1422 gold_assert(this->eh_frame_section_ == os);
1423
1424 elfcpp::Elf_Xword orig_flags = os->flags();
1425
1426 Eh_frame::Eh_frame_section_disposition disp =
1427 Eh_frame::EH_UNRECOGNIZED_SECTION;
1428 if (!parameters->incremental())
1429 {
1430 disp = this->eh_frame_data_->add_ehframe_input_section(object,
1431 symbols,
1432 symbols_size,
1433 symbol_names,
1434 symbol_names_size,
1435 shndx,
1436 reloc_shndx,
1437 reloc_type);
1438 }
1439
1440 if (disp == Eh_frame::EH_OPTIMIZABLE_SECTION)
1441 {
1442 os->update_flags_for_input_section(shdr.get_sh_flags());
1443
1444 // A writable .eh_frame section is a RELRO section.
1445 if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
1446 != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
1447 {
1448 os->set_is_relro();
1449 os->set_order(ORDER_RELRO);
1450 }
1451
1452 *off = -1;
1453 return os;
1454 }
1455
1456 if (disp == Eh_frame::EH_END_MARKER_SECTION && !this->added_eh_frame_data_)
1457 {
1458 // We found the end marker section, so now we can add the set of
1459 // optimized sections to the output section. We need to postpone
1460 // adding this until we've found a section we can optimize so that
1461 // the .eh_frame section in crtbeginT.o winds up at the start of
1462 // the output section.
1463 os->add_output_section_data(this->eh_frame_data_);
1464 this->added_eh_frame_data_ = true;
1465 }
1466
1467 // We couldn't handle this .eh_frame section for some reason.
1468 // Add it as a normal section.
1469 bool saw_sections_clause = this->script_options_->saw_sections_clause();
1470 *off = os->add_input_section(this, object, shndx, ".eh_frame", shdr,
1471 reloc_shndx, saw_sections_clause);
1472 this->have_added_input_section_ = true;
1473
1474 if ((orig_flags & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR))
1475 != (os->flags() & (elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR)))
1476 os->set_order(this->default_section_order(os, false));
1477
1478 return os;
1479 }
1480
1481 void
finalize_eh_frame_section()1482 Layout::finalize_eh_frame_section()
1483 {
1484 // If we never found an end marker section, we need to add the
1485 // optimized eh sections to the output section now.
1486 if (!parameters->incremental()
1487 && this->eh_frame_section_ != NULL
1488 && !this->added_eh_frame_data_)
1489 {
1490 this->eh_frame_section_->add_output_section_data(this->eh_frame_data_);
1491 this->added_eh_frame_data_ = true;
1492 }
1493 }
1494
1495 // Create and return the magic .eh_frame section. Create
1496 // .eh_frame_hdr also if appropriate. OBJECT is the object with the
1497 // input .eh_frame section; it may be NULL.
1498
1499 Output_section*
make_eh_frame_section(const Relobj * object)1500 Layout::make_eh_frame_section(const Relobj* object)
1501 {
1502 // FIXME: On x86_64, this could use SHT_X86_64_UNWIND rather than
1503 // SHT_PROGBITS.
1504 Output_section* os = this->choose_output_section(object, ".eh_frame",
1505 elfcpp::SHT_PROGBITS,
1506 elfcpp::SHF_ALLOC, false,
1507 ORDER_EHFRAME, false);
1508 if (os == NULL)
1509 return NULL;
1510
1511 if (this->eh_frame_section_ == NULL)
1512 {
1513 this->eh_frame_section_ = os;
1514 this->eh_frame_data_ = new Eh_frame();
1515
1516 // For incremental linking, we do not optimize .eh_frame sections
1517 // or create a .eh_frame_hdr section.
1518 if (parameters->options().eh_frame_hdr() && !parameters->incremental())
1519 {
1520 Output_section* hdr_os =
1521 this->choose_output_section(NULL, ".eh_frame_hdr",
1522 elfcpp::SHT_PROGBITS,
1523 elfcpp::SHF_ALLOC, false,
1524 ORDER_EHFRAME, false);
1525
1526 if (hdr_os != NULL)
1527 {
1528 Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os,
1529 this->eh_frame_data_);
1530 hdr_os->add_output_section_data(hdr_posd);
1531
1532 hdr_os->set_after_input_sections();
1533
1534 if (!this->script_options_->saw_phdrs_clause())
1535 {
1536 Output_segment* hdr_oseg;
1537 hdr_oseg = this->make_output_segment(elfcpp::PT_GNU_EH_FRAME,
1538 elfcpp::PF_R);
1539 hdr_oseg->add_output_section_to_nonload(hdr_os,
1540 elfcpp::PF_R);
1541 }
1542
1543 this->eh_frame_data_->set_eh_frame_hdr(hdr_posd);
1544 }
1545 }
1546 }
1547
1548 return os;
1549 }
1550
1551 // Add an exception frame for a PLT. This is called from target code.
1552
1553 void
add_eh_frame_for_plt(Output_data * plt,const unsigned char * cie_data,size_t cie_length,const unsigned char * fde_data,size_t fde_length)1554 Layout::add_eh_frame_for_plt(Output_data* plt, const unsigned char* cie_data,
1555 size_t cie_length, const unsigned char* fde_data,
1556 size_t fde_length)
1557 {
1558 if (parameters->incremental())
1559 {
1560 // FIXME: Maybe this could work some day....
1561 return;
1562 }
1563 Output_section* os = this->make_eh_frame_section(NULL);
1564 if (os == NULL)
1565 return;
1566 this->eh_frame_data_->add_ehframe_for_plt(plt, cie_data, cie_length,
1567 fde_data, fde_length);
1568 if (!this->added_eh_frame_data_)
1569 {
1570 os->add_output_section_data(this->eh_frame_data_);
1571 this->added_eh_frame_data_ = true;
1572 }
1573 }
1574
1575 // Scan a .debug_info or .debug_types section, and add summary
1576 // information to the .gdb_index section.
1577
1578 template<int size, bool big_endian>
1579 void
add_to_gdb_index(bool is_type_unit,Sized_relobj<size,big_endian> * object,const unsigned char * symbols,off_t symbols_size,unsigned int shndx,unsigned int reloc_shndx,unsigned int reloc_type)1580 Layout::add_to_gdb_index(bool is_type_unit,
1581 Sized_relobj<size, big_endian>* object,
1582 const unsigned char* symbols,
1583 off_t symbols_size,
1584 unsigned int shndx,
1585 unsigned int reloc_shndx,
1586 unsigned int reloc_type)
1587 {
1588 if (this->gdb_index_data_ == NULL)
1589 {
1590 Output_section* os = this->choose_output_section(NULL, ".gdb_index",
1591 elfcpp::SHT_PROGBITS, 0,
1592 false, ORDER_INVALID,
1593 false);
1594 if (os == NULL)
1595 return;
1596
1597 this->gdb_index_data_ = new Gdb_index(os);
1598 os->add_output_section_data(this->gdb_index_data_);
1599 os->set_after_input_sections();
1600 }
1601
1602 this->gdb_index_data_->scan_debug_info(is_type_unit, object, symbols,
1603 symbols_size, shndx, reloc_shndx,
1604 reloc_type);
1605 }
1606
1607 // Add POSD to an output section using NAME, TYPE, and FLAGS. Return
1608 // the output section.
1609
1610 Output_section*
add_output_section_data(const char * name,elfcpp::Elf_Word type,elfcpp::Elf_Xword flags,Output_section_data * posd,Output_section_order order,bool is_relro)1611 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
1612 elfcpp::Elf_Xword flags,
1613 Output_section_data* posd,
1614 Output_section_order order, bool is_relro)
1615 {
1616 Output_section* os = this->choose_output_section(NULL, name, type, flags,
1617 false, order, is_relro);
1618 if (os != NULL)
1619 os->add_output_section_data(posd);
1620 return os;
1621 }
1622
1623 // Map section flags to segment flags.
1624
1625 elfcpp::Elf_Word
section_flags_to_segment(elfcpp::Elf_Xword flags)1626 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
1627 {
1628 elfcpp::Elf_Word ret = elfcpp::PF_R;
1629 if ((flags & elfcpp::SHF_WRITE) != 0)
1630 ret |= elfcpp::PF_W;
1631 if ((flags & elfcpp::SHF_EXECINSTR) != 0)
1632 ret |= elfcpp::PF_X;
1633 return ret;
1634 }
1635
1636 // Make a new Output_section, and attach it to segments as
1637 // appropriate. ORDER is the order in which this section should
1638 // appear in the output segment. IS_RELRO is true if this is a relro
1639 // (read-only after relocations) section.
1640
1641 Output_section*
make_output_section(const char * name,elfcpp::Elf_Word type,elfcpp::Elf_Xword flags,Output_section_order order,bool is_relro)1642 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
1643 elfcpp::Elf_Xword flags,
1644 Output_section_order order, bool is_relro)
1645 {
1646 Output_section* os;
1647 if ((flags & elfcpp::SHF_ALLOC) == 0
1648 && strcmp(parameters->options().compress_debug_sections(), "none") != 0
1649 && is_compressible_debug_section(name))
1650 os = new Output_compressed_section(¶meters->options(), name, type,
1651 flags);
1652 else if ((flags & elfcpp::SHF_ALLOC) == 0
1653 && parameters->options().strip_debug_non_line()
1654 && strcmp(".debug_abbrev", name) == 0)
1655 {
1656 os = this->debug_abbrev_ = new Output_reduced_debug_abbrev_section(
1657 name, type, flags);
1658 if (this->debug_info_)
1659 this->debug_info_->set_abbreviations(this->debug_abbrev_);
1660 }
1661 else if ((flags & elfcpp::SHF_ALLOC) == 0
1662 && parameters->options().strip_debug_non_line()
1663 && strcmp(".debug_info", name) == 0)
1664 {
1665 os = this->debug_info_ = new Output_reduced_debug_info_section(
1666 name, type, flags);
1667 if (this->debug_abbrev_)
1668 this->debug_info_->set_abbreviations(this->debug_abbrev_);
1669 }
1670 else
1671 {
1672 // Sometimes .init_array*, .preinit_array* and .fini_array* do
1673 // not have correct section types. Force them here.
1674 if (type == elfcpp::SHT_PROGBITS)
1675 {
1676 if (is_prefix_of(".init_array", name))
1677 type = elfcpp::SHT_INIT_ARRAY;
1678 else if (is_prefix_of(".preinit_array", name))
1679 type = elfcpp::SHT_PREINIT_ARRAY;
1680 else if (is_prefix_of(".fini_array", name))
1681 type = elfcpp::SHT_FINI_ARRAY;
1682 }
1683
1684 // FIXME: const_cast is ugly.
1685 Target* target = const_cast<Target*>(¶meters->target());
1686 os = target->make_output_section(name, type, flags);
1687 }
1688
1689 // With -z relro, we have to recognize the special sections by name.
1690 // There is no other way.
1691 bool is_relro_local = false;
1692 if (!this->script_options_->saw_sections_clause()
1693 && parameters->options().relro()
1694 && (flags & elfcpp::SHF_ALLOC) != 0
1695 && (flags & elfcpp::SHF_WRITE) != 0)
1696 {
1697 if (type == elfcpp::SHT_PROGBITS)
1698 {
1699 if ((flags & elfcpp::SHF_TLS) != 0)
1700 is_relro = true;
1701 else if (strcmp(name, ".data.rel.ro") == 0)
1702 is_relro = true;
1703 else if (strcmp(name, ".data.rel.ro.local") == 0)
1704 {
1705 is_relro = true;
1706 is_relro_local = true;
1707 }
1708 else if (strcmp(name, ".ctors") == 0
1709 || strcmp(name, ".dtors") == 0
1710 || strcmp(name, ".jcr") == 0)
1711 is_relro = true;
1712 }
1713 else if (type == elfcpp::SHT_INIT_ARRAY
1714 || type == elfcpp::SHT_FINI_ARRAY
1715 || type == elfcpp::SHT_PREINIT_ARRAY)
1716 is_relro = true;
1717 }
1718
1719 if (is_relro)
1720 os->set_is_relro();
1721
1722 if (order == ORDER_INVALID && (flags & elfcpp::SHF_ALLOC) != 0)
1723 order = this->default_section_order(os, is_relro_local);
1724
1725 os->set_order(order);
1726
1727 parameters->target().new_output_section(os);
1728
1729 this->section_list_.push_back(os);
1730
1731 // The GNU linker by default sorts some sections by priority, so we
1732 // do the same. We need to know that this might happen before we
1733 // attach any input sections.
1734 if (!this->script_options_->saw_sections_clause()
1735 && !parameters->options().relocatable()
1736 && (strcmp(name, ".init_array") == 0
1737 || strcmp(name, ".fini_array") == 0
1738 || (!parameters->options().ctors_in_init_array()
1739 && (strcmp(name, ".ctors") == 0
1740 || strcmp(name, ".dtors") == 0))))
1741 os->set_may_sort_attached_input_sections();
1742
1743 // The GNU linker by default sorts .text.{unlikely,exit,startup,hot}
1744 // sections before other .text sections. We are compatible. We
1745 // need to know that this might happen before we attach any input
1746 // sections.
1747 if (parameters->options().text_reorder()
1748 && !this->script_options_->saw_sections_clause()
1749 && !this->is_section_ordering_specified()
1750 && !parameters->options().relocatable()
1751 && strcmp(name, ".text") == 0)
1752 os->set_may_sort_attached_input_sections();
1753
1754 // GNU linker sorts section by name with --sort-section=name.
1755 if (strcmp(parameters->options().sort_section(), "name") == 0)
1756 os->set_must_sort_attached_input_sections();
1757
1758 // Check for .stab*str sections, as .stab* sections need to link to
1759 // them.
1760 if (type == elfcpp::SHT_STRTAB
1761 && !this->have_stabstr_section_
1762 && strncmp(name, ".stab", 5) == 0
1763 && strcmp(name + strlen(name) - 3, "str") == 0)
1764 this->have_stabstr_section_ = true;
1765
1766 // During a full incremental link, we add patch space to most
1767 // PROGBITS and NOBITS sections. Flag those that may be
1768 // arbitrarily padded.
1769 if ((type == elfcpp::SHT_PROGBITS || type == elfcpp::SHT_NOBITS)
1770 && order != ORDER_INTERP
1771 && order != ORDER_INIT
1772 && order != ORDER_PLT
1773 && order != ORDER_FINI
1774 && order != ORDER_RELRO_LAST
1775 && order != ORDER_NON_RELRO_FIRST
1776 && strcmp(name, ".eh_frame") != 0
1777 && strcmp(name, ".ctors") != 0
1778 && strcmp(name, ".dtors") != 0
1779 && strcmp(name, ".jcr") != 0)
1780 {
1781 os->set_is_patch_space_allowed();
1782
1783 // Certain sections require "holes" to be filled with
1784 // specific fill patterns. These fill patterns may have
1785 // a minimum size, so we must prevent allocations from the
1786 // free list that leave a hole smaller than the minimum.
1787 if (strcmp(name, ".debug_info") == 0)
1788 os->set_free_space_fill(new Output_fill_debug_info(false));
1789 else if (strcmp(name, ".debug_types") == 0)
1790 os->set_free_space_fill(new Output_fill_debug_info(true));
1791 else if (strcmp(name, ".debug_line") == 0)
1792 os->set_free_space_fill(new Output_fill_debug_line());
1793 }
1794
1795 // If we have already attached the sections to segments, then we
1796 // need to attach this one now. This happens for sections created
1797 // directly by the linker.
1798 if (this->sections_are_attached_)
1799 this->attach_section_to_segment(¶meters->target(), os);
1800
1801 return os;
1802 }
1803
1804 // Return the default order in which a section should be placed in an
1805 // output segment. This function captures a lot of the ideas in
1806 // ld/scripttempl/elf.sc in the GNU linker. Note that the order of a
1807 // linker created section is normally set when the section is created;
1808 // this function is used for input sections.
1809
1810 Output_section_order
default_section_order(Output_section * os,bool is_relro_local)1811 Layout::default_section_order(Output_section* os, bool is_relro_local)
1812 {
1813 gold_assert((os->flags() & elfcpp::SHF_ALLOC) != 0);
1814 bool is_write = (os->flags() & elfcpp::SHF_WRITE) != 0;
1815 bool is_execinstr = (os->flags() & elfcpp::SHF_EXECINSTR) != 0;
1816 bool is_bss = false;
1817
1818 switch (os->type())
1819 {
1820 default:
1821 case elfcpp::SHT_PROGBITS:
1822 break;
1823 case elfcpp::SHT_NOBITS:
1824 is_bss = true;
1825 break;
1826 case elfcpp::SHT_RELA:
1827 case elfcpp::SHT_REL:
1828 if (!is_write)
1829 return ORDER_DYNAMIC_RELOCS;
1830 break;
1831 case elfcpp::SHT_HASH:
1832 case elfcpp::SHT_DYNAMIC:
1833 case elfcpp::SHT_SHLIB:
1834 case elfcpp::SHT_DYNSYM:
1835 case elfcpp::SHT_GNU_HASH:
1836 case elfcpp::SHT_GNU_verdef:
1837 case elfcpp::SHT_GNU_verneed:
1838 case elfcpp::SHT_GNU_versym:
1839 if (!is_write)
1840 return ORDER_DYNAMIC_LINKER;
1841 break;
1842 case elfcpp::SHT_NOTE:
1843 return is_write ? ORDER_RW_NOTE : ORDER_RO_NOTE;
1844 }
1845
1846 if ((os->flags() & elfcpp::SHF_TLS) != 0)
1847 return is_bss ? ORDER_TLS_BSS : ORDER_TLS_DATA;
1848
1849 if (!is_bss && !is_write)
1850 {
1851 if (is_execinstr)
1852 {
1853 if (strcmp(os->name(), ".init") == 0)
1854 return ORDER_INIT;
1855 else if (strcmp(os->name(), ".fini") == 0)
1856 return ORDER_FINI;
1857 }
1858 return is_execinstr ? ORDER_TEXT : ORDER_READONLY;
1859 }
1860
1861 if (os->is_relro())
1862 return is_relro_local ? ORDER_RELRO_LOCAL : ORDER_RELRO;
1863
1864 if (os->is_small_section())
1865 return is_bss ? ORDER_SMALL_BSS : ORDER_SMALL_DATA;
1866 if (os->is_large_section())
1867 return is_bss ? ORDER_LARGE_BSS : ORDER_LARGE_DATA;
1868
1869 return is_bss ? ORDER_BSS : ORDER_DATA;
1870 }
1871
1872 // Attach output sections to segments. This is called after we have
1873 // seen all the input sections.
1874
1875 void
attach_sections_to_segments(const Target * target)1876 Layout::attach_sections_to_segments(const Target* target)
1877 {
1878 for (Section_list::iterator p = this->section_list_.begin();
1879 p != this->section_list_.end();
1880 ++p)
1881 this->attach_section_to_segment(target, *p);
1882
1883 this->sections_are_attached_ = true;
1884 }
1885
1886 // Attach an output section to a segment.
1887
1888 void
attach_section_to_segment(const Target * target,Output_section * os)1889 Layout::attach_section_to_segment(const Target* target, Output_section* os)
1890 {
1891 if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1892 this->unattached_section_list_.push_back(os);
1893 else
1894 this->attach_allocated_section_to_segment(target, os);
1895 }
1896
1897 // Attach an allocated output section to a segment.
1898
1899 void
attach_allocated_section_to_segment(const Target * target,Output_section * os)1900 Layout::attach_allocated_section_to_segment(const Target* target,
1901 Output_section* os)
1902 {
1903 elfcpp::Elf_Xword flags = os->flags();
1904 gold_assert((flags & elfcpp::SHF_ALLOC) != 0);
1905
1906 if (parameters->options().relocatable())
1907 return;
1908
1909 // If we have a SECTIONS clause, we can't handle the attachment to
1910 // segments until after we've seen all the sections.
1911 if (this->script_options_->saw_sections_clause())
1912 return;
1913
1914 gold_assert(!this->script_options_->saw_phdrs_clause());
1915
1916 // This output section goes into a PT_LOAD segment.
1917
1918 elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
1919
1920 // If this output section's segment has extra flags that need to be set,
1921 // coming from a linker plugin, do that.
1922 seg_flags |= os->extra_segment_flags();
1923
1924 // Check for --section-start.
1925 uint64_t addr;
1926 bool is_address_set = parameters->options().section_start(os->name(), &addr);
1927
1928 // In general the only thing we really care about for PT_LOAD
1929 // segments is whether or not they are writable or executable,
1930 // so that is how we search for them.
1931 // Large data sections also go into their own PT_LOAD segment.
1932 // People who need segments sorted on some other basis will
1933 // have to use a linker script.
1934
1935 Segment_list::const_iterator p;
1936 if (!os->is_unique_segment())
1937 {
1938 for (p = this->segment_list_.begin();
1939 p != this->segment_list_.end();
1940 ++p)
1941 {
1942 if ((*p)->type() != elfcpp::PT_LOAD)
1943 continue;
1944 if ((*p)->is_unique_segment())
1945 continue;
1946 if (!parameters->options().omagic()
1947 && ((*p)->flags() & elfcpp::PF_W) != (seg_flags & elfcpp::PF_W))
1948 continue;
1949 if ((target->isolate_execinstr() || parameters->options().rosegment())
1950 && ((*p)->flags() & elfcpp::PF_X) != (seg_flags & elfcpp::PF_X))
1951 continue;
1952 // If -Tbss was specified, we need to separate the data and BSS
1953 // segments.
1954 if (parameters->options().user_set_Tbss())
1955 {
1956 if ((os->type() == elfcpp::SHT_NOBITS)
1957 == (*p)->has_any_data_sections())
1958 continue;
1959 }
1960 if (os->is_large_data_section() && !(*p)->is_large_data_segment())
1961 continue;
1962
1963 if (is_address_set)
1964 {
1965 if ((*p)->are_addresses_set())
1966 continue;
1967
1968 (*p)->add_initial_output_data(os);
1969 (*p)->update_flags_for_output_section(seg_flags);
1970 (*p)->set_addresses(addr, addr);
1971 break;
1972 }
1973
1974 (*p)->add_output_section_to_load(this, os, seg_flags);
1975 break;
1976 }
1977 }
1978
1979 if (p == this->segment_list_.end()
1980 || os->is_unique_segment())
1981 {
1982 Output_segment* oseg = this->make_output_segment(elfcpp::PT_LOAD,
1983 seg_flags);
1984 if (os->is_large_data_section())
1985 oseg->set_is_large_data_segment();
1986 oseg->add_output_section_to_load(this, os, seg_flags);
1987 if (is_address_set)
1988 oseg->set_addresses(addr, addr);
1989 // Check if segment should be marked unique. For segments marked
1990 // unique by linker plugins, set the new alignment if specified.
1991 if (os->is_unique_segment())
1992 {
1993 oseg->set_is_unique_segment();
1994 if (os->segment_alignment() != 0)
1995 oseg->set_minimum_p_align(os->segment_alignment());
1996 }
1997 }
1998
1999 // If we see a loadable SHT_NOTE section, we create a PT_NOTE
2000 // segment.
2001 if (os->type() == elfcpp::SHT_NOTE)
2002 {
2003 // See if we already have an equivalent PT_NOTE segment.
2004 for (p = this->segment_list_.begin();
2005 p != segment_list_.end();
2006 ++p)
2007 {
2008 if ((*p)->type() == elfcpp::PT_NOTE
2009 && (((*p)->flags() & elfcpp::PF_W)
2010 == (seg_flags & elfcpp::PF_W)))
2011 {
2012 (*p)->add_output_section_to_nonload(os, seg_flags);
2013 break;
2014 }
2015 }
2016
2017 if (p == this->segment_list_.end())
2018 {
2019 Output_segment* oseg = this->make_output_segment(elfcpp::PT_NOTE,
2020 seg_flags);
2021 oseg->add_output_section_to_nonload(os, seg_flags);
2022 }
2023 }
2024
2025 // If we see a loadable SHF_TLS section, we create a PT_TLS
2026 // segment. There can only be one such segment.
2027 if ((flags & elfcpp::SHF_TLS) != 0)
2028 {
2029 if (this->tls_segment_ == NULL)
2030 this->make_output_segment(elfcpp::PT_TLS, seg_flags);
2031 this->tls_segment_->add_output_section_to_nonload(os, seg_flags);
2032 }
2033
2034 // If -z relro is in effect, and we see a relro section, we create a
2035 // PT_GNU_RELRO segment. There can only be one such segment.
2036 if (os->is_relro() && parameters->options().relro())
2037 {
2038 gold_assert(seg_flags == (elfcpp::PF_R | elfcpp::PF_W));
2039 if (this->relro_segment_ == NULL)
2040 this->make_output_segment(elfcpp::PT_GNU_RELRO, seg_flags);
2041 this->relro_segment_->add_output_section_to_nonload(os, seg_flags);
2042 }
2043
2044 // If we see a section named .interp, put it into a PT_INTERP
2045 // segment. This seems broken to me, but this is what GNU ld does,
2046 // and glibc expects it.
2047 if (strcmp(os->name(), ".interp") == 0
2048 && !this->script_options_->saw_phdrs_clause())
2049 {
2050 if (this->interp_segment_ == NULL)
2051 this->make_output_segment(elfcpp::PT_INTERP, seg_flags);
2052 else
2053 gold_warning(_("multiple '.interp' sections in input files "
2054 "may cause confusing PT_INTERP segment"));
2055 this->interp_segment_->add_output_section_to_nonload(os, seg_flags);
2056 }
2057 }
2058
2059 // Make an output section for a script.
2060
2061 Output_section*
make_output_section_for_script(const char * name,Script_sections::Section_type section_type)2062 Layout::make_output_section_for_script(
2063 const char* name,
2064 Script_sections::Section_type section_type)
2065 {
2066 name = this->namepool_.add(name, false, NULL);
2067 elfcpp::Elf_Xword sh_flags = elfcpp::SHF_ALLOC;
2068 if (section_type == Script_sections::ST_NOLOAD)
2069 sh_flags = 0;
2070 Output_section* os = this->make_output_section(name, elfcpp::SHT_PROGBITS,
2071 sh_flags, ORDER_INVALID,
2072 false);
2073 os->set_found_in_sections_clause();
2074 if (section_type == Script_sections::ST_NOLOAD)
2075 os->set_is_noload();
2076 return os;
2077 }
2078
2079 // Return the number of segments we expect to see.
2080
2081 size_t
expected_segment_count() const2082 Layout::expected_segment_count() const
2083 {
2084 size_t ret = this->segment_list_.size();
2085
2086 // If we didn't see a SECTIONS clause in a linker script, we should
2087 // already have the complete list of segments. Otherwise we ask the
2088 // SECTIONS clause how many segments it expects, and add in the ones
2089 // we already have (PT_GNU_STACK, PT_GNU_EH_FRAME, etc.)
2090
2091 if (!this->script_options_->saw_sections_clause())
2092 return ret;
2093 else
2094 {
2095 const Script_sections* ss = this->script_options_->script_sections();
2096 return ret + ss->expected_segment_count(this);
2097 }
2098 }
2099
2100 // Handle the .note.GNU-stack section at layout time. SEEN_GNU_STACK
2101 // is whether we saw a .note.GNU-stack section in the object file.
2102 // GNU_STACK_FLAGS is the section flags. The flags give the
2103 // protection required for stack memory. We record this in an
2104 // executable as a PT_GNU_STACK segment. If an object file does not
2105 // have a .note.GNU-stack segment, we must assume that it is an old
2106 // object. On some targets that will force an executable stack.
2107
2108 void
layout_gnu_stack(bool seen_gnu_stack,uint64_t gnu_stack_flags,const Object * obj)2109 Layout::layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags,
2110 const Object* obj)
2111 {
2112 if (!seen_gnu_stack)
2113 {
2114 this->input_without_gnu_stack_note_ = true;
2115 if (parameters->options().warn_execstack()
2116 && parameters->target().is_default_stack_executable())
2117 gold_warning(_("%s: missing .note.GNU-stack section"
2118 " implies executable stack"),
2119 obj->name().c_str());
2120 }
2121 else
2122 {
2123 this->input_with_gnu_stack_note_ = true;
2124 if ((gnu_stack_flags & elfcpp::SHF_EXECINSTR) != 0)
2125 {
2126 this->input_requires_executable_stack_ = true;
2127 if (parameters->options().warn_execstack())
2128 gold_warning(_("%s: requires executable stack"),
2129 obj->name().c_str());
2130 }
2131 }
2132 }
2133
2134 // Create automatic note sections.
2135
2136 void
create_notes()2137 Layout::create_notes()
2138 {
2139 this->create_gold_note();
2140 this->create_executable_stack_info();
2141 this->create_build_id();
2142 }
2143
2144 // Create the dynamic sections which are needed before we read the
2145 // relocs.
2146
2147 void
create_initial_dynamic_sections(Symbol_table * symtab)2148 Layout::create_initial_dynamic_sections(Symbol_table* symtab)
2149 {
2150 if (parameters->doing_static_link())
2151 return;
2152
2153 this->dynamic_section_ = this->choose_output_section(NULL, ".dynamic",
2154 elfcpp::SHT_DYNAMIC,
2155 (elfcpp::SHF_ALLOC
2156 | elfcpp::SHF_WRITE),
2157 false, ORDER_RELRO,
2158 true);
2159
2160 // A linker script may discard .dynamic, so check for NULL.
2161 if (this->dynamic_section_ != NULL)
2162 {
2163 this->dynamic_symbol_ =
2164 symtab->define_in_output_data("_DYNAMIC", NULL,
2165 Symbol_table::PREDEFINED,
2166 this->dynamic_section_, 0, 0,
2167 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
2168 elfcpp::STV_HIDDEN, 0, false, false);
2169
2170 this->dynamic_data_ = new Output_data_dynamic(&this->dynpool_);
2171
2172 this->dynamic_section_->add_output_section_data(this->dynamic_data_);
2173 }
2174 }
2175
2176 // For each output section whose name can be represented as C symbol,
2177 // define __start and __stop symbols for the section. This is a GNU
2178 // extension.
2179
2180 void
define_section_symbols(Symbol_table * symtab)2181 Layout::define_section_symbols(Symbol_table* symtab)
2182 {
2183 for (Section_list::const_iterator p = this->section_list_.begin();
2184 p != this->section_list_.end();
2185 ++p)
2186 {
2187 const char* const name = (*p)->name();
2188 if (is_cident(name))
2189 {
2190 const std::string name_string(name);
2191 const std::string start_name(cident_section_start_prefix
2192 + name_string);
2193 const std::string stop_name(cident_section_stop_prefix
2194 + name_string);
2195
2196 symtab->define_in_output_data(start_name.c_str(),
2197 NULL, // version
2198 Symbol_table::PREDEFINED,
2199 *p,
2200 0, // value
2201 0, // symsize
2202 elfcpp::STT_NOTYPE,
2203 elfcpp::STB_GLOBAL,
2204 elfcpp::STV_DEFAULT,
2205 0, // nonvis
2206 false, // offset_is_from_end
2207 true); // only_if_ref
2208
2209 symtab->define_in_output_data(stop_name.c_str(),
2210 NULL, // version
2211 Symbol_table::PREDEFINED,
2212 *p,
2213 0, // value
2214 0, // symsize
2215 elfcpp::STT_NOTYPE,
2216 elfcpp::STB_GLOBAL,
2217 elfcpp::STV_DEFAULT,
2218 0, // nonvis
2219 true, // offset_is_from_end
2220 true); // only_if_ref
2221 }
2222 }
2223 }
2224
2225 // Define symbols for group signatures.
2226
2227 void
define_group_signatures(Symbol_table * symtab)2228 Layout::define_group_signatures(Symbol_table* symtab)
2229 {
2230 for (Group_signatures::iterator p = this->group_signatures_.begin();
2231 p != this->group_signatures_.end();
2232 ++p)
2233 {
2234 Symbol* sym = symtab->lookup(p->signature, NULL);
2235 if (sym != NULL)
2236 p->section->set_info_symndx(sym);
2237 else
2238 {
2239 // Force the name of the group section to the group
2240 // signature, and use the group's section symbol as the
2241 // signature symbol.
2242 if (strcmp(p->section->name(), p->signature) != 0)
2243 {
2244 const char* name = this->namepool_.add(p->signature,
2245 true, NULL);
2246 p->section->set_name(name);
2247 }
2248 p->section->set_needs_symtab_index();
2249 p->section->set_info_section_symndx(p->section);
2250 }
2251 }
2252
2253 this->group_signatures_.clear();
2254 }
2255
2256 // Find the first read-only PT_LOAD segment, creating one if
2257 // necessary.
2258
2259 Output_segment*
find_first_load_seg(const Target * target)2260 Layout::find_first_load_seg(const Target* target)
2261 {
2262 Output_segment* best = NULL;
2263 for (Segment_list::const_iterator p = this->segment_list_.begin();
2264 p != this->segment_list_.end();
2265 ++p)
2266 {
2267 if ((*p)->type() == elfcpp::PT_LOAD
2268 && ((*p)->flags() & elfcpp::PF_R) != 0
2269 && (parameters->options().omagic()
2270 || ((*p)->flags() & elfcpp::PF_W) == 0)
2271 && (!target->isolate_execinstr()
2272 || ((*p)->flags() & elfcpp::PF_X) == 0))
2273 {
2274 if (best == NULL || this->segment_precedes(*p, best))
2275 best = *p;
2276 }
2277 }
2278 if (best != NULL)
2279 return best;
2280
2281 gold_assert(!this->script_options_->saw_phdrs_clause());
2282
2283 Output_segment* load_seg = this->make_output_segment(elfcpp::PT_LOAD,
2284 elfcpp::PF_R);
2285 return load_seg;
2286 }
2287
2288 // Save states of all current output segments. Store saved states
2289 // in SEGMENT_STATES.
2290
2291 void
save_segments(Segment_states * segment_states)2292 Layout::save_segments(Segment_states* segment_states)
2293 {
2294 for (Segment_list::const_iterator p = this->segment_list_.begin();
2295 p != this->segment_list_.end();
2296 ++p)
2297 {
2298 Output_segment* segment = *p;
2299 // Shallow copy.
2300 Output_segment* copy = new Output_segment(*segment);
2301 (*segment_states)[segment] = copy;
2302 }
2303 }
2304
2305 // Restore states of output segments and delete any segment not found in
2306 // SEGMENT_STATES.
2307
2308 void
restore_segments(const Segment_states * segment_states)2309 Layout::restore_segments(const Segment_states* segment_states)
2310 {
2311 // Go through the segment list and remove any segment added in the
2312 // relaxation loop.
2313 this->tls_segment_ = NULL;
2314 this->relro_segment_ = NULL;
2315 Segment_list::iterator list_iter = this->segment_list_.begin();
2316 while (list_iter != this->segment_list_.end())
2317 {
2318 Output_segment* segment = *list_iter;
2319 Segment_states::const_iterator states_iter =
2320 segment_states->find(segment);
2321 if (states_iter != segment_states->end())
2322 {
2323 const Output_segment* copy = states_iter->second;
2324 // Shallow copy to restore states.
2325 *segment = *copy;
2326
2327 // Also fix up TLS and RELRO segment pointers as appropriate.
2328 if (segment->type() == elfcpp::PT_TLS)
2329 this->tls_segment_ = segment;
2330 else if (segment->type() == elfcpp::PT_GNU_RELRO)
2331 this->relro_segment_ = segment;
2332
2333 ++list_iter;
2334 }
2335 else
2336 {
2337 list_iter = this->segment_list_.erase(list_iter);
2338 // This is a segment created during section layout. It should be
2339 // safe to remove it since we should have removed all pointers to it.
2340 delete segment;
2341 }
2342 }
2343 }
2344
2345 // Clean up after relaxation so that sections can be laid out again.
2346
2347 void
clean_up_after_relaxation()2348 Layout::clean_up_after_relaxation()
2349 {
2350 // Restore the segments to point state just prior to the relaxation loop.
2351 Script_sections* script_section = this->script_options_->script_sections();
2352 script_section->release_segments();
2353 this->restore_segments(this->segment_states_);
2354
2355 // Reset section addresses and file offsets
2356 for (Section_list::iterator p = this->section_list_.begin();
2357 p != this->section_list_.end();
2358 ++p)
2359 {
2360 (*p)->restore_states();
2361
2362 // If an input section changes size because of relaxation,
2363 // we need to adjust the section offsets of all input sections.
2364 // after such a section.
2365 if ((*p)->section_offsets_need_adjustment())
2366 (*p)->adjust_section_offsets();
2367
2368 (*p)->reset_address_and_file_offset();
2369 }
2370
2371 // Reset special output object address and file offsets.
2372 for (Data_list::iterator p = this->special_output_list_.begin();
2373 p != this->special_output_list_.end();
2374 ++p)
2375 (*p)->reset_address_and_file_offset();
2376
2377 // A linker script may have created some output section data objects.
2378 // They are useless now.
2379 for (Output_section_data_list::const_iterator p =
2380 this->script_output_section_data_list_.begin();
2381 p != this->script_output_section_data_list_.end();
2382 ++p)
2383 delete *p;
2384 this->script_output_section_data_list_.clear();
2385
2386 // Special-case fill output objects are recreated each time through
2387 // the relaxation loop.
2388 this->reset_relax_output();
2389 }
2390
2391 void
reset_relax_output()2392 Layout::reset_relax_output()
2393 {
2394 for (Data_list::const_iterator p = this->relax_output_list_.begin();
2395 p != this->relax_output_list_.end();
2396 ++p)
2397 delete *p;
2398 this->relax_output_list_.clear();
2399 }
2400
2401 // Prepare for relaxation.
2402
2403 void
prepare_for_relaxation()2404 Layout::prepare_for_relaxation()
2405 {
2406 // Create an relaxation debug check if in debugging mode.
2407 if (is_debugging_enabled(DEBUG_RELAXATION))
2408 this->relaxation_debug_check_ = new Relaxation_debug_check();
2409
2410 // Save segment states.
2411 this->segment_states_ = new Segment_states();
2412 this->save_segments(this->segment_states_);
2413
2414 for(Section_list::const_iterator p = this->section_list_.begin();
2415 p != this->section_list_.end();
2416 ++p)
2417 (*p)->save_states();
2418
2419 if (is_debugging_enabled(DEBUG_RELAXATION))
2420 this->relaxation_debug_check_->check_output_data_for_reset_values(
2421 this->section_list_, this->special_output_list_,
2422 this->relax_output_list_);
2423
2424 // Also enable recording of output section data from scripts.
2425 this->record_output_section_data_from_script_ = true;
2426 }
2427
2428 // If the user set the address of the text segment, that may not be
2429 // compatible with putting the segment headers and file headers into
2430 // that segment. For isolate_execinstr() targets, it's the rodata
2431 // segment rather than text where we might put the headers.
2432 static inline bool
load_seg_unusable_for_headers(const Target * target)2433 load_seg_unusable_for_headers(const Target* target)
2434 {
2435 const General_options& options = parameters->options();
2436 if (target->isolate_execinstr())
2437 return (options.user_set_Trodata_segment()
2438 && options.Trodata_segment() % target->abi_pagesize() != 0);
2439 else
2440 return (options.user_set_Ttext()
2441 && options.Ttext() % target->abi_pagesize() != 0);
2442 }
2443
2444 // Relaxation loop body: If target has no relaxation, this runs only once
2445 // Otherwise, the target relaxation hook is called at the end of
2446 // each iteration. If the hook returns true, it means re-layout of
2447 // section is required.
2448 //
2449 // The number of segments created by a linking script without a PHDRS
2450 // clause may be affected by section sizes and alignments. There is
2451 // a remote chance that relaxation causes different number of PT_LOAD
2452 // segments are created and sections are attached to different segments.
2453 // Therefore, we always throw away all segments created during section
2454 // layout. In order to be able to restart the section layout, we keep
2455 // a copy of the segment list right before the relaxation loop and use
2456 // that to restore the segments.
2457 //
2458 // PASS is the current relaxation pass number.
2459 // SYMTAB is a symbol table.
2460 // PLOAD_SEG is the address of a pointer for the load segment.
2461 // PHDR_SEG is a pointer to the PHDR segment.
2462 // SEGMENT_HEADERS points to the output segment header.
2463 // FILE_HEADER points to the output file header.
2464 // PSHNDX is the address to store the output section index.
2465
2466 off_t inline
relaxation_loop_body(int pass,Target * target,Symbol_table * symtab,Output_segment ** pload_seg,Output_segment * phdr_seg,Output_segment_headers * segment_headers,Output_file_header * file_header,unsigned int * pshndx)2467 Layout::relaxation_loop_body(
2468 int pass,
2469 Target* target,
2470 Symbol_table* symtab,
2471 Output_segment** pload_seg,
2472 Output_segment* phdr_seg,
2473 Output_segment_headers* segment_headers,
2474 Output_file_header* file_header,
2475 unsigned int* pshndx)
2476 {
2477 // If this is not the first iteration, we need to clean up after
2478 // relaxation so that we can lay out the sections again.
2479 if (pass != 0)
2480 this->clean_up_after_relaxation();
2481
2482 // If there is a SECTIONS clause, put all the input sections into
2483 // the required order.
2484 Output_segment* load_seg;
2485 if (this->script_options_->saw_sections_clause())
2486 load_seg = this->set_section_addresses_from_script(symtab);
2487 else if (parameters->options().relocatable())
2488 load_seg = NULL;
2489 else
2490 load_seg = this->find_first_load_seg(target);
2491
2492 if (parameters->options().oformat_enum()
2493 != General_options::OBJECT_FORMAT_ELF)
2494 load_seg = NULL;
2495
2496 if (load_seg_unusable_for_headers(target))
2497 {
2498 load_seg = NULL;
2499 phdr_seg = NULL;
2500 }
2501
2502 gold_assert(phdr_seg == NULL
2503 || load_seg != NULL
2504 || this->script_options_->saw_sections_clause());
2505
2506 // If the address of the load segment we found has been set by
2507 // --section-start rather than by a script, then adjust the VMA and
2508 // LMA downward if possible to include the file and section headers.
2509 uint64_t header_gap = 0;
2510 if (load_seg != NULL
2511 && load_seg->are_addresses_set()
2512 && !this->script_options_->saw_sections_clause()
2513 && !parameters->options().relocatable())
2514 {
2515 file_header->finalize_data_size();
2516 segment_headers->finalize_data_size();
2517 size_t sizeof_headers = (file_header->data_size()
2518 + segment_headers->data_size());
2519 const uint64_t abi_pagesize = target->abi_pagesize();
2520 uint64_t hdr_paddr = load_seg->paddr() - sizeof_headers;
2521 hdr_paddr &= ~(abi_pagesize - 1);
2522 uint64_t subtract = load_seg->paddr() - hdr_paddr;
2523 if (load_seg->paddr() < subtract || load_seg->vaddr() < subtract)
2524 load_seg = NULL;
2525 else
2526 {
2527 load_seg->set_addresses(load_seg->vaddr() - subtract,
2528 load_seg->paddr() - subtract);
2529 header_gap = subtract - sizeof_headers;
2530 }
2531 }
2532
2533 // Lay out the segment headers.
2534 if (!parameters->options().relocatable())
2535 {
2536 gold_assert(segment_headers != NULL);
2537 if (header_gap != 0 && load_seg != NULL)
2538 {
2539 Output_data_zero_fill* z = new Output_data_zero_fill(header_gap, 1);
2540 load_seg->add_initial_output_data(z);
2541 }
2542 if (load_seg != NULL)
2543 load_seg->add_initial_output_data(segment_headers);
2544 if (phdr_seg != NULL)
2545 phdr_seg->add_initial_output_data(segment_headers);
2546 }
2547
2548 // Lay out the file header.
2549 if (load_seg != NULL)
2550 load_seg->add_initial_output_data(file_header);
2551
2552 if (this->script_options_->saw_phdrs_clause()
2553 && !parameters->options().relocatable())
2554 {
2555 // Support use of FILEHDRS and PHDRS attachments in a PHDRS
2556 // clause in a linker script.
2557 Script_sections* ss = this->script_options_->script_sections();
2558 ss->put_headers_in_phdrs(file_header, segment_headers);
2559 }
2560
2561 // We set the output section indexes in set_segment_offsets and
2562 // set_section_indexes.
2563 *pshndx = 1;
2564
2565 // Set the file offsets of all the segments, and all the sections
2566 // they contain.
2567 off_t off;
2568 if (!parameters->options().relocatable())
2569 off = this->set_segment_offsets(target, load_seg, pshndx);
2570 else
2571 off = this->set_relocatable_section_offsets(file_header, pshndx);
2572
2573 // Verify that the dummy relaxation does not change anything.
2574 if (is_debugging_enabled(DEBUG_RELAXATION))
2575 {
2576 if (pass == 0)
2577 this->relaxation_debug_check_->read_sections(this->section_list_);
2578 else
2579 this->relaxation_debug_check_->verify_sections(this->section_list_);
2580 }
2581
2582 *pload_seg = load_seg;
2583 return off;
2584 }
2585
2586 // Search the list of patterns and find the postion of the given section
2587 // name in the output section. If the section name matches a glob
2588 // pattern and a non-glob name, then the non-glob position takes
2589 // precedence. Return 0 if no match is found.
2590
2591 unsigned int
find_section_order_index(const std::string & section_name)2592 Layout::find_section_order_index(const std::string& section_name)
2593 {
2594 Unordered_map<std::string, unsigned int>::iterator map_it;
2595 map_it = this->input_section_position_.find(section_name);
2596 if (map_it != this->input_section_position_.end())
2597 return map_it->second;
2598
2599 // Absolute match failed. Linear search the glob patterns.
2600 std::vector<std::string>::iterator it;
2601 for (it = this->input_section_glob_.begin();
2602 it != this->input_section_glob_.end();
2603 ++it)
2604 {
2605 if (fnmatch((*it).c_str(), section_name.c_str(), FNM_NOESCAPE) == 0)
2606 {
2607 map_it = this->input_section_position_.find(*it);
2608 gold_assert(map_it != this->input_section_position_.end());
2609 return map_it->second;
2610 }
2611 }
2612 return 0;
2613 }
2614
2615 // Read the sequence of input sections from the file specified with
2616 // option --section-ordering-file.
2617
2618 void
read_layout_from_file()2619 Layout::read_layout_from_file()
2620 {
2621 const char* filename = parameters->options().section_ordering_file();
2622 std::ifstream in;
2623 std::string line;
2624
2625 in.open(filename);
2626 if (!in)
2627 gold_fatal(_("unable to open --section-ordering-file file %s: %s"),
2628 filename, strerror(errno));
2629
2630 std::getline(in, line); // this chops off the trailing \n, if any
2631 unsigned int position = 1;
2632 this->set_section_ordering_specified();
2633
2634 while (in)
2635 {
2636 if (!line.empty() && line[line.length() - 1] == '\r') // Windows
2637 line.resize(line.length() - 1);
2638 // Ignore comments, beginning with '#'
2639 if (line[0] == '#')
2640 {
2641 std::getline(in, line);
2642 continue;
2643 }
2644 this->input_section_position_[line] = position;
2645 // Store all glob patterns in a vector.
2646 if (is_wildcard_string(line.c_str()))
2647 this->input_section_glob_.push_back(line);
2648 position++;
2649 std::getline(in, line);
2650 }
2651 }
2652
2653 // Finalize the layout. When this is called, we have created all the
2654 // output sections and all the output segments which are based on
2655 // input sections. We have several things to do, and we have to do
2656 // them in the right order, so that we get the right results correctly
2657 // and efficiently.
2658
2659 // 1) Finalize the list of output segments and create the segment
2660 // table header.
2661
2662 // 2) Finalize the dynamic symbol table and associated sections.
2663
2664 // 3) Determine the final file offset of all the output segments.
2665
2666 // 4) Determine the final file offset of all the SHF_ALLOC output
2667 // sections.
2668
2669 // 5) Create the symbol table sections and the section name table
2670 // section.
2671
2672 // 6) Finalize the symbol table: set symbol values to their final
2673 // value and make a final determination of which symbols are going
2674 // into the output symbol table.
2675
2676 // 7) Create the section table header.
2677
2678 // 8) Determine the final file offset of all the output sections which
2679 // are not SHF_ALLOC, including the section table header.
2680
2681 // 9) Finalize the ELF file header.
2682
2683 // This function returns the size of the output file.
2684
2685 off_t
finalize(const Input_objects * input_objects,Symbol_table * symtab,Target * target,const Task * task)2686 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab,
2687 Target* target, const Task* task)
2688 {
2689 target->finalize_sections(this, input_objects, symtab);
2690
2691 this->count_local_symbols(task, input_objects);
2692
2693 this->link_stabs_sections();
2694
2695 Output_segment* phdr_seg = NULL;
2696 if (!parameters->options().relocatable() && !parameters->doing_static_link())
2697 {
2698 // There was a dynamic object in the link. We need to create
2699 // some information for the dynamic linker.
2700
2701 // Create the PT_PHDR segment which will hold the program
2702 // headers.
2703 if (!this->script_options_->saw_phdrs_clause())
2704 phdr_seg = this->make_output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
2705
2706 // Create the dynamic symbol table, including the hash table.
2707 Output_section* dynstr;
2708 std::vector<Symbol*> dynamic_symbols;
2709 unsigned int local_dynamic_count;
2710 Versions versions(*this->script_options()->version_script_info(),
2711 &this->dynpool_);
2712 this->create_dynamic_symtab(input_objects, symtab, &dynstr,
2713 &local_dynamic_count, &dynamic_symbols,
2714 &versions);
2715
2716 // Create the .interp section to hold the name of the
2717 // interpreter, and put it in a PT_INTERP segment. Don't do it
2718 // if we saw a .interp section in an input file.
2719 if ((!parameters->options().shared()
2720 || parameters->options().dynamic_linker() != NULL)
2721 && this->interp_segment_ == NULL)
2722 this->create_interp(target);
2723
2724 // Finish the .dynamic section to hold the dynamic data, and put
2725 // it in a PT_DYNAMIC segment.
2726 this->finish_dynamic_section(input_objects, symtab);
2727
2728 // We should have added everything we need to the dynamic string
2729 // table.
2730 this->dynpool_.set_string_offsets();
2731
2732 // Create the version sections. We can't do this until the
2733 // dynamic string table is complete.
2734 this->create_version_sections(&versions, symtab, local_dynamic_count,
2735 dynamic_symbols, dynstr);
2736
2737 // Set the size of the _DYNAMIC symbol. We can't do this until
2738 // after we call create_version_sections.
2739 this->set_dynamic_symbol_size(symtab);
2740 }
2741
2742 // Create segment headers.
2743 Output_segment_headers* segment_headers =
2744 (parameters->options().relocatable()
2745 ? NULL
2746 : new Output_segment_headers(this->segment_list_));
2747
2748 // Lay out the file header.
2749 Output_file_header* file_header = new Output_file_header(target, symtab,
2750 segment_headers);
2751
2752 this->special_output_list_.push_back(file_header);
2753 if (segment_headers != NULL)
2754 this->special_output_list_.push_back(segment_headers);
2755
2756 // Find approriate places for orphan output sections if we are using
2757 // a linker script.
2758 if (this->script_options_->saw_sections_clause())
2759 this->place_orphan_sections_in_script();
2760
2761 Output_segment* load_seg;
2762 off_t off;
2763 unsigned int shndx;
2764 int pass = 0;
2765
2766 // Take a snapshot of the section layout as needed.
2767 if (target->may_relax())
2768 this->prepare_for_relaxation();
2769
2770 // Run the relaxation loop to lay out sections.
2771 do
2772 {
2773 off = this->relaxation_loop_body(pass, target, symtab, &load_seg,
2774 phdr_seg, segment_headers, file_header,
2775 &shndx);
2776 pass++;
2777 }
2778 while (target->may_relax()
2779 && target->relax(pass, input_objects, symtab, this, task));
2780
2781 // Check if data segment size is less than the safe value with PIE links.
2782 // Warn about bug http://b/20165734 for unsafe sizes.
2783 if (parameters->options().pie() && target->max_pie_data_segment_size())
2784 {
2785 Segment_list::const_iterator p;
2786 uint64_t re_vaddr = 0, re_memsz = 0, rw_vaddr = 0, rw_memsz = 0;
2787 uint64_t data_seg_size = 0;
2788 for (p = this->segment_list_.begin();
2789 p != this->segment_list_.end();
2790 ++p)
2791 {
2792 // With -Wl,--rosegment, note the end addr of "R E" segment.
2793 if (parameters->options().rosegment()
2794 && (*p)->type() == elfcpp::PT_LOAD
2795 && ((*p)->flags() & elfcpp::PF_X) != 0
2796 && ((*p)->flags() & elfcpp::PF_R) != 0)
2797 {
2798 re_vaddr = (*p)->vaddr();
2799 re_memsz = (*p)->memsz();
2800 continue;
2801 }
2802 if ((*p)->type() == elfcpp::PT_LOAD
2803 && ((*p)->flags() & elfcpp::PF_W) != 0
2804 && ((*p)->flags() & elfcpp::PF_R) != 0)
2805 {
2806 rw_vaddr = (*p)->vaddr();
2807 rw_memsz = (*p)->memsz();
2808 break;
2809 }
2810 }
2811
2812 // With -Wl,--rosegment, report data segment size as delta of end of
2813 // "RW" segment and end of "R E" segment. Otherwise, data segment
2814 // size is just the memsz of "RW" segment.
2815 if (parameters->options().rosegment())
2816 data_seg_size = (rw_vaddr + rw_memsz) - (re_vaddr + re_memsz);
2817 else
2818 data_seg_size = rw_memsz;
2819
2820 if (data_seg_size >= target->max_pie_data_segment_size())
2821 gold_warning(
2822 _("Unsafe PIE data segment size (%" PRIu64 " > %" PRIu64 "). "
2823 "For kernels with CONFIG_ARCH_BINFMT_ELF_RANDOMIZE_PIE enabled, "
2824 "load_elf_binary() attempts to map a PIE binary into an address "
2825 "range immediately below mm->mmap_base. The first PT_LOAD segment "
2826 "is mapped below mm->mmap_base, the subsequent PT_LOAD segment(s) "
2827 "end up being mapped above mm->mmap_base into the area that is "
2828 "supposed to be the \"gap\" between the stack and the binary. Since"
2829 " the size of the \"gap\" on x86_64 is only guaranteed to be 128MB "
2830 "this means that binaries with large data segments > 128MB can end "
2831 "up mapping part of their data segment over their stack resulting "
2832 "in corruption of the stack. Any PIE binary with a data segment > "
2833 "128MB is vulnerable to this. It is suggested to turn off PIE."),
2834 data_seg_size,
2835 target->max_pie_data_segment_size());
2836 }
2837
2838 // If there is a load segment that contains the file and program headers,
2839 // provide a symbol __ehdr_start pointing there.
2840 // A program can use this to examine itself robustly.
2841 Symbol *ehdr_start = symtab->lookup("__ehdr_start");
2842 if (ehdr_start != NULL && ehdr_start->is_predefined())
2843 {
2844 if (load_seg != NULL)
2845 ehdr_start->set_output_segment(load_seg, Symbol::SEGMENT_START);
2846 else
2847 ehdr_start->set_undefined();
2848 }
2849
2850 // Set the file offsets of all the non-data sections we've seen so
2851 // far which don't have to wait for the input sections. We need
2852 // this in order to finalize local symbols in non-allocated
2853 // sections.
2854 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
2855
2856 // Set the section indexes of all unallocated sections seen so far,
2857 // in case any of them are somehow referenced by a symbol.
2858 shndx = this->set_section_indexes(shndx);
2859
2860 // Create the symbol table sections.
2861 this->create_symtab_sections(input_objects, symtab, shndx, &off);
2862 if (!parameters->doing_static_link())
2863 this->assign_local_dynsym_offsets(input_objects);
2864
2865 // Process any symbol assignments from a linker script. This must
2866 // be called after the symbol table has been finalized.
2867 this->script_options_->finalize_symbols(symtab, this);
2868
2869 // Create the incremental inputs sections.
2870 if (this->incremental_inputs_)
2871 {
2872 this->incremental_inputs_->finalize();
2873 this->create_incremental_info_sections(symtab);
2874 }
2875
2876 // Create the .shstrtab section.
2877 Output_section* shstrtab_section = this->create_shstrtab();
2878
2879 // Set the file offsets of the rest of the non-data sections which
2880 // don't have to wait for the input sections.
2881 off = this->set_section_offsets(off, BEFORE_INPUT_SECTIONS_PASS);
2882
2883 // Now that all sections have been created, set the section indexes
2884 // for any sections which haven't been done yet.
2885 shndx = this->set_section_indexes(shndx);
2886
2887 // Create the section table header.
2888 this->create_shdrs(shstrtab_section, &off);
2889
2890 // If there are no sections which require postprocessing, we can
2891 // handle the section names now, and avoid a resize later.
2892 if (!this->any_postprocessing_sections_)
2893 {
2894 off = this->set_section_offsets(off,
2895 POSTPROCESSING_SECTIONS_PASS);
2896 off =
2897 this->set_section_offsets(off,
2898 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
2899 }
2900
2901 file_header->set_section_info(this->section_headers_, shstrtab_section);
2902
2903 // Now we know exactly where everything goes in the output file
2904 // (except for non-allocated sections which require postprocessing).
2905 Output_data::layout_complete();
2906
2907 this->output_file_size_ = off;
2908
2909 return off;
2910 }
2911
2912 // Create a note header following the format defined in the ELF ABI.
2913 // NAME is the name, NOTE_TYPE is the type, SECTION_NAME is the name
2914 // of the section to create, DESCSZ is the size of the descriptor.
2915 // ALLOCATE is true if the section should be allocated in memory.
2916 // This returns the new note section. It sets *TRAILING_PADDING to
2917 // the number of trailing zero bytes required.
2918
2919 Output_section*
create_note(const char * name,int note_type,const char * section_name,size_t descsz,bool allocate,size_t * trailing_padding)2920 Layout::create_note(const char* name, int note_type,
2921 const char* section_name, size_t descsz,
2922 bool allocate, size_t* trailing_padding)
2923 {
2924 // Authorities all agree that the values in a .note field should
2925 // be aligned on 4-byte boundaries for 32-bit binaries. However,
2926 // they differ on what the alignment is for 64-bit binaries.
2927 // The GABI says unambiguously they take 8-byte alignment:
2928 // http://sco.com/developers/gabi/latest/ch5.pheader.html#note_section
2929 // Other documentation says alignment should always be 4 bytes:
2930 // http://www.netbsd.org/docs/kernel/elf-notes.html#note-format
2931 // GNU ld and GNU readelf both support the latter (at least as of
2932 // version 2.16.91), and glibc always generates the latter for
2933 // .note.ABI-tag (as of version 1.6), so that's the one we go with
2934 // here.
2935 #ifdef GABI_FORMAT_FOR_DOTNOTE_SECTION // This is not defined by default.
2936 const int size = parameters->target().get_size();
2937 #else
2938 const int size = 32;
2939 #endif
2940
2941 // The contents of the .note section.
2942 size_t namesz = strlen(name) + 1;
2943 size_t aligned_namesz = align_address(namesz, size / 8);
2944 size_t aligned_descsz = align_address(descsz, size / 8);
2945
2946 size_t notehdrsz = 3 * (size / 8) + aligned_namesz;
2947
2948 unsigned char* buffer = new unsigned char[notehdrsz];
2949 memset(buffer, 0, notehdrsz);
2950
2951 bool is_big_endian = parameters->target().is_big_endian();
2952
2953 if (size == 32)
2954 {
2955 if (!is_big_endian)
2956 {
2957 elfcpp::Swap<32, false>::writeval(buffer, namesz);
2958 elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
2959 elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
2960 }
2961 else
2962 {
2963 elfcpp::Swap<32, true>::writeval(buffer, namesz);
2964 elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
2965 elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
2966 }
2967 }
2968 else if (size == 64)
2969 {
2970 if (!is_big_endian)
2971 {
2972 elfcpp::Swap<64, false>::writeval(buffer, namesz);
2973 elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
2974 elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
2975 }
2976 else
2977 {
2978 elfcpp::Swap<64, true>::writeval(buffer, namesz);
2979 elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
2980 elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
2981 }
2982 }
2983 else
2984 gold_unreachable();
2985
2986 memcpy(buffer + 3 * (size / 8), name, namesz);
2987
2988 elfcpp::Elf_Xword flags = 0;
2989 Output_section_order order = ORDER_INVALID;
2990 if (allocate)
2991 {
2992 flags = elfcpp::SHF_ALLOC;
2993 order = ORDER_RO_NOTE;
2994 }
2995 Output_section* os = this->choose_output_section(NULL, section_name,
2996 elfcpp::SHT_NOTE,
2997 flags, false, order, false);
2998 if (os == NULL)
2999 return NULL;
3000
3001 Output_section_data* posd = new Output_data_const_buffer(buffer, notehdrsz,
3002 size / 8,
3003 "** note header");
3004 os->add_output_section_data(posd);
3005
3006 *trailing_padding = aligned_descsz - descsz;
3007
3008 return os;
3009 }
3010
3011 // For an executable or shared library, create a note to record the
3012 // version of gold used to create the binary.
3013
3014 void
create_gold_note()3015 Layout::create_gold_note()
3016 {
3017 if (parameters->options().relocatable()
3018 || parameters->incremental_update())
3019 return;
3020
3021 std::string desc = std::string("gold ") + gold::get_version_string();
3022
3023 size_t trailing_padding;
3024 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_GOLD_VERSION,
3025 ".note.gnu.gold-version", desc.size(),
3026 false, &trailing_padding);
3027 if (os == NULL)
3028 return;
3029
3030 Output_section_data* posd = new Output_data_const(desc, 4);
3031 os->add_output_section_data(posd);
3032
3033 if (trailing_padding > 0)
3034 {
3035 posd = new Output_data_zero_fill(trailing_padding, 0);
3036 os->add_output_section_data(posd);
3037 }
3038 }
3039
3040 // Record whether the stack should be executable. This can be set
3041 // from the command line using the -z execstack or -z noexecstack
3042 // options. Otherwise, if any input file has a .note.GNU-stack
3043 // section with the SHF_EXECINSTR flag set, the stack should be
3044 // executable. Otherwise, if at least one input file a
3045 // .note.GNU-stack section, and some input file has no .note.GNU-stack
3046 // section, we use the target default for whether the stack should be
3047 // executable. Otherwise, we don't generate a stack note. When
3048 // generating a object file, we create a .note.GNU-stack section with
3049 // the appropriate marking. When generating an executable or shared
3050 // library, we create a PT_GNU_STACK segment.
3051
3052 void
create_executable_stack_info()3053 Layout::create_executable_stack_info()
3054 {
3055 bool is_stack_executable;
3056 if (parameters->options().is_execstack_set())
3057 {
3058 is_stack_executable = parameters->options().is_stack_executable();
3059 if (!is_stack_executable
3060 && this->input_requires_executable_stack_
3061 && parameters->options().warn_execstack())
3062 gold_warning(_("one or more inputs require executable stack, "
3063 "but -z noexecstack was given"));
3064 }
3065 else if (!this->input_with_gnu_stack_note_)
3066 return;
3067 else
3068 {
3069 if (this->input_requires_executable_stack_)
3070 is_stack_executable = true;
3071 else if (this->input_without_gnu_stack_note_)
3072 is_stack_executable =
3073 parameters->target().is_default_stack_executable();
3074 else
3075 is_stack_executable = false;
3076 }
3077
3078 if (parameters->options().relocatable())
3079 {
3080 const char* name = this->namepool_.add(".note.GNU-stack", false, NULL);
3081 elfcpp::Elf_Xword flags = 0;
3082 if (is_stack_executable)
3083 flags |= elfcpp::SHF_EXECINSTR;
3084 this->make_output_section(name, elfcpp::SHT_PROGBITS, flags,
3085 ORDER_INVALID, false);
3086 }
3087 else
3088 {
3089 if (this->script_options_->saw_phdrs_clause())
3090 return;
3091 int flags = elfcpp::PF_R | elfcpp::PF_W;
3092 if (is_stack_executable)
3093 flags |= elfcpp::PF_X;
3094 this->make_output_segment(elfcpp::PT_GNU_STACK, flags);
3095 }
3096 }
3097
3098 // If --build-id was used, set up the build ID note.
3099
3100 void
create_build_id()3101 Layout::create_build_id()
3102 {
3103 if (!parameters->options().user_set_build_id())
3104 return;
3105
3106 const char* style = parameters->options().build_id();
3107 if (strcmp(style, "none") == 0)
3108 return;
3109
3110 // Set DESCSZ to the size of the note descriptor. When possible,
3111 // set DESC to the note descriptor contents.
3112 size_t descsz;
3113 std::string desc;
3114 if (strcmp(style, "md5") == 0)
3115 descsz = 128 / 8;
3116 else if ((strcmp(style, "sha1") == 0) || (strcmp(style, "tree") == 0))
3117 descsz = 160 / 8;
3118 else if (strcmp(style, "uuid") == 0)
3119 {
3120 const size_t uuidsz = 128 / 8;
3121
3122 char buffer[uuidsz];
3123 memset(buffer, 0, uuidsz);
3124
3125 int descriptor = open_descriptor(-1, "/dev/urandom", O_RDONLY);
3126 if (descriptor < 0)
3127 gold_error(_("--build-id=uuid failed: could not open /dev/urandom: %s"),
3128 strerror(errno));
3129 else
3130 {
3131 ssize_t got = ::read(descriptor, buffer, uuidsz);
3132 release_descriptor(descriptor, true);
3133 if (got < 0)
3134 gold_error(_("/dev/urandom: read failed: %s"), strerror(errno));
3135 else if (static_cast<size_t>(got) != uuidsz)
3136 gold_error(_("/dev/urandom: expected %zu bytes, got %zd bytes"),
3137 uuidsz, got);
3138 }
3139
3140 desc.assign(buffer, uuidsz);
3141 descsz = uuidsz;
3142 }
3143 else if (strncmp(style, "0x", 2) == 0)
3144 {
3145 hex_init();
3146 const char* p = style + 2;
3147 while (*p != '\0')
3148 {
3149 if (hex_p(p[0]) && hex_p(p[1]))
3150 {
3151 char c = (hex_value(p[0]) << 4) | hex_value(p[1]);
3152 desc += c;
3153 p += 2;
3154 }
3155 else if (*p == '-' || *p == ':')
3156 ++p;
3157 else
3158 gold_fatal(_("--build-id argument '%s' not a valid hex number"),
3159 style);
3160 }
3161 descsz = desc.size();
3162 }
3163 else
3164 gold_fatal(_("unrecognized --build-id argument '%s'"), style);
3165
3166 // Create the note.
3167 size_t trailing_padding;
3168 Output_section* os = this->create_note("GNU", elfcpp::NT_GNU_BUILD_ID,
3169 ".note.gnu.build-id", descsz, true,
3170 &trailing_padding);
3171 if (os == NULL)
3172 return;
3173
3174 if (!desc.empty())
3175 {
3176 // We know the value already, so we fill it in now.
3177 gold_assert(desc.size() == descsz);
3178
3179 Output_section_data* posd = new Output_data_const(desc, 4);
3180 os->add_output_section_data(posd);
3181
3182 if (trailing_padding != 0)
3183 {
3184 posd = new Output_data_zero_fill(trailing_padding, 0);
3185 os->add_output_section_data(posd);
3186 }
3187 }
3188 else
3189 {
3190 // We need to compute a checksum after we have completed the
3191 // link.
3192 gold_assert(trailing_padding == 0);
3193 this->build_id_note_ = new Output_data_zero_fill(descsz, 4);
3194 os->add_output_section_data(this->build_id_note_);
3195 }
3196 }
3197
3198 // If we have both .stabXX and .stabXXstr sections, then the sh_link
3199 // field of the former should point to the latter. I'm not sure who
3200 // started this, but the GNU linker does it, and some tools depend
3201 // upon it.
3202
3203 void
link_stabs_sections()3204 Layout::link_stabs_sections()
3205 {
3206 if (!this->have_stabstr_section_)
3207 return;
3208
3209 for (Section_list::iterator p = this->section_list_.begin();
3210 p != this->section_list_.end();
3211 ++p)
3212 {
3213 if ((*p)->type() != elfcpp::SHT_STRTAB)
3214 continue;
3215
3216 const char* name = (*p)->name();
3217 if (strncmp(name, ".stab", 5) != 0)
3218 continue;
3219
3220 size_t len = strlen(name);
3221 if (strcmp(name + len - 3, "str") != 0)
3222 continue;
3223
3224 std::string stab_name(name, len - 3);
3225 Output_section* stab_sec;
3226 stab_sec = this->find_output_section(stab_name.c_str());
3227 if (stab_sec != NULL)
3228 stab_sec->set_link_section(*p);
3229 }
3230 }
3231
3232 // Create .gnu_incremental_inputs and related sections needed
3233 // for the next run of incremental linking to check what has changed.
3234
3235 void
create_incremental_info_sections(Symbol_table * symtab)3236 Layout::create_incremental_info_sections(Symbol_table* symtab)
3237 {
3238 Incremental_inputs* incr = this->incremental_inputs_;
3239
3240 gold_assert(incr != NULL);
3241
3242 // Create the .gnu_incremental_inputs, _symtab, and _relocs input sections.
3243 incr->create_data_sections(symtab);
3244
3245 // Add the .gnu_incremental_inputs section.
3246 const char* incremental_inputs_name =
3247 this->namepool_.add(".gnu_incremental_inputs", false, NULL);
3248 Output_section* incremental_inputs_os =
3249 this->make_output_section(incremental_inputs_name,
3250 elfcpp::SHT_GNU_INCREMENTAL_INPUTS, 0,
3251 ORDER_INVALID, false);
3252 incremental_inputs_os->add_output_section_data(incr->inputs_section());
3253
3254 // Add the .gnu_incremental_symtab section.
3255 const char* incremental_symtab_name =
3256 this->namepool_.add(".gnu_incremental_symtab", false, NULL);
3257 Output_section* incremental_symtab_os =
3258 this->make_output_section(incremental_symtab_name,
3259 elfcpp::SHT_GNU_INCREMENTAL_SYMTAB, 0,
3260 ORDER_INVALID, false);
3261 incremental_symtab_os->add_output_section_data(incr->symtab_section());
3262 incremental_symtab_os->set_entsize(4);
3263
3264 // Add the .gnu_incremental_relocs section.
3265 const char* incremental_relocs_name =
3266 this->namepool_.add(".gnu_incremental_relocs", false, NULL);
3267 Output_section* incremental_relocs_os =
3268 this->make_output_section(incremental_relocs_name,
3269 elfcpp::SHT_GNU_INCREMENTAL_RELOCS, 0,
3270 ORDER_INVALID, false);
3271 incremental_relocs_os->add_output_section_data(incr->relocs_section());
3272 incremental_relocs_os->set_entsize(incr->relocs_entsize());
3273
3274 // Add the .gnu_incremental_got_plt section.
3275 const char* incremental_got_plt_name =
3276 this->namepool_.add(".gnu_incremental_got_plt", false, NULL);
3277 Output_section* incremental_got_plt_os =
3278 this->make_output_section(incremental_got_plt_name,
3279 elfcpp::SHT_GNU_INCREMENTAL_GOT_PLT, 0,
3280 ORDER_INVALID, false);
3281 incremental_got_plt_os->add_output_section_data(incr->got_plt_section());
3282
3283 // Add the .gnu_incremental_strtab section.
3284 const char* incremental_strtab_name =
3285 this->namepool_.add(".gnu_incremental_strtab", false, NULL);
3286 Output_section* incremental_strtab_os = this->make_output_section(incremental_strtab_name,
3287 elfcpp::SHT_STRTAB, 0,
3288 ORDER_INVALID, false);
3289 Output_data_strtab* strtab_data =
3290 new Output_data_strtab(incr->get_stringpool());
3291 incremental_strtab_os->add_output_section_data(strtab_data);
3292
3293 incremental_inputs_os->set_after_input_sections();
3294 incremental_symtab_os->set_after_input_sections();
3295 incremental_relocs_os->set_after_input_sections();
3296 incremental_got_plt_os->set_after_input_sections();
3297
3298 incremental_inputs_os->set_link_section(incremental_strtab_os);
3299 incremental_symtab_os->set_link_section(incremental_inputs_os);
3300 incremental_relocs_os->set_link_section(incremental_inputs_os);
3301 incremental_got_plt_os->set_link_section(incremental_inputs_os);
3302 }
3303
3304 // Return whether SEG1 should be before SEG2 in the output file. This
3305 // is based entirely on the segment type and flags. When this is
3306 // called the segment addresses have normally not yet been set.
3307
3308 bool
segment_precedes(const Output_segment * seg1,const Output_segment * seg2)3309 Layout::segment_precedes(const Output_segment* seg1,
3310 const Output_segment* seg2)
3311 {
3312 elfcpp::Elf_Word type1 = seg1->type();
3313 elfcpp::Elf_Word type2 = seg2->type();
3314
3315 // The single PT_PHDR segment is required to precede any loadable
3316 // segment. We simply make it always first.
3317 if (type1 == elfcpp::PT_PHDR)
3318 {
3319 gold_assert(type2 != elfcpp::PT_PHDR);
3320 return true;
3321 }
3322 if (type2 == elfcpp::PT_PHDR)
3323 return false;
3324
3325 // The single PT_INTERP segment is required to precede any loadable
3326 // segment. We simply make it always second.
3327 if (type1 == elfcpp::PT_INTERP)
3328 {
3329 gold_assert(type2 != elfcpp::PT_INTERP);
3330 return true;
3331 }
3332 if (type2 == elfcpp::PT_INTERP)
3333 return false;
3334
3335 // We then put PT_LOAD segments before any other segments.
3336 if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
3337 return true;
3338 if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
3339 return false;
3340
3341 // We put the PT_TLS segment last except for the PT_GNU_RELRO
3342 // segment, because that is where the dynamic linker expects to find
3343 // it (this is just for efficiency; other positions would also work
3344 // correctly).
3345 if (type1 == elfcpp::PT_TLS
3346 && type2 != elfcpp::PT_TLS
3347 && type2 != elfcpp::PT_GNU_RELRO)
3348 return false;
3349 if (type2 == elfcpp::PT_TLS
3350 && type1 != elfcpp::PT_TLS
3351 && type1 != elfcpp::PT_GNU_RELRO)
3352 return true;
3353
3354 // We put the PT_GNU_RELRO segment last, because that is where the
3355 // dynamic linker expects to find it (as with PT_TLS, this is just
3356 // for efficiency).
3357 if (type1 == elfcpp::PT_GNU_RELRO && type2 != elfcpp::PT_GNU_RELRO)
3358 return false;
3359 if (type2 == elfcpp::PT_GNU_RELRO && type1 != elfcpp::PT_GNU_RELRO)
3360 return true;
3361
3362 const elfcpp::Elf_Word flags1 = seg1->flags();
3363 const elfcpp::Elf_Word flags2 = seg2->flags();
3364
3365 // The order of non-PT_LOAD segments is unimportant. We simply sort
3366 // by the numeric segment type and flags values. There should not
3367 // be more than one segment with the same type and flags, except
3368 // when a linker script specifies such.
3369 if (type1 != elfcpp::PT_LOAD)
3370 {
3371 if (type1 != type2)
3372 return type1 < type2;
3373 gold_assert(flags1 != flags2
3374 || this->script_options_->saw_phdrs_clause());
3375 return flags1 < flags2;
3376 }
3377
3378 // If the addresses are set already, sort by load address.
3379 if (seg1->are_addresses_set())
3380 {
3381 if (!seg2->are_addresses_set())
3382 return true;
3383
3384 unsigned int section_count1 = seg1->output_section_count();
3385 unsigned int section_count2 = seg2->output_section_count();
3386 if (section_count1 == 0 && section_count2 > 0)
3387 return true;
3388 if (section_count1 > 0 && section_count2 == 0)
3389 return false;
3390
3391 uint64_t paddr1 = (seg1->are_addresses_set()
3392 ? seg1->paddr()
3393 : seg1->first_section_load_address());
3394 uint64_t paddr2 = (seg2->are_addresses_set()
3395 ? seg2->paddr()
3396 : seg2->first_section_load_address());
3397
3398 if (paddr1 != paddr2)
3399 return paddr1 < paddr2;
3400 }
3401 else if (seg2->are_addresses_set())
3402 return false;
3403
3404 // A segment which holds large data comes after a segment which does
3405 // not hold large data.
3406 if (seg1->is_large_data_segment())
3407 {
3408 if (!seg2->is_large_data_segment())
3409 return false;
3410 }
3411 else if (seg2->is_large_data_segment())
3412 return true;
3413
3414 // Otherwise, we sort PT_LOAD segments based on the flags. Readonly
3415 // segments come before writable segments. Then writable segments
3416 // with data come before writable segments without data. Then
3417 // executable segments come before non-executable segments. Then
3418 // the unlikely case of a non-readable segment comes before the
3419 // normal case of a readable segment. If there are multiple
3420 // segments with the same type and flags, we require that the
3421 // address be set, and we sort by virtual address and then physical
3422 // address.
3423 if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
3424 return (flags1 & elfcpp::PF_W) == 0;
3425 if ((flags1 & elfcpp::PF_W) != 0
3426 && seg1->has_any_data_sections() != seg2->has_any_data_sections())
3427 return seg1->has_any_data_sections();
3428 if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
3429 return (flags1 & elfcpp::PF_X) != 0;
3430 if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
3431 return (flags1 & elfcpp::PF_R) == 0;
3432
3433 // We shouldn't get here--we shouldn't create segments which we
3434 // can't distinguish. Unless of course we are using a weird linker
3435 // script or overlapping --section-start options. We could also get
3436 // here if plugins want unique segments for subsets of sections.
3437 gold_assert(this->script_options_->saw_phdrs_clause()
3438 || parameters->options().any_section_start()
3439 || this->is_unique_segment_for_sections_specified());
3440 return false;
3441 }
3442
3443 // Increase OFF so that it is congruent to ADDR modulo ABI_PAGESIZE.
3444
3445 static off_t
align_file_offset(off_t off,uint64_t addr,uint64_t abi_pagesize)3446 align_file_offset(off_t off, uint64_t addr, uint64_t abi_pagesize)
3447 {
3448 uint64_t unsigned_off = off;
3449 uint64_t aligned_off = ((unsigned_off & ~(abi_pagesize - 1))
3450 | (addr & (abi_pagesize - 1)));
3451 if (aligned_off < unsigned_off)
3452 aligned_off += abi_pagesize;
3453 return aligned_off;
3454 }
3455
3456 // On targets where the text segment contains only executable code,
3457 // a non-executable segment is never the text segment.
3458
3459 static inline bool
is_text_segment(const Target * target,const Output_segment * seg)3460 is_text_segment(const Target* target, const Output_segment* seg)
3461 {
3462 elfcpp::Elf_Xword flags = seg->flags();
3463 if ((flags & elfcpp::PF_W) != 0)
3464 return false;
3465 if ((flags & elfcpp::PF_X) == 0)
3466 return !target->isolate_execinstr();
3467 return true;
3468 }
3469
3470 // Set the file offsets of all the segments, and all the sections they
3471 // contain. They have all been created. LOAD_SEG must be be laid out
3472 // first. Return the offset of the data to follow.
3473
3474 off_t
set_segment_offsets(const Target * target,Output_segment * load_seg,unsigned int * pshndx)3475 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
3476 unsigned int* pshndx)
3477 {
3478 // Sort them into the final order. We use a stable sort so that we
3479 // don't randomize the order of indistinguishable segments created
3480 // by linker scripts.
3481 std::stable_sort(this->segment_list_.begin(), this->segment_list_.end(),
3482 Layout::Compare_segments(this));
3483
3484 // Find the PT_LOAD segments, and set their addresses and offsets
3485 // and their section's addresses and offsets.
3486 uint64_t start_addr;
3487 if (parameters->options().user_set_Ttext())
3488 start_addr = parameters->options().Ttext();
3489 else if (parameters->options().output_is_position_independent())
3490 start_addr = 0;
3491 else
3492 start_addr = target->default_text_segment_address();
3493
3494 uint64_t addr = start_addr;
3495 off_t off = 0;
3496
3497 // If LOAD_SEG is NULL, then the file header and segment headers
3498 // will not be loadable. But they still need to be at offset 0 in
3499 // the file. Set their offsets now.
3500 if (load_seg == NULL)
3501 {
3502 for (Data_list::iterator p = this->special_output_list_.begin();
3503 p != this->special_output_list_.end();
3504 ++p)
3505 {
3506 off = align_address(off, (*p)->addralign());
3507 (*p)->set_address_and_file_offset(0, off);
3508 off += (*p)->data_size();
3509 }
3510 }
3511
3512 unsigned int increase_relro = this->increase_relro_;
3513 if (this->script_options_->saw_sections_clause())
3514 increase_relro = 0;
3515
3516 const bool check_sections = parameters->options().check_sections();
3517 Output_segment* last_load_segment = NULL;
3518
3519 unsigned int shndx_begin = *pshndx;
3520 unsigned int shndx_load_seg = *pshndx;
3521
3522 for (Segment_list::iterator p = this->segment_list_.begin();
3523 p != this->segment_list_.end();
3524 ++p)
3525 {
3526 if ((*p)->type() == elfcpp::PT_LOAD)
3527 {
3528 if (target->isolate_execinstr())
3529 {
3530 // When we hit the segment that should contain the
3531 // file headers, reset the file offset so we place
3532 // it and subsequent segments appropriately.
3533 // We'll fix up the preceding segments below.
3534 if (load_seg == *p)
3535 {
3536 if (off == 0)
3537 load_seg = NULL;
3538 else
3539 {
3540 off = 0;
3541 shndx_load_seg = *pshndx;
3542 }
3543 }
3544 }
3545 else
3546 {
3547 // Verify that the file headers fall into the first segment.
3548 if (load_seg != NULL && load_seg != *p)
3549 gold_unreachable();
3550 load_seg = NULL;
3551 }
3552
3553 bool are_addresses_set = (*p)->are_addresses_set();
3554 if (are_addresses_set)
3555 {
3556 // When it comes to setting file offsets, we care about
3557 // the physical address.
3558 addr = (*p)->paddr();
3559 }
3560 else if (parameters->options().user_set_Ttext()
3561 && (parameters->options().omagic()
3562 || is_text_segment(target, *p)))
3563 {
3564 are_addresses_set = true;
3565 }
3566 else if (parameters->options().user_set_Trodata_segment()
3567 && ((*p)->flags() & (elfcpp::PF_W | elfcpp::PF_X)) == 0)
3568 {
3569 addr = parameters->options().Trodata_segment();
3570 are_addresses_set = true;
3571 }
3572 else if (parameters->options().user_set_Tdata()
3573 && ((*p)->flags() & elfcpp::PF_W) != 0
3574 && (!parameters->options().user_set_Tbss()
3575 || (*p)->has_any_data_sections()))
3576 {
3577 addr = parameters->options().Tdata();
3578 are_addresses_set = true;
3579 }
3580 else if (parameters->options().user_set_Tbss()
3581 && ((*p)->flags() & elfcpp::PF_W) != 0
3582 && !(*p)->has_any_data_sections())
3583 {
3584 addr = parameters->options().Tbss();
3585 are_addresses_set = true;
3586 }
3587
3588 uint64_t orig_addr = addr;
3589 uint64_t orig_off = off;
3590
3591 uint64_t aligned_addr = 0;
3592 uint64_t abi_pagesize = target->abi_pagesize();
3593 uint64_t common_pagesize = target->common_pagesize();
3594
3595 if (!parameters->options().nmagic()
3596 && !parameters->options().omagic())
3597 (*p)->set_minimum_p_align(abi_pagesize);
3598
3599 if (!are_addresses_set)
3600 {
3601 // Skip the address forward one page, maintaining the same
3602 // position within the page. This lets us store both segments
3603 // overlapping on a single page in the file, but the loader will
3604 // put them on different pages in memory. We will revisit this
3605 // decision once we know the size of the segment.
3606
3607 uint64_t max_align = (*p)->maximum_alignment();
3608 if (max_align > abi_pagesize)
3609 addr = align_address(addr, max_align);
3610 aligned_addr = addr;
3611
3612 if (load_seg == *p)
3613 {
3614 // This is the segment that will contain the file
3615 // headers, so its offset will have to be exactly zero.
3616 gold_assert(orig_off == 0);
3617
3618 // If the target wants a fixed minimum distance from the
3619 // text segment to the read-only segment, move up now.
3620 uint64_t min_addr =
3621 start_addr + (parameters->options().user_set_rosegment_gap()
3622 ? parameters->options().rosegment_gap()
3623 : target->rosegment_gap());
3624 if (addr < min_addr)
3625 addr = min_addr;
3626
3627 // But this is not the first segment! To make its
3628 // address congruent with its offset, that address better
3629 // be aligned to the ABI-mandated page size.
3630 addr = align_address(addr, abi_pagesize);
3631 aligned_addr = addr;
3632 }
3633 else
3634 {
3635 if ((addr & (abi_pagesize - 1)) != 0)
3636 addr = addr + abi_pagesize;
3637
3638 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
3639 }
3640 }
3641
3642 if (!parameters->options().nmagic()
3643 && !parameters->options().omagic())
3644 {
3645 // Here we are also taking care of the case when
3646 // the maximum segment alignment is larger than the page size.
3647 off = align_file_offset(off, addr,
3648 std::max(abi_pagesize,
3649 (*p)->maximum_alignment()));
3650 }
3651 else
3652 {
3653 // This is -N or -n with a section script which prevents
3654 // us from using a load segment. We need to ensure that
3655 // the file offset is aligned to the alignment of the
3656 // segment. This is because the linker script
3657 // implicitly assumed a zero offset. If we don't align
3658 // here, then the alignment of the sections in the
3659 // linker script may not match the alignment of the
3660 // sections in the set_section_addresses call below,
3661 // causing an error about dot moving backward.
3662 off = align_address(off, (*p)->maximum_alignment());
3663 }
3664
3665 unsigned int shndx_hold = *pshndx;
3666 bool has_relro = false;
3667 uint64_t new_addr = (*p)->set_section_addresses(target, this,
3668 false, addr,
3669 &increase_relro,
3670 &has_relro,
3671 &off, pshndx);
3672
3673 // Now that we know the size of this segment, we may be able
3674 // to save a page in memory, at the cost of wasting some
3675 // file space, by instead aligning to the start of a new
3676 // page. Here we use the real machine page size rather than
3677 // the ABI mandated page size. If the segment has been
3678 // aligned so that the relro data ends at a page boundary,
3679 // we do not try to realign it.
3680
3681 if (!are_addresses_set
3682 && !has_relro
3683 && aligned_addr != addr
3684 && !parameters->incremental())
3685 {
3686 uint64_t first_off = (common_pagesize
3687 - (aligned_addr
3688 & (common_pagesize - 1)));
3689 uint64_t last_off = new_addr & (common_pagesize - 1);
3690 if (first_off > 0
3691 && last_off > 0
3692 && ((aligned_addr & ~ (common_pagesize - 1))
3693 != (new_addr & ~ (common_pagesize - 1)))
3694 && first_off + last_off <= common_pagesize)
3695 {
3696 *pshndx = shndx_hold;
3697 addr = align_address(aligned_addr, common_pagesize);
3698 addr = align_address(addr, (*p)->maximum_alignment());
3699 if ((addr & (abi_pagesize - 1)) != 0)
3700 addr = addr + abi_pagesize;
3701 off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
3702 off = align_file_offset(off, addr, abi_pagesize);
3703
3704 increase_relro = this->increase_relro_;
3705 if (this->script_options_->saw_sections_clause())
3706 increase_relro = 0;
3707 has_relro = false;
3708
3709 new_addr = (*p)->set_section_addresses(target, this,
3710 true, addr,
3711 &increase_relro,
3712 &has_relro,
3713 &off, pshndx);
3714 }
3715 }
3716
3717 addr = new_addr;
3718
3719 // Implement --check-sections. We know that the segments
3720 // are sorted by LMA.
3721 if (check_sections && last_load_segment != NULL)
3722 {
3723 gold_assert(last_load_segment->paddr() <= (*p)->paddr());
3724 if (last_load_segment->paddr() + last_load_segment->memsz()
3725 > (*p)->paddr())
3726 {
3727 unsigned long long lb1 = last_load_segment->paddr();
3728 unsigned long long le1 = lb1 + last_load_segment->memsz();
3729 unsigned long long lb2 = (*p)->paddr();
3730 unsigned long long le2 = lb2 + (*p)->memsz();
3731 gold_error(_("load segment overlap [0x%llx -> 0x%llx] and "
3732 "[0x%llx -> 0x%llx]"),
3733 lb1, le1, lb2, le2);
3734 }
3735 }
3736 last_load_segment = *p;
3737 }
3738 }
3739
3740 if (load_seg != NULL && target->isolate_execinstr())
3741 {
3742 // Process the early segments again, setting their file offsets
3743 // so they land after the segments starting at LOAD_SEG.
3744 off = align_file_offset(off, 0, target->abi_pagesize());
3745
3746 this->reset_relax_output();
3747
3748 for (Segment_list::iterator p = this->segment_list_.begin();
3749 *p != load_seg;
3750 ++p)
3751 {
3752 if ((*p)->type() == elfcpp::PT_LOAD)
3753 {
3754 // We repeat the whole job of assigning addresses and
3755 // offsets, but we really only want to change the offsets and
3756 // must ensure that the addresses all come out the same as
3757 // they did the first time through.
3758 bool has_relro = false;
3759 const uint64_t old_addr = (*p)->vaddr();
3760 const uint64_t old_end = old_addr + (*p)->memsz();
3761 uint64_t new_addr = (*p)->set_section_addresses(target, this,
3762 true, old_addr,
3763 &increase_relro,
3764 &has_relro,
3765 &off,
3766 &shndx_begin);
3767 gold_assert(new_addr == old_end);
3768 }
3769 }
3770
3771 gold_assert(shndx_begin == shndx_load_seg);
3772 }
3773
3774 // Handle the non-PT_LOAD segments, setting their offsets from their
3775 // section's offsets.
3776 for (Segment_list::iterator p = this->segment_list_.begin();
3777 p != this->segment_list_.end();
3778 ++p)
3779 {
3780 if ((*p)->type() != elfcpp::PT_LOAD)
3781 (*p)->set_offset((*p)->type() == elfcpp::PT_GNU_RELRO
3782 ? increase_relro
3783 : 0);
3784 }
3785
3786 // Set the TLS offsets for each section in the PT_TLS segment.
3787 if (this->tls_segment_ != NULL)
3788 this->tls_segment_->set_tls_offsets();
3789
3790 return off;
3791 }
3792
3793 // Set the offsets of all the allocated sections when doing a
3794 // relocatable link. This does the same jobs as set_segment_offsets,
3795 // only for a relocatable link.
3796
3797 off_t
set_relocatable_section_offsets(Output_data * file_header,unsigned int * pshndx)3798 Layout::set_relocatable_section_offsets(Output_data* file_header,
3799 unsigned int* pshndx)
3800 {
3801 off_t off = 0;
3802
3803 file_header->set_address_and_file_offset(0, 0);
3804 off += file_header->data_size();
3805
3806 for (Section_list::iterator p = this->section_list_.begin();
3807 p != this->section_list_.end();
3808 ++p)
3809 {
3810 // We skip unallocated sections here, except that group sections
3811 // have to come first.
3812 if (((*p)->flags() & elfcpp::SHF_ALLOC) == 0
3813 && (*p)->type() != elfcpp::SHT_GROUP)
3814 continue;
3815
3816 off = align_address(off, (*p)->addralign());
3817
3818 // The linker script might have set the address.
3819 if (!(*p)->is_address_valid())
3820 (*p)->set_address(0);
3821 (*p)->set_file_offset(off);
3822 (*p)->finalize_data_size();
3823 if ((*p)->type() != elfcpp::SHT_NOBITS)
3824 off += (*p)->data_size();
3825
3826 (*p)->set_out_shndx(*pshndx);
3827 ++*pshndx;
3828 }
3829
3830 return off;
3831 }
3832
3833 // Set the file offset of all the sections not associated with a
3834 // segment.
3835
3836 off_t
set_section_offsets(off_t off,Layout::Section_offset_pass pass)3837 Layout::set_section_offsets(off_t off, Layout::Section_offset_pass pass)
3838 {
3839 off_t startoff = off;
3840 off_t maxoff = off;
3841
3842 for (Section_list::iterator p = this->unattached_section_list_.begin();
3843 p != this->unattached_section_list_.end();
3844 ++p)
3845 {
3846 // The symtab section is handled in create_symtab_sections.
3847 if (*p == this->symtab_section_)
3848 continue;
3849
3850 // If we've already set the data size, don't set it again.
3851 if ((*p)->is_offset_valid() && (*p)->is_data_size_valid())
3852 continue;
3853
3854 if (pass == BEFORE_INPUT_SECTIONS_PASS
3855 && (*p)->requires_postprocessing())
3856 {
3857 (*p)->create_postprocessing_buffer();
3858 this->any_postprocessing_sections_ = true;
3859 }
3860
3861 if (pass == BEFORE_INPUT_SECTIONS_PASS
3862 && (*p)->after_input_sections())
3863 continue;
3864 else if (pass == POSTPROCESSING_SECTIONS_PASS
3865 && (!(*p)->after_input_sections()
3866 || (*p)->type() == elfcpp::SHT_STRTAB))
3867 continue;
3868 else if (pass == STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
3869 && (!(*p)->after_input_sections()
3870 || (*p)->type() != elfcpp::SHT_STRTAB))
3871 continue;
3872
3873 if (!parameters->incremental_update())
3874 {
3875 off = align_address(off, (*p)->addralign());
3876 (*p)->set_file_offset(off);
3877 (*p)->finalize_data_size();
3878 }
3879 else
3880 {
3881 // Incremental update: allocate file space from free list.
3882 (*p)->pre_finalize_data_size();
3883 off_t current_size = (*p)->current_data_size();
3884 off = this->allocate(current_size, (*p)->addralign(), startoff);
3885 if (off == -1)
3886 {
3887 if (is_debugging_enabled(DEBUG_INCREMENTAL))
3888 this->free_list_.dump();
3889 gold_assert((*p)->output_section() != NULL);
3890 gold_fallback(_("out of patch space for section %s; "
3891 "relink with --incremental-full"),
3892 (*p)->output_section()->name());
3893 }
3894 (*p)->set_file_offset(off);
3895 (*p)->finalize_data_size();
3896 if ((*p)->data_size() > current_size)
3897 {
3898 gold_assert((*p)->output_section() != NULL);
3899 gold_fallback(_("%s: section changed size; "
3900 "relink with --incremental-full"),
3901 (*p)->output_section()->name());
3902 }
3903 gold_debug(DEBUG_INCREMENTAL,
3904 "set_section_offsets: %08lx %08lx %s",
3905 static_cast<long>(off),
3906 static_cast<long>((*p)->data_size()),
3907 ((*p)->output_section() != NULL
3908 ? (*p)->output_section()->name() : "(special)"));
3909 }
3910
3911 off += (*p)->data_size();
3912 if (off > maxoff)
3913 maxoff = off;
3914
3915 // At this point the name must be set.
3916 if (pass != STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS)
3917 this->namepool_.add((*p)->name(), false, NULL);
3918 }
3919 return maxoff;
3920 }
3921
3922 // Set the section indexes of all the sections not associated with a
3923 // segment.
3924
3925 unsigned int
set_section_indexes(unsigned int shndx)3926 Layout::set_section_indexes(unsigned int shndx)
3927 {
3928 for (Section_list::iterator p = this->unattached_section_list_.begin();
3929 p != this->unattached_section_list_.end();
3930 ++p)
3931 {
3932 if (!(*p)->has_out_shndx())
3933 {
3934 (*p)->set_out_shndx(shndx);
3935 ++shndx;
3936 }
3937 }
3938 return shndx;
3939 }
3940
3941 // Set the section addresses according to the linker script. This is
3942 // only called when we see a SECTIONS clause. This returns the
3943 // program segment which should hold the file header and segment
3944 // headers, if any. It will return NULL if they should not be in a
3945 // segment.
3946
3947 Output_segment*
set_section_addresses_from_script(Symbol_table * symtab)3948 Layout::set_section_addresses_from_script(Symbol_table* symtab)
3949 {
3950 Script_sections* ss = this->script_options_->script_sections();
3951 gold_assert(ss->saw_sections_clause());
3952 return this->script_options_->set_section_addresses(symtab, this);
3953 }
3954
3955 // Place the orphan sections in the linker script.
3956
3957 void
place_orphan_sections_in_script()3958 Layout::place_orphan_sections_in_script()
3959 {
3960 Script_sections* ss = this->script_options_->script_sections();
3961 gold_assert(ss->saw_sections_clause());
3962
3963 // Place each orphaned output section in the script.
3964 for (Section_list::iterator p = this->section_list_.begin();
3965 p != this->section_list_.end();
3966 ++p)
3967 {
3968 if (!(*p)->found_in_sections_clause())
3969 ss->place_orphan(*p);
3970 }
3971 }
3972
3973 // Count the local symbols in the regular symbol table and the dynamic
3974 // symbol table, and build the respective string pools.
3975
3976 void
count_local_symbols(const Task * task,const Input_objects * input_objects)3977 Layout::count_local_symbols(const Task* task,
3978 const Input_objects* input_objects)
3979 {
3980 // First, figure out an upper bound on the number of symbols we'll
3981 // be inserting into each pool. This helps us create the pools with
3982 // the right size, to avoid unnecessary hashtable resizing.
3983 unsigned int symbol_count = 0;
3984 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
3985 p != input_objects->relobj_end();
3986 ++p)
3987 symbol_count += (*p)->local_symbol_count();
3988
3989 // Go from "upper bound" to "estimate." We overcount for two
3990 // reasons: we double-count symbols that occur in more than one
3991 // object file, and we count symbols that are dropped from the
3992 // output. Add it all together and assume we overcount by 100%.
3993 symbol_count /= 2;
3994
3995 // We assume all symbols will go into both the sympool and dynpool.
3996 this->sympool_.reserve(symbol_count);
3997 this->dynpool_.reserve(symbol_count);
3998
3999 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4000 p != input_objects->relobj_end();
4001 ++p)
4002 {
4003 Task_lock_obj<Object> tlo(task, *p);
4004 (*p)->count_local_symbols(&this->sympool_, &this->dynpool_);
4005 }
4006 }
4007
4008 // Create the symbol table sections. Here we also set the final
4009 // values of the symbols. At this point all the loadable sections are
4010 // fully laid out. SHNUM is the number of sections so far.
4011
4012 void
create_symtab_sections(const Input_objects * input_objects,Symbol_table * symtab,unsigned int shnum,off_t * poff)4013 Layout::create_symtab_sections(const Input_objects* input_objects,
4014 Symbol_table* symtab,
4015 unsigned int shnum,
4016 off_t* poff)
4017 {
4018 int symsize;
4019 unsigned int align;
4020 if (parameters->target().get_size() == 32)
4021 {
4022 symsize = elfcpp::Elf_sizes<32>::sym_size;
4023 align = 4;
4024 }
4025 else if (parameters->target().get_size() == 64)
4026 {
4027 symsize = elfcpp::Elf_sizes<64>::sym_size;
4028 align = 8;
4029 }
4030 else
4031 gold_unreachable();
4032
4033 // Compute file offsets relative to the start of the symtab section.
4034 off_t off = 0;
4035
4036 // Save space for the dummy symbol at the start of the section. We
4037 // never bother to write this out--it will just be left as zero.
4038 off += symsize;
4039 unsigned int local_symbol_index = 1;
4040
4041 // Add STT_SECTION symbols for each Output section which needs one.
4042 for (Section_list::iterator p = this->section_list_.begin();
4043 p != this->section_list_.end();
4044 ++p)
4045 {
4046 if (!(*p)->needs_symtab_index())
4047 (*p)->set_symtab_index(-1U);
4048 else
4049 {
4050 (*p)->set_symtab_index(local_symbol_index);
4051 ++local_symbol_index;
4052 off += symsize;
4053 }
4054 }
4055
4056 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4057 p != input_objects->relobj_end();
4058 ++p)
4059 {
4060 unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
4061 off, symtab);
4062 off += (index - local_symbol_index) * symsize;
4063 local_symbol_index = index;
4064 }
4065
4066 unsigned int local_symcount = local_symbol_index;
4067 gold_assert(static_cast<off_t>(local_symcount * symsize) == off);
4068
4069 off_t dynoff;
4070 size_t dyn_global_index;
4071 size_t dyncount;
4072 if (this->dynsym_section_ == NULL)
4073 {
4074 dynoff = 0;
4075 dyn_global_index = 0;
4076 dyncount = 0;
4077 }
4078 else
4079 {
4080 dyn_global_index = this->dynsym_section_->info();
4081 off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
4082 dynoff = this->dynsym_section_->offset() + locsize;
4083 dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
4084 gold_assert(static_cast<off_t>(dyncount * symsize)
4085 == this->dynsym_section_->data_size() - locsize);
4086 }
4087
4088 off_t global_off = off;
4089 off = symtab->finalize(off, dynoff, dyn_global_index, dyncount,
4090 &this->sympool_, &local_symcount);
4091
4092 if (!parameters->options().strip_all())
4093 {
4094 this->sympool_.set_string_offsets();
4095
4096 const char* symtab_name = this->namepool_.add(".symtab", false, NULL);
4097 Output_section* osymtab = this->make_output_section(symtab_name,
4098 elfcpp::SHT_SYMTAB,
4099 0, ORDER_INVALID,
4100 false);
4101 this->symtab_section_ = osymtab;
4102
4103 Output_section_data* pos = new Output_data_fixed_space(off, align,
4104 "** symtab");
4105 osymtab->add_output_section_data(pos);
4106
4107 // We generate a .symtab_shndx section if we have more than
4108 // SHN_LORESERVE sections. Technically it is possible that we
4109 // don't need one, because it is possible that there are no
4110 // symbols in any of sections with indexes larger than
4111 // SHN_LORESERVE. That is probably unusual, though, and it is
4112 // easier to always create one than to compute section indexes
4113 // twice (once here, once when writing out the symbols).
4114 if (shnum >= elfcpp::SHN_LORESERVE)
4115 {
4116 const char* symtab_xindex_name = this->namepool_.add(".symtab_shndx",
4117 false, NULL);
4118 Output_section* osymtab_xindex =
4119 this->make_output_section(symtab_xindex_name,
4120 elfcpp::SHT_SYMTAB_SHNDX, 0,
4121 ORDER_INVALID, false);
4122
4123 size_t symcount = off / symsize;
4124 this->symtab_xindex_ = new Output_symtab_xindex(symcount);
4125
4126 osymtab_xindex->add_output_section_data(this->symtab_xindex_);
4127
4128 osymtab_xindex->set_link_section(osymtab);
4129 osymtab_xindex->set_addralign(4);
4130 osymtab_xindex->set_entsize(4);
4131
4132 osymtab_xindex->set_after_input_sections();
4133
4134 // This tells the driver code to wait until the symbol table
4135 // has written out before writing out the postprocessing
4136 // sections, including the .symtab_shndx section.
4137 this->any_postprocessing_sections_ = true;
4138 }
4139
4140 const char* strtab_name = this->namepool_.add(".strtab", false, NULL);
4141 Output_section* ostrtab = this->make_output_section(strtab_name,
4142 elfcpp::SHT_STRTAB,
4143 0, ORDER_INVALID,
4144 false);
4145
4146 Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
4147 ostrtab->add_output_section_data(pstr);
4148
4149 off_t symtab_off;
4150 if (!parameters->incremental_update())
4151 symtab_off = align_address(*poff, align);
4152 else
4153 {
4154 symtab_off = this->allocate(off, align, *poff);
4155 if (off == -1)
4156 gold_fallback(_("out of patch space for symbol table; "
4157 "relink with --incremental-full"));
4158 gold_debug(DEBUG_INCREMENTAL,
4159 "create_symtab_sections: %08lx %08lx .symtab",
4160 static_cast<long>(symtab_off),
4161 static_cast<long>(off));
4162 }
4163
4164 symtab->set_file_offset(symtab_off + global_off);
4165 osymtab->set_file_offset(symtab_off);
4166 osymtab->finalize_data_size();
4167 osymtab->set_link_section(ostrtab);
4168 osymtab->set_info(local_symcount);
4169 osymtab->set_entsize(symsize);
4170
4171 if (symtab_off + off > *poff)
4172 *poff = symtab_off + off;
4173 }
4174 }
4175
4176 // Create the .shstrtab section, which holds the names of the
4177 // sections. At the time this is called, we have created all the
4178 // output sections except .shstrtab itself.
4179
4180 Output_section*
create_shstrtab()4181 Layout::create_shstrtab()
4182 {
4183 // FIXME: We don't need to create a .shstrtab section if we are
4184 // stripping everything.
4185
4186 const char* name = this->namepool_.add(".shstrtab", false, NULL);
4187
4188 Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0,
4189 ORDER_INVALID, false);
4190
4191 if (strcmp(parameters->options().compress_debug_sections(), "none") != 0)
4192 {
4193 // We can't write out this section until we've set all the
4194 // section names, and we don't set the names of compressed
4195 // output sections until relocations are complete. FIXME: With
4196 // the current names we use, this is unnecessary.
4197 os->set_after_input_sections();
4198 }
4199
4200 Output_section_data* posd = new Output_data_strtab(&this->namepool_);
4201 os->add_output_section_data(posd);
4202
4203 return os;
4204 }
4205
4206 // Create the section headers. SIZE is 32 or 64. OFF is the file
4207 // offset.
4208
4209 void
create_shdrs(const Output_section * shstrtab_section,off_t * poff)4210 Layout::create_shdrs(const Output_section* shstrtab_section, off_t* poff)
4211 {
4212 Output_section_headers* oshdrs;
4213 oshdrs = new Output_section_headers(this,
4214 &this->segment_list_,
4215 &this->section_list_,
4216 &this->unattached_section_list_,
4217 &this->namepool_,
4218 shstrtab_section);
4219 off_t off;
4220 if (!parameters->incremental_update())
4221 off = align_address(*poff, oshdrs->addralign());
4222 else
4223 {
4224 oshdrs->pre_finalize_data_size();
4225 off = this->allocate(oshdrs->data_size(), oshdrs->addralign(), *poff);
4226 if (off == -1)
4227 gold_fallback(_("out of patch space for section header table; "
4228 "relink with --incremental-full"));
4229 gold_debug(DEBUG_INCREMENTAL,
4230 "create_shdrs: %08lx %08lx (section header table)",
4231 static_cast<long>(off),
4232 static_cast<long>(off + oshdrs->data_size()));
4233 }
4234 oshdrs->set_address_and_file_offset(0, off);
4235 off += oshdrs->data_size();
4236 if (off > *poff)
4237 *poff = off;
4238 this->section_headers_ = oshdrs;
4239 }
4240
4241 // Count the allocated sections.
4242
4243 size_t
allocated_output_section_count() const4244 Layout::allocated_output_section_count() const
4245 {
4246 size_t section_count = 0;
4247 for (Segment_list::const_iterator p = this->segment_list_.begin();
4248 p != this->segment_list_.end();
4249 ++p)
4250 section_count += (*p)->output_section_count();
4251 return section_count;
4252 }
4253
4254 // Create the dynamic symbol table.
4255
4256 void
create_dynamic_symtab(const Input_objects * input_objects,Symbol_table * symtab,Output_section ** pdynstr,unsigned int * plocal_dynamic_count,std::vector<Symbol * > * pdynamic_symbols,Versions * pversions)4257 Layout::create_dynamic_symtab(const Input_objects* input_objects,
4258 Symbol_table* symtab,
4259 Output_section** pdynstr,
4260 unsigned int* plocal_dynamic_count,
4261 std::vector<Symbol*>* pdynamic_symbols,
4262 Versions* pversions)
4263 {
4264 // Count all the symbols in the dynamic symbol table, and set the
4265 // dynamic symbol indexes.
4266
4267 // Skip symbol 0, which is always all zeroes.
4268 unsigned int index = 1;
4269
4270 // Add STT_SECTION symbols for each Output section which needs one.
4271 for (Section_list::iterator p = this->section_list_.begin();
4272 p != this->section_list_.end();
4273 ++p)
4274 {
4275 if (!(*p)->needs_dynsym_index())
4276 (*p)->set_dynsym_index(-1U);
4277 else
4278 {
4279 (*p)->set_dynsym_index(index);
4280 ++index;
4281 }
4282 }
4283
4284 // Count the local symbols that need to go in the dynamic symbol table,
4285 // and set the dynamic symbol indexes.
4286 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4287 p != input_objects->relobj_end();
4288 ++p)
4289 {
4290 unsigned int new_index = (*p)->set_local_dynsym_indexes(index);
4291 index = new_index;
4292 }
4293
4294 unsigned int local_symcount = index;
4295 *plocal_dynamic_count = local_symcount;
4296
4297 index = symtab->set_dynsym_indexes(index, pdynamic_symbols,
4298 &this->dynpool_, pversions);
4299
4300 int symsize;
4301 unsigned int align;
4302 const int size = parameters->target().get_size();
4303 if (size == 32)
4304 {
4305 symsize = elfcpp::Elf_sizes<32>::sym_size;
4306 align = 4;
4307 }
4308 else if (size == 64)
4309 {
4310 symsize = elfcpp::Elf_sizes<64>::sym_size;
4311 align = 8;
4312 }
4313 else
4314 gold_unreachable();
4315
4316 // Create the dynamic symbol table section.
4317
4318 Output_section* dynsym = this->choose_output_section(NULL, ".dynsym",
4319 elfcpp::SHT_DYNSYM,
4320 elfcpp::SHF_ALLOC,
4321 false,
4322 ORDER_DYNAMIC_LINKER,
4323 false);
4324
4325 // Check for NULL as a linker script may discard .dynsym.
4326 if (dynsym != NULL)
4327 {
4328 Output_section_data* odata = new Output_data_fixed_space(index * symsize,
4329 align,
4330 "** dynsym");
4331 dynsym->add_output_section_data(odata);
4332
4333 dynsym->set_info(local_symcount);
4334 dynsym->set_entsize(symsize);
4335 dynsym->set_addralign(align);
4336
4337 this->dynsym_section_ = dynsym;
4338 }
4339
4340 Output_data_dynamic* const odyn = this->dynamic_data_;
4341 if (odyn != NULL)
4342 {
4343 odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
4344 odyn->add_constant(elfcpp::DT_SYMENT, symsize);
4345 }
4346
4347 // If there are more than SHN_LORESERVE allocated sections, we
4348 // create a .dynsym_shndx section. It is possible that we don't
4349 // need one, because it is possible that there are no dynamic
4350 // symbols in any of the sections with indexes larger than
4351 // SHN_LORESERVE. This is probably unusual, though, and at this
4352 // time we don't know the actual section indexes so it is
4353 // inconvenient to check.
4354 if (this->allocated_output_section_count() >= elfcpp::SHN_LORESERVE)
4355 {
4356 Output_section* dynsym_xindex =
4357 this->choose_output_section(NULL, ".dynsym_shndx",
4358 elfcpp::SHT_SYMTAB_SHNDX,
4359 elfcpp::SHF_ALLOC,
4360 false, ORDER_DYNAMIC_LINKER, false);
4361
4362 if (dynsym_xindex != NULL)
4363 {
4364 this->dynsym_xindex_ = new Output_symtab_xindex(index);
4365
4366 dynsym_xindex->add_output_section_data(this->dynsym_xindex_);
4367
4368 dynsym_xindex->set_link_section(dynsym);
4369 dynsym_xindex->set_addralign(4);
4370 dynsym_xindex->set_entsize(4);
4371
4372 dynsym_xindex->set_after_input_sections();
4373
4374 // This tells the driver code to wait until the symbol table
4375 // has written out before writing out the postprocessing
4376 // sections, including the .dynsym_shndx section.
4377 this->any_postprocessing_sections_ = true;
4378 }
4379 }
4380
4381 // Create the dynamic string table section.
4382
4383 Output_section* dynstr = this->choose_output_section(NULL, ".dynstr",
4384 elfcpp::SHT_STRTAB,
4385 elfcpp::SHF_ALLOC,
4386 false,
4387 ORDER_DYNAMIC_LINKER,
4388 false);
4389 *pdynstr = dynstr;
4390 if (dynstr != NULL)
4391 {
4392 Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
4393 dynstr->add_output_section_data(strdata);
4394
4395 if (dynsym != NULL)
4396 dynsym->set_link_section(dynstr);
4397 if (this->dynamic_section_ != NULL)
4398 this->dynamic_section_->set_link_section(dynstr);
4399
4400 if (odyn != NULL)
4401 {
4402 odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
4403 odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
4404 }
4405 }
4406
4407 // Create the hash tables. The Gnu-style hash table must be
4408 // built first, because it changes the order of the symbols
4409 // in the dynamic symbol table.
4410
4411 if (strcmp(parameters->options().hash_style(), "gnu") == 0
4412 || strcmp(parameters->options().hash_style(), "both") == 0)
4413 {
4414 unsigned char* phash;
4415 unsigned int hashlen;
4416 Dynobj::create_gnu_hash_table(*pdynamic_symbols, local_symcount,
4417 &phash, &hashlen);
4418
4419 Output_section* hashsec =
4420 this->choose_output_section(NULL, ".gnu.hash", elfcpp::SHT_GNU_HASH,
4421 elfcpp::SHF_ALLOC, false,
4422 ORDER_DYNAMIC_LINKER, false);
4423
4424 Output_section_data* hashdata = new Output_data_const_buffer(phash,
4425 hashlen,
4426 align,
4427 "** hash");
4428 if (hashsec != NULL && hashdata != NULL)
4429 hashsec->add_output_section_data(hashdata);
4430
4431 if (hashsec != NULL)
4432 {
4433 if (dynsym != NULL)
4434 hashsec->set_link_section(dynsym);
4435
4436 // For a 64-bit target, the entries in .gnu.hash do not have
4437 // a uniform size, so we only set the entry size for a
4438 // 32-bit target.
4439 if (parameters->target().get_size() == 32)
4440 hashsec->set_entsize(4);
4441
4442 if (odyn != NULL)
4443 odyn->add_section_address(elfcpp::DT_GNU_HASH, hashsec);
4444 }
4445 }
4446
4447 if (strcmp(parameters->options().hash_style(), "sysv") == 0
4448 || strcmp(parameters->options().hash_style(), "both") == 0)
4449 {
4450 unsigned char* phash;
4451 unsigned int hashlen;
4452 Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
4453 &phash, &hashlen);
4454
4455 Output_section* hashsec =
4456 this->choose_output_section(NULL, ".hash", elfcpp::SHT_HASH,
4457 elfcpp::SHF_ALLOC, false,
4458 ORDER_DYNAMIC_LINKER, false);
4459
4460 Output_section_data* hashdata = new Output_data_const_buffer(phash,
4461 hashlen,
4462 align,
4463 "** hash");
4464 if (hashsec != NULL && hashdata != NULL)
4465 hashsec->add_output_section_data(hashdata);
4466
4467 if (hashsec != NULL)
4468 {
4469 if (dynsym != NULL)
4470 hashsec->set_link_section(dynsym);
4471 hashsec->set_entsize(4);
4472 }
4473
4474 if (odyn != NULL)
4475 odyn->add_section_address(elfcpp::DT_HASH, hashsec);
4476 }
4477 }
4478
4479 // Assign offsets to each local portion of the dynamic symbol table.
4480
4481 void
assign_local_dynsym_offsets(const Input_objects * input_objects)4482 Layout::assign_local_dynsym_offsets(const Input_objects* input_objects)
4483 {
4484 Output_section* dynsym = this->dynsym_section_;
4485 if (dynsym == NULL)
4486 return;
4487
4488 off_t off = dynsym->offset();
4489
4490 // Skip the dummy symbol at the start of the section.
4491 off += dynsym->entsize();
4492
4493 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
4494 p != input_objects->relobj_end();
4495 ++p)
4496 {
4497 unsigned int count = (*p)->set_local_dynsym_offset(off);
4498 off += count * dynsym->entsize();
4499 }
4500 }
4501
4502 // Create the version sections.
4503
4504 void
create_version_sections(const Versions * versions,const Symbol_table * symtab,unsigned int local_symcount,const std::vector<Symbol * > & dynamic_symbols,const Output_section * dynstr)4505 Layout::create_version_sections(const Versions* versions,
4506 const Symbol_table* symtab,
4507 unsigned int local_symcount,
4508 const std::vector<Symbol*>& dynamic_symbols,
4509 const Output_section* dynstr)
4510 {
4511 if (!versions->any_defs() && !versions->any_needs())
4512 return;
4513
4514 switch (parameters->size_and_endianness())
4515 {
4516 #ifdef HAVE_TARGET_32_LITTLE
4517 case Parameters::TARGET_32_LITTLE:
4518 this->sized_create_version_sections<32, false>(versions, symtab,
4519 local_symcount,
4520 dynamic_symbols, dynstr);
4521 break;
4522 #endif
4523 #ifdef HAVE_TARGET_32_BIG
4524 case Parameters::TARGET_32_BIG:
4525 this->sized_create_version_sections<32, true>(versions, symtab,
4526 local_symcount,
4527 dynamic_symbols, dynstr);
4528 break;
4529 #endif
4530 #ifdef HAVE_TARGET_64_LITTLE
4531 case Parameters::TARGET_64_LITTLE:
4532 this->sized_create_version_sections<64, false>(versions, symtab,
4533 local_symcount,
4534 dynamic_symbols, dynstr);
4535 break;
4536 #endif
4537 #ifdef HAVE_TARGET_64_BIG
4538 case Parameters::TARGET_64_BIG:
4539 this->sized_create_version_sections<64, true>(versions, symtab,
4540 local_symcount,
4541 dynamic_symbols, dynstr);
4542 break;
4543 #endif
4544 default:
4545 gold_unreachable();
4546 }
4547 }
4548
4549 // Create the version sections, sized version.
4550
4551 template<int size, bool big_endian>
4552 void
sized_create_version_sections(const Versions * versions,const Symbol_table * symtab,unsigned int local_symcount,const std::vector<Symbol * > & dynamic_symbols,const Output_section * dynstr)4553 Layout::sized_create_version_sections(
4554 const Versions* versions,
4555 const Symbol_table* symtab,
4556 unsigned int local_symcount,
4557 const std::vector<Symbol*>& dynamic_symbols,
4558 const Output_section* dynstr)
4559 {
4560 Output_section* vsec = this->choose_output_section(NULL, ".gnu.version",
4561 elfcpp::SHT_GNU_versym,
4562 elfcpp::SHF_ALLOC,
4563 false,
4564 ORDER_DYNAMIC_LINKER,
4565 false);
4566
4567 // Check for NULL since a linker script may discard this section.
4568 if (vsec != NULL)
4569 {
4570 unsigned char* vbuf;
4571 unsigned int vsize;
4572 versions->symbol_section_contents<size, big_endian>(symtab,
4573 &this->dynpool_,
4574 local_symcount,
4575 dynamic_symbols,
4576 &vbuf, &vsize);
4577
4578 Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2,
4579 "** versions");
4580
4581 vsec->add_output_section_data(vdata);
4582 vsec->set_entsize(2);
4583 vsec->set_link_section(this->dynsym_section_);
4584 }
4585
4586 Output_data_dynamic* const odyn = this->dynamic_data_;
4587 if (odyn != NULL && vsec != NULL)
4588 odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
4589
4590 if (versions->any_defs())
4591 {
4592 Output_section* vdsec;
4593 vdsec = this->choose_output_section(NULL, ".gnu.version_d",
4594 elfcpp::SHT_GNU_verdef,
4595 elfcpp::SHF_ALLOC,
4596 false, ORDER_DYNAMIC_LINKER, false);
4597
4598 if (vdsec != NULL)
4599 {
4600 unsigned char* vdbuf;
4601 unsigned int vdsize;
4602 unsigned int vdentries;
4603 versions->def_section_contents<size, big_endian>(&this->dynpool_,
4604 &vdbuf, &vdsize,
4605 &vdentries);
4606
4607 Output_section_data* vddata =
4608 new Output_data_const_buffer(vdbuf, vdsize, 4, "** version defs");
4609
4610 vdsec->add_output_section_data(vddata);
4611 vdsec->set_link_section(dynstr);
4612 vdsec->set_info(vdentries);
4613
4614 if (odyn != NULL)
4615 {
4616 odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
4617 odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
4618 }
4619 }
4620 }
4621
4622 if (versions->any_needs())
4623 {
4624 Output_section* vnsec;
4625 vnsec = this->choose_output_section(NULL, ".gnu.version_r",
4626 elfcpp::SHT_GNU_verneed,
4627 elfcpp::SHF_ALLOC,
4628 false, ORDER_DYNAMIC_LINKER, false);
4629
4630 if (vnsec != NULL)
4631 {
4632 unsigned char* vnbuf;
4633 unsigned int vnsize;
4634 unsigned int vnentries;
4635 versions->need_section_contents<size, big_endian>(&this->dynpool_,
4636 &vnbuf, &vnsize,
4637 &vnentries);
4638
4639 Output_section_data* vndata =
4640 new Output_data_const_buffer(vnbuf, vnsize, 4, "** version refs");
4641
4642 vnsec->add_output_section_data(vndata);
4643 vnsec->set_link_section(dynstr);
4644 vnsec->set_info(vnentries);
4645
4646 if (odyn != NULL)
4647 {
4648 odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
4649 odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
4650 }
4651 }
4652 }
4653 }
4654
4655 // Create the .interp section and PT_INTERP segment.
4656
4657 void
create_interp(const Target * target)4658 Layout::create_interp(const Target* target)
4659 {
4660 gold_assert(this->interp_segment_ == NULL);
4661
4662 const char* interp = parameters->options().dynamic_linker();
4663 if (interp == NULL)
4664 {
4665 interp = target->dynamic_linker();
4666 gold_assert(interp != NULL);
4667 }
4668
4669 size_t len = strlen(interp) + 1;
4670
4671 Output_section_data* odata = new Output_data_const(interp, len, 1);
4672
4673 Output_section* osec = this->choose_output_section(NULL, ".interp",
4674 elfcpp::SHT_PROGBITS,
4675 elfcpp::SHF_ALLOC,
4676 false, ORDER_INTERP,
4677 false);
4678 if (osec != NULL)
4679 osec->add_output_section_data(odata);
4680 }
4681
4682 // Add dynamic tags for the PLT and the dynamic relocs. This is
4683 // called by the target-specific code. This does nothing if not doing
4684 // a dynamic link.
4685
4686 // USE_REL is true for REL relocs rather than RELA relocs.
4687
4688 // If PLT_GOT is not NULL, then DT_PLTGOT points to it.
4689
4690 // If PLT_REL is not NULL, it is used for DT_PLTRELSZ, and DT_JMPREL,
4691 // and we also set DT_PLTREL. We use PLT_REL's output section, since
4692 // some targets have multiple reloc sections in PLT_REL.
4693
4694 // If DYN_REL is not NULL, it is used for DT_REL/DT_RELA,
4695 // DT_RELSZ/DT_RELASZ, DT_RELENT/DT_RELAENT. Again we use the output
4696 // section.
4697
4698 // If ADD_DEBUG is true, we add a DT_DEBUG entry when generating an
4699 // executable.
4700
4701 void
add_target_dynamic_tags(bool use_rel,const Output_data * plt_got,const Output_data * plt_rel,const Output_data_reloc_generic * dyn_rel,bool add_debug,bool dynrel_includes_plt)4702 Layout::add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
4703 const Output_data* plt_rel,
4704 const Output_data_reloc_generic* dyn_rel,
4705 bool add_debug, bool dynrel_includes_plt)
4706 {
4707 Output_data_dynamic* odyn = this->dynamic_data_;
4708 if (odyn == NULL)
4709 return;
4710
4711 if (plt_got != NULL && plt_got->output_section() != NULL)
4712 odyn->add_section_address(elfcpp::DT_PLTGOT, plt_got);
4713
4714 if (plt_rel != NULL && plt_rel->output_section() != NULL)
4715 {
4716 odyn->add_section_size(elfcpp::DT_PLTRELSZ, plt_rel->output_section());
4717 odyn->add_section_address(elfcpp::DT_JMPREL, plt_rel->output_section());
4718 odyn->add_constant(elfcpp::DT_PLTREL,
4719 use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA);
4720 }
4721
4722 if ((dyn_rel != NULL && dyn_rel->output_section() != NULL)
4723 || (dynrel_includes_plt
4724 && plt_rel != NULL
4725 && plt_rel->output_section() != NULL))
4726 {
4727 bool have_dyn_rel = dyn_rel != NULL && dyn_rel->output_section() != NULL;
4728 bool have_plt_rel = plt_rel != NULL && plt_rel->output_section() != NULL;
4729 odyn->add_section_address(use_rel ? elfcpp::DT_REL : elfcpp::DT_RELA,
4730 (have_dyn_rel
4731 ? dyn_rel->output_section()
4732 : plt_rel->output_section()));
4733 elfcpp::DT size_tag = use_rel ? elfcpp::DT_RELSZ : elfcpp::DT_RELASZ;
4734 if (have_dyn_rel && have_plt_rel && dynrel_includes_plt)
4735 odyn->add_section_size(size_tag,
4736 dyn_rel->output_section(),
4737 plt_rel->output_section());
4738 else if (have_dyn_rel)
4739 odyn->add_section_size(size_tag, dyn_rel->output_section());
4740 else
4741 odyn->add_section_size(size_tag, plt_rel->output_section());
4742 const int size = parameters->target().get_size();
4743 elfcpp::DT rel_tag;
4744 int rel_size;
4745 if (use_rel)
4746 {
4747 rel_tag = elfcpp::DT_RELENT;
4748 if (size == 32)
4749 rel_size = Reloc_types<elfcpp::SHT_REL, 32, false>::reloc_size;
4750 else if (size == 64)
4751 rel_size = Reloc_types<elfcpp::SHT_REL, 64, false>::reloc_size;
4752 else
4753 gold_unreachable();
4754 }
4755 else
4756 {
4757 rel_tag = elfcpp::DT_RELAENT;
4758 if (size == 32)
4759 rel_size = Reloc_types<elfcpp::SHT_RELA, 32, false>::reloc_size;
4760 else if (size == 64)
4761 rel_size = Reloc_types<elfcpp::SHT_RELA, 64, false>::reloc_size;
4762 else
4763 gold_unreachable();
4764 }
4765 odyn->add_constant(rel_tag, rel_size);
4766
4767 if (parameters->options().combreloc() && have_dyn_rel)
4768 {
4769 size_t c = dyn_rel->relative_reloc_count();
4770 if (c > 0)
4771 odyn->add_constant((use_rel
4772 ? elfcpp::DT_RELCOUNT
4773 : elfcpp::DT_RELACOUNT),
4774 c);
4775 }
4776 }
4777
4778 if (add_debug && !parameters->options().shared())
4779 {
4780 // The value of the DT_DEBUG tag is filled in by the dynamic
4781 // linker at run time, and used by the debugger.
4782 odyn->add_constant(elfcpp::DT_DEBUG, 0);
4783 }
4784 }
4785
4786 // Finish the .dynamic section and PT_DYNAMIC segment.
4787
4788 void
finish_dynamic_section(const Input_objects * input_objects,const Symbol_table * symtab)4789 Layout::finish_dynamic_section(const Input_objects* input_objects,
4790 const Symbol_table* symtab)
4791 {
4792 if (!this->script_options_->saw_phdrs_clause()
4793 && this->dynamic_section_ != NULL)
4794 {
4795 Output_segment* oseg = this->make_output_segment(elfcpp::PT_DYNAMIC,
4796 (elfcpp::PF_R
4797 | elfcpp::PF_W));
4798 oseg->add_output_section_to_nonload(this->dynamic_section_,
4799 elfcpp::PF_R | elfcpp::PF_W);
4800 }
4801
4802 Output_data_dynamic* const odyn = this->dynamic_data_;
4803 if (odyn == NULL)
4804 return;
4805
4806 for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
4807 p != input_objects->dynobj_end();
4808 ++p)
4809 {
4810 if (!(*p)->is_needed() && (*p)->as_needed())
4811 {
4812 // This dynamic object was linked with --as-needed, but it
4813 // is not needed.
4814 continue;
4815 }
4816
4817 odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
4818 }
4819
4820 if (parameters->options().shared())
4821 {
4822 const char* soname = parameters->options().soname();
4823 if (soname != NULL)
4824 odyn->add_string(elfcpp::DT_SONAME, soname);
4825 }
4826
4827 Symbol* sym = symtab->lookup(parameters->options().init());
4828 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
4829 odyn->add_symbol(elfcpp::DT_INIT, sym);
4830
4831 sym = symtab->lookup(parameters->options().fini());
4832 if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
4833 odyn->add_symbol(elfcpp::DT_FINI, sym);
4834
4835 // Look for .init_array, .preinit_array and .fini_array by checking
4836 // section types.
4837 for(Layout::Section_list::const_iterator p = this->section_list_.begin();
4838 p != this->section_list_.end();
4839 ++p)
4840 switch((*p)->type())
4841 {
4842 case elfcpp::SHT_FINI_ARRAY:
4843 odyn->add_section_address(elfcpp::DT_FINI_ARRAY, *p);
4844 odyn->add_section_size(elfcpp::DT_FINI_ARRAYSZ, *p);
4845 break;
4846 case elfcpp::SHT_INIT_ARRAY:
4847 odyn->add_section_address(elfcpp::DT_INIT_ARRAY, *p);
4848 odyn->add_section_size(elfcpp::DT_INIT_ARRAYSZ, *p);
4849 break;
4850 case elfcpp::SHT_PREINIT_ARRAY:
4851 odyn->add_section_address(elfcpp::DT_PREINIT_ARRAY, *p);
4852 odyn->add_section_size(elfcpp::DT_PREINIT_ARRAYSZ, *p);
4853 break;
4854 default:
4855 break;
4856 }
4857
4858 // Add a DT_RPATH entry if needed.
4859 const General_options::Dir_list& rpath(parameters->options().rpath());
4860 if (!rpath.empty())
4861 {
4862 std::string rpath_val;
4863 for (General_options::Dir_list::const_iterator p = rpath.begin();
4864 p != rpath.end();
4865 ++p)
4866 {
4867 if (rpath_val.empty())
4868 rpath_val = p->name();
4869 else
4870 {
4871 // Eliminate duplicates.
4872 General_options::Dir_list::const_iterator q;
4873 for (q = rpath.begin(); q != p; ++q)
4874 if (q->name() == p->name())
4875 break;
4876 if (q == p)
4877 {
4878 rpath_val += ':';
4879 rpath_val += p->name();
4880 }
4881 }
4882 }
4883
4884 if (!parameters->options().enable_new_dtags())
4885 odyn->add_string(elfcpp::DT_RPATH, rpath_val);
4886 else
4887 odyn->add_string(elfcpp::DT_RUNPATH, rpath_val);
4888 }
4889
4890 // Look for text segments that have dynamic relocations.
4891 bool have_textrel = false;
4892 if (!this->script_options_->saw_sections_clause())
4893 {
4894 for (Segment_list::const_iterator p = this->segment_list_.begin();
4895 p != this->segment_list_.end();
4896 ++p)
4897 {
4898 if ((*p)->type() == elfcpp::PT_LOAD
4899 && ((*p)->flags() & elfcpp::PF_W) == 0
4900 && (*p)->has_dynamic_reloc())
4901 {
4902 have_textrel = true;
4903 break;
4904 }
4905 }
4906 }
4907 else
4908 {
4909 // We don't know the section -> segment mapping, so we are
4910 // conservative and just look for readonly sections with
4911 // relocations. If those sections wind up in writable segments,
4912 // then we have created an unnecessary DT_TEXTREL entry.
4913 for (Section_list::const_iterator p = this->section_list_.begin();
4914 p != this->section_list_.end();
4915 ++p)
4916 {
4917 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0
4918 && ((*p)->flags() & elfcpp::SHF_WRITE) == 0
4919 && (*p)->has_dynamic_reloc())
4920 {
4921 have_textrel = true;
4922 break;
4923 }
4924 }
4925 }
4926
4927 if (parameters->options().filter() != NULL)
4928 odyn->add_string(elfcpp::DT_FILTER, parameters->options().filter());
4929 if (parameters->options().any_auxiliary())
4930 {
4931 for (options::String_set::const_iterator p =
4932 parameters->options().auxiliary_begin();
4933 p != parameters->options().auxiliary_end();
4934 ++p)
4935 odyn->add_string(elfcpp::DT_AUXILIARY, *p);
4936 }
4937
4938 // Add a DT_FLAGS entry if necessary.
4939 unsigned int flags = 0;
4940 if (have_textrel)
4941 {
4942 // Add a DT_TEXTREL for compatibility with older loaders.
4943 odyn->add_constant(elfcpp::DT_TEXTREL, 0);
4944 flags |= elfcpp::DF_TEXTREL;
4945
4946 if (parameters->options().text())
4947 gold_error(_("read-only segment has dynamic relocations"));
4948 else if (parameters->options().warn_shared_textrel()
4949 && parameters->options().shared())
4950 gold_warning(_("shared library text segment is not shareable"));
4951 }
4952 if (parameters->options().shared() && this->has_static_tls())
4953 flags |= elfcpp::DF_STATIC_TLS;
4954 if (parameters->options().origin())
4955 flags |= elfcpp::DF_ORIGIN;
4956 if (parameters->options().Bsymbolic()
4957 && !parameters->options().have_dynamic_list())
4958 {
4959 flags |= elfcpp::DF_SYMBOLIC;
4960 // Add DT_SYMBOLIC for compatibility with older loaders.
4961 odyn->add_constant(elfcpp::DT_SYMBOLIC, 0);
4962 }
4963 if (parameters->options().now())
4964 flags |= elfcpp::DF_BIND_NOW;
4965 if (flags != 0)
4966 odyn->add_constant(elfcpp::DT_FLAGS, flags);
4967
4968 flags = 0;
4969 if (parameters->options().global())
4970 flags |= elfcpp::DF_1_GLOBAL;
4971 if (parameters->options().initfirst())
4972 flags |= elfcpp::DF_1_INITFIRST;
4973 if (parameters->options().interpose())
4974 flags |= elfcpp::DF_1_INTERPOSE;
4975 if (parameters->options().loadfltr())
4976 flags |= elfcpp::DF_1_LOADFLTR;
4977 if (parameters->options().nodefaultlib())
4978 flags |= elfcpp::DF_1_NODEFLIB;
4979 if (parameters->options().nodelete())
4980 flags |= elfcpp::DF_1_NODELETE;
4981 if (parameters->options().nodlopen())
4982 flags |= elfcpp::DF_1_NOOPEN;
4983 if (parameters->options().nodump())
4984 flags |= elfcpp::DF_1_NODUMP;
4985 if (!parameters->options().shared())
4986 flags &= ~(elfcpp::DF_1_INITFIRST
4987 | elfcpp::DF_1_NODELETE
4988 | elfcpp::DF_1_NOOPEN);
4989 if (parameters->options().origin())
4990 flags |= elfcpp::DF_1_ORIGIN;
4991 if (parameters->options().now())
4992 flags |= elfcpp::DF_1_NOW;
4993 if (parameters->options().Bgroup())
4994 flags |= elfcpp::DF_1_GROUP;
4995 if (flags != 0)
4996 odyn->add_constant(elfcpp::DT_FLAGS_1, flags);
4997 }
4998
4999 // Set the size of the _DYNAMIC symbol table to be the size of the
5000 // dynamic data.
5001
5002 void
set_dynamic_symbol_size(const Symbol_table * symtab)5003 Layout::set_dynamic_symbol_size(const Symbol_table* symtab)
5004 {
5005 Output_data_dynamic* const odyn = this->dynamic_data_;
5006 if (odyn == NULL)
5007 return;
5008 odyn->finalize_data_size();
5009 if (this->dynamic_symbol_ == NULL)
5010 return;
5011 off_t data_size = odyn->data_size();
5012 const int size = parameters->target().get_size();
5013 if (size == 32)
5014 symtab->get_sized_symbol<32>(this->dynamic_symbol_)->set_symsize(data_size);
5015 else if (size == 64)
5016 symtab->get_sized_symbol<64>(this->dynamic_symbol_)->set_symsize(data_size);
5017 else
5018 gold_unreachable();
5019 }
5020
5021 // The mapping of input section name prefixes to output section names.
5022 // In some cases one prefix is itself a prefix of another prefix; in
5023 // such a case the longer prefix must come first. These prefixes are
5024 // based on the GNU linker default ELF linker script.
5025
5026 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
5027 #define MAPPING_INIT_EXACT(f, t) { f, 0, t, sizeof(t) - 1 }
5028 const Layout::Section_name_mapping Layout::section_name_mapping[] =
5029 {
5030 MAPPING_INIT(".text.", ".text"),
5031 MAPPING_INIT(".rodata.", ".rodata"),
5032 MAPPING_INIT(".data.rel.ro.local.", ".data.rel.ro.local"),
5033 MAPPING_INIT_EXACT(".data.rel.ro.local", ".data.rel.ro.local"),
5034 MAPPING_INIT(".data.rel.ro.", ".data.rel.ro"),
5035 MAPPING_INIT_EXACT(".data.rel.ro", ".data.rel.ro"),
5036 MAPPING_INIT(".data.", ".data"),
5037 MAPPING_INIT(".bss.", ".bss"),
5038 MAPPING_INIT(".tdata.", ".tdata"),
5039 MAPPING_INIT(".tbss.", ".tbss"),
5040 MAPPING_INIT(".init_array.", ".init_array"),
5041 MAPPING_INIT(".fini_array.", ".fini_array"),
5042 MAPPING_INIT(".sdata.", ".sdata"),
5043 MAPPING_INIT(".sbss.", ".sbss"),
5044 // FIXME: In the GNU linker, .sbss2 and .sdata2 are handled
5045 // differently depending on whether it is creating a shared library.
5046 MAPPING_INIT(".sdata2.", ".sdata"),
5047 MAPPING_INIT(".sbss2.", ".sbss"),
5048 MAPPING_INIT(".lrodata.", ".lrodata"),
5049 MAPPING_INIT(".ldata.", ".ldata"),
5050 MAPPING_INIT(".lbss.", ".lbss"),
5051 MAPPING_INIT(".gcc_except_table.", ".gcc_except_table"),
5052 MAPPING_INIT(".gnu.linkonce.d.rel.ro.local.", ".data.rel.ro.local"),
5053 MAPPING_INIT(".gnu.linkonce.d.rel.ro.", ".data.rel.ro"),
5054 MAPPING_INIT(".gnu.linkonce.t.", ".text"),
5055 MAPPING_INIT(".gnu.linkonce.r.", ".rodata"),
5056 MAPPING_INIT(".gnu.linkonce.d.", ".data"),
5057 MAPPING_INIT(".gnu.linkonce.b.", ".bss"),
5058 MAPPING_INIT(".gnu.linkonce.s.", ".sdata"),
5059 MAPPING_INIT(".gnu.linkonce.sb.", ".sbss"),
5060 MAPPING_INIT(".gnu.linkonce.s2.", ".sdata"),
5061 MAPPING_INIT(".gnu.linkonce.sb2.", ".sbss"),
5062 MAPPING_INIT(".gnu.linkonce.wi.", ".debug_info"),
5063 MAPPING_INIT(".gnu.linkonce.td.", ".tdata"),
5064 MAPPING_INIT(".gnu.linkonce.tb.", ".tbss"),
5065 MAPPING_INIT(".gnu.linkonce.lr.", ".lrodata"),
5066 MAPPING_INIT(".gnu.linkonce.l.", ".ldata"),
5067 MAPPING_INIT(".gnu.linkonce.lb.", ".lbss"),
5068 MAPPING_INIT(".ARM.extab", ".ARM.extab"),
5069 MAPPING_INIT(".gnu.linkonce.armextab.", ".ARM.extab"),
5070 MAPPING_INIT(".ARM.exidx", ".ARM.exidx"),
5071 MAPPING_INIT(".gnu.linkonce.armexidx.", ".ARM.exidx"),
5072 MAPPING_INIT("_function_patch_prologue.", "_function_patch_prologue"),
5073 MAPPING_INIT("_function_patch_epilogue.", "_function_patch_epilogue"),
5074 };
5075 #undef MAPPING_INIT
5076 #undef MAPPING_INIT_EXACT
5077
5078 const int Layout::section_name_mapping_count =
5079 (sizeof(Layout::section_name_mapping)
5080 / sizeof(Layout::section_name_mapping[0]));
5081
5082 // Choose the output section name to use given an input section name.
5083 // Set *PLEN to the length of the name. *PLEN is initialized to the
5084 // length of NAME.
5085
5086 const char*
output_section_name(const Relobj * relobj,const char * name,size_t * plen)5087 Layout::output_section_name(const Relobj* relobj, const char* name,
5088 size_t* plen)
5089 {
5090 // gcc 4.3 generates the following sorts of section names when it
5091 // needs a section name specific to a function:
5092 // .text.FN
5093 // .rodata.FN
5094 // .sdata2.FN
5095 // .data.FN
5096 // .data.rel.FN
5097 // .data.rel.local.FN
5098 // .data.rel.ro.FN
5099 // .data.rel.ro.local.FN
5100 // .sdata.FN
5101 // .bss.FN
5102 // .sbss.FN
5103 // .tdata.FN
5104 // .tbss.FN
5105
5106 // The GNU linker maps all of those to the part before the .FN,
5107 // except that .data.rel.local.FN is mapped to .data, and
5108 // .data.rel.ro.local.FN is mapped to .data.rel.ro. The sections
5109 // beginning with .data.rel.ro.local are grouped together.
5110
5111 // For an anonymous namespace, the string FN can contain a '.'.
5112
5113 // Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
5114 // GNU linker maps to .rodata.
5115
5116 // The .data.rel.ro sections are used with -z relro. The sections
5117 // are recognized by name. We use the same names that the GNU
5118 // linker does for these sections.
5119
5120 // It is hard to handle this in a principled way, so we don't even
5121 // try. We use a table of mappings. If the input section name is
5122 // not found in the table, we simply use it as the output section
5123 // name.
5124
5125 const Section_name_mapping* psnm = section_name_mapping;
5126 for (int i = 0; i < section_name_mapping_count; ++i, ++psnm)
5127 {
5128 if (psnm->fromlen > 0)
5129 {
5130 if (strncmp(name, psnm->from, psnm->fromlen) == 0)
5131 {
5132 *plen = psnm->tolen;
5133 return psnm->to;
5134 }
5135 }
5136 else
5137 {
5138 if (strcmp(name, psnm->from) == 0)
5139 {
5140 *plen = psnm->tolen;
5141 return psnm->to;
5142 }
5143 }
5144 }
5145
5146 // As an additional complication, .ctors sections are output in
5147 // either .ctors or .init_array sections, and .dtors sections are
5148 // output in either .dtors or .fini_array sections.
5149 if (is_prefix_of(".ctors.", name) || is_prefix_of(".dtors.", name))
5150 {
5151 if (parameters->options().ctors_in_init_array())
5152 {
5153 *plen = 11;
5154 return name[1] == 'c' ? ".init_array" : ".fini_array";
5155 }
5156 else
5157 {
5158 *plen = 6;
5159 return name[1] == 'c' ? ".ctors" : ".dtors";
5160 }
5161 }
5162 if (parameters->options().ctors_in_init_array()
5163 && (strcmp(name, ".ctors") == 0 || strcmp(name, ".dtors") == 0))
5164 {
5165 // To make .init_array/.fini_array work with gcc we must exclude
5166 // .ctors and .dtors sections from the crtbegin and crtend
5167 // files.
5168 if (relobj == NULL
5169 || (!Layout::match_file_name(relobj, "crtbegin")
5170 && !Layout::match_file_name(relobj, "crtend")))
5171 {
5172 *plen = 11;
5173 return name[1] == 'c' ? ".init_array" : ".fini_array";
5174 }
5175 }
5176
5177 return name;
5178 }
5179
5180 // Return true if RELOBJ is an input file whose base name matches
5181 // FILE_NAME. The base name must have an extension of ".o", and must
5182 // be exactly FILE_NAME.o or FILE_NAME, one character, ".o". This is
5183 // to match crtbegin.o as well as crtbeginS.o without getting confused
5184 // by other possibilities. Overall matching the file name this way is
5185 // a dreadful hack, but the GNU linker does it in order to better
5186 // support gcc, and we need to be compatible.
5187
5188 bool
match_file_name(const Relobj * relobj,const char * match)5189 Layout::match_file_name(const Relobj* relobj, const char* match)
5190 {
5191 const std::string& file_name(relobj->name());
5192 const char* base_name = lbasename(file_name.c_str());
5193 size_t match_len = strlen(match);
5194 if (strncmp(base_name, match, match_len) != 0)
5195 return false;
5196 size_t base_len = strlen(base_name);
5197 if (base_len != match_len + 2 && base_len != match_len + 3)
5198 return false;
5199 return memcmp(base_name + base_len - 2, ".o", 2) == 0;
5200 }
5201
5202 // Check if a comdat group or .gnu.linkonce section with the given
5203 // NAME is selected for the link. If there is already a section,
5204 // *KEPT_SECTION is set to point to the existing section and the
5205 // function returns false. Otherwise, OBJECT, SHNDX, IS_COMDAT, and
5206 // IS_GROUP_NAME are recorded for this NAME in the layout object,
5207 // *KEPT_SECTION is set to the internal copy and the function returns
5208 // true.
5209
5210 bool
find_or_add_kept_section(const std::string & name,Relobj * object,unsigned int shndx,bool is_comdat,bool is_group_name,Kept_section ** kept_section)5211 Layout::find_or_add_kept_section(const std::string& name,
5212 Relobj* object,
5213 unsigned int shndx,
5214 bool is_comdat,
5215 bool is_group_name,
5216 Kept_section** kept_section)
5217 {
5218 // It's normal to see a couple of entries here, for the x86 thunk
5219 // sections. If we see more than a few, we're linking a C++
5220 // program, and we resize to get more space to minimize rehashing.
5221 if (this->signatures_.size() > 4
5222 && !this->resized_signatures_)
5223 {
5224 reserve_unordered_map(&this->signatures_,
5225 this->number_of_input_files_ * 64);
5226 this->resized_signatures_ = true;
5227 }
5228
5229 Kept_section candidate;
5230 std::pair<Signatures::iterator, bool> ins =
5231 this->signatures_.insert(std::make_pair(name, candidate));
5232
5233 if (kept_section != NULL)
5234 *kept_section = &ins.first->second;
5235 if (ins.second)
5236 {
5237 // This is the first time we've seen this signature.
5238 ins.first->second.set_object(object);
5239 ins.first->second.set_shndx(shndx);
5240 if (is_comdat)
5241 ins.first->second.set_is_comdat();
5242 if (is_group_name)
5243 ins.first->second.set_is_group_name();
5244 return true;
5245 }
5246
5247 // We have already seen this signature.
5248
5249 if (ins.first->second.is_group_name())
5250 {
5251 // We've already seen a real section group with this signature.
5252 // If the kept group is from a plugin object, and we're in the
5253 // replacement phase, accept the new one as a replacement.
5254 if (ins.first->second.object() == NULL
5255 && parameters->options().plugins()->in_replacement_phase())
5256 {
5257 ins.first->second.set_object(object);
5258 ins.first->second.set_shndx(shndx);
5259 return true;
5260 }
5261 return false;
5262 }
5263 else if (is_group_name)
5264 {
5265 // This is a real section group, and we've already seen a
5266 // linkonce section with this signature. Record that we've seen
5267 // a section group, and don't include this section group.
5268 ins.first->second.set_is_group_name();
5269 return false;
5270 }
5271 else
5272 {
5273 // We've already seen a linkonce section and this is a linkonce
5274 // section. These don't block each other--this may be the same
5275 // symbol name with different section types.
5276 return true;
5277 }
5278 }
5279
5280 // Store the allocated sections into the section list.
5281
5282 void
get_allocated_sections(Section_list * section_list) const5283 Layout::get_allocated_sections(Section_list* section_list) const
5284 {
5285 for (Section_list::const_iterator p = this->section_list_.begin();
5286 p != this->section_list_.end();
5287 ++p)
5288 if (((*p)->flags() & elfcpp::SHF_ALLOC) != 0)
5289 section_list->push_back(*p);
5290 }
5291
5292 // Store the executable sections into the section list.
5293
5294 void
get_executable_sections(Section_list * section_list) const5295 Layout::get_executable_sections(Section_list* section_list) const
5296 {
5297 for (Section_list::const_iterator p = this->section_list_.begin();
5298 p != this->section_list_.end();
5299 ++p)
5300 if (((*p)->flags() & (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
5301 == (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
5302 section_list->push_back(*p);
5303 }
5304
5305 // Create an output segment.
5306
5307 Output_segment*
make_output_segment(elfcpp::Elf_Word type,elfcpp::Elf_Word flags)5308 Layout::make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags)
5309 {
5310 gold_assert(!parameters->options().relocatable());
5311 Output_segment* oseg = new Output_segment(type, flags);
5312 this->segment_list_.push_back(oseg);
5313
5314 if (type == elfcpp::PT_TLS)
5315 this->tls_segment_ = oseg;
5316 else if (type == elfcpp::PT_GNU_RELRO)
5317 this->relro_segment_ = oseg;
5318 else if (type == elfcpp::PT_INTERP)
5319 this->interp_segment_ = oseg;
5320
5321 return oseg;
5322 }
5323
5324 // Return the file offset of the normal symbol table.
5325
5326 off_t
symtab_section_offset() const5327 Layout::symtab_section_offset() const
5328 {
5329 if (this->symtab_section_ != NULL)
5330 return this->symtab_section_->offset();
5331 return 0;
5332 }
5333
5334 // Return the section index of the normal symbol table. It may have
5335 // been stripped by the -s/--strip-all option.
5336
5337 unsigned int
symtab_section_shndx() const5338 Layout::symtab_section_shndx() const
5339 {
5340 if (this->symtab_section_ != NULL)
5341 return this->symtab_section_->out_shndx();
5342 return 0;
5343 }
5344
5345 // Write out the Output_sections. Most won't have anything to write,
5346 // since most of the data will come from input sections which are
5347 // handled elsewhere. But some Output_sections do have Output_data.
5348
5349 void
write_output_sections(Output_file * of) const5350 Layout::write_output_sections(Output_file* of) const
5351 {
5352 for (Section_list::const_iterator p = this->section_list_.begin();
5353 p != this->section_list_.end();
5354 ++p)
5355 {
5356 if (!(*p)->after_input_sections())
5357 (*p)->write(of);
5358 }
5359 }
5360
5361 // Write out data not associated with a section or the symbol table.
5362
5363 void
write_data(const Symbol_table * symtab,Output_file * of) const5364 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
5365 {
5366 if (!parameters->options().strip_all())
5367 {
5368 const Output_section* symtab_section = this->symtab_section_;
5369 for (Section_list::const_iterator p = this->section_list_.begin();
5370 p != this->section_list_.end();
5371 ++p)
5372 {
5373 if ((*p)->needs_symtab_index())
5374 {
5375 gold_assert(symtab_section != NULL);
5376 unsigned int index = (*p)->symtab_index();
5377 gold_assert(index > 0 && index != -1U);
5378 off_t off = (symtab_section->offset()
5379 + index * symtab_section->entsize());
5380 symtab->write_section_symbol(*p, this->symtab_xindex_, of, off);
5381 }
5382 }
5383 }
5384
5385 const Output_section* dynsym_section = this->dynsym_section_;
5386 for (Section_list::const_iterator p = this->section_list_.begin();
5387 p != this->section_list_.end();
5388 ++p)
5389 {
5390 if ((*p)->needs_dynsym_index())
5391 {
5392 gold_assert(dynsym_section != NULL);
5393 unsigned int index = (*p)->dynsym_index();
5394 gold_assert(index > 0 && index != -1U);
5395 off_t off = (dynsym_section->offset()
5396 + index * dynsym_section->entsize());
5397 symtab->write_section_symbol(*p, this->dynsym_xindex_, of, off);
5398 }
5399 }
5400
5401 // Write out the Output_data which are not in an Output_section.
5402 for (Data_list::const_iterator p = this->special_output_list_.begin();
5403 p != this->special_output_list_.end();
5404 ++p)
5405 (*p)->write(of);
5406
5407 // Write out the Output_data which are not in an Output_section
5408 // and are regenerated in each iteration of relaxation.
5409 for (Data_list::const_iterator p = this->relax_output_list_.begin();
5410 p != this->relax_output_list_.end();
5411 ++p)
5412 (*p)->write(of);
5413 }
5414
5415 // Write out the Output_sections which can only be written after the
5416 // input sections are complete.
5417
5418 void
write_sections_after_input_sections(Output_file * of)5419 Layout::write_sections_after_input_sections(Output_file* of)
5420 {
5421 // Determine the final section offsets, and thus the final output
5422 // file size. Note we finalize the .shstrab last, to allow the
5423 // after_input_section sections to modify their section-names before
5424 // writing.
5425 if (this->any_postprocessing_sections_)
5426 {
5427 off_t off = this->output_file_size_;
5428 off = this->set_section_offsets(off, POSTPROCESSING_SECTIONS_PASS);
5429
5430 // Now that we've finalized the names, we can finalize the shstrab.
5431 off =
5432 this->set_section_offsets(off,
5433 STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS);
5434
5435 if (off > this->output_file_size_)
5436 {
5437 of->resize(off);
5438 this->output_file_size_ = off;
5439 }
5440 }
5441
5442 for (Section_list::const_iterator p = this->section_list_.begin();
5443 p != this->section_list_.end();
5444 ++p)
5445 {
5446 if ((*p)->after_input_sections())
5447 (*p)->write(of);
5448 }
5449
5450 this->section_headers_->write(of);
5451 }
5452
5453 // Build IDs can be computed as a "flat" sha1 or md5 of a string of bytes,
5454 // or as a "tree" where each chunk of the string is hashed and then those
5455 // hashes are put into a (much smaller) string which is hashed with sha1.
5456 // We compute a checksum over the entire file because that is simplest.
5457
5458 Task_token*
queue_build_id_tasks(Workqueue * workqueue,Task_token * build_id_blocker,Output_file * of)5459 Layout::queue_build_id_tasks(Workqueue* workqueue, Task_token* build_id_blocker,
5460 Output_file* of)
5461 {
5462 const size_t filesize = (this->output_file_size() <= 0 ? 0
5463 : static_cast<size_t>(this->output_file_size()));
5464 if (this->build_id_note_ != NULL
5465 && strcmp(parameters->options().build_id(), "tree") == 0
5466 && parameters->options().build_id_chunk_size_for_treehash() > 0
5467 && filesize > 0
5468 && (filesize >=
5469 parameters->options().build_id_min_file_size_for_treehash()))
5470 {
5471 static const size_t MD5_OUTPUT_SIZE_IN_BYTES = 16;
5472 const size_t chunk_size =
5473 parameters->options().build_id_chunk_size_for_treehash();
5474 const size_t num_hashes = ((filesize - 1) / chunk_size) + 1;
5475 Task_token* post_hash_tasks_blocker = new Task_token(true);
5476 post_hash_tasks_blocker->add_blockers(num_hashes);
5477 this->size_of_array_of_hashes_ = num_hashes * MD5_OUTPUT_SIZE_IN_BYTES;
5478 const unsigned char* src = of->get_input_view(0, filesize);
5479 this->input_view_ = src;
5480 unsigned char *dst = new unsigned char[this->size_of_array_of_hashes_];
5481 this->array_of_hashes_ = dst;
5482 for (size_t i = 0, src_offset = 0; i < num_hashes;
5483 i++, dst += MD5_OUTPUT_SIZE_IN_BYTES, src_offset += chunk_size)
5484 {
5485 size_t size = std::min(chunk_size, filesize - src_offset);
5486 workqueue->queue(new Hash_task(src + src_offset,
5487 size,
5488 dst,
5489 build_id_blocker,
5490 post_hash_tasks_blocker));
5491 }
5492 return post_hash_tasks_blocker;
5493 }
5494 return build_id_blocker;
5495 }
5496
5497 // If a tree-style build ID was requested, the parallel part of that computation
5498 // is already done, and the final hash-of-hashes is computed here. For other
5499 // types of build IDs, all the work is done here.
5500
5501 void
write_build_id(Output_file * of) const5502 Layout::write_build_id(Output_file* of) const
5503 {
5504 if (this->build_id_note_ == NULL)
5505 return;
5506
5507 unsigned char* ov = of->get_output_view(this->build_id_note_->offset(),
5508 this->build_id_note_->data_size());
5509
5510 if (this->array_of_hashes_ == NULL)
5511 {
5512 const size_t output_file_size = this->output_file_size();
5513 const unsigned char* iv = of->get_input_view(0, output_file_size);
5514 const char* style = parameters->options().build_id();
5515
5516 // If we get here with style == "tree" then the output must be
5517 // too small for chunking, and we use SHA-1 in that case.
5518 if ((strcmp(style, "sha1") == 0) || (strcmp(style, "tree") == 0))
5519 sha1_buffer(reinterpret_cast<const char*>(iv), output_file_size, ov);
5520 else if (strcmp(style, "md5") == 0)
5521 md5_buffer(reinterpret_cast<const char*>(iv), output_file_size, ov);
5522 else
5523 gold_unreachable();
5524
5525 of->free_input_view(0, output_file_size, iv);
5526 }
5527 else
5528 {
5529 // Non-overlapping substrings of the output file have been hashed.
5530 // Compute SHA-1 hash of the hashes.
5531 sha1_buffer(reinterpret_cast<const char*>(this->array_of_hashes_),
5532 this->size_of_array_of_hashes_, ov);
5533 delete[] this->array_of_hashes_;
5534 of->free_input_view(0, this->output_file_size(), this->input_view_);
5535 }
5536
5537 of->write_output_view(this->build_id_note_->offset(),
5538 this->build_id_note_->data_size(),
5539 ov);
5540 }
5541
5542 // Write out a binary file. This is called after the link is
5543 // complete. IN is the temporary output file we used to generate the
5544 // ELF code. We simply walk through the segments, read them from
5545 // their file offset in IN, and write them to their load address in
5546 // the output file. FIXME: with a bit more work, we could support
5547 // S-records and/or Intel hex format here.
5548
5549 void
write_binary(Output_file * in) const5550 Layout::write_binary(Output_file* in) const
5551 {
5552 gold_assert(parameters->options().oformat_enum()
5553 == General_options::OBJECT_FORMAT_BINARY);
5554
5555 // Get the size of the binary file.
5556 uint64_t max_load_address = 0;
5557 for (Segment_list::const_iterator p = this->segment_list_.begin();
5558 p != this->segment_list_.end();
5559 ++p)
5560 {
5561 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
5562 {
5563 uint64_t max_paddr = (*p)->paddr() + (*p)->filesz();
5564 if (max_paddr > max_load_address)
5565 max_load_address = max_paddr;
5566 }
5567 }
5568
5569 Output_file out(parameters->options().output_file_name());
5570 out.open(max_load_address);
5571
5572 for (Segment_list::const_iterator p = this->segment_list_.begin();
5573 p != this->segment_list_.end();
5574 ++p)
5575 {
5576 if ((*p)->type() == elfcpp::PT_LOAD && (*p)->filesz() > 0)
5577 {
5578 const unsigned char* vin = in->get_input_view((*p)->offset(),
5579 (*p)->filesz());
5580 unsigned char* vout = out.get_output_view((*p)->paddr(),
5581 (*p)->filesz());
5582 memcpy(vout, vin, (*p)->filesz());
5583 out.write_output_view((*p)->paddr(), (*p)->filesz(), vout);
5584 in->free_input_view((*p)->offset(), (*p)->filesz(), vin);
5585 }
5586 }
5587
5588 out.close();
5589 }
5590
5591 // Print the output sections to the map file.
5592
5593 void
print_to_mapfile(Mapfile * mapfile) const5594 Layout::print_to_mapfile(Mapfile* mapfile) const
5595 {
5596 for (Segment_list::const_iterator p = this->segment_list_.begin();
5597 p != this->segment_list_.end();
5598 ++p)
5599 (*p)->print_sections_to_mapfile(mapfile);
5600 for (Section_list::const_iterator p = this->unattached_section_list_.begin();
5601 p != this->unattached_section_list_.end();
5602 ++p)
5603 (*p)->print_to_mapfile(mapfile);
5604 }
5605
5606 // Print statistical information to stderr. This is used for --stats.
5607
5608 void
print_stats() const5609 Layout::print_stats() const
5610 {
5611 this->namepool_.print_stats("section name pool");
5612 this->sympool_.print_stats("output symbol name pool");
5613 this->dynpool_.print_stats("dynamic name pool");
5614
5615 for (Section_list::const_iterator p = this->section_list_.begin();
5616 p != this->section_list_.end();
5617 ++p)
5618 (*p)->print_merge_stats();
5619 }
5620
5621 // Write_sections_task methods.
5622
5623 // We can always run this task.
5624
5625 Task_token*
is_runnable()5626 Write_sections_task::is_runnable()
5627 {
5628 return NULL;
5629 }
5630
5631 // We need to unlock both OUTPUT_SECTIONS_BLOCKER and FINAL_BLOCKER
5632 // when finished.
5633
5634 void
locks(Task_locker * tl)5635 Write_sections_task::locks(Task_locker* tl)
5636 {
5637 tl->add(this, this->output_sections_blocker_);
5638 if (this->input_sections_blocker_ != NULL)
5639 tl->add(this, this->input_sections_blocker_);
5640 tl->add(this, this->final_blocker_);
5641 }
5642
5643 // Run the task--write out the data.
5644
5645 void
run(Workqueue *)5646 Write_sections_task::run(Workqueue*)
5647 {
5648 this->layout_->write_output_sections(this->of_);
5649 }
5650
5651 // Write_data_task methods.
5652
5653 // We can always run this task.
5654
5655 Task_token*
is_runnable()5656 Write_data_task::is_runnable()
5657 {
5658 return NULL;
5659 }
5660
5661 // We need to unlock FINAL_BLOCKER when finished.
5662
5663 void
locks(Task_locker * tl)5664 Write_data_task::locks(Task_locker* tl)
5665 {
5666 tl->add(this, this->final_blocker_);
5667 }
5668
5669 // Run the task--write out the data.
5670
5671 void
run(Workqueue *)5672 Write_data_task::run(Workqueue*)
5673 {
5674 this->layout_->write_data(this->symtab_, this->of_);
5675 }
5676
5677 // Write_symbols_task methods.
5678
5679 // We can always run this task.
5680
5681 Task_token*
is_runnable()5682 Write_symbols_task::is_runnable()
5683 {
5684 return NULL;
5685 }
5686
5687 // We need to unlock FINAL_BLOCKER when finished.
5688
5689 void
locks(Task_locker * tl)5690 Write_symbols_task::locks(Task_locker* tl)
5691 {
5692 tl->add(this, this->final_blocker_);
5693 }
5694
5695 // Run the task--write out the symbols.
5696
5697 void
run(Workqueue *)5698 Write_symbols_task::run(Workqueue*)
5699 {
5700 this->symtab_->write_globals(this->sympool_, this->dynpool_,
5701 this->layout_->symtab_xindex(),
5702 this->layout_->dynsym_xindex(), this->of_);
5703 }
5704
5705 // Write_after_input_sections_task methods.
5706
5707 // We can only run this task after the input sections have completed.
5708
5709 Task_token*
is_runnable()5710 Write_after_input_sections_task::is_runnable()
5711 {
5712 if (this->input_sections_blocker_->is_blocked())
5713 return this->input_sections_blocker_;
5714 return NULL;
5715 }
5716
5717 // We need to unlock FINAL_BLOCKER when finished.
5718
5719 void
locks(Task_locker * tl)5720 Write_after_input_sections_task::locks(Task_locker* tl)
5721 {
5722 tl->add(this, this->final_blocker_);
5723 }
5724
5725 // Run the task.
5726
5727 void
run(Workqueue *)5728 Write_after_input_sections_task::run(Workqueue*)
5729 {
5730 this->layout_->write_sections_after_input_sections(this->of_);
5731 }
5732
5733 // Close_task_runner methods.
5734
5735 // Finish up the build ID computation, if necessary, and write a binary file,
5736 // if necessary. Then close the output file.
5737
5738 void
run(Workqueue *,const Task *)5739 Close_task_runner::run(Workqueue*, const Task*)
5740 {
5741 // At this point the multi-threaded part of the build ID computation,
5742 // if any, is done. See queue_build_id_tasks().
5743 this->layout_->write_build_id(this->of_);
5744
5745 // If we've been asked to create a binary file, we do so here.
5746 if (this->options_->oformat_enum() != General_options::OBJECT_FORMAT_ELF)
5747 this->layout_->write_binary(this->of_);
5748
5749 this->of_->close();
5750 }
5751
5752 // Instantiate the templates we need. We could use the configure
5753 // script to restrict this to only the ones for implemented targets.
5754
5755 #ifdef HAVE_TARGET_32_LITTLE
5756 template
5757 Output_section*
5758 Layout::init_fixed_output_section<32, false>(
5759 const char* name,
5760 elfcpp::Shdr<32, false>& shdr);
5761 #endif
5762
5763 #ifdef HAVE_TARGET_32_BIG
5764 template
5765 Output_section*
5766 Layout::init_fixed_output_section<32, true>(
5767 const char* name,
5768 elfcpp::Shdr<32, true>& shdr);
5769 #endif
5770
5771 #ifdef HAVE_TARGET_64_LITTLE
5772 template
5773 Output_section*
5774 Layout::init_fixed_output_section<64, false>(
5775 const char* name,
5776 elfcpp::Shdr<64, false>& shdr);
5777 #endif
5778
5779 #ifdef HAVE_TARGET_64_BIG
5780 template
5781 Output_section*
5782 Layout::init_fixed_output_section<64, true>(
5783 const char* name,
5784 elfcpp::Shdr<64, true>& shdr);
5785 #endif
5786
5787 #ifdef HAVE_TARGET_32_LITTLE
5788 template
5789 Output_section*
5790 Layout::layout<32, false>(Sized_relobj_file<32, false>* object,
5791 unsigned int shndx,
5792 const char* name,
5793 const elfcpp::Shdr<32, false>& shdr,
5794 unsigned int, unsigned int, off_t*);
5795 #endif
5796
5797 #ifdef HAVE_TARGET_32_BIG
5798 template
5799 Output_section*
5800 Layout::layout<32, true>(Sized_relobj_file<32, true>* object,
5801 unsigned int shndx,
5802 const char* name,
5803 const elfcpp::Shdr<32, true>& shdr,
5804 unsigned int, unsigned int, off_t*);
5805 #endif
5806
5807 #ifdef HAVE_TARGET_64_LITTLE
5808 template
5809 Output_section*
5810 Layout::layout<64, false>(Sized_relobj_file<64, false>* object,
5811 unsigned int shndx,
5812 const char* name,
5813 const elfcpp::Shdr<64, false>& shdr,
5814 unsigned int, unsigned int, off_t*);
5815 #endif
5816
5817 #ifdef HAVE_TARGET_64_BIG
5818 template
5819 Output_section*
5820 Layout::layout<64, true>(Sized_relobj_file<64, true>* object,
5821 unsigned int shndx,
5822 const char* name,
5823 const elfcpp::Shdr<64, true>& shdr,
5824 unsigned int, unsigned int, off_t*);
5825 #endif
5826
5827 #ifdef HAVE_TARGET_32_LITTLE
5828 template
5829 Output_section*
5830 Layout::layout_reloc<32, false>(Sized_relobj_file<32, false>* object,
5831 unsigned int reloc_shndx,
5832 const elfcpp::Shdr<32, false>& shdr,
5833 Output_section* data_section,
5834 Relocatable_relocs* rr);
5835 #endif
5836
5837 #ifdef HAVE_TARGET_32_BIG
5838 template
5839 Output_section*
5840 Layout::layout_reloc<32, true>(Sized_relobj_file<32, true>* object,
5841 unsigned int reloc_shndx,
5842 const elfcpp::Shdr<32, true>& shdr,
5843 Output_section* data_section,
5844 Relocatable_relocs* rr);
5845 #endif
5846
5847 #ifdef HAVE_TARGET_64_LITTLE
5848 template
5849 Output_section*
5850 Layout::layout_reloc<64, false>(Sized_relobj_file<64, false>* object,
5851 unsigned int reloc_shndx,
5852 const elfcpp::Shdr<64, false>& shdr,
5853 Output_section* data_section,
5854 Relocatable_relocs* rr);
5855 #endif
5856
5857 #ifdef HAVE_TARGET_64_BIG
5858 template
5859 Output_section*
5860 Layout::layout_reloc<64, true>(Sized_relobj_file<64, true>* object,
5861 unsigned int reloc_shndx,
5862 const elfcpp::Shdr<64, true>& shdr,
5863 Output_section* data_section,
5864 Relocatable_relocs* rr);
5865 #endif
5866
5867 #ifdef HAVE_TARGET_32_LITTLE
5868 template
5869 void
5870 Layout::layout_group<32, false>(Symbol_table* symtab,
5871 Sized_relobj_file<32, false>* object,
5872 unsigned int,
5873 const char* group_section_name,
5874 const char* signature,
5875 const elfcpp::Shdr<32, false>& shdr,
5876 elfcpp::Elf_Word flags,
5877 std::vector<unsigned int>* shndxes);
5878 #endif
5879
5880 #ifdef HAVE_TARGET_32_BIG
5881 template
5882 void
5883 Layout::layout_group<32, true>(Symbol_table* symtab,
5884 Sized_relobj_file<32, true>* object,
5885 unsigned int,
5886 const char* group_section_name,
5887 const char* signature,
5888 const elfcpp::Shdr<32, true>& shdr,
5889 elfcpp::Elf_Word flags,
5890 std::vector<unsigned int>* shndxes);
5891 #endif
5892
5893 #ifdef HAVE_TARGET_64_LITTLE
5894 template
5895 void
5896 Layout::layout_group<64, false>(Symbol_table* symtab,
5897 Sized_relobj_file<64, false>* object,
5898 unsigned int,
5899 const char* group_section_name,
5900 const char* signature,
5901 const elfcpp::Shdr<64, false>& shdr,
5902 elfcpp::Elf_Word flags,
5903 std::vector<unsigned int>* shndxes);
5904 #endif
5905
5906 #ifdef HAVE_TARGET_64_BIG
5907 template
5908 void
5909 Layout::layout_group<64, true>(Symbol_table* symtab,
5910 Sized_relobj_file<64, true>* object,
5911 unsigned int,
5912 const char* group_section_name,
5913 const char* signature,
5914 const elfcpp::Shdr<64, true>& shdr,
5915 elfcpp::Elf_Word flags,
5916 std::vector<unsigned int>* shndxes);
5917 #endif
5918
5919 #ifdef HAVE_TARGET_32_LITTLE
5920 template
5921 Output_section*
5922 Layout::layout_eh_frame<32, false>(Sized_relobj_file<32, false>* object,
5923 const unsigned char* symbols,
5924 off_t symbols_size,
5925 const unsigned char* symbol_names,
5926 off_t symbol_names_size,
5927 unsigned int shndx,
5928 const elfcpp::Shdr<32, false>& shdr,
5929 unsigned int reloc_shndx,
5930 unsigned int reloc_type,
5931 off_t* off);
5932 #endif
5933
5934 #ifdef HAVE_TARGET_32_BIG
5935 template
5936 Output_section*
5937 Layout::layout_eh_frame<32, true>(Sized_relobj_file<32, true>* object,
5938 const unsigned char* symbols,
5939 off_t symbols_size,
5940 const unsigned char* symbol_names,
5941 off_t symbol_names_size,
5942 unsigned int shndx,
5943 const elfcpp::Shdr<32, true>& shdr,
5944 unsigned int reloc_shndx,
5945 unsigned int reloc_type,
5946 off_t* off);
5947 #endif
5948
5949 #ifdef HAVE_TARGET_64_LITTLE
5950 template
5951 Output_section*
5952 Layout::layout_eh_frame<64, false>(Sized_relobj_file<64, false>* object,
5953 const unsigned char* symbols,
5954 off_t symbols_size,
5955 const unsigned char* symbol_names,
5956 off_t symbol_names_size,
5957 unsigned int shndx,
5958 const elfcpp::Shdr<64, false>& shdr,
5959 unsigned int reloc_shndx,
5960 unsigned int reloc_type,
5961 off_t* off);
5962 #endif
5963
5964 #ifdef HAVE_TARGET_64_BIG
5965 template
5966 Output_section*
5967 Layout::layout_eh_frame<64, true>(Sized_relobj_file<64, true>* object,
5968 const unsigned char* symbols,
5969 off_t symbols_size,
5970 const unsigned char* symbol_names,
5971 off_t symbol_names_size,
5972 unsigned int shndx,
5973 const elfcpp::Shdr<64, true>& shdr,
5974 unsigned int reloc_shndx,
5975 unsigned int reloc_type,
5976 off_t* off);
5977 #endif
5978
5979 #ifdef HAVE_TARGET_32_LITTLE
5980 template
5981 void
5982 Layout::add_to_gdb_index(bool is_type_unit,
5983 Sized_relobj<32, false>* object,
5984 const unsigned char* symbols,
5985 off_t symbols_size,
5986 unsigned int shndx,
5987 unsigned int reloc_shndx,
5988 unsigned int reloc_type);
5989 #endif
5990
5991 #ifdef HAVE_TARGET_32_BIG
5992 template
5993 void
5994 Layout::add_to_gdb_index(bool is_type_unit,
5995 Sized_relobj<32, true>* object,
5996 const unsigned char* symbols,
5997 off_t symbols_size,
5998 unsigned int shndx,
5999 unsigned int reloc_shndx,
6000 unsigned int reloc_type);
6001 #endif
6002
6003 #ifdef HAVE_TARGET_64_LITTLE
6004 template
6005 void
6006 Layout::add_to_gdb_index(bool is_type_unit,
6007 Sized_relobj<64, false>* object,
6008 const unsigned char* symbols,
6009 off_t symbols_size,
6010 unsigned int shndx,
6011 unsigned int reloc_shndx,
6012 unsigned int reloc_type);
6013 #endif
6014
6015 #ifdef HAVE_TARGET_64_BIG
6016 template
6017 void
6018 Layout::add_to_gdb_index(bool is_type_unit,
6019 Sized_relobj<64, true>* object,
6020 const unsigned char* symbols,
6021 off_t symbols_size,
6022 unsigned int shndx,
6023 unsigned int reloc_shndx,
6024 unsigned int reloc_type);
6025 #endif
6026
6027 } // End namespace gold.
6028