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.Ordinal = e1.ordinal; 814 e2.Noname = e1.noname; 815 e2.Data = e1.data; 816 e2.Private = e1.isPrivate; 817 e2.Constant = e1.constant; 818 exports.push_back(e2); 819 } 820 821 std::string libName = getImportName(asLib); 822 std::string path = getImplibPath(); 823 824 if (!config->incremental) { 825 checkError(writeImportLibrary(libName, path, exports, config->machine, 826 config->mingw)); 827 return; 828 } 829 830 // If the import library already exists, replace it only if the contents 831 // have changed. 832 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 833 path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 834 if (!oldBuf) { 835 checkError(writeImportLibrary(libName, path, exports, config->machine, 836 config->mingw)); 837 return; 838 } 839 840 SmallString<128> tmpName; 841 if (std::error_code ec = 842 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 843 fatal("cannot create temporary file for import library " + path + ": " + 844 ec.message()); 845 846 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine, 847 config->mingw)) { 848 checkError(std::move(e)); 849 return; 850 } 851 852 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 853 tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 854 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 855 oldBuf->reset(); 856 checkError(errorCodeToError(sys::fs::rename(tmpName, path))); 857 } else { 858 sys::fs::remove(tmpName); 859 } 860 } 861 862 static void parseModuleDefs(StringRef path) { 863 std::unique_ptr<MemoryBuffer> mb = 864 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 865 /*RequiresNullTerminator=*/false, 866 /*IsVolatile=*/true), 867 "could not open " + path); 868 COFFModuleDefinition m = check(parseCOFFModuleDefinition( 869 mb->getMemBufferRef(), config->machine, config->mingw)); 870 871 // Include in /reproduce: output if applicable. 872 driver->takeBuffer(std::move(mb)); 873 874 if (config->outputFile.empty()) 875 config->outputFile = std::string(saver.save(m.OutputFile)); 876 config->importName = std::string(saver.save(m.ImportName)); 877 if (m.ImageBase) 878 config->imageBase = m.ImageBase; 879 if (m.StackReserve) 880 config->stackReserve = m.StackReserve; 881 if (m.StackCommit) 882 config->stackCommit = m.StackCommit; 883 if (m.HeapReserve) 884 config->heapReserve = m.HeapReserve; 885 if (m.HeapCommit) 886 config->heapCommit = m.HeapCommit; 887 if (m.MajorImageVersion) 888 config->majorImageVersion = m.MajorImageVersion; 889 if (m.MinorImageVersion) 890 config->minorImageVersion = m.MinorImageVersion; 891 if (m.MajorOSVersion) 892 config->majorOSVersion = m.MajorOSVersion; 893 if (m.MinorOSVersion) 894 config->minorOSVersion = m.MinorOSVersion; 895 896 for (COFFShortExport e1 : m.Exports) { 897 Export e2; 898 // In simple cases, only Name is set. Renamed exports are parsed 899 // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 900 // it shouldn't be a normal exported function but a forward to another 901 // DLL instead. This is supported by both MS and GNU linkers. 902 if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 903 StringRef(e1.Name).contains('.')) { 904 e2.name = saver.save(e1.ExtName); 905 e2.forwardTo = saver.save(e1.Name); 906 config->exports.push_back(e2); 907 continue; 908 } 909 e2.name = saver.save(e1.Name); 910 e2.extName = saver.save(e1.ExtName); 911 e2.ordinal = e1.Ordinal; 912 e2.noname = e1.Noname; 913 e2.data = e1.Data; 914 e2.isPrivate = e1.Private; 915 e2.constant = e1.Constant; 916 config->exports.push_back(e2); 917 } 918 } 919 920 void LinkerDriver::enqueueTask(std::function<void()> task) { 921 taskQueue.push_back(std::move(task)); 922 } 923 924 bool LinkerDriver::run() { 925 ScopedTimer t(ctx.inputFileTimer); 926 927 bool didWork = !taskQueue.empty(); 928 while (!taskQueue.empty()) { 929 taskQueue.front()(); 930 taskQueue.pop_front(); 931 } 932 return didWork; 933 } 934 935 // Parse an /order file. If an option is given, the linker places 936 // COMDAT sections in the same order as their names appear in the 937 // given file. 938 static void parseOrderFile(COFFLinkerContext &ctx, StringRef arg) { 939 // For some reason, the MSVC linker requires a filename to be 940 // preceded by "@". 941 if (!arg.startswith("@")) { 942 error("malformed /order option: '@' missing"); 943 return; 944 } 945 946 // Get a list of all comdat sections for error checking. 947 DenseSet<StringRef> set; 948 for (Chunk *c : ctx.symtab.getChunks()) 949 if (auto *sec = dyn_cast<SectionChunk>(c)) 950 if (sec->sym) 951 set.insert(sec->sym->getName()); 952 953 // Open a file. 954 StringRef path = arg.substr(1); 955 std::unique_ptr<MemoryBuffer> mb = 956 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 957 /*RequiresNullTerminator=*/false, 958 /*IsVolatile=*/true), 959 "could not open " + path); 960 961 // Parse a file. An order file contains one symbol per line. 962 // All symbols that were not present in a given order file are 963 // considered to have the lowest priority 0 and are placed at 964 // end of an output section. 965 for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 966 std::string s(arg); 967 if (config->machine == I386 && !isDecorated(s)) 968 s = "_" + s; 969 970 if (set.count(s) == 0) { 971 if (config->warnMissingOrderSymbol) 972 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 973 } 974 else 975 config->order[s] = INT_MIN + config->order.size(); 976 } 977 978 // Include in /reproduce: output if applicable. 979 driver->takeBuffer(std::move(mb)); 980 } 981 982 static void parseCallGraphFile(COFFLinkerContext &ctx, StringRef path) { 983 std::unique_ptr<MemoryBuffer> mb = 984 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 985 /*RequiresNullTerminator=*/false, 986 /*IsVolatile=*/true), 987 "could not open " + path); 988 989 // Build a map from symbol name to section. 990 DenseMap<StringRef, Symbol *> map; 991 for (ObjFile *file : ctx.objFileInstances) 992 for (Symbol *sym : file->getSymbols()) 993 if (sym) 994 map[sym->getName()] = sym; 995 996 auto findSection = [&](StringRef name) -> SectionChunk * { 997 Symbol *sym = map.lookup(name); 998 if (!sym) { 999 if (config->warnMissingOrderSymbol) 1000 warn(path + ": no such symbol: " + name); 1001 return nullptr; 1002 } 1003 1004 if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 1005 return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 1006 return nullptr; 1007 }; 1008 1009 for (StringRef line : args::getLines(*mb)) { 1010 SmallVector<StringRef, 3> fields; 1011 line.split(fields, ' '); 1012 uint64_t count; 1013 1014 if (fields.size() != 3 || !to_integer(fields[2], count)) { 1015 error(path + ": parse error"); 1016 return; 1017 } 1018 1019 if (SectionChunk *from = findSection(fields[0])) 1020 if (SectionChunk *to = findSection(fields[1])) 1021 config->callGraphProfile[{from, to}] += count; 1022 } 1023 1024 // Include in /reproduce: output if applicable. 1025 driver->takeBuffer(std::move(mb)); 1026 } 1027 1028 static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { 1029 for (ObjFile *obj : ctx.objFileInstances) { 1030 if (obj->callgraphSec) { 1031 ArrayRef<uint8_t> contents; 1032 cantFail( 1033 obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1034 BinaryStreamReader reader(contents, support::little); 1035 while (!reader.empty()) { 1036 uint32_t fromIndex, toIndex; 1037 uint64_t count; 1038 if (Error err = reader.readInteger(fromIndex)) 1039 fatal(toString(obj) + ": Expected 32-bit integer"); 1040 if (Error err = reader.readInteger(toIndex)) 1041 fatal(toString(obj) + ": Expected 32-bit integer"); 1042 if (Error err = reader.readInteger(count)) 1043 fatal(toString(obj) + ": Expected 64-bit integer"); 1044 auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1045 auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1046 if (!fromSym || !toSym) 1047 continue; 1048 auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1049 auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1050 if (from && to) 1051 config->callGraphProfile[{from, to}] += count; 1052 } 1053 } 1054 } 1055 } 1056 1057 static void markAddrsig(Symbol *s) { 1058 if (auto *d = dyn_cast_or_null<Defined>(s)) 1059 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 1060 c->keepUnique = true; 1061 } 1062 1063 static void findKeepUniqueSections(COFFLinkerContext &ctx) { 1064 // Exported symbols could be address-significant in other executables or DSOs, 1065 // so we conservatively mark them as address-significant. 1066 for (Export &r : config->exports) 1067 markAddrsig(r.sym); 1068 1069 // Visit the address-significance table in each object file and mark each 1070 // referenced symbol as address-significant. 1071 for (ObjFile *obj : ctx.objFileInstances) { 1072 ArrayRef<Symbol *> syms = obj->getSymbols(); 1073 if (obj->addrsigSec) { 1074 ArrayRef<uint8_t> contents; 1075 cantFail( 1076 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 1077 const uint8_t *cur = contents.begin(); 1078 while (cur != contents.end()) { 1079 unsigned size; 1080 const char *err; 1081 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 1082 if (err) 1083 fatal(toString(obj) + ": could not decode addrsig section: " + err); 1084 if (symIndex >= syms.size()) 1085 fatal(toString(obj) + ": invalid symbol index in addrsig section"); 1086 markAddrsig(syms[symIndex]); 1087 cur += size; 1088 } 1089 } else { 1090 // If an object file does not have an address-significance table, 1091 // conservatively mark all of its symbols as address-significant. 1092 for (Symbol *s : syms) 1093 markAddrsig(s); 1094 } 1095 } 1096 } 1097 1098 // link.exe replaces each %foo% in altPath with the contents of environment 1099 // variable foo, and adds the two magic env vars _PDB (expands to the basename 1100 // of pdb's output path) and _EXT (expands to the extension of the output 1101 // binary). 1102 // lld only supports %_PDB% and %_EXT% and warns on references to all other env 1103 // vars. 1104 static void parsePDBAltPath(StringRef altPath) { 1105 SmallString<128> buf; 1106 StringRef pdbBasename = 1107 sys::path::filename(config->pdbPath, sys::path::Style::windows); 1108 StringRef binaryExtension = 1109 sys::path::extension(config->outputFile, sys::path::Style::windows); 1110 if (!binaryExtension.empty()) 1111 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 1112 1113 // Invariant: 1114 // +--------- cursor ('a...' might be the empty string). 1115 // | +----- firstMark 1116 // | | +- secondMark 1117 // v v v 1118 // a...%...%... 1119 size_t cursor = 0; 1120 while (cursor < altPath.size()) { 1121 size_t firstMark, secondMark; 1122 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos || 1123 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) { 1124 // Didn't find another full fragment, treat rest of string as literal. 1125 buf.append(altPath.substr(cursor)); 1126 break; 1127 } 1128 1129 // Found a full fragment. Append text in front of first %, and interpret 1130 // text between first and second % as variable name. 1131 buf.append(altPath.substr(cursor, firstMark - cursor)); 1132 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1); 1133 if (var.equals_insensitive("%_pdb%")) 1134 buf.append(pdbBasename); 1135 else if (var.equals_insensitive("%_ext%")) 1136 buf.append(binaryExtension); 1137 else { 1138 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 1139 var + " as literal"); 1140 buf.append(var); 1141 } 1142 1143 cursor = secondMark + 1; 1144 } 1145 1146 config->pdbAltPath = buf; 1147 } 1148 1149 /// Convert resource files and potentially merge input resource object 1150 /// trees into one resource tree. 1151 /// Call after ObjFile::Instances is complete. 1152 void LinkerDriver::convertResources() { 1153 std::vector<ObjFile *> resourceObjFiles; 1154 1155 for (ObjFile *f : ctx.objFileInstances) { 1156 if (f->isResourceObjFile()) 1157 resourceObjFiles.push_back(f); 1158 } 1159 1160 if (!config->mingw && 1161 (resourceObjFiles.size() > 1 || 1162 (resourceObjFiles.size() == 1 && !resources.empty()))) { 1163 error((!resources.empty() ? "internal .obj file created from .res files" 1164 : toString(resourceObjFiles[1])) + 1165 ": more than one resource obj file not allowed, already got " + 1166 toString(resourceObjFiles.front())); 1167 return; 1168 } 1169 1170 if (resources.empty() && resourceObjFiles.size() <= 1) { 1171 // No resources to convert, and max one resource object file in 1172 // the input. Keep that preconverted resource section as is. 1173 for (ObjFile *f : resourceObjFiles) 1174 f->includeResourceChunks(); 1175 return; 1176 } 1177 ObjFile *f = 1178 make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles)); 1179 ctx.symtab.addFile(f); 1180 f->includeResourceChunks(); 1181 } 1182 1183 // In MinGW, if no symbols are chosen to be exported, then all symbols are 1184 // automatically exported by default. This behavior can be forced by the 1185 // -export-all-symbols option, so that it happens even when exports are 1186 // explicitly specified. The automatic behavior can be disabled using the 1187 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 1188 // than MinGW in the case that nothing is explicitly exported. 1189 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1190 if (!args.hasArg(OPT_export_all_symbols)) { 1191 if (!config->dll) 1192 return; 1193 1194 if (!config->exports.empty()) 1195 return; 1196 if (args.hasArg(OPT_exclude_all_symbols)) 1197 return; 1198 } 1199 1200 AutoExporter exporter; 1201 1202 for (auto *arg : args.filtered(OPT_wholearchive_file)) 1203 if (Optional<StringRef> path = doFindFile(arg->getValue())) 1204 exporter.addWholeArchive(*path); 1205 1206 ctx.symtab.forEachSymbol([&](Symbol *s) { 1207 auto *def = dyn_cast<Defined>(s); 1208 if (!exporter.shouldExport(ctx, def)) 1209 return; 1210 1211 if (!def->isGCRoot) { 1212 def->isGCRoot = true; 1213 config->gcroot.push_back(def); 1214 } 1215 1216 Export e; 1217 e.name = def->getName(); 1218 e.sym = def; 1219 if (Chunk *c = def->getChunk()) 1220 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 1221 e.data = true; 1222 s->isUsedInRegularObj = true; 1223 config->exports.push_back(e); 1224 }); 1225 } 1226 1227 // lld has a feature to create a tar file containing all input files as well as 1228 // all command line options, so that other people can run lld again with exactly 1229 // the same inputs. This feature is accessible via /linkrepro and /reproduce. 1230 // 1231 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 1232 // name while /reproduce takes a full path. We have /linkrepro for compatibility 1233 // with Microsoft link.exe. 1234 Optional<std::string> getReproduceFile(const opt::InputArgList &args) { 1235 if (auto *arg = args.getLastArg(OPT_reproduce)) 1236 return std::string(arg->getValue()); 1237 1238 if (auto *arg = args.getLastArg(OPT_linkrepro)) { 1239 SmallString<64> path = StringRef(arg->getValue()); 1240 sys::path::append(path, "repro.tar"); 1241 return std::string(path); 1242 } 1243 1244 // This is intentionally not guarded by OPT_lldignoreenv since writing 1245 // a repro tar file doesn't affect the main output. 1246 if (auto *path = getenv("LLD_REPRODUCE")) 1247 return std::string(path); 1248 1249 return None; 1250 } 1251 1252 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 1253 ScopedTimer rootTimer(ctx.rootTimer); 1254 1255 // Needed for LTO. 1256 InitializeAllTargetInfos(); 1257 InitializeAllTargets(); 1258 InitializeAllTargetMCs(); 1259 InitializeAllAsmParsers(); 1260 InitializeAllAsmPrinters(); 1261 1262 // If the first command line argument is "/lib", link.exe acts like lib.exe. 1263 // We call our own implementation of lib.exe that understands bitcode files. 1264 if (argsArr.size() > 1 && 1265 (StringRef(argsArr[1]).equals_insensitive("/lib") || 1266 StringRef(argsArr[1]).equals_insensitive("-lib"))) { 1267 if (llvm::libDriverMain(argsArr.slice(1)) != 0) 1268 fatal("lib failed"); 1269 return; 1270 } 1271 1272 // Parse command line options. 1273 ArgParser parser; 1274 opt::InputArgList args = parser.parse(argsArr); 1275 1276 // Parse and evaluate -mllvm options. 1277 std::vector<const char *> v; 1278 v.push_back("lld-link (LLVM option parsing)"); 1279 for (auto *arg : args.filtered(OPT_mllvm)) 1280 v.push_back(arg->getValue()); 1281 cl::ResetAllOptionOccurrences(); 1282 cl::ParseCommandLineOptions(v.size(), v.data()); 1283 1284 // Handle /errorlimit early, because error() depends on it. 1285 if (auto *arg = args.getLastArg(OPT_errorlimit)) { 1286 int n = 20; 1287 StringRef s = arg->getValue(); 1288 if (s.getAsInteger(10, n)) 1289 error(arg->getSpelling() + " number expected, but got " + s); 1290 errorHandler().errorLimit = n; 1291 } 1292 1293 // Handle /help 1294 if (args.hasArg(OPT_help)) { 1295 printHelp(argsArr[0]); 1296 return; 1297 } 1298 1299 // /threads: takes a positive integer and provides the default value for 1300 // /opt:lldltojobs=. 1301 if (auto *arg = args.getLastArg(OPT_threads)) { 1302 StringRef v(arg->getValue()); 1303 unsigned threads = 0; 1304 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1305 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1306 arg->getValue() + "'"); 1307 parallel::strategy = hardware_concurrency(threads); 1308 config->thinLTOJobs = v.str(); 1309 } 1310 1311 if (args.hasArg(OPT_show_timing)) 1312 config->showTiming = true; 1313 1314 config->showSummary = args.hasArg(OPT_summary); 1315 1316 // Handle --version, which is an lld extension. This option is a bit odd 1317 // because it doesn't start with "/", but we deliberately chose "--" to 1318 // avoid conflict with /version and for compatibility with clang-cl. 1319 if (args.hasArg(OPT_dash_dash_version)) { 1320 message(getLLDVersion()); 1321 return; 1322 } 1323 1324 // Handle /lldmingw early, since it can potentially affect how other 1325 // options are handled. 1326 config->mingw = args.hasArg(OPT_lldmingw); 1327 1328 // Handle /linkrepro and /reproduce. 1329 if (Optional<std::string> path = getReproduceFile(args)) { 1330 Expected<std::unique_ptr<TarWriter>> errOrWriter = 1331 TarWriter::create(*path, sys::path::stem(*path)); 1332 1333 if (errOrWriter) { 1334 tar = std::move(*errOrWriter); 1335 } else { 1336 error("/linkrepro: failed to open " + *path + ": " + 1337 toString(errOrWriter.takeError())); 1338 } 1339 } 1340 1341 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 1342 if (args.hasArg(OPT_deffile)) 1343 config->noEntry = true; 1344 else 1345 fatal("no input files"); 1346 } 1347 1348 // Construct search path list. 1349 searchPaths.push_back(""); 1350 for (auto *arg : args.filtered(OPT_libpath)) 1351 searchPaths.push_back(arg->getValue()); 1352 if (!args.hasArg(OPT_lldignoreenv)) 1353 addLibSearchPaths(); 1354 1355 // Handle /ignore 1356 for (auto *arg : args.filtered(OPT_ignore)) { 1357 SmallVector<StringRef, 8> vec; 1358 StringRef(arg->getValue()).split(vec, ','); 1359 for (StringRef s : vec) { 1360 if (s == "4037") 1361 config->warnMissingOrderSymbol = false; 1362 else if (s == "4099") 1363 config->warnDebugInfoUnusable = false; 1364 else if (s == "4217") 1365 config->warnLocallyDefinedImported = false; 1366 else if (s == "longsections") 1367 config->warnLongSectionNames = false; 1368 // Other warning numbers are ignored. 1369 } 1370 } 1371 1372 // Handle /out 1373 if (auto *arg = args.getLastArg(OPT_out)) 1374 config->outputFile = arg->getValue(); 1375 1376 // Handle /verbose 1377 if (args.hasArg(OPT_verbose)) 1378 config->verbose = true; 1379 errorHandler().verbose = config->verbose; 1380 1381 // Handle /force or /force:unresolved 1382 if (args.hasArg(OPT_force, OPT_force_unresolved)) 1383 config->forceUnresolved = true; 1384 1385 // Handle /force or /force:multiple 1386 if (args.hasArg(OPT_force, OPT_force_multiple)) 1387 config->forceMultiple = true; 1388 1389 // Handle /force or /force:multipleres 1390 if (args.hasArg(OPT_force, OPT_force_multipleres)) 1391 config->forceMultipleRes = true; 1392 1393 // Handle /debug 1394 DebugKind debug = parseDebugKind(args); 1395 if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1396 debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 1397 config->debug = true; 1398 config->incremental = true; 1399 } 1400 1401 // Handle /demangle 1402 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no); 1403 1404 // Handle /debugtype 1405 config->debugTypes = parseDebugTypes(args); 1406 1407 // Handle /driver[:uponly|:wdm]. 1408 config->driverUponly = args.hasArg(OPT_driver_uponly) || 1409 args.hasArg(OPT_driver_uponly_wdm) || 1410 args.hasArg(OPT_driver_wdm_uponly); 1411 config->driverWdm = args.hasArg(OPT_driver_wdm) || 1412 args.hasArg(OPT_driver_uponly_wdm) || 1413 args.hasArg(OPT_driver_wdm_uponly); 1414 config->driver = 1415 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1416 1417 // Handle /pdb 1418 bool shouldCreatePDB = 1419 (debug == DebugKind::Full || debug == DebugKind::GHash || 1420 debug == DebugKind::NoGHash); 1421 if (shouldCreatePDB) { 1422 if (auto *arg = args.getLastArg(OPT_pdb)) 1423 config->pdbPath = arg->getValue(); 1424 if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 1425 config->pdbAltPath = arg->getValue(); 1426 if (auto *arg = args.getLastArg(OPT_pdbpagesize)) 1427 parsePDBPageSize(arg->getValue()); 1428 if (args.hasArg(OPT_natvis)) 1429 config->natvisFiles = args.getAllArgValues(OPT_natvis); 1430 if (args.hasArg(OPT_pdbstream)) { 1431 for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 1432 const std::pair<StringRef, StringRef> nameFile = value.split("="); 1433 const StringRef name = nameFile.first; 1434 const std::string file = nameFile.second.str(); 1435 config->namedStreams[name] = file; 1436 } 1437 } 1438 1439 if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 1440 config->pdbSourcePath = arg->getValue(); 1441 } 1442 1443 // Handle /pdbstripped 1444 if (args.hasArg(OPT_pdbstripped)) 1445 warn("ignoring /pdbstripped flag, it is not yet supported"); 1446 1447 // Handle /noentry 1448 if (args.hasArg(OPT_noentry)) { 1449 if (args.hasArg(OPT_dll)) 1450 config->noEntry = true; 1451 else 1452 error("/noentry must be specified with /dll"); 1453 } 1454 1455 // Handle /dll 1456 if (args.hasArg(OPT_dll)) { 1457 config->dll = true; 1458 config->manifestID = 2; 1459 } 1460 1461 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 1462 // because we need to explicitly check whether that option or its inverse was 1463 // present in the argument list in order to handle /fixed. 1464 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 1465 if (dynamicBaseArg && 1466 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 1467 config->dynamicBase = false; 1468 1469 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 1470 // default setting for any other project type.", but link.exe defaults to 1471 // /FIXED:NO for exe outputs as well. Match behavior, not docs. 1472 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 1473 if (fixed) { 1474 if (dynamicBaseArg && 1475 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 1476 error("/fixed must not be specified with /dynamicbase"); 1477 } else { 1478 config->relocatable = false; 1479 config->dynamicBase = false; 1480 } 1481 } 1482 1483 // Handle /appcontainer 1484 config->appContainer = 1485 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 1486 1487 // Handle /machine 1488 if (auto *arg = args.getLastArg(OPT_machine)) { 1489 config->machine = getMachineType(arg->getValue()); 1490 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 1491 fatal(Twine("unknown /machine argument: ") + arg->getValue()); 1492 } 1493 1494 // Handle /nodefaultlib:<filename> 1495 for (auto *arg : args.filtered(OPT_nodefaultlib)) 1496 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 1497 1498 // Handle /nodefaultlib 1499 if (args.hasArg(OPT_nodefaultlib_all)) 1500 config->noDefaultLibAll = true; 1501 1502 // Handle /base 1503 if (auto *arg = args.getLastArg(OPT_base)) 1504 parseNumbers(arg->getValue(), &config->imageBase); 1505 1506 // Handle /filealign 1507 if (auto *arg = args.getLastArg(OPT_filealign)) { 1508 parseNumbers(arg->getValue(), &config->fileAlign); 1509 if (!isPowerOf2_64(config->fileAlign)) 1510 error("/filealign: not a power of two: " + Twine(config->fileAlign)); 1511 } 1512 1513 // Handle /stack 1514 if (auto *arg = args.getLastArg(OPT_stack)) 1515 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 1516 1517 // Handle /guard:cf 1518 if (auto *arg = args.getLastArg(OPT_guard)) 1519 parseGuard(arg->getValue()); 1520 1521 // Handle /heap 1522 if (auto *arg = args.getLastArg(OPT_heap)) 1523 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 1524 1525 // Handle /version 1526 if (auto *arg = args.getLastArg(OPT_version)) 1527 parseVersion(arg->getValue(), &config->majorImageVersion, 1528 &config->minorImageVersion); 1529 1530 // Handle /subsystem 1531 if (auto *arg = args.getLastArg(OPT_subsystem)) 1532 parseSubsystem(arg->getValue(), &config->subsystem, 1533 &config->majorSubsystemVersion, 1534 &config->minorSubsystemVersion); 1535 1536 // Handle /osversion 1537 if (auto *arg = args.getLastArg(OPT_osversion)) { 1538 parseVersion(arg->getValue(), &config->majorOSVersion, 1539 &config->minorOSVersion); 1540 } else { 1541 config->majorOSVersion = config->majorSubsystemVersion; 1542 config->minorOSVersion = config->minorSubsystemVersion; 1543 } 1544 1545 // Handle /timestamp 1546 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 1547 if (arg->getOption().getID() == OPT_repro) { 1548 config->timestamp = 0; 1549 config->repro = true; 1550 } else { 1551 config->repro = false; 1552 StringRef value(arg->getValue()); 1553 if (value.getAsInteger(0, config->timestamp)) 1554 fatal(Twine("invalid timestamp: ") + value + 1555 ". Expected 32-bit integer"); 1556 } 1557 } else { 1558 config->repro = false; 1559 config->timestamp = time(nullptr); 1560 } 1561 1562 // Handle /alternatename 1563 for (auto *arg : args.filtered(OPT_alternatename)) 1564 parseAlternateName(arg->getValue()); 1565 1566 // Handle /include 1567 for (auto *arg : args.filtered(OPT_incl)) 1568 addUndefined(arg->getValue()); 1569 1570 // Handle /implib 1571 if (auto *arg = args.getLastArg(OPT_implib)) 1572 config->implib = arg->getValue(); 1573 1574 // Handle /opt. 1575 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1576 Optional<ICFLevel> icfLevel = None; 1577 if (args.hasArg(OPT_profile)) 1578 icfLevel = ICFLevel::None; 1579 unsigned tailMerge = 1; 1580 bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER; 1581 bool ltoDebugPM = false; 1582 for (auto *arg : args.filtered(OPT_opt)) { 1583 std::string str = StringRef(arg->getValue()).lower(); 1584 SmallVector<StringRef, 1> vec; 1585 StringRef(str).split(vec, ','); 1586 for (StringRef s : vec) { 1587 if (s == "ref") { 1588 doGC = true; 1589 } else if (s == "noref") { 1590 doGC = false; 1591 } else if (s == "icf" || s.startswith("icf=")) { 1592 icfLevel = ICFLevel::All; 1593 } else if (s == "safeicf") { 1594 icfLevel = ICFLevel::Safe; 1595 } else if (s == "noicf") { 1596 icfLevel = ICFLevel::None; 1597 } else if (s == "lldtailmerge") { 1598 tailMerge = 2; 1599 } else if (s == "nolldtailmerge") { 1600 tailMerge = 0; 1601 } else if (s == "ltonewpassmanager") { 1602 ltoNewPM = true; 1603 } else if (s == "noltonewpassmanager") { 1604 ltoNewPM = false; 1605 } else if (s == "ltodebugpassmanager") { 1606 ltoDebugPM = true; 1607 } else if (s == "noltodebugpassmanager") { 1608 ltoDebugPM = false; 1609 } else if (s.startswith("lldlto=")) { 1610 StringRef optLevel = s.substr(7); 1611 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 1612 error("/opt:lldlto: invalid optimization level: " + optLevel); 1613 } else if (s.startswith("lldltojobs=")) { 1614 StringRef jobs = s.substr(11); 1615 if (!get_threadpool_strategy(jobs)) 1616 error("/opt:lldltojobs: invalid job count: " + jobs); 1617 config->thinLTOJobs = jobs.str(); 1618 } else if (s.startswith("lldltopartitions=")) { 1619 StringRef n = s.substr(17); 1620 if (n.getAsInteger(10, config->ltoPartitions) || 1621 config->ltoPartitions == 0) 1622 error("/opt:lldltopartitions: invalid partition count: " + n); 1623 } else if (s != "lbr" && s != "nolbr") 1624 error("/opt: unknown option: " + s); 1625 } 1626 } 1627 1628 if (!icfLevel) 1629 icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 1630 config->doGC = doGC; 1631 config->doICF = icfLevel.getValue(); 1632 config->tailMerge = 1633 (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1634 config->ltoNewPassManager = ltoNewPM; 1635 config->ltoDebugPassManager = ltoDebugPM; 1636 1637 // Handle /lldsavetemps 1638 if (args.hasArg(OPT_lldsavetemps)) 1639 config->saveTemps = true; 1640 1641 // Handle /kill-at 1642 if (args.hasArg(OPT_kill_at)) 1643 config->killAt = true; 1644 1645 // Handle /lldltocache 1646 if (auto *arg = args.getLastArg(OPT_lldltocache)) 1647 config->ltoCache = arg->getValue(); 1648 1649 // Handle /lldsavecachepolicy 1650 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 1651 config->ltoCachePolicy = CHECK( 1652 parseCachePruningPolicy(arg->getValue()), 1653 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 1654 1655 // Handle /failifmismatch 1656 for (auto *arg : args.filtered(OPT_failifmismatch)) 1657 checkFailIfMismatch(arg->getValue(), nullptr); 1658 1659 // Handle /merge 1660 for (auto *arg : args.filtered(OPT_merge)) 1661 parseMerge(arg->getValue()); 1662 1663 // Add default section merging rules after user rules. User rules take 1664 // precedence, but we will emit a warning if there is a conflict. 1665 parseMerge(".idata=.rdata"); 1666 parseMerge(".didat=.rdata"); 1667 parseMerge(".edata=.rdata"); 1668 parseMerge(".xdata=.rdata"); 1669 parseMerge(".bss=.data"); 1670 1671 if (config->mingw) { 1672 parseMerge(".ctors=.rdata"); 1673 parseMerge(".dtors=.rdata"); 1674 parseMerge(".CRT=.rdata"); 1675 } 1676 1677 // Handle /section 1678 for (auto *arg : args.filtered(OPT_section)) 1679 parseSection(arg->getValue()); 1680 1681 // Handle /align 1682 if (auto *arg = args.getLastArg(OPT_align)) { 1683 parseNumbers(arg->getValue(), &config->align); 1684 if (!isPowerOf2_64(config->align)) 1685 error("/align: not a power of two: " + StringRef(arg->getValue())); 1686 if (!args.hasArg(OPT_driver)) 1687 warn("/align specified without /driver; image may not run"); 1688 } 1689 1690 // Handle /aligncomm 1691 for (auto *arg : args.filtered(OPT_aligncomm)) 1692 parseAligncomm(arg->getValue()); 1693 1694 // Handle /manifestdependency. 1695 for (auto *arg : args.filtered(OPT_manifestdependency)) 1696 config->manifestDependencies.insert(arg->getValue()); 1697 1698 // Handle /manifest and /manifest: 1699 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 1700 if (arg->getOption().getID() == OPT_manifest) 1701 config->manifest = Configuration::SideBySide; 1702 else 1703 parseManifest(arg->getValue()); 1704 } 1705 1706 // Handle /manifestuac 1707 if (auto *arg = args.getLastArg(OPT_manifestuac)) 1708 parseManifestUAC(arg->getValue()); 1709 1710 // Handle /manifestfile 1711 if (auto *arg = args.getLastArg(OPT_manifestfile)) 1712 config->manifestFile = arg->getValue(); 1713 1714 // Handle /manifestinput 1715 for (auto *arg : args.filtered(OPT_manifestinput)) 1716 config->manifestInput.push_back(arg->getValue()); 1717 1718 if (!config->manifestInput.empty() && 1719 config->manifest != Configuration::Embed) { 1720 fatal("/manifestinput: requires /manifest:embed"); 1721 } 1722 1723 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1724 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1725 args.hasArg(OPT_thinlto_index_only_arg); 1726 config->thinLTOIndexOnlyArg = 1727 args.getLastArgValue(OPT_thinlto_index_only_arg); 1728 config->thinLTOPrefixReplace = 1729 getOldNewOptions(args, OPT_thinlto_prefix_replace); 1730 config->thinLTOObjectSuffixReplace = 1731 getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 1732 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1733 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1734 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1735 // Handle miscellaneous boolean flags. 1736 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1737 OPT_lto_pgo_warn_mismatch_no, true); 1738 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 1739 config->allowIsolation = 1740 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 1741 config->incremental = 1742 args.hasFlag(OPT_incremental, OPT_incremental_no, 1743 !config->doGC && config->doICF == ICFLevel::None && 1744 !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 1745 config->integrityCheck = 1746 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 1747 config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 1748 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 1749 for (auto *arg : args.filtered(OPT_swaprun)) 1750 parseSwaprun(arg->getValue()); 1751 config->terminalServerAware = 1752 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 1753 config->debugDwarf = debug == DebugKind::Dwarf; 1754 config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 1755 config->debugSymtab = debug == DebugKind::Symtab; 1756 config->autoImport = 1757 args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 1758 config->pseudoRelocs = args.hasFlag( 1759 OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1760 config->callGraphProfileSort = args.hasFlag( 1761 OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1762 config->stdcallFixup = 1763 args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1764 config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 1765 1766 // Don't warn about long section names, such as .debug_info, for mingw or 1767 // when -debug:dwarf is requested. 1768 if (config->mingw || config->debugDwarf) 1769 config->warnLongSectionNames = false; 1770 1771 config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 1772 config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 1773 1774 if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 1775 warn("/lldmap and /map have the same output file '" + config->mapFile + 1776 "'.\n>>> ignoring /lldmap"); 1777 config->lldmapFile.clear(); 1778 } 1779 1780 if (config->incremental && args.hasArg(OPT_profile)) { 1781 warn("ignoring '/incremental' due to '/profile' specification"); 1782 config->incremental = false; 1783 } 1784 1785 if (config->incremental && args.hasArg(OPT_order)) { 1786 warn("ignoring '/incremental' due to '/order' specification"); 1787 config->incremental = false; 1788 } 1789 1790 if (config->incremental && config->doGC) { 1791 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 1792 "disable"); 1793 config->incremental = false; 1794 } 1795 1796 if (config->incremental && config->doICF != ICFLevel::None) { 1797 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 1798 "disable"); 1799 config->incremental = false; 1800 } 1801 1802 if (errorCount()) 1803 return; 1804 1805 std::set<sys::fs::UniqueID> wholeArchives; 1806 for (auto *arg : args.filtered(OPT_wholearchive_file)) 1807 if (Optional<StringRef> path = doFindFile(arg->getValue())) 1808 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 1809 wholeArchives.insert(*id); 1810 1811 // A predicate returning true if a given path is an argument for 1812 // /wholearchive:, or /wholearchive is enabled globally. 1813 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 1814 // needs to be handled as "/wholearchive:foo.obj foo.obj". 1815 auto isWholeArchive = [&](StringRef path) -> bool { 1816 if (args.hasArg(OPT_wholearchive_flag)) 1817 return true; 1818 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 1819 return wholeArchives.count(*id); 1820 return false; 1821 }; 1822 1823 // Create a list of input files. These can be given as OPT_INPUT options 1824 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 1825 // and OPT_end_lib. 1826 bool inLib = false; 1827 for (auto *arg : args) { 1828 switch (arg->getOption().getID()) { 1829 case OPT_end_lib: 1830 if (!inLib) 1831 error("stray " + arg->getSpelling()); 1832 inLib = false; 1833 break; 1834 case OPT_start_lib: 1835 if (inLib) 1836 error("nested " + arg->getSpelling()); 1837 inLib = true; 1838 break; 1839 case OPT_wholearchive_file: 1840 if (Optional<StringRef> path = findFile(arg->getValue())) 1841 enqueuePath(*path, true, inLib); 1842 break; 1843 case OPT_INPUT: 1844 if (Optional<StringRef> path = findFile(arg->getValue())) 1845 enqueuePath(*path, isWholeArchive(*path), inLib); 1846 break; 1847 default: 1848 // Ignore other options. 1849 break; 1850 } 1851 } 1852 1853 // Process files specified as /defaultlib. These should be enequeued after 1854 // other files, which is why they are in a separate loop. 1855 for (auto *arg : args.filtered(OPT_defaultlib)) 1856 if (Optional<StringRef> path = findLib(arg->getValue())) 1857 enqueuePath(*path, false, false); 1858 1859 // Read all input files given via the command line. 1860 run(); 1861 1862 if (errorCount()) 1863 return; 1864 1865 // We should have inferred a machine type by now from the input files, but if 1866 // not we assume x64. 1867 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 1868 warn("/machine is not specified. x64 is assumed"); 1869 config->machine = AMD64; 1870 } 1871 config->wordsize = config->is64() ? 8 : 4; 1872 1873 // Handle /safeseh, x86 only, on by default, except for mingw. 1874 if (config->machine == I386) { 1875 config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 1876 config->noSEH = args.hasArg(OPT_noseh); 1877 } 1878 1879 // Handle /functionpadmin 1880 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 1881 parseFunctionPadMin(arg, config->machine); 1882 1883 if (tar) 1884 tar->append("response.txt", 1885 createResponseFile(args, filePaths, 1886 ArrayRef<StringRef>(searchPaths).slice(1))); 1887 1888 // Handle /largeaddressaware 1889 config->largeAddressAware = args.hasFlag( 1890 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 1891 1892 // Handle /highentropyva 1893 config->highEntropyVA = 1894 config->is64() && 1895 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 1896 1897 if (!config->dynamicBase && 1898 (config->machine == ARMNT || config->machine == ARM64)) 1899 error("/dynamicbase:no is not compatible with " + 1900 machineToStr(config->machine)); 1901 1902 // Handle /export 1903 for (auto *arg : args.filtered(OPT_export)) { 1904 Export e = parseExport(arg->getValue()); 1905 if (config->machine == I386) { 1906 if (!isDecorated(e.name)) 1907 e.name = saver.save("_" + e.name); 1908 if (!e.extName.empty() && !isDecorated(e.extName)) 1909 e.extName = saver.save("_" + e.extName); 1910 } 1911 config->exports.push_back(e); 1912 } 1913 1914 // Handle /def 1915 if (auto *arg = args.getLastArg(OPT_deffile)) { 1916 // parseModuleDefs mutates Config object. 1917 parseModuleDefs(arg->getValue()); 1918 } 1919 1920 // Handle generation of import library from a def file. 1921 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 1922 fixupExports(); 1923 createImportLibrary(/*asLib=*/true); 1924 return; 1925 } 1926 1927 // Windows specific -- if no /subsystem is given, we need to infer 1928 // that from entry point name. Must happen before /entry handling, 1929 // and after the early return when just writing an import library. 1930 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 1931 config->subsystem = inferSubsystem(); 1932 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 1933 fatal("subsystem must be defined"); 1934 } 1935 1936 // Handle /entry and /dll 1937 if (auto *arg = args.getLastArg(OPT_entry)) { 1938 config->entry = addUndefined(mangle(arg->getValue())); 1939 } else if (!config->entry && !config->noEntry) { 1940 if (args.hasArg(OPT_dll)) { 1941 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 1942 : "_DllMainCRTStartup"; 1943 config->entry = addUndefined(s); 1944 } else if (config->driverWdm) { 1945 // /driver:wdm implies /entry:_NtProcessStartup 1946 config->entry = addUndefined(mangle("_NtProcessStartup")); 1947 } else { 1948 // Windows specific -- If entry point name is not given, we need to 1949 // infer that from user-defined entry name. 1950 StringRef s = findDefaultEntry(); 1951 if (s.empty()) 1952 fatal("entry point must be defined"); 1953 config->entry = addUndefined(s); 1954 log("Entry name inferred: " + s); 1955 } 1956 } 1957 1958 // Handle /delayload 1959 for (auto *arg : args.filtered(OPT_delayload)) { 1960 config->delayLoads.insert(StringRef(arg->getValue()).lower()); 1961 if (config->machine == I386) { 1962 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 1963 } else { 1964 config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 1965 } 1966 } 1967 1968 // Set default image name if neither /out or /def set it. 1969 if (config->outputFile.empty()) { 1970 config->outputFile = getOutputPath( 1971 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue()); 1972 } 1973 1974 // Fail early if an output file is not writable. 1975 if (auto e = tryCreateFile(config->outputFile)) { 1976 error("cannot open output file " + config->outputFile + ": " + e.message()); 1977 return; 1978 } 1979 1980 if (shouldCreatePDB) { 1981 // Put the PDB next to the image if no /pdb flag was passed. 1982 if (config->pdbPath.empty()) { 1983 config->pdbPath = config->outputFile; 1984 sys::path::replace_extension(config->pdbPath, ".pdb"); 1985 } 1986 1987 // The embedded PDB path should be the absolute path to the PDB if no 1988 // /pdbaltpath flag was passed. 1989 if (config->pdbAltPath.empty()) { 1990 config->pdbAltPath = config->pdbPath; 1991 1992 // It's important to make the path absolute and remove dots. This path 1993 // will eventually be written into the PE header, and certain Microsoft 1994 // tools won't work correctly if these assumptions are not held. 1995 sys::fs::make_absolute(config->pdbAltPath); 1996 sys::path::remove_dots(config->pdbAltPath); 1997 } else { 1998 // Don't do this earlier, so that Config->OutputFile is ready. 1999 parsePDBAltPath(config->pdbAltPath); 2000 } 2001 } 2002 2003 // Set default image base if /base is not given. 2004 if (config->imageBase == uint64_t(-1)) 2005 config->imageBase = getDefaultImageBase(); 2006 2007 ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr); 2008 if (config->machine == I386) { 2009 ctx.symtab.addAbsolute("___safe_se_handler_table", 0); 2010 ctx.symtab.addAbsolute("___safe_se_handler_count", 0); 2011 } 2012 2013 ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0); 2014 ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0); 2015 ctx.symtab.addAbsolute(mangle("__guard_flags"), 0); 2016 ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0); 2017 ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0); 2018 ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0); 2019 ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0); 2020 // Needed for MSVC 2017 15.5 CRT. 2021 ctx.symtab.addAbsolute(mangle("__enclave_config"), 0); 2022 // Needed for MSVC 2019 16.8 CRT. 2023 ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0); 2024 ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0); 2025 2026 if (config->pseudoRelocs) { 2027 ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 2028 ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 2029 } 2030 if (config->mingw) { 2031 ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0); 2032 ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0); 2033 } 2034 2035 // This code may add new undefined symbols to the link, which may enqueue more 2036 // symbol resolution tasks, so we need to continue executing tasks until we 2037 // converge. 2038 do { 2039 // Windows specific -- if entry point is not found, 2040 // search for its mangled names. 2041 if (config->entry) 2042 mangleMaybe(config->entry); 2043 2044 // Windows specific -- Make sure we resolve all dllexported symbols. 2045 for (Export &e : config->exports) { 2046 if (!e.forwardTo.empty()) 2047 continue; 2048 e.sym = addUndefined(e.name); 2049 if (!e.directives) 2050 e.symbolName = mangleMaybe(e.sym); 2051 } 2052 2053 // Add weak aliases. Weak aliases is a mechanism to give remaining 2054 // undefined symbols final chance to be resolved successfully. 2055 for (auto pair : config->alternateNames) { 2056 StringRef from = pair.first; 2057 StringRef to = pair.second; 2058 Symbol *sym = ctx.symtab.find(from); 2059 if (!sym) 2060 continue; 2061 if (auto *u = dyn_cast<Undefined>(sym)) 2062 if (!u->weakAlias) 2063 u->weakAlias = ctx.symtab.addUndefined(to); 2064 } 2065 2066 // If any inputs are bitcode files, the LTO code generator may create 2067 // references to library functions that are not explicit in the bitcode 2068 // file's symbol table. If any of those library functions are defined in a 2069 // bitcode file in an archive member, we need to arrange to use LTO to 2070 // compile those archive members by adding them to the link beforehand. 2071 if (!ctx.bitcodeFileInstances.empty()) 2072 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2073 ctx.symtab.addLibcall(s); 2074 2075 // Windows specific -- if __load_config_used can be resolved, resolve it. 2076 if (ctx.symtab.findUnderscore("_load_config_used")) 2077 addUndefined(mangle("_load_config_used")); 2078 } while (run()); 2079 2080 if (args.hasArg(OPT_include_optional)) { 2081 // Handle /includeoptional 2082 for (auto *arg : args.filtered(OPT_include_optional)) 2083 if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue()))) 2084 addUndefined(arg->getValue()); 2085 while (run()); 2086 } 2087 2088 // Create wrapped symbols for -wrap option. 2089 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args); 2090 // Load more object files that might be needed for wrapped symbols. 2091 if (!wrapped.empty()) 2092 while (run()); 2093 2094 if (config->autoImport || config->stdcallFixup) { 2095 // MinGW specific. 2096 // Load any further object files that might be needed for doing automatic 2097 // imports, and do stdcall fixups. 2098 // 2099 // For cases with no automatically imported symbols, this iterates once 2100 // over the symbol table and doesn't do anything. 2101 // 2102 // For the normal case with a few automatically imported symbols, this 2103 // should only need to be run once, since each new object file imported 2104 // is an import library and wouldn't add any new undefined references, 2105 // but there's nothing stopping the __imp_ symbols from coming from a 2106 // normal object file as well (although that won't be used for the 2107 // actual autoimport later on). If this pass adds new undefined references, 2108 // we won't iterate further to resolve them. 2109 // 2110 // If stdcall fixups only are needed for loading import entries from 2111 // a DLL without import library, this also just needs running once. 2112 // If it ends up pulling in more object files from static libraries, 2113 // (and maybe doing more stdcall fixups along the way), this would need 2114 // to loop these two calls. 2115 ctx.symtab.loadMinGWSymbols(); 2116 run(); 2117 } 2118 2119 // At this point, we should not have any symbols that cannot be resolved. 2120 // If we are going to do codegen for link-time optimization, check for 2121 // unresolvable symbols first, so we don't spend time generating code that 2122 // will fail to link anyway. 2123 if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved) 2124 ctx.symtab.reportUnresolvable(); 2125 if (errorCount()) 2126 return; 2127 2128 config->hadExplicitExports = !config->exports.empty(); 2129 if (config->mingw) { 2130 // In MinGW, all symbols are automatically exported if no symbols 2131 // are chosen to be exported. 2132 maybeExportMinGWSymbols(args); 2133 } 2134 2135 // Do LTO by compiling bitcode input files to a set of native COFF files then 2136 // link those files (unless -thinlto-index-only was given, in which case we 2137 // resolve symbols and write indices, but don't generate native code or link). 2138 ctx.symtab.compileBitcodeFiles(); 2139 2140 // If -thinlto-index-only is given, we should create only "index 2141 // files" and not object files. Index file creation is already done 2142 // in compileBitcodeFiles, so we are done if that's the case. 2143 if (config->thinLTOIndexOnly) 2144 return; 2145 2146 // If we generated native object files from bitcode files, this resolves 2147 // references to the symbols we use from them. 2148 run(); 2149 2150 // Apply symbol renames for -wrap. 2151 if (!wrapped.empty()) 2152 wrapSymbols(ctx, wrapped); 2153 2154 // Resolve remaining undefined symbols and warn about imported locals. 2155 ctx.symtab.resolveRemainingUndefines(); 2156 if (errorCount()) 2157 return; 2158 2159 if (config->mingw) { 2160 // Make sure the crtend.o object is the last object file. This object 2161 // file can contain terminating section chunks that need to be placed 2162 // last. GNU ld processes files and static libraries explicitly in the 2163 // order provided on the command line, while lld will pull in needed 2164 // files from static libraries only after the last object file on the 2165 // command line. 2166 for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); 2167 i != e; i++) { 2168 ObjFile *file = *i; 2169 if (isCrtend(file->getName())) { 2170 ctx.objFileInstances.erase(i); 2171 ctx.objFileInstances.push_back(file); 2172 break; 2173 } 2174 } 2175 } 2176 2177 // Windows specific -- when we are creating a .dll file, we also 2178 // need to create a .lib file. In MinGW mode, we only do that when the 2179 // -implib option is given explicitly, for compatibility with GNU ld. 2180 if (!config->exports.empty() || config->dll) { 2181 fixupExports(); 2182 if (!config->mingw || !config->implib.empty()) 2183 createImportLibrary(/*asLib=*/false); 2184 assignExportOrdinals(); 2185 } 2186 2187 // Handle /output-def (MinGW specific). 2188 if (auto *arg = args.getLastArg(OPT_output_def)) 2189 writeDefFile(arg->getValue()); 2190 2191 // Set extra alignment for .comm symbols 2192 for (auto pair : config->alignComm) { 2193 StringRef name = pair.first; 2194 uint32_t alignment = pair.second; 2195 2196 Symbol *sym = ctx.symtab.find(name); 2197 if (!sym) { 2198 warn("/aligncomm symbol " + name + " not found"); 2199 continue; 2200 } 2201 2202 // If the symbol isn't common, it must have been replaced with a regular 2203 // symbol, which will carry its own alignment. 2204 auto *dc = dyn_cast<DefinedCommon>(sym); 2205 if (!dc) 2206 continue; 2207 2208 CommonChunk *c = dc->getChunk(); 2209 c->setAlignment(std::max(c->getAlignment(), alignment)); 2210 } 2211 2212 // Windows specific -- Create an embedded or side-by-side manifest. 2213 // /manifestdependency: enables /manifest unless an explicit /manifest:no is 2214 // also passed. 2215 if (config->manifest == Configuration::Embed) 2216 addBuffer(createManifestRes(), false, false); 2217 else if (config->manifest == Configuration::SideBySide || 2218 (config->manifest == Configuration::Default && 2219 !config->manifestDependencies.empty())) 2220 createSideBySideManifest(); 2221 2222 // Handle /order. We want to do this at this moment because we 2223 // need a complete list of comdat sections to warn on nonexistent 2224 // functions. 2225 if (auto *arg = args.getLastArg(OPT_order)) { 2226 if (args.hasArg(OPT_call_graph_ordering_file)) 2227 error("/order and /call-graph-order-file may not be used together"); 2228 parseOrderFile(ctx, arg->getValue()); 2229 config->callGraphProfileSort = false; 2230 } 2231 2232 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2233 if (config->callGraphProfileSort) { 2234 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2235 parseCallGraphFile(ctx, arg->getValue()); 2236 } 2237 readCallGraphsFromObjectFiles(ctx); 2238 } 2239 2240 // Handle /print-symbol-order. 2241 if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2242 config->printSymbolOrder = arg->getValue(); 2243 2244 // Identify unreferenced COMDAT sections. 2245 if (config->doGC) { 2246 if (config->mingw) { 2247 // markLive doesn't traverse .eh_frame, but the personality function is 2248 // only reached that way. The proper solution would be to parse and 2249 // traverse the .eh_frame section, like the ELF linker does. 2250 // For now, just manually try to retain the known possible personality 2251 // functions. This doesn't bring in more object files, but only marks 2252 // functions that already have been included to be retained. 2253 for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) { 2254 Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n)); 2255 if (d && !d->isGCRoot) { 2256 d->isGCRoot = true; 2257 config->gcroot.push_back(d); 2258 } 2259 } 2260 } 2261 2262 markLive(ctx); 2263 } 2264 2265 // Needs to happen after the last call to addFile(). 2266 convertResources(); 2267 2268 // Identify identical COMDAT sections to merge them. 2269 if (config->doICF != ICFLevel::None) { 2270 findKeepUniqueSections(ctx); 2271 doICF(ctx, config->doICF); 2272 } 2273 2274 // Write the result. 2275 writeResult(ctx); 2276 2277 // Stop early so we can print the results. 2278 rootTimer.stop(); 2279 if (config->showTiming) 2280 ctx.rootTimer.print(); 2281 } 2282 2283 } // namespace coff 2284 } // namespace lld 2285