xref: /openbsd-src/gnu/llvm/lld/ELF/ScriptLexer.cpp (revision dfe94b169149f14cc1aee2cf6dad58a8d9a1860c)
1ece8a530Spatrick //===- ScriptLexer.cpp ----------------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick //
9ece8a530Spatrick // This file defines a lexer for the linker script.
10ece8a530Spatrick //
11ece8a530Spatrick // The linker script's grammar is not complex but ambiguous due to the
12ece8a530Spatrick // lack of the formal specification of the language. What we are trying to
13ece8a530Spatrick // do in this and other files in LLD is to make a "reasonable" linker
14ece8a530Spatrick // script processor.
15ece8a530Spatrick //
16ece8a530Spatrick // Among simplicity, compatibility and efficiency, we put the most
17ece8a530Spatrick // emphasis on simplicity when we wrote this lexer. Compatibility with the
18ece8a530Spatrick // GNU linkers is important, but we did not try to clone every tiny corner
19ece8a530Spatrick // case of their lexers, as even ld.bfd and ld.gold are subtly different
20ece8a530Spatrick // in various corner cases. We do not care much about efficiency because
21ece8a530Spatrick // the time spent in parsing linker scripts is usually negligible.
22ece8a530Spatrick //
23ece8a530Spatrick // Our grammar of the linker script is LL(2), meaning that it needs at
24ece8a530Spatrick // most two-token lookahead to parse. The only place we need two-token
25ece8a530Spatrick // lookahead is labels in version scripts, where we need to parse "local :"
26ece8a530Spatrick // as if "local:".
27ece8a530Spatrick //
28ece8a530Spatrick // Overall, this lexer works fine for most linker scripts. There might
29ece8a530Spatrick // be room for improving compatibility, but that's probably not at the
30ece8a530Spatrick // top of our todo list.
31ece8a530Spatrick //
32ece8a530Spatrick //===----------------------------------------------------------------------===//
33ece8a530Spatrick 
34ece8a530Spatrick #include "ScriptLexer.h"
35ece8a530Spatrick #include "lld/Common/ErrorHandler.h"
36ece8a530Spatrick #include "llvm/ADT/Twine.h"
37*dfe94b16Srobert #include "llvm/Support/ErrorHandling.h"
38*dfe94b16Srobert #include <algorithm>
39ece8a530Spatrick 
40ece8a530Spatrick using namespace llvm;
41bb684c34Spatrick using namespace lld;
42bb684c34Spatrick using namespace lld::elf;
43ece8a530Spatrick 
44ece8a530Spatrick // Returns a whole line containing the current token.
getLine()45ece8a530Spatrick StringRef ScriptLexer::getLine() {
46ece8a530Spatrick   StringRef s = getCurrentMB().getBuffer();
47ece8a530Spatrick   StringRef tok = tokens[pos - 1];
48ece8a530Spatrick 
49ece8a530Spatrick   size_t pos = s.rfind('\n', tok.data() - s.data());
50ece8a530Spatrick   if (pos != StringRef::npos)
51ece8a530Spatrick     s = s.substr(pos + 1);
52ece8a530Spatrick   return s.substr(0, s.find_first_of("\r\n"));
53ece8a530Spatrick }
54ece8a530Spatrick 
55ece8a530Spatrick // Returns 1-based line number of the current token.
getLineNumber()56ece8a530Spatrick size_t ScriptLexer::getLineNumber() {
57667950d7Spatrick   if (pos == 0)
58667950d7Spatrick     return 1;
59ece8a530Spatrick   StringRef s = getCurrentMB().getBuffer();
60ece8a530Spatrick   StringRef tok = tokens[pos - 1];
611cf9926bSpatrick   const size_t tokOffset = tok.data() - s.data();
621cf9926bSpatrick 
631cf9926bSpatrick   // For the first token, or when going backwards, start from the beginning of
641cf9926bSpatrick   // the buffer. If this token is after the previous token, start from the
651cf9926bSpatrick   // previous token.
661cf9926bSpatrick   size_t line = 1;
671cf9926bSpatrick   size_t start = 0;
681cf9926bSpatrick   if (lastLineNumberOffset > 0 && tokOffset >= lastLineNumberOffset) {
691cf9926bSpatrick     start = lastLineNumberOffset;
701cf9926bSpatrick     line = lastLineNumber;
711cf9926bSpatrick   }
721cf9926bSpatrick 
731cf9926bSpatrick   line += s.substr(start, tokOffset - start).count('\n');
741cf9926bSpatrick 
751cf9926bSpatrick   // Store the line number of this token for reuse.
761cf9926bSpatrick   lastLineNumberOffset = tokOffset;
771cf9926bSpatrick   lastLineNumber = line;
781cf9926bSpatrick 
791cf9926bSpatrick   return line;
80ece8a530Spatrick }
81ece8a530Spatrick 
82ece8a530Spatrick // Returns 0-based column number of the current token.
getColumnNumber()83ece8a530Spatrick size_t ScriptLexer::getColumnNumber() {
84ece8a530Spatrick   StringRef tok = tokens[pos - 1];
85ece8a530Spatrick   return tok.data() - getLine().data();
86ece8a530Spatrick }
87ece8a530Spatrick 
getCurrentLocation()88ece8a530Spatrick std::string ScriptLexer::getCurrentLocation() {
89bb684c34Spatrick   std::string filename = std::string(getCurrentMB().getBufferIdentifier());
90ece8a530Spatrick   return (filename + ":" + Twine(getLineNumber())).str();
91ece8a530Spatrick }
92ece8a530Spatrick 
ScriptLexer(MemoryBufferRef mb)93ece8a530Spatrick ScriptLexer::ScriptLexer(MemoryBufferRef mb) { tokenize(mb); }
94ece8a530Spatrick 
95ece8a530Spatrick // We don't want to record cascading errors. Keep only the first one.
setError(const Twine & msg)96ece8a530Spatrick void ScriptLexer::setError(const Twine &msg) {
97ece8a530Spatrick   if (errorCount())
98ece8a530Spatrick     return;
99ece8a530Spatrick 
100ece8a530Spatrick   std::string s = (getCurrentLocation() + ": " + msg).str();
101ece8a530Spatrick   if (pos)
102ece8a530Spatrick     s += "\n>>> " + getLine().str() + "\n>>> " +
103ece8a530Spatrick          std::string(getColumnNumber(), ' ') + "^";
104ece8a530Spatrick   error(s);
105ece8a530Spatrick }
106ece8a530Spatrick 
107ece8a530Spatrick // Split S into linker script tokens.
tokenize(MemoryBufferRef mb)108ece8a530Spatrick void ScriptLexer::tokenize(MemoryBufferRef mb) {
109ece8a530Spatrick   std::vector<StringRef> vec;
110ece8a530Spatrick   mbs.push_back(mb);
111ece8a530Spatrick   StringRef s = mb.getBuffer();
112ece8a530Spatrick   StringRef begin = s;
113ece8a530Spatrick 
114ece8a530Spatrick   for (;;) {
115ece8a530Spatrick     s = skipSpace(s);
116ece8a530Spatrick     if (s.empty())
117ece8a530Spatrick       break;
118ece8a530Spatrick 
119ece8a530Spatrick     // Quoted token. Note that double-quote characters are parts of a token
120ece8a530Spatrick     // because, in a glob match context, only unquoted tokens are interpreted
121ece8a530Spatrick     // as glob patterns. Double-quoted tokens are literal patterns in that
122ece8a530Spatrick     // context.
123ece8a530Spatrick     if (s.startswith("\"")) {
124ece8a530Spatrick       size_t e = s.find("\"", 1);
125ece8a530Spatrick       if (e == StringRef::npos) {
126ece8a530Spatrick         StringRef filename = mb.getBufferIdentifier();
127ece8a530Spatrick         size_t lineno = begin.substr(0, s.data() - begin.data()).count('\n');
128ece8a530Spatrick         error(filename + ":" + Twine(lineno + 1) + ": unclosed quote");
129ece8a530Spatrick         return;
130ece8a530Spatrick       }
131ece8a530Spatrick 
132ece8a530Spatrick       vec.push_back(s.take_front(e + 1));
133ece8a530Spatrick       s = s.substr(e + 1);
134ece8a530Spatrick       continue;
135ece8a530Spatrick     }
136ece8a530Spatrick 
137*dfe94b16Srobert     // Some operators form separate tokens.
138*dfe94b16Srobert     if (s.startswith("<<=") || s.startswith(">>=")) {
139*dfe94b16Srobert       vec.push_back(s.substr(0, 3));
140*dfe94b16Srobert       s = s.substr(3);
141*dfe94b16Srobert       continue;
142*dfe94b16Srobert     }
143*dfe94b16Srobert     if (s.size() > 1 && ((s[1] == '=' && strchr("*/+-<>&|", s[0])) ||
144*dfe94b16Srobert                          (s[0] == s[1] && strchr("<>&|", s[0])))) {
145ece8a530Spatrick       vec.push_back(s.substr(0, 2));
146ece8a530Spatrick       s = s.substr(2);
147ece8a530Spatrick       continue;
148ece8a530Spatrick     }
149ece8a530Spatrick 
150ece8a530Spatrick     // Unquoted token. This is more relaxed than tokens in C-like language,
151ece8a530Spatrick     // so that you can write "file-name.cpp" as one bare token, for example.
152ece8a530Spatrick     size_t pos = s.find_first_not_of(
153ece8a530Spatrick         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
154ece8a530Spatrick         "0123456789_.$/\\~=+[]*?-!^:");
155ece8a530Spatrick 
156ece8a530Spatrick     // A character that cannot start a word (which is usually a
157ece8a530Spatrick     // punctuation) forms a single character token.
158ece8a530Spatrick     if (pos == 0)
159ece8a530Spatrick       pos = 1;
160ece8a530Spatrick     vec.push_back(s.substr(0, pos));
161ece8a530Spatrick     s = s.substr(pos);
162ece8a530Spatrick   }
163ece8a530Spatrick 
164ece8a530Spatrick   tokens.insert(tokens.begin() + pos, vec.begin(), vec.end());
165ece8a530Spatrick }
166ece8a530Spatrick 
167ece8a530Spatrick // Skip leading whitespace characters or comments.
skipSpace(StringRef s)168ece8a530Spatrick StringRef ScriptLexer::skipSpace(StringRef s) {
169ece8a530Spatrick   for (;;) {
170ece8a530Spatrick     if (s.startswith("/*")) {
171ece8a530Spatrick       size_t e = s.find("*/", 2);
172ece8a530Spatrick       if (e == StringRef::npos) {
1731cf9926bSpatrick         setError("unclosed comment in a linker script");
174ece8a530Spatrick         return "";
175ece8a530Spatrick       }
176ece8a530Spatrick       s = s.substr(e + 2);
177ece8a530Spatrick       continue;
178ece8a530Spatrick     }
179ece8a530Spatrick     if (s.startswith("#")) {
180ece8a530Spatrick       size_t e = s.find('\n', 1);
181ece8a530Spatrick       if (e == StringRef::npos)
182ece8a530Spatrick         e = s.size() - 1;
183ece8a530Spatrick       s = s.substr(e + 1);
184ece8a530Spatrick       continue;
185ece8a530Spatrick     }
186ece8a530Spatrick     size_t size = s.size();
187ece8a530Spatrick     s = s.ltrim();
188ece8a530Spatrick     if (s.size() == size)
189ece8a530Spatrick       return s;
190ece8a530Spatrick   }
191ece8a530Spatrick }
192ece8a530Spatrick 
193ece8a530Spatrick // An erroneous token is handled as if it were the last token before EOF.
atEOF()194ece8a530Spatrick bool ScriptLexer::atEOF() { return errorCount() || tokens.size() == pos; }
195ece8a530Spatrick 
196ece8a530Spatrick // Split a given string as an expression.
197ece8a530Spatrick // This function returns "3", "*" and "5" for "3*5" for example.
tokenizeExpr(StringRef s)198ece8a530Spatrick static std::vector<StringRef> tokenizeExpr(StringRef s) {
199*dfe94b16Srobert   StringRef ops = "!~*/+-<>?:="; // List of operators
200ece8a530Spatrick 
201ece8a530Spatrick   // Quoted strings are literal strings, so we don't want to split it.
202ece8a530Spatrick   if (s.startswith("\""))
203ece8a530Spatrick     return {s};
204ece8a530Spatrick 
205ece8a530Spatrick   // Split S with operators as separators.
206ece8a530Spatrick   std::vector<StringRef> ret;
207ece8a530Spatrick   while (!s.empty()) {
208ece8a530Spatrick     size_t e = s.find_first_of(ops);
209ece8a530Spatrick 
210ece8a530Spatrick     // No need to split if there is no operator.
211ece8a530Spatrick     if (e == StringRef::npos) {
212ece8a530Spatrick       ret.push_back(s);
213ece8a530Spatrick       break;
214ece8a530Spatrick     }
215ece8a530Spatrick 
216bb684c34Spatrick     // Get a token before the operator.
217ece8a530Spatrick     if (e != 0)
218ece8a530Spatrick       ret.push_back(s.substr(0, e));
219ece8a530Spatrick 
220ece8a530Spatrick     // Get the operator as a token.
221ece8a530Spatrick     // Keep !=, ==, >=, <=, << and >> operators as a single tokens.
222ece8a530Spatrick     if (s.substr(e).startswith("!=") || s.substr(e).startswith("==") ||
223ece8a530Spatrick         s.substr(e).startswith(">=") || s.substr(e).startswith("<=") ||
224ece8a530Spatrick         s.substr(e).startswith("<<") || s.substr(e).startswith(">>")) {
225ece8a530Spatrick       ret.push_back(s.substr(e, 2));
226ece8a530Spatrick       s = s.substr(e + 2);
227ece8a530Spatrick     } else {
228ece8a530Spatrick       ret.push_back(s.substr(e, 1));
229ece8a530Spatrick       s = s.substr(e + 1);
230ece8a530Spatrick     }
231ece8a530Spatrick   }
232ece8a530Spatrick   return ret;
233ece8a530Spatrick }
234ece8a530Spatrick 
235ece8a530Spatrick // In contexts where expressions are expected, the lexer should apply
236ece8a530Spatrick // different tokenization rules than the default one. By default,
237ece8a530Spatrick // arithmetic operator characters are regular characters, but in the
238ece8a530Spatrick // expression context, they should be independent tokens.
239ece8a530Spatrick //
240ece8a530Spatrick // For example, "foo*3" should be tokenized to "foo", "*" and "3" only
241ece8a530Spatrick // in the expression context.
242ece8a530Spatrick //
243ece8a530Spatrick // This function may split the current token into multiple tokens.
maybeSplitExpr()244ece8a530Spatrick void ScriptLexer::maybeSplitExpr() {
245ece8a530Spatrick   if (!inExpr || errorCount() || atEOF())
246ece8a530Spatrick     return;
247ece8a530Spatrick 
248ece8a530Spatrick   std::vector<StringRef> v = tokenizeExpr(tokens[pos]);
249ece8a530Spatrick   if (v.size() == 1)
250ece8a530Spatrick     return;
251ece8a530Spatrick   tokens.erase(tokens.begin() + pos);
252ece8a530Spatrick   tokens.insert(tokens.begin() + pos, v.begin(), v.end());
253ece8a530Spatrick }
254ece8a530Spatrick 
next()255ece8a530Spatrick StringRef ScriptLexer::next() {
256ece8a530Spatrick   maybeSplitExpr();
257ece8a530Spatrick 
258ece8a530Spatrick   if (errorCount())
259ece8a530Spatrick     return "";
260ece8a530Spatrick   if (atEOF()) {
261ece8a530Spatrick     setError("unexpected EOF");
262ece8a530Spatrick     return "";
263ece8a530Spatrick   }
264ece8a530Spatrick   return tokens[pos++];
265ece8a530Spatrick }
266ece8a530Spatrick 
peek()267ece8a530Spatrick StringRef ScriptLexer::peek() {
268ece8a530Spatrick   StringRef tok = next();
269ece8a530Spatrick   if (errorCount())
270ece8a530Spatrick     return "";
271ece8a530Spatrick   pos = pos - 1;
272ece8a530Spatrick   return tok;
273ece8a530Spatrick }
274ece8a530Spatrick 
peek2()275ece8a530Spatrick StringRef ScriptLexer::peek2() {
276ece8a530Spatrick   skip();
277ece8a530Spatrick   StringRef tok = next();
278ece8a530Spatrick   if (errorCount())
279ece8a530Spatrick     return "";
280ece8a530Spatrick   pos = pos - 2;
281ece8a530Spatrick   return tok;
282ece8a530Spatrick }
283ece8a530Spatrick 
consume(StringRef tok)284ece8a530Spatrick bool ScriptLexer::consume(StringRef tok) {
285ece8a530Spatrick   if (peek() == tok) {
286ece8a530Spatrick     skip();
287ece8a530Spatrick     return true;
288ece8a530Spatrick   }
289ece8a530Spatrick   return false;
290ece8a530Spatrick }
291ece8a530Spatrick 
292ece8a530Spatrick // Consumes Tok followed by ":". Space is allowed between Tok and ":".
consumeLabel(StringRef tok)293ece8a530Spatrick bool ScriptLexer::consumeLabel(StringRef tok) {
294ece8a530Spatrick   if (consume((tok + ":").str()))
295ece8a530Spatrick     return true;
296ece8a530Spatrick   if (tokens.size() >= pos + 2 && tokens[pos] == tok &&
297ece8a530Spatrick       tokens[pos + 1] == ":") {
298ece8a530Spatrick     pos += 2;
299ece8a530Spatrick     return true;
300ece8a530Spatrick   }
301ece8a530Spatrick   return false;
302ece8a530Spatrick }
303ece8a530Spatrick 
skip()304ece8a530Spatrick void ScriptLexer::skip() { (void)next(); }
305ece8a530Spatrick 
expect(StringRef expect)306ece8a530Spatrick void ScriptLexer::expect(StringRef expect) {
307ece8a530Spatrick   if (errorCount())
308ece8a530Spatrick     return;
309ece8a530Spatrick   StringRef tok = next();
310ece8a530Spatrick   if (tok != expect)
311ece8a530Spatrick     setError(expect + " expected, but got " + tok);
312ece8a530Spatrick }
313ece8a530Spatrick 
314ece8a530Spatrick // Returns true if S encloses T.
encloses(StringRef s,StringRef t)315ece8a530Spatrick static bool encloses(StringRef s, StringRef t) {
316ece8a530Spatrick   return s.bytes_begin() <= t.bytes_begin() && t.bytes_end() <= s.bytes_end();
317ece8a530Spatrick }
318ece8a530Spatrick 
getCurrentMB()319ece8a530Spatrick MemoryBufferRef ScriptLexer::getCurrentMB() {
320ece8a530Spatrick   // Find input buffer containing the current token.
321667950d7Spatrick   assert(!mbs.empty());
322667950d7Spatrick   if (pos == 0)
323667950d7Spatrick     return mbs.back();
324ece8a530Spatrick   for (MemoryBufferRef mb : mbs)
325ece8a530Spatrick     if (encloses(mb.getBuffer(), tokens[pos - 1]))
326ece8a530Spatrick       return mb;
327ece8a530Spatrick   llvm_unreachable("getCurrentMB: failed to find a token");
328ece8a530Spatrick }
329