More section layout code.
[external/binutils.git] / gold / layout.cc
1 // layout.cc -- lay out output file sections for gold
2
3 #include "gold.h"
4
5 #include <cassert>
6 #include <cstring>
7 #include <algorithm>
8 #include <iostream>
9 #include <utility>
10
11 #include "output.h"
12 #include "layout.h"
13
14 namespace gold
15 {
16
17 // Layout_task methods.
18
19 Layout_task::~Layout_task()
20 {
21 }
22
23 // This task can be run when it is unblocked.
24
25 Task::Is_runnable_type
26 Layout_task::is_runnable(Workqueue*)
27 {
28   if (this->this_blocker_->is_blocked())
29     return IS_BLOCKED;
30   return IS_RUNNABLE;
31 }
32
33 // We don't need to hold any locks for the duration of this task.  In
34 // fact this task will be the only one running.
35
36 Task_locker*
37 Layout_task::locks(Workqueue*)
38 {
39   return NULL;
40 }
41
42 // Lay out the sections.  This is called after all the input objects
43 // have been read.
44
45 void
46 Layout_task::run(Workqueue*)
47 {
48   Layout layout(this->options_);
49   layout.init();
50   for (Input_objects::Object_list::const_iterator p =
51          this->input_objects_->begin();
52        p != this->input_objects_->end();
53        ++p)
54     (*p)->layout(&layout);
55   layout.finalize(this->input_objects_);
56 }
57
58 // Layout methods.
59
60 Layout::Layout(const General_options& options)
61   : options_(options), namepool_(), signatures_(),
62     section_name_map_(), segment_list_(), section_list_(),
63     data_list_()
64 {
65 }
66
67 // Prepare for doing layout.
68
69 void
70 Layout::init()
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   segment_list_.reserve(12);
75 }
76
77 // Hash a key we use to look up an output section mapping.
78
79 size_t
80 Layout::Hash_key::operator()(const Layout::Key& k) const
81 {
82  return reinterpret_cast<size_t>(k.first) + k.second.first + k.second.second;
83 }
84
85 // Whether to include this section in the link.
86
87 template<int size, bool big_endian>
88 bool
89 Layout::include_section(Object*, const char*,
90                         const elfcpp::Shdr<size, big_endian>& shdr)
91 {
92   // Some section types are never linked.  Some are only linked when
93   // doing a relocateable link.
94   switch (shdr.get_sh_type())
95     {
96     case elfcpp::SHT_NULL:
97     case elfcpp::SHT_SYMTAB:
98     case elfcpp::SHT_DYNSYM:
99     case elfcpp::SHT_STRTAB:
100     case elfcpp::SHT_HASH:
101     case elfcpp::SHT_DYNAMIC:
102     case elfcpp::SHT_SYMTAB_SHNDX:
103       return false;
104
105     case elfcpp::SHT_RELA:
106     case elfcpp::SHT_REL:
107     case elfcpp::SHT_GROUP:
108       return this->options_.is_relocatable();
109
110     default:
111       // FIXME: Handle stripping debug sections here.
112       return true;
113     }
114 }
115
116 // Return the output section to use for input section NAME, with
117 // header HEADER, from object OBJECT.  Set *OFF to the offset of this
118 // input section without the output section.
119
120 template<int size, bool big_endian>
121 Output_section*
122 Layout::layout(Object* object, const char* name,
123                const elfcpp::Shdr<size, big_endian>& shdr, off_t* off)
124 {
125   if (!this->include_section(object, name, shdr))
126     return NULL;
127
128   // Unless we are doing a relocateable link, .gnu.linkonce sections
129   // are laid out as though they were named for the sections are
130   // placed into.
131   if (!this->options_.is_relocatable() && Layout::is_linkonce(name))
132     name = Layout::linkonce_output_name(name);
133
134   // FIXME: Handle SHF_OS_NONCONFORMING here.
135
136   // Canonicalize the section name.
137   name = this->namepool_.add(name);
138
139   // Find the output section.  The output section is selected based on
140   // the section name, type, and flags.
141
142   // FIXME: If we want to do relaxation, we need to modify this
143   // algorithm.  We also build a list of input sections for each
144   // output section.  Then we relax all the input sections.  Then we
145   // walk down the list and adjust all the offsets.
146
147   elfcpp::Elf_Word type = shdr.get_sh_type();
148   elfcpp::Elf_Xword flags = shdr.get_sh_flags();
149   const Key key(name, std::make_pair(type, flags));
150   const std::pair<Key, Output_section*> v(key, NULL);
151   std::pair<Section_name_map::iterator, bool> ins(
152     this->section_name_map_.insert(v));
153
154   Output_section* os;
155   if (!ins.second)
156     os = ins.first->second;
157   else
158     {
159       // This is the first time we've seen this name/type/flags
160       // combination.
161       os = this->make_output_section(name, type, flags);
162       ins.first->second = os;
163     }
164
165   // FIXME: Handle SHF_LINK_ORDER somewhere.
166
167   *off = os->add_input_section(object, name, shdr);
168
169   return os;
170 }
171
172 // Return whether SEG1 should be before SEG2 in the output file.  This
173 // is based entirely on the segment type and flags.  When this is
174 // called the segment addresses has normally not yet been set.
175
176 bool
177 Layout::segment_precedes(const Output_segment* seg1,
178                          const Output_segment* seg2)
179 {
180   elfcpp::Elf_Word type1 = seg1->type();
181   elfcpp::Elf_Word type2 = seg2->type();
182
183   // The single PT_PHDR segment is required to precede any loadable
184   // segment.  We simply make it always first.
185   if (type1 == elfcpp::PT_PHDR)
186     {
187       assert(type2 != elfcpp::PT_PHDR);
188       return true;
189     }
190   if (type2 == elfcpp::PT_PHDR)
191     return false;
192
193   // The single PT_INTERP segment is required to precede any loadable
194   // segment.  We simply make it always second.
195   if (type1 == elfcpp::PT_INTERP)
196     {
197       assert(type2 != elfcpp::PT_INTERP);
198       return true;
199     }
200   if (type2 == elfcpp::PT_INTERP)
201     return false;
202
203   // We then put PT_LOAD segments before any other segments.
204   if (type1 == elfcpp::PT_LOAD && type2 != elfcpp::PT_LOAD)
205     return true;
206   if (type2 == elfcpp::PT_LOAD && type1 != elfcpp::PT_LOAD)
207     return false;
208
209   const elfcpp::Elf_Word flags1 = seg1->flags();
210   const elfcpp::Elf_Word flags2 = seg2->flags();
211
212   // The order of non-PT_LOAD segments is unimportant.  We simply sort
213   // by the numeric segment type and flags values.  There should not
214   // be more than one segment with the same type and flags.
215   if (type1 != elfcpp::PT_LOAD)
216     {
217       if (type1 != type2)
218         return type1 < type2;
219       assert(flags1 != flags2);
220       return flags1 < flags2;
221     }
222
223   // We sort PT_LOAD segments based on the flags.  Readonly segments
224   // come before writable segments.  Then executable segments come
225   // before non-executable segments.  Then the unlikely case of a
226   // non-readable segment comes before the normal case of a readable
227   // segment.  If there are multiple segments with the same type and
228   // flags, we require that the address be set, and we sort by
229   // virtual address and then physical address.
230   if ((flags1 & elfcpp::PF_W) != (flags2 & elfcpp::PF_W))
231     return (flags1 & elfcpp::PF_W) == 0;
232   if ((flags1 & elfcpp::PF_X) != (flags2 & elfcpp::PF_X))
233     return (flags1 & elfcpp::PF_X) != 0;
234   if ((flags1 & elfcpp::PF_R) != (flags2 & elfcpp::PF_R))
235     return (flags1 & elfcpp::PF_R) == 0;
236
237   uint64_t vaddr1 = seg1->vaddr();
238   uint64_t vaddr2 = seg2->vaddr();
239   if (vaddr1 != vaddr2)
240     return vaddr1 < vaddr2;
241
242   uint64_t paddr1 = seg1->paddr();
243   uint64_t paddr2 = seg2->paddr();
244   assert(paddr1 != paddr2);
245   return paddr1 < paddr2;
246 }
247
248 // Map section flags to segment flags.
249
250 elfcpp::Elf_Word
251 Layout::section_flags_to_segment(elfcpp::Elf_Xword flags)
252 {
253   elfcpp::Elf_Word ret = elfcpp::PF_R;
254   if ((flags & elfcpp::SHF_WRITE) != 0)
255     ret |= elfcpp::PF_W;
256   if ((flags & elfcpp::SHF_EXECINSTR) != 0)
257     ret |= elfcpp::PF_X;
258   return ret;
259 }
260
261 // Make a new Output_section, and attach it to segments as
262 // appropriate.
263
264 Output_section*
265 Layout::make_output_section(const char* name, elfcpp::Elf_Word type,
266                             elfcpp::Elf_Xword flags)
267 {
268   Output_section* os = new Output_section(name, type, flags);
269
270   if ((flags & elfcpp::SHF_ALLOC) == 0)
271     this->section_list_.push_back(os);
272   else
273     {
274       // This output section goes into a PT_LOAD segment.
275
276       elfcpp::Elf_Word seg_flags = Layout::section_flags_to_segment(flags);
277
278       // The only thing we really care about for PT_LOAD segments is
279       // whether or not they are writable, so that is how we search
280       // for them.  People who need segments sorted on some other
281       // basis will have to wait until we implement a mechanism for
282       // them to describe the segments they want.
283
284       Segment_list::const_iterator p;
285       for (p = this->segment_list_.begin();
286            p != this->segment_list_.end();
287            ++p)
288         {
289           if ((*p)->type() == elfcpp::PT_LOAD
290               && ((*p)->flags() & elfcpp::PF_W) == (seg_flags & elfcpp::PF_W))
291             {
292               (*p)->add_output_section(os);
293               break;
294             }
295         }
296
297       if (p == this->segment_list_.end())
298         {
299           Output_segment* oseg = new Output_segment(elfcpp::PT_LOAD,
300                                                     seg_flags);
301           this->segment_list_.push_back(oseg);
302           oseg->add_output_section(os);
303         }
304
305       // If we see a loadable SHT_NOTE section, we create a PT_NOTE
306       // segment.
307       if (type == elfcpp::SHT_NOTE)
308         {
309           // See if we already have an equivalent PT_NOTE segment.
310           for (p = this->segment_list_.begin();
311                p != segment_list_.end();
312                ++p)
313             {
314               if ((*p)->type() == elfcpp::PT_NOTE
315                   && (((*p)->flags() & elfcpp::PF_W)
316                       == (seg_flags & elfcpp::PF_W)))
317                 {
318                   (*p)->add_output_section(os);
319                   break;
320                 }
321             }
322
323           if (p == this->segment_list_.end())
324             {
325               Output_segment* oseg = new Output_segment(elfcpp::PT_NOTE,
326                                                         seg_flags);
327               this->segment_list_.push_back(oseg);
328               oseg->add_output_section(os);
329             }
330         }
331
332       // If we see a loadable SHF_TLS section, we create a PT_TLS
333       // segment.
334       if ((flags & elfcpp::SHF_TLS) != 0)
335         {
336           // See if we already have an equivalent PT_TLS segment.
337           for (p = this->segment_list_.begin();
338                p != segment_list_.end();
339                ++p)
340             {
341               if ((*p)->type() == elfcpp::PT_TLS
342                   && (((*p)->flags() & elfcpp::PF_W)
343                       == (seg_flags & elfcpp::PF_W)))
344                 {
345                   (*p)->add_output_section(os);
346                   break;
347                 }
348             }
349
350           if (p == this->segment_list_.end())
351             {
352               Output_segment* oseg = new Output_segment(elfcpp::PT_TLS,
353                                                         seg_flags);
354               this->segment_list_.push_back(oseg);
355               oseg->add_output_section(os);
356             }
357         }
358     }
359
360   return os;
361 }
362
363 // Create the sections for the symbol table.
364
365 void
366 Layout::create_symtab_sections()
367 {
368 }
369
370 // Finalize the layout.  When this is called, we have created all the
371 // output sections and all the output segments which are based on
372 // input sections.  We have several things to do, and we have to do
373 // them in the right order, so that we get the right results correctly
374 // and efficiently.
375
376 // 1) Finalize the list of output segments and create the segment
377 // table header.
378
379 // 2) Finalize the dynamic symbol table and associated sections.
380
381 // 3) Determine the final file offset of all the output segments.
382
383 // 4) Determine the final file offset of all the SHF_ALLOC output
384 // sections.
385
386 // 5) Finalize the symbol table: set symbol values to their final
387 // value and make a final determination of which symbols are going
388 // into the output symbol table.
389
390 // 6) Create the symbol table sections and the section name table
391 // section.
392
393 // 7) Create the section table header.
394
395 // 8) Determine the final file offset of all the output sections which
396 // are not SHF_ALLOC, including the section table header.
397
398 // 9) Finalize the ELF file header.
399
400 void
401 Layout::finalize(const Input_objects* input_objects)
402 {
403   if (input_objects->any_dynamic())
404     {
405       // If there are any dynamic objects in the link, then we need
406       // some additional segments: PT_PHDRS, PT_INTERP, and
407       // PT_DYNAMIC.  We also need to finalize the dynamic symbol
408       // table and create the dynamic hash table.
409       abort();
410     }
411
412   // FIXME: Handle PT_GNU_STACK.
413
414   std::sort(this->segment_list_.begin(), this->segment_list_.end(),
415             Layout::Compare_segments());
416
417   Output_segment_headers* segment_headers;
418   segment_headers = new Output_segment_headers(this->segment_list_);
419 }
420
421 // The mapping of .gnu.linkonce section names to real section names.
422
423 #define MAPPING_INIT(f, t) { f, sizeof(f) - 1, t }
424 const Layout::Linkonce_mapping Layout::linkonce_mapping[] =
425 {
426   MAPPING_INIT("d.rel.ro", ".data.rel.ro"),     // Must be before "d".
427   MAPPING_INIT("t", ".text"),
428   MAPPING_INIT("r", ".rodata"),
429   MAPPING_INIT("d", ".data"),
430   MAPPING_INIT("b", ".bss"),
431   MAPPING_INIT("s", ".sdata"),
432   MAPPING_INIT("sb", ".sbss"),
433   MAPPING_INIT("s2", ".sdata2"),
434   MAPPING_INIT("sb2", ".sbss2"),
435   MAPPING_INIT("wi", ".debug_info"),
436   MAPPING_INIT("td", ".tdata"),
437   MAPPING_INIT("tb", ".tbss"),
438   MAPPING_INIT("lr", ".lrodata"),
439   MAPPING_INIT("l", ".ldata"),
440   MAPPING_INIT("lb", ".lbss"),
441 };
442 #undef MAPPING_INIT
443
444 const int Layout::linkonce_mapping_count =
445   sizeof(Layout::linkonce_mapping) / sizeof(Layout::linkonce_mapping[0]);
446
447 // Return the name of the output section to use for a .gnu.linkonce
448 // section.  This is based on the default ELF linker script of the old
449 // GNU linker.  For example, we map a name like ".gnu.linkonce.t.foo"
450 // to ".text".
451
452 const char*
453 Layout::linkonce_output_name(const char* name)
454 {
455   const char* s = name + sizeof(".gnu.linkonce") - 1;
456   if (*s != '.')
457     return name;
458   ++s;
459   const Linkonce_mapping* plm = linkonce_mapping;
460   for (int i = 0; i < linkonce_mapping_count; ++i, ++plm)
461     {
462       if (strncmp(s, plm->from, plm->fromlen) == 0 && s[plm->fromlen] == '.')
463         return plm->to;
464     }
465   return name;
466 }
467
468 // Record the signature of a comdat section, and return whether to
469 // include it in the link.  If GROUP is true, this is a regular
470 // section group.  If GROUP is false, this is a group signature
471 // derived from the name of a linkonce section.  We want linkonce
472 // signatures and group signatures to block each other, but we don't
473 // want a linkonce signature to block another linkonce signature.
474
475 bool
476 Layout::add_comdat(const char* signature, bool group)
477 {
478   std::string sig(signature);
479   std::pair<Signatures::iterator, bool> ins(
480     this->signatures_.insert(std::make_pair(signature, group)));
481
482   if (ins.second)
483     {
484       // This is the first time we've seen this signature.
485       return true;
486     }
487
488   if (ins.first->second)
489     {
490       // We've already seen a real section group with this signature.
491       return false;
492     }
493   else if (group)
494     {
495       // This is a real section group, and we've already seen a
496       // linkonce section with tihs signature.  Record that we've seen
497       // a section group, and don't include this section group.
498       ins.first->second = true;
499       return false;
500     }
501   else
502     {
503       // We've already seen a linkonce section and this is a linkonce
504       // section.  These don't block each other--this may be the same
505       // symbol name with different section types.
506       return true;
507     }
508 }
509
510 // Instantiate the templates we need.  We could use the configure
511 // script to restrict this to only the ones for implemented targets.
512
513 template
514 Output_section*
515 Layout::layout<32, false>(Object* object, const char* name,
516                           const elfcpp::Shdr<32, false>& shdr, off_t*);
517
518 template
519 Output_section*
520 Layout::layout<32, true>(Object* object, const char* name,
521                          const elfcpp::Shdr<32, true>& shdr, off_t*);
522
523 template
524 Output_section*
525 Layout::layout<64, false>(Object* object, const char* name,
526                           const elfcpp::Shdr<64, false>& shdr, off_t*);
527
528 template
529 Output_section*
530 Layout::layout<64, true>(Object* object, const char* name,
531                          const elfcpp::Shdr<64, true>& shdr, off_t*);
532
533
534 } // End namespace gold.