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