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