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