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 // Our grammar of the linker script is LL(2), meaning that it needs at 24 // most two-token lookahead to parse. The only place we need two-token 25 // lookahead is labels in version scripts, where we need to parse "local :" 26 // as if "local:". 27 // 28 // Overall, this lexer works fine for most linker scripts. There might 29 // be room for improving compatibility, but that's probably not at the 30 // top of our todo list. 31 // 32 //===----------------------------------------------------------------------===// 33 34 #include "ScriptLexer.h" 35 #include "lld/Common/ErrorHandler.h" 36 #include "llvm/ADT/Twine.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include <algorithm> 39 40 using namespace llvm; 41 using namespace lld; 42 using namespace lld::elf; 43 44 // Returns a whole line containing the current token. 45 StringRef ScriptLexer::getLine() { 46 StringRef s = getCurrentMB().getBuffer(); 47 StringRef tok = tokens[pos - 1]; 48 49 size_t pos = s.rfind('\n', tok.data() - s.data()); 50 if (pos != StringRef::npos) 51 s = s.substr(pos + 1); 52 return s.substr(0, s.find_first_of("\r\n")); 53 } 54 55 // Returns 1-based line number of the current token. 56 size_t ScriptLexer::getLineNumber() { 57 if (pos == 0) 58 return 1; 59 StringRef s = getCurrentMB().getBuffer(); 60 StringRef tok = tokens[pos - 1]; 61 const size_t tokOffset = tok.data() - s.data(); 62 63 // For the first token, or when going backwards, start from the beginning of 64 // the buffer. If this token is after the previous token, start from the 65 // previous token. 66 size_t line = 1; 67 size_t start = 0; 68 if (lastLineNumberOffset > 0 && tokOffset >= lastLineNumberOffset) { 69 start = lastLineNumberOffset; 70 line = lastLineNumber; 71 } 72 73 line += s.substr(start, tokOffset - start).count('\n'); 74 75 // Store the line number of this token for reuse. 76 lastLineNumberOffset = tokOffset; 77 lastLineNumber = line; 78 79 return line; 80 } 81 82 // Returns 0-based column number of the current token. 83 size_t ScriptLexer::getColumnNumber() { 84 StringRef tok = tokens[pos - 1]; 85 return tok.data() - getLine().data(); 86 } 87 88 std::string ScriptLexer::getCurrentLocation() { 89 std::string filename = std::string(getCurrentMB().getBufferIdentifier()); 90 return (filename + ":" + Twine(getLineNumber())).str(); 91 } 92 93 ScriptLexer::ScriptLexer(MemoryBufferRef mb) { tokenize(mb); } 94 95 // We don't want to record cascading errors. Keep only the first one. 96 void ScriptLexer::setError(const Twine &msg) { 97 if (errorCount()) 98 return; 99 100 std::string s = (getCurrentLocation() + ": " + msg).str(); 101 if (pos) 102 s += "\n>>> " + getLine().str() + "\n>>> " + 103 std::string(getColumnNumber(), ' ') + "^"; 104 error(s); 105 } 106 107 // Split S into linker script tokens. 108 void ScriptLexer::tokenize(MemoryBufferRef mb) { 109 std::vector<StringRef> vec; 110 mbs.push_back(mb); 111 StringRef s = mb.getBuffer(); 112 StringRef begin = s; 113 114 for (;;) { 115 s = skipSpace(s); 116 if (s.empty()) 117 break; 118 119 // Quoted token. Note that double-quote characters are parts of a token 120 // because, in a glob match context, only unquoted tokens are interpreted 121 // as glob patterns. Double-quoted tokens are literal patterns in that 122 // context. 123 if (s.startswith("\"")) { 124 size_t e = s.find("\"", 1); 125 if (e == StringRef::npos) { 126 StringRef filename = mb.getBufferIdentifier(); 127 size_t lineno = begin.substr(0, s.data() - begin.data()).count('\n'); 128 error(filename + ":" + Twine(lineno + 1) + ": unclosed quote"); 129 return; 130 } 131 132 vec.push_back(s.take_front(e + 1)); 133 s = s.substr(e + 1); 134 continue; 135 } 136 137 // ">foo" is parsed to ">" and "foo", but ">>" is parsed to ">>". 138 // "|", "||", "&" and "&&" are different operators. 139 if (s.startswith("<<") || s.startswith("<=") || s.startswith(">>") || 140 s.startswith(">=") || s.startswith("||") || s.startswith("&&")) { 141 vec.push_back(s.substr(0, 2)); 142 s = s.substr(2); 143 continue; 144 } 145 146 // Unquoted token. This is more relaxed than tokens in C-like language, 147 // so that you can write "file-name.cpp" as one bare token, for example. 148 size_t pos = s.find_first_not_of( 149 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 150 "0123456789_.$/\\~=+[]*?-!^:"); 151 152 // A character that cannot start a word (which is usually a 153 // punctuation) forms a single character token. 154 if (pos == 0) 155 pos = 1; 156 vec.push_back(s.substr(0, pos)); 157 s = s.substr(pos); 158 } 159 160 tokens.insert(tokens.begin() + pos, vec.begin(), vec.end()); 161 } 162 163 // Skip leading whitespace characters or comments. 164 StringRef ScriptLexer::skipSpace(StringRef s) { 165 for (;;) { 166 if (s.startswith("/*")) { 167 size_t e = s.find("*/", 2); 168 if (e == StringRef::npos) { 169 setError("unclosed comment in a linker script"); 170 return ""; 171 } 172 s = s.substr(e + 2); 173 continue; 174 } 175 if (s.startswith("#")) { 176 size_t e = s.find('\n', 1); 177 if (e == StringRef::npos) 178 e = s.size() - 1; 179 s = s.substr(e + 1); 180 continue; 181 } 182 size_t size = s.size(); 183 s = s.ltrim(); 184 if (s.size() == size) 185 return s; 186 } 187 } 188 189 // An erroneous token is handled as if it were the last token before EOF. 190 bool ScriptLexer::atEOF() { return errorCount() || tokens.size() == pos; } 191 192 // Split a given string as an expression. 193 // This function returns "3", "*" and "5" for "3*5" for example. 194 static std::vector<StringRef> tokenizeExpr(StringRef s) { 195 StringRef ops = "+-*/:!~=<>"; // List of operators 196 197 // Quoted strings are literal strings, so we don't want to split it. 198 if (s.startswith("\"")) 199 return {s}; 200 201 // Split S with operators as separators. 202 std::vector<StringRef> ret; 203 while (!s.empty()) { 204 size_t e = s.find_first_of(ops); 205 206 // No need to split if there is no operator. 207 if (e == StringRef::npos) { 208 ret.push_back(s); 209 break; 210 } 211 212 // Get a token before the operator. 213 if (e != 0) 214 ret.push_back(s.substr(0, e)); 215 216 // Get the operator as a token. 217 // Keep !=, ==, >=, <=, << and >> operators as a single tokens. 218 if (s.substr(e).startswith("!=") || s.substr(e).startswith("==") || 219 s.substr(e).startswith(">=") || s.substr(e).startswith("<=") || 220 s.substr(e).startswith("<<") || s.substr(e).startswith(">>")) { 221 ret.push_back(s.substr(e, 2)); 222 s = s.substr(e + 2); 223 } else { 224 ret.push_back(s.substr(e, 1)); 225 s = s.substr(e + 1); 226 } 227 } 228 return ret; 229 } 230 231 // In contexts where expressions are expected, the lexer should apply 232 // different tokenization rules than the default one. By default, 233 // arithmetic operator characters are regular characters, but in the 234 // expression context, they should be independent tokens. 235 // 236 // For example, "foo*3" should be tokenized to "foo", "*" and "3" only 237 // in the expression context. 238 // 239 // This function may split the current token into multiple tokens. 240 void ScriptLexer::maybeSplitExpr() { 241 if (!inExpr || errorCount() || atEOF()) 242 return; 243 244 std::vector<StringRef> v = tokenizeExpr(tokens[pos]); 245 if (v.size() == 1) 246 return; 247 tokens.erase(tokens.begin() + pos); 248 tokens.insert(tokens.begin() + pos, v.begin(), v.end()); 249 } 250 251 StringRef ScriptLexer::next() { 252 maybeSplitExpr(); 253 254 if (errorCount()) 255 return ""; 256 if (atEOF()) { 257 setError("unexpected EOF"); 258 return ""; 259 } 260 return tokens[pos++]; 261 } 262 263 StringRef ScriptLexer::peek() { 264 StringRef tok = next(); 265 if (errorCount()) 266 return ""; 267 pos = pos - 1; 268 return tok; 269 } 270 271 StringRef ScriptLexer::peek2() { 272 skip(); 273 StringRef tok = next(); 274 if (errorCount()) 275 return ""; 276 pos = pos - 2; 277 return tok; 278 } 279 280 bool ScriptLexer::consume(StringRef tok) { 281 if (peek() == tok) { 282 skip(); 283 return true; 284 } 285 return false; 286 } 287 288 // Consumes Tok followed by ":". Space is allowed between Tok and ":". 289 bool ScriptLexer::consumeLabel(StringRef tok) { 290 if (consume((tok + ":").str())) 291 return true; 292 if (tokens.size() >= pos + 2 && tokens[pos] == tok && 293 tokens[pos + 1] == ":") { 294 pos += 2; 295 return true; 296 } 297 return false; 298 } 299 300 void ScriptLexer::skip() { (void)next(); } 301 302 void ScriptLexer::expect(StringRef expect) { 303 if (errorCount()) 304 return; 305 StringRef tok = next(); 306 if (tok != expect) 307 setError(expect + " expected, but got " + tok); 308 } 309 310 // Returns true if S encloses T. 311 static bool encloses(StringRef s, StringRef t) { 312 return s.bytes_begin() <= t.bytes_begin() && t.bytes_end() <= s.bytes_end(); 313 } 314 315 MemoryBufferRef ScriptLexer::getCurrentMB() { 316 // Find input buffer containing the current token. 317 assert(!mbs.empty()); 318 if (pos == 0) 319 return mbs.back(); 320 for (MemoryBufferRef mb : mbs) 321 if (encloses(mb.getBuffer(), tokens[pos - 1])) 322 return mb; 323 llvm_unreachable("getCurrentMB: failed to find a token"); 324 } 325