146b69c69SDimitry Andric //===- ScriptLexer.cpp ----------------------------------------------------===//
246b69c69SDimitry Andric //
346b69c69SDimitry Andric //                             The LLVM Linker
446b69c69SDimitry Andric //
546b69c69SDimitry Andric // This file is distributed under the University of Illinois Open Source
646b69c69SDimitry Andric // License. See LICENSE.TXT for details.
746b69c69SDimitry Andric //
846b69c69SDimitry Andric //===----------------------------------------------------------------------===//
946b69c69SDimitry Andric //
1046b69c69SDimitry Andric // This file defines a lexer for the linker script.
1146b69c69SDimitry Andric //
1246b69c69SDimitry Andric // The linker script's grammar is not complex but ambiguous due to the
1346b69c69SDimitry Andric // lack of the formal specification of the language. What we are trying to
1446b69c69SDimitry Andric // do in this and other files in LLD is to make a "reasonable" linker
1546b69c69SDimitry Andric // script processor.
1646b69c69SDimitry Andric //
1746b69c69SDimitry Andric // Among simplicity, compatibility and efficiency, we put the most
1846b69c69SDimitry Andric // emphasis on simplicity when we wrote this lexer. Compatibility with the
1946b69c69SDimitry Andric // GNU linkers is important, but we did not try to clone every tiny corner
2046b69c69SDimitry Andric // case of their lexers, as even ld.bfd and ld.gold are subtly different
2146b69c69SDimitry Andric // in various corner cases. We do not care much about efficiency because
2246b69c69SDimitry Andric // the time spent in parsing linker scripts is usually negligible.
2346b69c69SDimitry Andric //
2446b69c69SDimitry Andric // Our grammar of the linker script is LL(2), meaning that it needs at
2546b69c69SDimitry Andric // most two-token lookahead to parse. The only place we need two-token
2646b69c69SDimitry Andric // lookahead is labels in version scripts, where we need to parse "local :"
2746b69c69SDimitry Andric // as if "local:".
2846b69c69SDimitry Andric //
2946b69c69SDimitry Andric // Overall, this lexer works fine for most linker scripts. There might
3046b69c69SDimitry Andric // be room for improving compatibility, but that's probably not at the
3146b69c69SDimitry Andric // top of our todo list.
3246b69c69SDimitry Andric //
3346b69c69SDimitry Andric //===----------------------------------------------------------------------===//
3446b69c69SDimitry Andric 
3546b69c69SDimitry Andric #include "ScriptLexer.h"
3610dc89a5SDimitry Andric #include "lld/Common/ErrorHandler.h"
3746b69c69SDimitry Andric #include "llvm/ADT/Twine.h"
3846b69c69SDimitry Andric 
3946b69c69SDimitry Andric using namespace llvm;
4046b69c69SDimitry Andric using namespace lld;
4146b69c69SDimitry Andric using namespace lld::elf;
4246b69c69SDimitry Andric 
4346b69c69SDimitry Andric // Returns a whole line containing the current token.
4446b69c69SDimitry Andric StringRef ScriptLexer::getLine() {
4546b69c69SDimitry Andric   StringRef S = getCurrentMB().getBuffer();
4646b69c69SDimitry Andric   StringRef Tok = Tokens[Pos - 1];
4746b69c69SDimitry Andric 
4846b69c69SDimitry Andric   size_t Pos = S.rfind('\n', Tok.data() - S.data());
4946b69c69SDimitry Andric   if (Pos != StringRef::npos)
5046b69c69SDimitry Andric     S = S.substr(Pos + 1);
5146b69c69SDimitry Andric   return S.substr(0, S.find_first_of("\r\n"));
5246b69c69SDimitry Andric }
5346b69c69SDimitry Andric 
5446b69c69SDimitry Andric // Returns 1-based line number of the current token.
5546b69c69SDimitry Andric size_t ScriptLexer::getLineNumber() {
5646b69c69SDimitry Andric   StringRef S = getCurrentMB().getBuffer();
5746b69c69SDimitry Andric   StringRef Tok = Tokens[Pos - 1];
5846b69c69SDimitry Andric   return S.substr(0, Tok.data() - S.data()).count('\n') + 1;
5946b69c69SDimitry Andric }
6046b69c69SDimitry Andric 
6146b69c69SDimitry Andric // Returns 0-based column number of the current token.
6246b69c69SDimitry Andric size_t ScriptLexer::getColumnNumber() {
6346b69c69SDimitry Andric   StringRef Tok = Tokens[Pos - 1];
6446b69c69SDimitry Andric   return Tok.data() - getLine().data();
6546b69c69SDimitry Andric }
6646b69c69SDimitry Andric 
6746b69c69SDimitry Andric std::string ScriptLexer::getCurrentLocation() {
6846b69c69SDimitry Andric   std::string Filename = getCurrentMB().getBufferIdentifier();
6946b69c69SDimitry Andric   if (!Pos)
7046b69c69SDimitry Andric     return Filename;
7146b69c69SDimitry Andric   return (Filename + ":" + Twine(getLineNumber())).str();
7246b69c69SDimitry Andric }
7346b69c69SDimitry Andric 
7446b69c69SDimitry Andric ScriptLexer::ScriptLexer(MemoryBufferRef MB) { tokenize(MB); }
7546b69c69SDimitry Andric 
7646b69c69SDimitry Andric // We don't want to record cascading errors. Keep only the first one.
7746b69c69SDimitry Andric void ScriptLexer::setError(const Twine &Msg) {
7810dc89a5SDimitry Andric   if (errorCount())
7946b69c69SDimitry Andric     return;
8046b69c69SDimitry Andric 
8110dc89a5SDimitry Andric   std::string S = (getCurrentLocation() + ": " + Msg).str();
8210dc89a5SDimitry Andric   if (Pos)
8310dc89a5SDimitry Andric     S += "\n>>> " + getLine().str() + "\n>>> " +
8410dc89a5SDimitry Andric          std::string(getColumnNumber(), ' ') + "^";
8510dc89a5SDimitry Andric   error(S);
8646b69c69SDimitry Andric }
8746b69c69SDimitry Andric 
8846b69c69SDimitry Andric // Split S into linker script tokens.
8946b69c69SDimitry Andric void ScriptLexer::tokenize(MemoryBufferRef MB) {
9046b69c69SDimitry Andric   std::vector<StringRef> Vec;
9146b69c69SDimitry Andric   MBs.push_back(MB);
9246b69c69SDimitry Andric   StringRef S = MB.getBuffer();
9346b69c69SDimitry Andric   StringRef Begin = S;
9446b69c69SDimitry Andric 
9546b69c69SDimitry Andric   for (;;) {
9646b69c69SDimitry Andric     S = skipSpace(S);
9746b69c69SDimitry Andric     if (S.empty())
9846b69c69SDimitry Andric       break;
9946b69c69SDimitry Andric 
10046b69c69SDimitry Andric     // Quoted token. Note that double-quote characters are parts of a token
10146b69c69SDimitry Andric     // because, in a glob match context, only unquoted tokens are interpreted
10246b69c69SDimitry Andric     // as glob patterns. Double-quoted tokens are literal patterns in that
10346b69c69SDimitry Andric     // context.
10446b69c69SDimitry Andric     if (S.startswith("\"")) {
10546b69c69SDimitry Andric       size_t E = S.find("\"", 1);
10646b69c69SDimitry Andric       if (E == StringRef::npos) {
10746b69c69SDimitry Andric         StringRef Filename = MB.getBufferIdentifier();
10846b69c69SDimitry Andric         size_t Lineno = Begin.substr(0, S.data() - Begin.data()).count('\n');
10946b69c69SDimitry Andric         error(Filename + ":" + Twine(Lineno + 1) + ": unclosed quote");
11046b69c69SDimitry Andric         return;
11146b69c69SDimitry Andric       }
11246b69c69SDimitry Andric 
11346b69c69SDimitry Andric       Vec.push_back(S.take_front(E + 1));
11446b69c69SDimitry Andric       S = S.substr(E + 1);
11546b69c69SDimitry Andric       continue;
11646b69c69SDimitry Andric     }
11746b69c69SDimitry Andric 
11846b69c69SDimitry Andric     // Unquoted token. This is more relaxed than tokens in C-like language,
11946b69c69SDimitry Andric     // so that you can write "file-name.cpp" as one bare token, for example.
12046b69c69SDimitry Andric     size_t Pos = S.find_first_not_of(
12146b69c69SDimitry Andric         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
12246b69c69SDimitry Andric         "0123456789_.$/\\~=+[]*?-!<>^:");
12346b69c69SDimitry Andric 
12446b69c69SDimitry Andric     // A character that cannot start a word (which is usually a
12546b69c69SDimitry Andric     // punctuation) forms a single character token.
12646b69c69SDimitry Andric     if (Pos == 0)
12746b69c69SDimitry Andric       Pos = 1;
12846b69c69SDimitry Andric     Vec.push_back(S.substr(0, Pos));
12946b69c69SDimitry Andric     S = S.substr(Pos);
13046b69c69SDimitry Andric   }
13146b69c69SDimitry Andric 
13246b69c69SDimitry Andric   Tokens.insert(Tokens.begin() + Pos, Vec.begin(), Vec.end());
13346b69c69SDimitry Andric }
13446b69c69SDimitry Andric 
13546b69c69SDimitry Andric // Skip leading whitespace characters or comments.
13646b69c69SDimitry Andric StringRef ScriptLexer::skipSpace(StringRef S) {
13746b69c69SDimitry Andric   for (;;) {
13846b69c69SDimitry Andric     if (S.startswith("/*")) {
13946b69c69SDimitry Andric       size_t E = S.find("*/", 2);
14046b69c69SDimitry Andric       if (E == StringRef::npos) {
14146b69c69SDimitry Andric         error("unclosed comment in a linker script");
14246b69c69SDimitry Andric         return "";
14346b69c69SDimitry Andric       }
14446b69c69SDimitry Andric       S = S.substr(E + 2);
14546b69c69SDimitry Andric       continue;
14646b69c69SDimitry Andric     }
14746b69c69SDimitry Andric     if (S.startswith("#")) {
14846b69c69SDimitry Andric       size_t E = S.find('\n', 1);
14946b69c69SDimitry Andric       if (E == StringRef::npos)
15046b69c69SDimitry Andric         E = S.size() - 1;
15146b69c69SDimitry Andric       S = S.substr(E + 1);
15246b69c69SDimitry Andric       continue;
15346b69c69SDimitry Andric     }
15446b69c69SDimitry Andric     size_t Size = S.size();
15546b69c69SDimitry Andric     S = S.ltrim();
15646b69c69SDimitry Andric     if (S.size() == Size)
15746b69c69SDimitry Andric       return S;
15846b69c69SDimitry Andric   }
15946b69c69SDimitry Andric }
16046b69c69SDimitry Andric 
16146b69c69SDimitry Andric // An erroneous token is handled as if it were the last token before EOF.
16210dc89a5SDimitry Andric bool ScriptLexer::atEOF() { return errorCount() || Tokens.size() == Pos; }
16346b69c69SDimitry Andric 
16446b69c69SDimitry Andric // Split a given string as an expression.
16546b69c69SDimitry Andric // This function returns "3", "*" and "5" for "3*5" for example.
16646b69c69SDimitry Andric static std::vector<StringRef> tokenizeExpr(StringRef S) {
16710dc89a5SDimitry Andric   StringRef Ops = "+-*/:!~"; // List of operators
16846b69c69SDimitry Andric 
16946b69c69SDimitry Andric   // Quoted strings are literal strings, so we don't want to split it.
17046b69c69SDimitry Andric   if (S.startswith("\""))
17146b69c69SDimitry Andric     return {S};
17246b69c69SDimitry Andric 
17310dc89a5SDimitry Andric   // Split S with operators as separators.
17446b69c69SDimitry Andric   std::vector<StringRef> Ret;
17546b69c69SDimitry Andric   while (!S.empty()) {
17646b69c69SDimitry Andric     size_t E = S.find_first_of(Ops);
17746b69c69SDimitry Andric 
17846b69c69SDimitry Andric     // No need to split if there is no operator.
17946b69c69SDimitry Andric     if (E == StringRef::npos) {
18046b69c69SDimitry Andric       Ret.push_back(S);
18146b69c69SDimitry Andric       break;
18246b69c69SDimitry Andric     }
18346b69c69SDimitry Andric 
18446b69c69SDimitry Andric     // Get a token before the opreator.
18546b69c69SDimitry Andric     if (E != 0)
18646b69c69SDimitry Andric       Ret.push_back(S.substr(0, E));
18746b69c69SDimitry Andric 
18810dc89a5SDimitry Andric     // Get the operator as a token. Keep != as one token.
18910dc89a5SDimitry Andric     if (S.substr(E).startswith("!=")) {
19010dc89a5SDimitry Andric       Ret.push_back(S.substr(E, 2));
19110dc89a5SDimitry Andric       S = S.substr(E + 2);
19210dc89a5SDimitry Andric     } else {
19346b69c69SDimitry Andric       Ret.push_back(S.substr(E, 1));
19446b69c69SDimitry Andric       S = S.substr(E + 1);
19546b69c69SDimitry Andric     }
19610dc89a5SDimitry Andric   }
19746b69c69SDimitry Andric   return Ret;
19846b69c69SDimitry Andric }
19946b69c69SDimitry Andric 
20046b69c69SDimitry Andric // In contexts where expressions are expected, the lexer should apply
20146b69c69SDimitry Andric // different tokenization rules than the default one. By default,
20246b69c69SDimitry Andric // arithmetic operator characters are regular characters, but in the
20346b69c69SDimitry Andric // expression context, they should be independent tokens.
20446b69c69SDimitry Andric //
20546b69c69SDimitry Andric // For example, "foo*3" should be tokenized to "foo", "*" and "3" only
20646b69c69SDimitry Andric // in the expression context.
20746b69c69SDimitry Andric //
20846b69c69SDimitry Andric // This function may split the current token into multiple tokens.
20946b69c69SDimitry Andric void ScriptLexer::maybeSplitExpr() {
21010dc89a5SDimitry Andric   if (!InExpr || errorCount() || atEOF())
21146b69c69SDimitry Andric     return;
21246b69c69SDimitry Andric 
21346b69c69SDimitry Andric   std::vector<StringRef> V = tokenizeExpr(Tokens[Pos]);
21446b69c69SDimitry Andric   if (V.size() == 1)
21546b69c69SDimitry Andric     return;
21646b69c69SDimitry Andric   Tokens.erase(Tokens.begin() + Pos);
21746b69c69SDimitry Andric   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
21846b69c69SDimitry Andric }
21946b69c69SDimitry Andric 
22046b69c69SDimitry Andric StringRef ScriptLexer::next() {
22146b69c69SDimitry Andric   maybeSplitExpr();
22246b69c69SDimitry Andric 
22310dc89a5SDimitry Andric   if (errorCount())
22446b69c69SDimitry Andric     return "";
22546b69c69SDimitry Andric   if (atEOF()) {
22646b69c69SDimitry Andric     setError("unexpected EOF");
22746b69c69SDimitry Andric     return "";
22846b69c69SDimitry Andric   }
22946b69c69SDimitry Andric   return Tokens[Pos++];
23046b69c69SDimitry Andric }
23146b69c69SDimitry Andric 
23246b69c69SDimitry Andric StringRef ScriptLexer::peek() {
23346b69c69SDimitry Andric   StringRef Tok = next();
23410dc89a5SDimitry Andric   if (errorCount())
23546b69c69SDimitry Andric     return "";
23646b69c69SDimitry Andric   Pos = Pos - 1;
23746b69c69SDimitry Andric   return Tok;
23846b69c69SDimitry Andric }
23946b69c69SDimitry Andric 
24046b69c69SDimitry Andric bool ScriptLexer::consume(StringRef Tok) {
24146b69c69SDimitry Andric   if (peek() == Tok) {
24246b69c69SDimitry Andric     skip();
24346b69c69SDimitry Andric     return true;
24446b69c69SDimitry Andric   }
24546b69c69SDimitry Andric   return false;
24646b69c69SDimitry Andric }
24746b69c69SDimitry Andric 
24846b69c69SDimitry Andric // Consumes Tok followed by ":". Space is allowed between Tok and ":".
24946b69c69SDimitry Andric bool ScriptLexer::consumeLabel(StringRef Tok) {
25046b69c69SDimitry Andric   if (consume((Tok + ":").str()))
25146b69c69SDimitry Andric     return true;
25246b69c69SDimitry Andric   if (Tokens.size() >= Pos + 2 && Tokens[Pos] == Tok &&
25346b69c69SDimitry Andric       Tokens[Pos + 1] == ":") {
25446b69c69SDimitry Andric     Pos += 2;
25546b69c69SDimitry Andric     return true;
25646b69c69SDimitry Andric   }
25746b69c69SDimitry Andric   return false;
25846b69c69SDimitry Andric }
25946b69c69SDimitry Andric 
26046b69c69SDimitry Andric void ScriptLexer::skip() { (void)next(); }
26146b69c69SDimitry Andric 
26246b69c69SDimitry Andric void ScriptLexer::expect(StringRef Expect) {
26310dc89a5SDimitry Andric   if (errorCount())
26446b69c69SDimitry Andric     return;
26546b69c69SDimitry Andric   StringRef Tok = next();
26646b69c69SDimitry Andric   if (Tok != Expect)
26746b69c69SDimitry Andric     setError(Expect + " expected, but got " + Tok);
26846b69c69SDimitry Andric }
26946b69c69SDimitry Andric 
27046b69c69SDimitry Andric // Returns true if S encloses T.
27146b69c69SDimitry Andric static bool encloses(StringRef S, StringRef T) {
27246b69c69SDimitry Andric   return S.bytes_begin() <= T.bytes_begin() && T.bytes_end() <= S.bytes_end();
27346b69c69SDimitry Andric }
27446b69c69SDimitry Andric 
27546b69c69SDimitry Andric MemoryBufferRef ScriptLexer::getCurrentMB() {
27646b69c69SDimitry Andric   // Find input buffer containing the current token.
27746b69c69SDimitry Andric   assert(!MBs.empty());
27846b69c69SDimitry Andric   if (!Pos)
27946b69c69SDimitry Andric     return MBs[0];
28046b69c69SDimitry Andric 
28146b69c69SDimitry Andric   for (MemoryBufferRef MB : MBs)
28246b69c69SDimitry Andric     if (encloses(MB.getBuffer(), Tokens[Pos - 1]))
28346b69c69SDimitry Andric       return MB;
28446b69c69SDimitry Andric   llvm_unreachable("getCurrentMB: failed to find a token");
28546b69c69SDimitry Andric }
286