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