1 //===- ScriptParser.cpp ---------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains a recursive-descendent parser for linker scripts. 11 // Parsed results are stored to Config and Script global objects. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ScriptParser.h" 16 #include "Config.h" 17 #include "Driver.h" 18 #include "InputSection.h" 19 #include "LinkerScript.h" 20 #include "OutputSections.h" 21 #include "ScriptLexer.h" 22 #include "Symbols.h" 23 #include "Target.h" 24 #include "lld/Common/Memory.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/Path.h" 34 #include <cassert> 35 #include <limits> 36 #include <vector> 37 38 using namespace llvm; 39 using namespace llvm::ELF; 40 using namespace llvm::support::endian; 41 using namespace lld; 42 using namespace lld::elf; 43 44 static bool isUnderSysroot(StringRef Path); 45 46 namespace { 47 class ScriptParser final : ScriptLexer { 48 public: 49 ScriptParser(MemoryBufferRef MB) 50 : ScriptLexer(MB), 51 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {} 52 53 void readLinkerScript(); 54 void readVersionScript(); 55 void readDynamicList(); 56 void readDefsym(StringRef Name); 57 58 private: 59 void addFile(StringRef Path); 60 61 void readAsNeeded(); 62 void readEntry(); 63 void readExtern(); 64 void readGroup(); 65 void readInclude(); 66 void readInput(); 67 void readMemory(); 68 void readOutput(); 69 void readOutputArch(); 70 void readOutputFormat(); 71 void readPhdrs(); 72 void readRegionAlias(); 73 void readSearchDir(); 74 void readSections(); 75 void readVersion(); 76 void readVersionScriptCommand(); 77 78 SymbolAssignment *readSymbolAssignment(StringRef Name); 79 ByteCommand *readByteCommand(StringRef Tok); 80 uint32_t readFill(); 81 uint32_t parseFill(StringRef Tok); 82 void readSectionAddressType(OutputSection *Cmd); 83 OutputSection *readOverlaySectionDescription(); 84 OutputSection *readOutputSectionDescription(StringRef OutSec); 85 std::vector<BaseCommand *> readOverlay(); 86 std::vector<StringRef> readOutputSectionPhdrs(); 87 InputSectionDescription *readInputSectionDescription(StringRef Tok); 88 StringMatcher readFilePatterns(); 89 std::vector<SectionPattern> readInputSectionsList(); 90 InputSectionDescription *readInputSectionRules(StringRef FilePattern); 91 unsigned readPhdrType(); 92 SortSectionPolicy readSortKind(); 93 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden); 94 SymbolAssignment *readAssignment(StringRef Tok); 95 void readSort(); 96 Expr readAssert(); 97 Expr readConstant(); 98 Expr getPageSize(); 99 100 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef); 101 std::pair<uint32_t, uint32_t> readMemoryAttributes(); 102 103 Expr combine(StringRef Op, Expr L, Expr R); 104 Expr readExpr(); 105 Expr readExpr1(Expr Lhs, int MinPrec); 106 StringRef readParenLiteral(); 107 Expr readPrimary(); 108 Expr readTernary(Expr Cond); 109 Expr readParenExpr(); 110 111 // For parsing version script. 112 std::vector<SymbolVersion> readVersionExtern(); 113 void readAnonymousDeclaration(); 114 void readVersionDeclaration(StringRef VerStr); 115 116 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>> 117 readSymbols(); 118 119 // True if a script being read is in a subdirectory specified by -sysroot. 120 bool IsUnderSysroot; 121 122 // A set to detect an INCLUDE() cycle. 123 StringSet<> Seen; 124 }; 125 } // namespace 126 127 static StringRef unquote(StringRef S) { 128 if (S.startswith("\"")) 129 return S.substr(1, S.size() - 2); 130 return S; 131 } 132 133 static bool isUnderSysroot(StringRef Path) { 134 if (Config->Sysroot == "") 135 return false; 136 for (; !Path.empty(); Path = sys::path::parent_path(Path)) 137 if (sys::fs::equivalent(Config->Sysroot, Path)) 138 return true; 139 return false; 140 } 141 142 // Some operations only support one non absolute value. Move the 143 // absolute one to the right hand side for convenience. 144 static void moveAbsRight(ExprValue &A, ExprValue &B) { 145 if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute())) 146 std::swap(A, B); 147 if (!B.isAbsolute()) 148 error(A.Loc + ": at least one side of the expression must be absolute"); 149 } 150 151 static ExprValue add(ExprValue A, ExprValue B) { 152 moveAbsRight(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(ExprValue A, ExprValue B) { 164 moveAbsRight(A, B); 165 return {A.Sec, A.ForceAbsolute, 166 (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc}; 167 } 168 169 static ExprValue bitOr(ExprValue A, ExprValue B) { 170 moveAbsRight(A, B); 171 return {A.Sec, A.ForceAbsolute, 172 (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc}; 173 } 174 175 void ScriptParser::readDynamicList() { 176 Config->HasDynamicList = true; 177 expect("{"); 178 std::vector<SymbolVersion> Locals; 179 std::vector<SymbolVersion> Globals; 180 std::tie(Locals, Globals) = readSymbols(); 181 expect(";"); 182 183 if (!atEOF()) { 184 setError("EOF expected, but got " + next()); 185 return; 186 } 187 if (!Locals.empty()) { 188 setError("\"local:\" scope not supported in --dynamic-list"); 189 return; 190 } 191 192 for (SymbolVersion V : Globals) 193 Config->DynamicList.push_back(V); 194 } 195 196 void ScriptParser::readVersionScript() { 197 readVersionScriptCommand(); 198 if (!atEOF()) 199 setError("EOF expected, but got " + next()); 200 } 201 202 void ScriptParser::readVersionScriptCommand() { 203 if (consume("{")) { 204 readAnonymousDeclaration(); 205 return; 206 } 207 208 while (!atEOF() && !errorCount() && peek() != "}") { 209 StringRef VerStr = next(); 210 if (VerStr == "{") { 211 setError("anonymous version definition is used in " 212 "combination with other version definitions"); 213 return; 214 } 215 expect("{"); 216 readVersionDeclaration(VerStr); 217 } 218 } 219 220 void ScriptParser::readVersion() { 221 expect("{"); 222 readVersionScriptCommand(); 223 expect("}"); 224 } 225 226 void ScriptParser::readLinkerScript() { 227 while (!atEOF()) { 228 StringRef Tok = next(); 229 if (Tok == ";") 230 continue; 231 232 if (Tok == "ENTRY") { 233 readEntry(); 234 } else if (Tok == "EXTERN") { 235 readExtern(); 236 } else if (Tok == "GROUP") { 237 readGroup(); 238 } else if (Tok == "INCLUDE") { 239 readInclude(); 240 } else if (Tok == "INPUT") { 241 readInput(); 242 } else if (Tok == "MEMORY") { 243 readMemory(); 244 } else if (Tok == "OUTPUT") { 245 readOutput(); 246 } else if (Tok == "OUTPUT_ARCH") { 247 readOutputArch(); 248 } else if (Tok == "OUTPUT_FORMAT") { 249 readOutputFormat(); 250 } else if (Tok == "PHDRS") { 251 readPhdrs(); 252 } else if (Tok == "REGION_ALIAS") { 253 readRegionAlias(); 254 } else if (Tok == "SEARCH_DIR") { 255 readSearchDir(); 256 } else if (Tok == "SECTIONS") { 257 readSections(); 258 } else if (Tok == "VERSION") { 259 readVersion(); 260 } else if (SymbolAssignment *Cmd = readAssignment(Tok)) { 261 Script->SectionCommands.push_back(Cmd); 262 } else { 263 setError("unknown directive: " + Tok); 264 } 265 } 266 } 267 268 void ScriptParser::readDefsym(StringRef Name) { 269 Expr E = readExpr(); 270 if (!atEOF()) 271 setError("EOF expected, but got " + next()); 272 SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation()); 273 Script->SectionCommands.push_back(Cmd); 274 } 275 276 void ScriptParser::addFile(StringRef S) { 277 if (IsUnderSysroot && S.startswith("/")) { 278 SmallString<128> PathData; 279 StringRef Path = (Config->Sysroot + S).toStringRef(PathData); 280 if (sys::fs::exists(Path)) { 281 Driver->addFile(Saver.save(Path), /*WithLOption=*/false); 282 return; 283 } 284 } 285 286 if (S.startswith("/")) { 287 Driver->addFile(S, /*WithLOption=*/false); 288 } else if (S.startswith("=")) { 289 if (Config->Sysroot.empty()) 290 Driver->addFile(S.substr(1), /*WithLOption=*/false); 291 else 292 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)), 293 /*WithLOption=*/false); 294 } else if (S.startswith("-l")) { 295 Driver->addLibrary(S.substr(2)); 296 } else if (sys::fs::exists(S)) { 297 Driver->addFile(S, /*WithLOption=*/false); 298 } else { 299 if (Optional<std::string> Path = findFromSearchPaths(S)) 300 Driver->addFile(Saver.save(*Path), /*WithLOption=*/true); 301 else 302 setError("unable to find " + S); 303 } 304 } 305 306 void ScriptParser::readAsNeeded() { 307 expect("("); 308 bool Orig = Config->AsNeeded; 309 Config->AsNeeded = true; 310 while (!errorCount() && !consume(")")) 311 addFile(unquote(next())); 312 Config->AsNeeded = Orig; 313 } 314 315 void ScriptParser::readEntry() { 316 // -e <symbol> takes predecence over ENTRY(<symbol>). 317 expect("("); 318 StringRef Tok = next(); 319 if (Config->Entry.empty()) 320 Config->Entry = Tok; 321 expect(")"); 322 } 323 324 void ScriptParser::readExtern() { 325 expect("("); 326 while (!errorCount() && !consume(")")) 327 Config->Undefined.push_back(next()); 328 } 329 330 void ScriptParser::readGroup() { 331 bool Orig = InputFile::IsInGroup; 332 InputFile::IsInGroup = true; 333 readInput(); 334 InputFile::IsInGroup = Orig; 335 if (!Orig) 336 ++InputFile::NextGroupId; 337 } 338 339 void ScriptParser::readInclude() { 340 StringRef Tok = unquote(next()); 341 342 if (!Seen.insert(Tok).second) { 343 setError("there is a cycle in linker script INCLUDEs"); 344 return; 345 } 346 347 if (Optional<std::string> Path = searchLinkerScript(Tok)) { 348 if (Optional<MemoryBufferRef> MB = readFile(*Path)) 349 tokenize(*MB); 350 return; 351 } 352 setError("cannot find linker script " + Tok); 353 } 354 355 void ScriptParser::readInput() { 356 expect("("); 357 while (!errorCount() && !consume(")")) { 358 if (consume("AS_NEEDED")) 359 readAsNeeded(); 360 else 361 addFile(unquote(next())); 362 } 363 } 364 365 void ScriptParser::readOutput() { 366 // -o <file> takes predecence over OUTPUT(<file>). 367 expect("("); 368 StringRef Tok = next(); 369 if (Config->OutputFile.empty()) 370 Config->OutputFile = unquote(Tok); 371 expect(")"); 372 } 373 374 void ScriptParser::readOutputArch() { 375 // OUTPUT_ARCH is ignored for now. 376 expect("("); 377 while (!errorCount() && !consume(")")) 378 skip(); 379 } 380 381 void ScriptParser::readOutputFormat() { 382 // Error checking only for now. 383 expect("("); 384 skip(); 385 if (consume(")")) 386 return; 387 expect(","); 388 skip(); 389 expect(","); 390 skip(); 391 expect(")"); 392 } 393 394 void ScriptParser::readPhdrs() { 395 expect("{"); 396 397 while (!errorCount() && !consume("}")) { 398 PhdrsCommand Cmd; 399 Cmd.Name = next(); 400 Cmd.Type = readPhdrType(); 401 402 while (!errorCount() && !consume(";")) { 403 if (consume("FILEHDR")) 404 Cmd.HasFilehdr = true; 405 else if (consume("PHDRS")) 406 Cmd.HasPhdrs = true; 407 else if (consume("AT")) 408 Cmd.LMAExpr = readParenExpr(); 409 else if (consume("FLAGS")) 410 Cmd.Flags = readParenExpr()().getValue(); 411 else 412 setError("unexpected header attribute: " + next()); 413 } 414 415 Script->PhdrsCommands.push_back(Cmd); 416 } 417 } 418 419 void ScriptParser::readRegionAlias() { 420 expect("("); 421 StringRef Alias = unquote(next()); 422 expect(","); 423 StringRef Name = next(); 424 expect(")"); 425 426 if (Script->MemoryRegions.count(Alias)) 427 setError("redefinition of memory region '" + Alias + "'"); 428 if (!Script->MemoryRegions.count(Name)) 429 setError("memory region '" + Name + "' is not defined"); 430 Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]}); 431 } 432 433 void ScriptParser::readSearchDir() { 434 expect("("); 435 StringRef Tok = next(); 436 if (!Config->Nostdlib) 437 Config->SearchPaths.push_back(unquote(Tok)); 438 expect(")"); 439 } 440 441 // This reads an overlay description. Overlays are used to describe output 442 // sections that use the same virtual memory range and normally would trigger 443 // linker's sections sanity check failures. 444 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description 445 std::vector<BaseCommand *> ScriptParser::readOverlay() { 446 // VA and LMA expressions are optional, though for simplicity of 447 // implementation we assume they are not. That is what OVERLAY was designed 448 // for first of all: to allow sections with overlapping VAs at different LMAs. 449 Expr AddrExpr = readExpr(); 450 expect(":"); 451 expect("AT"); 452 Expr LMAExpr = readParenExpr(); 453 expect("{"); 454 455 std::vector<BaseCommand *> V; 456 OutputSection *Prev = nullptr; 457 while (!errorCount() && !consume("}")) { 458 // VA is the same for all sections. The LMAs are consecutive in memory 459 // starting from the base load address specified. 460 OutputSection *OS = readOverlaySectionDescription(); 461 OS->AddrExpr = AddrExpr; 462 if (Prev) 463 OS->LMAExpr = [=] { return Prev->getLMA() + Prev->Size; }; 464 else 465 OS->LMAExpr = LMAExpr; 466 V.push_back(OS); 467 Prev = OS; 468 } 469 470 // According to the specification, at the end of the overlay, the location 471 // counter should be equal to the overlay base address plus size of the 472 // largest section seen in the overlay. 473 // Here we want to create the Dot assignment command to achieve that. 474 Expr MoveDot = [=] { 475 uint64_t Max = 0; 476 for (BaseCommand *Cmd : V) 477 Max = std::max(Max, cast<OutputSection>(Cmd)->Size); 478 return AddrExpr().getValue() + Max; 479 }; 480 V.push_back(make<SymbolAssignment>(".", MoveDot, getCurrentLocation())); 481 return V; 482 } 483 484 void ScriptParser::readSections() { 485 Script->HasSectionsCommand = true; 486 487 // -no-rosegment is used to avoid placing read only non-executable sections in 488 // their own segment. We do the same if SECTIONS command is present in linker 489 // script. See comment for computeFlags(). 490 Config->SingleRoRx = true; 491 492 expect("{"); 493 std::vector<BaseCommand *> V; 494 while (!errorCount() && !consume("}")) { 495 StringRef Tok = next(); 496 if (Tok == "OVERLAY") { 497 for (BaseCommand *Cmd : readOverlay()) 498 V.push_back(Cmd); 499 continue; 500 } 501 502 if (BaseCommand *Cmd = readAssignment(Tok)) 503 V.push_back(Cmd); 504 else 505 V.push_back(readOutputSectionDescription(Tok)); 506 } 507 508 if (!atEOF() && consume("INSERT")) { 509 std::vector<BaseCommand *> *Dest = nullptr; 510 if (consume("AFTER")) 511 Dest = &Script->InsertAfterCommands[next()]; 512 else if (consume("BEFORE")) 513 Dest = &Script->InsertBeforeCommands[next()]; 514 else 515 setError("expected AFTER/BEFORE, but got '" + next() + "'"); 516 if (Dest) 517 Dest->insert(Dest->end(), V.begin(), V.end()); 518 return; 519 } 520 521 Script->SectionCommands.insert(Script->SectionCommands.end(), V.begin(), 522 V.end()); 523 } 524 525 static int precedence(StringRef Op) { 526 return StringSwitch<int>(Op) 527 .Cases("*", "/", "%", 6) 528 .Cases("+", "-", 5) 529 .Cases("<<", ">>", 4) 530 .Cases("<", "<=", ">", ">=", "==", "!=", 3) 531 .Case("&", 2) 532 .Case("|", 1) 533 .Default(-1); 534 } 535 536 StringMatcher ScriptParser::readFilePatterns() { 537 std::vector<StringRef> V; 538 while (!errorCount() && !consume(")")) 539 V.push_back(next()); 540 return StringMatcher(V); 541 } 542 543 SortSectionPolicy ScriptParser::readSortKind() { 544 if (consume("SORT") || consume("SORT_BY_NAME")) 545 return SortSectionPolicy::Name; 546 if (consume("SORT_BY_ALIGNMENT")) 547 return SortSectionPolicy::Alignment; 548 if (consume("SORT_BY_INIT_PRIORITY")) 549 return SortSectionPolicy::Priority; 550 if (consume("SORT_NONE")) 551 return SortSectionPolicy::None; 552 return SortSectionPolicy::Default; 553 } 554 555 // Reads SECTIONS command contents in the following form: 556 // 557 // <contents> ::= <elem>* 558 // <elem> ::= <exclude>? <glob-pattern> 559 // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")" 560 // 561 // For example, 562 // 563 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz) 564 // 565 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o". 566 // The semantics of that is section .foo in any file, section .bar in 567 // any file but a.o, and section .baz in any file but b.o. 568 std::vector<SectionPattern> ScriptParser::readInputSectionsList() { 569 std::vector<SectionPattern> Ret; 570 while (!errorCount() && peek() != ")") { 571 StringMatcher ExcludeFilePat; 572 if (consume("EXCLUDE_FILE")) { 573 expect("("); 574 ExcludeFilePat = readFilePatterns(); 575 } 576 577 std::vector<StringRef> V; 578 while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE") 579 V.push_back(next()); 580 581 if (!V.empty()) 582 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)}); 583 else 584 setError("section pattern is expected"); 585 } 586 return Ret; 587 } 588 589 // Reads contents of "SECTIONS" directive. That directive contains a 590 // list of glob patterns for input sections. The grammar is as follows. 591 // 592 // <patterns> ::= <section-list> 593 // | <sort> "(" <section-list> ")" 594 // | <sort> "(" <sort> "(" <section-list> ")" ")" 595 // 596 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT" 597 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE" 598 // 599 // <section-list> is parsed by readInputSectionsList(). 600 InputSectionDescription * 601 ScriptParser::readInputSectionRules(StringRef FilePattern) { 602 auto *Cmd = make<InputSectionDescription>(FilePattern); 603 expect("("); 604 605 while (!errorCount() && !consume(")")) { 606 SortSectionPolicy Outer = readSortKind(); 607 SortSectionPolicy Inner = SortSectionPolicy::Default; 608 std::vector<SectionPattern> V; 609 if (Outer != SortSectionPolicy::Default) { 610 expect("("); 611 Inner = readSortKind(); 612 if (Inner != SortSectionPolicy::Default) { 613 expect("("); 614 V = readInputSectionsList(); 615 expect(")"); 616 } else { 617 V = readInputSectionsList(); 618 } 619 expect(")"); 620 } else { 621 V = readInputSectionsList(); 622 } 623 624 for (SectionPattern &Pat : V) { 625 Pat.SortInner = Inner; 626 Pat.SortOuter = Outer; 627 } 628 629 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns)); 630 } 631 return Cmd; 632 } 633 634 InputSectionDescription * 635 ScriptParser::readInputSectionDescription(StringRef Tok) { 636 // Input section wildcard can be surrounded by KEEP. 637 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep 638 if (Tok == "KEEP") { 639 expect("("); 640 StringRef FilePattern = next(); 641 InputSectionDescription *Cmd = readInputSectionRules(FilePattern); 642 expect(")"); 643 Script->KeptSections.push_back(Cmd); 644 return Cmd; 645 } 646 return readInputSectionRules(Tok); 647 } 648 649 void ScriptParser::readSort() { 650 expect("("); 651 expect("CONSTRUCTORS"); 652 expect(")"); 653 } 654 655 Expr ScriptParser::readAssert() { 656 expect("("); 657 Expr E = readExpr(); 658 expect(","); 659 StringRef Msg = unquote(next()); 660 expect(")"); 661 662 return [=] { 663 if (!E().getValue()) 664 error(Msg); 665 return Script->getDot(); 666 }; 667 } 668 669 // Reads a FILL(expr) command. We handle the FILL command as an 670 // alias for =fillexp section attribute, which is different from 671 // what GNU linkers do. 672 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html 673 uint32_t ScriptParser::readFill() { 674 expect("("); 675 uint32_t V = parseFill(next()); 676 expect(")"); 677 return V; 678 } 679 680 // Reads an expression and/or the special directive for an output 681 // section definition. Directive is one of following: "(NOLOAD)", 682 // "(COPY)", "(INFO)" or "(OVERLAY)". 683 // 684 // An output section name can be followed by an address expression 685 // and/or directive. This grammar is not LL(1) because "(" can be 686 // interpreted as either the beginning of some expression or beginning 687 // of directive. 688 // 689 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html 690 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html 691 void ScriptParser::readSectionAddressType(OutputSection *Cmd) { 692 if (consume("(")) { 693 if (consume("NOLOAD")) { 694 expect(")"); 695 Cmd->Noload = true; 696 return; 697 } 698 if (consume("COPY") || consume("INFO") || consume("OVERLAY")) { 699 expect(")"); 700 Cmd->NonAlloc = true; 701 return; 702 } 703 Cmd->AddrExpr = readExpr(); 704 expect(")"); 705 } else { 706 Cmd->AddrExpr = readExpr(); 707 } 708 709 if (consume("(")) { 710 expect("NOLOAD"); 711 expect(")"); 712 Cmd->Noload = true; 713 } 714 } 715 716 static Expr checkAlignment(Expr E, std::string &Loc) { 717 return [=] { 718 uint64_t Alignment = std::max((uint64_t)1, E().getValue()); 719 if (!isPowerOf2_64(Alignment)) { 720 error(Loc + ": alignment must be power of 2"); 721 return (uint64_t)1; // Return a dummy value. 722 } 723 return Alignment; 724 }; 725 } 726 727 OutputSection *ScriptParser::readOverlaySectionDescription() { 728 OutputSection *Cmd = 729 Script->createOutputSection(next(), getCurrentLocation()); 730 Cmd->InOverlay = true; 731 expect("{"); 732 while (!errorCount() && !consume("}")) 733 Cmd->SectionCommands.push_back(readInputSectionRules(next())); 734 Cmd->Phdrs = readOutputSectionPhdrs(); 735 return Cmd; 736 } 737 738 OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) { 739 OutputSection *Cmd = 740 Script->createOutputSection(OutSec, getCurrentLocation()); 741 742 size_t SymbolsReferenced = Script->ReferencedSymbols.size(); 743 744 if (peek() != ":") 745 readSectionAddressType(Cmd); 746 expect(":"); 747 748 std::string Location = getCurrentLocation(); 749 if (consume("AT")) 750 Cmd->LMAExpr = readParenExpr(); 751 if (consume("ALIGN")) 752 Cmd->AlignExpr = checkAlignment(readParenExpr(), Location); 753 if (consume("SUBALIGN")) 754 Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location); 755 756 // Parse constraints. 757 if (consume("ONLY_IF_RO")) 758 Cmd->Constraint = ConstraintKind::ReadOnly; 759 if (consume("ONLY_IF_RW")) 760 Cmd->Constraint = ConstraintKind::ReadWrite; 761 expect("{"); 762 763 while (!errorCount() && !consume("}")) { 764 StringRef Tok = next(); 765 if (Tok == ";") { 766 // Empty commands are allowed. Do nothing here. 767 } else if (SymbolAssignment *Assign = readAssignment(Tok)) { 768 Cmd->SectionCommands.push_back(Assign); 769 } else if (ByteCommand *Data = readByteCommand(Tok)) { 770 Cmd->SectionCommands.push_back(Data); 771 } else if (Tok == "CONSTRUCTORS") { 772 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors 773 // by name. This is for very old file formats such as ECOFF/XCOFF. 774 // For ELF, we should ignore. 775 } else if (Tok == "FILL") { 776 Cmd->Filler = readFill(); 777 } else if (Tok == "SORT") { 778 readSort(); 779 } else if (peek() == "(") { 780 Cmd->SectionCommands.push_back(readInputSectionDescription(Tok)); 781 } else { 782 setError("unknown command " + Tok); 783 } 784 } 785 786 if (consume(">")) 787 Cmd->MemoryRegionName = next(); 788 789 if (consume("AT")) { 790 expect(">"); 791 Cmd->LMARegionName = next(); 792 } 793 794 if (Cmd->LMAExpr && !Cmd->LMARegionName.empty()) 795 error("section can't have both LMA and a load region"); 796 797 Cmd->Phdrs = readOutputSectionPhdrs(); 798 799 if (consume("=")) 800 Cmd->Filler = parseFill(next()); 801 else if (peek().startswith("=")) 802 Cmd->Filler = parseFill(next().drop_front()); 803 804 // Consume optional comma following output section command. 805 consume(","); 806 807 if (Script->ReferencedSymbols.size() > SymbolsReferenced) 808 Cmd->ExpressionsUseSymbols = true; 809 return Cmd; 810 } 811 812 // Parses a given string as a octal/decimal/hexadecimal number and 813 // returns it as a big-endian number. Used for `=<fillexp>`. 814 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html 815 // 816 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary 817 // size, while ld.gold always handles it as a 32-bit big-endian number. 818 // We are compatible with ld.gold because it's easier to implement. 819 uint32_t ScriptParser::parseFill(StringRef Tok) { 820 uint32_t V = 0; 821 if (!to_integer(Tok, V)) 822 setError("invalid filler expression: " + Tok); 823 824 uint32_t Buf; 825 write32be(&Buf, V); 826 return Buf; 827 } 828 829 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) { 830 expect("("); 831 SymbolAssignment *Cmd = readSymbolAssignment(next()); 832 Cmd->Provide = Provide; 833 Cmd->Hidden = Hidden; 834 expect(")"); 835 return Cmd; 836 } 837 838 SymbolAssignment *ScriptParser::readAssignment(StringRef Tok) { 839 // Assert expression returns Dot, so this is equal to ".=." 840 if (Tok == "ASSERT") 841 return make<SymbolAssignment>(".", readAssert(), getCurrentLocation()); 842 843 size_t OldPos = Pos; 844 SymbolAssignment *Cmd = nullptr; 845 if (peek() == "=" || peek() == "+=") 846 Cmd = readSymbolAssignment(Tok); 847 else if (Tok == "PROVIDE") 848 Cmd = readProvideHidden(true, false); 849 else if (Tok == "HIDDEN") 850 Cmd = readProvideHidden(false, true); 851 else if (Tok == "PROVIDE_HIDDEN") 852 Cmd = readProvideHidden(true, true); 853 854 if (Cmd) { 855 Cmd->CommandString = 856 Tok.str() + " " + 857 llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " "); 858 expect(";"); 859 } 860 return Cmd; 861 } 862 863 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef Name) { 864 StringRef Op = next(); 865 assert(Op == "=" || Op == "+="); 866 Expr E = readExpr(); 867 if (Op == "+=") { 868 std::string Loc = getCurrentLocation(); 869 E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); }; 870 } 871 return make<SymbolAssignment>(Name, E, getCurrentLocation()); 872 } 873 874 // This is an operator-precedence parser to parse a linker 875 // script expression. 876 Expr ScriptParser::readExpr() { 877 // Our lexer is context-aware. Set the in-expression bit so that 878 // they apply different tokenization rules. 879 bool Orig = InExpr; 880 InExpr = true; 881 Expr E = readExpr1(readPrimary(), 0); 882 InExpr = Orig; 883 return E; 884 } 885 886 Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) { 887 if (Op == "+") 888 return [=] { return add(L(), R()); }; 889 if (Op == "-") 890 return [=] { return sub(L(), R()); }; 891 if (Op == "*") 892 return [=] { return L().getValue() * R().getValue(); }; 893 if (Op == "/") { 894 std::string Loc = getCurrentLocation(); 895 return [=]() -> uint64_t { 896 if (uint64_t RV = R().getValue()) 897 return L().getValue() / RV; 898 error(Loc + ": division by zero"); 899 return 0; 900 }; 901 } 902 if (Op == "%") { 903 std::string Loc = getCurrentLocation(); 904 return [=]() -> uint64_t { 905 if (uint64_t RV = R().getValue()) 906 return L().getValue() % RV; 907 error(Loc + ": modulo by zero"); 908 return 0; 909 }; 910 } 911 if (Op == "<<") 912 return [=] { return L().getValue() << R().getValue(); }; 913 if (Op == ">>") 914 return [=] { return L().getValue() >> R().getValue(); }; 915 if (Op == "<") 916 return [=] { return L().getValue() < R().getValue(); }; 917 if (Op == ">") 918 return [=] { return L().getValue() > R().getValue(); }; 919 if (Op == ">=") 920 return [=] { return L().getValue() >= R().getValue(); }; 921 if (Op == "<=") 922 return [=] { return L().getValue() <= R().getValue(); }; 923 if (Op == "==") 924 return [=] { return L().getValue() == R().getValue(); }; 925 if (Op == "!=") 926 return [=] { return L().getValue() != R().getValue(); }; 927 if (Op == "&") 928 return [=] { return bitAnd(L(), R()); }; 929 if (Op == "|") 930 return [=] { return bitOr(L(), R()); }; 931 llvm_unreachable("invalid operator"); 932 } 933 934 // This is a part of the operator-precedence parser. This function 935 // assumes that the remaining token stream starts with an operator. 936 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) { 937 while (!atEOF() && !errorCount()) { 938 // Read an operator and an expression. 939 if (consume("?")) 940 return readTernary(Lhs); 941 StringRef Op1 = peek(); 942 if (precedence(Op1) < MinPrec) 943 break; 944 skip(); 945 Expr Rhs = readPrimary(); 946 947 // Evaluate the remaining part of the expression first if the 948 // next operator has greater precedence than the previous one. 949 // For example, if we have read "+" and "3", and if the next 950 // operator is "*", then we'll evaluate 3 * ... part first. 951 while (!atEOF()) { 952 StringRef Op2 = peek(); 953 if (precedence(Op2) <= precedence(Op1)) 954 break; 955 Rhs = readExpr1(Rhs, precedence(Op2)); 956 } 957 958 Lhs = combine(Op1, Lhs, Rhs); 959 } 960 return Lhs; 961 } 962 963 Expr ScriptParser::getPageSize() { 964 std::string Location = getCurrentLocation(); 965 return [=]() -> uint64_t { 966 if (Target) 967 return Target->PageSize; 968 error(Location + ": unable to calculate page size"); 969 return 4096; // Return a dummy value. 970 }; 971 } 972 973 Expr ScriptParser::readConstant() { 974 StringRef S = readParenLiteral(); 975 if (S == "COMMONPAGESIZE") 976 return getPageSize(); 977 if (S == "MAXPAGESIZE") 978 return [] { return Config->MaxPageSize; }; 979 setError("unknown constant: " + S); 980 return [] { return 0; }; 981 } 982 983 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with 984 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may 985 // have "K" (Ki) or "M" (Mi) suffixes. 986 static Optional<uint64_t> parseInt(StringRef Tok) { 987 // Hexadecimal 988 uint64_t Val; 989 if (Tok.startswith_lower("0x")) { 990 if (!to_integer(Tok.substr(2), Val, 16)) 991 return None; 992 return Val; 993 } 994 if (Tok.endswith_lower("H")) { 995 if (!to_integer(Tok.drop_back(), Val, 16)) 996 return None; 997 return Val; 998 } 999 1000 // Decimal 1001 if (Tok.endswith_lower("K")) { 1002 if (!to_integer(Tok.drop_back(), Val, 10)) 1003 return None; 1004 return Val * 1024; 1005 } 1006 if (Tok.endswith_lower("M")) { 1007 if (!to_integer(Tok.drop_back(), Val, 10)) 1008 return None; 1009 return Val * 1024 * 1024; 1010 } 1011 if (!to_integer(Tok, Val, 10)) 1012 return None; 1013 return Val; 1014 } 1015 1016 ByteCommand *ScriptParser::readByteCommand(StringRef Tok) { 1017 int Size = StringSwitch<int>(Tok) 1018 .Case("BYTE", 1) 1019 .Case("SHORT", 2) 1020 .Case("LONG", 4) 1021 .Case("QUAD", 8) 1022 .Default(-1); 1023 if (Size == -1) 1024 return nullptr; 1025 1026 size_t OldPos = Pos; 1027 Expr E = readParenExpr(); 1028 std::string CommandString = 1029 Tok.str() + " " + 1030 llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " "); 1031 return make<ByteCommand>(E, Size, CommandString); 1032 } 1033 1034 StringRef ScriptParser::readParenLiteral() { 1035 expect("("); 1036 bool Orig = InExpr; 1037 InExpr = false; 1038 StringRef Tok = next(); 1039 InExpr = Orig; 1040 expect(")"); 1041 return Tok; 1042 } 1043 1044 static void checkIfExists(OutputSection *Cmd, StringRef Location) { 1045 if (Cmd->Location.empty() && Script->ErrorOnMissingSection) 1046 error(Location + ": undefined section " + Cmd->Name); 1047 } 1048 1049 Expr ScriptParser::readPrimary() { 1050 if (peek() == "(") 1051 return readParenExpr(); 1052 1053 if (consume("~")) { 1054 Expr E = readPrimary(); 1055 return [=] { return ~E().getValue(); }; 1056 } 1057 if (consume("!")) { 1058 Expr E = readPrimary(); 1059 return [=] { return !E().getValue(); }; 1060 } 1061 if (consume("-")) { 1062 Expr E = readPrimary(); 1063 return [=] { return -E().getValue(); }; 1064 } 1065 1066 StringRef Tok = next(); 1067 std::string Location = getCurrentLocation(); 1068 1069 // Built-in functions are parsed here. 1070 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. 1071 if (Tok == "ABSOLUTE") { 1072 Expr Inner = readParenExpr(); 1073 return [=] { 1074 ExprValue I = Inner(); 1075 I.ForceAbsolute = true; 1076 return I; 1077 }; 1078 } 1079 if (Tok == "ADDR") { 1080 StringRef Name = readParenLiteral(); 1081 OutputSection *Sec = Script->getOrCreateOutputSection(Name); 1082 return [=]() -> ExprValue { 1083 checkIfExists(Sec, Location); 1084 return {Sec, false, 0, Location}; 1085 }; 1086 } 1087 if (Tok == "ALIGN") { 1088 expect("("); 1089 Expr E = readExpr(); 1090 if (consume(")")) { 1091 E = checkAlignment(E, Location); 1092 return [=] { return alignTo(Script->getDot(), E().getValue()); }; 1093 } 1094 expect(","); 1095 Expr E2 = checkAlignment(readExpr(), Location); 1096 expect(")"); 1097 return [=] { 1098 ExprValue V = E(); 1099 V.Alignment = E2().getValue(); 1100 return V; 1101 }; 1102 } 1103 if (Tok == "ALIGNOF") { 1104 StringRef Name = readParenLiteral(); 1105 OutputSection *Cmd = Script->getOrCreateOutputSection(Name); 1106 return [=] { 1107 checkIfExists(Cmd, Location); 1108 return Cmd->Alignment; 1109 }; 1110 } 1111 if (Tok == "ASSERT") 1112 return readAssert(); 1113 if (Tok == "CONSTANT") 1114 return readConstant(); 1115 if (Tok == "DATA_SEGMENT_ALIGN") { 1116 expect("("); 1117 Expr E = readExpr(); 1118 expect(","); 1119 readExpr(); 1120 expect(")"); 1121 return [=] { 1122 return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue())); 1123 }; 1124 } 1125 if (Tok == "DATA_SEGMENT_END") { 1126 expect("("); 1127 expect("."); 1128 expect(")"); 1129 return [] { return Script->getDot(); }; 1130 } 1131 if (Tok == "DATA_SEGMENT_RELRO_END") { 1132 // GNU linkers implements more complicated logic to handle 1133 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and 1134 // just align to the next page boundary for simplicity. 1135 expect("("); 1136 readExpr(); 1137 expect(","); 1138 readExpr(); 1139 expect(")"); 1140 Expr E = getPageSize(); 1141 return [=] { return alignTo(Script->getDot(), E().getValue()); }; 1142 } 1143 if (Tok == "DEFINED") { 1144 StringRef Name = readParenLiteral(); 1145 return [=] { return Symtab->find(Name) ? 1 : 0; }; 1146 } 1147 if (Tok == "LENGTH") { 1148 StringRef Name = readParenLiteral(); 1149 if (Script->MemoryRegions.count(Name) == 0) { 1150 setError("memory region not defined: " + Name); 1151 return [] { return 0; }; 1152 } 1153 return [=] { return Script->MemoryRegions[Name]->Length; }; 1154 } 1155 if (Tok == "LOADADDR") { 1156 StringRef Name = readParenLiteral(); 1157 OutputSection *Cmd = Script->getOrCreateOutputSection(Name); 1158 return [=] { 1159 checkIfExists(Cmd, Location); 1160 return Cmd->getLMA(); 1161 }; 1162 } 1163 if (Tok == "MAX" || Tok == "MIN") { 1164 expect("("); 1165 Expr A = readExpr(); 1166 expect(","); 1167 Expr B = readExpr(); 1168 expect(")"); 1169 if (Tok == "MIN") 1170 return [=] { return std::min(A().getValue(), B().getValue()); }; 1171 return [=] { return std::max(A().getValue(), B().getValue()); }; 1172 } 1173 if (Tok == "ORIGIN") { 1174 StringRef Name = readParenLiteral(); 1175 if (Script->MemoryRegions.count(Name) == 0) { 1176 setError("memory region not defined: " + Name); 1177 return [] { return 0; }; 1178 } 1179 return [=] { return Script->MemoryRegions[Name]->Origin; }; 1180 } 1181 if (Tok == "SEGMENT_START") { 1182 expect("("); 1183 skip(); 1184 expect(","); 1185 Expr E = readExpr(); 1186 expect(")"); 1187 return [=] { return E(); }; 1188 } 1189 if (Tok == "SIZEOF") { 1190 StringRef Name = readParenLiteral(); 1191 OutputSection *Cmd = Script->getOrCreateOutputSection(Name); 1192 // Linker script does not create an output section if its content is empty. 1193 // We want to allow SIZEOF(.foo) where .foo is a section which happened to 1194 // be empty. 1195 return [=] { return Cmd->Size; }; 1196 } 1197 if (Tok == "SIZEOF_HEADERS") 1198 return [=] { return elf::getHeaderSize(); }; 1199 1200 // Tok is the dot. 1201 if (Tok == ".") 1202 return [=] { return Script->getSymbolValue(Tok, Location); }; 1203 1204 // Tok is a literal number. 1205 if (Optional<uint64_t> Val = parseInt(Tok)) 1206 return [=] { return *Val; }; 1207 1208 // Tok is a symbol name. 1209 if (!isValidCIdentifier(Tok)) 1210 setError("malformed number: " + Tok); 1211 Script->ReferencedSymbols.push_back(Tok); 1212 return [=] { return Script->getSymbolValue(Tok, Location); }; 1213 } 1214 1215 Expr ScriptParser::readTernary(Expr Cond) { 1216 Expr L = readExpr(); 1217 expect(":"); 1218 Expr R = readExpr(); 1219 return [=] { return Cond().getValue() ? L() : R(); }; 1220 } 1221 1222 Expr ScriptParser::readParenExpr() { 1223 expect("("); 1224 Expr E = readExpr(); 1225 expect(")"); 1226 return E; 1227 } 1228 1229 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() { 1230 std::vector<StringRef> Phdrs; 1231 while (!errorCount() && peek().startswith(":")) { 1232 StringRef Tok = next(); 1233 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1)); 1234 } 1235 return Phdrs; 1236 } 1237 1238 // Read a program header type name. The next token must be a 1239 // name of a program header type or a constant (e.g. "0x3"). 1240 unsigned ScriptParser::readPhdrType() { 1241 StringRef Tok = next(); 1242 if (Optional<uint64_t> Val = parseInt(Tok)) 1243 return *Val; 1244 1245 unsigned Ret = StringSwitch<unsigned>(Tok) 1246 .Case("PT_NULL", PT_NULL) 1247 .Case("PT_LOAD", PT_LOAD) 1248 .Case("PT_DYNAMIC", PT_DYNAMIC) 1249 .Case("PT_INTERP", PT_INTERP) 1250 .Case("PT_NOTE", PT_NOTE) 1251 .Case("PT_SHLIB", PT_SHLIB) 1252 .Case("PT_PHDR", PT_PHDR) 1253 .Case("PT_TLS", PT_TLS) 1254 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) 1255 .Case("PT_GNU_STACK", PT_GNU_STACK) 1256 .Case("PT_GNU_RELRO", PT_GNU_RELRO) 1257 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE) 1258 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED) 1259 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA) 1260 .Default(-1); 1261 1262 if (Ret == (unsigned)-1) { 1263 setError("invalid program header type: " + Tok); 1264 return PT_NULL; 1265 } 1266 return Ret; 1267 } 1268 1269 // Reads an anonymous version declaration. 1270 void ScriptParser::readAnonymousDeclaration() { 1271 std::vector<SymbolVersion> Locals; 1272 std::vector<SymbolVersion> Globals; 1273 std::tie(Locals, Globals) = readSymbols(); 1274 1275 for (SymbolVersion V : Locals) { 1276 if (V.Name == "*") 1277 Config->DefaultSymbolVersion = VER_NDX_LOCAL; 1278 else 1279 Config->VersionScriptLocals.push_back(V); 1280 } 1281 1282 for (SymbolVersion V : Globals) 1283 Config->VersionScriptGlobals.push_back(V); 1284 1285 expect(";"); 1286 } 1287 1288 // Reads a non-anonymous version definition, 1289 // e.g. "VerStr { global: foo; bar; local: *; };". 1290 void ScriptParser::readVersionDeclaration(StringRef VerStr) { 1291 // Read a symbol list. 1292 std::vector<SymbolVersion> Locals; 1293 std::vector<SymbolVersion> Globals; 1294 std::tie(Locals, Globals) = readSymbols(); 1295 1296 for (SymbolVersion V : Locals) { 1297 if (V.Name == "*") 1298 Config->DefaultSymbolVersion = VER_NDX_LOCAL; 1299 else 1300 Config->VersionScriptLocals.push_back(V); 1301 } 1302 1303 // Create a new version definition and add that to the global symbols. 1304 VersionDefinition Ver; 1305 Ver.Name = VerStr; 1306 Ver.Globals = Globals; 1307 1308 // User-defined version number starts from 2 because 0 and 1 are 1309 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively. 1310 Ver.Id = Config->VersionDefinitions.size() + 2; 1311 Config->VersionDefinitions.push_back(Ver); 1312 1313 // Each version may have a parent version. For example, "Ver2" 1314 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" 1315 // as a parent. This version hierarchy is, probably against your 1316 // instinct, purely for hint; the runtime doesn't care about it 1317 // at all. In LLD, we simply ignore it. 1318 if (peek() != ";") 1319 skip(); 1320 expect(";"); 1321 } 1322 1323 static bool hasWildcard(StringRef S) { 1324 return S.find_first_of("?*[") != StringRef::npos; 1325 } 1326 1327 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };". 1328 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>> 1329 ScriptParser::readSymbols() { 1330 std::vector<SymbolVersion> Locals; 1331 std::vector<SymbolVersion> Globals; 1332 std::vector<SymbolVersion> *V = &Globals; 1333 1334 while (!errorCount()) { 1335 if (consume("}")) 1336 break; 1337 if (consumeLabel("local")) { 1338 V = &Locals; 1339 continue; 1340 } 1341 if (consumeLabel("global")) { 1342 V = &Globals; 1343 continue; 1344 } 1345 1346 if (consume("extern")) { 1347 std::vector<SymbolVersion> Ext = readVersionExtern(); 1348 V->insert(V->end(), Ext.begin(), Ext.end()); 1349 } else { 1350 StringRef Tok = next(); 1351 V->push_back({unquote(Tok), false, hasWildcard(Tok)}); 1352 } 1353 expect(";"); 1354 } 1355 return {Locals, Globals}; 1356 } 1357 1358 // Reads an "extern C++" directive, e.g., 1359 // "extern "C++" { ns::*; "f(int, double)"; };" 1360 // 1361 // The last semicolon is optional. E.g. this is OK: 1362 // "extern "C++" { ns::*; "f(int, double)" };" 1363 std::vector<SymbolVersion> ScriptParser::readVersionExtern() { 1364 StringRef Tok = next(); 1365 bool IsCXX = Tok == "\"C++\""; 1366 if (!IsCXX && Tok != "\"C\"") 1367 setError("Unknown language"); 1368 expect("{"); 1369 1370 std::vector<SymbolVersion> Ret; 1371 while (!errorCount() && peek() != "}") { 1372 StringRef Tok = next(); 1373 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok); 1374 Ret.push_back({unquote(Tok), IsCXX, HasWildcard}); 1375 if (consume("}")) 1376 return Ret; 1377 expect(";"); 1378 } 1379 1380 expect("}"); 1381 return Ret; 1382 } 1383 1384 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2, 1385 StringRef S3) { 1386 if (!consume(S1) && !consume(S2) && !consume(S3)) { 1387 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3); 1388 return 0; 1389 } 1390 expect("="); 1391 return readExpr()().getValue(); 1392 } 1393 1394 // Parse the MEMORY command as specified in: 1395 // https://sourceware.org/binutils/docs/ld/MEMORY.html 1396 // 1397 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... } 1398 void ScriptParser::readMemory() { 1399 expect("{"); 1400 while (!errorCount() && !consume("}")) { 1401 StringRef Name = next(); 1402 1403 uint32_t Flags = 0; 1404 uint32_t NegFlags = 0; 1405 if (consume("(")) { 1406 std::tie(Flags, NegFlags) = readMemoryAttributes(); 1407 expect(")"); 1408 } 1409 expect(":"); 1410 1411 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o"); 1412 expect(","); 1413 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l"); 1414 1415 // Add the memory region to the region map. 1416 MemoryRegion *MR = 1417 make<MemoryRegion>(Name, Origin, Length, Flags, NegFlags); 1418 if (!Script->MemoryRegions.insert({Name, MR}).second) 1419 setError("region '" + Name + "' already defined"); 1420 } 1421 } 1422 1423 // This function parses the attributes used to match against section 1424 // flags when placing output sections in a memory region. These flags 1425 // are only used when an explicit memory region name is not used. 1426 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() { 1427 uint32_t Flags = 0; 1428 uint32_t NegFlags = 0; 1429 bool Invert = false; 1430 1431 for (char C : next().lower()) { 1432 uint32_t Flag = 0; 1433 if (C == '!') 1434 Invert = !Invert; 1435 else if (C == 'w') 1436 Flag = SHF_WRITE; 1437 else if (C == 'x') 1438 Flag = SHF_EXECINSTR; 1439 else if (C == 'a') 1440 Flag = SHF_ALLOC; 1441 else if (C != 'r') 1442 setError("invalid memory region attribute"); 1443 1444 if (Invert) 1445 NegFlags |= Flag; 1446 else 1447 Flags |= Flag; 1448 } 1449 return {Flags, NegFlags}; 1450 } 1451 1452 void elf::readLinkerScript(MemoryBufferRef MB) { 1453 ScriptParser(MB).readLinkerScript(); 1454 } 1455 1456 void elf::readVersionScript(MemoryBufferRef MB) { 1457 ScriptParser(MB).readVersionScript(); 1458 } 1459 1460 void elf::readDynamicList(MemoryBufferRef MB) { 1461 ScriptParser(MB).readDynamicList(); 1462 } 1463 1464 void elf::readDefsym(StringRef Name, MemoryBufferRef MB) { 1465 ScriptParser(MB).readDefsym(Name); 1466 } 1467