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