layout.cc 197 KB
Newer Older
1
2
// layout.cc -- lay out output file sections for gold

3
// Copyright (C) 2006-2019 Free Software Foundation, Inc.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Written by Ian Lance Taylor <iant@google.com>.

// This file is part of gold.

// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
// MA 02110-1301, USA.

23
24
#include "gold.h"

25
#include <cerrno>
26
#include <cstring>
Ian Lance Taylor's avatar
Ian Lance Taylor committed
27
#include <algorithm>
28
#include <iostream>
29
#include <fstream>
30
#include <utility>
31
#include <fcntl.h>
32
#include <fnmatch.h>
33
34
35
36
#include <unistd.h>
#include "libiberty.h"
#include "md5.h"
#include "sha1.h"
37
38
39
40
#ifdef __MINGW32__
#include <windows.h>
#include <rpcdce.h>
#endif
41

Ian Lance Taylor's avatar
Ian Lance Taylor committed
42
#include "parameters.h"
43
#include "options.h"
Ian Lance Taylor's avatar
Ian Lance Taylor committed
44
#include "mapfile.h"
45
46
#include "script.h"
#include "script-sections.h"
47
#include "output.h"
48
#include "symtab.h"
49
#include "dynobj.h"
50
#include "ehframe.h"
51
#include "gdb-index.h"
52
#include "compressed_output.h"
Ian Lance Taylor's avatar
Ian Lance Taylor committed
53
#include "reduced_debug_output.h"
54
#include "object.h"
Ian Lance Taylor's avatar
Ian Lance Taylor committed
55
#include "reloc.h"
Ian Lance Taylor's avatar
Ian Lance Taylor committed
56
#include "descriptors.h"
57
#include "plugin.h"
58
59
#include "incremental.h"
#include "layout.h"
60
61
62
63

