1794366a2SRui Ueyama //===- ScriptLexer.cpp ----------------------------------------------------===//
2794366a2SRui Ueyama //
3794366a2SRui Ueyama //                             The LLVM Linker
4794366a2SRui Ueyama //
5794366a2SRui Ueyama // This file is distributed under the University of Illinois Open Source
6794366a2SRui Ueyama // License. See LICENSE.TXT for details.
7794366a2SRui Ueyama //
8794366a2SRui Ueyama //===----------------------------------------------------------------------===//
9794366a2SRui Ueyama //
104c82b4f6SRui Ueyama // This file defines a lexer for the linker script.
114c82b4f6SRui Ueyama //
124c82b4f6SRui Ueyama // The linker script's grammar is not complex but ambiguous due to the
134c82b4f6SRui Ueyama // lack of the formal specification of the language. What we are trying to
144c82b4f6SRui Ueyama // do in this and other files in LLD is to make a "reasonable" linker
154c82b4f6SRui Ueyama // script processor.
164c82b4f6SRui Ueyama //
174c82b4f6SRui Ueyama // Among simplicity, compatibility and efficiency, we put the most
184c82b4f6SRui Ueyama // emphasis on simplicity when we wrote this lexer. Compatibility with the
194c82b4f6SRui Ueyama // GNU linkers is important, but we did not try to clone every tiny corner
204c82b4f6SRui Ueyama // case of their lexers, as even ld.bfd and ld.gold are subtly different
214c82b4f6SRui Ueyama // in various corner cases. We do not care much about efficiency because
224c82b4f6SRui Ueyama // the time spent in parsing linker scripts is usually negligible.
234c82b4f6SRui Ueyama //
244c82b4f6SRui Ueyama // Our grammar of the linker script is LL(2), meaning that it needs at
254c82b4f6SRui Ueyama // most two-token lookahead to parse. The only place we need two-token
264c82b4f6SRui Ueyama // lookahead is labels in version scripts, where we need to parse "local :"
274c82b4f6SRui Ueyama // as if "local:".
284c82b4f6SRui Ueyama //
29731a66aeSRui Ueyama // Overall, this lexer works fine for most linker scripts. There might
30731a66aeSRui Ueyama // be room for improving compatibility, but that's probably not at the
31731a66aeSRui Ueyama // top of our todo list.
32794366a2SRui Ueyama //
33794366a2SRui Ueyama //===----------------------------------------------------------------------===//
34794366a2SRui Ueyama 
35794366a2SRui Ueyama #include "ScriptLexer.h"
36794366a2SRui Ueyama #include "Error.h"
37794366a2SRui Ueyama #include "llvm/ADT/Twine.h"
38794366a2SRui Ueyama 
39794366a2SRui Ueyama using namespace llvm;
40794366a2SRui Ueyama using namespace lld;
41794366a2SRui Ueyama using namespace lld::elf;
42794366a2SRui Ueyama 
43794366a2SRui Ueyama // Returns a whole line containing the current token.
44794366a2SRui Ueyama StringRef ScriptLexer::getLine() {
45794366a2SRui Ueyama   StringRef S = getCurrentMB().getBuffer();
46794366a2SRui Ueyama   StringRef Tok = Tokens[Pos - 1];
47794366a2SRui Ueyama 
48794366a2SRui Ueyama   size_t Pos = S.rfind('\n', Tok.data() - S.data());
49794366a2SRui Ueyama   if (Pos != StringRef::npos)
50794366a2SRui Ueyama     S = S.substr(Pos + 1);
51794366a2SRui Ueyama   return S.substr(0, S.find_first_of("\r\n"));
52794366a2SRui Ueyama }
53794366a2SRui Ueyama 
54794366a2SRui Ueyama // Returns 1-based line number of the current token.
55794366a2SRui Ueyama size_t ScriptLexer::getLineNumber() {
56794366a2SRui Ueyama   StringRef S = getCurrentMB().getBuffer();
57794366a2SRui Ueyama   StringRef Tok = Tokens[Pos - 1];
58794366a2SRui Ueyama   return S.substr(0, Tok.data() - S.data()).count('\n') + 1;
59794366a2SRui Ueyama }
60794366a2SRui Ueyama 
61794366a2SRui Ueyama // Returns 0-based column number of the current token.
62794366a2SRui Ueyama size_t ScriptLexer::getColumnNumber() {
63794366a2SRui Ueyama   StringRef Tok = Tokens[Pos - 1];
64794366a2SRui Ueyama   return Tok.data() - getLine().data();
65794366a2SRui Ueyama }
66794366a2SRui Ueyama 
67794366a2SRui Ueyama std::string ScriptLexer::getCurrentLocation() {
68794366a2SRui Ueyama   std::string Filename = getCurrentMB().getBufferIdentifier();
69794366a2SRui Ueyama   if (!Pos)
70794366a2SRui Ueyama     return Filename;
71794366a2SRui Ueyama   return (Filename + ":" + Twine(getLineNumber())).str();
72794366a2SRui Ueyama }
73794366a2SRui Ueyama 
74794366a2SRui Ueyama ScriptLexer::ScriptLexer(MemoryBufferRef MB) { tokenize(MB); }
75794366a2SRui Ueyama 
76794366a2SRui Ueyama // We don't want to record cascading errors. Keep only the first one.
77794366a2SRui Ueyama void ScriptLexer::setError(const Twine &Msg) {
78*ce608081SGeorge Rimar   if (ErrorCount)
79794366a2SRui Ueyama     return;
80794366a2SRui Ueyama 
81794366a2SRui Ueyama   if (!Pos) {
82794366a2SRui Ueyama     error(getCurrentLocation() + ": " + Msg);
83794366a2SRui Ueyama     return;
84794366a2SRui Ueyama   }
85794366a2SRui Ueyama 
86794366a2SRui Ueyama   std::string S = getCurrentLocation() + ": ";
87794366a2SRui Ueyama   error(S + Msg);
88794366a2SRui Ueyama   error(S + getLine());
89794366a2SRui Ueyama   error(S + std::string(getColumnNumber(), ' ') + "^");
90794366a2SRui Ueyama }
91794366a2SRui Ueyama 
92794366a2SRui Ueyama // Split S into linker script tokens.
93794366a2SRui Ueyama void ScriptLexer::tokenize(MemoryBufferRef MB) {
94794366a2SRui Ueyama   std::vector<StringRef> Vec;
95794366a2SRui Ueyama   MBs.push_back(MB);
96794366a2SRui Ueyama   StringRef S = MB.getBuffer();
97794366a2SRui Ueyama   StringRef Begin = S;
98794366a2SRui Ueyama 
99794366a2SRui Ueyama   for (;;) {
100794366a2SRui Ueyama     S = skipSpace(S);
101794366a2SRui Ueyama     if (S.empty())
102794366a2SRui Ueyama       break;
103794366a2SRui Ueyama 
104794366a2SRui Ueyama     // Quoted token. Note that double-quote characters are parts of a token
105794366a2SRui Ueyama     // because, in a glob match context, only unquoted tokens are interpreted
106794366a2SRui Ueyama     // as glob patterns. Double-quoted tokens are literal patterns in that
107794366a2SRui Ueyama     // context.
108794366a2SRui Ueyama     if (S.startswith("\"")) {
109794366a2SRui Ueyama       size_t E = S.find("\"", 1);
110794366a2SRui Ueyama       if (E == StringRef::npos) {
111794366a2SRui Ueyama         StringRef Filename = MB.getBufferIdentifier();
112794366a2SRui Ueyama         size_t Lineno = Begin.substr(0, S.data() - Begin.data()).count('\n');
113794366a2SRui Ueyama         error(Filename + ":" + Twine(Lineno + 1) + ": unclosed quote");
114794366a2SRui Ueyama         return;
115794366a2SRui Ueyama       }
116794366a2SRui Ueyama 
117794366a2SRui Ueyama       Vec.push_back(S.take_front(E + 1));
118794366a2SRui Ueyama       S = S.substr(E + 1);
119794366a2SRui Ueyama       continue;
120794366a2SRui Ueyama     }
121794366a2SRui Ueyama 
122794366a2SRui Ueyama     // Unquoted token. This is more relaxed than tokens in C-like language,
123794366a2SRui Ueyama     // so that you can write "file-name.cpp" as one bare token, for example.
124794366a2SRui Ueyama     size_t Pos = S.find_first_not_of(
125794366a2SRui Ueyama         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
126f5fce486SRui Ueyama         "0123456789_.$/\\~=+[]*?-!<>^:");
127794366a2SRui Ueyama 
128794366a2SRui Ueyama     // A character that cannot start a word (which is usually a
129794366a2SRui Ueyama     // punctuation) forms a single character token.
130794366a2SRui Ueyama     if (Pos == 0)
131794366a2SRui Ueyama       Pos = 1;
132794366a2SRui Ueyama     Vec.push_back(S.substr(0, Pos));
133794366a2SRui Ueyama     S = S.substr(Pos);
134794366a2SRui Ueyama   }
135794366a2SRui Ueyama 
136794366a2SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, Vec.begin(), Vec.end());
137794366a2SRui Ueyama }
138794366a2SRui Ueyama 
139794366a2SRui Ueyama // Skip leading whitespace characters or comments.
140794366a2SRui Ueyama StringRef ScriptLexer::skipSpace(StringRef S) {
141794366a2SRui Ueyama   for (;;) {
142794366a2SRui Ueyama     if (S.startswith("/*")) {
143794366a2SRui Ueyama       size_t E = S.find("*/", 2);
144794366a2SRui Ueyama       if (E == StringRef::npos) {
145794366a2SRui Ueyama         error("unclosed comment in a linker script");
146794366a2SRui Ueyama         return "";
147794366a2SRui Ueyama       }
148794366a2SRui Ueyama       S = S.substr(E + 2);
149794366a2SRui Ueyama       continue;
150794366a2SRui Ueyama     }
151794366a2SRui Ueyama     if (S.startswith("#")) {
152794366a2SRui Ueyama       size_t E = S.find('\n', 1);
153794366a2SRui Ueyama       if (E == StringRef::npos)
154794366a2SRui Ueyama         E = S.size() - 1;
155794366a2SRui Ueyama       S = S.substr(E + 1);
156794366a2SRui Ueyama       continue;
157794366a2SRui Ueyama     }
158794366a2SRui Ueyama     size_t Size = S.size();
159794366a2SRui Ueyama     S = S.ltrim();
160794366a2SRui Ueyama     if (S.size() == Size)
161794366a2SRui Ueyama       return S;
162794366a2SRui Ueyama   }
163794366a2SRui Ueyama }
164794366a2SRui Ueyama 
165794366a2SRui Ueyama // An erroneous token is handled as if it were the last token before EOF.
166*ce608081SGeorge Rimar bool ScriptLexer::atEOF() { return ErrorCount || Tokens.size() == Pos; }
167794366a2SRui Ueyama 
168731a66aeSRui Ueyama // Split a given string as an expression.
169731a66aeSRui Ueyama // This function returns "3", "*" and "5" for "3*5" for example.
170731a66aeSRui Ueyama static std::vector<StringRef> tokenizeExpr(StringRef S) {
171f5fce486SRui Ueyama   StringRef Ops = "+-*/:"; // List of operators
172731a66aeSRui Ueyama 
173731a66aeSRui Ueyama   // Quoted strings are literal strings, so we don't want to split it.
174731a66aeSRui Ueyama   if (S.startswith("\""))
175731a66aeSRui Ueyama     return {S};
176731a66aeSRui Ueyama 
177731a66aeSRui Ueyama   // Split S with +-*/ as separators.
178731a66aeSRui Ueyama   std::vector<StringRef> Ret;
179731a66aeSRui Ueyama   while (!S.empty()) {
180731a66aeSRui Ueyama     size_t E = S.find_first_of(Ops);
181731a66aeSRui Ueyama 
182731a66aeSRui Ueyama     // No need to split if there is no operator.
183731a66aeSRui Ueyama     if (E == StringRef::npos) {
184731a66aeSRui Ueyama       Ret.push_back(S);
185731a66aeSRui Ueyama       break;
186731a66aeSRui Ueyama     }
187731a66aeSRui Ueyama 
188731a66aeSRui Ueyama     // Get a token before the opreator.
189731a66aeSRui Ueyama     if (E != 0)
190731a66aeSRui Ueyama       Ret.push_back(S.substr(0, E));
191731a66aeSRui Ueyama 
192731a66aeSRui Ueyama     // Get the operator as a token.
193731a66aeSRui Ueyama     Ret.push_back(S.substr(E, 1));
194731a66aeSRui Ueyama     S = S.substr(E + 1);
195731a66aeSRui Ueyama   }
196731a66aeSRui Ueyama   return Ret;
197731a66aeSRui Ueyama }
198731a66aeSRui Ueyama 
199731a66aeSRui Ueyama // In contexts where expressions are expected, the lexer should apply
200731a66aeSRui Ueyama // different tokenization rules than the default one. By default,
201731a66aeSRui Ueyama // arithmetic operator characters are regular characters, but in the
202731a66aeSRui Ueyama // expression context, they should be independent tokens.
203731a66aeSRui Ueyama //
204731a66aeSRui Ueyama // For example, "foo*3" should be tokenized to "foo", "*" and "3" only
205731a66aeSRui Ueyama // in the expression context.
206731a66aeSRui Ueyama //
207731a66aeSRui Ueyama // This function may split the current token into multiple tokens.
208731a66aeSRui Ueyama void ScriptLexer::maybeSplitExpr() {
209*ce608081SGeorge Rimar   if (!InExpr || ErrorCount || atEOF())
210731a66aeSRui Ueyama     return;
211731a66aeSRui Ueyama 
212731a66aeSRui Ueyama   std::vector<StringRef> V = tokenizeExpr(Tokens[Pos]);
213731a66aeSRui Ueyama   if (V.size() == 1)
214731a66aeSRui Ueyama     return;
215731a66aeSRui Ueyama   Tokens.erase(Tokens.begin() + Pos);
216731a66aeSRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
217731a66aeSRui Ueyama }
218731a66aeSRui Ueyama 
219794366a2SRui Ueyama StringRef ScriptLexer::next() {
220731a66aeSRui Ueyama   maybeSplitExpr();
221731a66aeSRui Ueyama 
222*ce608081SGeorge Rimar   if (ErrorCount)
223794366a2SRui Ueyama     return "";
224794366a2SRui Ueyama   if (atEOF()) {
225794366a2SRui Ueyama     setError("unexpected EOF");
226794366a2SRui Ueyama     return "";
227794366a2SRui Ueyama   }
228794366a2SRui Ueyama   return Tokens[Pos++];
229794366a2SRui Ueyama }
230794366a2SRui Ueyama 
231f5fce486SRui Ueyama StringRef ScriptLexer::peek() {
232f5fce486SRui Ueyama   StringRef Tok = next();
233*ce608081SGeorge Rimar   if (ErrorCount)
234794366a2SRui Ueyama     return "";
235f5fce486SRui Ueyama   Pos = Pos - 1;
236794366a2SRui Ueyama   return Tok;
237794366a2SRui Ueyama }
238794366a2SRui Ueyama 
239794366a2SRui Ueyama bool ScriptLexer::consume(StringRef Tok) {
240794366a2SRui Ueyama   if (peek() == Tok) {
241794366a2SRui Ueyama     skip();
242794366a2SRui Ueyama     return true;
243794366a2SRui Ueyama   }
244794366a2SRui Ueyama   return false;
245794366a2SRui Ueyama }
246794366a2SRui Ueyama 
247f5fce486SRui Ueyama // Consumes Tok followed by ":". Space is allowed between Tok and ":".
248f5fce486SRui Ueyama bool ScriptLexer::consumeLabel(StringRef Tok) {
249f5fce486SRui Ueyama   if (consume((Tok + ":").str()))
250f5fce486SRui Ueyama     return true;
251f5fce486SRui Ueyama   if (Tokens.size() >= Pos + 2 && Tokens[Pos] == Tok &&
252f5fce486SRui Ueyama       Tokens[Pos + 1] == ":") {
253f5fce486SRui Ueyama     Pos += 2;
254f5fce486SRui Ueyama     return true;
255f5fce486SRui Ueyama   }
256f5fce486SRui Ueyama   return false;
257f5fce486SRui Ueyama }
258f5fce486SRui Ueyama 
259794366a2SRui Ueyama void ScriptLexer::skip() { (void)next(); }
260794366a2SRui Ueyama 
261794366a2SRui Ueyama void ScriptLexer::expect(StringRef Expect) {
262*ce608081SGeorge Rimar   if (ErrorCount)
263794366a2SRui Ueyama     return;
264794366a2SRui Ueyama   StringRef Tok = next();
265794366a2SRui Ueyama   if (Tok != Expect)
266794366a2SRui Ueyama     setError(Expect + " expected, but got " + Tok);
267794366a2SRui Ueyama }
268794366a2SRui Ueyama 
269794366a2SRui Ueyama // Returns true if S encloses T.
270794366a2SRui Ueyama static bool encloses(StringRef S, StringRef T) {
271794366a2SRui Ueyama   return S.bytes_begin() <= T.bytes_begin() && T.bytes_end() <= S.bytes_end();
272794366a2SRui Ueyama }
273794366a2SRui Ueyama 
274794366a2SRui Ueyama MemoryBufferRef ScriptLexer::getCurrentMB() {
275794366a2SRui Ueyama   // Find input buffer containing the current token.
276794366a2SRui Ueyama   assert(!MBs.empty());
277794366a2SRui Ueyama   if (!Pos)
278794366a2SRui Ueyama     return MBs[0];
279794366a2SRui Ueyama 
280794366a2SRui Ueyama   for (MemoryBufferRef MB : MBs)
281794366a2SRui Ueyama     if (encloses(MB.getBuffer(), Tokens[Pos - 1]))
282794366a2SRui Ueyama       return MB;
283794366a2SRui Ueyama   llvm_unreachable("getCurrentMB: failed to find a token");
284794366a2SRui Ueyama }
285