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