JITLink.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. //===------------- JITLink.cpp - Core Run-time JIT linker APIs ------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ExecutionEngine/JITLink/JITLink.h"
  9. #include "llvm/BinaryFormat/Magic.h"
  10. #include "llvm/ExecutionEngine/JITLink/COFF.h"
  11. #include "llvm/ExecutionEngine/JITLink/ELF.h"
  12. #include "llvm/ExecutionEngine/JITLink/MachO.h"
  13. #include "llvm/Support/Format.h"
  14. #include "llvm/Support/MemoryBuffer.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. using namespace llvm;
  17. using namespace llvm::object;
  18. #define DEBUG_TYPE "jitlink"
  19. namespace {
  20. enum JITLinkErrorCode { GenericJITLinkError = 1 };
  21. // FIXME: This class is only here to support the transition to llvm::Error. It
  22. // will be removed once this transition is complete. Clients should prefer to
  23. // deal with the Error value directly, rather than converting to error_code.
  24. class JITLinkerErrorCategory : public std::error_category {
  25. public:
  26. const char *name() const noexcept override { return "runtimedyld"; }
  27. std::string message(int Condition) const override {
  28. switch (static_cast<JITLinkErrorCode>(Condition)) {
  29. case GenericJITLinkError:
  30. return "Generic JITLink error";
  31. }
  32. llvm_unreachable("Unrecognized JITLinkErrorCode");
  33. }
  34. };
  35. } // namespace
  36. namespace llvm {
  37. namespace jitlink {
  38. char JITLinkError::ID = 0;
  39. void JITLinkError::log(raw_ostream &OS) const { OS << ErrMsg; }
  40. std::error_code JITLinkError::convertToErrorCode() const {
  41. static JITLinkerErrorCategory TheJITLinkerErrorCategory;
  42. return std::error_code(GenericJITLinkError, TheJITLinkerErrorCategory);
  43. }
  44. const char *getGenericEdgeKindName(Edge::Kind K) {
  45. switch (K) {
  46. case Edge::Invalid:
  47. return "INVALID RELOCATION";
  48. case Edge::KeepAlive:
  49. return "Keep-Alive";
  50. default:
  51. return "<Unrecognized edge kind>";
  52. }
  53. }
  54. const char *getLinkageName(Linkage L) {
  55. switch (L) {
  56. case Linkage::Strong:
  57. return "strong";
  58. case Linkage::Weak:
  59. return "weak";
  60. }
  61. llvm_unreachable("Unrecognized llvm.jitlink.Linkage enum");
  62. }
  63. const char *getScopeName(Scope S) {
  64. switch (S) {
  65. case Scope::Default:
  66. return "default";
  67. case Scope::Hidden:
  68. return "hidden";
  69. case Scope::Local:
  70. return "local";
  71. }
  72. llvm_unreachable("Unrecognized llvm.jitlink.Scope enum");
  73. }
  74. raw_ostream &operator<<(raw_ostream &OS, const Block &B) {
  75. return OS << B.getAddress() << " -- " << (B.getAddress() + B.getSize())
  76. << ": "
  77. << "size = " << formatv("{0:x8}", B.getSize()) << ", "
  78. << (B.isZeroFill() ? "zero-fill" : "content")
  79. << ", align = " << B.getAlignment()
  80. << ", align-ofs = " << B.getAlignmentOffset()
  81. << ", section = " << B.getSection().getName();
  82. }
  83. raw_ostream &operator<<(raw_ostream &OS, const Symbol &Sym) {
  84. OS << Sym.getAddress() << " (" << (Sym.isDefined() ? "block" : "addressable")
  85. << " + " << formatv("{0:x8}", Sym.getOffset())
  86. << "): size: " << formatv("{0:x8}", Sym.getSize())
  87. << ", linkage: " << formatv("{0:6}", getLinkageName(Sym.getLinkage()))
  88. << ", scope: " << formatv("{0:8}", getScopeName(Sym.getScope())) << ", "
  89. << (Sym.isLive() ? "live" : "dead") << " - "
  90. << (Sym.hasName() ? Sym.getName() : "<anonymous symbol>");
  91. return OS;
  92. }
  93. void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
  94. StringRef EdgeKindName) {
  95. OS << "edge@" << B.getAddress() + E.getOffset() << ": " << B.getAddress()
  96. << " + " << formatv("{0:x}", E.getOffset()) << " -- " << EdgeKindName
  97. << " -> ";
  98. auto &TargetSym = E.getTarget();
  99. if (TargetSym.hasName())
  100. OS << TargetSym.getName();
  101. else {
  102. auto &TargetBlock = TargetSym.getBlock();
  103. auto &TargetSec = TargetBlock.getSection();
  104. orc::ExecutorAddr SecAddress(~uint64_t(0));
  105. for (auto *B : TargetSec.blocks())
  106. if (B->getAddress() < SecAddress)
  107. SecAddress = B->getAddress();
  108. orc::ExecutorAddrDiff SecDelta = TargetSym.getAddress() - SecAddress;
  109. OS << TargetSym.getAddress() << " (section " << TargetSec.getName();
  110. if (SecDelta)
  111. OS << " + " << formatv("{0:x}", SecDelta);
  112. OS << " / block " << TargetBlock.getAddress();
  113. if (TargetSym.getOffset())
  114. OS << " + " << formatv("{0:x}", TargetSym.getOffset());
  115. OS << ")";
  116. }
  117. if (E.getAddend() != 0)
  118. OS << " + " << E.getAddend();
  119. }
  120. Section::~Section() {
  121. for (auto *Sym : Symbols)
  122. Sym->~Symbol();
  123. for (auto *B : Blocks)
  124. B->~Block();
  125. }
  126. Block &LinkGraph::splitBlock(Block &B, size_t SplitIndex,
  127. SplitBlockCache *Cache) {
  128. assert(SplitIndex > 0 && "splitBlock can not be called with SplitIndex == 0");
  129. // If the split point covers all of B then just return B.
  130. if (SplitIndex == B.getSize())
  131. return B;
  132. assert(SplitIndex < B.getSize() && "SplitIndex out of range");
  133. // Create the new block covering [ 0, SplitIndex ).
  134. auto &NewBlock =
  135. B.isZeroFill()
  136. ? createZeroFillBlock(B.getSection(), SplitIndex, B.getAddress(),
  137. B.getAlignment(), B.getAlignmentOffset())
  138. : createContentBlock(
  139. B.getSection(), B.getContent().slice(0, SplitIndex),
  140. B.getAddress(), B.getAlignment(), B.getAlignmentOffset());
  141. // Modify B to cover [ SplitIndex, B.size() ).
  142. B.setAddress(B.getAddress() + SplitIndex);
  143. B.setContent(B.getContent().slice(SplitIndex));
  144. B.setAlignmentOffset((B.getAlignmentOffset() + SplitIndex) %
  145. B.getAlignment());
  146. // Handle edge transfer/update.
  147. {
  148. // Copy edges to NewBlock (recording their iterators so that we can remove
  149. // them from B), and update of Edges remaining on B.
  150. std::vector<Block::edge_iterator> EdgesToRemove;
  151. for (auto I = B.edges().begin(); I != B.edges().end();) {
  152. if (I->getOffset() < SplitIndex) {
  153. NewBlock.addEdge(*I);
  154. I = B.removeEdge(I);
  155. } else {
  156. I->setOffset(I->getOffset() - SplitIndex);
  157. ++I;
  158. }
  159. }
  160. }
  161. // Handle symbol transfer/update.
  162. {
  163. // Initialize the symbols cache if necessary.
  164. SplitBlockCache LocalBlockSymbolsCache;
  165. if (!Cache)
  166. Cache = &LocalBlockSymbolsCache;
  167. if (*Cache == std::nullopt) {
  168. *Cache = SplitBlockCache::value_type();
  169. for (auto *Sym : B.getSection().symbols())
  170. if (&Sym->getBlock() == &B)
  171. (*Cache)->push_back(Sym);
  172. llvm::sort(**Cache, [](const Symbol *LHS, const Symbol *RHS) {
  173. return LHS->getOffset() > RHS->getOffset();
  174. });
  175. }
  176. auto &BlockSymbols = **Cache;
  177. // Transfer all symbols with offset less than SplitIndex to NewBlock.
  178. while (!BlockSymbols.empty() &&
  179. BlockSymbols.back()->getOffset() < SplitIndex) {
  180. auto *Sym = BlockSymbols.back();
  181. // If the symbol extends beyond the split, update the size to be within
  182. // the new block.
  183. if (Sym->getOffset() + Sym->getSize() > SplitIndex)
  184. Sym->setSize(SplitIndex - Sym->getOffset());
  185. Sym->setBlock(NewBlock);
  186. BlockSymbols.pop_back();
  187. }
  188. // Update offsets for all remaining symbols in B.
  189. for (auto *Sym : BlockSymbols)
  190. Sym->setOffset(Sym->getOffset() - SplitIndex);
  191. }
  192. return NewBlock;
  193. }
  194. void LinkGraph::dump(raw_ostream &OS) {
  195. DenseMap<Block *, std::vector<Symbol *>> BlockSymbols;
  196. // Map from blocks to the symbols pointing at them.
  197. for (auto *Sym : defined_symbols())
  198. BlockSymbols[&Sym->getBlock()].push_back(Sym);
  199. // For each block, sort its symbols by something approximating
  200. // relevance.
  201. for (auto &KV : BlockSymbols)
  202. llvm::sort(KV.second, [](const Symbol *LHS, const Symbol *RHS) {
  203. if (LHS->getOffset() != RHS->getOffset())
  204. return LHS->getOffset() < RHS->getOffset();
  205. if (LHS->getLinkage() != RHS->getLinkage())
  206. return LHS->getLinkage() < RHS->getLinkage();
  207. if (LHS->getScope() != RHS->getScope())
  208. return LHS->getScope() < RHS->getScope();
  209. if (LHS->hasName()) {
  210. if (!RHS->hasName())
  211. return true;
  212. return LHS->getName() < RHS->getName();
  213. }
  214. return false;
  215. });
  216. for (auto &Sec : sections()) {
  217. OS << "section " << Sec.getName() << ":\n\n";
  218. std::vector<Block *> SortedBlocks;
  219. llvm::copy(Sec.blocks(), std::back_inserter(SortedBlocks));
  220. llvm::sort(SortedBlocks, [](const Block *LHS, const Block *RHS) {
  221. return LHS->getAddress() < RHS->getAddress();
  222. });
  223. for (auto *B : SortedBlocks) {
  224. OS << " block " << B->getAddress()
  225. << " size = " << formatv("{0:x8}", B->getSize())
  226. << ", align = " << B->getAlignment()
  227. << ", alignment-offset = " << B->getAlignmentOffset();
  228. if (B->isZeroFill())
  229. OS << ", zero-fill";
  230. OS << "\n";
  231. auto BlockSymsI = BlockSymbols.find(B);
  232. if (BlockSymsI != BlockSymbols.end()) {
  233. OS << " symbols:\n";
  234. auto &Syms = BlockSymsI->second;
  235. for (auto *Sym : Syms)
  236. OS << " " << *Sym << "\n";
  237. } else
  238. OS << " no symbols\n";
  239. if (!B->edges_empty()) {
  240. OS << " edges:\n";
  241. std::vector<Edge> SortedEdges;
  242. llvm::copy(B->edges(), std::back_inserter(SortedEdges));
  243. llvm::sort(SortedEdges, [](const Edge &LHS, const Edge &RHS) {
  244. return LHS.getOffset() < RHS.getOffset();
  245. });
  246. for (auto &E : SortedEdges) {
  247. OS << " " << B->getFixupAddress(E) << " (block + "
  248. << formatv("{0:x8}", E.getOffset()) << "), addend = ";
  249. if (E.getAddend() >= 0)
  250. OS << formatv("+{0:x8}", E.getAddend());
  251. else
  252. OS << formatv("-{0:x8}", -E.getAddend());
  253. OS << ", kind = " << getEdgeKindName(E.getKind()) << ", target = ";
  254. if (E.getTarget().hasName())
  255. OS << E.getTarget().getName();
  256. else
  257. OS << "addressable@"
  258. << formatv("{0:x16}", E.getTarget().getAddress()) << "+"
  259. << formatv("{0:x8}", E.getTarget().getOffset());
  260. OS << "\n";
  261. }
  262. } else
  263. OS << " no edges\n";
  264. OS << "\n";
  265. }
  266. }
  267. OS << "Absolute symbols:\n";
  268. if (!absolute_symbols().empty()) {
  269. for (auto *Sym : absolute_symbols())
  270. OS << " " << Sym->getAddress() << ": " << *Sym << "\n";
  271. } else
  272. OS << " none\n";
  273. OS << "\nExternal symbols:\n";
  274. if (!external_symbols().empty()) {
  275. for (auto *Sym : external_symbols())
  276. OS << " " << Sym->getAddress() << ": " << *Sym << "\n";
  277. } else
  278. OS << " none\n";
  279. }
  280. raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF) {
  281. switch (LF) {
  282. case SymbolLookupFlags::RequiredSymbol:
  283. return OS << "RequiredSymbol";
  284. case SymbolLookupFlags::WeaklyReferencedSymbol:
  285. return OS << "WeaklyReferencedSymbol";
  286. }
  287. llvm_unreachable("Unrecognized lookup flags");
  288. }
  289. void JITLinkAsyncLookupContinuation::anchor() {}
  290. JITLinkContext::~JITLinkContext() = default;
  291. bool JITLinkContext::shouldAddDefaultTargetPasses(const Triple &TT) const {
  292. return true;
  293. }
  294. LinkGraphPassFunction JITLinkContext::getMarkLivePass(const Triple &TT) const {
  295. return LinkGraphPassFunction();
  296. }
  297. Error JITLinkContext::modifyPassConfig(LinkGraph &G,
  298. PassConfiguration &Config) {
  299. return Error::success();
  300. }
  301. Error markAllSymbolsLive(LinkGraph &G) {
  302. for (auto *Sym : G.defined_symbols())
  303. Sym->setLive(true);
  304. return Error::success();
  305. }
  306. Error makeTargetOutOfRangeError(const LinkGraph &G, const Block &B,
  307. const Edge &E) {
  308. std::string ErrMsg;
  309. {
  310. raw_string_ostream ErrStream(ErrMsg);
  311. Section &Sec = B.getSection();
  312. ErrStream << "In graph " << G.getName() << ", section " << Sec.getName()
  313. << ": relocation target ";
  314. if (E.getTarget().hasName()) {
  315. ErrStream << "\"" << E.getTarget().getName() << "\"";
  316. } else
  317. ErrStream << E.getTarget().getBlock().getSection().getName() << " + "
  318. << formatv("{0:x}", E.getOffset());
  319. ErrStream << " at address " << formatv("{0:x}", E.getTarget().getAddress())
  320. << " is out of range of " << G.getEdgeKindName(E.getKind())
  321. << " fixup at " << formatv("{0:x}", B.getFixupAddress(E)) << " (";
  322. Symbol *BestSymbolForBlock = nullptr;
  323. for (auto *Sym : Sec.symbols())
  324. if (&Sym->getBlock() == &B && Sym->hasName() && Sym->getOffset() == 0 &&
  325. (!BestSymbolForBlock ||
  326. Sym->getScope() < BestSymbolForBlock->getScope() ||
  327. Sym->getLinkage() < BestSymbolForBlock->getLinkage()))
  328. BestSymbolForBlock = Sym;
  329. if (BestSymbolForBlock)
  330. ErrStream << BestSymbolForBlock->getName() << ", ";
  331. else
  332. ErrStream << "<anonymous block> @ ";
  333. ErrStream << formatv("{0:x}", B.getAddress()) << " + "
  334. << formatv("{0:x}", E.getOffset()) << ")";
  335. }
  336. return make_error<JITLinkError>(std::move(ErrMsg));
  337. }
  338. Error makeAlignmentError(llvm::orc::ExecutorAddr Loc, uint64_t Value, int N,
  339. const Edge &E) {
  340. return make_error<JITLinkError>("0x" + llvm::utohexstr(Loc.getValue()) +
  341. " improper alignment for relocation " +
  342. formatv("{0:d}", E.getKind()) + ": 0x" +
  343. llvm::utohexstr(Value) +
  344. " is not aligned to " + Twine(N) + " bytes");
  345. }
  346. Expected<std::unique_ptr<LinkGraph>>
  347. createLinkGraphFromObject(MemoryBufferRef ObjectBuffer) {
  348. auto Magic = identify_magic(ObjectBuffer.getBuffer());
  349. switch (Magic) {
  350. case file_magic::macho_object:
  351. return createLinkGraphFromMachOObject(ObjectBuffer);
  352. case file_magic::elf_relocatable:
  353. return createLinkGraphFromELFObject(ObjectBuffer);
  354. case file_magic::coff_object:
  355. return createLinkGraphFromCOFFObject(ObjectBuffer);
  356. default:
  357. return make_error<JITLinkError>("Unsupported file format");
  358. };
  359. }
  360. void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx) {
  361. switch (G->getTargetTriple().getObjectFormat()) {
  362. case Triple::MachO:
  363. return link_MachO(std::move(G), std::move(Ctx));
  364. case Triple::ELF:
  365. return link_ELF(std::move(G), std::move(Ctx));
  366. case Triple::COFF:
  367. return link_COFF(std::move(G), std::move(Ctx));
  368. default:
  369. Ctx->notifyFailed(make_error<JITLinkError>("Unsupported object format"));
  370. };
  371. }
  372. } // end namespace jitlink
  373. } // end namespace llvm