Copyright update for binutils
[external/binutils.git] / gold / script-sections.cc
1 // script-sections.cc -- linker script SECTIONS for gold
2
3 // Copyright (C) 2008-2016 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 <list>
28 #include <map>
29 #include <string>
30 #include <vector>
31 #include <fnmatch.h>
32
33 #include "parameters.h"
34 #include "object.h"
35 #include "layout.h"
36 #include "output.h"
37 #include "script-c.h"
38 #include "script.h"
39 #include "script-sections.h"
40
41 // Support for the SECTIONS clause in linker scripts.
42
43 namespace gold
44 {
45
46 // A region of memory.
47 class Memory_region
48 {
49  public:
50   Memory_region(const char* name, size_t namelen, unsigned int attributes,
51                 Expression* start, Expression* length)
52     : name_(name, namelen),
53       attributes_(attributes),
54       start_(start),
55       length_(length),
56       current_offset_(0),
57       vma_sections_(),
58       lma_sections_(),
59       last_section_(NULL)
60   { }
61
62   // Return the name of this region.
63   const std::string&
64   name() const
65   { return this->name_; }
66
67   // Return the start address of this region.
68   Expression*
69   start_address() const
70   { return this->start_; }
71
72   // Return the length of this region.
73   Expression*
74   length() const
75   { return this->length_; }
76
77   // Print the region (when debugging).
78   void
79   print(FILE*) const;
80
81   // Return true if <name,namelen> matches this region.
82   bool
83   name_match(const char* name, size_t namelen)
84   {
85     return (this->name_.length() == namelen
86             && strncmp(this->name_.c_str(), name, namelen) == 0);
87   }
88
89   Expression*
90   get_current_address() const
91   {
92     return
93       script_exp_binary_add(this->start_,
94                             script_exp_integer(this->current_offset_));
95   }
96
97   void
98   set_address(uint64_t addr, const Symbol_table* symtab, const Layout* layout)
99   {
100     uint64_t start = this->start_->eval(symtab, layout, false);
101     uint64_t len = this->length_->eval(symtab, layout, false);
102     if (addr < start || addr >= start + len)
103       gold_error(_("address 0x%llx is not within region %s"),
104                  static_cast<unsigned long long>(addr),
105                  this->name_.c_str());
106     else if (addr < start + this->current_offset_)
107       gold_error(_("address 0x%llx moves dot backwards in region %s"),
108                  static_cast<unsigned long long>(addr),
109                  this->name_.c_str());
110     this->current_offset_ = addr - start;
111   }
112
113   void
114   increment_offset(std::string section_name, uint64_t amount,
115                    const Symbol_table* symtab, const Layout* layout)
116   {
117     this->current_offset_ += amount;
118
119     if (this->current_offset_
120         > this->length_->eval(symtab, layout, false))
121       gold_error(_("section %s overflows end of region %s"),
122                  section_name.c_str(), this->name_.c_str());
123   }
124
125   // Returns true iff there is room left in this region
126   // for AMOUNT more bytes of data.
127   bool
128   has_room_for(const Symbol_table* symtab, const Layout* layout,
129                uint64_t amount) const
130   {
131     return (this->current_offset_ + amount
132             < this->length_->eval(symtab, layout, false));
133   }
134
135   // Return true if the provided section flags
136   // are compatible with this region's attributes.
137   bool
138   attributes_compatible(elfcpp::Elf_Xword flags, elfcpp::Elf_Xword type) const;
139
140   void
141   add_section(Output_section_definition* sec, bool vma)
142   {
143     if (vma)
144       this->vma_sections_.push_back(sec);
145     else
146       this->lma_sections_.push_back(sec);
147   }
148
149   typedef std::vector<Output_section_definition*> Section_list;
150
151   // Return the start of the list of sections
152   // whose VMAs are taken from this region.
153   Section_list::const_iterator
154   get_vma_section_list_start() const
155   { return this->vma_sections_.begin(); }
156
157   // Return the start of the list of sections
158   // whose LMAs are taken from this region.
159   Section_list::const_iterator
160   get_lma_section_list_start() const
161   { return this->lma_sections_.begin(); }
162
163   // Return the end of the list of sections
164   // whose VMAs are taken from this region.
165   Section_list::const_iterator
166   get_vma_section_list_end() const
167   { return this->vma_sections_.end(); }
168
169   // Return the end of the list of sections
170   // whose LMAs are taken from this region.
171   Section_list::const_iterator
172   get_lma_section_list_end() const
173   { return this->lma_sections_.end(); }
174
175   Output_section_definition*
176   get_last_section() const
177   { return this->last_section_; }
178
179   void
180   set_last_section(Output_section_definition* sec)
181   { this->last_section_ = sec; }
182
183  private:
184
185   std::string name_;
186   unsigned int attributes_;
187   Expression* start_;
188   Expression* length_;
189   // The offset to the next free byte in the region.
190   // Note - for compatibility with GNU LD we only maintain one offset
191   // regardless of whether the region is being used for VMA values,
192   // LMA values, or both.
193   uint64_t current_offset_;
194   // A list of sections whose VMAs are set inside this region.
195   Section_list vma_sections_;
196   // A list of sections whose LMAs are set inside this region.
197   Section_list lma_sections_;
198   // The latest section to make use of this region.
199   Output_section_definition* last_section_;
200 };
201
202 // Return true if the provided section flags
203 // are compatible with this region's attributes.
204
205 bool
206 Memory_region::attributes_compatible(elfcpp::Elf_Xword flags,
207                                      elfcpp::Elf_Xword type) const
208 {
209   unsigned int attrs = this->attributes_;
210
211   // No attributes means that this region is not compatible with anything.
212   if (attrs == 0)
213     return false;
214
215   bool match = true;
216   do
217     {
218       switch (attrs & - attrs)
219         {
220         case MEM_EXECUTABLE:
221           if ((flags & elfcpp::SHF_EXECINSTR) == 0)
222             match = false;
223           break;
224
225         case MEM_WRITEABLE:
226           if ((flags & elfcpp::SHF_WRITE) == 0)
227             match = false;
228           break;
229
230         case MEM_READABLE:
231           // All sections are presumed readable.
232           break;
233
234         case MEM_ALLOCATABLE:
235           if ((flags & elfcpp::SHF_ALLOC) == 0)
236             match = false;
237           break;
238
239         case MEM_INITIALIZED:
240           if ((type & elfcpp::SHT_NOBITS) != 0)
241             match = false;
242           break;
243         }
244       attrs &= ~ (attrs & - attrs);
245     }
246   while (attrs != 0);
247   
248   return match;
249 }
250   
251 // Print a memory region.
252
253 void
254 Memory_region::print(FILE* f) const
255 {
256   fprintf(f, "  %s", this->name_.c_str());
257
258   unsigned int attrs = this->attributes_;
259   if (attrs != 0)
260     {
261       fprintf(f, " (");
262       do
263         {
264           switch (attrs & - attrs)
265             {
266             case MEM_EXECUTABLE:  fputc('x', f); break;
267             case MEM_WRITEABLE:   fputc('w', f); break;
268             case MEM_READABLE:    fputc('r', f); break;
269             case MEM_ALLOCATABLE: fputc('a', f); break;
270             case MEM_INITIALIZED: fputc('i', f); break;
271             default:
272               gold_unreachable();
273             }
274           attrs &= ~ (attrs & - attrs);
275         }
276       while (attrs != 0);
277       fputc(')', f);
278     }
279
280   fprintf(f, " : origin = ");
281   this->start_->print(f);
282   fprintf(f, ", length = ");
283   this->length_->print(f);
284   fprintf(f, "\n");
285 }
286
287 // Manage orphan sections.  This is intended to be largely compatible
288 // with the GNU linker.  The Linux kernel implicitly relies on
289 // something similar to the GNU linker's orphan placement.  We
290 // originally used a simpler scheme here, but it caused the kernel
291 // build to fail, and was also rather inefficient.
292
293 class Orphan_section_placement
294 {
295  private:
296   typedef Script_sections::Elements_iterator Elements_iterator;
297
298  public:
299   Orphan_section_placement();
300
301   // Handle an output section during initialization of this mapping.
302   void
303   output_section_init(const std::string& name, Output_section*,
304                       Elements_iterator location);
305
306   // Initialize the last location.
307   void
308   last_init(Elements_iterator location);
309
310   // Set *PWHERE to the address of an iterator pointing to the
311   // location to use for an orphan section.  Return true if the
312   // iterator has a value, false otherwise.
313   bool
314   find_place(Output_section*, Elements_iterator** pwhere);
315
316   // Return the iterator being used for sections at the very end of
317   // the linker script.
318   Elements_iterator
319   last_place() const;
320
321  private:
322   // The places that we specifically recognize.  This list is copied
323   // from the GNU linker.
324   enum Place_index
325   {
326     PLACE_TEXT,
327     PLACE_RODATA,
328     PLACE_DATA,
329     PLACE_TLS,
330     PLACE_TLS_BSS,
331     PLACE_BSS,
332     PLACE_REL,
333     PLACE_INTERP,
334     PLACE_NONALLOC,
335     PLACE_LAST,
336     PLACE_MAX
337   };
338
339   // The information we keep for a specific place.
340   struct Place
341   {
342     // The name of sections for this place.
343     const char* name;
344     // Whether we have a location for this place.
345     bool have_location;
346     // The iterator for this place.
347     Elements_iterator location;
348   };
349
350   // Initialize one place element.
351   void
352   initialize_place(Place_index, const char*);
353
354   // The places.
355   Place places_[PLACE_MAX];
356   // True if this is the first call to output_section_init.
357   bool first_init_;
358 };
359
360 // Initialize Orphan_section_placement.
361
362 Orphan_section_placement::Orphan_section_placement()
363   : first_init_(true)
364 {
365   this->initialize_place(PLACE_TEXT, ".text");
366   this->initialize_place(PLACE_RODATA, ".rodata");
367   this->initialize_place(PLACE_DATA, ".data");
368   this->initialize_place(PLACE_TLS, NULL);
369   this->initialize_place(PLACE_TLS_BSS, NULL);
370   this->initialize_place(PLACE_BSS, ".bss");
371   this->initialize_place(PLACE_REL, NULL);
372   this->initialize_place(PLACE_INTERP, ".interp");
373   this->initialize_place(PLACE_NONALLOC, NULL);
374   this->initialize_place(PLACE_LAST, NULL);
375 }
376
377 // Initialize one place element.
378
379 void
380 Orphan_section_placement::initialize_place(Place_index index, const char* name)
381 {
382   this->places_[index].name = name;
383   this->places_[index].have_location = false;
384 }
385
386 // While initializing the Orphan_section_placement information, this
387 // is called once for each output section named in the linker script.
388 // If we found an output section during the link, it will be passed in
389 // OS.
390
391 void
392 Orphan_section_placement::output_section_init(const std::string& name,
393                                               Output_section* os,
394                                               Elements_iterator location)
395 {
396   bool first_init = this->first_init_;
397   this->first_init_ = false;
398
399   for (int i = 0; i < PLACE_MAX; ++i)
400     {
401       if (this->places_[i].name != NULL && this->places_[i].name == name)
402         {
403           if (this->places_[i].have_location)
404             {
405               // We have already seen a section with this name.
406               return;
407             }
408
409           this->places_[i].location = location;
410           this->places_[i].have_location = true;
411
412           // If we just found the .bss section, restart the search for
413           // an unallocated section.  This follows the GNU linker's
414           // behaviour.
415           if (i == PLACE_BSS)
416             this->places_[PLACE_NONALLOC].have_location = false;
417
418           return;
419         }
420     }
421
422   // Relocation sections.
423   if (!this->places_[PLACE_REL].have_location
424       && os != NULL
425       && (os->type() == elfcpp::SHT_REL || os->type() == elfcpp::SHT_RELA)
426       && (os->flags() & elfcpp::SHF_ALLOC) != 0)
427     {
428       this->places_[PLACE_REL].location = location;
429       this->places_[PLACE_REL].have_location = true;
430     }
431
432   // We find the location for unallocated sections by finding the
433   // first debugging or comment section after the BSS section (if
434   // there is one).
435   if (!this->places_[PLACE_NONALLOC].have_location
436       && (name == ".comment" || Layout::is_debug_info_section(name.c_str())))
437     {
438       // We add orphan sections after the location in PLACES_.  We
439       // want to store unallocated sections before LOCATION.  If this
440       // is the very first section, we can't use it.
441       if (!first_init)
442         {
443           --location;
444           this->places_[PLACE_NONALLOC].location = location;
445           this->places_[PLACE_NONALLOC].have_location = true;
446         }
447     }
448 }
449
450 // Initialize the last location.
451
452 void
453 Orphan_section_placement::last_init(Elements_iterator location)
454 {
455   this->places_[PLACE_LAST].location = location;
456   this->places_[PLACE_LAST].have_location = true;
457 }
458
459 // Set *PWHERE to the address of an iterator pointing to the location
460 // to use for an orphan section.  Return true if the iterator has a
461 // value, false otherwise.
462
463 bool
464 Orphan_section_placement::find_place(Output_section* os,
465                                      Elements_iterator** pwhere)
466 {
467   // Figure out where OS should go.  This is based on the GNU linker
468   // code.  FIXME: The GNU linker handles small data sections
469   // specially, but we don't.
470   elfcpp::Elf_Word type = os->type();
471   elfcpp::Elf_Xword flags = os->flags();
472   Place_index index;
473   if ((flags & elfcpp::SHF_ALLOC) == 0
474       && !Layout::is_debug_info_section(os->name()))
475     index = PLACE_NONALLOC;
476   else if ((flags & elfcpp::SHF_ALLOC) == 0)
477     index = PLACE_LAST;
478   else if (type == elfcpp::SHT_NOTE)
479     index = PLACE_INTERP;
480   else if ((flags & elfcpp::SHF_TLS) != 0)
481     {
482       if (type == elfcpp::SHT_NOBITS)
483         index = PLACE_TLS_BSS;
484       else
485         index = PLACE_TLS;
486     }
487   else if (type == elfcpp::SHT_NOBITS)
488     index = PLACE_BSS;
489   else if ((flags & elfcpp::SHF_WRITE) != 0)
490     index = PLACE_DATA;
491   else if (type == elfcpp::SHT_REL || type == elfcpp::SHT_RELA)
492     index = PLACE_REL;
493   else if ((flags & elfcpp::SHF_EXECINSTR) == 0)
494     index = PLACE_RODATA;
495   else
496     index = PLACE_TEXT;
497
498   // If we don't have a location yet, try to find one based on a
499   // plausible ordering of sections.
500   if (!this->places_[index].have_location)
501     {
502       Place_index follow;
503       switch (index)
504         {
505         default:
506           follow = PLACE_MAX;
507           break;
508         case PLACE_RODATA:
509           follow = PLACE_TEXT;
510           break;
511         case PLACE_BSS:
512           follow = PLACE_DATA;
513           break;
514         case PLACE_REL:
515           follow = PLACE_TEXT;
516           break;
517         case PLACE_INTERP:
518           follow = PLACE_TEXT;
519           break;
520         case PLACE_TLS:
521           follow = PLACE_DATA;
522           break;
523         case PLACE_TLS_BSS:
524           follow = PLACE_TLS;
525           if (!this->places_[PLACE_TLS].have_location)
526             follow = PLACE_DATA;
527           break;
528         }
529       if (follow != PLACE_MAX && this->places_[follow].have_location)
530         {
531           // Set the location of INDEX to the location of FOLLOW.  The
532           // location of INDEX will then be incremented by the caller,
533           // so anything in INDEX will continue to be after anything
534           // in FOLLOW.
535           this->places_[index].location = this->places_[follow].location;
536           this->places_[index].have_location = true;
537         }
538     }
539
540   *pwhere = &this->places_[index].location;
541   bool ret = this->places_[index].have_location;
542
543   // The caller will set the location.
544   this->places_[index].have_location = true;
545
546   return ret;
547 }
548
549 // Return the iterator being used for sections at the very end of the
550 // linker script.
551
552 Orphan_section_placement::Elements_iterator
553 Orphan_section_placement::last_place() const
554 {
555   gold_assert(this->places_[PLACE_LAST].have_location);
556   return this->places_[PLACE_LAST].location;
557 }
558
559 // An element in a SECTIONS clause.
560
561 class Sections_element
562 {
563  public:
564   Sections_element()
565   { }
566
567   virtual ~Sections_element()
568   { }
569
570   // Return whether an output section is relro.
571   virtual bool
572   is_relro() const
573   { return false; }
574
575   // Record that an output section is relro.
576   virtual void
577   set_is_relro()
578   { }
579
580   // Create any required output sections.  The only real
581   // implementation is in Output_section_definition.
582   virtual void
583   create_sections(Layout*)
584   { }
585
586   // Add any symbol being defined to the symbol table.
587   virtual void
588   add_symbols_to_table(Symbol_table*)
589   { }
590
591   // Finalize symbols and check assertions.
592   virtual void
593   finalize_symbols(Symbol_table*, const Layout*, uint64_t*)
594   { }
595
596   // Return the output section name to use for an input file name and
597   // section name.  This only real implementation is in
598   // Output_section_definition.
599   virtual const char*
600   output_section_name(const char*, const char*, Output_section***,
601                       Script_sections::Section_type*, bool*)
602   { return NULL; }
603
604   // Initialize OSP with an output section.
605   virtual void
606   orphan_section_init(Orphan_section_placement*,
607                       Script_sections::Elements_iterator)
608   { }
609
610   // Set section addresses.  This includes applying assignments if the
611   // expression is an absolute value.
612   virtual void
613   set_section_addresses(Symbol_table*, Layout*, uint64_t*, uint64_t*,
614                         uint64_t*)
615   { }
616
617   // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
618   // this section is constrained, and the input sections do not match,
619   // return the constraint, and set *POSD.
620   virtual Section_constraint
621   check_constraint(Output_section_definition**)
622   { return CONSTRAINT_NONE; }
623
624   // See if this is the alternate output section for a constrained
625   // output section.  If it is, transfer the Output_section and return
626   // true.  Otherwise return false.
627   virtual bool
628   alternate_constraint(Output_section_definition*, Section_constraint)
629   { return false; }
630
631   // Get the list of segments to use for an allocated section when
632   // using a PHDRS clause.  If this is an allocated section, return
633   // the Output_section, and set *PHDRS_LIST (the first parameter) to
634   // the list of PHDRS to which it should be attached.  If the PHDRS
635   // were not specified, don't change *PHDRS_LIST.  When not returning
636   // NULL, set *ORPHAN (the second parameter) according to whether
637   // this is an orphan section--one that is not mentioned in the
638   // linker script.
639   virtual Output_section*
640   allocate_to_segment(String_list**, bool*)
641   { return NULL; }
642
643   // Look for an output section by name and return the address, the
644   // load address, the alignment, and the size.  This is used when an
645   // expression refers to an output section which was not actually
646   // created.  This returns true if the section was found, false
647   // otherwise.  The only real definition is for
648   // Output_section_definition.
649   virtual bool
650   get_output_section_info(const char*, uint64_t*, uint64_t*, uint64_t*,
651                           uint64_t*) const
652   { return false; }
653
654   // Return the associated Output_section if there is one.
655   virtual Output_section*
656   get_output_section() const
657   { return NULL; }
658
659   // Set the section's memory regions.
660   virtual void
661   set_memory_region(Memory_region*, bool)
662   { gold_error(_("Attempt to set a memory region for a non-output section")); }
663
664   // Print the element for debugging purposes.
665   virtual void
666   print(FILE* f) const = 0;
667 };
668
669 // An assignment in a SECTIONS clause outside of an output section.
670
671 class Sections_element_assignment : public Sections_element
672 {
673  public:
674   Sections_element_assignment(const char* name, size_t namelen,
675                               Expression* val, bool provide, bool hidden)
676     : assignment_(name, namelen, false, val, provide, hidden)
677   { }
678
679   // Add the symbol to the symbol table.
680   void
681   add_symbols_to_table(Symbol_table* symtab)
682   { this->assignment_.add_to_table(symtab); }
683
684   // Finalize the symbol.
685   void
686   finalize_symbols(Symbol_table* symtab, const Layout* layout,
687                    uint64_t* dot_value)
688   {
689     this->assignment_.finalize_with_dot(symtab, layout, *dot_value, NULL);
690   }
691
692   // Set the section address.  There is no section here, but if the
693   // value is absolute, we set the symbol.  This permits us to use
694   // absolute symbols when setting dot.
695   void
696   set_section_addresses(Symbol_table* symtab, Layout* layout,
697                         uint64_t* dot_value, uint64_t*, uint64_t*)
698   {
699     this->assignment_.set_if_absolute(symtab, layout, true, *dot_value, NULL);
700   }
701
702   // Print for debugging.
703   void
704   print(FILE* f) const
705   {
706     fprintf(f, "  ");
707     this->assignment_.print(f);
708   }
709
710  private:
711   Symbol_assignment assignment_;
712 };
713
714 // An assignment to the dot symbol in a SECTIONS clause outside of an
715 // output section.
716
717 class Sections_element_dot_assignment : public Sections_element
718 {
719  public:
720   Sections_element_dot_assignment(Expression* val)
721     : val_(val)
722   { }
723
724   // Finalize the symbol.
725   void
726   finalize_symbols(Symbol_table* symtab, const Layout* layout,
727                    uint64_t* dot_value)
728   {
729     // We ignore the section of the result because outside of an
730     // output section definition the dot symbol is always considered
731     // to be absolute.
732     *dot_value = this->val_->eval_with_dot(symtab, layout, true, *dot_value,
733                                            NULL, NULL, NULL, false);
734   }
735
736   // Update the dot symbol while setting section addresses.
737   void
738   set_section_addresses(Symbol_table* symtab, Layout* layout,
739                         uint64_t* dot_value, uint64_t* dot_alignment,
740                         uint64_t* load_address)
741   {
742     *dot_value = this->val_->eval_with_dot(symtab, layout, false, *dot_value,
743                                            NULL, NULL, dot_alignment, false);
744     *load_address = *dot_value;
745   }
746
747   // Print for debugging.
748   void
749   print(FILE* f) const
750   {
751     fprintf(f, "  . = ");
752     this->val_->print(f);
753     fprintf(f, "\n");
754   }
755
756  private:
757   Expression* val_;
758 };
759
760 // An assertion in a SECTIONS clause outside of an output section.
761
762 class Sections_element_assertion : public Sections_element
763 {
764  public:
765   Sections_element_assertion(Expression* check, const char* message,
766                              size_t messagelen)
767     : assertion_(check, message, messagelen)
768   { }
769
770   // Check the assertion.
771   void
772   finalize_symbols(Symbol_table* symtab, const Layout* layout, uint64_t*)
773   { this->assertion_.check(symtab, layout); }
774
775   // Print for debugging.
776   void
777   print(FILE* f) const
778   {
779     fprintf(f, "  ");
780     this->assertion_.print(f);
781   }
782
783  private:
784   Script_assertion assertion_;
785 };
786
787 // An element in an output section in a SECTIONS clause.
788
789 class Output_section_element
790 {
791  public:
792   // A list of input sections.
793   typedef std::list<Output_section::Input_section> Input_section_list;
794
795   Output_section_element()
796   { }
797
798   virtual ~Output_section_element()
799   { }
800
801   // Return whether this element requires an output section to exist.
802   virtual bool
803   needs_output_section() const
804   { return false; }
805
806   // Add any symbol being defined to the symbol table.
807   virtual void
808   add_symbols_to_table(Symbol_table*)
809   { }
810
811   // Finalize symbols and check assertions.
812   virtual void
813   finalize_symbols(Symbol_table*, const Layout*, uint64_t*, Output_section**)
814   { }
815
816   // Return whether this element matches FILE_NAME and SECTION_NAME.
817   // The only real implementation is in Output_section_element_input.
818   virtual bool
819   match_name(const char*, const char*, bool *) const
820   { return false; }
821
822   // Set section addresses.  This includes applying assignments if the
823   // expression is an absolute value.
824   virtual void
825   set_section_addresses(Symbol_table*, Layout*, Output_section*, uint64_t,
826                         uint64_t*, uint64_t*, Output_section**, std::string*,
827                         Input_section_list*)
828   { }
829
830   // Print the element for debugging purposes.
831   virtual void
832   print(FILE* f) const = 0;
833
834  protected:
835   // Return a fill string that is LENGTH bytes long, filling it with
836   // FILL.
837   std::string
838   get_fill_string(const std::string* fill, section_size_type length) const;
839 };
840
841 std::string
842 Output_section_element::get_fill_string(const std::string* fill,
843                                         section_size_type length) const
844 {
845   std::string this_fill;
846   this_fill.reserve(length);
847   while (this_fill.length() + fill->length() <= length)
848     this_fill += *fill;
849   if (this_fill.length() < length)
850     this_fill.append(*fill, 0, length - this_fill.length());
851   return this_fill;
852 }
853
854 // A symbol assignment in an output section.
855
856 class Output_section_element_assignment : public Output_section_element
857 {
858  public:
859   Output_section_element_assignment(const char* name, size_t namelen,
860                                     Expression* val, bool provide,
861                                     bool hidden)
862     : assignment_(name, namelen, false, val, provide, hidden)
863   { }
864
865   // Add the symbol to the symbol table.
866   void
867   add_symbols_to_table(Symbol_table* symtab)
868   { this->assignment_.add_to_table(symtab); }
869
870   // Finalize the symbol.
871   void
872   finalize_symbols(Symbol_table* symtab, const Layout* layout,
873                    uint64_t* dot_value, Output_section** dot_section)
874   {
875     this->assignment_.finalize_with_dot(symtab, layout, *dot_value,
876                                         *dot_section);
877   }
878
879   // Set the section address.  There is no section here, but if the
880   // value is absolute, we set the symbol.  This permits us to use
881   // absolute symbols when setting dot.
882   void
883   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
884                         uint64_t, uint64_t* dot_value, uint64_t*,
885                         Output_section** dot_section, std::string*,
886                         Input_section_list*)
887   {
888     this->assignment_.set_if_absolute(symtab, layout, true, *dot_value,
889                                       *dot_section);
890   }
891
892   // Print for debugging.
893   void
894   print(FILE* f) const
895   {
896     fprintf(f, "    ");
897     this->assignment_.print(f);
898   }
899
900  private:
901   Symbol_assignment assignment_;
902 };
903
904 // An assignment to the dot symbol in an output section.
905
906 class Output_section_element_dot_assignment : public Output_section_element
907 {
908  public:
909   Output_section_element_dot_assignment(Expression* val)
910     : val_(val)
911   { }
912
913   // An assignment to dot within an output section is enough to force
914   // the output section to exist.
915   bool
916   needs_output_section() const
917   { return true; }
918
919   // Finalize the symbol.
920   void
921   finalize_symbols(Symbol_table* symtab, const Layout* layout,
922                    uint64_t* dot_value, Output_section** dot_section)
923   {
924     *dot_value = this->val_->eval_with_dot(symtab, layout, true, *dot_value,
925                                            *dot_section, dot_section, NULL,
926                                            true);
927   }
928
929   // Update the dot symbol while setting section addresses.
930   void
931   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
932                         uint64_t, uint64_t* dot_value, uint64_t*,
933                         Output_section** dot_section, std::string*,
934                         Input_section_list*);
935
936   // Print for debugging.
937   void
938   print(FILE* f) const
939   {
940     fprintf(f, "    . = ");
941     this->val_->print(f);
942     fprintf(f, "\n");
943   }
944
945  private:
946   Expression* val_;
947 };
948
949 // Update the dot symbol while setting section addresses.
950
951 void
952 Output_section_element_dot_assignment::set_section_addresses(
953     Symbol_table* symtab,
954     Layout* layout,
955     Output_section* output_section,
956     uint64_t,
957     uint64_t* dot_value,
958     uint64_t* dot_alignment,
959     Output_section** dot_section,
960     std::string* fill,
961     Input_section_list*)
962 {
963   uint64_t next_dot = this->val_->eval_with_dot(symtab, layout, false,
964                                                 *dot_value, *dot_section,
965                                                 dot_section, dot_alignment,
966                                                 true);
967   if (next_dot < *dot_value)
968     gold_error(_("dot may not move backward"));
969   if (next_dot > *dot_value && output_section != NULL)
970     {
971       section_size_type length = convert_to_section_size_type(next_dot
972                                                               - *dot_value);
973       Output_section_data* posd;
974       if (fill->empty())
975         posd = new Output_data_zero_fill(length, 0);
976       else
977         {
978           std::string this_fill = this->get_fill_string(fill, length);
979           posd = new Output_data_const(this_fill, 0);
980         }
981       output_section->add_output_section_data(posd);
982       layout->new_output_section_data_from_script(posd);
983     }
984   *dot_value = next_dot;
985 }
986
987 // An assertion in an output section.
988
989 class Output_section_element_assertion : public Output_section_element
990 {
991  public:
992   Output_section_element_assertion(Expression* check, const char* message,
993                                    size_t messagelen)
994     : assertion_(check, message, messagelen)
995   { }
996
997   void
998   print(FILE* f) const
999   {
1000     fprintf(f, "    ");
1001     this->assertion_.print(f);
1002   }
1003
1004  private:
1005   Script_assertion assertion_;
1006 };
1007
1008 // We use a special instance of Output_section_data to handle BYTE,
1009 // SHORT, etc.  This permits forward references to symbols in the
1010 // expressions.
1011
1012 class Output_data_expression : public Output_section_data
1013 {
1014  public:
1015   Output_data_expression(int size, bool is_signed, Expression* val,
1016                          const Symbol_table* symtab, const Layout* layout,
1017                          uint64_t dot_value, Output_section* dot_section)
1018     : Output_section_data(size, 0, true),
1019       is_signed_(is_signed), val_(val), symtab_(symtab),
1020       layout_(layout), dot_value_(dot_value), dot_section_(dot_section)
1021   { }
1022
1023  protected:
1024   // Write the data to the output file.
1025   void
1026   do_write(Output_file*);
1027
1028   // Write the data to a buffer.
1029   void
1030   do_write_to_buffer(unsigned char*);
1031
1032   // Write to a map file.
1033   void
1034   do_print_to_mapfile(Mapfile* mapfile) const
1035   { mapfile->print_output_data(this, _("** expression")); }
1036
1037  private:
1038   template<bool big_endian>
1039   void
1040   endian_write_to_buffer(uint64_t, unsigned char*);
1041
1042   bool is_signed_;
1043   Expression* val_;
1044   const Symbol_table* symtab_;
1045   const Layout* layout_;
1046   uint64_t dot_value_;
1047   Output_section* dot_section_;
1048 };
1049
1050 // Write the data element to the output file.
1051
1052 void
1053 Output_data_expression::do_write(Output_file* of)
1054 {
1055   unsigned char* view = of->get_output_view(this->offset(), this->data_size());
1056   this->write_to_buffer(view);
1057   of->write_output_view(this->offset(), this->data_size(), view);
1058 }
1059
1060 // Write the data element to a buffer.
1061
1062 void
1063 Output_data_expression::do_write_to_buffer(unsigned char* buf)
1064 {
1065   uint64_t val = this->val_->eval_with_dot(this->symtab_, this->layout_,
1066                                            true, this->dot_value_,
1067                                            this->dot_section_, NULL, NULL,
1068                                            false);
1069
1070   if (parameters->target().is_big_endian())
1071     this->endian_write_to_buffer<true>(val, buf);
1072   else
1073     this->endian_write_to_buffer<false>(val, buf);
1074 }
1075
1076 template<bool big_endian>
1077 void
1078 Output_data_expression::endian_write_to_buffer(uint64_t val,
1079                                                unsigned char* buf)
1080 {
1081   switch (this->data_size())
1082     {
1083     case 1:
1084       elfcpp::Swap_unaligned<8, big_endian>::writeval(buf, val);
1085       break;
1086     case 2:
1087       elfcpp::Swap_unaligned<16, big_endian>::writeval(buf, val);
1088       break;
1089     case 4:
1090       elfcpp::Swap_unaligned<32, big_endian>::writeval(buf, val);
1091       break;
1092     case 8:
1093       if (parameters->target().get_size() == 32)
1094         {
1095           val &= 0xffffffff;
1096           if (this->is_signed_ && (val & 0x80000000) != 0)
1097             val |= 0xffffffff00000000LL;
1098         }
1099       elfcpp::Swap_unaligned<64, big_endian>::writeval(buf, val);
1100       break;
1101     default:
1102       gold_unreachable();
1103     }
1104 }
1105
1106 // A data item in an output section.
1107
1108 class Output_section_element_data : public Output_section_element
1109 {
1110  public:
1111   Output_section_element_data(int size, bool is_signed, Expression* val)
1112     : size_(size), is_signed_(is_signed), val_(val)
1113   { }
1114
1115   // If there is a data item, then we must create an output section.
1116   bool
1117   needs_output_section() const
1118   { return true; }
1119
1120   // Finalize symbols--we just need to update dot.
1121   void
1122   finalize_symbols(Symbol_table*, const Layout*, uint64_t* dot_value,
1123                    Output_section**)
1124   { *dot_value += this->size_; }
1125
1126   // Store the value in the section.
1127   void
1128   set_section_addresses(Symbol_table*, Layout*, Output_section*, uint64_t,
1129                         uint64_t* dot_value, uint64_t*, Output_section**,
1130                         std::string*, Input_section_list*);
1131
1132   // Print for debugging.
1133   void
1134   print(FILE*) const;
1135
1136  private:
1137   // The size in bytes.
1138   int size_;
1139   // Whether the value is signed.
1140   bool is_signed_;
1141   // The value.
1142   Expression* val_;
1143 };
1144
1145 // Store the value in the section.
1146
1147 void
1148 Output_section_element_data::set_section_addresses(
1149     Symbol_table* symtab,
1150     Layout* layout,
1151     Output_section* os,
1152     uint64_t,
1153     uint64_t* dot_value,
1154     uint64_t*,
1155     Output_section** dot_section,
1156     std::string*,
1157     Input_section_list*)
1158 {
1159   gold_assert(os != NULL);
1160   Output_data_expression* expression =
1161     new Output_data_expression(this->size_, this->is_signed_, this->val_,
1162                                symtab, layout, *dot_value, *dot_section);
1163   os->add_output_section_data(expression);
1164   layout->new_output_section_data_from_script(expression);
1165   *dot_value += this->size_;
1166 }
1167
1168 // Print for debugging.
1169
1170 void
1171 Output_section_element_data::print(FILE* f) const
1172 {
1173   const char* s;
1174   switch (this->size_)
1175     {
1176     case 1:
1177       s = "BYTE";
1178       break;
1179     case 2:
1180       s = "SHORT";
1181       break;
1182     case 4:
1183       s = "LONG";
1184       break;
1185     case 8:
1186       if (this->is_signed_)
1187         s = "SQUAD";
1188       else
1189         s = "QUAD";
1190       break;
1191     default:
1192       gold_unreachable();
1193     }
1194   fprintf(f, "    %s(", s);
1195   this->val_->print(f);
1196   fprintf(f, ")\n");
1197 }
1198
1199 // A fill value setting in an output section.
1200
1201 class Output_section_element_fill : public Output_section_element
1202 {
1203  public:
1204   Output_section_element_fill(Expression* val)
1205     : val_(val)
1206   { }
1207
1208   // Update the fill value while setting section addresses.
1209   void
1210   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
1211                         uint64_t, uint64_t* dot_value, uint64_t*,
1212                         Output_section** dot_section,
1213                         std::string* fill, Input_section_list*)
1214   {
1215     Output_section* fill_section;
1216     uint64_t fill_val = this->val_->eval_with_dot(symtab, layout, false,
1217                                                   *dot_value, *dot_section,
1218                                                   &fill_section, NULL, false);
1219     if (fill_section != NULL)
1220       gold_warning(_("fill value is not absolute"));
1221     // FIXME: The GNU linker supports fill values of arbitrary length.
1222     unsigned char fill_buff[4];
1223     elfcpp::Swap_unaligned<32, true>::writeval(fill_buff, fill_val);
1224     fill->assign(reinterpret_cast<char*>(fill_buff), 4);
1225   }
1226
1227   // Print for debugging.
1228   void
1229   print(FILE* f) const
1230   {
1231     fprintf(f, "    FILL(");
1232     this->val_->print(f);
1233     fprintf(f, ")\n");
1234   }
1235
1236  private:
1237   // The new fill value.
1238   Expression* val_;
1239 };
1240
1241 // An input section specification in an output section
1242
1243 class Output_section_element_input : public Output_section_element
1244 {
1245  public:
1246   Output_section_element_input(const Input_section_spec* spec, bool keep);
1247
1248   // Finalize symbols--just update the value of the dot symbol.
1249   void
1250   finalize_symbols(Symbol_table*, const Layout*, uint64_t* dot_value,
1251                    Output_section** dot_section)
1252   {
1253     *dot_value = this->final_dot_value_;
1254     *dot_section = this->final_dot_section_;
1255   }
1256
1257   // See whether we match FILE_NAME and SECTION_NAME as an input section.
1258   // If we do then also indicate whether the section should be KEPT.
1259   bool
1260   match_name(const char* file_name, const char* section_name, bool* keep) const;
1261
1262   // Set the section address.
1263   void
1264   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
1265                         uint64_t subalign, uint64_t* dot_value, uint64_t*,
1266                         Output_section**, std::string* fill,
1267                         Input_section_list*);
1268
1269   // Print for debugging.
1270   void
1271   print(FILE* f) const;
1272
1273  private:
1274   // An input section pattern.
1275   struct Input_section_pattern
1276   {
1277     std::string pattern;
1278     bool pattern_is_wildcard;
1279     Sort_wildcard sort;
1280
1281     Input_section_pattern(const char* patterna, size_t patternlena,
1282                           Sort_wildcard sorta)
1283       : pattern(patterna, patternlena),
1284         pattern_is_wildcard(is_wildcard_string(this->pattern.c_str())),
1285         sort(sorta)
1286     { }
1287   };
1288
1289   typedef std::vector<Input_section_pattern> Input_section_patterns;
1290
1291   // Filename_exclusions is a pair of filename pattern and a bool
1292   // indicating whether the filename is a wildcard.
1293   typedef std::vector<std::pair<std::string, bool> > Filename_exclusions;
1294
1295   // Return whether STRING matches PATTERN, where IS_WILDCARD_PATTERN
1296   // indicates whether this is a wildcard pattern.
1297   static inline bool
1298   match(const char* string, const char* pattern, bool is_wildcard_pattern)
1299   {
1300     return (is_wildcard_pattern
1301             ? fnmatch(pattern, string, 0) == 0
1302             : strcmp(string, pattern) == 0);
1303   }
1304
1305   // See if we match a file name.
1306   bool
1307   match_file_name(const char* file_name) const;
1308
1309   // The file name pattern.  If this is the empty string, we match all
1310   // files.
1311   std::string filename_pattern_;
1312   // Whether the file name pattern is a wildcard.
1313   bool filename_is_wildcard_;
1314   // How the file names should be sorted.  This may only be
1315   // SORT_WILDCARD_NONE or SORT_WILDCARD_BY_NAME.
1316   Sort_wildcard filename_sort_;
1317   // The list of file names to exclude.
1318   Filename_exclusions filename_exclusions_;
1319   // The list of input section patterns.
1320   Input_section_patterns input_section_patterns_;
1321   // Whether to keep this section when garbage collecting.
1322   bool keep_;
1323   // The value of dot after including all matching sections.
1324   uint64_t final_dot_value_;
1325   // The section where dot is defined after including all matching
1326   // sections.
1327   Output_section* final_dot_section_;
1328 };
1329
1330 // Construct Output_section_element_input.  The parser records strings
1331 // as pointers into a copy of the script file, which will go away when
1332 // parsing is complete.  We make sure they are in std::string objects.
1333
1334 Output_section_element_input::Output_section_element_input(
1335     const Input_section_spec* spec,
1336     bool keep)
1337   : filename_pattern_(),
1338     filename_is_wildcard_(false),
1339     filename_sort_(spec->file.sort),
1340     filename_exclusions_(),
1341     input_section_patterns_(),
1342     keep_(keep),
1343     final_dot_value_(0),
1344     final_dot_section_(NULL)
1345 {
1346   // The filename pattern "*" is common, and matches all files.  Turn
1347   // it into the empty string.
1348   if (spec->file.name.length != 1 || spec->file.name.value[0] != '*')
1349     this->filename_pattern_.assign(spec->file.name.value,
1350                                    spec->file.name.length);
1351   this->filename_is_wildcard_ = is_wildcard_string(this->filename_pattern_.c_str());
1352
1353   if (spec->input_sections.exclude != NULL)
1354     {
1355       for (String_list::const_iterator p =
1356              spec->input_sections.exclude->begin();
1357            p != spec->input_sections.exclude->end();
1358            ++p)
1359         {
1360           bool is_wildcard = is_wildcard_string((*p).c_str());
1361           this->filename_exclusions_.push_back(std::make_pair(*p,
1362                                                               is_wildcard));
1363         }
1364     }
1365
1366   if (spec->input_sections.sections != NULL)
1367     {
1368       Input_section_patterns& isp(this->input_section_patterns_);
1369       for (String_sort_list::const_iterator p =
1370              spec->input_sections.sections->begin();
1371            p != spec->input_sections.sections->end();
1372            ++p)
1373         isp.push_back(Input_section_pattern(p->name.value, p->name.length,
1374                                             p->sort));
1375     }
1376 }
1377
1378 // See whether we match FILE_NAME.
1379
1380 bool
1381 Output_section_element_input::match_file_name(const char* file_name) const
1382 {
1383   if (!this->filename_pattern_.empty())
1384     {
1385       // If we were called with no filename, we refuse to match a
1386       // pattern which requires a file name.
1387       if (file_name == NULL)
1388         return false;
1389
1390       if (!match(file_name, this->filename_pattern_.c_str(),
1391                  this->filename_is_wildcard_))
1392         return false;
1393     }
1394
1395   if (file_name != NULL)
1396     {
1397       // Now we have to see whether FILE_NAME matches one of the
1398       // exclusion patterns, if any.
1399       for (Filename_exclusions::const_iterator p =
1400              this->filename_exclusions_.begin();
1401            p != this->filename_exclusions_.end();
1402            ++p)
1403         {
1404           if (match(file_name, p->first.c_str(), p->second))
1405             return false;
1406         }
1407     }
1408
1409   return true;
1410 }
1411
1412 // See whether we match FILE_NAME and SECTION_NAME.  If we do then
1413 // KEEP indicates whether the section should survive garbage collection.
1414
1415 bool
1416 Output_section_element_input::match_name(const char* file_name,
1417                                          const char* section_name,
1418                                          bool *keep) const
1419 {
1420   if (!this->match_file_name(file_name))
1421     return false;
1422
1423   *keep = this->keep_;
1424
1425   // If there are no section name patterns, then we match.
1426   if (this->input_section_patterns_.empty())
1427     return true;
1428
1429   // See whether we match the section name patterns.
1430   for (Input_section_patterns::const_iterator p =
1431          this->input_section_patterns_.begin();
1432        p != this->input_section_patterns_.end();
1433        ++p)
1434     {
1435       if (match(section_name, p->pattern.c_str(), p->pattern_is_wildcard))
1436         return true;
1437     }
1438
1439   // We didn't match any section names, so we didn't match.
1440   return false;
1441 }
1442
1443 // Information we use to sort the input sections.
1444
1445 class Input_section_info
1446 {
1447  public:
1448   Input_section_info(const Output_section::Input_section& input_section)
1449     : input_section_(input_section), section_name_(),
1450       size_(0), addralign_(1)
1451   { }
1452
1453   // Return the simple input section.
1454   const Output_section::Input_section&
1455   input_section() const
1456   { return this->input_section_; }
1457
1458   // Return the object.
1459   Relobj*
1460   relobj() const
1461   { return this->input_section_.relobj(); }
1462
1463   // Return the section index.
1464   unsigned int
1465   shndx()
1466   { return this->input_section_.shndx(); }
1467
1468   // Return the section name.
1469   const std::string&
1470   section_name() const
1471   { return this->section_name_; }
1472
1473   // Set the section name.
1474   void
1475   set_section_name(const std::string name)
1476   {
1477     if (is_compressed_debug_section(name.c_str()))
1478       this->section_name_ = corresponding_uncompressed_section_name(name);
1479     else
1480       this->section_name_ = name;
1481   }
1482
1483   // Return the section size.
1484   uint64_t
1485   size() const
1486   { return this->size_; }
1487
1488   // Set the section size.
1489   void
1490   set_size(uint64_t size)
1491   { this->size_ = size; }
1492
1493   // Return the address alignment.
1494   uint64_t
1495   addralign() const
1496   { return this->addralign_; }
1497
1498   // Set the address alignment.
1499   void
1500   set_addralign(uint64_t addralign)
1501   { this->addralign_ = addralign; }
1502
1503  private:
1504   // Input section, can be a relaxed section.
1505   Output_section::Input_section input_section_;
1506   // Name of the section. 
1507   std::string section_name_;
1508   // Section size.
1509   uint64_t size_;
1510   // Address alignment.
1511   uint64_t addralign_;
1512 };
1513
1514 // A class to sort the input sections.
1515
1516 class Input_section_sorter
1517 {
1518  public:
1519   Input_section_sorter(Sort_wildcard filename_sort, Sort_wildcard section_sort)
1520     : filename_sort_(filename_sort), section_sort_(section_sort)
1521   { }
1522
1523   bool
1524   operator()(const Input_section_info&, const Input_section_info&) const;
1525
1526  private:
1527   Sort_wildcard filename_sort_;
1528   Sort_wildcard section_sort_;
1529 };
1530
1531 bool
1532 Input_section_sorter::operator()(const Input_section_info& isi1,
1533                                  const Input_section_info& isi2) const
1534 {
1535   if (this->section_sort_ == SORT_WILDCARD_BY_NAME
1536       || this->section_sort_ == SORT_WILDCARD_BY_NAME_BY_ALIGNMENT
1537       || (this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT_BY_NAME
1538           && isi1.addralign() == isi2.addralign()))
1539     {
1540       if (isi1.section_name() != isi2.section_name())
1541         return isi1.section_name() < isi2.section_name();
1542     }
1543   if (this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT
1544       || this->section_sort_ == SORT_WILDCARD_BY_NAME_BY_ALIGNMENT
1545       || this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT_BY_NAME)
1546     {
1547       if (isi1.addralign() != isi2.addralign())
1548         return isi1.addralign() < isi2.addralign();
1549     }
1550   if (this->filename_sort_ == SORT_WILDCARD_BY_NAME)
1551     {
1552       if (isi1.relobj()->name() != isi2.relobj()->name())
1553         return (isi1.relobj()->name() < isi2.relobj()->name());
1554     }
1555
1556   // Otherwise we leave them in the same order.
1557   return false;
1558 }
1559
1560 // Set the section address.  Look in INPUT_SECTIONS for sections which
1561 // match this spec, sort them as specified, and add them to the output
1562 // section.
1563
1564 void
1565 Output_section_element_input::set_section_addresses(
1566     Symbol_table*,
1567     Layout* layout,
1568     Output_section* output_section,
1569     uint64_t subalign,
1570     uint64_t* dot_value,
1571     uint64_t*,
1572     Output_section** dot_section,
1573     std::string* fill,
1574     Input_section_list* input_sections)
1575 {
1576   // We build a list of sections which match each
1577   // Input_section_pattern.
1578
1579   // If none of the patterns specify a sort option, we throw all
1580   // matching input sections into a single bin, in the order we
1581   // find them.  Otherwise, we put matching input sections into
1582   // a separate bin for each pattern, and sort each one as
1583   // specified.  Thus, an input section spec like this:
1584   //   *(.foo .bar)
1585   // will group all .foo and .bar sections in the order seen,
1586   // whereas this:
1587   //   *(.foo) *(.bar)
1588   // will group all .foo sections followed by all .bar sections.
1589   // This matches Gnu ld behavior.
1590
1591   // Things get really weird, though, when you add a sort spec
1592   // on some, but not all, of the patterns, like this:
1593   //   *(SORT_BY_NAME(.foo) .bar)
1594   // We do not attempt to match Gnu ld behavior in this case.
1595
1596   typedef std::vector<std::vector<Input_section_info> > Matching_sections;
1597   size_t input_pattern_count = this->input_section_patterns_.size();
1598   bool any_patterns_with_sort = false;
1599   for (size_t i = 0; i < input_pattern_count; ++i)
1600     {
1601       const Input_section_pattern& isp(this->input_section_patterns_[i]);
1602       if (isp.sort != SORT_WILDCARD_NONE)
1603         any_patterns_with_sort = true;
1604     }
1605   if (input_pattern_count == 0 || !any_patterns_with_sort)
1606     input_pattern_count = 1;
1607   Matching_sections matching_sections(input_pattern_count);
1608
1609   // Look through the list of sections for this output section.  Add
1610   // each one which matches to one of the elements of
1611   // MATCHING_SECTIONS.
1612
1613   Input_section_list::iterator p = input_sections->begin();
1614   while (p != input_sections->end())
1615     {
1616       Relobj* relobj = p->relobj();
1617       unsigned int shndx = p->shndx();      
1618       Input_section_info isi(*p);
1619
1620       // Calling section_name and section_addralign is not very
1621       // efficient.
1622
1623       // Lock the object so that we can get information about the
1624       // section.  This is OK since we know we are single-threaded
1625       // here.
1626       {
1627         const Task* task = reinterpret_cast<const Task*>(-1);
1628         Task_lock_obj<Object> tl(task, relobj);
1629
1630         isi.set_section_name(relobj->section_name(shndx));
1631         if (p->is_relaxed_input_section())
1632           {
1633             // We use current data size because relaxed section sizes may not
1634             // have finalized yet.
1635             isi.set_size(p->relaxed_input_section()->current_data_size());
1636             isi.set_addralign(p->relaxed_input_section()->addralign());
1637           }
1638         else
1639           {
1640             isi.set_size(relobj->section_size(shndx));
1641             isi.set_addralign(relobj->section_addralign(shndx));
1642           }
1643       }
1644
1645       if (!this->match_file_name(relobj->name().c_str()))
1646         ++p;
1647       else if (this->input_section_patterns_.empty())
1648         {
1649           matching_sections[0].push_back(isi);
1650           p = input_sections->erase(p);
1651         }
1652       else
1653         {
1654           size_t i;
1655           for (i = 0; i < input_pattern_count; ++i)
1656             {
1657               const Input_section_pattern&
1658                 isp(this->input_section_patterns_[i]);
1659               if (match(isi.section_name().c_str(), isp.pattern.c_str(),
1660                         isp.pattern_is_wildcard))
1661                 break;
1662             }
1663
1664           if (i >= this->input_section_patterns_.size())
1665             ++p;
1666           else
1667             {
1668               if (!any_patterns_with_sort)
1669                 i = 0;
1670               matching_sections[i].push_back(isi);
1671               p = input_sections->erase(p);
1672             }
1673         }
1674     }
1675
1676   // Look through MATCHING_SECTIONS.  Sort each one as specified,
1677   // using a stable sort so that we get the default order when
1678   // sections are otherwise equal.  Add each input section to the
1679   // output section.
1680
1681   uint64_t dot = *dot_value;
1682   for (size_t i = 0; i < input_pattern_count; ++i)
1683     {
1684       if (matching_sections[i].empty())
1685         continue;
1686
1687       gold_assert(output_section != NULL);
1688
1689       const Input_section_pattern& isp(this->input_section_patterns_[i]);
1690       if (isp.sort != SORT_WILDCARD_NONE
1691           || this->filename_sort_ != SORT_WILDCARD_NONE)
1692         std::stable_sort(matching_sections[i].begin(),
1693                          matching_sections[i].end(),
1694                          Input_section_sorter(this->filename_sort_,
1695                                               isp.sort));
1696
1697       for (std::vector<Input_section_info>::const_iterator p =
1698              matching_sections[i].begin();
1699            p != matching_sections[i].end();
1700            ++p)
1701         {
1702           // Override the original address alignment if SUBALIGN is specified
1703           // and is greater than the original alignment.  We need to make a
1704           // copy of the input section to modify the alignment.
1705           Output_section::Input_section sis(p->input_section());
1706
1707           uint64_t this_subalign = sis.addralign();
1708           if (!sis.is_input_section())
1709             sis.output_section_data()->finalize_data_size();    
1710           uint64_t data_size = sis.data_size();
1711           if (this_subalign < subalign)
1712             {
1713               this_subalign = subalign;
1714               sis.set_addralign(subalign);
1715             }
1716
1717           uint64_t address = align_address(dot, this_subalign);
1718
1719           if (address > dot && !fill->empty())
1720             {
1721               section_size_type length =
1722                 convert_to_section_size_type(address - dot);
1723               std::string this_fill = this->get_fill_string(fill, length);
1724               Output_section_data* posd = new Output_data_const(this_fill, 0);
1725               output_section->add_output_section_data(posd);
1726               layout->new_output_section_data_from_script(posd);
1727             }
1728
1729           output_section->add_script_input_section(sis);
1730           dot = address + data_size;
1731         }
1732     }
1733
1734   // An SHF_TLS/SHT_NOBITS section does not take up any
1735   // address space.
1736   if (output_section == NULL
1737       || (output_section->flags() & elfcpp::SHF_TLS) == 0
1738       || output_section->type() != elfcpp::SHT_NOBITS)
1739     *dot_value = dot;
1740
1741   this->final_dot_value_ = *dot_value;
1742   this->final_dot_section_ = *dot_section;
1743 }
1744
1745 // Print for debugging.
1746
1747 void
1748 Output_section_element_input::print(FILE* f) const
1749 {
1750   fprintf(f, "    ");
1751
1752   if (this->keep_)
1753     fprintf(f, "KEEP(");
1754
1755   if (!this->filename_pattern_.empty())
1756     {
1757       bool need_close_paren = false;
1758       switch (this->filename_sort_)
1759         {
1760         case SORT_WILDCARD_NONE:
1761           break;
1762         case SORT_WILDCARD_BY_NAME:
1763           fprintf(f, "SORT_BY_NAME(");
1764           need_close_paren = true;
1765           break;
1766         default:
1767           gold_unreachable();
1768         }
1769
1770       fprintf(f, "%s", this->filename_pattern_.c_str());
1771
1772       if (need_close_paren)
1773         fprintf(f, ")");
1774     }
1775
1776   if (!this->input_section_patterns_.empty()
1777       || !this->filename_exclusions_.empty())
1778     {
1779       fprintf(f, "(");
1780
1781       bool need_space = false;
1782       if (!this->filename_exclusions_.empty())
1783         {
1784           fprintf(f, "EXCLUDE_FILE(");
1785           bool need_comma = false;
1786           for (Filename_exclusions::const_iterator p =
1787                  this->filename_exclusions_.begin();
1788                p != this->filename_exclusions_.end();
1789                ++p)
1790             {
1791               if (need_comma)
1792                 fprintf(f, ", ");
1793               fprintf(f, "%s", p->first.c_str());
1794               need_comma = true;
1795             }
1796           fprintf(f, ")");
1797           need_space = true;
1798         }
1799
1800       for (Input_section_patterns::const_iterator p =
1801              this->input_section_patterns_.begin();
1802            p != this->input_section_patterns_.end();
1803            ++p)
1804         {
1805           if (need_space)
1806             fprintf(f, " ");
1807
1808           int close_parens = 0;
1809           switch (p->sort)
1810             {
1811             case SORT_WILDCARD_NONE:
1812               break;
1813             case SORT_WILDCARD_BY_NAME:
1814               fprintf(f, "SORT_BY_NAME(");
1815               close_parens = 1;
1816               break;
1817             case SORT_WILDCARD_BY_ALIGNMENT:
1818               fprintf(f, "SORT_BY_ALIGNMENT(");
1819               close_parens = 1;
1820               break;
1821             case SORT_WILDCARD_BY_NAME_BY_ALIGNMENT:
1822               fprintf(f, "SORT_BY_NAME(SORT_BY_ALIGNMENT(");
1823               close_parens = 2;
1824               break;
1825             case SORT_WILDCARD_BY_ALIGNMENT_BY_NAME:
1826               fprintf(f, "SORT_BY_ALIGNMENT(SORT_BY_NAME(");
1827               close_parens = 2;
1828               break;
1829             default:
1830               gold_unreachable();
1831             }
1832
1833           fprintf(f, "%s", p->pattern.c_str());
1834
1835           for (int i = 0; i < close_parens; ++i)
1836             fprintf(f, ")");
1837
1838           need_space = true;
1839         }
1840
1841       fprintf(f, ")");
1842     }
1843
1844   if (this->keep_)
1845     fprintf(f, ")");
1846
1847   fprintf(f, "\n");
1848 }
1849
1850 // An output section.
1851
1852 class Output_section_definition : public Sections_element
1853 {
1854  public:
1855   typedef Output_section_element::Input_section_list Input_section_list;
1856
1857   Output_section_definition(const char* name, size_t namelen,
1858                             const Parser_output_section_header* header);
1859
1860   // Finish the output section with the information in the trailer.
1861   void
1862   finish(const Parser_output_section_trailer* trailer);
1863
1864   // Add a symbol to be defined.
1865   void
1866   add_symbol_assignment(const char* name, size_t length, Expression* value,
1867                         bool provide, bool hidden);
1868
1869   // Add an assignment to the special dot symbol.
1870   void
1871   add_dot_assignment(Expression* value);
1872
1873   // Add an assertion.
1874   void
1875   add_assertion(Expression* check, const char* message, size_t messagelen);
1876
1877   // Add a data item to the current output section.
1878   void
1879   add_data(int size, bool is_signed, Expression* val);
1880
1881   // Add a setting for the fill value.
1882   void
1883   add_fill(Expression* val);
1884
1885   // Add an input section specification.
1886   void
1887   add_input_section(const Input_section_spec* spec, bool keep);
1888
1889   // Return whether the output section is relro.
1890   bool
1891   is_relro() const
1892   { return this->is_relro_; }
1893
1894   // Record that the output section is relro.
1895   void
1896   set_is_relro()
1897   { this->is_relro_ = true; }
1898
1899   // Create any required output sections.
1900   void
1901   create_sections(Layout*);
1902
1903   // Add any symbols being defined to the symbol table.
1904   void
1905   add_symbols_to_table(Symbol_table* symtab);
1906
1907   // Finalize symbols and check assertions.
1908   void
1909   finalize_symbols(Symbol_table*, const Layout*, uint64_t*);
1910
1911   // Return the output section name to use for an input file name and
1912   // section name.
1913   const char*
1914   output_section_name(const char* file_name, const char* section_name,
1915                       Output_section***, Script_sections::Section_type*,
1916                       bool*);
1917
1918   // Initialize OSP with an output section.
1919   void
1920   orphan_section_init(Orphan_section_placement* osp,
1921                       Script_sections::Elements_iterator p)
1922   { osp->output_section_init(this->name_, this->output_section_, p); }
1923
1924   // Set the section address.
1925   void
1926   set_section_addresses(Symbol_table* symtab, Layout* layout,
1927                         uint64_t* dot_value, uint64_t*,
1928                         uint64_t* load_address);
1929
1930   // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
1931   // this section is constrained, and the input sections do not match,
1932   // return the constraint, and set *POSD.
1933   Section_constraint
1934   check_constraint(Output_section_definition** posd);
1935
1936   // See if this is the alternate output section for a constrained
1937   // output section.  If it is, transfer the Output_section and return
1938   // true.  Otherwise return false.
1939   bool
1940   alternate_constraint(Output_section_definition*, Section_constraint);
1941
1942   // Get the list of segments to use for an allocated section when
1943   // using a PHDRS clause.
1944   Output_section*
1945   allocate_to_segment(String_list** phdrs_list, bool* orphan);
1946
1947   // Look for an output section by name and return the address, the
1948   // load address, the alignment, and the size.  This is used when an
1949   // expression refers to an output section which was not actually
1950   // created.  This returns true if the section was found, false
1951   // otherwise.
1952   bool
1953   get_output_section_info(const char*, uint64_t*, uint64_t*, uint64_t*,
1954                           uint64_t*) const;
1955
1956   // Return the associated Output_section if there is one.
1957   Output_section*
1958   get_output_section() const
1959   { return this->output_section_; }
1960
1961   // Print the contents to the FILE.  This is for debugging.
1962   void
1963   print(FILE*) const;
1964
1965   // Return the output section type if specified or Script_sections::ST_NONE.
1966   Script_sections::Section_type
1967   section_type() const;
1968
1969   // Store the memory region to use.
1970   void
1971   set_memory_region(Memory_region*, bool set_vma);
1972
1973   void
1974   set_section_vma(Expression* address)
1975   { this->address_ = address; }
1976   
1977   void
1978   set_section_lma(Expression* address)
1979   { this->load_address_ = address; }
1980
1981   const std::string&
1982   get_section_name() const
1983   { return this->name_; }
1984   
1985  private:
1986   static const char*
1987   script_section_type_name(Script_section_type);
1988
1989   typedef std::vector<Output_section_element*> Output_section_elements;
1990
1991   // The output section name.
1992   std::string name_;
1993   // The address.  This may be NULL.
1994   Expression* address_;
1995   // The load address.  This may be NULL.
1996   Expression* load_address_;
1997   // The alignment.  This may be NULL.
1998   Expression* align_;
1999   // The input section alignment.  This may be NULL.
2000   Expression* subalign_;
2001   // The constraint, if any.
2002   Section_constraint constraint_;
2003   // The fill value.  This may be NULL.
2004   Expression* fill_;
2005   // The list of segments this section should go into.  This may be
2006   // NULL.
2007   String_list* phdrs_;
2008   // The list of elements defining the section.
2009   Output_section_elements elements_;
2010   // The Output_section created for this definition.  This will be
2011   // NULL if none was created.
2012   Output_section* output_section_;
2013   // The address after it has been evaluated.
2014   uint64_t evaluated_address_;
2015   // The load address after it has been evaluated.
2016   uint64_t evaluated_load_address_;
2017   // The alignment after it has been evaluated.
2018   uint64_t evaluated_addralign_;
2019   // The output section is relro.
2020   bool is_relro_;
2021   // The output section type if specified.
2022   enum Script_section_type script_section_type_;
2023 };
2024
2025 // Constructor.
2026
2027 Output_section_definition::Output_section_definition(
2028     const char* name,
2029     size_t namelen,
2030     const Parser_output_section_header* header)
2031   : name_(name, namelen),
2032     address_(header->address),
2033     load_address_(header->load_address),
2034     align_(header->align),
2035     subalign_(header->subalign),
2036     constraint_(header->constraint),
2037     fill_(NULL),
2038     phdrs_(NULL),
2039     elements_(),
2040     output_section_(NULL),
2041     evaluated_address_(0),
2042     evaluated_load_address_(0),
2043     evaluated_addralign_(0),
2044     is_relro_(false),
2045     script_section_type_(header->section_type)
2046 {
2047 }
2048
2049 // Finish an output section.
2050
2051 void
2052 Output_section_definition::finish(const Parser_output_section_trailer* trailer)
2053 {
2054   this->fill_ = trailer->fill;
2055   this->phdrs_ = trailer->phdrs;
2056 }
2057
2058 // Add a symbol to be defined.
2059
2060 void
2061 Output_section_definition::add_symbol_assignment(const char* name,
2062                                                  size_t length,
2063                                                  Expression* value,
2064                                                  bool provide,
2065                                                  bool hidden)
2066 {
2067   Output_section_element* p = new Output_section_element_assignment(name,
2068                                                                     length,
2069                                                                     value,
2070                                                                     provide,
2071                                                                     hidden);
2072   this->elements_.push_back(p);
2073 }
2074
2075 // Add an assignment to the special dot symbol.
2076
2077 void
2078 Output_section_definition::add_dot_assignment(Expression* value)
2079 {
2080   Output_section_element* p = new Output_section_element_dot_assignment(value);
2081   this->elements_.push_back(p);
2082 }
2083
2084 // Add an assertion.
2085
2086 void
2087 Output_section_definition::add_assertion(Expression* check,
2088                                          const char* message,
2089                                          size_t messagelen)
2090 {
2091   Output_section_element* p = new Output_section_element_assertion(check,
2092                                                                    message,
2093                                                                    messagelen);
2094   this->elements_.push_back(p);
2095 }
2096
2097 // Add a data item to the current output section.
2098
2099 void
2100 Output_section_definition::add_data(int size, bool is_signed, Expression* val)
2101 {
2102   Output_section_element* p = new Output_section_element_data(size, is_signed,
2103                                                               val);
2104   this->elements_.push_back(p);
2105 }
2106
2107 // Add a setting for the fill value.
2108
2109 void
2110 Output_section_definition::add_fill(Expression* val)
2111 {
2112   Output_section_element* p = new Output_section_element_fill(val);
2113   this->elements_.push_back(p);
2114 }
2115
2116 // Add an input section specification.
2117
2118 void
2119 Output_section_definition::add_input_section(const Input_section_spec* spec,
2120                                              bool keep)
2121 {
2122   Output_section_element* p = new Output_section_element_input(spec, keep);
2123   this->elements_.push_back(p);
2124 }
2125
2126 // Create any required output sections.  We need an output section if
2127 // there is a data statement here.
2128
2129 void
2130 Output_section_definition::create_sections(Layout* layout)
2131 {
2132   if (this->output_section_ != NULL)
2133     return;
2134   for (Output_section_elements::const_iterator p = this->elements_.begin();
2135        p != this->elements_.end();
2136        ++p)
2137     {
2138       if ((*p)->needs_output_section())
2139         {
2140           const char* name = this->name_.c_str();
2141           this->output_section_ =
2142             layout->make_output_section_for_script(name, this->section_type());
2143           return;
2144         }
2145     }
2146 }
2147
2148 // Add any symbols being defined to the symbol table.
2149
2150 void
2151 Output_section_definition::add_symbols_to_table(Symbol_table* symtab)
2152 {
2153   for (Output_section_elements::iterator p = this->elements_.begin();
2154        p != this->elements_.end();
2155        ++p)
2156     (*p)->add_symbols_to_table(symtab);
2157 }
2158
2159 // Finalize symbols and check assertions.
2160
2161 void
2162 Output_section_definition::finalize_symbols(Symbol_table* symtab,
2163                                             const Layout* layout,
2164                                             uint64_t* dot_value)
2165 {
2166   if (this->output_section_ != NULL)
2167     *dot_value = this->output_section_->address();
2168   else
2169     {
2170       uint64_t address = *dot_value;
2171       if (this->address_ != NULL)
2172         {
2173           address = this->address_->eval_with_dot(symtab, layout, true,
2174                                                   *dot_value, NULL,
2175                                                   NULL, NULL, false);
2176         }
2177       if (this->align_ != NULL)
2178         {
2179           uint64_t align = this->align_->eval_with_dot(symtab, layout, true,
2180                                                        *dot_value, NULL,
2181                                                        NULL, NULL, false);
2182           address = align_address(address, align);
2183         }
2184       *dot_value = address;
2185     }
2186
2187   Output_section* dot_section = this->output_section_;
2188   for (Output_section_elements::iterator p = this->elements_.begin();
2189        p != this->elements_.end();
2190        ++p)
2191     (*p)->finalize_symbols(symtab, layout, dot_value, &dot_section);
2192 }
2193
2194 // Return the output section name to use for an input section name.
2195
2196 const char*
2197 Output_section_definition::output_section_name(
2198     const char* file_name,
2199     const char* section_name,
2200     Output_section*** slot,
2201     Script_sections::Section_type* psection_type,
2202     bool* keep)
2203 {
2204   // Ask each element whether it matches NAME.
2205   for (Output_section_elements::const_iterator p = this->elements_.begin();
2206        p != this->elements_.end();
2207        ++p)
2208     {
2209       if ((*p)->match_name(file_name, section_name, keep))
2210         {
2211           // We found a match for NAME, which means that it should go
2212           // into this output section.
2213           *slot = &this->output_section_;
2214           *psection_type = this->section_type();
2215           return this->name_.c_str();
2216         }
2217     }
2218
2219   // We don't know about this section name.
2220   return NULL;
2221 }
2222
2223 // Return true if memory from START to START + LENGTH is contained
2224 // within a memory region.
2225
2226 bool
2227 Script_sections::block_in_region(Symbol_table* symtab, Layout* layout,
2228                                  uint64_t start, uint64_t length) const
2229 {
2230   if (this->memory_regions_ == NULL)
2231     return false;
2232
2233   for (Memory_regions::const_iterator mr = this->memory_regions_->begin();
2234        mr != this->memory_regions_->end();
2235        ++mr)
2236     {
2237       uint64_t s = (*mr)->start_address()->eval(symtab, layout, false);
2238       uint64_t l = (*mr)->length()->eval(symtab, layout, false);
2239
2240       if (s <= start
2241           && (s + l) >= (start + length))
2242         return true;
2243     }
2244
2245   return false;
2246 }
2247
2248 // Find a memory region that should be used by a given output SECTION.
2249 // If provided set PREVIOUS_SECTION_RETURN to point to the last section
2250 // that used the return memory region.
2251
2252 Memory_region*
2253 Script_sections::find_memory_region(
2254     Output_section_definition* section,
2255     bool find_vma_region,
2256     bool explicit_only,
2257     Output_section_definition** previous_section_return)
2258 {
2259   if (previous_section_return != NULL)
2260     * previous_section_return = NULL;
2261
2262   // Walk the memory regions specified in this script, if any.
2263   if (this->memory_regions_ == NULL)
2264     return NULL;
2265
2266   // The /DISCARD/ section never gets assigned to any region.
2267   if (section->get_section_name() == "/DISCARD/")
2268     return NULL;
2269
2270   Memory_region* first_match = NULL;
2271
2272   // First check to see if a region has been assigned to this section.
2273   for (Memory_regions::const_iterator mr = this->memory_regions_->begin();
2274        mr != this->memory_regions_->end();
2275        ++mr)
2276     {
2277       if (find_vma_region)
2278         {
2279           for (Memory_region::Section_list::const_iterator s =
2280                  (*mr)->get_vma_section_list_start();
2281                s != (*mr)->get_vma_section_list_end();
2282                ++s)
2283             if ((*s) == section)
2284               {
2285                 (*mr)->set_last_section(section);
2286                 return *mr;
2287               }
2288         }
2289       else
2290         {
2291           for (Memory_region::Section_list::const_iterator s =
2292                  (*mr)->get_lma_section_list_start();
2293                s != (*mr)->get_lma_section_list_end();
2294                ++s)
2295             if ((*s) == section)
2296               {
2297                 (*mr)->set_last_section(section);
2298                 return *mr;
2299               }
2300         }
2301
2302       if (!explicit_only)
2303         {
2304           // Make a note of the first memory region whose attributes
2305           // are compatible with the section.  If we do not find an
2306           // explicit region assignment, then we will return this region.
2307           Output_section* out_sec = section->get_output_section();
2308           if (first_match == NULL
2309               && out_sec != NULL
2310               && (*mr)->attributes_compatible(out_sec->flags(),
2311                                               out_sec->type()))
2312             first_match = *mr;
2313         }
2314     }
2315
2316   // With LMA computations, if an explicit region has not been specified then
2317   // we will want to set the difference between the VMA and the LMA of the
2318   // section were searching for to be the same as the difference between the
2319   // VMA and LMA of the last section to be added to first matched region.
2320   // Hence, if it was asked for, we return a pointer to the last section
2321   // known to be used by the first matched region.
2322   if (first_match != NULL
2323       && previous_section_return != NULL)
2324     *previous_section_return = first_match->get_last_section();
2325
2326   return first_match;
2327 }
2328
2329 // Set the section address.  Note that the OUTPUT_SECTION_ field will
2330 // be NULL if no input sections were mapped to this output section.
2331 // We still have to adjust dot and process symbol assignments.
2332
2333 void
2334 Output_section_definition::set_section_addresses(Symbol_table* symtab,
2335                                                  Layout* layout,
2336                                                  uint64_t* dot_value,
2337                                                  uint64_t* dot_alignment,
2338                                                  uint64_t* load_address)
2339 {
2340   Memory_region* vma_region = NULL;
2341   Memory_region* lma_region = NULL;
2342   Script_sections* script_sections =
2343     layout->script_options()->script_sections();
2344   uint64_t address;
2345   uint64_t old_dot_value = *dot_value;
2346   uint64_t old_load_address = *load_address;
2347
2348   // If input section sorting is requested via --section-ordering-file or
2349   // linker plugins, then do it here.  This is important because we want 
2350   // any sorting specified in the linker scripts, which will be done after
2351   // this, to take precedence.  The final order of input sections is then 
2352   // guaranteed to be according to the linker script specification.
2353   if (this->output_section_ != NULL
2354       && this->output_section_->input_section_order_specified())
2355     this->output_section_->sort_attached_input_sections();
2356
2357   // Decide the start address for the section.  The algorithm is:
2358   // 1) If an address has been specified in a linker script, use that.
2359   // 2) Otherwise if a memory region has been specified for the section,
2360   //    use the next free address in the region.
2361   // 3) Otherwise if memory regions have been specified find the first
2362   //    region whose attributes are compatible with this section and
2363   //    install it into that region.
2364   // 4) Otherwise use the current location counter.
2365
2366   if (this->output_section_ != NULL
2367       // Check for --section-start.
2368       && parameters->options().section_start(this->output_section_->name(),
2369                                              &address))
2370     ;
2371   else if (this->address_ == NULL)
2372     {
2373       vma_region = script_sections->find_memory_region(this, true, false, NULL);
2374       if (vma_region != NULL)
2375         address = vma_region->get_current_address()->eval(symtab, layout,
2376                                                           false);
2377       else
2378         address = *dot_value;
2379     }
2380   else
2381     {
2382       vma_region = script_sections->find_memory_region(this, true, true, NULL);
2383       address = this->address_->eval_with_dot(symtab, layout, true,
2384                                               *dot_value, NULL, NULL,
2385                                               dot_alignment, false);
2386       if (vma_region != NULL)
2387         vma_region->set_address(address, symtab, layout);
2388     }
2389
2390   uint64_t align;
2391   if (this->align_ == NULL)
2392     {
2393       if (this->output_section_ == NULL)
2394         align = 0;
2395       else
2396         align = this->output_section_->addralign();
2397     }
2398   else
2399     {
2400       Output_section* align_section;
2401       align = this->align_->eval_with_dot(symtab, layout, true, *dot_value,
2402                                           NULL, &align_section, NULL, false);
2403       if (align_section != NULL)
2404         gold_warning(_("alignment of section %s is not absolute"),
2405                      this->name_.c_str());
2406       if (this->output_section_ != NULL)
2407         this->output_section_->set_addralign(align);
2408     }
2409
2410   address = align_address(address, align);
2411
2412   uint64_t start_address = address;
2413
2414   *dot_value = address;
2415
2416   // Except for NOLOAD sections, the address of non-SHF_ALLOC sections is
2417   // forced to zero, regardless of what the linker script wants.
2418   if (this->output_section_ != NULL
2419       && ((this->output_section_->flags() & elfcpp::SHF_ALLOC) != 0
2420           || this->output_section_->is_noload()))
2421     this->output_section_->set_address(address);
2422
2423   this->evaluated_address_ = address;
2424   this->evaluated_addralign_ = align;
2425
2426   uint64_t laddr;
2427
2428   if (this->load_address_ == NULL)
2429     {
2430       Output_section_definition* previous_section;
2431
2432       // Determine if an LMA region has been set for this section.
2433       lma_region = script_sections->find_memory_region(this, false, false,
2434                                                        &previous_section);
2435
2436       if (lma_region != NULL)
2437         {
2438           if (previous_section == NULL)
2439             // The LMA address was explicitly set to the given region.
2440             laddr = lma_region->get_current_address()->eval(symtab, layout,
2441                                                             false);
2442           else 
2443             {
2444               // We are not going to use the discovered lma_region, so
2445               // make sure that we do not update it in the code below.
2446               lma_region = NULL;
2447
2448               if (this->address_ != NULL || previous_section == this)
2449                 {
2450                   // Either an explicit VMA address has been set, or an
2451                   // explicit VMA region has been set, so set the LMA equal to
2452                   // the VMA.
2453                   laddr = address;
2454                 }
2455               else
2456                 {
2457                   // The LMA address was not explicitly or implicitly set.
2458                   //
2459                   // We have been given the first memory region that is
2460                   // compatible with the current section and a pointer to the
2461                   // last section to use this region.  Set the LMA of this
2462                   // section so that the difference between its' VMA and LMA
2463                   // is the same as the difference between the VMA and LMA of
2464                   // the last section in the given region.
2465                   laddr = address + (previous_section->evaluated_load_address_
2466                                      - previous_section->evaluated_address_);
2467                 }
2468             }
2469
2470           if (this->output_section_ != NULL)
2471             this->output_section_->set_load_address(laddr);
2472         }
2473       else
2474         {
2475           // Do not set the load address of the output section, if one exists.
2476           // This allows future sections to determine what the load address
2477           // should be.  If none is ever set, it will default to being the
2478           // same as the vma address.
2479           laddr = address;
2480         }
2481     }
2482   else
2483     {
2484       laddr = this->load_address_->eval_with_dot(symtab, layout, true,
2485                                                  *dot_value,
2486                                                  this->output_section_,
2487                                                  NULL, NULL, false);
2488       if (this->output_section_ != NULL)
2489         this->output_section_->set_load_address(laddr);
2490     }
2491
2492   this->evaluated_load_address_ = laddr;
2493
2494   uint64_t subalign;
2495   if (this->subalign_ == NULL)
2496     subalign = 0;
2497   else
2498     {
2499       Output_section* subalign_section;
2500       subalign = this->subalign_->eval_with_dot(symtab, layout, true,
2501                                                 *dot_value, NULL,
2502                                                 &subalign_section, NULL,
2503                                                 false);
2504       if (subalign_section != NULL)
2505         gold_warning(_("subalign of section %s is not absolute"),
2506                      this->name_.c_str());
2507     }
2508
2509   std::string fill;
2510   if (this->fill_ != NULL)
2511     {
2512       // FIXME: The GNU linker supports fill values of arbitrary
2513       // length.
2514       Output_section* fill_section;
2515       uint64_t fill_val = this->fill_->eval_with_dot(symtab, layout, true,
2516                                                      *dot_value,
2517                                                      NULL, &fill_section,
2518                                                      NULL, false);
2519       if (fill_section != NULL)
2520         gold_warning(_("fill of section %s is not absolute"),
2521                      this->name_.c_str());
2522       unsigned char fill_buff[4];
2523       elfcpp::Swap_unaligned<32, true>::writeval(fill_buff, fill_val);
2524       fill.assign(reinterpret_cast<char*>(fill_buff), 4);
2525     }
2526
2527   Input_section_list input_sections;
2528   if (this->output_section_ != NULL)
2529     {
2530       // Get the list of input sections attached to this output
2531       // section.  This will leave the output section with only
2532       // Output_section_data entries.
2533       address += this->output_section_->get_input_sections(address,
2534                                                            fill,
2535                                                            &input_sections);
2536       *dot_value = address;
2537     }
2538
2539   Output_section* dot_section = this->output_section_;
2540   for (Output_section_elements::iterator p = this->elements_.begin();
2541        p != this->elements_.end();
2542        ++p)
2543     (*p)->set_section_addresses(symtab, layout, this->output_section_,
2544                                 subalign, dot_value, dot_alignment,
2545                                 &dot_section, &fill, &input_sections);
2546
2547   gold_assert(input_sections.empty());
2548
2549   if (vma_region != NULL)
2550     {
2551       // Update the VMA region being used by the section now that we know how
2552       // big it is.  Use the current address in the region, rather than
2553       // start_address because that might have been aligned upwards and we
2554       // need to allow for the padding.
2555       Expression* addr = vma_region->get_current_address();
2556       uint64_t size = *dot_value - addr->eval(symtab, layout, false);
2557
2558       vma_region->increment_offset(this->get_section_name(), size,
2559                                    symtab, layout);
2560     }
2561
2562   // If the LMA region is different from the VMA region, then increment the
2563   // offset there as well.  Note that we use the same "dot_value -
2564   // start_address" formula that is used in the load_address assignment below.
2565   if (lma_region != NULL && lma_region != vma_region)
2566     lma_region->increment_offset(this->get_section_name(),
2567                                  *dot_value - start_address,
2568                                  symtab, layout);
2569
2570   // Compute the load address for the following section.
2571   if (this->output_section_ == NULL)
2572     *load_address = *dot_value;
2573   else if (this->load_address_ == NULL)
2574     {
2575       if (lma_region == NULL)
2576         *load_address = *dot_value;
2577       else
2578         *load_address =
2579           lma_region->get_current_address()->eval(symtab, layout, false);
2580     }
2581   else
2582     *load_address = (this->output_section_->load_address()
2583                      + (*dot_value - start_address));
2584
2585   if (this->output_section_ != NULL)
2586     {
2587       if (this->is_relro_)
2588         this->output_section_->set_is_relro();
2589       else
2590         this->output_section_->clear_is_relro();
2591
2592       // If this is a NOLOAD section, keep dot and load address unchanged.
2593       if (this->output_section_->is_noload())
2594         {
2595           *dot_value = old_dot_value;
2596           *load_address = old_load_address;
2597         }
2598     }
2599 }
2600
2601 // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
2602 // this section is constrained, and the input sections do not match,
2603 // return the constraint, and set *POSD.
2604
2605 Section_constraint
2606 Output_section_definition::check_constraint(Output_section_definition** posd)
2607 {
2608   switch (this->constraint_)
2609     {
2610     case CONSTRAINT_NONE:
2611       return CONSTRAINT_NONE;
2612
2613     case CONSTRAINT_ONLY_IF_RO:
2614       if (this->output_section_ != NULL
2615           && (this->output_section_->flags() & elfcpp::SHF_WRITE) != 0)
2616         {
2617           *posd = this;
2618           return CONSTRAINT_ONLY_IF_RO;
2619         }
2620       return CONSTRAINT_NONE;
2621
2622     case CONSTRAINT_ONLY_IF_RW:
2623       if (this->output_section_ != NULL
2624           && (this->output_section_->flags() & elfcpp::SHF_WRITE) == 0)
2625         {
2626           *posd = this;
2627           return CONSTRAINT_ONLY_IF_RW;
2628         }
2629       return CONSTRAINT_NONE;
2630
2631     case CONSTRAINT_SPECIAL:
2632       if (this->output_section_ != NULL)
2633         gold_error(_("SPECIAL constraints are not implemented"));
2634       return CONSTRAINT_NONE;
2635
2636     default:
2637       gold_unreachable();
2638     }
2639 }
2640
2641 // See if this is the alternate output section for a constrained
2642 // output section.  If it is, transfer the Output_section and return
2643 // true.  Otherwise return false.
2644
2645 bool
2646 Output_section_definition::alternate_constraint(
2647     Output_section_definition* posd,
2648     Section_constraint constraint)
2649 {
2650   if (this->name_ != posd->name_)
2651     return false;
2652
2653   switch (constraint)
2654     {
2655     case CONSTRAINT_ONLY_IF_RO:
2656       if (this->constraint_ != CONSTRAINT_ONLY_IF_RW)
2657         return false;
2658       break;
2659
2660     case CONSTRAINT_ONLY_IF_RW:
2661       if (this->constraint_ != CONSTRAINT_ONLY_IF_RO)
2662         return false;
2663       break;
2664
2665     default:
2666       gold_unreachable();
2667     }
2668
2669   // We have found the alternate constraint.  We just need to move
2670   // over the Output_section.  When constraints are used properly,
2671   // THIS should not have an output_section pointer, as all the input
2672   // sections should have matched the other definition.
2673
2674   if (this->output_section_ != NULL)
2675     gold_error(_("mismatched definition for constrained sections"));
2676
2677   this->output_section_ = posd->output_section_;
2678   posd->output_section_ = NULL;
2679
2680   if (this->is_relro_)
2681     this->output_section_->set_is_relro();
2682   else
2683     this->output_section_->clear_is_relro();
2684
2685   return true;
2686 }
2687
2688 // Get the list of segments to use for an allocated section when using
2689 // a PHDRS clause.
2690
2691 Output_section*
2692 Output_section_definition::allocate_to_segment(String_list** phdrs_list,
2693                                                bool* orphan)
2694 {
2695   // Update phdrs_list even if we don't have an output section. It
2696   // might be used by the following sections.
2697   if (this->phdrs_ != NULL)
2698     *phdrs_list = this->phdrs_;
2699
2700   if (this->output_section_ == NULL)
2701     return NULL;
2702   if ((this->output_section_->flags() & elfcpp::SHF_ALLOC) == 0)
2703     return NULL;
2704   *orphan = false;
2705   return this->output_section_;
2706 }
2707
2708 // Look for an output section by name and return the address, the load
2709 // address, the alignment, and the size.  This is used when an
2710 // expression refers to an output section which was not actually
2711 // created.  This returns true if the section was found, false
2712 // otherwise.
2713
2714 bool
2715 Output_section_definition::get_output_section_info(const char* name,
2716                                                    uint64_t* address,
2717                                                    uint64_t* load_address,
2718                                                    uint64_t* addralign,
2719                                                    uint64_t* size) const
2720 {
2721   if (this->name_ != name)
2722     return false;
2723
2724   if (this->output_section_ != NULL)
2725     {
2726       *address = this->output_section_->address();
2727       if (this->output_section_->has_load_address())
2728         *load_address = this->output_section_->load_address();
2729       else
2730         *load_address = *address;
2731       *addralign = this->output_section_->addralign();
2732       *size = this->output_section_->current_data_size();
2733     }
2734   else
2735     {
2736       *address = this->evaluated_address_;
2737       *load_address = this->evaluated_load_address_;
2738       *addralign = this->evaluated_addralign_;
2739       *size = 0;
2740     }
2741
2742   return true;
2743 }
2744
2745 // Print for debugging.
2746
2747 void
2748 Output_section_definition::print(FILE* f) const
2749 {
2750   fprintf(f, "  %s ", this->name_.c_str());
2751
2752   if (this->address_ != NULL)
2753     {
2754       this->address_->print(f);
2755       fprintf(f, " ");
2756     }
2757
2758   if (this->script_section_type_ != SCRIPT_SECTION_TYPE_NONE)
2759       fprintf(f, "(%s) ",
2760               this->script_section_type_name(this->script_section_type_));
2761
2762   fprintf(f, ": ");
2763
2764   if (this->load_address_ != NULL)
2765     {
2766       fprintf(f, "AT(");
2767       this->load_address_->print(f);
2768       fprintf(f, ") ");
2769     }
2770
2771   if (this->align_ != NULL)
2772     {
2773       fprintf(f, "ALIGN(");
2774       this->align_->print(f);
2775       fprintf(f, ") ");
2776     }
2777
2778   if (this->subalign_ != NULL)
2779     {
2780       fprintf(f, "SUBALIGN(");
2781       this->subalign_->print(f);
2782       fprintf(f, ") ");
2783     }
2784
2785   fprintf(f, "{\n");
2786
2787   for (Output_section_elements::const_iterator p = this->elements_.begin();
2788        p != this->elements_.end();
2789        ++p)
2790     (*p)->print(f);
2791
2792   fprintf(f, "  }");
2793
2794   if (this->fill_ != NULL)
2795     {
2796       fprintf(f, " = ");
2797       this->fill_->print(f);
2798     }
2799
2800   if (this->phdrs_ != NULL)
2801     {
2802       for (String_list::const_iterator p = this->phdrs_->begin();
2803            p != this->phdrs_->end();
2804            ++p)
2805         fprintf(f, " :%s", p->c_str());
2806     }
2807
2808   fprintf(f, "\n");
2809 }
2810
2811 Script_sections::Section_type
2812 Output_section_definition::section_type() const
2813 {
2814   switch (this->script_section_type_)
2815     {
2816     case SCRIPT_SECTION_TYPE_NONE:
2817       return Script_sections::ST_NONE;
2818     case SCRIPT_SECTION_TYPE_NOLOAD:
2819       return Script_sections::ST_NOLOAD;
2820     case SCRIPT_SECTION_TYPE_COPY:
2821     case SCRIPT_SECTION_TYPE_DSECT:
2822     case SCRIPT_SECTION_TYPE_INFO:
2823     case SCRIPT_SECTION_TYPE_OVERLAY:
2824       // There are not really support so we treat them as ST_NONE.  The
2825       // parse should have issued errors for them already.
2826       return Script_sections::ST_NONE;
2827     default:
2828       gold_unreachable();
2829     }
2830 }
2831
2832 // Return the name of a script section type.
2833
2834 const char*
2835 Output_section_definition::script_section_type_name(
2836     Script_section_type script_section_type)
2837 {
2838   switch (script_section_type)
2839     {
2840     case SCRIPT_SECTION_TYPE_NONE:
2841       return "NONE";
2842     case SCRIPT_SECTION_TYPE_NOLOAD:
2843       return "NOLOAD";
2844     case SCRIPT_SECTION_TYPE_DSECT:
2845       return "DSECT";
2846     case SCRIPT_SECTION_TYPE_COPY:
2847       return "COPY";
2848     case SCRIPT_SECTION_TYPE_INFO:
2849       return "INFO";
2850     case SCRIPT_SECTION_TYPE_OVERLAY:
2851       return "OVERLAY";
2852     default:
2853       gold_unreachable();
2854     }
2855 }
2856
2857 void
2858 Output_section_definition::set_memory_region(Memory_region* mr, bool set_vma)
2859 {
2860   gold_assert(mr != NULL);
2861   // Add the current section to the specified region's list.
2862   mr->add_section(this, set_vma);
2863 }
2864
2865 // An output section created to hold orphaned input sections.  These
2866 // do not actually appear in linker scripts.  However, for convenience
2867 // when setting the output section addresses, we put a marker to these
2868 // sections in the appropriate place in the list of SECTIONS elements.
2869
2870 class Orphan_output_section : public Sections_element
2871 {
2872  public:
2873   Orphan_output_section(Output_section* os)
2874     : os_(os)
2875   { }
2876
2877   // Return whether the orphan output section is relro.  We can just
2878   // check the output section because we always set the flag, if
2879   // needed, just after we create the Orphan_output_section.
2880   bool
2881   is_relro() const
2882   { return this->os_->is_relro(); }
2883
2884   // Initialize OSP with an output section.  This should have been
2885   // done already.
2886   void
2887   orphan_section_init(Orphan_section_placement*,
2888                       Script_sections::Elements_iterator)
2889   { gold_unreachable(); }
2890
2891   // Set section addresses.
2892   void
2893   set_section_addresses(Symbol_table*, Layout*, uint64_t*, uint64_t*,
2894                         uint64_t*);
2895
2896   // Get the list of segments to use for an allocated section when
2897   // using a PHDRS clause.
2898   Output_section*
2899   allocate_to_segment(String_list**, bool*);
2900
2901   // Return the associated Output_section.
2902   Output_section*
2903   get_output_section() const
2904   { return this->os_; }
2905
2906   // Print for debugging.
2907   void
2908   print(FILE* f) const
2909   {
2910     fprintf(f, "  marker for orphaned output section %s\n",
2911             this->os_->name());
2912   }
2913
2914  private:
2915   Output_section* os_;
2916 };
2917
2918 // Set section addresses.
2919
2920 void
2921 Orphan_output_section::set_section_addresses(Symbol_table*, Layout*,
2922                                              uint64_t* dot_value,
2923                                              uint64_t*,
2924                                              uint64_t* load_address)
2925 {
2926   typedef std::list<Output_section::Input_section> Input_section_list;
2927
2928   bool have_load_address = *load_address != *dot_value;
2929
2930   uint64_t address = *dot_value;
2931   address = align_address(address, this->os_->addralign());
2932
2933   // If input section sorting is requested via --section-ordering-file or
2934   // linker plugins, then do it here.  This is important because we want 
2935   // any sorting specified in the linker scripts, which will be done after
2936   // this, to take precedence.  The final order of input sections is then 
2937   // guaranteed to be according to the linker script specification.
2938   if (this->os_ != NULL
2939       && this->os_->input_section_order_specified())
2940     this->os_->sort_attached_input_sections();
2941
2942   // For a relocatable link, all orphan sections are put at
2943   // address 0.  In general we expect all sections to be at
2944   // address 0 for a relocatable link, but we permit the linker
2945   // script to override that for specific output sections.
2946   if (parameters->options().relocatable())
2947     {
2948       address = 0;
2949       *load_address = 0;
2950       have_load_address = false;
2951     }
2952
2953   if ((this->os_->flags() & elfcpp::SHF_ALLOC) != 0)
2954     {
2955       this->os_->set_address(address);
2956       if (have_load_address)
2957         this->os_->set_load_address(align_address(*load_address,
2958                                                   this->os_->addralign()));
2959     }
2960
2961   Input_section_list input_sections;
2962   address += this->os_->get_input_sections(address, "", &input_sections);
2963
2964   for (Input_section_list::iterator p = input_sections.begin();
2965        p != input_sections.end();
2966        ++p)
2967     {
2968       uint64_t addralign = p->addralign();
2969       if (!p->is_input_section())
2970         p->output_section_data()->finalize_data_size(); 
2971       uint64_t size = p->data_size();
2972       address = align_address(address, addralign);
2973       this->os_->add_script_input_section(*p);
2974       address += size;
2975     }
2976
2977   if (parameters->options().relocatable())
2978     {
2979       // For a relocatable link, reset DOT_VALUE to 0.
2980       *dot_value = 0;
2981       *load_address = 0;
2982     }
2983   else if (this->os_ == NULL
2984            || (this->os_->flags() & elfcpp::SHF_TLS) == 0
2985            || this->os_->type() != elfcpp::SHT_NOBITS)
2986     {
2987       // An SHF_TLS/SHT_NOBITS section does not take up any address space.
2988       if (!have_load_address)
2989         *load_address = address;
2990       else
2991         *load_address += address - *dot_value;
2992
2993       *dot_value = address;
2994     }
2995 }
2996
2997 // Get the list of segments to use for an allocated section when using
2998 // a PHDRS clause.  If this is an allocated section, return the
2999 // Output_section.  We don't change the list of segments.
3000
3001 Output_section*
3002 Orphan_output_section::allocate_to_segment(String_list**, bool* orphan)
3003 {
3004   if ((this->os_->flags() & elfcpp::SHF_ALLOC) == 0)
3005     return NULL;
3006   *orphan = true;
3007   return this->os_;
3008 }
3009
3010 // Class Phdrs_element.  A program header from a PHDRS clause.
3011
3012 class Phdrs_element
3013 {
3014  public:
3015   Phdrs_element(const char* name, size_t namelen, unsigned int type,
3016                 bool includes_filehdr, bool includes_phdrs,
3017                 bool is_flags_valid, unsigned int flags,
3018                 Expression* load_address)
3019     : name_(name, namelen), type_(type), includes_filehdr_(includes_filehdr),
3020       includes_phdrs_(includes_phdrs), is_flags_valid_(is_flags_valid),
3021       flags_(flags), load_address_(load_address), load_address_value_(0),
3022       segment_(NULL)
3023   { }
3024
3025   // Return the name of this segment.
3026   const std::string&
3027   name() const
3028   { return this->name_; }
3029
3030   // Return the type of the segment.
3031   unsigned int
3032   type() const
3033   { return this->type_; }
3034
3035   // Whether to include the file header.
3036   bool
3037   includes_filehdr() const
3038   { return this->includes_filehdr_; }
3039
3040   // Whether to include the program headers.
3041   bool
3042   includes_phdrs() const
3043   { return this->includes_phdrs_; }
3044
3045   // Return whether there is a load address.
3046   bool
3047   has_load_address() const
3048   { return this->load_address_ != NULL; }
3049
3050   // Evaluate the load address expression if there is one.
3051   void
3052   eval_load_address(Symbol_table* symtab, Layout* layout)
3053   {
3054     if (this->load_address_ != NULL)
3055       this->load_address_value_ = this->load_address_->eval(symtab, layout,
3056                                                             true);
3057   }
3058
3059   // Return the load address.
3060   uint64_t
3061   load_address() const
3062   {
3063     gold_assert(this->load_address_ != NULL);
3064     return this->load_address_value_;
3065   }
3066
3067   // Create the segment.
3068   Output_segment*
3069   create_segment(Layout* layout)
3070   {
3071     this->segment_ = layout->make_output_segment(this->type_, this->flags_);
3072     return this->segment_;
3073   }
3074
3075   // Return the segment.
3076   Output_segment*
3077   segment()
3078   { return this->segment_; }
3079
3080   // Release the segment.
3081   void
3082   release_segment()
3083   { this->segment_ = NULL; }
3084
3085   // Set the segment flags if appropriate.
3086   void
3087   set_flags_if_valid()
3088   {
3089     if (this->is_flags_valid_)
3090       this->segment_->set_flags(this->flags_);
3091   }
3092
3093   // Print for debugging.
3094   void
3095   print(FILE*) const;
3096
3097  private:
3098   // The name used in the script.
3099   std::string name_;
3100   // The type of the segment (PT_LOAD, etc.).
3101   unsigned int type_;
3102   // Whether this segment includes the file header.
3103   bool includes_filehdr_;
3104   // Whether this segment includes the section headers.
3105   bool includes_phdrs_;
3106   // Whether the flags were explicitly specified.
3107   bool is_flags_valid_;
3108   // The flags for this segment (PF_R, etc.) if specified.
3109   unsigned int flags_;
3110   // The expression for the load address for this segment.  This may
3111   // be NULL.
3112   Expression* load_address_;
3113   // The actual load address from evaluating the expression.
3114   uint64_t load_address_value_;
3115   // The segment itself.
3116   Output_segment* segment_;
3117 };
3118
3119 // Print for debugging.
3120
3121 void
3122 Phdrs_element::print(FILE* f) const
3123 {
3124   fprintf(f, "  %s 0x%x", this->name_.c_str(), this->type_);
3125   if (this->includes_filehdr_)
3126     fprintf(f, " FILEHDR");
3127   if (this->includes_phdrs_)
3128     fprintf(f, " PHDRS");
3129   if (this->is_flags_valid_)
3130     fprintf(f, " FLAGS(%u)", this->flags_);
3131   if (this->load_address_ != NULL)
3132     {
3133       fprintf(f, " AT(");
3134       this->load_address_->print(f);
3135       fprintf(f, ")");
3136     }
3137   fprintf(f, ";\n");
3138 }
3139
3140 // Add a memory region.
3141
3142 void
3143 Script_sections::add_memory_region(const char* name, size_t namelen,
3144                                    unsigned int attributes,
3145                                    Expression* start, Expression* length)
3146 {
3147   if (this->memory_regions_ == NULL)
3148     this->memory_regions_ = new Memory_regions();
3149   else if (this->find_memory_region(name, namelen))
3150     {
3151       gold_error(_("region '%.*s' already defined"), static_cast<int>(namelen),
3152                   name);
3153       // FIXME: Add a GOLD extension to allow multiple regions with the same
3154       // name.  This would amount to a single region covering disjoint blocks
3155       // of memory, which is useful for embedded devices.
3156     }
3157
3158   // FIXME: Check the length and start values.  Currently we allow
3159   // non-constant expressions for these values, whereas LD does not.
3160
3161   // FIXME: Add a GOLD extension to allow NEGATIVE LENGTHS.  This would
3162   // describe a region that packs from the end address going down, rather
3163   // than the start address going up.  This would be useful for embedded
3164   // devices.
3165
3166   this->memory_regions_->push_back(new Memory_region(name, namelen, attributes,
3167                                                      start, length));
3168 }
3169
3170 // Find a memory region.
3171
3172 Memory_region*
3173 Script_sections::find_memory_region(const char* name, size_t namelen)
3174 {
3175   if (this->memory_regions_ == NULL)
3176     return NULL;
3177
3178   for (Memory_regions::const_iterator m = this->memory_regions_->begin();
3179        m != this->memory_regions_->end();
3180        ++m)
3181     if ((*m)->name_match(name, namelen))
3182       return *m;
3183
3184   return NULL;
3185 }
3186
3187 // Find a memory region's origin.
3188
3189 Expression*
3190 Script_sections::find_memory_region_origin(const char* name, size_t namelen)
3191 {
3192   Memory_region* mr = find_memory_region(name, namelen);
3193   if (mr == NULL)
3194     return NULL;
3195
3196   return mr->start_address();
3197 }
3198
3199 // Find a memory region's length.
3200
3201 Expression*
3202 Script_sections::find_memory_region_length(const char* name, size_t namelen)
3203 {
3204   Memory_region* mr = find_memory_region(name, namelen);
3205   if (mr == NULL)
3206     return NULL;
3207
3208   return mr->length();
3209 }
3210
3211 // Set the memory region to use for the current section.
3212
3213 void
3214 Script_sections::set_memory_region(Memory_region* mr, bool set_vma)
3215 {
3216   gold_assert(!this->sections_elements_->empty());
3217   this->sections_elements_->back()->set_memory_region(mr, set_vma);
3218 }
3219
3220 // Class Script_sections.
3221
3222 Script_sections::Script_sections()
3223   : saw_sections_clause_(false),
3224     in_sections_clause_(false),
3225     sections_elements_(NULL),
3226     output_section_(NULL),
3227     memory_regions_(NULL),
3228     phdrs_elements_(NULL),
3229     orphan_section_placement_(NULL),
3230     data_segment_align_start_(),
3231     saw_data_segment_align_(false),
3232     saw_relro_end_(false),
3233     saw_segment_start_expression_(false),
3234     segments_created_(false)
3235 {
3236 }
3237
3238 // Start a SECTIONS clause.
3239
3240 void
3241 Script_sections::start_sections()
3242 {
3243   gold_assert(!this->in_sections_clause_ && this->output_section_ == NULL);
3244   this->saw_sections_clause_ = true;
3245   this->in_sections_clause_ = true;
3246   if (this->sections_elements_ == NULL)
3247     this->sections_elements_ = new Sections_elements;
3248 }
3249
3250 // Finish a SECTIONS clause.
3251
3252 void
3253 Script_sections::finish_sections()
3254 {
3255   gold_assert(this->in_sections_clause_ && this->output_section_ == NULL);
3256   this->in_sections_clause_ = false;
3257 }
3258
3259 // Add a symbol to be defined.
3260
3261 void
3262 Script_sections::add_symbol_assignment(const char* name, size_t length,
3263                                        Expression* val, bool provide,
3264                                        bool hidden)
3265 {
3266   if (this->output_section_ != NULL)
3267     this->output_section_->add_symbol_assignment(name, length, val,
3268                                                  provide, hidden);
3269   else
3270     {
3271       Sections_element* p = new Sections_element_assignment(name, length,
3272                                                             val, provide,
3273                                                             hidden);
3274       this->sections_elements_->push_back(p);
3275     }
3276 }
3277
3278 // Add an assignment to the special dot symbol.
3279
3280 void
3281 Script_sections::add_dot_assignment(Expression* val)
3282 {
3283   if (this->output_section_ != NULL)
3284     this->output_section_->add_dot_assignment(val);
3285   else
3286     {
3287       // The GNU linker permits assignments to . to appears outside of
3288       // a SECTIONS clause, and treats it as appearing inside, so
3289       // sections_elements_ may be NULL here.
3290       if (this->sections_elements_ == NULL)
3291         {
3292           this->sections_elements_ = new Sections_elements;
3293           this->saw_sections_clause_ = true;
3294         }
3295
3296       Sections_element* p = new Sections_element_dot_assignment(val);
3297       this->sections_elements_->push_back(p);
3298     }
3299 }
3300
3301 // Add an assertion.
3302
3303 void
3304 Script_sections::add_assertion(Expression* check, const char* message,
3305                                size_t messagelen)
3306 {
3307   if (this->output_section_ != NULL)
3308     this->output_section_->add_assertion(check, message, messagelen);
3309   else
3310     {
3311       Sections_element* p = new Sections_element_assertion(check, message,
3312                                                            messagelen);
3313       this->sections_elements_->push_back(p);
3314     }
3315 }
3316
3317 // Start processing entries for an output section.
3318
3319 void
3320 Script_sections::start_output_section(
3321     const char* name,
3322     size_t namelen,
3323     const Parser_output_section_header* header)
3324 {
3325   Output_section_definition* posd = new Output_section_definition(name,
3326                                                                   namelen,
3327                                                                   header);
3328   this->sections_elements_->push_back(posd);
3329   gold_assert(this->output_section_ == NULL);
3330   this->output_section_ = posd;
3331 }
3332
3333 // Stop processing entries for an output section.
3334
3335 void
3336 Script_sections::finish_output_section(
3337     const Parser_output_section_trailer* trailer)
3338 {
3339   gold_assert(this->output_section_ != NULL);
3340   this->output_section_->finish(trailer);
3341   this->output_section_ = NULL;
3342 }
3343
3344 // Add a data item to the current output section.
3345
3346 void
3347 Script_sections::add_data(int size, bool is_signed, Expression* val)
3348 {
3349   gold_assert(this->output_section_ != NULL);
3350   this->output_section_->add_data(size, is_signed, val);
3351 }
3352
3353 // Add a fill value setting to the current output section.
3354
3355 void
3356 Script_sections::add_fill(Expression* val)
3357 {
3358   gold_assert(this->output_section_ != NULL);
3359   this->output_section_->add_fill(val);
3360 }
3361
3362 // Add an input section specification to the current output section.
3363
3364 void
3365 Script_sections::add_input_section(const Input_section_spec* spec, bool keep)
3366 {
3367   gold_assert(this->output_section_ != NULL);
3368   this->output_section_->add_input_section(spec, keep);
3369 }
3370
3371 // This is called when we see DATA_SEGMENT_ALIGN.  It means that any
3372 // subsequent output sections may be relro.
3373
3374 void
3375 Script_sections::data_segment_align()
3376 {
3377   if (this->saw_data_segment_align_)
3378     gold_error(_("DATA_SEGMENT_ALIGN may only appear once in a linker script"));
3379   gold_assert(!this->sections_elements_->empty());
3380   Sections_elements::iterator p = this->sections_elements_->end();
3381   --p;
3382   this->data_segment_align_start_ = p;
3383   this->saw_data_segment_align_ = true;
3384 }
3385
3386 // This is called when we see DATA_SEGMENT_RELRO_END.  It means that
3387 // any output sections seen since DATA_SEGMENT_ALIGN are relro.
3388
3389 void
3390 Script_sections::data_segment_relro_end()
3391 {
3392   if (this->saw_relro_end_)
3393     gold_error(_("DATA_SEGMENT_RELRO_END may only appear once "
3394                  "in a linker script"));
3395   this->saw_relro_end_ = true;
3396
3397   if (!this->saw_data_segment_align_)
3398     gold_error(_("DATA_SEGMENT_RELRO_END must follow DATA_SEGMENT_ALIGN"));
3399   else
3400     {
3401       Sections_elements::iterator p = this->data_segment_align_start_;
3402       for (++p; p != this->sections_elements_->end(); ++p)
3403         (*p)->set_is_relro();
3404     }
3405 }
3406
3407 // Create any required sections.
3408
3409 void
3410 Script_sections::create_sections(Layout* layout)
3411 {
3412   if (!this->saw_sections_clause_)
3413     return;
3414   for (Sections_elements::iterator p = this->sections_elements_->begin();
3415        p != this->sections_elements_->end();
3416        ++p)
3417     (*p)->create_sections(layout);
3418 }
3419
3420 // Add any symbols we are defining to the symbol table.
3421
3422 void
3423 Script_sections::add_symbols_to_table(Symbol_table* symtab)
3424 {
3425   if (!this->saw_sections_clause_)
3426     return;
3427   for (Sections_elements::iterator p = this->sections_elements_->begin();
3428        p != this->sections_elements_->end();
3429        ++p)
3430     (*p)->add_symbols_to_table(symtab);
3431 }
3432
3433 // Finalize symbols and check assertions.
3434
3435 void
3436 Script_sections::finalize_symbols(Symbol_table* symtab, const Layout* layout)
3437 {
3438   if (!this->saw_sections_clause_)
3439     return;
3440   uint64_t dot_value = 0;
3441   for (Sections_elements::iterator p = this->sections_elements_->begin();
3442        p != this->sections_elements_->end();
3443        ++p)
3444     (*p)->finalize_symbols(symtab, layout, &dot_value);
3445 }
3446
3447 // Return the name of the output section to use for an input file name
3448 // and section name.
3449
3450 const char*
3451 Script_sections::output_section_name(
3452     const char* file_name,
3453     const char* section_name,
3454     Output_section*** output_section_slot,
3455     Script_sections::Section_type* psection_type,
3456     bool* keep)
3457 {
3458   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
3459        p != this->sections_elements_->end();
3460        ++p)
3461     {
3462       const char* ret = (*p)->output_section_name(file_name, section_name,
3463                                                   output_section_slot,
3464                                                   psection_type, keep);
3465
3466       if (ret != NULL)
3467         {
3468           // The special name /DISCARD/ means that the input section
3469           // should be discarded.
3470           if (strcmp(ret, "/DISCARD/") == 0)
3471             {
3472               *output_section_slot = NULL;
3473               *psection_type = Script_sections::ST_NONE;
3474               return NULL;
3475             }
3476           return ret;
3477         }
3478     }
3479
3480   // If we couldn't find a mapping for the name, the output section
3481   // gets the name of the input section.
3482
3483   *output_section_slot = NULL;
3484   *psection_type = Script_sections::ST_NONE;
3485
3486   return section_name;
3487 }
3488
3489 // Place a marker for an orphan output section into the SECTIONS
3490 // clause.
3491
3492 void
3493 Script_sections::place_orphan(Output_section* os)
3494 {
3495   Orphan_section_placement* osp = this->orphan_section_placement_;
3496   if (osp == NULL)
3497     {
3498       // Initialize the Orphan_section_placement structure.
3499       osp = new Orphan_section_placement();
3500       for (Sections_elements::iterator p = this->sections_elements_->begin();
3501            p != this->sections_elements_->end();
3502            ++p)
3503         (*p)->orphan_section_init(osp, p);
3504       gold_assert(!this->sections_elements_->empty());
3505       Sections_elements::iterator last = this->sections_elements_->end();
3506       --last;
3507       osp->last_init(last);
3508       this->orphan_section_placement_ = osp;
3509     }
3510
3511   Orphan_output_section* orphan = new Orphan_output_section(os);
3512
3513   // Look for where to put ORPHAN.
3514   Sections_elements::iterator* where;
3515   if (osp->find_place(os, &where))
3516     {
3517       if ((**where)->is_relro())
3518         os->set_is_relro();
3519       else
3520         os->clear_is_relro();
3521
3522       // We want to insert ORPHAN after *WHERE, and then update *WHERE
3523       // so that the next one goes after this one.
3524       Sections_elements::iterator p = *where;
3525       gold_assert(p != this->sections_elements_->end());
3526       ++p;
3527       *where = this->sections_elements_->insert(p, orphan);
3528     }
3529   else
3530     {
3531       os->clear_is_relro();
3532       // We don't have a place to put this orphan section.  Put it,
3533       // and all other sections like it, at the end, but before the
3534       // sections which always come at the end.
3535       Sections_elements::iterator last = osp->last_place();
3536       *where = this->sections_elements_->insert(last, orphan);
3537     }
3538 }
3539
3540 // Set the addresses of all the output sections.  Walk through all the
3541 // elements, tracking the dot symbol.  Apply assignments which set
3542 // absolute symbol values, in case they are used when setting dot.
3543 // Fill in data statement values.  As we find output sections, set the
3544 // address, set the address of all associated input sections, and
3545 // update dot.  Return the segment which should hold the file header
3546 // and segment headers, if any.
3547
3548 Output_segment*
3549 Script_sections::set_section_addresses(Symbol_table* symtab, Layout* layout)
3550 {
3551   gold_assert(this->saw_sections_clause_);
3552          
3553   // Implement ONLY_IF_RO/ONLY_IF_RW constraints.  These are a pain
3554   // for our representation.
3555   for (Sections_elements::iterator p = this->sections_elements_->begin();
3556        p != this->sections_elements_->end();
3557        ++p)
3558     {
3559       Output_section_definition* posd;
3560       Section_constraint failed_constraint = (*p)->check_constraint(&posd);
3561       if (failed_constraint != CONSTRAINT_NONE)
3562         {
3563           Sections_elements::iterator q;
3564           for (q = this->sections_elements_->begin();
3565                q != this->sections_elements_->end();
3566                ++q)
3567             {
3568               if (q != p)
3569                 {
3570                   if ((*q)->alternate_constraint(posd, failed_constraint))
3571                     break;
3572                 }
3573             }
3574
3575           if (q == this->sections_elements_->end())
3576             gold_error(_("no matching section constraint"));
3577         }
3578     }
3579
3580   // Force the alignment of the first TLS section to be the maximum
3581   // alignment of all TLS sections.
3582   Output_section* first_tls = NULL;
3583   uint64_t tls_align = 0;
3584   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
3585        p != this->sections_elements_->end();
3586        ++p)
3587     {
3588       Output_section* os = (*p)->get_output_section();
3589       if (os != NULL && (os->flags() & elfcpp::SHF_TLS) != 0)
3590         {
3591           if (first_tls == NULL)
3592             first_tls = os;
3593           if (os->addralign() > tls_align)
3594             tls_align = os->addralign();
3595         }
3596     }
3597   if (first_tls != NULL)
3598     first_tls->set_addralign(tls_align);
3599
3600   // For a relocatable link, we implicitly set dot to zero.
3601   uint64_t dot_value = 0;
3602   uint64_t dot_alignment = 0;
3603   uint64_t load_address = 0;
3604
3605   // Check to see if we want to use any of -Ttext, -Tdata and -Tbss options
3606   // to set section addresses.  If the script has any SEGMENT_START
3607   // expression, we do not set the section addresses.
3608   bool use_tsection_options =
3609     (!this->saw_segment_start_expression_
3610      && (parameters->options().user_set_Ttext()
3611          || parameters->options().user_set_Tdata()
3612          || parameters->options().user_set_Tbss()));
3613
3614   for (Sections_elements::iterator p = this->sections_elements_->begin();
3615        p != this->sections_elements_->end();
3616        ++p)
3617     {
3618       Output_section* os = (*p)->get_output_section();
3619
3620       // Handle -Ttext, -Tdata and -Tbss options.  We do this by looking for
3621       // the special sections by names and doing dot assignments. 
3622       if (use_tsection_options
3623           && os != NULL
3624           && (os->flags() & elfcpp::SHF_ALLOC) != 0)
3625         {
3626           uint64_t new_dot_value = dot_value;
3627
3628           if (parameters->options().user_set_Ttext()
3629               && strcmp(os->name(), ".text") == 0)
3630             new_dot_value = parameters->options().Ttext();
3631           else if (parameters->options().user_set_Tdata()
3632               && strcmp(os->name(), ".data") == 0)
3633             new_dot_value = parameters->options().Tdata();
3634           else if (parameters->options().user_set_Tbss()
3635               && strcmp(os->name(), ".bss") == 0)
3636             new_dot_value = parameters->options().Tbss();
3637
3638           // Update dot and load address if necessary.
3639           if (new_dot_value < dot_value)
3640             gold_error(_("dot may not move backward"));
3641           else if (new_dot_value != dot_value)
3642             {
3643               dot_value = new_dot_value;
3644               load_address = new_dot_value;
3645             }
3646         }
3647
3648       (*p)->set_section_addresses(symtab, layout, &dot_value, &dot_alignment,
3649                                   &load_address);
3650     } 
3651
3652   if (this->phdrs_elements_ != NULL)
3653     {
3654       for (Phdrs_elements::iterator p = this->phdrs_elements_->begin();
3655            p != this->phdrs_elements_->end();
3656            ++p)
3657         (*p)->eval_load_address(symtab, layout);
3658     }
3659
3660   return this->create_segments(layout, dot_alignment);
3661 }
3662
3663 // Sort the sections in order to put them into segments.
3664
3665 class Sort_output_sections
3666 {
3667  public:
3668   Sort_output_sections(const Script_sections::Sections_elements* elements)
3669    : elements_(elements)
3670   { }
3671
3672   bool
3673   operator()(const Output_section* os1, const Output_section* os2) const;
3674
3675  private:
3676   int
3677   script_compare(const Output_section* os1, const Output_section* os2) const;
3678
3679  private:
3680   const Script_sections::Sections_elements* elements_;
3681 };
3682
3683 bool
3684 Sort_output_sections::operator()(const Output_section* os1,
3685                                  const Output_section* os2) const
3686 {
3687   // Sort first by the load address.
3688   uint64_t lma1 = (os1->has_load_address()
3689                    ? os1->load_address()
3690                    : os1->address());
3691   uint64_t lma2 = (os2->has_load_address()
3692                    ? os2->load_address()
3693                    : os2->address());
3694   if (lma1 != lma2)
3695     return lma1 < lma2;
3696
3697   // Then sort by the virtual address.
3698   if (os1->address() != os2->address())
3699     return os1->address() < os2->address();
3700
3701   // If the linker script says which of these sections is first, go
3702   // with what it says.
3703   int i = this->script_compare(os1, os2);
3704   if (i != 0)
3705     return i < 0;
3706
3707   // Sort PROGBITS before NOBITS.
3708   bool nobits1 = os1->type() == elfcpp::SHT_NOBITS;
3709   bool nobits2 = os2->type() == elfcpp::SHT_NOBITS;
3710   if (nobits1 != nobits2)
3711     return nobits2;
3712
3713   // Sort PROGBITS TLS sections to the end, NOBITS TLS sections to the
3714   // beginning.
3715   bool tls1 = (os1->flags() & elfcpp::SHF_TLS) != 0;
3716   bool tls2 = (os2->flags() & elfcpp::SHF_TLS) != 0;
3717   if (tls1 != tls2)
3718     return nobits1 ? tls1 : tls2;
3719
3720   // Sort non-NOLOAD before NOLOAD.
3721   if (os1->is_noload() && !os2->is_noload())
3722     return true;
3723   if (!os1->is_noload() && os2->is_noload())
3724     return true;
3725
3726   // The sections seem practically identical.  Sort by name to get a
3727   // stable sort.
3728   return os1->name() < os2->name();
3729 }
3730
3731 // Return -1 if OS1 comes before OS2 in ELEMENTS_, 1 if comes after, 0
3732 // if either OS1 or OS2 is not mentioned.  This ensures that we keep
3733 // empty sections in the order in which they appear in a linker
3734 // script.
3735
3736 int
3737 Sort_output_sections::script_compare(const Output_section* os1,
3738                                      const Output_section* os2) const
3739 {
3740   if (this->elements_ == NULL)
3741     return 0;
3742
3743   bool found_os1 = false;
3744   bool found_os2 = false;
3745   for (Script_sections::Sections_elements::const_iterator
3746          p = this->elements_->begin();
3747        p != this->elements_->end();
3748        ++p)
3749     {
3750       if (os2 == (*p)->get_output_section())
3751         {
3752           if (found_os1)
3753             return -1;
3754           found_os2 = true;
3755         }
3756       else if (os1 == (*p)->get_output_section())
3757         {
3758           if (found_os2)
3759             return 1;
3760           found_os1 = true;
3761         }
3762     }
3763
3764   return 0;
3765 }
3766
3767 // Return whether OS is a BSS section.  This is a SHT_NOBITS section.
3768 // We treat a section with the SHF_TLS flag set as taking up space
3769 // even if it is SHT_NOBITS (this is true of .tbss), as we allocate
3770 // space for them in the file.
3771
3772 bool
3773 Script_sections::is_bss_section(const Output_section* os)
3774 {
3775   return (os->type() == elfcpp::SHT_NOBITS
3776           && (os->flags() & elfcpp::SHF_TLS) == 0);
3777 }
3778
3779 // Return the size taken by the file header and the program headers.
3780
3781 size_t
3782 Script_sections::total_header_size(Layout* layout) const
3783 {
3784   size_t segment_count = layout->segment_count();
3785   size_t file_header_size;
3786   size_t segment_headers_size;
3787   if (parameters->target().get_size() == 32)
3788     {
3789       file_header_size = elfcpp::Elf_sizes<32>::ehdr_size;
3790       segment_headers_size = segment_count * elfcpp::Elf_sizes<32>::phdr_size;
3791     }
3792   else if (parameters->target().get_size() == 64)
3793     {
3794       file_header_size = elfcpp::Elf_sizes<64>::ehdr_size;
3795       segment_headers_size = segment_count * elfcpp::Elf_sizes<64>::phdr_size;
3796     }
3797   else
3798     gold_unreachable();
3799
3800   return file_header_size + segment_headers_size;
3801 }
3802
3803 // Return the amount we have to subtract from the LMA to accommodate
3804 // headers of the given size.  The complication is that the file
3805 // header have to be at the start of a page, as otherwise it will not
3806 // be at the start of the file.
3807
3808 uint64_t
3809 Script_sections::header_size_adjustment(uint64_t lma,
3810                                         size_t sizeof_headers) const
3811 {
3812   const uint64_t abi_pagesize = parameters->target().abi_pagesize();
3813   uint64_t hdr_lma = lma - sizeof_headers;
3814   hdr_lma &= ~(abi_pagesize - 1);
3815   return lma - hdr_lma;
3816 }
3817
3818 // Create the PT_LOAD segments when using a SECTIONS clause.  Returns
3819 // the segment which should hold the file header and segment headers,
3820 // if any.
3821
3822 Output_segment*
3823 Script_sections::create_segments(Layout* layout, uint64_t dot_alignment)
3824 {
3825   gold_assert(this->saw_sections_clause_);
3826
3827   if (parameters->options().relocatable())
3828     return NULL;
3829
3830   if (this->saw_phdrs_clause())
3831     return create_segments_from_phdrs_clause(layout, dot_alignment);
3832
3833   Layout::Section_list sections;
3834   layout->get_allocated_sections(&sections);
3835
3836   // Sort the sections by address.
3837   std::stable_sort(sections.begin(), sections.end(), 
3838                    Sort_output_sections(this->sections_elements_));
3839
3840   this->create_note_and_tls_segments(layout, &sections);
3841
3842   // Walk through the sections adding them to PT_LOAD segments.
3843   const uint64_t abi_pagesize = parameters->target().abi_pagesize();
3844   Output_segment* first_seg = NULL;
3845   Output_segment* current_seg = NULL;
3846   bool is_current_seg_readonly = true;
3847   Layout::Section_list::iterator plast = sections.end();
3848   uint64_t last_vma = 0;
3849   uint64_t last_lma = 0;
3850   uint64_t last_size = 0;
3851   for (Layout::Section_list::iterator p = sections.begin();
3852        p != sections.end();
3853        ++p)
3854     {
3855       const uint64_t vma = (*p)->address();
3856       const uint64_t lma = ((*p)->has_load_address()
3857                             ? (*p)->load_address()
3858                             : vma);
3859       const uint64_t size = (*p)->current_data_size();
3860
3861       bool need_new_segment;
3862       if (current_seg == NULL)
3863         need_new_segment = true;
3864       else if (lma - vma != last_lma - last_vma)
3865         {
3866           // This section has a different LMA relationship than the
3867           // last one; we need a new segment.
3868           need_new_segment = true;
3869         }
3870       else if (align_address(last_lma + last_size, abi_pagesize)
3871                < align_address(lma, abi_pagesize))
3872         {
3873           // Putting this section in the segment would require
3874           // skipping a page.
3875           need_new_segment = true;
3876         }
3877       else if (is_bss_section(*plast) && !is_bss_section(*p))
3878         {
3879           // A non-BSS section can not follow a BSS section in the
3880           // same segment.
3881           need_new_segment = true;
3882         }
3883       else if (is_current_seg_readonly
3884                && ((*p)->flags() & elfcpp::SHF_WRITE) != 0
3885                && !parameters->options().omagic())
3886         {
3887           // Don't put a writable section in the same segment as a
3888           // non-writable section.
3889           need_new_segment = true;
3890         }
3891       else
3892         {
3893           // Otherwise, reuse the existing segment.
3894           need_new_segment = false;
3895         }
3896
3897       elfcpp::Elf_Word seg_flags =
3898         Layout::section_flags_to_segment((*p)->flags());
3899
3900       if (need_new_segment)
3901         {
3902           current_seg = layout->make_output_segment(elfcpp::PT_LOAD,
3903                                                     seg_flags);
3904           current_seg->set_addresses(vma, lma);
3905           current_seg->set_minimum_p_align(dot_alignment);
3906           if (first_seg == NULL)
3907             first_seg = current_seg;
3908           is_current_seg_readonly = true;
3909         }
3910
3911       current_seg->add_output_section_to_load(layout, *p, seg_flags);
3912
3913       if (((*p)->flags() & elfcpp::SHF_WRITE) != 0)
3914         is_current_seg_readonly = false;
3915
3916       plast = p;
3917       last_vma = vma;
3918       last_lma = lma;
3919       last_size = size;
3920     }
3921
3922   // An ELF program should work even if the program headers are not in
3923   // a PT_LOAD segment.  However, it appears that the Linux kernel
3924   // does not set the AT_PHDR auxiliary entry in that case.  It sets
3925   // the load address to p_vaddr - p_offset of the first PT_LOAD
3926   // segment.  It then sets AT_PHDR to the load address plus the
3927   // offset to the program headers, e_phoff in the file header.  This
3928   // fails when the program headers appear in the file before the
3929   // first PT_LOAD segment.  Therefore, we always create a PT_LOAD
3930   // segment to hold the file header and the program headers.  This is
3931   // effectively what the GNU linker does, and it is slightly more
3932   // efficient in any case.  We try to use the first PT_LOAD segment
3933   // if we can, otherwise we make a new one.
3934
3935   if (first_seg == NULL)
3936     return NULL;
3937
3938   // -n or -N mean that the program is not demand paged and there is
3939   // no need to put the program headers in a PT_LOAD segment.
3940   if (parameters->options().nmagic() || parameters->options().omagic())
3941     return NULL;
3942
3943   size_t sizeof_headers = this->total_header_size(layout);
3944
3945   uint64_t vma = first_seg->vaddr();
3946   uint64_t lma = first_seg->paddr();
3947
3948   uint64_t subtract = this->header_size_adjustment(lma, sizeof_headers);
3949
3950   if ((lma & (abi_pagesize - 1)) >= sizeof_headers)
3951     {
3952       first_seg->set_addresses(vma - subtract, lma - subtract);
3953       return first_seg;
3954     }
3955
3956   // If there is no room to squeeze in the headers, then punt.  The
3957   // resulting executable probably won't run on GNU/Linux, but we
3958   // trust that the user knows what they are doing.
3959   if (lma < subtract || vma < subtract)
3960     return NULL;
3961
3962   // If memory regions have been specified and the address range
3963   // we are about to use is not contained within any region then
3964   // issue a warning message about the segment we are going to
3965   // create.  It will be outside of any region and so possibly
3966   // using non-existent or protected memory.  We test LMA rather
3967   // than VMA since we assume that the headers will never be
3968   // relocated.
3969   if (this->memory_regions_ != NULL
3970       && !this->block_in_region (NULL, layout, lma - subtract, subtract))
3971     gold_warning(_("creating a segment to contain the file and program"
3972                    " headers outside of any MEMORY region"));
3973
3974   Output_segment* load_seg = layout->make_output_segment(elfcpp::PT_LOAD,
3975                                                          elfcpp::PF_R);
3976   load_seg->set_addresses(vma - subtract, lma - subtract);
3977
3978   return load_seg;
3979 }
3980
3981 // Create a PT_NOTE segment for each SHT_NOTE section and a PT_TLS
3982 // segment if there are any SHT_TLS sections.
3983
3984 void
3985 Script_sections::create_note_and_tls_segments(
3986     Layout* layout,
3987     const Layout::Section_list* sections)
3988 {
3989   gold_assert(!this->saw_phdrs_clause());
3990
3991   bool saw_tls = false;
3992   for (Layout::Section_list::const_iterator p = sections->begin();
3993        p != sections->end();
3994        ++p)
3995     {
3996       if ((*p)->type() == elfcpp::SHT_NOTE)
3997         {
3998           elfcpp::Elf_Word seg_flags =
3999             Layout::section_flags_to_segment((*p)->flags());
4000           Output_segment* oseg = layout->make_output_segment(elfcpp::PT_NOTE,
4001                                                              seg_flags);
4002           oseg->add_output_section_to_nonload(*p, seg_flags);
4003
4004           // Incorporate any subsequent SHT_NOTE sections, in the
4005           // hopes that the script is sensible.
4006           Layout::Section_list::const_iterator pnext = p + 1;
4007           while (pnext != sections->end()
4008                  && (*pnext)->type() == elfcpp::SHT_NOTE)
4009             {
4010               seg_flags = Layout::section_flags_to_segment((*pnext)->flags());
4011               oseg->add_output_section_to_nonload(*pnext, seg_flags);
4012               p = pnext;
4013               ++pnext;
4014             }
4015         }
4016
4017       if (((*p)->flags() & elfcpp::SHF_TLS) != 0)
4018         {
4019           if (saw_tls)
4020             gold_error(_("TLS sections are not adjacent"));
4021
4022           elfcpp::Elf_Word seg_flags =
4023             Layout::section_flags_to_segment((*p)->flags());
4024           Output_segment* oseg = layout->make_output_segment(elfcpp::PT_TLS,
4025                                                              seg_flags);
4026           oseg->add_output_section_to_nonload(*p, seg_flags);
4027
4028           Layout::Section_list::const_iterator pnext = p + 1;
4029           while (pnext != sections->end()
4030                  && ((*pnext)->flags() & elfcpp::SHF_TLS) != 0)
4031             {
4032               seg_flags = Layout::section_flags_to_segment((*pnext)->flags());
4033               oseg->add_output_section_to_nonload(*pnext, seg_flags);
4034               p = pnext;
4035               ++pnext;
4036             }
4037
4038           saw_tls = true;
4039         }
4040
4041       // If we see a section named .interp then put the .interp section
4042       // in a PT_INTERP segment.
4043       // This is for GNU ld compatibility.
4044       if (strcmp((*p)->name(), ".interp") == 0)
4045         {
4046           elfcpp::Elf_Word seg_flags =
4047             Layout::section_flags_to_segment((*p)->flags());
4048           Output_segment* oseg = layout->make_output_segment(elfcpp::PT_INTERP,
4049                                                              seg_flags);
4050           oseg->add_output_section_to_nonload(*p, seg_flags);
4051         }
4052     }
4053
4054     this->segments_created_ = true;
4055 }
4056
4057 // Add a program header.  The PHDRS clause is syntactically distinct
4058 // from the SECTIONS clause, but we implement it with the SECTIONS
4059 // support because PHDRS is useless if there is no SECTIONS clause.
4060
4061 void
4062 Script_sections::add_phdr(const char* name, size_t namelen, unsigned int type,
4063                           bool includes_filehdr, bool includes_phdrs,
4064                           bool is_flags_valid, unsigned int flags,
4065                           Expression* load_address)
4066 {
4067   if (this->phdrs_elements_ == NULL)
4068     this->phdrs_elements_ = new Phdrs_elements();
4069   this->phdrs_elements_->push_back(new Phdrs_element(name, namelen, type,
4070                                                      includes_filehdr,
4071                                                      includes_phdrs,
4072                                                      is_flags_valid, flags,
4073                                                      load_address));
4074 }
4075
4076 // Return the number of segments we expect to create based on the
4077 // SECTIONS clause.  This is used to implement SIZEOF_HEADERS.
4078
4079 size_t
4080 Script_sections::expected_segment_count(const Layout* layout) const
4081 {
4082   // If we've already created the segments, we won't be adding any more.
4083   if (this->segments_created_)
4084     return 0;
4085
4086   if (this->saw_phdrs_clause())
4087     return this->phdrs_elements_->size();
4088
4089   Layout::Section_list sections;
4090   layout->get_allocated_sections(&sections);
4091
4092   // We assume that we will need two PT_LOAD segments.
4093   size_t ret = 2;
4094
4095   bool saw_note = false;
4096   bool saw_tls = false;
4097   bool saw_interp = false;
4098   for (Layout::Section_list::const_iterator p = sections.begin();
4099        p != sections.end();
4100        ++p)
4101     {
4102       if ((*p)->type() == elfcpp::SHT_NOTE)
4103         {
4104           // Assume that all note sections will fit into a single
4105           // PT_NOTE segment.
4106           if (!saw_note)
4107             {
4108               ++ret;
4109               saw_note = true;
4110             }
4111         }
4112       else if (((*p)->flags() & elfcpp::SHF_TLS) != 0)
4113         {
4114           // There can only be one PT_TLS segment.
4115           if (!saw_tls)
4116             {
4117               ++ret;
4118               saw_tls = true;
4119             }
4120         }
4121       else if (strcmp((*p)->name(), ".interp") == 0)
4122         {
4123           // There can only be one PT_INTERP segment.
4124           if (!saw_interp)
4125             {
4126               ++ret;
4127               saw_interp = true;
4128             }
4129         }
4130     }
4131
4132   return ret;
4133 }
4134
4135 // Create the segments from a PHDRS clause.  Return the segment which
4136 // should hold the file header and program headers, if any.
4137
4138 Output_segment*
4139 Script_sections::create_segments_from_phdrs_clause(Layout* layout,
4140                                                    uint64_t dot_alignment)
4141 {
4142   this->attach_sections_using_phdrs_clause(layout);
4143   return this->set_phdrs_clause_addresses(layout, dot_alignment);
4144 }
4145
4146 // Create the segments from the PHDRS clause, and put the output
4147 // sections in them.
4148
4149 void
4150 Script_sections::attach_sections_using_phdrs_clause(Layout* layout)
4151 {
4152   typedef std::map<std::string, Output_segment*> Name_to_segment;
4153   Name_to_segment name_to_segment;
4154   for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
4155        p != this->phdrs_elements_->end();
4156        ++p)
4157     name_to_segment[(*p)->name()] = (*p)->create_segment(layout);
4158   this->segments_created_ = true;
4159
4160   // Walk through the output sections and attach them to segments.
4161   // Output sections in the script which do not list segments are
4162   // attached to the same set of segments as the immediately preceding
4163   // output section.
4164   
4165   String_list* phdr_names = NULL;
4166   bool load_segments_only = false;
4167   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
4168        p != this->sections_elements_->end();
4169        ++p)
4170     {
4171       bool is_orphan;
4172       String_list* old_phdr_names = phdr_names;
4173       Output_section* os = (*p)->allocate_to_segment(&phdr_names, &is_orphan);
4174       if (os == NULL)
4175         continue;
4176
4177       elfcpp::Elf_Word seg_flags =
4178         Layout::section_flags_to_segment(os->flags());
4179
4180       if (phdr_names == NULL)
4181         {
4182           // Don't worry about empty orphan sections.
4183           if (is_orphan && os->current_data_size() > 0)
4184             gold_error(_("allocated section %s not in any segment"),
4185                        os->name());
4186
4187           // To avoid later crashes drop this section into the first
4188           // PT_LOAD segment.
4189           for (Phdrs_elements::const_iterator ppe =
4190                  this->phdrs_elements_->begin();
4191                ppe != this->phdrs_elements_->end();
4192                ++ppe)
4193             {
4194               Output_segment* oseg = (*ppe)->segment();
4195               if (oseg->type() == elfcpp::PT_LOAD)
4196                 {
4197                   oseg->add_output_section_to_load(layout, os, seg_flags);
4198                   break;
4199                 }
4200             }
4201
4202           continue;
4203         }
4204
4205       // We see a list of segments names.  Disable PT_LOAD segment only
4206       // filtering.
4207       if (old_phdr_names != phdr_names)
4208         load_segments_only = false;
4209                 
4210       // If this is an orphan section--one that was not explicitly
4211       // mentioned in the linker script--then it should not inherit
4212       // any segment type other than PT_LOAD.  Otherwise, e.g., the
4213       // PT_INTERP segment will pick up following orphan sections,
4214       // which does not make sense.  If this is not an orphan section,
4215       // we trust the linker script.
4216       if (is_orphan)
4217         {
4218           // Enable PT_LOAD segments only filtering until we see another
4219           // list of segment names.
4220           load_segments_only = true;
4221         }
4222
4223       bool in_load_segment = false;
4224       for (String_list::const_iterator q = phdr_names->begin();
4225            q != phdr_names->end();
4226            ++q)
4227         {
4228           Name_to_segment::const_iterator r = name_to_segment.find(*q);
4229           if (r == name_to_segment.end())
4230             gold_error(_("no segment %s"), q->c_str());
4231           else
4232             {
4233               if (load_segments_only
4234                   && r->second->type() != elfcpp::PT_LOAD)
4235                 continue;
4236
4237               if (r->second->type() != elfcpp::PT_LOAD)
4238                 r->second->add_output_section_to_nonload(os, seg_flags);
4239               else
4240                 {
4241                   r->second->add_output_section_to_load(layout, os, seg_flags);
4242                   if (in_load_segment)
4243                     gold_error(_("section in two PT_LOAD segments"));
4244                   in_load_segment = true;
4245                 }
4246             }
4247         }
4248
4249       if (!in_load_segment)
4250         gold_error(_("allocated section not in any PT_LOAD segment"));
4251     }
4252 }
4253
4254 // Set the addresses for segments created from a PHDRS clause.  Return
4255 // the segment which should hold the file header and program headers,
4256 // if any.
4257
4258 Output_segment*
4259 Script_sections::set_phdrs_clause_addresses(Layout* layout,
4260                                             uint64_t dot_alignment)
4261 {
4262   Output_segment* load_seg = NULL;
4263   for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
4264        p != this->phdrs_elements_->end();
4265        ++p)
4266     {
4267       // Note that we have to set the flags after adding the output
4268       // sections to the segment, as adding an output segment can
4269       // change the flags.
4270       (*p)->set_flags_if_valid();
4271
4272       Output_segment* oseg = (*p)->segment();
4273
4274       if (oseg->type() != elfcpp::PT_LOAD)
4275         {
4276           // The addresses of non-PT_LOAD segments are set from the
4277           // PT_LOAD segments.
4278           if ((*p)->has_load_address())
4279             gold_error(_("may only specify load address for PT_LOAD segment"));
4280           continue;
4281         }
4282
4283       oseg->set_minimum_p_align(dot_alignment);
4284
4285       // The output sections should have addresses from the SECTIONS
4286       // clause.  The addresses don't have to be in order, so find the
4287       // one with the lowest load address.  Use that to set the
4288       // address of the segment.
4289
4290       Output_section* osec = oseg->section_with_lowest_load_address();
4291       if (osec == NULL)
4292         {
4293           oseg->set_addresses(0, 0);
4294           continue;
4295         }
4296
4297       uint64_t vma = osec->address();
4298       uint64_t lma = osec->has_load_address() ? osec->load_address() : vma;
4299
4300       // Override the load address of the section with the load
4301       // address specified for the segment.
4302       if ((*p)->has_load_address())
4303         {
4304           if (osec->has_load_address())
4305             gold_warning(_("PHDRS load address overrides "
4306                            "section %s load address"),
4307                          osec->name());
4308
4309           lma = (*p)->load_address();
4310         }
4311
4312       bool headers = (*p)->includes_filehdr() && (*p)->includes_phdrs();
4313       if (!headers && ((*p)->includes_filehdr() || (*p)->includes_phdrs()))
4314         {
4315           // We could support this if we wanted to.
4316           gold_error(_("using only one of FILEHDR and PHDRS is "
4317                        "not currently supported"));
4318         }
4319       if (headers)
4320         {
4321           size_t sizeof_headers = this->total_header_size(layout);
4322           uint64_t subtract = this->header_size_adjustment(lma,
4323                                                            sizeof_headers);
4324           if (lma >= subtract && vma >= subtract)
4325             {
4326               lma -= subtract;
4327               vma -= subtract;
4328             }
4329           else
4330             {
4331               gold_error(_("sections loaded on first page without room "
4332                            "for file and program headers "
4333                            "are not supported"));
4334             }
4335
4336           if (load_seg != NULL)
4337             gold_error(_("using FILEHDR and PHDRS on more than one "
4338                          "PT_LOAD segment is not currently supported"));
4339           load_seg = oseg;
4340         }
4341
4342       oseg->set_addresses(vma, lma);
4343     }
4344
4345   return load_seg;
4346 }
4347
4348 // Add the file header and segment headers to non-load segments
4349 // specified in the PHDRS clause.
4350
4351 void
4352 Script_sections::put_headers_in_phdrs(Output_data* file_header,
4353                                       Output_data* segment_headers)
4354 {
4355   gold_assert(this->saw_phdrs_clause());
4356   for (Phdrs_elements::iterator p = this->phdrs_elements_->begin();
4357        p != this->phdrs_elements_->end();
4358        ++p)
4359     {
4360       if ((*p)->type() != elfcpp::PT_LOAD)
4361         {
4362           if ((*p)->includes_phdrs())
4363             (*p)->segment()->add_initial_output_data(segment_headers);
4364           if ((*p)->includes_filehdr())
4365             (*p)->segment()->add_initial_output_data(file_header);
4366         }
4367     }
4368 }
4369
4370 // Look for an output section by name and return the address, the load
4371 // address, the alignment, and the size.  This is used when an
4372 // expression refers to an output section which was not actually
4373 // created.  This returns true if the section was found, false
4374 // otherwise.
4375
4376 bool
4377 Script_sections::get_output_section_info(const char* name, uint64_t* address,
4378                                          uint64_t* load_address,
4379                                          uint64_t* addralign,
4380                                          uint64_t* size) const
4381 {
4382   if (!this->saw_sections_clause_)
4383     return false;
4384   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
4385        p != this->sections_elements_->end();
4386        ++p)
4387     if ((*p)->get_output_section_info(name, address, load_address, addralign,
4388                                       size))
4389       return true;
4390   return false;
4391 }
4392
4393 // Release all Output_segments.  This remove all pointers to all
4394 // Output_segments.
4395
4396 void
4397 Script_sections::release_segments()
4398 {
4399   if (this->saw_phdrs_clause())
4400     {
4401       for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
4402            p != this->phdrs_elements_->end();
4403            ++p)
4404         (*p)->release_segment();
4405     }
4406 }
4407
4408 // Print the SECTIONS clause to F for debugging.
4409
4410 void
4411 Script_sections::print(FILE* f) const
4412 {
4413   if (this->phdrs_elements_ != NULL)
4414     {
4415       fprintf(f, "PHDRS {\n");
4416       for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
4417            p != this->phdrs_elements_->end();
4418            ++p)
4419         (*p)->print(f);
4420       fprintf(f, "}\n");
4421     }
4422
4423   if (this->memory_regions_ != NULL)
4424     {
4425       fprintf(f, "MEMORY {\n");
4426       for (Memory_regions::const_iterator m = this->memory_regions_->begin();
4427            m != this->memory_regions_->end();
4428            ++m)
4429         (*m)->print(f);
4430       fprintf(f, "}\n");
4431     }
4432
4433   if (!this->saw_sections_clause_)
4434     return;
4435
4436   fprintf(f, "SECTIONS {\n");
4437
4438   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
4439        p != this->sections_elements_->end();
4440        ++p)
4441     (*p)->print(f);
4442
4443   fprintf(f, "}\n");
4444 }
4445
4446 } // End namespace gold.