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