1//===- ScriptLexer.cpp ----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a lexer for the linker script.
10//
11// The linker script's grammar is not complex but ambiguous due to the
12// lack of the formal specification of the language. What we are trying to
13// do in this and other files in LLD is to make a "reasonable" linker
14// script processor.
15//
16// Among simplicity, compatibility and efficiency, we put the most
17// emphasis on simplicity when we wrote this lexer. Compatibility with the
18// GNU linkers is important, but we did not try to clone every tiny corner
19// case of their lexers, as even ld.bfd and ld.gold are subtly different
20// in various corner cases. We do not care much about efficiency because
21// the time spent in parsing linker scripts is usually negligible.
22//
23// Overall, this lexer works fine for most linker scripts. There might
24// be room for improving compatibility, but that's probably not at the
25// top of our todo list.
26//
27//===----------------------------------------------------------------------===//
28
29#include "ScriptLexer.h"
30#include "Config.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/Path.h"
35
36using namespace llvm;
37using namespace lld;
38using namespace lld::elf;
39
40ScriptLexer::Buffer::Buffer(Ctx &ctx, MemoryBufferRef mb)
41 : s(mb.getBuffer()), filename(mb.getBufferIdentifier()),
42 begin(mb.getBufferStart()) {
43 if (ctx.arg.sysroot == "")
44 return;
45 StringRef path = filename;
46 for (; !path.empty(); path = sys::path::parent_path(path)) {
47 if (!sys::fs::equivalent(A: ctx.arg.sysroot, B: path))
48 continue;
49 isUnderSysroot = true;
50 return;
51 }
52}
53
54ScriptLexer::ScriptLexer(Ctx &ctx, MemoryBufferRef mb)
55 : ctx(ctx), curBuf(ctx, mb), mbs(1, mb) {
56 activeFilenames.insert(V: mb.getBufferIdentifier());
57}
58
59// Returns a whole line containing the current token.
60StringRef ScriptLexer::getLine() {
61 StringRef s = getCurrentMB().getBuffer();
62
63 size_t pos = s.rfind(C: '\n', From: prevTok.data() - s.data());
64 if (pos != StringRef::npos)
65 s = s.substr(Start: pos + 1);
66 return s.substr(Start: 0, N: s.find_first_of(Chars: "\r\n"));
67}
68
69// Returns 0-based column number of the current token.
70size_t ScriptLexer::getColumnNumber() {
71 return prevTok.data() - getLine().data();
72}
73
74std::string ScriptLexer::getCurrentLocation() {
75 std::string filename = std::string(getCurrentMB().getBufferIdentifier());
76 return (filename + ":" + Twine(prevTokLine)).str();
77}
78
79// We don't want to record cascading errors. Keep only the first one.
80void ScriptLexer::setError(const Twine &msg) {
81 if (errCount(ctx))
82 return;
83
84 std::string s = (getCurrentLocation() + ": " + msg).str();
85 if (prevTok.size())
86 s += "\n>>> " + getLine().str() + "\n>>> " +
87 std::string(getColumnNumber(), ' ') + "^";
88 ErrAlways(ctx) << s;
89}
90
91void ScriptLexer::lex() {
92 for (;;) {
93 StringRef &s = curBuf.s;
94 s = skipSpace(s);
95 if (s.empty()) {
96 // If this buffer is from an INCLUDE command, switch to the "return
97 // value"; otherwise, mark EOF.
98 if (buffers.empty()) {
99 eof = true;
100 return;
101 }
102 activeFilenames.erase(V: curBuf.filename);
103 curBuf = buffers.pop_back_val();
104 continue;
105 }
106 curTokState = lexState;
107
108 // Quoted token. Note that double-quote characters are parts of a token
109 // because, in a glob match context, only unquoted tokens are interpreted
110 // as glob patterns. Double-quoted tokens are literal patterns in that
111 // context.
112 if (s.starts_with(Prefix: "\"")) {
113 size_t e = s.find(Str: "\"", From: 1);
114 if (e == StringRef::npos) {
115 size_t lineno =
116 StringRef(curBuf.begin, s.data() - curBuf.begin).count(C: '\n');
117 ErrAlways(ctx) << curBuf.filename << ":" << (lineno + 1)
118 << ": unclosed quote";
119 return;
120 }
121
122 curTok = s.take_front(N: e + 1);
123 s = s.substr(Start: e + 1);
124 return;
125 }
126
127 // In Script and Expr states, recognize compound assignment operators.
128 auto recognizeAssign = [&]() -> bool {
129 if (s.starts_with(Prefix: "<<=") || s.starts_with(Prefix: ">>=")) {
130 curTok = s.substr(Start: 0, N: 3);
131 s = s.substr(Start: 3);
132 return true;
133 }
134 if (s.size() > 1 && (s[1] == '=' && strchr(s: "+-*/!&^|", c: s[0]))) {
135 curTok = s.substr(Start: 0, N: 2);
136 s = s.substr(Start: 2);
137 return true;
138 }
139 return false;
140 };
141
142 // Unquoted token. The non-expression token is more relaxed than tokens in
143 // C-like languages, so that you can write "file-name.cpp" as one bare
144 // token.
145 size_t pos;
146 constexpr StringRef scriptAndVersionChars =
147 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
148 "0123456789_.$/\\~=+[]*?-!^:";
149 constexpr StringRef exprChars =
150 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
151 "0123456789_.$";
152 switch (lexState) {
153 case State::Script:
154 if (recognizeAssign())
155 return;
156 pos = s.find_first_not_of(Chars: scriptAndVersionChars);
157 break;
158 case State::Expr:
159 if (recognizeAssign())
160 return;
161 pos = s.find_first_not_of(Chars: exprChars);
162 if (pos == 0 && s.size() >= 2 &&
163 ((s[0] == s[1] && strchr(s: "<>&|", c: s[0])) ||
164 is_contained(Set: {"==", "!=", "<=", ">=", "<<", ">>"}, Element: s.substr(Start: 0, N: 2))))
165 pos = 2;
166 break;
167 case State::VersionNode:
168 // Treat `:` as a token boundary unless it's part of a scope operator `::`
169 // (for extern "C++"). This behavior resembles GNU ld and allows proper
170 // tokenization of patterns like `local:*`.
171 pos = 0;
172 for (; pos != s.size(); ++pos) {
173 if (s[pos] == ':') {
174 if (pos + 1 != s.size() && s[pos + 1] == ':') {
175 ++pos;
176 continue;
177 }
178 } else if (scriptAndVersionChars.contains(C: s[pos]))
179 continue;
180 break;
181 }
182 break;
183 }
184
185 if (pos == 0)
186 pos = 1;
187 curTok = s.substr(Start: 0, N: pos);
188 s = s.substr(Start: pos);
189 break;
190 }
191}
192
193// Skip leading whitespace characters or comments.
194StringRef ScriptLexer::skipSpace(StringRef s) {
195 for (;;) {
196 if (s.starts_with(Prefix: "/*")) {
197 size_t e = s.find(Str: "*/", From: 2);
198 if (e == StringRef::npos) {
199 setError("unclosed comment in a linker script");
200 return "";
201 }
202 curBuf.lineNumber += s.substr(Start: 0, N: e).count(C: '\n');
203 s = s.substr(Start: e + 2);
204 continue;
205 }
206 if (s.starts_with(Prefix: "#")) {
207 size_t e = s.find(C: '\n', From: 1);
208 if (e == StringRef::npos)
209 e = s.size() - 1;
210 else
211 ++curBuf.lineNumber;
212 s = s.substr(Start: e + 1);
213 continue;
214 }
215 StringRef saved = s;
216 s = s.ltrim();
217 auto len = saved.size() - s.size();
218 if (len == 0)
219 return s;
220 curBuf.lineNumber += saved.substr(Start: 0, N: len).count(C: '\n');
221 }
222}
223
224// Used to determine whether to stop parsing. Treat errors like EOF.
225bool ScriptLexer::atEOF() { return eof || errCount(ctx); }
226
227StringRef ScriptLexer::next() {
228 prevTok = peek();
229 // `prevTokLine` is not updated for EOF so that the line number in `setError`
230 // will be more useful.
231 if (prevTok.size())
232 prevTokLine = curBuf.lineNumber;
233 return std::exchange(obj&: curTok, new_val: StringRef(curBuf.s.data(), 0));
234}
235
236StringRef ScriptLexer::peek() {
237 // curTok is invalid if curTokState and lexState mismatch.
238 if (curTok.size() && curTokState != lexState) {
239 curBuf.s = StringRef(curTok.data(), curBuf.s.end() - curTok.data());
240 curTok = {};
241 }
242 if (curTok.empty())
243 lex();
244 return curTok;
245}
246
247bool ScriptLexer::consume(StringRef tok) {
248 if (peek() != tok)
249 return false;
250 next();
251 return true;
252}
253
254void ScriptLexer::skip() { (void)next(); }
255
256void ScriptLexer::expect(StringRef expect) {
257 if (errCount(ctx))
258 return;
259 StringRef tok = next();
260 if (tok != expect) {
261 if (atEOF())
262 setError("unexpected EOF");
263 else
264 setError(expect + " expected, but got " + tok);
265 }
266}
267
268ScriptLexer::Token ScriptLexer::till(StringRef tok) {
269 StringRef str = next();
270 if (str == tok)
271 return {};
272 if (!atEOF())
273 return {.str: str};
274 prevTok = {};
275 setError("unexpected EOF");
276 return {};
277}
278
279// Returns true if S encloses T.
280static bool encloses(StringRef s, StringRef t) {
281 return s.bytes_begin() <= t.bytes_begin() && t.bytes_end() <= s.bytes_end();
282}
283
284MemoryBufferRef ScriptLexer::getCurrentMB() {
285 // Find input buffer containing the current token.
286 assert(!mbs.empty());
287 for (MemoryBufferRef mb : mbs)
288 if (encloses(s: mb.getBuffer(), t: curBuf.s))
289 return mb;
290 llvm_unreachable("getCurrentMB: failed to find a token");
291}
292