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