Driver.cpp 66 KB

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