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