OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-stable/] [binutils-2.20.1/] [gold/] [layout.cc] - Blame information for rev 862

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.