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