PR gold/12910
[platform/upstream/binutils.git] / gold / layout.h
1 // layout.h -- lay out output file sections for gold  -*- C++ -*-
2
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011 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 #ifndef GOLD_LAYOUT_H
24 #define GOLD_LAYOUT_H
25
26 #include <cstring>
27 #include <list>
28 #include <map>
29 #include <string>
30 #include <utility>
31 #include <vector>
32
33 #include "script.h"
34 #include "workqueue.h"
35 #include "object.h"
36 #include "dynobj.h"
37 #include "stringpool.h"
38
39 namespace gold
40 {
41
42 class General_options;
43 class Incremental_inputs;
44 class Incremental_binary;
45 class Input_objects;
46 class Mapfile;
47 class Symbol_table;
48 class Output_section_data;
49 class Output_section;
50 class Output_section_headers;
51 class Output_segment_headers;
52 class Output_file_header;
53 class Output_segment;
54 class Output_data;
55 class Output_data_reloc_generic;
56 class Output_data_dynamic;
57 class Output_symtab_xindex;
58 class Output_reduced_debug_abbrev_section;
59 class Output_reduced_debug_info_section;
60 class Eh_frame;
61 class Target;
62 struct Timespec;
63
64 // Return TRUE if SECNAME is the name of a compressed debug section.
65 extern bool
66 is_compressed_debug_section(const char* secname);
67
68 // Maintain a list of free space within a section, segment, or file.
69 // Used for incremental update links.
70
71 class Free_list
72 {
73  public:
74   Free_list()
75     : list_(), last_remove_(list_.begin()), extend_(false), length_(0)
76   { }
77
78   void
79   init(off_t len, bool extend);
80
81   void
82   remove(off_t start, off_t end);
83
84   off_t
85   allocate(off_t len, uint64_t align, off_t minoff);
86
87   void
88   dump();
89
90   static void
91   print_stats();
92
93  private:
94   struct Free_list_node
95   {
96     Free_list_node(off_t start, off_t end)
97       : start_(start), end_(end)
98     { }
99     off_t start_;
100     off_t end_;
101   };
102   typedef std::list<Free_list_node>::iterator Iterator;
103
104   // The free list.
105   std::list<Free_list_node> list_;
106
107   // The last node visited during a remove operation.
108   Iterator last_remove_;
109
110   // Whether we can extend past the original length.
111   bool extend_;
112
113   // The total length of the section, segment, or file.
114   off_t length_;
115
116   // Statistics:
117   // The total number of free lists used.
118   static unsigned int num_lists;
119   // The total number of free list nodes used.
120   static unsigned int num_nodes;
121   // The total number of calls to Free_list::remove.
122   static unsigned int num_removes;
123   // The total number of nodes visited during calls to Free_list::remove.
124   static unsigned int num_remove_visits;
125   // The total number of calls to Free_list::allocate.
126   static unsigned int num_allocates;
127   // The total number of nodes visited during calls to Free_list::allocate.
128   static unsigned int num_allocate_visits;
129 };
130
131 // This task function handles mapping the input sections to output
132 // sections and laying them out in memory.
133
134 class Layout_task_runner : public Task_function_runner
135 {
136  public:
137   // OPTIONS is the command line options, INPUT_OBJECTS is the list of
138   // input objects, SYMTAB is the symbol table, LAYOUT is the layout
139   // object.
140   Layout_task_runner(const General_options& options,
141                      const Input_objects* input_objects,
142                      Symbol_table* symtab,
143                      Target* target,
144                      Layout* layout,
145                      Mapfile* mapfile)
146     : options_(options), input_objects_(input_objects), symtab_(symtab),
147       target_(target), layout_(layout), mapfile_(mapfile)
148   { }
149
150   // Run the operation.
151   void
152   run(Workqueue*, const Task*);
153
154  private:
155   Layout_task_runner(const Layout_task_runner&);
156   Layout_task_runner& operator=(const Layout_task_runner&);
157
158   const General_options& options_;
159   const Input_objects* input_objects_;
160   Symbol_table* symtab_;
161   Target* target_;
162   Layout* layout_;
163   Mapfile* mapfile_;
164 };
165
166 // This class holds information about the comdat group or
167 // .gnu.linkonce section that will be kept for a given signature.
168
169 class Kept_section
170 {
171  private:
172   // For a comdat group, we build a mapping from the name of each
173   // section in the group to the section index and the size in object.
174   // When we discard a group in some other object file, we use this
175   // map to figure out which kept section the discarded section is
176   // associated with.  We then use that mapping when processing relocs
177   // against discarded sections.
178   struct Comdat_section_info
179   {
180     // The section index.
181     unsigned int shndx;
182     // The section size.
183     uint64_t size;
184
185     Comdat_section_info(unsigned int a_shndx, uint64_t a_size)
186       : shndx(a_shndx), size(a_size)
187     { }
188   };
189
190   // Most comdat groups have only one or two sections, so we use a
191   // std::map rather than an Unordered_map to optimize for that case
192   // without paying too heavily for groups with more sections.
193   typedef std::map<std::string, Comdat_section_info> Comdat_group;
194
195  public:
196   Kept_section()
197     : object_(NULL), shndx_(0), is_comdat_(false), is_group_name_(false)
198   { this->u_.linkonce_size = 0; }
199
200   // We need to support copies for the signature map in the Layout
201   // object, but we should never copy an object after it has been
202   // marked as a comdat section.
203   Kept_section(const Kept_section& k)
204     : object_(k.object_), shndx_(k.shndx_), is_comdat_(false),
205       is_group_name_(k.is_group_name_)
206   {
207     gold_assert(!k.is_comdat_);
208     this->u_.linkonce_size = 0;
209   }
210
211   ~Kept_section()
212   {
213     if (this->is_comdat_)
214       delete this->u_.group_sections;
215   }
216
217   // The object where this section lives.
218   Relobj*
219   object() const
220   { return this->object_; }
221
222   // Set the object.
223   void
224   set_object(Relobj* object)
225   {
226     gold_assert(this->object_ == NULL);
227     this->object_ = object;
228   }
229
230   // The section index.
231   unsigned int
232   shndx() const
233   { return this->shndx_; }
234
235   // Set the section index.
236   void
237   set_shndx(unsigned int shndx)
238   {
239     gold_assert(this->shndx_ == 0);
240     this->shndx_ = shndx;
241   }
242
243   // Whether this is a comdat group.
244   bool
245   is_comdat() const
246   { return this->is_comdat_; }
247
248   // Set that this is a comdat group.
249   void
250   set_is_comdat()
251   {
252     gold_assert(!this->is_comdat_);
253     this->is_comdat_ = true;
254     this->u_.group_sections = new Comdat_group();
255   }
256
257   // Whether this is associated with the name of a group or section
258   // rather than the symbol name derived from a linkonce section.
259   bool
260   is_group_name() const
261   { return this->is_group_name_; }
262
263   // Note that this represents a comdat group rather than a single
264   // linkonce section.
265   void
266   set_is_group_name()
267   { this->is_group_name_ = true; }
268
269   // Add a section to the group list.
270   void
271   add_comdat_section(const std::string& name, unsigned int shndx,
272                      uint64_t size)
273   {
274     gold_assert(this->is_comdat_);
275     Comdat_section_info sinfo(shndx, size);
276     this->u_.group_sections->insert(std::make_pair(name, sinfo));
277   }
278
279   // Look for a section name in the group list, and return whether it
280   // was found.  If found, returns the section index and size.
281   bool
282   find_comdat_section(const std::string& name, unsigned int* pshndx,
283                       uint64_t* psize) const
284   {
285     gold_assert(this->is_comdat_);
286     Comdat_group::const_iterator p = this->u_.group_sections->find(name);
287     if (p == this->u_.group_sections->end())
288       return false;
289     *pshndx = p->second.shndx;
290     *psize = p->second.size;
291     return true;
292   }
293
294   // If there is only one section in the group list, return true, and
295   // return the section index and size.
296   bool
297   find_single_comdat_section(unsigned int* pshndx, uint64_t* psize) const
298   {
299     gold_assert(this->is_comdat_);
300     if (this->u_.group_sections->size() != 1)
301       return false;
302     Comdat_group::const_iterator p = this->u_.group_sections->begin();
303     *pshndx = p->second.shndx;
304     *psize = p->second.size;
305     return true;
306   }
307
308   // Return the size of a linkonce section.
309   uint64_t
310   linkonce_size() const
311   {
312     gold_assert(!this->is_comdat_);
313     return this->u_.linkonce_size;
314   }
315
316   // Set the size of a linkonce section.
317   void
318   set_linkonce_size(uint64_t size)
319   {
320     gold_assert(!this->is_comdat_);
321     this->u_.linkonce_size = size;
322   }
323
324  private:
325   // No assignment.
326   Kept_section& operator=(const Kept_section&);
327
328   // The object containing the comdat group or .gnu.linkonce section.
329   Relobj* object_;
330   // Index of the group section for comdats and the section itself for
331   // .gnu.linkonce.
332   unsigned int shndx_;
333   // True if this is for a comdat group rather than a .gnu.linkonce
334   // section.
335   bool is_comdat_;
336   // The Kept_sections are values of a mapping, that maps names to
337   // them.  This field is true if this struct is associated with the
338   // name of a comdat or .gnu.linkonce, false if it is associated with
339   // the name of a symbol obtained from the .gnu.linkonce.* name
340   // through some heuristics.
341   bool is_group_name_;
342   union
343   {
344     // If the is_comdat_ field is true, this holds a map from names of
345     // the sections in the group to section indexes in object_ and to
346     // section sizes.
347     Comdat_group* group_sections;
348     // If the is_comdat_ field is false, this holds the size of the
349     // single section.
350     uint64_t linkonce_size;
351   } u_;
352 };
353
354 // The ordering for output sections.  This controls how output
355 // sections are ordered within a PT_LOAD output segment.
356
357 enum Output_section_order
358 {
359   // Unspecified.  Used for non-load segments.  Also used for the file
360   // and segment headers.
361   ORDER_INVALID,
362
363   // The PT_INTERP section should come first, so that the dynamic
364   // linker can pick it up quickly.
365   ORDER_INTERP,
366
367   // Loadable read-only note sections come next so that the PT_NOTE
368   // segment is on the first page of the executable.
369   ORDER_RO_NOTE,
370
371   // Put read-only sections used by the dynamic linker early in the
372   // executable to minimize paging.
373   ORDER_DYNAMIC_LINKER,
374
375   // Put reloc sections used by the dynamic linker after other
376   // sections used by the dynamic linker; otherwise, objcopy and strip
377   // get confused.
378   ORDER_DYNAMIC_RELOCS,
379
380   // Put the PLT reloc section after the other dynamic relocs;
381   // otherwise, prelink gets confused.
382   ORDER_DYNAMIC_PLT_RELOCS,
383
384   // The .init section.
385   ORDER_INIT,
386
387   // The PLT.
388   ORDER_PLT,
389
390   // The regular text sections.
391   ORDER_TEXT,
392
393   // The .fini section.
394   ORDER_FINI,
395
396   // The read-only sections.
397   ORDER_READONLY,
398
399   // The exception frame sections.
400   ORDER_EHFRAME,
401
402   // The TLS sections come first in the data section.
403   ORDER_TLS_DATA,
404   ORDER_TLS_BSS,
405
406   // Local RELRO (read-only after relocation) sections come before
407   // non-local RELRO sections.  This data will be fully resolved by
408   // the prelinker.
409   ORDER_RELRO_LOCAL,
410
411   // Non-local RELRO sections are grouped together after local RELRO
412   // sections.  All RELRO sections must be adjacent so that they can
413   // all be put into a PT_GNU_RELRO segment.
414   ORDER_RELRO,
415
416   // We permit marking exactly one output section as the last RELRO
417   // section.  We do this so that the read-only GOT can be adjacent to
418   // the writable GOT.
419   ORDER_RELRO_LAST,
420
421   // Similarly, we permit marking exactly one output section as the
422   // first non-RELRO section.
423   ORDER_NON_RELRO_FIRST,
424
425   // The regular data sections come after the RELRO sections.
426   ORDER_DATA,
427
428   // Large data sections normally go in large data segments.
429   ORDER_LARGE_DATA,
430
431   // Group writable notes so that we can have a single PT_NOTE
432   // segment.
433   ORDER_RW_NOTE,
434
435   // The small data sections must be at the end of the data sections,
436   // so that they can be adjacent to the small BSS sections.
437   ORDER_SMALL_DATA,
438
439   // The BSS sections start here.
440
441   // The small BSS sections must be at the start of the BSS sections,
442   // so that they can be adjacent to the small data sections.
443   ORDER_SMALL_BSS,
444
445   // The regular BSS sections.
446   ORDER_BSS,
447
448   // The large BSS sections come after the other BSS sections.
449   ORDER_LARGE_BSS,
450
451   // Maximum value.
452   ORDER_MAX
453 };
454
455 // This class handles the details of laying out input sections.
456
457 class Layout
458 {
459  public:
460   Layout(int number_of_input_files, Script_options*);
461
462   ~Layout()
463   {
464     delete this->relaxation_debug_check_;
465     delete this->segment_states_;
466   }
467
468   // For incremental links, record the base file to be modified.
469   void
470   set_incremental_base(Incremental_binary* base);
471
472   Incremental_binary*
473   incremental_base()
474   { return this->incremental_base_; }
475
476   // For incremental links, record the initial fixed layout of a section
477   // from the base file, and return a pointer to the Output_section.
478   template<int size, bool big_endian>
479   Output_section*
480   init_fixed_output_section(const char*, elfcpp::Shdr<size, big_endian>&);
481
482   // Given an input section SHNDX, named NAME, with data in SHDR, from
483   // the object file OBJECT, return the output section where this
484   // input section should go.  RELOC_SHNDX is the index of a
485   // relocation section which applies to this section, or 0 if none,
486   // or -1U if more than one.  RELOC_TYPE is the type of the
487   // relocation section if there is one.  Set *OFFSET to the offset
488   // within the output section.
489   template<int size, bool big_endian>
490   Output_section*
491   layout(Sized_relobj_file<size, big_endian> *object, unsigned int shndx,
492          const char* name, const elfcpp::Shdr<size, big_endian>& shdr,
493          unsigned int reloc_shndx, unsigned int reloc_type, off_t* offset);
494
495   // For incremental updates, allocate a block of memory from the
496   // free list.  Find a block starting at or after MINOFF.
497   off_t
498   allocate(off_t len, uint64_t align, off_t minoff)
499   { return this->free_list_.allocate(len, align, minoff); }
500
501   unsigned int
502   find_section_order_index(const std::string&);
503
504   void
505   read_layout_from_file();
506
507   // Layout an input reloc section when doing a relocatable link.  The
508   // section is RELOC_SHNDX in OBJECT, with data in SHDR.
509   // DATA_SECTION is the reloc section to which it refers.  RR is the
510   // relocatable information.
511   template<int size, bool big_endian>
512   Output_section*
513   layout_reloc(Sized_relobj_file<size, big_endian>* object,
514                unsigned int reloc_shndx,
515                const elfcpp::Shdr<size, big_endian>& shdr,
516                Output_section* data_section,
517                Relocatable_relocs* rr);
518
519   // Layout a group section when doing a relocatable link.
520   template<int size, bool big_endian>
521   void
522   layout_group(Symbol_table* symtab,
523                Sized_relobj_file<size, big_endian>* object,
524                unsigned int group_shndx,
525                const char* group_section_name,
526                const char* signature,
527                const elfcpp::Shdr<size, big_endian>& shdr,
528                elfcpp::Elf_Word flags,
529                std::vector<unsigned int>* shndxes);
530
531   // Like layout, only for exception frame sections.  OBJECT is an
532   // object file.  SYMBOLS is the contents of the symbol table
533   // section, with size SYMBOLS_SIZE.  SYMBOL_NAMES is the contents of
534   // the symbol name section, with size SYMBOL_NAMES_SIZE.  SHNDX is a
535   // .eh_frame section in OBJECT.  SHDR is the section header.
536   // RELOC_SHNDX is the index of a relocation section which applies to
537   // this section, or 0 if none, or -1U if more than one.  RELOC_TYPE
538   // is the type of the relocation section if there is one.  This
539   // returns the output section, and sets *OFFSET to the offset.
540   template<int size, bool big_endian>
541   Output_section*
542   layout_eh_frame(Sized_relobj_file<size, big_endian>* object,
543                   const unsigned char* symbols,
544                   off_t symbols_size,
545                   const unsigned char* symbol_names,
546                   off_t symbol_names_size,
547                   unsigned int shndx,
548                   const elfcpp::Shdr<size, big_endian>& shdr,
549                   unsigned int reloc_shndx, unsigned int reloc_type,
550                   off_t* offset);
551
552   // Handle a GNU stack note.  This is called once per input object
553   // file.  SEEN_GNU_STACK is true if the object file has a
554   // .note.GNU-stack section.  GNU_STACK_FLAGS is the section flags
555   // from that section if there was one.
556   void
557   layout_gnu_stack(bool seen_gnu_stack, uint64_t gnu_stack_flags,
558                    const Object*);
559
560   // Add an Output_section_data to the layout.  This is used for
561   // special sections like the GOT section.  ORDER is where the
562   // section should wind up in the output segment.  IS_RELRO is true
563   // for relro sections.
564   Output_section*
565   add_output_section_data(const char* name, elfcpp::Elf_Word type,
566                           elfcpp::Elf_Xword flags,
567                           Output_section_data*, Output_section_order order,
568                           bool is_relro);
569
570   // Increase the size of the relro segment by this much.
571   void
572   increase_relro(unsigned int s)
573   { this->increase_relro_ += s; }
574
575   // Create dynamic sections if necessary.
576   void
577   create_initial_dynamic_sections(Symbol_table*);
578
579   // Define __start and __stop symbols for output sections.
580   void
581   define_section_symbols(Symbol_table*);
582
583   // Create automatic note sections.
584   void
585   create_notes();
586
587   // Create sections for linker scripts.
588   void
589   create_script_sections()
590   { this->script_options_->create_script_sections(this); }
591
592   // Define symbols from any linker script.
593   void
594   define_script_symbols(Symbol_table* symtab)
595   { this->script_options_->add_symbols_to_table(symtab); }
596
597   // Define symbols for group signatures.
598   void
599   define_group_signatures(Symbol_table*);
600
601   // Return the Stringpool used for symbol names.
602   const Stringpool*
603   sympool() const
604   { return &this->sympool_; }
605
606   // Return the Stringpool used for dynamic symbol names and dynamic
607   // tags.
608   const Stringpool*
609   dynpool() const
610   { return &this->dynpool_; }
611
612   // Return the symtab_xindex section used to hold large section
613   // indexes for the normal symbol table.
614   Output_symtab_xindex*
615   symtab_xindex() const
616   { return this->symtab_xindex_; }
617
618   // Return the dynsym_xindex section used to hold large section
619   // indexes for the dynamic symbol table.
620   Output_symtab_xindex*
621   dynsym_xindex() const
622   { return this->dynsym_xindex_; }
623
624   // Return whether a section is a .gnu.linkonce section, given the
625   // section name.
626   static inline bool
627   is_linkonce(const char* name)
628   { return strncmp(name, ".gnu.linkonce", sizeof(".gnu.linkonce") - 1) == 0; }
629
630   // Whether we have added an input section.
631   bool
632   have_added_input_section() const
633   { return this->have_added_input_section_; }
634
635   // Return true if a section is a debugging section.
636   static inline bool
637   is_debug_info_section(const char* name)
638   {
639     // Debugging sections can only be recognized by name.
640     return (strncmp(name, ".debug", sizeof(".debug") - 1) == 0
641             || strncmp(name, ".zdebug", sizeof(".zdebug") - 1) == 0
642             || strncmp(name, ".gnu.linkonce.wi.",
643                        sizeof(".gnu.linkonce.wi.") - 1) == 0
644             || strncmp(name, ".line", sizeof(".line") - 1) == 0
645             || strncmp(name, ".stab", sizeof(".stab") - 1) == 0);
646   }
647
648   // Return true if RELOBJ is an input file whose base name matches
649   // FILE_NAME.  The base name must have an extension of ".o", and
650   // must be exactly FILE_NAME.o or FILE_NAME, one character, ".o".
651   static bool
652   match_file_name(const Relobj* relobj, const char* file_name);
653
654   // Check if a comdat group or .gnu.linkonce section with the given
655   // NAME is selected for the link.  If there is already a section,
656   // *KEPT_SECTION is set to point to the signature and the function
657   // returns false.  Otherwise, OBJECT, SHNDX,IS_COMDAT, and
658   // IS_GROUP_NAME are recorded for this NAME in the layout object,
659   // *KEPT_SECTION is set to the internal copy and the function return
660   // false.
661   bool
662   find_or_add_kept_section(const std::string& name, Relobj* object, 
663                            unsigned int shndx, bool is_comdat,
664                            bool is_group_name, Kept_section** kept_section);
665
666   // Finalize the layout after all the input sections have been added.
667   off_t
668   finalize(const Input_objects*, Symbol_table*, Target*, const Task*);
669
670   // Return whether any sections require postprocessing.
671   bool
672   any_postprocessing_sections() const
673   { return this->any_postprocessing_sections_; }
674
675   // Return the size of the output file.
676   off_t
677   output_file_size() const
678   { return this->output_file_size_; }
679
680   // Return the TLS segment.  This will return NULL if there isn't
681   // one.
682   Output_segment*
683   tls_segment() const
684   { return this->tls_segment_; }
685
686   // Return the normal symbol table.
687   Output_section*
688   symtab_section() const
689   {
690     gold_assert(this->symtab_section_ != NULL);
691     return this->symtab_section_;
692   }
693
694   // Return the file offset of the normal symbol table.
695   off_t
696   symtab_section_offset() const;
697
698   // Return the dynamic symbol table.
699   Output_section*
700   dynsym_section() const
701   {
702     gold_assert(this->dynsym_section_ != NULL);
703     return this->dynsym_section_;
704   }
705
706   // Return the dynamic tags.
707   Output_data_dynamic*
708   dynamic_data() const
709   { return this->dynamic_data_; }
710
711   // Write out the output sections.
712   void
713   write_output_sections(Output_file* of) const;
714
715   // Write out data not associated with an input file or the symbol
716   // table.
717   void
718   write_data(const Symbol_table*, Output_file*) const;
719
720   // Write out output sections which can not be written until all the
721   // input sections are complete.
722   void
723   write_sections_after_input_sections(Output_file* of);
724
725   // Return an output section named NAME, or NULL if there is none.
726   Output_section*
727   find_output_section(const char* name) const;
728
729   // Return an output segment of type TYPE, with segment flags SET set
730   // and segment flags CLEAR clear.  Return NULL if there is none.
731   Output_segment*
732   find_output_segment(elfcpp::PT type, elfcpp::Elf_Word set,
733                       elfcpp::Elf_Word clear) const;
734
735   // Return the number of segments we expect to produce.
736   size_t
737   expected_segment_count() const;
738
739   // Set a flag to indicate that an object file uses the static TLS model.
740   void
741   set_has_static_tls()
742   { this->has_static_tls_ = true; }
743
744   // Return true if any object file uses the static TLS model.
745   bool
746   has_static_tls() const
747   { return this->has_static_tls_; }
748
749   // Return the options which may be set by a linker script.
750   Script_options*
751   script_options()
752   { return this->script_options_; }
753
754   const Script_options*
755   script_options() const
756   { return this->script_options_; }
757
758   // Return the object managing inputs in incremental build. NULL in
759   // non-incremental builds.
760   Incremental_inputs*
761   incremental_inputs() const
762   { return this->incremental_inputs_; }
763
764   // For the target-specific code to add dynamic tags which are common
765   // to most targets.
766   void
767   add_target_dynamic_tags(bool use_rel, const Output_data* plt_got,
768                           const Output_data* plt_rel,
769                           const Output_data_reloc_generic* dyn_rel,
770                           bool add_debug, bool dynrel_includes_plt);
771
772   // Compute and write out the build ID if needed.
773   void
774   write_build_id(Output_file*) const;
775
776   // Rewrite output file in binary format.
777   void
778   write_binary(Output_file* in) const;
779
780   // Print output sections to the map file.
781   void
782   print_to_mapfile(Mapfile*) const;
783
784   // Dump statistical information to stderr.
785   void
786   print_stats() const;
787
788   // A list of segments.
789
790   typedef std::vector<Output_segment*> Segment_list;
791
792   // A list of sections.
793
794   typedef std::vector<Output_section*> Section_list;
795
796   // The list of information to write out which is not attached to
797   // either a section or a segment.
798   typedef std::vector<Output_data*> Data_list;
799
800   // Store the allocated sections into the section list.  This is used
801   // by the linker script code.
802   void
803   get_allocated_sections(Section_list*) const;
804
805   // Make a section for a linker script to hold data.
806   Output_section*
807   make_output_section_for_script(const char* name,
808                                  Script_sections::Section_type section_type);
809
810   // Make a segment.  This is used by the linker script code.
811   Output_segment*
812   make_output_segment(elfcpp::Elf_Word type, elfcpp::Elf_Word flags);
813
814   // Return the number of segments.
815   size_t
816   segment_count() const
817   { return this->segment_list_.size(); }
818
819   // Map from section flags to segment flags.
820   static elfcpp::Elf_Word
821   section_flags_to_segment(elfcpp::Elf_Xword flags);
822
823   // Attach sections to segments.
824   void
825   attach_sections_to_segments();
826
827   // For relaxation clean up, we need to know output section data created
828   // from a linker script.
829   void
830   new_output_section_data_from_script(Output_section_data* posd)
831   {
832     if (this->record_output_section_data_from_script_)
833       this->script_output_section_data_list_.push_back(posd);
834   }
835
836   // Return section list.
837   const Section_list&
838   section_list() const
839   { return this->section_list_; }
840
841  private:
842   Layout(const Layout&);
843   Layout& operator=(const Layout&);
844
845   // Mapping from input section names to output section names.
846   struct Section_name_mapping
847   {
848     const char* from;
849     int fromlen;
850     const char* to;
851     int tolen;
852   };
853   static const Section_name_mapping section_name_mapping[];
854   static const int section_name_mapping_count;
855
856   // During a relocatable link, a list of group sections and
857   // signatures.
858   struct Group_signature
859   {
860     // The group section.
861     Output_section* section;
862     // The signature.
863     const char* signature;
864
865     Group_signature()
866       : section(NULL), signature(NULL)
867     { }
868
869     Group_signature(Output_section* sectiona, const char* signaturea)
870       : section(sectiona), signature(signaturea)
871     { }
872   };
873   typedef std::vector<Group_signature> Group_signatures;
874
875   // Create a note section, filling in the header.
876   Output_section*
877   create_note(const char* name, int note_type, const char* section_name,
878               size_t descsz, bool allocate, size_t* trailing_padding);
879
880   // Create a note section for gold version.
881   void
882   create_gold_note();
883
884   // Record whether the stack must be executable.
885   void
886   create_executable_stack_info();
887
888   // Create a build ID note if needed.
889   void
890   create_build_id();
891
892   // Link .stab and .stabstr sections.
893   void
894   link_stabs_sections();
895
896   // Create .gnu_incremental_inputs and .gnu_incremental_strtab sections needed
897   // for the next run of incremental linking to check what has changed.
898   void
899   create_incremental_info_sections(Symbol_table*);
900
901   // Find the first read-only PT_LOAD segment, creating one if
902   // necessary.
903   Output_segment*
904   find_first_load_seg();
905
906   // Count the local symbols in the regular symbol table and the dynamic
907   // symbol table, and build the respective string pools.
908   void
909   count_local_symbols(const Task*, const Input_objects*);
910
911   // Create the output sections for the symbol table.
912   void
913   create_symtab_sections(const Input_objects*, Symbol_table*,
914                          unsigned int, off_t*);
915
916   // Create the .shstrtab section.
917   Output_section*
918   create_shstrtab();
919
920   // Create the section header table.
921   void
922   create_shdrs(const Output_section* shstrtab_section, off_t*);
923
924   // Create the dynamic symbol table.
925   void
926   create_dynamic_symtab(const Input_objects*, Symbol_table*,
927                         Output_section** pdynstr,
928                         unsigned int* plocal_dynamic_count,
929                         std::vector<Symbol*>* pdynamic_symbols,
930                         Versions* versions);
931
932   // Assign offsets to each local portion of the dynamic symbol table.
933   void
934   assign_local_dynsym_offsets(const Input_objects*);
935
936   // Finish the .dynamic section and PT_DYNAMIC segment.
937   void
938   finish_dynamic_section(const Input_objects*, const Symbol_table*);
939
940   // Set the size of the _DYNAMIC symbol.
941   void
942   set_dynamic_symbol_size(const Symbol_table*);
943
944   // Create the .interp section and PT_INTERP segment.
945   void
946   create_interp(const Target* target);
947
948   // Create the version sections.
949   void
950   create_version_sections(const Versions*,
951                           const Symbol_table*,
952                           unsigned int local_symcount,
953                           const std::vector<Symbol*>& dynamic_symbols,
954                           const Output_section* dynstr);
955
956   template<int size, bool big_endian>
957   void
958   sized_create_version_sections(const Versions* versions,
959                                 const Symbol_table*,
960                                 unsigned int local_symcount,
961                                 const std::vector<Symbol*>& dynamic_symbols,
962                                 const Output_section* dynstr);
963
964   // Return whether to include this section in the link.
965   template<int size, bool big_endian>
966   bool
967   include_section(Sized_relobj_file<size, big_endian>* object, const char* name,
968                   const elfcpp::Shdr<size, big_endian>&);
969
970   // Return the output section name to use given an input section
971   // name.  Set *PLEN to the length of the name.  *PLEN must be
972   // initialized to the length of NAME.
973   static const char*
974   output_section_name(const Relobj*, const char* name, size_t* plen);
975
976   // Return the number of allocated output sections.
977   size_t
978   allocated_output_section_count() const;
979
980   // Return the output section for NAME, TYPE and FLAGS.
981   Output_section*
982   get_output_section(const char* name, Stringpool::Key name_key,
983                      elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
984                      Output_section_order order, bool is_relro);
985
986   // Choose the output section for NAME in RELOBJ.
987   Output_section*
988   choose_output_section(const Relobj* relobj, const char* name,
989                         elfcpp::Elf_Word type, elfcpp::Elf_Xword flags,
990                         bool is_input_section, Output_section_order order,
991                         bool is_relro);
992
993   // Create a new Output_section.
994   Output_section*
995   make_output_section(const char* name, elfcpp::Elf_Word type,
996                       elfcpp::Elf_Xword flags, Output_section_order order,
997                       bool is_relro);
998
999   // Attach a section to a segment.
1000   void
1001   attach_section_to_segment(Output_section*);
1002
1003   // Get section order.
1004   Output_section_order
1005   default_section_order(Output_section*, bool is_relro_local);
1006
1007   // Attach an allocated section to a segment.
1008   void
1009   attach_allocated_section_to_segment(Output_section*);
1010
1011   // Set the final file offsets of all the segments.
1012   off_t
1013   set_segment_offsets(const Target*, Output_segment*, unsigned int* pshndx);
1014
1015   // Set the file offsets of the sections when doing a relocatable
1016   // link.
1017   off_t
1018   set_relocatable_section_offsets(Output_data*, unsigned int* pshndx);
1019
1020   // Set the final file offsets of all the sections not associated
1021   // with a segment.  We set section offsets in three passes: the
1022   // first handles all allocated sections, the second sections that
1023   // require postprocessing, and the last the late-bound STRTAB
1024   // sections (probably only shstrtab, which is the one we care about
1025   // because it holds section names).
1026   enum Section_offset_pass
1027   {
1028     BEFORE_INPUT_SECTIONS_PASS,
1029     POSTPROCESSING_SECTIONS_PASS,
1030     STRTAB_AFTER_POSTPROCESSING_SECTIONS_PASS
1031   };
1032   off_t
1033   set_section_offsets(off_t, Section_offset_pass pass);
1034
1035   // Set the final section indexes of all the sections not associated
1036   // with a segment.  Returns the next unused index.
1037   unsigned int
1038   set_section_indexes(unsigned int pshndx);
1039
1040   // Set the section addresses when using a script.
1041   Output_segment*
1042   set_section_addresses_from_script(Symbol_table*);
1043
1044   // Find appropriate places or orphan sections in a script.
1045   void
1046   place_orphan_sections_in_script();
1047
1048   // Return whether SEG1 comes before SEG2 in the output file.
1049   static bool
1050   segment_precedes(const Output_segment* seg1, const Output_segment* seg2);
1051
1052   // Use to save and restore segments during relaxation. 
1053   typedef Unordered_map<const Output_segment*, const Output_segment*>
1054     Segment_states;
1055
1056   // Save states of current output segments.
1057   void
1058   save_segments(Segment_states*);
1059
1060   // Restore output segment states.
1061   void
1062   restore_segments(const Segment_states*);
1063
1064   // Clean up after relaxation so that it is possible to lay out the
1065   // sections and segments again.
1066   void
1067   clean_up_after_relaxation();
1068
1069   // Doing preparation work for relaxation.  This is factored out to make
1070   // Layout::finalized a bit smaller and easier to read.
1071   void
1072   prepare_for_relaxation();
1073
1074   // Main body of the relaxation loop, which lays out the section.
1075   off_t
1076   relaxation_loop_body(int, Target*, Symbol_table*, Output_segment**,
1077                        Output_segment*, Output_segment_headers*,
1078                        Output_file_header*, unsigned int*);
1079
1080   // A mapping used for kept comdats/.gnu.linkonce group signatures.
1081   typedef Unordered_map<std::string, Kept_section> Signatures;
1082
1083   // Mapping from input section name/type/flags to output section.  We
1084   // use canonicalized strings here.
1085
1086   typedef std::pair<Stringpool::Key,
1087                     std::pair<elfcpp::Elf_Word, elfcpp::Elf_Xword> > Key;
1088
1089   struct Hash_key
1090   {
1091     size_t
1092     operator()(const Key& k) const;
1093   };
1094
1095   typedef Unordered_map<Key, Output_section*, Hash_key> Section_name_map;
1096
1097   // A comparison class for segments.
1098
1099   struct Compare_segments
1100   {
1101     bool
1102     operator()(const Output_segment* seg1, const Output_segment* seg2)
1103     { return Layout::segment_precedes(seg1, seg2); }
1104   };
1105
1106   typedef std::vector<Output_section_data*> Output_section_data_list;
1107
1108   // Debug checker class.
1109   class Relaxation_debug_check
1110   {
1111    public:
1112     Relaxation_debug_check()
1113       : section_infos_()
1114     { }
1115  
1116     // Check that sections and special data are in reset states.
1117     void
1118     check_output_data_for_reset_values(const Layout::Section_list&,
1119                                        const Layout::Data_list&);
1120   
1121     // Record information of a section list.
1122     void
1123     read_sections(const Layout::Section_list&);
1124
1125     // Verify a section list with recorded information.
1126     void
1127     verify_sections(const Layout::Section_list&);
1128  
1129    private:
1130     // Information we care about a section.
1131     struct Section_info
1132     {
1133       // Output section described by this.
1134       Output_section* output_section;
1135       // Load address.
1136       uint64_t address;
1137       // Data size.
1138       off_t data_size;
1139       // File offset.
1140       off_t offset;
1141     };
1142
1143     // Section information.
1144     std::vector<Section_info> section_infos_;
1145   };
1146
1147   // The number of input files, for sizing tables.
1148   int number_of_input_files_;
1149   // Information set by scripts or by command line options.
1150   Script_options* script_options_;
1151   // The output section names.
1152   Stringpool namepool_;
1153   // The output symbol names.
1154   Stringpool sympool_;
1155   // The dynamic strings, if needed.
1156   Stringpool dynpool_;
1157   // The list of group sections and linkonce sections which we have seen.
1158   Signatures signatures_;
1159   // The mapping from input section name/type/flags to output sections.
1160   Section_name_map section_name_map_;
1161   // The list of output segments.
1162   Segment_list segment_list_;
1163   // The list of output sections.
1164   Section_list section_list_;
1165   // The list of output sections which are not attached to any output
1166   // segment.
1167   Section_list unattached_section_list_;
1168   // The list of unattached Output_data objects which require special
1169   // handling because they are not Output_sections.
1170   Data_list special_output_list_;
1171   // The section headers.
1172   Output_section_headers* section_headers_;
1173   // A pointer to the PT_TLS segment if there is one.
1174   Output_segment* tls_segment_;
1175   // A pointer to the PT_GNU_RELRO segment if there is one.
1176   Output_segment* relro_segment_;
1177   // A pointer to the PT_INTERP segment if there is one.
1178   Output_segment* interp_segment_;
1179   // A backend may increase the size of the PT_GNU_RELRO segment if
1180   // there is one.  This is the amount to increase it by.
1181   unsigned int increase_relro_;
1182   // The SHT_SYMTAB output section.
1183   Output_section* symtab_section_;
1184   // The SHT_SYMTAB_SHNDX for the regular symbol table if there is one.
1185   Output_symtab_xindex* symtab_xindex_;
1186   // The SHT_DYNSYM output section if there is one.
1187   Output_section* dynsym_section_;
1188   // The SHT_SYMTAB_SHNDX for the dynamic symbol table if there is one.
1189   Output_symtab_xindex* dynsym_xindex_;
1190   // The SHT_DYNAMIC output section if there is one.
1191   Output_section* dynamic_section_;
1192   // The _DYNAMIC symbol if there is one.
1193   Symbol* dynamic_symbol_;
1194   // The dynamic data which goes into dynamic_section_.
1195   Output_data_dynamic* dynamic_data_;
1196   // The exception frame output section if there is one.
1197   Output_section* eh_frame_section_;
1198   // The exception frame data for eh_frame_section_.
1199   Eh_frame* eh_frame_data_;
1200   // Whether we have added eh_frame_data_ to the .eh_frame section.
1201   bool added_eh_frame_data_;
1202   // The exception frame header output section if there is one.
1203   Output_section* eh_frame_hdr_section_;
1204   // The space for the build ID checksum if there is one.
1205   Output_section_data* build_id_note_;
1206   // The output section containing dwarf abbreviations
1207   Output_reduced_debug_abbrev_section* debug_abbrev_;
1208   // The output section containing the dwarf debug info tree
1209   Output_reduced_debug_info_section* debug_info_;
1210   // A list of group sections and their signatures.
1211   Group_signatures group_signatures_;
1212   // The size of the output file.
1213   off_t output_file_size_;
1214   // Whether we have added an input section to an output section.
1215   bool have_added_input_section_;
1216   // Whether we have attached the sections to the segments.
1217   bool sections_are_attached_;
1218   // Whether we have seen an object file marked to require an
1219   // executable stack.
1220   bool input_requires_executable_stack_;
1221   // Whether we have seen at least one object file with an executable
1222   // stack marker.
1223   bool input_with_gnu_stack_note_;
1224   // Whether we have seen at least one object file without an
1225   // executable stack marker.
1226   bool input_without_gnu_stack_note_;
1227   // Whether we have seen an object file that uses the static TLS model.
1228   bool has_static_tls_;
1229   // Whether any sections require postprocessing.
1230   bool any_postprocessing_sections_;
1231   // Whether we have resized the signatures_ hash table.
1232   bool resized_signatures_;
1233   // Whether we have created a .stab*str output section.
1234   bool have_stabstr_section_;
1235   // In incremental build, holds information check the inputs and build the
1236   // .gnu_incremental_inputs section.
1237   Incremental_inputs* incremental_inputs_;
1238   // Whether we record output section data created in script
1239   bool record_output_section_data_from_script_;
1240   // List of output data that needs to be removed at relaxation clean up.
1241   Output_section_data_list script_output_section_data_list_;
1242   // Structure to save segment states before entering the relaxation loop.
1243   Segment_states* segment_states_;
1244   // A relaxation debug checker.  We only create one when in debugging mode.
1245   Relaxation_debug_check* relaxation_debug_check_;
1246   // Hash a pattern to its position in the section ordering file.
1247   Unordered_map<std::string, unsigned int> input_section_position_;
1248   // Vector of glob only patterns in the section_ordering file.
1249   std::vector<std::string> input_section_glob_;
1250   // For incremental links, the base file to be modified.
1251   Incremental_binary* incremental_base_;
1252   // For incremental links, a list of free space within the file.
1253   Free_list free_list_;
1254 };
1255
1256 // This task handles writing out data in output sections which is not
1257 // part of an input section, or which requires special handling.  When
1258 // this is done, it unblocks both output_sections_blocker and
1259 // final_blocker.
1260
1261 class Write_sections_task : public Task
1262 {
1263  public:
1264   Write_sections_task(const Layout* layout, Output_file* of,
1265                       Task_token* output_sections_blocker,
1266                       Task_token* final_blocker)
1267     : layout_(layout), of_(of),
1268       output_sections_blocker_(output_sections_blocker),
1269       final_blocker_(final_blocker)
1270   { }
1271
1272   // The standard Task methods.
1273
1274   Task_token*
1275   is_runnable();
1276
1277   void
1278   locks(Task_locker*);
1279
1280   void
1281   run(Workqueue*);
1282
1283   std::string
1284   get_name() const
1285   { return "Write_sections_task"; }
1286
1287  private:
1288   class Write_sections_locker;
1289
1290   const Layout* layout_;
1291   Output_file* of_;
1292   Task_token* output_sections_blocker_;
1293   Task_token* final_blocker_;
1294 };
1295
1296 // This task handles writing out data which is not part of a section
1297 // or segment.
1298
1299 class Write_data_task : public Task
1300 {
1301  public:
1302   Write_data_task(const Layout* layout, const Symbol_table* symtab,
1303                   Output_file* of, Task_token* final_blocker)
1304     : layout_(layout), symtab_(symtab), of_(of), final_blocker_(final_blocker)
1305   { }
1306
1307   // The standard Task methods.
1308
1309   Task_token*
1310   is_runnable();
1311
1312   void
1313   locks(Task_locker*);
1314
1315   void
1316   run(Workqueue*);
1317
1318   std::string
1319   get_name() const
1320   { return "Write_data_task"; }
1321
1322  private:
1323   const Layout* layout_;
1324   const Symbol_table* symtab_;
1325   Output_file* of_;
1326   Task_token* final_blocker_;
1327 };
1328
1329 // This task handles writing out the global symbols.
1330
1331 class Write_symbols_task : public Task
1332 {
1333  public:
1334   Write_symbols_task(const Layout* layout, const Symbol_table* symtab,
1335                      const Input_objects* input_objects,
1336                      const Stringpool* sympool, const Stringpool* dynpool,
1337                      Output_file* of, Task_token* final_blocker)
1338     : layout_(layout), symtab_(symtab), input_objects_(input_objects),
1339       sympool_(sympool), dynpool_(dynpool), of_(of),
1340       final_blocker_(final_blocker)
1341   { }
1342
1343   // The standard Task methods.
1344
1345   Task_token*
1346   is_runnable();
1347
1348   void
1349   locks(Task_locker*);
1350
1351   void
1352   run(Workqueue*);
1353
1354   std::string
1355   get_name() const
1356   { return "Write_symbols_task"; }
1357
1358  private:
1359   const Layout* layout_;
1360   const Symbol_table* symtab_;
1361   const Input_objects* input_objects_;
1362   const Stringpool* sympool_;
1363   const Stringpool* dynpool_;
1364   Output_file* of_;
1365   Task_token* final_blocker_;
1366 };
1367
1368 // This task handles writing out data in output sections which can't
1369 // be written out until all the input sections have been handled.
1370 // This is for sections whose contents is based on the contents of
1371 // other output sections.
1372
1373 class Write_after_input_sections_task : public Task
1374 {
1375  public:
1376   Write_after_input_sections_task(Layout* layout, Output_file* of,
1377                                   Task_token* input_sections_blocker,
1378                                   Task_token* final_blocker)
1379     : layout_(layout), of_(of),
1380       input_sections_blocker_(input_sections_blocker),
1381       final_blocker_(final_blocker)
1382   { }
1383
1384   // The standard Task methods.
1385
1386   Task_token*
1387   is_runnable();
1388
1389   void
1390   locks(Task_locker*);
1391
1392   void
1393   run(Workqueue*);
1394
1395   std::string
1396   get_name() const
1397   { return "Write_after_input_sections_task"; }
1398
1399  private:
1400   Layout* layout_;
1401   Output_file* of_;
1402   Task_token* input_sections_blocker_;
1403   Task_token* final_blocker_;
1404 };
1405
1406 // This task function handles closing the file.
1407
1408 class Close_task_runner : public Task_function_runner
1409 {
1410  public:
1411   Close_task_runner(const General_options* options, const Layout* layout,
1412                     Output_file* of)
1413     : options_(options), layout_(layout), of_(of)
1414   { }
1415
1416   // Run the operation.
1417   void
1418   run(Workqueue*, const Task*);
1419
1420  private:
1421   const General_options* options_;
1422   const Layout* layout_;
1423   Output_file* of_;
1424 };
1425
1426 // A small helper function to align an address.
1427
1428 inline uint64_t
1429 align_address(uint64_t address, uint64_t addralign)
1430 {
1431   if (addralign != 0)
1432     address = (address + addralign - 1) &~ (addralign - 1);
1433   return address;
1434 }
1435
1436 } // End namespace gold.
1437
1438 #endif // !defined(GOLD_LAYOUT_H)