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