]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/ScriptLexer.cpp
Merge lld trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / ScriptLexer.cpp
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 (Error)
79     return;
80   Error = true;
81
82   if (!Pos) {
83     error(getCurrentLocation() + ": " + Msg);
84     return;
85   }
86
87   std::string S = getCurrentLocation() + ": ";
88   error(S + Msg);
89   error(S + getLine());
90   error(S + std::string(getColumnNumber(), ' ') + "^");
91 }
92
93 // Split S into linker script tokens.
94 void ScriptLexer::tokenize(MemoryBufferRef MB) {
95   std::vector<StringRef> Vec;
96   MBs.push_back(MB);
97   StringRef S = MB.getBuffer();
98   StringRef Begin = S;
99
100   for (;;) {
101     S = skipSpace(S);
102     if (S.empty())
103       break;
104
105     // Quoted token. Note that double-quote characters are parts of a token
106     // because, in a glob match context, only unquoted tokens are interpreted
107     // as glob patterns. Double-quoted tokens are literal patterns in that
108     // context.
109     if (S.startswith("\"")) {
110       size_t E = S.find("\"", 1);
111       if (E == StringRef::npos) {
112         StringRef Filename = MB.getBufferIdentifier();
113         size_t Lineno = Begin.substr(0, S.data() - Begin.data()).count('\n');
114         error(Filename + ":" + Twine(Lineno + 1) + ": unclosed quote");
115         return;
116       }
117
118       Vec.push_back(S.take_front(E + 1));
119       S = S.substr(E + 1);
120       continue;
121     }
122
123     // Unquoted token. This is more relaxed than tokens in C-like language,
124     // so that you can write "file-name.cpp" as one bare token, for example.
125     size_t Pos = S.find_first_not_of(
126         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
127         "0123456789_.$/\\~=+[]*?-!<>^:");
128
129     // A character that cannot start a word (which is usually a
130     // punctuation) forms a single character token.
131     if (Pos == 0)
132       Pos = 1;
133     Vec.push_back(S.substr(0, Pos));
134     S = S.substr(Pos);
135   }
136
137   Tokens.insert(Tokens.begin() + Pos, Vec.begin(), Vec.end());
138 }
139
140 // Skip leading whitespace characters or comments.
141 StringRef ScriptLexer::skipSpace(StringRef S) {
142   for (;;) {
143     if (S.startswith("/*")) {
144       size_t E = S.find("*/", 2);
145       if (E == StringRef::npos) {
146         error("unclosed comment in a linker script");
147         return "";
148       }
149       S = S.substr(E + 2);
150       continue;
151     }
152     if (S.startswith("#")) {
153       size_t E = S.find('\n', 1);
154       if (E == StringRef::npos)
155         E = S.size() - 1;
156       S = S.substr(E + 1);
157       continue;
158     }
159     size_t Size = S.size();
160     S = S.ltrim();
161     if (S.size() == Size)
162       return S;
163   }
164 }
165
166 // An erroneous token is handled as if it were the last token before EOF.
167 bool ScriptLexer::atEOF() { return Error || Tokens.size() == Pos; }
168
169 // Split a given string as an expression.
170 // This function returns "3", "*" and "5" for "3*5" for example.
171 static std::vector<StringRef> tokenizeExpr(StringRef S) {
172   StringRef Ops = "+-*/:"; // List of operators
173
174   // Quoted strings are literal strings, so we don't want to split it.
175   if (S.startswith("\""))
176     return {S};
177
178   // Split S with +-*/ as separators.
179   std::vector<StringRef> Ret;
180   while (!S.empty()) {
181     size_t E = S.find_first_of(Ops);
182
183     // No need to split if there is no operator.
184     if (E == StringRef::npos) {
185       Ret.push_back(S);
186       break;
187     }
188
189     // Get a token before the opreator.
190     if (E != 0)
191       Ret.push_back(S.substr(0, E));
192
193     // Get the operator as a token.
194     Ret.push_back(S.substr(E, 1));
195     S = S.substr(E + 1);
196   }
197   return Ret;
198 }
199
200 // In contexts where expressions are expected, the lexer should apply
201 // different tokenization rules than the default one. By default,
202 // arithmetic operator characters are regular characters, but in the
203 // expression context, they should be independent tokens.
204 //
205 // For example, "foo*3" should be tokenized to "foo", "*" and "3" only
206 // in the expression context.
207 //
208 // This function may split the current token into multiple tokens.
209 void ScriptLexer::maybeSplitExpr() {
210   if (!InExpr || Error || atEOF())
211     return;
212
213   std::vector<StringRef> V = tokenizeExpr(Tokens[Pos]);
214   if (V.size() == 1)
215     return;
216   Tokens.erase(Tokens.begin() + Pos);
217   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
218 }
219
220 StringRef ScriptLexer::next() {
221   maybeSplitExpr();
222
223   if (Error)
224     return "";
225   if (atEOF()) {
226     setError("unexpected EOF");
227     return "";
228   }
229   return Tokens[Pos++];
230 }
231
232 StringRef ScriptLexer::peek() {
233   StringRef Tok = next();
234   if (Error)
235     return "";
236   Pos = Pos - 1;
237   return Tok;
238 }
239
240 bool ScriptLexer::consume(StringRef Tok) {
241   if (peek() == Tok) {
242     skip();
243     return true;
244   }
245   return false;
246 }
247
248 // Consumes Tok followed by ":". Space is allowed between Tok and ":".
249 bool ScriptLexer::consumeLabel(StringRef Tok) {
250   if (consume((Tok + ":").str()))
251     return true;
252   if (Tokens.size() >= Pos + 2 && Tokens[Pos] == Tok &&
253       Tokens[Pos + 1] == ":") {
254     Pos += 2;
255     return true;
256   }
257   return false;
258 }
259
260 void ScriptLexer::skip() { (void)next(); }
261
262 void ScriptLexer::expect(StringRef Expect) {
263   if (Error)
264     return;
265   StringRef Tok = next();
266   if (Tok != Expect)
267     setError(Expect + " expected, but got " + Tok);
268 }
269
270 // Returns true if S encloses T.
271 static bool encloses(StringRef S, StringRef T) {
272   return S.bytes_begin() <= T.bytes_begin() && T.bytes_end() <= S.bytes_end();
273 }
274
275 MemoryBufferRef ScriptLexer::getCurrentMB() {
276   // Find input buffer containing the current token.
277   assert(!MBs.empty());
278   if (!Pos)
279     return MBs[0];
280
281   for (MemoryBufferRef MB : MBs)
282     if (encloses(MB.getBuffer(), Tokens[Pos - 1]))
283       return MB;
284   llvm_unreachable("getCurrentMB: failed to find a token");
285 }