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