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