Create a note section with the version of gold.
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 // Copyright 2006, 2007 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 <cstring>
26 #include <algorithm>
27 #include <iostream>
28 #include <utility>
29
30 #include "parameters.h"
31 #include "output.h"
32 #include "symtab.h"
33 #include "dynobj.h"
34 #include "ehframe.h"
35 #include "layout.h"
36
37 namespace gold
38 {
39
40 // Layout_task_runner methods.
41
42 // Lay out the sections.  This is called after all the input objects
43 // have been read.
44
45 void
46 Layout_task_runner::run(Workqueue* workqueue)
47 {
48   off_t file_size = this->layout_->finalize(this->input_objects_,
49                                             this->symtab_);
50
51   // Now we know the final size of the output file and we know where
52   // each piece of information goes.
53   Output_file* of = new Output_file(this->options_,
54                                     this->input_objects_->target());
55   of->open(file_size);
56
57   // Queue up the final set of tasks.
58   gold::queue_final_tasks(this->options_, this->input_objects_,
59                           this->symtab_, this->layout_, workqueue, of);
60 }
61
62 // Layout methods.
63
64 Layout::Layout(const General_options& options)
65   : options_(options), namepool_(), sympool_(), dynpool_(), signatures_(),
66     section_name_map_(), segment_list_(), section_list_(),
67     unattached_section_list_(), special_output_list_(),
68     tls_segment_(NULL), symtab_section_(NULL),
69     dynsym_section_(NULL), dynamic_section_(NULL), dynamic_data_(NULL),
70     eh_frame_section_(NULL)
71 {
72   // Make space for more than enough segments for a typical file.
73   // This is just for efficiency--it's OK if we wind up needing more.
74   this->segment_list_.reserve(12);
75
76   // We expect three unattached Output_data objects: the file header,
77   // the segment headers, and the section headers.
78   this->special_output_list_.reserve(3);
79 }
80
81 // Hash a key we use to look up an output section mapping.
82
83 size_t
84 Layout::Hash_key::operator()(const Layout::Key& k) const
85 {
86  return k.first + k.second.first + k.second.second;
87 }
88
89 // Whether to include this section in the link.
90
91 template<int size, bool big_endian>
92 bool
93 Layout::include_section(Object*, const char*,
94                         const elfcpp::Shdr<size, big_endian>& shdr)
95 {
96   // Some section types are never linked.  Some are only linked when
97   // doing a relocateable link.
98   switch (shdr.get_sh_type())
99     {
100     case elfcpp::SHT_NULL:
101     case elfcpp::SHT_SYMTAB:
102     case elfcpp::SHT_DYNSYM:
103     case elfcpp::SHT_STRTAB:
104     case elfcpp::SHT_HASH:
105     case elfcpp::SHT_DYNAMIC:
106     case elfcpp::SHT_SYMTAB_SHNDX:
107       return false;
108
109     case elfcpp::SHT_RELA:
110     case elfcpp::SHT_REL:
111     case elfcpp::SHT_GROUP:
112       return parameters->output_is_object();
113
114     default:
115       // FIXME: Handle stripping debug sections here.
116       return true;
117     }
118 }
119
120 // Return an output section named NAME, or NULL if there is none.
121
122 Output_section*
123 Layout::find_output_section(const char* name) const
124 {
125   for (Section_name_map::const_iterator p = this->section_name_map_.begin();
126        p != this->section_name_map_.end();
127        ++p)
128     if (strcmp(p->second->name(), name) == 0)
129       return p->second;
130   return NULL;
131 }
132
133 // Return an output segment of type TYPE, with segment flags SET set
134 // and segment flags CLEAR clear.  Return NULL if there is none.
135
136 Output_segment*
137 Layout::find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
138                             elfcpp::Elf_Word clear) const
139 {
140   for (Segment_list::const_iterator p = this->segment_list_.begin();
141        p != this->segment_list_.end();
142        ++p)
143     if (static_cast<elfcpp::PT>((*p)->type()) == type
144         && ((*p)->flags() & set) == set
145         && ((*p)->flags() & clear) == 0)
146       return *p;
147   return NULL;
148 }
149
150 // Return the output section to use for section NAME with type TYPE
151 // and section flags FLAGS.
152
153 Output_section*
154 Layout::get_output_section(const char* name, Stringpool::Key name_key,
155                            elfcpp::Elf_Word type, elfcpp::Elf_Xword flags)
156 {
157   // We should ignore some flags.
158   flags &= ~ (elfcpp::SHF_INFO_LINK
159               | elfcpp::SHF_LINK_ORDER
160               | elfcpp::SHF_GROUP
161               | elfcpp::SHF_MERGE
162               | elfcpp::SHF_STRINGS);
163
164   const Key key(name_key, std::make_pair(type, flags));
165   const std::pair<Key, Output_section*> v(key, NULL);
166   std::pair<Section_name_map::iterator, bool> ins(
167     this->section_name_map_.insert(v));
168
169   if (!ins.second)
170     return ins.first->second;
171   else
172     {
173       // This is the first time we've seen this name/type/flags
174       // combination.
175       Output_section* os = this->make_output_section(name, type, flags);
176       ins.first->second = os;
177       return os;
178     }
179 }
180
181 // Return the output section to use for input section SHNDX, with name
182 // NAME, with header HEADER, from object OBJECT.  Set *OFF to the
183 // offset of this input section without the output section.
184
185 template<int size, bool big_endian>
186 Output_section*
187 Layout::layout(Relobj* object, unsigned int shndx, const char* name,
188                const elfcpp::Shdr<size, big_endian>& shdr, off_t* off)
189 {
190   if (!this->include_section(object, name, shdr))
191     return NULL;
192
193   // If we are not doing a relocateable link, choose the name to use
194   // for the output section.
195   size_t len = strlen(name);
196   if (!parameters->output_is_object())
197     name = Layout::output_section_name(name, &len);
198
199   // FIXME: Handle SHF_OS_NONCONFORMING here.
200
201   // Canonicalize the section name.
202   Stringpool::Key name_key;
203   name = this->namepool_.add(name, len, &name_key);
204
205   // Find the output section.  The output section is selected based on
206   // the section name, type, and flags.
207   Output_section* os = this->get_output_section(name, name_key,
208                                                 shdr.get_sh_type(),
209                                                 shdr.get_sh_flags());
210
211   // Special GNU handling of sections named .eh_frame.
212   if (!parameters->output_is_object()
213       && strcmp(name, ".eh_frame") == 0
214       && shdr.get_sh_size() > 0
215       && shdr.get_sh_type() == elfcpp::SHT_PROGBITS
216       && shdr.get_sh_flags() == elfcpp::SHF_ALLOC)
217     {
218       this->layout_eh_frame(object, shndx, name, shdr, os, off);
219       return os;
220     }
221
222   // FIXME: Handle SHF_LINK_ORDER somewhere.
223
224   *off = os->add_input_section(object, shndx, name, shdr);
225
226   return os;
227 }
228
229 // Special GNU handling of sections named .eh_frame.  They will
230 // normally hold exception frame data.
231
232 template<int size, bool big_endian>
233 void
234 Layout::layout_eh_frame(Relobj* object,
235                         unsigned int shndx,
236                         const char* name,
237                         const elfcpp::Shdr<size, big_endian>& shdr,
238                         Output_section* os, off_t* off)
239 {
240   if (this->eh_frame_section_ == NULL)
241     {
242       this->eh_frame_section_ = os;
243
244       if (this->options_.create_eh_frame_hdr())
245         {
246           Stringpool::Key hdr_name_key;
247           const char* hdr_name = this->namepool_.add(".eh_frame_hdr",
248                                                      &hdr_name_key);
249           Output_section* hdr_os =
250             this->get_output_section(hdr_name, hdr_name_key,
251                                      elfcpp::SHT_PROGBITS,
252                                      elfcpp::SHF_ALLOC);
253
254           Eh_frame_hdr* hdr_posd = new Eh_frame_hdr(os);
255           hdr_os->add_output_section_data(hdr_posd);
256
257           Output_segment* hdr_oseg =
258             new Output_segment(elfcpp::PT_GNU_EH_FRAME, elfcpp::PF_R);
259           this->segment_list_.push_back(hdr_oseg);
260           hdr_oseg->add_output_section(hdr_os, elfcpp::PF_R);
261         }
262     }
263
264   gold_assert(this->eh_frame_section_ == os);
265
266   *off = os->add_input_section(object, shndx, name, shdr);
267 }
268
269 // Add POSD to an output section using NAME, TYPE, and FLAGS.
270
271 void
272 Layout::add_output_section_data(const char* name, elfcpp::Elf_Word type,
273                                 elfcpp::Elf_Xword flags,
274                                 Output_section_data* posd)
275 {
276   // Canonicalize the name.
277   Stringpool::Key name_key;
278   name = this->namepool_.add(name, &name_key);
279
280   Output_section* os = this->get_output_section(name, name_key, type, flags);
281   os->add_output_section_data(posd);
282 }
283
284 // Map section flags to segment flags.
285
286 elfcpp::Elf_Word
287 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
288 {
289   elfcpp::Elf_Word ret = elfcpp::PF_R;
290   if ((flags & elfcpp::SHF_WRITE) != 0)
291     ret |= elfcpp::PF_W;
292   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
293     ret |= elfcpp::PF_X;
294   return ret;
295 }
296
297 // Make a new Output_section, and attach it to segments as
298 // appropriate.
299
300 Output_section*
301 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
302                             elfcpp::Elf_Xword flags)
303 {
304   Output_section* os = new Output_section(name, type, flags);
305   this->section_list_.push_back(os);
306
307   if ((flags & elfcpp::SHF_ALLOC) == 0)
308     this->unattached_section_list_.push_back(os);
309   else
310     {
311       // This output section goes into a PT_LOAD segment.
312
313       elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
314
315       // The only thing we really care about for PT_LOAD segments is
316       // whether or not they are writable, so that is how we search
317       // for them.  People who need segments sorted on some other
318       // basis will have to wait until we implement a mechanism for
319       // them to describe the segments they want.
320
321       Segment_list::const_iterator p;
322       for (p = this->segment_list_.begin();
323            p != this->segment_list_.end();
324            ++p)
325         {
326           if ((*p)->type() == elfcpp::PT_LOAD
327               && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
328             {
329               (*p)->add_output_section(os, seg_flags);
330               break;
331             }
332         }
333
334       if (p == this->segment_list_.end())
335         {
336           Output_segment* oseg = new Output_segment(elfcpp::PT_LOAD,
337                                                     seg_flags);
338           this->segment_list_.push_back(oseg);
339           oseg->add_output_section(os, seg_flags);
340         }
341
342       // If we see a loadable SHT_NOTE section, we create a PT_NOTE
343       // segment.
344       if (type == elfcpp::SHT_NOTE)
345         {
346           // See if we already have an equivalent PT_NOTE segment.
347           for (p = this->segment_list_.begin();
348                p != segment_list_.end();
349                ++p)
350             {
351               if ((*p)->type() == elfcpp::PT_NOTE
352                   && (((*p)->flags() & elfcpp::PF_W)
353                       == (seg_flags & elfcpp::PF_W)))
354                 {
355                   (*p)->add_output_section(os, seg_flags);
356                   break;
357                 }
358             }
359
360           if (p == this->segment_list_.end())
361             {
362               Output_segment* oseg = new Output_segment(elfcpp::PT_NOTE,
363                                                         seg_flags);
364               this->segment_list_.push_back(oseg);
365               oseg->add_output_section(os, seg_flags);
366             }
367         }
368
369       // If we see a loadable SHF_TLS section, we create a PT_TLS
370       // segment.  There can only be one such segment.
371       if ((flags & elfcpp::SHF_TLS) != 0)
372         {
373           if (this->tls_segment_ == NULL)
374             {
375               this->tls_segment_ = new Output_segment(elfcpp::PT_TLS,
376                                                       seg_flags);
377               this->segment_list_.push_back(this->tls_segment_);
378             }
379           this->tls_segment_->add_output_section(os, seg_flags);
380         }
381     }
382
383   return os;
384 }
385
386 // Create the dynamic sections which are needed before we read the
387 // relocs.
388
389 void
390 Layout::create_initial_dynamic_sections(const Input_objects* input_objects,
391                                         Symbol_table* symtab)
392 {
393   if (!input_objects->any_dynamic())
394     return;
395
396   const char* dynamic_name = this->namepool_.add(".dynamic", NULL);
397   this->dynamic_section_ = this->make_output_section(dynamic_name,
398                                                      elfcpp::SHT_DYNAMIC,
399                                                      (elfcpp::SHF_ALLOC
400                                                       | elfcpp::SHF_WRITE));
401
402   symtab->define_in_output_data(input_objects->target(), "_DYNAMIC", NULL,
403                                 this->dynamic_section_, 0, 0,
404                                 elfcpp::STT_OBJECT, elfcpp::STB_LOCAL,
405                                 elfcpp::STV_HIDDEN, 0, false, false);
406
407   this->dynamic_data_ =  new Output_data_dynamic(&this->dynpool_);
408
409   this->dynamic_section_->add_output_section_data(this->dynamic_data_);
410 }
411
412 // For each output section whose name can be represented as C symbol,
413 // define __start and __stop symbols for the section.  This is a GNU
414 // extension.
415
416 void
417 Layout::define_section_symbols(Symbol_table* symtab, const Target* target)
418 {
419   for (Section_list::const_iterator p = this->section_list_.begin();
420        p != this->section_list_.end();
421        ++p)
422     {
423       const char* const name = (*p)->name();
424       if (name[strspn(name,
425                       ("0123456789"
426                        "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
427                        "abcdefghijklmnopqrstuvwxyz"
428                        "_"))]
429           == '\0')
430         {
431           const std::string name_string(name);
432           const std::string start_name("__start_" + name_string);
433           const std::string stop_name("__stop_" + name_string);
434
435           symtab->define_in_output_data(target,
436                                         start_name.c_str(),
437                                         NULL, // version
438                                         *p,
439                                         0, // value
440                                         0, // symsize
441                                         elfcpp::STT_NOTYPE,
442                                         elfcpp::STB_GLOBAL,
443                                         elfcpp::STV_DEFAULT,
444                                         0, // nonvis
445                                         false, // offset_is_from_end
446                                         false); // only_if_ref
447
448           symtab->define_in_output_data(target,
449                                         stop_name.c_str(),
450                                         NULL, // version
451                                         *p,
452                                         0, // value
453                                         0, // symsize
454                                         elfcpp::STT_NOTYPE,
455                                         elfcpp::STB_GLOBAL,
456                                         elfcpp::STV_DEFAULT,
457                                         0, // nonvis
458                                         true, // offset_is_from_end
459                                         false); // only_if_ref
460         }
461     }
462 }
463
464 // Find the first read-only PT_LOAD segment, creating one if
465 // necessary.
466
467 Output_segment*
468 Layout::find_first_load_seg()
469 {
470   for (Segment_list::const_iterator p = this->segment_list_.begin();
471        p != this->segment_list_.end();
472        ++p)
473     {
474       if ((*p)->type() == elfcpp::PT_LOAD
475           && ((*p)->flags() & elfcpp::PF_R) != 0
476           && ((*p)->flags() & elfcpp::PF_W) == 0)
477         return *p;
478     }
479
480   Output_segment* load_seg = new Output_segment(elfcpp::PT_LOAD, elfcpp::PF_R);
481   this->segment_list_.push_back(load_seg);
482   return load_seg;
483 }
484
485 // Finalize the layout.  When this is called, we have created all the
486 // output sections and all the output segments which are based on
487 // input sections.  We have several things to do, and we have to do
488 // them in the right order, so that we get the right results correctly
489 // and efficiently.
490
491 // 1) Finalize the list of output segments and create the segment
492 // table header.
493
494 // 2) Finalize the dynamic symbol table and associated sections.
495
496 // 3) Determine the final file offset of all the output segments.
497
498 // 4) Determine the final file offset of all the SHF_ALLOC output
499 // sections.
500
501 // 5) Create the symbol table sections and the section name table
502 // section.
503
504 // 6) Finalize the symbol table: set symbol values to their final
505 // value and make a final determination of which symbols are going
506 // into the output symbol table.
507
508 // 7) Create the section table header.
509
510 // 8) Determine the final file offset of all the output sections which
511 // are not SHF_ALLOC, including the section table header.
512
513 // 9) Finalize the ELF file header.
514
515 // This function returns the size of the output file.
516
517 off_t
518 Layout::finalize(const Input_objects* input_objects, Symbol_table* symtab)
519 {
520   Target* const target = input_objects->target();
521
522   target->finalize_sections(this);
523
524   this->create_note_section();
525
526   Output_segment* phdr_seg = NULL;
527   if (input_objects->any_dynamic())
528     {
529       // There was a dynamic object in the link.  We need to create
530       // some information for the dynamic linker.
531
532       // Create the PT_PHDR segment which will hold the program
533       // headers.
534       phdr_seg = new Output_segment(elfcpp::PT_PHDR, elfcpp::PF_R);
535       this->segment_list_.push_back(phdr_seg);
536
537       // Create the dynamic symbol table, including the hash table.
538       Output_section* dynstr;
539       std::vector<Symbol*> dynamic_symbols;
540       unsigned int local_dynamic_count;
541       Versions versions;
542       this->create_dynamic_symtab(target, symtab, &dynstr,
543                                   &local_dynamic_count, &dynamic_symbols,
544                                   &versions);
545
546       // Create the .interp section to hold the name of the
547       // interpreter, and put it in a PT_INTERP segment.
548       this->create_interp(target);
549
550       // Finish the .dynamic section to hold the dynamic data, and put
551       // it in a PT_DYNAMIC segment.
552       this->finish_dynamic_section(input_objects, symtab);
553
554       // We should have added everything we need to the dynamic string
555       // table.
556       this->dynpool_.set_string_offsets();
557
558       // Create the version sections.  We can't do this until the
559       // dynamic string table is complete.
560       this->create_version_sections(&versions, local_dynamic_count,
561                                     dynamic_symbols, dynstr);
562     }
563
564   // FIXME: Handle PT_GNU_STACK.
565
566   Output_segment* load_seg = this->find_first_load_seg();
567
568   // Lay out the segment headers.
569   Output_segment_headers* segment_headers;
570   segment_headers = new Output_segment_headers(this->segment_list_);
571   load_seg->add_initial_output_data(segment_headers);
572   this->special_output_list_.push_back(segment_headers);
573   if (phdr_seg != NULL)
574     phdr_seg->add_initial_output_data(segment_headers);
575
576   // Lay out the file header.
577   Output_file_header* file_header;
578   file_header = new Output_file_header(target, symtab, segment_headers);
579   load_seg->add_initial_output_data(file_header);
580   this->special_output_list_.push_back(file_header);
581
582   // We set the output section indexes in set_segment_offsets and
583   // set_section_offsets.
584   unsigned int shndx = 1;
585
586   // Set the file offsets of all the segments, and all the sections
587   // they contain.
588   off_t off = this->set_segment_offsets(target, load_seg, &shndx);
589
590   // Create the symbol table sections.
591   this->create_symtab_sections(input_objects, symtab, &off);
592
593   // Create the .shstrtab section.
594   Output_section* shstrtab_section = this->create_shstrtab();
595
596   // Set the file offsets of all the sections not associated with
597   // segments.
598   off = this->set_section_offsets(off, &shndx);
599
600   // Create the section table header.
601   Output_section_headers* oshdrs = this->create_shdrs(&off);
602
603   file_header->set_section_info(oshdrs, shstrtab_section);
604
605   // Now we know exactly where everything goes in the output file.
606   Output_data::layout_complete();
607
608   return off;
609 }
610
611 // Create a .note section for an executable or shared library.  This
612 // records the version of gold used to create the binary.
613
614 void
615 Layout::create_note_section()
616 {
617   if (parameters->output_is_object())
618     return;
619
620   const int size = parameters->get_size();
621
622   // The contents of the .note section.
623   const char* name = "GNU";
624   std::string desc(std::string("gold ") + gold::get_version_string());
625   size_t namesz = strlen(name) + 1;
626   size_t aligned_namesz = align_address(namesz, size / 8);
627   size_t descsz = desc.length() + 1;
628   size_t aligned_descsz = align_address(descsz, size / 8);
629   const int note_type = 4;
630
631   size_t notesz = 3 * (size / 8) + aligned_namesz + aligned_descsz;
632
633   unsigned char buffer[128];
634   gold_assert(sizeof buffer >= notesz);
635   memset(buffer, 0, notesz);
636
637   bool is_big_endian = parameters->is_big_endian();
638
639   if (size == 32)
640     {
641       if (!is_big_endian)
642         {
643           elfcpp::Swap<32, false>::writeval(buffer, namesz);
644           elfcpp::Swap<32, false>::writeval(buffer + 4, descsz);
645           elfcpp::Swap<32, false>::writeval(buffer + 8, note_type);
646         }
647       else
648         {
649           elfcpp::Swap<32, true>::writeval(buffer, namesz);
650           elfcpp::Swap<32, true>::writeval(buffer + 4, descsz);
651           elfcpp::Swap<32, true>::writeval(buffer + 8, note_type);
652         }
653     }
654   else if (size == 64)
655     {
656       if (!is_big_endian)
657         {
658           elfcpp::Swap<64, false>::writeval(buffer, namesz);
659           elfcpp::Swap<64, false>::writeval(buffer + 8, descsz);
660           elfcpp::Swap<64, false>::writeval(buffer + 16, note_type);
661         }
662       else
663         {
664           elfcpp::Swap<64, true>::writeval(buffer, namesz);
665           elfcpp::Swap<64, true>::writeval(buffer + 8, descsz);
666           elfcpp::Swap<64, true>::writeval(buffer + 16, note_type);
667         }
668     }
669   else
670     gold_unreachable();
671
672   memcpy(buffer + 3 * (size / 8), name, namesz);
673   memcpy(buffer + 3 * (size / 8) + aligned_namesz, desc.data(), descsz);
674
675   const char* note_name = this->namepool_.add(".note", NULL);
676   Output_section* os = this->make_output_section(note_name,
677                                                  elfcpp::SHT_NOTE,
678                                                  0);
679   Output_section_data* posd = new Output_data_const(buffer, notesz,
680                                                     size / 8);
681   os->add_output_section_data(posd);
682 }
683
684 // Return whether SEG1 should be before SEG2 in the output file.  This
685 // is based entirely on the segment type and flags.  When this is
686 // called the segment addresses has normally not yet been set.
687
688 bool
689 Layout::segment_precedes(const Output_segment* seg1,
690                          const Output_segment* seg2)
691 {
692   elfcpp::Elf_Word type1 = seg1->type();
693   elfcpp::Elf_Word type2 = seg2->type();
694
695   // The single PT_PHDR segment is required to precede any loadable
696   // segment.  We simply make it always first.
697   if (type1 == elfcpp::PT_PHDR)
698     {
699       gold_assert(type2 != elfcpp::PT_PHDR);
700       return true;
701     }
702   if (type2 == elfcpp::PT_PHDR)
703     return false;
704
705   // The single PT_INTERP segment is required to precede any loadable
706   // segment.  We simply make it always second.
707   if (type1 == elfcpp::PT_INTERP)
708     {
709       gold_assert(type2 != elfcpp::PT_INTERP);
710       return true;
711     }
712   if (type2 == elfcpp::PT_INTERP)
713     return false;
714
715   // We then put PT_LOAD segments before any other segments.
716   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
717     return true;
718   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
719     return false;
720
721   // We put the PT_TLS segment last, because that is where the dynamic
722   // linker expects to find it (this is just for efficiency; other
723   // positions would also work correctly).
724   if (type1 == elfcpp::PT_TLS && type2 != elfcpp::PT_TLS)
725     return false;
726   if (type2 == elfcpp::PT_TLS && type1 != elfcpp::PT_TLS)
727     return true;
728
729   const elfcpp::Elf_Word flags1 = seg1->flags();
730   const elfcpp::Elf_Word flags2 = seg2->flags();
731
732   // The order of non-PT_LOAD segments is unimportant.  We simply sort
733   // by the numeric segment type and flags values.  There should not
734   // be more than one segment with the same type and flags.
735   if (type1 != elfcpp::PT_LOAD)
736     {
737       if (type1 != type2)
738         return type1 < type2;
739       gold_assert(flags1 != flags2);
740       return flags1 < flags2;
741     }
742
743   // We sort PT_LOAD segments based on the flags.  Readonly segments
744   // come before writable segments.  Then executable segments come
745   // before non-executable segments.  Then the unlikely case of a
746   // non-readable segment comes before the normal case of a readable
747   // segment.  If there are multiple segments with the same type and
748   // flags, we require that the address be set, and we sort by
749   // virtual address and then physical address.
750   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
751     return (flags1 & elfcpp::PF_W) == 0;
752   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
753     return (flags1 & elfcpp::PF_X) != 0;
754   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
755     return (flags1 & elfcpp::PF_R) == 0;
756
757   uint64_t vaddr1 = seg1->vaddr();
758   uint64_t vaddr2 = seg2->vaddr();
759   if (vaddr1 != vaddr2)
760     return vaddr1 < vaddr2;
761
762   uint64_t paddr1 = seg1->paddr();
763   uint64_t paddr2 = seg2->paddr();
764   gold_assert(paddr1 != paddr2);
765   return paddr1 < paddr2;
766 }
767
768 // Set the file offsets of all the segments, and all the sections they
769 // contain.  They have all been created.  LOAD_SEG must be be laid out
770 // first.  Return the offset of the data to follow.
771
772 off_t
773 Layout::set_segment_offsets(const Target* target, Output_segment* load_seg,
774                             unsigned int *pshndx)
775 {
776   // Sort them into the final order.
777   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
778             Layout::Compare_segments());
779
780   // Find the PT_LOAD segments, and set their addresses and offsets
781   // and their section's addresses and offsets.
782   uint64_t addr = target->text_segment_address();
783   off_t off = 0;
784   bool was_readonly = false;
785   for (Segment_list::iterator p = this->segment_list_.begin();
786        p != this->segment_list_.end();
787        ++p)
788     {
789       if ((*p)->type() == elfcpp::PT_LOAD)
790         {
791           if (load_seg != NULL && load_seg != *p)
792             gold_unreachable();
793           load_seg = NULL;
794
795           // If the last segment was readonly, and this one is not,
796           // then skip the address forward one page, maintaining the
797           // same position within the page.  This lets us store both
798           // segments overlapping on a single page in the file, but
799           // the loader will put them on different pages in memory.
800
801           uint64_t orig_addr = addr;
802           uint64_t orig_off = off;
803
804           uint64_t aligned_addr = addr;
805           uint64_t abi_pagesize = target->abi_pagesize();
806
807           // FIXME: This should depend on the -n and -N options.
808           (*p)->set_minimum_addralign(target->common_pagesize());
809
810           if (was_readonly && ((*p)->flags() & elfcpp::PF_W) != 0)
811             {
812               uint64_t align = (*p)->addralign();
813
814               addr = align_address(addr, align);
815               aligned_addr = addr;
816               if ((addr & (abi_pagesize - 1)) != 0)
817                 addr = addr + abi_pagesize;
818             }
819
820           unsigned int shndx_hold = *pshndx;
821           off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
822           uint64_t new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
823
824           // Now that we know the size of this segment, we may be able
825           // to save a page in memory, at the cost of wasting some
826           // file space, by instead aligning to the start of a new
827           // page.  Here we use the real machine page size rather than
828           // the ABI mandated page size.
829
830           if (aligned_addr != addr)
831             {
832               uint64_t common_pagesize = target->common_pagesize();
833               uint64_t first_off = (common_pagesize
834                                     - (aligned_addr
835                                        & (common_pagesize - 1)));
836               uint64_t last_off = new_addr & (common_pagesize - 1);
837               if (first_off > 0
838                   && last_off > 0
839                   && ((aligned_addr & ~ (common_pagesize - 1))
840                       != (new_addr & ~ (common_pagesize - 1)))
841                   && first_off + last_off <= common_pagesize)
842                 {
843                   *pshndx = shndx_hold;
844                   addr = align_address(aligned_addr, common_pagesize);
845                   off = orig_off + ((addr - orig_addr) & (abi_pagesize - 1));
846                   new_addr = (*p)->set_section_addresses(addr, &off, pshndx);
847                 }
848             }
849
850           addr = new_addr;
851
852           if (((*p)->flags() & elfcpp::PF_W) == 0)
853             was_readonly = true;
854         }
855     }
856
857   // Handle the non-PT_LOAD segments, setting their offsets from their
858   // section's offsets.
859   for (Segment_list::iterator p = this->segment_list_.begin();
860        p != this->segment_list_.end();
861        ++p)
862     {
863       if ((*p)->type() != elfcpp::PT_LOAD)
864         (*p)->set_offset();
865     }
866
867   return off;
868 }
869
870 // Set the file offset of all the sections not associated with a
871 // segment.
872
873 off_t
874 Layout::set_section_offsets(off_t off, unsigned int* pshndx)
875 {
876   for (Section_list::iterator p = this->unattached_section_list_.begin();
877        p != this->unattached_section_list_.end();
878        ++p)
879     {
880       (*p)->set_out_shndx(*pshndx);
881       ++*pshndx;
882       if ((*p)->offset() != -1)
883         continue;
884       off = align_address(off, (*p)->addralign());
885       (*p)->set_address(0, off);
886       off += (*p)->data_size();
887     }
888   return off;
889 }
890
891 // Create the symbol table sections.  Here we also set the final
892 // values of the symbols.  At this point all the loadable sections are
893 // fully laid out.
894
895 void
896 Layout::create_symtab_sections(const Input_objects* input_objects,
897                                Symbol_table* symtab,
898                                off_t* poff)
899 {
900   int symsize;
901   unsigned int align;
902   if (parameters->get_size() == 32)
903     {
904       symsize = elfcpp::Elf_sizes<32>::sym_size;
905       align = 4;
906     }
907   else if (parameters->get_size() == 64)
908     {
909       symsize = elfcpp::Elf_sizes<64>::sym_size;
910       align = 8;
911     }
912   else
913     gold_unreachable();
914
915   off_t off = *poff;
916   off = align_address(off, align);
917   off_t startoff = off;
918
919   // Save space for the dummy symbol at the start of the section.  We
920   // never bother to write this out--it will just be left as zero.
921   off += symsize;
922   unsigned int local_symbol_index = 1;
923
924   // Add STT_SECTION symbols for each Output section which needs one.
925   for (Section_list::iterator p = this->section_list_.begin();
926        p != this->section_list_.end();
927        ++p)
928     {
929       if (!(*p)->needs_symtab_index())
930         (*p)->set_symtab_index(-1U);
931       else
932         {
933           (*p)->set_symtab_index(local_symbol_index);
934           ++local_symbol_index;
935           off += symsize;
936         }
937     }
938
939   for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
940        p != input_objects->relobj_end();
941        ++p)
942     {
943       Task_lock_obj<Object> tlo(**p);
944       unsigned int index = (*p)->finalize_local_symbols(local_symbol_index,
945                                                         off,
946                                                         &this->sympool_);
947       off += (index - local_symbol_index) * symsize;
948       local_symbol_index = index;
949     }
950
951   unsigned int local_symcount = local_symbol_index;
952   gold_assert(local_symcount * symsize == off - startoff);
953
954   off_t dynoff;
955   size_t dyn_global_index;
956   size_t dyncount;
957   if (this->dynsym_section_ == NULL)
958     {
959       dynoff = 0;
960       dyn_global_index = 0;
961       dyncount = 0;
962     }
963   else
964     {
965       dyn_global_index = this->dynsym_section_->info();
966       off_t locsize = dyn_global_index * this->dynsym_section_->entsize();
967       dynoff = this->dynsym_section_->offset() + locsize;
968       dyncount = (this->dynsym_section_->data_size() - locsize) / symsize;
969       gold_assert(static_cast<off_t>(dyncount * symsize)
970                   == this->dynsym_section_->data_size() - locsize);
971     }
972
973   off = symtab->finalize(local_symcount, off, dynoff, dyn_global_index,
974                          dyncount, &this->sympool_);
975
976   this->sympool_.set_string_offsets();
977
978   const char* symtab_name = this->namepool_.add(".symtab", NULL);
979   Output_section* osymtab = this->make_output_section(symtab_name,
980                                                       elfcpp::SHT_SYMTAB,
981                                                       0);
982   this->symtab_section_ = osymtab;
983
984   Output_section_data* pos = new Output_data_space(off - startoff,
985                                                    align);
986   osymtab->add_output_section_data(pos);
987
988   const char* strtab_name = this->namepool_.add(".strtab", NULL);
989   Output_section* ostrtab = this->make_output_section(strtab_name,
990                                                       elfcpp::SHT_STRTAB,
991                                                       0);
992
993   Output_section_data* pstr = new Output_data_strtab(&this->sympool_);
994   ostrtab->add_output_section_data(pstr);
995
996   osymtab->set_address(0, startoff);
997   osymtab->set_link_section(ostrtab);
998   osymtab->set_info(local_symcount);
999   osymtab->set_entsize(symsize);
1000
1001   *poff = off;
1002 }
1003
1004 // Create the .shstrtab section, which holds the names of the
1005 // sections.  At the time this is called, we have created all the
1006 // output sections except .shstrtab itself.
1007
1008 Output_section*
1009 Layout::create_shstrtab()
1010 {
1011   // FIXME: We don't need to create a .shstrtab section if we are
1012   // stripping everything.
1013
1014   const char* name = this->namepool_.add(".shstrtab", NULL);
1015
1016   this->namepool_.set_string_offsets();
1017
1018   Output_section* os = this->make_output_section(name, elfcpp::SHT_STRTAB, 0);
1019
1020   Output_section_data* posd = new Output_data_strtab(&this->namepool_);
1021   os->add_output_section_data(posd);
1022
1023   return os;
1024 }
1025
1026 // Create the section headers.  SIZE is 32 or 64.  OFF is the file
1027 // offset.
1028
1029 Output_section_headers*
1030 Layout::create_shdrs(off_t* poff)
1031 {
1032   Output_section_headers* oshdrs;
1033   oshdrs = new Output_section_headers(this,
1034                                       &this->segment_list_,
1035                                       &this->unattached_section_list_,
1036                                       &this->namepool_);
1037   off_t off = align_address(*poff, oshdrs->addralign());
1038   oshdrs->set_address(0, off);
1039   off += oshdrs->data_size();
1040   *poff = off;
1041   this->special_output_list_.push_back(oshdrs);
1042   return oshdrs;
1043 }
1044
1045 // Create the dynamic symbol table.
1046
1047 void
1048 Layout::create_dynamic_symtab(const Target* target, Symbol_table* symtab,
1049                               Output_section **pdynstr,
1050                               unsigned int* plocal_dynamic_count,
1051                               std::vector<Symbol*>* pdynamic_symbols,
1052                               Versions* pversions)
1053 {
1054   // Count all the symbols in the dynamic symbol table, and set the
1055   // dynamic symbol indexes.
1056
1057   // Skip symbol 0, which is always all zeroes.
1058   unsigned int index = 1;
1059
1060   // Add STT_SECTION symbols for each Output section which needs one.
1061   for (Section_list::iterator p = this->section_list_.begin();
1062        p != this->section_list_.end();
1063        ++p)
1064     {
1065       if (!(*p)->needs_dynsym_index())
1066         (*p)->set_dynsym_index(-1U);
1067       else
1068         {
1069           (*p)->set_dynsym_index(index);
1070           ++index;
1071         }
1072     }
1073
1074   // FIXME: Some targets apparently require local symbols in the
1075   // dynamic symbol table.  Here is where we will have to count them,
1076   // and set the dynamic symbol indexes, and add the names to
1077   // this->dynpool_.
1078
1079   unsigned int local_symcount = index;
1080   *plocal_dynamic_count = local_symcount;
1081
1082   // FIXME: We have to tell set_dynsym_indexes whether the
1083   // -E/--export-dynamic option was used.
1084   index = symtab->set_dynsym_indexes(&this->options_, target, index,
1085                                      pdynamic_symbols, &this->dynpool_,
1086                                      pversions);
1087
1088   int symsize;
1089   unsigned int align;
1090   const int size = parameters->get_size();
1091   if (size == 32)
1092     {
1093       symsize = elfcpp::Elf_sizes<32>::sym_size;
1094       align = 4;
1095     }
1096   else if (size == 64)
1097     {
1098       symsize = elfcpp::Elf_sizes<64>::sym_size;
1099       align = 8;
1100     }
1101   else
1102     gold_unreachable();
1103
1104   // Create the dynamic symbol table section.
1105
1106   const char* dynsym_name = this->namepool_.add(".dynsym", NULL);
1107   Output_section* dynsym = this->make_output_section(dynsym_name,
1108                                                      elfcpp::SHT_DYNSYM,
1109                                                      elfcpp::SHF_ALLOC);
1110
1111   Output_section_data* odata = new Output_data_space(index * symsize,
1112                                                      align);
1113   dynsym->add_output_section_data(odata);
1114
1115   dynsym->set_info(local_symcount);
1116   dynsym->set_entsize(symsize);
1117   dynsym->set_addralign(align);
1118
1119   this->dynsym_section_ = dynsym;
1120
1121   Output_data_dynamic* const odyn = this->dynamic_data_;
1122   odyn->add_section_address(elfcpp::DT_SYMTAB, dynsym);
1123   odyn->add_constant(elfcpp::DT_SYMENT, symsize);
1124
1125   // Create the dynamic string table section.
1126
1127   const char* dynstr_name = this->namepool_.add(".dynstr", NULL);
1128   Output_section* dynstr = this->make_output_section(dynstr_name,
1129                                                      elfcpp::SHT_STRTAB,
1130                                                      elfcpp::SHF_ALLOC);
1131
1132   Output_section_data* strdata = new Output_data_strtab(&this->dynpool_);
1133   dynstr->add_output_section_data(strdata);
1134
1135   dynsym->set_link_section(dynstr);
1136   this->dynamic_section_->set_link_section(dynstr);
1137
1138   odyn->add_section_address(elfcpp::DT_STRTAB, dynstr);
1139   odyn->add_section_size(elfcpp::DT_STRSZ, dynstr);
1140
1141   *pdynstr = dynstr;
1142
1143   // Create the hash tables.
1144
1145   // FIXME: We need an option to create a GNU hash table.
1146
1147   unsigned char* phash;
1148   unsigned int hashlen;
1149   Dynobj::create_elf_hash_table(*pdynamic_symbols, local_symcount,
1150                                 &phash, &hashlen);
1151
1152   const char* hash_name = this->namepool_.add(".hash", NULL);
1153   Output_section* hashsec = this->make_output_section(hash_name,
1154                                                       elfcpp::SHT_HASH,
1155                                                       elfcpp::SHF_ALLOC);
1156
1157   Output_section_data* hashdata = new Output_data_const_buffer(phash,
1158                                                                hashlen,
1159                                                                align);
1160   hashsec->add_output_section_data(hashdata);
1161
1162   hashsec->set_link_section(dynsym);
1163   hashsec->set_entsize(4);
1164
1165   odyn->add_section_address(elfcpp::DT_HASH, hashsec);
1166 }
1167
1168 // Create the version sections.
1169
1170 void
1171 Layout::create_version_sections(const Versions* versions,
1172                                 unsigned int local_symcount,
1173                                 const std::vector<Symbol*>& dynamic_symbols,
1174                                 const Output_section* dynstr)
1175 {
1176   if (!versions->any_defs() && !versions->any_needs())
1177     return;
1178
1179   if (parameters->get_size() == 32)
1180     {
1181       if (parameters->is_big_endian())
1182         {
1183 #ifdef HAVE_TARGET_32_BIG
1184           this->sized_create_version_sections
1185               SELECT_SIZE_ENDIAN_NAME(32, true)(
1186                   versions, local_symcount, dynamic_symbols, dynstr
1187                   SELECT_SIZE_ENDIAN(32, true));
1188 #else
1189           gold_unreachable();
1190 #endif
1191         }
1192       else
1193         {
1194 #ifdef HAVE_TARGET_32_LITTLE
1195           this->sized_create_version_sections
1196               SELECT_SIZE_ENDIAN_NAME(32, false)(
1197                   versions, local_symcount, dynamic_symbols, dynstr
1198                   SELECT_SIZE_ENDIAN(32, false));
1199 #else
1200           gold_unreachable();
1201 #endif
1202         }
1203     }
1204   else if (parameters->get_size() == 64)
1205     {
1206       if (parameters->is_big_endian())
1207         {
1208 #ifdef HAVE_TARGET_64_BIG
1209           this->sized_create_version_sections
1210               SELECT_SIZE_ENDIAN_NAME(64, true)(
1211                   versions, local_symcount, dynamic_symbols, dynstr
1212                   SELECT_SIZE_ENDIAN(64, true));
1213 #else
1214           gold_unreachable();
1215 #endif
1216         }
1217       else
1218         {
1219 #ifdef HAVE_TARGET_64_LITTLE
1220           this->sized_create_version_sections
1221               SELECT_SIZE_ENDIAN_NAME(64, false)(
1222                   versions, local_symcount, dynamic_symbols, dynstr
1223                   SELECT_SIZE_ENDIAN(64, false));
1224 #else
1225           gold_unreachable();
1226 #endif
1227         }
1228     }
1229   else
1230     gold_unreachable();
1231 }
1232
1233 // Create the version sections, sized version.
1234
1235 template<int size, bool big_endian>
1236 void
1237 Layout::sized_create_version_sections(
1238     const Versions* versions,
1239     unsigned int local_symcount,
1240     const std::vector<Symbol*>& dynamic_symbols,
1241     const Output_section* dynstr
1242     ACCEPT_SIZE_ENDIAN)
1243 {
1244   const char* vname = this->namepool_.add(".gnu.version", NULL);
1245   Output_section* vsec = this->make_output_section(vname,
1246                                                    elfcpp::SHT_GNU_versym,
1247                                                    elfcpp::SHF_ALLOC);
1248
1249   unsigned char* vbuf;
1250   unsigned int vsize;
1251   versions->symbol_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1252       &this->dynpool_, local_symcount, dynamic_symbols, &vbuf, &vsize
1253       SELECT_SIZE_ENDIAN(size, big_endian));
1254
1255   Output_section_data* vdata = new Output_data_const_buffer(vbuf, vsize, 2);
1256
1257   vsec->add_output_section_data(vdata);
1258   vsec->set_entsize(2);
1259   vsec->set_link_section(this->dynsym_section_);
1260
1261   Output_data_dynamic* const odyn = this->dynamic_data_;
1262   odyn->add_section_address(elfcpp::DT_VERSYM, vsec);
1263
1264   if (versions->any_defs())
1265     {
1266       const char* vdname = this->namepool_.add(".gnu.version_d", NULL);
1267       Output_section *vdsec;
1268       vdsec = this->make_output_section(vdname, elfcpp::SHT_GNU_verdef,
1269                                         elfcpp::SHF_ALLOC);
1270
1271       unsigned char* vdbuf;
1272       unsigned int vdsize;
1273       unsigned int vdentries;
1274       versions->def_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)(
1275           &this->dynpool_, &vdbuf, &vdsize, &vdentries
1276           SELECT_SIZE_ENDIAN(size, big_endian));
1277
1278       Output_section_data* vddata = new Output_data_const_buffer(vdbuf,
1279                                                                  vdsize,
1280                                                                  4);
1281
1282       vdsec->add_output_section_data(vddata);
1283       vdsec->set_link_section(dynstr);
1284       vdsec->set_info(vdentries);
1285
1286       odyn->add_section_address(elfcpp::DT_VERDEF, vdsec);
1287       odyn->add_constant(elfcpp::DT_VERDEFNUM, vdentries);
1288     }
1289
1290   if (versions->any_needs())
1291     {
1292       const char* vnname = this->namepool_.add(".gnu.version_r", NULL);
1293       Output_section* vnsec;
1294       vnsec = this->make_output_section(vnname, elfcpp::SHT_GNU_verneed,
1295                                         elfcpp::SHF_ALLOC);
1296
1297       unsigned char* vnbuf;
1298       unsigned int vnsize;
1299       unsigned int vnentries;
1300       versions->need_section_contents SELECT_SIZE_ENDIAN_NAME(size, big_endian)
1301         (&this->dynpool_, &vnbuf, &vnsize, &vnentries
1302          SELECT_SIZE_ENDIAN(size, big_endian));
1303
1304       Output_section_data* vndata = new Output_data_const_buffer(vnbuf,
1305                                                                  vnsize,
1306                                                                  4);
1307
1308       vnsec->add_output_section_data(vndata);
1309       vnsec->set_link_section(dynstr);
1310       vnsec->set_info(vnentries);
1311
1312       odyn->add_section_address(elfcpp::DT_VERNEED, vnsec);
1313       odyn->add_constant(elfcpp::DT_VERNEEDNUM, vnentries);
1314     }
1315 }
1316
1317 // Create the .interp section and PT_INTERP segment.
1318
1319 void
1320 Layout::create_interp(const Target* target)
1321 {
1322   const char* interp = this->options_.dynamic_linker();
1323   if (interp == NULL)
1324     {
1325       interp = target->dynamic_linker();
1326       gold_assert(interp != NULL);
1327     }
1328
1329   size_t len = strlen(interp) + 1;
1330
1331   Output_section_data* odata = new Output_data_const(interp, len, 1);
1332
1333   const char* interp_name = this->namepool_.add(".interp", NULL);
1334   Output_section* osec = this->make_output_section(interp_name,
1335                                                    elfcpp::SHT_PROGBITS,
1336                                                    elfcpp::SHF_ALLOC);
1337   osec->add_output_section_data(odata);
1338
1339   Output_segment* oseg = new Output_segment(elfcpp::PT_INTERP, elfcpp::PF_R);
1340   this->segment_list_.push_back(oseg);
1341   oseg->add_initial_output_section(osec, elfcpp::PF_R);
1342 }
1343
1344 // Finish the .dynamic section and PT_DYNAMIC segment.
1345
1346 void
1347 Layout::finish_dynamic_section(const Input_objects* input_objects,
1348                                const Symbol_table* symtab)
1349 {
1350   Output_segment* oseg = new Output_segment(elfcpp::PT_DYNAMIC,
1351                                             elfcpp::PF_R | elfcpp::PF_W);
1352   this->segment_list_.push_back(oseg);
1353   oseg->add_initial_output_section(this->dynamic_section_,
1354                                    elfcpp::PF_R | elfcpp::PF_W);
1355
1356   Output_data_dynamic* const odyn = this->dynamic_data_;
1357
1358   for (Input_objects::Dynobj_iterator p = input_objects->dynobj_begin();
1359        p != input_objects->dynobj_end();
1360        ++p)
1361     {
1362       // FIXME: Handle --as-needed.
1363       odyn->add_string(elfcpp::DT_NEEDED, (*p)->soname());
1364     }
1365
1366   // FIXME: Support --init and --fini.
1367   Symbol* sym = symtab->lookup("_init");
1368   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1369     odyn->add_symbol(elfcpp::DT_INIT, sym);
1370
1371   sym = symtab->lookup("_fini");
1372   if (sym != NULL && sym->is_defined() && !sym->is_from_dynobj())
1373     odyn->add_symbol(elfcpp::DT_FINI, sym);
1374
1375   // FIXME: Support DT_INIT_ARRAY and DT_FINI_ARRAY.
1376
1377   // Add a DT_RPATH entry if needed.
1378   const General_options::Dir_list& rpath(this->options_.rpath());
1379   if (!rpath.empty())
1380     {
1381       std::string rpath_val;
1382       for (General_options::Dir_list::const_iterator p = rpath.begin();
1383            p != rpath.end();
1384            ++p)
1385         {
1386           if (rpath_val.empty())
1387             rpath_val = p->name();
1388           else
1389             {
1390               // Eliminate duplicates.
1391               General_options::Dir_list::const_iterator q;
1392               for (q = rpath.begin(); q != p; ++q)
1393                 if (q->name() == p->name())
1394                   break;
1395               if (q == p)
1396                 {
1397                   rpath_val += ':';
1398                   rpath_val += p->name();
1399                 }
1400             }
1401         }
1402
1403       odyn->add_string(elfcpp::DT_RPATH, rpath_val);
1404     }
1405 }
1406
1407 // The mapping of .gnu.linkonce section names to real section names.
1408
1409 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t, sizeof(t) - 1 }
1410 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
1411 {
1412   MAPPING_INIT("d.rel.ro", ".data.rel.ro"),     // Must be before "d".
1413   MAPPING_INIT("t", ".text"),
1414   MAPPING_INIT("r", ".rodata"),
1415   MAPPING_INIT("d", ".data"),
1416   MAPPING_INIT("b", ".bss"),
1417   MAPPING_INIT("s", ".sdata"),
1418   MAPPING_INIT("sb", ".sbss"),
1419   MAPPING_INIT("s2", ".sdata2"),
1420   MAPPING_INIT("sb2", ".sbss2"),
1421   MAPPING_INIT("wi", ".debug_info"),
1422   MAPPING_INIT("td", ".tdata"),
1423   MAPPING_INIT("tb", ".tbss"),
1424   MAPPING_INIT("lr", ".lrodata"),
1425   MAPPING_INIT("l", ".ldata"),
1426   MAPPING_INIT("lb", ".lbss"),
1427 };
1428 #undef MAPPING_INIT
1429
1430 const int Layout::linkonce_mapping_count =
1431   sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
1432
1433 // Return the name of the output section to use for a .gnu.linkonce
1434 // section.  This is based on the default ELF linker script of the old
1435 // GNU linker.  For example, we map a name like ".gnu.linkonce.t.foo"
1436 // to ".text".  Set *PLEN to the length of the name.  *PLEN is
1437 // initialized to the length of NAME.
1438
1439 const char*
1440 Layout::linkonce_output_name(const char* name, size_t *plen)
1441 {
1442   const char* s = name + sizeof(".gnu.linkonce") - 1;
1443   if (*s != '.')
1444     return name;
1445   ++s;
1446   const Linkonce_mapping* plm = linkonce_mapping;
1447   for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
1448     {
1449       if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
1450         {
1451           *plen = plm->tolen;
1452           return plm->to;
1453         }
1454     }
1455   return name;
1456 }
1457
1458 // Choose the output section name to use given an input section name.
1459 // Set *PLEN to the length of the name.  *PLEN is initialized to the
1460 // length of NAME.
1461
1462 const char*
1463 Layout::output_section_name(const char* name, size_t* plen)
1464 {
1465   if (Layout::is_linkonce(name))
1466     {
1467       // .gnu.linkonce sections are laid out as though they were named
1468       // for the sections are placed into.
1469       return Layout::linkonce_output_name(name, plen);
1470     }
1471
1472   // If the section name has no '.', or only an initial '.', we use
1473   // the name unchanged (i.e., ".text" is unchanged).
1474
1475   // Otherwise, if the section name does not include ".rel", we drop
1476   // the last '.'  and everything that follows (i.e., ".text.XXX"
1477   // becomes ".text").
1478
1479   // Otherwise, if the section name has zero or one '.' after the
1480   // ".rel", we use the name unchanged (i.e., ".rel.text" is
1481   // unchanged).
1482
1483   // Otherwise, we drop the last '.' and everything that follows
1484   // (i.e., ".rel.text.XXX" becomes ".rel.text").
1485
1486   const char* s = name;
1487   if (*s == '.')
1488     ++s;
1489   const char* sdot = strchr(s, '.');
1490   if (sdot == NULL)
1491     return name;
1492
1493   const char* srel = strstr(s, ".rel");
1494   if (srel == NULL)
1495     {
1496       *plen = sdot - name;
1497       return name;
1498     }
1499
1500   sdot = strchr(srel + 1, '.');
1501   if (sdot == NULL)
1502     return name;
1503   sdot = strchr(sdot + 1, '.');
1504   if (sdot == NULL)
1505     return name;
1506
1507   *plen = sdot - name;
1508   return name;
1509 }
1510
1511 // Record the signature of a comdat section, and return whether to
1512 // include it in the link.  If GROUP is true, this is a regular
1513 // section group.  If GROUP is false, this is a group signature
1514 // derived from the name of a linkonce section.  We want linkonce
1515 // signatures and group signatures to block each other, but we don't
1516 // want a linkonce signature to block another linkonce signature.
1517
1518 bool
1519 Layout::add_comdat(const char* signature, bool group)
1520 {
1521   std::string sig(signature);
1522   std::pair<Signatures::iterator, bool> ins(
1523     this->signatures_.insert(std::make_pair(sig, group)));
1524
1525   if (ins.second)
1526     {
1527       // This is the first time we've seen this signature.
1528       return true;
1529     }
1530
1531   if (ins.first->second)
1532     {
1533       // We've already seen a real section group with this signature.
1534       return false;
1535     }
1536   else if (group)
1537     {
1538       // This is a real section group, and we've already seen a
1539       // linkonce section with this signature.  Record that we've seen
1540       // a section group, and don't include this section group.
1541       ins.first->second = true;
1542       return false;
1543     }
1544   else
1545     {
1546       // We've already seen a linkonce section and this is a linkonce
1547       // section.  These don't block each other--this may be the same
1548       // symbol name with different section types.
1549       return true;
1550     }
1551 }
1552
1553 // Write out data not associated with a section or the symbol table.
1554
1555 void
1556 Layout::write_data(const Symbol_table* symtab, Output_file* of) const
1557 {
1558   const Output_section* symtab_section = this->symtab_section_;
1559   for (Section_list::const_iterator p = this->section_list_.begin();
1560        p != this->section_list_.end();
1561        ++p)
1562     {
1563       if ((*p)->needs_symtab_index())
1564         {
1565           gold_assert(symtab_section != NULL);
1566           unsigned int index = (*p)->symtab_index();
1567           gold_assert(index > 0 && index != -1U);
1568           off_t off = (symtab_section->offset()
1569                        + index * symtab_section->entsize());
1570           symtab->write_section_symbol(*p, of, off);
1571         }
1572     }
1573
1574   const Output_section* dynsym_section = this->dynsym_section_;
1575   for (Section_list::const_iterator p = this->section_list_.begin();
1576        p != this->section_list_.end();
1577        ++p)
1578     {
1579       if ((*p)->needs_dynsym_index())
1580         {
1581           gold_assert(dynsym_section != NULL);
1582           unsigned int index = (*p)->dynsym_index();
1583           gold_assert(index > 0 && index != -1U);
1584           off_t off = (dynsym_section->offset()
1585                        + index * dynsym_section->entsize());
1586           symtab->write_section_symbol(*p, of, off);
1587         }
1588     }
1589
1590   // Write out the Output_sections.  Most won't have anything to
1591   // write, since most of the data will come from input sections which
1592   // are handled elsewhere.  But some Output_sections do have
1593   // Output_data.
1594   for (Section_list::const_iterator p = this->section_list_.begin();
1595        p != this->section_list_.end();
1596        ++p)
1597     (*p)->write(of);
1598
1599   // Write out the Output_data which are not in an Output_section.
1600   for (Data_list::const_iterator p = this->special_output_list_.begin();
1601        p != this->special_output_list_.end();
1602        ++p)
1603     (*p)->write(of);
1604 }
1605
1606 // Write_data_task methods.
1607
1608 // We can always run this task.
1609
1610 Task::Is_runnable_type
1611 Write_data_task::is_runnable(Workqueue*)
1612 {
1613   return IS_RUNNABLE;
1614 }
1615
1616 // We need to unlock FINAL_BLOCKER when finished.
1617
1618 Task_locker*
1619 Write_data_task::locks(Workqueue* workqueue)
1620 {
1621   return new Task_locker_block(*this->final_blocker_, workqueue);
1622 }
1623
1624 // Run the task--write out the data.
1625
1626 void
1627 Write_data_task::run(Workqueue*)
1628 {
1629   this->layout_->write_data(this->symtab_, this->of_);
1630 }
1631
1632 // Write_symbols_task methods.
1633
1634 // We can always run this task.
1635
1636 Task::Is_runnable_type
1637 Write_symbols_task::is_runnable(Workqueue*)
1638 {
1639   return IS_RUNNABLE;
1640 }
1641
1642 // We need to unlock FINAL_BLOCKER when finished.
1643
1644 Task_locker*
1645 Write_symbols_task::locks(Workqueue* workqueue)
1646 {
1647   return new Task_locker_block(*this->final_blocker_, workqueue);
1648 }
1649
1650 // Run the task--write out the symbols.
1651
1652 void
1653 Write_symbols_task::run(Workqueue*)
1654 {
1655   this->symtab_->write_globals(this->target_, this->sympool_, this->dynpool_,
1656                                this->of_);
1657 }
1658
1659 // Close_task_runner methods.
1660
1661 // Run the task--close the file.
1662
1663 void
1664 Close_task_runner::run(Workqueue*)
1665 {
1666   this->of_->close();
1667 }
1668
1669 // Instantiate the templates we need.  We could use the configure
1670 // script to restrict this to only the ones for implemented targets.
1671
1672 #ifdef HAVE_TARGET_32_LITTLE
1673 template
1674 Output_section*
1675 Layout::layout<32, false>(Relobj* object, unsigned int shndx, const char* name,
1676                           const elfcpp::Shdr<32, false>& shdr, off_t*);
1677 #endif
1678
1679 #ifdef HAVE_TARGET_32_BIG
1680 template
1681 Output_section*
1682 Layout::layout<32, true>(Relobj* object, unsigned int shndx, const char* name,
1683                          const elfcpp::Shdr<32, true>& shdr, off_t*);
1684 #endif
1685
1686 #ifdef HAVE_TARGET_64_LITTLE
1687 template
1688 Output_section*
1689 Layout::layout<64, false>(Relobj* object, unsigned int shndx, const char* name,
1690                           const elfcpp::Shdr<64, false>& shdr, off_t*);
1691 #endif
1692
1693 #ifdef HAVE_TARGET_64_BIG
1694 template
1695 Output_section*
1696 Layout::layout<64, true>(Relobj* object, unsigned int shndx, const char* name,
1697                          const elfcpp::Shdr<64, true>& shdr, off_t*);
1698 #endif
1699
1700
1701 } // End namespace gold.