990a1a2c7712357da122691f1a6a60d53588a195
[external/binutils.git] / gold / script-sections.cc
1 // script-sections.cc -- linker script SECTIONS for gold
2
3 // Copyright 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cstring>
26 #include <algorithm>
27 #include <list>
28 #include <map>
29 #include <string>
30 #include <vector>
31 #include <fnmatch.h>
32
33 #include "parameters.h"
34 #include "object.h"
35 #include "layout.h"
36 #include "output.h"
37 #include "script-c.h"
38 #include "script.h"
39 #include "script-sections.h"
40
41 // Support for the SECTIONS clause in linker scripts.
42
43 namespace gold
44 {
45
46 // An element in a SECTIONS clause.
47
48 class Sections_element
49 {
50  public:
51   Sections_element()
52   { }
53
54   virtual ~Sections_element()
55   { }
56
57   // Record that an output section is relro.
58   virtual void
59   set_is_relro()
60   { }
61
62   // Create any required output sections.  The only real
63   // implementation is in Output_section_definition.
64   virtual void
65   create_sections(Layout*)
66   { }
67
68   // Add any symbol being defined to the symbol table.
69   virtual void
70   add_symbols_to_table(Symbol_table*)
71   { }
72
73   // Finalize symbols and check assertions.
74   virtual void
75   finalize_symbols(Symbol_table*, const Layout*, uint64_t*)
76   { }
77
78   // Return the output section name to use for an input file name and
79   // section name.  This only real implementation is in
80   // Output_section_definition.
81   virtual const char*
82   output_section_name(const char*, const char*, Output_section***)
83   { return NULL; }
84
85   // Return whether to place an orphan output section after this
86   // element.
87   virtual bool
88   place_orphan_here(const Output_section *, bool*, bool*) const
89   { return false; }
90
91   // Set section addresses.  This includes applying assignments if the
92   // the expression is an absolute value.
93   virtual void
94   set_section_addresses(Symbol_table*, Layout*, uint64_t*, uint64_t*)
95   { }
96
97   // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
98   // this section is constrained, and the input sections do not match,
99   // return the constraint, and set *POSD.
100   virtual Section_constraint
101   check_constraint(Output_section_definition**)
102   { return CONSTRAINT_NONE; }
103
104   // See if this is the alternate output section for a constrained
105   // output section.  If it is, transfer the Output_section and return
106   // true.  Otherwise return false.
107   virtual bool
108   alternate_constraint(Output_section_definition*, Section_constraint)
109   { return false; }
110
111   // Get the list of segments to use for an allocated section when
112   // using a PHDRS clause.  If this is an allocated section, return
113   // the Output_section, and set *PHDRS_LIST (the first parameter) to
114   // the list of PHDRS to which it should be attached.  If the PHDRS
115   // were not specified, don't change *PHDRS_LIST.  When not returning
116   // NULL, set *ORPHAN (the second parameter) according to whether
117   // this is an orphan section--one that is not mentioned in the
118   // linker script.
119   virtual Output_section*
120   allocate_to_segment(String_list**, bool*)
121   { return NULL; }
122
123   // Look for an output section by name and return the address, the
124   // load address, the alignment, and the size.  This is used when an
125   // expression refers to an output section which was not actually
126   // created.  This returns true if the section was found, false
127   // otherwise.  The only real definition is for
128   // Output_section_definition.
129   virtual bool
130   get_output_section_info(const char*, uint64_t*, uint64_t*, uint64_t*,
131                           uint64_t*) const
132   { return false; }
133
134   // Return the associated Output_section if there is one.
135   virtual Output_section*
136   get_output_section() const
137   { return NULL; }
138
139   // Print the element for debugging purposes.
140   virtual void
141   print(FILE* f) const = 0;
142 };
143
144 // An assignment in a SECTIONS clause outside of an output section.
145
146 class Sections_element_assignment : public Sections_element
147 {
148  public:
149   Sections_element_assignment(const char* name, size_t namelen,
150                               Expression* val, bool provide, bool hidden)
151     : assignment_(name, namelen, val, provide, hidden)
152   { }
153
154   // Add the symbol to the symbol table.
155   void
156   add_symbols_to_table(Symbol_table* symtab)
157   { this->assignment_.add_to_table(symtab); }
158
159   // Finalize the symbol.
160   void
161   finalize_symbols(Symbol_table* symtab, const Layout* layout,
162                    uint64_t* dot_value)
163   {
164     this->assignment_.finalize_with_dot(symtab, layout, *dot_value, NULL);
165   }
166
167   // Set the section address.  There is no section here, but if the
168   // value is absolute, we set the symbol.  This permits us to use
169   // absolute symbols when setting dot.
170   void
171   set_section_addresses(Symbol_table* symtab, Layout* layout,
172                         uint64_t* dot_value, uint64_t*)
173   {
174     this->assignment_.set_if_absolute(symtab, layout, true, *dot_value);
175   }
176
177   // Print for debugging.
178   void
179   print(FILE* f) const
180   {
181     fprintf(f, "  ");
182     this->assignment_.print(f);
183   }
184
185  private:
186   Symbol_assignment assignment_;
187 };
188
189 // An assignment to the dot symbol in a SECTIONS clause outside of an
190 // output section.
191
192 class Sections_element_dot_assignment : public Sections_element
193 {
194  public:
195   Sections_element_dot_assignment(Expression* val)
196     : val_(val)
197   { }
198
199   // Finalize the symbol.
200   void
201   finalize_symbols(Symbol_table* symtab, const Layout* layout,
202                    uint64_t* dot_value)
203   {
204     // We ignore the section of the result because outside of an
205     // output section definition the dot symbol is always considered
206     // to be absolute.
207     Output_section* dummy;
208     *dot_value = this->val_->eval_with_dot(symtab, layout, true, *dot_value,
209                                            NULL, &dummy);
210   }
211
212   // Update the dot symbol while setting section addresses.
213   void
214   set_section_addresses(Symbol_table* symtab, Layout* layout,
215                         uint64_t* dot_value, uint64_t* load_address)
216   {
217     Output_section* dummy;
218     *dot_value = this->val_->eval_with_dot(symtab, layout, false, *dot_value,
219                                            NULL, &dummy);
220     *load_address = *dot_value;
221   }
222
223   // Print for debugging.
224   void
225   print(FILE* f) const
226   {
227     fprintf(f, "  . = ");
228     this->val_->print(f);
229     fprintf(f, "\n");
230   }
231
232  private:
233   Expression* val_;
234 };
235
236 // An assertion in a SECTIONS clause outside of an output section.
237
238 class Sections_element_assertion : public Sections_element
239 {
240  public:
241   Sections_element_assertion(Expression* check, const char* message,
242                              size_t messagelen)
243     : assertion_(check, message, messagelen)
244   { }
245
246   // Check the assertion.
247   void
248   finalize_symbols(Symbol_table* symtab, const Layout* layout, uint64_t*)
249   { this->assertion_.check(symtab, layout); }
250
251   // Print for debugging.
252   void
253   print(FILE* f) const
254   {
255     fprintf(f, "  ");
256     this->assertion_.print(f);
257   }
258
259  private:
260   Script_assertion assertion_;
261 };
262
263 // An element in an output section in a SECTIONS clause.
264
265 class Output_section_element
266 {
267  public:
268   // A list of input sections.
269   typedef std::list<std::pair<Relobj*, unsigned int> > Input_section_list;
270
271   Output_section_element()
272   { }
273
274   virtual ~Output_section_element()
275   { }
276
277   // Return whether this element requires an output section to exist.
278   virtual bool
279   needs_output_section() const
280   { return false; }
281
282   // Add any symbol being defined to the symbol table.
283   virtual void
284   add_symbols_to_table(Symbol_table*)
285   { }
286
287   // Finalize symbols and check assertions.
288   virtual void
289   finalize_symbols(Symbol_table*, const Layout*, uint64_t*, Output_section**)
290   { }
291
292   // Return whether this element matches FILE_NAME and SECTION_NAME.
293   // The only real implementation is in Output_section_element_input.
294   virtual bool
295   match_name(const char*, const char*) const
296   { return false; }
297
298   // Set section addresses.  This includes applying assignments if the
299   // the expression is an absolute value.
300   virtual void
301   set_section_addresses(Symbol_table*, Layout*, Output_section*, uint64_t,
302                         uint64_t*, Output_section**, std::string*,
303                         Input_section_list*)
304   { }
305
306   // Print the element for debugging purposes.
307   virtual void
308   print(FILE* f) const = 0;
309
310  protected:
311   // Return a fill string that is LENGTH bytes long, filling it with
312   // FILL.
313   std::string
314   get_fill_string(const std::string* fill, section_size_type length) const;
315 };
316
317 std::string
318 Output_section_element::get_fill_string(const std::string* fill,
319                                         section_size_type length) const
320 {
321   std::string this_fill;
322   this_fill.reserve(length);
323   while (this_fill.length() + fill->length() <= length)
324     this_fill += *fill;
325   if (this_fill.length() < length)
326     this_fill.append(*fill, 0, length - this_fill.length());
327   return this_fill;
328 }
329
330 // A symbol assignment in an output section.
331
332 class Output_section_element_assignment : public Output_section_element
333 {
334  public:
335   Output_section_element_assignment(const char* name, size_t namelen,
336                                     Expression* val, bool provide,
337                                     bool hidden)
338     : assignment_(name, namelen, val, provide, hidden)
339   { }
340
341   // Add the symbol to the symbol table.
342   void
343   add_symbols_to_table(Symbol_table* symtab)
344   { this->assignment_.add_to_table(symtab); }
345
346   // Finalize the symbol.
347   void
348   finalize_symbols(Symbol_table* symtab, const Layout* layout,
349                    uint64_t* dot_value, Output_section** dot_section)
350   {
351     this->assignment_.finalize_with_dot(symtab, layout, *dot_value,
352                                         *dot_section);
353   }
354
355   // Set the section address.  There is no section here, but if the
356   // value is absolute, we set the symbol.  This permits us to use
357   // absolute symbols when setting dot.
358   void
359   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
360                         uint64_t, uint64_t* dot_value, Output_section**,
361                         std::string*, Input_section_list*)
362   {
363     this->assignment_.set_if_absolute(symtab, layout, true, *dot_value);
364   }
365
366   // Print for debugging.
367   void
368   print(FILE* f) const
369   {
370     fprintf(f, "    ");
371     this->assignment_.print(f);
372   }
373
374  private:
375   Symbol_assignment assignment_;
376 };
377
378 // An assignment to the dot symbol in an output section.
379
380 class Output_section_element_dot_assignment : public Output_section_element
381 {
382  public:
383   Output_section_element_dot_assignment(Expression* val)
384     : val_(val)
385   { }
386
387   // Finalize the symbol.
388   void
389   finalize_symbols(Symbol_table* symtab, const Layout* layout,
390                    uint64_t* dot_value, Output_section** dot_section)
391   {
392     *dot_value = this->val_->eval_with_dot(symtab, layout, true, *dot_value,
393                                            *dot_section, dot_section);
394   }
395
396   // Update the dot symbol while setting section addresses.
397   void
398   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
399                         uint64_t, uint64_t* dot_value, Output_section**,
400                         std::string*, Input_section_list*);
401
402   // Print for debugging.
403   void
404   print(FILE* f) const
405   {
406     fprintf(f, "    . = ");
407     this->val_->print(f);
408     fprintf(f, "\n");
409   }
410
411  private:
412   Expression* val_;
413 };
414
415 // Update the dot symbol while setting section addresses.
416
417 void
418 Output_section_element_dot_assignment::set_section_addresses(
419     Symbol_table* symtab,
420     Layout* layout,
421     Output_section* output_section,
422     uint64_t,
423     uint64_t* dot_value,
424     Output_section** dot_section,
425     std::string* fill,
426     Input_section_list*)
427 {
428   uint64_t next_dot = this->val_->eval_with_dot(symtab, layout, false,
429                                                 *dot_value, *dot_section,
430                                                 dot_section);
431   if (next_dot < *dot_value)
432     gold_error(_("dot may not move backward"));
433   if (next_dot > *dot_value && output_section != NULL)
434     {
435       section_size_type length = convert_to_section_size_type(next_dot
436                                                               - *dot_value);
437       Output_section_data* posd;
438       if (fill->empty())
439         posd = new Output_data_zero_fill(length, 0);
440       else
441         {
442           std::string this_fill = this->get_fill_string(fill, length);
443           posd = new Output_data_const(this_fill, 0);
444         }
445       output_section->add_output_section_data(posd);
446     }
447   *dot_value = next_dot;
448 }
449
450 // An assertion in an output section.
451
452 class Output_section_element_assertion : public Output_section_element
453 {
454  public:
455   Output_section_element_assertion(Expression* check, const char* message,
456                                    size_t messagelen)
457     : assertion_(check, message, messagelen)
458   { }
459
460   void
461   print(FILE* f) const
462   {
463     fprintf(f, "    ");
464     this->assertion_.print(f);
465   }
466
467  private:
468   Script_assertion assertion_;
469 };
470
471 // We use a special instance of Output_section_data to handle BYTE,
472 // SHORT, etc.  This permits forward references to symbols in the
473 // expressions.
474
475 class Output_data_expression : public Output_section_data
476 {
477  public:
478   Output_data_expression(int size, bool is_signed, Expression* val,
479                          const Symbol_table* symtab, const Layout* layout,
480                          uint64_t dot_value, Output_section* dot_section)
481     : Output_section_data(size, 0),
482       is_signed_(is_signed), val_(val), symtab_(symtab),
483       layout_(layout), dot_value_(dot_value), dot_section_(dot_section)
484   { }
485
486  protected:
487   // Write the data to the output file.
488   void
489   do_write(Output_file*);
490
491   // Write the data to a buffer.
492   void
493   do_write_to_buffer(unsigned char*);
494
495   // Write to a map file.
496   void
497   do_print_to_mapfile(Mapfile* mapfile) const
498   { mapfile->print_output_data(this, _("** expression")); }
499
500  private:
501   template<bool big_endian>
502   void
503   endian_write_to_buffer(uint64_t, unsigned char*);
504
505   bool is_signed_;
506   Expression* val_;
507   const Symbol_table* symtab_;
508   const Layout* layout_;
509   uint64_t dot_value_;
510   Output_section* dot_section_;
511 };
512
513 // Write the data element to the output file.
514
515 void
516 Output_data_expression::do_write(Output_file* of)
517 {
518   unsigned char* view = of->get_output_view(this->offset(), this->data_size());
519   this->write_to_buffer(view);
520   of->write_output_view(this->offset(), this->data_size(), view);
521 }
522
523 // Write the data element to a buffer.
524
525 void
526 Output_data_expression::do_write_to_buffer(unsigned char* buf)
527 {
528   Output_section* dummy;
529   uint64_t val = this->val_->eval_with_dot(this->symtab_, this->layout_,
530                                            true, this->dot_value_,
531                                            this->dot_section_, &dummy);
532
533   if (parameters->target().is_big_endian())
534     this->endian_write_to_buffer<true>(val, buf);
535   else
536     this->endian_write_to_buffer<false>(val, buf);
537 }
538
539 template<bool big_endian>
540 void
541 Output_data_expression::endian_write_to_buffer(uint64_t val,
542                                                unsigned char* buf)
543 {
544   switch (this->data_size())
545     {
546     case 1:
547       elfcpp::Swap_unaligned<8, big_endian>::writeval(buf, val);
548       break;
549     case 2:
550       elfcpp::Swap_unaligned<16, big_endian>::writeval(buf, val);
551       break;
552     case 4:
553       elfcpp::Swap_unaligned<32, big_endian>::writeval(buf, val);
554       break;
555     case 8:
556       if (parameters->target().get_size() == 32)
557         {
558           val &= 0xffffffff;
559           if (this->is_signed_ && (val & 0x80000000) != 0)
560             val |= 0xffffffff00000000LL;
561         }
562       elfcpp::Swap_unaligned<64, big_endian>::writeval(buf, val);
563       break;
564     default:
565       gold_unreachable();
566     }
567 }
568
569 // A data item in an output section.
570
571 class Output_section_element_data : public Output_section_element
572 {
573  public:
574   Output_section_element_data(int size, bool is_signed, Expression* val)
575     : size_(size), is_signed_(is_signed), val_(val)
576   { }
577
578   // If there is a data item, then we must create an output section.
579   bool
580   needs_output_section() const
581   { return true; }
582
583   // Finalize symbols--we just need to update dot.
584   void
585   finalize_symbols(Symbol_table*, const Layout*, uint64_t* dot_value,
586                    Output_section**)
587   { *dot_value += this->size_; }
588
589   // Store the value in the section.
590   void
591   set_section_addresses(Symbol_table*, Layout*, Output_section*, uint64_t,
592                         uint64_t* dot_value, Output_section**, std::string*,
593                         Input_section_list*);
594
595   // Print for debugging.
596   void
597   print(FILE*) const;
598
599  private:
600   // The size in bytes.
601   int size_;
602   // Whether the value is signed.
603   bool is_signed_;
604   // The value.
605   Expression* val_;
606 };
607
608 // Store the value in the section.
609
610 void
611 Output_section_element_data::set_section_addresses(
612     Symbol_table* symtab,
613     Layout* layout,
614     Output_section* os,
615     uint64_t,
616     uint64_t* dot_value,
617     Output_section** dot_section,
618     std::string*,
619     Input_section_list*)
620 {
621   gold_assert(os != NULL);
622   os->add_output_section_data(new Output_data_expression(this->size_,
623                                                          this->is_signed_,
624                                                          this->val_,
625                                                          symtab,
626                                                          layout,
627                                                          *dot_value,
628                                                          *dot_section));
629   *dot_value += this->size_;
630 }
631
632 // Print for debugging.
633
634 void
635 Output_section_element_data::print(FILE* f) const
636 {
637   const char* s;
638   switch (this->size_)
639     {
640     case 1:
641       s = "BYTE";
642       break;
643     case 2:
644       s = "SHORT";
645       break;
646     case 4:
647       s = "LONG";
648       break;
649     case 8:
650       if (this->is_signed_)
651         s = "SQUAD";
652       else
653         s = "QUAD";
654       break;
655     default:
656       gold_unreachable();
657     }
658   fprintf(f, "    %s(", s);
659   this->val_->print(f);
660   fprintf(f, ")\n");
661 }
662
663 // A fill value setting in an output section.
664
665 class Output_section_element_fill : public Output_section_element
666 {
667  public:
668   Output_section_element_fill(Expression* val)
669     : val_(val)
670   { }
671
672   // Update the fill value while setting section addresses.
673   void
674   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
675                         uint64_t, uint64_t* dot_value,
676                         Output_section** dot_section,
677                         std::string* fill, Input_section_list*)
678   {
679     Output_section* fill_section;
680     uint64_t fill_val = this->val_->eval_with_dot(symtab, layout, false,
681                                                   *dot_value, *dot_section,
682                                                   &fill_section);
683     if (fill_section != NULL)
684       gold_warning(_("fill value is not absolute"));
685     // FIXME: The GNU linker supports fill values of arbitrary length.
686     unsigned char fill_buff[4];
687     elfcpp::Swap_unaligned<32, true>::writeval(fill_buff, fill_val);
688     fill->assign(reinterpret_cast<char*>(fill_buff), 4);
689   }
690
691   // Print for debugging.
692   void
693   print(FILE* f) const
694   {
695     fprintf(f, "    FILL(");
696     this->val_->print(f);
697     fprintf(f, ")\n");
698   }
699
700  private:
701   // The new fill value.
702   Expression* val_;
703 };
704
705 // Return whether STRING contains a wildcard character.  This is used
706 // to speed up matching.
707
708 static inline bool
709 is_wildcard_string(const std::string& s)
710 {
711   return strpbrk(s.c_str(), "?*[") != NULL;
712 }
713
714 // An input section specification in an output section
715
716 class Output_section_element_input : public Output_section_element
717 {
718  public:
719   Output_section_element_input(const Input_section_spec* spec, bool keep);
720
721   // Finalize symbols--just update the value of the dot symbol.
722   void
723   finalize_symbols(Symbol_table*, const Layout*, uint64_t* dot_value,
724                    Output_section** dot_section)
725   {
726     *dot_value = this->final_dot_value_;
727     *dot_section = this->final_dot_section_;
728   }
729
730   // See whether we match FILE_NAME and SECTION_NAME as an input
731   // section.
732   bool
733   match_name(const char* file_name, const char* section_name) const;
734
735   // Set the section address.
736   void
737   set_section_addresses(Symbol_table* symtab, Layout* layout, Output_section*,
738                         uint64_t subalign, uint64_t* dot_value,
739                         Output_section**, std::string* fill,
740                         Input_section_list*);
741
742   // Print for debugging.
743   void
744   print(FILE* f) const;
745
746  private:
747   // An input section pattern.
748   struct Input_section_pattern
749   {
750     std::string pattern;
751     bool pattern_is_wildcard;
752     Sort_wildcard sort;
753
754     Input_section_pattern(const char* patterna, size_t patternlena,
755                           Sort_wildcard sorta)
756       : pattern(patterna, patternlena),
757         pattern_is_wildcard(is_wildcard_string(this->pattern)),
758         sort(sorta)
759     { }
760   };
761
762   typedef std::vector<Input_section_pattern> Input_section_patterns;
763
764   // Filename_exclusions is a pair of filename pattern and a bool
765   // indicating whether the filename is a wildcard.
766   typedef std::vector<std::pair<std::string, bool> > Filename_exclusions;
767
768   // Return whether STRING matches PATTERN, where IS_WILDCARD_PATTERN
769   // indicates whether this is a wildcard pattern.
770   static inline bool
771   match(const char* string, const char* pattern, bool is_wildcard_pattern)
772   {
773     return (is_wildcard_pattern
774             ? fnmatch(pattern, string, 0) == 0
775             : strcmp(string, pattern) == 0);
776   }
777
778   // See if we match a file name.
779   bool
780   match_file_name(const char* file_name) const;
781
782   // The file name pattern.  If this is the empty string, we match all
783   // files.
784   std::string filename_pattern_;
785   // Whether the file name pattern is a wildcard.
786   bool filename_is_wildcard_;
787   // How the file names should be sorted.  This may only be
788   // SORT_WILDCARD_NONE or SORT_WILDCARD_BY_NAME.
789   Sort_wildcard filename_sort_;
790   // The list of file names to exclude.
791   Filename_exclusions filename_exclusions_;
792   // The list of input section patterns.
793   Input_section_patterns input_section_patterns_;
794   // Whether to keep this section when garbage collecting.
795   bool keep_;
796   // The value of dot after including all matching sections.
797   uint64_t final_dot_value_;
798   // The section where dot is defined after including all matching
799   // sections.
800   Output_section* final_dot_section_;
801 };
802
803 // Construct Output_section_element_input.  The parser records strings
804 // as pointers into a copy of the script file, which will go away when
805 // parsing is complete.  We make sure they are in std::string objects.
806
807 Output_section_element_input::Output_section_element_input(
808     const Input_section_spec* spec,
809     bool keep)
810   : filename_pattern_(),
811     filename_is_wildcard_(false),
812     filename_sort_(spec->file.sort),
813     filename_exclusions_(),
814     input_section_patterns_(),
815     keep_(keep),
816     final_dot_value_(0),
817     final_dot_section_(NULL)
818 {
819   // The filename pattern "*" is common, and matches all files.  Turn
820   // it into the empty string.
821   if (spec->file.name.length != 1 || spec->file.name.value[0] != '*')
822     this->filename_pattern_.assign(spec->file.name.value,
823                                    spec->file.name.length);
824   this->filename_is_wildcard_ = is_wildcard_string(this->filename_pattern_);
825
826   if (spec->input_sections.exclude != NULL)
827     {
828       for (String_list::const_iterator p =
829              spec->input_sections.exclude->begin();
830            p != spec->input_sections.exclude->end();
831            ++p)
832         {
833           bool is_wildcard = is_wildcard_string(*p);
834           this->filename_exclusions_.push_back(std::make_pair(*p,
835                                                               is_wildcard));
836         }
837     }
838
839   if (spec->input_sections.sections != NULL)
840     {
841       Input_section_patterns& isp(this->input_section_patterns_);
842       for (String_sort_list::const_iterator p =
843              spec->input_sections.sections->begin();
844            p != spec->input_sections.sections->end();
845            ++p)
846         isp.push_back(Input_section_pattern(p->name.value, p->name.length,
847                                             p->sort));
848     }
849 }
850
851 // See whether we match FILE_NAME.
852
853 bool
854 Output_section_element_input::match_file_name(const char* file_name) const
855 {
856   if (!this->filename_pattern_.empty())
857     {
858       // If we were called with no filename, we refuse to match a
859       // pattern which requires a file name.
860       if (file_name == NULL)
861         return false;
862
863       if (!match(file_name, this->filename_pattern_.c_str(),
864                  this->filename_is_wildcard_))
865         return false;
866     }
867
868   if (file_name != NULL)
869     {
870       // Now we have to see whether FILE_NAME matches one of the
871       // exclusion patterns, if any.
872       for (Filename_exclusions::const_iterator p =
873              this->filename_exclusions_.begin();
874            p != this->filename_exclusions_.end();
875            ++p)
876         {
877           if (match(file_name, p->first.c_str(), p->second))
878             return false;
879         }
880     }
881
882   return true;
883 }
884
885 // See whether we match FILE_NAME and SECTION_NAME.
886
887 bool
888 Output_section_element_input::match_name(const char* file_name,
889                                          const char* section_name) const
890 {
891   if (!this->match_file_name(file_name))
892     return false;
893
894   // If there are no section name patterns, then we match.
895   if (this->input_section_patterns_.empty())
896     return true;
897
898   // See whether we match the section name patterns.
899   for (Input_section_patterns::const_iterator p =
900          this->input_section_patterns_.begin();
901        p != this->input_section_patterns_.end();
902        ++p)
903     {
904       if (match(section_name, p->pattern.c_str(), p->pattern_is_wildcard))
905         return true;
906     }
907
908   // We didn't match any section names, so we didn't match.
909   return false;
910 }
911
912 // Information we use to sort the input sections.
913
914 struct Input_section_info
915 {
916   Relobj* relobj;
917   unsigned int shndx;
918   std::string section_name;
919   uint64_t size;
920   uint64_t addralign;
921 };
922
923 // A class to sort the input sections.
924
925 class Input_section_sorter
926 {
927  public:
928   Input_section_sorter(Sort_wildcard filename_sort, Sort_wildcard section_sort)
929     : filename_sort_(filename_sort), section_sort_(section_sort)
930   { }
931
932   bool
933   operator()(const Input_section_info&, const Input_section_info&) const;
934
935  private:
936   Sort_wildcard filename_sort_;
937   Sort_wildcard section_sort_;
938 };
939
940 bool
941 Input_section_sorter::operator()(const Input_section_info& isi1,
942                                  const Input_section_info& isi2) const
943 {
944   if (this->section_sort_ == SORT_WILDCARD_BY_NAME
945       || this->section_sort_ == SORT_WILDCARD_BY_NAME_BY_ALIGNMENT
946       || (this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT_BY_NAME
947           && isi1.addralign == isi2.addralign))
948     {
949       if (isi1.section_name != isi2.section_name)
950         return isi1.section_name < isi2.section_name;
951     }
952   if (this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT
953       || this->section_sort_ == SORT_WILDCARD_BY_NAME_BY_ALIGNMENT
954       || this->section_sort_ == SORT_WILDCARD_BY_ALIGNMENT_BY_NAME)
955     {
956       if (isi1.addralign != isi2.addralign)
957         return isi1.addralign < isi2.addralign;
958     }
959   if (this->filename_sort_ == SORT_WILDCARD_BY_NAME)
960     {
961       if (isi1.relobj->name() != isi2.relobj->name())
962         return isi1.relobj->name() < isi2.relobj->name();
963     }
964
965   // Otherwise we leave them in the same order.
966   return false;
967 }
968
969 // Set the section address.  Look in INPUT_SECTIONS for sections which
970 // match this spec, sort them as specified, and add them to the output
971 // section.
972
973 void
974 Output_section_element_input::set_section_addresses(
975     Symbol_table*,
976     Layout*,
977     Output_section* output_section,
978     uint64_t subalign,
979     uint64_t* dot_value,
980     Output_section** dot_section,
981     std::string* fill,
982     Input_section_list* input_sections)
983 {
984   // We build a list of sections which match each
985   // Input_section_pattern.
986
987   typedef std::vector<std::vector<Input_section_info> > Matching_sections;
988   size_t input_pattern_count = this->input_section_patterns_.size();
989   if (input_pattern_count == 0)
990     input_pattern_count = 1;
991   Matching_sections matching_sections(input_pattern_count);
992
993   // Look through the list of sections for this output section.  Add
994   // each one which matches to one of the elements of
995   // MATCHING_SECTIONS.
996
997   Input_section_list::iterator p = input_sections->begin();
998   while (p != input_sections->end())
999     {
1000       // Calling section_name and section_addralign is not very
1001       // efficient.
1002       Input_section_info isi;
1003       isi.relobj = p->first;
1004       isi.shndx = p->second;
1005
1006       // Lock the object so that we can get information about the
1007       // section.  This is OK since we know we are single-threaded
1008       // here.
1009       {
1010         const Task* task = reinterpret_cast<const Task*>(-1);
1011         Task_lock_obj<Object> tl(task, p->first);
1012
1013         isi.section_name = p->first->section_name(p->second);
1014         isi.size = p->first->section_size(p->second);
1015         isi.addralign = p->first->section_addralign(p->second);
1016       }
1017
1018       if (!this->match_file_name(isi.relobj->name().c_str()))
1019         ++p;
1020       else if (this->input_section_patterns_.empty())
1021         {
1022           matching_sections[0].push_back(isi);
1023           p = input_sections->erase(p);
1024         }
1025       else
1026         {
1027           size_t i;
1028           for (i = 0; i < input_pattern_count; ++i)
1029             {
1030               const Input_section_pattern&
1031                 isp(this->input_section_patterns_[i]);
1032               if (match(isi.section_name.c_str(), isp.pattern.c_str(),
1033                         isp.pattern_is_wildcard))
1034                 break;
1035             }
1036
1037           if (i >= this->input_section_patterns_.size())
1038             ++p;
1039           else
1040             {
1041               matching_sections[i].push_back(isi);
1042               p = input_sections->erase(p);
1043             }
1044         }
1045     }
1046
1047   // Look through MATCHING_SECTIONS.  Sort each one as specified,
1048   // using a stable sort so that we get the default order when
1049   // sections are otherwise equal.  Add each input section to the
1050   // output section.
1051
1052   for (size_t i = 0; i < input_pattern_count; ++i)
1053     {
1054       if (matching_sections[i].empty())
1055         continue;
1056
1057       gold_assert(output_section != NULL);
1058
1059       const Input_section_pattern& isp(this->input_section_patterns_[i]);
1060       if (isp.sort != SORT_WILDCARD_NONE
1061           || this->filename_sort_ != SORT_WILDCARD_NONE)
1062         std::stable_sort(matching_sections[i].begin(),
1063                          matching_sections[i].end(),
1064                          Input_section_sorter(this->filename_sort_,
1065                                               isp.sort));
1066
1067       for (std::vector<Input_section_info>::const_iterator p =
1068              matching_sections[i].begin();
1069            p != matching_sections[i].end();
1070            ++p)
1071         {
1072           uint64_t this_subalign = p->addralign;
1073           if (this_subalign < subalign)
1074             this_subalign = subalign;
1075
1076           uint64_t address = align_address(*dot_value, this_subalign);
1077
1078           if (address > *dot_value && !fill->empty())
1079             {
1080               section_size_type length =
1081                 convert_to_section_size_type(address - *dot_value);
1082               std::string this_fill = this->get_fill_string(fill, length);
1083               Output_section_data* posd = new Output_data_const(this_fill, 0);
1084               output_section->add_output_section_data(posd);
1085             }
1086
1087           output_section->add_input_section_for_script(p->relobj,
1088                                                        p->shndx,
1089                                                        p->size,
1090                                                        this_subalign);
1091
1092           *dot_value = address + p->size;
1093         }
1094     }
1095
1096   this->final_dot_value_ = *dot_value;
1097   this->final_dot_section_ = *dot_section;
1098 }
1099
1100 // Print for debugging.
1101
1102 void
1103 Output_section_element_input::print(FILE* f) const
1104 {
1105   fprintf(f, "    ");
1106
1107   if (this->keep_)
1108     fprintf(f, "KEEP(");
1109
1110   if (!this->filename_pattern_.empty())
1111     {
1112       bool need_close_paren = false;
1113       switch (this->filename_sort_)
1114         {
1115         case SORT_WILDCARD_NONE:
1116           break;
1117         case SORT_WILDCARD_BY_NAME:
1118           fprintf(f, "SORT_BY_NAME(");
1119           need_close_paren = true;
1120           break;
1121         default:
1122           gold_unreachable();
1123         }
1124
1125       fprintf(f, "%s", this->filename_pattern_.c_str());
1126
1127       if (need_close_paren)
1128         fprintf(f, ")");
1129     }
1130
1131   if (!this->input_section_patterns_.empty()
1132       || !this->filename_exclusions_.empty())
1133     {
1134       fprintf(f, "(");
1135
1136       bool need_space = false;
1137       if (!this->filename_exclusions_.empty())
1138         {
1139           fprintf(f, "EXCLUDE_FILE(");
1140           bool need_comma = false;
1141           for (Filename_exclusions::const_iterator p =
1142                  this->filename_exclusions_.begin();
1143                p != this->filename_exclusions_.end();
1144                ++p)
1145             {
1146               if (need_comma)
1147                 fprintf(f, ", ");
1148               fprintf(f, "%s", p->first.c_str());
1149               need_comma = true;
1150             }
1151           fprintf(f, ")");
1152           need_space = true;
1153         }
1154
1155       for (Input_section_patterns::const_iterator p =
1156              this->input_section_patterns_.begin();
1157            p != this->input_section_patterns_.end();
1158            ++p)
1159         {
1160           if (need_space)
1161             fprintf(f, " ");
1162
1163           int close_parens = 0;
1164           switch (p->sort)
1165             {
1166             case SORT_WILDCARD_NONE:
1167               break;
1168             case SORT_WILDCARD_BY_NAME:
1169               fprintf(f, "SORT_BY_NAME(");
1170               close_parens = 1;
1171               break;
1172             case SORT_WILDCARD_BY_ALIGNMENT:
1173               fprintf(f, "SORT_BY_ALIGNMENT(");
1174               close_parens = 1;
1175               break;
1176             case SORT_WILDCARD_BY_NAME_BY_ALIGNMENT:
1177               fprintf(f, "SORT_BY_NAME(SORT_BY_ALIGNMENT(");
1178               close_parens = 2;
1179               break;
1180             case SORT_WILDCARD_BY_ALIGNMENT_BY_NAME:
1181               fprintf(f, "SORT_BY_ALIGNMENT(SORT_BY_NAME(");
1182               close_parens = 2;
1183               break;
1184             default:
1185               gold_unreachable();
1186             }
1187
1188           fprintf(f, "%s", p->pattern.c_str());
1189
1190           for (int i = 0; i < close_parens; ++i)
1191             fprintf(f, ")");
1192
1193           need_space = true;
1194         }
1195
1196       fprintf(f, ")");
1197     }
1198
1199   if (this->keep_)
1200     fprintf(f, ")");
1201
1202   fprintf(f, "\n");
1203 }
1204
1205 // An output section.
1206
1207 class Output_section_definition : public Sections_element
1208 {
1209  public:
1210   typedef Output_section_element::Input_section_list Input_section_list;
1211
1212   Output_section_definition(const char* name, size_t namelen,
1213                             const Parser_output_section_header* header);
1214
1215   // Finish the output section with the information in the trailer.
1216   void
1217   finish(const Parser_output_section_trailer* trailer);
1218
1219   // Add a symbol to be defined.
1220   void
1221   add_symbol_assignment(const char* name, size_t length, Expression* value,
1222                         bool provide, bool hidden);
1223
1224   // Add an assignment to the special dot symbol.
1225   void
1226   add_dot_assignment(Expression* value);
1227
1228   // Add an assertion.
1229   void
1230   add_assertion(Expression* check, const char* message, size_t messagelen);
1231
1232   // Add a data item to the current output section.
1233   void
1234   add_data(int size, bool is_signed, Expression* val);
1235
1236   // Add a setting for the fill value.
1237   void
1238   add_fill(Expression* val);
1239
1240   // Add an input section specification.
1241   void
1242   add_input_section(const Input_section_spec* spec, bool keep);
1243
1244   // Record that the output section is relro.
1245   void
1246   set_is_relro()
1247   { this->is_relro_ = true; }
1248
1249   // Create any required output sections.
1250   void
1251   create_sections(Layout*);
1252
1253   // Add any symbols being defined to the symbol table.
1254   void
1255   add_symbols_to_table(Symbol_table* symtab);
1256
1257   // Finalize symbols and check assertions.
1258   void
1259   finalize_symbols(Symbol_table*, const Layout*, uint64_t*);
1260
1261   // Return the output section name to use for an input file name and
1262   // section name.
1263   const char*
1264   output_section_name(const char* file_name, const char* section_name,
1265                       Output_section***);
1266
1267   // Return whether to place an orphan section after this one.
1268   bool
1269   place_orphan_here(const Output_section *os, bool* exact, bool*) const;
1270
1271   // Set the section address.
1272   void
1273   set_section_addresses(Symbol_table* symtab, Layout* layout,
1274                         uint64_t* dot_value, uint64_t* load_address);
1275
1276   // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
1277   // this section is constrained, and the input sections do not match,
1278   // return the constraint, and set *POSD.
1279   Section_constraint
1280   check_constraint(Output_section_definition** posd);
1281
1282   // See if this is the alternate output section for a constrained
1283   // output section.  If it is, transfer the Output_section and return
1284   // true.  Otherwise return false.
1285   bool
1286   alternate_constraint(Output_section_definition*, Section_constraint);
1287
1288   // Get the list of segments to use for an allocated section when
1289   // using a PHDRS clause.
1290   Output_section*
1291   allocate_to_segment(String_list** phdrs_list, bool* orphan);
1292
1293   // Look for an output section by name and return the address, the
1294   // load address, the alignment, and the size.  This is used when an
1295   // expression refers to an output section which was not actually
1296   // created.  This returns true if the section was found, false
1297   // otherwise.
1298   bool
1299   get_output_section_info(const char*, uint64_t*, uint64_t*, uint64_t*,
1300                           uint64_t*) const;
1301
1302   // Return the associated Output_section if there is one.
1303   Output_section*
1304   get_output_section() const
1305   { return this->output_section_; }
1306
1307   // Print the contents to the FILE.  This is for debugging.
1308   void
1309   print(FILE*) const;
1310
1311  private:
1312   typedef std::vector<Output_section_element*> Output_section_elements;
1313
1314   // The output section name.
1315   std::string name_;
1316   // The address.  This may be NULL.
1317   Expression* address_;
1318   // The load address.  This may be NULL.
1319   Expression* load_address_;
1320   // The alignment.  This may be NULL.
1321   Expression* align_;
1322   // The input section alignment.  This may be NULL.
1323   Expression* subalign_;
1324   // The constraint, if any.
1325   Section_constraint constraint_;
1326   // The fill value.  This may be NULL.
1327   Expression* fill_;
1328   // The list of segments this section should go into.  This may be
1329   // NULL.
1330   String_list* phdrs_;
1331   // The list of elements defining the section.
1332   Output_section_elements elements_;
1333   // The Output_section created for this definition.  This will be
1334   // NULL if none was created.
1335   Output_section* output_section_;
1336   // The address after it has been evaluated.
1337   uint64_t evaluated_address_;
1338   // The load address after it has been evaluated.
1339   uint64_t evaluated_load_address_;
1340   // The alignment after it has been evaluated.
1341   uint64_t evaluated_addralign_;
1342   // The output section is relro.
1343   bool is_relro_;
1344 };
1345
1346 // Constructor.
1347
1348 Output_section_definition::Output_section_definition(
1349     const char* name,
1350     size_t namelen,
1351     const Parser_output_section_header* header)
1352   : name_(name, namelen),
1353     address_(header->address),
1354     load_address_(header->load_address),
1355     align_(header->align),
1356     subalign_(header->subalign),
1357     constraint_(header->constraint),
1358     fill_(NULL),
1359     phdrs_(NULL),
1360     elements_(),
1361     output_section_(NULL),
1362     evaluated_address_(0),
1363     evaluated_load_address_(0),
1364     evaluated_addralign_(0),
1365     is_relro_(false)
1366 {
1367 }
1368
1369 // Finish an output section.
1370
1371 void
1372 Output_section_definition::finish(const Parser_output_section_trailer* trailer)
1373 {
1374   this->fill_ = trailer->fill;
1375   this->phdrs_ = trailer->phdrs;
1376 }
1377
1378 // Add a symbol to be defined.
1379
1380 void
1381 Output_section_definition::add_symbol_assignment(const char* name,
1382                                                  size_t length,
1383                                                  Expression* value,
1384                                                  bool provide,
1385                                                  bool hidden)
1386 {
1387   Output_section_element* p = new Output_section_element_assignment(name,
1388                                                                     length,
1389                                                                     value,
1390                                                                     provide,
1391                                                                     hidden);
1392   this->elements_.push_back(p);
1393 }
1394
1395 // Add an assignment to the special dot symbol.
1396
1397 void
1398 Output_section_definition::add_dot_assignment(Expression* value)
1399 {
1400   Output_section_element* p = new Output_section_element_dot_assignment(value);
1401   this->elements_.push_back(p);
1402 }
1403
1404 // Add an assertion.
1405
1406 void
1407 Output_section_definition::add_assertion(Expression* check,
1408                                          const char* message,
1409                                          size_t messagelen)
1410 {
1411   Output_section_element* p = new Output_section_element_assertion(check,
1412                                                                    message,
1413                                                                    messagelen);
1414   this->elements_.push_back(p);
1415 }
1416
1417 // Add a data item to the current output section.
1418
1419 void
1420 Output_section_definition::add_data(int size, bool is_signed, Expression* val)
1421 {
1422   Output_section_element* p = new Output_section_element_data(size, is_signed,
1423                                                               val);
1424   this->elements_.push_back(p);
1425 }
1426
1427 // Add a setting for the fill value.
1428
1429 void
1430 Output_section_definition::add_fill(Expression* val)
1431 {
1432   Output_section_element* p = new Output_section_element_fill(val);
1433   this->elements_.push_back(p);
1434 }
1435
1436 // Add an input section specification.
1437
1438 void
1439 Output_section_definition::add_input_section(const Input_section_spec* spec,
1440                                              bool keep)
1441 {
1442   Output_section_element* p = new Output_section_element_input(spec, keep);
1443   this->elements_.push_back(p);
1444 }
1445
1446 // Create any required output sections.  We need an output section if
1447 // there is a data statement here.
1448
1449 void
1450 Output_section_definition::create_sections(Layout* layout)
1451 {
1452   if (this->output_section_ != NULL)
1453     return;
1454   for (Output_section_elements::const_iterator p = this->elements_.begin();
1455        p != this->elements_.end();
1456        ++p)
1457     {
1458       if ((*p)->needs_output_section())
1459         {
1460           const char* name = this->name_.c_str();
1461           this->output_section_ = layout->make_output_section_for_script(name);
1462           return;
1463         }
1464     }
1465 }
1466
1467 // Add any symbols being defined to the symbol table.
1468
1469 void
1470 Output_section_definition::add_symbols_to_table(Symbol_table* symtab)
1471 {
1472   for (Output_section_elements::iterator p = this->elements_.begin();
1473        p != this->elements_.end();
1474        ++p)
1475     (*p)->add_symbols_to_table(symtab);
1476 }
1477
1478 // Finalize symbols and check assertions.
1479
1480 void
1481 Output_section_definition::finalize_symbols(Symbol_table* symtab,
1482                                             const Layout* layout,
1483                                             uint64_t* dot_value)
1484 {
1485   if (this->output_section_ != NULL)
1486     *dot_value = this->output_section_->address();
1487   else
1488     {
1489       uint64_t address = *dot_value;
1490       if (this->address_ != NULL)
1491         {
1492           Output_section* dummy;
1493           address = this->address_->eval_with_dot(symtab, layout, true,
1494                                                   *dot_value, NULL,
1495                                                   &dummy);
1496         }
1497       if (this->align_ != NULL)
1498         {
1499           Output_section* dummy;
1500           uint64_t align = this->align_->eval_with_dot(symtab, layout, true,
1501                                                        *dot_value,
1502                                                        NULL,
1503                                                        &dummy);
1504           address = align_address(address, align);
1505         }
1506       *dot_value = address;
1507     }
1508
1509   Output_section* dot_section = this->output_section_;
1510   for (Output_section_elements::iterator p = this->elements_.begin();
1511        p != this->elements_.end();
1512        ++p)
1513     (*p)->finalize_symbols(symtab, layout, dot_value, &dot_section);
1514 }
1515
1516 // Return the output section name to use for an input section name.
1517
1518 const char*
1519 Output_section_definition::output_section_name(const char* file_name,
1520                                                const char* section_name,
1521                                                Output_section*** slot)
1522 {
1523   // Ask each element whether it matches NAME.
1524   for (Output_section_elements::const_iterator p = this->elements_.begin();
1525        p != this->elements_.end();
1526        ++p)
1527     {
1528       if ((*p)->match_name(file_name, section_name))
1529         {
1530           // We found a match for NAME, which means that it should go
1531           // into this output section.
1532           *slot = &this->output_section_;
1533           return this->name_.c_str();
1534         }
1535     }
1536
1537   // We don't know about this section name.
1538   return NULL;
1539 }
1540
1541 // Return whether to place an orphan output section after this
1542 // section.
1543
1544 bool
1545 Output_section_definition::place_orphan_here(const Output_section *os,
1546                                              bool* exact,
1547                                              bool* is_relro) const
1548 {
1549   *is_relro = this->is_relro_;
1550
1551   // Check for the simple case first.
1552   if (this->output_section_ != NULL
1553       && this->output_section_->type() == os->type()
1554       && this->output_section_->flags() == os->flags())
1555     {
1556       *exact = true;
1557       return true;
1558     }
1559
1560   // Otherwise use some heuristics.
1561
1562   if ((os->flags() & elfcpp::SHF_ALLOC) == 0)
1563     return false;
1564
1565   if (os->type() == elfcpp::SHT_NOBITS)
1566     {
1567       if (this->name_ == ".bss")
1568         {
1569           *exact = true;
1570           return true;
1571         }
1572       if (this->output_section_ != NULL
1573           && this->output_section_->type() == elfcpp::SHT_NOBITS)
1574         return true;
1575     }
1576   else if (os->type() == elfcpp::SHT_NOTE)
1577     {
1578       if (this->output_section_ != NULL
1579           && this->output_section_->type() == elfcpp::SHT_NOTE)
1580         {
1581           *exact = true;
1582           return true;
1583         }
1584       if (this->name_.compare(0, 5, ".note") == 0)
1585         {
1586           *exact = true;
1587           return true;
1588         }
1589       if (this->name_ == ".interp")
1590         return true;
1591       if (this->output_section_ != NULL
1592           && this->output_section_->type() == elfcpp::SHT_PROGBITS
1593           && (this->output_section_->flags() & elfcpp::SHF_WRITE) == 0)
1594         return true;
1595     }
1596   else if (os->type() == elfcpp::SHT_REL || os->type() == elfcpp::SHT_RELA)
1597     {
1598       if (this->name_.compare(0, 4, ".rel") == 0)
1599         {
1600           *exact = true;
1601           return true;
1602         }
1603       if (this->output_section_ != NULL
1604           && (this->output_section_->type() == elfcpp::SHT_REL
1605               || this->output_section_->type() == elfcpp::SHT_RELA))
1606         {
1607           *exact = true;
1608           return true;
1609         }
1610       if (this->output_section_ != NULL
1611           && this->output_section_->type() == elfcpp::SHT_PROGBITS
1612           && (this->output_section_->flags() & elfcpp::SHF_WRITE) == 0)
1613         return true;
1614     }
1615   else if (os->type() == elfcpp::SHT_PROGBITS
1616            && (os->flags() & elfcpp::SHF_WRITE) != 0)
1617     {
1618       if (this->name_ == ".data")
1619         {
1620           *exact = true;
1621           return true;
1622         }
1623       if (this->output_section_ != NULL
1624           && this->output_section_->type() == elfcpp::SHT_PROGBITS
1625           && (this->output_section_->flags() & elfcpp::SHF_WRITE) != 0)
1626         return true;
1627     }
1628   else if (os->type() == elfcpp::SHT_PROGBITS
1629            && (os->flags() & elfcpp::SHF_EXECINSTR) != 0)
1630     {
1631       if (this->name_ == ".text")
1632         {
1633           *exact = true;
1634           return true;
1635         }
1636       if (this->output_section_ != NULL
1637           && this->output_section_->type() == elfcpp::SHT_PROGBITS
1638           && (this->output_section_->flags() & elfcpp::SHF_EXECINSTR) != 0)
1639         return true;
1640     }
1641   else if (os->type() == elfcpp::SHT_PROGBITS
1642            || (os->type() != elfcpp::SHT_PROGBITS
1643                && (os->flags() & elfcpp::SHF_WRITE) == 0))
1644     {
1645       if (this->name_ == ".rodata")
1646         {
1647           *exact = true;
1648           return true;
1649         }
1650       if (this->output_section_ != NULL
1651           && this->output_section_->type() == elfcpp::SHT_PROGBITS
1652           && (this->output_section_->flags() & elfcpp::SHF_WRITE) == 0)
1653         return true;
1654     }
1655
1656   return false;
1657 }
1658
1659 // Set the section address.  Note that the OUTPUT_SECTION_ field will
1660 // be NULL if no input sections were mapped to this output section.
1661 // We still have to adjust dot and process symbol assignments.
1662
1663 void
1664 Output_section_definition::set_section_addresses(Symbol_table* symtab,
1665                                                  Layout* layout,
1666                                                  uint64_t* dot_value,
1667                                                  uint64_t* load_address)
1668 {
1669   uint64_t address;
1670   if (this->address_ == NULL)
1671     address = *dot_value;
1672   else
1673     {
1674       Output_section* dummy;
1675       address = this->address_->eval_with_dot(symtab, layout, true,
1676                                               *dot_value, NULL, &dummy);
1677     }
1678
1679   uint64_t align;
1680   if (this->align_ == NULL)
1681     {
1682       if (this->output_section_ == NULL)
1683         align = 0;
1684       else
1685         align = this->output_section_->addralign();
1686     }
1687   else
1688     {
1689       Output_section* align_section;
1690       align = this->align_->eval_with_dot(symtab, layout, true, *dot_value,
1691                                           NULL, &align_section);
1692       if (align_section != NULL)
1693         gold_warning(_("alignment of section %s is not absolute"),
1694                      this->name_.c_str());
1695       if (this->output_section_ != NULL)
1696         this->output_section_->set_addralign(align);
1697     }
1698
1699   address = align_address(address, align);
1700
1701   uint64_t start_address = address;
1702
1703   *dot_value = address;
1704
1705   // The address of non-SHF_ALLOC sections is forced to zero,
1706   // regardless of what the linker script wants.
1707   if (this->output_section_ != NULL
1708       && (this->output_section_->flags() & elfcpp::SHF_ALLOC) != 0)
1709     this->output_section_->set_address(address);
1710
1711   this->evaluated_address_ = address;
1712   this->evaluated_addralign_ = align;
1713
1714   if (this->load_address_ == NULL)
1715     this->evaluated_load_address_ = address;
1716   else
1717     {
1718       Output_section* dummy;
1719       uint64_t load_address =
1720         this->load_address_->eval_with_dot(symtab, layout, true, *dot_value,
1721                                            this->output_section_, &dummy);
1722       if (this->output_section_ != NULL)
1723         this->output_section_->set_load_address(load_address);
1724       this->evaluated_load_address_ = load_address;
1725     }
1726
1727   uint64_t subalign;
1728   if (this->subalign_ == NULL)
1729     subalign = 0;
1730   else
1731     {
1732       Output_section* subalign_section;
1733       subalign = this->subalign_->eval_with_dot(symtab, layout, true,
1734                                                 *dot_value, NULL,
1735                                                 &subalign_section);
1736       if (subalign_section != NULL)
1737         gold_warning(_("subalign of section %s is not absolute"),
1738                      this->name_.c_str());
1739     }
1740
1741   std::string fill;
1742   if (this->fill_ != NULL)
1743     {
1744       // FIXME: The GNU linker supports fill values of arbitrary
1745       // length.
1746       Output_section* fill_section;
1747       uint64_t fill_val = this->fill_->eval_with_dot(symtab, layout, true,
1748                                                      *dot_value,
1749                                                      NULL,
1750                                                      &fill_section);
1751       if (fill_section != NULL)
1752         gold_warning(_("fill of section %s is not absolute"),
1753                      this->name_.c_str());
1754       unsigned char fill_buff[4];
1755       elfcpp::Swap_unaligned<32, true>::writeval(fill_buff, fill_val);
1756       fill.assign(reinterpret_cast<char*>(fill_buff), 4);
1757     }
1758
1759   Input_section_list input_sections;
1760   if (this->output_section_ != NULL)
1761     {
1762       // Get the list of input sections attached to this output
1763       // section.  This will leave the output section with only
1764       // Output_section_data entries.
1765       address += this->output_section_->get_input_sections(address,
1766                                                            fill,
1767                                                            &input_sections);
1768       *dot_value = address;
1769     }
1770
1771   Output_section* dot_section = this->output_section_;
1772   for (Output_section_elements::iterator p = this->elements_.begin();
1773        p != this->elements_.end();
1774        ++p)
1775     (*p)->set_section_addresses(symtab, layout, this->output_section_,
1776                                 subalign, dot_value, &dot_section, &fill,
1777                                 &input_sections);
1778
1779   gold_assert(input_sections.empty());
1780
1781   if (this->load_address_ == NULL || this->output_section_ == NULL)
1782     *load_address = *dot_value;
1783   else
1784     *load_address = (this->output_section_->load_address()
1785                      + (*dot_value - start_address));
1786
1787   if (this->output_section_ != NULL)
1788     {
1789       if (this->is_relro_)
1790         this->output_section_->set_is_relro();
1791       else
1792         this->output_section_->clear_is_relro();
1793     }
1794 }
1795
1796 // Check a constraint (ONLY_IF_RO, etc.) on an output section.  If
1797 // this section is constrained, and the input sections do not match,
1798 // return the constraint, and set *POSD.
1799
1800 Section_constraint
1801 Output_section_definition::check_constraint(Output_section_definition** posd)
1802 {
1803   switch (this->constraint_)
1804     {
1805     case CONSTRAINT_NONE:
1806       return CONSTRAINT_NONE;
1807
1808     case CONSTRAINT_ONLY_IF_RO:
1809       if (this->output_section_ != NULL
1810           && (this->output_section_->flags() & elfcpp::SHF_WRITE) != 0)
1811         {
1812           *posd = this;
1813           return CONSTRAINT_ONLY_IF_RO;
1814         }
1815       return CONSTRAINT_NONE;
1816
1817     case CONSTRAINT_ONLY_IF_RW:
1818       if (this->output_section_ != NULL
1819           && (this->output_section_->flags() & elfcpp::SHF_WRITE) == 0)
1820         {
1821           *posd = this;
1822           return CONSTRAINT_ONLY_IF_RW;
1823         }
1824       return CONSTRAINT_NONE;
1825
1826     case CONSTRAINT_SPECIAL:
1827       if (this->output_section_ != NULL)
1828         gold_error(_("SPECIAL constraints are not implemented"));
1829       return CONSTRAINT_NONE;
1830
1831     default:
1832       gold_unreachable();
1833     }
1834 }
1835
1836 // See if this is the alternate output section for a constrained
1837 // output section.  If it is, transfer the Output_section and return
1838 // true.  Otherwise return false.
1839
1840 bool
1841 Output_section_definition::alternate_constraint(
1842     Output_section_definition* posd,
1843     Section_constraint constraint)
1844 {
1845   if (this->name_ != posd->name_)
1846     return false;
1847
1848   switch (constraint)
1849     {
1850     case CONSTRAINT_ONLY_IF_RO:
1851       if (this->constraint_ != CONSTRAINT_ONLY_IF_RW)
1852         return false;
1853       break;
1854
1855     case CONSTRAINT_ONLY_IF_RW:
1856       if (this->constraint_ != CONSTRAINT_ONLY_IF_RO)
1857         return false;
1858       break;
1859
1860     default:
1861       gold_unreachable();
1862     }
1863
1864   // We have found the alternate constraint.  We just need to move
1865   // over the Output_section.  When constraints are used properly,
1866   // THIS should not have an output_section pointer, as all the input
1867   // sections should have matched the other definition.
1868
1869   if (this->output_section_ != NULL)
1870     gold_error(_("mismatched definition for constrained sections"));
1871
1872   this->output_section_ = posd->output_section_;
1873   posd->output_section_ = NULL;
1874
1875   if (this->is_relro_)
1876     this->output_section_->set_is_relro();
1877   else
1878     this->output_section_->clear_is_relro();
1879
1880   return true;
1881 }
1882
1883 // Get the list of segments to use for an allocated section when using
1884 // a PHDRS clause.
1885
1886 Output_section*
1887 Output_section_definition::allocate_to_segment(String_list** phdrs_list,
1888                                                bool* orphan)
1889 {
1890   if (this->output_section_ == NULL)
1891     return NULL;
1892   if ((this->output_section_->flags() & elfcpp::SHF_ALLOC) == 0)
1893     return NULL;
1894   *orphan = false;
1895   if (this->phdrs_ != NULL)
1896     *phdrs_list = this->phdrs_;
1897   return this->output_section_;
1898 }
1899
1900 // Look for an output section by name and return the address, the load
1901 // address, the alignment, and the size.  This is used when an
1902 // expression refers to an output section which was not actually
1903 // created.  This returns true if the section was found, false
1904 // otherwise.
1905
1906 bool
1907 Output_section_definition::get_output_section_info(const char* name,
1908                                                    uint64_t* address,
1909                                                    uint64_t* load_address,
1910                                                    uint64_t* addralign,
1911                                                    uint64_t* size) const
1912 {
1913   if (this->name_ != name)
1914     return false;
1915
1916   if (this->output_section_ != NULL)
1917     {
1918       *address = this->output_section_->address();
1919       if (this->output_section_->has_load_address())
1920         *load_address = this->output_section_->load_address();
1921       else
1922         *load_address = *address;
1923       *addralign = this->output_section_->addralign();
1924       *size = this->output_section_->current_data_size();
1925     }
1926   else
1927     {
1928       *address = this->evaluated_address_;
1929       *load_address = this->evaluated_load_address_;
1930       *addralign = this->evaluated_addralign_;
1931       *size = 0;
1932     }
1933
1934   return true;
1935 }
1936
1937 // Print for debugging.
1938
1939 void
1940 Output_section_definition::print(FILE* f) const
1941 {
1942   fprintf(f, "  %s ", this->name_.c_str());
1943
1944   if (this->address_ != NULL)
1945     {
1946       this->address_->print(f);
1947       fprintf(f, " ");
1948     }
1949
1950   fprintf(f, ": ");
1951
1952   if (this->load_address_ != NULL)
1953     {
1954       fprintf(f, "AT(");
1955       this->load_address_->print(f);
1956       fprintf(f, ") ");
1957     }
1958
1959   if (this->align_ != NULL)
1960     {
1961       fprintf(f, "ALIGN(");
1962       this->align_->print(f);
1963       fprintf(f, ") ");
1964     }
1965
1966   if (this->subalign_ != NULL)
1967     {
1968       fprintf(f, "SUBALIGN(");
1969       this->subalign_->print(f);
1970       fprintf(f, ") ");
1971     }
1972
1973   fprintf(f, "{\n");
1974
1975   for (Output_section_elements::const_iterator p = this->elements_.begin();
1976        p != this->elements_.end();
1977        ++p)
1978     (*p)->print(f);
1979
1980   fprintf(f, "  }");
1981
1982   if (this->fill_ != NULL)
1983     {
1984       fprintf(f, " = ");
1985       this->fill_->print(f);
1986     }
1987
1988   if (this->phdrs_ != NULL)
1989     {
1990       for (String_list::const_iterator p = this->phdrs_->begin();
1991            p != this->phdrs_->end();
1992            ++p)
1993         fprintf(f, " :%s", p->c_str());
1994     }
1995
1996   fprintf(f, "\n");
1997 }
1998
1999 // An output section created to hold orphaned input sections.  These
2000 // do not actually appear in linker scripts.  However, for convenience
2001 // when setting the output section addresses, we put a marker to these
2002 // sections in the appropriate place in the list of SECTIONS elements.
2003
2004 class Orphan_output_section : public Sections_element
2005 {
2006  public:
2007   Orphan_output_section(Output_section* os)
2008     : os_(os)
2009   { }
2010
2011   // Return whether to place an orphan section after this one.
2012   bool
2013   place_orphan_here(const Output_section *os, bool* exact, bool*) const;
2014
2015   // Set section addresses.
2016   void
2017   set_section_addresses(Symbol_table*, Layout*, uint64_t*, uint64_t*);
2018
2019   // Get the list of segments to use for an allocated section when
2020   // using a PHDRS clause.
2021   Output_section*
2022   allocate_to_segment(String_list**, bool*);
2023
2024   // Return the associated Output_section.
2025   Output_section*
2026   get_output_section() const
2027   { return this->os_; }
2028
2029   // Print for debugging.
2030   void
2031   print(FILE* f) const
2032   {
2033     fprintf(f, "  marker for orphaned output section %s\n",
2034             this->os_->name());
2035   }
2036
2037  private:
2038   Output_section* os_;
2039 };
2040
2041 // Whether to place another orphan section after this one.
2042
2043 bool
2044 Orphan_output_section::place_orphan_here(const Output_section* os,
2045                                          bool* exact,
2046                                          bool* is_relro) const
2047 {
2048   if (this->os_->type() == os->type()
2049       && this->os_->flags() == os->flags())
2050     {
2051       *exact = true;
2052       *is_relro = this->os_->is_relro();
2053       return true;
2054     }
2055   return false;
2056 }
2057
2058 // Set section addresses.
2059
2060 void
2061 Orphan_output_section::set_section_addresses(Symbol_table*, Layout*,
2062                                              uint64_t* dot_value,
2063                                              uint64_t* load_address)
2064 {
2065   typedef std::list<std::pair<Relobj*, unsigned int> > Input_section_list;
2066
2067   bool have_load_address = *load_address != *dot_value;
2068
2069   uint64_t address = *dot_value;
2070   address = align_address(address, this->os_->addralign());
2071
2072   if ((this->os_->flags() & elfcpp::SHF_ALLOC) != 0)
2073     {
2074       this->os_->set_address(address);
2075       if (have_load_address)
2076         this->os_->set_load_address(align_address(*load_address,
2077                                                   this->os_->addralign()));
2078     }
2079
2080   Input_section_list input_sections;
2081   address += this->os_->get_input_sections(address, "", &input_sections);
2082
2083   for (Input_section_list::iterator p = input_sections.begin();
2084        p != input_sections.end();
2085        ++p)
2086     {
2087       uint64_t addralign;
2088       uint64_t size;
2089
2090       // We know what are single-threaded, so it is OK to lock the
2091       // object.
2092       {
2093         const Task* task = reinterpret_cast<const Task*>(-1);
2094         Task_lock_obj<Object> tl(task, p->first);
2095         addralign = p->first->section_addralign(p->second);
2096         size = p->first->section_size(p->second);
2097       }
2098
2099       address = align_address(address, addralign);
2100       this->os_->add_input_section_for_script(p->first, p->second, size,
2101                                               addralign);
2102       address += size;
2103     }
2104
2105   if (!have_load_address)
2106     *load_address = address;
2107   else
2108     *load_address += address - *dot_value;
2109
2110   *dot_value = address;
2111 }
2112
2113 // Get the list of segments to use for an allocated section when using
2114 // a PHDRS clause.  If this is an allocated section, return the
2115 // Output_section.  We don't change the list of segments.
2116
2117 Output_section*
2118 Orphan_output_section::allocate_to_segment(String_list**, bool* orphan)
2119 {
2120   if ((this->os_->flags() & elfcpp::SHF_ALLOC) == 0)
2121     return NULL;
2122   *orphan = true;
2123   return this->os_;
2124 }
2125
2126 // Class Phdrs_element.  A program header from a PHDRS clause.
2127
2128 class Phdrs_element
2129 {
2130  public:
2131   Phdrs_element(const char* name, size_t namelen, unsigned int type,
2132                 bool includes_filehdr, bool includes_phdrs,
2133                 bool is_flags_valid, unsigned int flags,
2134                 Expression* load_address)
2135     : name_(name, namelen), type_(type), includes_filehdr_(includes_filehdr),
2136       includes_phdrs_(includes_phdrs), is_flags_valid_(is_flags_valid),
2137       flags_(flags), load_address_(load_address), load_address_value_(0),
2138       segment_(NULL)
2139   { }
2140
2141   // Return the name of this segment.
2142   const std::string&
2143   name() const
2144   { return this->name_; }
2145
2146   // Return the type of the segment.
2147   unsigned int
2148   type() const
2149   { return this->type_; }
2150
2151   // Whether to include the file header.
2152   bool
2153   includes_filehdr() const
2154   { return this->includes_filehdr_; }
2155
2156   // Whether to include the program headers.
2157   bool
2158   includes_phdrs() const
2159   { return this->includes_phdrs_; }
2160
2161   // Return whether there is a load address.
2162   bool
2163   has_load_address() const
2164   { return this->load_address_ != NULL; }
2165
2166   // Evaluate the load address expression if there is one.
2167   void
2168   eval_load_address(Symbol_table* symtab, Layout* layout)
2169   {
2170     if (this->load_address_ != NULL)
2171       this->load_address_value_ = this->load_address_->eval(symtab, layout,
2172                                                             true);
2173   }
2174
2175   // Return the load address.
2176   uint64_t
2177   load_address() const
2178   {
2179     gold_assert(this->load_address_ != NULL);
2180     return this->load_address_value_;
2181   }
2182
2183   // Create the segment.
2184   Output_segment*
2185   create_segment(Layout* layout)
2186   {
2187     this->segment_ = layout->make_output_segment(this->type_, this->flags_);
2188     return this->segment_;
2189   }
2190
2191   // Return the segment.
2192   Output_segment*
2193   segment()
2194   { return this->segment_; }
2195
2196   // Set the segment flags if appropriate.
2197   void
2198   set_flags_if_valid()
2199   {
2200     if (this->is_flags_valid_)
2201       this->segment_->set_flags(this->flags_);
2202   }
2203
2204   // Print for debugging.
2205   void
2206   print(FILE*) const;
2207
2208  private:
2209   // The name used in the script.
2210   std::string name_;
2211   // The type of the segment (PT_LOAD, etc.).
2212   unsigned int type_;
2213   // Whether this segment includes the file header.
2214   bool includes_filehdr_;
2215   // Whether this segment includes the section headers.
2216   bool includes_phdrs_;
2217   // Whether the flags were explicitly specified.
2218   bool is_flags_valid_;
2219   // The flags for this segment (PF_R, etc.) if specified.
2220   unsigned int flags_;
2221   // The expression for the load address for this segment.  This may
2222   // be NULL.
2223   Expression* load_address_;
2224   // The actual load address from evaluating the expression.
2225   uint64_t load_address_value_;
2226   // The segment itself.
2227   Output_segment* segment_;
2228 };
2229
2230 // Print for debugging.
2231
2232 void
2233 Phdrs_element::print(FILE* f) const
2234 {
2235   fprintf(f, "  %s 0x%x", this->name_.c_str(), this->type_);
2236   if (this->includes_filehdr_)
2237     fprintf(f, " FILEHDR");
2238   if (this->includes_phdrs_)
2239     fprintf(f, " PHDRS");
2240   if (this->is_flags_valid_)
2241     fprintf(f, " FLAGS(%u)", this->flags_);
2242   if (this->load_address_ != NULL)
2243     {
2244       fprintf(f, " AT(");
2245       this->load_address_->print(f);
2246       fprintf(f, ")");
2247     }
2248   fprintf(f, ";\n");
2249 }
2250
2251 // Class Script_sections.
2252
2253 Script_sections::Script_sections()
2254   : saw_sections_clause_(false),
2255     in_sections_clause_(false),
2256     sections_elements_(NULL),
2257     output_section_(NULL),
2258     phdrs_elements_(NULL),
2259     data_segment_align_index_(-1U),
2260     saw_relro_end_(false)
2261 {
2262 }
2263
2264 // Start a SECTIONS clause.
2265
2266 void
2267 Script_sections::start_sections()
2268 {
2269   gold_assert(!this->in_sections_clause_ && this->output_section_ == NULL);
2270   this->saw_sections_clause_ = true;
2271   this->in_sections_clause_ = true;
2272   if (this->sections_elements_ == NULL)
2273     this->sections_elements_ = new Sections_elements;
2274 }
2275
2276 // Finish a SECTIONS clause.
2277
2278 void
2279 Script_sections::finish_sections()
2280 {
2281   gold_assert(this->in_sections_clause_ && this->output_section_ == NULL);
2282   this->in_sections_clause_ = false;
2283 }
2284
2285 // Add a symbol to be defined.
2286
2287 void
2288 Script_sections::add_symbol_assignment(const char* name, size_t length,
2289                                        Expression* val, bool provide,
2290                                        bool hidden)
2291 {
2292   if (this->output_section_ != NULL)
2293     this->output_section_->add_symbol_assignment(name, length, val,
2294                                                  provide, hidden);
2295   else
2296     {
2297       Sections_element* p = new Sections_element_assignment(name, length,
2298                                                             val, provide,
2299                                                             hidden);
2300       this->sections_elements_->push_back(p);
2301     }
2302 }
2303
2304 // Add an assignment to the special dot symbol.
2305
2306 void
2307 Script_sections::add_dot_assignment(Expression* val)
2308 {
2309   if (this->output_section_ != NULL)
2310     this->output_section_->add_dot_assignment(val);
2311   else
2312     {
2313       Sections_element* p = new Sections_element_dot_assignment(val);
2314       this->sections_elements_->push_back(p);
2315     }
2316 }
2317
2318 // Add an assertion.
2319
2320 void
2321 Script_sections::add_assertion(Expression* check, const char* message,
2322                                size_t messagelen)
2323 {
2324   if (this->output_section_ != NULL)
2325     this->output_section_->add_assertion(check, message, messagelen);
2326   else
2327     {
2328       Sections_element* p = new Sections_element_assertion(check, message,
2329                                                            messagelen);
2330       this->sections_elements_->push_back(p);
2331     }
2332 }
2333
2334 // Start processing entries for an output section.
2335
2336 void
2337 Script_sections::start_output_section(
2338     const char* name,
2339     size_t namelen,
2340     const Parser_output_section_header *header)
2341 {
2342   Output_section_definition* posd = new Output_section_definition(name,
2343                                                                   namelen,
2344                                                                   header);
2345   this->sections_elements_->push_back(posd);
2346   gold_assert(this->output_section_ == NULL);
2347   this->output_section_ = posd;
2348 }
2349
2350 // Stop processing entries for an output section.
2351
2352 void
2353 Script_sections::finish_output_section(
2354     const Parser_output_section_trailer* trailer)
2355 {
2356   gold_assert(this->output_section_ != NULL);
2357   this->output_section_->finish(trailer);
2358   this->output_section_ = NULL;
2359 }
2360
2361 // Add a data item to the current output section.
2362
2363 void
2364 Script_sections::add_data(int size, bool is_signed, Expression* val)
2365 {
2366   gold_assert(this->output_section_ != NULL);
2367   this->output_section_->add_data(size, is_signed, val);
2368 }
2369
2370 // Add a fill value setting to the current output section.
2371
2372 void
2373 Script_sections::add_fill(Expression* val)
2374 {
2375   gold_assert(this->output_section_ != NULL);
2376   this->output_section_->add_fill(val);
2377 }
2378
2379 // Add an input section specification to the current output section.
2380
2381 void
2382 Script_sections::add_input_section(const Input_section_spec* spec, bool keep)
2383 {
2384   gold_assert(this->output_section_ != NULL);
2385   this->output_section_->add_input_section(spec, keep);
2386 }
2387
2388 // This is called when we see DATA_SEGMENT_ALIGN.  It means that any
2389 // subsequent output sections may be relro.
2390
2391 void
2392 Script_sections::data_segment_align()
2393 {
2394   if (this->data_segment_align_index_ != -1U)
2395     gold_error(_("DATA_SEGMENT_ALIGN may only appear once in a linker script"));
2396   this->data_segment_align_index_ = this->sections_elements_->size();
2397 }
2398
2399 // This is called when we see DATA_SEGMENT_RELRO_END.  It means that
2400 // any output sections seen since DATA_SEGMENT_ALIGN are relro.
2401
2402 void
2403 Script_sections::data_segment_relro_end()
2404 {
2405   if (this->saw_relro_end_)
2406     gold_error(_("DATA_SEGMENT_RELRO_END may only appear once "
2407                  "in a linker script"));
2408   this->saw_relro_end_ = true;
2409
2410   if (this->data_segment_align_index_ == -1U)
2411     gold_error(_("DATA_SEGMENT_RELRO_END must follow DATA_SEGMENT_ALIGN"));
2412   else
2413     {
2414       for (size_t i = this->data_segment_align_index_;
2415            i < this->sections_elements_->size();
2416            ++i)
2417         (*this->sections_elements_)[i]->set_is_relro();
2418     }
2419 }
2420
2421 // Create any required sections.
2422
2423 void
2424 Script_sections::create_sections(Layout* layout)
2425 {
2426   if (!this->saw_sections_clause_)
2427     return;
2428   for (Sections_elements::iterator p = this->sections_elements_->begin();
2429        p != this->sections_elements_->end();
2430        ++p)
2431     (*p)->create_sections(layout);
2432 }
2433
2434 // Add any symbols we are defining to the symbol table.
2435
2436 void
2437 Script_sections::add_symbols_to_table(Symbol_table* symtab)
2438 {
2439   if (!this->saw_sections_clause_)
2440     return;
2441   for (Sections_elements::iterator p = this->sections_elements_->begin();
2442        p != this->sections_elements_->end();
2443        ++p)
2444     (*p)->add_symbols_to_table(symtab);
2445 }
2446
2447 // Finalize symbols and check assertions.
2448
2449 void
2450 Script_sections::finalize_symbols(Symbol_table* symtab, const Layout* layout)
2451 {
2452   if (!this->saw_sections_clause_)
2453     return;
2454   uint64_t dot_value = 0;
2455   for (Sections_elements::iterator p = this->sections_elements_->begin();
2456        p != this->sections_elements_->end();
2457        ++p)
2458     (*p)->finalize_symbols(symtab, layout, &dot_value);
2459 }
2460
2461 // Return the name of the output section to use for an input file name
2462 // and section name.
2463
2464 const char*
2465 Script_sections::output_section_name(const char* file_name,
2466                                      const char* section_name,
2467                                      Output_section*** output_section_slot)
2468 {
2469   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
2470        p != this->sections_elements_->end();
2471        ++p)
2472     {
2473       const char* ret = (*p)->output_section_name(file_name, section_name,
2474                                                   output_section_slot);
2475
2476       if (ret != NULL)
2477         {
2478           // The special name /DISCARD/ means that the input section
2479           // should be discarded.
2480           if (strcmp(ret, "/DISCARD/") == 0)
2481             {
2482               *output_section_slot = NULL;
2483               return NULL;
2484             }
2485           return ret;
2486         }
2487     }
2488
2489   // If we couldn't find a mapping for the name, the output section
2490   // gets the name of the input section.
2491
2492   *output_section_slot = NULL;
2493
2494   return section_name;
2495 }
2496
2497 // Place a marker for an orphan output section into the SECTIONS
2498 // clause.
2499
2500 void
2501 Script_sections::place_orphan(Output_section* os)
2502 {
2503   // Look for an output section definition which matches the output
2504   // section.  Put a marker after that section.
2505   bool is_relro = false;
2506   Sections_elements::iterator place = this->sections_elements_->end();
2507   for (Sections_elements::iterator p = this->sections_elements_->begin();
2508        p != this->sections_elements_->end();
2509        ++p)
2510     {
2511       bool exact = false;
2512       bool is_relro_here;
2513       if ((*p)->place_orphan_here(os, &exact, &is_relro_here))
2514         {
2515           place = p;
2516           is_relro = is_relro_here;
2517           if (exact)
2518             break;
2519         }
2520     }
2521
2522   // The insert function puts the new element before the iterator.
2523   if (place != this->sections_elements_->end())
2524     ++place;
2525
2526   this->sections_elements_->insert(place, new Orphan_output_section(os));
2527
2528   if (is_relro)
2529     os->set_is_relro();
2530   else
2531     os->clear_is_relro();
2532 }
2533
2534 // Set the addresses of all the output sections.  Walk through all the
2535 // elements, tracking the dot symbol.  Apply assignments which set
2536 // absolute symbol values, in case they are used when setting dot.
2537 // Fill in data statement values.  As we find output sections, set the
2538 // address, set the address of all associated input sections, and
2539 // update dot.  Return the segment which should hold the file header
2540 // and segment headers, if any.
2541
2542 Output_segment*
2543 Script_sections::set_section_addresses(Symbol_table* symtab, Layout* layout)
2544 {
2545   gold_assert(this->saw_sections_clause_);
2546
2547   // Implement ONLY_IF_RO/ONLY_IF_RW constraints.  These are a pain
2548   // for our representation.
2549   for (Sections_elements::iterator p = this->sections_elements_->begin();
2550        p != this->sections_elements_->end();
2551        ++p)
2552     {
2553       Output_section_definition* posd;
2554       Section_constraint failed_constraint = (*p)->check_constraint(&posd);
2555       if (failed_constraint != CONSTRAINT_NONE)
2556         {
2557           Sections_elements::iterator q;
2558           for (q = this->sections_elements_->begin();
2559                q != this->sections_elements_->end();
2560                ++q)
2561             {
2562               if (q != p)
2563                 {
2564                   if ((*q)->alternate_constraint(posd, failed_constraint))
2565                     break;
2566                 }
2567             }
2568
2569           if (q == this->sections_elements_->end())
2570             gold_error(_("no matching section constraint"));
2571         }
2572     }
2573
2574   // Force the alignment of the first TLS section to be the maximum
2575   // alignment of all TLS sections.
2576   Output_section* first_tls = NULL;
2577   uint64_t tls_align = 0;
2578   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
2579        p != this->sections_elements_->end();
2580        ++p)
2581     {
2582       Output_section *os = (*p)->get_output_section();
2583       if (os != NULL && (os->flags() & elfcpp::SHF_TLS) != 0)
2584         {
2585           if (first_tls == NULL)
2586             first_tls = os;
2587           if (os->addralign() > tls_align)
2588             tls_align = os->addralign();
2589         }
2590     }
2591   if (first_tls != NULL)
2592     first_tls->set_addralign(tls_align);
2593
2594   // For a relocatable link, we implicitly set dot to zero.
2595   uint64_t dot_value = 0;
2596   uint64_t load_address = 0;
2597   for (Sections_elements::iterator p = this->sections_elements_->begin();
2598        p != this->sections_elements_->end();
2599        ++p)
2600     (*p)->set_section_addresses(symtab, layout, &dot_value, &load_address);
2601
2602   if (this->phdrs_elements_ != NULL)
2603     {
2604       for (Phdrs_elements::iterator p = this->phdrs_elements_->begin();
2605            p != this->phdrs_elements_->end();
2606            ++p)
2607         (*p)->eval_load_address(symtab, layout);
2608     }
2609
2610   return this->create_segments(layout);
2611 }
2612
2613 // Sort the sections in order to put them into segments.
2614
2615 class Sort_output_sections
2616 {
2617  public:
2618   bool
2619   operator()(const Output_section* os1, const Output_section* os2) const;
2620 };
2621
2622 bool
2623 Sort_output_sections::operator()(const Output_section* os1,
2624                                  const Output_section* os2) const
2625 {
2626   // Sort first by the load address.
2627   uint64_t lma1 = (os1->has_load_address()
2628                    ? os1->load_address()
2629                    : os1->address());
2630   uint64_t lma2 = (os2->has_load_address()
2631                    ? os2->load_address()
2632                    : os2->address());
2633   if (lma1 != lma2)
2634     return lma1 < lma2;
2635
2636   // Then sort by the virtual address.
2637   if (os1->address() != os2->address())
2638     return os1->address() < os2->address();
2639
2640   // Sort TLS sections to the end.
2641   bool tls1 = (os1->flags() & elfcpp::SHF_TLS) != 0;
2642   bool tls2 = (os2->flags() & elfcpp::SHF_TLS) != 0;
2643   if (tls1 != tls2)
2644     return tls2;
2645
2646   // Sort PROGBITS before NOBITS.
2647   if (os1->type() == elfcpp::SHT_PROGBITS && os2->type() == elfcpp::SHT_NOBITS)
2648     return true;
2649   if (os1->type() == elfcpp::SHT_NOBITS && os2->type() == elfcpp::SHT_PROGBITS)
2650     return false;
2651
2652   // Otherwise we don't care.
2653   return false;
2654 }
2655
2656 // Return whether OS is a BSS section.  This is a SHT_NOBITS section.
2657 // We treat a section with the SHF_TLS flag set as taking up space
2658 // even if it is SHT_NOBITS (this is true of .tbss), as we allocate
2659 // space for them in the file.
2660
2661 bool
2662 Script_sections::is_bss_section(const Output_section* os)
2663 {
2664   return (os->type() == elfcpp::SHT_NOBITS
2665           && (os->flags() & elfcpp::SHF_TLS) == 0);
2666 }
2667
2668 // Return the size taken by the file header and the program headers.
2669
2670 size_t
2671 Script_sections::total_header_size(Layout* layout) const
2672 {
2673   size_t segment_count = layout->segment_count();
2674   size_t file_header_size;
2675   size_t segment_headers_size;
2676   if (parameters->target().get_size() == 32)
2677     {
2678       file_header_size = elfcpp::Elf_sizes<32>::ehdr_size;
2679       segment_headers_size = segment_count * elfcpp::Elf_sizes<32>::phdr_size;
2680     }
2681   else if (parameters->target().get_size() == 64)
2682     {
2683       file_header_size = elfcpp::Elf_sizes<64>::ehdr_size;
2684       segment_headers_size = segment_count * elfcpp::Elf_sizes<64>::phdr_size;
2685     }
2686   else
2687     gold_unreachable();
2688
2689   return file_header_size + segment_headers_size;
2690 }
2691
2692 // Return the amount we have to subtract from the LMA to accomodate
2693 // headers of the given size.  The complication is that the file
2694 // header have to be at the start of a page, as otherwise it will not
2695 // be at the start of the file.
2696
2697 uint64_t
2698 Script_sections::header_size_adjustment(uint64_t lma,
2699                                         size_t sizeof_headers) const
2700 {
2701   const uint64_t abi_pagesize = parameters->target().abi_pagesize();
2702   uint64_t hdr_lma = lma - sizeof_headers;
2703   hdr_lma &= ~(abi_pagesize - 1);
2704   return lma - hdr_lma;
2705 }
2706
2707 // Create the PT_LOAD segments when using a SECTIONS clause.  Returns
2708 // the segment which should hold the file header and segment headers,
2709 // if any.
2710
2711 Output_segment*
2712 Script_sections::create_segments(Layout* layout)
2713 {
2714   gold_assert(this->saw_sections_clause_);
2715
2716   if (parameters->options().relocatable())
2717     return NULL;
2718
2719   if (this->saw_phdrs_clause())
2720     return create_segments_from_phdrs_clause(layout);
2721
2722   Layout::Section_list sections;
2723   layout->get_allocated_sections(&sections);
2724
2725   // Sort the sections by address.
2726   std::stable_sort(sections.begin(), sections.end(), Sort_output_sections());
2727
2728   this->create_note_and_tls_segments(layout, &sections);
2729
2730   // Walk through the sections adding them to PT_LOAD segments.
2731   const uint64_t abi_pagesize = parameters->target().abi_pagesize();
2732   Output_segment* first_seg = NULL;
2733   Output_segment* current_seg = NULL;
2734   bool is_current_seg_readonly = true;
2735   Layout::Section_list::iterator plast = sections.end();
2736   uint64_t last_vma = 0;
2737   uint64_t last_lma = 0;
2738   uint64_t last_size = 0;
2739   for (Layout::Section_list::iterator p = sections.begin();
2740        p != sections.end();
2741        ++p)
2742     {
2743       const uint64_t vma = (*p)->address();
2744       const uint64_t lma = ((*p)->has_load_address()
2745                             ? (*p)->load_address()
2746                             : vma);
2747       const uint64_t size = (*p)->current_data_size();
2748
2749       bool need_new_segment;
2750       if (current_seg == NULL)
2751         need_new_segment = true;
2752       else if (lma - vma != last_lma - last_vma)
2753         {
2754           // This section has a different LMA relationship than the
2755           // last one; we need a new segment.
2756           need_new_segment = true;
2757         }
2758       else if (align_address(last_lma + last_size, abi_pagesize)
2759                < align_address(lma, abi_pagesize))
2760         {
2761           // Putting this section in the segment would require
2762           // skipping a page.
2763           need_new_segment = true;
2764         }
2765       else if (is_bss_section(*plast) && !is_bss_section(*p))
2766         {
2767           // A non-BSS section can not follow a BSS section in the
2768           // same segment.
2769           need_new_segment = true;
2770         }
2771       else if (is_current_seg_readonly
2772                && ((*p)->flags() & elfcpp::SHF_WRITE) != 0
2773                && !parameters->options().omagic())
2774         {
2775           // Don't put a writable section in the same segment as a
2776           // non-writable section.
2777           need_new_segment = true;
2778         }
2779       else
2780         {
2781           // Otherwise, reuse the existing segment.
2782           need_new_segment = false;
2783         }
2784
2785       elfcpp::Elf_Word seg_flags =
2786         Layout::section_flags_to_segment((*p)->flags());
2787
2788       if (need_new_segment)
2789         {
2790           current_seg = layout->make_output_segment(elfcpp::PT_LOAD,
2791                                                     seg_flags);
2792           current_seg->set_addresses(vma, lma);
2793           if (first_seg == NULL)
2794             first_seg = current_seg;
2795           is_current_seg_readonly = true;
2796         }
2797
2798       current_seg->add_output_section(*p, seg_flags);
2799
2800       if (((*p)->flags() & elfcpp::SHF_WRITE) != 0)
2801         is_current_seg_readonly = false;
2802
2803       plast = p;
2804       last_vma = vma;
2805       last_lma = lma;
2806       last_size = size;
2807     }
2808
2809   // An ELF program should work even if the program headers are not in
2810   // a PT_LOAD segment.  However, it appears that the Linux kernel
2811   // does not set the AT_PHDR auxiliary entry in that case.  It sets
2812   // the load address to p_vaddr - p_offset of the first PT_LOAD
2813   // segment.  It then sets AT_PHDR to the load address plus the
2814   // offset to the program headers, e_phoff in the file header.  This
2815   // fails when the program headers appear in the file before the
2816   // first PT_LOAD segment.  Therefore, we always create a PT_LOAD
2817   // segment to hold the file header and the program headers.  This is
2818   // effectively what the GNU linker does, and it is slightly more
2819   // efficient in any case.  We try to use the first PT_LOAD segment
2820   // if we can, otherwise we make a new one.
2821
2822   if (first_seg == NULL)
2823     return NULL;
2824
2825   size_t sizeof_headers = this->total_header_size(layout);
2826
2827   uint64_t vma = first_seg->vaddr();
2828   uint64_t lma = first_seg->paddr();
2829
2830   uint64_t subtract = this->header_size_adjustment(lma, sizeof_headers);
2831
2832   if ((lma & (abi_pagesize - 1)) >= sizeof_headers)
2833     {
2834       first_seg->set_addresses(vma - subtract, lma - subtract);
2835       return first_seg;
2836     }
2837
2838   // If there is no room to squeeze in the headers, then punt.  The
2839   // resulting executable probably won't run on GNU/Linux, but we
2840   // trust that the user knows what they are doing.
2841   if (lma < subtract || vma < subtract)
2842     return NULL;
2843
2844   Output_segment* load_seg = layout->make_output_segment(elfcpp::PT_LOAD,
2845                                                          elfcpp::PF_R);
2846   load_seg->set_addresses(vma - subtract, lma - subtract);
2847
2848   return load_seg;
2849 }
2850
2851 // Create a PT_NOTE segment for each SHT_NOTE section and a PT_TLS
2852 // segment if there are any SHT_TLS sections.
2853
2854 void
2855 Script_sections::create_note_and_tls_segments(
2856     Layout* layout,
2857     const Layout::Section_list* sections)
2858 {
2859   gold_assert(!this->saw_phdrs_clause());
2860
2861   bool saw_tls = false;
2862   for (Layout::Section_list::const_iterator p = sections->begin();
2863        p != sections->end();
2864        ++p)
2865     {
2866       if ((*p)->type() == elfcpp::SHT_NOTE)
2867         {
2868           elfcpp::Elf_Word seg_flags =
2869             Layout::section_flags_to_segment((*p)->flags());
2870           Output_segment* oseg = layout->make_output_segment(elfcpp::PT_NOTE,
2871                                                              seg_flags);
2872           oseg->add_output_section(*p, seg_flags);
2873
2874           // Incorporate any subsequent SHT_NOTE sections, in the
2875           // hopes that the script is sensible.
2876           Layout::Section_list::const_iterator pnext = p + 1;
2877           while (pnext != sections->end()
2878                  && (*pnext)->type() == elfcpp::SHT_NOTE)
2879             {
2880               seg_flags = Layout::section_flags_to_segment((*pnext)->flags());
2881               oseg->add_output_section(*pnext, seg_flags);
2882               p = pnext;
2883               ++pnext;
2884             }
2885         }
2886
2887       if (((*p)->flags() & elfcpp::SHF_TLS) != 0)
2888         {
2889           if (saw_tls)
2890             gold_error(_("TLS sections are not adjacent"));
2891
2892           elfcpp::Elf_Word seg_flags =
2893             Layout::section_flags_to_segment((*p)->flags());
2894           Output_segment* oseg = layout->make_output_segment(elfcpp::PT_TLS,
2895                                                              seg_flags);
2896           oseg->add_output_section(*p, seg_flags);
2897
2898           Layout::Section_list::const_iterator pnext = p + 1;
2899           while (pnext != sections->end()
2900                  && ((*pnext)->flags() & elfcpp::SHF_TLS) != 0)
2901             {
2902               seg_flags = Layout::section_flags_to_segment((*pnext)->flags());
2903               oseg->add_output_section(*pnext, seg_flags);
2904               p = pnext;
2905               ++pnext;
2906             }
2907
2908           saw_tls = true;
2909         }
2910     }
2911 }
2912
2913 // Add a program header.  The PHDRS clause is syntactically distinct
2914 // from the SECTIONS clause, but we implement it with the SECTIONS
2915 // support becauase PHDRS is useless if there is no SECTIONS clause.
2916
2917 void
2918 Script_sections::add_phdr(const char* name, size_t namelen, unsigned int type,
2919                           bool includes_filehdr, bool includes_phdrs,
2920                           bool is_flags_valid, unsigned int flags,
2921                           Expression* load_address)
2922 {
2923   if (this->phdrs_elements_ == NULL)
2924     this->phdrs_elements_ = new Phdrs_elements();
2925   this->phdrs_elements_->push_back(new Phdrs_element(name, namelen, type,
2926                                                      includes_filehdr,
2927                                                      includes_phdrs,
2928                                                      is_flags_valid, flags,
2929                                                      load_address));
2930 }
2931
2932 // Return the number of segments we expect to create based on the
2933 // SECTIONS clause.  This is used to implement SIZEOF_HEADERS.
2934
2935 size_t
2936 Script_sections::expected_segment_count(const Layout* layout) const
2937 {
2938   if (this->saw_phdrs_clause())
2939     return this->phdrs_elements_->size();
2940
2941   Layout::Section_list sections;
2942   layout->get_allocated_sections(&sections);
2943
2944   // We assume that we will need two PT_LOAD segments.
2945   size_t ret = 2;
2946
2947   bool saw_note = false;
2948   bool saw_tls = false;
2949   for (Layout::Section_list::const_iterator p = sections.begin();
2950        p != sections.end();
2951        ++p)
2952     {
2953       if ((*p)->type() == elfcpp::SHT_NOTE)
2954         {
2955           // Assume that all note sections will fit into a single
2956           // PT_NOTE segment.
2957           if (!saw_note)
2958             {
2959               ++ret;
2960               saw_note = true;
2961             }
2962         }
2963       else if (((*p)->flags() & elfcpp::SHF_TLS) != 0)
2964         {
2965           // There can only be one PT_TLS segment.
2966           if (!saw_tls)
2967             {
2968               ++ret;
2969               saw_tls = true;
2970             }
2971         }
2972     }
2973
2974   return ret;
2975 }
2976
2977 // Create the segments from a PHDRS clause.  Return the segment which
2978 // should hold the file header and program headers, if any.
2979
2980 Output_segment*
2981 Script_sections::create_segments_from_phdrs_clause(Layout* layout)
2982 {
2983   this->attach_sections_using_phdrs_clause(layout);
2984   return this->set_phdrs_clause_addresses(layout);
2985 }
2986
2987 // Create the segments from the PHDRS clause, and put the output
2988 // sections in them.
2989
2990 void
2991 Script_sections::attach_sections_using_phdrs_clause(Layout* layout)
2992 {
2993   typedef std::map<std::string, Output_segment*> Name_to_segment;
2994   Name_to_segment name_to_segment;
2995   for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
2996        p != this->phdrs_elements_->end();
2997        ++p)
2998     name_to_segment[(*p)->name()] = (*p)->create_segment(layout);
2999
3000   // Walk through the output sections and attach them to segments.
3001   // Output sections in the script which do not list segments are
3002   // attached to the same set of segments as the immediately preceding
3003   // output section.
3004   String_list* phdr_names = NULL;
3005   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
3006        p != this->sections_elements_->end();
3007        ++p)
3008     {
3009       bool orphan;
3010       Output_section* os = (*p)->allocate_to_segment(&phdr_names, &orphan);
3011       if (os == NULL)
3012         continue;
3013
3014       if (phdr_names == NULL)
3015         {
3016           gold_error(_("allocated section not in any segment"));
3017           continue;
3018         }
3019
3020       // If this is an orphan section--one that was not explicitly
3021       // mentioned in the linker script--then it should not inherit
3022       // any segment type other than PT_LOAD.  Otherwise, e.g., the
3023       // PT_INTERP segment will pick up following orphan sections,
3024       // which does not make sense.  If this is not an orphan section,
3025       // we trust the linker script.
3026       if (orphan)
3027         {
3028           String_list::iterator q = phdr_names->begin();
3029           while (q != phdr_names->end())
3030             {
3031               Name_to_segment::const_iterator r = name_to_segment.find(*q);
3032               // We give errors about unknown segments below.
3033               if (r == name_to_segment.end()
3034                   || r->second->type() == elfcpp::PT_LOAD)
3035                 ++q;
3036               else
3037                 q = phdr_names->erase(q);
3038             }
3039         }
3040
3041       bool in_load_segment = false;
3042       for (String_list::const_iterator q = phdr_names->begin();
3043            q != phdr_names->end();
3044            ++q)
3045         {
3046           Name_to_segment::const_iterator r = name_to_segment.find(*q);
3047           if (r == name_to_segment.end())
3048             gold_error(_("no segment %s"), q->c_str());
3049           else
3050             {
3051               elfcpp::Elf_Word seg_flags =
3052                 Layout::section_flags_to_segment(os->flags());
3053               r->second->add_output_section(os, seg_flags);
3054
3055               if (r->second->type() == elfcpp::PT_LOAD)
3056                 {
3057                   if (in_load_segment)
3058                     gold_error(_("section in two PT_LOAD segments"));
3059                   in_load_segment = true;
3060                 }
3061             }
3062         }
3063
3064       if (!in_load_segment)
3065         gold_error(_("allocated section not in any PT_LOAD segment"));
3066     }
3067 }
3068
3069 // Set the addresses for segments created from a PHDRS clause.  Return
3070 // the segment which should hold the file header and program headers,
3071 // if any.
3072
3073 Output_segment*
3074 Script_sections::set_phdrs_clause_addresses(Layout* layout)
3075 {
3076   Output_segment* load_seg = NULL;
3077   for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
3078        p != this->phdrs_elements_->end();
3079        ++p)
3080     {
3081       // Note that we have to set the flags after adding the output
3082       // sections to the segment, as adding an output segment can
3083       // change the flags.
3084       (*p)->set_flags_if_valid();
3085
3086       Output_segment* oseg = (*p)->segment();
3087
3088       if (oseg->type() != elfcpp::PT_LOAD)
3089         {
3090           // The addresses of non-PT_LOAD segments are set from the
3091           // PT_LOAD segments.
3092           if ((*p)->has_load_address())
3093             gold_error(_("may only specify load address for PT_LOAD segment"));
3094           continue;
3095         }
3096
3097       // The output sections should have addresses from the SECTIONS
3098       // clause.  The addresses don't have to be in order, so find the
3099       // one with the lowest load address.  Use that to set the
3100       // address of the segment.
3101
3102       Output_section* osec = oseg->section_with_lowest_load_address();
3103       if (osec == NULL)
3104         {
3105           oseg->set_addresses(0, 0);
3106           continue;
3107         }
3108
3109       uint64_t vma = osec->address();
3110       uint64_t lma = osec->has_load_address() ? osec->load_address() : vma;
3111
3112       // Override the load address of the section with the load
3113       // address specified for the segment.
3114       if ((*p)->has_load_address())
3115         {
3116           if (osec->has_load_address())
3117             gold_warning(_("PHDRS load address overrides "
3118                            "section %s load address"),
3119                          osec->name());
3120
3121           lma = (*p)->load_address();
3122         }
3123
3124       bool headers = (*p)->includes_filehdr() && (*p)->includes_phdrs();
3125       if (!headers && ((*p)->includes_filehdr() || (*p)->includes_phdrs()))
3126         {
3127           // We could support this if we wanted to.
3128           gold_error(_("using only one of FILEHDR and PHDRS is "
3129                        "not currently supported"));
3130         }
3131       if (headers)
3132         {
3133           size_t sizeof_headers = this->total_header_size(layout);
3134           uint64_t subtract = this->header_size_adjustment(lma,
3135                                                            sizeof_headers);
3136           if (lma >= subtract && vma >= subtract)
3137             {
3138               lma -= subtract;
3139               vma -= subtract;
3140             }
3141           else
3142             {
3143               gold_error(_("sections loaded on first page without room "
3144                            "for file and program headers "
3145                            "are not supported"));
3146             }
3147
3148           if (load_seg != NULL)
3149             gold_error(_("using FILEHDR and PHDRS on more than one "
3150                          "PT_LOAD segment is not currently supported"));
3151           load_seg = oseg;
3152         }
3153
3154       oseg->set_addresses(vma, lma);
3155     }
3156
3157   return load_seg;
3158 }
3159
3160 // Add the file header and segment headers to non-load segments
3161 // specified in the PHDRS clause.
3162
3163 void
3164 Script_sections::put_headers_in_phdrs(Output_data* file_header,
3165                                       Output_data* segment_headers)
3166 {
3167   gold_assert(this->saw_phdrs_clause());
3168   for (Phdrs_elements::iterator p = this->phdrs_elements_->begin();
3169        p != this->phdrs_elements_->end();
3170        ++p)
3171     {
3172       if ((*p)->type() != elfcpp::PT_LOAD)
3173         {
3174           if ((*p)->includes_phdrs())
3175             (*p)->segment()->add_initial_output_data(segment_headers);
3176           if ((*p)->includes_filehdr())
3177             (*p)->segment()->add_initial_output_data(file_header);
3178         }
3179     }
3180 }
3181
3182 // Look for an output section by name and return the address, the load
3183 // address, the alignment, and the size.  This is used when an
3184 // expression refers to an output section which was not actually
3185 // created.  This returns true if the section was found, false
3186 // otherwise.
3187
3188 bool
3189 Script_sections::get_output_section_info(const char* name, uint64_t* address,
3190                                          uint64_t* load_address,
3191                                          uint64_t* addralign,
3192                                          uint64_t* size) const
3193 {
3194   if (!this->saw_sections_clause_)
3195     return false;
3196   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
3197        p != this->sections_elements_->end();
3198        ++p)
3199     if ((*p)->get_output_section_info(name, address, load_address, addralign,
3200                                       size))
3201       return true;
3202   return false;
3203 }
3204
3205 // Print the SECTIONS clause to F for debugging.
3206
3207 void
3208 Script_sections::print(FILE* f) const
3209 {
3210   if (!this->saw_sections_clause_)
3211     return;
3212
3213   fprintf(f, "SECTIONS {\n");
3214
3215   for (Sections_elements::const_iterator p = this->sections_elements_->begin();
3216        p != this->sections_elements_->end();
3217        ++p)
3218     (*p)->print(f);
3219
3220   fprintf(f, "}\n");
3221
3222   if (this->phdrs_elements_ != NULL)
3223     {
3224       fprintf(f, "PHDRS {\n");
3225       for (Phdrs_elements::const_iterator p = this->phdrs_elements_->begin();
3226            p != this->phdrs_elements_->end();
3227            ++p)
3228         (*p)->print(f);
3229       fprintf(f, "}\n");
3230     }
3231 }
3232
3233 } // End namespace gold.