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