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