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