llvm-jitlink.cpp 72 KB

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