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