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