1 //===- ScriptLexer.cpp ----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a lexer for the linker script.
11 //
12 // The linker script's grammar is not complex but ambiguous due to the
13 // lack of the formal specification of the language. What we are trying to
14 // do in this and other files in LLD is to make a "reasonable" linker
15 // script processor.
16 //
17 // Among simplicity, compatibility and efficiency, we put the most
18 // emphasis on simplicity when we wrote this lexer. Compatibility with the
19 // GNU linkers is important, but we did not try to clone every tiny corner
20 // case of their lexers, as even ld.bfd and ld.gold are subtly different
21 // in various corner cases. We do not care much about efficiency because
22 // the time spent in parsing linker scripts is usually negligible.
23 //
24 // Our grammar of the linker script is LL(2), meaning that it needs at
25 // most two-token lookahead to parse. The only place we need two-token
26 // lookahead is labels in version scripts, where we need to parse "local :"
27 // as if "local:".
28 //
29 // Overall, this lexer works fine for most linker scripts. There might
30 // be room for improving compatibility, but that's probably not at the
31 // top of our todo list.
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "ScriptLexer.h"
36 #include "Error.h"
37 #include "llvm/ADT/Twine.h"
38 
39 using namespace llvm;
40 using namespace lld;
41 using namespace lld::elf;
42 
43 // Returns a whole line containing the current token.
44 StringRef ScriptLexer::getLine() {
45   StringRef S = getCurrentMB().getBuffer();
46   StringRef Tok = Tokens[Pos - 1];
47 
48   size_t Pos = S.rfind('\n', Tok.data() - S.data());
49   if (Pos != StringRef::npos)
50     S = S.substr(Pos + 1);
51   return S.substr(0, S.find_first_of("\r\n"));
52 }
53 
54 // Returns 1-based line number of the current token.
55 size_t ScriptLexer::getLineNumber() {
56   StringRef S = getCurrentMB().getBuffer();
57   StringRef Tok = Tokens[Pos - 1];
58   return S.substr(0, Tok.data() - S.data()).count('\n') + 1;
59 }
60 
61 // Returns 0-based column number of the current token.
62 size_t ScriptLexer::getColumnNumber() {
63   StringRef Tok = Tokens[Pos - 1];
64   return Tok.data() - getLine().data();
65 }
66 
67 std::string ScriptLexer::getCurrentLocation() {
68   std::string Filename = getCurrentMB().getBufferIdentifier();
69   if (!Pos)
70     return Filename;
71   return (Filename + ":" + Twine(getLineNumber())).str();
72 }
73 
74 ScriptLexer::ScriptLexer(MemoryBufferRef MB) { tokenize(MB); }
75 
76 // We don't want to record cascading errors. Keep only the first one.
77 void ScriptLexer::setError(const Twine &Msg) {
78   if (ErrorCount)
79     return;
80 
81   if (!Pos) {
82     error(getCurrentLocation() + ": " + Msg);
83     return;
84   }
85 
86   std::string S = getCurrentLocation() + ": ";
87   error(S + Msg);
88   error(S + getLine());
89   error(S + std::string(getColumnNumber(), ' ') + "^");
90 }
91 
92 // Split S into linker script tokens.
93 void ScriptLexer::tokenize(MemoryBufferRef MB) {
94   std::vector<StringRef> Vec;
95   MBs.push_back(MB);
96   StringRef S = MB.getBuffer();
97   StringRef Begin = S;
98 
99   for (;;) {
100     S = skipSpace(S);
101     if (S.empty())
102       break;
103 
104     // Quoted token. Note that double-quote characters are parts of a token
105     // because, in a glob match context, only unquoted tokens are interpreted
106     // as glob patterns. Double-quoted tokens are literal patterns in that
107     // context.
108     if (S.startswith("\"")) {
109       size_t E = S.find("\"", 1);
110       if (E == StringRef::npos) {
111         StringRef Filename = MB.getBufferIdentifier();
112         size_t Lineno = Begin.substr(0, S.data() - Begin.data()).count('\n');
113         error(Filename + ":" + Twine(Lineno + 1) + ": unclosed quote");
114         return;
115       }
116 
117       Vec.push_back(S.take_front(E + 1));
118       S = S.substr(E + 1);
119       continue;
120     }
121 
122     // Unquoted token. This is more relaxed than tokens in C-like language,
123     // so that you can write "file-name.cpp" as one bare token, for example.
124     size_t Pos = S.find_first_not_of(
125         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
126         "0123456789_.$/\\~=+[]*?-!<>^:");
127 
128     // A character that cannot start a word (which is usually a
129     // punctuation) forms a single character token.
130     if (Pos == 0)
131       Pos = 1;
132     Vec.push_back(S.substr(0, Pos));
133     S = S.substr(Pos);
134   }
135 
136   Tokens.insert(Tokens.begin() + Pos, Vec.begin(), Vec.end());
137 }
138 
139 // Skip leading whitespace characters or comments.
140 StringRef ScriptLexer::skipSpace(StringRef S) {
141   for (;;) {
142     if (S.startswith("/*")) {
143       size_t E = S.find("*/", 2);
144       if (E == StringRef::npos) {
145         error("unclosed comment in a linker script");
146         return "";
147       }
148       S = S.substr(E + 2);
149       continue;
150     }
151     if (S.startswith("#")) {
152       size_t E = S.find('\n', 1);
153       if (E == StringRef::npos)
154         E = S.size() - 1;
155       S = S.substr(E + 1);
156       continue;
157     }
158     size_t Size = S.size();
159     S = S.ltrim();
160     if (S.size() == Size)
161       return S;
162   }
163 }
164 
165 // An erroneous token is handled as if it were the last token before EOF.
166 bool ScriptLexer::atEOF() { return ErrorCount || Tokens.size() == Pos; }
167 
168 // Split a given string as an expression.
169 // This function returns "3", "*" and "5" for "3*5" for example.
170 static std::vector<StringRef> tokenizeExpr(StringRef S) {
171   StringRef Ops = "+-*/:!"; // List of operators
172 
173   // Quoted strings are literal strings, so we don't want to split it.
174   if (S.startswith("\""))
175     return {S};
176 
177   // Split S with +-*/ as separators.
178   std::vector<StringRef> Ret;
179   while (!S.empty()) {
180     size_t E = S.find_first_of(Ops);
181 
182     // No need to split if there is no operator.
183     if (E == StringRef::npos) {
184       Ret.push_back(S);
185       break;
186     }
187 
188     // Get a token before the opreator.
189     if (E != 0)
190       Ret.push_back(S.substr(0, E));
191 
192     // Get the operator as a token. Keep != as one token.
193     if (S.substr(E).startswith("!=")) {
194       Ret.push_back(S.substr(E, 2));
195       S = S.substr(E + 2);
196     } else {
197       Ret.push_back(S.substr(E, 1));
198       S = S.substr(E + 1);
199     }
200   }
201   return Ret;
202 }
203 
204 // In contexts where expressions are expected, the lexer should apply
205 // different tokenization rules than the default one. By default,
206 // arithmetic operator characters are regular characters, but in the
207 // expression context, they should be independent tokens.
208 //
209 // For example, "foo*3" should be tokenized to "foo", "*" and "3" only
210 // in the expression context.
211 //
212 // This function may split the current token into multiple tokens.
213 void ScriptLexer::maybeSplitExpr() {
214   if (!InExpr || ErrorCount || atEOF())
215     return;
216 
217   std::vector<StringRef> V = tokenizeExpr(Tokens[Pos]);
218   if (V.size() == 1)
219     return;
220   Tokens.erase(Tokens.begin() + Pos);
221   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
222 }
223 
224 StringRef ScriptLexer::next() {
225   maybeSplitExpr();
226 
227   if (ErrorCount)
228     return "";
229   if (atEOF()) {
230     setError("unexpected EOF");
231     return "";
232   }
233   return Tokens[Pos++];
234 }
235 
236 StringRef ScriptLexer::peek() {
237   StringRef Tok = next();
238   if (ErrorCount)
239     return "";
240   Pos = Pos - 1;
241   return Tok;
242 }
243 
244 bool ScriptLexer::consume(StringRef Tok) {
245   if (peek() == Tok) {
246     skip();
247     return true;
248   }
249   return false;
250 }
251 
252 // Consumes Tok followed by ":". Space is allowed between Tok and ":".
253 bool ScriptLexer::consumeLabel(StringRef Tok) {
254   if (consume((Tok + ":").str()))
255     return true;
256   if (Tokens.size() >= Pos + 2 && Tokens[Pos] == Tok &&
257       Tokens[Pos + 1] == ":") {
258     Pos += 2;
259     return true;
260   }
261   return false;
262 }
263 
264 void ScriptLexer::skip() { (void)next(); }
265 
266 void ScriptLexer::expect(StringRef Expect) {
267   if (ErrorCount)
268     return;
269   StringRef Tok = next();
270   if (Tok != Expect)
271     setError(Expect + " expected, but got " + Tok);
272 }
273 
274 // Returns true if S encloses T.
275 static bool encloses(StringRef S, StringRef T) {
276   return S.bytes_begin() <= T.bytes_begin() && T.bytes_end() <= S.bytes_end();
277 }
278 
279 MemoryBufferRef ScriptLexer::getCurrentMB() {
280   // Find input buffer containing the current token.
281   assert(!MBs.empty());
282   if (!Pos)
283     return MBs[0];
284 
285   for (MemoryBufferRef MB : MBs)
286     if (encloses(MB.getBuffer(), Tokens[Pos - 1]))
287       return MB;
288   llvm_unreachable("getCurrentMB: failed to find a token");
289 }
290