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