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 "Error.h" 19 #include "Memory.h" 20 #include "Symbols.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(EC, "unable to find " + Prog + " in PATH"); 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 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]". 132 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major, 133 uint32_t *Minor) { 134 StringRef SysStr, Ver; 135 std::tie(SysStr, Ver) = Arg.split(','); 136 *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower()) 137 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION) 138 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI) 139 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION) 140 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER) 141 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM) 142 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) 143 .Case("native", IMAGE_SUBSYSTEM_NATIVE) 144 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI) 145 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI) 146 .Default(IMAGE_SUBSYSTEM_UNKNOWN); 147 if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN) 148 fatal("unknown subsystem: " + SysStr); 149 if (!Ver.empty()) 150 parseVersion(Ver, Major, Minor); 151 } 152 153 // Parse a string of the form of "<from>=<to>". 154 // Results are directly written to Config. 155 void parseAlternateName(StringRef S) { 156 StringRef From, To; 157 std::tie(From, To) = S.split('='); 158 if (From.empty() || To.empty()) 159 fatal("/alternatename: invalid argument: " + S); 160 auto It = Config->AlternateNames.find(From); 161 if (It != Config->AlternateNames.end() && It->second != To) 162 fatal("/alternatename: conflicts: " + S); 163 Config->AlternateNames.insert(It, std::make_pair(From, To)); 164 } 165 166 // Parse a string of the form of "<from>=<to>". 167 // Results are directly written to Config. 168 void parseMerge(StringRef S) { 169 StringRef From, To; 170 std::tie(From, To) = S.split('='); 171 if (From.empty() || To.empty()) 172 fatal("/merge: invalid argument: " + S); 173 auto Pair = Config->Merge.insert(std::make_pair(From, To)); 174 bool Inserted = Pair.second; 175 if (!Inserted) { 176 StringRef Existing = Pair.first->second; 177 if (Existing != To) 178 warn(S + ": already merged into " + Existing); 179 } 180 } 181 182 static uint32_t parseSectionAttributes(StringRef S) { 183 uint32_t Ret = 0; 184 for (char C : S.lower()) { 185 switch (C) { 186 case 'd': 187 Ret |= IMAGE_SCN_MEM_DISCARDABLE; 188 break; 189 case 'e': 190 Ret |= IMAGE_SCN_MEM_EXECUTE; 191 break; 192 case 'k': 193 Ret |= IMAGE_SCN_MEM_NOT_CACHED; 194 break; 195 case 'p': 196 Ret |= IMAGE_SCN_MEM_NOT_PAGED; 197 break; 198 case 'r': 199 Ret |= IMAGE_SCN_MEM_READ; 200 break; 201 case 's': 202 Ret |= IMAGE_SCN_MEM_SHARED; 203 break; 204 case 'w': 205 Ret |= IMAGE_SCN_MEM_WRITE; 206 break; 207 default: 208 fatal("/section: invalid argument: " + S); 209 } 210 } 211 return Ret; 212 } 213 214 // Parses /section option argument. 215 void parseSection(StringRef S) { 216 StringRef Name, Attrs; 217 std::tie(Name, Attrs) = S.split(','); 218 if (Name.empty() || Attrs.empty()) 219 fatal("/section: invalid argument: " + S); 220 Config->Section[Name] = parseSectionAttributes(Attrs); 221 } 222 223 // Parses /aligncomm option argument. 224 void parseAligncomm(StringRef S) { 225 StringRef Name, Align; 226 std::tie(Name, Align) = S.split(','); 227 if (Name.empty() || Align.empty()) { 228 error("/aligncomm: invalid argument: " + S); 229 return; 230 } 231 int V; 232 if (Align.getAsInteger(0, V)) { 233 error("/aligncomm: invalid argument: " + S); 234 return; 235 } 236 Config->AlignComm[Name] = std::max(Config->AlignComm[Name], 1 << V); 237 } 238 239 // Parses a string in the form of "EMBED[,=<integer>]|NO". 240 // Results are directly written to Config. 241 void parseManifest(StringRef Arg) { 242 if (Arg.equals_lower("no")) { 243 Config->Manifest = Configuration::No; 244 return; 245 } 246 if (!Arg.startswith_lower("embed")) 247 fatal("invalid option " + Arg); 248 Config->Manifest = Configuration::Embed; 249 Arg = Arg.substr(strlen("embed")); 250 if (Arg.empty()) 251 return; 252 if (!Arg.startswith_lower(",id=")) 253 fatal("invalid option " + Arg); 254 Arg = Arg.substr(strlen(",id=")); 255 if (Arg.getAsInteger(0, Config->ManifestID)) 256 fatal("invalid option " + Arg); 257 } 258 259 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO". 260 // Results are directly written to Config. 261 void parseManifestUAC(StringRef Arg) { 262 if (Arg.equals_lower("no")) { 263 Config->ManifestUAC = false; 264 return; 265 } 266 for (;;) { 267 Arg = Arg.ltrim(); 268 if (Arg.empty()) 269 return; 270 if (Arg.startswith_lower("level=")) { 271 Arg = Arg.substr(strlen("level=")); 272 std::tie(Config->ManifestLevel, Arg) = Arg.split(" "); 273 continue; 274 } 275 if (Arg.startswith_lower("uiaccess=")) { 276 Arg = Arg.substr(strlen("uiaccess=")); 277 std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" "); 278 continue; 279 } 280 fatal("invalid option " + Arg); 281 } 282 } 283 284 // An RAII temporary file class that automatically removes a temporary file. 285 namespace { 286 class TemporaryFile { 287 public: 288 TemporaryFile(StringRef Prefix, StringRef Extn, StringRef Contents = "") { 289 SmallString<128> S; 290 if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S)) 291 fatal(EC, "cannot create a temporary file"); 292 Path = S.str(); 293 294 if (!Contents.empty()) { 295 std::error_code EC; 296 raw_fd_ostream OS(Path, EC, sys::fs::F_None); 297 if (EC) 298 fatal(EC, "failed to open " + Path); 299 OS << Contents; 300 } 301 } 302 303 TemporaryFile(TemporaryFile &&Obj) { 304 std::swap(Path, Obj.Path); 305 } 306 307 ~TemporaryFile() { 308 if (Path.empty()) 309 return; 310 if (sys::fs::remove(Path)) 311 fatal("failed to remove " + Path); 312 } 313 314 // Returns a memory buffer of this temporary file. 315 // Note that this function does not leave the file open, 316 // so it is safe to remove the file immediately after this function 317 // is called (you cannot remove an opened file on Windows.) 318 std::unique_ptr<MemoryBuffer> getMemoryBuffer() { 319 // IsVolatileSize=true forces MemoryBuffer to not use mmap(). 320 return check(MemoryBuffer::getFile(Path, /*FileSize=*/-1, 321 /*RequiresNullTerminator=*/false, 322 /*IsVolatileSize=*/true), 323 "could not open " + Path); 324 } 325 326 std::string Path; 327 }; 328 } 329 330 static std::string createDefaultXml() { 331 std::string Ret; 332 raw_string_ostream OS(Ret); 333 334 // Emit the XML. Note that we do *not* verify that the XML attributes are 335 // syntactically correct. This is intentional for link.exe compatibility. 336 OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n" 337 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n" 338 << " manifestVersion=\"1.0\">\n"; 339 if (Config->ManifestUAC) { 340 OS << " <trustInfo>\n" 341 << " <security>\n" 342 << " <requestedPrivileges>\n" 343 << " <requestedExecutionLevel level=" << Config->ManifestLevel 344 << " uiAccess=" << Config->ManifestUIAccess << "/>\n" 345 << " </requestedPrivileges>\n" 346 << " </security>\n" 347 << " </trustInfo>\n"; 348 } 349 if (!Config->ManifestDependency.empty()) { 350 OS << " <dependency>\n" 351 << " <dependentAssembly>\n" 352 << " <assemblyIdentity " << Config->ManifestDependency << " />\n" 353 << " </dependentAssembly>\n" 354 << " </dependency>\n"; 355 } 356 OS << "</assembly>\n"; 357 return OS.str(); 358 } 359 360 static std::string createManifestXmlWithInternalMt(StringRef DefaultXml) { 361 std::unique_ptr<MemoryBuffer> DefaultXmlCopy = 362 MemoryBuffer::getMemBufferCopy(DefaultXml); 363 364 windows_manifest::WindowsManifestMerger Merger; 365 if (auto E = Merger.merge(*DefaultXmlCopy.get())) 366 fatal(E, "internal manifest tool failed on default xml"); 367 368 for (StringRef Filename : Config->ManifestInput) { 369 std::unique_ptr<MemoryBuffer> Manifest = 370 check(MemoryBuffer::getFile(Filename)); 371 if (auto E = Merger.merge(*Manifest.get())) 372 fatal(E, "internal manifest tool failed on file " + Filename); 373 } 374 375 return Merger.getMergedManifest().get()->getBuffer(); 376 } 377 378 static std::string createManifestXmlWithExternalMt(StringRef DefaultXml) { 379 // Create the default manifest file as a temporary file. 380 TemporaryFile Default("defaultxml", "manifest"); 381 std::error_code EC; 382 raw_fd_ostream OS(Default.Path, EC, sys::fs::F_Text); 383 if (EC) 384 fatal(EC, "failed to open " + Default.Path); 385 OS << DefaultXml; 386 OS.close(); 387 388 // Merge user-supplied manifests if they are given. Since libxml2 is not 389 // enabled, we must shell out to Microsoft's mt.exe tool. 390 TemporaryFile User("user", "manifest"); 391 392 Executor E("mt.exe"); 393 E.add("/manifest"); 394 E.add(Default.Path); 395 for (StringRef Filename : Config->ManifestInput) { 396 E.add("/manifest"); 397 E.add(Filename); 398 } 399 E.add("/nologo"); 400 E.add("/out:" + StringRef(User.Path)); 401 E.run(); 402 403 return check(MemoryBuffer::getFile(User.Path), "could not open " + User.Path) 404 .get() 405 ->getBuffer(); 406 } 407 408 static std::string createManifestXml() { 409 std::string DefaultXml = createDefaultXml(); 410 if (Config->ManifestInput.empty()) 411 return DefaultXml; 412 413 if (windows_manifest::isAvailable()) 414 return createManifestXmlWithInternalMt(DefaultXml); 415 416 return createManifestXmlWithExternalMt(DefaultXml); 417 } 418 419 static std::unique_ptr<MemoryBuffer> 420 createMemoryBufferForManifestRes(size_t ManifestSize) { 421 size_t ResSize = alignTo( 422 object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE + 423 sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) + 424 sizeof(object::WinResHeaderSuffix) + ManifestSize, 425 object::WIN_RES_DATA_ALIGNMENT); 426 return MemoryBuffer::getNewMemBuffer(ResSize, 427 Config->OutputFile + ".manifest.res"); 428 } 429 430 static void writeResFileHeader(char *&Buf) { 431 memcpy(Buf, COFF::WinResMagic, sizeof(COFF::WinResMagic)); 432 Buf += sizeof(COFF::WinResMagic); 433 memset(Buf, 0, object::WIN_RES_NULL_ENTRY_SIZE); 434 Buf += object::WIN_RES_NULL_ENTRY_SIZE; 435 } 436 437 static void writeResEntryHeader(char *&Buf, size_t ManifestSize) { 438 // Write the prefix. 439 auto *Prefix = reinterpret_cast<object::WinResHeaderPrefix *>(Buf); 440 Prefix->DataSize = ManifestSize; 441 Prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) + 442 sizeof(object::WinResIDs) + 443 sizeof(object::WinResHeaderSuffix); 444 Buf += sizeof(object::WinResHeaderPrefix); 445 446 // Write the Type/Name IDs. 447 auto *IDs = reinterpret_cast<object::WinResIDs *>(Buf); 448 IDs->setType(RT_MANIFEST); 449 IDs->setName(Config->ManifestID); 450 Buf += sizeof(object::WinResIDs); 451 452 // Write the suffix. 453 auto *Suffix = reinterpret_cast<object::WinResHeaderSuffix *>(Buf); 454 Suffix->DataVersion = 0; 455 Suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE; 456 Suffix->Language = SUBLANG_ENGLISH_US; 457 Suffix->Version = 0; 458 Suffix->Characteristics = 0; 459 Buf += sizeof(object::WinResHeaderSuffix); 460 } 461 462 // Create a resource file containing a manifest XML. 463 std::unique_ptr<MemoryBuffer> createManifestRes() { 464 std::string Manifest = createManifestXml(); 465 466 std::unique_ptr<MemoryBuffer> Res = 467 createMemoryBufferForManifestRes(Manifest.size()); 468 469 char *Buf = const_cast<char *>(Res->getBufferStart()); 470 writeResFileHeader(Buf); 471 writeResEntryHeader(Buf, Manifest.size()); 472 473 // Copy the manifest data into the .res file. 474 std::copy(Manifest.begin(), Manifest.end(), Buf); 475 return Res; 476 } 477 478 void createSideBySideManifest() { 479 std::string Path = Config->ManifestFile; 480 if (Path == "") 481 Path = Config->OutputFile + ".manifest"; 482 std::error_code EC; 483 raw_fd_ostream Out(Path, EC, sys::fs::F_Text); 484 if (EC) 485 fatal(EC, "failed to create manifest"); 486 Out << createManifestXml(); 487 } 488 489 // Parse a string in the form of 490 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]" 491 // or "<name>=<dllname>.<name>". 492 // Used for parsing /export arguments. 493 Export parseExport(StringRef Arg) { 494 Export E; 495 StringRef Rest; 496 std::tie(E.Name, Rest) = Arg.split(","); 497 if (E.Name.empty()) 498 goto err; 499 500 if (E.Name.contains('=')) { 501 StringRef X, Y; 502 std::tie(X, Y) = E.Name.split("="); 503 504 // If "<name>=<dllname>.<name>". 505 if (Y.contains(".")) { 506 E.Name = X; 507 E.ForwardTo = Y; 508 return E; 509 } 510 511 E.ExtName = X; 512 E.Name = Y; 513 if (E.Name.empty()) 514 goto err; 515 } 516 517 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]" 518 while (!Rest.empty()) { 519 StringRef Tok; 520 std::tie(Tok, Rest) = Rest.split(","); 521 if (Tok.equals_lower("noname")) { 522 if (E.Ordinal == 0) 523 goto err; 524 E.Noname = true; 525 continue; 526 } 527 if (Tok.equals_lower("data")) { 528 E.Data = true; 529 continue; 530 } 531 if (Tok.equals_lower("constant")) { 532 E.Constant = true; 533 continue; 534 } 535 if (Tok.equals_lower("private")) { 536 E.Private = true; 537 continue; 538 } 539 if (Tok.startswith("@")) { 540 int32_t Ord; 541 if (Tok.substr(1).getAsInteger(0, Ord)) 542 goto err; 543 if (Ord <= 0 || 65535 < Ord) 544 goto err; 545 E.Ordinal = Ord; 546 continue; 547 } 548 goto err; 549 } 550 return E; 551 552 err: 553 fatal("invalid /export: " + Arg); 554 } 555 556 static StringRef undecorate(StringRef Sym) { 557 if (Config->Machine != I386) 558 return Sym; 559 return Sym.startswith("_") ? Sym.substr(1) : Sym; 560 } 561 562 // Performs error checking on all /export arguments. 563 // It also sets ordinals. 564 void fixupExports() { 565 // Symbol ordinals must be unique. 566 std::set<uint16_t> Ords; 567 for (Export &E : Config->Exports) { 568 if (E.Ordinal == 0) 569 continue; 570 if (!Ords.insert(E.Ordinal).second) 571 fatal("duplicate export ordinal: " + E.Name); 572 } 573 574 for (Export &E : Config->Exports) { 575 SymbolBody *Sym = E.Sym; 576 if (!E.ForwardTo.empty() || !Sym) { 577 E.SymbolName = E.Name; 578 } else { 579 if (auto *U = dyn_cast<Undefined>(Sym)) 580 if (U->WeakAlias) 581 Sym = U->WeakAlias; 582 E.SymbolName = Sym->getName(); 583 } 584 } 585 586 for (Export &E : Config->Exports) { 587 if (!E.ForwardTo.empty()) { 588 E.ExportName = undecorate(E.Name); 589 } else { 590 E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName); 591 } 592 } 593 594 // Uniquefy by name. 595 std::map<StringRef, Export *> Map; 596 std::vector<Export> V; 597 for (Export &E : Config->Exports) { 598 auto Pair = Map.insert(std::make_pair(E.ExportName, &E)); 599 bool Inserted = Pair.second; 600 if (Inserted) { 601 V.push_back(E); 602 continue; 603 } 604 Export *Existing = Pair.first->second; 605 if (E == *Existing || E.Name != Existing->Name) 606 continue; 607 warn("duplicate /export option: " + E.Name); 608 } 609 Config->Exports = std::move(V); 610 611 // Sort by name. 612 std::sort(Config->Exports.begin(), Config->Exports.end(), 613 [](const Export &A, const Export &B) { 614 return A.ExportName < B.ExportName; 615 }); 616 } 617 618 void assignExportOrdinals() { 619 // Assign unique ordinals if default (= 0). 620 uint16_t Max = 0; 621 for (Export &E : Config->Exports) 622 Max = std::max(Max, E.Ordinal); 623 for (Export &E : Config->Exports) 624 if (E.Ordinal == 0) 625 E.Ordinal = ++Max; 626 } 627 628 // Parses a string in the form of "key=value" and check 629 // if value matches previous values for the same key. 630 void checkFailIfMismatch(StringRef Arg) { 631 StringRef K, V; 632 std::tie(K, V) = Arg.split('='); 633 if (K.empty() || V.empty()) 634 fatal("/failifmismatch: invalid argument: " + Arg); 635 StringRef Existing = Config->MustMatch[K]; 636 if (!Existing.empty() && V != Existing) 637 fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V + 638 " for key " + K); 639 Config->MustMatch[K] = V; 640 } 641 642 // Convert Windows resource files (.res files) to a .obj file. 643 MemoryBufferRef convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) { 644 object::WindowsResourceParser Parser; 645 646 for (MemoryBufferRef MB : MBs) { 647 std::unique_ptr<object::Binary> Bin = check(object::createBinary(MB)); 648 object::WindowsResource *RF = dyn_cast<object::WindowsResource>(Bin.get()); 649 if (!RF) 650 fatal("cannot compile non-resource file as resource"); 651 if (auto EC = Parser.parse(RF)) 652 fatal(EC, "failed to parse .res file"); 653 } 654 655 Expected<std::unique_ptr<MemoryBuffer>> E = 656 llvm::object::writeWindowsResourceCOFF(Config->Machine, Parser); 657 if (!E) 658 fatal(errorToErrorCode(E.takeError()), "failed to write .res to COFF"); 659 660 MemoryBufferRef MBRef = **E; 661 make<std::unique_ptr<MemoryBuffer>>(std::move(*E)); // take ownership 662 return MBRef; 663 } 664 665 // Run MSVC link.exe for given in-memory object files. 666 // Command line options are copied from those given to LLD. 667 // This is for the /msvclto option. 668 void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) { 669 // Write the in-memory object files to disk. 670 std::vector<TemporaryFile> Temps; 671 for (StringRef S : Objects) { 672 Temps.emplace_back("lto", "obj", S); 673 Rsp += quote(Temps.back().Path) + "\n"; 674 } 675 676 log("link.exe " + Rsp); 677 678 // Run MSVC link.exe. 679 Temps.emplace_back("lto", "rsp", Rsp); 680 Executor E("link.exe"); 681 E.add(Twine("@" + Temps.back().Path)); 682 E.run(); 683 } 684 685 // Create OptTable 686 687 // Create prefix string literals used in Options.td 688 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; 689 #include "Options.inc" 690 #undef PREFIX 691 692 // Create table mapping all options defined in Options.td 693 static const llvm::opt::OptTable::Info InfoTable[] = { 694 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ 695 {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \ 696 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, 697 #include "Options.inc" 698 #undef OPTION 699 }; 700 701 COFFOptTable::COFFOptTable() : OptTable(InfoTable, true) {} 702 703 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) { 704 if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) { 705 StringRef S = Arg->getValue(); 706 if (S != "windows" && S != "posix") 707 error("invalid response file quoting: " + S); 708 if (S == "windows") 709 return cl::TokenizeWindowsCommandLine; 710 return cl::TokenizeGNUCommandLine; 711 } 712 // The COFF linker always defaults to Windows quoting. 713 return cl::TokenizeWindowsCommandLine; 714 } 715 716 // Parses a given list of options. 717 opt::InputArgList ArgParser::parse(ArrayRef<const char *> Argv) { 718 // Make InputArgList from string vectors. 719 unsigned MissingIndex; 720 unsigned MissingCount; 721 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size()); 722 723 // We need to get the quoting style for response files before parsing all 724 // options so we parse here before and ignore all the options but 725 // --rsp-quoting. 726 opt::InputArgList Args = Table.ParseArgs(Vec, MissingIndex, MissingCount); 727 728 // Expand response files (arguments in the form of @<filename>) 729 // and then parse the argument again. 730 cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec); 731 Args = Table.ParseArgs(Vec, MissingIndex, MissingCount); 732 733 // Print the real command line if response files are expanded. 734 if (Args.hasArg(OPT_verbose) && Argv.size() != Vec.size()) { 735 std::string Msg = "Command line:"; 736 for (const char *S : Vec) 737 Msg += " " + std::string(S); 738 message(Msg); 739 } 740 741 if (MissingCount) 742 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument"); 743 for (auto *Arg : Args.filtered(OPT_UNKNOWN)) 744 warn("ignoring unknown argument: " + Arg->getSpelling()); 745 return Args; 746 } 747 748 // link.exe has an interesting feature. If LINK or _LINK_ environment 749 // variables exist, their contents are handled as command line strings. 750 // So you can pass extra arguments using them. 751 opt::InputArgList ArgParser::parseLINK(std::vector<const char *> Argv) { 752 // Concatenate LINK env and command line arguments, and then parse them. 753 if (Optional<std::string> S = Process::GetEnv("LINK")) { 754 std::vector<const char *> V = tokenize(*S); 755 Argv.insert(Argv.begin(), V.begin(), V.end()); 756 } 757 if (Optional<std::string> S = Process::GetEnv("_LINK_")) { 758 std::vector<const char *> V = tokenize(*S); 759 Argv.insert(Argv.begin(), V.begin(), V.end()); 760 } 761 return parse(Argv); 762 } 763 764 std::vector<const char *> ArgParser::tokenize(StringRef S) { 765 SmallVector<const char *, 16> Tokens; 766 cl::TokenizeWindowsCommandLine(S, Saver, Tokens); 767 return std::vector<const char *>(Tokens.begin(), Tokens.end()); 768 } 769 770 void printHelp(const char *Argv0) { 771 COFFOptTable Table; 772 Table.PrintHelp(outs(), Argv0, "LLVM Linker", false); 773 } 774 775 } // namespace coff 776 } // namespace lld 777