namespace gold
{

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Class Free_list.

// The total number of free lists used.
unsigned int Free_list::num_lists = 0;
// The total number of free list nodes used.
unsigned int Free_list::num_nodes = 0;
// The total number of calls to Free_list::remove.
unsigned int Free_list::num_removes = 0;
// The total number of nodes visited during calls to Free_list::remove.
unsigned int Free_list::num_remove_visits = 0;
// The total number of calls to Free_list::allocate.
unsigned int Free_list::num_allocates = 0;
// The total number of nodes visited during calls to Free_list::allocate.
unsigned int Free_list::num_allocate_visits = 0;

// Initialize the free list.  Creates a single free list node that
// describes the entire region of length LEN.  If EXTEND is true,
// allocate() is allowed to extend the region beyond its initial
// length.

void
Free_list::init(off_t len, bool extend)
{
  this->list_.push_front(Free_list_node(0, len));
  this->last_remove_ = this->list_.begin();
  this->extend_ = extend;
  this->length_ = len;
  ++Free_list::num_lists;
  ++Free_list::num_nodes;
}

// Remove a chunk from the free list.  Because we start with a single
// node that covers the entire section, and remove chunks from it one
// at a time, we do not need to coalesce chunks or handle cases that
// span more than one free node.  We expect to remove chunks from the
// free list in order, and we expect to have only a few chunks of free
// space left (corresponding to files that have changed since the last
// incremental link), so a simple linear list should provide sufficient
// performance.

void
Free_list::remove(off_t start, off_t end)
{
  if (start == end)
    return;
  gold_assert(start < end);

  ++Free_list::num_removes;

  Iterator p = this->last_remove_;
  if (p->start_ > start)
    p = this->list_.begin();

  for (; p != this->list_.end(); ++p)
    {
      ++Free_list::num_remove_visits;
      // Find a node that wholly contains the indicated region.
      if (p->start_ <= start && p->end_ >= end)
	{
	  // Case 1: the indicated region spans the whole node.
	  // Add some fuzz to avoid creating tiny free chunks.
	  if (p->start_ + 3 >= start && p->end_ <= end + 3)
	    p = this->list_.erase(p);
	  // Case 2: remove a chunk from the start of the node.
	  else if (p->start_ + 3 >= start)
	    p->start_ = end;
	  // Case 3: remove a chunk from the end of the node.
	  else if (p->end_ <= end + 3)
	    p->end_ = start;
	  // Case 4: remove a chunk from the middle, and split
	  // the node into two.
	  else
	    {
	      Free_list_node newnode(p->start_, start);
	      p->start_ = end;
	      this->list_.insert(p, newnode);
	      ++Free_list::num_nodes;
	    }
	  this->last_remove_ = p;
	  return;
	}
    }

  // Did not find a node containing the given chunk.  This could happen
  // because a small chunk was already removed due to the fuzz.
  gold_debug(DEBUG_INCREMENTAL,
	     "Free_list::remove(%d,%d) not found",
	     static_cast<int>(start), static_cast<int>(end));
}

// Allocate a chunk of size LEN from the free list.  Returns -1ULL
// if a sufficiently large chunk of free space is not found.
// We use a simple first-fit algorithm.

off_t
Free_list::allocate(off_t len, uint64_t align, off_t minoff)
{
  gold_debug(DEBUG_INCREMENTAL,
162
163
164
	     "Free_list::allocate(%08lx, %d, %08lx)",
	     static_cast<long>(len), static_cast<int>(align),
	     static_cast<long>(minoff));
165
166
167
168
169
  if (len == 0)
    return align_address(minoff, align);

  ++Free_list::num_allocates;

170
171
172
173
174
  // We usually want to drop free chunks smaller than 4 bytes.
  // If we need to guarantee a minimum hole size, though, we need
  // to keep track of all free chunks.
  const int fuzz = this->min_hole_ > 0 ? 0 : 3;

175
176
177
178
179
180
  for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
    {
      ++Free_list::num_allocate_visits;
      off_t start = p->start_ > minoff ? p->start_ : minoff;
      start = align_address(start, align);
      off_t end = start + len;
181
182
183
184
185
      if (end > p->end_ && p->end_ == this->length_ && this->extend_)
	{
	  this->length_ = end;
	  p->end_ = end;
	}
186
      if (end == p->end_ || (end <= p->end_ - this->min_hole_))
187
	{
188
	  if (p->start_ + fuzz >= start && p->end_ <= end + fuzz)
189
	    this->list_.erase(p);
190
	  else if (p->start_ + fuzz >= start)
191
	    p->start_ = end;
192
	  else if (p->end_ <= end + fuzz)
193
194
195
196
197
198
199
200
201
202
203
	    p->end_ = start;
	  else
	    {
	      Free_list_node newnode(p->start_, start);
	      p->start_ = end;
	      this->list_.insert(p, newnode);
	      ++Free_list::num_nodes;
	    }
	  return start;
	}
    }
204
205
206
207
208
209
  if (this->extend_)
    {
      off_t start = align_address(this->length_, align);
      this->length_ = start + len;
      return start;
    }
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
  return -1;
}

// Dump the free list (for debugging).
void
Free_list::dump()
{
  gold_info("Free list:\n     start      end   length\n");
  for (Iterator p = this->list_.begin(); p != this->list_.end(); ++p)
    gold_info("  %08lx %08lx %08lx", static_cast<long>(p->start_),
	      static_cast<long>(p->end_),
	      static_cast<long>(p->end_ - p->start_));
}

// Print the statistics for the free lists.
void
Free_list::print_stats()
{
  fprintf(stderr, _("%s: total free lists: %u\n"),
229
	  program_name, Free_list::num_lists);
230
  fprintf(stderr, _("%s: total free list nodes: %u\n"),
231
	  program_name, Free_list::num_nodes);
232
  fprintf(stderr, _("%s: calls to Free_list::remove: %u\n"),
233
	  program_name, Free_list::num_removes);
234
  fprintf(stderr, _("%s: nodes visited: %u\n"),
235
	  program_name, Free_list::num_remove_visits);
236
  fprintf(stderr, _("%s: calls to Free_list::allocate: %u\n"),
237
	  program_name, Free_list::num_allocates);
238
  fprintf(stderr, _("%s: nodes visited: %u\n"),
239
	  program_name, Free_list::num_allocate_visits);
240
241
}

242
243
244
245
246
// A Hash_task computes the MD5 checksum of an array of char.

class Hash_task : public Task
{
 public:
247
248
  Hash_task(Output_file* of,
	    size_t offset,
Roland McGrath's avatar
gold/    
Roland McGrath committed
249
250
251
	    size_t size,
	    unsigned char* dst,
	    Task_token* final_blocker)
252
    : of_(of), offset_(offset), size_(size), dst_(dst),
253
254
255
256
257
      final_blocker_(final_blocker)
  { }

  void
  run(Workqueue*)
258
259
260
261
262
263
  {
    const unsigned char* iv =
	this->of_->get_input_view(this->offset_, this->size_);
    md5_buffer(reinterpret_cast<const char*>(iv), this->size_, this->dst_);
    this->of_->free_input_view(this->offset_, this->size_, iv);
  }
264
265

  Task_token*
266
267
  is_runnable()
  { return NULL; }
268
269
270
271
272
273
274
275
276
277
278

  // Unblock FINAL_BLOCKER_ when done.
  void
  locks(Task_locker* tl)
  { tl->add(this, this->final_blocker_); }

  std::string
  get_name() const
  { return "Hash_task"; }

