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 else if (s == "longsections") 1192 config->warnLongSectionNames = false; 1193 // Other warning numbers are ignored. 1194 } 1195 } 1196 1197 // Handle /out 1198 if (auto *arg = args.getLastArg(OPT_out)) 1199 config->outputFile = arg->getValue(); 1200 1201 // Handle /verbose 1202 if (args.hasArg(OPT_verbose)) 1203 config->verbose = true; 1204 errorHandler().verbose = config->verbose; 1205 1206 // Handle /force or /force:unresolved 1207 if (args.hasArg(OPT_force, OPT_force_unresolved)) 1208 config->forceUnresolved = true; 1209 1210 // Handle /force or /force:multiple 1211 if (args.hasArg(OPT_force, OPT_force_multiple)) 1212 config->forceMultiple = true; 1213 1214 // Handle /force or /force:multipleres 1215 if (args.hasArg(OPT_force, OPT_force_multipleres)) 1216 config->forceMultipleRes = true; 1217 1218 // Handle /debug 1219 DebugKind debug = parseDebugKind(args); 1220 if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1221 debug == DebugKind::GHash) { 1222 config->debug = true; 1223 config->incremental = true; 1224 } 1225 1226 // Handle /demangle 1227 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no); 1228 1229 // Handle /debugtype 1230 config->debugTypes = parseDebugTypes(args); 1231 1232 // Handle /pdb 1233 bool shouldCreatePDB = 1234 (debug == DebugKind::Full || debug == DebugKind::GHash); 1235 if (shouldCreatePDB) { 1236 if (auto *arg = args.getLastArg(OPT_pdb)) 1237 config->pdbPath = arg->getValue(); 1238 if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 1239 config->pdbAltPath = arg->getValue(); 1240 if (args.hasArg(OPT_natvis)) 1241 config->natvisFiles = args.getAllArgValues(OPT_natvis); 1242 1243 if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 1244 config->pdbSourcePath = arg->getValue(); 1245 } 1246 1247 // Handle /noentry 1248 if (args.hasArg(OPT_noentry)) { 1249 if (args.hasArg(OPT_dll)) 1250 config->noEntry = true; 1251 else 1252 error("/noentry must be specified with /dll"); 1253 } 1254 1255 // Handle /dll 1256 if (args.hasArg(OPT_dll)) { 1257 config->dll = true; 1258 config->manifestID = 2; 1259 } 1260 1261 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 1262 // because we need to explicitly check whether that option or its inverse was 1263 // present in the argument list in order to handle /fixed. 1264 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 1265 if (dynamicBaseArg && 1266 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 1267 config->dynamicBase = false; 1268 1269 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 1270 // default setting for any other project type.", but link.exe defaults to 1271 // /FIXED:NO for exe outputs as well. Match behavior, not docs. 1272 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 1273 if (fixed) { 1274 if (dynamicBaseArg && 1275 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 1276 error("/fixed must not be specified with /dynamicbase"); 1277 } else { 1278 config->relocatable = false; 1279 config->dynamicBase = false; 1280 } 1281 } 1282 1283 // Handle /appcontainer 1284 config->appContainer = 1285 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 1286 1287 // Handle /machine 1288 if (auto *arg = args.getLastArg(OPT_machine)) { 1289 config->machine = getMachineType(arg->getValue()); 1290 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 1291 fatal(Twine("unknown /machine argument: ") + arg->getValue()); 1292 } 1293 1294 // Handle /nodefaultlib:<filename> 1295 for (auto *arg : args.filtered(OPT_nodefaultlib)) 1296 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 1297 1298 // Handle /nodefaultlib 1299 if (args.hasArg(OPT_nodefaultlib_all)) 1300 config->noDefaultLibAll = true; 1301 1302 // Handle /base 1303 if (auto *arg = args.getLastArg(OPT_base)) 1304 parseNumbers(arg->getValue(), &config->imageBase); 1305 1306 // Handle /filealign 1307 if (auto *arg = args.getLastArg(OPT_filealign)) { 1308 parseNumbers(arg->getValue(), &config->fileAlign); 1309 if (!isPowerOf2_64(config->fileAlign)) 1310 error("/filealign: not a power of two: " + Twine(config->fileAlign)); 1311 } 1312 1313 // Handle /stack 1314 if (auto *arg = args.getLastArg(OPT_stack)) 1315 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 1316 1317 // Handle /guard:cf 1318 if (auto *arg = args.getLastArg(OPT_guard)) 1319 parseGuard(arg->getValue()); 1320 1321 // Handle /heap 1322 if (auto *arg = args.getLastArg(OPT_heap)) 1323 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 1324 1325 // Handle /version 1326 if (auto *arg = args.getLastArg(OPT_version)) 1327 parseVersion(arg->getValue(), &config->majorImageVersion, 1328 &config->minorImageVersion); 1329 1330 // Handle /subsystem 1331 if (auto *arg = args.getLastArg(OPT_subsystem)) 1332 parseSubsystem(arg->getValue(), &config->subsystem, &config->majorOSVersion, 1333 &config->minorOSVersion); 1334 1335 // Handle /timestamp 1336 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 1337 if (arg->getOption().getID() == OPT_repro) { 1338 config->timestamp = 0; 1339 config->repro = true; 1340 } else { 1341 config->repro = false; 1342 StringRef value(arg->getValue()); 1343 if (value.getAsInteger(0, config->timestamp)) 1344 fatal(Twine("invalid timestamp: ") + value + 1345 ". Expected 32-bit integer"); 1346 } 1347 } else { 1348 config->repro = false; 1349 config->timestamp = time(nullptr); 1350 } 1351 1352 // Handle /alternatename 1353 for (auto *arg : args.filtered(OPT_alternatename)) 1354 parseAlternateName(arg->getValue()); 1355 1356 // Handle /include 1357 for (auto *arg : args.filtered(OPT_incl)) 1358 addUndefined(arg->getValue()); 1359 1360 // Handle /implib 1361 if (auto *arg = args.getLastArg(OPT_implib)) 1362 config->implib = arg->getValue(); 1363 1364 // Handle /opt. 1365 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1366 unsigned icfLevel = 1367 args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on 1368 unsigned tailMerge = 1; 1369 for (auto *arg : args.filtered(OPT_opt)) { 1370 std::string str = StringRef(arg->getValue()).lower(); 1371 SmallVector<StringRef, 1> vec; 1372 StringRef(str).split(vec, ','); 1373 for (StringRef s : vec) { 1374 if (s == "ref") { 1375 doGC = true; 1376 } else if (s == "noref") { 1377 doGC = false; 1378 } else if (s == "icf" || s.startswith("icf=")) { 1379 icfLevel = 2; 1380 } else if (s == "noicf") { 1381 icfLevel = 0; 1382 } else if (s == "lldtailmerge") { 1383 tailMerge = 2; 1384 } else if (s == "nolldtailmerge") { 1385 tailMerge = 0; 1386 } else if (s.startswith("lldlto=")) { 1387 StringRef optLevel = s.substr(7); 1388 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 1389 error("/opt:lldlto: invalid optimization level: " + optLevel); 1390 } else if (s.startswith("lldltojobs=")) { 1391 StringRef jobs = s.substr(11); 1392 if (jobs.getAsInteger(10, config->thinLTOJobs) || 1393 config->thinLTOJobs == 0) 1394 error("/opt:lldltojobs: invalid job count: " + jobs); 1395 } else if (s.startswith("lldltopartitions=")) { 1396 StringRef n = s.substr(17); 1397 if (n.getAsInteger(10, config->ltoPartitions) || 1398 config->ltoPartitions == 0) 1399 error("/opt:lldltopartitions: invalid partition count: " + n); 1400 } else if (s != "lbr" && s != "nolbr") 1401 error("/opt: unknown option: " + s); 1402 } 1403 } 1404 1405 // Limited ICF is enabled if GC is enabled and ICF was never mentioned 1406 // explicitly. 1407 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical 1408 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical 1409 // comdat readonly data. 1410 if (icfLevel == 1 && !doGC) 1411 icfLevel = 0; 1412 config->doGC = doGC; 1413 config->doICF = icfLevel > 0; 1414 config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2; 1415 1416 // Handle /lldsavetemps 1417 if (args.hasArg(OPT_lldsavetemps)) 1418 config->saveTemps = true; 1419 1420 // Handle /kill-at 1421 if (args.hasArg(OPT_kill_at)) 1422 config->killAt = true; 1423 1424 // Handle /lldltocache 1425 if (auto *arg = args.getLastArg(OPT_lldltocache)) 1426 config->ltoCache = arg->getValue(); 1427 1428 // Handle /lldsavecachepolicy 1429 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 1430 config->ltoCachePolicy = CHECK( 1431 parseCachePruningPolicy(arg->getValue()), 1432 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 1433 1434 // Handle /failifmismatch 1435 for (auto *arg : args.filtered(OPT_failifmismatch)) 1436 checkFailIfMismatch(arg->getValue(), nullptr); 1437 1438 // Handle /merge 1439 for (auto *arg : args.filtered(OPT_merge)) 1440 parseMerge(arg->getValue()); 1441 1442 // Add default section merging rules after user rules. User rules take 1443 // precedence, but we will emit a warning if there is a conflict. 1444 parseMerge(".idata=.rdata"); 1445 parseMerge(".didat=.rdata"); 1446 parseMerge(".edata=.rdata"); 1447 parseMerge(".xdata=.rdata"); 1448 parseMerge(".bss=.data"); 1449 1450 if (config->mingw) { 1451 parseMerge(".ctors=.rdata"); 1452 parseMerge(".dtors=.rdata"); 1453 parseMerge(".CRT=.rdata"); 1454 } 1455 1456 // Handle /section 1457 for (auto *arg : args.filtered(OPT_section)) 1458 parseSection(arg->getValue()); 1459 1460 // Handle /align 1461 if (auto *arg = args.getLastArg(OPT_align)) { 1462 parseNumbers(arg->getValue(), &config->align); 1463 if (!isPowerOf2_64(config->align)) 1464 error("/align: not a power of two: " + StringRef(arg->getValue())); 1465 } 1466 1467 // Handle /aligncomm 1468 for (auto *arg : args.filtered(OPT_aligncomm)) 1469 parseAligncomm(arg->getValue()); 1470 1471 // Handle /manifestdependency. This enables /manifest unless /manifest:no is 1472 // also passed. 1473 if (auto *arg = args.getLastArg(OPT_manifestdependency)) { 1474 config->manifestDependency = arg->getValue(); 1475 config->manifest = Configuration::SideBySide; 1476 } 1477 1478 // Handle /manifest and /manifest: 1479 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 1480 if (arg->getOption().getID() == OPT_manifest) 1481 config->manifest = Configuration::SideBySide; 1482 else 1483 parseManifest(arg->getValue()); 1484 } 1485 1486 // Handle /manifestuac 1487 if (auto *arg = args.getLastArg(OPT_manifestuac)) 1488 parseManifestUAC(arg->getValue()); 1489 1490 // Handle /manifestfile 1491 if (auto *arg = args.getLastArg(OPT_manifestfile)) 1492 config->manifestFile = arg->getValue(); 1493 1494 // Handle /manifestinput 1495 for (auto *arg : args.filtered(OPT_manifestinput)) 1496 config->manifestInput.push_back(arg->getValue()); 1497 1498 if (!config->manifestInput.empty() && 1499 config->manifest != Configuration::Embed) { 1500 fatal("/manifestinput: requires /manifest:embed"); 1501 } 1502 1503 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1504 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1505 args.hasArg(OPT_thinlto_index_only_arg); 1506 config->thinLTOIndexOnlyArg = 1507 args.getLastArgValue(OPT_thinlto_index_only_arg); 1508 config->thinLTOPrefixReplace = 1509 getOldNewOptions(args, OPT_thinlto_prefix_replace); 1510 config->thinLTOObjectSuffixReplace = 1511 getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 1512 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1513 // Handle miscellaneous boolean flags. 1514 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 1515 config->allowIsolation = 1516 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 1517 config->incremental = 1518 args.hasFlag(OPT_incremental, OPT_incremental_no, 1519 !config->doGC && !config->doICF && !args.hasArg(OPT_order) && 1520 !args.hasArg(OPT_profile)); 1521 config->integrityCheck = 1522 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 1523 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 1524 for (auto *arg : args.filtered(OPT_swaprun)) 1525 parseSwaprun(arg->getValue()); 1526 config->terminalServerAware = 1527 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 1528 config->debugDwarf = debug == DebugKind::Dwarf; 1529 config->debugGHashes = debug == DebugKind::GHash; 1530 config->debugSymtab = debug == DebugKind::Symtab; 1531 1532 // Don't warn about long section names, such as .debug_info, for mingw or when 1533 // -debug:dwarf is requested. 1534 if (config->mingw || config->debugDwarf) 1535 config->warnLongSectionNames = false; 1536 1537 config->mapFile = getMapFile(args); 1538 1539 if (config->incremental && args.hasArg(OPT_profile)) { 1540 warn("ignoring '/incremental' due to '/profile' specification"); 1541 config->incremental = false; 1542 } 1543 1544 if (config->incremental && args.hasArg(OPT_order)) { 1545 warn("ignoring '/incremental' due to '/order' specification"); 1546 config->incremental = false; 1547 } 1548 1549 if (config->incremental && config->doGC) { 1550 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 1551 "disable"); 1552 config->incremental = false; 1553 } 1554 1555 if (config->incremental && config->doICF) { 1556 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 1557 "disable"); 1558 config->incremental = false; 1559 } 1560 1561 if (errorCount()) 1562 return; 1563 1564 std::set<sys::fs::UniqueID> wholeArchives; 1565 for (auto *arg : args.filtered(OPT_wholearchive_file)) 1566 if (Optional<StringRef> path = doFindFile(arg->getValue())) 1567 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 1568 wholeArchives.insert(*id); 1569 1570 // A predicate returning true if a given path is an argument for 1571 // /wholearchive:, or /wholearchive is enabled globally. 1572 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 1573 // needs to be handled as "/wholearchive:foo.obj foo.obj". 1574 auto isWholeArchive = [&](StringRef path) -> bool { 1575 if (args.hasArg(OPT_wholearchive_flag)) 1576 return true; 1577 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 1578 return wholeArchives.count(*id); 1579 return false; 1580 }; 1581 1582 // Create a list of input files. These can be given as OPT_INPUT options 1583 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 1584 // and OPT_end_lib. 1585 bool inLib = false; 1586 for (auto *arg : args) { 1587 switch (arg->getOption().getID()) { 1588 case OPT_end_lib: 1589 if (!inLib) 1590 error("stray " + arg->getSpelling()); 1591 inLib = false; 1592 break; 1593 case OPT_start_lib: 1594 if (inLib) 1595 error("nested " + arg->getSpelling()); 1596 inLib = true; 1597 break; 1598 case OPT_wholearchive_file: 1599 if (Optional<StringRef> path = findFile(arg->getValue())) 1600 enqueuePath(*path, true, inLib); 1601 break; 1602 case OPT_INPUT: 1603 if (Optional<StringRef> path = findFile(arg->getValue())) 1604 enqueuePath(*path, isWholeArchive(*path), inLib); 1605 break; 1606 default: 1607 // Ignore other options. 1608 break; 1609 } 1610 } 1611 1612 // Process files specified as /defaultlib. These should be enequeued after 1613 // other files, which is why they are in a separate loop. 1614 for (auto *arg : args.filtered(OPT_defaultlib)) 1615 if (Optional<StringRef> path = findLib(arg->getValue())) 1616 enqueuePath(*path, false, false); 1617 1618 // Windows specific -- Create a resource file containing a manifest file. 1619 if (config->manifest == Configuration::Embed) 1620 addBuffer(createManifestRes(), false, false); 1621 1622 // Read all input files given via the command line. 1623 run(); 1624 1625 if (errorCount()) 1626 return; 1627 1628 // We should have inferred a machine type by now from the input files, but if 1629 // not we assume x64. 1630 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 1631 warn("/machine is not specified. x64 is assumed"); 1632 config->machine = AMD64; 1633 } 1634 config->wordsize = config->is64() ? 8 : 4; 1635 1636 // Handle /safeseh, x86 only, on by default, except for mingw. 1637 if (config->machine == I386 && 1638 args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw)) 1639 config->safeSEH = true; 1640 1641 // Handle /functionpadmin 1642 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 1643 parseFunctionPadMin(arg, config->machine); 1644 1645 if (tar) 1646 tar->append("response.txt", 1647 createResponseFile(args, filePaths, 1648 ArrayRef<StringRef>(searchPaths).slice(1))); 1649 1650 // Handle /largeaddressaware 1651 config->largeAddressAware = args.hasFlag( 1652 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 1653 1654 // Handle /highentropyva 1655 config->highEntropyVA = 1656 config->is64() && 1657 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 1658 1659 if (!config->dynamicBase && 1660 (config->machine == ARMNT || config->machine == ARM64)) 1661 error("/dynamicbase:no is not compatible with " + 1662 machineToStr(config->machine)); 1663 1664 // Handle /export 1665 for (auto *arg : args.filtered(OPT_export)) { 1666 Export e = parseExport(arg->getValue()); 1667 if (config->machine == I386) { 1668 if (!isDecorated(e.name)) 1669 e.name = saver.save("_" + e.name); 1670 if (!e.extName.empty() && !isDecorated(e.extName)) 1671 e.extName = saver.save("_" + e.extName); 1672 } 1673 config->exports.push_back(e); 1674 } 1675 1676 // Handle /def 1677 if (auto *arg = args.getLastArg(OPT_deffile)) { 1678 // parseModuleDefs mutates Config object. 1679 parseModuleDefs(arg->getValue()); 1680 } 1681 1682 // Handle generation of import library from a def file. 1683 if (!args.hasArg(OPT_INPUT)) { 1684 fixupExports(); 1685 createImportLibrary(/*asLib=*/true); 1686 return; 1687 } 1688 1689 // Windows specific -- if no /subsystem is given, we need to infer 1690 // that from entry point name. Must happen before /entry handling, 1691 // and after the early return when just writing an import library. 1692 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 1693 config->subsystem = inferSubsystem(); 1694 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 1695 fatal("subsystem must be defined"); 1696 } 1697 1698 // Handle /entry and /dll 1699 if (auto *arg = args.getLastArg(OPT_entry)) { 1700 config->entry = addUndefined(mangle(arg->getValue())); 1701 } else if (!config->entry && !config->noEntry) { 1702 if (args.hasArg(OPT_dll)) { 1703 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 1704 : "_DllMainCRTStartup"; 1705 config->entry = addUndefined(s); 1706 } else { 1707 // Windows specific -- If entry point name is not given, we need to 1708 // infer that from user-defined entry name. 1709 StringRef s = findDefaultEntry(); 1710 if (s.empty()) 1711 fatal("entry point must be defined"); 1712 config->entry = addUndefined(s); 1713 log("Entry name inferred: " + s); 1714 } 1715 } 1716 1717 // Handle /delayload 1718 for (auto *arg : args.filtered(OPT_delayload)) { 1719 config->delayLoads.insert(StringRef(arg->getValue()).lower()); 1720 if (config->machine == I386) { 1721 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 1722 } else { 1723 config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 1724 } 1725 } 1726 1727 // Set default image name if neither /out or /def set it. 1728 if (config->outputFile.empty()) { 1729 config->outputFile = 1730 getOutputPath((*args.filtered(OPT_INPUT).begin())->getValue()); 1731 } 1732 1733 // Fail early if an output file is not writable. 1734 if (auto e = tryCreateFile(config->outputFile)) { 1735 error("cannot open output file " + config->outputFile + ": " + e.message()); 1736 return; 1737 } 1738 1739 if (shouldCreatePDB) { 1740 // Put the PDB next to the image if no /pdb flag was passed. 1741 if (config->pdbPath.empty()) { 1742 config->pdbPath = config->outputFile; 1743 sys::path::replace_extension(config->pdbPath, ".pdb"); 1744 } 1745 1746 // The embedded PDB path should be the absolute path to the PDB if no 1747 // /pdbaltpath flag was passed. 1748 if (config->pdbAltPath.empty()) { 1749 config->pdbAltPath = config->pdbPath; 1750 1751 // It's important to make the path absolute and remove dots. This path 1752 // will eventually be written into the PE header, and certain Microsoft 1753 // tools won't work correctly if these assumptions are not held. 1754 sys::fs::make_absolute(config->pdbAltPath); 1755 sys::path::remove_dots(config->pdbAltPath); 1756 } else { 1757 // Don't do this earlier, so that Config->OutputFile is ready. 1758 parsePDBAltPath(config->pdbAltPath); 1759 } 1760 } 1761 1762 // Set default image base if /base is not given. 1763 if (config->imageBase == uint64_t(-1)) 1764 config->imageBase = getDefaultImageBase(); 1765 1766 symtab->addSynthetic(mangle("__ImageBase"), nullptr); 1767 if (config->machine == I386) { 1768 symtab->addAbsolute("___safe_se_handler_table", 0); 1769 symtab->addAbsolute("___safe_se_handler_count", 0); 1770 } 1771 1772 symtab->addAbsolute(mangle("__guard_fids_count"), 0); 1773 symtab->addAbsolute(mangle("__guard_fids_table"), 0); 1774 symtab->addAbsolute(mangle("__guard_flags"), 0); 1775 symtab->addAbsolute(mangle("__guard_iat_count"), 0); 1776 symtab->addAbsolute(mangle("__guard_iat_table"), 0); 1777 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); 1778 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); 1779 // Needed for MSVC 2017 15.5 CRT. 1780 symtab->addAbsolute(mangle("__enclave_config"), 0); 1781 1782 if (config->mingw) { 1783 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 1784 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 1785 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0); 1786 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0); 1787 } 1788 1789 // This code may add new undefined symbols to the link, which may enqueue more 1790 // symbol resolution tasks, so we need to continue executing tasks until we 1791 // converge. 1792 do { 1793 // Windows specific -- if entry point is not found, 1794 // search for its mangled names. 1795 if (config->entry) 1796 mangleMaybe(config->entry); 1797 1798 // Windows specific -- Make sure we resolve all dllexported symbols. 1799 for (Export &e : config->exports) { 1800 if (!e.forwardTo.empty()) 1801 continue; 1802 e.sym = addUndefined(e.name); 1803 if (!e.directives) 1804 e.symbolName = mangleMaybe(e.sym); 1805 } 1806 1807 // Add weak aliases. Weak aliases is a mechanism to give remaining 1808 // undefined symbols final chance to be resolved successfully. 1809 for (auto pair : config->alternateNames) { 1810 StringRef from = pair.first; 1811 StringRef to = pair.second; 1812 Symbol *sym = symtab->find(from); 1813 if (!sym) 1814 continue; 1815 if (auto *u = dyn_cast<Undefined>(sym)) 1816 if (!u->weakAlias) 1817 u->weakAlias = symtab->addUndefined(to); 1818 } 1819 1820 // If any inputs are bitcode files, the LTO code generator may create 1821 // references to library functions that are not explicit in the bitcode 1822 // file's symbol table. If any of those library functions are defined in a 1823 // bitcode file in an archive member, we need to arrange to use LTO to 1824 // compile those archive members by adding them to the link beforehand. 1825 if (!BitcodeFile::instances.empty()) 1826 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 1827 symtab->addLibcall(s); 1828 1829 // Windows specific -- if __load_config_used can be resolved, resolve it. 1830 if (symtab->findUnderscore("_load_config_used")) 1831 addUndefined(mangle("_load_config_used")); 1832 } while (run()); 1833 1834 if (args.hasArg(OPT_include_optional)) { 1835 // Handle /includeoptional 1836 for (auto *arg : args.filtered(OPT_include_optional)) 1837 if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue()))) 1838 addUndefined(arg->getValue()); 1839 while (run()); 1840 } 1841 1842 if (config->mingw) { 1843 // Load any further object files that might be needed for doing automatic 1844 // imports. 1845 // 1846 // For cases with no automatically imported symbols, this iterates once 1847 // over the symbol table and doesn't do anything. 1848 // 1849 // For the normal case with a few automatically imported symbols, this 1850 // should only need to be run once, since each new object file imported 1851 // is an import library and wouldn't add any new undefined references, 1852 // but there's nothing stopping the __imp_ symbols from coming from a 1853 // normal object file as well (although that won't be used for the 1854 // actual autoimport later on). If this pass adds new undefined references, 1855 // we won't iterate further to resolve them. 1856 symtab->loadMinGWAutomaticImports(); 1857 run(); 1858 } 1859 1860 // At this point, we should not have any symbols that cannot be resolved. 1861 // If we are going to do codegen for link-time optimization, check for 1862 // unresolvable symbols first, so we don't spend time generating code that 1863 // will fail to link anyway. 1864 if (!BitcodeFile::instances.empty() && !config->forceUnresolved) 1865 symtab->reportUnresolvable(); 1866 if (errorCount()) 1867 return; 1868 1869 // Do LTO by compiling bitcode input files to a set of native COFF files then 1870 // link those files (unless -thinlto-index-only was given, in which case we 1871 // resolve symbols and write indices, but don't generate native code or link). 1872 symtab->addCombinedLTOObjects(); 1873 1874 // If -thinlto-index-only is given, we should create only "index 1875 // files" and not object files. Index file creation is already done 1876 // in addCombinedLTOObject, so we are done if that's the case. 1877 if (config->thinLTOIndexOnly) 1878 return; 1879 1880 // If we generated native object files from bitcode files, this resolves 1881 // references to the symbols we use from them. 1882 run(); 1883 1884 // Resolve remaining undefined symbols and warn about imported locals. 1885 symtab->resolveRemainingUndefines(); 1886 if (errorCount()) 1887 return; 1888 1889 config->hadExplicitExports = !config->exports.empty(); 1890 if (config->mingw) { 1891 // In MinGW, all symbols are automatically exported if no symbols 1892 // are chosen to be exported. 1893 maybeExportMinGWSymbols(args); 1894 1895 // Make sure the crtend.o object is the last object file. This object 1896 // file can contain terminating section chunks that need to be placed 1897 // last. GNU ld processes files and static libraries explicitly in the 1898 // order provided on the command line, while lld will pull in needed 1899 // files from static libraries only after the last object file on the 1900 // command line. 1901 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end(); 1902 i != e; i++) { 1903 ObjFile *file = *i; 1904 if (isCrtend(file->getName())) { 1905 ObjFile::instances.erase(i); 1906 ObjFile::instances.push_back(file); 1907 break; 1908 } 1909 } 1910 } 1911 1912 // Windows specific -- when we are creating a .dll file, we also 1913 // need to create a .lib file. In MinGW mode, we only do that when the 1914 // -implib option is given explicitly, for compatibility with GNU ld. 1915 if (!config->exports.empty() || config->dll) { 1916 fixupExports(); 1917 if (!config->mingw || !config->implib.empty()) 1918 createImportLibrary(/*asLib=*/false); 1919 assignExportOrdinals(); 1920 } 1921 1922 // Handle /output-def (MinGW specific). 1923 if (auto *arg = args.getLastArg(OPT_output_def)) 1924 writeDefFile(arg->getValue()); 1925 1926 // Set extra alignment for .comm symbols 1927 for (auto pair : config->alignComm) { 1928 StringRef name = pair.first; 1929 uint32_t alignment = pair.second; 1930 1931 Symbol *sym = symtab->find(name); 1932 if (!sym) { 1933 warn("/aligncomm symbol " + name + " not found"); 1934 continue; 1935 } 1936 1937 // If the symbol isn't common, it must have been replaced with a regular 1938 // symbol, which will carry its own alignment. 1939 auto *dc = dyn_cast<DefinedCommon>(sym); 1940 if (!dc) 1941 continue; 1942 1943 CommonChunk *c = dc->getChunk(); 1944 c->setAlignment(std::max(c->getAlignment(), alignment)); 1945 } 1946 1947 // Windows specific -- Create a side-by-side manifest file. 1948 if (config->manifest == Configuration::SideBySide) 1949 createSideBySideManifest(); 1950 1951 // Handle /order. We want to do this at this moment because we 1952 // need a complete list of comdat sections to warn on nonexistent 1953 // functions. 1954 if (auto *arg = args.getLastArg(OPT_order)) 1955 parseOrderFile(arg->getValue()); 1956 1957 // Identify unreferenced COMDAT sections. 1958 if (config->doGC) 1959 markLive(symtab->getChunks()); 1960 1961 // Needs to happen after the last call to addFile(). 1962 convertResources(); 1963 1964 // Identify identical COMDAT sections to merge them. 1965 if (config->doICF) { 1966 findKeepUniqueSections(); 1967 doICF(symtab->getChunks()); 1968 } 1969 1970 // Write the result. 1971 writeResult(); 1972 1973 // Stop early so we can print the results. 1974 Timer::root().stop(); 1975 if (config->showTiming) 1976 Timer::root().print(); 1977 } 1978 1979 } // namespace coff 1980 } // namespace lld 1981