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