 private:
279
280
  Output_file* of_;
  const size_t offset_;
281
282
283
284
285
  const size_t size_;
  unsigned char* const dst_;
  Task_token* const final_blocker_;
};

286
287
288
289
290
291
292
293
294
// Layout::Relaxation_debug_check methods.

// Check that sections and special data are in reset states.
// We do not save states for Output_sections and special Output_data.
// So we check that they have not assigned any addresses or offsets.
// clean_up_after_relaxation simply resets their addresses and offsets.
void
Layout::Relaxation_debug_check::check_output_data_for_reset_values(
    const Layout::Section_list& sections,
Roland McGrath's avatar
gold/    
Roland McGrath committed
295
296
    const Layout::Data_list& special_outputs,
    const Layout::Data_list& relax_outputs)
297
298
299
300
301
302
303
304
305
306
{
  for(Layout::Section_list::const_iterator p = sections.begin();
      p != sections.end();
      ++p)
    gold_assert((*p)->address_and_file_offset_have_reset_values());

  for(Layout::Data_list::const_iterator p = special_outputs.begin();
      p != special_outputs.end();
      ++p)
    gold_assert((*p)->address_and_file_offset_have_reset_values());
Roland McGrath's avatar
gold/    
Roland McGrath committed
307
308

  gold_assert(relax_outputs.empty());
309
}
310

311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Save information of SECTIONS for checking later.

void
Layout::Relaxation_debug_check::read_sections(
    const Layout::Section_list& sections)
{
  for(Layout::Section_list::const_iterator p = sections.begin();
      p != sections.end();
      ++p)
    {
      Output_section* os = *p;
      Section_info info;
      info.output_section = os;
      info.address = os->is_address_valid() ? os->address() : 0;
      info.data_size = os->is_data_size_valid() ? os->data_size() : -1;
      info.offset = os->is_offset_valid()? os->offset() : -1 ;
      this->section_infos_.push_back(info);
    }
}

// Verify SECTIONS using previously recorded information.

void
Layout::Relaxation_debug_check::verify_sections(
    const Layout::Section_list& sections)
{
  size_t i = 0;
  for(Layout::Section_list::const_iterator p = sections.begin();
      p != sections.end();
      ++p, ++i)
    {
      Output_section* os = *p;
      uint64_t address = os->is_address_valid() ? os->address() : 0;
      off_t data_size = os->is_data_size_valid() ? os->data_size() : -1;
      off_t offset = os->is_offset_valid()? os->offset() : -1 ;

      if (i >= this->section_infos_.size())
	{
	  gold_fatal("Section_info of %s missing.\n", os->name());
	}
      const Section_info& info = this->section_infos_[i];
      if (os != info.output_section)
	gold_fatal("Section order changed.  Expecting %s but see %s\n",
		   info.output_section->name(), os->name());
      if (address != info.address
	  || data_size != info.data_size
	  || offset != info.offset)
	gold_fatal("Section %s changed.\n", os->name());
    }
}

362
// Layout_task_runner methods.
363
364
365
366
367

// Lay out the sections.  This is called after all the input objects
// have been read.

void
368
Layout_task_runner::run(Workqueue* workqueue, const Task* task)
369
{
370
371
372
373
  // See if any of the input definitions violate the One Definition Rule.
  // TODO: if this is too slow, do this as a task, rather than inline.
  this->symtab_->detect_odr_violations(task, this->options_.output_file_name());

374
375
376
  Layout* layout = this->layout_;
  off_t file_size = layout->finalize(this->input_objects_,
				     this->symtab_,
377
				     this->target_,
378
				     task);
379
380
381

  // Now we know the final size of the output file and we know where
  // each piece of information goes.
Ian Lance Taylor's avatar
Ian Lance Taylor committed
382
383
384
385

  if (this->mapfile_ != NULL)
    {
      this->mapfile_->print_discarded_sections(this->input_objects_);
386
      layout->print_to_mapfile(this->mapfile_);
Ian Lance Taylor's avatar
Ian Lance Taylor committed
387
388
    }

389
  Output_file* of;
390
  if (layout->incremental_base() == NULL)
391
392
393
394
395
396
397
398
    {
      of = new Output_file(parameters->options().output_file_name());
      if (this->options_.oformat_enum() != General_options::OBJECT_FORMAT_ELF)
	of->set_is_temporary();
      of->open(file_size);
    }
  else
    {
399
400
401
402
403
404
405
406
      of = layout->incremental_base()->output_file();

      // Apply the incremental relocations for symbols whose values
      // have changed.  We do this before we resize the file and start
      // writing anything else to it, so that we can read the old
      // incremental information from the file before (possibly)
      // overwriting it.
      if (parameters->incremental_update())
407
408
	layout->incremental_base()->apply_incremental_relocs(this->symtab_,
							     this->layout_,
409
410
							     of);

411
412
      of->resize(file_size);
    }
413
414
415

  // Queue up the final set of tasks.
  gold::queue_final_tasks(this->options_, this->input_objects_,
416
			  this->symtab_, layout, workqueue, of);
417
418
419
420
}

// Layout methods.

421
Layout::Layout(int number_of_input_files, Script_options* script_options)
422
  : number_of_input_files_(number_of_input_files),
423
    script_options_(script_options),
424
425
426
427
428
429
430
431
432
    namepool_(),
    sympool_(),
    dynpool_(),
    signatures_(),
    section_name_map_(),
    segment_list_(),
    section_list_(),
    unattached_section_list_(),
    special_output_list_(),
Roland McGrath's avatar
gold/    
Roland McGrath committed
433
    relax_output_list_(),
434
435
    section_headers_(NULL),
    tls_segment_(NULL),
436
    relro_segment_(NULL),
Ian Lance Taylor's avatar
Ian Lance Taylor committed
437
    interp_segment_(NULL),
438
    increase_relro_(0),
439
440
441
442
443
    symtab_section_(NULL),
    symtab_xindex_(NULL),
    dynsym_section_(NULL),
    dynsym_xindex_(NULL),
    dynamic_section_(NULL),
Ian Lance Taylor's avatar
Ian Lance Taylor committed
444
    dynamic_symbol_(NULL),
445
446
447
448
449
    dynamic_data_(NULL),
    eh_frame_section_(NULL),
    eh_frame_data_(NULL),
    added_eh_frame_data_(false),
    eh_frame_hdr_section_(NULL),
450
    gdb_index_data_(NULL),
451
    build_id_note_(NULL),
Ian Lance Taylor's avatar
Ian Lance Taylor committed
452
453
    debug_abbrev_(NULL),
    debug_info_(NULL),
454
455
    group_signatures_(),
    output_file_size_(-1),
Ian Lance Taylor's avatar
Ian Lance Taylor committed
456
    have_added_input_section_(false),
457
    sections_are_attached_(false),
458
459
    input_requires_executable_stack_(false),
    input_with_gnu_stack_note_(false),
460
    input_without_gnu_stack_note_(false),
461
    has_static_tls_(false),
462
    any_postprocessing_sections_(false),
463
    resized_signatures_(false),
Ian Lance Taylor's avatar
Ian Lance Taylor committed
464
    have_stabstr_section_(false),
465
    section_ordering_specified_(false),
466
    unique_segment_for_sections_specified_(false),
467
468
    incremental_inputs_(NULL),
    record_output_section_data_from_script_(false),
469
    lto_slim_object_(false),
470
471
    script_output_section_data_list_(),
    segment_states_(NULL),
472
    relaxation_debug_check_(NULL),
Sriraman Tallam's avatar
   
Sriraman Tallam committed
473
    section_order_map_(),
474
    section_segment_map_(),
475
476
    input_section_position_(),
    input_section_glob_(),
477
    incremental_base_(NULL),
478
479
    free_list_(),
    gnu_properties_()
Ian Lance Taylor's avatar
Ian Lance Taylor committed
480
481
482
{
  // Make space for more than enough segments for a typical file.
  // This is just for efficiency--it's OK if we wind up needing more.
483
484
  this->segment_list_.reserve(12);

485
486
487
  // We expect two unattached Output_data objects: the file header and
  // the segment headers.
  this->special_output_list_.reserve(2);
488
489

  // Initialize structure needed for an incremental build.
490
  if (parameters->incremental())
491
    this->incremental_inputs_ = new Incremental_inputs;
Ian Lance Taylor's avatar
Ian Lance Taylor committed
492
493
494
495

  // The section name pool is worth optimizing in all cases, because
  // it is small, but there are often overlaps due to .rel sections.
  this->namepool_.set_optimize();
Ian Lance Taylor's avatar
Ian Lance Taylor committed
496
497
}

498
499
500
501
502
503
504
505
506
// For incremental links, record the base file to be modified.

void
Layout::set_incremental_base(Incremental_binary* base)
{
  this->incremental_base_ = base;
  this->free_list_.init(base->output_file()->filesize(), true);
}

507
508
509
510
511
// Hash a key we use to look up an output section mapping.

size_t
Layout::Hash_key::operator()(const Layout::Key& k) const
{
512
 return k.first + k.second.first + k.second.second;
513
514
}

Cary Coutant's avatar
gold/    
Cary Coutant committed
515
516
517
518
// These are the debug sections that are actually used by gdb.
// Currently, we've checked versions of gdb up to and including 7.4.
// We only check the part of the name that follows ".debug_" or
// ".zdebug_".
519
520

static const char* gdb_sections[] =
Cary Coutant's avatar
gold/    
Cary Coutant committed
521
522
523
524
525
{
  "abbrev",
  "addr",         // Fission extension
  // "aranges",   // not used by gdb as of 7.4
  "frame",
526
  "gdb_scripts",
Cary Coutant's avatar
gold/    
Cary Coutant committed
527
528
529
530
531
532
533
534
  "info",
  "types",
  "line",
  "loc",
  "macinfo",
  "macro",
  // "pubnames",  // not used by gdb as of 7.4
  // "pubtypes",  // not used by gdb as of 7.4
535
536
  // "gnu_pubnames",  // Fission extension
  // "gnu_pubtypes",  // Fission extension
Cary Coutant's avatar
gold/    
Cary Coutant committed
537
538
  "ranges",
  "str",
539
  "str_offsets",
540
541
};

Cary Coutant's avatar
gold/    
Cary Coutant committed
542
543
// This is the minimum set of sections needed for line numbers.

Ian Lance Taylor's avatar
Ian Lance Taylor committed
544
static const char* lines_only_debug_sections[] =
Cary Coutant's avatar
gold/    
Cary Coutant committed
545
546
547
548
549
{
  "abbrev",
  // "addr",      // Fission extension
  // "aranges",   // not used by gdb as of 7.4
  // "frame",
550
  // "gdb_scripts",
Cary Coutant's avatar
gold/    
Cary Coutant committed
551
552
553
554
555
556
557
558
  "info",
  // "types",
  "line",
  // "loc",
  // "macinfo",
  // "macro",
  // "pubnames",  // not used by gdb as of 7.4
  // "pubtypes",  // not used by gdb as of 7.4
559
560
  // "gnu_pubnames",  // Fission extension
  // "gnu_pubtypes",  // Fission extension
Cary Coutant's avatar
gold/    
Cary Coutant committed
561
562
  // "ranges",
  "str",
563
  "str_offsets",  // Fission extension
Cary Coutant's avatar
gold/    
Cary Coutant committed
564
565
566
567
568
569
570
571
572
};

// These sections are the DWARF fast-lookup tables, and are not needed
// when building a .gdb_index section.

static const char* gdb_fast_lookup_sections[] =
{
  "aranges",
  "pubnames",
573
  "gnu_pubnames",
Cary Coutant's avatar
gold/    
Cary Coutant committed
574
  "pubtypes",
575
  "gnu_pubtypes",
Ian Lance Taylor's avatar
Ian Lance Taylor committed
576
577
};

Cary Coutant's avatar
gold/    
Cary Coutant committed
578
579
580
581
// Returns whether the given debug section is in the list of
// debug-sections-used-by-some-version-of-gdb.  SUFFIX is the
// portion of the name following ".debug_" or ".zdebug_".

582
static inline bool
Cary Coutant's avatar
gold/    
Cary Coutant committed
583
is_gdb_debug_section(const char* suffix)
584
585
586
{
  // We can do this faster: binary search or a hashtable.  But why bother?
  for (size_t i = 0; i < sizeof(gdb_sections)/sizeof(*gdb_sections); ++i)
Cary Coutant's avatar
gold/    
Cary Coutant committed
587
    if (strcmp(suffix, gdb_sections[i]) == 0)
588
589
590
591
      return true;
  return false;
}

Cary Coutant's avatar
gold/    
Cary Coutant committed
592
593
// Returns whether the given section is needed for lines-only debugging.

Ian Lance Taylor's avatar
Ian Lance Taylor committed
594
static inline bool
Cary Coutant's avatar
gold/    
Cary Coutant committed
595
is_lines_only_debug_section(const char* suffix)
Ian Lance Taylor's avatar
Ian Lance Taylor committed
596
597
598
599
600
{
  // We can do this faster: binary search or a hashtable.  But why bother?
  for (size_t i = 0;
       i < sizeof(lines_only_debug_sections)/sizeof(*lines_only_debug_sections);
       ++i)
Cary Coutant's avatar
gold/    
Cary Coutant committed
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    if (strcmp(suffix, lines_only_debug_sections[i]) == 0)
      return true;
  return false;
}

// Returns whether the given section is a fast-lookup section that
// will not be needed when building a .gdb_index section.

static inline bool
is_gdb_fast_lookup_section(const char* suffix)
{
  // We can do this faster: binary search or a hashtable.  But why bother?
  for (size_t i = 0;
       i < sizeof(gdb_fast_lookup_sections)/sizeof(*gdb_fast_lookup_sections);
       ++i)
    if (strcmp(suffix, gdb_fast_lookup_sections[i]) == 0)
Ian Lance Taylor's avatar
Ian Lance Taylor committed
617
618
619
620
      return true;
  return false;
}

Cary Coutant's avatar
Cary Coutant committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
// Sometimes we compress sections.  This is typically done for
// sections that are not part of normal program execution (such as
// .debug_* sections), and where the readers of these sections know
// how to deal with compressed sections.  This routine doesn't say for
// certain whether we'll compress -- it depends on commandline options
// as well -- just whether this section is a candidate for compression.
// (The Output_compressed_section class decides whether to compress
// a given section, and picks the name of the compressed section.)

static bool
is_compressible_debug_section(const char* secname)
{
  return (is_prefix_of(".debug", secname));
}

// We may see compressed debug sections in input files.  Return TRUE
// if this is the name of a compressed debug section.

bool
is_compressed_debug_section(const char* secname)
{
  return (is_prefix_of(".zdebug", secname));
}

645
646
647
648
649
650
651
652
653
std::string
corresponding_uncompressed_section_name(std::string secname)
{
  gold_assert(secname[0] == '.' && secname[1] == 'z');
  std::string ret(".");
  ret.append(secname, 2, std::string::npos);
  return ret;
}

654
655
656
657
// Whether to include this section in the link.

template<int size, bool big_endian>
bool
658
Layout::include_section(Sized_relobj_file<size, big_endian>*, const char* name,
659
660
			const elfcpp::Shdr<size, big_endian>& shdr)
{
661
662
  if (!parameters->options().relocatable()
      && (shdr.get_sh_flags() & elfcpp::SHF_EXCLUDE))
663
664
    return false;

665
666
667
668
669
670
671
  elfcpp::Elf_Word sh_type = shdr.get_sh_type();

  if ((sh_type >= elfcpp::SHT_LOOS && sh_type <= elfcpp::SHT_HIOS)
      || (sh_type >= elfcpp::SHT_LOPROC && sh_type <= elfcpp::SHT_HIPROC))
    return parameters->target().should_include_section(sh_type);

  switch (sh_type)
672
673
674
675
676
677
678
679
680
    {
    case elfcpp::SHT_NULL:
    case elfcpp::SHT_SYMTAB:
    case elfcpp::SHT_DYNSYM:
    case elfcpp::SHT_HASH:
    case elfcpp::SHT_DYNAMIC:
    case elfcpp::SHT_SYMTAB_SHNDX:
      return false;

681
682
683
684
685
686
687
688
    case elfcpp::SHT_STRTAB:
      // Discard the sections which have special meanings in the ELF
      // ABI.  Keep others (e.g., .stabstr).  We could also do this by
      // checking the sh_link fields of the appropriate sections.
      return (strcmp(name, ".dynstr") != 0
	      && strcmp(name, ".strtab") != 0
	      && strcmp(name, ".shstrtab") != 0);

689
690
691
    case elfcpp::SHT_RELA:
    case elfcpp::SHT_REL:
    case elfcpp::SHT_GROUP:
Ian Lance Taylor's avatar
Ian Lance Taylor committed
692
693
      // If we are emitting relocations these should be handled
      // elsewhere.
694
      gold_assert(!parameters->options().relocatable());
Ian Lance Taylor's avatar
Ian Lance Taylor committed
695
      return false;
696

697
    case elfcpp::SHT_PROGBITS:
698
      if (parameters->options().strip_debug()
699
700
	  && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
	{
701
	  if (is_debug_info_section(name))
702
703
	    return false;
	}
Ian Lance Taylor's avatar
Ian Lance Taylor committed
704
705
706
707
      if (parameters->options().strip_debug_non_line()
	  && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
	{
	  // Debugging sections can only be recognized by name.
Cary Coutant's avatar
gold/    
Cary Coutant committed
708
709
710
711
712
	  if (is_prefix_of(".debug_", name)
	      && !is_lines_only_debug_section(name + 7))
	    return false;
	  if (is_prefix_of(".zdebug_", name)
	      && !is_lines_only_debug_section(name + 8))
Ian Lance Taylor's avatar
Ian Lance Taylor committed
713
714
	    return false;
	}
715
      if (parameters->options().strip_debug_gdb()
716
717
718
	  && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
	{
	  // Debugging sections can only be recognized by name.
Cary Coutant's avatar
gold/    
Cary Coutant committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
	  if (is_prefix_of(".debug_", name)
	      && !is_gdb_debug_section(name + 7))
	    return false;
	  if (is_prefix_of(".zdebug_", name)
	      && !is_gdb_debug_section(name + 8))
	    return false;
	}
      if (parameters->options().gdb_index()
	  && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
	{
	  // When building .gdb_index, we can strip .debug_pubnames,
	  // .debug_pubtypes, and .debug_aranges sections.
	  if (is_prefix_of(".debug_", name)
	      && is_gdb_fast_lookup_section(name + 7))
	    return false;
	  if (is_prefix_of(".zdebug_", name)
	      && is_gdb_fast_lookup_section(name + 8))
736
737
	    return false;
	}
738
      if (parameters->options().strip_lto_sections()
739
740
741
742
743
744
745
	  && !parameters->options().relocatable()
	  && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
	{
	  // Ignore LTO sections containing intermediate code.
	  if (is_prefix_of(".gnu.lto_", name))
	    return false;
	}
Ian Lance Taylor's avatar
Ian Lance Taylor committed
746
747
748
749
750
      // The GNU linker strips .gnu_debuglink sections, so we do too.
      // This is a feature used to keep debugging information in
      // separate files.
      if (strcmp(name, ".gnu_debuglink") == 0)
	return false;
751
752
      return true;

753
754
755
756
757
    default:
      return true;
    }
}

758
// Return an output section named NAME, or NULL if there is none.
759
760

Output_section*
761
Layout::find_output_section(const char* name) const
762
{
763
764
  for (Section_list::const_iterator p = this->section_list_.begin();
       p != this->section_list_.end();
765
       ++p)
766
767
    if (strcmp((*p)->name(), name) == 0)
      return *p;
768
769
  return NULL;
}
770

771
772
// Return an output segment of type TYPE, with segment flags SET set
// and segment flags CLEAR clear.  Return NULL if there is none.
773

774
775
776
777
778
779
780
781
782
783
784
785
786
Output_segment*
Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
			    elfcpp::Elf_Word clear) const
{
  for (Segment_list::const_iterator p = this->segment_list_.begin();
       p != this->segment_list_.end();
       ++p)
    if (static_cast<elfcpp::PT>((*p)->type()) == type
	&& ((*p)->flags() & set) == set
	&& ((*p)->flags() & clear) == 0)
      return *p;
  return NULL;
}
787

788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
// When we put a .ctors or .dtors section with more than one word into
// a .init_array or .fini_array section, we need to reverse the words
// in the .ctors/.dtors section.  This is because .init_array executes
// constructors front to back, where .ctors executes them back to
// front, and vice-versa for .fini_array/.dtors.  Although we do want
// to remap .ctors/.dtors into .init_array/.fini_array because it can
// be more efficient, we don't want to change the order in which
// constructors/destructors are run.  This set just keeps track of
// these sections which need to be reversed.  It is only changed by
// Layout::layout.  It should be a private member of Layout, but that
// would require layout.h to #include object.h to get the definition
// of Section_id.
static Unordered_set<Section_id, Section_id_hash> ctors_sections_in_init_array;

// Return whether OBJECT/SHNDX is a .ctors/.dtors section mapped to a
// .init_array/.fini_array section.

bool
Layout::is_ctors_in_init_array(Relobj* relobj, unsigned int shndx) const
{
  return (ctors_sections_in_init_array.find(Section_id(relobj, shndx))
	  != ctors_sections_in_init_array.end());
}

812
// Return the output section to use for section NAME with type TYPE
813
// and section flags FLAGS.  NAME must be canonicalized in the string
Ian Lance Taylor's avatar
Ian Lance Taylor committed
814
815
// pool, and NAME_KEY is the key.  ORDER is where this should appear
// in the output sections.  IS_RELRO is true for a relro section.
816

817
Output_section*
818
Layout::get_output_section(const char* name, Stringpool::Key name_key,
819
			   elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
820
			   Output_section_order order, bool is_relro)
821
{
Ian Lance Taylor's avatar
Ian Lance Taylor committed
822
823
824
825
826
827
828
829
830
831
832
833
  elfcpp::Elf_Word lookup_type = type;

  // For lookup purposes, treat INIT_ARRAY, FINI_ARRAY, and
  // PREINIT_ARRAY like PROGBITS.  This ensures that we combine
  // .init_array, .fini_array, and .preinit_array sections by name
  // whatever their type in the input file.  We do this because the
  // types are not always right in the input files.
  if (lookup_type == elfcpp::SHT_INIT_ARRAY
      || lookup_type == elfcpp::SHT_FINI_ARRAY
      || lookup_type == elfcpp::SHT_PREINIT_ARRAY)
    lookup_type = elfcpp::SHT_PROGBITS;

834
835
836
837
838
839
840
841
  elfcpp::Elf_Xword lookup_flags = flags;

  // Ignoring SHF_WRITE and SHF_EXECINSTR here means that we combine
  // read-write with read-only sections.  Some other ELF linkers do
  // not do this.  FIXME: Perhaps there should be an option
  // controlling this.
  lookup_flags &= ~(elfcpp::SHF_WRITE | elfcpp::SHF_EXECINSTR);

Ian Lance Taylor's avatar
Ian Lance Taylor committed
842
  const Key key(name_key, std::make_pair(lookup_type, lookup_flags));
843
844
845
846
847
  const std::pair<Key, Output_section*> v(key, NULL);
  std::pair<Section_name_map::iterator, bool> ins(
    this->section_name_map_.insert(v));

  if (!ins.second)
848
    return ins.first->second;
849
850
851
  else
    {
      // This is the first time we've seen this name/type/flags
852
853
854
855
856
      // combination.  For compatibility with the GNU linker, we
      // combine sections with contents and zero flags with sections
      // with non-zero flags.  This is a workaround for cases where
      // assembler code forgets to set section flags.  FIXME: Perhaps
      // there should be an option to control this.
857
      Output_section* os = NULL;
858

Ian Lance Taylor's avatar
Ian Lance Taylor committed
859
      if (lookup_type == elfcpp::SHT_PROGBITS)
860
	{
861
862
863
864
865
	  if (flags == 0)
	    {
	      Output_section* same_name = this->find_output_section(name);
	      if (same_name != NULL
		  && (same_name->type() == elfcpp::SHT_PROGBITS
Ian Lance Taylor's avatar
Ian Lance Taylor committed
866
867
868
		      || same_name->type() == elfcpp::SHT_INIT_ARRAY
		      || same_name->type() == elfcpp::SHT_FINI_ARRAY
		      || same_name->type() == elfcpp::SHT_PREINIT_ARRAY)
869
870
871
872
873
874
875
		  && (same_name->flags() & elfcpp::SHF_TLS) == 0)
		os = same_name;
	    }
	  else if ((flags & elfcpp::SHF_TLS) == 0)
	    {
	      elfcpp::Elf_Xword zero_flags = 0;
	      const Key zero_key(name_key, std::make_pair(lookup_type,
Ian Lance Taylor's avatar
Ian Lance Taylor committed
876
							  zero_flags));
877
878
879
	      Section_name_map::iterator p =
		  this->section_name_map_.find(zero_key);
	      if (p != this->section_name_map_.end())
880
		os = p->second;
881
	    }
882
	}
883

884
      if (os == NULL)
885
886
	os = this->make_output_section(name, type, flags, order, is_relro);

887
      ins.first->second = os;
888
      return os;
889
    }
890
891
}

Nick Clifton's avatar
Nick Clifton committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
// Returns TRUE iff NAME (an input section from RELOBJ) will
// be mapped to an output section that should be KEPT.

bool
Layout::keep_input_section(const Relobj* relobj, const char* name)
{
  if (! this->script_options_->saw_sections_clause())
    return false;

  Script_sections* ss = this->script_options_->script_sections();
  const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
  Output_section** output_section_slot;
  Script_sections::Section_type script_section_type;
  bool keep;

  name = ss->output_section_name(file_name, name, &output_section_slot,
908
				 &script_section_type, &keep, true);
Nick Clifton's avatar
Nick Clifton committed
909
910
911
  return name != NULL && keep;
}

912
913
914
915
916
917
918
919
920
921
// Clear the input section flags that should not be copied to the
// output section.

elfcpp::Elf_Xword
Layout::get_output_section_flags(elfcpp::Elf_Xword input_section_flags)
{
  // Some flags in the input section should not be automatically
  // copied to the output section.
  input_section_flags &= ~ (elfcpp::SHF_INFO_LINK
			    | elfcpp::SHF_GROUP
922
			    | elfcpp::SHF_COMPRESSED
923
924
925
926
927
928
929
930
931
932
933
			    | elfcpp::SHF_MERGE
			    | elfcpp::SHF_STRINGS);

  // We only clear the SHF_LINK_ORDER flag in for
  // a non-relocatable link.
  if (!parameters->options().relocatable())
    input_section_flags &= ~elfcpp::SHF_LINK_ORDER;

  return input_section_flags;
}

934
935
// Pick the output section to use for section NAME, in input file
// RELOBJ, with type TYPE and flags FLAGS.  RELOBJ may be NULL for a
936
937
// linker created section.  IS_INPUT_SECTION is true if we are
// choosing an output section for an input section found in a input
Ian Lance Taylor's avatar
Ian Lance Taylor committed
938
939
// file.  ORDER is where this section should appear in the output
// sections.  IS_RELRO is true for a relro section.  This will return
940
941
942
// NULL if the input section should be discarded.  MATCH_INPUT_SPEC
// is true if the section name should be matched against input specs
// in a linker script.
943
944
945
946

Output_section*
Layout::choose_output_section(const Relobj* relobj, const char* name,
			      elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
947
			      bool is_input_section, Output_section_order order,
948
949
			      bool is_relro, bool is_reloc,
			      bool match_input_spec)
950
{
951
952
953
954
  // We should not see any input sections after we have attached
  // sections to segments.
  gold_assert(!is_input_section || !this->sections_are_attached_);

955
  flags = this->get_output_section_flags(flags);
956

957
  if (this->script_options_->saw_sections_clause() && !is_reloc)
958
959
960
961
962
963
964
    {
      // We are using a SECTIONS clause, so the output section is
      // chosen based only on the name.

      Script_sections* ss = this->script_options_->script_sections();
      const char* file_name = relobj == NULL ? NULL : relobj->name().c_str();
      Output_section** output_section_slot;
965
      Script_sections::Section_type script_section_type;
966
      const char* orig_name = name;
Nick Clifton's avatar
Nick Clifton committed
967
      bool keep;
968
      name = ss->output_section_name(file_name, name, &output_section_slot,
969
970
				     &script_section_type, &keep,
				     match_input_spec);
Nick Clifton's avatar
Nick Clifton committed
971

972
973
      if (name == NULL)
	{
974
975
976
977
	  gold_debug(DEBUG_SCRIPT, _("Unable to create output section '%s' "
				     "because it is not allowed by the "
				     "SECTIONS clause of the linker script"),
		     orig_name);
978
979
980
981
	  // The SECTIONS clause says to discard this input section.
	  return NULL;
	}

982
983
984
985
986
987
988
989
990
991
992
993
      // We can only handle script section types ST_NONE and ST_NOLOAD.
      switch (script_section_type)
	{
	case Script_sections::ST_NONE:
	  break;
	case Script_sections::ST_NOLOAD:
	  flags &= elfcpp::SHF_ALLOC;
	  break;
	default:
	  gold_unreachable();
	}

994
995
996
997
998
999
1000
      // If this is an orphan section--one not mentioned in the linker
      // script--then OUTPUT_SECTION_SLOT will be NULL, and we do the
      // default processing below.

      if (output_section_slot != NULL)
	{
	  if (*output_section_slot != NULL)