1 //===- ScriptParser.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 contains a recursive-descendent parser for linker scripts. 10 // Parsed results are stored to Config and Script global objects. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ScriptParser.h" 15 #include "Config.h" 16 #include "Driver.h" 17 #include "InputFiles.h" 18 #include "LinkerScript.h" 19 #include "OutputSections.h" 20 #include "ScriptLexer.h" 21 #include "SymbolTable.h" 22 #include "Symbols.h" 23 #include "Target.h" 24 #include "lld/Common/CommonLinkerContext.h" 25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/StringSet.h" 28 #include "llvm/ADT/StringSwitch.h" 29 #include "llvm/BinaryFormat/ELF.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/FileSystem.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/Path.h" 35 #include "llvm/Support/SaveAndRestore.h" 36 #include "llvm/Support/TimeProfiler.h" 37 #include <cassert> 38 #include <limits> 39 #include <vector> 40 41 using namespace llvm; 42 using namespace llvm::ELF; 43 using namespace llvm::support::endian; 44 using namespace lld; 45 using namespace lld::elf; 46 47 namespace { 48 class ScriptParser final : ScriptLexer { 49 public: 50 ScriptParser(MemoryBufferRef mb) : ScriptLexer(mb) { 51 // Initialize IsUnderSysroot 52 if (config->sysroot == "") 53 return; 54 StringRef path = mb.getBufferIdentifier(); 55 for (; !path.empty(); path = sys::path::parent_path(path)) { 56 if (!sys::fs::equivalent(config->sysroot, path)) 57 continue; 58 isUnderSysroot = true; 59 return; 60 } 61 } 62 63 void readLinkerScript(); 64 void readVersionScript(); 65 void readDynamicList(); 66 void readDefsym(StringRef name); 67 68 private: 69 void addFile(StringRef path); 70 71 void readAsNeeded(); 72 void readEntry(); 73 void readExtern(); 74 void readGroup(); 75 void readInclude(); 76 void readInput(); 77 void readMemory(); 78 void readOutput(); 79 void readOutputArch(); 80 void readOutputFormat(); 81 void readOverwriteSections(); 82 void readPhdrs(); 83 void readRegionAlias(); 84 void readSearchDir(); 85 void readSections(); 86 void readTarget(); 87 void readVersion(); 88 void readVersionScriptCommand(); 89 90 SymbolAssignment *readSymbolAssignment(StringRef name); 91 ByteCommand *readByteCommand(StringRef tok); 92 std::array<uint8_t, 4> readFill(); 93 bool readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2); 94 void readSectionAddressType(OutputSection *cmd); 95 OutputDesc *readOverlaySectionDescription(); 96 OutputDesc *readOutputSectionDescription(StringRef outSec); 97 SmallVector<SectionCommand *, 0> readOverlay(); 98 SmallVector<StringRef, 0> readOutputSectionPhdrs(); 99 std::pair<uint64_t, uint64_t> readInputSectionFlags(); 100 InputSectionDescription *readInputSectionDescription(StringRef tok); 101 StringMatcher readFilePatterns(); 102 SmallVector<SectionPattern, 0> readInputSectionsList(); 103 InputSectionDescription *readInputSectionRules(StringRef filePattern, 104 uint64_t withFlags, 105 uint64_t withoutFlags); 106 unsigned readPhdrType(); 107 SortSectionPolicy peekSortKind(); 108 SortSectionPolicy readSortKind(); 109 SymbolAssignment *readProvideHidden(bool provide, bool hidden); 110 SymbolAssignment *readAssignment(StringRef tok); 111 void readSort(); 112 Expr readAssert(); 113 Expr readConstant(); 114 Expr getPageSize(); 115 116 Expr readMemoryAssignment(StringRef, StringRef, StringRef); 117 void readMemoryAttributes(uint32_t &flags, uint32_t &invFlags, 118 uint32_t &negFlags, uint32_t &negInvFlags); 119 120 Expr combine(StringRef op, Expr l, Expr r); 121 Expr readExpr(); 122 Expr readExpr1(Expr lhs, int minPrec); 123 StringRef readParenLiteral(); 124 Expr readPrimary(); 125 Expr readTernary(Expr cond); 126 Expr readParenExpr(); 127 128 // For parsing version script. 129 SmallVector<SymbolVersion, 0> readVersionExtern(); 130 void readAnonymousDeclaration(); 131 void readVersionDeclaration(StringRef verStr); 132 133 std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>> 134 readSymbols(); 135 136 // True if a script being read is in the --sysroot directory. 137 bool isUnderSysroot = false; 138 139 bool seenDataAlign = false; 140 bool seenRelroEnd = false; 141 142 // A set to detect an INCLUDE() cycle. 143 StringSet<> seen; 144 }; 145 } // namespace 146 147 static StringRef unquote(StringRef s) { 148 if (s.startswith("\"")) 149 return s.substr(1, s.size() - 2); 150 return s; 151 } 152 153 // Some operations only support one non absolute value. Move the 154 // absolute one to the right hand side for convenience. 155 static void moveAbsRight(ExprValue &a, ExprValue &b) { 156 if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute())) 157 std::swap(a, b); 158 if (!b.isAbsolute()) 159 error(a.loc + ": at least one side of the expression must be absolute"); 160 } 161 162 static ExprValue add(ExprValue a, ExprValue b) { 163 moveAbsRight(a, b); 164 return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc}; 165 } 166 167 static ExprValue sub(ExprValue a, ExprValue b) { 168 // The distance between two symbols in sections is absolute. 169 if (!a.isAbsolute() && !b.isAbsolute()) 170 return a.getValue() - b.getValue(); 171 return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc}; 172 } 173 174 static ExprValue bitAnd(ExprValue a, ExprValue b) { 175 moveAbsRight(a, b); 176 return {a.sec, a.forceAbsolute, 177 (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc}; 178 } 179 180 static ExprValue bitOr(ExprValue a, ExprValue b) { 181 moveAbsRight(a, b); 182 return {a.sec, a.forceAbsolute, 183 (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc}; 184 } 185 186 void ScriptParser::readDynamicList() { 187 expect("{"); 188 SmallVector<SymbolVersion, 0> locals; 189 SmallVector<SymbolVersion, 0> globals; 190 std::tie(locals, globals) = readSymbols(); 191 expect(";"); 192 193 if (!atEOF()) { 194 setError("EOF expected, but got " + next()); 195 return; 196 } 197 if (!locals.empty()) { 198 setError("\"local:\" scope not supported in --dynamic-list"); 199 return; 200 } 201 202 for (SymbolVersion v : globals) 203 config->dynamicList.push_back(v); 204 } 205 206 void ScriptParser::readVersionScript() { 207 readVersionScriptCommand(); 208 if (!atEOF()) 209 setError("EOF expected, but got " + next()); 210 } 211 212 void ScriptParser::readVersionScriptCommand() { 213 if (consume("{")) { 214 readAnonymousDeclaration(); 215 return; 216 } 217 218 while (!atEOF() && !errorCount() && peek() != "}") { 219 StringRef verStr = next(); 220 if (verStr == "{") { 221 setError("anonymous version definition is used in " 222 "combination with other version definitions"); 223 return; 224 } 225 expect("{"); 226 readVersionDeclaration(verStr); 227 } 228 } 229 230 void ScriptParser::readVersion() { 231 expect("{"); 232 readVersionScriptCommand(); 233 expect("}"); 234 } 235 236 void ScriptParser::readLinkerScript() { 237 while (!atEOF()) { 238 StringRef tok = next(); 239 if (tok == ";") 240 continue; 241 242 if (tok == "ENTRY") { 243 readEntry(); 244 } else if (tok == "EXTERN") { 245 readExtern(); 246 } else if (tok == "GROUP") { 247 readGroup(); 248 } else if (tok == "INCLUDE") { 249 readInclude(); 250 } else if (tok == "INPUT") { 251 readInput(); 252 } else if (tok == "MEMORY") { 253 readMemory(); 254 } else if (tok == "OUTPUT") { 255 readOutput(); 256 } else if (tok == "OUTPUT_ARCH") { 257 readOutputArch(); 258 } else if (tok == "OUTPUT_FORMAT") { 259 readOutputFormat(); 260 } else if (tok == "OVERWRITE_SECTIONS") { 261 readOverwriteSections(); 262 } else if (tok == "PHDRS") { 263 readPhdrs(); 264 } else if (tok == "REGION_ALIAS") { 265 readRegionAlias(); 266 } else if (tok == "SEARCH_DIR") { 267 readSearchDir(); 268 } else if (tok == "SECTIONS") { 269 readSections(); 270 } else if (tok == "TARGET") { 271 readTarget(); 272 } else if (tok == "VERSION") { 273 readVersion(); 274 } else if (SymbolAssignment *cmd = readAssignment(tok)) { 275 script->sectionCommands.push_back(cmd); 276 } else { 277 setError("unknown directive: " + tok); 278 } 279 } 280 } 281 282 void ScriptParser::readDefsym(StringRef name) { 283 if (errorCount()) 284 return; 285 Expr e = readExpr(); 286 if (!atEOF()) 287 setError("EOF expected, but got " + next()); 288 SymbolAssignment *cmd = make<SymbolAssignment>(name, e, getCurrentLocation()); 289 script->sectionCommands.push_back(cmd); 290 } 291 292 void ScriptParser::addFile(StringRef s) { 293 if (isUnderSysroot && s.startswith("/")) { 294 SmallString<128> pathData; 295 StringRef path = (config->sysroot + s).toStringRef(pathData); 296 if (sys::fs::exists(path)) 297 driver->addFile(saver().save(path), /*withLOption=*/false); 298 else 299 setError("cannot find " + s + " inside " + config->sysroot); 300 return; 301 } 302 303 if (s.startswith("/")) { 304 // Case 1: s is an absolute path. Just open it. 305 driver->addFile(s, /*withLOption=*/false); 306 } else if (s.startswith("=")) { 307 // Case 2: relative to the sysroot. 308 if (config->sysroot.empty()) 309 driver->addFile(s.substr(1), /*withLOption=*/false); 310 else 311 driver->addFile(saver().save(config->sysroot + "/" + s.substr(1)), 312 /*withLOption=*/false); 313 } else if (s.startswith("-l")) { 314 // Case 3: search in the list of library paths. 315 driver->addLibrary(s.substr(2)); 316 } else { 317 // Case 4: s is a relative path. Search in the directory of the script file. 318 std::string filename = std::string(getCurrentMB().getBufferIdentifier()); 319 StringRef directory = sys::path::parent_path(filename); 320 if (!directory.empty()) { 321 SmallString<0> path(directory); 322 sys::path::append(path, s); 323 if (sys::fs::exists(path)) { 324 driver->addFile(path, /*withLOption=*/false); 325 return; 326 } 327 } 328 // Then search in the current working directory. 329 if (sys::fs::exists(s)) { 330 driver->addFile(s, /*withLOption=*/false); 331 } else { 332 // Finally, search in the list of library paths. 333 if (Optional<std::string> path = findFromSearchPaths(s)) 334 driver->addFile(saver().save(*path), /*withLOption=*/true); 335 else 336 setError("unable to find " + s); 337 } 338 } 339 } 340 341 void ScriptParser::readAsNeeded() { 342 expect("("); 343 bool orig = config->asNeeded; 344 config->asNeeded = true; 345 while (!errorCount() && !consume(")")) 346 addFile(unquote(next())); 347 config->asNeeded = orig; 348 } 349 350 void ScriptParser::readEntry() { 351 // -e <symbol> takes predecence over ENTRY(<symbol>). 352 expect("("); 353 StringRef tok = next(); 354 if (config->entry.empty()) 355 config->entry = unquote(tok); 356 expect(")"); 357 } 358 359 void ScriptParser::readExtern() { 360 expect("("); 361 while (!errorCount() && !consume(")")) 362 config->undefined.push_back(unquote(next())); 363 } 364 365 void ScriptParser::readGroup() { 366 bool orig = InputFile::isInGroup; 367 InputFile::isInGroup = true; 368 readInput(); 369 InputFile::isInGroup = orig; 370 if (!orig) 371 ++InputFile::nextGroupId; 372 } 373 374 void ScriptParser::readInclude() { 375 StringRef tok = unquote(next()); 376 377 if (!seen.insert(tok).second) { 378 setError("there is a cycle in linker script INCLUDEs"); 379 return; 380 } 381 382 if (Optional<std::string> path = searchScript(tok)) { 383 if (Optional<MemoryBufferRef> mb = readFile(*path)) 384 tokenize(*mb); 385 return; 386 } 387 setError("cannot find linker script " + tok); 388 } 389 390 void ScriptParser::readInput() { 391 expect("("); 392 while (!errorCount() && !consume(")")) { 393 if (consume("AS_NEEDED")) 394 readAsNeeded(); 395 else 396 addFile(unquote(next())); 397 } 398 } 399 400 void ScriptParser::readOutput() { 401 // -o <file> takes predecence over OUTPUT(<file>). 402 expect("("); 403 StringRef tok = next(); 404 if (config->outputFile.empty()) 405 config->outputFile = unquote(tok); 406 expect(")"); 407 } 408 409 void ScriptParser::readOutputArch() { 410 // OUTPUT_ARCH is ignored for now. 411 expect("("); 412 while (!errorCount() && !consume(")")) 413 skip(); 414 } 415 416 static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) { 417 return StringSwitch<std::pair<ELFKind, uint16_t>>(s) 418 .Case("elf32-i386", {ELF32LEKind, EM_386}) 419 .Case("elf32-avr", {ELF32LEKind, EM_AVR}) 420 .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU}) 421 .Case("elf32-littlearm", {ELF32LEKind, EM_ARM}) 422 .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64}) 423 .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64}) 424 .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64}) 425 .Case("elf64-bigaarch64", {ELF64BEKind, EM_AARCH64}) 426 .Case("elf32-powerpc", {ELF32BEKind, EM_PPC}) 427 .Case("elf32-powerpcle", {ELF32LEKind, EM_PPC}) 428 .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64}) 429 .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64}) 430 .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64}) 431 .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS}) 432 .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS}) 433 .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS}) 434 .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS}) 435 .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS}) 436 .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS}) 437 .Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV}) 438 .Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV}) 439 .Case("elf64-sparc", {ELF64BEKind, EM_SPARCV9}) 440 .Case("elf32-msp430", {ELF32LEKind, EM_MSP430}) 441 .Default({ELFNoneKind, EM_NONE}); 442 } 443 444 // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose 445 // big if -EB is specified, little if -EL is specified, or default if neither is 446 // specified. 447 void ScriptParser::readOutputFormat() { 448 expect("("); 449 450 StringRef s; 451 config->bfdname = unquote(next()); 452 if (!consume(")")) { 453 expect(","); 454 s = unquote(next()); 455 if (config->optEB) 456 config->bfdname = s; 457 expect(","); 458 s = unquote(next()); 459 if (config->optEL) 460 config->bfdname = s; 461 consume(")"); 462 } 463 s = config->bfdname; 464 if (s.consume_back("-freebsd")) 465 config->osabi = ELFOSABI_FREEBSD; 466 467 std::tie(config->ekind, config->emachine) = parseBfdName(s); 468 if (config->emachine == EM_NONE) 469 setError("unknown output format name: " + config->bfdname); 470 if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips") 471 config->mipsN32Abi = true; 472 if (config->emachine == EM_MSP430) 473 config->osabi = ELFOSABI_STANDALONE; 474 } 475 476 void ScriptParser::readPhdrs() { 477 expect("{"); 478 479 while (!errorCount() && !consume("}")) { 480 PhdrsCommand cmd; 481 cmd.name = next(); 482 cmd.type = readPhdrType(); 483 484 while (!errorCount() && !consume(";")) { 485 if (consume("FILEHDR")) 486 cmd.hasFilehdr = true; 487 else if (consume("PHDRS")) 488 cmd.hasPhdrs = true; 489 else if (consume("AT")) 490 cmd.lmaExpr = readParenExpr(); 491 else if (consume("FLAGS")) 492 cmd.flags = readParenExpr()().getValue(); 493 else 494 setError("unexpected header attribute: " + next()); 495 } 496 497 script->phdrsCommands.push_back(cmd); 498 } 499 } 500 501 void ScriptParser::readRegionAlias() { 502 expect("("); 503 StringRef alias = unquote(next()); 504 expect(","); 505 StringRef name = next(); 506 expect(")"); 507 508 if (script->memoryRegions.count(alias)) 509 setError("redefinition of memory region '" + alias + "'"); 510 if (!script->memoryRegions.count(name)) 511 setError("memory region '" + name + "' is not defined"); 512 script->memoryRegions.insert({alias, script->memoryRegions[name]}); 513 } 514 515 void ScriptParser::readSearchDir() { 516 expect("("); 517 StringRef tok = next(); 518 if (!config->nostdlib) 519 config->searchPaths.push_back(unquote(tok)); 520 expect(")"); 521 } 522 523 // This reads an overlay description. Overlays are used to describe output 524 // sections that use the same virtual memory range and normally would trigger 525 // linker's sections sanity check failures. 526 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description 527 SmallVector<SectionCommand *, 0> ScriptParser::readOverlay() { 528 // VA and LMA expressions are optional, though for simplicity of 529 // implementation we assume they are not. That is what OVERLAY was designed 530 // for first of all: to allow sections with overlapping VAs at different LMAs. 531 Expr addrExpr = readExpr(); 532 expect(":"); 533 expect("AT"); 534 Expr lmaExpr = readParenExpr(); 535 expect("{"); 536 537 SmallVector<SectionCommand *, 0> v; 538 OutputSection *prev = nullptr; 539 while (!errorCount() && !consume("}")) { 540 // VA is the same for all sections. The LMAs are consecutive in memory 541 // starting from the base load address specified. 542 OutputDesc *osd = readOverlaySectionDescription(); 543 osd->osec.addrExpr = addrExpr; 544 if (prev) 545 osd->osec.lmaExpr = [=] { return prev->getLMA() + prev->size; }; 546 else 547 osd->osec.lmaExpr = lmaExpr; 548 v.push_back(osd); 549 prev = &osd->osec; 550 } 551 552 // According to the specification, at the end of the overlay, the location 553 // counter should be equal to the overlay base address plus size of the 554 // largest section seen in the overlay. 555 // Here we want to create the Dot assignment command to achieve that. 556 Expr moveDot = [=] { 557 uint64_t max = 0; 558 for (SectionCommand *cmd : v) 559 max = std::max(max, cast<OutputDesc>(cmd)->osec.size); 560 return addrExpr().getValue() + max; 561 }; 562 v.push_back(make<SymbolAssignment>(".", moveDot, getCurrentLocation())); 563 return v; 564 } 565 566 void ScriptParser::readOverwriteSections() { 567 expect("{"); 568 while (!errorCount() && !consume("}")) 569 script->overwriteSections.push_back(readOutputSectionDescription(next())); 570 } 571 572 void ScriptParser::readSections() { 573 expect("{"); 574 SmallVector<SectionCommand *, 0> v; 575 while (!errorCount() && !consume("}")) { 576 StringRef tok = next(); 577 if (tok == "OVERLAY") { 578 for (SectionCommand *cmd : readOverlay()) 579 v.push_back(cmd); 580 continue; 581 } else if (tok == "INCLUDE") { 582 readInclude(); 583 continue; 584 } 585 586 if (SectionCommand *cmd = readAssignment(tok)) 587 v.push_back(cmd); 588 else 589 v.push_back(readOutputSectionDescription(tok)); 590 } 591 592 // If DATA_SEGMENT_RELRO_END is absent, for sections after DATA_SEGMENT_ALIGN, 593 // the relro fields should be cleared. 594 if (!seenRelroEnd) 595 for (SectionCommand *cmd : v) 596 if (auto *osd = dyn_cast<OutputDesc>(cmd)) 597 osd->osec.relro = false; 598 599 script->sectionCommands.insert(script->sectionCommands.end(), v.begin(), 600 v.end()); 601 602 if (atEOF() || !consume("INSERT")) { 603 script->hasSectionsCommand = true; 604 return; 605 } 606 607 bool isAfter = false; 608 if (consume("AFTER")) 609 isAfter = true; 610 else if (!consume("BEFORE")) 611 setError("expected AFTER/BEFORE, but got '" + next() + "'"); 612 StringRef where = next(); 613 SmallVector<StringRef, 0> names; 614 for (SectionCommand *cmd : v) 615 if (auto *os = dyn_cast<OutputDesc>(cmd)) 616 names.push_back(os->osec.name); 617 if (!names.empty()) 618 script->insertCommands.push_back({std::move(names), isAfter, where}); 619 } 620 621 void ScriptParser::readTarget() { 622 // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers, 623 // we accept only a limited set of BFD names (i.e. "elf" or "binary") 624 // for --format. We recognize only /^elf/ and "binary" in the linker 625 // script as well. 626 expect("("); 627 StringRef tok = unquote(next()); 628 expect(")"); 629 630 if (tok.startswith("elf")) 631 config->formatBinary = false; 632 else if (tok == "binary") 633 config->formatBinary = true; 634 else 635 setError("unknown target: " + tok); 636 } 637 638 static int precedence(StringRef op) { 639 return StringSwitch<int>(op) 640 .Cases("*", "/", "%", 10) 641 .Cases("+", "-", 9) 642 .Cases("<<", ">>", 8) 643 .Cases("<", "<=", ">", ">=", 7) 644 .Cases("==", "!=", 6) 645 .Case("&", 5) 646 .Case("|", 4) 647 .Case("&&", 3) 648 .Case("||", 2) 649 .Case("?", 1) 650 .Default(-1); 651 } 652 653 StringMatcher ScriptParser::readFilePatterns() { 654 StringMatcher Matcher; 655 656 while (!errorCount() && !consume(")")) 657 Matcher.addPattern(SingleStringMatcher(next())); 658 return Matcher; 659 } 660 661 SortSectionPolicy ScriptParser::peekSortKind() { 662 return StringSwitch<SortSectionPolicy>(peek()) 663 .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name) 664 .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment) 665 .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority) 666 .Case("SORT_NONE", SortSectionPolicy::None) 667 .Default(SortSectionPolicy::Default); 668 } 669 670 SortSectionPolicy ScriptParser::readSortKind() { 671 SortSectionPolicy ret = peekSortKind(); 672 if (ret != SortSectionPolicy::Default) 673 skip(); 674 return ret; 675 } 676 677 // Reads SECTIONS command contents in the following form: 678 // 679 // <contents> ::= <elem>* 680 // <elem> ::= <exclude>? <glob-pattern> 681 // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")" 682 // 683 // For example, 684 // 685 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz) 686 // 687 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o". 688 // The semantics of that is section .foo in any file, section .bar in 689 // any file but a.o, and section .baz in any file but b.o. 690 SmallVector<SectionPattern, 0> ScriptParser::readInputSectionsList() { 691 SmallVector<SectionPattern, 0> ret; 692 while (!errorCount() && peek() != ")") { 693 StringMatcher excludeFilePat; 694 if (consume("EXCLUDE_FILE")) { 695 expect("("); 696 excludeFilePat = readFilePatterns(); 697 } 698 699 StringMatcher SectionMatcher; 700 // Break if the next token is ), EXCLUDE_FILE, or SORT*. 701 while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE" && 702 peekSortKind() == SortSectionPolicy::Default) 703 SectionMatcher.addPattern(unquote(next())); 704 705 if (!SectionMatcher.empty()) 706 ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)}); 707 else if (excludeFilePat.empty()) 708 break; 709 else 710 setError("section pattern is expected"); 711 } 712 return ret; 713 } 714 715 // Reads contents of "SECTIONS" directive. That directive contains a 716 // list of glob patterns for input sections. The grammar is as follows. 717 // 718 // <patterns> ::= <section-list> 719 // | <sort> "(" <section-list> ")" 720 // | <sort> "(" <sort> "(" <section-list> ")" ")" 721 // 722 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT" 723 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE" 724 // 725 // <section-list> is parsed by readInputSectionsList(). 726 InputSectionDescription * 727 ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags, 728 uint64_t withoutFlags) { 729 auto *cmd = 730 make<InputSectionDescription>(filePattern, withFlags, withoutFlags); 731 expect("("); 732 733 while (!errorCount() && !consume(")")) { 734 SortSectionPolicy outer = readSortKind(); 735 SortSectionPolicy inner = SortSectionPolicy::Default; 736 SmallVector<SectionPattern, 0> v; 737 if (outer != SortSectionPolicy::Default) { 738 expect("("); 739 inner = readSortKind(); 740 if (inner != SortSectionPolicy::Default) { 741 expect("("); 742 v = readInputSectionsList(); 743 expect(")"); 744 } else { 745 v = readInputSectionsList(); 746 } 747 expect(")"); 748 } else { 749 v = readInputSectionsList(); 750 } 751 752 for (SectionPattern &pat : v) { 753 pat.sortInner = inner; 754 pat.sortOuter = outer; 755 } 756 757 std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns)); 758 } 759 return cmd; 760 } 761 762 InputSectionDescription * 763 ScriptParser::readInputSectionDescription(StringRef tok) { 764 // Input section wildcard can be surrounded by KEEP. 765 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep 766 uint64_t withFlags = 0; 767 uint64_t withoutFlags = 0; 768 if (tok == "KEEP") { 769 expect("("); 770 if (consume("INPUT_SECTION_FLAGS")) 771 std::tie(withFlags, withoutFlags) = readInputSectionFlags(); 772 InputSectionDescription *cmd = 773 readInputSectionRules(next(), withFlags, withoutFlags); 774 expect(")"); 775 script->keptSections.push_back(cmd); 776 return cmd; 777 } 778 if (tok == "INPUT_SECTION_FLAGS") { 779 std::tie(withFlags, withoutFlags) = readInputSectionFlags(); 780 tok = next(); 781 } 782 return readInputSectionRules(tok, withFlags, withoutFlags); 783 } 784 785 void ScriptParser::readSort() { 786 expect("("); 787 expect("CONSTRUCTORS"); 788 expect(")"); 789 } 790 791 Expr ScriptParser::readAssert() { 792 expect("("); 793 Expr e = readExpr(); 794 expect(","); 795 StringRef msg = unquote(next()); 796 expect(")"); 797 798 return [=] { 799 if (!e().getValue()) 800 errorOrWarn(msg); 801 return script->getDot(); 802 }; 803 } 804 805 #define ECase(X) \ 806 { #X, X } 807 constexpr std::pair<const char *, unsigned> typeMap[] = { 808 ECase(SHT_PROGBITS), ECase(SHT_NOTE), ECase(SHT_NOBITS), 809 ECase(SHT_INIT_ARRAY), ECase(SHT_FINI_ARRAY), ECase(SHT_PREINIT_ARRAY), 810 }; 811 #undef ECase 812 813 // Tries to read the special directive for an output section definition which 814 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and 815 // "(TYPE=<value>)". 816 // Tok1 and Tok2 are next 2 tokens peeked. See comment for 817 // readSectionAddressType below. 818 bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2) { 819 if (tok1 != "(") 820 return false; 821 if (tok2 != "NOLOAD" && tok2 != "COPY" && tok2 != "INFO" && 822 tok2 != "OVERLAY" && tok2 != "TYPE") 823 return false; 824 825 expect("("); 826 if (consume("NOLOAD")) { 827 cmd->type = SHT_NOBITS; 828 cmd->typeIsSet = true; 829 } else if (consume("TYPE")) { 830 expect("="); 831 StringRef value = peek(); 832 auto it = llvm::find_if(typeMap, [=](auto e) { return e.first == value; }); 833 if (it != std::end(typeMap)) { 834 // The value is a recognized literal SHT_*. 835 cmd->type = it->second; 836 skip(); 837 } else if (value.startswith("SHT_")) { 838 setError("unknown section type " + value); 839 } else { 840 // Otherwise, read an expression. 841 cmd->type = readExpr()().getValue(); 842 } 843 cmd->typeIsSet = true; 844 } else { 845 skip(); // This is "COPY", "INFO" or "OVERLAY". 846 cmd->nonAlloc = true; 847 } 848 expect(")"); 849 return true; 850 } 851 852 // Reads an expression and/or the special directive for an output 853 // section definition. Directive is one of following: "(NOLOAD)", 854 // "(COPY)", "(INFO)" or "(OVERLAY)". 855 // 856 // An output section name can be followed by an address expression 857 // and/or directive. This grammar is not LL(1) because "(" can be 858 // interpreted as either the beginning of some expression or beginning 859 // of directive. 860 // 861 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html 862 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html 863 void ScriptParser::readSectionAddressType(OutputSection *cmd) { 864 // Temporarily set inExpr to support TYPE=<value> without spaces. 865 bool saved = std::exchange(inExpr, true); 866 bool isDirective = readSectionDirective(cmd, peek(), peek2()); 867 inExpr = saved; 868 if (isDirective) 869 return; 870 871 cmd->addrExpr = readExpr(); 872 if (peek() == "(" && !readSectionDirective(cmd, "(", peek2())) 873 setError("unknown section directive: " + peek2()); 874 } 875 876 static Expr checkAlignment(Expr e, std::string &loc) { 877 return [=] { 878 uint64_t alignment = std::max((uint64_t)1, e().getValue()); 879 if (!isPowerOf2_64(alignment)) { 880 error(loc + ": alignment must be power of 2"); 881 return (uint64_t)1; // Return a dummy value. 882 } 883 return alignment; 884 }; 885 } 886 887 OutputDesc *ScriptParser::readOverlaySectionDescription() { 888 OutputDesc *osd = script->createOutputSection(next(), getCurrentLocation()); 889 osd->osec.inOverlay = true; 890 expect("{"); 891 while (!errorCount() && !consume("}")) { 892 uint64_t withFlags = 0; 893 uint64_t withoutFlags = 0; 894 if (consume("INPUT_SECTION_FLAGS")) 895 std::tie(withFlags, withoutFlags) = readInputSectionFlags(); 896 osd->osec.commands.push_back( 897 readInputSectionRules(next(), withFlags, withoutFlags)); 898 } 899 return osd; 900 } 901 902 OutputDesc *ScriptParser::readOutputSectionDescription(StringRef outSec) { 903 OutputDesc *cmd = script->createOutputSection(outSec, getCurrentLocation()); 904 OutputSection *osec = &cmd->osec; 905 // Maybe relro. Will reset to false if DATA_SEGMENT_RELRO_END is absent. 906 osec->relro = seenDataAlign && !seenRelroEnd; 907 908 size_t symbolsReferenced = script->referencedSymbols.size(); 909 910 if (peek() != ":") 911 readSectionAddressType(osec); 912 expect(":"); 913 914 std::string location = getCurrentLocation(); 915 if (consume("AT")) 916 osec->lmaExpr = readParenExpr(); 917 if (consume("ALIGN")) 918 osec->alignExpr = checkAlignment(readParenExpr(), location); 919 if (consume("SUBALIGN")) 920 osec->subalignExpr = checkAlignment(readParenExpr(), location); 921 922 // Parse constraints. 923 if (consume("ONLY_IF_RO")) 924 osec->constraint = ConstraintKind::ReadOnly; 925 if (consume("ONLY_IF_RW")) 926 osec->constraint = ConstraintKind::ReadWrite; 927 expect("{"); 928 929 while (!errorCount() && !consume("}")) { 930 StringRef tok = next(); 931 if (tok == ";") { 932 // Empty commands are allowed. Do nothing here. 933 } else if (SymbolAssignment *assign = readAssignment(tok)) { 934 osec->commands.push_back(assign); 935 } else if (ByteCommand *data = readByteCommand(tok)) { 936 osec->commands.push_back(data); 937 } else if (tok == "CONSTRUCTORS") { 938 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors 939 // by name. This is for very old file formats such as ECOFF/XCOFF. 940 // For ELF, we should ignore. 941 } else if (tok == "FILL") { 942 // We handle the FILL command as an alias for =fillexp section attribute, 943 // which is different from what GNU linkers do. 944 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html 945 if (peek() != "(") 946 setError("( expected, but got " + peek()); 947 osec->filler = readFill(); 948 } else if (tok == "SORT") { 949 readSort(); 950 } else if (tok == "INCLUDE") { 951 readInclude(); 952 } else if (tok == "(" || tok == ")") { 953 setError("expected filename pattern"); 954 } else if (peek() == "(") { 955 osec->commands.push_back(readInputSectionDescription(tok)); 956 } else { 957 // We have a file name and no input sections description. It is not a 958 // commonly used syntax, but still acceptable. In that case, all sections 959 // from the file will be included. 960 // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not 961 // handle this case here as it will already have been matched by the 962 // case above. 963 auto *isd = make<InputSectionDescription>(tok); 964 isd->sectionPatterns.push_back({{}, StringMatcher("*")}); 965 osec->commands.push_back(isd); 966 } 967 } 968 969 if (consume(">")) 970 osec->memoryRegionName = std::string(next()); 971 972 if (consume("AT")) { 973 expect(">"); 974 osec->lmaRegionName = std::string(next()); 975 } 976 977 if (osec->lmaExpr && !osec->lmaRegionName.empty()) 978 error("section can't have both LMA and a load region"); 979 980 osec->phdrs = readOutputSectionPhdrs(); 981 982 if (peek() == "=" || peek().startswith("=")) { 983 inExpr = true; 984 consume("="); 985 osec->filler = readFill(); 986 inExpr = false; 987 } 988 989 // Consume optional comma following output section command. 990 consume(","); 991 992 if (script->referencedSymbols.size() > symbolsReferenced) 993 osec->expressionsUseSymbols = true; 994 return cmd; 995 } 996 997 // Reads a `=<fillexp>` expression and returns its value as a big-endian number. 998 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html 999 // We do not support using symbols in such expressions. 1000 // 1001 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary 1002 // size, while ld.gold always handles it as a 32-bit big-endian number. 1003 // We are compatible with ld.gold because it's easier to implement. 1004 // Also, we require that expressions with operators must be wrapped into 1005 // round brackets. We did it to resolve the ambiguity when parsing scripts like: 1006 // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } } 1007 std::array<uint8_t, 4> ScriptParser::readFill() { 1008 uint64_t value = readPrimary()().val; 1009 if (value > UINT32_MAX) 1010 setError("filler expression result does not fit 32-bit: 0x" + 1011 Twine::utohexstr(value)); 1012 1013 std::array<uint8_t, 4> buf; 1014 write32be(buf.data(), (uint32_t)value); 1015 return buf; 1016 } 1017 1018 SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) { 1019 expect("("); 1020 SymbolAssignment *cmd = readSymbolAssignment(next()); 1021 cmd->provide = provide; 1022 cmd->hidden = hidden; 1023 expect(")"); 1024 return cmd; 1025 } 1026 1027 SymbolAssignment *ScriptParser::readAssignment(StringRef tok) { 1028 // Assert expression returns Dot, so this is equal to ".=." 1029 if (tok == "ASSERT") 1030 return make<SymbolAssignment>(".", readAssert(), getCurrentLocation()); 1031 1032 size_t oldPos = pos; 1033 SymbolAssignment *cmd = nullptr; 1034 if (peek().startswith("=")) { 1035 // Support = followed by an expression without whitespace. 1036 SaveAndRestore<bool> saved(inExpr, true); 1037 cmd = readSymbolAssignment(tok); 1038 } else if (peek() == "+=") { 1039 cmd = readSymbolAssignment(tok); 1040 } else if (tok == "PROVIDE") { 1041 SaveAndRestore<bool> saved(inExpr, true); 1042 cmd = readProvideHidden(true, false); 1043 } else if (tok == "HIDDEN") { 1044 SaveAndRestore<bool> saved(inExpr, true); 1045 cmd = readProvideHidden(false, true); 1046 } else if (tok == "PROVIDE_HIDDEN") { 1047 SaveAndRestore<bool> saved(inExpr, true); 1048 cmd = readProvideHidden(true, true); 1049 } 1050 1051 if (cmd) { 1052 cmd->commandString = 1053 tok.str() + " " + 1054 llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " "); 1055 expect(";"); 1056 } 1057 return cmd; 1058 } 1059 1060 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) { 1061 name = unquote(name); 1062 StringRef op = next(); 1063 assert(op == "=" || op == "+="); 1064 Expr e = readExpr(); 1065 if (op == "+=") { 1066 std::string loc = getCurrentLocation(); 1067 e = [=] { return add(script->getSymbolValue(name, loc), e()); }; 1068 } 1069 return make<SymbolAssignment>(name, e, getCurrentLocation()); 1070 } 1071 1072 // This is an operator-precedence parser to parse a linker 1073 // script expression. 1074 Expr ScriptParser::readExpr() { 1075 // Our lexer is context-aware. Set the in-expression bit so that 1076 // they apply different tokenization rules. 1077 bool orig = inExpr; 1078 inExpr = true; 1079 Expr e = readExpr1(readPrimary(), 0); 1080 inExpr = orig; 1081 return e; 1082 } 1083 1084 Expr ScriptParser::combine(StringRef op, Expr l, Expr r) { 1085 if (op == "+") 1086 return [=] { return add(l(), r()); }; 1087 if (op == "-") 1088 return [=] { return sub(l(), r()); }; 1089 if (op == "*") 1090 return [=] { return l().getValue() * r().getValue(); }; 1091 if (op == "/") { 1092 std::string loc = getCurrentLocation(); 1093 return [=]() -> uint64_t { 1094 if (uint64_t rv = r().getValue()) 1095 return l().getValue() / rv; 1096 error(loc + ": division by zero"); 1097 return 0; 1098 }; 1099 } 1100 if (op == "%") { 1101 std::string loc = getCurrentLocation(); 1102 return [=]() -> uint64_t { 1103 if (uint64_t rv = r().getValue()) 1104 return l().getValue() % rv; 1105 error(loc + ": modulo by zero"); 1106 return 0; 1107 }; 1108 } 1109 if (op == "<<") 1110 return [=] { return l().getValue() << r().getValue(); }; 1111 if (op == ">>") 1112 return [=] { return l().getValue() >> r().getValue(); }; 1113 if (op == "<") 1114 return [=] { return l().getValue() < r().getValue(); }; 1115 if (op == ">") 1116 return [=] { return l().getValue() > r().getValue(); }; 1117 if (op == ">=") 1118 return [=] { return l().getValue() >= r().getValue(); }; 1119 if (op == "<=") 1120 return [=] { return l().getValue() <= r().getValue(); }; 1121 if (op == "==") 1122 return [=] { return l().getValue() == r().getValue(); }; 1123 if (op == "!=") 1124 return [=] { return l().getValue() != r().getValue(); }; 1125 if (op == "||") 1126 return [=] { return l().getValue() || r().getValue(); }; 1127 if (op == "&&") 1128 return [=] { return l().getValue() && r().getValue(); }; 1129 if (op == "&") 1130 return [=] { return bitAnd(l(), r()); }; 1131 if (op == "|") 1132 return [=] { return bitOr(l(), r()); }; 1133 llvm_unreachable("invalid operator"); 1134 } 1135 1136 // This is a part of the operator-precedence parser. This function 1137 // assumes that the remaining token stream starts with an operator. 1138 Expr ScriptParser::readExpr1(Expr lhs, int minPrec) { 1139 while (!atEOF() && !errorCount()) { 1140 // Read an operator and an expression. 1141 StringRef op1 = peek(); 1142 if (precedence(op1) < minPrec) 1143 break; 1144 if (consume("?")) 1145 return readTernary(lhs); 1146 skip(); 1147 Expr rhs = readPrimary(); 1148 1149 // Evaluate the remaining part of the expression first if the 1150 // next operator has greater precedence than the previous one. 1151 // For example, if we have read "+" and "3", and if the next 1152 // operator is "*", then we'll evaluate 3 * ... part first. 1153 while (!atEOF()) { 1154 StringRef op2 = peek(); 1155 if (precedence(op2) <= precedence(op1)) 1156 break; 1157 rhs = readExpr1(rhs, precedence(op2)); 1158 } 1159 1160 lhs = combine(op1, lhs, rhs); 1161 } 1162 return lhs; 1163 } 1164 1165 Expr ScriptParser::getPageSize() { 1166 std::string location = getCurrentLocation(); 1167 return [=]() -> uint64_t { 1168 if (target) 1169 return config->commonPageSize; 1170 error(location + ": unable to calculate page size"); 1171 return 4096; // Return a dummy value. 1172 }; 1173 } 1174 1175 Expr ScriptParser::readConstant() { 1176 StringRef s = readParenLiteral(); 1177 if (s == "COMMONPAGESIZE") 1178 return getPageSize(); 1179 if (s == "MAXPAGESIZE") 1180 return [] { return config->maxPageSize; }; 1181 setError("unknown constant: " + s); 1182 return [] { return 0; }; 1183 } 1184 1185 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with 1186 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may 1187 // have "K" (Ki) or "M" (Mi) suffixes. 1188 static Optional<uint64_t> parseInt(StringRef tok) { 1189 // Hexadecimal 1190 uint64_t val; 1191 if (tok.startswith_insensitive("0x")) { 1192 if (!to_integer(tok.substr(2), val, 16)) 1193 return None; 1194 return val; 1195 } 1196 if (tok.endswith_insensitive("H")) { 1197 if (!to_integer(tok.drop_back(), val, 16)) 1198 return None; 1199 return val; 1200 } 1201 1202 // Decimal 1203 if (tok.endswith_insensitive("K")) { 1204 if (!to_integer(tok.drop_back(), val, 10)) 1205 return None; 1206 return val * 1024; 1207 } 1208 if (tok.endswith_insensitive("M")) { 1209 if (!to_integer(tok.drop_back(), val, 10)) 1210 return None; 1211 return val * 1024 * 1024; 1212 } 1213 if (!to_integer(tok, val, 10)) 1214 return None; 1215 return val; 1216 } 1217 1218 ByteCommand *ScriptParser::readByteCommand(StringRef tok) { 1219 int size = StringSwitch<int>(tok) 1220 .Case("BYTE", 1) 1221 .Case("SHORT", 2) 1222 .Case("LONG", 4) 1223 .Case("QUAD", 8) 1224 .Default(-1); 1225 if (size == -1) 1226 return nullptr; 1227 1228 size_t oldPos = pos; 1229 Expr e = readParenExpr(); 1230 std::string commandString = 1231 tok.str() + " " + 1232 llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " "); 1233 return make<ByteCommand>(e, size, commandString); 1234 } 1235 1236 static llvm::Optional<uint64_t> parseFlag(StringRef tok) { 1237 if (llvm::Optional<uint64_t> asInt = parseInt(tok)) 1238 return asInt; 1239 #define CASE_ENT(enum) #enum, ELF::enum 1240 return StringSwitch<llvm::Optional<uint64_t>>(tok) 1241 .Case(CASE_ENT(SHF_WRITE)) 1242 .Case(CASE_ENT(SHF_ALLOC)) 1243 .Case(CASE_ENT(SHF_EXECINSTR)) 1244 .Case(CASE_ENT(SHF_MERGE)) 1245 .Case(CASE_ENT(SHF_STRINGS)) 1246 .Case(CASE_ENT(SHF_INFO_LINK)) 1247 .Case(CASE_ENT(SHF_LINK_ORDER)) 1248 .Case(CASE_ENT(SHF_OS_NONCONFORMING)) 1249 .Case(CASE_ENT(SHF_GROUP)) 1250 .Case(CASE_ENT(SHF_TLS)) 1251 .Case(CASE_ENT(SHF_COMPRESSED)) 1252 .Case(CASE_ENT(SHF_EXCLUDE)) 1253 .Case(CASE_ENT(SHF_ARM_PURECODE)) 1254 .Default(None); 1255 #undef CASE_ENT 1256 } 1257 1258 // Reads the '(' <flags> ')' list of section flags in 1259 // INPUT_SECTION_FLAGS '(' <flags> ')' in the 1260 // following form: 1261 // <flags> ::= <flag> 1262 // | <flags> & flag 1263 // <flag> ::= Recognized Flag Name, or Integer value of flag. 1264 // If the first character of <flag> is a ! then this means without flag, 1265 // otherwise with flag. 1266 // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and 1267 // without flag SHF_WRITE. 1268 std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() { 1269 uint64_t withFlags = 0; 1270 uint64_t withoutFlags = 0; 1271 expect("("); 1272 while (!errorCount()) { 1273 StringRef tok = unquote(next()); 1274 bool without = tok.consume_front("!"); 1275 if (llvm::Optional<uint64_t> flag = parseFlag(tok)) { 1276 if (without) 1277 withoutFlags |= *flag; 1278 else 1279 withFlags |= *flag; 1280 } else { 1281 setError("unrecognised flag: " + tok); 1282 } 1283 if (consume(")")) 1284 break; 1285 if (!consume("&")) { 1286 next(); 1287 setError("expected & or )"); 1288 } 1289 } 1290 return std::make_pair(withFlags, withoutFlags); 1291 } 1292 1293 StringRef ScriptParser::readParenLiteral() { 1294 expect("("); 1295 bool orig = inExpr; 1296 inExpr = false; 1297 StringRef tok = next(); 1298 inExpr = orig; 1299 expect(")"); 1300 return tok; 1301 } 1302 1303 static void checkIfExists(const OutputSection &osec, StringRef location) { 1304 if (osec.location.empty() && script->errorOnMissingSection) 1305 error(location + ": undefined section " + osec.name); 1306 } 1307 1308 static bool isValidSymbolName(StringRef s) { 1309 auto valid = [](char c) { 1310 return isAlnum(c) || c == '$' || c == '.' || c == '_'; 1311 }; 1312 return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid); 1313 } 1314 1315 Expr ScriptParser::readPrimary() { 1316 if (peek() == "(") 1317 return readParenExpr(); 1318 1319 if (consume("~")) { 1320 Expr e = readPrimary(); 1321 return [=] { return ~e().getValue(); }; 1322 } 1323 if (consume("!")) { 1324 Expr e = readPrimary(); 1325 return [=] { return !e().getValue(); }; 1326 } 1327 if (consume("-")) { 1328 Expr e = readPrimary(); 1329 return [=] { return -e().getValue(); }; 1330 } 1331 1332 StringRef tok = next(); 1333 std::string location = getCurrentLocation(); 1334 1335 // Built-in functions are parsed here. 1336 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. 1337 if (tok == "ABSOLUTE") { 1338 Expr inner = readParenExpr(); 1339 return [=] { 1340 ExprValue i = inner(); 1341 i.forceAbsolute = true; 1342 return i; 1343 }; 1344 } 1345 if (tok == "ADDR") { 1346 StringRef name = readParenLiteral(); 1347 OutputSection *osec = &script->getOrCreateOutputSection(name)->osec; 1348 osec->usedInExpression = true; 1349 return [=]() -> ExprValue { 1350 checkIfExists(*osec, location); 1351 return {osec, false, 0, location}; 1352 }; 1353 } 1354 if (tok == "ALIGN") { 1355 expect("("); 1356 Expr e = readExpr(); 1357 if (consume(")")) { 1358 e = checkAlignment(e, location); 1359 return [=] { return alignTo(script->getDot(), e().getValue()); }; 1360 } 1361 expect(","); 1362 Expr e2 = checkAlignment(readExpr(), location); 1363 expect(")"); 1364 return [=] { 1365 ExprValue v = e(); 1366 v.alignment = e2().getValue(); 1367 return v; 1368 }; 1369 } 1370 if (tok == "ALIGNOF") { 1371 StringRef name = readParenLiteral(); 1372 OutputSection *osec = &script->getOrCreateOutputSection(name)->osec; 1373 return [=] { 1374 checkIfExists(*osec, location); 1375 return osec->alignment; 1376 }; 1377 } 1378 if (tok == "ASSERT") 1379 return readAssert(); 1380 if (tok == "CONSTANT") 1381 return readConstant(); 1382 if (tok == "DATA_SEGMENT_ALIGN") { 1383 expect("("); 1384 Expr e = readExpr(); 1385 expect(","); 1386 readExpr(); 1387 expect(")"); 1388 seenDataAlign = true; 1389 return [=] { 1390 return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue())); 1391 }; 1392 } 1393 if (tok == "DATA_SEGMENT_END") { 1394 expect("("); 1395 expect("."); 1396 expect(")"); 1397 return [] { return script->getDot(); }; 1398 } 1399 if (tok == "DATA_SEGMENT_RELRO_END") { 1400 // GNU linkers implements more complicated logic to handle 1401 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and 1402 // just align to the next page boundary for simplicity. 1403 expect("("); 1404 readExpr(); 1405 expect(","); 1406 readExpr(); 1407 expect(")"); 1408 seenRelroEnd = true; 1409 Expr e = getPageSize(); 1410 return [=] { return alignTo(script->getDot(), e().getValue()); }; 1411 } 1412 if (tok == "DEFINED") { 1413 StringRef name = unquote(readParenLiteral()); 1414 return [=] { 1415 Symbol *b = symtab->find(name); 1416 return (b && b->isDefined()) ? 1 : 0; 1417 }; 1418 } 1419 if (tok == "LENGTH") { 1420 StringRef name = readParenLiteral(); 1421 if (script->memoryRegions.count(name) == 0) { 1422 setError("memory region not defined: " + name); 1423 return [] { return 0; }; 1424 } 1425 return script->memoryRegions[name]->length; 1426 } 1427 if (tok == "LOADADDR") { 1428 StringRef name = readParenLiteral(); 1429 OutputSection *osec = &script->getOrCreateOutputSection(name)->osec; 1430 osec->usedInExpression = true; 1431 return [=] { 1432 checkIfExists(*osec, location); 1433 return osec->getLMA(); 1434 }; 1435 } 1436 if (tok == "LOG2CEIL") { 1437 expect("("); 1438 Expr a = readExpr(); 1439 expect(")"); 1440 return [=] { 1441 // LOG2CEIL(0) is defined to be 0. 1442 return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1))); 1443 }; 1444 } 1445 if (tok == "MAX" || tok == "MIN") { 1446 expect("("); 1447 Expr a = readExpr(); 1448 expect(","); 1449 Expr b = readExpr(); 1450 expect(")"); 1451 if (tok == "MIN") 1452 return [=] { return std::min(a().getValue(), b().getValue()); }; 1453 return [=] { return std::max(a().getValue(), b().getValue()); }; 1454 } 1455 if (tok == "ORIGIN") { 1456 StringRef name = readParenLiteral(); 1457 if (script->memoryRegions.count(name) == 0) { 1458 setError("memory region not defined: " + name); 1459 return [] { return 0; }; 1460 } 1461 return script->memoryRegions[name]->origin; 1462 } 1463 if (tok == "SEGMENT_START") { 1464 expect("("); 1465 skip(); 1466 expect(","); 1467 Expr e = readExpr(); 1468 expect(")"); 1469 return [=] { return e(); }; 1470 } 1471 if (tok == "SIZEOF") { 1472 StringRef name = readParenLiteral(); 1473 OutputSection *cmd = &script->getOrCreateOutputSection(name)->osec; 1474 // Linker script does not create an output section if its content is empty. 1475 // We want to allow SIZEOF(.foo) where .foo is a section which happened to 1476 // be empty. 1477 return [=] { return cmd->size; }; 1478 } 1479 if (tok == "SIZEOF_HEADERS") 1480 return [=] { return elf::getHeaderSize(); }; 1481 1482 // Tok is the dot. 1483 if (tok == ".") 1484 return [=] { return script->getSymbolValue(tok, location); }; 1485 1486 // Tok is a literal number. 1487 if (Optional<uint64_t> val = parseInt(tok)) 1488 return [=] { return *val; }; 1489 1490 // Tok is a symbol name. 1491 if (tok.startswith("\"")) 1492 tok = unquote(tok); 1493 else if (!isValidSymbolName(tok)) 1494 setError("malformed number: " + tok); 1495 script->referencedSymbols.push_back(tok); 1496 return [=] { return script->getSymbolValue(tok, location); }; 1497 } 1498 1499 Expr ScriptParser::readTernary(Expr cond) { 1500 Expr l = readExpr(); 1501 expect(":"); 1502 Expr r = readExpr(); 1503 return [=] { return cond().getValue() ? l() : r(); }; 1504 } 1505 1506 Expr ScriptParser::readParenExpr() { 1507 expect("("); 1508 Expr e = readExpr(); 1509 expect(")"); 1510 return e; 1511 } 1512 1513 SmallVector<StringRef, 0> ScriptParser::readOutputSectionPhdrs() { 1514 SmallVector<StringRef, 0> phdrs; 1515 while (!errorCount() && peek().startswith(":")) { 1516 StringRef tok = next(); 1517 phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1)); 1518 } 1519 return phdrs; 1520 } 1521 1522 // Read a program header type name. The next token must be a 1523 // name of a program header type or a constant (e.g. "0x3"). 1524 unsigned ScriptParser::readPhdrType() { 1525 StringRef tok = next(); 1526 if (Optional<uint64_t> val = parseInt(tok)) 1527 return *val; 1528 1529 unsigned ret = StringSwitch<unsigned>(tok) 1530 .Case("PT_NULL", PT_NULL) 1531 .Case("PT_LOAD", PT_LOAD) 1532 .Case("PT_DYNAMIC", PT_DYNAMIC) 1533 .Case("PT_INTERP", PT_INTERP) 1534 .Case("PT_NOTE", PT_NOTE) 1535 .Case("PT_SHLIB", PT_SHLIB) 1536 .Case("PT_PHDR", PT_PHDR) 1537 .Case("PT_TLS", PT_TLS) 1538 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) 1539 .Case("PT_GNU_STACK", PT_GNU_STACK) 1540 .Case("PT_GNU_RELRO", PT_GNU_RELRO) 1541 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE) 1542 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED) 1543 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA) 1544 .Default(-1); 1545 1546 if (ret == (unsigned)-1) { 1547 setError("invalid program header type: " + tok); 1548 return PT_NULL; 1549 } 1550 return ret; 1551 } 1552 1553 // Reads an anonymous version declaration. 1554 void ScriptParser::readAnonymousDeclaration() { 1555 SmallVector<SymbolVersion, 0> locals; 1556 SmallVector<SymbolVersion, 0> globals; 1557 std::tie(locals, globals) = readSymbols(); 1558 for (const SymbolVersion &pat : locals) 1559 config->versionDefinitions[VER_NDX_LOCAL].localPatterns.push_back(pat); 1560 for (const SymbolVersion &pat : globals) 1561 config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(pat); 1562 1563 expect(";"); 1564 } 1565 1566 // Reads a non-anonymous version definition, 1567 // e.g. "VerStr { global: foo; bar; local: *; };". 1568 void ScriptParser::readVersionDeclaration(StringRef verStr) { 1569 // Read a symbol list. 1570 SmallVector<SymbolVersion, 0> locals; 1571 SmallVector<SymbolVersion, 0> globals; 1572 std::tie(locals, globals) = readSymbols(); 1573 1574 // Create a new version definition and add that to the global symbols. 1575 VersionDefinition ver; 1576 ver.name = verStr; 1577 ver.nonLocalPatterns = std::move(globals); 1578 ver.localPatterns = std::move(locals); 1579 ver.id = config->versionDefinitions.size(); 1580 config->versionDefinitions.push_back(ver); 1581 1582 // Each version may have a parent version. For example, "Ver2" 1583 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" 1584 // as a parent. This version hierarchy is, probably against your 1585 // instinct, purely for hint; the runtime doesn't care about it 1586 // at all. In LLD, we simply ignore it. 1587 if (next() != ";") 1588 expect(";"); 1589 } 1590 1591 bool elf::hasWildcard(StringRef s) { 1592 return s.find_first_of("?*[") != StringRef::npos; 1593 } 1594 1595 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };". 1596 std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>> 1597 ScriptParser::readSymbols() { 1598 SmallVector<SymbolVersion, 0> locals; 1599 SmallVector<SymbolVersion, 0> globals; 1600 SmallVector<SymbolVersion, 0> *v = &globals; 1601 1602 while (!errorCount()) { 1603 if (consume("}")) 1604 break; 1605 if (consumeLabel("local")) { 1606 v = &locals; 1607 continue; 1608 } 1609 if (consumeLabel("global")) { 1610 v = &globals; 1611 continue; 1612 } 1613 1614 if (consume("extern")) { 1615 SmallVector<SymbolVersion, 0> ext = readVersionExtern(); 1616 v->insert(v->end(), ext.begin(), ext.end()); 1617 } else { 1618 StringRef tok = next(); 1619 v->push_back({unquote(tok), false, hasWildcard(tok)}); 1620 } 1621 expect(";"); 1622 } 1623 return {locals, globals}; 1624 } 1625 1626 // Reads an "extern C++" directive, e.g., 1627 // "extern "C++" { ns::*; "f(int, double)"; };" 1628 // 1629 // The last semicolon is optional. E.g. this is OK: 1630 // "extern "C++" { ns::*; "f(int, double)" };" 1631 SmallVector<SymbolVersion, 0> ScriptParser::readVersionExtern() { 1632 StringRef tok = next(); 1633 bool isCXX = tok == "\"C++\""; 1634 if (!isCXX && tok != "\"C\"") 1635 setError("Unknown language"); 1636 expect("{"); 1637 1638 SmallVector<SymbolVersion, 0> ret; 1639 while (!errorCount() && peek() != "}") { 1640 StringRef tok = next(); 1641 ret.push_back( 1642 {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)}); 1643 if (consume("}")) 1644 return ret; 1645 expect(";"); 1646 } 1647 1648 expect("}"); 1649 return ret; 1650 } 1651 1652 Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2, 1653 StringRef s3) { 1654 if (!consume(s1) && !consume(s2) && !consume(s3)) { 1655 setError("expected one of: " + s1 + ", " + s2 + ", or " + s3); 1656 return [] { return 0; }; 1657 } 1658 expect("="); 1659 return readExpr(); 1660 } 1661 1662 // Parse the MEMORY command as specified in: 1663 // https://sourceware.org/binutils/docs/ld/MEMORY.html 1664 // 1665 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... } 1666 void ScriptParser::readMemory() { 1667 expect("{"); 1668 while (!errorCount() && !consume("}")) { 1669 StringRef tok = next(); 1670 if (tok == "INCLUDE") { 1671 readInclude(); 1672 continue; 1673 } 1674 1675 uint32_t flags = 0; 1676 uint32_t invFlags = 0; 1677 uint32_t negFlags = 0; 1678 uint32_t negInvFlags = 0; 1679 if (consume("(")) { 1680 readMemoryAttributes(flags, invFlags, negFlags, negInvFlags); 1681 expect(")"); 1682 } 1683 expect(":"); 1684 1685 Expr origin = readMemoryAssignment("ORIGIN", "org", "o"); 1686 expect(","); 1687 Expr length = readMemoryAssignment("LENGTH", "len", "l"); 1688 1689 // Add the memory region to the region map. 1690 MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, invFlags, 1691 negFlags, negInvFlags); 1692 if (!script->memoryRegions.insert({tok, mr}).second) 1693 setError("region '" + tok + "' already defined"); 1694 } 1695 } 1696 1697 // This function parses the attributes used to match against section 1698 // flags when placing output sections in a memory region. These flags 1699 // are only used when an explicit memory region name is not used. 1700 void ScriptParser::readMemoryAttributes(uint32_t &flags, uint32_t &invFlags, 1701 uint32_t &negFlags, 1702 uint32_t &negInvFlags) { 1703 bool invert = false; 1704 1705 for (char c : next().lower()) { 1706 if (c == '!') { 1707 invert = !invert; 1708 std::swap(flags, negFlags); 1709 std::swap(invFlags, negInvFlags); 1710 continue; 1711 } 1712 if (c == 'w') 1713 flags |= SHF_WRITE; 1714 else if (c == 'x') 1715 flags |= SHF_EXECINSTR; 1716 else if (c == 'a') 1717 flags |= SHF_ALLOC; 1718 else if (c == 'r') 1719 invFlags |= SHF_WRITE; 1720 else 1721 setError("invalid memory region attribute"); 1722 } 1723 1724 if (invert) { 1725 std::swap(flags, negFlags); 1726 std::swap(invFlags, negInvFlags); 1727 } 1728 } 1729 1730 void elf::readLinkerScript(MemoryBufferRef mb) { 1731 llvm::TimeTraceScope timeScope("Read linker script", 1732 mb.getBufferIdentifier()); 1733 ScriptParser(mb).readLinkerScript(); 1734 } 1735 1736 void elf::readVersionScript(MemoryBufferRef mb) { 1737 llvm::TimeTraceScope timeScope("Read version script", 1738 mb.getBufferIdentifier()); 1739 ScriptParser(mb).readVersionScript(); 1740 } 1741 1742 void elf::readDynamicList(MemoryBufferRef mb) { 1743 llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier()); 1744 ScriptParser(mb).readDynamicList(); 1745 } 1746 1747 void elf::readDefsym(StringRef name, MemoryBufferRef mb) { 1748 llvm::TimeTraceScope timeScope("Read defsym input", name); 1749 ScriptParser(mb).readDefsym(name); 1750 } 1751