1 //===- DriverUtils.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 utility functions for the driver. Because there 11 // are so many small functions, we created this separate file to make 12 // Driver.cpp less cluttered. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "Config.h" 17 #include "Driver.h" 18 #include "Symbols.h" 19 #include "lld/Common/ErrorHandler.h" 20 #include "lld/Common/Memory.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/BinaryFormat/COFF.h" 24 #include "llvm/Object/COFF.h" 25 #include "llvm/Object/WindowsResource.h" 26 #include "llvm/Option/Arg.h" 27 #include "llvm/Option/ArgList.h" 28 #include "llvm/Option/Option.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/FileUtilities.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Support/Process.h" 33 #include "llvm/Support/Program.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/WindowsManifest/WindowsManifestMerger.h" 36 #include <memory> 37 38 using namespace llvm::COFF; 39 using namespace llvm; 40 using llvm::sys::Process; 41 42 namespace lld { 43 namespace coff { 44 namespace { 45 46 const uint16_t SUBLANG_ENGLISH_US = 0x0409; 47 const uint16_t RT_MANIFEST = 24; 48 49 class Executor { 50 public: 51 explicit Executor(StringRef S) : Prog(Saver.save(S)) {} 52 void add(StringRef S) { Args.push_back(Saver.save(S)); } 53 void add(std::string &S) { Args.push_back(Saver.save(S)); } 54 void add(Twine S) { Args.push_back(Saver.save(S)); } 55 void add(const char *S) { Args.push_back(Saver.save(S)); } 56 57 void run() { 58 ErrorOr<std::string> ExeOrErr = sys::findProgramByName(Prog); 59 if (auto EC = ExeOrErr.getError()) 60 fatal("unable to find " + Prog + " in PATH: " + EC.message()); 61 StringRef Exe = Saver.save(*ExeOrErr); 62 Args.insert(Args.begin(), Exe); 63 64 std::vector<const char *> Vec; 65 for (StringRef S : Args) 66 Vec.push_back(S.data()); 67 Vec.push_back(nullptr); 68 69 if (sys::ExecuteAndWait(Args[0], Vec.data()) != 0) 70 fatal("ExecuteAndWait failed: " + 71 llvm::join(Args.begin(), Args.end(), " ")); 72 } 73 74 private: 75 StringRef Prog; 76 std::vector<StringRef> Args; 77 }; 78 79 } // anonymous namespace 80 81 // Returns /machine's value. 82 MachineTypes getMachineType(StringRef S) { 83 MachineTypes MT = StringSwitch<MachineTypes>(S.lower()) 84 .Cases("x64", "amd64", AMD64) 85 .Cases("x86", "i386", I386) 86 .Case("arm", ARMNT) 87 .Case("arm64", ARM64) 88 .Default(IMAGE_FILE_MACHINE_UNKNOWN); 89 if (MT != IMAGE_FILE_MACHINE_UNKNOWN) 90 return MT; 91 fatal("unknown /machine argument: " + S); 92 } 93 94 StringRef machineToStr(MachineTypes MT) { 95 switch (MT) { 96 case ARMNT: 97 return "arm"; 98 case ARM64: 99 return "arm64"; 100 case AMD64: 101 return "x64"; 102 case I386: 103 return "x86"; 104 default: 105 llvm_unreachable("unknown machine type"); 106 } 107 } 108 109 // Parses a string in the form of "<integer>[,<integer>]". 110 void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) { 111 StringRef S1, S2; 112 std::tie(S1, S2) = Arg.split(','); 113 if (S1.getAsInteger(0, *Addr)) 114 fatal("invalid number: " + S1); 115 if (Size && !S2.empty() && S2.getAsInteger(0, *Size)) 116 fatal("invalid number: " + S2); 117 } 118 119 // Parses a string in the form of "<integer>[.<integer>]". 120 // If second number is not present, Minor is set to 0. 121 void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) { 122 StringRef S1, S2; 123 std::tie(S1, S2) = Arg.split('.'); 124 if (S1.getAsInteger(0, *Major)) 125 fatal("invalid number: " + S1); 126 *Minor = 0; 127 if (!S2.empty() && S2.getAsInteger(0, *Minor)) 128 fatal("invalid number: " + S2); 129 } 130 131 void parseGuard(StringRef FullArg) { 132 SmallVector<StringRef, 1> SplitArgs; 133 FullArg.split(SplitArgs, ","); 134 for (StringRef Arg : SplitArgs) { 135 if (Arg.equals_lower("no")) 136 Config->GuardCF = GuardCFLevel::Off; 137 else if (Arg.equals_lower("nolongjmp")) 138 Config->GuardCF = GuardCFLevel::NoLongJmp; 139 else if (Arg.equals_lower("cf") || Arg.equals_lower("longjmp")) 140 Config->GuardCF = GuardCFLevel::Full; 141 else 142 fatal("invalid argument to /guard: " + Arg); 143 } 144 } 145 146 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]". 147 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major, 148 uint32_t *Minor) { 149 StringRef SysStr, Ver; 150 std::tie(SysStr, Ver) = Arg.split(','); 151 *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower()) 152 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION) 153 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI) 154 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION) 155 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER) 156 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM) 157 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) 158 .Case("native", IMAGE_SUBSYSTEM_NATIVE) 159 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI) 160 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI) 161 .Default(IMAGE_SUBSYSTEM_UNKNOWN); 162 if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN) 163 fatal("unknown subsystem: " + SysStr); 164 if (!Ver.empty()) 165 parseVersion(Ver, Major, Minor); 166 } 167 168 // Parse a string of the form of "<from>=<to>". 169 // Results are directly written to Config. 170 void parseAlternateName(StringRef S) { 171 StringRef From, To; 172 std::tie(From, To) = S.split('='); 173 if (From.empty() || To.empty()) 174 fatal("/alternatename: invalid argument: " + S); 175 auto It = Config->AlternateNames.find(From); 176 if (It != Config->AlternateNames.end() && It->second != To) 177 fatal("/alternatename: conflicts: " + S); 178 Config->AlternateNames.insert(It, std::make_pair(From, To)); 179 } 180 181 // Parse a string of the form of "<from>=<to>". 182 // Results are directly written to Config. 183 void parseMerge(StringRef S) { 184 StringRef From, To; 185 std::tie(From, To) = S.split('='); 186 if (From.empty() || To.empty()) 187 fatal("/merge: invalid argument: " + S); 188 auto Pair = Config->Merge.insert(std::make_pair(From, To)); 189 bool Inserted = Pair.second; 190 if (!Inserted) { 191 StringRef Existing = Pair.first->second; 192 if (Existing != To) 193 warn(S + ": already merged into " + Existing); 194 } 195 } 196 197 static uint32_t parseSectionAttributes(StringRef S) { 198 uint32_t Ret = 0; 199 for (char C : S.lower()) { 200 switch (C) { 201 case 'd': 202 Ret |= IMAGE_SCN_MEM_DISCARDABLE; 203 break; 204 case 'e': 205 Ret |= IMAGE_SCN_MEM_EXECUTE; 206 break; 207 case 'k': 208 Ret |= IMAGE_SCN_MEM_NOT_CACHED; 209 break; 210 case 'p': 211 Ret |= IMAGE_SCN_MEM_NOT_PAGED; 212 break; 213 case 'r': 214 Ret |= IMAGE_SCN_MEM_READ; 215 break; 216 case 's': 217 Ret |= IMAGE_SCN_MEM_SHARED; 218 break; 219 case 'w': 220 Ret |= IMAGE_SCN_MEM_WRITE; 221 break; 222 default: 223 fatal("/section: invalid argument: " + S); 224 } 225 } 226 return Ret; 227 } 228 229 // Parses /section option argument. 230 void parseSection(StringRef S) { 231 StringRef Name, Attrs; 232 std::tie(Name, Attrs) = S.split(','); 233 if (Name.empty() || Attrs.empty()) 234 fatal("/section: invalid argument: " + S); 235 Config->Section[Name] = parseSectionAttributes(Attrs); 236 } 237 238 // Parses /aligncomm option argument. 239 void parseAligncomm(StringRef S) { 240 StringRef Name, Align; 241 std::tie(Name, Align) = S.split(','); 242 if (Name.empty() || Align.empty()) { 243 error("/aligncomm: invalid argument: " + S); 244 return; 245 } 246 int V; 247 if (Align.getAsInteger(0, V)) { 248 error("/aligncomm: invalid argument: " + S); 249 return; 250 } 251 Config->AlignComm[Name] = std::max(Config->AlignComm[Name], 1 << V); 252 } 253 254 // Parses a string in the form of "EMBED[,=<integer>]|NO". 255 // Results are directly written to Config. 256 void parseManifest(StringRef Arg) { 257 if (Arg.equals_lower("no")) { 258 Config->Manifest = Configuration::No; 259 return; 260 } 261 if (!Arg.startswith_lower("embed")) 262 fatal("invalid option " + Arg); 263 Config->Manifest = Configuration::Embed; 264 Arg = Arg.substr(strlen("embed")); 265 if (Arg.empty()) 266 return; 267 if (!Arg.startswith_lower(",id=")) 268 fatal("invalid option " + Arg); 269 Arg = Arg.substr(strlen(",id=")); 270 if (Arg.getAsInteger(0, Config->ManifestID)) 271 fatal("invalid option " + Arg); 272 } 273 274 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO". 275 // Results are directly written to Config. 276 void parseManifestUAC(StringRef Arg) { 277 if (Arg.equals_lower("no")) { 278 Config->ManifestUAC = false; 279 return; 280 } 281 for (;;) { 282 Arg = Arg.ltrim(); 283 if (Arg.empty()) 284 return; 285 if (Arg.startswith_lower("level=")) { 286 Arg = Arg.substr(strlen("level=")); 287 std::tie(Config->ManifestLevel, Arg) = Arg.split(" "); 288 continue; 289 } 290 if (Arg.startswith_lower("uiaccess=")) { 291 Arg = Arg.substr(strlen("uiaccess=")); 292 std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" "); 293 continue; 294 } 295 fatal("invalid option " + Arg); 296 } 297 } 298 299 // An RAII temporary file class that automatically removes a temporary file. 300 namespace { 301 class TemporaryFile { 302 public: 303 TemporaryFile(StringRef Prefix, StringRef Extn, StringRef Contents = "") { 304 SmallString<128> S; 305 if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S)) 306 fatal("cannot create a temporary file: " + EC.message()); 307 Path = S.str(); 308 309 if (!Contents.empty()) { 310 std::error_code EC; 311 raw_fd_ostream OS(Path, EC, sys::fs::F_None); 312 if (EC) 313 fatal("failed to open " + Path + ": " + EC.message()); 314 OS << Contents; 315 } 316 } 317 318 TemporaryFile(TemporaryFile &&Obj) { 319 std::swap(Path, Obj.Path); 320 } 321 322 ~TemporaryFile() { 323 if (Path.empty()) 324 return; 325 if (sys::fs::remove(Path)) 326 fatal("failed to remove " + Path); 327 } 328 329 // Returns a memory buffer of this temporary file. 330 // Note that this function does not leave the file open, 331 // so it is safe to remove the file immediately after this function 332 // is called (you cannot remove an opened file on Windows.) 333 std::unique_ptr<MemoryBuffer> getMemoryBuffer() { 334 // IsVolatileSize=true forces MemoryBuffer to not use mmap(). 335 return CHECK(MemoryBuffer::getFile(Path, /*FileSize=*/-1, 336 /*RequiresNullTerminator=*/false, 337 /*IsVolatileSize=*/true), 338 "could not open " + Path); 339 } 340 341 std::string Path; 342 }; 343 } 344 345 static std::string createDefaultXml() { 346 std::string Ret; 347 raw_string_ostream OS(Ret); 348 349 // Emit the XML. Note that we do *not* verify that the XML attributes are 350 // syntactically correct. This is intentional for link.exe compatibility. 351 OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n" 352 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n" 353 << " manifestVersion=\"1.0\">\n"; 354 if (Config->ManifestUAC) { 355 OS << " <trustInfo>\n" 356 << " <security>\n" 357 << " <requestedPrivileges>\n" 358 << " <requestedExecutionLevel level=" << Config->ManifestLevel 359 << " uiAccess=" << Config->ManifestUIAccess << "/>\n" 360 << " </requestedPrivileges>\n" 361 << " </security>\n" 362 << " </trustInfo>\n"; 363 } 364 if (!Config->ManifestDependency.empty()) { 365 OS << " <dependency>\n" 366 << " <dependentAssembly>\n" 367 << " <assemblyIdentity " << Config->ManifestDependency << " />\n" 368 << " </dependentAssembly>\n" 369 << " </dependency>\n"; 370 } 371 OS << "</assembly>\n"; 372 return OS.str(); 373 } 374 375 static std::string createManifestXmlWithInternalMt(StringRef DefaultXml) { 376 std::unique_ptr<MemoryBuffer> DefaultXmlCopy = 377 MemoryBuffer::getMemBufferCopy(DefaultXml); 378 379 windows_manifest::WindowsManifestMerger Merger; 380 if (auto E = Merger.merge(*DefaultXmlCopy.get())) 381 fatal("internal manifest tool failed on default xml: " + 382 toString(std::move(E))); 383 384 for (StringRef Filename : Config->ManifestInput) { 385 std::unique_ptr<MemoryBuffer> Manifest = 386 check(MemoryBuffer::getFile(Filename)); 387 if (auto E = Merger.merge(*Manifest.get())) 388 fatal("internal manifest tool failed on file " + Filename + ": " + 389 toString(std::move(E))); 390 } 391 392 return Merger.getMergedManifest().get()->getBuffer(); 393 } 394 395 static std::string createManifestXmlWithExternalMt(StringRef DefaultXml) { 396 // Create the default manifest file as a temporary file. 397 TemporaryFile Default("defaultxml", "manifest"); 398 std::error_code EC; 399 raw_fd_ostream OS(Default.Path, EC, sys::fs::F_Text); 400 if (EC) 401 fatal("failed to open " + Default.Path + ": " + EC.message()); 402 OS << DefaultXml; 403 OS.close(); 404 405 // Merge user-supplied manifests if they are given. Since libxml2 is not 406 // enabled, we must shell out to Microsoft's mt.exe tool. 407 TemporaryFile User("user", "manifest"); 408 409 Executor E("mt.exe"); 410 E.add("/manifest"); 411 E.add(Default.Path); 412 for (StringRef Filename : Config->ManifestInput) { 413 E.add("/manifest"); 414 E.add(Filename); 415 } 416 E.add("/nologo"); 417 E.add("/out:" + StringRef(User.Path)); 418 E.run(); 419 420 return CHECK(MemoryBuffer::getFile(User.Path), "could not open " + User.Path) 421 .get() 422 ->getBuffer(); 423 } 424 425 static std::string createManifestXml() { 426 std::string DefaultXml = createDefaultXml(); 427 if (Config->ManifestInput.empty()) 428 return DefaultXml; 429 430 if (windows_manifest::isAvailable()) 431 return createManifestXmlWithInternalMt(DefaultXml); 432 433 return createManifestXmlWithExternalMt(DefaultXml); 434 } 435 436 static std::unique_ptr<WritableMemoryBuffer> 437 createMemoryBufferForManifestRes(size_t ManifestSize) { 438 size_t ResSize = alignTo( 439 object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE + 440 sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) + 441 sizeof(object::WinResHeaderSuffix) + ManifestSize, 442 object::WIN_RES_DATA_ALIGNMENT); 443 return WritableMemoryBuffer::getNewMemBuffer(ResSize, Config->OutputFile + 444 ".manifest.res"); 445 } 446 447 static void writeResFileHeader(char *&Buf) { 448 memcpy(Buf, COFF::WinResMagic, sizeof(COFF::WinResMagic)); 449 Buf += sizeof(COFF::WinResMagic); 450 memset(Buf, 0, object::WIN_RES_NULL_ENTRY_SIZE); 451 Buf += object::WIN_RES_NULL_ENTRY_SIZE; 452 } 453 454 static void writeResEntryHeader(char *&Buf, size_t ManifestSize) { 455 // Write the prefix. 456 auto *Prefix = reinterpret_cast<object::WinResHeaderPrefix *>(Buf); 457 Prefix->DataSize = ManifestSize; 458 Prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) + 459 sizeof(object::WinResIDs) + 460 sizeof(object::WinResHeaderSuffix); 461 Buf += sizeof(object::WinResHeaderPrefix); 462 463 // Write the Type/Name IDs. 464 auto *IDs = reinterpret_cast<object::WinResIDs *>(Buf); 465 IDs->setType(RT_MANIFEST); 466 IDs->setName(Config->ManifestID); 467 Buf += sizeof(object::WinResIDs); 468 469 // Write the suffix. 470 auto *Suffix = reinterpret_cast<object::WinResHeaderSuffix *>(Buf); 471 Suffix->DataVersion = 0; 472 Suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE; 473 Suffix->Language = SUBLANG_ENGLISH_US; 474 Suffix->Version = 0; 475 Suffix->Characteristics = 0; 476 Buf += sizeof(object::WinResHeaderSuffix); 477 } 478 479 // Create a resource file containing a manifest XML. 480 std::unique_ptr<MemoryBuffer> createManifestRes() { 481 std::string Manifest = createManifestXml(); 482 483 std::unique_ptr<WritableMemoryBuffer> Res = 484 createMemoryBufferForManifestRes(Manifest.size()); 485 486 char *Buf = Res->getBufferStart(); 487 writeResFileHeader(Buf); 488 writeResEntryHeader(Buf, Manifest.size()); 489 490 // Copy the manifest data into the .res file. 491 std::copy(Manifest.begin(), Manifest.end(), Buf); 492 return std::move(Res); 493 } 494 495 void createSideBySideManifest() { 496 std::string Path = Config->ManifestFile; 497 if (Path == "") 498 Path = Config->OutputFile + ".manifest"; 499 std::error_code EC; 500 raw_fd_ostream Out(Path, EC, sys::fs::F_Text); 501 if (EC) 502 fatal("failed to create manifest: " + EC.message()); 503 Out << createManifestXml(); 504 } 505 506 // Parse a string in the form of 507 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]" 508 // or "<name>=<dllname>.<name>". 509 // Used for parsing /export arguments. 510 Export parseExport(StringRef Arg) { 511 Export E; 512 StringRef Rest; 513 std::tie(E.Name, Rest) = Arg.split(","); 514 if (E.Name.empty()) 515 goto err; 516 517 if (E.Name.contains('=')) { 518 StringRef X, Y; 519 std::tie(X, Y) = E.Name.split("="); 520 521 // If "<name>=<dllname>.<name>". 522 if (Y.contains(".")) { 523 E.Name = X; 524 E.ForwardTo = Y; 525 return E; 526 } 527 528 E.ExtName = X; 529 E.Name = Y; 530 if (E.Name.empty()) 531 goto err; 532 } 533 534 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]" 535 while (!Rest.empty()) { 536 StringRef Tok; 537 std::tie(Tok, Rest) = Rest.split(","); 538 if (Tok.equals_lower("noname")) { 539 if (E.Ordinal == 0) 540 goto err; 541 E.Noname = true; 542 continue; 543 } 544 if (Tok.equals_lower("data")) { 545 E.Data = true; 546 continue; 547 } 548 if (Tok.equals_lower("constant")) { 549 E.Constant = true; 550 continue; 551 } 552 if (Tok.equals_lower("private")) { 553 E.Private = true; 554 continue; 555 } 556 if (Tok.startswith("@")) { 557 int32_t Ord; 558 if (Tok.substr(1).getAsInteger(0, Ord)) 559 goto err; 560 if (Ord <= 0 || 65535 < Ord) 561 goto err; 562 E.Ordinal = Ord; 563 continue; 564 } 565 goto err; 566 } 567 return E; 568 569 err: 570 fatal("invalid /export: " + Arg); 571 } 572 573 static StringRef undecorate(StringRef Sym) { 574 if (Config->Machine != I386) 575 return Sym; 576 // In MSVC mode, a fully decorated stdcall function is exported 577 // as-is with the leading underscore (with type IMPORT_NAME). 578 // In MinGW mode, a decorated stdcall function gets the underscore 579 // removed, just like normal cdecl functions. 580 if (Sym.startswith("_") && Sym.contains('@') && !Config->MinGW) 581 return Sym; 582 return Sym.startswith("_") ? Sym.substr(1) : Sym; 583 } 584 585 // Convert stdcall/fastcall style symbols into unsuffixed symbols, 586 // with or without a leading underscore. (MinGW specific.) 587 static StringRef killAt(StringRef Sym, bool Prefix) { 588 if (Sym.empty()) 589 return Sym; 590 // Strip any trailing stdcall suffix 591 Sym = Sym.substr(0, Sym.find('@', 1)); 592 if (!Sym.startswith("@")) { 593 if (Prefix && !Sym.startswith("_")) 594 return Saver.save("_" + Sym); 595 return Sym; 596 } 597 // For fastcall, remove the leading @ and replace it with an 598 // underscore, if prefixes are used. 599 Sym = Sym.substr(1); 600 if (Prefix) 601 Sym = Saver.save("_" + Sym); 602 return Sym; 603 } 604 605 // Performs error checking on all /export arguments. 606 // It also sets ordinals. 607 void fixupExports() { 608 // Symbol ordinals must be unique. 609 std::set<uint16_t> Ords; 610 for (Export &E : Config->Exports) { 611 if (E.Ordinal == 0) 612 continue; 613 if (!Ords.insert(E.Ordinal).second) 614 fatal("duplicate export ordinal: " + E.Name); 615 } 616 617 for (Export &E : Config->Exports) { 618 Symbol *Sym = E.Sym; 619 if (!E.ForwardTo.empty() || !Sym) { 620 E.SymbolName = E.Name; 621 } else { 622 if (auto *U = dyn_cast<Undefined>(Sym)) 623 if (U->WeakAlias) 624 Sym = U->WeakAlias; 625 E.SymbolName = Sym->getName(); 626 } 627 } 628 629 for (Export &E : Config->Exports) { 630 if (!E.ForwardTo.empty()) { 631 E.ExportName = undecorate(E.Name); 632 } else { 633 E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName); 634 } 635 } 636 637 if (Config->KillAt && Config->Machine == I386) { 638 for (Export &E : Config->Exports) { 639 E.Name = killAt(E.Name, true); 640 E.ExportName = killAt(E.ExportName, false); 641 E.ExtName = killAt(E.ExtName, true); 642 E.SymbolName = killAt(E.SymbolName, true); 643 } 644 } 645 646 // Uniquefy by name. 647 DenseMap<StringRef, Export *> Map(Config->Exports.size()); 648 std::vector<Export> V; 649 for (Export &E : Config->Exports) { 650 auto Pair = Map.insert(std::make_pair(E.ExportName, &E)); 651 bool Inserted = Pair.second; 652 if (Inserted) { 653 V.push_back(E); 654 continue; 655 } 656 Export *Existing = Pair.first->second; 657 if (E == *Existing || E.Name != Existing->Name) 658 continue; 659 warn("duplicate /export option: " + E.Name); 660 } 661 Config->Exports = std::move(V); 662 663 // Sort by name. 664 std::sort(Config->Exports.begin(), Config->Exports.end(), 665 [](const Export &A, const Export &B) { 666 return A.ExportName < B.ExportName; 667 }); 668 } 669 670 void assignExportOrdinals() { 671 // Assign unique ordinals if default (= 0). 672 uint16_t Max = 0; 673 for (Export &E : Config->Exports) 674 Max = std::max(Max, E.Ordinal); 675 for (Export &E : Config->Exports) 676 if (E.Ordinal == 0) 677 E.Ordinal = ++Max; 678 } 679 680 // Parses a string in the form of "key=value" and check 681 // if value matches previous values for the same key. 682 void checkFailIfMismatch(StringRef Arg) { 683 StringRef K, V; 684 std::tie(K, V) = Arg.split('='); 685 if (K.empty() || V.empty()) 686 fatal("/failifmismatch: invalid argument: " + Arg); 687 StringRef Existing = Config->MustMatch[K]; 688 if (!Existing.empty() && V != Existing) 689 fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V + 690 " for key " + K); 691 Config->MustMatch[K] = V; 692 } 693 694 // Convert Windows resource files (.res files) to a .obj file. 695 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> MBs) { 696 object::WindowsResourceParser Parser; 697 698 for (MemoryBufferRef MB : MBs) { 699 std::unique_ptr<object::Binary> Bin = check(object::createBinary(MB)); 700 object::WindowsResource *RF = dyn_cast<object::WindowsResource>(Bin.get()); 701 if (!RF) 702 fatal("cannot compile non-resource file as resource"); 703 if (auto EC = Parser.parse(RF)) 704 fatal("failed to parse .res file: " + toString(std::move(EC))); 705 } 706 707 Expected<std::unique_ptr<MemoryBuffer>> E = 708 llvm::object::writeWindowsResourceCOFF(Config->Machine, Parser); 709 if (!E) 710 fatal("failed to write .res to COFF: " + toString(E.takeError())); 711 712 MemoryBufferRef MBRef = **E; 713 make<std::unique_ptr<MemoryBuffer>>(std::move(*E)); // take ownership 714 return MBRef; 715 } 716 717 // Run MSVC link.exe for given in-memory object files. 718 // Command line options are copied from those given to LLD. 719 // This is for the /msvclto option. 720 void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) { 721 // Write the in-memory object files to disk. 722 std::vector<TemporaryFile> Temps; 723 for (StringRef S : Objects) { 724 Temps.emplace_back("lto", "obj", S); 725 Rsp += quote(Temps.back().Path) + "\n"; 726 } 727 728 log("link.exe " + Rsp); 729 730 // Run MSVC link.exe. 731 Temps.emplace_back("lto", "rsp", Rsp); 732 Executor E("link.exe"); 733 E.add(Twine("@" + Temps.back().Path)); 734 E.run(); 735 } 736 737 // Create OptTable 738 739 // Create prefix string literals used in Options.td 740 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; 741 #include "Options.inc" 742 #undef PREFIX 743 744 // Create table mapping all options defined in Options.td 745 static const llvm::opt::OptTable::Info InfoTable[] = { 746 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ 747 {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \ 748 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, 749 #include "Options.inc" 750 #undef OPTION 751 }; 752 753 COFFOptTable::COFFOptTable() : OptTable(InfoTable, true) {} 754 755 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) { 756 if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) { 757 StringRef S = Arg->getValue(); 758 if (S != "windows" && S != "posix") 759 error("invalid response file quoting: " + S); 760 if (S == "windows") 761 return cl::TokenizeWindowsCommandLine; 762 return cl::TokenizeGNUCommandLine; 763 } 764 // The COFF linker always defaults to Windows quoting. 765 return cl::TokenizeWindowsCommandLine; 766 } 767 768 // Parses a given list of options. 769 opt::InputArgList ArgParser::parse(ArrayRef<const char *> Argv) { 770 // Make InputArgList from string vectors. 771 unsigned MissingIndex; 772 unsigned MissingCount; 773 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size()); 774 775 // We need to get the quoting style for response files before parsing all 776 // options so we parse here before and ignore all the options but 777 // --rsp-quoting. 778 opt::InputArgList Args = Table.ParseArgs(Vec, MissingIndex, MissingCount); 779 780 // Expand response files (arguments in the form of @<filename>) 781 // and then parse the argument again. 782 cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec); 783 Args = Table.ParseArgs(Vec, MissingIndex, MissingCount); 784 785 // Print the real command line if response files are expanded. 786 if (Args.hasArg(OPT_verbose) && Argv.size() != Vec.size()) { 787 std::string Msg = "Command line:"; 788 for (const char *S : Vec) 789 Msg += " " + std::string(S); 790 message(Msg); 791 } 792 793 // Handle /WX early since it converts missing argument warnings to errors. 794 errorHandler().FatalWarnings = Args.hasFlag(OPT_WX, OPT_WX_no, false); 795 796 if (MissingCount) 797 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument"); 798 for (auto *Arg : Args.filtered(OPT_UNKNOWN)) 799 warn("ignoring unknown argument: " + Arg->getSpelling()); 800 return Args; 801 } 802 803 // Tokenizes and parses a given string as command line in .drective section. 804 // /EXPORT options are processed in fastpath. 805 std::pair<opt::InputArgList, std::vector<StringRef>> 806 ArgParser::parseDirectives(StringRef S) { 807 std::vector<StringRef> Exports; 808 SmallVector<const char *, 16> Rest; 809 810 for (StringRef Tok : tokenize(S)) { 811 if (Tok.startswith_lower("/export:") || Tok.startswith_lower("-export:")) 812 Exports.push_back(Tok.substr(strlen("/export:"))); 813 else 814 Rest.push_back(Tok.data()); 815 } 816 817 // Make InputArgList from unparsed string vectors. 818 unsigned MissingIndex; 819 unsigned MissingCount; 820 821 opt::InputArgList Args = Table.ParseArgs(Rest, MissingIndex, MissingCount); 822 823 if (MissingCount) 824 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument"); 825 for (auto *Arg : Args.filtered(OPT_UNKNOWN)) 826 warn("ignoring unknown argument: " + Arg->getSpelling()); 827 return {std::move(Args), std::move(Exports)}; 828 } 829 830 // link.exe has an interesting feature. If LINK or _LINK_ environment 831 // variables exist, their contents are handled as command line strings. 832 // So you can pass extra arguments using them. 833 opt::InputArgList ArgParser::parseLINK(std::vector<const char *> Argv) { 834 // Concatenate LINK env and command line arguments, and then parse them. 835 if (Optional<std::string> S = Process::GetEnv("LINK")) { 836 std::vector<const char *> V = tokenize(*S); 837 Argv.insert(Argv.begin(), V.begin(), V.end()); 838 } 839 if (Optional<std::string> S = Process::GetEnv("_LINK_")) { 840 std::vector<const char *> V = tokenize(*S); 841 Argv.insert(Argv.begin(), V.begin(), V.end()); 842 } 843 return parse(Argv); 844 } 845 846 std::vector<const char *> ArgParser::tokenize(StringRef S) { 847 SmallVector<const char *, 16> Tokens; 848 cl::TokenizeWindowsCommandLine(S, Saver, Tokens); 849 return std::vector<const char *>(Tokens.begin(), Tokens.end()); 850 } 851 852 void printHelp(const char *Argv0) { 853 COFFOptTable().PrintHelp(outs(), Argv0, "LLVM Linker", false); 854 } 855 856 } // namespace coff 857 } // namespace lld 858