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