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