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