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