1 //===- Driver.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "Config.h" 11 #include "Driver.h" 12 #include "Error.h" 13 #include "InputFiles.h" 14 #include "SymbolTable.h" 15 #include "Symbols.h" 16 #include "Writer.h" 17 #include "lld/Driver/Driver.h" 18 #include "llvm/ADT/Optional.h" 19 #include "llvm/LibDriver/LibDriver.h" 20 #include "llvm/Option/Arg.h" 21 #include "llvm/Option/ArgList.h" 22 #include "llvm/Option/Option.h" 23 #include "llvm/Support/Debug.h" 24 #include "llvm/Support/Path.h" 25 #include "llvm/Support/Process.h" 26 #include "llvm/Support/TargetSelect.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <algorithm> 29 #include <memory> 30 31 using namespace llvm; 32 using namespace llvm::COFF; 33 using llvm::sys::Process; 34 using llvm::sys::fs::OpenFlags; 35 using llvm::sys::fs::file_magic; 36 using llvm::sys::fs::identify_magic; 37 38 namespace lld { 39 namespace coff { 40 41 Configuration *Config; 42 LinkerDriver *Driver; 43 44 bool link(llvm::ArrayRef<const char *> Args) { 45 Configuration C; 46 LinkerDriver D; 47 Config = &C; 48 Driver = &D; 49 Driver->link(Args); 50 return true; 51 } 52 53 // Drop directory components and replace extension with ".exe" or ".dll". 54 static std::string getOutputPath(StringRef Path) { 55 auto P = Path.find_last_of("\\/"); 56 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1); 57 const char* E = Config->DLL ? ".dll" : ".exe"; 58 return (S.substr(0, S.rfind('.')) + E).str(); 59 } 60 61 // Opens a file. Path has to be resolved already. 62 // Newly created memory buffers are owned by this driver. 63 MemoryBufferRef LinkerDriver::openFile(StringRef Path) { 64 std::unique_ptr<MemoryBuffer> MB = 65 check(MemoryBuffer::getFile(Path), "could not open " + Path); 66 MemoryBufferRef MBRef = MB->getMemBufferRef(); 67 OwningMBs.push_back(std::move(MB)); // take ownership 68 return MBRef; 69 } 70 71 static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) { 72 // File type is detected by contents, not by file extension. 73 file_magic Magic = identify_magic(MB.getBuffer()); 74 if (Magic == file_magic::archive) 75 return std::unique_ptr<InputFile>(new ArchiveFile(MB)); 76 if (Magic == file_magic::bitcode) 77 return std::unique_ptr<InputFile>(new BitcodeFile(MB)); 78 if (Config->OutputFile == "") 79 Config->OutputFile = getOutputPath(MB.getBufferIdentifier()); 80 return std::unique_ptr<InputFile>(new ObjectFile(MB)); 81 } 82 83 static bool isDecorated(StringRef Sym) { 84 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?"); 85 } 86 87 // Parses .drectve section contents and returns a list of files 88 // specified by /defaultlib. 89 void LinkerDriver::parseDirectives(StringRef S) { 90 llvm::opt::InputArgList Args = Parser.parse(S); 91 92 for (auto *Arg : Args) { 93 switch (Arg->getOption().getID()) { 94 case OPT_alternatename: 95 parseAlternateName(Arg->getValue()); 96 break; 97 case OPT_defaultlib: 98 if (Optional<StringRef> Path = findLib(Arg->getValue())) { 99 MemoryBufferRef MB = openFile(*Path); 100 Symtab.addFile(createFile(MB)); 101 } 102 break; 103 case OPT_export: { 104 Export E = parseExport(Arg->getValue()); 105 E.Directives = true; 106 Config->Exports.push_back(E); 107 break; 108 } 109 case OPT_failifmismatch: 110 checkFailIfMismatch(Arg->getValue()); 111 break; 112 case OPT_incl: 113 addUndefined(Arg->getValue()); 114 break; 115 case OPT_merge: 116 parseMerge(Arg->getValue()); 117 break; 118 case OPT_nodefaultlib: 119 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 120 break; 121 case OPT_section: 122 parseSection(Arg->getValue()); 123 break; 124 case OPT_editandcontinue: 125 case OPT_fastfail: 126 case OPT_guardsym: 127 case OPT_throwingnew: 128 break; 129 default: 130 fatal(Arg->getSpelling() + " is not allowed in .drectve"); 131 } 132 } 133 } 134 135 // Find file from search paths. You can omit ".obj", this function takes 136 // care of that. Note that the returned path is not guaranteed to exist. 137 StringRef LinkerDriver::doFindFile(StringRef Filename) { 138 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos); 139 if (hasPathSep) 140 return Filename; 141 bool hasExt = (Filename.find('.') != StringRef::npos); 142 for (StringRef Dir : SearchPaths) { 143 SmallString<128> Path = Dir; 144 llvm::sys::path::append(Path, Filename); 145 if (llvm::sys::fs::exists(Path.str())) 146 return Alloc.save(Path.str()); 147 if (!hasExt) { 148 Path.append(".obj"); 149 if (llvm::sys::fs::exists(Path.str())) 150 return Alloc.save(Path.str()); 151 } 152 } 153 return Filename; 154 } 155 156 // Resolves a file path. This never returns the same path 157 // (in that case, it returns None). 158 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) { 159 StringRef Path = doFindFile(Filename); 160 bool Seen = !VisitedFiles.insert(Path.lower()).second; 161 if (Seen) 162 return None; 163 return Path; 164 } 165 166 // Find library file from search path. 167 StringRef LinkerDriver::doFindLib(StringRef Filename) { 168 // Add ".lib" to Filename if that has no file extension. 169 bool hasExt = (Filename.find('.') != StringRef::npos); 170 if (!hasExt) 171 Filename = Alloc.save(Filename + ".lib"); 172 return doFindFile(Filename); 173 } 174 175 // Resolves a library path. /nodefaultlib options are taken into 176 // consideration. This never returns the same path (in that case, 177 // it returns None). 178 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) { 179 if (Config->NoDefaultLibAll) 180 return None; 181 StringRef Path = doFindLib(Filename); 182 if (Config->NoDefaultLibs.count(Path)) 183 return None; 184 bool Seen = !VisitedFiles.insert(Path.lower()).second; 185 if (Seen) 186 return None; 187 return Path; 188 } 189 190 // Parses LIB environment which contains a list of search paths. 191 void LinkerDriver::addLibSearchPaths() { 192 Optional<std::string> EnvOpt = Process::GetEnv("LIB"); 193 if (!EnvOpt.hasValue()) 194 return; 195 StringRef Env = Alloc.save(*EnvOpt); 196 while (!Env.empty()) { 197 StringRef Path; 198 std::tie(Path, Env) = Env.split(';'); 199 SearchPaths.push_back(Path); 200 } 201 } 202 203 Undefined *LinkerDriver::addUndefined(StringRef Name) { 204 Undefined *U = Symtab.addUndefined(Name); 205 Config->GCRoot.insert(U); 206 return U; 207 } 208 209 // Symbol names are mangled by appending "_" prefix on x86. 210 StringRef LinkerDriver::mangle(StringRef Sym) { 211 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN); 212 if (Config->Machine == I386) 213 return Alloc.save("_" + Sym); 214 return Sym; 215 } 216 217 // Windows specific -- find default entry point name. 218 StringRef LinkerDriver::findDefaultEntry() { 219 // User-defined main functions and their corresponding entry points. 220 static const char *Entries[][2] = { 221 {"main", "mainCRTStartup"}, 222 {"wmain", "wmainCRTStartup"}, 223 {"WinMain", "WinMainCRTStartup"}, 224 {"wWinMain", "wWinMainCRTStartup"}, 225 }; 226 for (auto E : Entries) { 227 StringRef Entry = Symtab.findMangle(mangle(E[0])); 228 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->Body)) 229 return mangle(E[1]); 230 } 231 return ""; 232 } 233 234 WindowsSubsystem LinkerDriver::inferSubsystem() { 235 if (Config->DLL) 236 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 237 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain")) 238 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 239 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain")) 240 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 241 return IMAGE_SUBSYSTEM_UNKNOWN; 242 } 243 244 static uint64_t getDefaultImageBase() { 245 if (Config->is64()) 246 return Config->DLL ? 0x180000000 : 0x140000000; 247 return Config->DLL ? 0x10000000 : 0x400000; 248 } 249 250 void LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) { 251 // If the first command line argument is "/lib", link.exe acts like lib.exe. 252 // We call our own implementation of lib.exe that understands bitcode files. 253 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) { 254 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0) 255 fatal("lib failed"); 256 return; 257 } 258 259 // Needed for LTO. 260 llvm::InitializeAllTargetInfos(); 261 llvm::InitializeAllTargets(); 262 llvm::InitializeAllTargetMCs(); 263 llvm::InitializeAllAsmParsers(); 264 llvm::InitializeAllAsmPrinters(); 265 llvm::InitializeAllDisassemblers(); 266 267 // Parse command line options. 268 llvm::opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1)); 269 270 // Handle /help 271 if (Args.hasArg(OPT_help)) { 272 printHelp(ArgsArr[0]); 273 return; 274 } 275 276 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end()) 277 fatal("no input files"); 278 279 // Construct search path list. 280 SearchPaths.push_back(""); 281 for (auto *Arg : Args.filtered(OPT_libpath)) 282 SearchPaths.push_back(Arg->getValue()); 283 addLibSearchPaths(); 284 285 // Handle /out 286 if (auto *Arg = Args.getLastArg(OPT_out)) 287 Config->OutputFile = Arg->getValue(); 288 289 // Handle /verbose 290 if (Args.hasArg(OPT_verbose)) 291 Config->Verbose = true; 292 293 // Handle /force or /force:unresolved 294 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved)) 295 Config->Force = true; 296 297 // Handle /debug 298 if (Args.hasArg(OPT_debug)) 299 Config->Debug = true; 300 301 // Handle /noentry 302 if (Args.hasArg(OPT_noentry)) { 303 if (!Args.hasArg(OPT_dll)) 304 fatal("/noentry must be specified with /dll"); 305 Config->NoEntry = true; 306 } 307 308 // Handle /dll 309 if (Args.hasArg(OPT_dll)) { 310 Config->DLL = true; 311 Config->ManifestID = 2; 312 } 313 314 // Handle /fixed 315 if (Args.hasArg(OPT_fixed)) { 316 if (Args.hasArg(OPT_dynamicbase)) 317 fatal("/fixed must not be specified with /dynamicbase"); 318 Config->Relocatable = false; 319 Config->DynamicBase = false; 320 } 321 322 // Handle /machine 323 if (auto *Arg = Args.getLastArg(OPT_machine)) 324 Config->Machine = getMachineType(Arg->getValue()); 325 326 // Handle /nodefaultlib:<filename> 327 for (auto *Arg : Args.filtered(OPT_nodefaultlib)) 328 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 329 330 // Handle /nodefaultlib 331 if (Args.hasArg(OPT_nodefaultlib_all)) 332 Config->NoDefaultLibAll = true; 333 334 // Handle /base 335 if (auto *Arg = Args.getLastArg(OPT_base)) 336 parseNumbers(Arg->getValue(), &Config->ImageBase); 337 338 // Handle /stack 339 if (auto *Arg = Args.getLastArg(OPT_stack)) 340 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit); 341 342 // Handle /heap 343 if (auto *Arg = Args.getLastArg(OPT_heap)) 344 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit); 345 346 // Handle /version 347 if (auto *Arg = Args.getLastArg(OPT_version)) 348 parseVersion(Arg->getValue(), &Config->MajorImageVersion, 349 &Config->MinorImageVersion); 350 351 // Handle /subsystem 352 if (auto *Arg = Args.getLastArg(OPT_subsystem)) 353 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, 354 &Config->MinorOSVersion); 355 356 // Handle /alternatename 357 for (auto *Arg : Args.filtered(OPT_alternatename)) 358 parseAlternateName(Arg->getValue()); 359 360 // Handle /include 361 for (auto *Arg : Args.filtered(OPT_incl)) 362 addUndefined(Arg->getValue()); 363 364 // Handle /implib 365 if (auto *Arg = Args.getLastArg(OPT_implib)) 366 Config->Implib = Arg->getValue(); 367 368 // Handle /opt 369 for (auto *Arg : Args.filtered(OPT_opt)) { 370 std::string Str = StringRef(Arg->getValue()).lower(); 371 SmallVector<StringRef, 1> Vec; 372 StringRef(Str).split(Vec, ','); 373 for (StringRef S : Vec) { 374 if (S == "noref") { 375 Config->DoGC = false; 376 Config->DoICF = false; 377 continue; 378 } 379 if (S == "icf" || StringRef(S).startswith("icf=")) { 380 Config->DoICF = true; 381 continue; 382 } 383 if (S == "noicf") { 384 Config->DoICF = false; 385 continue; 386 } 387 if (StringRef(S).startswith("lldlto=")) { 388 StringRef OptLevel = StringRef(S).substr(7); 389 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) || 390 Config->LTOOptLevel > 3) 391 fatal("/opt:lldlto: invalid optimization level: " + OptLevel); 392 continue; 393 } 394 if (StringRef(S).startswith("lldltojobs=")) { 395 StringRef Jobs = StringRef(S).substr(11); 396 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0) 397 fatal("/opt:lldltojobs: invalid job count: " + Jobs); 398 continue; 399 } 400 if (S != "ref" && S != "lbr" && S != "nolbr") 401 fatal("/opt: unknown option: " + S); 402 } 403 } 404 405 // Handle /failifmismatch 406 for (auto *Arg : Args.filtered(OPT_failifmismatch)) 407 checkFailIfMismatch(Arg->getValue()); 408 409 // Handle /merge 410 for (auto *Arg : Args.filtered(OPT_merge)) 411 parseMerge(Arg->getValue()); 412 413 // Handle /section 414 for (auto *Arg : Args.filtered(OPT_section)) 415 parseSection(Arg->getValue()); 416 417 // Handle /manifest 418 if (auto *Arg = Args.getLastArg(OPT_manifest_colon)) 419 parseManifest(Arg->getValue()); 420 421 // Handle /manifestuac 422 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) 423 parseManifestUAC(Arg->getValue()); 424 425 // Handle /manifestdependency 426 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) 427 Config->ManifestDependency = Arg->getValue(); 428 429 // Handle /manifestfile 430 if (auto *Arg = Args.getLastArg(OPT_manifestfile)) 431 Config->ManifestFile = Arg->getValue(); 432 433 // Handle /manifestinput 434 for (auto *Arg : Args.filtered(OPT_manifestinput)) 435 Config->ManifestInput.push_back(Arg->getValue()); 436 437 // Handle miscellaneous boolean flags. 438 if (Args.hasArg(OPT_allowbind_no)) 439 Config->AllowBind = false; 440 if (Args.hasArg(OPT_allowisolation_no)) 441 Config->AllowIsolation = false; 442 if (Args.hasArg(OPT_dynamicbase_no)) 443 Config->DynamicBase = false; 444 if (Args.hasArg(OPT_nxcompat_no)) 445 Config->NxCompat = false; 446 if (Args.hasArg(OPT_tsaware_no)) 447 Config->TerminalServerAware = false; 448 if (Args.hasArg(OPT_nosymtab)) 449 Config->WriteSymtab = false; 450 451 // Create a list of input files. Files can be given as arguments 452 // for /defaultlib option. 453 std::vector<StringRef> Paths; 454 std::vector<MemoryBufferRef> MBs; 455 for (auto *Arg : Args.filtered(OPT_INPUT)) 456 if (Optional<StringRef> Path = findFile(Arg->getValue())) 457 Paths.push_back(*Path); 458 for (auto *Arg : Args.filtered(OPT_defaultlib)) 459 if (Optional<StringRef> Path = findLib(Arg->getValue())) 460 Paths.push_back(*Path); 461 for (StringRef Path : Paths) 462 MBs.push_back(openFile(Path)); 463 464 // Windows specific -- Create a resource file containing a manifest file. 465 if (Config->Manifest == Configuration::Embed) { 466 std::unique_ptr<MemoryBuffer> MB = createManifestRes(); 467 MBs.push_back(MB->getMemBufferRef()); 468 OwningMBs.push_back(std::move(MB)); // take ownership 469 } 470 471 // Windows specific -- Input files can be Windows resource files (.res files). 472 // We invoke cvtres.exe to convert resource files to a regular COFF file 473 // then link the result file normally. 474 std::vector<MemoryBufferRef> Resources; 475 auto NotResource = [](MemoryBufferRef MB) { 476 return identify_magic(MB.getBuffer()) != file_magic::windows_resource; 477 }; 478 auto It = std::stable_partition(MBs.begin(), MBs.end(), NotResource); 479 if (It != MBs.end()) { 480 Resources.insert(Resources.end(), It, MBs.end()); 481 MBs.erase(It, MBs.end()); 482 } 483 484 // Read all input files given via the command line. Note that step() 485 // doesn't read files that are specified by directive sections. 486 for (MemoryBufferRef MB : MBs) 487 Symtab.addFile(createFile(MB)); 488 Symtab.step(); 489 490 // Determine machine type and check if all object files are 491 // for the same CPU type. Note that this needs to be done before 492 // any call to mangle(). 493 for (std::unique_ptr<InputFile> &File : Symtab.getFiles()) { 494 MachineTypes MT = File->getMachineType(); 495 if (MT == IMAGE_FILE_MACHINE_UNKNOWN) 496 continue; 497 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { 498 Config->Machine = MT; 499 continue; 500 } 501 if (Config->Machine != MT) 502 fatal(File->getShortName() + ": machine type " + machineToStr(MT) + 503 " conflicts with " + machineToStr(Config->Machine)); 504 } 505 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { 506 llvm::errs() << "warning: /machine is not specified. x64 is assumed.\n"; 507 Config->Machine = AMD64; 508 } 509 510 // Windows specific -- Convert Windows resource files to a COFF file. 511 if (!Resources.empty()) { 512 std::unique_ptr<MemoryBuffer> MB = convertResToCOFF(Resources); 513 Symtab.addFile(createFile(MB->getMemBufferRef())); 514 OwningMBs.push_back(std::move(MB)); // take ownership 515 } 516 517 // Handle /largeaddressaware 518 if (Config->is64() || Args.hasArg(OPT_largeaddressaware)) 519 Config->LargeAddressAware = true; 520 521 // Handle /highentropyva 522 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no)) 523 Config->HighEntropyVA = true; 524 525 // Handle /entry and /dll 526 if (auto *Arg = Args.getLastArg(OPT_entry)) { 527 Config->Entry = addUndefined(mangle(Arg->getValue())); 528 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) { 529 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" 530 : "_DllMainCRTStartup"; 531 Config->Entry = addUndefined(S); 532 } else if (!Config->NoEntry) { 533 // Windows specific -- If entry point name is not given, we need to 534 // infer that from user-defined entry name. 535 StringRef S = findDefaultEntry(); 536 if (S.empty()) 537 fatal("entry point must be defined"); 538 Config->Entry = addUndefined(S); 539 if (Config->Verbose) 540 llvm::outs() << "Entry name inferred: " << S << "\n"; 541 } 542 543 // Handle /export 544 for (auto *Arg : Args.filtered(OPT_export)) { 545 Export E = parseExport(Arg->getValue()); 546 if (Config->Machine == I386) { 547 if (!isDecorated(E.Name)) 548 E.Name = Alloc.save("_" + E.Name); 549 if (!E.ExtName.empty() && !isDecorated(E.ExtName)) 550 E.ExtName = Alloc.save("_" + E.ExtName); 551 } 552 Config->Exports.push_back(E); 553 } 554 555 // Handle /def 556 if (auto *Arg = Args.getLastArg(OPT_deffile)) { 557 MemoryBufferRef MB = openFile(Arg->getValue()); 558 // parseModuleDefs mutates Config object. 559 parseModuleDefs(MB, &Alloc); 560 } 561 562 // Handle /delayload 563 for (auto *Arg : Args.filtered(OPT_delayload)) { 564 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower()); 565 if (Config->Machine == I386) { 566 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8"); 567 } else { 568 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2"); 569 } 570 } 571 572 // Set default image base if /base is not given. 573 if (Config->ImageBase == uint64_t(-1)) 574 Config->ImageBase = getDefaultImageBase(); 575 576 Symtab.addRelative(mangle("__ImageBase"), 0); 577 if (Config->Machine == I386) { 578 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0); 579 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0); 580 } 581 582 // We do not support /guard:cf (control flow protection) yet. 583 // Define CFG symbols anyway so that we can link MSVC 2015 CRT. 584 Symtab.addAbsolute(mangle("__guard_fids_table"), 0); 585 Symtab.addAbsolute(mangle("__guard_fids_count"), 0); 586 Symtab.addAbsolute(mangle("__guard_flags"), 0x100); 587 588 // Read as much files as we can from directives sections. 589 Symtab.run(); 590 591 // Resolve auxiliary symbols until we get a convergence. 592 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file. 593 // A new file may contain a directive section to add new command line options. 594 // That's why we have to repeat until converge.) 595 for (;;) { 596 // Windows specific -- if entry point is not found, 597 // search for its mangled names. 598 if (Config->Entry) 599 Symtab.mangleMaybe(Config->Entry); 600 601 // Windows specific -- Make sure we resolve all dllexported symbols. 602 for (Export &E : Config->Exports) { 603 if (!E.ForwardTo.empty()) 604 continue; 605 E.Sym = addUndefined(E.Name); 606 if (!E.Directives) 607 Symtab.mangleMaybe(E.Sym); 608 } 609 610 // Add weak aliases. Weak aliases is a mechanism to give remaining 611 // undefined symbols final chance to be resolved successfully. 612 for (auto Pair : Config->AlternateNames) { 613 StringRef From = Pair.first; 614 StringRef To = Pair.second; 615 Symbol *Sym = Symtab.find(From); 616 if (!Sym) 617 continue; 618 if (auto *U = dyn_cast<Undefined>(Sym->Body)) 619 if (!U->WeakAlias) 620 U->WeakAlias = Symtab.addUndefined(To); 621 } 622 623 // Windows specific -- if __load_config_used can be resolved, resolve it. 624 if (Symtab.findUnderscore("_load_config_used")) 625 addUndefined(mangle("_load_config_used")); 626 627 if (Symtab.queueEmpty()) 628 break; 629 Symtab.run(); 630 } 631 632 // Do LTO by compiling bitcode input files to a set of native COFF files then 633 // link those files. 634 Symtab.addCombinedLTOObjects(); 635 636 // Make sure we have resolved all symbols. 637 Symtab.reportRemainingUndefines(/*Resolve=*/true); 638 639 // Windows specific -- if no /subsystem is given, we need to infer 640 // that from entry point name. 641 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 642 Config->Subsystem = inferSubsystem(); 643 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 644 fatal("subsystem must be defined"); 645 } 646 647 // Handle /safeseh. 648 if (Args.hasArg(OPT_safeseh)) 649 for (ObjectFile *File : Symtab.ObjectFiles) 650 if (!File->SEHCompat) 651 fatal("/safeseh: " + File->getName() + " is not compatible with SEH"); 652 653 // Windows specific -- when we are creating a .dll file, we also 654 // need to create a .lib file. 655 if (!Config->Exports.empty() || Config->DLL) { 656 fixupExports(); 657 writeImportLibrary(); 658 assignExportOrdinals(); 659 } 660 661 // Windows specific -- Create a side-by-side manifest file. 662 if (Config->Manifest == Configuration::SideBySide) 663 createSideBySideManifest(); 664 665 // Create a dummy PDB file to satisfy build sytem rules. 666 if (auto *Arg = Args.getLastArg(OPT_pdb)) 667 createPDB(Arg->getValue()); 668 669 // Identify unreferenced COMDAT sections. 670 if (Config->DoGC) 671 markLive(Symtab.getChunks()); 672 673 // Identify identical COMDAT sections to merge them. 674 if (Config->DoICF) 675 doICF(Symtab.getChunks()); 676 677 // Write the result. 678 writeResult(&Symtab); 679 680 // Create a symbol map file containing symbol VAs and their names 681 // to help debugging. 682 if (auto *Arg = Args.getLastArg(OPT_lldmap)) { 683 std::error_code EC; 684 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text); 685 if (EC) 686 fatal(EC, "could not create the symbol map"); 687 Symtab.printMap(Out); 688 } 689 // Call exit to avoid calling destructors. 690 exit(0); 691 } 692 693 } // namespace coff 694 } // namespace lld 695