10b57cec5SDimitry Andric //===- ScriptLexer.cpp ----------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines a lexer for the linker script.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // The linker script's grammar is not complex but ambiguous due to the
120b57cec5SDimitry Andric // lack of the formal specification of the language. What we are trying to
130b57cec5SDimitry Andric // do in this and other files in LLD is to make a "reasonable" linker
140b57cec5SDimitry Andric // script processor.
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric // Among simplicity, compatibility and efficiency, we put the most
170b57cec5SDimitry Andric // emphasis on simplicity when we wrote this lexer. Compatibility with the
180b57cec5SDimitry Andric // GNU linkers is important, but we did not try to clone every tiny corner
190b57cec5SDimitry Andric // case of their lexers, as even ld.bfd and ld.gold are subtly different
200b57cec5SDimitry Andric // in various corner cases. We do not care much about efficiency because
210b57cec5SDimitry Andric // the time spent in parsing linker scripts is usually negligible.
220b57cec5SDimitry Andric //
230b57cec5SDimitry Andric // Our grammar of the linker script is LL(2), meaning that it needs at
240b57cec5SDimitry Andric // most two-token lookahead to parse. The only place we need two-token
250b57cec5SDimitry Andric // lookahead is labels in version scripts, where we need to parse "local :"
260b57cec5SDimitry Andric // as if "local:".
270b57cec5SDimitry Andric //
280b57cec5SDimitry Andric // Overall, this lexer works fine for most linker scripts. There might
290b57cec5SDimitry Andric // be room for improving compatibility, but that's probably not at the
300b57cec5SDimitry Andric // top of our todo list.
310b57cec5SDimitry Andric //
320b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric #include "ScriptLexer.h"
350b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
360b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
3781ad6265SDimitry Andric #include "llvm/Support/ErrorHandling.h"
3881ad6265SDimitry Andric #include <algorithm>
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric using namespace llvm;
415ffd83dbSDimitry Andric using namespace lld;
425ffd83dbSDimitry Andric using namespace lld::elf;
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric // Returns a whole line containing the current token.
getLine()450b57cec5SDimitry Andric StringRef ScriptLexer::getLine() {
460b57cec5SDimitry Andric   StringRef s = getCurrentMB().getBuffer();
470b57cec5SDimitry Andric   StringRef tok = tokens[pos - 1];
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric   size_t pos = s.rfind('\n', tok.data() - s.data());
500b57cec5SDimitry Andric   if (pos != StringRef::npos)
510b57cec5SDimitry Andric     s = s.substr(pos + 1);
520b57cec5SDimitry Andric   return s.substr(0, s.find_first_of("\r\n"));
530b57cec5SDimitry Andric }
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric // Returns 1-based line number of the current token.
getLineNumber()560b57cec5SDimitry Andric size_t ScriptLexer::getLineNumber() {
57e837bb5cSDimitry Andric   if (pos == 0)
58e837bb5cSDimitry Andric     return 1;
590b57cec5SDimitry Andric   StringRef s = getCurrentMB().getBuffer();
600b57cec5SDimitry Andric   StringRef tok = tokens[pos - 1];
61fe6060f1SDimitry Andric   const size_t tokOffset = tok.data() - s.data();
62fe6060f1SDimitry Andric 
63fe6060f1SDimitry Andric   // For the first token, or when going backwards, start from the beginning of
64fe6060f1SDimitry Andric   // the buffer. If this token is after the previous token, start from the
65fe6060f1SDimitry Andric   // previous token.
66fe6060f1SDimitry Andric   size_t line = 1;
67fe6060f1SDimitry Andric   size_t start = 0;
68fe6060f1SDimitry Andric   if (lastLineNumberOffset > 0 && tokOffset >= lastLineNumberOffset) {
69fe6060f1SDimitry Andric     start = lastLineNumberOffset;
70fe6060f1SDimitry Andric     line = lastLineNumber;
71fe6060f1SDimitry Andric   }
72fe6060f1SDimitry Andric 
73fe6060f1SDimitry Andric   line += s.substr(start, tokOffset - start).count('\n');
74fe6060f1SDimitry Andric 
75fe6060f1SDimitry Andric   // Store the line number of this token for reuse.
76fe6060f1SDimitry Andric   lastLineNumberOffset = tokOffset;
77fe6060f1SDimitry Andric   lastLineNumber = line;
78fe6060f1SDimitry Andric 
79fe6060f1SDimitry Andric   return line;
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric // Returns 0-based column number of the current token.
getColumnNumber()830b57cec5SDimitry Andric size_t ScriptLexer::getColumnNumber() {
840b57cec5SDimitry Andric   StringRef tok = tokens[pos - 1];
850b57cec5SDimitry Andric   return tok.data() - getLine().data();
860b57cec5SDimitry Andric }
870b57cec5SDimitry Andric 
getCurrentLocation()880b57cec5SDimitry Andric std::string ScriptLexer::getCurrentLocation() {
895ffd83dbSDimitry Andric   std::string filename = std::string(getCurrentMB().getBufferIdentifier());
900b57cec5SDimitry Andric   return (filename + ":" + Twine(getLineNumber())).str();
910b57cec5SDimitry Andric }
920b57cec5SDimitry Andric 
ScriptLexer(MemoryBufferRef mb)930b57cec5SDimitry Andric ScriptLexer::ScriptLexer(MemoryBufferRef mb) { tokenize(mb); }
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric // We don't want to record cascading errors. Keep only the first one.
setError(const Twine & msg)960b57cec5SDimitry Andric void ScriptLexer::setError(const Twine &msg) {
970b57cec5SDimitry Andric   if (errorCount())
980b57cec5SDimitry Andric     return;
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   std::string s = (getCurrentLocation() + ": " + msg).str();
1010b57cec5SDimitry Andric   if (pos)
1020b57cec5SDimitry Andric     s += "\n>>> " + getLine().str() + "\n>>> " +
1030b57cec5SDimitry Andric          std::string(getColumnNumber(), ' ') + "^";
1040b57cec5SDimitry Andric   error(s);
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric // Split S into linker script tokens.
tokenize(MemoryBufferRef mb)1080b57cec5SDimitry Andric void ScriptLexer::tokenize(MemoryBufferRef mb) {
1090b57cec5SDimitry Andric   std::vector<StringRef> vec;
1100b57cec5SDimitry Andric   mbs.push_back(mb);
1110b57cec5SDimitry Andric   StringRef s = mb.getBuffer();
1120b57cec5SDimitry Andric   StringRef begin = s;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   for (;;) {
1150b57cec5SDimitry Andric     s = skipSpace(s);
1160b57cec5SDimitry Andric     if (s.empty())
1170b57cec5SDimitry Andric       break;
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric     // Quoted token. Note that double-quote characters are parts of a token
1200b57cec5SDimitry Andric     // because, in a glob match context, only unquoted tokens are interpreted
1210b57cec5SDimitry Andric     // as glob patterns. Double-quoted tokens are literal patterns in that
1220b57cec5SDimitry Andric     // context.
123*fe013be4SDimitry Andric     if (s.starts_with("\"")) {
1240b57cec5SDimitry Andric       size_t e = s.find("\"", 1);
1250b57cec5SDimitry Andric       if (e == StringRef::npos) {
1260b57cec5SDimitry Andric         StringRef filename = mb.getBufferIdentifier();
1270b57cec5SDimitry Andric         size_t lineno = begin.substr(0, s.data() - begin.data()).count('\n');
1280b57cec5SDimitry Andric         error(filename + ":" + Twine(lineno + 1) + ": unclosed quote");
1290b57cec5SDimitry Andric         return;
1300b57cec5SDimitry Andric       }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric       vec.push_back(s.take_front(e + 1));
1330b57cec5SDimitry Andric       s = s.substr(e + 1);
1340b57cec5SDimitry Andric       continue;
1350b57cec5SDimitry Andric     }
1360b57cec5SDimitry Andric 
13781ad6265SDimitry Andric     // Some operators form separate tokens.
138*fe013be4SDimitry Andric     if (s.starts_with("<<=") || s.starts_with(">>=")) {
13981ad6265SDimitry Andric       vec.push_back(s.substr(0, 3));
14081ad6265SDimitry Andric       s = s.substr(3);
14181ad6265SDimitry Andric       continue;
14281ad6265SDimitry Andric     }
143*fe013be4SDimitry Andric     if (s.size() > 1 && ((s[1] == '=' && strchr("*/+-<>&^|", s[0])) ||
14481ad6265SDimitry Andric                          (s[0] == s[1] && strchr("<>&|", s[0])))) {
1450b57cec5SDimitry Andric       vec.push_back(s.substr(0, 2));
1460b57cec5SDimitry Andric       s = s.substr(2);
1470b57cec5SDimitry Andric       continue;
1480b57cec5SDimitry Andric     }
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric     // Unquoted token. This is more relaxed than tokens in C-like language,
1510b57cec5SDimitry Andric     // so that you can write "file-name.cpp" as one bare token, for example.
1520b57cec5SDimitry Andric     size_t pos = s.find_first_not_of(
1530b57cec5SDimitry Andric         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
1540b57cec5SDimitry Andric         "0123456789_.$/\\~=+[]*?-!^:");
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     // A character that cannot start a word (which is usually a
1570b57cec5SDimitry Andric     // punctuation) forms a single character token.
1580b57cec5SDimitry Andric     if (pos == 0)
1590b57cec5SDimitry Andric       pos = 1;
1600b57cec5SDimitry Andric     vec.push_back(s.substr(0, pos));
1610b57cec5SDimitry Andric     s = s.substr(pos);
1620b57cec5SDimitry Andric   }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   tokens.insert(tokens.begin() + pos, vec.begin(), vec.end());
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric // Skip leading whitespace characters or comments.
skipSpace(StringRef s)1680b57cec5SDimitry Andric StringRef ScriptLexer::skipSpace(StringRef s) {
1690b57cec5SDimitry Andric   for (;;) {
170*fe013be4SDimitry Andric     if (s.starts_with("/*")) {
1710b57cec5SDimitry Andric       size_t e = s.find("*/", 2);
1720b57cec5SDimitry Andric       if (e == StringRef::npos) {
173e8d8bef9SDimitry Andric         setError("unclosed comment in a linker script");
1740b57cec5SDimitry Andric         return "";
1750b57cec5SDimitry Andric       }
1760b57cec5SDimitry Andric       s = s.substr(e + 2);
1770b57cec5SDimitry Andric       continue;
1780b57cec5SDimitry Andric     }
179*fe013be4SDimitry Andric     if (s.starts_with("#")) {
1800b57cec5SDimitry Andric       size_t e = s.find('\n', 1);
1810b57cec5SDimitry Andric       if (e == StringRef::npos)
1820b57cec5SDimitry Andric         e = s.size() - 1;
1830b57cec5SDimitry Andric       s = s.substr(e + 1);
1840b57cec5SDimitry Andric       continue;
1850b57cec5SDimitry Andric     }
1860b57cec5SDimitry Andric     size_t size = s.size();
1870b57cec5SDimitry Andric     s = s.ltrim();
1880b57cec5SDimitry Andric     if (s.size() == size)
1890b57cec5SDimitry Andric       return s;
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric // An erroneous token is handled as if it were the last token before EOF.
atEOF()1940b57cec5SDimitry Andric bool ScriptLexer::atEOF() { return errorCount() || tokens.size() == pos; }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric // Split a given string as an expression.
1970b57cec5SDimitry Andric // This function returns "3", "*" and "5" for "3*5" for example.
tokenizeExpr(StringRef s)1980b57cec5SDimitry Andric static std::vector<StringRef> tokenizeExpr(StringRef s) {
199*fe013be4SDimitry Andric   StringRef ops = "!~*/+-<>?^:="; // List of operators
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   // Quoted strings are literal strings, so we don't want to split it.
202*fe013be4SDimitry Andric   if (s.starts_with("\""))
2030b57cec5SDimitry Andric     return {s};
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   // Split S with operators as separators.
2060b57cec5SDimitry Andric   std::vector<StringRef> ret;
2070b57cec5SDimitry Andric   while (!s.empty()) {
2080b57cec5SDimitry Andric     size_t e = s.find_first_of(ops);
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric     // No need to split if there is no operator.
2110b57cec5SDimitry Andric     if (e == StringRef::npos) {
2120b57cec5SDimitry Andric       ret.push_back(s);
2130b57cec5SDimitry Andric       break;
2140b57cec5SDimitry Andric     }
2150b57cec5SDimitry Andric 
2165ffd83dbSDimitry Andric     // Get a token before the operator.
2170b57cec5SDimitry Andric     if (e != 0)
2180b57cec5SDimitry Andric       ret.push_back(s.substr(0, e));
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric     // Get the operator as a token.
2210b57cec5SDimitry Andric     // Keep !=, ==, >=, <=, << and >> operators as a single tokens.
222*fe013be4SDimitry Andric     if (s.substr(e).starts_with("!=") || s.substr(e).starts_with("==") ||
223*fe013be4SDimitry Andric         s.substr(e).starts_with(">=") || s.substr(e).starts_with("<=") ||
224*fe013be4SDimitry Andric         s.substr(e).starts_with("<<") || s.substr(e).starts_with(">>")) {
2250b57cec5SDimitry Andric       ret.push_back(s.substr(e, 2));
2260b57cec5SDimitry Andric       s = s.substr(e + 2);
2270b57cec5SDimitry Andric     } else {
2280b57cec5SDimitry Andric       ret.push_back(s.substr(e, 1));
2290b57cec5SDimitry Andric       s = s.substr(e + 1);
2300b57cec5SDimitry Andric     }
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric   return ret;
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric // In contexts where expressions are expected, the lexer should apply
2360b57cec5SDimitry Andric // different tokenization rules than the default one. By default,
2370b57cec5SDimitry Andric // arithmetic operator characters are regular characters, but in the
2380b57cec5SDimitry Andric // expression context, they should be independent tokens.
2390b57cec5SDimitry Andric //
2400b57cec5SDimitry Andric // For example, "foo*3" should be tokenized to "foo", "*" and "3" only
2410b57cec5SDimitry Andric // in the expression context.
2420b57cec5SDimitry Andric //
2430b57cec5SDimitry Andric // This function may split the current token into multiple tokens.
maybeSplitExpr()2440b57cec5SDimitry Andric void ScriptLexer::maybeSplitExpr() {
2450b57cec5SDimitry Andric   if (!inExpr || errorCount() || atEOF())
2460b57cec5SDimitry Andric     return;
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   std::vector<StringRef> v = tokenizeExpr(tokens[pos]);
2490b57cec5SDimitry Andric   if (v.size() == 1)
2500b57cec5SDimitry Andric     return;
2510b57cec5SDimitry Andric   tokens.erase(tokens.begin() + pos);
2520b57cec5SDimitry Andric   tokens.insert(tokens.begin() + pos, v.begin(), v.end());
2530b57cec5SDimitry Andric }
2540b57cec5SDimitry Andric 
next()2550b57cec5SDimitry Andric StringRef ScriptLexer::next() {
2560b57cec5SDimitry Andric   maybeSplitExpr();
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   if (errorCount())
2590b57cec5SDimitry Andric     return "";
2600b57cec5SDimitry Andric   if (atEOF()) {
2610b57cec5SDimitry Andric     setError("unexpected EOF");
2620b57cec5SDimitry Andric     return "";
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric   return tokens[pos++];
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric 
peek()2670b57cec5SDimitry Andric StringRef ScriptLexer::peek() {
2680b57cec5SDimitry Andric   StringRef tok = next();
2690b57cec5SDimitry Andric   if (errorCount())
2700b57cec5SDimitry Andric     return "";
2710b57cec5SDimitry Andric   pos = pos - 1;
2720b57cec5SDimitry Andric   return tok;
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
peek2()2750b57cec5SDimitry Andric StringRef ScriptLexer::peek2() {
2760b57cec5SDimitry Andric   skip();
2770b57cec5SDimitry Andric   StringRef tok = next();
2780b57cec5SDimitry Andric   if (errorCount())
2790b57cec5SDimitry Andric     return "";
2800b57cec5SDimitry Andric   pos = pos - 2;
2810b57cec5SDimitry Andric   return tok;
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
consume(StringRef tok)2840b57cec5SDimitry Andric bool ScriptLexer::consume(StringRef tok) {
2850b57cec5SDimitry Andric   if (peek() == tok) {
2860b57cec5SDimitry Andric     skip();
2870b57cec5SDimitry Andric     return true;
2880b57cec5SDimitry Andric   }
2890b57cec5SDimitry Andric   return false;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric // Consumes Tok followed by ":". Space is allowed between Tok and ":".
consumeLabel(StringRef tok)2930b57cec5SDimitry Andric bool ScriptLexer::consumeLabel(StringRef tok) {
2940b57cec5SDimitry Andric   if (consume((tok + ":").str()))
2950b57cec5SDimitry Andric     return true;
2960b57cec5SDimitry Andric   if (tokens.size() >= pos + 2 && tokens[pos] == tok &&
2970b57cec5SDimitry Andric       tokens[pos + 1] == ":") {
2980b57cec5SDimitry Andric     pos += 2;
2990b57cec5SDimitry Andric     return true;
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric   return false;
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
skip()3040b57cec5SDimitry Andric void ScriptLexer::skip() { (void)next(); }
3050b57cec5SDimitry Andric 
expect(StringRef expect)3060b57cec5SDimitry Andric void ScriptLexer::expect(StringRef expect) {
3070b57cec5SDimitry Andric   if (errorCount())
3080b57cec5SDimitry Andric     return;
3090b57cec5SDimitry Andric   StringRef tok = next();
3100b57cec5SDimitry Andric   if (tok != expect)
3110b57cec5SDimitry Andric     setError(expect + " expected, but got " + tok);
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric // Returns true if S encloses T.
encloses(StringRef s,StringRef t)3150b57cec5SDimitry Andric static bool encloses(StringRef s, StringRef t) {
3160b57cec5SDimitry Andric   return s.bytes_begin() <= t.bytes_begin() && t.bytes_end() <= s.bytes_end();
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
getCurrentMB()3190b57cec5SDimitry Andric MemoryBufferRef ScriptLexer::getCurrentMB() {
3200b57cec5SDimitry Andric   // Find input buffer containing the current token.
321e837bb5cSDimitry Andric   assert(!mbs.empty());
322e837bb5cSDimitry Andric   if (pos == 0)
323e837bb5cSDimitry Andric     return mbs.back();
3240b57cec5SDimitry Andric   for (MemoryBufferRef mb : mbs)
3250b57cec5SDimitry Andric     if (encloses(mb.getBuffer(), tokens[pos - 1]))
3260b57cec5SDimitry Andric       return mb;
3270b57cec5SDimitry Andric   llvm_unreachable("getCurrentMB: failed to find a token");
3280b57cec5SDimitry Andric }
329