Home | History | Annotate | Download | only in gold
      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 (at) 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   static unsigned long
   1528   get_init_priority(const char*);
   1529 
   1530   Sort_wildcard filename_sort_;
   1531   Sort_wildcard section_sort_;
   1532 };
   1533 
   1534 // Return a relative priority of the section with the specified NAME
   1535 // (a lower value meand a higher priority), or 0 if it should be compared
   1536 // with others as strings.
   1537 // The implementation of this function is copied from ld/ldlang.c.
   1538 
   1539 unsigned long
   1540 Input_section_sorter::get_init_priority(const char* name)
   1541 {
   1542   char* end;
   1543   unsigned long init_priority;
   1544 
   1545   // GCC uses the following section names for the init_priority
   1546   // attribute with numerical values 101 and 65535 inclusive. A
   1547   // lower value means a higher priority.
   1548   //
   1549   // 1: .init_array.NNNN/.fini_array.NNNN: Where NNNN is the
   1550   //    decimal numerical value of the init_priority attribute.
   1551   //    The order of execution in .init_array is forward and
   1552   //    .fini_array is backward.
   1553   // 2: .ctors.NNNN/.dtors.NNNN: Where NNNN is 65535 minus the
   1554   //    decimal numerical value of the init_priority attribute.
   1555   //    The order of execution in .ctors is backward and .dtors
   1556   //    is forward.
   1557 
   1558   if (strncmp(name, ".init_array.", 12) == 0
   1559       || strncmp(name, ".fini_array.", 12) == 0)
   1560     {
   1561       init_priority = strtoul(name + 12, &end, 10);
   1562       return *end ? 0 : init_priority;
   1563     }
   1564   else if (strncmp(name, ".ctors.", 7) == 0
   1565 	   || strncmp(name, ".dtors.", 7) == 0)
   1566     {
   1567       init_priority = strtoul(name + 7, &end, 10);
   1568       return *end ? 0 : 65535 - init_priority;
   1569     }
   1570 
   1571   return 0;
   1572 }
   1573 
   1574 bool
   1575 Input_section_sorter::operator()(const Input_section_info& isi1,
   1576 				 const Input_section_info& isi2) const
   1577 {
   1578   if (this->section_sort_ == SORT_WILDCARD_BY_INIT_PRIORITY)
   1579     {
   1580       unsigned long ip1 = get_init_priority(isi1.section_name().c_str());
   1581       unsigned long ip2 = get_init_priority(isi2.section_name().c_str());
   1582       if (ip1 != 0 && ip2 != 0 && ip1 != ip2)
   1583 	return ip1 < ip2;
   1584     }
   1585   if (this->section_sort_ == SORT_WILDCARD_BY_NAME
   1586       || this->section_sort_ == SORT_WILDCARD_BY_NAME_BY_ALIGNMENT
   1587       || (this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT_BY_NAME
   1588 	  && isi1.addralign() == isi2.addralign())
   1589       || this->section_sort_ == SORT_WILDCARD_BY_INIT_PRIORITY)
   1590     {
   1591       if (isi1.section_name() != isi2.section_name())
   1592 	return isi1.section_name() < isi2.section_name();
   1593     }
   1594   if (this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT
   1595       || this->section_sort_ == SORT_WILDCARD_BY_NAME_BY_ALIGNMENT
   1596       || this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT_BY_NAME)
   1597     {
   1598       if (isi1.addralign() != isi2.addralign())
   1599 	return isi1.addralign() < isi2.addralign();
   1600     }
   1601   if (this->filename_sort_ == SORT_WILDCARD_BY_NAME)
   1602     {
   1603       if (isi1.relobj()->name() != isi2.relobj()->name())
   1604 	return (isi1.relobj()->name() < isi2.relobj()->name());
   1605     }
   1606 
   1607   // Otherwise we leave them in the same order.
   1608   return false;
   1609 }
   1610 
   1611 // Set the section address.  Look in INPUT_SECTIONS for sections which
   1612 // match this spec, sort them as specified, and add them to the output
   1613 // section.
   1614 
   1615 void
   1616 Output_section_element_input::set_section_addresses(
   1617     Symbol_table*,
   1618     Layout* layout,
   1619     Output_section* output_section,
   1620     uint64_t subalign,
   1621     uint64_t* dot_value,
   1622     uint64_t*,
   1623     Output_section** dot_section,
   1624     std::string* fill,
   1625     Input_section_list* input_sections)
   1626 {
   1627   // We build a list of sections which match each
   1628   // Input_section_pattern.
   1629 
   1630   // If none of the patterns specify a sort option, we throw all
   1631   // matching input sections into a single bin, in the order we
   1632   // find them.  Otherwise, we put matching input sections into
   1633   // a separate bin for each pattern, and sort each one as
   1634   // specified.  Thus, an input section spec like this:
   1635   //   *(.foo .bar)
   1636   // will group all .foo and .bar sections in the order seen,
   1637   // whereas this:
   1638   //   *(.foo) *(.bar)
   1639   // will group all .foo sections followed by all .bar sections.
   1640   // This matches Gnu ld behavior.
   1641 
   1642   // Things get really weird, though, when you add a sort spec
   1643   // on some, but not all, of the patterns, like this:
   1644   //   *(SORT_BY_NAME(.foo) .bar)
   1645   // We do not attempt to match Gnu ld behavior in this case.
   1646 
   1647   typedef std::vector<std::vector<Input_section_info> > Matching_sections;
   1648   size_t input_pattern_count = this->input_section_patterns_.size();
   1649   size_t bin_count = 1;
   1650   bool any_patterns_with_sort = false;
   1651   for (size_t i = 0; i < input_pattern_count; ++i)
   1652     {
   1653       const Input_section_pattern& isp(this->input_section_patterns_[i]);
   1654       if (isp.sort != SORT_WILDCARD_NONE)
   1655 	any_patterns_with_sort = true;
   1656     }
   1657   if (any_patterns_with_sort)
   1658     bin_count = input_pattern_count;
   1659   Matching_sections matching_sections(bin_count);
   1660 
   1661   // Look through the list of sections for this output section.  Add
   1662   // each one which matches to one of the elements of
   1663   // MATCHING_SECTIONS.
   1664 
   1665   Input_section_list::iterator p = input_sections->begin();
   1666   while (p != input_sections->end())
   1667     {
   1668       Relobj* relobj = p->relobj();
   1669       unsigned int shndx = p->shndx();
   1670       Input_section_info isi(*p);
   1671 
   1672       // Calling section_name and section_addralign is not very
   1673       // efficient.
   1674 
   1675       // Lock the object so that we can get information about the
   1676       // section.  This is OK since we know we are single-threaded
   1677       // here.
   1678       {
   1679 	const Task* task = reinterpret_cast<const Task*>(-1);
   1680 	Task_lock_obj<Object> tl(task, relobj);
   1681 
   1682 	isi.set_section_name(relobj->section_name(shndx));
   1683 	if (p->is_relaxed_input_section())
   1684 	  {
   1685 	    // We use current data size because relaxed section sizes may not
   1686 	    // have finalized yet.
   1687 	    isi.set_size(p->relaxed_input_section()->current_data_size());
   1688 	    isi.set_addralign(p->relaxed_input_section()->addralign());
   1689 	  }
   1690 	else
   1691 	  {
   1692 	    isi.set_size(relobj->section_size(shndx));
   1693 	    isi.set_addralign(relobj->section_addralign(shndx));
   1694 	  }
   1695       }
   1696 
   1697       if (!this->match_file_name(relobj->name().c_str()))
   1698 	++p;
   1699       else if (this->input_section_patterns_.empty())
   1700 	{
   1701 	  matching_sections[0].push_back(isi);
   1702 	  p = input_sections->erase(p);
   1703 	}
   1704       else
   1705 	{
   1706 	  size_t i;
   1707 	  for (i = 0; i < input_pattern_count; ++i)
   1708 	    {
   1709 	      const Input_section_pattern&
   1710 		isp(this->input_section_patterns_[i]);
   1711 	      if (match(isi.section_name().c_str(), isp.pattern.c_str(),
   1712 			isp.pattern_is_wildcard))
   1713 		break;
   1714 	    }
   1715 
   1716 	  if (i >= input_pattern_count)
   1717 	    ++p;
   1718 	  else
   1719 	    {
   1720 	      if (i >= bin_count)
   1721 		i = 0;
   1722 	      matching_sections[i].push_back(isi);
   1723 	      p = input_sections->erase(p);
   1724 	    }
   1725 	}
   1726     }
   1727 
   1728   // Look through MATCHING_SECTIONS.  Sort each one as specified,
   1729   // using a stable sort so that we get the default order when
   1730   // sections are otherwise equal.  Add each input section to the
   1731   // output section.
   1732 
   1733   uint64_t dot = *dot_value;
   1734   for (size_t i = 0; i < bin_count; ++i)
   1735     {
   1736       if (matching_sections[i].empty())
   1737 	continue;
   1738 
   1739       gold_assert(output_section != NULL);
   1740 
   1741       const Input_section_pattern& isp(this->input_section_patterns_[i]);
   1742       if (isp.sort != SORT_WILDCARD_NONE
   1743 	  || this->filename_sort_ != SORT_WILDCARD_NONE)
   1744 	std::stable_sort(matching_sections[i].begin(),
   1745 			 matching_sections[i].end(),
   1746 			 Input_section_sorter(this->filename_sort_,
   1747 					      isp.sort));
   1748 
   1749       for (std::vector<Input_section_info>::const_iterator p =
   1750 	     matching_sections[i].begin();
   1751 	   p != matching_sections[i].end();
   1752 	   ++p)
   1753 	{
   1754 	  // Override the original address alignment if SUBALIGN is specified
   1755 	  // and is greater than the original alignment.  We need to make a
   1756 	  // copy of the input section to modify the alignment.
   1757 	  Output_section::Input_section sis(p->input_section());
   1758 
   1759 	  uint64_t this_subalign = sis.addralign();
   1760 	  if (!sis.is_input_section())
   1761 	    sis.output_section_data()->finalize_data_size();
   1762 	  uint64_t data_size = sis.data_size();
   1763 	  if (this_subalign < subalign)
   1764 	    {
   1765 	      this_subalign = subalign;
   1766 	      sis.set_addralign(subalign);
   1767 	    }
   1768 
   1769 	  uint64_t address = align_address(dot, this_subalign);
   1770 
   1771 	  if (address > dot && !fill->empty())
   1772 	    {
   1773 	      section_size_type length =
   1774 		convert_to_section_size_type(address - dot);
   1775 	      std::string this_fill = this->get_fill_string(fill, length);
   1776 	      Output_section_data* posd = new Output_data_const(this_fill, 0);
   1777 	      output_section->add_output_section_data(posd);
   1778 	      layout->new_output_section_data_from_script(posd);
   1779 	    }
   1780 
   1781 	  output_section->add_script_input_section(sis);
   1782 	  dot = address + data_size;
   1783 	}
   1784     }
   1785 
   1786   // An SHF_TLS/SHT_NOBITS section does not take up any
   1787   // address space.
   1788   if (output_section == NULL
   1789       || (output_section->flags() & elfcpp::SHF_TLS) == 0
   1790       || output_section->type() != elfcpp::SHT_NOBITS)
   1791     *dot_value = dot;
   1792 
   1793   this->final_dot_value_ = *dot_value;
   1794   this->final_dot_section_ = *dot_section;
   1795 }
   1796 
   1797 // Print for debugging.
   1798 
   1799 void
   1800 Output_section_element_input::print(FILE* f) const
   1801 {
   1802   fprintf(f, "    ");
   1803 
   1804   if (this->keep_)
   1805     fprintf(f, "KEEP(");
   1806 
   1807   if (!this->filename_pattern_.empty())
   1808     {
   1809       bool need_close_paren = false;
   1810       switch (this->filename_sort_)
   1811 	{
   1812 	case SORT_WILDCARD_NONE:
   1813 	  break;
   1814 	case SORT_WILDCARD_BY_NAME:
   1815 	  fprintf(f, "SORT_BY_NAME(");
   1816 	  need_close_paren = true;
   1817 	  break;
   1818 	default:
   1819 	  gold_unreachable();
   1820 	}
   1821 
   1822       fprintf(f, "%s", this->filename_pattern_.c_str());
   1823 
   1824       if (need_close_paren)
   1825 	fprintf(f, ")");
   1826     }
   1827 
   1828   if (!this->input_section_patterns_.empty()
   1829       || !this->filename_exclusions_.empty())
   1830     {
   1831       fprintf(f, "(");
   1832 
   1833       bool need_space = false;
   1834       if (!this->filename_exclusions_.empty())
   1835 	{
   1836 	  fprintf(f, "EXCLUDE_FILE(");
   1837 	  bool need_comma = false;
   1838 	  for (Filename_exclusions::const_iterator p =
   1839 		 this->filename_exclusions_.begin();
   1840 	       p != this->filename_exclusions_.end();
   1841 	       ++p)
   1842 	    {
   1843 	      if (need_comma)
   1844 		fprintf(f, ", ");
   1845 	      fprintf(f, "%s", p->first.c_str());
   1846 	      need_comma = true;
   1847 	    }
   1848 	  fprintf(f, ")");
   1849 	  need_space = true;
   1850 	}
   1851 
   1852       for (Input_section_patterns::const_iterator p =
   1853 	     this->input_section_patterns_.begin();
   1854 	   p != this->input_section_patterns_.end();
   1855 	   ++p)
   1856 	{
   1857 	  if (need_space)
   1858 	    fprintf(f, " ");
   1859 
   1860 	  int close_parens = 0;
   1861 	  switch (p->sort)
   1862 	    {
   1863 	    case SORT_WILDCARD_NONE:
   1864 	      break;
   1865 	    case SORT_WILDCARD_BY_NAME:
   1866 	      fprintf(f, "SORT_BY_NAME(");
   1867 	      close_parens = 1;
   1868 	      break;
   1869 	    case SORT_WILDCARD_BY_ALIGNMENT:
   1870 	      fprintf(f, "SORT_BY_ALIGNMENT(");
   1871 	      close_parens = 1;
   1872 	      break;
   1873 	    case SORT_WILDCARD_BY_NAME_BY_ALIGNMENT:
   1874 	      fprintf(f, "SORT_BY_NAME(SORT_BY_ALIGNMENT(");
   1875 	      close_parens = 2;
   1876 	      break;
   1877 	    case SORT_WILDCARD_BY_ALIGNMENT_BY_NAME:
   1878 	      fprintf(f, "SORT_BY_ALIGNMENT(SORT_BY_NAME(");
   1879 	      close_parens = 2;
   1880 	      break;
   1881 	    case SORT_WILDCARD_BY_INIT_PRIORITY:
   1882 	      fprintf(f, "SORT_BY_INIT_PRIORITY(");
   1883 	      close_parens = 1;
   1884 	      break;
   1885 	    default:
   1886 	      gold_unreachable();
   1887 	    }
   1888 
   1889 	  fprintf(f, "%s", p->pattern.c_str());
   1890 
   1891 	  for (int i = 0; i < close_parens; ++i)
   1892 	    fprintf(f, ")");
   1893 
   1894 	  need_space = true;
   1895 	}
   1896 
   1897       fprintf(f, ")");
   1898     }
   1899 
   1900   if (this->keep_)
   1901     fprintf(f, ")");
   1902 
   1903   fprintf(f, "\n");
   1904 }
   1905 
   1906 // An output section.
   1907 
   1908 class Output_section_definition : public Sections_element
   1909 {
   1910  public:
   1911   typedef Output_section_element::Input_section_list Input_section_list;
   1912 
   1913   Output_section_definition(const char* name, size_t namelen,
   1914 			    const Parser_output_section_header* header);
   1915 
   1916   // Finish the output section with the information in the trailer.
   1917   void
   1918   finish(const Parser_output_section_trailer* trailer);
   1919 
   1920   // Add a symbol to be defined.
   1921   void
   1922   add_symbol_assignment(const char* name, size_t length, Expression* value,
   1923 			bool provide, bool hidden);
   1924 
   1925   // Add an assignment to the special dot symbol.
   1926   void
   1927   add_dot_assignment(Expression* value);
   1928 
   1929   // Add an assertion.
   1930   void
   1931   add_assertion(Expression* check, const char* message, size_t messagelen);
   1932 
   1933   // Add a data item to the current output section.
   1934   void
   1935   add_data(int size, bool is_signed, Expression* val);
   1936 
   1937   // Add a setting for the fill value.
   1938   void
   1939   add_fill(Expression* val);
   1940 
   1941   // Add an input section specification.
   1942   void
   1943   add_input_section(const Input_section_spec* spec, bool keep);
   1944 
   1945   // Return whether the output section is relro.
   1946   bool
   1947   is_relro() const
   1948   { return this->is_relro_; }
   1949 
   1950   // Record that the output section is relro.
   1951   void
   1952   set_is_relro()
   1953   { this->is_relro_ = true; }
   1954 
   1955   // Create any required output sections.
   1956   void
   1957   create_sections(Layout*);
   1958 
   1959   // Add any symbols being defined to the symbol table.
   1960   void
   1961   add_symbols_to_table(Symbol_table* symtab);
   1962 
   1963   // Finalize symbols and check assertions.
   1964   void
   1965   finalize_symbols(Symbol_table*, const Layout*, uint64_t*);
   1966 
   1967   // Return the output section name to use for an input file name and
   1968   // section name.
   1969   const char*
   1970   output_section_name(const char* file_name, const char* section_name,
   1971 		      Output_section***, Script_sections::Section_type*,
   1972 		      bool*);
   1973 
   1974   // Initialize OSP with an output section.
   1975   void
   1976   orphan_section_init(Orphan_section_placement* osp,
   1977 		      Script_sections::Elements_iterator p)
   1978   { osp->output_section_init(this->name_, this->output_section_, p); }
   1979 
   1980   // Set the section address.
   1981   void
   1982   set_section_addresses(Symbol_table* symtab, Layout* layout,
   1983 			uint64_t* dot_value, uint64_t*,
   1984 			uint64_t* load_address);
   1985 
   1986   // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
   1987   // this section is constrained, and the input sections do not match,
   1988   // return the constraint, and set *POSD.
   1989   Section_constraint
   1990   check_constraint(Output_section_definition** posd);
   1991 
   1992   // See if this is the alternate output section for a constrained
   1993   // output section.  If it is, transfer the Output_section and return
   1994   // true.  Otherwise return false.
   1995   bool
   1996   alternate_constraint(Output_section_definition*, Section_constraint);
   1997 
   1998   // Get the list of segments to use for an allocated section when
   1999   // using a PHDRS clause.
   2000   Output_section*
   2001   allocate_to_segment(String_list** phdrs_list, bool* orphan);
   2002 
   2003   // Look for an output section by name and return the address, the
   2004   // load address, the alignment, and the size.  This is used when an
   2005   // expression refers to an output section which was not actually
   2006   // created.  This returns true if the section was found, false
   2007   // otherwise.
   2008   bool
   2009   get_output_section_info(const char*, uint64_t*, uint64_t*, uint64_t*,
   2010                           uint64_t*) const;
   2011 
   2012   // Return the associated Output_section if there is one.
   2013   Output_section*
   2014   get_output_section() const
   2015   { return this->output_section_; }
   2016 
   2017   // Print the contents to the FILE.  This is for debugging.
   2018   void
   2019   print(FILE*) const;
   2020 
   2021   // Return the output section type if specified or Script_sections::ST_NONE.
   2022   Script_sections::Section_type
   2023   section_type() const;
   2024 
   2025   // Store the memory region to use.
   2026   void
   2027   set_memory_region(Memory_region*, bool set_vma);
   2028 
   2029   void
   2030   set_section_vma(Expression* address)
   2031   { this->address_ = address; }
   2032 
   2033   void
   2034   set_section_lma(Expression* address)
   2035   { this->load_address_ = address; }
   2036 
   2037   const std::string&
   2038   get_section_name() const
   2039   { return this->name_; }
   2040 
   2041  private:
   2042   static const char*
   2043   script_section_type_name(Script_section_type);
   2044 
   2045   typedef std::vector<Output_section_element*> Output_section_elements;
   2046 
   2047   // The output section name.
   2048   std::string name_;
   2049   // The address.  This may be NULL.
   2050   Expression* address_;
   2051   // The load address.  This may be NULL.
   2052   Expression* load_address_;
   2053   // The alignment.  This may be NULL.
   2054   Expression* align_;
   2055   // The input section alignment.  This may be NULL.
   2056   Expression* subalign_;
   2057   // The constraint, if any.
   2058   Section_constraint constraint_;
   2059   // The fill value.  This may be NULL.
   2060   Expression* fill_;
   2061   // The list of segments this section should go into.  This may be
   2062   // NULL.
   2063   String_list* phdrs_;
   2064   // The list of elements defining the section.
   2065   Output_section_elements elements_;
   2066   // The Output_section created for this definition.  This will be
   2067   // NULL if none was created.
   2068   Output_section* output_section_;
   2069   // The address after it has been evaluated.
   2070   uint64_t evaluated_address_;
   2071   // The load address after it has been evaluated.
   2072   uint64_t evaluated_load_address_;
   2073   // The alignment after it has been evaluated.
   2074   uint64_t evaluated_addralign_;
   2075   // The output section is relro.
   2076   bool is_relro_;
   2077   // The output section type if specified.
   2078   enum Script_section_type script_section_type_;
   2079 };
   2080 
   2081 // Constructor.
   2082 
   2083 Output_section_definition::Output_section_definition(
   2084     const char* name,
   2085     size_t namelen,
   2086     const Parser_output_section_header* header)
   2087   : name_(name, namelen),
   2088     address_(header->address),
   2089     load_address_(header->load_address),
   2090     align_(header->align),
   2091     subalign_(header->subalign),
   2092     constraint_(header->constraint),
   2093     fill_(NULL),
   2094     phdrs_(NULL),
   2095     elements_(),
   2096     output_section_(NULL),
   2097     evaluated_address_(0),
   2098     evaluated_load_address_(0),
   2099     evaluated_addralign_(0),
   2100     is_relro_(false),
   2101     script_section_type_(header->section_type)
   2102 {
   2103 }
   2104 
   2105 // Finish an output section.
   2106 
   2107 void
   2108 Output_section_definition::finish(const Parser_output_section_trailer* trailer)
   2109 {
   2110   this->fill_ = trailer->fill;
   2111   this->phdrs_ = trailer->phdrs;
   2112 }
   2113 
   2114 // Add a symbol to be defined.
   2115 
   2116 void
   2117 Output_section_definition::add_symbol_assignment(const char* name,
   2118 						 size_t length,
   2119 						 Expression* value,
   2120 						 bool provide,
   2121 						 bool hidden)
   2122 {
   2123   Output_section_element* p = new Output_section_element_assignment(name,
   2124 								    length,
   2125 								    value,
   2126 								    provide,
   2127 								    hidden);
   2128   this->elements_.push_back(p);
   2129 }
   2130 
   2131 // Add an assignment to the special dot symbol.
   2132 
   2133 void
   2134 Output_section_definition::add_dot_assignment(Expression* value)
   2135 {
   2136   Output_section_element* p = new Output_section_element_dot_assignment(value);
   2137   this->elements_.push_back(p);
   2138 }
   2139 
   2140 // Add an assertion.
   2141 
   2142 void
   2143 Output_section_definition::add_assertion(Expression* check,
   2144 					 const char* message,
   2145 					 size_t messagelen)
   2146 {
   2147   Output_section_element* p = new Output_section_element_assertion(check,
   2148 								   message,
   2149 								   messagelen);
   2150   this->elements_.push_back(p);
   2151 }
   2152 
   2153 // Add a data item to the current output section.
   2154 
   2155 void
   2156 Output_section_definition::add_data(int size, bool is_signed, Expression* val)
   2157 {
   2158   Output_section_element* p = new Output_section_element_data(size, is_signed,
   2159 							      val);
   2160   this->elements_.push_back(p);
   2161 }
   2162 
   2163 // Add a setting for the fill value.
   2164 
   2165 void
   2166 Output_section_definition::add_fill(Expression* val)
   2167 {
   2168   Output_section_element* p = new Output_section_element_fill(val);
   2169   this->elements_.push_back(p);
   2170 }
   2171 
   2172 // Add an input section specification.
   2173 
   2174 void
   2175 Output_section_definition::add_input_section(const Input_section_spec* spec,
   2176 					     bool keep)
   2177 {
   2178   Output_section_element* p = new Output_section_element_input(spec, keep);
   2179   this->elements_.push_back(p);
   2180 }
   2181 
   2182 // Create any required output sections.  We need an output section if
   2183 // there is a data statement here.
   2184 
   2185 void
   2186 Output_section_definition::create_sections(Layout* layout)
   2187 {
   2188   if (this->output_section_ != NULL)
   2189     return;
   2190   for (Output_section_elements::const_iterator p = this->elements_.begin();
   2191        p != this->elements_.end();
   2192        ++p)
   2193     {
   2194       if ((*p)->needs_output_section())
   2195 	{
   2196 	  const char* name = this->name_.c_str();
   2197 	  this->output_section_ =
   2198 	    layout->make_output_section_for_script(name, this->section_type());
   2199 	  return;
   2200 	}
   2201     }
   2202 }
   2203 
   2204 // Add any symbols being defined to the symbol table.
   2205 
   2206 void
   2207 Output_section_definition::add_symbols_to_table(Symbol_table* symtab)
   2208 {
   2209   for (Output_section_elements::iterator p = this->elements_.begin();
   2210        p != this->elements_.end();
   2211        ++p)
   2212     (*p)->add_symbols_to_table(symtab);
   2213 }
   2214 
   2215 // Finalize symbols and check assertions.
   2216 
   2217 void
   2218 Output_section_definition::finalize_symbols(Symbol_table* symtab,
   2219 					    const Layout* layout,
   2220 					    uint64_t* dot_value)
   2221 {
   2222   if (this->output_section_ != NULL)
   2223     *dot_value = this->output_section_->address();
   2224   else
   2225     {
   2226       uint64_t address = *dot_value;
   2227       if (this->address_ != NULL)
   2228 	{
   2229 	  address = this->address_->eval_with_dot(symtab, layout, true,
   2230 						  *dot_value, NULL,
   2231 						  NULL, NULL, false);
   2232 	}
   2233       if (this->align_ != NULL)
   2234 	{
   2235 	  uint64_t align = this->align_->eval_with_dot(symtab, layout, true,
   2236 						       *dot_value, NULL,
   2237 						       NULL, NULL, false);
   2238 	  address = align_address(address, align);
   2239 	}
   2240       *dot_value = address;
   2241     }
   2242 
   2243   Output_section* dot_section = this->output_section_;
   2244   for (Output_section_elements::iterator p = this->elements_.begin();
   2245        p != this->elements_.end();
   2246        ++p)
   2247     (*p)->finalize_symbols(symtab, layout, dot_value, &dot_section);
   2248 }
   2249 
   2250 // Return the output section name to use for an input section name.
   2251 
   2252 const char*
   2253 Output_section_definition::output_section_name(
   2254     const char* file_name,
   2255     const char* section_name,
   2256     Output_section*** slot,
   2257     Script_sections::Section_type* psection_type,
   2258     bool* keep)
   2259 {
   2260   // Ask each element whether it matches NAME.
   2261   for (Output_section_elements::const_iterator p = this->elements_.begin();
   2262        p != this->elements_.end();
   2263        ++p)
   2264     {
   2265       if ((*p)->match_name(file_name, section_name, keep))
   2266 	{
   2267 	  // We found a match for NAME, which means that it should go
   2268 	  // into this output section.
   2269 	  *slot = &this->output_section_;
   2270 	  *psection_type = this->section_type();
   2271 	  return this->name_.c_str();
   2272 	}
   2273     }
   2274 
   2275   // We don't know about this section name.
   2276   return NULL;
   2277 }
   2278 
   2279 // Return true if memory from START to START + LENGTH is contained
   2280 // within a memory region.
   2281 
   2282 bool
   2283 Script_sections::block_in_region(Symbol_table* symtab, Layout* layout,
   2284 				 uint64_t start, uint64_t length) const
   2285 {
   2286   if (this->memory_regions_ == NULL)
   2287     return false;
   2288 
   2289   for (Memory_regions::const_iterator mr = this->memory_regions_->begin();
   2290        mr != this->memory_regions_->end();
   2291        ++mr)
   2292     {
   2293       uint64_t s = (*mr)->start_address()->eval(symtab, layout, false);
   2294       uint64_t l = (*mr)->length()->eval(symtab, layout, false);
   2295 
   2296       if (s <= start
   2297 	  && (s + l) >= (start + length))
   2298 	return true;
   2299     }
   2300 
   2301   return false;
   2302 }
   2303 
   2304 // Find a memory region that should be used by a given output SECTION.
   2305 // If provided set PREVIOUS_SECTION_RETURN to point to the last section
   2306 // that used the return memory region.
   2307 
   2308 Memory_region*
   2309 Script_sections::find_memory_region(
   2310     Output_section_definition* section,
   2311     bool find_vma_region,
   2312     bool explicit_only,
   2313     Output_section_definition** previous_section_return)
   2314 {
   2315   if (previous_section_return != NULL)
   2316     * previous_section_return = NULL;
   2317 
   2318   // Walk the memory regions specified in this script, if any.
   2319   if (this->memory_regions_ == NULL)
   2320     return NULL;
   2321 
   2322   // The /DISCARD/ section never gets assigned to any region.
   2323   if (section->get_section_name() == "/DISCARD/")
   2324     return NULL;
   2325 
   2326   Memory_region* first_match = NULL;
   2327 
   2328   // First check to see if a region has been assigned to this section.
   2329   for (Memory_regions::const_iterator mr = this->memory_regions_->begin();
   2330        mr != this->memory_regions_->end();
   2331        ++mr)
   2332     {
   2333       if (find_vma_region)
   2334 	{
   2335 	  for (Memory_region::Section_list::const_iterator s =
   2336 		 (*mr)->get_vma_section_list_start();
   2337 	       s != (*mr)->get_vma_section_list_end();
   2338 	       ++s)
   2339 	    if ((*s) == section)
   2340 	      {
   2341 		(*mr)->set_last_section(section);
   2342 		return *mr;
   2343 	      }
   2344 	}
   2345       else
   2346 	{
   2347 	  for (Memory_region::Section_list::const_iterator s =
   2348 		 (*mr)->get_lma_section_list_start();
   2349 	       s != (*mr)->get_lma_section_list_end();
   2350 	       ++s)
   2351 	    if ((*s) == section)
   2352 	      {
   2353 		(*mr)->set_last_section(section);
   2354 		return *mr;
   2355 	      }
   2356 	}
   2357 
   2358       if (!explicit_only)
   2359 	{
   2360 	  // Make a note of the first memory region whose attributes
   2361 	  // are compatible with the section.  If we do not find an
   2362 	  // explicit region assignment, then we will return this region.
   2363 	  Output_section* out_sec = section->get_output_section();
   2364 	  if (first_match == NULL
   2365 	      && out_sec != NULL
   2366 	      && (*mr)->attributes_compatible(out_sec->flags(),
   2367 					      out_sec->type()))
   2368 	    first_match = *mr;
   2369 	}
   2370     }
   2371 
   2372   // With LMA computations, if an explicit region has not been specified then
   2373   // we will want to set the difference between the VMA and the LMA of the
   2374   // section were searching for to be the same as the difference between the
   2375   // VMA and LMA of the last section to be added to first matched region.
   2376   // Hence, if it was asked for, we return a pointer to the last section
   2377   // known to be used by the first matched region.
   2378   if (first_match != NULL
   2379       && previous_section_return != NULL)
   2380     *previous_section_return = first_match->get_last_section();
   2381 
   2382   return first_match;
   2383 }
   2384 
   2385 // Set the section address.  Note that the OUTPUT_SECTION_ field will
   2386 // be NULL if no input sections were mapped to this output section.
   2387 // We still have to adjust dot and process symbol assignments.
   2388 
   2389 void
   2390 Output_section_definition::set_section_addresses(Symbol_table* symtab,
   2391 						 Layout* layout,
   2392 						 uint64_t* dot_value,
   2393 						 uint64_t* dot_alignment,
   2394                                                  uint64_t* load_address)
   2395 {
   2396   Memory_region* vma_region = NULL;
   2397   Memory_region* lma_region = NULL;
   2398   Script_sections* script_sections =
   2399     layout->script_options()->script_sections();
   2400   uint64_t address;
   2401   uint64_t old_dot_value = *dot_value;
   2402   uint64_t old_load_address = *load_address;
   2403 
   2404   // If input section sorting is requested via --section-ordering-file or
   2405   // linker plugins, then do it here.  This is important because we want
   2406   // any sorting specified in the linker scripts, which will be done after
   2407   // this, to take precedence.  The final order of input sections is then
   2408   // guaranteed to be according to the linker script specification.
   2409   if (this->output_section_ != NULL
   2410       && this->output_section_->input_section_order_specified())
   2411     this->output_section_->sort_attached_input_sections();
   2412 
   2413   // Decide the start address for the section.  The algorithm is:
   2414   // 1) If an address has been specified in a linker script, use that.
   2415   // 2) Otherwise if a memory region has been specified for the section,
   2416   //    use the next free address in the region.
   2417   // 3) Otherwise if memory regions have been specified find the first
   2418   //    region whose attributes are compatible with this section and
   2419   //    install it into that region.
   2420   // 4) Otherwise use the current location counter.
   2421 
   2422   if (this->output_section_ != NULL
   2423       // Check for --section-start.
   2424       && parameters->options().section_start(this->output_section_->name(),
   2425 					     &address))
   2426     ;
   2427   else if (this->address_ == NULL)
   2428     {
   2429       vma_region = script_sections->find_memory_region(this, true, false, NULL);
   2430       if (vma_region != NULL)
   2431 	address = vma_region->get_current_address()->eval(symtab, layout,
   2432 							  false);
   2433       else
   2434 	address = *dot_value;
   2435     }
   2436   else
   2437     {
   2438       vma_region = script_sections->find_memory_region(this, true, true, NULL);
   2439       address = this->address_->eval_with_dot(symtab, layout, true,
   2440 					      *dot_value, NULL, NULL,
   2441 					      dot_alignment, false);
   2442       if (vma_region != NULL)
   2443 	vma_region->set_address(address, symtab, layout);
   2444     }
   2445 
   2446   uint64_t align;
   2447   if (this->align_ == NULL)
   2448     {
   2449       if (this->output_section_ == NULL)
   2450 	align = 0;
   2451       else
   2452 	align = this->output_section_->addralign();
   2453     }
   2454   else
   2455     {
   2456       Output_section* align_section;
   2457       align = this->align_->eval_with_dot(symtab, layout, true, *dot_value,
   2458 					  NULL, &align_section, NULL, false);
   2459       if (align_section != NULL)
   2460 	gold_warning(_("alignment of section %s is not absolute"),
   2461 		     this->name_.c_str());
   2462       if (this->output_section_ != NULL)
   2463 	this->output_section_->set_addralign(align);
   2464     }
   2465 
   2466   address = align_address(address, align);
   2467 
   2468   uint64_t start_address = address;
   2469 
   2470   *dot_value = address;
   2471 
   2472   // Except for NOLOAD sections, the address of non-SHF_ALLOC sections is
   2473   // forced to zero, regardless of what the linker script wants.
   2474   if (this->output_section_ != NULL
   2475       && ((this->output_section_->flags() & elfcpp::SHF_ALLOC) != 0
   2476 	  || this->output_section_->is_noload()))
   2477     this->output_section_->set_address(address);
   2478 
   2479   this->evaluated_address_ = address;
   2480   this->evaluated_addralign_ = align;
   2481 
   2482   uint64_t laddr;
   2483 
   2484   if (this->load_address_ == NULL)
   2485     {
   2486       Output_section_definition* previous_section;
   2487 
   2488       // Determine if an LMA region has been set for this section.
   2489       lma_region = script_sections->find_memory_region(this, false, false,
   2490 						       &previous_section);
   2491 
   2492       if (lma_region != NULL)
   2493 	{
   2494 	  if (previous_section == NULL)
   2495 	    // The LMA address was explicitly set to the given region.
   2496 	    laddr = lma_region->get_current_address()->eval(symtab, layout,
   2497 							    false);
   2498 	  else
   2499 	    {
   2500 	      // We are not going to use the discovered lma_region, so
   2501 	      // make sure that we do not update it in the code below.
   2502 	      lma_region = NULL;
   2503 
   2504 	      if (this->address_ != NULL || previous_section == this)
   2505 		{
   2506 		  // Either an explicit VMA address has been set, or an
   2507 		  // explicit VMA region has been set, so set the LMA equal to
   2508 		  // the VMA.
   2509 		  laddr = address;
   2510 		}
   2511 	      else
   2512 		{
   2513 		  // The LMA address was not explicitly or implicitly set.
   2514 		  //
   2515 		  // We have been given the first memory region that is
   2516 		  // compatible with the current section and a pointer to the
   2517 		  // last section to use this region.  Set the LMA of this
   2518 		  // section so that the difference between its' VMA and LMA
   2519 		  // is the same as the difference between the VMA and LMA of
   2520 		  // the last section in the given region.
   2521 		  laddr = address + (previous_section->evaluated_load_address_
   2522 				     - previous_section->evaluated_address_);
   2523 		}
   2524 	    }
   2525 
   2526 	  if (this->output_section_ != NULL)
   2527 	    this->output_section_->set_load_address(laddr);
   2528 	}
   2529       else
   2530 	{
   2531 	  // Do not set the load address of the output section, if one exists.
   2532 	  // This allows future sections to determine what the load address
   2533 	  // should be.  If none is ever set, it will default to being the
   2534 	  // same as the vma address.
   2535 	  laddr = address;
   2536 	}
   2537     }
   2538   else
   2539     {
   2540       laddr = this->load_address_->eval_with_dot(symtab, layout, true,
   2541 						 *dot_value,
   2542 						 this->output_section_,
   2543 						 NULL, NULL, false);
   2544       if (this->output_section_ != NULL)
   2545         this->output_section_->set_load_address(laddr);
   2546     }
   2547 
   2548   this->evaluated_load_address_ = laddr;
   2549 
   2550   uint64_t subalign;
   2551   if (this->subalign_ == NULL)
   2552     subalign = 0;
   2553   else
   2554     {
   2555       Output_section* subalign_section;
   2556       subalign = this->subalign_->eval_with_dot(symtab, layout, true,
   2557 						*dot_value, NULL,
   2558 						&subalign_section, NULL,
   2559 						false);
   2560       if (subalign_section != NULL)
   2561 	gold_warning(_("subalign of section %s is not absolute"),
   2562 		     this->name_.c_str());
   2563     }
   2564 
   2565   std::string fill;
   2566   if (this->fill_ != NULL)
   2567     {
   2568       // FIXME: The GNU linker supports fill values of arbitrary
   2569       // length.
   2570       Output_section* fill_section;
   2571       uint64_t fill_val = this->fill_->eval_with_dot(symtab, layout, true,
   2572 						     *dot_value,
   2573 						     NULL, &fill_section,
   2574 						     NULL, false);
   2575       if (fill_section != NULL)
   2576 	gold_warning(_("fill of section %s is not absolute"),
   2577 		     this->name_.c_str());
   2578       unsigned char fill_buff[4];
   2579       elfcpp::Swap_unaligned<32, true>::writeval(fill_buff, fill_val);
   2580       fill.assign(reinterpret_cast<char*>(fill_buff), 4);
   2581     }
   2582 
   2583   Input_section_list input_sections;
   2584   if (this->output_section_ != NULL)
   2585     {
   2586       // Get the list of input sections attached to this output
   2587       // section.  This will leave the output section with only
   2588       // Output_section_data entries.
   2589       address += this->output_section_->get_input_sections(address,
   2590 							   fill,
   2591 							   &input_sections);
   2592       *dot_value = address;
   2593     }
   2594 
   2595   Output_section* dot_section = this->output_section_;
   2596   for (Output_section_elements::iterator p = this->elements_.begin();
   2597        p != this->elements_.end();
   2598        ++p)
   2599     (*p)->set_section_addresses(symtab, layout, this->output_section_,
   2600 				subalign, dot_value, dot_alignment,
   2601 				&dot_section, &fill, &input_sections);
   2602 
   2603   gold_assert(input_sections.empty());
   2604 
   2605   if (vma_region != NULL)
   2606     {
   2607       // Update the VMA region being used by the section now that we know how
   2608       // big it is.  Use the current address in the region, rather than
   2609       // start_address because that might have been aligned upwards and we
   2610       // need to allow for the padding.
   2611       Expression* addr = vma_region->get_current_address();
   2612       uint64_t size = *dot_value - addr->eval(symtab, layout, false);
   2613 
   2614       vma_region->increment_offset(this->get_section_name(), size,
   2615 				   symtab, layout);
   2616     }
   2617 
   2618   // If the LMA region is different from the VMA region, then increment the
   2619   // offset there as well.  Note that we use the same "dot_value -
   2620   // start_address" formula that is used in the load_address assignment below.
   2621   if (lma_region != NULL && lma_region != vma_region)
   2622     lma_region->increment_offset(this->get_section_name(),
   2623 				 *dot_value - start_address,
   2624 				 symtab, layout);
   2625 
   2626   // Compute the load address for the following section.
   2627   if (this->output_section_ == NULL)
   2628     *load_address = *dot_value;
   2629   else if (this->load_address_ == NULL)
   2630     {
   2631       if (lma_region == NULL)
   2632 	*load_address = *dot_value;
   2633       else
   2634 	*load_address =
   2635 	  lma_region->get_current_address()->eval(symtab, layout, false);
   2636     }
   2637   else
   2638     *load_address = (this->output_section_->load_address()
   2639                      + (*dot_value - start_address));
   2640 
   2641   if (this->output_section_ != NULL)
   2642     {
   2643       if (this->is_relro_)
   2644 	this->output_section_->set_is_relro();
   2645       else
   2646 	this->output_section_->clear_is_relro();
   2647 
   2648       // If this is a NOLOAD section, keep dot and load address unchanged.
   2649       if (this->output_section_->is_noload())
   2650 	{
   2651 	  *dot_value = old_dot_value;
   2652 	  *load_address = old_load_address;
   2653 	}
   2654     }
   2655 }
   2656 
   2657 // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
   2658 // this section is constrained, and the input sections do not match,
   2659 // return the constraint, and set *POSD.
   2660 
   2661 Section_constraint
   2662 Output_section_definition::check_constraint(Output_section_definition** posd)
   2663 {
   2664   switch (this->constraint_)
   2665     {
   2666     case CONSTRAINT_NONE:
   2667       return CONSTRAINT_NONE;
   2668 
   2669     case CONSTRAINT_ONLY_IF_RO:
   2670       if (this->output_section_ != NULL
   2671 	  && (this->output_section_->flags() & elfcpp::SHF_WRITE) != 0)
   2672 	{
   2673 	  *posd = this;
   2674 	  return CONSTRAINT_ONLY_IF_RO;
   2675 	}
   2676       return CONSTRAINT_NONE;
   2677 
   2678     case CONSTRAINT_ONLY_IF_RW:
   2679       if (this->output_section_ != NULL
   2680 	  && (this->output_section_->flags() & elfcpp::SHF_WRITE) == 0)
   2681 	{
   2682 	  *posd = this;
   2683 	  return CONSTRAINT_ONLY_IF_RW;
   2684 	}
   2685       return CONSTRAINT_NONE;
   2686 
   2687     case CONSTRAINT_SPECIAL:
   2688       if (this->output_section_ != NULL)
   2689 	gold_error(_("SPECIAL constraints are not implemented"));
   2690       return CONSTRAINT_NONE;
   2691 
   2692     default:
   2693       gold_unreachable();
   2694     }
   2695 }
   2696 
   2697 // See if this is the alternate output section for a constrained
   2698 // output section.  If it is, transfer the Output_section and return
   2699 // true.  Otherwise return false.
   2700 
   2701 bool
   2702 Output_section_definition::alternate_constraint(
   2703     Output_section_definition* posd,
   2704     Section_constraint constraint)
   2705 {
   2706   if (this->name_ != posd->name_)
   2707     return false;
   2708 
   2709   switch (constraint)
   2710     {
   2711     case CONSTRAINT_ONLY_IF_RO:
   2712       if (this->constraint_ != CONSTRAINT_ONLY_IF_RW)
   2713 	return false;
   2714       break;
   2715 
   2716     case CONSTRAINT_ONLY_IF_RW:
   2717       if (this->constraint_ != CONSTRAINT_ONLY_IF_RO)
   2718 	return false;
   2719       break;
   2720 
   2721     default:
   2722       gold_unreachable();
   2723     }
   2724 
   2725   // We have found the alternate constraint.  We just need to move
   2726   // over the Output_section.  When constraints are used properly,
   2727   // THIS should not have an output_section pointer, as all the input
   2728   // sections should have matched the other definition.
   2729 
   2730   if (this->output_section_ != NULL)
   2731     gold_error(_("mismatched definition for constrained sections"));
   2732 
   2733   this->output_section_ = posd->output_section_;
   2734   posd->output_section_ = NULL;
   2735 
   2736   if (this->is_relro_)
   2737     this->output_section_->set_is_relro();
   2738   else
   2739     this->output_section_->clear_is_relro();
   2740 
   2741   return true;
   2742 }
   2743 
   2744 // Get the list of segments to use for an allocated section when using
   2745 // a PHDRS clause.
   2746 
   2747 Output_section*
   2748 Output_section_definition::allocate_to_segment(String_list** phdrs_list,
   2749 					       bool* orphan)
   2750 {
   2751   // Update phdrs_list even if we don't have an output section. It
   2752   // might be used by the following sections.
   2753   if (this->phdrs_ != NULL)
   2754     *phdrs_list = this->phdrs_;
   2755 
   2756   if (this->output_section_ == NULL)
   2757     return NULL;
   2758   if ((this->output_section_->flags() & elfcpp::SHF_ALLOC) == 0)
   2759     return NULL;
   2760   *orphan = false;
   2761   return this->output_section_;
   2762 }
   2763 
   2764 // Look for an output section by name and return the address, the load
   2765 // address, the alignment, and the size.  This is used when an
   2766 // expression refers to an output section which was not actually
   2767 // created.  This returns true if the section was found, false
   2768 // otherwise.
   2769 
   2770 bool
   2771 Output_section_definition::get_output_section_info(const char* name,
   2772                                                    uint64_t* address,
   2773                                                    uint64_t* load_address,
   2774                                                    uint64_t* addralign,
   2775                                                    uint64_t* size) const
   2776 {
   2777   if (this->name_ != name)
   2778     return false;
   2779 
   2780   if (this->output_section_ != NULL)
   2781     {
   2782       *address = this->output_section_->address();
   2783       if (this->output_section_->has_load_address())
   2784         *load_address = this->output_section_->load_address();
   2785       else
   2786         *load_address = *address;
   2787       *addralign = this->output_section_->addralign();
   2788       *size = this->output_section_->current_data_size();
   2789     }
   2790   else
   2791     {
   2792       *address = this->evaluated_address_;
   2793       *load_address = this->evaluated_load_address_;
   2794       *addralign = this->evaluated_addralign_;
   2795       *size = 0;
   2796     }
   2797 
   2798   return true;
   2799 }
   2800 
   2801 // Print for debugging.
   2802 
   2803 void
   2804 Output_section_definition::print(FILE* f) const
   2805 {
   2806   fprintf(f, "  %s ", this->name_.c_str());
   2807 
   2808   if (this->address_ != NULL)
   2809     {
   2810       this->address_->print(f);
   2811       fprintf(f, " ");
   2812     }
   2813 
   2814   if (this->script_section_type_ != SCRIPT_SECTION_TYPE_NONE)
   2815       fprintf(f, "(%s) ",
   2816 	      this->script_section_type_name(this->script_section_type_));
   2817 
   2818   fprintf(f, ": ");
   2819 
   2820   if (this->load_address_ != NULL)
   2821     {
   2822       fprintf(f, "AT(");
   2823       this->load_address_->print(f);
   2824       fprintf(f, ") ");
   2825     }
   2826 
   2827   if (this->align_ != NULL)
   2828     {
   2829       fprintf(f, "ALIGN(");
   2830       this->align_->print(f);
   2831       fprintf(f, ") ");
   2832     }
   2833 
   2834   if (this->subalign_ != NULL)
   2835     {
   2836       fprintf(f, "SUBALIGN(");
   2837       this->subalign_->print(f);
   2838       fprintf(f, ") ");
   2839     }
   2840 
   2841   fprintf(f, "{\n");
   2842 
   2843   for (Output_section_elements::const_iterator p = this->elements_.begin();
   2844        p != this->elements_.end();
   2845        ++p)
   2846     (*p)->print(f);
   2847 
   2848   fprintf(f, "  }");
   2849 
   2850   if (this->fill_ != NULL)
   2851     {
   2852       fprintf(f, " = ");
   2853       this->fill_->print(f);
   2854     }
   2855 
   2856   if (this->phdrs_ != NULL)
   2857     {
   2858       for (String_list::const_iterator p = this->phdrs_->begin();
   2859 	   p != this->phdrs_->end();
   2860 	   ++p)
   2861 	fprintf(f, " :%s", p->c_str());
   2862     }
   2863 
   2864   fprintf(f, "\n");
   2865 }
   2866 
   2867 Script_sections::Section_type
   2868 Output_section_definition::section_type() const
   2869 {
   2870   switch (this->script_section_type_)
   2871     {
   2872     case SCRIPT_SECTION_TYPE_NONE:
   2873       return Script_sections::ST_NONE;
   2874     case SCRIPT_SECTION_TYPE_NOLOAD:
   2875       return Script_sections::ST_NOLOAD;
   2876     case SCRIPT_SECTION_TYPE_COPY:
   2877     case SCRIPT_SECTION_TYPE_DSECT:
   2878     case SCRIPT_SECTION_TYPE_INFO:
   2879     case SCRIPT_SECTION_TYPE_OVERLAY:
   2880       // There are not really support so we treat them as ST_NONE.  The
   2881       // parse should have issued errors for them already.
   2882       return Script_sections::ST_NONE;
   2883     default:
   2884       gold_unreachable();
   2885     }
   2886 }
   2887 
   2888 // Return the name of a script section type.
   2889 
   2890 const char*
   2891 Output_section_definition::script_section_type_name(
   2892     Script_section_type script_section_type)
   2893 {
   2894   switch (script_section_type)
   2895     {
   2896     case SCRIPT_SECTION_TYPE_NONE:
   2897       return "NONE";
   2898     case SCRIPT_SECTION_TYPE_NOLOAD:
   2899       return "NOLOAD";
   2900     case SCRIPT_SECTION_TYPE_DSECT:
   2901       return "DSECT";
   2902     case SCRIPT_SECTION_TYPE_COPY:
   2903       return "COPY";
   2904     case SCRIPT_SECTION_TYPE_INFO:
   2905       return "INFO";
   2906     case SCRIPT_SECTION_TYPE_OVERLAY:
   2907       return "OVERLAY";
   2908     default:
   2909       gold_unreachable();
   2910     }
   2911 }
   2912 
   2913 void
   2914 Output_section_definition::set_memory_region(Memory_region* mr, bool set_vma)
   2915 {
   2916   gold_assert(mr != NULL);
   2917   // Add the current section to the specified region's list.
   2918   mr->add_section(this, set_vma);
   2919 }
   2920 
   2921 // An output section created to hold orphaned input sections.  These
   2922 // do not actually appear in linker scripts.  However, for convenience
   2923 // when setting the output section addresses, we put a marker to these
   2924 // sections in the appropriate place in the list of SECTIONS elements.
   2925 
   2926 class Orphan_output_section : public Sections_element
   2927 {
   2928  public:
   2929   Orphan_output_section(Output_section* os)
   2930     : os_(os)
   2931   { }
   2932 
   2933   // Return whether the orphan output section is relro.  We can just
   2934   // check the output section because we always set the flag, if
   2935   // needed, just after we create the Orphan_output_section.
   2936   bool
   2937   is_relro() const
   2938   { return this->os_->is_relro(); }
   2939 
   2940   // Initialize OSP with an output section.  This should have been
   2941   // done already.
   2942   void
   2943   orphan_section_init(Orphan_section_placement*,
   2944 		      Script_sections::Elements_iterator)
   2945   { gold_unreachable(); }
   2946 
   2947   // Set section addresses.
   2948   void
   2949   set_section_addresses(Symbol_table*, Layout*, uint64_t*, uint64_t*,
   2950 			uint64_t*);
   2951 
   2952   // Get the list of segments to use for an allocated section when
   2953   // using a PHDRS clause.
   2954   Output_section*
   2955   allocate_to_segment(String_list**, bool*);
   2956 
   2957   // Return the associated Output_section.
   2958   Output_section*
   2959   get_output_section() const
   2960   { return this->os_; }
   2961 
   2962   // Print for debugging.
   2963   void
   2964   print(FILE* f) const
   2965   {
   2966     fprintf(f, "  marker for orphaned output section %s\n",
   2967 	    this->os_->name());
   2968   }
   2969 
   2970  private:
   2971   Output_section* os_;
   2972 };
   2973 
   2974 // Set section addresses.
   2975 
   2976 void
   2977 Orphan_output_section::set_section_addresses(Symbol_table*, Layout*,
   2978 					     uint64_t* dot_value,
   2979 					     uint64_t*,
   2980                                              uint64_t* load_address)
   2981 {
   2982   typedef std::list<Output_section::Input_section> Input_section_list;
   2983 
   2984   bool have_load_address = *load_address != *dot_value;
   2985 
   2986   uint64_t address = *dot_value;
   2987   address = align_address(address, this->os_->addralign());
   2988 
   2989   // If input section sorting is requested via --section-ordering-file or
   2990   // linker plugins, then do it here.  This is important because we want
   2991   // any sorting specified in the linker scripts, which will be done after
   2992   // this, to take precedence.  The final order of input sections is then
   2993   // guaranteed to be according to the linker script specification.
   2994   if (this->os_ != NULL
   2995       && this->os_->input_section_order_specified())
   2996     this->os_->sort_attached_input_sections();
   2997 
   2998   // For a relocatable link, all orphan sections are put at
   2999   // address 0.  In general we expect all sections to be at
   3000   // address 0 for a relocatable link, but we permit the linker
   3001   // script to override that for specific output sections.
   3002   if (parameters->options().relocatable())
   3003     {
   3004       address = 0;
   3005       *load_address = 0;
   3006       have_load_address = false;
   3007     }
   3008 
   3009   if ((this->os_->flags() & elfcpp::SHF_ALLOC) != 0)
   3010     {
   3011       this->os_->set_address(address);
   3012       if (have_load_address)
   3013         this->os_->set_load_address(align_address(*load_address,
   3014                                                   this->os_->addralign()));
   3015     }
   3016 
   3017   Input_section_list input_sections;
   3018   address += this->os_->get_input_sections(address, "", &input_sections);
   3019 
   3020   for (Input_section_list::iterator p = input_sections.begin();
   3021        p != input_sections.end();
   3022        ++p)
   3023     {
   3024       uint64_t addralign = p->addralign();
   3025       if (!p->is_input_section())
   3026 	p->output_section_data()->finalize_data_size();
   3027       uint64_t size = p->data_size();
   3028       address = align_address(address, addralign);
   3029       this->os_->add_script_input_section(*p);
   3030       address += size;
   3031     }
   3032 
   3033   if (parameters->options().relocatable())
   3034     {
   3035       // For a relocatable link, reset DOT_VALUE to 0.
   3036       *dot_value = 0;
   3037       *load_address = 0;
   3038     }
   3039   else if (this->os_ == NULL
   3040 	   || (this->os_->flags() & elfcpp::SHF_TLS) == 0
   3041 	   || this->os_->type() != elfcpp::SHT_NOBITS)
   3042     {
   3043       // An SHF_TLS/SHT_NOBITS section does not take up any address space.
   3044       if (!have_load_address)
   3045 	*load_address = address;
   3046       else
   3047 	*load_address += address - *dot_value;
   3048 
   3049       *dot_value = address;
   3050     }
   3051 }
   3052 
   3053 // Get the list of segments to use for an allocated section when using
   3054 // a PHDRS clause.  If this is an allocated section, return the
   3055 // Output_section.  We don't change the list of segments.
   3056 
   3057 Output_section*
   3058 Orphan_output_section::allocate_to_segment(String_list**, bool* orphan)
   3059 {
   3060   if ((this->os_->flags() & elfcpp::SHF_ALLOC) == 0)
   3061     return NULL;
   3062   *orphan = true;
   3063   return this->os_;
   3064 }
   3065 
   3066 // Class Phdrs_element.  A program header from a PHDRS clause.
   3067 
   3068 class Phdrs_element
   3069 {
   3070  public:
   3071   Phdrs_element(const char* name, size_t namelen, unsigned int type,
   3072 		bool includes_filehdr, bool includes_phdrs,
   3073 		bool is_flags_valid, unsigned int flags,
   3074 		Expression* load_address)
   3075     : name_(name, namelen), type_(type), includes_filehdr_(includes_filehdr),
   3076       includes_phdrs_(includes_phdrs), is_flags_valid_(is_flags_valid),
   3077       flags_(flags), load_address_(load_address), load_address_value_(0),
   3078       segment_(NULL)
   3079   { }
   3080 
   3081   // Return the name of this segment.
   3082   const std::string&
   3083   name() const
   3084   { return this->name_; }
   3085 
   3086   // Return the type of the segment.
   3087   unsigned int
   3088   type() const
   3089   { return this->type_; }
   3090 
   3091   // Whether to include the file header.
   3092   bool
   3093   includes_filehdr() const
   3094   { return this->includes_filehdr_; }
   3095 
   3096   // Whether to include the program headers.
   3097   bool
   3098   includes_phdrs() const
   3099   { return this->includes_phdrs_; }
   3100 
   3101   // Return whether there is a load address.
   3102   bool
   3103   has_load_address() const
   3104   { return this->load_address_ != NULL; }
   3105 
   3106   // Evaluate the load address expression if there is one.
   3107   void
   3108   eval_load_address(Symbol_table* symtab, Layout* layout)
   3109   {
   3110     if (this->load_address_ != NULL)
   3111       this->load_address_value_ = this->load_address_->eval(symtab, layout,
   3112 							    true);
   3113   }
   3114 
   3115   // Return the load address.
   3116   uint64_t
   3117   load_address() const
   3118   {
   3119     gold_assert(this->load_address_ != NULL);
   3120     return this->load_address_value_;
   3121   }
   3122 
   3123   // Create the segment.
   3124   Output_segment*
   3125   create_segment(Layout* layout)
   3126   {
   3127     this->segment_ = layout->make_output_segment(this->type_, this->flags_);
   3128     return this->segment_;
   3129   }
   3130 
   3131   // Return the segment.
   3132   Output_segment*
   3133   segment()
   3134   { return this->segment_; }
   3135 
   3136   // Release the segment.
   3137   void
   3138   release_segment()
   3139   { this->segment_ = NULL; }
   3140 
   3141   // Set the segment flags if appropriate.
   3142   void
   3143   set_flags_if_valid()
   3144   {
   3145     if (this->is_flags_valid_)
   3146       this->segment_->set_flags(this->flags_);
   3147   }
   3148 
   3149   // Print for debugging.
   3150   void
   3151   print(FILE*) const;
   3152 
   3153  private:
   3154   // The name used in the script.
   3155   std::string name_;
   3156   // The type of the segment (PT_LOAD, etc.).
   3157   unsigned int type_;
   3158   // Whether this segment includes the file header.
   3159   bool includes_filehdr_;
   3160   // Whether this segment includes the section headers.
   3161   bool includes_phdrs_;
   3162   // Whether the flags were explicitly specified.
   3163   bool is_flags_valid_;
   3164   // The flags for this segment (PF_R, etc.) if specified.
   3165   unsigned int flags_;
   3166   // The expression for the load address for this segment.  This may
   3167   // be NULL.
   3168   Expression* load_address_;
   3169   // The actual load address from evaluating the expression.
   3170   uint64_t load_address_value_;
   3171   // The segment itself.
   3172   Output_segment* segment_;
   3173 };
   3174 
   3175 // Print for debugging.
   3176 
   3177 void
   3178 Phdrs_element::print(FILE* f) const
   3179 {
   3180   fprintf(f, "  %s 0x%x", this->name_.c_str(), this->type_);
   3181   if (this->includes_filehdr_)
   3182     fprintf(f, " FILEHDR");
   3183   if (this->includes_phdrs_)
   3184     fprintf(f, " PHDRS");
   3185   if (this->is_flags_valid_)
   3186     fprintf(f, " FLAGS(%u)", this->flags_);
   3187   if (this->load_address_ != NULL)
   3188     {
   3189       fprintf(f, " AT(");
   3190       this->load_address_->print(f);
   3191       fprintf(f, ")");
   3192     }
   3193   fprintf(f, ";\n");
   3194 }
   3195 
   3196 // Add a memory region.
   3197 
   3198 void
   3199 Script_sections::add_memory_region(const char* name, size_t namelen,
   3200 				   unsigned int attributes,
   3201 				   Expression* start, Expression* length)
   3202 {
   3203   if (this->memory_regions_ == NULL)
   3204     this->memory_regions_ = new Memory_regions();
   3205   else if (this->find_memory_region(name, namelen))
   3206     {
   3207       gold_error(_("region '%.*s' already defined"), static_cast<int>(namelen),
   3208                   name);
   3209       // FIXME: Add a GOLD extension to allow multiple regions with the same
   3210       // name.  This would amount to a single region covering disjoint blocks
   3211       // of memory, which is useful for embedded devices.
   3212     }
   3213 
   3214   // FIXME: Check the length and start values.  Currently we allow
   3215   // non-constant expressions for these values, whereas LD does not.
   3216 
   3217   // FIXME: Add a GOLD extension to allow NEGATIVE LENGTHS.  This would
   3218   // describe a region that packs from the end address going down, rather
   3219   // than the start address going up.  This would be useful for embedded
   3220   // devices.
   3221 
   3222   this->memory_regions_->push_back(new Memory_region(name, namelen, attributes,
   3223 						     start, length));
   3224 }
   3225 
   3226 // Find a memory region.
   3227 
   3228 Memory_region*
   3229 Script_sections::find_memory_region(const char* name, size_t namelen)
   3230 {
   3231   if (this->memory_regions_ == NULL)
   3232     return NULL;
   3233 
   3234   for (Memory_regions::const_iterator m = this->memory_regions_->begin();
   3235        m != this->memory_regions_->end();
   3236        ++m)
   3237     if ((*m)->name_match(name, namelen))
   3238       return *m;
   3239 
   3240   return NULL;
   3241 }
   3242 
   3243 // Find a memory region's origin.
   3244 
   3245 Expression*
   3246 Script_sections::find_memory_region_origin(const char* name, size_t namelen)
   3247 {
   3248   Memory_region* mr = find_memory_region(name, namelen);
   3249   if (mr == NULL)
   3250     return NULL;
   3251 
   3252   return mr->start_address();
   3253 }
   3254 
   3255 // Find a memory region's length.
   3256 
   3257 Expression*
   3258 Script_sections::find_memory_region_length(const char* name, size_t namelen)
   3259 {
   3260   Memory_region* mr = find_memory_region(name, namelen);
   3261   if (mr == NULL)
   3262     return NULL;
   3263 
   3264   return mr->length();
   3265 }
   3266 
   3267 // Set the memory region to use for the current section.
   3268 
   3269 void
   3270 Script_sections::set_memory_region(Memory_region* mr, bool set_vma)
   3271 {
   3272   gold_assert(!this->sections_elements_->empty());
   3273   this->sections_elements_->back()->set_memory_region(mr, set_vma);
   3274 }
   3275 
   3276 // Class Script_sections.
   3277 
   3278 Script_sections::Script_sections()
   3279   : saw_sections_clause_(false),
   3280     in_sections_clause_(false),
   3281     sections_elements_(NULL),
   3282     output_section_(NULL),
   3283     memory_regions_(NULL),
   3284     phdrs_elements_(NULL),
   3285     orphan_section_placement_(NULL),
   3286     data_segment_align_start_(),
   3287     saw_data_segment_align_(false),
   3288     saw_relro_end_(false),
   3289     saw_segment_start_expression_(false),
   3290     segments_created_(false)
   3291 {
   3292 }
   3293 
   3294 // Start a SECTIONS clause.
   3295 
   3296 void
   3297 Script_sections::start_sections()
   3298 {
   3299   gold_assert(!this->in_sections_clause_ && this->output_section_ == NULL);
   3300   this->saw_sections_clause_ = true;
   3301   this->in_sections_clause_ = true;
   3302   if (this->sections_elements_ == NULL)
   3303     this->sections_elements_ = new Sections_elements;
   3304 }
   3305 
   3306 // Finish a SECTIONS clause.
   3307 
   3308 void
   3309 Script_sections::finish_sections()
   3310 {
   3311   gold_assert(this->in_sections_clause_ && this->output_section_ == NULL);
   3312   this->in_sections_clause_ = false;
   3313 }
   3314 
   3315 // Add a symbol to be defined.
   3316 
   3317 void
   3318 Script_sections::add_symbol_assignment(const char* name, size_t length,
   3319 				       Expression* val, bool provide,
   3320 				       bool hidden)
   3321 {
   3322   if (this->output_section_ != NULL)
   3323     this->output_section_->add_symbol_assignment(name, length, val,
   3324 						 provide, hidden);
   3325   else
   3326     {
   3327       Sections_element* p = new Sections_element_assignment(name, length,
   3328 							    val, provide,
   3329 							    hidden);
   3330       this->sections_elements_->push_back(p);
   3331     }
   3332 }
   3333 
   3334 // Add an assignment to the special dot symbol.
   3335 
   3336 void
   3337 Script_sections::add_dot_assignment(Expression* val)
   3338 {
   3339   if (this->output_section_ != NULL)
   3340     this->output_section_->add_dot_assignment(val);
   3341   else
   3342     {
   3343       // The GNU linker permits assignments to . to appears outside of
   3344       // a SECTIONS clause, and treats it as appearing inside, so
   3345       // sections_elements_ may be NULL here.
   3346       if (this->sections_elements_ == NULL)
   3347 	{
   3348 	  this->sections_elements_ = new Sections_elements;
   3349 	  this->saw_sections_clause_ = true;
   3350 	}
   3351 
   3352       Sections_element* p = new Sections_element_dot_assignment(val);
   3353       this->sections_elements_->push_back(p);
   3354     }
   3355 }
   3356 
   3357 // Add an assertion.
   3358 
   3359 void
   3360 Script_sections::add_assertion(Expression* check, const char* message,
   3361 			       size_t messagelen)
   3362 {
   3363   if (this->output_section_ != NULL)
   3364     this->output_section_->add_assertion(check, message, messagelen);
   3365   else
   3366     {
   3367       Sections_element* p = new Sections_element_assertion(check, message,
   3368 							   messagelen);
   3369       this->sections_elements_->push_back(p);
   3370     }
   3371 }
   3372 
   3373 // Start processing entries for an output section.
   3374 
   3375 void
   3376 Script_sections::start_output_section(
   3377     const char* name,
   3378     size_t namelen,
   3379     const Parser_output_section_header* header)
   3380 {
   3381   Output_section_definition* posd = new Output_section_definition(name,
   3382 								  namelen,
   3383 								  header);
   3384   this->sections_elements_->push_back(posd);
   3385   gold_assert(this->output_section_ == NULL);
   3386   this->output_section_ = posd;
   3387 }
   3388 
   3389 // Stop processing entries for an output section.
   3390 
   3391 void
   3392 Script_sections::finish_output_section(
   3393     const Parser_output_section_trailer* trailer)
   3394 {
   3395   gold_assert(this->output_section_ != NULL);
   3396   this->output_section_->finish(trailer);
   3397   this->output_section_ = NULL;
   3398 }
   3399 
   3400 // Add a data item to the current output section.
   3401 
   3402 void
   3403 Script_sections::add_data(int size, bool is_signed, Expression* val)
   3404 {
   3405   gold_assert(this->output_section_ != NULL);
   3406   this->output_section_->add_data(size, is_signed, val);
   3407 }
   3408 
   3409 // Add a fill value setting to the current output section.
   3410 
   3411 void
   3412 Script_sections::add_fill(Expression* val)
   3413 {
   3414   gold_assert(this->output_section_ != NULL);
   3415   this->output_section_->add_fill(val);
   3416 }
   3417 
   3418 // Add an input section specification to the current output section.
   3419 
   3420 void
   3421 Script_sections::add_input_section(const Input_section_spec* spec, bool keep)
   3422 {
   3423   gold_assert(this->output_section_ != NULL);
   3424   this->output_section_->add_input_section(spec, keep);
   3425 }
   3426 
   3427 // This is called when we see DATA_SEGMENT_ALIGN.  It means that any
   3428 // subsequent output sections may be relro.
   3429 
   3430 void
   3431 Script_sections::data_segment_align()
   3432 {
   3433   if (this->saw_data_segment_align_)
   3434     gold_error(_("DATA_SEGMENT_ALIGN may only appear once in a linker script"));
   3435   gold_assert(!this->sections_elements_->empty());
   3436   Sections_elements::iterator p = this->sections_elements_->end();
   3437   --p;
   3438   this->data_segment_align_start_ = p;
   3439   this->saw_data_segment_align_ = true;
   3440 }
   3441 
   3442 // This is called when we see DATA_SEGMENT_RELRO_END.  It means that
   3443 // any output sections seen since DATA_SEGMENT_ALIGN are relro.
   3444 
   3445 void
   3446 Script_sections::data_segment_relro_end()
   3447 {
   3448   if (this->saw_relro_end_)
   3449     gold_error(_("DATA_SEGMENT_RELRO_END may only appear once "
   3450 		 "in a linker script"));
   3451   this->saw_relro_end_ = true;
   3452 
   3453   if (!this->saw_data_segment_align_)
   3454     gold_error(_("DATA_SEGMENT_RELRO_END must follow DATA_SEGMENT_ALIGN"));
   3455   else
   3456     {
   3457       Sections_elements::iterator p = this->data_segment_align_start_;
   3458       for (++p; p != this->sections_elements_->end(); ++p)
   3459 	(*p)->set_is_relro();
   3460     }
   3461 }
   3462 
   3463 // Create any required sections.
   3464 
   3465 void
   3466 Script_sections::create_sections(Layout* layout)
   3467 {
   3468   if (!this->saw_sections_clause_)
   3469     return;
   3470   for (Sections_elements::iterator p = this->sections_elements_->begin();
   3471        p != this->sections_elements_->end();
   3472        ++p)
   3473     (*p)->create_sections(layout);
   3474 }
   3475 
   3476 // Add any symbols we are defining to the symbol table.
   3477 
   3478 void
   3479 Script_sections::add_symbols_to_table(Symbol_table* symtab)
   3480 {
   3481   if (!this->saw_sections_clause_)
   3482     return;
   3483   for (Sections_elements::iterator p = this->sections_elements_->begin();
   3484        p != this->sections_elements_->end();
   3485        ++p)
   3486     (*p)->add_symbols_to_table(symtab);
   3487 }
   3488 
   3489 // Finalize symbols and check assertions.
   3490 
   3491 void
   3492 Script_sections::finalize_symbols(Symbol_table* symtab, const Layout* layout)
   3493 {
   3494   if (!this->saw_sections_clause_)
   3495     return;
   3496   uint64_t dot_value = 0;
   3497   for (Sections_elements::iterator p = this->sections_elements_->begin();
   3498        p != this->sections_elements_->end();
   3499        ++p)
   3500     (*p)->finalize_symbols(symtab, layout, &dot_value);
   3501 }
   3502 
   3503 // Return the name of the output section to use for an input file name
   3504 // and section name.
   3505 
   3506 const char*
   3507 Script_sections::output_section_name(
   3508     const char* file_name,
   3509     const char* section_name,
   3510     Output_section*** output_section_slot,
   3511     Script_sections::Section_type* psection_type,
   3512     bool* keep)
   3513 {
   3514   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
   3515        p != this->sections_elements_->end();
   3516        ++p)
   3517     {
   3518       const char* ret = (*p)->output_section_name(file_name, section_name,
   3519 						  output_section_slot,
   3520 						  psection_type, keep);
   3521 
   3522       if (ret != NULL)
   3523 	{
   3524 	  // The special name /DISCARD/ means that the input section
   3525 	  // should be discarded.
   3526 	  if (strcmp(ret, "/DISCARD/") == 0)
   3527 	    {
   3528 	      *output_section_slot = NULL;
   3529 	      *psection_type = Script_sections::ST_NONE;
   3530 	      return NULL;
   3531 	    }
   3532 	  return ret;
   3533 	}
   3534     }
   3535 
   3536   // If we couldn't find a mapping for the name, the output section
   3537   // gets the name of the input section.
   3538 
   3539   *output_section_slot = NULL;
   3540   *psection_type = Script_sections::ST_NONE;
   3541 
   3542   return section_name;
   3543 }
   3544 
   3545 // Place a marker for an orphan output section into the SECTIONS
   3546 // clause.
   3547 
   3548 void
   3549 Script_sections::place_orphan(Output_section* os)
   3550 {
   3551   Orphan_section_placement* osp = this->orphan_section_placement_;
   3552   if (osp == NULL)
   3553     {
   3554       // Initialize the Orphan_section_placement structure.
   3555       osp = new Orphan_section_placement();
   3556       for (Sections_elements::iterator p = this->sections_elements_->begin();
   3557 	   p != this->sections_elements_->end();
   3558 	   ++p)
   3559 	(*p)->orphan_section_init(osp, p);
   3560       gold_assert(!this->sections_elements_->empty());
   3561       Sections_elements::iterator last = this->sections_elements_->end();
   3562       --last;
   3563       osp->last_init(last);
   3564       this->orphan_section_placement_ = osp;
   3565     }
   3566 
   3567   Orphan_output_section* orphan = new Orphan_output_section(os);
   3568 
   3569   // Look for where to put ORPHAN.
   3570   Sections_elements::iterator* where;
   3571   if (osp->find_place(os, &where))
   3572     {
   3573       if ((**where)->is_relro())
   3574 	os->set_is_relro();
   3575       else
   3576 	os->clear_is_relro();
   3577 
   3578       // We want to insert ORPHAN after *WHERE, and then update *WHERE
   3579       // so that the next one goes after this one.
   3580       Sections_elements::iterator p = *where;
   3581       gold_assert(p != this->sections_elements_->end());
   3582       ++p;
   3583       *where = this->sections_elements_->insert(p, orphan);
   3584     }
   3585   else
   3586     {
   3587       os->clear_is_relro();
   3588       // We don't have a place to put this orphan section.  Put it,
   3589       // and all other sections like it, at the end, but before the
   3590       // sections which always come at the end.
   3591       Sections_elements::iterator last = osp->last_place();
   3592       *where = this->sections_elements_->insert(last, orphan);
   3593     }
   3594 }
   3595 
   3596 // Set the addresses of all the output sections.  Walk through all the
   3597 // elements, tracking the dot symbol.  Apply assignments which set
   3598 // absolute symbol values, in case they are used when setting dot.
   3599 // Fill in data statement values.  As we find output sections, set the
   3600 // address, set the address of all associated input sections, and
   3601 // update dot.  Return the segment which should hold the file header
   3602 // and segment headers, if any.
   3603 
   3604 Output_segment*
   3605 Script_sections::set_section_addresses(Symbol_table* symtab, Layout* layout)
   3606 {
   3607   gold_assert(this->saw_sections_clause_);
   3608 
   3609   // Implement ONLY_IF_RO/ONLY_IF_RW constraints.  These are a pain
   3610   // for our representation.
   3611   for (Sections_elements::iterator p = this->sections_elements_->begin();
   3612        p != this->sections_elements_->end();
   3613        ++p)
   3614     {
   3615       Output_section_definition* posd;
   3616       Section_constraint failed_constraint = (*p)->check_constraint(&posd);
   3617       if (failed_constraint != CONSTRAINT_NONE)
   3618 	{
   3619 	  Sections_elements::iterator q;
   3620 	  for (q = this->sections_elements_->begin();
   3621 	       q != this->sections_elements_->end();
   3622 	       ++q)
   3623 	    {
   3624 	      if (q != p)
   3625 		{
   3626 		  if ((*q)->alternate_constraint(posd, failed_constraint))
   3627 		    break;
   3628 		}
   3629 	    }
   3630 
   3631 	  if (q == this->sections_elements_->end())
   3632 	    gold_error(_("no matching section constraint"));
   3633 	}
   3634     }
   3635 
   3636   // Force the alignment of the first TLS section to be the maximum
   3637   // alignment of all TLS sections.
   3638   Output_section* first_tls = NULL;
   3639   uint64_t tls_align = 0;
   3640   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
   3641        p != this->sections_elements_->end();
   3642        ++p)
   3643     {
   3644       Output_section* os = (*p)->get_output_section();
   3645       if (os != NULL && (os->flags() & elfcpp::SHF_TLS) != 0)
   3646 	{
   3647 	  if (first_tls == NULL)
   3648 	    first_tls = os;
   3649 	  if (os->addralign() > tls_align)
   3650 	    tls_align = os->addralign();
   3651 	}
   3652     }
   3653   if (first_tls != NULL)
   3654     first_tls->set_addralign(tls_align);
   3655 
   3656   // For a relocatable link, we implicitly set dot to zero.
   3657   uint64_t dot_value = 0;
   3658   uint64_t dot_alignment = 0;
   3659   uint64_t load_address = 0;
   3660 
   3661   // Check to see if we want to use any of -Ttext, -Tdata and -Tbss options
   3662   // to set section addresses.  If the script has any SEGMENT_START
   3663   // expression, we do not set the section addresses.
   3664   bool use_tsection_options =
   3665     (!this->saw_segment_start_expression_
   3666      && (parameters->options().user_set_Ttext()
   3667 	 || parameters->options().user_set_Tdata()
   3668 	 || parameters->options().user_set_Tbss()));
   3669 
   3670   for (Sections_elements::iterator p = this->sections_elements_->begin();
   3671        p != this->sections_elements_->end();
   3672        ++p)
   3673     {
   3674       Output_section* os = (*p)->get_output_section();
   3675 
   3676       // Handle -Ttext, -Tdata and -Tbss options.  We do this by looking for
   3677       // the special sections by names and doing dot assignments.
   3678       if (use_tsection_options
   3679 	  && os != NULL
   3680 	  && (os->flags() & elfcpp::SHF_ALLOC) != 0)
   3681 	{
   3682 	  uint64_t new_dot_value = dot_value;
   3683 
   3684 	  if (parameters->options().user_set_Ttext()
   3685 	      && strcmp(os->name(), ".text") == 0)
   3686 	    new_dot_value = parameters->options().Ttext();
   3687 	  else if (parameters->options().user_set_Tdata()
   3688 	      && strcmp(os->name(), ".data") == 0)
   3689 	    new_dot_value = parameters->options().Tdata();
   3690 	  else if (parameters->options().user_set_Tbss()
   3691 	      && strcmp(os->name(), ".bss") == 0)
   3692 	    new_dot_value = parameters->options().Tbss();
   3693 
   3694 	  // Update dot and load address if necessary.
   3695 	  if (new_dot_value < dot_value)
   3696 	    gold_error(_("dot may not move backward"));
   3697 	  else if (new_dot_value != dot_value)
   3698 	    {
   3699 	      dot_value = new_dot_value;
   3700 	      load_address = new_dot_value;
   3701 	    }
   3702 	}
   3703 
   3704       (*p)->set_section_addresses(symtab, layout, &dot_value, &dot_alignment,
   3705 				  &load_address);
   3706     }
   3707 
   3708   if (this->phdrs_elements_ != NULL)
   3709     {
   3710       for (Phdrs_elements::iterator p = this->phdrs_elements_->begin();
   3711 	   p != this->phdrs_elements_->end();
   3712 	   ++p)
   3713 	(*p)->eval_load_address(symtab, layout);
   3714     }
   3715 
   3716   return this->create_segments(layout, dot_alignment);
   3717 }
   3718 
   3719 // Sort the sections in order to put them into segments.
   3720 
   3721 class Sort_output_sections
   3722 {
   3723  public:
   3724   Sort_output_sections(const Script_sections::Sections_elements* elements)
   3725    : elements_(elements)
   3726   { }
   3727 
   3728   bool
   3729   operator()(const Output_section* os1, const Output_section* os2) const;
   3730 
   3731  private:
   3732   int
   3733   script_compare(const Output_section* os1, const Output_section* os2) const;
   3734 
   3735  private:
   3736   const Script_sections::Sections_elements* elements_;
   3737 };
   3738 
   3739 bool
   3740 Sort_output_sections::operator()(const Output_section* os1,
   3741 				 const Output_section* os2) const
   3742 {
   3743   // Sort first by the load address.
   3744   uint64_t lma1 = (os1->has_load_address()
   3745 		   ? os1->load_address()
   3746 		   : os1->address());
   3747   uint64_t lma2 = (os2->has_load_address()
   3748 		   ? os2->load_address()
   3749 		   : os2->address());
   3750   if (lma1 != lma2)
   3751     return lma1 < lma2;
   3752 
   3753   // Then sort by the virtual address.
   3754   if (os1->address() != os2->address())
   3755     return os1->address() < os2->address();
   3756 
   3757   // If the linker script says which of these sections is first, go
   3758   // with what it says.
   3759   int i = this->script_compare(os1, os2);
   3760   if (i != 0)
   3761     return i < 0;
   3762 
   3763   // Sort PROGBITS before NOBITS.
   3764   bool nobits1 = os1->type() == elfcpp::SHT_NOBITS;
   3765   bool nobits2 = os2->type() == elfcpp::SHT_NOBITS;
   3766   if (nobits1 != nobits2)
   3767     return nobits2;
   3768 
   3769   // Sort PROGBITS TLS sections to the end, NOBITS TLS sections to the
   3770   // beginning.
   3771   bool tls1 = (os1->flags() & elfcpp::SHF_TLS) != 0;
   3772   bool tls2 = (os2->flags() & elfcpp::SHF_TLS) != 0;
   3773   if (tls1 != tls2)
   3774     return nobits1 ? tls1 : tls2;
   3775 
   3776   // Sort non-NOLOAD before NOLOAD.
   3777   if (os1->is_noload() && !os2->is_noload())
   3778     return true;
   3779   if (!os1->is_noload() && os2->is_noload())
   3780     return true;
   3781 
   3782   // The sections seem practically identical.  Sort by name to get a
   3783   // stable sort.
   3784   return os1->name() < os2->name();
   3785 }
   3786 
   3787 // Return -1 if OS1 comes before OS2 in ELEMENTS_, 1 if comes after, 0
   3788 // if either OS1 or OS2 is not mentioned.  This ensures that we keep
   3789 // empty sections in the order in which they appear in a linker
   3790 // script.
   3791 
   3792 int
   3793 Sort_output_sections::script_compare(const Output_section* os1,
   3794 				     const Output_section* os2) const
   3795 {
   3796   if (this->elements_ == NULL)
   3797     return 0;
   3798 
   3799   bool found_os1 = false;
   3800   bool found_os2 = false;
   3801   for (Script_sections::Sections_elements::const_iterator
   3802 	 p = this->elements_->begin();
   3803        p != this->elements_->end();
   3804        ++p)
   3805     {
   3806       if (os2 == (*p)->get_output_section())
   3807 	{
   3808 	  if (found_os1)
   3809 	    return -1;
   3810 	  found_os2 = true;
   3811 	}
   3812       else if (os1 == (*p)->get_output_section())
   3813 	{
   3814 	  if (found_os2)
   3815 	    return 1;
   3816 	  found_os1 = true;
   3817 	}
   3818     }
   3819 
   3820   return 0;
   3821 }
   3822 
   3823 // Return whether OS is a BSS section.  This is a SHT_NOBITS section.
   3824 // We treat a section with the SHF_TLS flag set as taking up space
   3825 // even if it is SHT_NOBITS (this is true of .tbss), as we allocate
   3826 // space for them in the file.
   3827 
   3828 bool
   3829 Script_sections::is_bss_section(const Output_section* os)
   3830 {
   3831   return (os->type() == elfcpp::SHT_NOBITS
   3832 	  && (os->flags() & elfcpp::SHF_TLS) == 0);
   3833 }
   3834 
   3835 // Return the size taken by the file header and the program headers.
   3836 
   3837 size_t
   3838 Script_sections::total_header_size(Layout* layout) const
   3839 {
   3840   size_t segment_count = layout->segment_count();
   3841   size_t file_header_size;
   3842   size_t segment_headers_size;
   3843   if (parameters->target().get_size() == 32)
   3844     {
   3845       file_header_size = elfcpp::Elf_sizes<32>::ehdr_size;
   3846       segment_headers_size = segment_count * elfcpp::Elf_sizes<32>::phdr_size;
   3847     }
   3848   else if (parameters->target().get_size() == 64)
   3849     {
   3850       file_header_size = elfcpp::Elf_sizes<64>::ehdr_size;
   3851       segment_headers_size = segment_count * elfcpp::Elf_sizes<64>::phdr_size;
   3852     }
   3853   else
   3854     gold_unreachable();
   3855 
   3856   return file_header_size + segment_headers_size;
   3857 }
   3858 
   3859 // Return the amount we have to subtract from the LMA to accommodate
   3860 // headers of the given size.  The complication is that the file
   3861 // header have to be at the start of a page, as otherwise it will not
   3862 // be at the start of the file.
   3863 
   3864 uint64_t
   3865 Script_sections::header_size_adjustment(uint64_t lma,
   3866 					size_t sizeof_headers) const
   3867 {
   3868   const uint64_t abi_pagesize = parameters->target().abi_pagesize();
   3869   uint64_t hdr_lma = lma - sizeof_headers;
   3870   hdr_lma &= ~(abi_pagesize - 1);
   3871   return lma - hdr_lma;
   3872 }
   3873 
   3874 // Create the PT_LOAD segments when using a SECTIONS clause.  Returns
   3875 // the segment which should hold the file header and segment headers,
   3876 // if any.
   3877 
   3878 Output_segment*
   3879 Script_sections::create_segments(Layout* layout, uint64_t dot_alignment)
   3880 {
   3881   gold_assert(this->saw_sections_clause_);
   3882 
   3883   if (parameters->options().relocatable())
   3884     return NULL;
   3885 
   3886   if (this->saw_phdrs_clause())
   3887     return create_segments_from_phdrs_clause(layout, dot_alignment);
   3888 
   3889   Layout::Section_list sections;
   3890   layout->get_allocated_sections(&sections);
   3891 
   3892   // Sort the sections by address.
   3893   std::stable_sort(sections.begin(), sections.end(),
   3894 		   Sort_output_sections(this->sections_elements_));
   3895 
   3896   this->create_note_and_tls_segments(layout, &sections);
   3897 
   3898   // Walk through the sections adding them to PT_LOAD segments.
   3899   const uint64_t abi_pagesize = parameters->target().abi_pagesize();
   3900   Output_segment* first_seg = NULL;
   3901   Output_segment* current_seg = NULL;
   3902   bool is_current_seg_readonly = true;
   3903   Layout::Section_list::iterator plast = sections.end();
   3904   uint64_t last_vma = 0;
   3905   uint64_t last_lma = 0;
   3906   uint64_t last_size = 0;
   3907   for (Layout::Section_list::iterator p = sections.begin();
   3908        p != sections.end();
   3909        ++p)
   3910     {
   3911       const uint64_t vma = (*p)->address();
   3912       const uint64_t lma = ((*p)->has_load_address()
   3913 			    ? (*p)->load_address()
   3914 			    : vma);
   3915       const uint64_t size = (*p)->current_data_size();
   3916 
   3917       bool need_new_segment;
   3918       if (current_seg == NULL)
   3919 	need_new_segment = true;
   3920       else if (lma - vma != last_lma - last_vma)
   3921 	{
   3922 	  // This section has a different LMA relationship than the
   3923 	  // last one; we need a new segment.
   3924 	  need_new_segment = true;
   3925 	}
   3926       else if (align_address(last_lma + last_size, abi_pagesize)
   3927 	       < align_address(lma, abi_pagesize))
   3928 	{
   3929 	  // Putting this section in the segment would require
   3930 	  // skipping a page.
   3931 	  need_new_segment = true;
   3932 	}
   3933       else if (is_bss_section(*plast) && !is_bss_section(*p))
   3934 	{
   3935 	  // A non-BSS section can not follow a BSS section in the
   3936 	  // same segment.
   3937 	  need_new_segment = true;
   3938 	}
   3939       else if (is_current_seg_readonly
   3940 	       && ((*p)->flags() & elfcpp::SHF_WRITE) != 0
   3941 	       && !parameters->options().omagic())
   3942 	{
   3943 	  // Don't put a writable section in the same segment as a
   3944 	  // non-writable section.
   3945 	  need_new_segment = true;
   3946 	}
   3947       else
   3948 	{
   3949 	  // Otherwise, reuse the existing segment.
   3950 	  need_new_segment = false;
   3951 	}
   3952 
   3953       elfcpp::Elf_Word seg_flags =
   3954 	Layout::section_flags_to_segment((*p)->flags());
   3955 
   3956       if (need_new_segment)
   3957 	{
   3958 	  current_seg = layout->make_output_segment(elfcpp::PT_LOAD,
   3959 						    seg_flags);
   3960 	  current_seg->set_addresses(vma, lma);
   3961 	  current_seg->set_minimum_p_align(dot_alignment);
   3962 	  if (first_seg == NULL)
   3963 	    first_seg = current_seg;
   3964 	  is_current_seg_readonly = true;
   3965 	}
   3966 
   3967       current_seg->add_output_section_to_load(layout, *p, seg_flags);
   3968 
   3969       if (((*p)->flags() & elfcpp::SHF_WRITE) != 0)
   3970 	is_current_seg_readonly = false;
   3971 
   3972       plast = p;
   3973       last_vma = vma;
   3974       last_lma = lma;
   3975       last_size = size;
   3976     }
   3977 
   3978   // An ELF program should work even if the program headers are not in
   3979   // a PT_LOAD segment.  However, it appears that the Linux kernel
   3980   // does not set the AT_PHDR auxiliary entry in that case.  It sets
   3981   // the load address to p_vaddr - p_offset of the first PT_LOAD
   3982   // segment.  It then sets AT_PHDR to the load address plus the
   3983   // offset to the program headers, e_phoff in the file header.  This
   3984   // fails when the program headers appear in the file before the
   3985   // first PT_LOAD segment.  Therefore, we always create a PT_LOAD
   3986   // segment to hold the file header and the program headers.  This is
   3987   // effectively what the GNU linker does, and it is slightly more
   3988   // efficient in any case.  We try to use the first PT_LOAD segment
   3989   // if we can, otherwise we make a new one.
   3990 
   3991   if (first_seg == NULL)
   3992     return NULL;
   3993 
   3994   // -n or -N mean that the program is not demand paged and there is
   3995   // no need to put the program headers in a PT_LOAD segment.
   3996   if (parameters->options().nmagic() || parameters->options().omagic())
   3997     return NULL;
   3998 
   3999   size_t sizeof_headers = this->total_header_size(layout);
   4000 
   4001   uint64_t vma = first_seg->vaddr();
   4002   uint64_t lma = first_seg->paddr();
   4003 
   4004   uint64_t subtract = this->header_size_adjustment(lma, sizeof_headers);
   4005 
   4006   if ((lma & (abi_pagesize - 1)) >= sizeof_headers)
   4007     {
   4008       first_seg->set_addresses(vma - subtract, lma - subtract);
   4009       return first_seg;
   4010     }
   4011 
   4012   // If there is no room to squeeze in the headers, then punt.  The
   4013   // resulting executable probably won't run on GNU/Linux, but we
   4014   // trust that the user knows what they are doing.
   4015   if (lma < subtract || vma < subtract)
   4016     return NULL;
   4017 
   4018   // If memory regions have been specified and the address range
   4019   // we are about to use is not contained within any region then
   4020   // issue a warning message about the segment we are going to
   4021   // create.  It will be outside of any region and so possibly
   4022   // using non-existent or protected memory.  We test LMA rather
   4023   // than VMA since we assume that the headers will never be
   4024   // relocated.
   4025   if (this->memory_regions_ != NULL
   4026       && !this->block_in_region (NULL, layout, lma - subtract, subtract))
   4027     gold_warning(_("creating a segment to contain the file and program"
   4028 		   " headers outside of any MEMORY region"));
   4029 
   4030   Output_segment* load_seg = layout->make_output_segment(elfcpp::PT_LOAD,
   4031 							 elfcpp::PF_R);
   4032   load_seg->set_addresses(vma - subtract, lma - subtract);
   4033 
   4034   return load_seg;
   4035 }
   4036 
   4037 // Create a PT_NOTE segment for each SHT_NOTE section and a PT_TLS
   4038 // segment if there are any SHT_TLS sections.
   4039 
   4040 void
   4041 Script_sections::create_note_and_tls_segments(
   4042     Layout* layout,
   4043     const Layout::Section_list* sections)
   4044 {
   4045   gold_assert(!this->saw_phdrs_clause());
   4046 
   4047   bool saw_tls = false;
   4048   for (Layout::Section_list::const_iterator p = sections->begin();
   4049        p != sections->end();
   4050        ++p)
   4051     {
   4052       if ((*p)->type() == elfcpp::SHT_NOTE)
   4053 	{
   4054 	  elfcpp::Elf_Word seg_flags =
   4055 	    Layout::section_flags_to_segment((*p)->flags());
   4056 	  Output_segment* oseg = layout->make_output_segment(elfcpp::PT_NOTE,
   4057 							     seg_flags);
   4058 	  oseg->add_output_section_to_nonload(*p, seg_flags);
   4059 
   4060 	  // Incorporate any subsequent SHT_NOTE sections, in the
   4061 	  // hopes that the script is sensible.
   4062 	  Layout::Section_list::const_iterator pnext = p + 1;
   4063 	  while (pnext != sections->end()
   4064 		 && (*pnext)->type() == elfcpp::SHT_NOTE)
   4065 	    {
   4066 	      seg_flags = Layout::section_flags_to_segment((*pnext)->flags());
   4067 	      oseg->add_output_section_to_nonload(*pnext, seg_flags);
   4068 	      p = pnext;
   4069 	      ++pnext;
   4070 	    }
   4071 	}
   4072 
   4073       if (((*p)->flags() & elfcpp::SHF_TLS) != 0)
   4074 	{
   4075 	  if (saw_tls)
   4076 	    gold_error(_("TLS sections are not adjacent"));
   4077 
   4078 	  elfcpp::Elf_Word seg_flags =
   4079 	    Layout::section_flags_to_segment((*p)->flags());
   4080 	  Output_segment* oseg = layout->make_output_segment(elfcpp::PT_TLS,
   4081 							     seg_flags);
   4082 	  oseg->add_output_section_to_nonload(*p, seg_flags);
   4083 
   4084 	  Layout::Section_list::const_iterator pnext = p + 1;
   4085 	  while (pnext != sections->end()
   4086 		 && ((*pnext)->flags() & elfcpp::SHF_TLS) != 0)
   4087 	    {
   4088 	      seg_flags = Layout::section_flags_to_segment((*pnext)->flags());
   4089 	      oseg->add_output_section_to_nonload(*pnext, seg_flags);
   4090 	      p = pnext;
   4091 	      ++pnext;
   4092 	    }
   4093 
   4094 	  saw_tls = true;
   4095 	}
   4096 
   4097       // If we see a section named .interp then put the .interp section
   4098       // in a PT_INTERP segment.
   4099       // This is for GNU ld compatibility.
   4100       if (strcmp((*p)->name(), ".interp") == 0)
   4101 	{
   4102 	  elfcpp::Elf_Word seg_flags =
   4103 	    Layout::section_flags_to_segment((*p)->flags());
   4104 	  Output_segment* oseg = layout->make_output_segment(elfcpp::PT_INTERP,
   4105 							     seg_flags);
   4106 	  oseg->add_output_section_to_nonload(*p, seg_flags);
   4107 	}
   4108     }
   4109 
   4110     this->segments_created_ = true;
   4111 }
   4112 
   4113 // Add a program header.  The PHDRS clause is syntactically distinct
   4114 // from the SECTIONS clause, but we implement it with the SECTIONS
   4115 // support because PHDRS is useless if there is no SECTIONS clause.
   4116 
   4117 void
   4118 Script_sections::add_phdr(const char* name, size_t namelen, unsigned int type,
   4119 			  bool includes_filehdr, bool includes_phdrs,
   4120 			  bool is_flags_valid, unsigned int flags,
   4121 			  Expression* load_address)
   4122 {
   4123   if (this->phdrs_elements_ == NULL)
   4124     this->phdrs_elements_ = new Phdrs_elements();
   4125   this->phdrs_elements_->push_back(new Phdrs_element(name, namelen, type,
   4126 						     includes_filehdr,
   4127 						     includes_phdrs,
   4128 						     is_flags_valid, flags,
   4129 						     load_address));
   4130 }
   4131 
   4132 // Return the number of segments we expect to create based on the
   4133 // SECTIONS clause.  This is used to implement SIZEOF_HEADERS.
   4134 
   4135 size_t
   4136 Script_sections::expected_segment_count(const Layout* layout) const
   4137 {
   4138   // If we've already created the segments, we won't be adding any more.
   4139   if (this->segments_created_)
   4140     return 0;
   4141 
   4142   if (this->saw_phdrs_clause())
   4143     return this->phdrs_elements_->size();
   4144 
   4145   Layout::Section_list sections;
   4146   layout->get_allocated_sections(&sections);
   4147 
   4148   // We assume that we will need two PT_LOAD segments.
   4149   size_t ret = 2;
   4150 
   4151   bool saw_note = false;
   4152   bool saw_tls = false;
   4153   bool saw_interp = false;
   4154   for (Layout::Section_list::const_iterator p = sections.begin();
   4155        p != sections.end();
   4156        ++p)
   4157     {
   4158       if ((*p)->type() == elfcpp::SHT_NOTE)
   4159 	{
   4160 	  // Assume that all note sections will fit into a single
   4161 	  // PT_NOTE segment.
   4162 	  if (!saw_note)
   4163 	    {
   4164 	      ++ret;
   4165 	      saw_note = true;
   4166 	    }
   4167 	}
   4168       else if (((*p)->flags() & elfcpp::SHF_TLS) != 0)
   4169 	{
   4170 	  // There can only be one PT_TLS segment.
   4171 	  if (!saw_tls)
   4172 	    {
   4173 	      ++ret;
   4174 	      saw_tls = true;
   4175 	    }
   4176 	}
   4177       else if (strcmp((*p)->name(), ".interp") == 0)
   4178 	{
   4179 	  // There can only be one PT_INTERP segment.
   4180 	  if (!saw_interp)
   4181 	    {
   4182 	      ++ret;
   4183 	      saw_interp = true;
   4184 	    }
   4185 	}
   4186     }
   4187 
   4188   return ret;
   4189 }
   4190 
   4191 // Create the segments from a PHDRS clause.  Return the segment which
   4192 // should hold the file header and program headers, if any.
   4193 
   4194 Output_segment*
   4195 Script_sections::create_segments_from_phdrs_clause(Layout* layout,
   4196 						   uint64_t dot_alignment)
   4197 {
   4198   this->attach_sections_using_phdrs_clause(layout);
   4199   return this->set_phdrs_clause_addresses(layout, dot_alignment);
   4200 }
   4201 
   4202 // Create the segments from the PHDRS clause, and put the output
   4203 // sections in them.
   4204 
   4205 void
   4206 Script_sections::attach_sections_using_phdrs_clause(Layout* layout)
   4207 {
   4208   typedef std::map<std::string, Output_segment*> Name_to_segment;
   4209   Name_to_segment name_to_segment;
   4210   for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
   4211        p != this->phdrs_elements_->end();
   4212        ++p)
   4213     name_to_segment[(*p)->name()] = (*p)->create_segment(layout);
   4214   this->segments_created_ = true;
   4215 
   4216   // Walk through the output sections and attach them to segments.
   4217   // Output sections in the script which do not list segments are
   4218   // attached to the same set of segments as the immediately preceding
   4219   // output section.
   4220 
   4221   String_list* phdr_names = NULL;
   4222   bool load_segments_only = false;
   4223   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
   4224        p != this->sections_elements_->end();
   4225        ++p)
   4226     {
   4227       bool is_orphan;
   4228       String_list* old_phdr_names = phdr_names;
   4229       Output_section* os = (*p)->allocate_to_segment(&phdr_names, &is_orphan);
   4230       if (os == NULL)
   4231 	continue;
   4232 
   4233       elfcpp::Elf_Word seg_flags =
   4234 	Layout::section_flags_to_segment(os->flags());
   4235 
   4236       if (phdr_names == NULL)
   4237 	{
   4238 	  // Don't worry about empty orphan sections.
   4239 	  if (is_orphan && os->current_data_size() > 0)
   4240 	    gold_error(_("allocated section %s not in any segment"),
   4241 		       os->name());
   4242 
   4243 	  // To avoid later crashes drop this section into the first
   4244 	  // PT_LOAD segment.
   4245 	  for (Phdrs_elements::const_iterator ppe =
   4246 		 this->phdrs_elements_->begin();
   4247 	       ppe != this->phdrs_elements_->end();
   4248 	       ++ppe)
   4249 	    {
   4250 	      Output_segment* oseg = (*ppe)->segment();
   4251 	      if (oseg->type() == elfcpp::PT_LOAD)
   4252 		{
   4253 		  oseg->add_output_section_to_load(layout, os, seg_flags);
   4254 		  break;
   4255 		}
   4256 	    }
   4257 
   4258 	  continue;
   4259 	}
   4260 
   4261       // We see a list of segments names.  Disable PT_LOAD segment only
   4262       // filtering.
   4263       if (old_phdr_names != phdr_names)
   4264 	load_segments_only = false;
   4265 
   4266       // If this is an orphan section--one that was not explicitly
   4267       // mentioned in the linker script--then it should not inherit
   4268       // any segment type other than PT_LOAD.  Otherwise, e.g., the
   4269       // PT_INTERP segment will pick up following orphan sections,
   4270       // which does not make sense.  If this is not an orphan section,
   4271       // we trust the linker script.
   4272       if (is_orphan)
   4273 	{
   4274 	  // Enable PT_LOAD segments only filtering until we see another
   4275 	  // list of segment names.
   4276 	  load_segments_only = true;
   4277 	}
   4278 
   4279       bool in_load_segment = false;
   4280       for (String_list::const_iterator q = phdr_names->begin();
   4281 	   q != phdr_names->end();
   4282 	   ++q)
   4283 	{
   4284 	  Name_to_segment::const_iterator r = name_to_segment.find(*q);
   4285 	  if (r == name_to_segment.end())
   4286 	    gold_error(_("no segment %s"), q->c_str());
   4287 	  else
   4288 	    {
   4289 	      if (load_segments_only
   4290 		  && r->second->type() != elfcpp::PT_LOAD)
   4291 		continue;
   4292 
   4293 	      if (r->second->type() != elfcpp::PT_LOAD)
   4294 		r->second->add_output_section_to_nonload(os, seg_flags);
   4295 	      else
   4296 		{
   4297 		  r->second->add_output_section_to_load(layout, os, seg_flags);
   4298 		  if (in_load_segment)
   4299 		    gold_error(_("section in two PT_LOAD segments"));
   4300 		  in_load_segment = true;
   4301 		}
   4302 	    }
   4303 	}
   4304 
   4305       if (!in_load_segment)
   4306 	gold_error(_("allocated section not in any PT_LOAD segment"));
   4307     }
   4308 }
   4309 
   4310 // Set the addresses for segments created from a PHDRS clause.  Return
   4311 // the segment which should hold the file header and program headers,
   4312 // if any.
   4313 
   4314 Output_segment*
   4315 Script_sections::set_phdrs_clause_addresses(Layout* layout,
   4316 					    uint64_t dot_alignment)
   4317 {
   4318   Output_segment* load_seg = NULL;
   4319   for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
   4320        p != this->phdrs_elements_->end();
   4321        ++p)
   4322     {
   4323       // Note that we have to set the flags after adding the output
   4324       // sections to the segment, as adding an output segment can
   4325       // change the flags.
   4326       (*p)->set_flags_if_valid();
   4327 
   4328       Output_segment* oseg = (*p)->segment();
   4329 
   4330       if (oseg->type() != elfcpp::PT_LOAD)
   4331 	{
   4332 	  // The addresses of non-PT_LOAD segments are set from the
   4333 	  // PT_LOAD segments.
   4334 	  if ((*p)->has_load_address())
   4335 	    gold_error(_("may only specify load address for PT_LOAD segment"));
   4336 	  continue;
   4337 	}
   4338 
   4339       oseg->set_minimum_p_align(dot_alignment);
   4340 
   4341       // The output sections should have addresses from the SECTIONS
   4342       // clause.  The addresses don't have to be in order, so find the
   4343       // one with the lowest load address.  Use that to set the
   4344       // address of the segment.
   4345 
   4346       Output_section* osec = oseg->section_with_lowest_load_address();
   4347       if (osec == NULL)
   4348 	{
   4349 	  oseg->set_addresses(0, 0);
   4350 	  continue;
   4351 	}
   4352 
   4353       uint64_t vma = osec->address();
   4354       uint64_t lma = osec->has_load_address() ? osec->load_address() : vma;
   4355 
   4356       // Override the load address of the section with the load
   4357       // address specified for the segment.
   4358       if ((*p)->has_load_address())
   4359 	{
   4360 	  if (osec->has_load_address())
   4361 	    gold_warning(_("PHDRS load address overrides "
   4362 			   "section %s load address"),
   4363 			 osec->name());
   4364 
   4365 	  lma = (*p)->load_address();
   4366 	}
   4367 
   4368       bool headers = (*p)->includes_filehdr() && (*p)->includes_phdrs();
   4369       if (!headers && ((*p)->includes_filehdr() || (*p)->includes_phdrs()))
   4370 	{
   4371 	  // We could support this if we wanted to.
   4372 	  gold_error(_("using only one of FILEHDR and PHDRS is "
   4373 		       "not currently supported"));
   4374 	}
   4375       if (headers)
   4376 	{
   4377 	  size_t sizeof_headers = this->total_header_size(layout);
   4378 	  uint64_t subtract = this->header_size_adjustment(lma,
   4379 							   sizeof_headers);
   4380 	  if (lma >= subtract && vma >= subtract)
   4381 	    {
   4382 	      lma -= subtract;
   4383 	      vma -= subtract;
   4384 	    }
   4385 	  else
   4386 	    {
   4387 	      gold_error(_("sections loaded on first page without room "
   4388 			   "for file and program headers "
   4389 			   "are not supported"));
   4390 	    }
   4391 
   4392 	  if (load_seg != NULL)
   4393 	    gold_error(_("using FILEHDR and PHDRS on more than one "
   4394 			 "PT_LOAD segment is not currently supported"));
   4395 	  load_seg = oseg;
   4396 	}
   4397 
   4398       oseg->set_addresses(vma, lma);
   4399     }
   4400 
   4401   return load_seg;
   4402 }
   4403 
   4404 // Add the file header and segment headers to non-load segments
   4405 // specified in the PHDRS clause.
   4406 
   4407 void
   4408 Script_sections::put_headers_in_phdrs(Output_data* file_header,
   4409 				      Output_data* segment_headers)
   4410 {
   4411   gold_assert(this->saw_phdrs_clause());
   4412   for (Phdrs_elements::iterator p = this->phdrs_elements_->begin();
   4413        p != this->phdrs_elements_->end();
   4414        ++p)
   4415     {
   4416       if ((*p)->type() != elfcpp::PT_LOAD)
   4417 	{
   4418 	  if ((*p)->includes_phdrs())
   4419 	    (*p)->segment()->add_initial_output_data(segment_headers);
   4420 	  if ((*p)->includes_filehdr())
   4421 	    (*p)->segment()->add_initial_output_data(file_header);
   4422 	}
   4423     }
   4424 }
   4425 
   4426 // Look for an output section by name and return the address, the load
   4427 // address, the alignment, and the size.  This is used when an
   4428 // expression refers to an output section which was not actually
   4429 // created.  This returns true if the section was found, false
   4430 // otherwise.
   4431 
   4432 bool
   4433 Script_sections::get_output_section_info(const char* name, uint64_t* address,
   4434                                          uint64_t* load_address,
   4435                                          uint64_t* addralign,
   4436                                          uint64_t* size) const
   4437 {
   4438   if (!this->saw_sections_clause_)
   4439     return false;
   4440   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
   4441        p != this->sections_elements_->end();
   4442        ++p)
   4443     if ((*p)->get_output_section_info(name, address, load_address, addralign,
   4444                                       size))
   4445       return true;
   4446   return false;
   4447 }
   4448 
   4449 // Release all Output_segments.  This remove all pointers to all
   4450 // Output_segments.
   4451 
   4452 void
   4453 Script_sections::release_segments()
   4454 {
   4455   if (this->saw_phdrs_clause())
   4456     {
   4457       for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
   4458 	   p != this->phdrs_elements_->end();
   4459 	   ++p)
   4460 	(*p)->release_segment();
   4461     }
   4462   this->segments_created_ = false;
   4463 }
   4464 
   4465 // Print the SECTIONS clause to F for debugging.
   4466 
   4467 void
   4468 Script_sections::print(FILE* f) const
   4469 {
   4470   if (this->phdrs_elements_ != NULL)
   4471     {
   4472       fprintf(f, "PHDRS {\n");
   4473       for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
   4474 	   p != this->phdrs_elements_->end();
   4475 	   ++p)
   4476 	(*p)->print(f);
   4477       fprintf(f, "}\n");
   4478     }
   4479 
   4480   if (this->memory_regions_ != NULL)
   4481     {
   4482       fprintf(f, "MEMORY {\n");
   4483       for (Memory_regions::const_iterator m = this->memory_regions_->begin();
   4484 	   m != this->memory_regions_->end();
   4485 	   ++m)
   4486 	(*m)->print(f);
   4487       fprintf(f, "}\n");
   4488     }
   4489 
   4490   if (!this->saw_sections_clause_)
   4491     return;
   4492 
   4493   fprintf(f, "SECTIONS {\n");
   4494 
   4495   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
   4496        p != this->sections_elements_->end();
   4497        ++p)
   4498     (*p)->print(f);
   4499 
   4500   fprintf(f, "}\n");
   4501 }
   4502 
   4503 } // End namespace gold.
   4504