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