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"
36*b8a59c8aSBob Haarman #include "lld/Common/ErrorHandler.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*b8a59c8aSBob Haarman   if (errorCount())
79794366a2SRui Ueyama     return;
80794366a2SRui Ueyama 
81de2d1066SGeorge Rimar   std::string S = (getCurrentLocation() + ": " + Msg).str();
82de2d1066SGeorge Rimar   if (Pos)
83de2d1066SGeorge Rimar     S += "\n>>> " + getLine().str() + "\n>>> " +
84de2d1066SGeorge Rimar          std::string(getColumnNumber(), ' ') + "^";
85de2d1066SGeorge Rimar   error(S);
86794366a2SRui Ueyama }
87794366a2SRui Ueyama 
88794366a2SRui Ueyama // Split S into linker script tokens.
89794366a2SRui Ueyama void ScriptLexer::tokenize(MemoryBufferRef MB) {
90794366a2SRui Ueyama   std::vector<StringRef> Vec;
91794366a2SRui Ueyama   MBs.push_back(MB);
92794366a2SRui Ueyama   StringRef S = MB.getBuffer();
93794366a2SRui Ueyama   StringRef Begin = S;
94794366a2SRui Ueyama 
95794366a2SRui Ueyama   for (;;) {
96794366a2SRui Ueyama     S = skipSpace(S);
97794366a2SRui Ueyama     if (S.empty())
98794366a2SRui Ueyama       break;
99794366a2SRui Ueyama 
100794366a2SRui Ueyama     // Quoted token. Note that double-quote characters are parts of a token
101794366a2SRui Ueyama     // because, in a glob match context, only unquoted tokens are interpreted
102794366a2SRui Ueyama     // as glob patterns. Double-quoted tokens are literal patterns in that
103794366a2SRui Ueyama     // context.
104794366a2SRui Ueyama     if (S.startswith("\"")) {
105794366a2SRui Ueyama       size_t E = S.find("\"", 1);
106794366a2SRui Ueyama       if (E == StringRef::npos) {
107794366a2SRui Ueyama         StringRef Filename = MB.getBufferIdentifier();
108794366a2SRui Ueyama         size_t Lineno = Begin.substr(0, S.data() - Begin.data()).count('\n');
109794366a2SRui Ueyama         error(Filename + ":" + Twine(Lineno + 1) + ": unclosed quote");
110794366a2SRui Ueyama         return;
111794366a2SRui Ueyama       }
112794366a2SRui Ueyama 
113794366a2SRui Ueyama       Vec.push_back(S.take_front(E + 1));
114794366a2SRui Ueyama       S = S.substr(E + 1);
115794366a2SRui Ueyama       continue;
116794366a2SRui Ueyama     }
117794366a2SRui Ueyama 
118794366a2SRui Ueyama     // Unquoted token. This is more relaxed than tokens in C-like language,
119794366a2SRui Ueyama     // so that you can write "file-name.cpp" as one bare token, for example.
120794366a2SRui Ueyama     size_t Pos = S.find_first_not_of(
121794366a2SRui Ueyama         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
122f5fce486SRui Ueyama         "0123456789_.$/\\~=+[]*?-!<>^:");
123794366a2SRui Ueyama 
124794366a2SRui Ueyama     // A character that cannot start a word (which is usually a
125794366a2SRui Ueyama     // punctuation) forms a single character token.
126794366a2SRui Ueyama     if (Pos == 0)
127794366a2SRui Ueyama       Pos = 1;
128794366a2SRui Ueyama     Vec.push_back(S.substr(0, Pos));
129794366a2SRui Ueyama     S = S.substr(Pos);
130794366a2SRui Ueyama   }
131794366a2SRui Ueyama 
132794366a2SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, Vec.begin(), Vec.end());
133794366a2SRui Ueyama }
134794366a2SRui Ueyama 
135794366a2SRui Ueyama // Skip leading whitespace characters or comments.
136794366a2SRui Ueyama StringRef ScriptLexer::skipSpace(StringRef S) {
137794366a2SRui Ueyama   for (;;) {
138794366a2SRui Ueyama     if (S.startswith("/*")) {
139794366a2SRui Ueyama       size_t E = S.find("*/", 2);
140794366a2SRui Ueyama       if (E == StringRef::npos) {
141794366a2SRui Ueyama         error("unclosed comment in a linker script");
142794366a2SRui Ueyama         return "";
143794366a2SRui Ueyama       }
144794366a2SRui Ueyama       S = S.substr(E + 2);
145794366a2SRui Ueyama       continue;
146794366a2SRui Ueyama     }
147794366a2SRui Ueyama     if (S.startswith("#")) {
148794366a2SRui Ueyama       size_t E = S.find('\n', 1);
149794366a2SRui Ueyama       if (E == StringRef::npos)
150794366a2SRui Ueyama         E = S.size() - 1;
151794366a2SRui Ueyama       S = S.substr(E + 1);
152794366a2SRui Ueyama       continue;
153794366a2SRui Ueyama     }
154794366a2SRui Ueyama     size_t Size = S.size();
155794366a2SRui Ueyama     S = S.ltrim();
156794366a2SRui Ueyama     if (S.size() == Size)
157794366a2SRui Ueyama       return S;
158794366a2SRui Ueyama   }
159794366a2SRui Ueyama }
160794366a2SRui Ueyama 
161794366a2SRui Ueyama // An erroneous token is handled as if it were the last token before EOF.
162*b8a59c8aSBob Haarman bool ScriptLexer::atEOF() { return errorCount() || Tokens.size() == Pos; }
163794366a2SRui Ueyama 
164731a66aeSRui Ueyama // Split a given string as an expression.
165731a66aeSRui Ueyama // This function returns "3", "*" and "5" for "3*5" for example.
166731a66aeSRui Ueyama static std::vector<StringRef> tokenizeExpr(StringRef S) {
16781eca18dSGeorge Rimar   StringRef Ops = "+-*/:!~"; // List of operators
168731a66aeSRui Ueyama 
169731a66aeSRui Ueyama   // Quoted strings are literal strings, so we don't want to split it.
170731a66aeSRui Ueyama   if (S.startswith("\""))
171731a66aeSRui Ueyama     return {S};
172731a66aeSRui Ueyama 
173970e783bSGeorge Rimar   // Split S with operators as separators.
174731a66aeSRui Ueyama   std::vector<StringRef> Ret;
175731a66aeSRui Ueyama   while (!S.empty()) {
176731a66aeSRui Ueyama     size_t E = S.find_first_of(Ops);
177731a66aeSRui Ueyama 
178731a66aeSRui Ueyama     // No need to split if there is no operator.
179731a66aeSRui Ueyama     if (E == StringRef::npos) {
180731a66aeSRui Ueyama       Ret.push_back(S);
181731a66aeSRui Ueyama       break;
182731a66aeSRui Ueyama     }
183731a66aeSRui Ueyama 
184731a66aeSRui Ueyama     // Get a token before the opreator.
185731a66aeSRui Ueyama     if (E != 0)
186731a66aeSRui Ueyama       Ret.push_back(S.substr(0, E));
187731a66aeSRui Ueyama 
1886f1d954eSHafiz Abid Qadeer     // Get the operator as a token. Keep != as one token.
1896f1d954eSHafiz Abid Qadeer     if (S.substr(E).startswith("!=")) {
1906f1d954eSHafiz Abid Qadeer       Ret.push_back(S.substr(E, 2));
1916f1d954eSHafiz Abid Qadeer       S = S.substr(E + 2);
1926f1d954eSHafiz Abid Qadeer     } else {
193731a66aeSRui Ueyama       Ret.push_back(S.substr(E, 1));
194731a66aeSRui Ueyama       S = S.substr(E + 1);
195731a66aeSRui Ueyama     }
1966f1d954eSHafiz Abid Qadeer   }
197731a66aeSRui Ueyama   return Ret;
198731a66aeSRui Ueyama }
199731a66aeSRui Ueyama 
200731a66aeSRui Ueyama // In contexts where expressions are expected, the lexer should apply
201731a66aeSRui Ueyama // different tokenization rules than the default one. By default,
202731a66aeSRui Ueyama // arithmetic operator characters are regular characters, but in the
203731a66aeSRui Ueyama // expression context, they should be independent tokens.
204731a66aeSRui Ueyama //
205731a66aeSRui Ueyama // For example, "foo*3" should be tokenized to "foo", "*" and "3" only
206731a66aeSRui Ueyama // in the expression context.
207731a66aeSRui Ueyama //
208731a66aeSRui Ueyama // This function may split the current token into multiple tokens.
209731a66aeSRui Ueyama void ScriptLexer::maybeSplitExpr() {
210*b8a59c8aSBob Haarman   if (!InExpr || errorCount() || atEOF())
211731a66aeSRui Ueyama     return;
212731a66aeSRui Ueyama 
213731a66aeSRui Ueyama   std::vector<StringRef> V = tokenizeExpr(Tokens[Pos]);
214731a66aeSRui Ueyama   if (V.size() == 1)
215731a66aeSRui Ueyama     return;
216731a66aeSRui Ueyama   Tokens.erase(Tokens.begin() + Pos);
217731a66aeSRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
218731a66aeSRui Ueyama }
219731a66aeSRui Ueyama 
220794366a2SRui Ueyama StringRef ScriptLexer::next() {
221731a66aeSRui Ueyama   maybeSplitExpr();
222731a66aeSRui Ueyama 
223*b8a59c8aSBob Haarman   if (errorCount())
224794366a2SRui Ueyama     return "";
225794366a2SRui Ueyama   if (atEOF()) {
226794366a2SRui Ueyama     setError("unexpected EOF");
227794366a2SRui Ueyama     return "";
228794366a2SRui Ueyama   }
229794366a2SRui Ueyama   return Tokens[Pos++];
230794366a2SRui Ueyama }
231794366a2SRui Ueyama 
232f5fce486SRui Ueyama StringRef ScriptLexer::peek() {
233f5fce486SRui Ueyama   StringRef Tok = next();
234*b8a59c8aSBob Haarman   if (errorCount())
235794366a2SRui Ueyama     return "";
236f5fce486SRui Ueyama   Pos = Pos - 1;
237794366a2SRui Ueyama   return Tok;
238794366a2SRui Ueyama }
239794366a2SRui Ueyama 
240794366a2SRui Ueyama bool ScriptLexer::consume(StringRef Tok) {
241794366a2SRui Ueyama   if (peek() == Tok) {
242794366a2SRui Ueyama     skip();
243794366a2SRui Ueyama     return true;
244794366a2SRui Ueyama   }
245794366a2SRui Ueyama   return false;
246794366a2SRui Ueyama }
247794366a2SRui Ueyama 
248f5fce486SRui Ueyama // Consumes Tok followed by ":". Space is allowed between Tok and ":".
249f5fce486SRui Ueyama bool ScriptLexer::consumeLabel(StringRef Tok) {
250f5fce486SRui Ueyama   if (consume((Tok + ":").str()))
251f5fce486SRui Ueyama     return true;
252f5fce486SRui Ueyama   if (Tokens.size() >= Pos + 2 && Tokens[Pos] == Tok &&
253f5fce486SRui Ueyama       Tokens[Pos + 1] == ":") {
254f5fce486SRui Ueyama     Pos += 2;
255f5fce486SRui Ueyama     return true;
256f5fce486SRui Ueyama   }
257f5fce486SRui Ueyama   return false;
258f5fce486SRui Ueyama }
259f5fce486SRui Ueyama 
260794366a2SRui Ueyama void ScriptLexer::skip() { (void)next(); }
261794366a2SRui Ueyama 
262794366a2SRui Ueyama void ScriptLexer::expect(StringRef Expect) {
263*b8a59c8aSBob Haarman   if (errorCount())
264794366a2SRui Ueyama     return;
265794366a2SRui Ueyama   StringRef Tok = next();
266794366a2SRui Ueyama   if (Tok != Expect)
267794366a2SRui Ueyama     setError(Expect + " expected, but got " + Tok);
268794366a2SRui Ueyama }
269794366a2SRui Ueyama 
270794366a2SRui Ueyama // Returns true if S encloses T.
271794366a2SRui Ueyama static bool encloses(StringRef S, StringRef T) {
272794366a2SRui Ueyama   return S.bytes_begin() <= T.bytes_begin() && T.bytes_end() <= S.bytes_end();
273794366a2SRui Ueyama }
274794366a2SRui Ueyama 
275794366a2SRui Ueyama MemoryBufferRef ScriptLexer::getCurrentMB() {
276794366a2SRui Ueyama   // Find input buffer containing the current token.
277794366a2SRui Ueyama   assert(!MBs.empty());
278794366a2SRui Ueyama   if (!Pos)
279794366a2SRui Ueyama     return MBs[0];
280794366a2SRui Ueyama 
281794366a2SRui Ueyama   for (MemoryBufferRef MB : MBs)
282794366a2SRui Ueyama     if (encloses(MB.getBuffer(), Tokens[Pos - 1]))
283794366a2SRui Ueyama       return MB;
284794366a2SRui Ueyama   llvm_unreachable("getCurrentMB: failed to find a token");
285794366a2SRui Ueyama }
286