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