Fully implement the SECTIONS clause.
[platform/upstream/binutils.git] / gold / script.cc
1 // script.cc -- handle linker scripts for gold.
2
3 // Copyright 2006, 2007, 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 <fnmatch.h>
26 #include <string>
27 #include <vector>
28 #include <cstdio>
29 #include <cstdlib>
30 #include "filenames.h"
31
32 #include "elfcpp.h"
33 #include "demangle.h"
34 #include "dirsearch.h"
35 #include "options.h"
36 #include "fileread.h"
37 #include "workqueue.h"
38 #include "readsyms.h"
39 #include "parameters.h"
40 #include "layout.h"
41 #include "symtab.h"
42 #include "script.h"
43 #include "script-c.h"
44
45 namespace gold
46 {
47
48 // A token read from a script file.  We don't implement keywords here;
49 // all keywords are simply represented as a string.
50
51 class Token
52 {
53  public:
54   // Token classification.
55   enum Classification
56   {
57     // Token is invalid.
58     TOKEN_INVALID,
59     // Token indicates end of input.
60     TOKEN_EOF,
61     // Token is a string of characters.
62     TOKEN_STRING,
63     // Token is a quoted string of characters.
64     TOKEN_QUOTED_STRING,
65     // Token is an operator.
66     TOKEN_OPERATOR,
67     // Token is a number (an integer).
68     TOKEN_INTEGER
69   };
70
71   // We need an empty constructor so that we can put this STL objects.
72   Token()
73     : classification_(TOKEN_INVALID), value_(NULL), value_length_(0),
74       opcode_(0), lineno_(0), charpos_(0)
75   { }
76
77   // A general token with no value.
78   Token(Classification classification, int lineno, int charpos)
79     : classification_(classification), value_(NULL), value_length_(0),
80       opcode_(0), lineno_(lineno), charpos_(charpos)
81   {
82     gold_assert(classification == TOKEN_INVALID
83                 || classification == TOKEN_EOF);
84   }
85
86   // A general token with a value.
87   Token(Classification classification, const char* value, size_t length,
88         int lineno, int charpos)
89     : classification_(classification), value_(value), value_length_(length),
90       opcode_(0), lineno_(lineno), charpos_(charpos)
91   {
92     gold_assert(classification != TOKEN_INVALID
93                 && classification != TOKEN_EOF);
94   }
95
96   // A token representing an operator.
97   Token(int opcode, int lineno, int charpos)
98     : classification_(TOKEN_OPERATOR), value_(NULL), value_length_(0),
99       opcode_(opcode), lineno_(lineno), charpos_(charpos)
100   { }
101
102   // Return whether the token is invalid.
103   bool
104   is_invalid() const
105   { return this->classification_ == TOKEN_INVALID; }
106
107   // Return whether this is an EOF token.
108   bool
109   is_eof() const
110   { return this->classification_ == TOKEN_EOF; }
111
112   // Return the token classification.
113   Classification
114   classification() const
115   { return this->classification_; }
116
117   // Return the line number at which the token starts.
118   int
119   lineno() const
120   { return this->lineno_; }
121
122   // Return the character position at this the token starts.
123   int
124   charpos() const
125   { return this->charpos_; }
126
127   // Get the value of a token.
128
129   const char*
130   string_value(size_t* length) const
131   {
132     gold_assert(this->classification_ == TOKEN_STRING
133                 || this->classification_ == TOKEN_QUOTED_STRING);
134     *length = this->value_length_;
135     return this->value_;
136   }
137
138   int
139   operator_value() const
140   {
141     gold_assert(this->classification_ == TOKEN_OPERATOR);
142     return this->opcode_;
143   }
144
145   uint64_t
146   integer_value() const
147   {
148     gold_assert(this->classification_ == TOKEN_INTEGER);
149     // Null terminate.
150     std::string s(this->value_, this->value_length_);
151     return strtoull(s.c_str(), NULL, 0);
152   }
153
154  private:
155   // The token classification.
156   Classification classification_;
157   // The token value, for TOKEN_STRING or TOKEN_QUOTED_STRING or
158   // TOKEN_INTEGER.
159   const char* value_;
160   // The length of the token value.
161   size_t value_length_;
162   // The token value, for TOKEN_OPERATOR.
163   int opcode_;
164   // The line number where this token started (one based).
165   int lineno_;
166   // The character position within the line where this token started
167   // (one based).
168   int charpos_;
169 };
170
171 // This class handles lexing a file into a sequence of tokens.
172
173 class Lex
174 {
175  public:
176   // We unfortunately have to support different lexing modes, because
177   // when reading different parts of a linker script we need to parse
178   // things differently.
179   enum Mode
180   {
181     // Reading an ordinary linker script.
182     LINKER_SCRIPT,
183     // Reading an expression in a linker script.
184     EXPRESSION,
185     // Reading a version script.
186     VERSION_SCRIPT
187   };
188
189   Lex(const char* input_string, size_t input_length, int parsing_token)
190     : input_string_(input_string), input_length_(input_length),
191       current_(input_string), mode_(LINKER_SCRIPT),
192       first_token_(parsing_token), token_(),
193       lineno_(1), linestart_(input_string)
194   { }
195
196   // Read a file into a string.
197   static void
198   read_file(Input_file*, std::string*);
199
200   // Return the next token.
201   const Token*
202   next_token();
203
204   // Return the current lexing mode.
205   Lex::Mode
206   mode() const
207   { return this->mode_; }
208
209   // Set the lexing mode.
210   void
211   set_mode(Mode mode)
212   { this->mode_ = mode; }
213
214  private:
215   Lex(const Lex&);
216   Lex& operator=(const Lex&);
217
218   // Make a general token with no value at the current location.
219   Token
220   make_token(Token::Classification c, const char* start) const
221   { return Token(c, this->lineno_, start - this->linestart_ + 1); }
222
223   // Make a general token with a value at the current location.
224   Token
225   make_token(Token::Classification c, const char* v, size_t len,
226              const char* start)
227     const
228   { return Token(c, v, len, this->lineno_, start - this->linestart_ + 1); }
229
230   // Make an operator token at the current location.
231   Token
232   make_token(int opcode, const char* start) const
233   { return Token(opcode, this->lineno_, start - this->linestart_ + 1); }
234
235   // Make an invalid token at the current location.
236   Token
237   make_invalid_token(const char* start)
238   { return this->make_token(Token::TOKEN_INVALID, start); }
239
240   // Make an EOF token at the current location.
241   Token
242   make_eof_token(const char* start)
243   { return this->make_token(Token::TOKEN_EOF, start); }
244
245   // Return whether C can be the first character in a name.  C2 is the
246   // next character, since we sometimes need that.
247   inline bool
248   can_start_name(char c, char c2);
249
250   // If C can appear in a name which has already started, return a
251   // pointer to a character later in the token or just past
252   // it. Otherwise, return NULL.
253   inline const char*
254   can_continue_name(const char* c);
255
256   // Return whether C, C2, C3 can start a hex number.
257   inline bool
258   can_start_hex(char c, char c2, char c3);
259
260   // If C can appear in a hex number which has already started, return
261   // a pointer to a character later in the token or just past
262   // it. Otherwise, return NULL.
263   inline const char*
264   can_continue_hex(const char* c);
265
266   // Return whether C can start a non-hex number.
267   static inline bool
268   can_start_number(char c);
269
270   // If C can appear in a decimal number which has already started,
271   // return a pointer to a character later in the token or just past
272   // it. Otherwise, return NULL.
273   inline const char*
274   can_continue_number(const char* c)
275   { return Lex::can_start_number(*c) ? c + 1 : NULL; }
276
277   // If C1 C2 C3 form a valid three character operator, return the
278   // opcode.  Otherwise return 0.
279   static inline int
280   three_char_operator(char c1, char c2, char c3);
281
282   // If C1 C2 form a valid two character operator, return the opcode.
283   // Otherwise return 0.
284   static inline int
285   two_char_operator(char c1, char c2);
286
287   // If C1 is a valid one character operator, return the opcode.
288   // Otherwise return 0.
289   static inline int
290   one_char_operator(char c1);
291
292   // Read the next token.
293   Token
294   get_token(const char**);
295
296   // Skip a C style /* */ comment.  Return false if the comment did
297   // not end.
298   bool
299   skip_c_comment(const char**);
300
301   // Skip a line # comment.  Return false if there was no newline.
302   bool
303   skip_line_comment(const char**);
304
305   // Build a token CLASSIFICATION from all characters that match
306   // CAN_CONTINUE_FN.  The token starts at START.  Start matching from
307   // MATCH.  Set *PP to the character following the token.
308   inline Token
309   gather_token(Token::Classification,
310                const char* (Lex::*can_continue_fn)(const char*),
311                const char* start, const char* match, const char** pp);
312
313   // Build a token from a quoted string.
314   Token
315   gather_quoted_string(const char** pp);
316
317   // The string we are tokenizing.
318   const char* input_string_;
319   // The length of the string.
320   size_t input_length_;
321   // The current offset into the string.
322   const char* current_;
323   // The current lexing mode.
324   Mode mode_;
325   // The code to use for the first token.  This is set to 0 after it
326   // is used.
327   int first_token_;
328   // The current token.
329   Token token_;
330   // The current line number.
331   int lineno_;
332   // The start of the current line in the string.
333   const char* linestart_;
334 };
335
336 // Read the whole file into memory.  We don't expect linker scripts to
337 // be large, so we just use a std::string as a buffer.  We ignore the
338 // data we've already read, so that we read aligned buffers.
339
340 void
341 Lex::read_file(Input_file* input_file, std::string* contents)
342 {
343   off_t filesize = input_file->file().filesize();
344   contents->clear();
345   contents->reserve(filesize);
346
347   off_t off = 0;
348   unsigned char buf[BUFSIZ];
349   while (off < filesize)
350     {
351       off_t get = BUFSIZ;
352       if (get > filesize - off)
353         get = filesize - off;
354       input_file->file().read(off, get, buf);
355       contents->append(reinterpret_cast<char*>(&buf[0]), get);
356       off += get;
357     }
358 }
359
360 // Return whether C can be the start of a name, if the next character
361 // is C2.  A name can being with a letter, underscore, period, or
362 // dollar sign.  Because a name can be a file name, we also permit
363 // forward slash, backslash, and tilde.  Tilde is the tricky case
364 // here; GNU ld also uses it as a bitwise not operator.  It is only
365 // recognized as the operator if it is not immediately followed by
366 // some character which can appear in a symbol.  That is, when we
367 // don't know that we are looking at an expression, "~0" is a file
368 // name, and "~ 0" is an expression using bitwise not.  We are
369 // compatible.
370
371 inline bool
372 Lex::can_start_name(char c, char c2)
373 {
374   switch (c)
375     {
376     case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
377     case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
378     case 'M': case 'N': case 'O': case 'Q': case 'P': case 'R':
379     case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
380     case 'Y': case 'Z':
381     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
382     case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
383     case 'm': case 'n': case 'o': case 'q': case 'p': case 'r':
384     case 's': case 't': case 'u': case 'v': case 'w': case 'x':
385     case 'y': case 'z':
386     case '_': case '.': case '$':
387       return true;
388
389     case '/': case '\\':
390       return this->mode_ == LINKER_SCRIPT;
391
392     case '~':
393       return this->mode_ == LINKER_SCRIPT && can_continue_name(&c2);
394
395     case '*': case '[': 
396       return this->mode_ == VERSION_SCRIPT;
397
398     default:
399       return false;
400     }
401 }
402
403 // Return whether C can continue a name which has already started.
404 // Subsequent characters in a name are the same as the leading
405 // characters, plus digits and "=+-:[],?*".  So in general the linker
406 // script language requires spaces around operators, unless we know
407 // that we are parsing an expression.
408
409 inline const char*
410 Lex::can_continue_name(const char* c)
411 {
412   switch (*c)
413     {
414     case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
415     case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
416     case 'M': case 'N': case 'O': case 'Q': case 'P': case 'R':
417     case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
418     case 'Y': case 'Z':
419     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
420     case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
421     case 'm': case 'n': case 'o': case 'q': case 'p': case 'r':
422     case 's': case 't': case 'u': case 'v': case 'w': case 'x':
423     case 'y': case 'z':
424     case '_': case '.': case '$':
425     case '0': case '1': case '2': case '3': case '4':
426     case '5': case '6': case '7': case '8': case '9':
427       return c + 1;
428
429     case '/': case '\\': case '~':
430     case '=': case '+':
431     case ',': case '?': 
432       if (this->mode_ == LINKER_SCRIPT)
433         return c + 1;
434       return NULL;
435
436     case '[': case ']': case '*': case '-':
437       if (this->mode_ == LINKER_SCRIPT || this->mode_ == VERSION_SCRIPT)
438         return c + 1;
439       return NULL;
440
441     case '^':
442       if (this->mode_ == VERSION_SCRIPT)
443         return c + 1;
444       return NULL;
445
446     case ':':
447       if (this->mode_ == LINKER_SCRIPT)
448         return c + 1;
449       else if (this->mode_ == VERSION_SCRIPT && (c[1] == ':'))
450         {
451           // A name can have '::' in it, as that's a c++ namespace
452           // separator. But a single colon is not part of a name.
453           return c + 2;
454         }
455       return NULL;
456
457     default:
458       return NULL;
459     }
460 }
461
462 // For a number we accept 0x followed by hex digits, or any sequence
463 // of digits.  The old linker accepts leading '$' for hex, and
464 // trailing HXBOD.  Those are for MRI compatibility and we don't
465 // accept them.  The old linker also accepts trailing MK for mega or
466 // kilo.  FIXME: Those are mentioned in the documentation, and we
467 // should accept them.
468
469 // Return whether C1 C2 C3 can start a hex number.
470
471 inline bool
472 Lex::can_start_hex(char c1, char c2, char c3)
473 {
474   if (c1 == '0' && (c2 == 'x' || c2 == 'X'))
475     return this->can_continue_hex(&c3);
476   return false;
477 }
478
479 // Return whether C can appear in a hex number.
480
481 inline const char*
482 Lex::can_continue_hex(const char* c)
483 {
484   switch (*c)
485     {
486     case '0': case '1': case '2': case '3': case '4':
487     case '5': case '6': case '7': case '8': case '9':
488     case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
489     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
490       return c + 1;
491
492     default:
493       return NULL;
494     }
495 }
496
497 // Return whether C can start a non-hex number.
498
499 inline bool
500 Lex::can_start_number(char c)
501 {
502   switch (c)
503     {
504     case '0': case '1': case '2': case '3': case '4':
505     case '5': case '6': case '7': case '8': case '9':
506       return true;
507
508     default:
509       return false;
510     }
511 }
512
513 // If C1 C2 C3 form a valid three character operator, return the
514 // opcode (defined in the yyscript.h file generated from yyscript.y).
515 // Otherwise return 0.
516
517 inline int
518 Lex::three_char_operator(char c1, char c2, char c3)
519 {
520   switch (c1)
521     {
522     case '<':
523       if (c2 == '<' && c3 == '=')
524         return LSHIFTEQ;
525       break;
526     case '>':
527       if (c2 == '>' && c3 == '=')
528         return RSHIFTEQ;
529       break;
530     default:
531       break;
532     }
533   return 0;
534 }
535
536 // If C1 C2 form a valid two character operator, return the opcode
537 // (defined in the yyscript.h file generated from yyscript.y).
538 // Otherwise return 0.
539
540 inline int
541 Lex::two_char_operator(char c1, char c2)
542 {
543   switch (c1)
544     {
545     case '=':
546       if (c2 == '=')
547         return EQ;
548       break;
549     case '!':
550       if (c2 == '=')
551         return NE;
552       break;
553     case '+':
554       if (c2 == '=')
555         return PLUSEQ;
556       break;
557     case '-':
558       if (c2 == '=')
559         return MINUSEQ;
560       break;
561     case '*':
562       if (c2 == '=')
563         return MULTEQ;
564       break;
565     case '/':
566       if (c2 == '=')
567         return DIVEQ;
568       break;
569     case '|':
570       if (c2 == '=')
571         return OREQ;
572       if (c2 == '|')
573         return OROR;
574       break;
575     case '&':
576       if (c2 == '=')
577         return ANDEQ;
578       if (c2 == '&')
579         return ANDAND;
580       break;
581     case '>':
582       if (c2 == '=')
583         return GE;
584       if (c2 == '>')
585         return RSHIFT;
586       break;
587     case '<':
588       if (c2 == '=')
589         return LE;
590       if (c2 == '<')
591         return LSHIFT;
592       break;
593     default:
594       break;
595     }
596   return 0;
597 }
598
599 // If C1 is a valid operator, return the opcode.  Otherwise return 0.
600
601 inline int
602 Lex::one_char_operator(char c1)
603 {
604   switch (c1)
605     {
606     case '+':
607     case '-':
608     case '*':
609     case '/':
610     case '%':
611     case '!':
612     case '&':
613     case '|':
614     case '^':
615     case '~':
616     case '<':
617     case '>':
618     case '=':
619     case '?':
620     case ',':
621     case '(':
622     case ')':
623     case '{':
624     case '}':
625     case '[':
626     case ']':
627     case ':':
628     case ';':
629       return c1;
630     default:
631       return 0;
632     }
633 }
634
635 // Skip a C style comment.  *PP points to just after the "/*".  Return
636 // false if the comment did not end.
637
638 bool
639 Lex::skip_c_comment(const char** pp)
640 {
641   const char* p = *pp;
642   while (p[0] != '*' || p[1] != '/')
643     {
644       if (*p == '\0')
645         {
646           *pp = p;
647           return false;
648         }
649
650       if (*p == '\n')
651         {
652           ++this->lineno_;
653           this->linestart_ = p + 1;
654         }
655       ++p;
656     }
657
658   *pp = p + 2;
659   return true;
660 }
661
662 // Skip a line # comment.  Return false if there was no newline.
663
664 bool
665 Lex::skip_line_comment(const char** pp)
666 {
667   const char* p = *pp;
668   size_t skip = strcspn(p, "\n");
669   if (p[skip] == '\0')
670     {
671       *pp = p + skip;
672       return false;
673     }
674
675   p += skip + 1;
676   ++this->lineno_;
677   this->linestart_ = p;
678   *pp = p;
679
680   return true;
681 }
682
683 // Build a token CLASSIFICATION from all characters that match
684 // CAN_CONTINUE_FN.  Update *PP.
685
686 inline Token
687 Lex::gather_token(Token::Classification classification,
688                   const char* (Lex::*can_continue_fn)(const char*),
689                   const char* start,
690                   const char* match,
691                   const char **pp)
692 {
693   const char* new_match = NULL;
694   while ((new_match = (this->*can_continue_fn)(match)))
695     match = new_match;
696   *pp = match;
697   return this->make_token(classification, start, match - start, start);
698 }
699
700 // Build a token from a quoted string.
701
702 Token
703 Lex::gather_quoted_string(const char** pp)
704 {
705   const char* start = *pp;
706   const char* p = start;
707   ++p;
708   size_t skip = strcspn(p, "\"\n");
709   if (p[skip] != '"')
710     return this->make_invalid_token(start);
711   *pp = p + skip + 1;
712   return this->make_token(Token::TOKEN_QUOTED_STRING, p, skip, start);
713 }
714
715 // Return the next token at *PP.  Update *PP.  General guideline: we
716 // require linker scripts to be simple ASCII.  No unicode linker
717 // scripts.  In particular we can assume that any '\0' is the end of
718 // the input.
719
720 Token
721 Lex::get_token(const char** pp)
722 {
723   const char* p = *pp;
724
725   while (true)
726     {
727       if (*p == '\0')
728         {
729           *pp = p;
730           return this->make_eof_token(p);
731         }
732
733       // Skip whitespace quickly.
734       while (*p == ' ' || *p == '\t')
735         ++p;
736
737       if (*p == '\n')
738         {
739           ++p;
740           ++this->lineno_;
741           this->linestart_ = p;
742           continue;
743         }
744
745       // Skip C style comments.
746       if (p[0] == '/' && p[1] == '*')
747         {
748           int lineno = this->lineno_;
749           int charpos = p - this->linestart_ + 1;
750
751           *pp = p + 2;
752           if (!this->skip_c_comment(pp))
753             return Token(Token::TOKEN_INVALID, lineno, charpos);
754           p = *pp;
755
756           continue;
757         }
758
759       // Skip line comments.
760       if (*p == '#')
761         {
762           *pp = p + 1;
763           if (!this->skip_line_comment(pp))
764             return this->make_eof_token(p);
765           p = *pp;
766           continue;
767         }
768
769       // Check for a name.
770       if (this->can_start_name(p[0], p[1]))
771         return this->gather_token(Token::TOKEN_STRING,
772                                   &Lex::can_continue_name,
773                                   p, p + 1, pp);
774
775       // We accept any arbitrary name in double quotes, as long as it
776       // does not cross a line boundary.
777       if (*p == '"')
778         {
779           *pp = p;
780           return this->gather_quoted_string(pp);
781         }
782
783       // Check for a number.
784
785       if (this->can_start_hex(p[0], p[1], p[2]))
786         return this->gather_token(Token::TOKEN_INTEGER,
787                                   &Lex::can_continue_hex,
788                                   p, p + 3, pp);
789
790       if (Lex::can_start_number(p[0]))
791         return this->gather_token(Token::TOKEN_INTEGER,
792                                   &Lex::can_continue_number,
793                                   p, p + 1, pp);
794
795       // Check for operators.
796
797       int opcode = Lex::three_char_operator(p[0], p[1], p[2]);
798       if (opcode != 0)
799         {
800           *pp = p + 3;
801           return this->make_token(opcode, p);
802         }
803
804       opcode = Lex::two_char_operator(p[0], p[1]);
805       if (opcode != 0)
806         {
807           *pp = p + 2;
808           return this->make_token(opcode, p);
809         }
810
811       opcode = Lex::one_char_operator(p[0]);
812       if (opcode != 0)
813         {
814           *pp = p + 1;
815           return this->make_token(opcode, p);
816         }
817
818       return this->make_token(Token::TOKEN_INVALID, p);
819     }
820 }
821
822 // Return the next token.
823
824 const Token*
825 Lex::next_token()
826 {
827   // The first token is special.
828   if (this->first_token_ != 0)
829     {
830       this->token_ = Token(this->first_token_, 0, 0);
831       this->first_token_ = 0;
832       return &this->token_;
833     }
834
835   this->token_ = this->get_token(&this->current_);
836
837   // Don't let an early null byte fool us into thinking that we've
838   // reached the end of the file.
839   if (this->token_.is_eof()
840       && (static_cast<size_t>(this->current_ - this->input_string_)
841           < this->input_length_))
842     this->token_ = this->make_invalid_token(this->current_);
843
844   return &this->token_;
845 }
846
847 // A trivial task which waits for THIS_BLOCKER to be clear and then
848 // clears NEXT_BLOCKER.  THIS_BLOCKER may be NULL.
849
850 class Script_unblock : public Task
851 {
852  public:
853   Script_unblock(Task_token* this_blocker, Task_token* next_blocker)
854     : this_blocker_(this_blocker), next_blocker_(next_blocker)
855   { }
856
857   ~Script_unblock()
858   {
859     if (this->this_blocker_ != NULL)
860       delete this->this_blocker_;
861   }
862
863   Task_token*
864   is_runnable()
865   {
866     if (this->this_blocker_ != NULL && this->this_blocker_->is_blocked())
867       return this->this_blocker_;
868     return NULL;
869   }
870
871   void
872   locks(Task_locker* tl)
873   { tl->add(this, this->next_blocker_); }
874
875   void
876   run(Workqueue*)
877   { }
878
879   std::string
880   get_name() const
881   { return "Script_unblock"; }
882
883  private:
884   Task_token* this_blocker_;
885   Task_token* next_blocker_;
886 };
887
888 // class Symbol_assignment.
889
890 // Add the symbol to the symbol table.  This makes sure the symbol is
891 // there and defined.  The actual value is stored later.  We can't
892 // determine the actual value at this point, because we can't
893 // necessarily evaluate the expression until all ordinary symbols have
894 // been finalized.
895
896 void
897 Symbol_assignment::add_to_table(Symbol_table* symtab)
898 {
899   elfcpp::STV vis = this->hidden_ ? elfcpp::STV_HIDDEN : elfcpp::STV_DEFAULT;
900   this->sym_ = symtab->define_as_constant(this->name_.c_str(),
901                                           NULL, // version
902                                           0, // value
903                                           0, // size
904                                           elfcpp::STT_NOTYPE,
905                                           elfcpp::STB_GLOBAL,
906                                           vis,
907                                           0, // nonvis
908                                           this->provide_);
909 }
910
911 // Finalize a symbol value.
912
913 void
914 Symbol_assignment::finalize(Symbol_table* symtab, const Layout* layout)
915 {
916   this->finalize_maybe_dot(symtab, layout, false, false, 0);
917 }
918
919 // Finalize a symbol value which can refer to the dot symbol.
920
921 void
922 Symbol_assignment::finalize_with_dot(Symbol_table* symtab,
923                                      const Layout* layout,
924                                      bool dot_has_value,
925                                      uint64_t dot_value)
926 {
927   this->finalize_maybe_dot(symtab, layout, true, dot_has_value, dot_value);
928 }
929
930 // Finalize a symbol value, internal version.
931
932 void
933 Symbol_assignment::finalize_maybe_dot(Symbol_table* symtab,
934                                       const Layout* layout,
935                                       bool is_dot_available,
936                                       bool dot_has_value,
937                                       uint64_t dot_value)
938 {
939   // If we were only supposed to provide this symbol, the sym_ field
940   // will be NULL if the symbol was not referenced.
941   if (this->sym_ == NULL)
942     {
943       gold_assert(this->provide_);
944       return;
945     }
946
947   if (parameters->get_size() == 32)
948     {
949 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
950       this->sized_finalize<32>(symtab, layout, is_dot_available, dot_has_value,
951                                dot_value);
952 #else
953       gold_unreachable();
954 #endif
955     }
956   else if (parameters->get_size() == 64)
957     {
958 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
959       this->sized_finalize<64>(symtab, layout, is_dot_available, dot_has_value,
960                                dot_value);
961 #else
962       gold_unreachable();
963 #endif
964     }
965   else
966     gold_unreachable();
967 }
968
969 template<int size>
970 void
971 Symbol_assignment::sized_finalize(Symbol_table* symtab, const Layout* layout,
972                                   bool is_dot_available, bool dot_has_value,
973                                   uint64_t dot_value)
974 {
975   bool dummy;
976   uint64_t final_val = this->val_->eval_maybe_dot(symtab, layout,
977                                                   is_dot_available,
978                                                   dot_has_value, dot_value,
979                                                   &dummy);
980   Sized_symbol<size>* ssym = symtab->get_sized_symbol<size>(this->sym_);
981   ssym->set_value(final_val);
982 }
983
984 // Set the symbol value if the expression yields an absolute value.
985
986 void
987 Symbol_assignment::set_if_absolute(Symbol_table* symtab, const Layout* layout,
988                                    bool is_dot_available, bool dot_has_value,
989                                    uint64_t dot_value)
990 {
991   if (this->sym_ == NULL)
992     return;
993
994   bool is_absolute;
995   uint64_t val = this->val_->eval_maybe_dot(symtab, layout, is_dot_available,
996                                             dot_has_value, dot_value,
997                                             &is_absolute);
998   if (!is_absolute)
999     return;
1000
1001   if (parameters->get_size() == 32)
1002     {
1003 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1004       Sized_symbol<32>* ssym = symtab->get_sized_symbol<32>(this->sym_);
1005       ssym->set_value(val);
1006 #else
1007       gold_unreachable();
1008 #endif
1009     }
1010   else if (parameters->get_size() == 64)
1011     {
1012 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1013       Sized_symbol<64>* ssym = symtab->get_sized_symbol<64>(this->sym_);
1014       ssym->set_value(val);
1015 #else
1016       gold_unreachable();
1017 #endif
1018     }
1019   else
1020     gold_unreachable();
1021 }
1022
1023 // Print for debugging.
1024
1025 void
1026 Symbol_assignment::print(FILE* f) const
1027 {
1028   if (this->provide_ && this->hidden_)
1029     fprintf(f, "PROVIDE_HIDDEN(");
1030   else if (this->provide_)
1031     fprintf(f, "PROVIDE(");
1032   else if (this->hidden_)
1033     gold_unreachable();
1034
1035   fprintf(f, "%s = ", this->name_.c_str());
1036   this->val_->print(f);
1037
1038   if (this->provide_ || this->hidden_)
1039     fprintf(f, ")");
1040
1041   fprintf(f, "\n");
1042 }
1043
1044 // Class Script_assertion.
1045
1046 // Check the assertion.
1047
1048 void
1049 Script_assertion::check(const Symbol_table* symtab, const Layout* layout)
1050 {
1051   if (!this->check_->eval(symtab, layout))
1052     gold_error("%s", this->message_.c_str());
1053 }
1054
1055 // Print for debugging.
1056
1057 void
1058 Script_assertion::print(FILE* f) const
1059 {
1060   fprintf(f, "ASSERT(");
1061   this->check_->print(f);
1062   fprintf(f, ", \"%s\")\n", this->message_.c_str());
1063 }
1064
1065 // Class Script_options.
1066
1067 Script_options::Script_options()
1068   : entry_(), symbol_assignments_(), version_script_info_(),
1069     script_sections_()
1070 {
1071 }
1072
1073 // Add a symbol to be defined.
1074
1075 void
1076 Script_options::add_symbol_assignment(const char* name, size_t length,
1077                                       Expression* value, bool provide,
1078                                       bool hidden)
1079 {
1080   if (length != 1 || name[0] != '.')
1081     {
1082       if (this->script_sections_.in_sections_clause())
1083         this->script_sections_.add_symbol_assignment(name, length, value,
1084                                                      provide, hidden);
1085       else
1086         {
1087           Symbol_assignment* p = new Symbol_assignment(name, length, value,
1088                                                        provide, hidden);
1089           this->symbol_assignments_.push_back(p);
1090         }
1091     }
1092   else
1093     {
1094       if (provide || hidden)
1095         gold_error(_("invalid use of PROVIDE for dot symbol"));
1096       if (!this->script_sections_.in_sections_clause())
1097         gold_error(_("invalid assignment to dot outside of SECTIONS"));
1098       else
1099         this->script_sections_.add_dot_assignment(value);
1100     }
1101 }
1102
1103 // Add an assertion.
1104
1105 void
1106 Script_options::add_assertion(Expression* check, const char* message,
1107                               size_t messagelen)
1108 {
1109   if (this->script_sections_.in_sections_clause())
1110     this->script_sections_.add_assertion(check, message, messagelen);
1111   else
1112     {
1113       Script_assertion* p = new Script_assertion(check, message, messagelen);
1114       this->assertions_.push_back(p);
1115     }
1116 }
1117
1118 // Add any symbols we are defining to the symbol table.
1119
1120 void
1121 Script_options::add_symbols_to_table(Symbol_table* symtab)
1122 {
1123   for (Symbol_assignments::iterator p = this->symbol_assignments_.begin();
1124        p != this->symbol_assignments_.end();
1125        ++p)
1126     (*p)->add_to_table(symtab);
1127   this->script_sections_.add_symbols_to_table(symtab);
1128 }
1129
1130 // Finalize symbol values.  Also check assertions.
1131
1132 void
1133 Script_options::finalize_symbols(Symbol_table* symtab, const Layout* layout)
1134 {
1135   for (Symbol_assignments::iterator p = this->symbol_assignments_.begin();
1136        p != this->symbol_assignments_.end();
1137        ++p)
1138     (*p)->finalize(symtab, layout);
1139
1140   for (Assertions::iterator p = this->assertions_.begin();
1141        p != this->assertions_.end();
1142        ++p)
1143     (*p)->check(symtab, layout);
1144
1145   this->script_sections_.finalize_symbols(symtab, layout);
1146 }
1147
1148 // Set section addresses.  We set all the symbols which have absolute
1149 // values.  Then we let the SECTIONS clause do its thing.  This
1150 // returns the segment which holds the file header and segment
1151 // headers, if any.
1152
1153 Output_segment*
1154 Script_options::set_section_addresses(Symbol_table* symtab, Layout* layout)
1155 {
1156   for (Symbol_assignments::iterator p = this->symbol_assignments_.begin();
1157        p != this->symbol_assignments_.end();
1158        ++p)
1159     (*p)->set_if_absolute(symtab, layout, false, false, 0);
1160
1161   return this->script_sections_.set_section_addresses(symtab, layout);
1162 }
1163
1164 // This class holds data passed through the parser to the lexer and to
1165 // the parser support functions.  This avoids global variables.  We
1166 // can't use global variables because we need not be called by a
1167 // singleton thread.
1168
1169 class Parser_closure
1170 {
1171  public:
1172   Parser_closure(const char* filename,
1173                  const Position_dependent_options& posdep_options,
1174                  bool in_group, bool is_in_sysroot,
1175                  Command_line* command_line,
1176                  Script_options* script_options,
1177                  Lex* lex)
1178     : filename_(filename), posdep_options_(posdep_options),
1179       in_group_(in_group), is_in_sysroot_(is_in_sysroot),
1180       command_line_(command_line), script_options_(script_options),
1181       version_script_info_(script_options->version_script_info()),
1182       lex_(lex), lineno_(0), charpos_(0), lex_mode_stack_(), inputs_(NULL)
1183   { 
1184     // We start out processing C symbols in the default lex mode.
1185     language_stack_.push_back("");
1186     lex_mode_stack_.push_back(lex->mode());
1187   }
1188
1189   // Return the file name.
1190   const char*
1191   filename() const
1192   { return this->filename_; }
1193
1194   // Return the position dependent options.  The caller may modify
1195   // this.
1196   Position_dependent_options&
1197   position_dependent_options()
1198   { return this->posdep_options_; }
1199
1200   // Return whether this script is being run in a group.
1201   bool
1202   in_group() const
1203   { return this->in_group_; }
1204
1205   // Return whether this script was found using a directory in the
1206   // sysroot.
1207   bool
1208   is_in_sysroot() const
1209   { return this->is_in_sysroot_; }
1210
1211   // Returns the Command_line structure passed in at constructor time.
1212   // This value may be NULL.  The caller may modify this, which modifies
1213   // the passed-in Command_line object (not a copy).
1214   Command_line*
1215   command_line()
1216   { return this->command_line_; }
1217
1218   // Return the options which may be set by a script.
1219   Script_options*
1220   script_options()
1221   { return this->script_options_; }
1222
1223   // Return the object in which version script information should be stored.
1224   Version_script_info*
1225   version_script()
1226   { return this->version_script_info_; }
1227
1228   // Return the next token, and advance.
1229   const Token*
1230   next_token()
1231   {
1232     const Token* token = this->lex_->next_token();
1233     this->lineno_ = token->lineno();
1234     this->charpos_ = token->charpos();
1235     return token;
1236   }
1237
1238   // Set a new lexer mode, pushing the current one.
1239   void
1240   push_lex_mode(Lex::Mode mode)
1241   {
1242     this->lex_mode_stack_.push_back(this->lex_->mode());
1243     this->lex_->set_mode(mode);
1244   }
1245
1246   // Pop the lexer mode.
1247   void
1248   pop_lex_mode()
1249   {
1250     gold_assert(!this->lex_mode_stack_.empty());
1251     this->lex_->set_mode(this->lex_mode_stack_.back());
1252     this->lex_mode_stack_.pop_back();
1253   }
1254
1255   // Return the current lexer mode.
1256   Lex::Mode
1257   lex_mode() const
1258   { return this->lex_mode_stack_.back(); }
1259
1260   // Return the line number of the last token.
1261   int
1262   lineno() const
1263   { return this->lineno_; }
1264
1265   // Return the character position in the line of the last token.
1266   int
1267   charpos() const
1268   { return this->charpos_; }
1269
1270   // Return the list of input files, creating it if necessary.  This
1271   // is a space leak--we never free the INPUTS_ pointer.
1272   Input_arguments*
1273   inputs()
1274   {
1275     if (this->inputs_ == NULL)
1276       this->inputs_ = new Input_arguments();
1277     return this->inputs_;
1278   }
1279
1280   // Return whether we saw any input files.
1281   bool
1282   saw_inputs() const
1283   { return this->inputs_ != NULL && !this->inputs_->empty(); }
1284
1285   // Return the current language being processed in a version script
1286   // (eg, "C++").  The empty string represents unmangled C names.
1287   const std::string&
1288   get_current_language() const
1289   { return this->language_stack_.back(); }
1290
1291   // Push a language onto the stack when entering an extern block.
1292   void push_language(const std::string& lang)
1293   { this->language_stack_.push_back(lang); }
1294
1295   // Pop a language off of the stack when exiting an extern block.
1296   void pop_language()
1297   {
1298     gold_assert(!this->language_stack_.empty());
1299     this->language_stack_.pop_back();
1300   }
1301
1302  private:
1303   // The name of the file we are reading.
1304   const char* filename_;
1305   // The position dependent options.
1306   Position_dependent_options posdep_options_;
1307   // Whether we are currently in a --start-group/--end-group.
1308   bool in_group_;
1309   // Whether the script was found in a sysrooted directory.
1310   bool is_in_sysroot_;
1311   // May be NULL if the user chooses not to pass one in.
1312   Command_line* command_line_;
1313   // Options which may be set from any linker script.
1314   Script_options* script_options_;
1315   // Information parsed from a version script.
1316   Version_script_info* version_script_info_;
1317   // The lexer.
1318   Lex* lex_;
1319   // The line number of the last token returned by next_token.
1320   int lineno_;
1321   // The column number of the last token returned by next_token.
1322   int charpos_;
1323   // A stack of lexer modes.
1324   std::vector<Lex::Mode> lex_mode_stack_;
1325   // A stack of which extern/language block we're inside. Can be C++,
1326   // java, or empty for C.
1327   std::vector<std::string> language_stack_;
1328   // New input files found to add to the link.
1329   Input_arguments* inputs_;
1330 };
1331
1332 // FILE was found as an argument on the command line.  Try to read it
1333 // as a script.  We've already read BYTES of data into P, but we
1334 // ignore that.  Return true if the file was handled.
1335
1336 bool
1337 read_input_script(Workqueue* workqueue, const General_options& options,
1338                   Symbol_table* symtab, Layout* layout,
1339                   Dirsearch* dirsearch, Input_objects* input_objects,
1340                   Input_group* input_group,
1341                   const Input_argument* input_argument,
1342                   Input_file* input_file, const unsigned char*, off_t,
1343                   Task_token* this_blocker, Task_token* next_blocker)
1344 {
1345   std::string input_string;
1346   Lex::read_file(input_file, &input_string);
1347
1348   Lex lex(input_string.c_str(), input_string.length(), PARSING_LINKER_SCRIPT);
1349
1350   Parser_closure closure(input_file->filename().c_str(),
1351                          input_argument->file().options(),
1352                          input_group != NULL,
1353                          input_file->is_in_sysroot(),
1354                          NULL,
1355                          layout->script_options(),
1356                          &lex);
1357
1358   if (yyparse(&closure) != 0)
1359     return false;
1360
1361   // THIS_BLOCKER must be clear before we may add anything to the
1362   // symbol table.  We are responsible for unblocking NEXT_BLOCKER
1363   // when we are done.  We are responsible for deleting THIS_BLOCKER
1364   // when it is unblocked.
1365
1366   if (!closure.saw_inputs())
1367     {
1368       // The script did not add any files to read.  Note that we are
1369       // not permitted to call NEXT_BLOCKER->unblock() here even if
1370       // THIS_BLOCKER is NULL, as we do not hold the workqueue lock.
1371       workqueue->queue(new Script_unblock(this_blocker, next_blocker));
1372       return true;
1373     }
1374
1375   for (Input_arguments::const_iterator p = closure.inputs()->begin();
1376        p != closure.inputs()->end();
1377        ++p)
1378     {
1379       Task_token* nb;
1380       if (p + 1 == closure.inputs()->end())
1381         nb = next_blocker;
1382       else
1383         {
1384           nb = new Task_token(true);
1385           nb->add_blocker();
1386         }
1387       workqueue->queue(new Read_symbols(options, input_objects, symtab,
1388                                         layout, dirsearch, &*p,
1389                                         input_group, this_blocker, nb));
1390       this_blocker = nb;
1391     }
1392
1393   return true;
1394 }
1395
1396 // Helper function for read_version_script() and
1397 // read_commandline_script().  Processes the given file in the mode
1398 // indicated by first_token and lex_mode.
1399
1400 static bool
1401 read_script_file(const char* filename, Command_line* cmdline,
1402                  int first_token, Lex::Mode lex_mode)
1403 {
1404   // TODO: if filename is a relative filename, search for it manually
1405   // using "." + cmdline->options()->search_path() -- not dirsearch.
1406   Dirsearch dirsearch;
1407
1408   // The file locking code wants to record a Task, but we haven't
1409   // started the workqueue yet.  This is only for debugging purposes,
1410   // so we invent a fake value.
1411   const Task* task = reinterpret_cast<const Task*>(-1);
1412
1413   Input_file_argument input_argument(filename, false, "",
1414                                      cmdline->position_dependent_options());
1415   Input_file input_file(&input_argument);
1416   if (!input_file.open(cmdline->options(), dirsearch, task))
1417     return false;
1418
1419   std::string input_string;
1420   Lex::read_file(&input_file, &input_string);
1421
1422   Lex lex(input_string.c_str(), input_string.length(), first_token);
1423   lex.set_mode(lex_mode);
1424
1425   Parser_closure closure(filename,
1426                          cmdline->position_dependent_options(),
1427                          false,
1428                          input_file.is_in_sysroot(),
1429                          cmdline,
1430                          cmdline->script_options(),
1431                          &lex);
1432   if (yyparse(&closure) != 0)
1433     {
1434       input_file.file().unlock(task);
1435       return false;
1436     }
1437
1438   input_file.file().unlock(task);
1439
1440   gold_assert(!closure.saw_inputs());
1441
1442   return true;
1443 }
1444
1445 // FILENAME was found as an argument to --script (-T).
1446 // Read it as a script, and execute its contents immediately.
1447
1448 bool
1449 read_commandline_script(const char* filename, Command_line* cmdline)
1450 {
1451   return read_script_file(filename, cmdline,
1452                           PARSING_LINKER_SCRIPT, Lex::LINKER_SCRIPT);
1453 }
1454
1455 // FILE was found as an argument to --version-script.  Read it as a
1456 // version script, and store its contents in
1457 // cmdline->script_options()->version_script_info().
1458
1459 bool
1460 read_version_script(const char* filename, Command_line* cmdline)
1461 {
1462   return read_script_file(filename, cmdline,
1463                           PARSING_VERSION_SCRIPT, Lex::VERSION_SCRIPT);
1464 }
1465
1466 // Implement the --defsym option on the command line.  Return true if
1467 // all is well.
1468
1469 bool
1470 Script_options::define_symbol(const char* definition)
1471 {
1472   Lex lex(definition, strlen(definition), PARSING_DEFSYM);
1473   lex.set_mode(Lex::EXPRESSION);
1474
1475   // Dummy value.
1476   Position_dependent_options posdep_options;
1477
1478   Parser_closure closure("command line", posdep_options, false, false, NULL,
1479                          this, &lex);
1480
1481   if (yyparse(&closure) != 0)
1482     return false;
1483
1484   gold_assert(!closure.saw_inputs());
1485
1486   return true;
1487 }
1488
1489 // Print the script to F for debugging.
1490
1491 void
1492 Script_options::print(FILE* f) const
1493 {
1494   fprintf(f, "%s: Dumping linker script\n", program_name);
1495
1496   if (!this->entry_.empty())
1497     fprintf(f, "ENTRY(%s)\n", this->entry_.c_str());
1498
1499   for (Symbol_assignments::const_iterator p =
1500          this->symbol_assignments_.begin();
1501        p != this->symbol_assignments_.end();
1502        ++p)
1503     (*p)->print(f);
1504
1505   for (Assertions::const_iterator p = this->assertions_.begin();
1506        p != this->assertions_.end();
1507        ++p)
1508     (*p)->print(f);
1509
1510   this->script_sections_.print(f);
1511
1512   this->version_script_info_.print(f);
1513 }
1514
1515 // Manage mapping from keywords to the codes expected by the bison
1516 // parser.  We construct one global object for each lex mode with
1517 // keywords.
1518
1519 class Keyword_to_parsecode
1520 {
1521  public:
1522   // The structure which maps keywords to parsecodes.
1523   struct Keyword_parsecode
1524   {
1525     // Keyword.
1526     const char* keyword;
1527     // Corresponding parsecode.
1528     int parsecode;
1529   };
1530
1531   Keyword_to_parsecode(const Keyword_parsecode* keywords,
1532                        int keyword_count)
1533       : keyword_parsecodes_(keywords), keyword_count_(keyword_count)
1534   { }
1535
1536   // Return the parsecode corresponding KEYWORD, or 0 if it is not a
1537   // keyword.
1538   int
1539   keyword_to_parsecode(const char* keyword, size_t len) const;
1540
1541  private:
1542   const Keyword_parsecode* keyword_parsecodes_;
1543   const int keyword_count_;
1544 };
1545
1546 // Mapping from keyword string to keyword parsecode.  This array must
1547 // be kept in sorted order.  Parsecodes are looked up using bsearch.
1548 // This array must correspond to the list of parsecodes in yyscript.y.
1549
1550 static const Keyword_to_parsecode::Keyword_parsecode
1551 script_keyword_parsecodes[] =
1552 {
1553   { "ABSOLUTE", ABSOLUTE },
1554   { "ADDR", ADDR },
1555   { "ALIGN", ALIGN_K },
1556   { "ALIGNOF", ALIGNOF },
1557   { "ASSERT", ASSERT_K },
1558   { "AS_NEEDED", AS_NEEDED },
1559   { "AT", AT },
1560   { "BIND", BIND },
1561   { "BLOCK", BLOCK },
1562   { "BYTE", BYTE },
1563   { "CONSTANT", CONSTANT },
1564   { "CONSTRUCTORS", CONSTRUCTORS },
1565   { "CREATE_OBJECT_SYMBOLS", CREATE_OBJECT_SYMBOLS },
1566   { "DATA_SEGMENT_ALIGN", DATA_SEGMENT_ALIGN },
1567   { "DATA_SEGMENT_END", DATA_SEGMENT_END },
1568   { "DATA_SEGMENT_RELRO_END", DATA_SEGMENT_RELRO_END },
1569   { "DEFINED", DEFINED },
1570   { "ENTRY", ENTRY },
1571   { "EXCLUDE_FILE", EXCLUDE_FILE },
1572   { "EXTERN", EXTERN },
1573   { "FILL", FILL },
1574   { "FLOAT", FLOAT },
1575   { "FORCE_COMMON_ALLOCATION", FORCE_COMMON_ALLOCATION },
1576   { "GROUP", GROUP },
1577   { "HLL", HLL },
1578   { "INCLUDE", INCLUDE },
1579   { "INHIBIT_COMMON_ALLOCATION", INHIBIT_COMMON_ALLOCATION },
1580   { "INPUT", INPUT },
1581   { "KEEP", KEEP },
1582   { "LENGTH", LENGTH },
1583   { "LOADADDR", LOADADDR },
1584   { "LONG", LONG },
1585   { "MAP", MAP },
1586   { "MAX", MAX_K },
1587   { "MEMORY", MEMORY },
1588   { "MIN", MIN_K },
1589   { "NEXT", NEXT },
1590   { "NOCROSSREFS", NOCROSSREFS },
1591   { "NOFLOAT", NOFLOAT },
1592   { "ONLY_IF_RO", ONLY_IF_RO },
1593   { "ONLY_IF_RW", ONLY_IF_RW },
1594   { "OPTION", OPTION },
1595   { "ORIGIN", ORIGIN },
1596   { "OUTPUT", OUTPUT },
1597   { "OUTPUT_ARCH", OUTPUT_ARCH },
1598   { "OUTPUT_FORMAT", OUTPUT_FORMAT },
1599   { "OVERLAY", OVERLAY },
1600   { "PHDRS", PHDRS },
1601   { "PROVIDE", PROVIDE },
1602   { "PROVIDE_HIDDEN", PROVIDE_HIDDEN },
1603   { "QUAD", QUAD },
1604   { "SEARCH_DIR", SEARCH_DIR },
1605   { "SECTIONS", SECTIONS },
1606   { "SEGMENT_START", SEGMENT_START },
1607   { "SHORT", SHORT },
1608   { "SIZEOF", SIZEOF },
1609   { "SIZEOF_HEADERS", SIZEOF_HEADERS },
1610   { "SORT_BY_ALIGNMENT", SORT_BY_ALIGNMENT },
1611   { "SORT_BY_NAME", SORT_BY_NAME },
1612   { "SPECIAL", SPECIAL },
1613   { "SQUAD", SQUAD },
1614   { "STARTUP", STARTUP },
1615   { "SUBALIGN", SUBALIGN },
1616   { "SYSLIB", SYSLIB },
1617   { "TARGET", TARGET_K },
1618   { "TRUNCATE", TRUNCATE },
1619   { "VERSION", VERSIONK },
1620   { "global", GLOBAL },
1621   { "l", LENGTH },
1622   { "len", LENGTH },
1623   { "local", LOCAL },
1624   { "o", ORIGIN },
1625   { "org", ORIGIN },
1626   { "sizeof_headers", SIZEOF_HEADERS },
1627 };
1628
1629 static const Keyword_to_parsecode
1630 script_keywords(&script_keyword_parsecodes[0],
1631                 (sizeof(script_keyword_parsecodes)
1632                  / sizeof(script_keyword_parsecodes[0])));
1633
1634 static const Keyword_to_parsecode::Keyword_parsecode
1635 version_script_keyword_parsecodes[] =
1636 {
1637   { "extern", EXTERN },
1638   { "global", GLOBAL },
1639   { "local", LOCAL },
1640 };
1641
1642 static const Keyword_to_parsecode
1643 version_script_keywords(&version_script_keyword_parsecodes[0],
1644                         (sizeof(version_script_keyword_parsecodes)
1645                          / sizeof(version_script_keyword_parsecodes[0])));
1646
1647 // Comparison function passed to bsearch.
1648
1649 extern "C"
1650 {
1651
1652 struct Ktt_key
1653 {
1654   const char* str;
1655   size_t len;
1656 };
1657
1658 static int
1659 ktt_compare(const void* keyv, const void* kttv)
1660 {
1661   const Ktt_key* key = static_cast<const Ktt_key*>(keyv);
1662   const Keyword_to_parsecode::Keyword_parsecode* ktt =
1663     static_cast<const Keyword_to_parsecode::Keyword_parsecode*>(kttv);
1664   int i = strncmp(key->str, ktt->keyword, key->len);
1665   if (i != 0)
1666     return i;
1667   if (ktt->keyword[key->len] != '\0')
1668     return -1;
1669   return 0;
1670 }
1671
1672 } // End extern "C".
1673
1674 int
1675 Keyword_to_parsecode::keyword_to_parsecode(const char* keyword,
1676                                            size_t len) const
1677 {
1678   Ktt_key key;
1679   key.str = keyword;
1680   key.len = len;
1681   void* kttv = bsearch(&key,
1682                        this->keyword_parsecodes_,
1683                        this->keyword_count_,
1684                        sizeof(this->keyword_parsecodes_[0]),
1685                        ktt_compare);
1686   if (kttv == NULL)
1687     return 0;
1688   Keyword_parsecode* ktt = static_cast<Keyword_parsecode*>(kttv);
1689   return ktt->parsecode;
1690 }
1691
1692 // The following structs are used within the VersionInfo class as well
1693 // as in the bison helper functions.  They store the information
1694 // parsed from the version script.
1695
1696 // A single version expression.
1697 // For example, pattern="std::map*" and language="C++".
1698 // pattern and language should be from the stringpool
1699 struct Version_expression {
1700   Version_expression(const std::string& pattern,
1701                      const std::string& language,
1702                      bool exact_match)
1703       : pattern(pattern), language(language), exact_match(exact_match) {}
1704
1705   std::string pattern;
1706   std::string language;
1707   // If false, we use glob() to match pattern.  If true, we use strcmp().
1708   bool exact_match;
1709 };
1710
1711
1712 // A list of expressions.
1713 struct Version_expression_list {
1714   std::vector<struct Version_expression> expressions;
1715 };
1716
1717
1718 // A list of which versions upon which another version depends.
1719 // Strings should be from the Stringpool.
1720 struct Version_dependency_list {
1721   std::vector<std::string> dependencies;
1722 };
1723
1724
1725 // The total definition of a version.  It includes the tag for the
1726 // version, its global and local expressions, and any dependencies.
1727 struct Version_tree {
1728   Version_tree()
1729       : tag(), global(NULL), local(NULL), dependencies(NULL) {}
1730
1731   std::string tag;
1732   const struct Version_expression_list* global;
1733   const struct Version_expression_list* local;
1734   const struct Version_dependency_list* dependencies;
1735 };
1736
1737 Version_script_info::~Version_script_info()
1738 {
1739   for (size_t k = 0; k < dependency_lists_.size(); ++k)
1740     delete dependency_lists_[k];
1741   for (size_t k = 0; k < version_trees_.size(); ++k)
1742     delete version_trees_[k];
1743   for (size_t k = 0; k < expression_lists_.size(); ++k)
1744     delete expression_lists_[k];
1745 }
1746
1747 std::vector<std::string>
1748 Version_script_info::get_versions() const
1749 {
1750   std::vector<std::string> ret;
1751   for (size_t j = 0; j < version_trees_.size(); ++j)
1752     ret.push_back(version_trees_[j]->tag);
1753   return ret;
1754 }
1755
1756 std::vector<std::string>
1757 Version_script_info::get_dependencies(const char* version) const
1758 {
1759   std::vector<std::string> ret;
1760   for (size_t j = 0; j < version_trees_.size(); ++j)
1761     if (version_trees_[j]->tag == version)
1762       {
1763         const struct Version_dependency_list* deps =
1764           version_trees_[j]->dependencies;
1765         if (deps != NULL)
1766           for (size_t k = 0; k < deps->dependencies.size(); ++k)
1767             ret.push_back(deps->dependencies[k]);
1768         return ret;
1769       }
1770   return ret;
1771 }
1772
1773 const std::string&
1774 Version_script_info::get_symbol_version_helper(const char* symbol_name,
1775                                                bool check_global) const
1776 {
1777   for (size_t j = 0; j < version_trees_.size(); ++j)
1778     {
1779       // Is it a global symbol for this version?
1780       const Version_expression_list* explist =
1781           check_global ? version_trees_[j]->global : version_trees_[j]->local;
1782       if (explist != NULL)
1783         for (size_t k = 0; k < explist->expressions.size(); ++k)
1784           {
1785             const char* name_to_match = symbol_name;
1786             const struct Version_expression& exp = explist->expressions[k];
1787             char* demangled_name = NULL;
1788             if (exp.language == "C++")
1789               {
1790                 demangled_name = cplus_demangle(symbol_name,
1791                                                 DMGL_ANSI | DMGL_PARAMS);
1792                 // This isn't a C++ symbol.
1793                 if (demangled_name == NULL)
1794                   continue;
1795                 name_to_match = demangled_name;
1796               }
1797             else if (exp.language == "Java")
1798               {
1799                 demangled_name = cplus_demangle(symbol_name,
1800                                                 (DMGL_ANSI | DMGL_PARAMS
1801                                                  | DMGL_JAVA));
1802                 // This isn't a Java symbol.
1803                 if (demangled_name == NULL)
1804                   continue;
1805                 name_to_match = demangled_name;
1806               }
1807             bool matched;
1808             if (exp.exact_match)
1809               matched = strcmp(exp.pattern.c_str(), name_to_match) == 0;
1810             else
1811               matched = fnmatch(exp.pattern.c_str(), name_to_match,
1812                                 FNM_NOESCAPE) == 0;
1813             if (demangled_name != NULL)
1814               free(demangled_name);
1815             if (matched)
1816               return version_trees_[j]->tag;
1817           }
1818     }
1819   static const std::string empty = "";
1820   return empty;
1821 }
1822
1823 struct Version_dependency_list*
1824 Version_script_info::allocate_dependency_list()
1825 {
1826   dependency_lists_.push_back(new Version_dependency_list);
1827   return dependency_lists_.back();
1828 }
1829
1830 struct Version_expression_list*
1831 Version_script_info::allocate_expression_list()
1832 {
1833   expression_lists_.push_back(new Version_expression_list);
1834   return expression_lists_.back();
1835 }
1836
1837 struct Version_tree*
1838 Version_script_info::allocate_version_tree()
1839 {
1840   version_trees_.push_back(new Version_tree);
1841   return version_trees_.back();
1842 }
1843
1844 // Print for debugging.
1845
1846 void
1847 Version_script_info::print(FILE* f) const
1848 {
1849   if (this->empty())
1850     return;
1851
1852   fprintf(f, "VERSION {");
1853
1854   for (size_t i = 0; i < this->version_trees_.size(); ++i)
1855     {
1856       const Version_tree* vt = this->version_trees_[i];
1857
1858       if (vt->tag.empty())
1859         fprintf(f, "  {\n");
1860       else
1861         fprintf(f, "  %s {\n", vt->tag.c_str());
1862
1863       if (vt->global != NULL)
1864         {
1865           fprintf(f, "    global :\n");
1866           this->print_expression_list(f, vt->global);
1867         }
1868
1869       if (vt->local != NULL)
1870         {
1871           fprintf(f, "    local :\n");
1872           this->print_expression_list(f, vt->local);
1873         }
1874
1875       fprintf(f, "  }");
1876       if (vt->dependencies != NULL)
1877         {
1878           const Version_dependency_list* deps = vt->dependencies;
1879           for (size_t j = 0; j < deps->dependencies.size(); ++j)
1880             {
1881               if (j < deps->dependencies.size() - 1)
1882                 fprintf(f, "\n");
1883               fprintf(f, "    %s", deps->dependencies[j].c_str());
1884             }
1885         }
1886       fprintf(f, ";\n");
1887     }
1888
1889   fprintf(f, "}\n");
1890 }
1891
1892 void
1893 Version_script_info::print_expression_list(
1894     FILE* f,
1895     const Version_expression_list* vel) const
1896 {
1897   std::string current_language;
1898   for (size_t i = 0; i < vel->expressions.size(); ++i)
1899     {
1900       const Version_expression& ve(vel->expressions[i]);
1901
1902       if (ve.language != current_language)
1903         {
1904           if (!current_language.empty())
1905             fprintf(f, "      }\n");
1906           fprintf(f, "      extern \"%s\" {\n", ve.language.c_str());
1907           current_language = ve.language;
1908         }
1909
1910       fprintf(f, "      ");
1911       if (!current_language.empty())
1912         fprintf(f, "  ");
1913
1914       if (ve.exact_match)
1915         fprintf(f, "\"");
1916       fprintf(f, "%s", ve.pattern.c_str());
1917       if (ve.exact_match)
1918         fprintf(f, "\"");
1919
1920       fprintf(f, "\n");
1921     }
1922
1923   if (!current_language.empty())
1924     fprintf(f, "      }\n");
1925 }
1926
1927 } // End namespace gold.
1928
1929 // The remaining functions are extern "C", so it's clearer to not put
1930 // them in namespace gold.
1931
1932 using namespace gold;
1933
1934 // This function is called by the bison parser to return the next
1935 // token.
1936
1937 extern "C" int
1938 yylex(YYSTYPE* lvalp, void* closurev)
1939 {
1940   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
1941   const Token* token = closure->next_token();
1942   switch (token->classification())
1943     {
1944     default:
1945       gold_unreachable();
1946
1947     case Token::TOKEN_INVALID:
1948       yyerror(closurev, "invalid character");
1949       return 0;
1950
1951     case Token::TOKEN_EOF:
1952       return 0;
1953
1954     case Token::TOKEN_STRING:
1955       {
1956         // This is either a keyword or a STRING.
1957         size_t len;
1958         const char* str = token->string_value(&len);
1959         int parsecode = 0;
1960         switch (closure->lex_mode())
1961           {
1962           case Lex::LINKER_SCRIPT:
1963             parsecode = script_keywords.keyword_to_parsecode(str, len);
1964             break;
1965           case Lex::VERSION_SCRIPT:
1966             parsecode = version_script_keywords.keyword_to_parsecode(str, len);
1967             break;
1968           default:
1969             break;
1970           }
1971         if (parsecode != 0)
1972           return parsecode;
1973         lvalp->string.value = str;
1974         lvalp->string.length = len;
1975         return STRING;
1976       }
1977
1978     case Token::TOKEN_QUOTED_STRING:
1979       lvalp->string.value = token->string_value(&lvalp->string.length);
1980       return QUOTED_STRING;
1981
1982     case Token::TOKEN_OPERATOR:
1983       return token->operator_value();
1984
1985     case Token::TOKEN_INTEGER:
1986       lvalp->integer = token->integer_value();
1987       return INTEGER;
1988     }
1989 }
1990
1991 // This function is called by the bison parser to report an error.
1992
1993 extern "C" void
1994 yyerror(void* closurev, const char* message)
1995 {
1996   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
1997   gold_error(_("%s:%d:%d: %s"), closure->filename(), closure->lineno(),
1998              closure->charpos(), message);
1999 }
2000
2001 // Called by the bison parser to add a file to the link.
2002
2003 extern "C" void
2004 script_add_file(void* closurev, const char* name, size_t length)
2005 {
2006   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2007
2008   // If this is an absolute path, and we found the script in the
2009   // sysroot, then we want to prepend the sysroot to the file name.
2010   // For example, this is how we handle a cross link to the x86_64
2011   // libc.so, which refers to /lib/libc.so.6.
2012   std::string name_string(name, length);
2013   const char* extra_search_path = ".";
2014   std::string script_directory;
2015   if (IS_ABSOLUTE_PATH(name_string.c_str()))
2016     {
2017       if (closure->is_in_sysroot())
2018         {
2019           const std::string& sysroot(parameters->sysroot());
2020           gold_assert(!sysroot.empty());
2021           name_string = sysroot + name_string;
2022         }
2023     }
2024   else
2025     {
2026       // In addition to checking the normal library search path, we
2027       // also want to check in the script-directory.
2028       const char *slash = strrchr(closure->filename(), '/');
2029       if (slash != NULL)
2030         {
2031           script_directory.assign(closure->filename(),
2032                                   slash - closure->filename() + 1);
2033           extra_search_path = script_directory.c_str();
2034         }
2035     }
2036
2037   Input_file_argument file(name_string.c_str(), false, extra_search_path,
2038                            closure->position_dependent_options());
2039   closure->inputs()->add_file(file);
2040 }
2041
2042 // Called by the bison parser to start a group.  If we are already in
2043 // a group, that means that this script was invoked within a
2044 // --start-group --end-group sequence on the command line, or that
2045 // this script was found in a GROUP of another script.  In that case,
2046 // we simply continue the existing group, rather than starting a new
2047 // one.  It is possible to construct a case in which this will do
2048 // something other than what would happen if we did a recursive group,
2049 // but it's hard to imagine why the different behaviour would be
2050 // useful for a real program.  Avoiding recursive groups is simpler
2051 // and more efficient.
2052
2053 extern "C" void
2054 script_start_group(void* closurev)
2055 {
2056   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2057   if (!closure->in_group())
2058     closure->inputs()->start_group();
2059 }
2060
2061 // Called by the bison parser at the end of a group.
2062
2063 extern "C" void
2064 script_end_group(void* closurev)
2065 {
2066   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2067   if (!closure->in_group())
2068     closure->inputs()->end_group();
2069 }
2070
2071 // Called by the bison parser to start an AS_NEEDED list.
2072
2073 extern "C" void
2074 script_start_as_needed(void* closurev)
2075 {
2076   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2077   closure->position_dependent_options().set_as_needed();
2078 }
2079
2080 // Called by the bison parser at the end of an AS_NEEDED list.
2081
2082 extern "C" void
2083 script_end_as_needed(void* closurev)
2084 {
2085   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2086   closure->position_dependent_options().clear_as_needed();
2087 }
2088
2089 // Called by the bison parser to set the entry symbol.
2090
2091 extern "C" void
2092 script_set_entry(void* closurev, const char* entry, size_t length)
2093 {
2094   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2095   closure->script_options()->set_entry(entry, length);
2096 }
2097
2098 // Called by the bison parser to define a symbol.
2099
2100 extern "C" void
2101 script_set_symbol(void* closurev, const char* name, size_t length,
2102                   Expression* value, int providei, int hiddeni)
2103 {
2104   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2105   const bool provide = providei != 0;
2106   const bool hidden = hiddeni != 0;
2107   closure->script_options()->add_symbol_assignment(name, length, value,
2108                                                    provide, hidden);
2109 }
2110
2111 // Called by the bison parser to add an assertion.
2112
2113 extern "C" void
2114 script_add_assertion(void* closurev, Expression* check, const char* message,
2115                      size_t messagelen)
2116 {
2117   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2118   closure->script_options()->add_assertion(check, message, messagelen);
2119 }
2120
2121 // Called by the bison parser to parse an OPTION.
2122
2123 extern "C" void
2124 script_parse_option(void* closurev, const char* option, size_t length)
2125 {
2126   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2127   // We treat the option as a single command-line option, even if
2128   // it has internal whitespace.
2129   if (closure->command_line() == NULL)
2130     {
2131       // There are some options that we could handle here--e.g.,
2132       // -lLIBRARY.  Should we bother?
2133       gold_warning(_("%s:%d:%d: ignoring command OPTION; OPTION is only valid"
2134                      " for scripts specified via -T/--script"),
2135                    closure->filename(), closure->lineno(), closure->charpos());
2136     }
2137   else
2138     {
2139       bool past_a_double_dash_option = false;
2140       char* mutable_option = strndup(option, length);
2141       gold_assert(mutable_option != NULL);
2142       closure->command_line()->process_one_option(1, &mutable_option, 0,
2143                                                   &past_a_double_dash_option);
2144       free(mutable_option);
2145     }
2146 }
2147
2148 /* Called by the bison parser to push the lexer into expression
2149    mode.  */
2150
2151 extern "C" void
2152 script_push_lex_into_expression_mode(void* closurev)
2153 {
2154   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2155   closure->push_lex_mode(Lex::EXPRESSION);
2156 }
2157
2158 /* Called by the bison parser to push the lexer into version
2159    mode.  */
2160
2161 extern "C" void
2162 script_push_lex_into_version_mode(void* closurev)
2163 {
2164   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2165   closure->push_lex_mode(Lex::VERSION_SCRIPT);
2166 }
2167
2168 /* Called by the bison parser to pop the lexer mode.  */
2169
2170 extern "C" void
2171 script_pop_lex_mode(void* closurev)
2172 {
2173   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2174   closure->pop_lex_mode();
2175 }
2176
2177 // Register an entire version node. For example:
2178 //
2179 // GLIBC_2.1 {
2180 //   global: foo;
2181 // } GLIBC_2.0;
2182 //
2183 // - tag is "GLIBC_2.1"
2184 // - tree contains the information "global: foo"
2185 // - deps contains "GLIBC_2.0"
2186
2187 extern "C" void
2188 script_register_vers_node(void*,
2189                           const char* tag,
2190                           int taglen,
2191                           struct Version_tree *tree,
2192                           struct Version_dependency_list *deps)
2193 {
2194   gold_assert(tree != NULL);
2195   gold_assert(tag != NULL);
2196   tree->dependencies = deps;
2197   tree->tag = std::string(tag, taglen);
2198 }
2199
2200 // Add a dependencies to the list of existing dependencies, if any,
2201 // and return the expanded list.
2202
2203 extern "C" struct Version_dependency_list *
2204 script_add_vers_depend(void* closurev,
2205                        struct Version_dependency_list *all_deps,
2206                        const char *depend_to_add, int deplen)
2207 {
2208   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2209   if (all_deps == NULL)
2210     all_deps = closure->version_script()->allocate_dependency_list();
2211   all_deps->dependencies.push_back(std::string(depend_to_add, deplen));
2212   return all_deps;
2213 }
2214
2215 // Add a pattern expression to an existing list of expressions, if any.
2216 // TODO: In the old linker, the last argument used to be a bool, but I
2217 // don't know what it meant.
2218
2219 extern "C" struct Version_expression_list *
2220 script_new_vers_pattern(void* closurev,
2221                         struct Version_expression_list *expressions,
2222                         const char *pattern, int patlen, int exact_match)
2223 {
2224   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2225   if (expressions == NULL)
2226     expressions = closure->version_script()->allocate_expression_list();
2227   expressions->expressions.push_back(
2228       Version_expression(std::string(pattern, patlen),
2229                          closure->get_current_language(),
2230                          static_cast<bool>(exact_match)));
2231   return expressions;
2232 }
2233
2234 // Attaches b to the end of a, and clears b.  So a = a + b and b = {}.
2235
2236 extern "C" struct Version_expression_list*
2237 script_merge_expressions(struct Version_expression_list *a,
2238                          struct Version_expression_list *b)
2239 {
2240   a->expressions.insert(a->expressions.end(),
2241                         b->expressions.begin(), b->expressions.end());
2242   // We could delete b and remove it from expressions_lists_, but
2243   // that's a lot of work.  This works just as well.
2244   b->expressions.clear();
2245   return a;
2246 }
2247
2248 // Combine the global and local expressions into a a Version_tree.
2249
2250 extern "C" struct Version_tree *
2251 script_new_vers_node(void* closurev,
2252                      struct Version_expression_list *global,
2253                      struct Version_expression_list *local)
2254 {
2255   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2256   Version_tree* tree = closure->version_script()->allocate_version_tree();
2257   tree->global = global;
2258   tree->local = local;
2259   return tree;
2260 }
2261
2262 // Handle a transition in language, such as at the
2263 // start or end of 'extern "C++"'
2264
2265 extern "C" void
2266 version_script_push_lang(void* closurev, const char* lang, int langlen)
2267 {
2268   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2269   closure->push_language(std::string(lang, langlen));
2270 }
2271
2272 extern "C" void
2273 version_script_pop_lang(void* closurev)
2274 {
2275   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2276   closure->pop_language();
2277 }
2278
2279 // Called by the bison parser to start a SECTIONS clause.
2280
2281 extern "C" void
2282 script_start_sections(void* closurev)
2283 {
2284   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2285   closure->script_options()->script_sections()->start_sections();
2286 }
2287
2288 // Called by the bison parser to finish a SECTIONS clause.
2289
2290 extern "C" void
2291 script_finish_sections(void* closurev)
2292 {
2293   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2294   closure->script_options()->script_sections()->finish_sections();
2295 }
2296
2297 // Start processing entries for an output section.
2298
2299 extern "C" void
2300 script_start_output_section(void* closurev, const char* name, size_t namelen,
2301                             const struct Parser_output_section_header* header)
2302 {
2303   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2304   closure->script_options()->script_sections()->start_output_section(name,
2305                                                                      namelen,
2306                                                                      header);
2307 }
2308
2309 // Finish processing entries for an output section.
2310
2311 extern "C" void
2312 script_finish_output_section(void* closurev, 
2313                              const struct Parser_output_section_trailer* trail)
2314 {
2315   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2316   closure->script_options()->script_sections()->finish_output_section(trail);
2317 }
2318
2319 // Add a data item (e.g., "WORD (0)") to the current output section.
2320
2321 extern "C" void
2322 script_add_data(void* closurev, int data_token, Expression* val)
2323 {
2324   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2325   int size;
2326   bool is_signed = true;
2327   switch (data_token)
2328     {
2329     case QUAD:
2330       size = 8;
2331       is_signed = false;
2332       break;
2333     case SQUAD:
2334       size = 8;
2335       break;
2336     case LONG:
2337       size = 4;
2338       break;
2339     case SHORT:
2340       size = 2;
2341       break;
2342     case BYTE:
2343       size = 1;
2344       break;
2345     default:
2346       gold_unreachable();
2347     }
2348   closure->script_options()->script_sections()->add_data(size, is_signed, val);
2349 }
2350
2351 // Add a clause setting the fill value to the current output section.
2352
2353 extern "C" void
2354 script_add_fill(void* closurev, Expression* val)
2355 {
2356   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2357   closure->script_options()->script_sections()->add_fill(val);
2358 }
2359
2360 // Add a new input section specification to the current output
2361 // section.
2362
2363 extern "C" void
2364 script_add_input_section(void* closurev,
2365                          const struct Input_section_spec* spec,
2366                          int keepi)
2367 {
2368   Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2369   bool keep = keepi != 0;
2370   closure->script_options()->script_sections()->add_input_section(spec, keep);
2371 }
2372
2373 // Create a new list of string/sort pairs.
2374
2375 extern "C" String_sort_list_ptr
2376 script_new_string_sort_list(const struct Wildcard_section* string_sort)
2377 {
2378   return new String_sort_list(1, *string_sort);
2379 }
2380
2381 // Add an entry to a list of string/sort pairs.  The way the parser
2382 // works permits us to simply modify the first parameter, rather than
2383 // copy the vector.
2384
2385 extern "C" String_sort_list_ptr
2386 script_string_sort_list_add(String_sort_list_ptr pv,
2387                             const struct Wildcard_section* string_sort)
2388 {
2389   if (pv == NULL)
2390     return script_new_string_sort_list(string_sort);
2391   else
2392     {
2393       pv->push_back(*string_sort);
2394       return pv;
2395     }
2396 }
2397
2398 // Create a new list of strings.
2399
2400 extern "C" String_list_ptr
2401 script_new_string_list(const char* str, size_t len)
2402 {
2403   return new String_list(1, std::string(str, len));
2404 }
2405
2406 // Add an element to a list of strings.  The way the parser works
2407 // permits us to simply modify the first parameter, rather than copy
2408 // the vector.
2409
2410 extern "C" String_list_ptr
2411 script_string_list_push_back(String_list_ptr pv, const char* str, size_t len)
2412 {
2413   pv->push_back(std::string(str, len));
2414   return pv;
2415 }
2416
2417 // Concatenate two string lists.  Either or both may be NULL.  The way
2418 // the parser works permits us to modify the parameters, rather than
2419 // copy the vector.
2420
2421 extern "C" String_list_ptr
2422 script_string_list_append(String_list_ptr pv1, String_list_ptr pv2)
2423 {
2424   if (pv1 == NULL)
2425     return pv2;
2426   if (pv2 == NULL)
2427     return pv1;
2428   pv1->insert(pv1->end(), pv2->begin(), pv2->end());
2429   return pv1;
2430 }