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