llvm-jitlink.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007
  1. //===- llvm-jitlink.cpp -- Command line interface/tester for llvm-jitlink -===//
  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. // This utility provides a simple command line interface to the llvm jitlink
  10. // library, which makes relocatable object files executable in memory. Its
  11. // primary function is as a testing utility for the jitlink library.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm-jitlink.h"
  15. #include "llvm/BinaryFormat/Magic.h"
  16. #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
  17. #include "llvm/ExecutionEngine/Orc/DebuggerSupportPlugin.h"
  18. #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h"
  19. #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h"
  20. #include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
  21. #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
  22. #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
  23. #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
  24. #include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
  25. #include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h"
  26. #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
  27. #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
  28. #include "llvm/MC/MCAsmInfo.h"
  29. #include "llvm/MC/MCContext.h"
  30. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  31. #include "llvm/MC/MCInstPrinter.h"
  32. #include "llvm/MC/MCInstrAnalysis.h"
  33. #include "llvm/MC/MCInstrInfo.h"
  34. #include "llvm/MC/MCRegisterInfo.h"
  35. #include "llvm/MC/MCSubtargetInfo.h"
  36. #include "llvm/MC/MCTargetOptions.h"
  37. #include "llvm/MC/TargetRegistry.h"
  38. #include "llvm/Object/COFF.h"
  39. #include "llvm/Object/MachO.h"
  40. #include "llvm/Object/ObjectFile.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/InitLLVM.h"
  44. #include "llvm/Support/MemoryBuffer.h"
  45. #include "llvm/Support/Path.h"
  46. #include "llvm/Support/Process.h"
  47. #include "llvm/Support/TargetSelect.h"
  48. #include "llvm/Support/Timer.h"
  49. #include <cstring>
  50. #include <list>
  51. #include <string>
  52. #ifdef LLVM_ON_UNIX
  53. #include <netdb.h>
  54. #include <netinet/in.h>
  55. #include <sys/socket.h>
  56. #include <unistd.h>
  57. #endif // LLVM_ON_UNIX
  58. #define DEBUG_TYPE "llvm_jitlink"
  59. using namespace llvm;
  60. using namespace llvm::jitlink;
  61. using namespace llvm::orc;
  62. static cl::OptionCategory JITLinkCategory("JITLink Options");
  63. static cl::list<std::string> InputFiles(cl::Positional, cl::OneOrMore,
  64. cl::desc("input files"),
  65. cl::cat(JITLinkCategory));
  66. static cl::list<std::string>
  67. LibrarySearchPaths("L",
  68. cl::desc("Add dir to the list of library search paths"),
  69. cl::Prefix, cl::cat(JITLinkCategory));
  70. static cl::list<std::string>
  71. Libraries("l",
  72. cl::desc("Link against library X in the library search paths"),
  73. cl::Prefix, cl::cat(JITLinkCategory));
  74. static cl::list<std::string>
  75. LibrariesHidden("hidden-l",
  76. cl::desc("Link against library X in the library search "
  77. "paths with hidden visibility"),
  78. cl::Prefix, cl::cat(JITLinkCategory));
  79. static cl::list<std::string>
  80. LoadHidden("load_hidden",
  81. cl::desc("Link against library X with hidden visibility"),
  82. cl::cat(JITLinkCategory));
  83. static cl::opt<bool> NoExec("noexec", cl::desc("Do not execute loaded code"),
  84. cl::init(false), cl::cat(JITLinkCategory));
  85. static cl::list<std::string>
  86. CheckFiles("check", cl::desc("File containing verifier checks"),
  87. cl::ZeroOrMore, cl::cat(JITLinkCategory));
  88. static cl::opt<std::string>
  89. CheckName("check-name", cl::desc("Name of checks to match against"),
  90. cl::init("jitlink-check"), cl::cat(JITLinkCategory));
  91. static cl::opt<std::string>
  92. EntryPointName("entry", cl::desc("Symbol to call as main entry point"),
  93. cl::init(""), cl::cat(JITLinkCategory));
  94. static cl::list<std::string> JITDylibs(
  95. "jd",
  96. cl::desc("Specifies the JITDylib to be used for any subsequent "
  97. "input file, -L<seacrh-path>, and -l<library> arguments"),
  98. cl::cat(JITLinkCategory));
  99. static cl::list<std::string>
  100. Dylibs("preload",
  101. cl::desc("Pre-load dynamic libraries (e.g. language runtimes "
  102. "required by the ORC runtime)"),
  103. cl::ZeroOrMore, cl::cat(JITLinkCategory));
  104. static cl::list<std::string> InputArgv("args", cl::Positional,
  105. cl::desc("<program arguments>..."),
  106. cl::ZeroOrMore, cl::PositionalEatsArgs,
  107. cl::cat(JITLinkCategory));
  108. static cl::opt<bool>
  109. DebuggerSupport("debugger-support",
  110. cl::desc("Enable debugger suppport (default = !-noexec)"),
  111. cl::init(true), cl::Hidden, cl::cat(JITLinkCategory));
  112. static cl::opt<bool>
  113. NoProcessSymbols("no-process-syms",
  114. cl::desc("Do not resolve to llvm-jitlink process symbols"),
  115. cl::init(false), cl::cat(JITLinkCategory));
  116. static cl::list<std::string> AbsoluteDefs(
  117. "define-abs",
  118. cl::desc("Inject absolute symbol definitions (syntax: <name>=<addr>)"),
  119. cl::ZeroOrMore, cl::cat(JITLinkCategory));
  120. static cl::list<std::string> TestHarnesses("harness", cl::Positional,
  121. cl::desc("Test harness files"),
  122. cl::ZeroOrMore,
  123. cl::PositionalEatsArgs,
  124. cl::cat(JITLinkCategory));
  125. static cl::opt<bool> ShowInitialExecutionSessionState(
  126. "show-init-es",
  127. cl::desc("Print ExecutionSession state before resolving entry point"),
  128. cl::init(false), cl::cat(JITLinkCategory));
  129. static cl::opt<bool> ShowEntryExecutionSessionState(
  130. "show-entry-es",
  131. cl::desc("Print ExecutionSession state after resolving entry point"),
  132. cl::init(false), cl::cat(JITLinkCategory));
  133. static cl::opt<bool> ShowAddrs(
  134. "show-addrs",
  135. cl::desc("Print registered symbol, section, got and stub addresses"),
  136. cl::init(false), cl::cat(JITLinkCategory));
  137. static cl::opt<bool> ShowLinkGraph(
  138. "show-graph",
  139. cl::desc("Print the link graph after fixups have been applied"),
  140. cl::init(false), cl::cat(JITLinkCategory));
  141. static cl::opt<bool> ShowSizes(
  142. "show-sizes",
  143. cl::desc("Show sizes pre- and post-dead stripping, and allocations"),
  144. cl::init(false), cl::cat(JITLinkCategory));
  145. static cl::opt<bool> ShowTimes("show-times",
  146. cl::desc("Show times for llvm-jitlink phases"),
  147. cl::init(false), cl::cat(JITLinkCategory));
  148. static cl::opt<std::string> SlabAllocateSizeString(
  149. "slab-allocate",
  150. cl::desc("Allocate from a slab of the given size "
  151. "(allowable suffixes: Kb, Mb, Gb. default = "
  152. "Kb)"),
  153. cl::init(""), cl::cat(JITLinkCategory));
  154. static cl::opt<uint64_t> SlabAddress(
  155. "slab-address",
  156. cl::desc("Set slab target address (requires -slab-allocate and -noexec)"),
  157. cl::init(~0ULL), cl::cat(JITLinkCategory));
  158. static cl::opt<uint64_t> SlabPageSize(
  159. "slab-page-size",
  160. cl::desc("Set page size for slab (requires -slab-allocate and -noexec)"),
  161. cl::init(0), cl::cat(JITLinkCategory));
  162. static cl::opt<bool> ShowRelocatedSectionContents(
  163. "show-relocated-section-contents",
  164. cl::desc("show section contents after fixups have been applied"),
  165. cl::init(false), cl::cat(JITLinkCategory));
  166. static cl::opt<bool> PhonyExternals(
  167. "phony-externals",
  168. cl::desc("resolve all otherwise unresolved externals to null"),
  169. cl::init(false), cl::cat(JITLinkCategory));
  170. static cl::opt<std::string> OutOfProcessExecutor(
  171. "oop-executor", cl::desc("Launch an out-of-process executor to run code"),
  172. cl::ValueOptional, cl::cat(JITLinkCategory));
  173. static cl::opt<std::string> OutOfProcessExecutorConnect(
  174. "oop-executor-connect",
  175. cl::desc("Connect to an out-of-process executor via TCP"),
  176. cl::cat(JITLinkCategory));
  177. static cl::opt<std::string>
  178. OrcRuntime("orc-runtime", cl::desc("Use ORC runtime from given path"),
  179. cl::init(""), cl::cat(JITLinkCategory));
  180. static cl::opt<bool> AddSelfRelocations(
  181. "add-self-relocations",
  182. cl::desc("Add relocations to function pointers to the current function"),
  183. cl::init(false), cl::cat(JITLinkCategory));
  184. ExitOnError ExitOnErr;
  185. LLVM_ATTRIBUTE_USED void linkComponents() {
  186. errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
  187. << (void *)&llvm_orc_deregisterEHFrameSectionWrapper
  188. << (void *)&llvm_orc_registerJITLoaderGDBWrapper;
  189. }
  190. static bool UseTestResultOverride = false;
  191. static int64_t TestResultOverride = 0;
  192. extern "C" LLVM_ATTRIBUTE_USED void
  193. llvm_jitlink_setTestResultOverride(int64_t Value) {
  194. TestResultOverride = Value;
  195. UseTestResultOverride = true;
  196. }
  197. static Error addSelfRelocations(LinkGraph &G);
  198. namespace llvm {
  199. static raw_ostream &
  200. operator<<(raw_ostream &OS, const Session::MemoryRegionInfo &MRI) {
  201. return OS << "target addr = "
  202. << format("0x%016" PRIx64, MRI.getTargetAddress())
  203. << ", content: " << (const void *)MRI.getContent().data() << " -- "
  204. << (const void *)(MRI.getContent().data() + MRI.getContent().size())
  205. << " (" << MRI.getContent().size() << " bytes)";
  206. }
  207. static raw_ostream &
  208. operator<<(raw_ostream &OS, const Session::SymbolInfoMap &SIM) {
  209. OS << "Symbols:\n";
  210. for (auto &SKV : SIM)
  211. OS << " \"" << SKV.first() << "\" " << SKV.second << "\n";
  212. return OS;
  213. }
  214. static raw_ostream &
  215. operator<<(raw_ostream &OS, const Session::FileInfo &FI) {
  216. for (auto &SIKV : FI.SectionInfos)
  217. OS << " Section \"" << SIKV.first() << "\": " << SIKV.second << "\n";
  218. for (auto &GOTKV : FI.GOTEntryInfos)
  219. OS << " GOT \"" << GOTKV.first() << "\": " << GOTKV.second << "\n";
  220. for (auto &StubKV : FI.StubInfos)
  221. OS << " Stub \"" << StubKV.first() << "\": " << StubKV.second << "\n";
  222. return OS;
  223. }
  224. static raw_ostream &
  225. operator<<(raw_ostream &OS, const Session::FileInfoMap &FIM) {
  226. for (auto &FIKV : FIM)
  227. OS << "File \"" << FIKV.first() << "\":\n" << FIKV.second;
  228. return OS;
  229. }
  230. static Error applyHarnessPromotions(Session &S, LinkGraph &G) {
  231. // If this graph is part of the test harness there's nothing to do.
  232. if (S.HarnessFiles.empty() || S.HarnessFiles.count(G.getName()))
  233. return Error::success();
  234. LLVM_DEBUG(dbgs() << "Applying promotions to graph " << G.getName() << "\n");
  235. // If this graph is part of the test then promote any symbols referenced by
  236. // the harness to default scope, remove all symbols that clash with harness
  237. // definitions.
  238. std::vector<Symbol *> DefinitionsToRemove;
  239. for (auto *Sym : G.defined_symbols()) {
  240. if (!Sym->hasName())
  241. continue;
  242. if (Sym->getLinkage() == Linkage::Weak) {
  243. if (!S.CanonicalWeakDefs.count(Sym->getName()) ||
  244. S.CanonicalWeakDefs[Sym->getName()] != G.getName()) {
  245. LLVM_DEBUG({
  246. dbgs() << " Externalizing weak symbol " << Sym->getName() << "\n";
  247. });
  248. DefinitionsToRemove.push_back(Sym);
  249. } else {
  250. LLVM_DEBUG({
  251. dbgs() << " Making weak symbol " << Sym->getName() << " strong\n";
  252. });
  253. if (S.HarnessExternals.count(Sym->getName()))
  254. Sym->setScope(Scope::Default);
  255. else
  256. Sym->setScope(Scope::Hidden);
  257. Sym->setLinkage(Linkage::Strong);
  258. }
  259. } else if (S.HarnessExternals.count(Sym->getName())) {
  260. LLVM_DEBUG(dbgs() << " Promoting " << Sym->getName() << "\n");
  261. Sym->setScope(Scope::Default);
  262. Sym->setLive(true);
  263. continue;
  264. } else if (S.HarnessDefinitions.count(Sym->getName())) {
  265. LLVM_DEBUG(dbgs() << " Externalizing " << Sym->getName() << "\n");
  266. DefinitionsToRemove.push_back(Sym);
  267. }
  268. }
  269. for (auto *Sym : DefinitionsToRemove)
  270. G.makeExternal(*Sym);
  271. return Error::success();
  272. }
  273. static uint64_t computeTotalBlockSizes(LinkGraph &G) {
  274. uint64_t TotalSize = 0;
  275. for (auto *B : G.blocks())
  276. TotalSize += B->getSize();
  277. return TotalSize;
  278. }
  279. static void dumpSectionContents(raw_ostream &OS, LinkGraph &G) {
  280. constexpr orc::ExecutorAddrDiff DumpWidth = 16;
  281. static_assert(isPowerOf2_64(DumpWidth), "DumpWidth must be a power of two");
  282. // Put sections in address order.
  283. std::vector<Section *> Sections;
  284. for (auto &S : G.sections())
  285. Sections.push_back(&S);
  286. llvm::sort(Sections, [](const Section *LHS, const Section *RHS) {
  287. if (llvm::empty(LHS->symbols()) && llvm::empty(RHS->symbols()))
  288. return false;
  289. if (llvm::empty(LHS->symbols()))
  290. return false;
  291. if (llvm::empty(RHS->symbols()))
  292. return true;
  293. SectionRange LHSRange(*LHS);
  294. SectionRange RHSRange(*RHS);
  295. return LHSRange.getStart() < RHSRange.getStart();
  296. });
  297. for (auto *S : Sections) {
  298. OS << S->getName() << " content:";
  299. if (llvm::empty(S->symbols())) {
  300. OS << "\n section empty\n";
  301. continue;
  302. }
  303. // Sort symbols into order, then render.
  304. std::vector<Symbol *> Syms(S->symbols().begin(), S->symbols().end());
  305. llvm::sort(Syms, [](const Symbol *LHS, const Symbol *RHS) {
  306. return LHS->getAddress() < RHS->getAddress();
  307. });
  308. orc::ExecutorAddr NextAddr(Syms.front()->getAddress().getValue() &
  309. ~(DumpWidth - 1));
  310. for (auto *Sym : Syms) {
  311. bool IsZeroFill = Sym->getBlock().isZeroFill();
  312. auto SymStart = Sym->getAddress();
  313. auto SymSize = Sym->getSize();
  314. auto SymEnd = SymStart + SymSize;
  315. const uint8_t *SymData = IsZeroFill ? nullptr
  316. : reinterpret_cast<const uint8_t *>(
  317. Sym->getSymbolContent().data());
  318. // Pad any space before the symbol starts.
  319. while (NextAddr != SymStart) {
  320. if (NextAddr % DumpWidth == 0)
  321. OS << formatv("\n{0:x16}:", NextAddr);
  322. OS << " ";
  323. ++NextAddr;
  324. }
  325. // Render the symbol content.
  326. while (NextAddr != SymEnd) {
  327. if (NextAddr % DumpWidth == 0)
  328. OS << formatv("\n{0:x16}:", NextAddr);
  329. if (IsZeroFill)
  330. OS << " 00";
  331. else
  332. OS << formatv(" {0:x-2}", SymData[NextAddr - SymStart]);
  333. ++NextAddr;
  334. }
  335. }
  336. OS << "\n";
  337. }
  338. }
  339. class JITLinkSlabAllocator final : public JITLinkMemoryManager {
  340. private:
  341. struct FinalizedAllocInfo {
  342. FinalizedAllocInfo(sys::MemoryBlock Mem,
  343. std::vector<shared::WrapperFunctionCall> DeallocActions)
  344. : Mem(Mem), DeallocActions(std::move(DeallocActions)) {}
  345. sys::MemoryBlock Mem;
  346. std::vector<shared::WrapperFunctionCall> DeallocActions;
  347. };
  348. public:
  349. static Expected<std::unique_ptr<JITLinkSlabAllocator>>
  350. Create(uint64_t SlabSize) {
  351. Error Err = Error::success();
  352. std::unique_ptr<JITLinkSlabAllocator> Allocator(
  353. new JITLinkSlabAllocator(SlabSize, Err));
  354. if (Err)
  355. return std::move(Err);
  356. return std::move(Allocator);
  357. }
  358. void allocate(const JITLinkDylib *JD, LinkGraph &G,
  359. OnAllocatedFunction OnAllocated) override {
  360. // Local class for allocation.
  361. class IPMMAlloc : public InFlightAlloc {
  362. public:
  363. IPMMAlloc(JITLinkSlabAllocator &Parent, BasicLayout BL,
  364. sys::MemoryBlock StandardSegs, sys::MemoryBlock FinalizeSegs)
  365. : Parent(Parent), BL(std::move(BL)),
  366. StandardSegs(std::move(StandardSegs)),
  367. FinalizeSegs(std::move(FinalizeSegs)) {}
  368. void finalize(OnFinalizedFunction OnFinalized) override {
  369. if (auto Err = applyProtections()) {
  370. OnFinalized(std::move(Err));
  371. return;
  372. }
  373. auto DeallocActions = runFinalizeActions(BL.graphAllocActions());
  374. if (!DeallocActions) {
  375. OnFinalized(DeallocActions.takeError());
  376. return;
  377. }
  378. if (auto Err = Parent.freeBlock(FinalizeSegs)) {
  379. OnFinalized(
  380. joinErrors(std::move(Err), runDeallocActions(*DeallocActions)));
  381. return;
  382. }
  383. OnFinalized(FinalizedAlloc(ExecutorAddr::fromPtr(
  384. new FinalizedAllocInfo(StandardSegs, std::move(*DeallocActions)))));
  385. }
  386. void abandon(OnAbandonedFunction OnAbandoned) override {
  387. OnAbandoned(joinErrors(Parent.freeBlock(StandardSegs),
  388. Parent.freeBlock(FinalizeSegs)));
  389. }
  390. private:
  391. Error applyProtections() {
  392. for (auto &KV : BL.segments()) {
  393. const auto &Group = KV.first;
  394. auto &Seg = KV.second;
  395. auto Prot = toSysMemoryProtectionFlags(Group.getMemProt());
  396. uint64_t SegSize =
  397. alignTo(Seg.ContentSize + Seg.ZeroFillSize, Parent.PageSize);
  398. sys::MemoryBlock MB(Seg.WorkingMem, SegSize);
  399. if (auto EC = sys::Memory::protectMappedMemory(MB, Prot))
  400. return errorCodeToError(EC);
  401. if (Prot & sys::Memory::MF_EXEC)
  402. sys::Memory::InvalidateInstructionCache(MB.base(),
  403. MB.allocatedSize());
  404. }
  405. return Error::success();
  406. }
  407. JITLinkSlabAllocator &Parent;
  408. BasicLayout BL;
  409. sys::MemoryBlock StandardSegs;
  410. sys::MemoryBlock FinalizeSegs;
  411. };
  412. BasicLayout BL(G);
  413. auto SegsSizes = BL.getContiguousPageBasedLayoutSizes(PageSize);
  414. if (!SegsSizes) {
  415. OnAllocated(SegsSizes.takeError());
  416. return;
  417. }
  418. char *AllocBase = nullptr;
  419. {
  420. std::lock_guard<std::mutex> Lock(SlabMutex);
  421. if (SegsSizes->total() > SlabRemaining.allocatedSize()) {
  422. OnAllocated(make_error<StringError>(
  423. "Slab allocator out of memory: request for " +
  424. formatv("{0:x}", SegsSizes->total()) +
  425. " bytes exceeds remaining capacity of " +
  426. formatv("{0:x}", SlabRemaining.allocatedSize()) + " bytes",
  427. inconvertibleErrorCode()));
  428. return;
  429. }
  430. AllocBase = reinterpret_cast<char *>(SlabRemaining.base());
  431. SlabRemaining =
  432. sys::MemoryBlock(AllocBase + SegsSizes->total(),
  433. SlabRemaining.allocatedSize() - SegsSizes->total());
  434. }
  435. sys::MemoryBlock StandardSegs(AllocBase, SegsSizes->StandardSegs);
  436. sys::MemoryBlock FinalizeSegs(AllocBase + SegsSizes->StandardSegs,
  437. SegsSizes->FinalizeSegs);
  438. auto NextStandardSegAddr = ExecutorAddr::fromPtr(StandardSegs.base());
  439. auto NextFinalizeSegAddr = ExecutorAddr::fromPtr(FinalizeSegs.base());
  440. LLVM_DEBUG({
  441. dbgs() << "JITLinkSlabAllocator allocated:\n";
  442. if (SegsSizes->StandardSegs)
  443. dbgs() << formatv(" [ {0:x16} -- {1:x16} ]", NextStandardSegAddr,
  444. NextStandardSegAddr + StandardSegs.allocatedSize())
  445. << " to stardard segs\n";
  446. else
  447. dbgs() << " no standard segs\n";
  448. if (SegsSizes->FinalizeSegs)
  449. dbgs() << formatv(" [ {0:x16} -- {1:x16} ]", NextFinalizeSegAddr,
  450. NextFinalizeSegAddr + FinalizeSegs.allocatedSize())
  451. << " to finalize segs\n";
  452. else
  453. dbgs() << " no finalize segs\n";
  454. });
  455. for (auto &KV : BL.segments()) {
  456. auto &Group = KV.first;
  457. auto &Seg = KV.second;
  458. auto &SegAddr =
  459. (Group.getMemDeallocPolicy() == MemDeallocPolicy::Standard)
  460. ? NextStandardSegAddr
  461. : NextFinalizeSegAddr;
  462. LLVM_DEBUG({
  463. dbgs() << " " << Group << " -> " << formatv("{0:x16}", SegAddr)
  464. << "\n";
  465. });
  466. Seg.WorkingMem = SegAddr.toPtr<char *>();
  467. Seg.Addr = SegAddr + NextSlabDelta;
  468. SegAddr += alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
  469. // Zero out the zero-fill memory.
  470. if (Seg.ZeroFillSize != 0)
  471. memset(Seg.WorkingMem + Seg.ContentSize, 0, Seg.ZeroFillSize);
  472. }
  473. NextSlabDelta += SegsSizes->total();
  474. if (auto Err = BL.apply()) {
  475. OnAllocated(std::move(Err));
  476. return;
  477. }
  478. OnAllocated(std::unique_ptr<InProcessMemoryManager::InFlightAlloc>(
  479. new IPMMAlloc(*this, std::move(BL), std::move(StandardSegs),
  480. std::move(FinalizeSegs))));
  481. }
  482. void deallocate(std::vector<FinalizedAlloc> FinalizedAllocs,
  483. OnDeallocatedFunction OnDeallocated) override {
  484. Error Err = Error::success();
  485. for (auto &FA : FinalizedAllocs) {
  486. std::unique_ptr<FinalizedAllocInfo> FAI(
  487. FA.release().toPtr<FinalizedAllocInfo *>());
  488. // FIXME: Run dealloc actions.
  489. Err = joinErrors(std::move(Err), freeBlock(FAI->Mem));
  490. }
  491. OnDeallocated(std::move(Err));
  492. }
  493. private:
  494. JITLinkSlabAllocator(uint64_t SlabSize, Error &Err) {
  495. ErrorAsOutParameter _(&Err);
  496. if (!SlabPageSize) {
  497. if (auto PageSizeOrErr = sys::Process::getPageSize())
  498. PageSize = *PageSizeOrErr;
  499. else {
  500. Err = PageSizeOrErr.takeError();
  501. return;
  502. }
  503. if (PageSize == 0) {
  504. Err = make_error<StringError>("Page size is zero",
  505. inconvertibleErrorCode());
  506. return;
  507. }
  508. } else
  509. PageSize = SlabPageSize;
  510. if (!isPowerOf2_64(PageSize)) {
  511. Err = make_error<StringError>("Page size is not a power of 2",
  512. inconvertibleErrorCode());
  513. return;
  514. }
  515. // Round slab request up to page size.
  516. SlabSize = (SlabSize + PageSize - 1) & ~(PageSize - 1);
  517. const sys::Memory::ProtectionFlags ReadWrite =
  518. static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
  519. sys::Memory::MF_WRITE);
  520. std::error_code EC;
  521. SlabRemaining =
  522. sys::Memory::allocateMappedMemory(SlabSize, nullptr, ReadWrite, EC);
  523. if (EC) {
  524. Err = errorCodeToError(EC);
  525. return;
  526. }
  527. // Calculate the target address delta to link as-if slab were at
  528. // SlabAddress.
  529. if (SlabAddress != ~0ULL)
  530. NextSlabDelta = ExecutorAddr(SlabAddress) -
  531. ExecutorAddr::fromPtr(SlabRemaining.base());
  532. }
  533. Error freeBlock(sys::MemoryBlock MB) {
  534. // FIXME: Return memory to slab.
  535. return Error::success();
  536. }
  537. std::mutex SlabMutex;
  538. sys::MemoryBlock SlabRemaining;
  539. uint64_t PageSize = 0;
  540. int64_t NextSlabDelta = 0;
  541. };
  542. Expected<uint64_t> getSlabAllocSize(StringRef SizeString) {
  543. SizeString = SizeString.trim();
  544. uint64_t Units = 1024;
  545. if (SizeString.endswith_insensitive("kb"))
  546. SizeString = SizeString.drop_back(2).rtrim();
  547. else if (SizeString.endswith_insensitive("mb")) {
  548. Units = 1024 * 1024;
  549. SizeString = SizeString.drop_back(2).rtrim();
  550. } else if (SizeString.endswith_insensitive("gb")) {
  551. Units = 1024 * 1024 * 1024;
  552. SizeString = SizeString.drop_back(2).rtrim();
  553. }
  554. uint64_t SlabSize = 0;
  555. if (SizeString.getAsInteger(10, SlabSize))
  556. return make_error<StringError>("Invalid numeric format for slab size",
  557. inconvertibleErrorCode());
  558. return SlabSize * Units;
  559. }
  560. static std::unique_ptr<JITLinkMemoryManager> createMemoryManager() {
  561. if (!SlabAllocateSizeString.empty()) {
  562. auto SlabSize = ExitOnErr(getSlabAllocSize(SlabAllocateSizeString));
  563. return ExitOnErr(JITLinkSlabAllocator::Create(SlabSize));
  564. }
  565. return ExitOnErr(InProcessMemoryManager::Create());
  566. }
  567. static Expected<MaterializationUnit::Interface>
  568. getTestObjectFileInterface(Session &S, MemoryBufferRef O) {
  569. // Get the standard interface for this object, but ignore the symbols field.
  570. // We'll handle that manually to include promotion.
  571. auto I = getObjectFileInterface(S.ES, O);
  572. if (!I)
  573. return I.takeError();
  574. I->SymbolFlags.clear();
  575. // If creating an object file was going to fail it would have happened above,
  576. // so we can 'cantFail' this.
  577. auto Obj = cantFail(object::ObjectFile::createObjectFile(O));
  578. // The init symbol must be included in the SymbolFlags map if present.
  579. if (I->InitSymbol)
  580. I->SymbolFlags[I->InitSymbol] =
  581. JITSymbolFlags::MaterializationSideEffectsOnly;
  582. for (auto &Sym : Obj->symbols()) {
  583. Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
  584. if (!SymFlagsOrErr)
  585. // TODO: Test this error.
  586. return SymFlagsOrErr.takeError();
  587. // Skip symbols not defined in this object file.
  588. if ((*SymFlagsOrErr & object::BasicSymbolRef::SF_Undefined))
  589. continue;
  590. auto Name = Sym.getName();
  591. if (!Name)
  592. return Name.takeError();
  593. // Skip symbols that have type SF_File.
  594. if (auto SymType = Sym.getType()) {
  595. if (*SymType == object::SymbolRef::ST_File)
  596. continue;
  597. } else
  598. return SymType.takeError();
  599. auto SymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
  600. if (!SymFlags)
  601. return SymFlags.takeError();
  602. if (SymFlags->isWeak()) {
  603. // If this is a weak symbol that's not defined in the harness then we
  604. // need to either mark it as strong (if this is the first definition
  605. // that we've seen) or discard it.
  606. if (S.HarnessDefinitions.count(*Name) || S.CanonicalWeakDefs.count(*Name))
  607. continue;
  608. S.CanonicalWeakDefs[*Name] = O.getBufferIdentifier();
  609. *SymFlags &= ~JITSymbolFlags::Weak;
  610. if (!S.HarnessExternals.count(*Name))
  611. *SymFlags &= ~JITSymbolFlags::Exported;
  612. } else if (S.HarnessExternals.count(*Name)) {
  613. *SymFlags |= JITSymbolFlags::Exported;
  614. } else if (S.HarnessDefinitions.count(*Name) ||
  615. !(*SymFlagsOrErr & object::BasicSymbolRef::SF_Global))
  616. continue;
  617. auto InternedName = S.ES.intern(*Name);
  618. I->SymbolFlags[InternedName] = std::move(*SymFlags);
  619. }
  620. return I;
  621. }
  622. static Error loadProcessSymbols(Session &S) {
  623. auto FilterMainEntryPoint =
  624. [EPName = S.ES.intern(EntryPointName)](SymbolStringPtr Name) {
  625. return Name != EPName;
  626. };
  627. S.MainJD->addGenerator(
  628. ExitOnErr(orc::EPCDynamicLibrarySearchGenerator::GetForTargetProcess(
  629. S.ES, std::move(FilterMainEntryPoint))));
  630. return Error::success();
  631. }
  632. static Error loadDylibs(Session &S) {
  633. LLVM_DEBUG(dbgs() << "Loading dylibs...\n");
  634. for (const auto &Dylib : Dylibs) {
  635. LLVM_DEBUG(dbgs() << " " << Dylib << "\n");
  636. auto G = orc::EPCDynamicLibrarySearchGenerator::Load(S.ES, Dylib.c_str());
  637. if (!G)
  638. return G.takeError();
  639. S.MainJD->addGenerator(std::move(*G));
  640. }
  641. return Error::success();
  642. }
  643. static Expected<std::unique_ptr<ExecutorProcessControl>> launchExecutor() {
  644. #ifndef LLVM_ON_UNIX
  645. // FIXME: Add support for Windows.
  646. return make_error<StringError>("-" + OutOfProcessExecutor.ArgStr +
  647. " not supported on non-unix platforms",
  648. inconvertibleErrorCode());
  649. #elif !LLVM_ENABLE_THREADS
  650. // Out of process mode using SimpleRemoteEPC depends on threads.
  651. return make_error<StringError>(
  652. "-" + OutOfProcessExecutor.ArgStr +
  653. " requires threads, but LLVM was built with "
  654. "LLVM_ENABLE_THREADS=Off",
  655. inconvertibleErrorCode());
  656. #else
  657. constexpr int ReadEnd = 0;
  658. constexpr int WriteEnd = 1;
  659. // Pipe FDs.
  660. int ToExecutor[2];
  661. int FromExecutor[2];
  662. pid_t ChildPID;
  663. // Create pipes to/from the executor..
  664. if (pipe(ToExecutor) != 0 || pipe(FromExecutor) != 0)
  665. return make_error<StringError>("Unable to create pipe for executor",
  666. inconvertibleErrorCode());
  667. ChildPID = fork();
  668. if (ChildPID == 0) {
  669. // In the child...
  670. // Close the parent ends of the pipes
  671. close(ToExecutor[WriteEnd]);
  672. close(FromExecutor[ReadEnd]);
  673. // Execute the child process.
  674. std::unique_ptr<char[]> ExecutorPath, FDSpecifier;
  675. {
  676. ExecutorPath = std::make_unique<char[]>(OutOfProcessExecutor.size() + 1);
  677. strcpy(ExecutorPath.get(), OutOfProcessExecutor.data());
  678. std::string FDSpecifierStr("filedescs=");
  679. FDSpecifierStr += utostr(ToExecutor[ReadEnd]);
  680. FDSpecifierStr += ',';
  681. FDSpecifierStr += utostr(FromExecutor[WriteEnd]);
  682. FDSpecifier = std::make_unique<char[]>(FDSpecifierStr.size() + 1);
  683. strcpy(FDSpecifier.get(), FDSpecifierStr.c_str());
  684. }
  685. char *const Args[] = {ExecutorPath.get(), FDSpecifier.get(), nullptr};
  686. int RC = execvp(ExecutorPath.get(), Args);
  687. if (RC != 0) {
  688. errs() << "unable to launch out-of-process executor \""
  689. << ExecutorPath.get() << "\"\n";
  690. exit(1);
  691. }
  692. }
  693. // else we're the parent...
  694. // Close the child ends of the pipes
  695. close(ToExecutor[ReadEnd]);
  696. close(FromExecutor[WriteEnd]);
  697. return SimpleRemoteEPC::Create<FDSimpleRemoteEPCTransport>(
  698. std::make_unique<DynamicThreadPoolTaskDispatcher>(),
  699. SimpleRemoteEPC::Setup(), FromExecutor[ReadEnd], ToExecutor[WriteEnd]);
  700. #endif
  701. }
  702. #if LLVM_ON_UNIX && LLVM_ENABLE_THREADS
  703. static Error createTCPSocketError(Twine Details) {
  704. return make_error<StringError>(
  705. formatv("Failed to connect TCP socket '{0}': {1}",
  706. OutOfProcessExecutorConnect, Details),
  707. inconvertibleErrorCode());
  708. }
  709. static Expected<int> connectTCPSocket(std::string Host, std::string PortStr) {
  710. addrinfo *AI;
  711. addrinfo Hints{};
  712. Hints.ai_family = AF_INET;
  713. Hints.ai_socktype = SOCK_STREAM;
  714. Hints.ai_flags = AI_NUMERICSERV;
  715. if (int EC = getaddrinfo(Host.c_str(), PortStr.c_str(), &Hints, &AI))
  716. return createTCPSocketError("Address resolution failed (" +
  717. StringRef(gai_strerror(EC)) + ")");
  718. // Cycle through the returned addrinfo structures and connect to the first
  719. // reachable endpoint.
  720. int SockFD;
  721. addrinfo *Server;
  722. for (Server = AI; Server != nullptr; Server = Server->ai_next) {
  723. // socket might fail, e.g. if the address family is not supported. Skip to
  724. // the next addrinfo structure in such a case.
  725. if ((SockFD = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol)) < 0)
  726. continue;
  727. // If connect returns null, we exit the loop with a working socket.
  728. if (connect(SockFD, Server->ai_addr, Server->ai_addrlen) == 0)
  729. break;
  730. close(SockFD);
  731. }
  732. freeaddrinfo(AI);
  733. // If we reached the end of the loop without connecting to a valid endpoint,
  734. // dump the last error that was logged in socket() or connect().
  735. if (Server == nullptr)
  736. return createTCPSocketError(std::strerror(errno));
  737. return SockFD;
  738. }
  739. #endif
  740. static Expected<std::unique_ptr<ExecutorProcessControl>> connectToExecutor() {
  741. #ifndef LLVM_ON_UNIX
  742. // FIXME: Add TCP support for Windows.
  743. return make_error<StringError>("-" + OutOfProcessExecutorConnect.ArgStr +
  744. " not supported on non-unix platforms",
  745. inconvertibleErrorCode());
  746. #elif !LLVM_ENABLE_THREADS
  747. // Out of process mode using SimpleRemoteEPC depends on threads.
  748. return make_error<StringError>(
  749. "-" + OutOfProcessExecutorConnect.ArgStr +
  750. " requires threads, but LLVM was built with "
  751. "LLVM_ENABLE_THREADS=Off",
  752. inconvertibleErrorCode());
  753. #else
  754. StringRef Host, PortStr;
  755. std::tie(Host, PortStr) = StringRef(OutOfProcessExecutorConnect).split(':');
  756. if (Host.empty())
  757. return createTCPSocketError("Host name for -" +
  758. OutOfProcessExecutorConnect.ArgStr +
  759. " can not be empty");
  760. if (PortStr.empty())
  761. return createTCPSocketError("Port number in -" +
  762. OutOfProcessExecutorConnect.ArgStr +
  763. " can not be empty");
  764. int Port = 0;
  765. if (PortStr.getAsInteger(10, Port))
  766. return createTCPSocketError("Port number '" + PortStr +
  767. "' is not a valid integer");
  768. Expected<int> SockFD = connectTCPSocket(Host.str(), PortStr.str());
  769. if (!SockFD)
  770. return SockFD.takeError();
  771. return SimpleRemoteEPC::Create<FDSimpleRemoteEPCTransport>(
  772. std::make_unique<DynamicThreadPoolTaskDispatcher>(),
  773. SimpleRemoteEPC::Setup(), *SockFD, *SockFD);
  774. #endif
  775. }
  776. class PhonyExternalsGenerator : public DefinitionGenerator {
  777. public:
  778. Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
  779. JITDylibLookupFlags JDLookupFlags,
  780. const SymbolLookupSet &LookupSet) override {
  781. SymbolMap PhonySymbols;
  782. for (auto &KV : LookupSet)
  783. PhonySymbols[KV.first] = JITEvaluatedSymbol(0, JITSymbolFlags::Exported);
  784. return JD.define(absoluteSymbols(std::move(PhonySymbols)));
  785. }
  786. };
  787. Expected<std::unique_ptr<Session>> Session::Create(Triple TT) {
  788. std::unique_ptr<ExecutorProcessControl> EPC;
  789. if (OutOfProcessExecutor.getNumOccurrences()) {
  790. /// If -oop-executor is passed then launch the executor.
  791. if (auto REPC = launchExecutor())
  792. EPC = std::move(*REPC);
  793. else
  794. return REPC.takeError();
  795. } else if (OutOfProcessExecutorConnect.getNumOccurrences()) {
  796. /// If -oop-executor-connect is passed then connect to the executor.
  797. if (auto REPC = connectToExecutor())
  798. EPC = std::move(*REPC);
  799. else
  800. return REPC.takeError();
  801. } else {
  802. /// Otherwise use SelfExecutorProcessControl to target the current process.
  803. auto PageSize = sys::Process::getPageSize();
  804. if (!PageSize)
  805. return PageSize.takeError();
  806. EPC = std::make_unique<SelfExecutorProcessControl>(
  807. std::make_shared<SymbolStringPool>(),
  808. std::make_unique<InPlaceTaskDispatcher>(), std::move(TT), *PageSize,
  809. createMemoryManager());
  810. }
  811. Error Err = Error::success();
  812. std::unique_ptr<Session> S(new Session(std::move(EPC), Err));
  813. if (Err)
  814. return std::move(Err);
  815. return std::move(S);
  816. }
  817. Session::~Session() {
  818. if (auto Err = ES.endSession())
  819. ES.reportError(std::move(Err));
  820. }
  821. Session::Session(std::unique_ptr<ExecutorProcessControl> EPC, Error &Err)
  822. : ES(std::move(EPC)),
  823. ObjLayer(ES, ES.getExecutorProcessControl().getMemMgr()) {
  824. /// Local ObjectLinkingLayer::Plugin class to forward modifyPassConfig to the
  825. /// Session.
  826. class JITLinkSessionPlugin : public ObjectLinkingLayer::Plugin {
  827. public:
  828. JITLinkSessionPlugin(Session &S) : S(S) {}
  829. void modifyPassConfig(MaterializationResponsibility &MR, LinkGraph &G,
  830. PassConfiguration &PassConfig) override {
  831. S.modifyPassConfig(G.getTargetTriple(), PassConfig);
  832. }
  833. Error notifyFailed(MaterializationResponsibility &MR) override {
  834. return Error::success();
  835. }
  836. Error notifyRemovingResources(ResourceKey K) override {
  837. return Error::success();
  838. }
  839. void notifyTransferringResources(ResourceKey DstKey,
  840. ResourceKey SrcKey) override {}
  841. private:
  842. Session &S;
  843. };
  844. ErrorAsOutParameter _(&Err);
  845. if (auto MainJDOrErr = ES.createJITDylib("main"))
  846. MainJD = &*MainJDOrErr;
  847. else {
  848. Err = MainJDOrErr.takeError();
  849. return;
  850. }
  851. if (!NoProcessSymbols)
  852. ExitOnErr(loadProcessSymbols(*this));
  853. ExitOnErr(loadDylibs(*this));
  854. auto &TT = ES.getExecutorProcessControl().getTargetTriple();
  855. if (DebuggerSupport && TT.isOSBinFormatMachO())
  856. ObjLayer.addPlugin(ExitOnErr(
  857. GDBJITDebugInfoRegistrationPlugin::Create(this->ES, *MainJD, TT)));
  858. // Set up the platform.
  859. if (TT.isOSBinFormatMachO() && !OrcRuntime.empty()) {
  860. if (auto P =
  861. MachOPlatform::Create(ES, ObjLayer, *MainJD, OrcRuntime.c_str()))
  862. ES.setPlatform(std::move(*P));
  863. else {
  864. Err = P.takeError();
  865. return;
  866. }
  867. } else if (TT.isOSBinFormatELF() && !OrcRuntime.empty()) {
  868. if (auto P =
  869. ELFNixPlatform::Create(ES, ObjLayer, *MainJD, OrcRuntime.c_str()))
  870. ES.setPlatform(std::move(*P));
  871. else {
  872. Err = P.takeError();
  873. return;
  874. }
  875. } else if (!TT.isOSWindows() && !TT.isOSBinFormatMachO()) {
  876. if (!NoExec)
  877. ObjLayer.addPlugin(std::make_unique<EHFrameRegistrationPlugin>(
  878. ES, ExitOnErr(EPCEHFrameRegistrar::Create(this->ES))));
  879. if (DebuggerSupport)
  880. ObjLayer.addPlugin(std::make_unique<DebugObjectManagerPlugin>(
  881. ES, ExitOnErr(createJITLoaderGDBRegistrar(this->ES))));
  882. }
  883. ObjLayer.addPlugin(std::make_unique<JITLinkSessionPlugin>(*this));
  884. // Process any harness files.
  885. for (auto &HarnessFile : TestHarnesses) {
  886. HarnessFiles.insert(HarnessFile);
  887. auto ObjBuffer =
  888. ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(HarnessFile)));
  889. auto ObjInterface =
  890. ExitOnErr(getObjectFileInterface(ES, ObjBuffer->getMemBufferRef()));
  891. for (auto &KV : ObjInterface.SymbolFlags)
  892. HarnessDefinitions.insert(*KV.first);
  893. auto Obj = ExitOnErr(
  894. object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef()));
  895. for (auto &Sym : Obj->symbols()) {
  896. uint32_t SymFlags = ExitOnErr(Sym.getFlags());
  897. auto Name = ExitOnErr(Sym.getName());
  898. if (Name.empty())
  899. continue;
  900. if (SymFlags & object::BasicSymbolRef::SF_Undefined)
  901. HarnessExternals.insert(Name);
  902. }
  903. }
  904. // If a name is defined by some harness file then it's a definition, not an
  905. // external.
  906. for (auto &DefName : HarnessDefinitions)
  907. HarnessExternals.erase(DefName.getKey());
  908. }
  909. void Session::dumpSessionInfo(raw_ostream &OS) {
  910. OS << "Registered addresses:\n" << SymbolInfos << FileInfos;
  911. }
  912. void Session::modifyPassConfig(const Triple &TT,
  913. PassConfiguration &PassConfig) {
  914. if (!CheckFiles.empty())
  915. PassConfig.PostFixupPasses.push_back([this](LinkGraph &G) {
  916. auto &EPC = ES.getExecutorProcessControl();
  917. if (EPC.getTargetTriple().getObjectFormat() == Triple::ELF)
  918. return registerELFGraphInfo(*this, G);
  919. if (EPC.getTargetTriple().getObjectFormat() == Triple::MachO)
  920. return registerMachOGraphInfo(*this, G);
  921. return make_error<StringError>("Unsupported object format for GOT/stub "
  922. "registration",
  923. inconvertibleErrorCode());
  924. });
  925. if (ShowLinkGraph)
  926. PassConfig.PostFixupPasses.push_back([](LinkGraph &G) -> Error {
  927. outs() << "Link graph \"" << G.getName() << "\" post-fixup:\n";
  928. G.dump(outs());
  929. return Error::success();
  930. });
  931. PassConfig.PrePrunePasses.push_back(
  932. [this](LinkGraph &G) { return applyHarnessPromotions(*this, G); });
  933. if (ShowSizes) {
  934. PassConfig.PrePrunePasses.push_back([this](LinkGraph &G) -> Error {
  935. SizeBeforePruning += computeTotalBlockSizes(G);
  936. return Error::success();
  937. });
  938. PassConfig.PostFixupPasses.push_back([this](LinkGraph &G) -> Error {
  939. SizeAfterFixups += computeTotalBlockSizes(G);
  940. return Error::success();
  941. });
  942. }
  943. if (ShowRelocatedSectionContents)
  944. PassConfig.PostFixupPasses.push_back([](LinkGraph &G) -> Error {
  945. outs() << "Relocated section contents for " << G.getName() << ":\n";
  946. dumpSectionContents(outs(), G);
  947. return Error::success();
  948. });
  949. if (AddSelfRelocations)
  950. PassConfig.PostPrunePasses.push_back(addSelfRelocations);
  951. }
  952. Expected<Session::FileInfo &> Session::findFileInfo(StringRef FileName) {
  953. auto FileInfoItr = FileInfos.find(FileName);
  954. if (FileInfoItr == FileInfos.end())
  955. return make_error<StringError>("file \"" + FileName + "\" not recognized",
  956. inconvertibleErrorCode());
  957. return FileInfoItr->second;
  958. }
  959. Expected<Session::MemoryRegionInfo &>
  960. Session::findSectionInfo(StringRef FileName, StringRef SectionName) {
  961. auto FI = findFileInfo(FileName);
  962. if (!FI)
  963. return FI.takeError();
  964. auto SecInfoItr = FI->SectionInfos.find(SectionName);
  965. if (SecInfoItr == FI->SectionInfos.end())
  966. return make_error<StringError>("no section \"" + SectionName +
  967. "\" registered for file \"" + FileName +
  968. "\"",
  969. inconvertibleErrorCode());
  970. return SecInfoItr->second;
  971. }
  972. Expected<Session::MemoryRegionInfo &>
  973. Session::findStubInfo(StringRef FileName, StringRef TargetName) {
  974. auto FI = findFileInfo(FileName);
  975. if (!FI)
  976. return FI.takeError();
  977. auto StubInfoItr = FI->StubInfos.find(TargetName);
  978. if (StubInfoItr == FI->StubInfos.end())
  979. return make_error<StringError>("no stub for \"" + TargetName +
  980. "\" registered for file \"" + FileName +
  981. "\"",
  982. inconvertibleErrorCode());
  983. return StubInfoItr->second;
  984. }
  985. Expected<Session::MemoryRegionInfo &>
  986. Session::findGOTEntryInfo(StringRef FileName, StringRef TargetName) {
  987. auto FI = findFileInfo(FileName);
  988. if (!FI)
  989. return FI.takeError();
  990. auto GOTInfoItr = FI->GOTEntryInfos.find(TargetName);
  991. if (GOTInfoItr == FI->GOTEntryInfos.end())
  992. return make_error<StringError>("no GOT entry for \"" + TargetName +
  993. "\" registered for file \"" + FileName +
  994. "\"",
  995. inconvertibleErrorCode());
  996. return GOTInfoItr->second;
  997. }
  998. bool Session::isSymbolRegistered(StringRef SymbolName) {
  999. return SymbolInfos.count(SymbolName);
  1000. }
  1001. Expected<Session::MemoryRegionInfo &>
  1002. Session::findSymbolInfo(StringRef SymbolName, Twine ErrorMsgStem) {
  1003. auto SymInfoItr = SymbolInfos.find(SymbolName);
  1004. if (SymInfoItr == SymbolInfos.end())
  1005. return make_error<StringError>(ErrorMsgStem + ": symbol " + SymbolName +
  1006. " not found",
  1007. inconvertibleErrorCode());
  1008. return SymInfoItr->second;
  1009. }
  1010. } // end namespace llvm
  1011. static Triple getFirstFileTriple() {
  1012. static Triple FirstTT = []() {
  1013. assert(!InputFiles.empty() && "InputFiles can not be empty");
  1014. for (auto InputFile : InputFiles) {
  1015. auto ObjBuffer =
  1016. ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(InputFile)));
  1017. switch (identify_magic(ObjBuffer->getBuffer())) {
  1018. case file_magic::elf_relocatable:
  1019. case file_magic::macho_object:
  1020. case file_magic::coff_object: {
  1021. auto Obj = ExitOnErr(
  1022. object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef()));
  1023. return Obj->makeTriple();
  1024. }
  1025. default:
  1026. break;
  1027. }
  1028. }
  1029. return Triple();
  1030. }();
  1031. return FirstTT;
  1032. }
  1033. static Error sanitizeArguments(const Triple &TT, const char *ArgV0) {
  1034. // -noexec and --args should not be used together.
  1035. if (NoExec && !InputArgv.empty())
  1036. errs() << "Warning: --args passed to -noexec run will be ignored.\n";
  1037. // Set the entry point name if not specified.
  1038. if (EntryPointName.empty())
  1039. EntryPointName = TT.getObjectFormat() == Triple::MachO ? "_main" : "main";
  1040. // Disable debugger support by default in noexec tests.
  1041. if (DebuggerSupport.getNumOccurrences() == 0 && NoExec)
  1042. DebuggerSupport = false;
  1043. // If -slab-allocate is passed, check that we're not trying to use it in
  1044. // -oop-executor or -oop-executor-connect mode.
  1045. //
  1046. // FIXME: Remove once we enable remote slab allocation.
  1047. if (SlabAllocateSizeString != "") {
  1048. if (OutOfProcessExecutor.getNumOccurrences() ||
  1049. OutOfProcessExecutorConnect.getNumOccurrences())
  1050. return make_error<StringError>(
  1051. "-slab-allocate cannot be used with -oop-executor or "
  1052. "-oop-executor-connect",
  1053. inconvertibleErrorCode());
  1054. }
  1055. // If -slab-address is passed, require -slab-allocate and -noexec
  1056. if (SlabAddress != ~0ULL) {
  1057. if (SlabAllocateSizeString == "" || !NoExec)
  1058. return make_error<StringError>(
  1059. "-slab-address requires -slab-allocate and -noexec",
  1060. inconvertibleErrorCode());
  1061. if (SlabPageSize == 0)
  1062. errs() << "Warning: -slab-address used without -slab-page-size.\n";
  1063. }
  1064. if (SlabPageSize != 0) {
  1065. // -slab-page-size requires slab alloc.
  1066. if (SlabAllocateSizeString == "")
  1067. return make_error<StringError>("-slab-page-size requires -slab-allocate",
  1068. inconvertibleErrorCode());
  1069. // Check -slab-page-size / -noexec interactions.
  1070. if (!NoExec) {
  1071. if (auto RealPageSize = sys::Process::getPageSize()) {
  1072. if (SlabPageSize % *RealPageSize)
  1073. return make_error<StringError>(
  1074. "-slab-page-size must be a multiple of real page size for exec "
  1075. "tests (did you mean to use -noexec ?)\n",
  1076. inconvertibleErrorCode());
  1077. } else {
  1078. errs() << "Could not retrieve process page size:\n";
  1079. logAllUnhandledErrors(RealPageSize.takeError(), errs(), "");
  1080. errs() << "Executing with slab page size = "
  1081. << formatv("{0:x}", SlabPageSize) << ".\n"
  1082. << "Tool may crash if " << formatv("{0:x}", SlabPageSize)
  1083. << " is not a multiple of the real process page size.\n"
  1084. << "(did you mean to use -noexec ?)";
  1085. }
  1086. }
  1087. }
  1088. // Only one of -oop-executor and -oop-executor-connect can be used.
  1089. if (!!OutOfProcessExecutor.getNumOccurrences() &&
  1090. !!OutOfProcessExecutorConnect.getNumOccurrences())
  1091. return make_error<StringError>(
  1092. "Only one of -" + OutOfProcessExecutor.ArgStr + " and -" +
  1093. OutOfProcessExecutorConnect.ArgStr + " can be specified",
  1094. inconvertibleErrorCode());
  1095. // If -oop-executor was used but no value was specified then use a sensible
  1096. // default.
  1097. if (!!OutOfProcessExecutor.getNumOccurrences() &&
  1098. OutOfProcessExecutor.empty()) {
  1099. SmallString<256> OOPExecutorPath(sys::fs::getMainExecutable(
  1100. ArgV0, reinterpret_cast<void *>(&sanitizeArguments)));
  1101. sys::path::remove_filename(OOPExecutorPath);
  1102. sys::path::append(OOPExecutorPath, "llvm-jitlink-executor");
  1103. OutOfProcessExecutor = OOPExecutorPath.str().str();
  1104. }
  1105. return Error::success();
  1106. }
  1107. static void addPhonyExternalsGenerator(Session &S) {
  1108. S.MainJD->addGenerator(std::make_unique<PhonyExternalsGenerator>());
  1109. }
  1110. static Error createJITDylibs(Session &S,
  1111. std::map<unsigned, JITDylib *> &IdxToJD) {
  1112. // First, set up JITDylibs.
  1113. LLVM_DEBUG(dbgs() << "Creating JITDylibs...\n");
  1114. {
  1115. // Create a "main" JITLinkDylib.
  1116. IdxToJD[0] = S.MainJD;
  1117. S.JDSearchOrder.push_back({S.MainJD, JITDylibLookupFlags::MatchAllSymbols});
  1118. LLVM_DEBUG(dbgs() << " 0: " << S.MainJD->getName() << "\n");
  1119. // Add any extra JITDylibs from the command line.
  1120. for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
  1121. JDItr != JDEnd; ++JDItr) {
  1122. auto JD = S.ES.createJITDylib(*JDItr);
  1123. if (!JD)
  1124. return JD.takeError();
  1125. unsigned JDIdx = JITDylibs.getPosition(JDItr - JITDylibs.begin());
  1126. IdxToJD[JDIdx] = &*JD;
  1127. S.JDSearchOrder.push_back({&*JD, JITDylibLookupFlags::MatchAllSymbols});
  1128. LLVM_DEBUG(dbgs() << " " << JDIdx << ": " << JD->getName() << "\n");
  1129. }
  1130. }
  1131. LLVM_DEBUG({
  1132. dbgs() << "Dylib search order is [ ";
  1133. for (auto &KV : S.JDSearchOrder)
  1134. dbgs() << KV.first->getName() << " ";
  1135. dbgs() << "]\n";
  1136. });
  1137. return Error::success();
  1138. }
  1139. static Error addAbsoluteSymbols(Session &S,
  1140. const std::map<unsigned, JITDylib *> &IdxToJD) {
  1141. // Define absolute symbols.
  1142. LLVM_DEBUG(dbgs() << "Defining absolute symbols...\n");
  1143. for (auto AbsDefItr = AbsoluteDefs.begin(), AbsDefEnd = AbsoluteDefs.end();
  1144. AbsDefItr != AbsDefEnd; ++AbsDefItr) {
  1145. unsigned AbsDefArgIdx =
  1146. AbsoluteDefs.getPosition(AbsDefItr - AbsoluteDefs.begin());
  1147. auto &JD = *std::prev(IdxToJD.lower_bound(AbsDefArgIdx))->second;
  1148. StringRef AbsDefStmt = *AbsDefItr;
  1149. size_t EqIdx = AbsDefStmt.find_first_of('=');
  1150. if (EqIdx == StringRef::npos)
  1151. return make_error<StringError>("Invalid absolute define \"" + AbsDefStmt +
  1152. "\". Syntax: <name>=<addr>",
  1153. inconvertibleErrorCode());
  1154. StringRef Name = AbsDefStmt.substr(0, EqIdx).trim();
  1155. StringRef AddrStr = AbsDefStmt.substr(EqIdx + 1).trim();
  1156. uint64_t Addr;
  1157. if (AddrStr.getAsInteger(0, Addr))
  1158. return make_error<StringError>("Invalid address expression \"" + AddrStr +
  1159. "\" in absolute define \"" + AbsDefStmt +
  1160. "\"",
  1161. inconvertibleErrorCode());
  1162. JITEvaluatedSymbol AbsDef(Addr, JITSymbolFlags::Exported);
  1163. if (auto Err = JD.define(absoluteSymbols({{S.ES.intern(Name), AbsDef}})))
  1164. return Err;
  1165. // Register the absolute symbol with the session symbol infos.
  1166. S.SymbolInfos[Name] = {ArrayRef<char>(), Addr};
  1167. }
  1168. return Error::success();
  1169. }
  1170. static Error addTestHarnesses(Session &S) {
  1171. LLVM_DEBUG(dbgs() << "Adding test harness objects...\n");
  1172. for (auto HarnessFile : TestHarnesses) {
  1173. LLVM_DEBUG(dbgs() << " " << HarnessFile << "\n");
  1174. auto ObjBuffer = errorOrToExpected(MemoryBuffer::getFile(HarnessFile));
  1175. if (!ObjBuffer)
  1176. return ObjBuffer.takeError();
  1177. if (auto Err = S.ObjLayer.add(*S.MainJD, std::move(*ObjBuffer)))
  1178. return Err;
  1179. }
  1180. return Error::success();
  1181. }
  1182. static Error addObjects(Session &S,
  1183. const std::map<unsigned, JITDylib *> &IdxToJD) {
  1184. // Load each object into the corresponding JITDylib..
  1185. LLVM_DEBUG(dbgs() << "Adding objects...\n");
  1186. for (auto InputFileItr = InputFiles.begin(), InputFileEnd = InputFiles.end();
  1187. InputFileItr != InputFileEnd; ++InputFileItr) {
  1188. unsigned InputFileArgIdx =
  1189. InputFiles.getPosition(InputFileItr - InputFiles.begin());
  1190. const std::string &InputFile = *InputFileItr;
  1191. if (StringRef(InputFile).endswith(".a"))
  1192. continue;
  1193. auto &JD = *std::prev(IdxToJD.lower_bound(InputFileArgIdx))->second;
  1194. LLVM_DEBUG(dbgs() << " " << InputFileArgIdx << ": \"" << InputFile
  1195. << "\" to " << JD.getName() << "\n";);
  1196. auto ObjBuffer = errorOrToExpected(MemoryBuffer::getFile(InputFile));
  1197. if (!ObjBuffer)
  1198. return ObjBuffer.takeError();
  1199. if (S.HarnessFiles.empty()) {
  1200. if (auto Err = S.ObjLayer.add(JD, std::move(*ObjBuffer)))
  1201. return Err;
  1202. } else {
  1203. // We're in -harness mode. Use a custom interface for this
  1204. // test object.
  1205. auto ObjInterface =
  1206. getTestObjectFileInterface(S, (*ObjBuffer)->getMemBufferRef());
  1207. if (!ObjInterface)
  1208. return ObjInterface.takeError();
  1209. if (auto Err = S.ObjLayer.add(JD, std::move(*ObjBuffer),
  1210. std::move(*ObjInterface)))
  1211. return Err;
  1212. }
  1213. }
  1214. return Error::success();
  1215. }
  1216. static Expected<MaterializationUnit::Interface>
  1217. getObjectFileInterfaceHidden(ExecutionSession &ES, MemoryBufferRef ObjBuffer) {
  1218. auto I = getObjectFileInterface(ES, ObjBuffer);
  1219. if (I) {
  1220. for (auto &KV : I->SymbolFlags)
  1221. KV.second &= ~JITSymbolFlags::Exported;
  1222. }
  1223. return I;
  1224. }
  1225. static Error addLibraries(Session &S,
  1226. const std::map<unsigned, JITDylib *> &IdxToJD) {
  1227. // 1. Collect search paths for each JITDylib.
  1228. DenseMap<const JITDylib *, SmallVector<StringRef, 2>> JDSearchPaths;
  1229. for (auto LSPItr = LibrarySearchPaths.begin(),
  1230. LSPEnd = LibrarySearchPaths.end();
  1231. LSPItr != LSPEnd; ++LSPItr) {
  1232. unsigned LibrarySearchPathIdx =
  1233. LibrarySearchPaths.getPosition(LSPItr - LibrarySearchPaths.begin());
  1234. auto &JD = *std::prev(IdxToJD.lower_bound(LibrarySearchPathIdx))->second;
  1235. StringRef LibrarySearchPath = *LSPItr;
  1236. if (sys::fs::get_file_type(LibrarySearchPath) !=
  1237. sys::fs::file_type::directory_file)
  1238. return make_error<StringError>("While linking " + JD.getName() + ", -L" +
  1239. LibrarySearchPath +
  1240. " does not point to a directory",
  1241. inconvertibleErrorCode());
  1242. JDSearchPaths[&JD].push_back(*LSPItr);
  1243. }
  1244. LLVM_DEBUG({
  1245. if (!JDSearchPaths.empty())
  1246. dbgs() << "Search paths:\n";
  1247. for (auto &KV : JDSearchPaths) {
  1248. dbgs() << " " << KV.first->getName() << ": [";
  1249. for (auto &LibSearchPath : KV.second)
  1250. dbgs() << " \"" << LibSearchPath << "\"";
  1251. dbgs() << " ]\n";
  1252. }
  1253. });
  1254. // 2. Collect library loads
  1255. struct LibraryLoad {
  1256. StringRef LibName;
  1257. bool IsPath = false;
  1258. unsigned Position;
  1259. StringRef *CandidateExtensions;
  1260. enum { Standard, Hidden } Modifier;
  1261. };
  1262. std::vector<LibraryLoad> LibraryLoads;
  1263. // Add archive files from the inputs to LibraryLoads.
  1264. for (auto InputFileItr = InputFiles.begin(), InputFileEnd = InputFiles.end();
  1265. InputFileItr != InputFileEnd; ++InputFileItr) {
  1266. StringRef InputFile = *InputFileItr;
  1267. if (!InputFile.endswith(".a"))
  1268. continue;
  1269. LibraryLoad LL;
  1270. LL.LibName = InputFile;
  1271. LL.IsPath = true;
  1272. LL.Position = InputFiles.getPosition(InputFileItr - InputFiles.begin());
  1273. LL.CandidateExtensions = nullptr;
  1274. LL.Modifier = LibraryLoad::Standard;
  1275. LibraryLoads.push_back(std::move(LL));
  1276. }
  1277. // Add -load_hidden arguments to LibraryLoads.
  1278. for (auto LibItr = LoadHidden.begin(), LibEnd = LoadHidden.end();
  1279. LibItr != LibEnd; ++LibItr) {
  1280. LibraryLoad LL;
  1281. LL.LibName = *LibItr;
  1282. LL.IsPath = true;
  1283. LL.Position = LoadHidden.getPosition(LibItr - LoadHidden.begin());
  1284. LL.CandidateExtensions = nullptr;
  1285. LL.Modifier = LibraryLoad::Hidden;
  1286. LibraryLoads.push_back(std::move(LL));
  1287. }
  1288. StringRef StandardExtensions[] = {".so", ".dylib", ".a"};
  1289. StringRef ArchiveExtensionsOnly[] = {".a"};
  1290. // Add -lx arguments to LibraryLoads.
  1291. for (auto LibItr = Libraries.begin(), LibEnd = Libraries.end();
  1292. LibItr != LibEnd; ++LibItr) {
  1293. LibraryLoad LL;
  1294. LL.LibName = *LibItr;
  1295. LL.Position = Libraries.getPosition(LibItr - Libraries.begin());
  1296. LL.CandidateExtensions = StandardExtensions;
  1297. LL.Modifier = LibraryLoad::Standard;
  1298. LibraryLoads.push_back(std::move(LL));
  1299. }
  1300. // Add -hidden-lx arguments to LibraryLoads.
  1301. for (auto LibHiddenItr = LibrariesHidden.begin(),
  1302. LibHiddenEnd = LibrariesHidden.end();
  1303. LibHiddenItr != LibHiddenEnd; ++LibHiddenItr) {
  1304. LibraryLoad LL;
  1305. LL.LibName = *LibHiddenItr;
  1306. LL.Position =
  1307. LibrariesHidden.getPosition(LibHiddenItr - LibrariesHidden.begin());
  1308. LL.CandidateExtensions = ArchiveExtensionsOnly;
  1309. LL.Modifier = LibraryLoad::Hidden;
  1310. LibraryLoads.push_back(std::move(LL));
  1311. }
  1312. // If there are any load-<modified> options then turn on flag overrides
  1313. // to avoid flag mismatch errors.
  1314. if (!LibrariesHidden.empty() || !LoadHidden.empty())
  1315. S.ObjLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
  1316. // Sort library loads by position in the argument list.
  1317. llvm::sort(LibraryLoads, [](const LibraryLoad &LHS, const LibraryLoad &RHS) {
  1318. return LHS.Position < RHS.Position;
  1319. });
  1320. // 3. Process library loads.
  1321. auto AddArchive = [&](const char *Path, const LibraryLoad &LL)
  1322. -> Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>> {
  1323. unique_function<Expected<MaterializationUnit::Interface>(
  1324. ExecutionSession & ES, MemoryBufferRef ObjBuffer)>
  1325. GetObjFileInterface;
  1326. switch (LL.Modifier) {
  1327. case LibraryLoad::Standard:
  1328. GetObjFileInterface = getObjectFileInterface;
  1329. break;
  1330. case LibraryLoad::Hidden:
  1331. GetObjFileInterface = getObjectFileInterfaceHidden;
  1332. break;
  1333. }
  1334. return StaticLibraryDefinitionGenerator::Load(
  1335. S.ObjLayer, Path, S.ES.getExecutorProcessControl().getTargetTriple(),
  1336. std::move(GetObjFileInterface));
  1337. };
  1338. for (auto &LL : LibraryLoads) {
  1339. bool LibFound = false;
  1340. auto &JD = *std::prev(IdxToJD.lower_bound(LL.Position))->second;
  1341. // If this is the name of a JITDylib then link against that.
  1342. if (auto *LJD = S.ES.getJITDylibByName(LL.LibName)) {
  1343. JD.addToLinkOrder(*LJD);
  1344. continue;
  1345. }
  1346. if (LL.IsPath) {
  1347. auto G = AddArchive(LL.LibName.str().c_str(), LL);
  1348. if (!G)
  1349. return createFileError(LL.LibName, G.takeError());
  1350. JD.addGenerator(std::move(*G));
  1351. LLVM_DEBUG({
  1352. dbgs() << "Adding generator for static library " << LL.LibName << " to "
  1353. << JD.getName() << "\n";
  1354. });
  1355. continue;
  1356. }
  1357. // Otherwise look through the search paths.
  1358. auto JDSearchPathsItr = JDSearchPaths.find(&JD);
  1359. if (JDSearchPathsItr != JDSearchPaths.end()) {
  1360. for (StringRef SearchPath : JDSearchPathsItr->second) {
  1361. for (const char *LibExt : {".dylib", ".so", ".a"}) {
  1362. SmallVector<char, 256> LibPath;
  1363. LibPath.reserve(SearchPath.size() + strlen("lib") +
  1364. LL.LibName.size() + strlen(LibExt) +
  1365. 2); // +2 for pathsep, null term.
  1366. llvm::copy(SearchPath, std::back_inserter(LibPath));
  1367. sys::path::append(LibPath, "lib" + LL.LibName + LibExt);
  1368. LibPath.push_back('\0');
  1369. // Skip missing or non-regular paths.
  1370. if (sys::fs::get_file_type(LibPath.data()) !=
  1371. sys::fs::file_type::regular_file) {
  1372. continue;
  1373. }
  1374. file_magic Magic;
  1375. if (auto EC = identify_magic(LibPath, Magic)) {
  1376. // If there was an error loading the file then skip it.
  1377. LLVM_DEBUG({
  1378. dbgs() << "Library search found \"" << LibPath
  1379. << "\", but could not identify file type (" << EC.message()
  1380. << "). Skipping.\n";
  1381. });
  1382. continue;
  1383. }
  1384. // We identified the magic. Assume that we can load it -- we'll reset
  1385. // in the default case.
  1386. LibFound = true;
  1387. switch (Magic) {
  1388. case file_magic::elf_shared_object:
  1389. case file_magic::macho_dynamically_linked_shared_lib: {
  1390. // TODO: On first reference to LibPath this should create a JITDylib
  1391. // with a generator and add it to JD's links-against list. Subsquent
  1392. // references should use the JITDylib created on the first
  1393. // reference.
  1394. auto G =
  1395. EPCDynamicLibrarySearchGenerator::Load(S.ES, LibPath.data());
  1396. if (!G)
  1397. return G.takeError();
  1398. LLVM_DEBUG({
  1399. dbgs() << "Adding generator for dynamic library "
  1400. << LibPath.data() << " to " << JD.getName() << "\n";
  1401. });
  1402. JD.addGenerator(std::move(*G));
  1403. break;
  1404. }
  1405. case file_magic::archive:
  1406. case file_magic::macho_universal_binary: {
  1407. auto G = AddArchive(LibPath.data(), LL);
  1408. if (!G)
  1409. return G.takeError();
  1410. JD.addGenerator(std::move(*G));
  1411. LLVM_DEBUG({
  1412. dbgs() << "Adding generator for static library " << LibPath.data()
  1413. << " to " << JD.getName() << "\n";
  1414. });
  1415. break;
  1416. }
  1417. default:
  1418. // This file isn't a recognized library kind.
  1419. LLVM_DEBUG({
  1420. dbgs() << "Library search found \"" << LibPath
  1421. << "\", but file type is not supported. Skipping.\n";
  1422. });
  1423. LibFound = false;
  1424. break;
  1425. }
  1426. if (LibFound)
  1427. break;
  1428. }
  1429. if (LibFound)
  1430. break;
  1431. }
  1432. }
  1433. if (!LibFound)
  1434. return make_error<StringError>("While linking " + JD.getName() +
  1435. ", could not find library for -l" +
  1436. LL.LibName,
  1437. inconvertibleErrorCode());
  1438. }
  1439. return Error::success();
  1440. }
  1441. static Error addProcessSymbols(Session &S,
  1442. const std::map<unsigned, JITDylib *> &IdxToJD) {
  1443. if (NoProcessSymbols)
  1444. return Error::success();
  1445. for (auto &KV : IdxToJD) {
  1446. auto &JD = *KV.second;
  1447. JD.addGenerator(ExitOnErr(
  1448. orc::EPCDynamicLibrarySearchGenerator::GetForTargetProcess(S.ES)));
  1449. }
  1450. return Error::success();
  1451. }
  1452. static Error addSessionInputs(Session &S) {
  1453. std::map<unsigned, JITDylib *> IdxToJD;
  1454. if (auto Err = createJITDylibs(S, IdxToJD))
  1455. return Err;
  1456. if (auto Err = addAbsoluteSymbols(S, IdxToJD))
  1457. return Err;
  1458. if (!TestHarnesses.empty())
  1459. if (auto Err = addTestHarnesses(S))
  1460. return Err;
  1461. if (auto Err = addObjects(S, IdxToJD))
  1462. return Err;
  1463. if (auto Err = addLibraries(S, IdxToJD))
  1464. return Err;
  1465. if (auto Err = addProcessSymbols(S, IdxToJD))
  1466. return Err;
  1467. return Error::success();
  1468. }
  1469. namespace {
  1470. struct TargetInfo {
  1471. const Target *TheTarget;
  1472. std::unique_ptr<MCSubtargetInfo> STI;
  1473. std::unique_ptr<MCRegisterInfo> MRI;
  1474. std::unique_ptr<MCAsmInfo> MAI;
  1475. std::unique_ptr<MCContext> Ctx;
  1476. std::unique_ptr<MCDisassembler> Disassembler;
  1477. std::unique_ptr<MCInstrInfo> MII;
  1478. std::unique_ptr<MCInstrAnalysis> MIA;
  1479. std::unique_ptr<MCInstPrinter> InstPrinter;
  1480. };
  1481. } // anonymous namespace
  1482. static TargetInfo getTargetInfo(const Triple &TT) {
  1483. auto TripleName = TT.str();
  1484. std::string ErrorStr;
  1485. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, ErrorStr);
  1486. if (!TheTarget)
  1487. ExitOnErr(make_error<StringError>("Error accessing target '" + TripleName +
  1488. "': " + ErrorStr,
  1489. inconvertibleErrorCode()));
  1490. std::unique_ptr<MCSubtargetInfo> STI(
  1491. TheTarget->createMCSubtargetInfo(TripleName, "", ""));
  1492. if (!STI)
  1493. ExitOnErr(
  1494. make_error<StringError>("Unable to create subtarget for " + TripleName,
  1495. inconvertibleErrorCode()));
  1496. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  1497. if (!MRI)
  1498. ExitOnErr(make_error<StringError>("Unable to create target register info "
  1499. "for " +
  1500. TripleName,
  1501. inconvertibleErrorCode()));
  1502. MCTargetOptions MCOptions;
  1503. std::unique_ptr<MCAsmInfo> MAI(
  1504. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  1505. if (!MAI)
  1506. ExitOnErr(make_error<StringError>("Unable to create target asm info " +
  1507. TripleName,
  1508. inconvertibleErrorCode()));
  1509. auto Ctx = std::make_unique<MCContext>(Triple(TripleName), MAI.get(),
  1510. MRI.get(), STI.get());
  1511. std::unique_ptr<MCDisassembler> Disassembler(
  1512. TheTarget->createMCDisassembler(*STI, *Ctx));
  1513. if (!Disassembler)
  1514. ExitOnErr(make_error<StringError>("Unable to create disassembler for " +
  1515. TripleName,
  1516. inconvertibleErrorCode()));
  1517. std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  1518. if (!MII)
  1519. ExitOnErr(make_error<StringError>("Unable to create instruction info for" +
  1520. TripleName,
  1521. inconvertibleErrorCode()));
  1522. std::unique_ptr<MCInstrAnalysis> MIA(
  1523. TheTarget->createMCInstrAnalysis(MII.get()));
  1524. if (!MIA)
  1525. ExitOnErr(make_error<StringError>(
  1526. "Unable to create instruction analysis for" + TripleName,
  1527. inconvertibleErrorCode()));
  1528. std::unique_ptr<MCInstPrinter> InstPrinter(
  1529. TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
  1530. if (!InstPrinter)
  1531. ExitOnErr(make_error<StringError>(
  1532. "Unable to create instruction printer for" + TripleName,
  1533. inconvertibleErrorCode()));
  1534. return {TheTarget, std::move(STI), std::move(MRI),
  1535. std::move(MAI), std::move(Ctx), std::move(Disassembler),
  1536. std::move(MII), std::move(MIA), std::move(InstPrinter)};
  1537. }
  1538. static Error runChecks(Session &S) {
  1539. const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
  1540. if (CheckFiles.empty())
  1541. return Error::success();
  1542. LLVM_DEBUG(dbgs() << "Running checks...\n");
  1543. auto TI = getTargetInfo(TT);
  1544. auto IsSymbolValid = [&S](StringRef Symbol) {
  1545. return S.isSymbolRegistered(Symbol);
  1546. };
  1547. auto GetSymbolInfo = [&S](StringRef Symbol) {
  1548. return S.findSymbolInfo(Symbol, "Can not get symbol info");
  1549. };
  1550. auto GetSectionInfo = [&S](StringRef FileName, StringRef SectionName) {
  1551. return S.findSectionInfo(FileName, SectionName);
  1552. };
  1553. auto GetStubInfo = [&S](StringRef FileName, StringRef SectionName) {
  1554. return S.findStubInfo(FileName, SectionName);
  1555. };
  1556. auto GetGOTInfo = [&S](StringRef FileName, StringRef SectionName) {
  1557. return S.findGOTEntryInfo(FileName, SectionName);
  1558. };
  1559. RuntimeDyldChecker Checker(
  1560. IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo, GetGOTInfo,
  1561. TT.isLittleEndian() ? support::little : support::big,
  1562. TI.Disassembler.get(), TI.InstPrinter.get(), dbgs());
  1563. std::string CheckLineStart = "# " + CheckName + ":";
  1564. for (auto &CheckFile : CheckFiles) {
  1565. auto CheckerFileBuf =
  1566. ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(CheckFile)));
  1567. if (!Checker.checkAllRulesInBuffer(CheckLineStart, &*CheckerFileBuf))
  1568. ExitOnErr(make_error<StringError>(
  1569. "Some checks in " + CheckFile + " failed", inconvertibleErrorCode()));
  1570. }
  1571. return Error::success();
  1572. }
  1573. static Error addSelfRelocations(LinkGraph &G) {
  1574. auto TI = getTargetInfo(G.getTargetTriple());
  1575. for (auto *Sym : G.defined_symbols())
  1576. if (Sym->isCallable())
  1577. if (auto Err = addFunctionPointerRelocationsToCurrentSymbol(
  1578. *Sym, G, *TI.Disassembler, *TI.MIA))
  1579. return Err;
  1580. return Error::success();
  1581. }
  1582. static void dumpSessionStats(Session &S) {
  1583. if (!ShowSizes)
  1584. return;
  1585. if (!OrcRuntime.empty())
  1586. outs() << "Note: Session stats include runtime and entry point lookup, but "
  1587. "not JITDylib initialization/deinitialization.\n";
  1588. if (ShowSizes)
  1589. outs() << " Total size of all blocks before pruning: "
  1590. << S.SizeBeforePruning
  1591. << "\n Total size of all blocks after fixups: " << S.SizeAfterFixups
  1592. << "\n";
  1593. }
  1594. static Expected<JITEvaluatedSymbol> getMainEntryPoint(Session &S) {
  1595. return S.ES.lookup(S.JDSearchOrder, S.ES.intern(EntryPointName));
  1596. }
  1597. static Expected<JITEvaluatedSymbol> getOrcRuntimeEntryPoint(Session &S) {
  1598. std::string RuntimeEntryPoint = "__orc_rt_run_program_wrapper";
  1599. const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
  1600. if (TT.getObjectFormat() == Triple::MachO)
  1601. RuntimeEntryPoint = '_' + RuntimeEntryPoint;
  1602. return S.ES.lookup(S.JDSearchOrder, S.ES.intern(RuntimeEntryPoint));
  1603. }
  1604. static Expected<int> runWithRuntime(Session &S, ExecutorAddr EntryPointAddr) {
  1605. StringRef DemangledEntryPoint = EntryPointName;
  1606. const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
  1607. if (TT.getObjectFormat() == Triple::MachO &&
  1608. DemangledEntryPoint.front() == '_')
  1609. DemangledEntryPoint = DemangledEntryPoint.drop_front();
  1610. using SPSRunProgramSig =
  1611. int64_t(SPSString, SPSString, SPSSequence<SPSString>);
  1612. int64_t Result;
  1613. if (auto Err = S.ES.callSPSWrapper<SPSRunProgramSig>(
  1614. EntryPointAddr, Result, S.MainJD->getName(), DemangledEntryPoint,
  1615. static_cast<std::vector<std::string> &>(InputArgv)))
  1616. return std::move(Err);
  1617. return Result;
  1618. }
  1619. static Expected<int> runWithoutRuntime(Session &S,
  1620. ExecutorAddr EntryPointAddr) {
  1621. return S.ES.getExecutorProcessControl().runAsMain(EntryPointAddr, InputArgv);
  1622. }
  1623. namespace {
  1624. struct JITLinkTimers {
  1625. TimerGroup JITLinkTG{"llvm-jitlink timers", "timers for llvm-jitlink phases"};
  1626. Timer LoadObjectsTimer{"load", "time to load/add object files", JITLinkTG};
  1627. Timer LinkTimer{"link", "time to link object files", JITLinkTG};
  1628. Timer RunTimer{"run", "time to execute jitlink'd code", JITLinkTG};
  1629. };
  1630. } // namespace
  1631. int main(int argc, char *argv[]) {
  1632. InitLLVM X(argc, argv);
  1633. InitializeAllTargetInfos();
  1634. InitializeAllTargetMCs();
  1635. InitializeAllDisassemblers();
  1636. cl::HideUnrelatedOptions({&JITLinkCategory, &getColorCategory()});
  1637. cl::ParseCommandLineOptions(argc, argv, "llvm jitlink tool");
  1638. ExitOnErr.setBanner(std::string(argv[0]) + ": ");
  1639. /// If timers are enabled, create a JITLinkTimers instance.
  1640. std::unique_ptr<JITLinkTimers> Timers =
  1641. ShowTimes ? std::make_unique<JITLinkTimers>() : nullptr;
  1642. ExitOnErr(sanitizeArguments(getFirstFileTriple(), argv[0]));
  1643. auto S = ExitOnErr(Session::Create(getFirstFileTriple()));
  1644. {
  1645. TimeRegion TR(Timers ? &Timers->LoadObjectsTimer : nullptr);
  1646. ExitOnErr(addSessionInputs(*S));
  1647. }
  1648. if (PhonyExternals)
  1649. addPhonyExternalsGenerator(*S);
  1650. if (ShowInitialExecutionSessionState)
  1651. S->ES.dump(outs());
  1652. JITEvaluatedSymbol EntryPoint = nullptr;
  1653. {
  1654. TimeRegion TR(Timers ? &Timers->LinkTimer : nullptr);
  1655. // Find the entry-point function unconditionally, since we want to force
  1656. // it to be materialized to collect stats.
  1657. EntryPoint = ExitOnErr(getMainEntryPoint(*S));
  1658. LLVM_DEBUG({
  1659. dbgs() << "Using entry point \"" << EntryPointName
  1660. << "\": " << formatv("{0:x16}", EntryPoint.getAddress()) << "\n";
  1661. });
  1662. // If we're running with the ORC runtime then replace the entry-point
  1663. // with the __orc_rt_run_program symbol.
  1664. if (!OrcRuntime.empty()) {
  1665. EntryPoint = ExitOnErr(getOrcRuntimeEntryPoint(*S));
  1666. LLVM_DEBUG({
  1667. dbgs() << "(called via __orc_rt_run_program_wrapper at "
  1668. << formatv("{0:x16}", EntryPoint.getAddress()) << ")\n";
  1669. });
  1670. }
  1671. }
  1672. if (ShowEntryExecutionSessionState)
  1673. S->ES.dump(outs());
  1674. if (ShowAddrs)
  1675. S->dumpSessionInfo(outs());
  1676. ExitOnErr(runChecks(*S));
  1677. dumpSessionStats(*S);
  1678. if (NoExec)
  1679. return 0;
  1680. int Result = 0;
  1681. {
  1682. LLVM_DEBUG(dbgs() << "Running \"" << EntryPointName << "\"...\n");
  1683. TimeRegion TR(Timers ? &Timers->RunTimer : nullptr);
  1684. if (!OrcRuntime.empty())
  1685. Result =
  1686. ExitOnErr(runWithRuntime(*S, ExecutorAddr(EntryPoint.getAddress())));
  1687. else
  1688. Result = ExitOnErr(
  1689. runWithoutRuntime(*S, ExecutorAddr(EntryPoint.getAddress())));
  1690. }
  1691. // Destroy the session.
  1692. ExitOnErr(S->ES.endSession());
  1693. S.reset();
  1694. // If the executing code set a test result override then use that.
  1695. if (UseTestResultOverride)
  1696. Result = TestResultOverride;
  1697. return Result;
  1698. }