1 // script.cc -- handle linker scripts for gold.
3 // Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@google.com>.
6 // This file is part of gold.
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.
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.
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.
31 #include "filenames.h"
35 #include "dirsearch.h"
38 #include "workqueue.h"
40 #include "parameters.h"
43 #include "target-select.h"
50 // A token read from a script file. We don't implement keywords here;
51 // all keywords are simply represented as a string.
56 // Token classification.
61 // Token indicates end of input.
63 // Token is a string of characters.
65 // Token is a quoted string of characters.
67 // Token is an operator.
69 // Token is a number (an integer).
73 // We need an empty constructor so that we can put this STL objects.
75 : classification_(TOKEN_INVALID), value_(NULL), value_length_(0),
76 opcode_(0), lineno_(0), charpos_(0)
79 // A general token with no value.
80 Token(Classification classification, int lineno, int charpos)
81 : classification_(classification), value_(NULL), value_length_(0),
82 opcode_(0), lineno_(lineno), charpos_(charpos)
84 gold_assert(classification == TOKEN_INVALID
85 || classification == TOKEN_EOF);
88 // A general token with a value.
89 Token(Classification classification, const char* value, size_t length,
90 int lineno, int charpos)
91 : classification_(classification), value_(value), value_length_(length),
92 opcode_(0), lineno_(lineno), charpos_(charpos)
94 gold_assert(classification != TOKEN_INVALID
95 && classification != TOKEN_EOF);
98 // A token representing an operator.
99 Token(int opcode, int lineno, int charpos)
100 : classification_(TOKEN_OPERATOR), value_(NULL), value_length_(0),
101 opcode_(opcode), lineno_(lineno), charpos_(charpos)
104 // Return whether the token is invalid.
107 { return this->classification_ == TOKEN_INVALID; }
109 // Return whether this is an EOF token.
112 { return this->classification_ == TOKEN_EOF; }
114 // Return the token classification.
116 classification() const
117 { return this->classification_; }
119 // Return the line number at which the token starts.
122 { return this->lineno_; }
124 // Return the character position at this the token starts.
127 { return this->charpos_; }
129 // Get the value of a token.
132 string_value(size_t* length) const
134 gold_assert(this->classification_ == TOKEN_STRING
135 || this->classification_ == TOKEN_QUOTED_STRING);
136 *length = this->value_length_;
141 operator_value() const
143 gold_assert(this->classification_ == TOKEN_OPERATOR);
144 return this->opcode_;
148 integer_value() const
150 gold_assert(this->classification_ == TOKEN_INTEGER);
152 std::string s(this->value_, this->value_length_);
153 return strtoull(s.c_str(), NULL, 0);
157 // The token classification.
158 Classification classification_;
159 // The token value, for TOKEN_STRING or TOKEN_QUOTED_STRING or
162 // The length of the token value.
163 size_t value_length_;
164 // The token value, for TOKEN_OPERATOR.
166 // The line number where this token started (one based).
168 // The character position within the line where this token started
173 // This class handles lexing a file into a sequence of tokens.
178 // We unfortunately have to support different lexing modes, because
179 // when reading different parts of a linker script we need to parse
180 // things differently.
183 // Reading an ordinary linker script.
185 // Reading an expression in a linker script.
187 // Reading a version script.
189 // Reading a --dynamic-list file.
193 Lex(const char* input_string, size_t input_length, int parsing_token)
194 : input_string_(input_string), input_length_(input_length),
195 current_(input_string), mode_(LINKER_SCRIPT),
196 first_token_(parsing_token), token_(),
197 lineno_(1), linestart_(input_string)
200 // Read a file into a string.
202 read_file(Input_file*, std::string*);
204 // Return the next token.
208 // Return the current lexing mode.
211 { return this->mode_; }
213 // Set the lexing mode.
216 { this->mode_ = mode; }
220 Lex& operator=(const Lex&);
222 // Make a general token with no value at the current location.
224 make_token(Token::Classification c, const char* start) const
225 { return Token(c, this->lineno_, start - this->linestart_ + 1); }
227 // Make a general token with a value at the current location.
229 make_token(Token::Classification c, const char* v, size_t len,
232 { return Token(c, v, len, this->lineno_, start - this->linestart_ + 1); }
234 // Make an operator token at the current location.
236 make_token(int opcode, const char* start) const
237 { return Token(opcode, this->lineno_, start - this->linestart_ + 1); }
239 // Make an invalid token at the current location.
241 make_invalid_token(const char* start)
242 { return this->make_token(Token::TOKEN_INVALID, start); }
244 // Make an EOF token at the current location.
246 make_eof_token(const char* start)
247 { return this->make_token(Token::TOKEN_EOF, start); }
249 // Return whether C can be the first character in a name. C2 is the
250 // next character, since we sometimes need that.
252 can_start_name(char c, char c2);
254 // If C can appear in a name which has already started, return a
255 // pointer to a character later in the token or just past
256 // it. Otherwise, return NULL.
258 can_continue_name(const char* c);
260 // Return whether C, C2, C3 can start a hex number.
262 can_start_hex(char c, char c2, char c3);
264 // If C can appear in a hex number which has already started, return
265 // a pointer to a character later in the token or just past
266 // it. Otherwise, return NULL.
268 can_continue_hex(const char* c);
270 // Return whether C can start a non-hex number.
272 can_start_number(char c);
274 // If C can appear in a decimal number which has already started,
275 // return a pointer to a character later in the token or just past
276 // it. Otherwise, return NULL.
278 can_continue_number(const char* c)
279 { return Lex::can_start_number(*c) ? c + 1 : NULL; }
281 // If C1 C2 C3 form a valid three character operator, return the
282 // opcode. Otherwise return 0.
284 three_char_operator(char c1, char c2, char c3);
286 // If C1 C2 form a valid two character operator, return the opcode.
287 // Otherwise return 0.
289 two_char_operator(char c1, char c2);
291 // If C1 is a valid one character operator, return the opcode.
292 // Otherwise return 0.
294 one_char_operator(char c1);
296 // Read the next token.
298 get_token(const char**);
300 // Skip a C style /* */ comment. Return false if the comment did
303 skip_c_comment(const char**);
305 // Skip a line # comment. Return false if there was no newline.
307 skip_line_comment(const char**);
309 // Build a token CLASSIFICATION from all characters that match
310 // CAN_CONTINUE_FN. The token starts at START. Start matching from
311 // MATCH. Set *PP to the character following the token.
313 gather_token(Token::Classification,
314 const char* (Lex::*can_continue_fn)(const char*),
315 const char* start, const char* match, const char** pp);
317 // Build a token from a quoted string.
319 gather_quoted_string(const char** pp);
321 // The string we are tokenizing.
322 const char* input_string_;
323 // The length of the string.
324 size_t input_length_;
325 // The current offset into the string.
326 const char* current_;
327 // The current lexing mode.
329 // The code to use for the first token. This is set to 0 after it
332 // The current token.
334 // The current line number.
336 // The start of the current line in the string.
337 const char* linestart_;
340 // Read the whole file into memory. We don't expect linker scripts to
341 // be large, so we just use a std::string as a buffer. We ignore the
342 // data we've already read, so that we read aligned buffers.
345 Lex::read_file(Input_file* input_file, std::string* contents)
347 off_t filesize = input_file->file().filesize();
349 contents->reserve(filesize);
352 unsigned char buf[BUFSIZ];
353 while (off < filesize)
356 if (get > filesize - off)
357 get = filesize - off;
358 input_file->file().read(off, get, buf);
359 contents->append(reinterpret_cast<char*>(&buf[0]), get);
364 // Return whether C can be the start of a name, if the next character
365 // is C2. A name can being with a letter, underscore, period, or
366 // dollar sign. Because a name can be a file name, we also permit
367 // forward slash, backslash, and tilde. Tilde is the tricky case
368 // here; GNU ld also uses it as a bitwise not operator. It is only
369 // recognized as the operator if it is not immediately followed by
370 // some character which can appear in a symbol. That is, when we
371 // don't know that we are looking at an expression, "~0" is a file
372 // name, and "~ 0" is an expression using bitwise not. We are
376 Lex::can_start_name(char c, char c2)
380 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
381 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
382 case 'M': case 'N': case 'O': case 'Q': case 'P': case 'R':
383 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
385 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
386 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
387 case 'm': case 'n': case 'o': case 'q': case 'p': case 'r':
388 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
390 case '_': case '.': case '$':
394 return this->mode_ == LINKER_SCRIPT;
397 return this->mode_ == LINKER_SCRIPT && can_continue_name(&c2);
400 return (this->mode_ == VERSION_SCRIPT
401 || this->mode_ == DYNAMIC_LIST
402 || (this->mode_ == LINKER_SCRIPT
403 && can_continue_name(&c2)));
410 // Return whether C can continue a name which has already started.
411 // Subsequent characters in a name are the same as the leading
412 // characters, plus digits and "=+-:[],?*". So in general the linker
413 // script language requires spaces around operators, unless we know
414 // that we are parsing an expression.
417 Lex::can_continue_name(const char* c)
421 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
422 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
423 case 'M': case 'N': case 'O': case 'Q': case 'P': case 'R':
424 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
426 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
427 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
428 case 'm': case 'n': case 'o': case 'q': case 'p': case 'r':
429 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
431 case '_': case '.': case '$':
432 case '0': case '1': case '2': case '3': case '4':
433 case '5': case '6': case '7': case '8': case '9':
436 // TODO(csilvers): why not allow ~ in names for version-scripts?
437 case '/': case '\\': case '~':
440 if (this->mode_ == LINKER_SCRIPT)
444 case '[': case ']': case '*': case '?': case '-':
445 if (this->mode_ == LINKER_SCRIPT || this->mode_ == VERSION_SCRIPT
446 || this->mode_ == DYNAMIC_LIST)
450 // TODO(csilvers): why allow this? ^ is meaningless in version scripts.
452 if (this->mode_ == VERSION_SCRIPT || this->mode_ == DYNAMIC_LIST)
457 if (this->mode_ == LINKER_SCRIPT)
459 else if ((this->mode_ == VERSION_SCRIPT || this->mode_ == DYNAMIC_LIST)
462 // A name can have '::' in it, as that's a c++ namespace
463 // separator. But a single colon is not part of a name.
473 // For a number we accept 0x followed by hex digits, or any sequence
474 // of digits. The old linker accepts leading '$' for hex, and
475 // trailing HXBOD. Those are for MRI compatibility and we don't
476 // accept them. The old linker also accepts trailing MK for mega or
477 // kilo. FIXME: Those are mentioned in the documentation, and we
478 // should accept them.
480 // Return whether C1 C2 C3 can start a hex number.
483 Lex::can_start_hex(char c1, char c2, char c3)
485 if (c1 == '0' && (c2 == 'x' || c2 == 'X'))
486 return this->can_continue_hex(&c3);
490 // Return whether C can appear in a hex number.
493 Lex::can_continue_hex(const char* c)
497 case '0': case '1': case '2': case '3': case '4':
498 case '5': case '6': case '7': case '8': case '9':
499 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
500 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
508 // Return whether C can start a non-hex number.
511 Lex::can_start_number(char c)
515 case '0': case '1': case '2': case '3': case '4':
516 case '5': case '6': case '7': case '8': case '9':
524 // If C1 C2 C3 form a valid three character operator, return the
525 // opcode (defined in the yyscript.h file generated from yyscript.y).
526 // Otherwise return 0.
529 Lex::three_char_operator(char c1, char c2, char c3)
534 if (c2 == '<' && c3 == '=')
538 if (c2 == '>' && c3 == '=')
547 // If C1 C2 form a valid two character operator, return the opcode
548 // (defined in the yyscript.h file generated from yyscript.y).
549 // Otherwise return 0.
552 Lex::two_char_operator(char c1, char c2)
610 // If C1 is a valid operator, return the opcode. Otherwise return 0.
613 Lex::one_char_operator(char c1)
646 // Skip a C style comment. *PP points to just after the "/*". Return
647 // false if the comment did not end.
650 Lex::skip_c_comment(const char** pp)
653 while (p[0] != '*' || p[1] != '/')
664 this->linestart_ = p + 1;
673 // Skip a line # comment. Return false if there was no newline.
676 Lex::skip_line_comment(const char** pp)
679 size_t skip = strcspn(p, "\n");
688 this->linestart_ = p;
694 // Build a token CLASSIFICATION from all characters that match
695 // CAN_CONTINUE_FN. Update *PP.
698 Lex::gather_token(Token::Classification classification,
699 const char* (Lex::*can_continue_fn)(const char*),
704 const char* new_match = NULL;
705 while ((new_match = (this->*can_continue_fn)(match)))
708 return this->make_token(classification, start, match - start, start);
711 // Build a token from a quoted string.
714 Lex::gather_quoted_string(const char** pp)
716 const char* start = *pp;
717 const char* p = start;
719 size_t skip = strcspn(p, "\"\n");
721 return this->make_invalid_token(start);
723 return this->make_token(Token::TOKEN_QUOTED_STRING, p, skip, start);
726 // Return the next token at *PP. Update *PP. General guideline: we
727 // require linker scripts to be simple ASCII. No unicode linker
728 // scripts. In particular we can assume that any '\0' is the end of
732 Lex::get_token(const char** pp)
741 return this->make_eof_token(p);
744 // Skip whitespace quickly.
745 while (*p == ' ' || *p == '\t')
752 this->linestart_ = p;
756 // Skip C style comments.
757 if (p[0] == '/' && p[1] == '*')
759 int lineno = this->lineno_;
760 int charpos = p - this->linestart_ + 1;
763 if (!this->skip_c_comment(pp))
764 return Token(Token::TOKEN_INVALID, lineno, charpos);
770 // Skip line comments.
774 if (!this->skip_line_comment(pp))
775 return this->make_eof_token(p);
781 if (this->can_start_name(p[0], p[1]))
782 return this->gather_token(Token::TOKEN_STRING,
783 &Lex::can_continue_name,
786 // We accept any arbitrary name in double quotes, as long as it
787 // does not cross a line boundary.
791 return this->gather_quoted_string(pp);
794 // Check for a number.
796 if (this->can_start_hex(p[0], p[1], p[2]))
797 return this->gather_token(Token::TOKEN_INTEGER,
798 &Lex::can_continue_hex,
801 if (Lex::can_start_number(p[0]))
802 return this->gather_token(Token::TOKEN_INTEGER,
803 &Lex::can_continue_number,
806 // Check for operators.
808 int opcode = Lex::three_char_operator(p[0], p[1], p[2]);
812 return this->make_token(opcode, p);
815 opcode = Lex::two_char_operator(p[0], p[1]);
819 return this->make_token(opcode, p);
822 opcode = Lex::one_char_operator(p[0]);
826 return this->make_token(opcode, p);
829 return this->make_token(Token::TOKEN_INVALID, p);
833 // Return the next token.
838 // The first token is special.
839 if (this->first_token_ != 0)
841 this->token_ = Token(this->first_token_, 0, 0);
842 this->first_token_ = 0;
843 return &this->token_;
846 this->token_ = this->get_token(&this->current_);
848 // Don't let an early null byte fool us into thinking that we've
849 // reached the end of the file.
850 if (this->token_.is_eof()
851 && (static_cast<size_t>(this->current_ - this->input_string_)
852 < this->input_length_))
853 this->token_ = this->make_invalid_token(this->current_);
855 return &this->token_;
858 // class Symbol_assignment.
860 // Add the symbol to the symbol table. This makes sure the symbol is
861 // there and defined. The actual value is stored later. We can't
862 // determine the actual value at this point, because we can't
863 // necessarily evaluate the expression until all ordinary symbols have
866 // The GNU linker lets symbol assignments in the linker script
867 // silently override defined symbols in object files. We are
868 // compatible. FIXME: Should we issue a warning?
871 Symbol_assignment::add_to_table(Symbol_table* symtab)
873 elfcpp::STV vis = this->hidden_ ? elfcpp::STV_HIDDEN : elfcpp::STV_DEFAULT;
874 this->sym_ = symtab->define_as_constant(this->name_.c_str(),
883 true); // force_override
886 // Finalize a symbol value.
889 Symbol_assignment::finalize(Symbol_table* symtab, const Layout* layout)
891 this->finalize_maybe_dot(symtab, layout, false, 0, NULL);
894 // Finalize a symbol value which can refer to the dot symbol.
897 Symbol_assignment::finalize_with_dot(Symbol_table* symtab,
898 const Layout* layout,
900 Output_section* dot_section)
902 this->finalize_maybe_dot(symtab, layout, true, dot_value, dot_section);
905 // Finalize a symbol value, internal version.
908 Symbol_assignment::finalize_maybe_dot(Symbol_table* symtab,
909 const Layout* layout,
910 bool is_dot_available,
912 Output_section* dot_section)
914 // If we were only supposed to provide this symbol, the sym_ field
915 // will be NULL if the symbol was not referenced.
916 if (this->sym_ == NULL)
918 gold_assert(this->provide_);
922 if (parameters->target().get_size() == 32)
924 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
925 this->sized_finalize<32>(symtab, layout, is_dot_available, dot_value,
931 else if (parameters->target().get_size() == 64)
933 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
934 this->sized_finalize<64>(symtab, layout, is_dot_available, dot_value,
946 Symbol_assignment::sized_finalize(Symbol_table* symtab, const Layout* layout,
947 bool is_dot_available, uint64_t dot_value,
948 Output_section* dot_section)
950 Output_section* section;
951 uint64_t final_val = this->val_->eval_maybe_dot(symtab, layout, true,
953 dot_value, dot_section,
955 Sized_symbol<size>* ssym = symtab->get_sized_symbol<size>(this->sym_);
956 ssym->set_value(final_val);
958 ssym->set_output_section(section);
961 // Set the symbol value if the expression yields an absolute value.
964 Symbol_assignment::set_if_absolute(Symbol_table* symtab, const Layout* layout,
965 bool is_dot_available, uint64_t dot_value)
967 if (this->sym_ == NULL)
970 Output_section* val_section;
971 uint64_t val = this->val_->eval_maybe_dot(symtab, layout, false,
972 is_dot_available, dot_value,
974 if (val_section != NULL)
977 if (parameters->target().get_size() == 32)
979 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
980 Sized_symbol<32>* ssym = symtab->get_sized_symbol<32>(this->sym_);
981 ssym->set_value(val);
986 else if (parameters->target().get_size() == 64)
988 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
989 Sized_symbol<64>* ssym = symtab->get_sized_symbol<64>(this->sym_);
990 ssym->set_value(val);
999 // Print for debugging.
1002 Symbol_assignment::print(FILE* f) const
1004 if (this->provide_ && this->hidden_)
1005 fprintf(f, "PROVIDE_HIDDEN(");
1006 else if (this->provide_)
1007 fprintf(f, "PROVIDE(");
1008 else if (this->hidden_)
1011 fprintf(f, "%s = ", this->name_.c_str());
1012 this->val_->print(f);
1014 if (this->provide_ || this->hidden_)
1020 // Class Script_assertion.
1022 // Check the assertion.
1025 Script_assertion::check(const Symbol_table* symtab, const Layout* layout)
1027 if (!this->check_->eval(symtab, layout, true))
1028 gold_error("%s", this->message_.c_str());
1031 // Print for debugging.
1034 Script_assertion::print(FILE* f) const
1036 fprintf(f, "ASSERT(");
1037 this->check_->print(f);
1038 fprintf(f, ", \"%s\")\n", this->message_.c_str());
1041 // Class Script_options.
1043 Script_options::Script_options()
1044 : entry_(), symbol_assignments_(), version_script_info_(),
1049 // Add a symbol to be defined.
1052 Script_options::add_symbol_assignment(const char* name, size_t length,
1053 Expression* value, bool provide,
1056 if (length != 1 || name[0] != '.')
1058 if (this->script_sections_.in_sections_clause())
1059 this->script_sections_.add_symbol_assignment(name, length, value,
1063 Symbol_assignment* p = new Symbol_assignment(name, length, value,
1065 this->symbol_assignments_.push_back(p);
1070 if (provide || hidden)
1071 gold_error(_("invalid use of PROVIDE for dot symbol"));
1072 if (!this->script_sections_.in_sections_clause())
1073 gold_error(_("invalid assignment to dot outside of SECTIONS"));
1075 this->script_sections_.add_dot_assignment(value);
1079 // Add an assertion.
1082 Script_options::add_assertion(Expression* check, const char* message,
1085 if (this->script_sections_.in_sections_clause())
1086 this->script_sections_.add_assertion(check, message, messagelen);
1089 Script_assertion* p = new Script_assertion(check, message, messagelen);
1090 this->assertions_.push_back(p);
1094 // Create sections required by any linker scripts.
1097 Script_options::create_script_sections(Layout* layout)
1099 if (this->saw_sections_clause())
1100 this->script_sections_.create_sections(layout);
1103 // Add any symbols we are defining to the symbol table.
1106 Script_options::add_symbols_to_table(Symbol_table* symtab)
1108 for (Symbol_assignments::iterator p = this->symbol_assignments_.begin();
1109 p != this->symbol_assignments_.end();
1111 (*p)->add_to_table(symtab);
1112 this->script_sections_.add_symbols_to_table(symtab);
1115 // Finalize symbol values. Also check assertions.
1118 Script_options::finalize_symbols(Symbol_table* symtab, const Layout* layout)
1120 // We finalize the symbols defined in SECTIONS first, because they
1121 // are the ones which may have changed. This way if symbol outside
1122 // SECTIONS are defined in terms of symbols inside SECTIONS, they
1123 // will get the right value.
1124 this->script_sections_.finalize_symbols(symtab, layout);
1126 for (Symbol_assignments::iterator p = this->symbol_assignments_.begin();
1127 p != this->symbol_assignments_.end();
1129 (*p)->finalize(symtab, layout);
1131 for (Assertions::iterator p = this->assertions_.begin();
1132 p != this->assertions_.end();
1134 (*p)->check(symtab, layout);
1137 // Set section addresses. We set all the symbols which have absolute
1138 // values. Then we let the SECTIONS clause do its thing. This
1139 // returns the segment which holds the file header and segment
1143 Script_options::set_section_addresses(Symbol_table* symtab, Layout* layout)
1145 for (Symbol_assignments::iterator p = this->symbol_assignments_.begin();
1146 p != this->symbol_assignments_.end();
1148 (*p)->set_if_absolute(symtab, layout, false, 0);
1150 return this->script_sections_.set_section_addresses(symtab, layout);
1153 // This class holds data passed through the parser to the lexer and to
1154 // the parser support functions. This avoids global variables. We
1155 // can't use global variables because we need not be called by a
1156 // singleton thread.
1158 class Parser_closure
1161 Parser_closure(const char* filename,
1162 const Position_dependent_options& posdep_options,
1163 bool in_group, bool is_in_sysroot,
1164 Command_line* command_line,
1165 Script_options* script_options,
1167 bool skip_on_incompatible_target)
1168 : filename_(filename), posdep_options_(posdep_options),
1169 in_group_(in_group), is_in_sysroot_(is_in_sysroot),
1170 skip_on_incompatible_target_(skip_on_incompatible_target),
1171 found_incompatible_target_(false),
1172 command_line_(command_line), script_options_(script_options),
1173 version_script_info_(script_options->version_script_info()),
1174 lex_(lex), lineno_(0), charpos_(0), lex_mode_stack_(), inputs_(NULL)
1176 // We start out processing C symbols in the default lex mode.
1177 language_stack_.push_back("");
1178 lex_mode_stack_.push_back(lex->mode());
1181 // Return the file name.
1184 { return this->filename_; }
1186 // Return the position dependent options. The caller may modify
1188 Position_dependent_options&
1189 position_dependent_options()
1190 { return this->posdep_options_; }
1192 // Return whether this script is being run in a group.
1195 { return this->in_group_; }
1197 // Return whether this script was found using a directory in the
1200 is_in_sysroot() const
1201 { return this->is_in_sysroot_; }
1203 // Whether to skip to the next file with the same name if we find an
1204 // incompatible target in an OUTPUT_FORMAT statement.
1206 skip_on_incompatible_target() const
1207 { return this->skip_on_incompatible_target_; }
1209 // Stop skipping to the next flie on an incompatible target. This
1210 // is called when we make some unrevocable change to the data
1213 clear_skip_on_incompatible_target()
1214 { this->skip_on_incompatible_target_ = false; }
1216 // Whether we found an incompatible target in an OUTPUT_FORMAT
1219 found_incompatible_target() const
1220 { return this->found_incompatible_target_; }
1222 // Note that we found an incompatible target.
1224 set_found_incompatible_target()
1225 { this->found_incompatible_target_ = true; }
1227 // Returns the Command_line structure passed in at constructor time.
1228 // This value may be NULL. The caller may modify this, which modifies
1229 // the passed-in Command_line object (not a copy).
1232 { return this->command_line_; }
1234 // Return the options which may be set by a script.
1237 { return this->script_options_; }
1239 // Return the object in which version script information should be stored.
1240 Version_script_info*
1242 { return this->version_script_info_; }
1244 // Return the next token, and advance.
1248 const Token* token = this->lex_->next_token();
1249 this->lineno_ = token->lineno();
1250 this->charpos_ = token->charpos();
1254 // Set a new lexer mode, pushing the current one.
1256 push_lex_mode(Lex::Mode mode)
1258 this->lex_mode_stack_.push_back(this->lex_->mode());
1259 this->lex_->set_mode(mode);
1262 // Pop the lexer mode.
1266 gold_assert(!this->lex_mode_stack_.empty());
1267 this->lex_->set_mode(this->lex_mode_stack_.back());
1268 this->lex_mode_stack_.pop_back();
1271 // Return the current lexer mode.
1274 { return this->lex_mode_stack_.back(); }
1276 // Return the line number of the last token.
1279 { return this->lineno_; }
1281 // Return the character position in the line of the last token.
1284 { return this->charpos_; }
1286 // Return the list of input files, creating it if necessary. This
1287 // is a space leak--we never free the INPUTS_ pointer.
1291 if (this->inputs_ == NULL)
1292 this->inputs_ = new Input_arguments();
1293 return this->inputs_;
1296 // Return whether we saw any input files.
1299 { return this->inputs_ != NULL && !this->inputs_->empty(); }
1301 // Return the current language being processed in a version script
1302 // (eg, "C++"). The empty string represents unmangled C names.
1304 get_current_language() const
1305 { return this->language_stack_.back(); }
1307 // Push a language onto the stack when entering an extern block.
1308 void push_language(const std::string& lang)
1309 { this->language_stack_.push_back(lang); }
1311 // Pop a language off of the stack when exiting an extern block.
1314 gold_assert(!this->language_stack_.empty());
1315 this->language_stack_.pop_back();
1319 // The name of the file we are reading.
1320 const char* filename_;
1321 // The position dependent options.
1322 Position_dependent_options posdep_options_;
1323 // Whether we are currently in a --start-group/--end-group.
1325 // Whether the script was found in a sysrooted directory.
1326 bool is_in_sysroot_;
1327 // If this is true, then if we find an OUTPUT_FORMAT with an
1328 // incompatible target, then we tell the parser to abort so that we
1329 // can search for the next file with the same name.
1330 bool skip_on_incompatible_target_;
1331 // True if we found an OUTPUT_FORMAT with an incompatible target.
1332 bool found_incompatible_target_;
1333 // May be NULL if the user chooses not to pass one in.
1334 Command_line* command_line_;
1335 // Options which may be set from any linker script.
1336 Script_options* script_options_;
1337 // Information parsed from a version script.
1338 Version_script_info* version_script_info_;
1341 // The line number of the last token returned by next_token.
1343 // The column number of the last token returned by next_token.
1345 // A stack of lexer modes.
1346 std::vector<Lex::Mode> lex_mode_stack_;
1347 // A stack of which extern/language block we're inside. Can be C++,
1348 // java, or empty for C.
1349 std::vector<std::string> language_stack_;
1350 // New input files found to add to the link.
1351 Input_arguments* inputs_;
1354 // FILE was found as an argument on the command line. Try to read it
1355 // as a script. Return true if the file was handled.
1358 read_input_script(Workqueue* workqueue, Symbol_table* symtab, Layout* layout,
1359 Dirsearch* dirsearch, int dirindex,
1360 Input_objects* input_objects, Mapfile* mapfile,
1361 Input_group* input_group,
1362 const Input_argument* input_argument,
1363 Input_file* input_file, Task_token* next_blocker,
1364 bool* used_next_blocker)
1366 *used_next_blocker = false;
1368 std::string input_string;
1369 Lex::read_file(input_file, &input_string);
1371 Lex lex(input_string.c_str(), input_string.length(), PARSING_LINKER_SCRIPT);
1373 Parser_closure closure(input_file->filename().c_str(),
1374 input_argument->file().options(),
1375 input_group != NULL,
1376 input_file->is_in_sysroot(),
1378 layout->script_options(),
1380 input_file->will_search_for());
1382 if (yyparse(&closure) != 0)
1384 if (closure.found_incompatible_target())
1386 Read_symbols::incompatible_warning(input_argument, input_file);
1387 Read_symbols::requeue(workqueue, input_objects, symtab, layout,
1388 dirsearch, dirindex, mapfile, input_argument,
1389 input_group, next_blocker);
1395 if (!closure.saw_inputs())
1398 Task_token* this_blocker = NULL;
1399 for (Input_arguments::const_iterator p = closure.inputs()->begin();
1400 p != closure.inputs()->end();
1404 if (p + 1 == closure.inputs()->end())
1408 nb = new Task_token(true);
1411 workqueue->queue_soon(new Read_symbols(input_objects, symtab,
1412 layout, dirsearch, 0, mapfile, &*p,
1413 input_group, this_blocker, nb));
1417 *used_next_blocker = true;
1422 // Helper function for read_version_script() and
1423 // read_commandline_script(). Processes the given file in the mode
1424 // indicated by first_token and lex_mode.
1427 read_script_file(const char* filename, Command_line* cmdline,
1428 Script_options* script_options,
1429 int first_token, Lex::Mode lex_mode)
1431 // TODO: if filename is a relative filename, search for it manually
1432 // using "." + cmdline->options()->search_path() -- not dirsearch.
1433 Dirsearch dirsearch;
1435 // The file locking code wants to record a Task, but we haven't
1436 // started the workqueue yet. This is only for debugging purposes,
1437 // so we invent a fake value.
1438 const Task* task = reinterpret_cast<const Task*>(-1);
1440 // We don't want this file to be opened in binary mode.
1441 Position_dependent_options posdep = cmdline->position_dependent_options();
1442 if (posdep.format_enum() == General_options::OBJECT_FORMAT_BINARY)
1443 posdep.set_format_enum(General_options::OBJECT_FORMAT_ELF);
1444 Input_file_argument input_argument(filename, false, "", false, posdep);
1445 Input_file input_file(&input_argument);
1447 if (!input_file.open(dirsearch, task, &dummy))
1450 std::string input_string;
1451 Lex::read_file(&input_file, &input_string);
1453 Lex lex(input_string.c_str(), input_string.length(), first_token);
1454 lex.set_mode(lex_mode);
1456 Parser_closure closure(filename,
1457 cmdline->position_dependent_options(),
1459 input_file.is_in_sysroot(),
1464 if (yyparse(&closure) != 0)
1466 input_file.file().unlock(task);
1470 input_file.file().unlock(task);
1472 gold_assert(!closure.saw_inputs());
1477 // FILENAME was found as an argument to --script (-T).
1478 // Read it as a script, and execute its contents immediately.
1481 read_commandline_script(const char* filename, Command_line* cmdline)
1483 return read_script_file(filename, cmdline, &cmdline->script_options(),
1484 PARSING_LINKER_SCRIPT, Lex::LINKER_SCRIPT);
1487 // FILENAME was found as an argument to --version-script. Read it as
1488 // a version script, and store its contents in
1489 // cmdline->script_options()->version_script_info().
1492 read_version_script(const char* filename, Command_line* cmdline)
1494 return read_script_file(filename, cmdline, &cmdline->script_options(),
1495 PARSING_VERSION_SCRIPT, Lex::VERSION_SCRIPT);
1498 // FILENAME was found as an argument to --dynamic-list. Read it as a
1499 // list of symbols, and store its contents in DYNAMIC_LIST.
1502 read_dynamic_list(const char* filename, Command_line* cmdline,
1503 Script_options* dynamic_list)
1505 return read_script_file(filename, cmdline, dynamic_list,
1506 PARSING_DYNAMIC_LIST, Lex::DYNAMIC_LIST);
1509 // Implement the --defsym option on the command line. Return true if
1513 Script_options::define_symbol(const char* definition)
1515 Lex lex(definition, strlen(definition), PARSING_DEFSYM);
1516 lex.set_mode(Lex::EXPRESSION);
1519 Position_dependent_options posdep_options;
1521 Parser_closure closure("command line", posdep_options, false, false, NULL,
1524 if (yyparse(&closure) != 0)
1527 gold_assert(!closure.saw_inputs());
1532 // Print the script to F for debugging.
1535 Script_options::print(FILE* f) const
1537 fprintf(f, "%s: Dumping linker script\n", program_name);
1539 if (!this->entry_.empty())
1540 fprintf(f, "ENTRY(%s)\n", this->entry_.c_str());
1542 for (Symbol_assignments::const_iterator p =
1543 this->symbol_assignments_.begin();
1544 p != this->symbol_assignments_.end();
1548 for (Assertions::const_iterator p = this->assertions_.begin();
1549 p != this->assertions_.end();
1553 this->script_sections_.print(f);
1555 this->version_script_info_.print(f);
1558 // Manage mapping from keywords to the codes expected by the bison
1559 // parser. We construct one global object for each lex mode with
1562 class Keyword_to_parsecode
1565 // The structure which maps keywords to parsecodes.
1566 struct Keyword_parsecode
1569 const char* keyword;
1570 // Corresponding parsecode.
1574 Keyword_to_parsecode(const Keyword_parsecode* keywords,
1576 : keyword_parsecodes_(keywords), keyword_count_(keyword_count)
1579 // Return the parsecode corresponding KEYWORD, or 0 if it is not a
1582 keyword_to_parsecode(const char* keyword, size_t len) const;
1585 const Keyword_parsecode* keyword_parsecodes_;
1586 const int keyword_count_;
1589 // Mapping from keyword string to keyword parsecode. This array must
1590 // be kept in sorted order. Parsecodes are looked up using bsearch.
1591 // This array must correspond to the list of parsecodes in yyscript.y.
1593 static const Keyword_to_parsecode::Keyword_parsecode
1594 script_keyword_parsecodes[] =
1596 { "ABSOLUTE", ABSOLUTE },
1598 { "ALIGN", ALIGN_K },
1599 { "ALIGNOF", ALIGNOF },
1600 { "ASSERT", ASSERT_K },
1601 { "AS_NEEDED", AS_NEEDED },
1606 { "CONSTANT", CONSTANT },
1607 { "CONSTRUCTORS", CONSTRUCTORS },
1608 { "CREATE_OBJECT_SYMBOLS", CREATE_OBJECT_SYMBOLS },
1609 { "DATA_SEGMENT_ALIGN", DATA_SEGMENT_ALIGN },
1610 { "DATA_SEGMENT_END", DATA_SEGMENT_END },
1611 { "DATA_SEGMENT_RELRO_END", DATA_SEGMENT_RELRO_END },
1612 { "DEFINED", DEFINED },
1614 { "EXCLUDE_FILE", EXCLUDE_FILE },
1615 { "EXTERN", EXTERN },
1618 { "FORCE_COMMON_ALLOCATION", FORCE_COMMON_ALLOCATION },
1621 { "INCLUDE", INCLUDE },
1622 { "INHIBIT_COMMON_ALLOCATION", INHIBIT_COMMON_ALLOCATION },
1625 { "LENGTH", LENGTH },
1626 { "LOADADDR", LOADADDR },
1630 { "MEMORY", MEMORY },
1633 { "NOCROSSREFS", NOCROSSREFS },
1634 { "NOFLOAT", NOFLOAT },
1635 { "ONLY_IF_RO", ONLY_IF_RO },
1636 { "ONLY_IF_RW", ONLY_IF_RW },
1637 { "OPTION", OPTION },
1638 { "ORIGIN", ORIGIN },
1639 { "OUTPUT", OUTPUT },
1640 { "OUTPUT_ARCH", OUTPUT_ARCH },
1641 { "OUTPUT_FORMAT", OUTPUT_FORMAT },
1642 { "OVERLAY", OVERLAY },
1644 { "PROVIDE", PROVIDE },
1645 { "PROVIDE_HIDDEN", PROVIDE_HIDDEN },
1647 { "SEARCH_DIR", SEARCH_DIR },
1648 { "SECTIONS", SECTIONS },
1649 { "SEGMENT_START", SEGMENT_START },
1651 { "SIZEOF", SIZEOF },
1652 { "SIZEOF_HEADERS", SIZEOF_HEADERS },
1653 { "SORT", SORT_BY_NAME },
1654 { "SORT_BY_ALIGNMENT", SORT_BY_ALIGNMENT },
1655 { "SORT_BY_NAME", SORT_BY_NAME },
1656 { "SPECIAL", SPECIAL },
1658 { "STARTUP", STARTUP },
1659 { "SUBALIGN", SUBALIGN },
1660 { "SYSLIB", SYSLIB },
1661 { "TARGET", TARGET_K },
1662 { "TRUNCATE", TRUNCATE },
1663 { "VERSION", VERSIONK },
1664 { "global", GLOBAL },
1670 { "sizeof_headers", SIZEOF_HEADERS },
1673 static const Keyword_to_parsecode
1674 script_keywords(&script_keyword_parsecodes[0],
1675 (sizeof(script_keyword_parsecodes)
1676 / sizeof(script_keyword_parsecodes[0])));
1678 static const Keyword_to_parsecode::Keyword_parsecode
1679 version_script_keyword_parsecodes[] =
1681 { "extern", EXTERN },
1682 { "global", GLOBAL },
1686 static const Keyword_to_parsecode
1687 version_script_keywords(&version_script_keyword_parsecodes[0],
1688 (sizeof(version_script_keyword_parsecodes)
1689 / sizeof(version_script_keyword_parsecodes[0])));
1691 static const Keyword_to_parsecode::Keyword_parsecode
1692 dynamic_list_keyword_parsecodes[] =
1694 { "extern", EXTERN },
1697 static const Keyword_to_parsecode
1698 dynamic_list_keywords(&dynamic_list_keyword_parsecodes[0],
1699 (sizeof(dynamic_list_keyword_parsecodes)
1700 / sizeof(dynamic_list_keyword_parsecodes[0])));
1704 // Comparison function passed to bsearch.
1716 ktt_compare(const void* keyv, const void* kttv)
1718 const Ktt_key* key = static_cast<const Ktt_key*>(keyv);
1719 const Keyword_to_parsecode::Keyword_parsecode* ktt =
1720 static_cast<const Keyword_to_parsecode::Keyword_parsecode*>(kttv);
1721 int i = strncmp(key->str, ktt->keyword, key->len);
1724 if (ktt->keyword[key->len] != '\0')
1729 } // End extern "C".
1732 Keyword_to_parsecode::keyword_to_parsecode(const char* keyword,
1738 void* kttv = bsearch(&key,
1739 this->keyword_parsecodes_,
1740 this->keyword_count_,
1741 sizeof(this->keyword_parsecodes_[0]),
1745 Keyword_parsecode* ktt = static_cast<Keyword_parsecode*>(kttv);
1746 return ktt->parsecode;
1749 // Helper class that calls cplus_demangle when needed and takes care of freeing
1752 class Lazy_demangler
1755 Lazy_demangler(const char* symbol, int options)
1756 : symbol_(symbol), options_(options), demangled_(NULL), did_demangle_(false)
1760 { free(this->demangled_); }
1762 // Return the demangled name. The actual demangling happens on the first call,
1763 // and the result is later cached.
1769 // The symbol to demangle.
1770 const char *symbol_;
1771 // Option flags to pass to cplus_demagle.
1773 // The cached demangled value, or NULL if demangling didn't happen yet or
1776 // Whether we already called cplus_demangle
1780 // Return the demangled name. The actual demangling happens on the first call,
1781 // and the result is later cached. Returns NULL if the symbol cannot be
1785 Lazy_demangler::get()
1787 if (!this->did_demangle_)
1789 this->demangled_ = cplus_demangle(this->symbol_, this->options_);
1790 this->did_demangle_ = true;
1792 return this->demangled_;
1795 // The following structs are used within the VersionInfo class as well
1796 // as in the bison helper functions. They store the information
1797 // parsed from the version script.
1799 // A single version expression.
1800 // For example, pattern="std::map*" and language="C++".
1801 // pattern and language should be from the stringpool
1802 struct Version_expression {
1803 Version_expression(const std::string& pattern,
1804 const std::string& language,
1806 : pattern(pattern), language(language), exact_match(exact_match) {}
1808 std::string pattern;
1809 std::string language;
1810 // If false, we use glob() to match pattern. If true, we use strcmp().
1815 // A list of expressions.
1816 struct Version_expression_list {
1817 std::vector<struct Version_expression> expressions;
1821 // A list of which versions upon which another version depends.
1822 // Strings should be from the Stringpool.
1823 struct Version_dependency_list {
1824 std::vector<std::string> dependencies;
1828 // The total definition of a version. It includes the tag for the
1829 // version, its global and local expressions, and any dependencies.
1830 struct Version_tree {
1832 : tag(), global(NULL), local(NULL), dependencies(NULL) {}
1835 const struct Version_expression_list* global;
1836 const struct Version_expression_list* local;
1837 const struct Version_dependency_list* dependencies;
1840 Version_script_info::~Version_script_info()
1846 Version_script_info::clear()
1848 for (size_t k = 0; k < dependency_lists_.size(); ++k)
1849 delete dependency_lists_[k];
1850 this->dependency_lists_.clear();
1851 for (size_t k = 0; k < version_trees_.size(); ++k)
1852 delete version_trees_[k];
1853 this->version_trees_.clear();
1854 for (size_t k = 0; k < expression_lists_.size(); ++k)
1855 delete expression_lists_[k];
1856 this->expression_lists_.clear();
1859 std::vector<std::string>
1860 Version_script_info::get_versions() const
1862 std::vector<std::string> ret;
1863 for (size_t j = 0; j < version_trees_.size(); ++j)
1864 if (!this->version_trees_[j]->tag.empty())
1865 ret.push_back(this->version_trees_[j]->tag);
1869 std::vector<std::string>
1870 Version_script_info::get_dependencies(const char* version) const
1872 std::vector<std::string> ret;
1873 for (size_t j = 0; j < version_trees_.size(); ++j)
1874 if (version_trees_[j]->tag == version)
1876 const struct Version_dependency_list* deps =
1877 version_trees_[j]->dependencies;
1879 for (size_t k = 0; k < deps->dependencies.size(); ++k)
1880 ret.push_back(deps->dependencies[k]);
1886 // Look up SYMBOL_NAME in the list of versions. If CHECK_GLOBAL is
1887 // true look at the globally visible symbols, otherwise look at the
1888 // symbols listed as "local:". Return true if the symbol is found,
1889 // false otherwise. If the symbol is found, then if PVERSION is not
1890 // NULL, set *PVERSION to the version.
1893 Version_script_info::get_symbol_version_helper(const char* symbol_name,
1895 std::string* pversion) const
1897 Lazy_demangler cpp_demangled_name(symbol_name, DMGL_ANSI | DMGL_PARAMS);
1898 Lazy_demangler java_demangled_name(symbol_name,
1899 DMGL_ANSI | DMGL_PARAMS | DMGL_JAVA);
1900 for (size_t j = 0; j < version_trees_.size(); ++j)
1902 // Is it a global symbol for this version?
1903 const Version_expression_list* explist =
1904 check_global ? version_trees_[j]->global : version_trees_[j]->local;
1905 if (explist != NULL)
1906 for (size_t k = 0; k < explist->expressions.size(); ++k)
1908 const char* name_to_match = symbol_name;
1909 const struct Version_expression& exp = explist->expressions[k];
1910 if (exp.language == "C++")
1912 name_to_match = cpp_demangled_name.get();
1913 // This isn't a C++ symbol.
1914 if (name_to_match == NULL)
1917 else if (exp.language == "Java")
1919 name_to_match = java_demangled_name.get();
1920 // This isn't a Java symbol.
1921 if (name_to_match == NULL)
1925 if (exp.exact_match)
1926 matched = strcmp(exp.pattern.c_str(), name_to_match) == 0;
1928 matched = fnmatch(exp.pattern.c_str(), name_to_match,
1932 if (pversion != NULL)
1933 *pversion = this->version_trees_[j]->tag;
1941 struct Version_dependency_list*
1942 Version_script_info::allocate_dependency_list()
1944 dependency_lists_.push_back(new Version_dependency_list);
1945 return dependency_lists_.back();
1948 struct Version_expression_list*
1949 Version_script_info::allocate_expression_list()
1951 expression_lists_.push_back(new Version_expression_list);
1952 return expression_lists_.back();
1955 struct Version_tree*
1956 Version_script_info::allocate_version_tree()
1958 version_trees_.push_back(new Version_tree);
1959 return version_trees_.back();
1962 // Print for debugging.
1965 Version_script_info::print(FILE* f) const
1970 fprintf(f, "VERSION {");
1972 for (size_t i = 0; i < this->version_trees_.size(); ++i)
1974 const Version_tree* vt = this->version_trees_[i];
1976 if (vt->tag.empty())
1979 fprintf(f, " %s {\n", vt->tag.c_str());
1981 if (vt->global != NULL)
1983 fprintf(f, " global :\n");
1984 this->print_expression_list(f, vt->global);
1987 if (vt->local != NULL)
1989 fprintf(f, " local :\n");
1990 this->print_expression_list(f, vt->local);
1994 if (vt->dependencies != NULL)
1996 const Version_dependency_list* deps = vt->dependencies;
1997 for (size_t j = 0; j < deps->dependencies.size(); ++j)
1999 if (j < deps->dependencies.size() - 1)
2001 fprintf(f, " %s", deps->dependencies[j].c_str());
2011 Version_script_info::print_expression_list(
2013 const Version_expression_list* vel) const
2015 std::string current_language;
2016 for (size_t i = 0; i < vel->expressions.size(); ++i)
2018 const Version_expression& ve(vel->expressions[i]);
2020 if (ve.language != current_language)
2022 if (!current_language.empty())
2024 fprintf(f, " extern \"%s\" {\n", ve.language.c_str());
2025 current_language = ve.language;
2029 if (!current_language.empty())
2034 fprintf(f, "%s", ve.pattern.c_str());
2041 if (!current_language.empty())
2045 } // End namespace gold.
2047 // The remaining functions are extern "C", so it's clearer to not put
2048 // them in namespace gold.
2050 using namespace gold;
2052 // This function is called by the bison parser to return the next
2056 yylex(YYSTYPE* lvalp, void* closurev)
2058 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2059 const Token* token = closure->next_token();
2060 switch (token->classification())
2065 case Token::TOKEN_INVALID:
2066 yyerror(closurev, "invalid character");
2069 case Token::TOKEN_EOF:
2072 case Token::TOKEN_STRING:
2074 // This is either a keyword or a STRING.
2076 const char* str = token->string_value(&len);
2078 switch (closure->lex_mode())
2080 case Lex::LINKER_SCRIPT:
2081 parsecode = script_keywords.keyword_to_parsecode(str, len);
2083 case Lex::VERSION_SCRIPT:
2084 parsecode = version_script_keywords.keyword_to_parsecode(str, len);
2086 case Lex::DYNAMIC_LIST:
2087 parsecode = dynamic_list_keywords.keyword_to_parsecode(str, len);
2094 lvalp->string.value = str;
2095 lvalp->string.length = len;
2099 case Token::TOKEN_QUOTED_STRING:
2100 lvalp->string.value = token->string_value(&lvalp->string.length);
2101 return QUOTED_STRING;
2103 case Token::TOKEN_OPERATOR:
2104 return token->operator_value();
2106 case Token::TOKEN_INTEGER:
2107 lvalp->integer = token->integer_value();
2112 // This function is called by the bison parser to report an error.
2115 yyerror(void* closurev, const char* message)
2117 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2118 gold_error(_("%s:%d:%d: %s"), closure->filename(), closure->lineno(),
2119 closure->charpos(), message);
2122 // Called by the bison parser to add a file to the link.
2125 script_add_file(void* closurev, const char* name, size_t length)
2127 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2129 // If this is an absolute path, and we found the script in the
2130 // sysroot, then we want to prepend the sysroot to the file name.
2131 // For example, this is how we handle a cross link to the x86_64
2132 // libc.so, which refers to /lib/libc.so.6.
2133 std::string name_string(name, length);
2134 const char* extra_search_path = ".";
2135 std::string script_directory;
2136 if (IS_ABSOLUTE_PATH(name_string.c_str()))
2138 if (closure->is_in_sysroot())
2140 const std::string& sysroot(parameters->options().sysroot());
2141 gold_assert(!sysroot.empty());
2142 name_string = sysroot + name_string;
2147 // In addition to checking the normal library search path, we
2148 // also want to check in the script-directory.
2149 const char *slash = strrchr(closure->filename(), '/');
2152 script_directory.assign(closure->filename(),
2153 slash - closure->filename() + 1);
2154 extra_search_path = script_directory.c_str();
2158 Input_file_argument file(name_string.c_str(), false, extra_search_path,
2159 false, closure->position_dependent_options());
2160 closure->inputs()->add_file(file);
2163 // Called by the bison parser to start a group. If we are already in
2164 // a group, that means that this script was invoked within a
2165 // --start-group --end-group sequence on the command line, or that
2166 // this script was found in a GROUP of another script. In that case,
2167 // we simply continue the existing group, rather than starting a new
2168 // one. It is possible to construct a case in which this will do
2169 // something other than what would happen if we did a recursive group,
2170 // but it's hard to imagine why the different behaviour would be
2171 // useful for a real program. Avoiding recursive groups is simpler
2172 // and more efficient.
2175 script_start_group(void* closurev)
2177 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2178 if (!closure->in_group())
2179 closure->inputs()->start_group();
2182 // Called by the bison parser at the end of a group.
2185 script_end_group(void* closurev)
2187 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2188 if (!closure->in_group())
2189 closure->inputs()->end_group();
2192 // Called by the bison parser to start an AS_NEEDED list.
2195 script_start_as_needed(void* closurev)
2197 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2198 closure->position_dependent_options().set_as_needed(true);
2201 // Called by the bison parser at the end of an AS_NEEDED list.
2204 script_end_as_needed(void* closurev)
2206 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2207 closure->position_dependent_options().set_as_needed(false);
2210 // Called by the bison parser to set the entry symbol.
2213 script_set_entry(void* closurev, const char* entry, size_t length)
2215 // We'll parse this exactly the same as --entry=ENTRY on the commandline
2216 // TODO(csilvers): FIXME -- call set_entry directly.
2217 std::string arg("--entry=");
2218 arg.append(entry, length);
2219 script_parse_option(closurev, arg.c_str(), arg.size());
2222 // Called by the bison parser to set whether to define common symbols.
2225 script_set_common_allocation(void* closurev, int set)
2227 const char* arg = set != 0 ? "--define-common" : "--no-define-common";
2228 script_parse_option(closurev, arg, strlen(arg));
2231 // Called by the bison parser to define a symbol.
2234 script_set_symbol(void* closurev, const char* name, size_t length,
2235 Expression* value, int providei, int hiddeni)
2237 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2238 const bool provide = providei != 0;
2239 const bool hidden = hiddeni != 0;
2240 closure->script_options()->add_symbol_assignment(name, length, value,
2242 closure->clear_skip_on_incompatible_target();
2245 // Called by the bison parser to add an assertion.
2248 script_add_assertion(void* closurev, Expression* check, const char* message,
2251 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2252 closure->script_options()->add_assertion(check, message, messagelen);
2253 closure->clear_skip_on_incompatible_target();
2256 // Called by the bison parser to parse an OPTION.
2259 script_parse_option(void* closurev, const char* option, size_t length)
2261 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2262 // We treat the option as a single command-line option, even if
2263 // it has internal whitespace.
2264 if (closure->command_line() == NULL)
2266 // There are some options that we could handle here--e.g.,
2267 // -lLIBRARY. Should we bother?
2268 gold_warning(_("%s:%d:%d: ignoring command OPTION; OPTION is only valid"
2269 " for scripts specified via -T/--script"),
2270 closure->filename(), closure->lineno(), closure->charpos());
2274 bool past_a_double_dash_option = false;
2275 const char* mutable_option = strndup(option, length);
2276 gold_assert(mutable_option != NULL);
2277 closure->command_line()->process_one_option(1, &mutable_option, 0,
2278 &past_a_double_dash_option);
2279 // The General_options class will quite possibly store a pointer
2280 // into mutable_option, so we can't free it. In cases the class
2281 // does not store such a pointer, this is a memory leak. Alas. :(
2283 closure->clear_skip_on_incompatible_target();
2286 // Called by the bison parser to handle OUTPUT_FORMAT. OUTPUT_FORMAT
2287 // takes either one or three arguments. In the three argument case,
2288 // the format depends on the endianness option, which we don't
2289 // currently support (FIXME). If we see an OUTPUT_FORMAT for the
2290 // wrong format, then we want to search for a new file. Returning 0
2291 // here will cause the parser to immediately abort.
2294 script_check_output_format(void* closurev,
2295 const char* default_name, size_t default_length,
2296 const char*, size_t, const char*, size_t)
2298 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2299 std::string name(default_name, default_length);
2300 Target* target = select_target_by_name(name.c_str());
2301 if (target == NULL || !parameters->is_compatible_target(target))
2303 if (closure->skip_on_incompatible_target())
2305 closure->set_found_incompatible_target();
2308 // FIXME: Should we warn about the unknown target?
2313 // Called by the bison parser to handle SEARCH_DIR. This is handled
2314 // exactly like a -L option.
2317 script_add_search_dir(void* closurev, const char* option, size_t length)
2319 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2320 if (closure->command_line() == NULL)
2321 gold_warning(_("%s:%d:%d: ignoring SEARCH_DIR; SEARCH_DIR is only valid"
2322 " for scripts specified via -T/--script"),
2323 closure->filename(), closure->lineno(), closure->charpos());
2326 std::string s = "-L" + std::string(option, length);
2327 script_parse_option(closurev, s.c_str(), s.size());
2331 /* Called by the bison parser to push the lexer into expression
2335 script_push_lex_into_expression_mode(void* closurev)
2337 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2338 closure->push_lex_mode(Lex::EXPRESSION);
2341 /* Called by the bison parser to push the lexer into version
2345 script_push_lex_into_version_mode(void* closurev)
2347 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2348 closure->push_lex_mode(Lex::VERSION_SCRIPT);
2351 /* Called by the bison parser to pop the lexer mode. */
2354 script_pop_lex_mode(void* closurev)
2356 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2357 closure->pop_lex_mode();
2360 // Register an entire version node. For example:
2366 // - tag is "GLIBC_2.1"
2367 // - tree contains the information "global: foo"
2368 // - deps contains "GLIBC_2.0"
2371 script_register_vers_node(void*,
2374 struct Version_tree *tree,
2375 struct Version_dependency_list *deps)
2377 gold_assert(tree != NULL);
2378 tree->dependencies = deps;
2380 tree->tag = std::string(tag, taglen);
2383 // Add a dependencies to the list of existing dependencies, if any,
2384 // and return the expanded list.
2386 extern "C" struct Version_dependency_list *
2387 script_add_vers_depend(void* closurev,
2388 struct Version_dependency_list *all_deps,
2389 const char *depend_to_add, int deplen)
2391 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2392 if (all_deps == NULL)
2393 all_deps = closure->version_script()->allocate_dependency_list();
2394 all_deps->dependencies.push_back(std::string(depend_to_add, deplen));
2398 // Add a pattern expression to an existing list of expressions, if any.
2399 // TODO: In the old linker, the last argument used to be a bool, but I
2400 // don't know what it meant.
2402 extern "C" struct Version_expression_list *
2403 script_new_vers_pattern(void* closurev,
2404 struct Version_expression_list *expressions,
2405 const char *pattern, int patlen, int exact_match)
2407 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2408 if (expressions == NULL)
2409 expressions = closure->version_script()->allocate_expression_list();
2410 expressions->expressions.push_back(
2411 Version_expression(std::string(pattern, patlen),
2412 closure->get_current_language(),
2413 static_cast<bool>(exact_match)));
2417 // Attaches b to the end of a, and clears b. So a = a + b and b = {}.
2419 extern "C" struct Version_expression_list*
2420 script_merge_expressions(struct Version_expression_list *a,
2421 struct Version_expression_list *b)
2423 a->expressions.insert(a->expressions.end(),
2424 b->expressions.begin(), b->expressions.end());
2425 // We could delete b and remove it from expressions_lists_, but
2426 // that's a lot of work. This works just as well.
2427 b->expressions.clear();
2431 // Combine the global and local expressions into a a Version_tree.
2433 extern "C" struct Version_tree *
2434 script_new_vers_node(void* closurev,
2435 struct Version_expression_list *global,
2436 struct Version_expression_list *local)
2438 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2439 Version_tree* tree = closure->version_script()->allocate_version_tree();
2440 tree->global = global;
2441 tree->local = local;
2445 // Handle a transition in language, such as at the
2446 // start or end of 'extern "C++"'
2449 version_script_push_lang(void* closurev, const char* lang, int langlen)
2451 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2452 closure->push_language(std::string(lang, langlen));
2456 version_script_pop_lang(void* closurev)
2458 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2459 closure->pop_language();
2462 // Called by the bison parser to start a SECTIONS clause.
2465 script_start_sections(void* closurev)
2467 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2468 closure->script_options()->script_sections()->start_sections();
2469 closure->clear_skip_on_incompatible_target();
2472 // Called by the bison parser to finish a SECTIONS clause.
2475 script_finish_sections(void* closurev)
2477 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2478 closure->script_options()->script_sections()->finish_sections();
2481 // Start processing entries for an output section.
2484 script_start_output_section(void* closurev, const char* name, size_t namelen,
2485 const struct Parser_output_section_header* header)
2487 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2488 closure->script_options()->script_sections()->start_output_section(name,
2493 // Finish processing entries for an output section.
2496 script_finish_output_section(void* closurev,
2497 const struct Parser_output_section_trailer* trail)
2499 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2500 closure->script_options()->script_sections()->finish_output_section(trail);
2503 // Add a data item (e.g., "WORD (0)") to the current output section.
2506 script_add_data(void* closurev, int data_token, Expression* val)
2508 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2510 bool is_signed = true;
2532 closure->script_options()->script_sections()->add_data(size, is_signed, val);
2535 // Add a clause setting the fill value to the current output section.
2538 script_add_fill(void* closurev, Expression* val)
2540 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2541 closure->script_options()->script_sections()->add_fill(val);
2544 // Add a new input section specification to the current output
2548 script_add_input_section(void* closurev,
2549 const struct Input_section_spec* spec,
2552 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2553 bool keep = keepi != 0;
2554 closure->script_options()->script_sections()->add_input_section(spec, keep);
2557 // When we see DATA_SEGMENT_ALIGN we record that following output
2558 // sections may be relro.
2561 script_data_segment_align(void* closurev)
2563 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2564 if (!closure->script_options()->saw_sections_clause())
2565 gold_error(_("%s:%d:%d: DATA_SEGMENT_ALIGN not in SECTIONS clause"),
2566 closure->filename(), closure->lineno(), closure->charpos());
2568 closure->script_options()->script_sections()->data_segment_align();
2571 // When we see DATA_SEGMENT_RELRO_END we know that all output sections
2572 // since DATA_SEGMENT_ALIGN should be relro.
2575 script_data_segment_relro_end(void* closurev)
2577 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2578 if (!closure->script_options()->saw_sections_clause())
2579 gold_error(_("%s:%d:%d: DATA_SEGMENT_ALIGN not in SECTIONS clause"),
2580 closure->filename(), closure->lineno(), closure->charpos());
2582 closure->script_options()->script_sections()->data_segment_relro_end();
2585 // Create a new list of string/sort pairs.
2587 extern "C" String_sort_list_ptr
2588 script_new_string_sort_list(const struct Wildcard_section* string_sort)
2590 return new String_sort_list(1, *string_sort);
2593 // Add an entry to a list of string/sort pairs. The way the parser
2594 // works permits us to simply modify the first parameter, rather than
2597 extern "C" String_sort_list_ptr
2598 script_string_sort_list_add(String_sort_list_ptr pv,
2599 const struct Wildcard_section* string_sort)
2602 return script_new_string_sort_list(string_sort);
2605 pv->push_back(*string_sort);
2610 // Create a new list of strings.
2612 extern "C" String_list_ptr
2613 script_new_string_list(const char* str, size_t len)
2615 return new String_list(1, std::string(str, len));
2618 // Add an element to a list of strings. The way the parser works
2619 // permits us to simply modify the first parameter, rather than copy
2622 extern "C" String_list_ptr
2623 script_string_list_push_back(String_list_ptr pv, const char* str, size_t len)
2626 return script_new_string_list(str, len);
2629 pv->push_back(std::string(str, len));
2634 // Concatenate two string lists. Either or both may be NULL. The way
2635 // the parser works permits us to modify the parameters, rather than
2638 extern "C" String_list_ptr
2639 script_string_list_append(String_list_ptr pv1, String_list_ptr pv2)
2645 pv1->insert(pv1->end(), pv2->begin(), pv2->end());
2649 // Add a new program header.
2652 script_add_phdr(void* closurev, const char* name, size_t namelen,
2653 unsigned int type, const Phdr_info* info)
2655 Parser_closure* closure = static_cast<Parser_closure*>(closurev);
2656 bool includes_filehdr = info->includes_filehdr != 0;
2657 bool includes_phdrs = info->includes_phdrs != 0;
2658 bool is_flags_valid = info->is_flags_valid != 0;
2659 Script_sections* ss = closure->script_options()->script_sections();
2660 ss->add_phdr(name, namelen, type, includes_filehdr, includes_phdrs,
2661 is_flags_valid, info->flags, info->load_address);
2662 closure->clear_skip_on_incompatible_target();
2665 // Convert a program header string to a type.
2667 #define PHDR_TYPE(NAME) { #NAME, sizeof(#NAME) - 1, elfcpp::NAME }
2674 } phdr_type_names[] =
2678 PHDR_TYPE(PT_DYNAMIC),
2679 PHDR_TYPE(PT_INTERP),
2681 PHDR_TYPE(PT_SHLIB),
2684 PHDR_TYPE(PT_GNU_EH_FRAME),
2685 PHDR_TYPE(PT_GNU_STACK),
2686 PHDR_TYPE(PT_GNU_RELRO)
2689 extern "C" unsigned int
2690 script_phdr_string_to_type(void* closurev, const char* name, size_t namelen)
2692 for (unsigned int i = 0;
2693 i < sizeof(phdr_type_names) / sizeof(phdr_type_names[0]);
2695 if (namelen == phdr_type_names[i].namelen
2696 && strncmp(name, phdr_type_names[i].name, namelen) == 0)
2697 return phdr_type_names[i].val;
2698 yyerror(closurev, _("unknown PHDR type (try integer)"));
2699 return elfcpp::PT_NULL;