1 //===- Driver.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 #include "Driver.h" 10 #include "Config.h" 11 #include "DebugTypes.h" 12 #include "ICF.h" 13 #include "InputFiles.h" 14 #include "MarkLive.h" 15 #include "MinGW.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "Writer.h" 19 #include "lld/Common/Args.h" 20 #include "lld/Common/Driver.h" 21 #include "lld/Common/ErrorHandler.h" 22 #include "lld/Common/Filesystem.h" 23 #include "lld/Common/Memory.h" 24 #include "lld/Common/Timer.h" 25 #include "lld/Common/Version.h" 26 #include "llvm/ADT/Optional.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/BinaryFormat/Magic.h" 29 #include "llvm/Config/llvm-config.h" 30 #include "llvm/LTO/LTO.h" 31 #include "llvm/Object/ArchiveWriter.h" 32 #include "llvm/Object/COFFImportFile.h" 33 #include "llvm/Object/COFFModuleDefinition.h" 34 #include "llvm/Object/WindowsMachineFlag.h" 35 #include "llvm/Option/Arg.h" 36 #include "llvm/Option/ArgList.h" 37 #include "llvm/Option/Option.h" 38 #include "llvm/Support/BinaryStreamReader.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/LEB128.h" 42 #include "llvm/Support/MathExtras.h" 43 #include "llvm/Support/Parallel.h" 44 #include "llvm/Support/Path.h" 45 #include "llvm/Support/Process.h" 46 #include "llvm/Support/TarWriter.h" 47 #include "llvm/Support/TargetSelect.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 50 #include <algorithm> 51 #include <future> 52 #include <memory> 53 54 using namespace llvm; 55 using namespace llvm::object; 56 using namespace llvm::COFF; 57 using namespace llvm::sys; 58 59 namespace lld { 60 namespace coff { 61 62 static Timer inputFileTimer("Input File Reading", Timer::root()); 63 64 Configuration *config; 65 LinkerDriver *driver; 66 67 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS, 68 raw_ostream &stderrOS) { 69 lld::stdoutOS = &stdoutOS; 70 lld::stderrOS = &stderrOS; 71 72 errorHandler().cleanupCallback = []() { 73 TpiSource::clear(); 74 freeArena(); 75 ObjFile::instances.clear(); 76 PDBInputFile::instances.clear(); 77 ImportFile::instances.clear(); 78 BitcodeFile::instances.clear(); 79 memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances)); 80 OutputSection::clear(); 81 }; 82 83 errorHandler().logName = args::getFilenameWithoutExe(args[0]); 84 errorHandler().errorLimitExceededMsg = 85 "too many errors emitted, stopping now" 86 " (use /errorlimit:0 to see all errors)"; 87 errorHandler().exitEarly = canExitEarly; 88 stderrOS.enable_colors(stderrOS.has_colors()); 89 90 config = make<Configuration>(); 91 symtab = make<SymbolTable>(); 92 driver = make<LinkerDriver>(); 93 94 driver->linkerMain(args); 95 96 // Call exit() if we can to avoid calling destructors. 97 if (canExitEarly) 98 exitLld(errorCount() ? 1 : 0); 99 100 bool ret = errorCount() == 0; 101 if (!canExitEarly) 102 errorHandler().reset(); 103 return ret; 104 } 105 106 // Parse options of the form "old;new". 107 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 108 unsigned id) { 109 auto *arg = args.getLastArg(id); 110 if (!arg) 111 return {"", ""}; 112 113 StringRef s = arg->getValue(); 114 std::pair<StringRef, StringRef> ret = s.split(';'); 115 if (ret.second.empty()) 116 error(arg->getSpelling() + " expects 'old;new' format, but got " + s); 117 return ret; 118 } 119 120 // Drop directory components and replace extension with 121 // ".exe", ".dll" or ".sys". 122 static std::string getOutputPath(StringRef path) { 123 StringRef ext = ".exe"; 124 if (config->dll) 125 ext = ".dll"; 126 else if (config->driver) 127 ext = ".sys"; 128 129 return (sys::path::stem(path) + ext).str(); 130 } 131 132 // Returns true if S matches /crtend.?\.o$/. 133 static bool isCrtend(StringRef s) { 134 if (!s.endswith(".o")) 135 return false; 136 s = s.drop_back(2); 137 if (s.endswith("crtend")) 138 return true; 139 return !s.empty() && s.drop_back().endswith("crtend"); 140 } 141 142 // ErrorOr is not default constructible, so it cannot be used as the type 143 // parameter of a future. 144 // FIXME: We could open the file in createFutureForFile and avoid needing to 145 // return an error here, but for the moment that would cost us a file descriptor 146 // (a limited resource on Windows) for the duration that the future is pending. 147 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>; 148 149 // Create a std::future that opens and maps a file using the best strategy for 150 // the host platform. 151 static std::future<MBErrPair> createFutureForFile(std::string path) { 152 #if _WIN64 153 // On Windows, file I/O is relatively slow so it is best to do this 154 // asynchronously. But 32-bit has issues with potentially launching tons 155 // of threads 156 auto strategy = std::launch::async; 157 #else 158 auto strategy = std::launch::deferred; 159 #endif 160 return std::async(strategy, [=]() { 161 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 162 /*RequiresNullTerminator=*/false); 163 if (!mbOrErr) 164 return MBErrPair{nullptr, mbOrErr.getError()}; 165 return MBErrPair{std::move(*mbOrErr), std::error_code()}; 166 }); 167 } 168 169 // Symbol names are mangled by prepending "_" on x86. 170 static StringRef mangle(StringRef sym) { 171 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN); 172 if (config->machine == I386) 173 return saver.save("_" + sym); 174 return sym; 175 } 176 177 static bool findUnderscoreMangle(StringRef sym) { 178 Symbol *s = symtab->findMangle(mangle(sym)); 179 return s && !isa<Undefined>(s); 180 } 181 182 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) { 183 MemoryBufferRef mbref = *mb; 184 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership 185 186 if (driver->tar) 187 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()), 188 mbref.getBuffer()); 189 return mbref; 190 } 191 192 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb, 193 bool wholeArchive, bool lazy) { 194 StringRef filename = mb->getBufferIdentifier(); 195 196 MemoryBufferRef mbref = takeBuffer(std::move(mb)); 197 filePaths.push_back(filename); 198 199 // File type is detected by contents, not by file extension. 200 switch (identify_magic(mbref.getBuffer())) { 201 case file_magic::windows_resource: 202 resources.push_back(mbref); 203 break; 204 case file_magic::archive: 205 if (wholeArchive) { 206 std::unique_ptr<Archive> file = 207 CHECK(Archive::create(mbref), filename + ": failed to parse archive"); 208 Archive *archive = file.get(); 209 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership 210 211 int memberIndex = 0; 212 for (MemoryBufferRef m : getArchiveMembers(archive)) 213 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++); 214 return; 215 } 216 symtab->addFile(make<ArchiveFile>(mbref)); 217 break; 218 case file_magic::bitcode: 219 if (lazy) 220 symtab->addFile(make<LazyObjFile>(mbref)); 221 else 222 symtab->addFile(make<BitcodeFile>(mbref, "", 0)); 223 break; 224 case file_magic::coff_object: 225 case file_magic::coff_import_library: 226 if (lazy) 227 symtab->addFile(make<LazyObjFile>(mbref)); 228 else 229 symtab->addFile(make<ObjFile>(mbref)); 230 break; 231 case file_magic::pdb: 232 symtab->addFile(make<PDBInputFile>(mbref)); 233 break; 234 case file_magic::coff_cl_gl_object: 235 error(filename + ": is not a native COFF file. Recompile without /GL"); 236 break; 237 case file_magic::pecoff_executable: 238 if (config->mingw) { 239 symtab->addFile(make<DLLFile>(mbref)); 240 break; 241 } 242 if (filename.endswith_insensitive(".dll")) { 243 error(filename + ": bad file type. Did you specify a DLL instead of an " 244 "import library?"); 245 break; 246 } 247 LLVM_FALLTHROUGH; 248 default: 249 error(mbref.getBufferIdentifier() + ": unknown file type"); 250 break; 251 } 252 } 253 254 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) { 255 auto future = std::make_shared<std::future<MBErrPair>>( 256 createFutureForFile(std::string(path))); 257 std::string pathStr = std::string(path); 258 enqueueTask([=]() { 259 auto mbOrErr = future->get(); 260 if (mbOrErr.second) { 261 std::string msg = 262 "could not open '" + pathStr + "': " + mbOrErr.second.message(); 263 // Check if the filename is a typo for an option flag. OptTable thinks 264 // that all args that are not known options and that start with / are 265 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for 266 // the option `/nodefaultlib` than a reference to a file in the root 267 // directory. 268 std::string nearest; 269 if (optTable.findNearest(pathStr, nearest) > 1) 270 error(msg); 271 else 272 error(msg + "; did you mean '" + nearest + "'"); 273 } else 274 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy); 275 }); 276 } 277 278 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName, 279 StringRef parentName, 280 uint64_t offsetInArchive) { 281 file_magic magic = identify_magic(mb.getBuffer()); 282 if (magic == file_magic::coff_import_library) { 283 InputFile *imp = make<ImportFile>(mb); 284 imp->parentName = parentName; 285 symtab->addFile(imp); 286 return; 287 } 288 289 InputFile *obj; 290 if (magic == file_magic::coff_object) { 291 obj = make<ObjFile>(mb); 292 } else if (magic == file_magic::bitcode) { 293 obj = make<BitcodeFile>(mb, parentName, offsetInArchive); 294 } else { 295 error("unknown file type: " + mb.getBufferIdentifier()); 296 return; 297 } 298 299 obj->parentName = parentName; 300 symtab->addFile(obj); 301 log("Loaded " + toString(obj) + " for " + symName); 302 } 303 304 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c, 305 const Archive::Symbol &sym, 306 StringRef parentName) { 307 308 auto reportBufferError = [=](Error &&e, StringRef childName) { 309 fatal("could not get the buffer for the member defining symbol " + 310 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " + 311 toString(std::move(e))); 312 }; 313 314 if (!c.getParent()->isThin()) { 315 uint64_t offsetInArchive = c.getChildOffset(); 316 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef(); 317 if (!mbOrErr) 318 reportBufferError(mbOrErr.takeError(), check(c.getFullName())); 319 MemoryBufferRef mb = mbOrErr.get(); 320 enqueueTask([=]() { 321 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName, 322 offsetInArchive); 323 }); 324 return; 325 } 326 327 std::string childName = CHECK( 328 c.getFullName(), 329 "could not get the filename for the member defining symbol " + 330 toCOFFString(sym)); 331 auto future = std::make_shared<std::future<MBErrPair>>( 332 createFutureForFile(childName)); 333 enqueueTask([=]() { 334 auto mbOrErr = future->get(); 335 if (mbOrErr.second) 336 reportBufferError(errorCodeToError(mbOrErr.second), childName); 337 // Pass empty string as archive name so that the original filename is 338 // used as the buffer identifier. 339 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), 340 toCOFFString(sym), "", /*OffsetInArchive=*/0); 341 }); 342 } 343 344 static bool isDecorated(StringRef sym) { 345 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") || 346 (!config->mingw && sym.contains('@')); 347 } 348 349 // Parses .drectve section contents and returns a list of files 350 // specified by /defaultlib. 351 void LinkerDriver::parseDirectives(InputFile *file) { 352 StringRef s = file->getDirectives(); 353 if (s.empty()) 354 return; 355 356 log("Directives: " + toString(file) + ": " + s); 357 358 ArgParser parser; 359 // .drectve is always tokenized using Windows shell rules. 360 // /EXPORT: option can appear too many times, processing in fastpath. 361 ParsedDirectives directives = parser.parseDirectives(s); 362 363 for (StringRef e : directives.exports) { 364 // If a common header file contains dllexported function 365 // declarations, many object files may end up with having the 366 // same /EXPORT options. In order to save cost of parsing them, 367 // we dedup them first. 368 if (!directivesExports.insert(e).second) 369 continue; 370 371 Export exp = parseExport(e); 372 if (config->machine == I386 && config->mingw) { 373 if (!isDecorated(exp.name)) 374 exp.name = saver.save("_" + exp.name); 375 if (!exp.extName.empty() && !isDecorated(exp.extName)) 376 exp.extName = saver.save("_" + exp.extName); 377 } 378 exp.directives = true; 379 config->exports.push_back(exp); 380 } 381 382 // Handle /include: in bulk. 383 for (StringRef inc : directives.includes) 384 addUndefined(inc); 385 386 for (auto *arg : directives.args) { 387 switch (arg->getOption().getID()) { 388 case OPT_aligncomm: 389 parseAligncomm(arg->getValue()); 390 break; 391 case OPT_alternatename: 392 parseAlternateName(arg->getValue()); 393 break; 394 case OPT_defaultlib: 395 if (Optional<StringRef> path = findLib(arg->getValue())) 396 enqueuePath(*path, false, false); 397 break; 398 case OPT_entry: 399 config->entry = addUndefined(mangle(arg->getValue())); 400 break; 401 case OPT_failifmismatch: 402 checkFailIfMismatch(arg->getValue(), file); 403 break; 404 case OPT_incl: 405 addUndefined(arg->getValue()); 406 break; 407 case OPT_merge: 408 parseMerge(arg->getValue()); 409 break; 410 case OPT_nodefaultlib: 411 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 412 break; 413 case OPT_section: 414 parseSection(arg->getValue()); 415 break; 416 case OPT_stack: 417 parseNumbers(arg->getValue(), &config->stackReserve, 418 &config->stackCommit); 419 break; 420 case OPT_subsystem: { 421 bool gotVersion = false; 422 parseSubsystem(arg->getValue(), &config->subsystem, 423 &config->majorSubsystemVersion, 424 &config->minorSubsystemVersion, &gotVersion); 425 if (gotVersion) { 426 config->majorOSVersion = config->majorSubsystemVersion; 427 config->minorOSVersion = config->minorSubsystemVersion; 428 } 429 break; 430 } 431 // Only add flags here that link.exe accepts in 432 // `#pragma comment(linker, "/flag")`-generated sections. 433 case OPT_editandcontinue: 434 case OPT_guardsym: 435 case OPT_throwingnew: 436 break; 437 default: 438 error(arg->getSpelling() + " is not allowed in .drectve"); 439 } 440 } 441 } 442 443 // Find file from search paths. You can omit ".obj", this function takes 444 // care of that. Note that the returned path is not guaranteed to exist. 445 StringRef LinkerDriver::doFindFile(StringRef filename) { 446 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 447 if (hasPathSep) 448 return filename; 449 bool hasExt = filename.contains('.'); 450 for (StringRef dir : searchPaths) { 451 SmallString<128> path = dir; 452 sys::path::append(path, filename); 453 if (sys::fs::exists(path.str())) 454 return saver.save(path.str()); 455 if (!hasExt) { 456 path.append(".obj"); 457 if (sys::fs::exists(path.str())) 458 return saver.save(path.str()); 459 } 460 } 461 return filename; 462 } 463 464 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 465 sys::fs::UniqueID ret; 466 if (sys::fs::getUniqueID(path, ret)) 467 return None; 468 return ret; 469 } 470 471 // Resolves a file path. This never returns the same path 472 // (in that case, it returns None). 473 Optional<StringRef> LinkerDriver::findFile(StringRef filename) { 474 StringRef path = doFindFile(filename); 475 476 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) { 477 bool seen = !visitedFiles.insert(*id).second; 478 if (seen) 479 return None; 480 } 481 482 if (path.endswith_insensitive(".lib")) 483 visitedLibs.insert(std::string(sys::path::filename(path))); 484 return path; 485 } 486 487 // MinGW specific. If an embedded directive specified to link to 488 // foo.lib, but it isn't found, try libfoo.a instead. 489 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 490 if (filename.contains('/') || filename.contains('\\')) 491 return filename; 492 493 SmallString<128> s = filename; 494 sys::path::replace_extension(s, ".a"); 495 StringRef libName = saver.save("lib" + s.str()); 496 return doFindFile(libName); 497 } 498 499 // Find library file from search path. 500 StringRef LinkerDriver::doFindLib(StringRef filename) { 501 // Add ".lib" to Filename if that has no file extension. 502 bool hasExt = filename.contains('.'); 503 if (!hasExt) 504 filename = saver.save(filename + ".lib"); 505 StringRef ret = doFindFile(filename); 506 // For MinGW, if the find above didn't turn up anything, try 507 // looking for a MinGW formatted library name. 508 if (config->mingw && ret == filename) 509 return doFindLibMinGW(filename); 510 return ret; 511 } 512 513 // Resolves a library path. /nodefaultlib options are taken into 514 // consideration. This never returns the same path (in that case, 515 // it returns None). 516 Optional<StringRef> LinkerDriver::findLib(StringRef filename) { 517 if (config->noDefaultLibAll) 518 return None; 519 if (!visitedLibs.insert(filename.lower()).second) 520 return None; 521 522 StringRef path = doFindLib(filename); 523 if (config->noDefaultLibs.count(path.lower())) 524 return None; 525 526 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 527 if (!visitedFiles.insert(*id).second) 528 return None; 529 return path; 530 } 531 532 // Parses LIB environment which contains a list of search paths. 533 void LinkerDriver::addLibSearchPaths() { 534 Optional<std::string> envOpt = Process::GetEnv("LIB"); 535 if (!envOpt.hasValue()) 536 return; 537 StringRef env = saver.save(*envOpt); 538 while (!env.empty()) { 539 StringRef path; 540 std::tie(path, env) = env.split(';'); 541 searchPaths.push_back(path); 542 } 543 } 544 545 Symbol *LinkerDriver::addUndefined(StringRef name) { 546 Symbol *b = symtab->addUndefined(name); 547 if (!b->isGCRoot) { 548 b->isGCRoot = true; 549 config->gcroot.push_back(b); 550 } 551 return b; 552 } 553 554 StringRef LinkerDriver::mangleMaybe(Symbol *s) { 555 // If the plain symbol name has already been resolved, do nothing. 556 Undefined *unmangled = dyn_cast<Undefined>(s); 557 if (!unmangled) 558 return ""; 559 560 // Otherwise, see if a similar, mangled symbol exists in the symbol table. 561 Symbol *mangled = symtab->findMangle(unmangled->getName()); 562 if (!mangled) 563 return ""; 564 565 // If we find a similar mangled symbol, make this an alias to it and return 566 // its name. 567 log(unmangled->getName() + " aliased to " + mangled->getName()); 568 unmangled->weakAlias = symtab->addUndefined(mangled->getName()); 569 return mangled->getName(); 570 } 571 572 // Windows specific -- find default entry point name. 573 // 574 // There are four different entry point functions for Windows executables, 575 // each of which corresponds to a user-defined "main" function. This function 576 // infers an entry point from a user-defined "main" function. 577 StringRef LinkerDriver::findDefaultEntry() { 578 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 579 "must handle /subsystem before calling this"); 580 581 if (config->mingw) 582 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 583 ? "WinMainCRTStartup" 584 : "mainCRTStartup"); 585 586 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 587 if (findUnderscoreMangle("wWinMain")) { 588 if (!findUnderscoreMangle("WinMain")) 589 return mangle("wWinMainCRTStartup"); 590 warn("found both wWinMain and WinMain; using latter"); 591 } 592 return mangle("WinMainCRTStartup"); 593 } 594 if (findUnderscoreMangle("wmain")) { 595 if (!findUnderscoreMangle("main")) 596 return mangle("wmainCRTStartup"); 597 warn("found both wmain and main; using latter"); 598 } 599 return mangle("mainCRTStartup"); 600 } 601 602 WindowsSubsystem LinkerDriver::inferSubsystem() { 603 if (config->dll) 604 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 605 if (config->mingw) 606 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 607 // Note that link.exe infers the subsystem from the presence of these 608 // functions even if /entry: or /nodefaultlib are passed which causes them 609 // to not be called. 610 bool haveMain = findUnderscoreMangle("main"); 611 bool haveWMain = findUnderscoreMangle("wmain"); 612 bool haveWinMain = findUnderscoreMangle("WinMain"); 613 bool haveWWinMain = findUnderscoreMangle("wWinMain"); 614 if (haveMain || haveWMain) { 615 if (haveWinMain || haveWWinMain) { 616 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 617 (haveWinMain ? "WinMain" : "wWinMain") + 618 "; defaulting to /subsystem:console"); 619 } 620 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 621 } 622 if (haveWinMain || haveWWinMain) 623 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 624 return IMAGE_SUBSYSTEM_UNKNOWN; 625 } 626 627 static uint64_t getDefaultImageBase() { 628 if (config->is64()) 629 return config->dll ? 0x180000000 : 0x140000000; 630 return config->dll ? 0x10000000 : 0x400000; 631 } 632 633 static std::string rewritePath(StringRef s) { 634 if (fs::exists(s)) 635 return relativeToRoot(s); 636 return std::string(s); 637 } 638 639 // Reconstructs command line arguments so that so that you can re-run 640 // the same command with the same inputs. This is for --reproduce. 641 static std::string createResponseFile(const opt::InputArgList &args, 642 ArrayRef<StringRef> filePaths, 643 ArrayRef<StringRef> searchPaths) { 644 SmallString<0> data; 645 raw_svector_ostream os(data); 646 647 for (auto *arg : args) { 648 switch (arg->getOption().getID()) { 649 case OPT_linkrepro: 650 case OPT_reproduce: 651 case OPT_INPUT: 652 case OPT_defaultlib: 653 case OPT_libpath: 654 case OPT_manifest: 655 case OPT_manifest_colon: 656 case OPT_manifestdependency: 657 case OPT_manifestfile: 658 case OPT_manifestinput: 659 case OPT_manifestuac: 660 break; 661 case OPT_call_graph_ordering_file: 662 case OPT_deffile: 663 case OPT_natvis: 664 os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n'; 665 break; 666 case OPT_order: { 667 StringRef orderFile = arg->getValue(); 668 orderFile.consume_front("@"); 669 os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n'; 670 break; 671 } 672 case OPT_pdbstream: { 673 const std::pair<StringRef, StringRef> nameFile = 674 StringRef(arg->getValue()).split("="); 675 os << arg->getSpelling() << nameFile.first << '=' 676 << quote(rewritePath(nameFile.second)) << '\n'; 677 break; 678 } 679 case OPT_implib: 680 case OPT_pdb: 681 case OPT_pdbstripped: 682 case OPT_out: 683 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 684 break; 685 default: 686 os << toString(*arg) << "\n"; 687 } 688 } 689 690 for (StringRef path : searchPaths) { 691 std::string relPath = relativeToRoot(path); 692 os << "/libpath:" << quote(relPath) << "\n"; 693 } 694 695 for (StringRef path : filePaths) 696 os << quote(relativeToRoot(path)) << "\n"; 697 698 return std::string(data.str()); 699 } 700 701 enum class DebugKind { 702 Unknown, 703 None, 704 Full, 705 FastLink, 706 GHash, 707 NoGHash, 708 Dwarf, 709 Symtab 710 }; 711 712 static DebugKind parseDebugKind(const opt::InputArgList &args) { 713 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 714 if (!a) 715 return DebugKind::None; 716 if (a->getNumValues() == 0) 717 return DebugKind::Full; 718 719 DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 720 .CaseLower("none", DebugKind::None) 721 .CaseLower("full", DebugKind::Full) 722 .CaseLower("fastlink", DebugKind::FastLink) 723 // LLD extensions 724 .CaseLower("ghash", DebugKind::GHash) 725 .CaseLower("noghash", DebugKind::NoGHash) 726 .CaseLower("dwarf", DebugKind::Dwarf) 727 .CaseLower("symtab", DebugKind::Symtab) 728 .Default(DebugKind::Unknown); 729 730 if (debug == DebugKind::FastLink) { 731 warn("/debug:fastlink unsupported; using /debug:full"); 732 return DebugKind::Full; 733 } 734 if (debug == DebugKind::Unknown) { 735 error("/debug: unknown option: " + Twine(a->getValue())); 736 return DebugKind::None; 737 } 738 return debug; 739 } 740 741 static unsigned parseDebugTypes(const opt::InputArgList &args) { 742 unsigned debugTypes = static_cast<unsigned>(DebugType::None); 743 744 if (auto *a = args.getLastArg(OPT_debugtype)) { 745 SmallVector<StringRef, 3> types; 746 StringRef(a->getValue()) 747 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 748 749 for (StringRef type : types) { 750 unsigned v = StringSwitch<unsigned>(type.lower()) 751 .Case("cv", static_cast<unsigned>(DebugType::CV)) 752 .Case("pdata", static_cast<unsigned>(DebugType::PData)) 753 .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 754 .Default(0); 755 if (v == 0) { 756 warn("/debugtype: unknown option '" + type + "'"); 757 continue; 758 } 759 debugTypes |= v; 760 } 761 return debugTypes; 762 } 763 764 // Default debug types 765 debugTypes = static_cast<unsigned>(DebugType::CV); 766 if (args.hasArg(OPT_driver)) 767 debugTypes |= static_cast<unsigned>(DebugType::PData); 768 if (args.hasArg(OPT_profile)) 769 debugTypes |= static_cast<unsigned>(DebugType::Fixup); 770 771 return debugTypes; 772 } 773 774 static std::string getMapFile(const opt::InputArgList &args, 775 opt::OptSpecifier os, opt::OptSpecifier osFile) { 776 auto *arg = args.getLastArg(os, osFile); 777 if (!arg) 778 return ""; 779 if (arg->getOption().getID() == osFile.getID()) 780 return arg->getValue(); 781 782 assert(arg->getOption().getID() == os.getID()); 783 StringRef outFile = config->outputFile; 784 return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 785 } 786 787 static std::string getImplibPath() { 788 if (!config->implib.empty()) 789 return std::string(config->implib); 790 SmallString<128> out = StringRef(config->outputFile); 791 sys::path::replace_extension(out, ".lib"); 792 return std::string(out.str()); 793 } 794 795 // The import name is calculated as follows: 796 // 797 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 798 // -----+----------------+---------------------+------------------ 799 // LINK | {value} | {value}.{.dll/.exe} | {output name} 800 // LIB | {value} | {value}.dll | {output name}.dll 801 // 802 static std::string getImportName(bool asLib) { 803 SmallString<128> out; 804 805 if (config->importName.empty()) { 806 out.assign(sys::path::filename(config->outputFile)); 807 if (asLib) 808 sys::path::replace_extension(out, ".dll"); 809 } else { 810 out.assign(config->importName); 811 if (!sys::path::has_extension(out)) 812 sys::path::replace_extension(out, 813 (config->dll || asLib) ? ".dll" : ".exe"); 814 } 815 816 return std::string(out.str()); 817 } 818 819 static void createImportLibrary(bool asLib) { 820 std::vector<COFFShortExport> exports; 821 for (Export &e1 : config->exports) { 822 COFFShortExport e2; 823 e2.Name = std::string(e1.name); 824 e2.SymbolName = std::string(e1.symbolName); 825 e2.ExtName = std::string(e1.extName); 826 e2.Ordinal = e1.ordinal; 827 e2.Noname = e1.noname; 828 e2.Data = e1.data; 829 e2.Private = e1.isPrivate; 830 e2.Constant = e1.constant; 831 exports.push_back(e2); 832 } 833 834 auto handleError = [](Error &&e) { 835 handleAllErrors(std::move(e), 836 [](ErrorInfoBase &eib) { error(eib.message()); }); 837 }; 838 std::string libName = getImportName(asLib); 839 std::string path = getImplibPath(); 840 841 if (!config->incremental) { 842 handleError(writeImportLibrary(libName, path, exports, config->machine, 843 config->mingw)); 844 return; 845 } 846 847 // If the import library already exists, replace it only if the contents 848 // have changed. 849 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 850 path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 851 if (!oldBuf) { 852 handleError(writeImportLibrary(libName, path, exports, config->machine, 853 config->mingw)); 854 return; 855 } 856 857 SmallString<128> tmpName; 858 if (std::error_code ec = 859 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 860 fatal("cannot create temporary file for import library " + path + ": " + 861 ec.message()); 862 863 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine, 864 config->mingw)) { 865 handleError(std::move(e)); 866 return; 867 } 868 869 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 870 tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 871 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 872 oldBuf->reset(); 873 handleError(errorCodeToError(sys::fs::rename(tmpName, path))); 874 } else { 875 sys::fs::remove(tmpName); 876 } 877 } 878 879 static void parseModuleDefs(StringRef path) { 880 std::unique_ptr<MemoryBuffer> mb = 881 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 882 /*RequiresNullTerminator=*/false, 883 /*IsVolatile=*/true), 884 "could not open " + path); 885 COFFModuleDefinition m = check(parseCOFFModuleDefinition( 886 mb->getMemBufferRef(), config->machine, config->mingw)); 887 888 // Include in /reproduce: output if applicable. 889 driver->takeBuffer(std::move(mb)); 890 891 if (config->outputFile.empty()) 892 config->outputFile = std::string(saver.save(m.OutputFile)); 893 config->importName = std::string(saver.save(m.ImportName)); 894 if (m.ImageBase) 895 config->imageBase = m.ImageBase; 896 if (m.StackReserve) 897 config->stackReserve = m.StackReserve; 898 if (m.StackCommit) 899 config->stackCommit = m.StackCommit; 900 if (m.HeapReserve) 901 config->heapReserve = m.HeapReserve; 902 if (m.HeapCommit) 903 config->heapCommit = m.HeapCommit; 904 if (m.MajorImageVersion) 905 config->majorImageVersion = m.MajorImageVersion; 906 if (m.MinorImageVersion) 907 config->minorImageVersion = m.MinorImageVersion; 908 if (m.MajorOSVersion) 909 config->majorOSVersion = m.MajorOSVersion; 910 if (m.MinorOSVersion) 911 config->minorOSVersion = m.MinorOSVersion; 912 913 for (COFFShortExport e1 : m.Exports) { 914 Export e2; 915 // In simple cases, only Name is set. Renamed exports are parsed 916 // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 917 // it shouldn't be a normal exported function but a forward to another 918 // DLL instead. This is supported by both MS and GNU linkers. 919 if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 920 StringRef(e1.Name).contains('.')) { 921 e2.name = saver.save(e1.ExtName); 922 e2.forwardTo = saver.save(e1.Name); 923 config->exports.push_back(e2); 924 continue; 925 } 926 e2.name = saver.save(e1.Name); 927 e2.extName = saver.save(e1.ExtName); 928 e2.ordinal = e1.Ordinal; 929 e2.noname = e1.Noname; 930 e2.data = e1.Data; 931 e2.isPrivate = e1.Private; 932 e2.constant = e1.Constant; 933 config->exports.push_back(e2); 934 } 935 } 936 937 void LinkerDriver::enqueueTask(std::function<void()> task) { 938 taskQueue.push_back(std::move(task)); 939 } 940 941 bool LinkerDriver::run() { 942 ScopedTimer t(inputFileTimer); 943 944 bool didWork = !taskQueue.empty(); 945 while (!taskQueue.empty()) { 946 taskQueue.front()(); 947 taskQueue.pop_front(); 948 } 949 return didWork; 950 } 951 952 // Parse an /order file. If an option is given, the linker places 953 // COMDAT sections in the same order as their names appear in the 954 // given file. 955 static void parseOrderFile(StringRef arg) { 956 // For some reason, the MSVC linker requires a filename to be 957 // preceded by "@". 958 if (!arg.startswith("@")) { 959 error("malformed /order option: '@' missing"); 960 return; 961 } 962 963 // Get a list of all comdat sections for error checking. 964 DenseSet<StringRef> set; 965 for (Chunk *c : symtab->getChunks()) 966 if (auto *sec = dyn_cast<SectionChunk>(c)) 967 if (sec->sym) 968 set.insert(sec->sym->getName()); 969 970 // Open a file. 971 StringRef path = arg.substr(1); 972 std::unique_ptr<MemoryBuffer> mb = 973 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 974 /*RequiresNullTerminator=*/false, 975 /*IsVolatile=*/true), 976 "could not open " + path); 977 978 // Parse a file. An order file contains one symbol per line. 979 // All symbols that were not present in a given order file are 980 // considered to have the lowest priority 0 and are placed at 981 // end of an output section. 982 for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 983 std::string s(arg); 984 if (config->machine == I386 && !isDecorated(s)) 985 s = "_" + s; 986 987 if (set.count(s) == 0) { 988 if (config->warnMissingOrderSymbol) 989 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 990 } 991 else 992 config->order[s] = INT_MIN + config->order.size(); 993 } 994 995 // Include in /reproduce: output if applicable. 996 driver->takeBuffer(std::move(mb)); 997 } 998 999 static void parseCallGraphFile(StringRef path) { 1000 std::unique_ptr<MemoryBuffer> mb = 1001 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1002 /*RequiresNullTerminator=*/false, 1003 /*IsVolatile=*/true), 1004 "could not open " + path); 1005 1006 // Build a map from symbol name to section. 1007 DenseMap<StringRef, Symbol *> map; 1008 for (ObjFile *file : ObjFile::instances) 1009 for (Symbol *sym : file->getSymbols()) 1010 if (sym) 1011 map[sym->getName()] = sym; 1012 1013 auto findSection = [&](StringRef name) -> SectionChunk * { 1014 Symbol *sym = map.lookup(name); 1015 if (!sym) { 1016 if (config->warnMissingOrderSymbol) 1017 warn(path + ": no such symbol: " + name); 1018 return nullptr; 1019 } 1020 1021 if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 1022 return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 1023 return nullptr; 1024 }; 1025 1026 for (StringRef line : args::getLines(*mb)) { 1027 SmallVector<StringRef, 3> fields; 1028 line.split(fields, ' '); 1029 uint64_t count; 1030 1031 if (fields.size() != 3 || !to_integer(fields[2], count)) { 1032 error(path + ": parse error"); 1033 return; 1034 } 1035 1036 if (SectionChunk *from = findSection(fields[0])) 1037 if (SectionChunk *to = findSection(fields[1])) 1038 config->callGraphProfile[{from, to}] += count; 1039 } 1040 1041 // Include in /reproduce: output if applicable. 1042 driver->takeBuffer(std::move(mb)); 1043 } 1044 1045 static void readCallGraphsFromObjectFiles() { 1046 for (ObjFile *obj : ObjFile::instances) { 1047 if (obj->callgraphSec) { 1048 ArrayRef<uint8_t> contents; 1049 cantFail( 1050 obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1051 BinaryStreamReader reader(contents, support::little); 1052 while (!reader.empty()) { 1053 uint32_t fromIndex, toIndex; 1054 uint64_t count; 1055 if (Error err = reader.readInteger(fromIndex)) 1056 fatal(toString(obj) + ": Expected 32-bit integer"); 1057 if (Error err = reader.readInteger(toIndex)) 1058 fatal(toString(obj) + ": Expected 32-bit integer"); 1059 if (Error err = reader.readInteger(count)) 1060 fatal(toString(obj) + ": Expected 64-bit integer"); 1061 auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1062 auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1063 if (!fromSym || !toSym) 1064 continue; 1065 auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1066 auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1067 if (from && to) 1068 config->callGraphProfile[{from, to}] += count; 1069 } 1070 } 1071 } 1072 } 1073 1074 static void markAddrsig(Symbol *s) { 1075 if (auto *d = dyn_cast_or_null<Defined>(s)) 1076 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 1077 c->keepUnique = true; 1078 } 1079 1080 static void findKeepUniqueSections() { 1081 // Exported symbols could be address-significant in other executables or DSOs, 1082 // so we conservatively mark them as address-significant. 1083 for (Export &r : config->exports) 1084 markAddrsig(r.sym); 1085 1086 // Visit the address-significance table in each object file and mark each 1087 // referenced symbol as address-significant. 1088 for (ObjFile *obj : ObjFile::instances) { 1089 ArrayRef<Symbol *> syms = obj->getSymbols(); 1090 if (obj->addrsigSec) { 1091 ArrayRef<uint8_t> contents; 1092 cantFail( 1093 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 1094 const uint8_t *cur = contents.begin(); 1095 while (cur != contents.end()) { 1096 unsigned size; 1097 const char *err; 1098 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 1099 if (err) 1100 fatal(toString(obj) + ": could not decode addrsig section: " + err); 1101 if (symIndex >= syms.size()) 1102 fatal(toString(obj) + ": invalid symbol index in addrsig section"); 1103 markAddrsig(syms[symIndex]); 1104 cur += size; 1105 } 1106 } else { 1107 // If an object file does not have an address-significance table, 1108 // conservatively mark all of its symbols as address-significant. 1109 for (Symbol *s : syms) 1110 markAddrsig(s); 1111 } 1112 } 1113 } 1114 1115 // link.exe replaces each %foo% in altPath with the contents of environment 1116 // variable foo, and adds the two magic env vars _PDB (expands to the basename 1117 // of pdb's output path) and _EXT (expands to the extension of the output 1118 // binary). 1119 // lld only supports %_PDB% and %_EXT% and warns on references to all other env 1120 // vars. 1121 static void parsePDBAltPath(StringRef altPath) { 1122 SmallString<128> buf; 1123 StringRef pdbBasename = 1124 sys::path::filename(config->pdbPath, sys::path::Style::windows); 1125 StringRef binaryExtension = 1126 sys::path::extension(config->outputFile, sys::path::Style::windows); 1127 if (!binaryExtension.empty()) 1128 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 1129 1130 // Invariant: 1131 // +--------- cursor ('a...' might be the empty string). 1132 // | +----- firstMark 1133 // | | +- secondMark 1134 // v v v 1135 // a...%...%... 1136 size_t cursor = 0; 1137 while (cursor < altPath.size()) { 1138 size_t firstMark, secondMark; 1139 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos || 1140 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) { 1141 // Didn't find another full fragment, treat rest of string as literal. 1142 buf.append(altPath.substr(cursor)); 1143 break; 1144 } 1145 1146 // Found a full fragment. Append text in front of first %, and interpret 1147 // text between first and second % as variable name. 1148 buf.append(altPath.substr(cursor, firstMark - cursor)); 1149 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1); 1150 if (var.equals_insensitive("%_pdb%")) 1151 buf.append(pdbBasename); 1152 else if (var.equals_insensitive("%_ext%")) 1153 buf.append(binaryExtension); 1154 else { 1155 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 1156 var + " as literal"); 1157 buf.append(var); 1158 } 1159 1160 cursor = secondMark + 1; 1161 } 1162 1163 config->pdbAltPath = buf; 1164 } 1165 1166 /// Convert resource files and potentially merge input resource object 1167 /// trees into one resource tree. 1168 /// Call after ObjFile::Instances is complete. 1169 void LinkerDriver::convertResources() { 1170 std::vector<ObjFile *> resourceObjFiles; 1171 1172 for (ObjFile *f : ObjFile::instances) { 1173 if (f->isResourceObjFile()) 1174 resourceObjFiles.push_back(f); 1175 } 1176 1177 if (!config->mingw && 1178 (resourceObjFiles.size() > 1 || 1179 (resourceObjFiles.size() == 1 && !resources.empty()))) { 1180 error((!resources.empty() ? "internal .obj file created from .res files" 1181 : toString(resourceObjFiles[1])) + 1182 ": more than one resource obj file not allowed, already got " + 1183 toString(resourceObjFiles.front())); 1184 return; 1185 } 1186 1187 if (resources.empty() && resourceObjFiles.size() <= 1) { 1188 // No resources to convert, and max one resource object file in 1189 // the input. Keep that preconverted resource section as is. 1190 for (ObjFile *f : resourceObjFiles) 1191 f->includeResourceChunks(); 1192 return; 1193 } 1194 ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles)); 1195 symtab->addFile(f); 1196 f->includeResourceChunks(); 1197 } 1198 1199 // In MinGW, if no symbols are chosen to be exported, then all symbols are 1200 // automatically exported by default. This behavior can be forced by the 1201 // -export-all-symbols option, so that it happens even when exports are 1202 // explicitly specified. The automatic behavior can be disabled using the 1203 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 1204 // than MinGW in the case that nothing is explicitly exported. 1205 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1206 if (!args.hasArg(OPT_export_all_symbols)) { 1207 if (!config->dll) 1208 return; 1209 1210 if (!config->exports.empty()) 1211 return; 1212 if (args.hasArg(OPT_exclude_all_symbols)) 1213 return; 1214 } 1215 1216 AutoExporter exporter; 1217 1218 for (auto *arg : args.filtered(OPT_wholearchive_file)) 1219 if (Optional<StringRef> path = doFindFile(arg->getValue())) 1220 exporter.addWholeArchive(*path); 1221 1222 symtab->forEachSymbol([&](Symbol *s) { 1223 auto *def = dyn_cast<Defined>(s); 1224 if (!exporter.shouldExport(def)) 1225 return; 1226 1227 if (!def->isGCRoot) { 1228 def->isGCRoot = true; 1229 config->gcroot.push_back(def); 1230 } 1231 1232 Export e; 1233 e.name = def->getName(); 1234 e.sym = def; 1235 if (Chunk *c = def->getChunk()) 1236 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 1237 e.data = true; 1238 s->isUsedInRegularObj = true; 1239 config->exports.push_back(e); 1240 }); 1241 } 1242 1243 // lld has a feature to create a tar file containing all input files as well as 1244 // all command line options, so that other people can run lld again with exactly 1245 // the same inputs. This feature is accessible via /linkrepro and /reproduce. 1246 // 1247 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 1248 // name while /reproduce takes a full path. We have /linkrepro for compatibility 1249 // with Microsoft link.exe. 1250 Optional<std::string> getReproduceFile(const opt::InputArgList &args) { 1251 if (auto *arg = args.getLastArg(OPT_reproduce)) 1252 return std::string(arg->getValue()); 1253 1254 if (auto *arg = args.getLastArg(OPT_linkrepro)) { 1255 SmallString<64> path = StringRef(arg->getValue()); 1256 sys::path::append(path, "repro.tar"); 1257 return std::string(path); 1258 } 1259 1260 // This is intentionally not guarded by OPT_lldignoreenv since writing 1261 // a repro tar file doesn't affect the main output. 1262 if (auto *path = getenv("LLD_REPRODUCE")) 1263 return std::string(path); 1264 1265 return None; 1266 } 1267 1268 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 1269 ScopedTimer rootTimer(Timer::root()); 1270 1271 // Needed for LTO. 1272 InitializeAllTargetInfos(); 1273 InitializeAllTargets(); 1274 InitializeAllTargetMCs(); 1275 InitializeAllAsmParsers(); 1276 InitializeAllAsmPrinters(); 1277 1278 // If the first command line argument is "/lib", link.exe acts like lib.exe. 1279 // We call our own implementation of lib.exe that understands bitcode files. 1280 if (argsArr.size() > 1 && 1281 (StringRef(argsArr[1]).equals_insensitive("/lib") || 1282 StringRef(argsArr[1]).equals_insensitive("-lib"))) { 1283 if (llvm::libDriverMain(argsArr.slice(1)) != 0) 1284 fatal("lib failed"); 1285 return; 1286 } 1287 1288 // Parse command line options. 1289 ArgParser parser; 1290 opt::InputArgList args = parser.parse(argsArr); 1291 1292 // Parse and evaluate -mllvm options. 1293 std::vector<const char *> v; 1294 v.push_back("lld-link (LLVM option parsing)"); 1295 for (auto *arg : args.filtered(OPT_mllvm)) 1296 v.push_back(arg->getValue()); 1297 cl::ResetAllOptionOccurrences(); 1298 cl::ParseCommandLineOptions(v.size(), v.data()); 1299 1300 // Handle /errorlimit early, because error() depends on it. 1301 if (auto *arg = args.getLastArg(OPT_errorlimit)) { 1302 int n = 20; 1303 StringRef s = arg->getValue(); 1304 if (s.getAsInteger(10, n)) 1305 error(arg->getSpelling() + " number expected, but got " + s); 1306 errorHandler().errorLimit = n; 1307 } 1308 1309 // Handle /help 1310 if (args.hasArg(OPT_help)) { 1311 printHelp(argsArr[0]); 1312 return; 1313 } 1314 1315 // /threads: takes a positive integer and provides the default value for 1316 // /opt:lldltojobs=. 1317 if (auto *arg = args.getLastArg(OPT_threads)) { 1318 StringRef v(arg->getValue()); 1319 unsigned threads = 0; 1320 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1321 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1322 arg->getValue() + "'"); 1323 parallel::strategy = hardware_concurrency(threads); 1324 config->thinLTOJobs = v.str(); 1325 } 1326 1327 if (args.hasArg(OPT_show_timing)) 1328 config->showTiming = true; 1329 1330 config->showSummary = args.hasArg(OPT_summary); 1331 1332 // Handle --version, which is an lld extension. This option is a bit odd 1333 // because it doesn't start with "/", but we deliberately chose "--" to 1334 // avoid conflict with /version and for compatibility with clang-cl. 1335 if (args.hasArg(OPT_dash_dash_version)) { 1336 message(getLLDVersion()); 1337 return; 1338 } 1339 1340 // Handle /lldmingw early, since it can potentially affect how other 1341 // options are handled. 1342 config->mingw = args.hasArg(OPT_lldmingw); 1343 1344 // Handle /linkrepro and /reproduce. 1345 if (Optional<std::string> path = getReproduceFile(args)) { 1346 Expected<std::unique_ptr<TarWriter>> errOrWriter = 1347 TarWriter::create(*path, sys::path::stem(*path)); 1348 1349 if (errOrWriter) { 1350 tar = std::move(*errOrWriter); 1351 } else { 1352 error("/linkrepro: failed to open " + *path + ": " + 1353 toString(errOrWriter.takeError())); 1354 } 1355 } 1356 1357 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 1358 if (args.hasArg(OPT_deffile)) 1359 config->noEntry = true; 1360 else 1361 fatal("no input files"); 1362 } 1363 1364 // Construct search path list. 1365 searchPaths.push_back(""); 1366 for (auto *arg : args.filtered(OPT_libpath)) 1367 searchPaths.push_back(arg->getValue()); 1368 if (!args.hasArg(OPT_lldignoreenv)) 1369 addLibSearchPaths(); 1370 1371 // Handle /ignore 1372 for (auto *arg : args.filtered(OPT_ignore)) { 1373 SmallVector<StringRef, 8> vec; 1374 StringRef(arg->getValue()).split(vec, ','); 1375 for (StringRef s : vec) { 1376 if (s == "4037") 1377 config->warnMissingOrderSymbol = false; 1378 else if (s == "4099") 1379 config->warnDebugInfoUnusable = false; 1380 else if (s == "4217") 1381 config->warnLocallyDefinedImported = false; 1382 else if (s == "longsections") 1383 config->warnLongSectionNames = false; 1384 // Other warning numbers are ignored. 1385 } 1386 } 1387 1388 // Handle /out 1389 if (auto *arg = args.getLastArg(OPT_out)) 1390 config->outputFile = arg->getValue(); 1391 1392 // Handle /verbose 1393 if (args.hasArg(OPT_verbose)) 1394 config->verbose = true; 1395 errorHandler().verbose = config->verbose; 1396 1397 // Handle /force or /force:unresolved 1398 if (args.hasArg(OPT_force, OPT_force_unresolved)) 1399 config->forceUnresolved = true; 1400 1401 // Handle /force or /force:multiple 1402 if (args.hasArg(OPT_force, OPT_force_multiple)) 1403 config->forceMultiple = true; 1404 1405 // Handle /force or /force:multipleres 1406 if (args.hasArg(OPT_force, OPT_force_multipleres)) 1407 config->forceMultipleRes = true; 1408 1409 // Handle /debug 1410 DebugKind debug = parseDebugKind(args); 1411 if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1412 debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 1413 config->debug = true; 1414 config->incremental = true; 1415 } 1416 1417 // Handle /demangle 1418 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no); 1419 1420 // Handle /debugtype 1421 config->debugTypes = parseDebugTypes(args); 1422 1423 // Handle /driver[:uponly|:wdm]. 1424 config->driverUponly = args.hasArg(OPT_driver_uponly) || 1425 args.hasArg(OPT_driver_uponly_wdm) || 1426 args.hasArg(OPT_driver_wdm_uponly); 1427 config->driverWdm = args.hasArg(OPT_driver_wdm) || 1428 args.hasArg(OPT_driver_uponly_wdm) || 1429 args.hasArg(OPT_driver_wdm_uponly); 1430 config->driver = 1431 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1432 1433 // Handle /pdb 1434 bool shouldCreatePDB = 1435 (debug == DebugKind::Full || debug == DebugKind::GHash || 1436 debug == DebugKind::NoGHash); 1437 if (shouldCreatePDB) { 1438 if (auto *arg = args.getLastArg(OPT_pdb)) 1439 config->pdbPath = arg->getValue(); 1440 if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 1441 config->pdbAltPath = arg->getValue(); 1442 if (args.hasArg(OPT_natvis)) 1443 config->natvisFiles = args.getAllArgValues(OPT_natvis); 1444 if (args.hasArg(OPT_pdbstream)) { 1445 for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 1446 const std::pair<StringRef, StringRef> nameFile = value.split("="); 1447 const StringRef name = nameFile.first; 1448 const std::string file = nameFile.second.str(); 1449 config->namedStreams[name] = file; 1450 } 1451 } 1452 1453 if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 1454 config->pdbSourcePath = arg->getValue(); 1455 } 1456 1457 // Handle /pdbstripped 1458 if (args.hasArg(OPT_pdbstripped)) 1459 warn("ignoring /pdbstripped flag, it is not yet supported"); 1460 1461 // Handle /noentry 1462 if (args.hasArg(OPT_noentry)) { 1463 if (args.hasArg(OPT_dll)) 1464 config->noEntry = true; 1465 else 1466 error("/noentry must be specified with /dll"); 1467 } 1468 1469 // Handle /dll 1470 if (args.hasArg(OPT_dll)) { 1471 config->dll = true; 1472 config->manifestID = 2; 1473 } 1474 1475 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 1476 // because we need to explicitly check whether that option or its inverse was 1477 // present in the argument list in order to handle /fixed. 1478 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 1479 if (dynamicBaseArg && 1480 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 1481 config->dynamicBase = false; 1482 1483 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 1484 // default setting for any other project type.", but link.exe defaults to 1485 // /FIXED:NO for exe outputs as well. Match behavior, not docs. 1486 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 1487 if (fixed) { 1488 if (dynamicBaseArg && 1489 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 1490 error("/fixed must not be specified with /dynamicbase"); 1491 } else { 1492 config->relocatable = false; 1493 config->dynamicBase = false; 1494 } 1495 } 1496 1497 // Handle /appcontainer 1498 config->appContainer = 1499 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 1500 1501 // Handle /machine 1502 if (auto *arg = args.getLastArg(OPT_machine)) { 1503 config->machine = getMachineType(arg->getValue()); 1504 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 1505 fatal(Twine("unknown /machine argument: ") + arg->getValue()); 1506 } 1507 1508 // Handle /nodefaultlib:<filename> 1509 for (auto *arg : args.filtered(OPT_nodefaultlib)) 1510 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 1511 1512 // Handle /nodefaultlib 1513 if (args.hasArg(OPT_nodefaultlib_all)) 1514 config->noDefaultLibAll = true; 1515 1516 // Handle /base 1517 if (auto *arg = args.getLastArg(OPT_base)) 1518 parseNumbers(arg->getValue(), &config->imageBase); 1519 1520 // Handle /filealign 1521 if (auto *arg = args.getLastArg(OPT_filealign)) { 1522 parseNumbers(arg->getValue(), &config->fileAlign); 1523 if (!isPowerOf2_64(config->fileAlign)) 1524 error("/filealign: not a power of two: " + Twine(config->fileAlign)); 1525 } 1526 1527 // Handle /stack 1528 if (auto *arg = args.getLastArg(OPT_stack)) 1529 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 1530 1531 // Handle /guard:cf 1532 if (auto *arg = args.getLastArg(OPT_guard)) 1533 parseGuard(arg->getValue()); 1534 1535 // Handle /heap 1536 if (auto *arg = args.getLastArg(OPT_heap)) 1537 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 1538 1539 // Handle /version 1540 if (auto *arg = args.getLastArg(OPT_version)) 1541 parseVersion(arg->getValue(), &config->majorImageVersion, 1542 &config->minorImageVersion); 1543 1544 // Handle /subsystem 1545 if (auto *arg = args.getLastArg(OPT_subsystem)) 1546 parseSubsystem(arg->getValue(), &config->subsystem, 1547 &config->majorSubsystemVersion, 1548 &config->minorSubsystemVersion); 1549 1550 // Handle /osversion 1551 if (auto *arg = args.getLastArg(OPT_osversion)) { 1552 parseVersion(arg->getValue(), &config->majorOSVersion, 1553 &config->minorOSVersion); 1554 } else { 1555 config->majorOSVersion = config->majorSubsystemVersion; 1556 config->minorOSVersion = config->minorSubsystemVersion; 1557 } 1558 1559 // Handle /timestamp 1560 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 1561 if (arg->getOption().getID() == OPT_repro) { 1562 config->timestamp = 0; 1563 config->repro = true; 1564 } else { 1565 config->repro = false; 1566 StringRef value(arg->getValue()); 1567 if (value.getAsInteger(0, config->timestamp)) 1568 fatal(Twine("invalid timestamp: ") + value + 1569 ". Expected 32-bit integer"); 1570 } 1571 } else { 1572 config->repro = false; 1573 config->timestamp = time(nullptr); 1574 } 1575 1576 // Handle /alternatename 1577 for (auto *arg : args.filtered(OPT_alternatename)) 1578 parseAlternateName(arg->getValue()); 1579 1580 // Handle /include 1581 for (auto *arg : args.filtered(OPT_incl)) 1582 addUndefined(arg->getValue()); 1583 1584 // Handle /implib 1585 if (auto *arg = args.getLastArg(OPT_implib)) 1586 config->implib = arg->getValue(); 1587 1588 // Handle /opt. 1589 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1590 Optional<ICFLevel> icfLevel = None; 1591 if (args.hasArg(OPT_profile)) 1592 icfLevel = ICFLevel::None; 1593 unsigned tailMerge = 1; 1594 bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER; 1595 bool ltoDebugPM = false; 1596 for (auto *arg : args.filtered(OPT_opt)) { 1597 std::string str = StringRef(arg->getValue()).lower(); 1598 SmallVector<StringRef, 1> vec; 1599 StringRef(str).split(vec, ','); 1600 for (StringRef s : vec) { 1601 if (s == "ref") { 1602 doGC = true; 1603 } else if (s == "noref") { 1604 doGC = false; 1605 } else if (s == "icf" || s.startswith("icf=")) { 1606 icfLevel = ICFLevel::All; 1607 } else if (s == "safeicf") { 1608 icfLevel = ICFLevel::Safe; 1609 } else if (s == "noicf") { 1610 icfLevel = ICFLevel::None; 1611 } else if (s == "lldtailmerge") { 1612 tailMerge = 2; 1613 } else if (s == "nolldtailmerge") { 1614 tailMerge = 0; 1615 } else if (s == "ltonewpassmanager") { 1616 ltoNewPM = true; 1617 } else if (s == "noltonewpassmanager") { 1618 ltoNewPM = false; 1619 } else if (s == "ltodebugpassmanager") { 1620 ltoDebugPM = true; 1621 } else if (s == "noltodebugpassmanager") { 1622 ltoDebugPM = false; 1623 } else if (s.startswith("lldlto=")) { 1624 StringRef optLevel = s.substr(7); 1625 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 1626 error("/opt:lldlto: invalid optimization level: " + optLevel); 1627 } else if (s.startswith("lldltojobs=")) { 1628 StringRef jobs = s.substr(11); 1629 if (!get_threadpool_strategy(jobs)) 1630 error("/opt:lldltojobs: invalid job count: " + jobs); 1631 config->thinLTOJobs = jobs.str(); 1632 } else if (s.startswith("lldltopartitions=")) { 1633 StringRef n = s.substr(17); 1634 if (n.getAsInteger(10, config->ltoPartitions) || 1635 config->ltoPartitions == 0) 1636 error("/opt:lldltopartitions: invalid partition count: " + n); 1637 } else if (s != "lbr" && s != "nolbr") 1638 error("/opt: unknown option: " + s); 1639 } 1640 } 1641 1642 if (!icfLevel) 1643 icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 1644 config->doGC = doGC; 1645 config->doICF = icfLevel.getValue(); 1646 config->tailMerge = 1647 (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1648 config->ltoNewPassManager = ltoNewPM; 1649 config->ltoDebugPassManager = ltoDebugPM; 1650 1651 // Handle /lldsavetemps 1652 if (args.hasArg(OPT_lldsavetemps)) 1653 config->saveTemps = true; 1654 1655 // Handle /kill-at 1656 if (args.hasArg(OPT_kill_at)) 1657 config->killAt = true; 1658 1659 // Handle /lldltocache 1660 if (auto *arg = args.getLastArg(OPT_lldltocache)) 1661 config->ltoCache = arg->getValue(); 1662 1663 // Handle /lldsavecachepolicy 1664 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 1665 config->ltoCachePolicy = CHECK( 1666 parseCachePruningPolicy(arg->getValue()), 1667 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 1668 1669 // Handle /failifmismatch 1670 for (auto *arg : args.filtered(OPT_failifmismatch)) 1671 checkFailIfMismatch(arg->getValue(), nullptr); 1672 1673 // Handle /merge 1674 for (auto *arg : args.filtered(OPT_merge)) 1675 parseMerge(arg->getValue()); 1676 1677 // Add default section merging rules after user rules. User rules take 1678 // precedence, but we will emit a warning if there is a conflict. 1679 parseMerge(".idata=.rdata"); 1680 parseMerge(".didat=.rdata"); 1681 parseMerge(".edata=.rdata"); 1682 parseMerge(".xdata=.rdata"); 1683 parseMerge(".bss=.data"); 1684 1685 if (config->mingw) { 1686 parseMerge(".ctors=.rdata"); 1687 parseMerge(".dtors=.rdata"); 1688 parseMerge(".CRT=.rdata"); 1689 } 1690 1691 // Handle /section 1692 for (auto *arg : args.filtered(OPT_section)) 1693 parseSection(arg->getValue()); 1694 1695 // Handle /align 1696 if (auto *arg = args.getLastArg(OPT_align)) { 1697 parseNumbers(arg->getValue(), &config->align); 1698 if (!isPowerOf2_64(config->align)) 1699 error("/align: not a power of two: " + StringRef(arg->getValue())); 1700 if (!args.hasArg(OPT_driver)) 1701 warn("/align specified without /driver; image may not run"); 1702 } 1703 1704 // Handle /aligncomm 1705 for (auto *arg : args.filtered(OPT_aligncomm)) 1706 parseAligncomm(arg->getValue()); 1707 1708 // Handle /manifestdependency. This enables /manifest unless /manifest:no is 1709 // also passed. 1710 if (auto *arg = args.getLastArg(OPT_manifestdependency)) { 1711 config->manifestDependency = arg->getValue(); 1712 config->manifest = Configuration::SideBySide; 1713 } 1714 1715 // Handle /manifest and /manifest: 1716 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 1717 if (arg->getOption().getID() == OPT_manifest) 1718 config->manifest = Configuration::SideBySide; 1719 else 1720 parseManifest(arg->getValue()); 1721 } 1722 1723 // Handle /manifestuac 1724 if (auto *arg = args.getLastArg(OPT_manifestuac)) 1725 parseManifestUAC(arg->getValue()); 1726 1727 // Handle /manifestfile 1728 if (auto *arg = args.getLastArg(OPT_manifestfile)) 1729 config->manifestFile = arg->getValue(); 1730 1731 // Handle /manifestinput 1732 for (auto *arg : args.filtered(OPT_manifestinput)) 1733 config->manifestInput.push_back(arg->getValue()); 1734 1735 if (!config->manifestInput.empty() && 1736 config->manifest != Configuration::Embed) { 1737 fatal("/manifestinput: requires /manifest:embed"); 1738 } 1739 1740 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1741 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1742 args.hasArg(OPT_thinlto_index_only_arg); 1743 config->thinLTOIndexOnlyArg = 1744 args.getLastArgValue(OPT_thinlto_index_only_arg); 1745 config->thinLTOPrefixReplace = 1746 getOldNewOptions(args, OPT_thinlto_prefix_replace); 1747 config->thinLTOObjectSuffixReplace = 1748 getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 1749 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1750 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1751 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1752 // Handle miscellaneous boolean flags. 1753 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 1754 config->allowIsolation = 1755 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 1756 config->incremental = 1757 args.hasFlag(OPT_incremental, OPT_incremental_no, 1758 !config->doGC && config->doICF == ICFLevel::None && 1759 !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 1760 config->integrityCheck = 1761 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 1762 config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 1763 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 1764 for (auto *arg : args.filtered(OPT_swaprun)) 1765 parseSwaprun(arg->getValue()); 1766 config->terminalServerAware = 1767 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 1768 config->debugDwarf = debug == DebugKind::Dwarf; 1769 config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 1770 config->debugSymtab = debug == DebugKind::Symtab; 1771 config->autoImport = 1772 args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 1773 config->pseudoRelocs = args.hasFlag( 1774 OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1775 config->callGraphProfileSort = args.hasFlag( 1776 OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1777 config->stdcallFixup = 1778 args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1779 config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 1780 1781 // Don't warn about long section names, such as .debug_info, for mingw or 1782 // when -debug:dwarf is requested. 1783 if (config->mingw || config->debugDwarf) 1784 config->warnLongSectionNames = false; 1785 1786 config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 1787 config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 1788 1789 if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 1790 warn("/lldmap and /map have the same output file '" + config->mapFile + 1791 "'.\n>>> ignoring /lldmap"); 1792 config->lldmapFile.clear(); 1793 } 1794 1795 if (config->incremental && args.hasArg(OPT_profile)) { 1796 warn("ignoring '/incremental' due to '/profile' specification"); 1797 config->incremental = false; 1798 } 1799 1800 if (config->incremental && args.hasArg(OPT_order)) { 1801 warn("ignoring '/incremental' due to '/order' specification"); 1802 config->incremental = false; 1803 } 1804 1805 if (config->incremental && config->doGC) { 1806 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 1807 "disable"); 1808 config->incremental = false; 1809 } 1810 1811 if (config->incremental && config->doICF != ICFLevel::None) { 1812 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 1813 "disable"); 1814 config->incremental = false; 1815 } 1816 1817 if (errorCount()) 1818 return; 1819 1820 std::set<sys::fs::UniqueID> wholeArchives; 1821 for (auto *arg : args.filtered(OPT_wholearchive_file)) 1822 if (Optional<StringRef> path = doFindFile(arg->getValue())) 1823 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 1824 wholeArchives.insert(*id); 1825 1826 // A predicate returning true if a given path is an argument for 1827 // /wholearchive:, or /wholearchive is enabled globally. 1828 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 1829 // needs to be handled as "/wholearchive:foo.obj foo.obj". 1830 auto isWholeArchive = [&](StringRef path) -> bool { 1831 if (args.hasArg(OPT_wholearchive_flag)) 1832 return true; 1833 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 1834 return wholeArchives.count(*id); 1835 return false; 1836 }; 1837 1838 // Create a list of input files. These can be given as OPT_INPUT options 1839 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 1840 // and OPT_end_lib. 1841 bool inLib = false; 1842 for (auto *arg : args) { 1843 switch (arg->getOption().getID()) { 1844 case OPT_end_lib: 1845 if (!inLib) 1846 error("stray " + arg->getSpelling()); 1847 inLib = false; 1848 break; 1849 case OPT_start_lib: 1850 if (inLib) 1851 error("nested " + arg->getSpelling()); 1852 inLib = true; 1853 break; 1854 case OPT_wholearchive_file: 1855 if (Optional<StringRef> path = findFile(arg->getValue())) 1856 enqueuePath(*path, true, inLib); 1857 break; 1858 case OPT_INPUT: 1859 if (Optional<StringRef> path = findFile(arg->getValue())) 1860 enqueuePath(*path, isWholeArchive(*path), inLib); 1861 break; 1862 default: 1863 // Ignore other options. 1864 break; 1865 } 1866 } 1867 1868 // Process files specified as /defaultlib. These should be enequeued after 1869 // other files, which is why they are in a separate loop. 1870 for (auto *arg : args.filtered(OPT_defaultlib)) 1871 if (Optional<StringRef> path = findLib(arg->getValue())) 1872 enqueuePath(*path, false, false); 1873 1874 // Windows specific -- Create a resource file containing a manifest file. 1875 if (config->manifest == Configuration::Embed) 1876 addBuffer(createManifestRes(), false, false); 1877 1878 // Read all input files given via the command line. 1879 run(); 1880 1881 if (errorCount()) 1882 return; 1883 1884 // We should have inferred a machine type by now from the input files, but if 1885 // not we assume x64. 1886 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 1887 warn("/machine is not specified. x64 is assumed"); 1888 config->machine = AMD64; 1889 } 1890 config->wordsize = config->is64() ? 8 : 4; 1891 1892 // Handle /safeseh, x86 only, on by default, except for mingw. 1893 if (config->machine == I386) { 1894 config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 1895 config->noSEH = args.hasArg(OPT_noseh); 1896 } 1897 1898 // Handle /functionpadmin 1899 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 1900 parseFunctionPadMin(arg, config->machine); 1901 1902 if (tar) 1903 tar->append("response.txt", 1904 createResponseFile(args, filePaths, 1905 ArrayRef<StringRef>(searchPaths).slice(1))); 1906 1907 // Handle /largeaddressaware 1908 config->largeAddressAware = args.hasFlag( 1909 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 1910 1911 // Handle /highentropyva 1912 config->highEntropyVA = 1913 config->is64() && 1914 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 1915 1916 if (!config->dynamicBase && 1917 (config->machine == ARMNT || config->machine == ARM64)) 1918 error("/dynamicbase:no is not compatible with " + 1919 machineToStr(config->machine)); 1920 1921 // Handle /export 1922 for (auto *arg : args.filtered(OPT_export)) { 1923 Export e = parseExport(arg->getValue()); 1924 if (config->machine == I386) { 1925 if (!isDecorated(e.name)) 1926 e.name = saver.save("_" + e.name); 1927 if (!e.extName.empty() && !isDecorated(e.extName)) 1928 e.extName = saver.save("_" + e.extName); 1929 } 1930 config->exports.push_back(e); 1931 } 1932 1933 // Handle /def 1934 if (auto *arg = args.getLastArg(OPT_deffile)) { 1935 // parseModuleDefs mutates Config object. 1936 parseModuleDefs(arg->getValue()); 1937 } 1938 1939 // Handle generation of import library from a def file. 1940 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 1941 fixupExports(); 1942 createImportLibrary(/*asLib=*/true); 1943 return; 1944 } 1945 1946 // Windows specific -- if no /subsystem is given, we need to infer 1947 // that from entry point name. Must happen before /entry handling, 1948 // and after the early return when just writing an import library. 1949 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 1950 config->subsystem = inferSubsystem(); 1951 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 1952 fatal("subsystem must be defined"); 1953 } 1954 1955 // Handle /entry and /dll 1956 if (auto *arg = args.getLastArg(OPT_entry)) { 1957 config->entry = addUndefined(mangle(arg->getValue())); 1958 } else if (!config->entry && !config->noEntry) { 1959 if (args.hasArg(OPT_dll)) { 1960 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 1961 : "_DllMainCRTStartup"; 1962 config->entry = addUndefined(s); 1963 } else if (config->driverWdm) { 1964 // /driver:wdm implies /entry:_NtProcessStartup 1965 config->entry = addUndefined(mangle("_NtProcessStartup")); 1966 } else { 1967 // Windows specific -- If entry point name is not given, we need to 1968 // infer that from user-defined entry name. 1969 StringRef s = findDefaultEntry(); 1970 if (s.empty()) 1971 fatal("entry point must be defined"); 1972 config->entry = addUndefined(s); 1973 log("Entry name inferred: " + s); 1974 } 1975 } 1976 1977 // Handle /delayload 1978 for (auto *arg : args.filtered(OPT_delayload)) { 1979 config->delayLoads.insert(StringRef(arg->getValue()).lower()); 1980 if (config->machine == I386) { 1981 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 1982 } else { 1983 config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 1984 } 1985 } 1986 1987 // Set default image name if neither /out or /def set it. 1988 if (config->outputFile.empty()) { 1989 config->outputFile = getOutputPath( 1990 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue()); 1991 } 1992 1993 // Fail early if an output file is not writable. 1994 if (auto e = tryCreateFile(config->outputFile)) { 1995 error("cannot open output file " + config->outputFile + ": " + e.message()); 1996 return; 1997 } 1998 1999 if (shouldCreatePDB) { 2000 // Put the PDB next to the image if no /pdb flag was passed. 2001 if (config->pdbPath.empty()) { 2002 config->pdbPath = config->outputFile; 2003 sys::path::replace_extension(config->pdbPath, ".pdb"); 2004 } 2005 2006 // The embedded PDB path should be the absolute path to the PDB if no 2007 // /pdbaltpath flag was passed. 2008 if (config->pdbAltPath.empty()) { 2009 config->pdbAltPath = config->pdbPath; 2010 2011 // It's important to make the path absolute and remove dots. This path 2012 // will eventually be written into the PE header, and certain Microsoft 2013 // tools won't work correctly if these assumptions are not held. 2014 sys::fs::make_absolute(config->pdbAltPath); 2015 sys::path::remove_dots(config->pdbAltPath); 2016 } else { 2017 // Don't do this earlier, so that Config->OutputFile is ready. 2018 parsePDBAltPath(config->pdbAltPath); 2019 } 2020 } 2021 2022 // Set default image base if /base is not given. 2023 if (config->imageBase == uint64_t(-1)) 2024 config->imageBase = getDefaultImageBase(); 2025 2026 symtab->addSynthetic(mangle("__ImageBase"), nullptr); 2027 if (config->machine == I386) { 2028 symtab->addAbsolute("___safe_se_handler_table", 0); 2029 symtab->addAbsolute("___safe_se_handler_count", 0); 2030 } 2031 2032 symtab->addAbsolute(mangle("__guard_fids_count"), 0); 2033 symtab->addAbsolute(mangle("__guard_fids_table"), 0); 2034 symtab->addAbsolute(mangle("__guard_flags"), 0); 2035 symtab->addAbsolute(mangle("__guard_iat_count"), 0); 2036 symtab->addAbsolute(mangle("__guard_iat_table"), 0); 2037 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); 2038 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); 2039 // Needed for MSVC 2017 15.5 CRT. 2040 symtab->addAbsolute(mangle("__enclave_config"), 0); 2041 // Needed for MSVC 2019 16.8 CRT. 2042 symtab->addAbsolute(mangle("__guard_eh_cont_count"), 0); 2043 symtab->addAbsolute(mangle("__guard_eh_cont_table"), 0); 2044 2045 if (config->pseudoRelocs) { 2046 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 2047 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 2048 } 2049 if (config->mingw) { 2050 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0); 2051 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0); 2052 } 2053 2054 // This code may add new undefined symbols to the link, which may enqueue more 2055 // symbol resolution tasks, so we need to continue executing tasks until we 2056 // converge. 2057 do { 2058 // Windows specific -- if entry point is not found, 2059 // search for its mangled names. 2060 if (config->entry) 2061 mangleMaybe(config->entry); 2062 2063 // Windows specific -- Make sure we resolve all dllexported symbols. 2064 for (Export &e : config->exports) { 2065 if (!e.forwardTo.empty()) 2066 continue; 2067 e.sym = addUndefined(e.name); 2068 if (!e.directives) 2069 e.symbolName = mangleMaybe(e.sym); 2070 } 2071 2072 // Add weak aliases. Weak aliases is a mechanism to give remaining 2073 // undefined symbols final chance to be resolved successfully. 2074 for (auto pair : config->alternateNames) { 2075 StringRef from = pair.first; 2076 StringRef to = pair.second; 2077 Symbol *sym = symtab->find(from); 2078 if (!sym) 2079 continue; 2080 if (auto *u = dyn_cast<Undefined>(sym)) 2081 if (!u->weakAlias) 2082 u->weakAlias = symtab->addUndefined(to); 2083 } 2084 2085 // If any inputs are bitcode files, the LTO code generator may create 2086 // references to library functions that are not explicit in the bitcode 2087 // file's symbol table. If any of those library functions are defined in a 2088 // bitcode file in an archive member, we need to arrange to use LTO to 2089 // compile those archive members by adding them to the link beforehand. 2090 if (!BitcodeFile::instances.empty()) 2091 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2092 symtab->addLibcall(s); 2093 2094 // Windows specific -- if __load_config_used can be resolved, resolve it. 2095 if (symtab->findUnderscore("_load_config_used")) 2096 addUndefined(mangle("_load_config_used")); 2097 } while (run()); 2098 2099 if (args.hasArg(OPT_include_optional)) { 2100 // Handle /includeoptional 2101 for (auto *arg : args.filtered(OPT_include_optional)) 2102 if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue()))) 2103 addUndefined(arg->getValue()); 2104 while (run()); 2105 } 2106 2107 // Create wrapped symbols for -wrap option. 2108 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 2109 // Load more object files that might be needed for wrapped symbols. 2110 if (!wrapped.empty()) 2111 while (run()); 2112 2113 if (config->autoImport || config->stdcallFixup) { 2114 // MinGW specific. 2115 // Load any further object files that might be needed for doing automatic 2116 // imports, and do stdcall fixups. 2117 // 2118 // For cases with no automatically imported symbols, this iterates once 2119 // over the symbol table and doesn't do anything. 2120 // 2121 // For the normal case with a few automatically imported symbols, this 2122 // should only need to be run once, since each new object file imported 2123 // is an import library and wouldn't add any new undefined references, 2124 // but there's nothing stopping the __imp_ symbols from coming from a 2125 // normal object file as well (although that won't be used for the 2126 // actual autoimport later on). If this pass adds new undefined references, 2127 // we won't iterate further to resolve them. 2128 // 2129 // If stdcall fixups only are needed for loading import entries from 2130 // a DLL without import library, this also just needs running once. 2131 // If it ends up pulling in more object files from static libraries, 2132 // (and maybe doing more stdcall fixups along the way), this would need 2133 // to loop these two calls. 2134 symtab->loadMinGWSymbols(); 2135 run(); 2136 } 2137 2138 // At this point, we should not have any symbols that cannot be resolved. 2139 // If we are going to do codegen for link-time optimization, check for 2140 // unresolvable symbols first, so we don't spend time generating code that 2141 // will fail to link anyway. 2142 if (!BitcodeFile::instances.empty() && !config->forceUnresolved) 2143 symtab->reportUnresolvable(); 2144 if (errorCount()) 2145 return; 2146 2147 config->hadExplicitExports = !config->exports.empty(); 2148 if (config->mingw) { 2149 // In MinGW, all symbols are automatically exported if no symbols 2150 // are chosen to be exported. 2151 maybeExportMinGWSymbols(args); 2152 } 2153 2154 // Do LTO by compiling bitcode input files to a set of native COFF files then 2155 // link those files (unless -thinlto-index-only was given, in which case we 2156 // resolve symbols and write indices, but don't generate native code or link). 2157 symtab->addCombinedLTOObjects(); 2158 2159 // If -thinlto-index-only is given, we should create only "index 2160 // files" and not object files. Index file creation is already done 2161 // in addCombinedLTOObject, so we are done if that's the case. 2162 if (config->thinLTOIndexOnly) 2163 return; 2164 2165 // If we generated native object files from bitcode files, this resolves 2166 // references to the symbols we use from them. 2167 run(); 2168 2169 // Apply symbol renames for -wrap. 2170 if (!wrapped.empty()) 2171 wrapSymbols(wrapped); 2172 2173 // Resolve remaining undefined symbols and warn about imported locals. 2174 symtab->resolveRemainingUndefines(); 2175 if (errorCount()) 2176 return; 2177 2178 if (config->mingw) { 2179 // Make sure the crtend.o object is the last object file. This object 2180 // file can contain terminating section chunks that need to be placed 2181 // last. GNU ld processes files and static libraries explicitly in the 2182 // order provided on the command line, while lld will pull in needed 2183 // files from static libraries only after the last object file on the 2184 // command line. 2185 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end(); 2186 i != e; i++) { 2187 ObjFile *file = *i; 2188 if (isCrtend(file->getName())) { 2189 ObjFile::instances.erase(i); 2190 ObjFile::instances.push_back(file); 2191 break; 2192 } 2193 } 2194 } 2195 2196 // Windows specific -- when we are creating a .dll file, we also 2197 // need to create a .lib file. In MinGW mode, we only do that when the 2198 // -implib option is given explicitly, for compatibility with GNU ld. 2199 if (!config->exports.empty() || config->dll) { 2200 fixupExports(); 2201 if (!config->mingw || !config->implib.empty()) 2202 createImportLibrary(/*asLib=*/false); 2203 assignExportOrdinals(); 2204 } 2205 2206 // Handle /output-def (MinGW specific). 2207 if (auto *arg = args.getLastArg(OPT_output_def)) 2208 writeDefFile(arg->getValue()); 2209 2210 // Set extra alignment for .comm symbols 2211 for (auto pair : config->alignComm) { 2212 StringRef name = pair.first; 2213 uint32_t alignment = pair.second; 2214 2215 Symbol *sym = symtab->find(name); 2216 if (!sym) { 2217 warn("/aligncomm symbol " + name + " not found"); 2218 continue; 2219 } 2220 2221 // If the symbol isn't common, it must have been replaced with a regular 2222 // symbol, which will carry its own alignment. 2223 auto *dc = dyn_cast<DefinedCommon>(sym); 2224 if (!dc) 2225 continue; 2226 2227 CommonChunk *c = dc->getChunk(); 2228 c->setAlignment(std::max(c->getAlignment(), alignment)); 2229 } 2230 2231 // Windows specific -- Create a side-by-side manifest file. 2232 if (config->manifest == Configuration::SideBySide) 2233 createSideBySideManifest(); 2234 2235 // Handle /order. We want to do this at this moment because we 2236 // need a complete list of comdat sections to warn on nonexistent 2237 // functions. 2238 if (auto *arg = args.getLastArg(OPT_order)) { 2239 if (args.hasArg(OPT_call_graph_ordering_file)) 2240 error("/order and /call-graph-order-file may not be used together"); 2241 parseOrderFile(arg->getValue()); 2242 config->callGraphProfileSort = false; 2243 } 2244 2245 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2246 if (config->callGraphProfileSort) { 2247 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2248 parseCallGraphFile(arg->getValue()); 2249 } 2250 readCallGraphsFromObjectFiles(); 2251 } 2252 2253 // Handle /print-symbol-order. 2254 if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2255 config->printSymbolOrder = arg->getValue(); 2256 2257 // Identify unreferenced COMDAT sections. 2258 if (config->doGC) { 2259 if (config->mingw) { 2260 // markLive doesn't traverse .eh_frame, but the personality function is 2261 // only reached that way. The proper solution would be to parse and 2262 // traverse the .eh_frame section, like the ELF linker does. 2263 // For now, just manually try to retain the known possible personality 2264 // functions. This doesn't bring in more object files, but only marks 2265 // functions that already have been included to be retained. 2266 for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) { 2267 Defined *d = dyn_cast_or_null<Defined>(symtab->findUnderscore(n)); 2268 if (d && !d->isGCRoot) { 2269 d->isGCRoot = true; 2270 config->gcroot.push_back(d); 2271 } 2272 } 2273 } 2274 2275 markLive(symtab->getChunks()); 2276 } 2277 2278 // Needs to happen after the last call to addFile(). 2279 convertResources(); 2280 2281 // Identify identical COMDAT sections to merge them. 2282 if (config->doICF != ICFLevel::None) { 2283 findKeepUniqueSections(); 2284 doICF(symtab->getChunks(), config->doICF); 2285 } 2286 2287 // Write the result. 2288 writeResult(); 2289 2290 // Stop early so we can print the results. 2291 rootTimer.stop(); 2292 if (config->showTiming) 2293 Timer::root().print(); 2294 } 2295 2296 } // namespace coff 2297 } // namespace lld 2298