Guest User

Untitled

a guest
Jan 1st, 2020
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 68.94 KB | None | 0 0
  1. //===- Driver.cpp ---------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8.  
  9. #include "Driver.h"
  10. #include "Config.h"
  11. #include "DebugTypes.h"
  12. #include "ICF.h"
  13. #include "InputFiles.h"
  14. #include "MarkLive.h"
  15. #include "MinGW.h"
  16. #include "SymbolTable.h"
  17. #include "Symbols.h"
  18. #include "Writer.h"
  19. #include "lld/Common/Args.h"
  20. #include "lld/Common/Driver.h"
  21. #include "lld/Common/ErrorHandler.h"
  22. #include "lld/Common/Filesystem.h"
  23. #include "lld/Common/Memory.h"
  24. #include "lld/Common/Threads.h"
  25. #include "lld/Common/Timer.h"
  26. #include "lld/Common/Version.h"
  27. #include "llvm/ADT/Optional.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/BinaryFormat/Magic.h"
  30. #include "llvm/LTO/LTO.h"
  31. #include "llvm/Object/ArchiveWriter.h"
  32. #include "llvm/Object/COFFImportFile.h"
  33. #include "llvm/Object/COFFModuleDefinition.h"
  34. #include "llvm/Object/WindowsMachineFlag.h"
  35. #include "llvm/Option/Arg.h"
  36. #include "llvm/Option/ArgList.h"
  37. #include "llvm/Option/Option.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/LEB128.h"
  41. #include "llvm/Support/MathExtras.h"
  42. #include "llvm/Support/Path.h"
  43. #include "llvm/Support/Process.h"
  44. #include "llvm/Support/TarWriter.h"
  45. #include "llvm/Support/TargetSelect.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
  48. #include <algorithm>
  49. #include <future>
  50. #include <memory>
  51.  
  52. using namespace llvm;
  53. using namespace llvm::object;
  54. using namespace llvm::COFF;
  55. using llvm::sys::Process;
  56.  
  57. namespace polly {
  58. void initializePollyPasses(llvm::PassRegistry &Registry);
  59. }
  60.  
  61. namespace lld {
  62. namespace coff {
  63.  
  64. static Timer inputFileTimer("Input File Reading", Timer::root());
  65.  
  66. Configuration *config;
  67. LinkerDriver *driver;
  68.  
  69. bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS,
  70. raw_ostream &stderrOS) {
  71. lld::stdoutOS = &stdoutOS;
  72. lld::stderrOS = &stderrOS;
  73.  
  74. errorHandler().logName = args::getFilenameWithoutExe(args[0]);
  75. errorHandler().errorLimitExceededMsg =
  76. "too many errors emitted, stopping now"
  77. " (use /errorlimit:0 to see all errors)";
  78. errorHandler().exitEarly = canExitEarly;
  79. stderrOS.enable_colors(stderrOS.has_colors());
  80.  
  81. config = make<Configuration>();
  82. symtab = make<SymbolTable>();
  83. driver = make<LinkerDriver>();
  84.  
  85. driver->link(args);
  86.  
  87. // Call exit() if we can to avoid calling destructors.
  88. if (canExitEarly)
  89. exitLld(errorCount() ? 1 : 0);
  90.  
  91. freeArena();
  92. ObjFile::instances.clear();
  93. ImportFile::instances.clear();
  94. BitcodeFile::instances.clear();
  95. memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
  96. return !errorCount();
  97. }
  98.  
  99. // Parse options of the form "old;new".
  100. static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
  101. unsigned id) {
  102. auto *arg = args.getLastArg(id);
  103. if (!arg)
  104. return {"", ""};
  105.  
  106. StringRef s = arg->getValue();
  107. std::pair<StringRef, StringRef> ret = s.split(';');
  108. if (ret.second.empty())
  109. error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
  110. return ret;
  111. }
  112.  
  113. // Drop directory components and replace extension with
  114. // ".exe", ".dll" or ".sys".
  115. static std::string getOutputPath(StringRef path) {
  116. StringRef ext = ".exe";
  117. if (config->dll)
  118. ext = ".dll";
  119. else if (config->driver)
  120. ext = ".sys";
  121.  
  122. return (sys::path::stem(path) + ext).str();
  123. }
  124.  
  125. // Returns true if S matches /crtend.?\.o$/.
  126. static bool isCrtend(StringRef s) {
  127. if (!s.endswith(".o"))
  128. return false;
  129. s = s.drop_back(2);
  130. if (s.endswith("crtend"))
  131. return true;
  132. return !s.empty() && s.drop_back().endswith("crtend");
  133. }
  134.  
  135. // ErrorOr is not default constructible, so it cannot be used as the type
  136. // parameter of a future.
  137. // FIXME: We could open the file in createFutureForFile and avoid needing to
  138. // return an error here, but for the moment that would cost us a file descriptor
  139. // (a limited resource on Windows) for the duration that the future is pending.
  140. using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
  141.  
  142. // Create a std::future that opens and maps a file using the best strategy for
  143. // the host platform.
  144. static std::future<MBErrPair> createFutureForFile(std::string path) {
  145. #if _WIN32
  146. // On Windows, file I/O is relatively slow so it is best to do this
  147. // asynchronously.
  148. auto strategy = std::launch::async;
  149. #else
  150. auto strategy = std::launch::deferred;
  151. #endif
  152. return std::async(strategy, [=]() {
  153. auto mbOrErr = MemoryBuffer::getFile(path,
  154. /*FileSize*/ -1,
  155. /*RequiresNullTerminator*/ false);
  156. if (!mbOrErr)
  157. return MBErrPair{nullptr, mbOrErr.getError()};
  158. return MBErrPair{std::move(*mbOrErr), std::error_code()};
  159. });
  160. }
  161.  
  162. // Symbol names are mangled by prepending "_" on x86.
  163. static StringRef mangle(StringRef sym) {
  164. assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
  165. if (config->machine == I386)
  166. return saver.save("_" + sym);
  167. return sym;
  168. }
  169.  
  170. static bool findUnderscoreMangle(StringRef sym) {
  171. Symbol *s = symtab->findMangle(mangle(sym));
  172. return s && !isa<Undefined>(s);
  173. }
  174.  
  175. MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
  176. MemoryBufferRef mbref = *mb;
  177. make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
  178.  
  179. if (driver->tar)
  180. driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
  181. mbref.getBuffer());
  182. return mbref;
  183. }
  184.  
  185. void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
  186. bool wholeArchive, bool lazy) {
  187. StringRef filename = mb->getBufferIdentifier();
  188.  
  189. MemoryBufferRef mbref = takeBuffer(std::move(mb));
  190. filePaths.push_back(filename);
  191.  
  192. // File type is detected by contents, not by file extension.
  193. switch (identify_magic(mbref.getBuffer())) {
  194. case file_magic::windows_resource:
  195. resources.push_back(mbref);
  196. break;
  197. case file_magic::archive:
  198. if (wholeArchive) {
  199. std::unique_ptr<Archive> file =
  200. CHECK(Archive::create(mbref), filename + ": failed to parse archive");
  201. Archive *archive = file.get();
  202. make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
  203.  
  204. int memberIndex = 0;
  205. for (MemoryBufferRef m : getArchiveMembers(archive))
  206. addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
  207. return;
  208. }
  209. symtab->addFile(make<ArchiveFile>(mbref));
  210. break;
  211. case file_magic::bitcode:
  212. if (lazy)
  213. symtab->addFile(make<LazyObjFile>(mbref));
  214. else
  215. symtab->addFile(make<BitcodeFile>(mbref, "", 0));
  216. break;
  217. case file_magic::coff_object:
  218. case file_magic::coff_import_library:
  219. if (lazy)
  220. symtab->addFile(make<LazyObjFile>(mbref));
  221. else
  222. symtab->addFile(make<ObjFile>(mbref));
  223. break;
  224. case file_magic::pdb:
  225. loadTypeServerSource(mbref);
  226. break;
  227. case file_magic::coff_cl_gl_object:
  228. error(filename + ": is not a native COFF file. Recompile without /GL");
  229. break;
  230. case file_magic::pecoff_executable:
  231. if (filename.endswith_lower(".dll")) {
  232. error(filename + ": bad file type. Did you specify a DLL instead of an "
  233. "import library?");
  234. break;
  235. }
  236. LLVM_FALLTHROUGH;
  237. default:
  238. error(mbref.getBufferIdentifier() + ": unknown file type");
  239. break;
  240. }
  241. }
  242.  
  243. void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
  244. auto future =
  245. std::make_shared<std::future<MBErrPair>>(createFutureForFile(path));
  246. std::string pathStr = path;
  247. enqueueTask([=]() {
  248. auto mbOrErr = future->get();
  249. if (mbOrErr.second) {
  250. std::string msg =
  251. "could not open '" + pathStr + "': " + mbOrErr.second.message();
  252. // Check if the filename is a typo for an option flag. OptTable thinks
  253. // that all args that are not known options and that start with / are
  254. // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
  255. // the option `/nodefaultlib` than a reference to a file in the root
  256. // directory.
  257. std::string nearest;
  258. if (COFFOptTable().findNearest(pathStr, nearest) > 1)
  259. error(msg);
  260. else
  261. error(msg + "; did you mean '" + nearest + "'");
  262. } else
  263. driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
  264. });
  265. }
  266.  
  267. void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
  268. StringRef parentName,
  269. uint64_t offsetInArchive) {
  270. file_magic magic = identify_magic(mb.getBuffer());
  271. if (magic == file_magic::coff_import_library) {
  272. InputFile *imp = make<ImportFile>(mb);
  273. imp->parentName = parentName;
  274. symtab->addFile(imp);
  275. return;
  276. }
  277.  
  278. InputFile *obj;
  279. if (magic == file_magic::coff_object) {
  280. obj = make<ObjFile>(mb);
  281. } else if (magic == file_magic::bitcode) {
  282. obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
  283. } else {
  284. error("unknown file type: " + mb.getBufferIdentifier());
  285. return;
  286. }
  287.  
  288. obj->parentName = parentName;
  289. symtab->addFile(obj);
  290. log("Loaded " + toString(obj) + " for " + symName);
  291. }
  292.  
  293. void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
  294. const Archive::Symbol &sym,
  295. StringRef parentName) {
  296.  
  297. auto reportBufferError = [=](Error &&e, StringRef childName) {
  298. fatal("could not get the buffer for the member defining symbol " +
  299. toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
  300. toString(std::move(e)));
  301. };
  302.  
  303. if (!c.getParent()->isThin()) {
  304. uint64_t offsetInArchive = c.getChildOffset();
  305. Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
  306. if (!mbOrErr)
  307. reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
  308. MemoryBufferRef mb = mbOrErr.get();
  309. enqueueTask([=]() {
  310. driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
  311. offsetInArchive);
  312. });
  313. return;
  314. }
  315.  
  316. std::string childName = CHECK(
  317. c.getFullName(),
  318. "could not get the filename for the member defining symbol " +
  319. toCOFFString(sym));
  320. auto future = std::make_shared<std::future<MBErrPair>>(
  321. createFutureForFile(childName));
  322. enqueueTask([=]() {
  323. auto mbOrErr = future->get();
  324. if (mbOrErr.second)
  325. reportBufferError(errorCodeToError(mbOrErr.second), childName);
  326. // Pass empty string as archive name so that the original filename is
  327. // used as the buffer identifier.
  328. driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
  329. toCOFFString(sym), "", /*OffsetInArchive=*/0);
  330. });
  331. }
  332.  
  333. static bool isDecorated(StringRef sym) {
  334. return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
  335. (!config->mingw && sym.contains('@'));
  336. }
  337.  
  338. // Parses .drectve section contents and returns a list of files
  339. // specified by /defaultlib.
  340. void LinkerDriver::parseDirectives(InputFile *file) {
  341. StringRef s = file->getDirectives();
  342. if (s.empty())
  343. return;
  344.  
  345. log("Directives: " + toString(file) + ": " + s);
  346.  
  347. ArgParser parser;
  348. // .drectve is always tokenized using Windows shell rules.
  349. // /EXPORT: option can appear too many times, processing in fastpath.
  350. opt::InputArgList args;
  351. std::vector<StringRef> exports;
  352. std::tie(args, exports) = parser.parseDirectives(s);
  353.  
  354. for (StringRef e : exports) {
  355. // If a common header file contains dllexported function
  356. // declarations, many object files may end up with having the
  357. // same /EXPORT options. In order to save cost of parsing them,
  358. // we dedup them first.
  359. if (!directivesExports.insert(e).second)
  360. continue;
  361.  
  362. Export exp = parseExport(e);
  363. if (config->machine == I386 && config->mingw) {
  364. if (!isDecorated(exp.name))
  365. exp.name = saver.save("_" + exp.name);
  366. if (!exp.extName.empty() && !isDecorated(exp.extName))
  367. exp.extName = saver.save("_" + exp.extName);
  368. }
  369. exp.directives = true;
  370. config->exports.push_back(exp);
  371. }
  372.  
  373. for (auto *arg : args) {
  374. switch (arg->getOption().getID()) {
  375. case OPT_aligncomm:
  376. parseAligncomm(arg->getValue());
  377. break;
  378. case OPT_alternatename:
  379. parseAlternateName(arg->getValue());
  380. break;
  381. case OPT_defaultlib:
  382. if (Optional<StringRef> path = findLib(arg->getValue()))
  383. enqueuePath(*path, false, false);
  384. break;
  385. case OPT_entry:
  386. config->entry = addUndefined(mangle(arg->getValue()));
  387. break;
  388. case OPT_failifmismatch:
  389. checkFailIfMismatch(arg->getValue(), file);
  390. break;
  391. case OPT_incl:
  392. addUndefined(arg->getValue());
  393. break;
  394. case OPT_merge:
  395. parseMerge(arg->getValue());
  396. break;
  397. case OPT_nodefaultlib:
  398. config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
  399. break;
  400. case OPT_section:
  401. parseSection(arg->getValue());
  402. break;
  403. case OPT_subsystem:
  404. parseSubsystem(arg->getValue(), &config->subsystem,
  405. &config->majorOSVersion, &config->minorOSVersion);
  406. break;
  407. // Only add flags here that link.exe accepts in
  408. // `#pragma comment(linker, "/flag")`-generated sections.
  409. case OPT_editandcontinue:
  410. case OPT_guardsym:
  411. case OPT_throwingnew:
  412. break;
  413. default:
  414. error(arg->getSpelling() + " is not allowed in .drectve");
  415. }
  416. }
  417. }
  418.  
  419. // Find file from search paths. You can omit ".obj", this function takes
  420. // care of that. Note that the returned path is not guaranteed to exist.
  421. StringRef LinkerDriver::doFindFile(StringRef filename) {
  422. bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
  423. if (hasPathSep)
  424. return filename;
  425. bool hasExt = filename.contains('.');
  426. for (StringRef dir : searchPaths) {
  427. SmallString<128> path = dir;
  428. sys::path::append(path, filename);
  429. if (sys::fs::exists(path.str()))
  430. return saver.save(path.str());
  431. if (!hasExt) {
  432. path.append(".obj");
  433. if (sys::fs::exists(path.str()))
  434. return saver.save(path.str());
  435. }
  436. }
  437. return filename;
  438. }
  439.  
  440. static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
  441. sys::fs::UniqueID ret;
  442. if (sys::fs::getUniqueID(path, ret))
  443. return None;
  444. return ret;
  445. }
  446.  
  447. // Resolves a file path. This never returns the same path
  448. // (in that case, it returns None).
  449. Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
  450. StringRef path = doFindFile(filename);
  451.  
  452. if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
  453. bool seen = !visitedFiles.insert(*id).second;
  454. if (seen)
  455. return None;
  456. }
  457.  
  458. if (path.endswith_lower(".lib"))
  459. visitedLibs.insert(sys::path::filename(path));
  460. return path;
  461. }
  462.  
  463. // MinGW specific. If an embedded directive specified to link to
  464. // foo.lib, but it isn't found, try libfoo.a instead.
  465. StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
  466. if (filename.contains('/') || filename.contains('\\'))
  467. return filename;
  468.  
  469. SmallString<128> s = filename;
  470. sys::path::replace_extension(s, ".a");
  471. StringRef libName = saver.save("lib" + s.str());
  472. return doFindFile(libName);
  473. }
  474.  
  475. // Find library file from search path.
  476. StringRef LinkerDriver::doFindLib(StringRef filename) {
  477. // Add ".lib" to Filename if that has no file extension.
  478. bool hasExt = filename.contains('.');
  479. if (!hasExt)
  480. filename = saver.save(filename + ".lib");
  481. StringRef ret = doFindFile(filename);
  482. // For MinGW, if the find above didn't turn up anything, try
  483. // looking for a MinGW formatted library name.
  484. if (config->mingw && ret == filename)
  485. return doFindLibMinGW(filename);
  486. return ret;
  487. }
  488.  
  489. // Resolves a library path. /nodefaultlib options are taken into
  490. // consideration. This never returns the same path (in that case,
  491. // it returns None).
  492. Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
  493. if (config->noDefaultLibAll)
  494. return None;
  495. if (!visitedLibs.insert(filename.lower()).second)
  496. return None;
  497.  
  498. StringRef path = doFindLib(filename);
  499. if (config->noDefaultLibs.count(path.lower()))
  500. return None;
  501.  
  502. if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
  503. if (!visitedFiles.insert(*id).second)
  504. return None;
  505. return path;
  506. }
  507.  
  508. // Parses LIB environment which contains a list of search paths.
  509. void LinkerDriver::addLibSearchPaths() {
  510. Optional<std::string> envOpt = Process::GetEnv("LIB");
  511. if (!envOpt.hasValue())
  512. return;
  513. StringRef env = saver.save(*envOpt);
  514. while (!env.empty()) {
  515. StringRef path;
  516. std::tie(path, env) = env.split(';');
  517. searchPaths.push_back(path);
  518. }
  519. }
  520.  
  521. Symbol *LinkerDriver::addUndefined(StringRef name) {
  522. Symbol *b = symtab->addUndefined(name);
  523. if (!b->isGCRoot) {
  524. b->isGCRoot = true;
  525. config->gcroot.push_back(b);
  526. }
  527. return b;
  528. }
  529.  
  530. StringRef LinkerDriver::mangleMaybe(Symbol *s) {
  531. // If the plain symbol name has already been resolved, do nothing.
  532. Undefined *unmangled = dyn_cast<Undefined>(s);
  533. if (!unmangled)
  534. return "";
  535.  
  536. // Otherwise, see if a similar, mangled symbol exists in the symbol table.
  537. Symbol *mangled = symtab->findMangle(unmangled->getName());
  538. if (!mangled)
  539. return "";
  540.  
  541. // If we find a similar mangled symbol, make this an alias to it and return
  542. // its name.
  543. log(unmangled->getName() + " aliased to " + mangled->getName());
  544. unmangled->weakAlias = symtab->addUndefined(mangled->getName());
  545. return mangled->getName();
  546. }
  547.  
  548. // Windows specific -- find default entry point name.
  549. //
  550. // There are four different entry point functions for Windows executables,
  551. // each of which corresponds to a user-defined "main" function. This function
  552. // infers an entry point from a user-defined "main" function.
  553. StringRef LinkerDriver::findDefaultEntry() {
  554. assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
  555. "must handle /subsystem before calling this");
  556.  
  557. if (config->mingw)
  558. return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
  559. ? "WinMainCRTStartup"
  560. : "mainCRTStartup");
  561.  
  562. if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
  563. if (findUnderscoreMangle("wWinMain")) {
  564. if (!findUnderscoreMangle("WinMain"))
  565. return mangle("wWinMainCRTStartup");
  566. warn("found both wWinMain and WinMain; using latter");
  567. }
  568. return mangle("WinMainCRTStartup");
  569. }
  570. if (findUnderscoreMangle("wmain")) {
  571. if (!findUnderscoreMangle("main"))
  572. return mangle("wmainCRTStartup");
  573. warn("found both wmain and main; using latter");
  574. }
  575. return mangle("mainCRTStartup");
  576. }
  577.  
  578. WindowsSubsystem LinkerDriver::inferSubsystem() {
  579. if (config->dll)
  580. return IMAGE_SUBSYSTEM_WINDOWS_GUI;
  581. if (config->mingw)
  582. return IMAGE_SUBSYSTEM_WINDOWS_CUI;
  583. // Note that link.exe infers the subsystem from the presence of these
  584. // functions even if /entry: or /nodefaultlib are passed which causes them
  585. // to not be called.
  586. bool haveMain = findUnderscoreMangle("main");
  587. bool haveWMain = findUnderscoreMangle("wmain");
  588. bool haveWinMain = findUnderscoreMangle("WinMain");
  589. bool haveWWinMain = findUnderscoreMangle("wWinMain");
  590. if (haveMain || haveWMain) {
  591. if (haveWinMain || haveWWinMain) {
  592. warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
  593. (haveWinMain ? "WinMain" : "wWinMain") +
  594. "; defaulting to /subsystem:console");
  595. }
  596. return IMAGE_SUBSYSTEM_WINDOWS_CUI;
  597. }
  598. if (haveWinMain || haveWWinMain)
  599. return IMAGE_SUBSYSTEM_WINDOWS_GUI;
  600. return IMAGE_SUBSYSTEM_UNKNOWN;
  601. }
  602.  
  603. static uint64_t getDefaultImageBase() {
  604. if (config->is64())
  605. return config->dll ? 0x180000000 : 0x140000000;
  606. return config->dll ? 0x10000000 : 0x400000;
  607. }
  608.  
  609. static std::string createResponseFile(const opt::InputArgList &args,
  610. ArrayRef<StringRef> filePaths,
  611. ArrayRef<StringRef> searchPaths) {
  612. SmallString<0> data;
  613. raw_svector_ostream os(data);
  614.  
  615. for (auto *arg : args) {
  616. switch (arg->getOption().getID()) {
  617. case OPT_linkrepro:
  618. case OPT_reproduce:
  619. case OPT_INPUT:
  620. case OPT_defaultlib:
  621. case OPT_libpath:
  622. case OPT_manifest:
  623. case OPT_manifest_colon:
  624. case OPT_manifestdependency:
  625. case OPT_manifestfile:
  626. case OPT_manifestinput:
  627. case OPT_manifestuac:
  628. break;
  629. case OPT_implib:
  630. case OPT_pdb:
  631. case OPT_out:
  632. os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
  633. break;
  634. default:
  635. os << toString(*arg) << "\n";
  636. }
  637. }
  638.  
  639. for (StringRef path : searchPaths) {
  640. std::string relPath = relativeToRoot(path);
  641. os << "/libpath:" << quote(relPath) << "\n";
  642. }
  643.  
  644. for (StringRef path : filePaths)
  645. os << quote(relativeToRoot(path)) << "\n";
  646.  
  647. return data.str();
  648. }
  649.  
  650. enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
  651.  
  652. static DebugKind parseDebugKind(const opt::InputArgList &args) {
  653. auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
  654. if (!a)
  655. return DebugKind::None;
  656. if (a->getNumValues() == 0)
  657. return DebugKind::Full;
  658.  
  659. DebugKind debug = StringSwitch<DebugKind>(a->getValue())
  660. .CaseLower("none", DebugKind::None)
  661. .CaseLower("full", DebugKind::Full)
  662. .CaseLower("fastlink", DebugKind::FastLink)
  663. // LLD extensions
  664. .CaseLower("ghash", DebugKind::GHash)
  665. .CaseLower("dwarf", DebugKind::Dwarf)
  666. .CaseLower("symtab", DebugKind::Symtab)
  667. .Default(DebugKind::Unknown);
  668.  
  669. if (debug == DebugKind::FastLink) {
  670. warn("/debug:fastlink unsupported; using /debug:full");
  671. return DebugKind::Full;
  672. }
  673. if (debug == DebugKind::Unknown) {
  674. error("/debug: unknown option: " + Twine(a->getValue()));
  675. return DebugKind::None;
  676. }
  677. return debug;
  678. }
  679.  
  680. static unsigned parseDebugTypes(const opt::InputArgList &args) {
  681. unsigned debugTypes = static_cast<unsigned>(DebugType::None);
  682.  
  683. if (auto *a = args.getLastArg(OPT_debugtype)) {
  684. SmallVector<StringRef, 3> types;
  685. StringRef(a->getValue())
  686. .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  687.  
  688. for (StringRef type : types) {
  689. unsigned v = StringSwitch<unsigned>(type.lower())
  690. .Case("cv", static_cast<unsigned>(DebugType::CV))
  691. .Case("pdata", static_cast<unsigned>(DebugType::PData))
  692. .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
  693. .Default(0);
  694. if (v == 0) {
  695. warn("/debugtype: unknown option '" + type + "'");
  696. continue;
  697. }
  698. debugTypes |= v;
  699. }
  700. return debugTypes;
  701. }
  702.  
  703. // Default debug types
  704. debugTypes = static_cast<unsigned>(DebugType::CV);
  705. if (args.hasArg(OPT_driver))
  706. debugTypes |= static_cast<unsigned>(DebugType::PData);
  707. if (args.hasArg(OPT_profile))
  708. debugTypes |= static_cast<unsigned>(DebugType::Fixup);
  709.  
  710. return debugTypes;
  711. }
  712.  
  713. static std::string getMapFile(const opt::InputArgList &args) {
  714. auto *arg = args.getLastArg(OPT_lldmap, OPT_lldmap_file);
  715. if (!arg)
  716. return "";
  717. if (arg->getOption().getID() == OPT_lldmap_file)
  718. return arg->getValue();
  719.  
  720. assert(arg->getOption().getID() == OPT_lldmap);
  721. StringRef outFile = config->outputFile;
  722. return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
  723. }
  724.  
  725. static std::string getImplibPath() {
  726. if (!config->implib.empty())
  727. return config->implib;
  728. SmallString<128> out = StringRef(config->outputFile);
  729. sys::path::replace_extension(out, ".lib");
  730. return out.str();
  731. }
  732.  
  733. // The import name is calculated as follows:
  734. //
  735. // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
  736. // -----+----------------+---------------------+------------------
  737. // LINK | {value} | {value}.{.dll/.exe} | {output name}
  738. // LIB | {value} | {value}.dll | {output name}.dll
  739. //
  740. static std::string getImportName(bool asLib) {
  741. SmallString<128> out;
  742.  
  743. if (config->importName.empty()) {
  744. out.assign(sys::path::filename(config->outputFile));
  745. if (asLib)
  746. sys::path::replace_extension(out, ".dll");
  747. } else {
  748. out.assign(config->importName);
  749. if (!sys::path::has_extension(out))
  750. sys::path::replace_extension(out,
  751. (config->dll || asLib) ? ".dll" : ".exe");
  752. }
  753.  
  754. return out.str();
  755. }
  756.  
  757. static void createImportLibrary(bool asLib) {
  758. std::vector<COFFShortExport> exports;
  759. for (Export &e1 : config->exports) {
  760. COFFShortExport e2;
  761. e2.Name = e1.name;
  762. e2.SymbolName = e1.symbolName;
  763. e2.ExtName = e1.extName;
  764. e2.Ordinal = e1.ordinal;
  765. e2.Noname = e1.noname;
  766. e2.Data = e1.data;
  767. e2.Private = e1.isPrivate;
  768. e2.Constant = e1.constant;
  769. exports.push_back(e2);
  770. }
  771.  
  772. auto handleError = [](Error &&e) {
  773. handleAllErrors(std::move(e),
  774. [](ErrorInfoBase &eib) { error(eib.message()); });
  775. };
  776. std::string libName = getImportName(asLib);
  777. std::string path = getImplibPath();
  778.  
  779. if (!config->incremental) {
  780. handleError(writeImportLibrary(libName, path, exports, config->machine,
  781. config->mingw));
  782. return;
  783. }
  784.  
  785. // If the import library already exists, replace it only if the contents
  786. // have changed.
  787. ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
  788. path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
  789. if (!oldBuf) {
  790. handleError(writeImportLibrary(libName, path, exports, config->machine,
  791. config->mingw));
  792. return;
  793. }
  794.  
  795. SmallString<128> tmpName;
  796. if (std::error_code ec =
  797. sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
  798. fatal("cannot create temporary file for import library " + path + ": " +
  799. ec.message());
  800.  
  801. if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
  802. config->mingw)) {
  803. handleError(std::move(e));
  804. return;
  805. }
  806.  
  807. std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
  808. tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
  809. if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
  810. oldBuf->reset();
  811. handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
  812. } else {
  813. sys::fs::remove(tmpName);
  814. }
  815. }
  816.  
  817. static void parseModuleDefs(StringRef path) {
  818. std::unique_ptr<MemoryBuffer> mb = CHECK(
  819. MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
  820. COFFModuleDefinition m = check(parseCOFFModuleDefinition(
  821. mb->getMemBufferRef(), config->machine, config->mingw));
  822.  
  823. if (config->outputFile.empty())
  824. config->outputFile = saver.save(m.OutputFile);
  825. config->importName = saver.save(m.ImportName);
  826. if (m.ImageBase)
  827. config->imageBase = m.ImageBase;
  828. if (m.StackReserve)
  829. config->stackReserve = m.StackReserve;
  830. if (m.StackCommit)
  831. config->stackCommit = m.StackCommit;
  832. if (m.HeapReserve)
  833. config->heapReserve = m.HeapReserve;
  834. if (m.HeapCommit)
  835. config->heapCommit = m.HeapCommit;
  836. if (m.MajorImageVersion)
  837. config->majorImageVersion = m.MajorImageVersion;
  838. if (m.MinorImageVersion)
  839. config->minorImageVersion = m.MinorImageVersion;
  840. if (m.MajorOSVersion)
  841. config->majorOSVersion = m.MajorOSVersion;
  842. if (m.MinorOSVersion)
  843. config->minorOSVersion = m.MinorOSVersion;
  844.  
  845. for (COFFShortExport e1 : m.Exports) {
  846. Export e2;
  847. // In simple cases, only Name is set. Renamed exports are parsed
  848. // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
  849. // it shouldn't be a normal exported function but a forward to another
  850. // DLL instead. This is supported by both MS and GNU linkers.
  851. if (e1.ExtName != e1.Name && StringRef(e1.Name).contains('.')) {
  852. e2.name = saver.save(e1.ExtName);
  853. e2.forwardTo = saver.save(e1.Name);
  854. config->exports.push_back(e2);
  855. continue;
  856. }
  857. e2.name = saver.save(e1.Name);
  858. e2.extName = saver.save(e1.ExtName);
  859. e2.ordinal = e1.Ordinal;
  860. e2.noname = e1.Noname;
  861. e2.data = e1.Data;
  862. e2.isPrivate = e1.Private;
  863. e2.constant = e1.Constant;
  864. config->exports.push_back(e2);
  865. }
  866. }
  867.  
  868. void LinkerDriver::enqueueTask(std::function<void()> task) {
  869. taskQueue.push_back(std::move(task));
  870. }
  871.  
  872. bool LinkerDriver::run() {
  873. ScopedTimer t(inputFileTimer);
  874.  
  875. bool didWork = !taskQueue.empty();
  876. while (!taskQueue.empty()) {
  877. taskQueue.front()();
  878. taskQueue.pop_front();
  879. }
  880. return didWork;
  881. }
  882.  
  883. // Parse an /order file. If an option is given, the linker places
  884. // COMDAT sections in the same order as their names appear in the
  885. // given file.
  886. static void parseOrderFile(StringRef arg) {
  887. // For some reason, the MSVC linker requires a filename to be
  888. // preceded by "@".
  889. if (!arg.startswith("@")) {
  890. error("malformed /order option: '@' missing");
  891. return;
  892. }
  893.  
  894. // Get a list of all comdat sections for error checking.
  895. DenseSet<StringRef> set;
  896. for (Chunk *c : symtab->getChunks())
  897. if (auto *sec = dyn_cast<SectionChunk>(c))
  898. if (sec->sym)
  899. set.insert(sec->sym->getName());
  900.  
  901. // Open a file.
  902. StringRef path = arg.substr(1);
  903. std::unique_ptr<MemoryBuffer> mb = CHECK(
  904. MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
  905.  
  906. // Parse a file. An order file contains one symbol per line.
  907. // All symbols that were not present in a given order file are
  908. // considered to have the lowest priority 0 and are placed at
  909. // end of an output section.
  910. for (std::string s : args::getLines(mb->getMemBufferRef())) {
  911. if (config->machine == I386 && !isDecorated(s))
  912. s = "_" + s;
  913.  
  914. if (set.count(s) == 0) {
  915. if (config->warnMissingOrderSymbol)
  916. warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
  917. }
  918. else
  919. config->order[s] = INT_MIN + config->order.size();
  920. }
  921. }
  922.  
  923. static void markAddrsig(Symbol *s) {
  924. if (auto *d = dyn_cast_or_null<Defined>(s))
  925. if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
  926. c->keepUnique = true;
  927. }
  928.  
  929. static void findKeepUniqueSections() {
  930. // Exported symbols could be address-significant in other executables or DSOs,
  931. // so we conservatively mark them as address-significant.
  932. for (Export &r : config->exports)
  933. markAddrsig(r.sym);
  934.  
  935. // Visit the address-significance table in each object file and mark each
  936. // referenced symbol as address-significant.
  937. for (ObjFile *obj : ObjFile::instances) {
  938. ArrayRef<Symbol *> syms = obj->getSymbols();
  939. if (obj->addrsigSec) {
  940. ArrayRef<uint8_t> contents;
  941. cantFail(
  942. obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
  943. const uint8_t *cur = contents.begin();
  944. while (cur != contents.end()) {
  945. unsigned size;
  946. const char *err;
  947. uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
  948. if (err)
  949. fatal(toString(obj) + ": could not decode addrsig section: " + err);
  950. if (symIndex >= syms.size())
  951. fatal(toString(obj) + ": invalid symbol index in addrsig section");
  952. markAddrsig(syms[symIndex]);
  953. cur += size;
  954. }
  955. } else {
  956. // If an object file does not have an address-significance table,
  957. // conservatively mark all of its symbols as address-significant.
  958. for (Symbol *s : syms)
  959. markAddrsig(s);
  960. }
  961. }
  962. }
  963.  
  964. // link.exe replaces each %foo% in altPath with the contents of environment
  965. // variable foo, and adds the two magic env vars _PDB (expands to the basename
  966. // of pdb's output path) and _EXT (expands to the extension of the output
  967. // binary).
  968. // lld only supports %_PDB% and %_EXT% and warns on references to all other env
  969. // vars.
  970. static void parsePDBAltPath(StringRef altPath) {
  971. SmallString<128> buf;
  972. StringRef pdbBasename =
  973. sys::path::filename(config->pdbPath, sys::path::Style::windows);
  974. StringRef binaryExtension =
  975. sys::path::extension(config->outputFile, sys::path::Style::windows);
  976. if (!binaryExtension.empty())
  977. binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
  978.  
  979. // Invariant:
  980. // +--------- cursor ('a...' might be the empty string).
  981. // | +----- firstMark
  982. // | | +- secondMark
  983. // v v v
  984. // a...%...%...
  985. size_t cursor = 0;
  986. while (cursor < altPath.size()) {
  987. size_t firstMark, secondMark;
  988. if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
  989. (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
  990. // Didn't find another full fragment, treat rest of string as literal.
  991. buf.append(altPath.substr(cursor));
  992. break;
  993. }
  994.  
  995. // Found a full fragment. Append text in front of first %, and interpret
  996. // text between first and second % as variable name.
  997. buf.append(altPath.substr(cursor, firstMark - cursor));
  998. StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
  999. if (var.equals_lower("%_pdb%"))
  1000. buf.append(pdbBasename);
  1001. else if (var.equals_lower("%_ext%"))
  1002. buf.append(binaryExtension);
  1003. else {
  1004. warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
  1005. var + " as literal");
  1006. buf.append(var);
  1007. }
  1008.  
  1009. cursor = secondMark + 1;
  1010. }
  1011.  
  1012. config->pdbAltPath = buf;
  1013. }
  1014.  
  1015. /// Convert resource files and potentially merge input resource object
  1016. /// trees into one resource tree.
  1017. /// Call after ObjFile::Instances is complete.
  1018. void LinkerDriver::convertResources() {
  1019. std::vector<ObjFile *> resourceObjFiles;
  1020.  
  1021. for (ObjFile *f : ObjFile::instances) {
  1022. if (f->isResourceObjFile())
  1023. resourceObjFiles.push_back(f);
  1024. }
  1025.  
  1026. if (!config->mingw &&
  1027. (resourceObjFiles.size() > 1 ||
  1028. (resourceObjFiles.size() == 1 && !resources.empty()))) {
  1029. error((!resources.empty() ? "internal .obj file created from .res files"
  1030. : toString(resourceObjFiles[1])) +
  1031. ": more than one resource obj file not allowed, already got " +
  1032. toString(resourceObjFiles.front()));
  1033. return;
  1034. }
  1035.  
  1036. if (resources.empty() && resourceObjFiles.size() <= 1) {
  1037. // No resources to convert, and max one resource object file in
  1038. // the input. Keep that preconverted resource section as is.
  1039. for (ObjFile *f : resourceObjFiles)
  1040. f->includeResourceChunks();
  1041. return;
  1042. }
  1043. ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles));
  1044. symtab->addFile(f);
  1045. f->includeResourceChunks();
  1046. }
  1047.  
  1048. // In MinGW, if no symbols are chosen to be exported, then all symbols are
  1049. // automatically exported by default. This behavior can be forced by the
  1050. // -export-all-symbols option, so that it happens even when exports are
  1051. // explicitly specified. The automatic behavior can be disabled using the
  1052. // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
  1053. // than MinGW in the case that nothing is explicitly exported.
  1054. void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
  1055. if (!config->dll)
  1056. return;
  1057.  
  1058. if (!args.hasArg(OPT_export_all_symbols)) {
  1059. if (!config->exports.empty())
  1060. return;
  1061. if (args.hasArg(OPT_exclude_all_symbols))
  1062. return;
  1063. }
  1064.  
  1065. AutoExporter exporter;
  1066.  
  1067. for (auto *arg : args.filtered(OPT_wholearchive_file))
  1068. if (Optional<StringRef> path = doFindFile(arg->getValue()))
  1069. exporter.addWholeArchive(*path);
  1070.  
  1071. symtab->forEachSymbol([&](Symbol *s) {
  1072. auto *def = dyn_cast<Defined>(s);
  1073. if (!exporter.shouldExport(def))
  1074. return;
  1075.  
  1076. Export e;
  1077. e.name = def->getName();
  1078. e.sym = def;
  1079. if (Chunk *c = def->getChunk())
  1080. if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
  1081. e.data = true;
  1082. config->exports.push_back(e);
  1083. });
  1084. }
  1085.  
  1086. // lld has a feature to create a tar file containing all input files as well as
  1087. // all command line options, so that other people can run lld again with exactly
  1088. // the same inputs. This feature is accessible via /linkrepro and /reproduce.
  1089. //
  1090. // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
  1091. // name while /reproduce takes a full path. We have /linkrepro for compatibility
  1092. // with Microsoft link.exe.
  1093. Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
  1094. if (auto *arg = args.getLastArg(OPT_reproduce))
  1095. return std::string(arg->getValue());
  1096.  
  1097. if (auto *arg = args.getLastArg(OPT_linkrepro)) {
  1098. SmallString<64> path = StringRef(arg->getValue());
  1099. sys::path::append(path, "repro.tar");
  1100. return path.str().str();
  1101. }
  1102.  
  1103. return None;
  1104. }
  1105.  
  1106. void LinkerDriver::link(ArrayRef<const char *> argsArr) {
  1107. // Needed for LTO.
  1108. InitializeAllTargetInfos();
  1109. InitializeAllTargets();
  1110. InitializeAllTargetMCs();
  1111. InitializeAllAsmParsers();
  1112. InitializeAllAsmPrinters();
  1113. PassRegistry &Registry = *PassRegistry::getPassRegistry();
  1114. polly::initializePollyPasses(Registry);
  1115.  
  1116. // If the first command line argument is "/lib", link.exe acts like lib.exe.
  1117. // We call our own implementation of lib.exe that understands bitcode files.
  1118. if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) {
  1119. if (llvm::libDriverMain(argsArr.slice(1)) != 0)
  1120. fatal("lib failed");
  1121. return;
  1122. }
  1123.  
  1124. // Parse command line options.
  1125. ArgParser parser;
  1126. opt::InputArgList args = parser.parse(argsArr);
  1127.  
  1128. // Parse and evaluate -mllvm options.
  1129. std::vector<const char *> v;
  1130. v.push_back("lld-link (LLVM option parsing)");
  1131. for (auto *arg : args.filtered(OPT_mllvm))
  1132. v.push_back(arg->getValue());
  1133. cl::ParseCommandLineOptions(v.size(), v.data());
  1134.  
  1135. // Handle /errorlimit early, because error() depends on it.
  1136. if (auto *arg = args.getLastArg(OPT_errorlimit)) {
  1137. int n = 20;
  1138. StringRef s = arg->getValue();
  1139. if (s.getAsInteger(10, n))
  1140. error(arg->getSpelling() + " number expected, but got " + s);
  1141. errorHandler().errorLimit = n;
  1142. }
  1143.  
  1144. // Handle /help
  1145. if (args.hasArg(OPT_help)) {
  1146. printHelp(argsArr[0]);
  1147. return;
  1148. }
  1149.  
  1150. lld::threadsEnabled = args.hasFlag(OPT_threads, OPT_threads_no, true);
  1151.  
  1152. if (args.hasArg(OPT_show_timing))
  1153. config->showTiming = true;
  1154.  
  1155. config->showSummary = args.hasArg(OPT_summary);
  1156.  
  1157. ScopedTimer t(Timer::root());
  1158. // Handle --version, which is an lld extension. This option is a bit odd
  1159. // because it doesn't start with "/", but we deliberately chose "--" to
  1160. // avoid conflict with /version and for compatibility with clang-cl.
  1161. if (args.hasArg(OPT_dash_dash_version)) {
  1162. lld::outs() << getLLDVersion() << "\n";
  1163. return;
  1164. }
  1165.  
  1166. // Handle /lldmingw early, since it can potentially affect how other
  1167. // options are handled.
  1168. config->mingw = args.hasArg(OPT_lldmingw);
  1169.  
  1170. // Handle /linkrepro and /reproduce.
  1171. if (Optional<std::string> path = getReproduceFile(args)) {
  1172. Expected<std::unique_ptr<TarWriter>> errOrWriter =
  1173. TarWriter::create(*path, sys::path::stem(*path));
  1174.  
  1175. if (errOrWriter) {
  1176. tar = std::move(*errOrWriter);
  1177. } else {
  1178. error("/linkrepro: failed to open " + *path + ": " +
  1179. toString(errOrWriter.takeError()));
  1180. }
  1181. }
  1182.  
  1183. if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
  1184. if (args.hasArg(OPT_deffile))
  1185. config->noEntry = true;
  1186. else
  1187. fatal("no input files");
  1188. }
  1189.  
  1190. // Construct search path list.
  1191. searchPaths.push_back("");
  1192. for (auto *arg : args.filtered(OPT_libpath))
  1193. searchPaths.push_back(arg->getValue());
  1194. if (!args.hasArg(OPT_lldignoreenv))
  1195. addLibSearchPaths();
  1196.  
  1197. // Handle /ignore
  1198. for (auto *arg : args.filtered(OPT_ignore)) {
  1199. SmallVector<StringRef, 8> vec;
  1200. StringRef(arg->getValue()).split(vec, ',');
  1201. for (StringRef s : vec) {
  1202. if (s == "4037")
  1203. config->warnMissingOrderSymbol = false;
  1204. else if (s == "4099")
  1205. config->warnDebugInfoUnusable = false;
  1206. else if (s == "4217")
  1207. config->warnLocallyDefinedImported = false;
  1208. else if (s == "longsections")
  1209. config->warnLongSectionNames = false;
  1210. // Other warning numbers are ignored.
  1211. }
  1212. }
  1213.  
  1214. // Handle /out
  1215. if (auto *arg = args.getLastArg(OPT_out))
  1216. config->outputFile = arg->getValue();
  1217.  
  1218. // Handle /verbose
  1219. if (args.hasArg(OPT_verbose))
  1220. config->verbose = true;
  1221. errorHandler().verbose = config->verbose;
  1222.  
  1223. // Handle /force or /force:unresolved
  1224. if (args.hasArg(OPT_force, OPT_force_unresolved))
  1225. config->forceUnresolved = true;
  1226.  
  1227. // Handle /force or /force:multiple
  1228. if (args.hasArg(OPT_force, OPT_force_multiple))
  1229. config->forceMultiple = true;
  1230.  
  1231. // Handle /force or /force:multipleres
  1232. if (args.hasArg(OPT_force, OPT_force_multipleres))
  1233. config->forceMultipleRes = true;
  1234.  
  1235. // Handle /debug
  1236. DebugKind debug = parseDebugKind(args);
  1237. if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
  1238. debug == DebugKind::GHash) {
  1239. config->debug = true;
  1240. config->incremental = true;
  1241. }
  1242.  
  1243. // Handle /demangle
  1244. config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
  1245.  
  1246. // Handle /debugtype
  1247. config->debugTypes = parseDebugTypes(args);
  1248.  
  1249. // Handle /driver[:uponly|:wdm].
  1250. config->driverUponly = args.hasArg(OPT_driver_uponly) ||
  1251. args.hasArg(OPT_driver_uponly_wdm) ||
  1252. args.hasArg(OPT_driver_wdm_uponly);
  1253. config->driverWdm = args.hasArg(OPT_driver_wdm) ||
  1254. args.hasArg(OPT_driver_uponly_wdm) ||
  1255. args.hasArg(OPT_driver_wdm_uponly);
  1256. config->driver =
  1257. config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
  1258.  
  1259. // Handle /pdb
  1260. bool shouldCreatePDB =
  1261. (debug == DebugKind::Full || debug == DebugKind::GHash);
  1262. if (shouldCreatePDB) {
  1263. if (auto *arg = args.getLastArg(OPT_pdb))
  1264. config->pdbPath = arg->getValue();
  1265. if (auto *arg = args.getLastArg(OPT_pdbaltpath))
  1266. config->pdbAltPath = arg->getValue();
  1267. if (args.hasArg(OPT_natvis))
  1268. config->natvisFiles = args.getAllArgValues(OPT_natvis);
  1269.  
  1270. if (auto *arg = args.getLastArg(OPT_pdb_source_path))
  1271. config->pdbSourcePath = arg->getValue();
  1272. }
  1273.  
  1274. // Handle /noentry
  1275. if (args.hasArg(OPT_noentry)) {
  1276. if (args.hasArg(OPT_dll))
  1277. config->noEntry = true;
  1278. else
  1279. error("/noentry must be specified with /dll");
  1280. }
  1281.  
  1282. // Handle /dll
  1283. if (args.hasArg(OPT_dll)) {
  1284. config->dll = true;
  1285. config->manifestID = 2;
  1286. }
  1287.  
  1288. // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
  1289. // because we need to explicitly check whether that option or its inverse was
  1290. // present in the argument list in order to handle /fixed.
  1291. auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
  1292. if (dynamicBaseArg &&
  1293. dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
  1294. config->dynamicBase = false;
  1295.  
  1296. // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
  1297. // default setting for any other project type.", but link.exe defaults to
  1298. // /FIXED:NO for exe outputs as well. Match behavior, not docs.
  1299. bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
  1300. if (fixed) {
  1301. if (dynamicBaseArg &&
  1302. dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
  1303. error("/fixed must not be specified with /dynamicbase");
  1304. } else {
  1305. config->relocatable = false;
  1306. config->dynamicBase = false;
  1307. }
  1308. }
  1309.  
  1310. // Handle /appcontainer
  1311. config->appContainer =
  1312. args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
  1313.  
  1314. // Handle /machine
  1315. if (auto *arg = args.getLastArg(OPT_machine)) {
  1316. config->machine = getMachineType(arg->getValue());
  1317. if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
  1318. fatal(Twine("unknown /machine argument: ") + arg->getValue());
  1319. }
  1320.  
  1321. // Handle /nodefaultlib:<filename>
  1322. for (auto *arg : args.filtered(OPT_nodefaultlib))
  1323. config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
  1324.  
  1325. // Handle /nodefaultlib
  1326. if (args.hasArg(OPT_nodefaultlib_all))
  1327. config->noDefaultLibAll = true;
  1328.  
  1329. // Handle /base
  1330. if (auto *arg = args.getLastArg(OPT_base))
  1331. parseNumbers(arg->getValue(), &config->imageBase);
  1332.  
  1333. // Handle /filealign
  1334. if (auto *arg = args.getLastArg(OPT_filealign)) {
  1335. parseNumbers(arg->getValue(), &config->fileAlign);
  1336. if (!isPowerOf2_64(config->fileAlign))
  1337. error("/filealign: not a power of two: " + Twine(config->fileAlign));
  1338. }
  1339.  
  1340. // Handle /stack
  1341. if (auto *arg = args.getLastArg(OPT_stack))
  1342. parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
  1343.  
  1344. // Handle /guard:cf
  1345. if (auto *arg = args.getLastArg(OPT_guard))
  1346. parseGuard(arg->getValue());
  1347.  
  1348. // Handle /heap
  1349. if (auto *arg = args.getLastArg(OPT_heap))
  1350. parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
  1351.  
  1352. // Handle /version
  1353. if (auto *arg = args.getLastArg(OPT_version))
  1354. parseVersion(arg->getValue(), &config->majorImageVersion,
  1355. &config->minorImageVersion);
  1356.  
  1357. // Handle /subsystem
  1358. if (auto *arg = args.getLastArg(OPT_subsystem))
  1359. parseSubsystem(arg->getValue(), &config->subsystem, &config->majorOSVersion,
  1360. &config->minorOSVersion);
  1361.  
  1362. // Handle /timestamp
  1363. if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
  1364. if (arg->getOption().getID() == OPT_repro) {
  1365. config->timestamp = 0;
  1366. config->repro = true;
  1367. } else {
  1368. config->repro = false;
  1369. StringRef value(arg->getValue());
  1370. if (value.getAsInteger(0, config->timestamp))
  1371. fatal(Twine("invalid timestamp: ") + value +
  1372. ". Expected 32-bit integer");
  1373. }
  1374. } else {
  1375. config->repro = false;
  1376. config->timestamp = time(nullptr);
  1377. }
  1378.  
  1379. // Handle /alternatename
  1380. for (auto *arg : args.filtered(OPT_alternatename))
  1381. parseAlternateName(arg->getValue());
  1382.  
  1383. // Handle /include
  1384. for (auto *arg : args.filtered(OPT_incl))
  1385. addUndefined(arg->getValue());
  1386.  
  1387. // Handle /implib
  1388. if (auto *arg = args.getLastArg(OPT_implib))
  1389. config->implib = arg->getValue();
  1390.  
  1391. // Handle /opt.
  1392. bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
  1393. unsigned icfLevel =
  1394. args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
  1395. unsigned tailMerge = 1;
  1396. for (auto *arg : args.filtered(OPT_opt)) {
  1397. std::string str = StringRef(arg->getValue()).lower();
  1398. SmallVector<StringRef, 1> vec;
  1399. StringRef(str).split(vec, ',');
  1400. for (StringRef s : vec) {
  1401. if (s == "ref") {
  1402. doGC = true;
  1403. } else if (s == "noref") {
  1404. doGC = false;
  1405. } else if (s == "icf" || s.startswith("icf=")) {
  1406. icfLevel = 2;
  1407. } else if (s == "noicf") {
  1408. icfLevel = 0;
  1409. } else if (s == "lldtailmerge") {
  1410. tailMerge = 2;
  1411. } else if (s == "nolldtailmerge") {
  1412. tailMerge = 0;
  1413. } else if (s.startswith("lldlto=")) {
  1414. StringRef optLevel = s.substr(7);
  1415. if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
  1416. error("/opt:lldlto: invalid optimization level: " + optLevel);
  1417. } else if (s.startswith("lldltojobs=")) {
  1418. StringRef jobs = s.substr(11);
  1419. if (jobs.getAsInteger(10, config->thinLTOJobs) ||
  1420. config->thinLTOJobs == 0)
  1421. error("/opt:lldltojobs: invalid job count: " + jobs);
  1422. } else if (s.startswith("lldltopartitions=")) {
  1423. StringRef n = s.substr(17);
  1424. if (n.getAsInteger(10, config->ltoPartitions) ||
  1425. config->ltoPartitions == 0)
  1426. error("/opt:lldltopartitions: invalid partition count: " + n);
  1427. } else if (s != "lbr" && s != "nolbr")
  1428. error("/opt: unknown option: " + s);
  1429. }
  1430. }
  1431.  
  1432. // Limited ICF is enabled if GC is enabled and ICF was never mentioned
  1433. // explicitly.
  1434. // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
  1435. // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
  1436. // comdat readonly data.
  1437. if (icfLevel == 1 && !doGC)
  1438. icfLevel = 0;
  1439. config->doGC = doGC;
  1440. config->doICF = icfLevel > 0;
  1441. config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2;
  1442.  
  1443. // Handle /lldsavetemps
  1444. if (args.hasArg(OPT_lldsavetemps))
  1445. config->saveTemps = true;
  1446.  
  1447. // Handle /kill-at
  1448. if (args.hasArg(OPT_kill_at))
  1449. config->killAt = true;
  1450.  
  1451. // Handle /lldltocache
  1452. if (auto *arg = args.getLastArg(OPT_lldltocache))
  1453. config->ltoCache = arg->getValue();
  1454.  
  1455. // Handle /lldsavecachepolicy
  1456. if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
  1457. config->ltoCachePolicy = CHECK(
  1458. parseCachePruningPolicy(arg->getValue()),
  1459. Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
  1460.  
  1461. // Handle /failifmismatch
  1462. for (auto *arg : args.filtered(OPT_failifmismatch))
  1463. checkFailIfMismatch(arg->getValue(), nullptr);
  1464.  
  1465. // Handle /merge
  1466. for (auto *arg : args.filtered(OPT_merge))
  1467. parseMerge(arg->getValue());
  1468.  
  1469. // Add default section merging rules after user rules. User rules take
  1470. // precedence, but we will emit a warning if there is a conflict.
  1471. parseMerge(".idata=.rdata");
  1472. parseMerge(".didat=.rdata");
  1473. parseMerge(".edata=.rdata");
  1474. parseMerge(".xdata=.rdata");
  1475. parseMerge(".bss=.data");
  1476.  
  1477. if (config->mingw) {
  1478. parseMerge(".ctors=.rdata");
  1479. parseMerge(".dtors=.rdata");
  1480. parseMerge(".CRT=.rdata");
  1481. }
  1482.  
  1483. // Handle /section
  1484. for (auto *arg : args.filtered(OPT_section))
  1485. parseSection(arg->getValue());
  1486.  
  1487. // Handle /align
  1488. if (auto *arg = args.getLastArg(OPT_align)) {
  1489. parseNumbers(arg->getValue(), &config->align);
  1490. if (!isPowerOf2_64(config->align))
  1491. error("/align: not a power of two: " + StringRef(arg->getValue()));
  1492. if (!args.hasArg(OPT_driver))
  1493. warn("/align specified without /driver; image may not run");
  1494. }
  1495.  
  1496. // Handle /aligncomm
  1497. for (auto *arg : args.filtered(OPT_aligncomm))
  1498. parseAligncomm(arg->getValue());
  1499.  
  1500. // Handle /manifestdependency. This enables /manifest unless /manifest:no is
  1501. // also passed.
  1502. if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
  1503. config->manifestDependency = arg->getValue();
  1504. config->manifest = Configuration::SideBySide;
  1505. }
  1506.  
  1507. // Handle /manifest and /manifest:
  1508. if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
  1509. if (arg->getOption().getID() == OPT_manifest)
  1510. config->manifest = Configuration::SideBySide;
  1511. else
  1512. parseManifest(arg->getValue());
  1513. }
  1514.  
  1515. // Handle /manifestuac
  1516. if (auto *arg = args.getLastArg(OPT_manifestuac))
  1517. parseManifestUAC(arg->getValue());
  1518.  
  1519. // Handle /manifestfile
  1520. if (auto *arg = args.getLastArg(OPT_manifestfile))
  1521. config->manifestFile = arg->getValue();
  1522.  
  1523. // Handle /manifestinput
  1524. for (auto *arg : args.filtered(OPT_manifestinput))
  1525. config->manifestInput.push_back(arg->getValue());
  1526.  
  1527. if (!config->manifestInput.empty() &&
  1528. config->manifest != Configuration::Embed) {
  1529. fatal("/manifestinput: requires /manifest:embed");
  1530. }
  1531.  
  1532. config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
  1533. config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
  1534. args.hasArg(OPT_thinlto_index_only_arg);
  1535. config->thinLTOIndexOnlyArg =
  1536. args.getLastArgValue(OPT_thinlto_index_only_arg);
  1537. config->thinLTOPrefixReplace =
  1538. getOldNewOptions(args, OPT_thinlto_prefix_replace);
  1539. config->thinLTOObjectSuffixReplace =
  1540. getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
  1541. config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
  1542. // Handle miscellaneous boolean flags.
  1543. config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
  1544. config->allowIsolation =
  1545. args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
  1546. config->incremental =
  1547. args.hasFlag(OPT_incremental, OPT_incremental_no,
  1548. !config->doGC && !config->doICF && !args.hasArg(OPT_order) &&
  1549. !args.hasArg(OPT_profile));
  1550. config->integrityCheck =
  1551. args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
  1552. config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
  1553. for (auto *arg : args.filtered(OPT_swaprun))
  1554. parseSwaprun(arg->getValue());
  1555. config->terminalServerAware =
  1556. !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
  1557. config->debugDwarf = debug == DebugKind::Dwarf;
  1558. config->debugGHashes = debug == DebugKind::GHash;
  1559. config->debugSymtab = debug == DebugKind::Symtab;
  1560.  
  1561. // Don't warn about long section names, such as .debug_info, for mingw or when
  1562. // -debug:dwarf is requested.
  1563. if (config->mingw || config->debugDwarf)
  1564. config->warnLongSectionNames = false;
  1565.  
  1566. config->mapFile = getMapFile(args);
  1567.  
  1568. if (config->incremental && args.hasArg(OPT_profile)) {
  1569. warn("ignoring '/incremental' due to '/profile' specification");
  1570. config->incremental = false;
  1571. }
  1572.  
  1573. if (config->incremental && args.hasArg(OPT_order)) {
  1574. warn("ignoring '/incremental' due to '/order' specification");
  1575. config->incremental = false;
  1576. }
  1577.  
  1578. if (config->incremental && config->doGC) {
  1579. warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
  1580. "disable");
  1581. config->incremental = false;
  1582. }
  1583.  
  1584. if (config->incremental && config->doICF) {
  1585. warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
  1586. "disable");
  1587. config->incremental = false;
  1588. }
  1589.  
  1590. if (errorCount())
  1591. return;
  1592.  
  1593. std::set<sys::fs::UniqueID> wholeArchives;
  1594. for (auto *arg : args.filtered(OPT_wholearchive_file))
  1595. if (Optional<StringRef> path = doFindFile(arg->getValue()))
  1596. if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
  1597. wholeArchives.insert(*id);
  1598.  
  1599. // A predicate returning true if a given path is an argument for
  1600. // /wholearchive:, or /wholearchive is enabled globally.
  1601. // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
  1602. // needs to be handled as "/wholearchive:foo.obj foo.obj".
  1603. auto isWholeArchive = [&](StringRef path) -> bool {
  1604. if (args.hasArg(OPT_wholearchive_flag))
  1605. return true;
  1606. if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
  1607. return wholeArchives.count(*id);
  1608. return false;
  1609. };
  1610.  
  1611. // Create a list of input files. These can be given as OPT_INPUT options
  1612. // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
  1613. // and OPT_end_lib.
  1614. bool inLib = false;
  1615. for (auto *arg : args) {
  1616. switch (arg->getOption().getID()) {
  1617. case OPT_end_lib:
  1618. if (!inLib)
  1619. error("stray " + arg->getSpelling());
  1620. inLib = false;
  1621. break;
  1622. case OPT_start_lib:
  1623. if (inLib)
  1624. error("nested " + arg->getSpelling());
  1625. inLib = true;
  1626. break;
  1627. case OPT_wholearchive_file:
  1628. if (Optional<StringRef> path = findFile(arg->getValue()))
  1629. enqueuePath(*path, true, inLib);
  1630. break;
  1631. case OPT_INPUT:
  1632. if (Optional<StringRef> path = findFile(arg->getValue()))
  1633. enqueuePath(*path, isWholeArchive(*path), inLib);
  1634. break;
  1635. default:
  1636. // Ignore other options.
  1637. break;
  1638. }
  1639. }
  1640.  
  1641. // Process files specified as /defaultlib. These should be enequeued after
  1642. // other files, which is why they are in a separate loop.
  1643. for (auto *arg : args.filtered(OPT_defaultlib))
  1644. if (Optional<StringRef> path = findLib(arg->getValue()))
  1645. enqueuePath(*path, false, false);
  1646.  
  1647. // Windows specific -- Create a resource file containing a manifest file.
  1648. if (config->manifest == Configuration::Embed)
  1649. addBuffer(createManifestRes(), false, false);
  1650.  
  1651. // Read all input files given via the command line.
  1652. run();
  1653.  
  1654. if (errorCount())
  1655. return;
  1656.  
  1657. // We should have inferred a machine type by now from the input files, but if
  1658. // not we assume x64.
  1659. if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
  1660. warn("/machine is not specified. x64 is assumed");
  1661. config->machine = AMD64;
  1662. }
  1663. config->wordsize = config->is64() ? 8 : 4;
  1664.  
  1665. // Handle /safeseh, x86 only, on by default, except for mingw.
  1666. if (config->machine == I386 &&
  1667. args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw))
  1668. config->safeSEH = true;
  1669.  
  1670. // Handle /functionpadmin
  1671. for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
  1672. parseFunctionPadMin(arg, config->machine);
  1673.  
  1674. if (tar)
  1675. tar->append("response.txt",
  1676. createResponseFile(args, filePaths,
  1677. ArrayRef<StringRef>(searchPaths).slice(1)));
  1678.  
  1679. // Handle /largeaddressaware
  1680. config->largeAddressAware = args.hasFlag(
  1681. OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
  1682.  
  1683. // Handle /highentropyva
  1684. config->highEntropyVA =
  1685. config->is64() &&
  1686. args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
  1687.  
  1688. if (!config->dynamicBase &&
  1689. (config->machine == ARMNT || config->machine == ARM64))
  1690. error("/dynamicbase:no is not compatible with " +
  1691. machineToStr(config->machine));
  1692.  
  1693. // Handle /export
  1694. for (auto *arg : args.filtered(OPT_export)) {
  1695. Export e = parseExport(arg->getValue());
  1696. if (config->machine == I386) {
  1697. if (!isDecorated(e.name))
  1698. e.name = saver.save("_" + e.name);
  1699. if (!e.extName.empty() && !isDecorated(e.extName))
  1700. e.extName = saver.save("_" + e.extName);
  1701. }
  1702. config->exports.push_back(e);
  1703. }
  1704.  
  1705. // Handle /def
  1706. if (auto *arg = args.getLastArg(OPT_deffile)) {
  1707. // parseModuleDefs mutates Config object.
  1708. parseModuleDefs(arg->getValue());
  1709. }
  1710.  
  1711. // Handle generation of import library from a def file.
  1712. if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
  1713. fixupExports();
  1714. createImportLibrary(/*asLib=*/true);
  1715. return;
  1716. }
  1717.  
  1718. // Windows specific -- if no /subsystem is given, we need to infer
  1719. // that from entry point name. Must happen before /entry handling,
  1720. // and after the early return when just writing an import library.
  1721. if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
  1722. config->subsystem = inferSubsystem();
  1723. if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
  1724. fatal("subsystem must be defined");
  1725. }
  1726.  
  1727. // Handle /entry and /dll
  1728. if (auto *arg = args.getLastArg(OPT_entry)) {
  1729. config->entry = addUndefined(mangle(arg->getValue()));
  1730. } else if (!config->entry && !config->noEntry) {
  1731. if (args.hasArg(OPT_dll)) {
  1732. StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
  1733. : "_DllMainCRTStartup";
  1734. config->entry = addUndefined(s);
  1735. } else if (config->driverWdm) {
  1736. // /driver:wdm implies /entry:_NtProcessStartup
  1737. config->entry = addUndefined(mangle("_NtProcessStartup"));
  1738. } else {
  1739. // Windows specific -- If entry point name is not given, we need to
  1740. // infer that from user-defined entry name.
  1741. StringRef s = findDefaultEntry();
  1742. if (s.empty())
  1743. fatal("entry point must be defined");
  1744. config->entry = addUndefined(s);
  1745. log("Entry name inferred: " + s);
  1746. }
  1747. }
  1748.  
  1749. // Handle /delayload
  1750. for (auto *arg : args.filtered(OPT_delayload)) {
  1751. config->delayLoads.insert(StringRef(arg->getValue()).lower());
  1752. if (config->machine == I386) {
  1753. config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
  1754. } else {
  1755. config->delayLoadHelper = addUndefined("__delayLoadHelper2");
  1756. }
  1757. }
  1758.  
  1759. // Set default image name if neither /out or /def set it.
  1760. if (config->outputFile.empty()) {
  1761. config->outputFile = getOutputPath(
  1762. (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
  1763. }
  1764.  
  1765. // Fail early if an output file is not writable.
  1766. if (auto e = tryCreateFile(config->outputFile)) {
  1767. error("cannot open output file " + config->outputFile + ": " + e.message());
  1768. return;
  1769. }
  1770.  
  1771. if (shouldCreatePDB) {
  1772. // Put the PDB next to the image if no /pdb flag was passed.
  1773. if (config->pdbPath.empty()) {
  1774. config->pdbPath = config->outputFile;
  1775. sys::path::replace_extension(config->pdbPath, ".pdb");
  1776. }
  1777.  
  1778. // The embedded PDB path should be the absolute path to the PDB if no
  1779. // /pdbaltpath flag was passed.
  1780. if (config->pdbAltPath.empty()) {
  1781. config->pdbAltPath = config->pdbPath;
  1782.  
  1783. // It's important to make the path absolute and remove dots. This path
  1784. // will eventually be written into the PE header, and certain Microsoft
  1785. // tools won't work correctly if these assumptions are not held.
  1786. sys::fs::make_absolute(config->pdbAltPath);
  1787. sys::path::remove_dots(config->pdbAltPath);
  1788. } else {
  1789. // Don't do this earlier, so that Config->OutputFile is ready.
  1790. parsePDBAltPath(config->pdbAltPath);
  1791. }
  1792. }
  1793.  
  1794. // Set default image base if /base is not given.
  1795. if (config->imageBase == uint64_t(-1))
  1796. config->imageBase = getDefaultImageBase();
  1797.  
  1798. symtab->addSynthetic(mangle("__ImageBase"), nullptr);
  1799. if (config->machine == I386) {
  1800. symtab->addAbsolute("___safe_se_handler_table", 0);
  1801. symtab->addAbsolute("___safe_se_handler_count", 0);
  1802. }
  1803.  
  1804. symtab->addAbsolute(mangle("__guard_fids_count"), 0);
  1805. symtab->addAbsolute(mangle("__guard_fids_table"), 0);
  1806. symtab->addAbsolute(mangle("__guard_flags"), 0);
  1807. symtab->addAbsolute(mangle("__guard_iat_count"), 0);
  1808. symtab->addAbsolute(mangle("__guard_iat_table"), 0);
  1809. symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
  1810. symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
  1811. // Needed for MSVC 2017 15.5 CRT.
  1812. symtab->addAbsolute(mangle("__enclave_config"), 0);
  1813.  
  1814. if (config->mingw) {
  1815. symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
  1816. symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
  1817. symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
  1818. symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
  1819. }
  1820.  
  1821. // This code may add new undefined symbols to the link, which may enqueue more
  1822. // symbol resolution tasks, so we need to continue executing tasks until we
  1823. // converge.
  1824. do {
  1825. // Windows specific -- if entry point is not found,
  1826. // search for its mangled names.
  1827. if (config->entry)
  1828. mangleMaybe(config->entry);
  1829.  
  1830. // Windows specific -- Make sure we resolve all dllexported symbols.
  1831. for (Export &e : config->exports) {
  1832. if (!e.forwardTo.empty())
  1833. continue;
  1834. e.sym = addUndefined(e.name);
  1835. if (!e.directives)
  1836. e.symbolName = mangleMaybe(e.sym);
  1837. }
  1838.  
  1839. // Add weak aliases. Weak aliases is a mechanism to give remaining
  1840. // undefined symbols final chance to be resolved successfully.
  1841. for (auto pair : config->alternateNames) {
  1842. StringRef from = pair.first;
  1843. StringRef to = pair.second;
  1844. Symbol *sym = symtab->find(from);
  1845. if (!sym)
  1846. continue;
  1847. if (auto *u = dyn_cast<Undefined>(sym))
  1848. if (!u->weakAlias)
  1849. u->weakAlias = symtab->addUndefined(to);
  1850. }
  1851.  
  1852. // If any inputs are bitcode files, the LTO code generator may create
  1853. // references to library functions that are not explicit in the bitcode
  1854. // file's symbol table. If any of those library functions are defined in a
  1855. // bitcode file in an archive member, we need to arrange to use LTO to
  1856. // compile those archive members by adding them to the link beforehand.
  1857. if (!BitcodeFile::instances.empty())
  1858. for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
  1859. symtab->addLibcall(s);
  1860.  
  1861. // Windows specific -- if __load_config_used can be resolved, resolve it.
  1862. if (symtab->findUnderscore("_load_config_used"))
  1863. addUndefined(mangle("_load_config_used"));
  1864. } while (run());
  1865.  
  1866. if (args.hasArg(OPT_include_optional)) {
  1867. // Handle /includeoptional
  1868. for (auto *arg : args.filtered(OPT_include_optional))
  1869. if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue())))
  1870. addUndefined(arg->getValue());
  1871. while (run());
  1872. }
  1873.  
  1874. if (config->mingw) {
  1875. // Load any further object files that might be needed for doing automatic
  1876. // imports.
  1877. //
  1878. // For cases with no automatically imported symbols, this iterates once
  1879. // over the symbol table and doesn't do anything.
  1880. //
  1881. // For the normal case with a few automatically imported symbols, this
  1882. // should only need to be run once, since each new object file imported
  1883. // is an import library and wouldn't add any new undefined references,
  1884. // but there's nothing stopping the __imp_ symbols from coming from a
  1885. // normal object file as well (although that won't be used for the
  1886. // actual autoimport later on). If this pass adds new undefined references,
  1887. // we won't iterate further to resolve them.
  1888. symtab->loadMinGWAutomaticImports();
  1889. run();
  1890. }
  1891.  
  1892. // At this point, we should not have any symbols that cannot be resolved.
  1893. // If we are going to do codegen for link-time optimization, check for
  1894. // unresolvable symbols first, so we don't spend time generating code that
  1895. // will fail to link anyway.
  1896. if (!BitcodeFile::instances.empty() && !config->forceUnresolved)
  1897. symtab->reportUnresolvable();
  1898. if (errorCount())
  1899. return;
  1900.  
  1901. // Do LTO by compiling bitcode input files to a set of native COFF files then
  1902. // link those files (unless -thinlto-index-only was given, in which case we
  1903. // resolve symbols and write indices, but don't generate native code or link).
  1904. symtab->addCombinedLTOObjects();
  1905.  
  1906. // If -thinlto-index-only is given, we should create only "index
  1907. // files" and not object files. Index file creation is already done
  1908. // in addCombinedLTOObject, so we are done if that's the case.
  1909. if (config->thinLTOIndexOnly)
  1910. return;
  1911.  
  1912. // If we generated native object files from bitcode files, this resolves
  1913. // references to the symbols we use from them.
  1914. run();
  1915.  
  1916. // Resolve remaining undefined symbols and warn about imported locals.
  1917. symtab->resolveRemainingUndefines();
  1918. if (errorCount())
  1919. return;
  1920.  
  1921. config->hadExplicitExports = !config->exports.empty();
  1922. if (config->mingw) {
  1923. // In MinGW, all symbols are automatically exported if no symbols
  1924. // are chosen to be exported.
  1925. maybeExportMinGWSymbols(args);
  1926.  
  1927. // Make sure the crtend.o object is the last object file. This object
  1928. // file can contain terminating section chunks that need to be placed
  1929. // last. GNU ld processes files and static libraries explicitly in the
  1930. // order provided on the command line, while lld will pull in needed
  1931. // files from static libraries only after the last object file on the
  1932. // command line.
  1933. for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
  1934. i != e; i++) {
  1935. ObjFile *file = *i;
  1936. if (isCrtend(file->getName())) {
  1937. ObjFile::instances.erase(i);
  1938. ObjFile::instances.push_back(file);
  1939. break;
  1940. }
  1941. }
  1942. }
  1943.  
  1944. // Windows specific -- when we are creating a .dll file, we also
  1945. // need to create a .lib file. In MinGW mode, we only do that when the
  1946. // -implib option is given explicitly, for compatibility with GNU ld.
  1947. if (!config->exports.empty() || config->dll) {
  1948. fixupExports();
  1949. if (!config->mingw || !config->implib.empty())
  1950. createImportLibrary(/*asLib=*/false);
  1951. assignExportOrdinals();
  1952. }
  1953.  
  1954. // Handle /output-def (MinGW specific).
  1955. if (auto *arg = args.getLastArg(OPT_output_def))
  1956. writeDefFile(arg->getValue());
  1957.  
  1958. // Set extra alignment for .comm symbols
  1959. for (auto pair : config->alignComm) {
  1960. StringRef name = pair.first;
  1961. uint32_t alignment = pair.second;
  1962.  
  1963. Symbol *sym = symtab->find(name);
  1964. if (!sym) {
  1965. warn("/aligncomm symbol " + name + " not found");
  1966. continue;
  1967. }
  1968.  
  1969. // If the symbol isn't common, it must have been replaced with a regular
  1970. // symbol, which will carry its own alignment.
  1971. auto *dc = dyn_cast<DefinedCommon>(sym);
  1972. if (!dc)
  1973. continue;
  1974.  
  1975. CommonChunk *c = dc->getChunk();
  1976. c->setAlignment(std::max(c->getAlignment(), alignment));
  1977. }
  1978.  
  1979. // Windows specific -- Create a side-by-side manifest file.
  1980. if (config->manifest == Configuration::SideBySide)
  1981. createSideBySideManifest();
  1982.  
  1983. // Handle /order. We want to do this at this moment because we
  1984. // need a complete list of comdat sections to warn on nonexistent
  1985. // functions.
  1986. if (auto *arg = args.getLastArg(OPT_order))
  1987. parseOrderFile(arg->getValue());
  1988.  
  1989. // Identify unreferenced COMDAT sections.
  1990. if (config->doGC)
  1991. markLive(symtab->getChunks());
  1992.  
  1993. // Needs to happen after the last call to addFile().
  1994. convertResources();
  1995.  
  1996. // Identify identical COMDAT sections to merge them.
  1997. if (config->doICF) {
  1998. findKeepUniqueSections();
  1999. doICF(symtab->getChunks());
  2000. }
  2001.  
  2002. // Write the result.
  2003. writeResult();
  2004.  
  2005. // Stop early so we can print the results.
  2006. Timer::root().stop();
  2007. if (config->showTiming)
  2008. Timer::root().print();
  2009. }
  2010.  
  2011. } // namespace coff
  2012. } // namespace lld
Add Comment
Please, Sign In to add comment