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