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