RuntimeDyld.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
  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. // Implementation of the MC-JIT runtime dynamic linker.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ExecutionEngine/RuntimeDyld.h"
  13. #include "RuntimeDyldCOFF.h"
  14. #include "RuntimeDyldELF.h"
  15. #include "RuntimeDyldImpl.h"
  16. #include "RuntimeDyldMachO.h"
  17. #include "llvm/Object/COFF.h"
  18. #include "llvm/Object/ELFObjectFile.h"
  19. #include "llvm/Support/Alignment.h"
  20. #include "llvm/Support/MSVCErrorWorkarounds.h"
  21. #include "llvm/Support/MathExtras.h"
  22. #include <mutex>
  23. #include <future>
  24. using namespace llvm;
  25. using namespace llvm::object;
  26. #define DEBUG_TYPE "dyld"
  27. namespace {
  28. enum RuntimeDyldErrorCode {
  29. GenericRTDyldError = 1
  30. };
  31. // FIXME: This class is only here to support the transition to llvm::Error. It
  32. // will be removed once this transition is complete. Clients should prefer to
  33. // deal with the Error value directly, rather than converting to error_code.
  34. class RuntimeDyldErrorCategory : public std::error_category {
  35. public:
  36. const char *name() const noexcept override { return "runtimedyld"; }
  37. std::string message(int Condition) const override {
  38. switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
  39. case GenericRTDyldError: return "Generic RuntimeDyld error";
  40. }
  41. llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
  42. }
  43. };
  44. }
  45. char RuntimeDyldError::ID = 0;
  46. void RuntimeDyldError::log(raw_ostream &OS) const {
  47. OS << ErrMsg << "\n";
  48. }
  49. std::error_code RuntimeDyldError::convertToErrorCode() const {
  50. static RuntimeDyldErrorCategory RTDyldErrorCategory;
  51. return std::error_code(GenericRTDyldError, RTDyldErrorCategory);
  52. }
  53. // Empty out-of-line virtual destructor as the key function.
  54. RuntimeDyldImpl::~RuntimeDyldImpl() = default;
  55. // Pin LoadedObjectInfo's vtables to this file.
  56. void RuntimeDyld::LoadedObjectInfo::anchor() {}
  57. namespace llvm {
  58. void RuntimeDyldImpl::registerEHFrames() {}
  59. void RuntimeDyldImpl::deregisterEHFrames() {
  60. MemMgr.deregisterEHFrames();
  61. }
  62. #ifndef NDEBUG
  63. static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
  64. dbgs() << "----- Contents of section " << S.getName() << " " << State
  65. << " -----";
  66. if (S.getAddress() == nullptr) {
  67. dbgs() << "\n <section not emitted>\n";
  68. return;
  69. }
  70. const unsigned ColsPerRow = 16;
  71. uint8_t *DataAddr = S.getAddress();
  72. uint64_t LoadAddr = S.getLoadAddress();
  73. unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
  74. unsigned BytesRemaining = S.getSize();
  75. if (StartPadding) {
  76. dbgs() << "\n" << format("0x%016" PRIx64,
  77. LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
  78. while (StartPadding--)
  79. dbgs() << " ";
  80. }
  81. while (BytesRemaining > 0) {
  82. if ((LoadAddr & (ColsPerRow - 1)) == 0)
  83. dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
  84. dbgs() << " " << format("%02x", *DataAddr);
  85. ++DataAddr;
  86. ++LoadAddr;
  87. --BytesRemaining;
  88. }
  89. dbgs() << "\n";
  90. }
  91. #endif
  92. // Resolve the relocations for all symbols we currently know about.
  93. void RuntimeDyldImpl::resolveRelocations() {
  94. std::lock_guard<sys::Mutex> locked(lock);
  95. // Print out the sections prior to relocation.
  96. LLVM_DEBUG({
  97. for (SectionEntry &S : Sections)
  98. dumpSectionMemory(S, "before relocations");
  99. });
  100. // First, resolve relocations associated with external symbols.
  101. if (auto Err = resolveExternalSymbols()) {
  102. HasError = true;
  103. ErrorStr = toString(std::move(Err));
  104. }
  105. resolveLocalRelocations();
  106. // Print out sections after relocation.
  107. LLVM_DEBUG({
  108. for (SectionEntry &S : Sections)
  109. dumpSectionMemory(S, "after relocations");
  110. });
  111. }
  112. void RuntimeDyldImpl::resolveLocalRelocations() {
  113. // Iterate over all outstanding relocations
  114. for (const auto &Rel : Relocations) {
  115. // The Section here (Sections[i]) refers to the section in which the
  116. // symbol for the relocation is located. The SectionID in the relocation
  117. // entry provides the section to which the relocation will be applied.
  118. unsigned Idx = Rel.first;
  119. uint64_t Addr = getSectionLoadAddress(Idx);
  120. LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
  121. << format("%p", (uintptr_t)Addr) << "\n");
  122. resolveRelocationList(Rel.second, Addr);
  123. }
  124. Relocations.clear();
  125. }
  126. void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
  127. uint64_t TargetAddress) {
  128. std::lock_guard<sys::Mutex> locked(lock);
  129. for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
  130. if (Sections[i].getAddress() == LocalAddress) {
  131. reassignSectionAddress(i, TargetAddress);
  132. return;
  133. }
  134. }
  135. llvm_unreachable("Attempting to remap address of unknown section!");
  136. }
  137. static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
  138. uint64_t &Result) {
  139. Expected<uint64_t> AddressOrErr = Sym.getAddress();
  140. if (!AddressOrErr)
  141. return AddressOrErr.takeError();
  142. Result = *AddressOrErr - Sec.getAddress();
  143. return Error::success();
  144. }
  145. Expected<RuntimeDyldImpl::ObjSectionToIDMap>
  146. RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
  147. std::lock_guard<sys::Mutex> locked(lock);
  148. // Save information about our target
  149. Arch = (Triple::ArchType)Obj.getArch();
  150. IsTargetLittleEndian = Obj.isLittleEndian();
  151. setMipsABI(Obj);
  152. // Compute the memory size required to load all sections to be loaded
  153. // and pass this information to the memory manager
  154. if (MemMgr.needsToReserveAllocationSpace()) {
  155. uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
  156. Align CodeAlign, RODataAlign, RWDataAlign;
  157. if (auto Err = computeTotalAllocSize(Obj, CodeSize, CodeAlign, RODataSize,
  158. RODataAlign, RWDataSize, RWDataAlign))
  159. return std::move(Err);
  160. MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
  161. RWDataSize, RWDataAlign);
  162. }
  163. // Used sections from the object file
  164. ObjSectionToIDMap LocalSections;
  165. // Common symbols requiring allocation, with their sizes and alignments
  166. CommonSymbolList CommonSymbolsToAllocate;
  167. uint64_t CommonSize = 0;
  168. uint32_t CommonAlign = 0;
  169. // First, collect all weak and common symbols. We need to know if stronger
  170. // definitions occur elsewhere.
  171. JITSymbolResolver::LookupSet ResponsibilitySet;
  172. {
  173. JITSymbolResolver::LookupSet Symbols;
  174. for (auto &Sym : Obj.symbols()) {
  175. Expected<uint32_t> FlagsOrErr = Sym.getFlags();
  176. if (!FlagsOrErr)
  177. // TODO: Test this error.
  178. return FlagsOrErr.takeError();
  179. if ((*FlagsOrErr & SymbolRef::SF_Common) ||
  180. (*FlagsOrErr & SymbolRef::SF_Weak)) {
  181. // Get symbol name.
  182. if (auto NameOrErr = Sym.getName())
  183. Symbols.insert(*NameOrErr);
  184. else
  185. return NameOrErr.takeError();
  186. }
  187. }
  188. if (auto ResultOrErr = Resolver.getResponsibilitySet(Symbols))
  189. ResponsibilitySet = std::move(*ResultOrErr);
  190. else
  191. return ResultOrErr.takeError();
  192. }
  193. // Parse symbols
  194. LLVM_DEBUG(dbgs() << "Parse symbols:\n");
  195. for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
  196. ++I) {
  197. Expected<uint32_t> FlagsOrErr = I->getFlags();
  198. if (!FlagsOrErr)
  199. // TODO: Test this error.
  200. return FlagsOrErr.takeError();
  201. // Skip undefined symbols.
  202. if (*FlagsOrErr & SymbolRef::SF_Undefined)
  203. continue;
  204. // Get the symbol type.
  205. object::SymbolRef::Type SymType;
  206. if (auto SymTypeOrErr = I->getType())
  207. SymType = *SymTypeOrErr;
  208. else
  209. return SymTypeOrErr.takeError();
  210. // Get symbol name.
  211. StringRef Name;
  212. if (auto NameOrErr = I->getName())
  213. Name = *NameOrErr;
  214. else
  215. return NameOrErr.takeError();
  216. // Compute JIT symbol flags.
  217. auto JITSymFlags = getJITSymbolFlags(*I);
  218. if (!JITSymFlags)
  219. return JITSymFlags.takeError();
  220. // If this is a weak definition, check to see if there's a strong one.
  221. // If there is, skip this symbol (we won't be providing it: the strong
  222. // definition will). If there's no strong definition, make this definition
  223. // strong.
  224. if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {
  225. // First check whether there's already a definition in this instance.
  226. if (GlobalSymbolTable.count(Name))
  227. continue;
  228. // If we're not responsible for this symbol, skip it.
  229. if (!ResponsibilitySet.count(Name))
  230. continue;
  231. // Otherwise update the flags on the symbol to make this definition
  232. // strong.
  233. if (JITSymFlags->isWeak())
  234. *JITSymFlags &= ~JITSymbolFlags::Weak;
  235. if (JITSymFlags->isCommon()) {
  236. *JITSymFlags &= ~JITSymbolFlags::Common;
  237. uint32_t Align = I->getAlignment();
  238. uint64_t Size = I->getCommonSize();
  239. if (!CommonAlign)
  240. CommonAlign = Align;
  241. CommonSize = alignTo(CommonSize, Align) + Size;
  242. CommonSymbolsToAllocate.push_back(*I);
  243. }
  244. }
  245. if (*FlagsOrErr & SymbolRef::SF_Absolute &&
  246. SymType != object::SymbolRef::ST_File) {
  247. uint64_t Addr = 0;
  248. if (auto AddrOrErr = I->getAddress())
  249. Addr = *AddrOrErr;
  250. else
  251. return AddrOrErr.takeError();
  252. unsigned SectionID = AbsoluteSymbolSection;
  253. LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
  254. << " SID: " << SectionID
  255. << " Offset: " << format("%p", (uintptr_t)Addr)
  256. << " flags: " << *FlagsOrErr << "\n");
  257. // Skip absolute symbol relocations.
  258. if (!Name.empty()) {
  259. auto Result = GlobalSymbolTable.insert_or_assign(
  260. Name, SymbolTableEntry(SectionID, Addr, *JITSymFlags));
  261. processNewSymbol(*I, Result.first->getValue());
  262. }
  263. } else if (SymType == object::SymbolRef::ST_Function ||
  264. SymType == object::SymbolRef::ST_Data ||
  265. SymType == object::SymbolRef::ST_Unknown ||
  266. SymType == object::SymbolRef::ST_Other) {
  267. section_iterator SI = Obj.section_end();
  268. if (auto SIOrErr = I->getSection())
  269. SI = *SIOrErr;
  270. else
  271. return SIOrErr.takeError();
  272. if (SI == Obj.section_end())
  273. continue;
  274. // Get symbol offset.
  275. uint64_t SectOffset;
  276. if (auto Err = getOffset(*I, *SI, SectOffset))
  277. return std::move(Err);
  278. bool IsCode = SI->isText();
  279. unsigned SectionID;
  280. if (auto SectionIDOrErr =
  281. findOrEmitSection(Obj, *SI, IsCode, LocalSections))
  282. SectionID = *SectionIDOrErr;
  283. else
  284. return SectionIDOrErr.takeError();
  285. LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
  286. << " SID: " << SectionID
  287. << " Offset: " << format("%p", (uintptr_t)SectOffset)
  288. << " flags: " << *FlagsOrErr << "\n");
  289. // Skip absolute symbol relocations.
  290. if (!Name.empty()) {
  291. auto Result = GlobalSymbolTable.insert_or_assign(
  292. Name, SymbolTableEntry(SectionID, SectOffset, *JITSymFlags));
  293. processNewSymbol(*I, Result.first->getValue());
  294. }
  295. }
  296. }
  297. // Allocate common symbols
  298. if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,
  299. CommonAlign))
  300. return std::move(Err);
  301. // Parse and process relocations
  302. LLVM_DEBUG(dbgs() << "Parse relocations:\n");
  303. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  304. SI != SE; ++SI) {
  305. StubMap Stubs;
  306. Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
  307. if (!RelSecOrErr)
  308. return RelSecOrErr.takeError();
  309. section_iterator RelocatedSection = *RelSecOrErr;
  310. if (RelocatedSection == SE)
  311. continue;
  312. relocation_iterator I = SI->relocation_begin();
  313. relocation_iterator E = SI->relocation_end();
  314. if (I == E && !ProcessAllSections)
  315. continue;
  316. bool IsCode = RelocatedSection->isText();
  317. unsigned SectionID = 0;
  318. if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
  319. LocalSections))
  320. SectionID = *SectionIDOrErr;
  321. else
  322. return SectionIDOrErr.takeError();
  323. LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
  324. for (; I != E;)
  325. if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
  326. I = *IOrErr;
  327. else
  328. return IOrErr.takeError();
  329. // If there is a NotifyStubEmitted callback set, call it to register any
  330. // stubs created for this section.
  331. if (NotifyStubEmitted) {
  332. StringRef FileName = Obj.getFileName();
  333. StringRef SectionName = Sections[SectionID].getName();
  334. for (auto &KV : Stubs) {
  335. auto &VR = KV.first;
  336. uint64_t StubAddr = KV.second;
  337. // If this is a named stub, just call NotifyStubEmitted.
  338. if (VR.SymbolName) {
  339. NotifyStubEmitted(FileName, SectionName, VR.SymbolName, SectionID,
  340. StubAddr);
  341. continue;
  342. }
  343. // Otherwise we will have to try a reverse lookup on the globla symbol table.
  344. for (auto &GSTMapEntry : GlobalSymbolTable) {
  345. StringRef SymbolName = GSTMapEntry.first();
  346. auto &GSTEntry = GSTMapEntry.second;
  347. if (GSTEntry.getSectionID() == VR.SectionID &&
  348. GSTEntry.getOffset() == VR.Offset) {
  349. NotifyStubEmitted(FileName, SectionName, SymbolName, SectionID,
  350. StubAddr);
  351. break;
  352. }
  353. }
  354. }
  355. }
  356. }
  357. // Process remaining sections
  358. if (ProcessAllSections) {
  359. LLVM_DEBUG(dbgs() << "Process remaining sections:\n");
  360. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  361. SI != SE; ++SI) {
  362. /* Ignore already loaded sections */
  363. if (LocalSections.find(*SI) != LocalSections.end())
  364. continue;
  365. bool IsCode = SI->isText();
  366. if (auto SectionIDOrErr =
  367. findOrEmitSection(Obj, *SI, IsCode, LocalSections))
  368. LLVM_DEBUG(dbgs() << "\tSectionID: " << (*SectionIDOrErr) << "\n");
  369. else
  370. return SectionIDOrErr.takeError();
  371. }
  372. }
  373. // Give the subclasses a chance to tie-up any loose ends.
  374. if (auto Err = finalizeLoad(Obj, LocalSections))
  375. return std::move(Err);
  376. // for (auto E : LocalSections)
  377. // llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
  378. return LocalSections;
  379. }
  380. // A helper method for computeTotalAllocSize.
  381. // Computes the memory size required to allocate sections with the given sizes,
  382. // assuming that all sections are allocated with the given alignment
  383. static uint64_t
  384. computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
  385. Align Alignment) {
  386. uint64_t TotalSize = 0;
  387. for (uint64_t SectionSize : SectionSizes)
  388. TotalSize += alignTo(SectionSize, Alignment);
  389. return TotalSize;
  390. }
  391. static bool isRequiredForExecution(const SectionRef Section) {
  392. const ObjectFile *Obj = Section.getObject();
  393. if (isa<object::ELFObjectFileBase>(Obj))
  394. return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
  395. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
  396. const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
  397. // Avoid loading zero-sized COFF sections.
  398. // In PE files, VirtualSize gives the section size, and SizeOfRawData
  399. // may be zero for sections with content. In Obj files, SizeOfRawData
  400. // gives the section size, and VirtualSize is always zero. Hence
  401. // the need to check for both cases below.
  402. bool HasContent =
  403. (CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);
  404. bool IsDiscardable =
  405. CoffSection->Characteristics &
  406. (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
  407. return HasContent && !IsDiscardable;
  408. }
  409. assert(isa<MachOObjectFile>(Obj));
  410. return true;
  411. }
  412. static bool isReadOnlyData(const SectionRef Section) {
  413. const ObjectFile *Obj = Section.getObject();
  414. if (isa<object::ELFObjectFileBase>(Obj))
  415. return !(ELFSectionRef(Section).getFlags() &
  416. (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
  417. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
  418. return ((COFFObj->getCOFFSection(Section)->Characteristics &
  419. (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
  420. | COFF::IMAGE_SCN_MEM_READ
  421. | COFF::IMAGE_SCN_MEM_WRITE))
  422. ==
  423. (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
  424. | COFF::IMAGE_SCN_MEM_READ));
  425. assert(isa<MachOObjectFile>(Obj));
  426. return false;
  427. }
  428. static bool isZeroInit(const SectionRef Section) {
  429. const ObjectFile *Obj = Section.getObject();
  430. if (isa<object::ELFObjectFileBase>(Obj))
  431. return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
  432. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
  433. return COFFObj->getCOFFSection(Section)->Characteristics &
  434. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
  435. auto *MachO = cast<MachOObjectFile>(Obj);
  436. unsigned SectionType = MachO->getSectionType(Section);
  437. return SectionType == MachO::S_ZEROFILL ||
  438. SectionType == MachO::S_GB_ZEROFILL;
  439. }
  440. static bool isTLS(const SectionRef Section) {
  441. const ObjectFile *Obj = Section.getObject();
  442. if (isa<object::ELFObjectFileBase>(Obj))
  443. return ELFSectionRef(Section).getFlags() & ELF::SHF_TLS;
  444. return false;
  445. }
  446. // Compute an upper bound of the memory size that is required to load all
  447. // sections
  448. Error RuntimeDyldImpl::computeTotalAllocSize(
  449. const ObjectFile &Obj, uint64_t &CodeSize, Align &CodeAlign,
  450. uint64_t &RODataSize, Align &RODataAlign, uint64_t &RWDataSize,
  451. Align &RWDataAlign) {
  452. // Compute the size of all sections required for execution
  453. std::vector<uint64_t> CodeSectionSizes;
  454. std::vector<uint64_t> ROSectionSizes;
  455. std::vector<uint64_t> RWSectionSizes;
  456. // Collect sizes of all sections to be loaded;
  457. // also determine the max alignment of all sections
  458. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  459. SI != SE; ++SI) {
  460. const SectionRef &Section = *SI;
  461. bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
  462. // Consider only the sections that are required to be loaded for execution
  463. if (IsRequired) {
  464. uint64_t DataSize = Section.getSize();
  465. Align Alignment = Section.getAlignment();
  466. bool IsCode = Section.isText();
  467. bool IsReadOnly = isReadOnlyData(Section);
  468. bool IsTLS = isTLS(Section);
  469. Expected<StringRef> NameOrErr = Section.getName();
  470. if (!NameOrErr)
  471. return NameOrErr.takeError();
  472. StringRef Name = *NameOrErr;
  473. uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
  474. uint64_t PaddingSize = 0;
  475. if (Name == ".eh_frame")
  476. PaddingSize += 4;
  477. if (StubBufSize != 0)
  478. PaddingSize += getStubAlignment().value() - 1;
  479. uint64_t SectionSize = DataSize + PaddingSize + StubBufSize;
  480. // The .eh_frame section (at least on Linux) needs an extra four bytes
  481. // padded
  482. // with zeroes added at the end. For MachO objects, this section has a
  483. // slightly different name, so this won't have any effect for MachO
  484. // objects.
  485. if (Name == ".eh_frame")
  486. SectionSize += 4;
  487. if (!SectionSize)
  488. SectionSize = 1;
  489. if (IsCode) {
  490. CodeAlign = std::max(CodeAlign, Alignment);
  491. CodeSectionSizes.push_back(SectionSize);
  492. } else if (IsReadOnly) {
  493. RODataAlign = std::max(RODataAlign, Alignment);
  494. ROSectionSizes.push_back(SectionSize);
  495. } else if (!IsTLS) {
  496. RWDataAlign = std::max(RWDataAlign, Alignment);
  497. RWSectionSizes.push_back(SectionSize);
  498. }
  499. }
  500. }
  501. // Compute Global Offset Table size. If it is not zero we
  502. // also update alignment, which is equal to a size of a
  503. // single GOT entry.
  504. if (unsigned GotSize = computeGOTSize(Obj)) {
  505. RWSectionSizes.push_back(GotSize);
  506. RWDataAlign = std::max(RWDataAlign, Align(getGOTEntrySize()));
  507. }
  508. // Compute the size of all common symbols
  509. uint64_t CommonSize = 0;
  510. Align CommonAlign;
  511. for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
  512. ++I) {
  513. Expected<uint32_t> FlagsOrErr = I->getFlags();
  514. if (!FlagsOrErr)
  515. // TODO: Test this error.
  516. return FlagsOrErr.takeError();
  517. if (*FlagsOrErr & SymbolRef::SF_Common) {
  518. // Add the common symbols to a list. We'll allocate them all below.
  519. uint64_t Size = I->getCommonSize();
  520. Align Alignment = Align(I->getAlignment());
  521. // If this is the first common symbol, use its alignment as the alignment
  522. // for the common symbols section.
  523. if (CommonSize == 0)
  524. CommonAlign = Alignment;
  525. CommonSize = alignTo(CommonSize, Alignment) + Size;
  526. }
  527. }
  528. if (CommonSize != 0) {
  529. RWSectionSizes.push_back(CommonSize);
  530. RWDataAlign = std::max(RWDataAlign, CommonAlign);
  531. }
  532. if (!CodeSectionSizes.empty()) {
  533. // Add 64 bytes for a potential IFunc resolver stub
  534. CodeSectionSizes.push_back(64);
  535. }
  536. // Compute the required allocation space for each different type of sections
  537. // (code, read-only data, read-write data) assuming that all sections are
  538. // allocated with the max alignment. Note that we cannot compute with the
  539. // individual alignments of the sections, because then the required size
  540. // depends on the order, in which the sections are allocated.
  541. CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
  542. RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
  543. RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
  544. return Error::success();
  545. }
  546. // compute GOT size
  547. unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {
  548. size_t GotEntrySize = getGOTEntrySize();
  549. if (!GotEntrySize)
  550. return 0;
  551. size_t GotSize = 0;
  552. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  553. SI != SE; ++SI) {
  554. for (const RelocationRef &Reloc : SI->relocations())
  555. if (relocationNeedsGot(Reloc))
  556. GotSize += GotEntrySize;
  557. }
  558. return GotSize;
  559. }
  560. // compute stub buffer size for the given section
  561. unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
  562. const SectionRef &Section) {
  563. if (!MemMgr.allowStubAllocation()) {
  564. return 0;
  565. }
  566. unsigned StubSize = getMaxStubSize();
  567. if (StubSize == 0) {
  568. return 0;
  569. }
  570. // FIXME: this is an inefficient way to handle this. We should computed the
  571. // necessary section allocation size in loadObject by walking all the sections
  572. // once.
  573. unsigned StubBufSize = 0;
  574. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  575. SI != SE; ++SI) {
  576. Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
  577. if (!RelSecOrErr)
  578. report_fatal_error(Twine(toString(RelSecOrErr.takeError())));
  579. section_iterator RelSecI = *RelSecOrErr;
  580. if (!(RelSecI == Section))
  581. continue;
  582. for (const RelocationRef &Reloc : SI->relocations())
  583. if (relocationNeedsStub(Reloc))
  584. StubBufSize += StubSize;
  585. }
  586. // Get section data size and alignment
  587. uint64_t DataSize = Section.getSize();
  588. Align Alignment = Section.getAlignment();
  589. // Add stubbuf size alignment
  590. Align StubAlignment = getStubAlignment();
  591. Align EndAlignment = commonAlignment(Alignment, DataSize);
  592. if (StubAlignment > EndAlignment)
  593. StubBufSize += StubAlignment.value() - EndAlignment.value();
  594. return StubBufSize;
  595. }
  596. uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
  597. unsigned Size) const {
  598. uint64_t Result = 0;
  599. if (IsTargetLittleEndian) {
  600. Src += Size - 1;
  601. while (Size--)
  602. Result = (Result << 8) | *Src--;
  603. } else
  604. while (Size--)
  605. Result = (Result << 8) | *Src++;
  606. return Result;
  607. }
  608. void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
  609. unsigned Size) const {
  610. if (IsTargetLittleEndian) {
  611. while (Size--) {
  612. *Dst++ = Value & 0xFF;
  613. Value >>= 8;
  614. }
  615. } else {
  616. Dst += Size - 1;
  617. while (Size--) {
  618. *Dst-- = Value & 0xFF;
  619. Value >>= 8;
  620. }
  621. }
  622. }
  623. Expected<JITSymbolFlags>
  624. RuntimeDyldImpl::getJITSymbolFlags(const SymbolRef &SR) {
  625. return JITSymbolFlags::fromObjectSymbol(SR);
  626. }
  627. Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
  628. CommonSymbolList &SymbolsToAllocate,
  629. uint64_t CommonSize,
  630. uint32_t CommonAlign) {
  631. if (SymbolsToAllocate.empty())
  632. return Error::success();
  633. // Allocate memory for the section
  634. unsigned SectionID = Sections.size();
  635. uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
  636. "<common symbols>", false);
  637. if (!Addr)
  638. report_fatal_error("Unable to allocate memory for common symbols!");
  639. uint64_t Offset = 0;
  640. Sections.push_back(
  641. SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
  642. memset(Addr, 0, CommonSize);
  643. LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
  644. << " new addr: " << format("%p", Addr)
  645. << " DataSize: " << CommonSize << "\n");
  646. // Assign the address of each symbol
  647. for (auto &Sym : SymbolsToAllocate) {
  648. uint32_t Alignment = Sym.getAlignment();
  649. uint64_t Size = Sym.getCommonSize();
  650. StringRef Name;
  651. if (auto NameOrErr = Sym.getName())
  652. Name = *NameOrErr;
  653. else
  654. return NameOrErr.takeError();
  655. if (Alignment) {
  656. // This symbol has an alignment requirement.
  657. uint64_t AlignOffset =
  658. offsetToAlignment((uint64_t)Addr, Align(Alignment));
  659. Addr += AlignOffset;
  660. Offset += AlignOffset;
  661. }
  662. auto JITSymFlags = getJITSymbolFlags(Sym);
  663. if (!JITSymFlags)
  664. return JITSymFlags.takeError();
  665. LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
  666. << format("%p", Addr) << "\n");
  667. if (!Name.empty()) // Skip absolute symbol relocations.
  668. GlobalSymbolTable[Name] =
  669. SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));
  670. Offset += Size;
  671. Addr += Size;
  672. }
  673. return Error::success();
  674. }
  675. Expected<unsigned>
  676. RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
  677. const SectionRef &Section,
  678. bool IsCode) {
  679. StringRef data;
  680. Align Alignment = Section.getAlignment();
  681. unsigned PaddingSize = 0;
  682. unsigned StubBufSize = 0;
  683. bool IsRequired = isRequiredForExecution(Section);
  684. bool IsVirtual = Section.isVirtual();
  685. bool IsZeroInit = isZeroInit(Section);
  686. bool IsReadOnly = isReadOnlyData(Section);
  687. bool IsTLS = isTLS(Section);
  688. uint64_t DataSize = Section.getSize();
  689. Expected<StringRef> NameOrErr = Section.getName();
  690. if (!NameOrErr)
  691. return NameOrErr.takeError();
  692. StringRef Name = *NameOrErr;
  693. StubBufSize = computeSectionStubBufSize(Obj, Section);
  694. // The .eh_frame section (at least on Linux) needs an extra four bytes padded
  695. // with zeroes added at the end. For MachO objects, this section has a
  696. // slightly different name, so this won't have any effect for MachO objects.
  697. if (Name == ".eh_frame")
  698. PaddingSize = 4;
  699. uintptr_t Allocate;
  700. unsigned SectionID = Sections.size();
  701. uint8_t *Addr;
  702. uint64_t LoadAddress = 0;
  703. const char *pData = nullptr;
  704. // If this section contains any bits (i.e. isn't a virtual or bss section),
  705. // grab a reference to them.
  706. if (!IsVirtual && !IsZeroInit) {
  707. // In either case, set the location of the unrelocated section in memory,
  708. // since we still process relocations for it even if we're not applying them.
  709. if (Expected<StringRef> E = Section.getContents())
  710. data = *E;
  711. else
  712. return E.takeError();
  713. pData = data.data();
  714. }
  715. // If there are any stubs then the section alignment needs to be at least as
  716. // high as stub alignment or padding calculations may by incorrect when the
  717. // section is remapped.
  718. if (StubBufSize != 0) {
  719. Alignment = std::max(Alignment, getStubAlignment());
  720. PaddingSize += getStubAlignment().value() - 1;
  721. }
  722. // Some sections, such as debug info, don't need to be loaded for execution.
  723. // Process those only if explicitly requested.
  724. if (IsRequired || ProcessAllSections) {
  725. Allocate = DataSize + PaddingSize + StubBufSize;
  726. if (!Allocate)
  727. Allocate = 1;
  728. if (IsTLS) {
  729. auto TLSSection = MemMgr.allocateTLSSection(Allocate, Alignment.value(),
  730. SectionID, Name);
  731. Addr = TLSSection.InitializationImage;
  732. LoadAddress = TLSSection.Offset;
  733. } else if (IsCode) {
  734. Addr = MemMgr.allocateCodeSection(Allocate, Alignment.value(), SectionID,
  735. Name);
  736. } else {
  737. Addr = MemMgr.allocateDataSection(Allocate, Alignment.value(), SectionID,
  738. Name, IsReadOnly);
  739. }
  740. if (!Addr)
  741. report_fatal_error("Unable to allocate section memory!");
  742. // Zero-initialize or copy the data from the image
  743. if (IsZeroInit || IsVirtual)
  744. memset(Addr, 0, DataSize);
  745. else
  746. memcpy(Addr, pData, DataSize);
  747. // Fill in any extra bytes we allocated for padding
  748. if (PaddingSize != 0) {
  749. memset(Addr + DataSize, 0, PaddingSize);
  750. // Update the DataSize variable to include padding.
  751. DataSize += PaddingSize;
  752. // Align DataSize to stub alignment if we have any stubs (PaddingSize will
  753. // have been increased above to account for this).
  754. if (StubBufSize > 0)
  755. DataSize &= -(uint64_t)getStubAlignment().value();
  756. }
  757. LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "
  758. << Name << " obj addr: " << format("%p", pData)
  759. << " new addr: " << format("%p", Addr) << " DataSize: "
  760. << DataSize << " StubBufSize: " << StubBufSize
  761. << " Allocate: " << Allocate << "\n");
  762. } else {
  763. // Even if we didn't load the section, we need to record an entry for it
  764. // to handle later processing (and by 'handle' I mean don't do anything
  765. // with these sections).
  766. Allocate = 0;
  767. Addr = nullptr;
  768. LLVM_DEBUG(
  769. dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
  770. << " obj addr: " << format("%p", data.data()) << " new addr: 0"
  771. << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
  772. << " Allocate: " << Allocate << "\n");
  773. }
  774. Sections.push_back(
  775. SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
  776. // The load address of a TLS section is not equal to the address of its
  777. // initialization image
  778. if (IsTLS)
  779. Sections.back().setLoadAddress(LoadAddress);
  780. // Debug info sections are linked as if their load address was zero
  781. if (!IsRequired)
  782. Sections.back().setLoadAddress(0);
  783. return SectionID;
  784. }
  785. Expected<unsigned>
  786. RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
  787. const SectionRef &Section,
  788. bool IsCode,
  789. ObjSectionToIDMap &LocalSections) {
  790. unsigned SectionID = 0;
  791. ObjSectionToIDMap::iterator i = LocalSections.find(Section);
  792. if (i != LocalSections.end())
  793. SectionID = i->second;
  794. else {
  795. if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
  796. SectionID = *SectionIDOrErr;
  797. else
  798. return SectionIDOrErr.takeError();
  799. LocalSections[Section] = SectionID;
  800. }
  801. return SectionID;
  802. }
  803. void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
  804. unsigned SectionID) {
  805. Relocations[SectionID].push_back(RE);
  806. }
  807. void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
  808. StringRef SymbolName) {
  809. // Relocation by symbol. If the symbol is found in the global symbol table,
  810. // create an appropriate section relocation. Otherwise, add it to
  811. // ExternalSymbolRelocations.
  812. RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
  813. if (Loc == GlobalSymbolTable.end()) {
  814. ExternalSymbolRelocations[SymbolName].push_back(RE);
  815. } else {
  816. assert(!SymbolName.empty() &&
  817. "Empty symbol should not be in GlobalSymbolTable");
  818. // Copy the RE since we want to modify its addend.
  819. RelocationEntry RECopy = RE;
  820. const auto &SymInfo = Loc->second;
  821. RECopy.Addend += SymInfo.getOffset();
  822. Relocations[SymInfo.getSectionID()].push_back(RECopy);
  823. }
  824. }
  825. uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
  826. unsigned AbiVariant) {
  827. if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be ||
  828. Arch == Triple::aarch64_32) {
  829. // This stub has to be able to access the full address space,
  830. // since symbol lookup won't necessarily find a handy, in-range,
  831. // PLT stub for functions which could be anywhere.
  832. // Stub can use ip0 (== x16) to calculate address
  833. writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>
  834. writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>
  835. writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>
  836. writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
  837. writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
  838. return Addr;
  839. } else if (Arch == Triple::arm || Arch == Triple::armeb) {
  840. // TODO: There is only ARM far stub now. We should add the Thumb stub,
  841. // and stubs for branches Thumb - ARM and ARM - Thumb.
  842. writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc, [pc, #-4]
  843. return Addr + 4;
  844. } else if (IsMipsO32ABI || IsMipsN32ABI) {
  845. // 0: 3c190000 lui t9,%hi(addr).
  846. // 4: 27390000 addiu t9,t9,%lo(addr).
  847. // 8: 03200008 jr t9.
  848. // c: 00000000 nop.
  849. const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
  850. const unsigned NopInstr = 0x0;
  851. unsigned JrT9Instr = 0x03200008;
  852. if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||
  853. (AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
  854. JrT9Instr = 0x03200009;
  855. writeBytesUnaligned(LuiT9Instr, Addr, 4);
  856. writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);
  857. writeBytesUnaligned(JrT9Instr, Addr + 8, 4);
  858. writeBytesUnaligned(NopInstr, Addr + 12, 4);
  859. return Addr;
  860. } else if (IsMipsN64ABI) {
  861. // 0: 3c190000 lui t9,%highest(addr).
  862. // 4: 67390000 daddiu t9,t9,%higher(addr).
  863. // 8: 0019CC38 dsll t9,t9,16.
  864. // c: 67390000 daddiu t9,t9,%hi(addr).
  865. // 10: 0019CC38 dsll t9,t9,16.
  866. // 14: 67390000 daddiu t9,t9,%lo(addr).
  867. // 18: 03200008 jr t9.
  868. // 1c: 00000000 nop.
  869. const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,
  870. DsllT9Instr = 0x19CC38;
  871. const unsigned NopInstr = 0x0;
  872. unsigned JrT9Instr = 0x03200008;
  873. if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
  874. JrT9Instr = 0x03200009;
  875. writeBytesUnaligned(LuiT9Instr, Addr, 4);
  876. writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);
  877. writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);
  878. writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);
  879. writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);
  880. writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);
  881. writeBytesUnaligned(JrT9Instr, Addr + 24, 4);
  882. writeBytesUnaligned(NopInstr, Addr + 28, 4);
  883. return Addr;
  884. } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
  885. // Depending on which version of the ELF ABI is in use, we need to
  886. // generate one of two variants of the stub. They both start with
  887. // the same sequence to load the target address into r12.
  888. writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
  889. writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
  890. writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
  891. writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
  892. writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
  893. if (AbiVariant == 2) {
  894. // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
  895. // The address is already in r12 as required by the ABI. Branch to it.
  896. writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
  897. writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
  898. writeInt32BE(Addr+28, 0x4E800420); // bctr
  899. } else {
  900. // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
  901. // Load the function address on r11 and sets it to control register. Also
  902. // loads the function TOC in r2 and environment pointer to r11.
  903. writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
  904. writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
  905. writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
  906. writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
  907. writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
  908. writeInt32BE(Addr+40, 0x4E800420); // bctr
  909. }
  910. return Addr;
  911. } else if (Arch == Triple::systemz) {
  912. writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
  913. writeInt16BE(Addr+2, 0x0000);
  914. writeInt16BE(Addr+4, 0x0004);
  915. writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
  916. // 8-byte address stored at Addr + 8
  917. return Addr;
  918. } else if (Arch == Triple::x86_64) {
  919. *Addr = 0xFF; // jmp
  920. *(Addr+1) = 0x25; // rip
  921. // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
  922. } else if (Arch == Triple::x86) {
  923. *Addr = 0xE9; // 32-bit pc-relative jump.
  924. }
  925. return Addr;
  926. }
  927. // Assign an address to a symbol name and resolve all the relocations
  928. // associated with it.
  929. void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
  930. uint64_t Addr) {
  931. // The address to use for relocation resolution is not
  932. // the address of the local section buffer. We must be doing
  933. // a remote execution environment of some sort. Relocations can't
  934. // be applied until all the sections have been moved. The client must
  935. // trigger this with a call to MCJIT::finalize() or
  936. // RuntimeDyld::resolveRelocations().
  937. //
  938. // Addr is a uint64_t because we can't assume the pointer width
  939. // of the target is the same as that of the host. Just use a generic
  940. // "big enough" type.
  941. LLVM_DEBUG(
  942. dbgs() << "Reassigning address for section " << SectionID << " ("
  943. << Sections[SectionID].getName() << "): "
  944. << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
  945. << " -> " << format("0x%016" PRIx64, Addr) << "\n");
  946. Sections[SectionID].setLoadAddress(Addr);
  947. }
  948. void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
  949. uint64_t Value) {
  950. for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
  951. const RelocationEntry &RE = Relocs[i];
  952. // Ignore relocations for sections that were not loaded
  953. if (RE.SectionID != AbsoluteSymbolSection &&
  954. Sections[RE.SectionID].getAddress() == nullptr)
  955. continue;
  956. resolveRelocation(RE, Value);
  957. }
  958. }
  959. void RuntimeDyldImpl::applyExternalSymbolRelocations(
  960. const StringMap<JITEvaluatedSymbol> ExternalSymbolMap) {
  961. for (auto &RelocKV : ExternalSymbolRelocations) {
  962. StringRef Name = RelocKV.first();
  963. RelocationList &Relocs = RelocKV.second;
  964. if (Name.size() == 0) {
  965. // This is an absolute symbol, use an address of zero.
  966. LLVM_DEBUG(dbgs() << "Resolving absolute relocations."
  967. << "\n");
  968. resolveRelocationList(Relocs, 0);
  969. } else {
  970. uint64_t Addr = 0;
  971. JITSymbolFlags Flags;
  972. RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
  973. if (Loc == GlobalSymbolTable.end()) {
  974. auto RRI = ExternalSymbolMap.find(Name);
  975. assert(RRI != ExternalSymbolMap.end() && "No result for symbol");
  976. Addr = RRI->second.getAddress();
  977. Flags = RRI->second.getFlags();
  978. } else {
  979. // We found the symbol in our global table. It was probably in a
  980. // Module that we loaded previously.
  981. const auto &SymInfo = Loc->second;
  982. Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
  983. SymInfo.getOffset();
  984. Flags = SymInfo.getFlags();
  985. }
  986. // FIXME: Implement error handling that doesn't kill the host program!
  987. if (!Addr && !Resolver.allowsZeroSymbols())
  988. report_fatal_error(Twine("Program used external function '") + Name +
  989. "' which could not be resolved!");
  990. // If Resolver returned UINT64_MAX, the client wants to handle this symbol
  991. // manually and we shouldn't resolve its relocations.
  992. if (Addr != UINT64_MAX) {
  993. // Tweak the address based on the symbol flags if necessary.
  994. // For example, this is used by RuntimeDyldMachOARM to toggle the low bit
  995. // if the target symbol is Thumb.
  996. Addr = modifyAddressBasedOnFlags(Addr, Flags);
  997. LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
  998. << format("0x%lx", Addr) << "\n");
  999. resolveRelocationList(Relocs, Addr);
  1000. }
  1001. }
  1002. }
  1003. ExternalSymbolRelocations.clear();
  1004. }
  1005. Error RuntimeDyldImpl::resolveExternalSymbols() {
  1006. StringMap<JITEvaluatedSymbol> ExternalSymbolMap;
  1007. // Resolution can trigger emission of more symbols, so iterate until
  1008. // we've resolved *everything*.
  1009. {
  1010. JITSymbolResolver::LookupSet ResolvedSymbols;
  1011. while (true) {
  1012. JITSymbolResolver::LookupSet NewSymbols;
  1013. for (auto &RelocKV : ExternalSymbolRelocations) {
  1014. StringRef Name = RelocKV.first();
  1015. if (!Name.empty() && !GlobalSymbolTable.count(Name) &&
  1016. !ResolvedSymbols.count(Name))
  1017. NewSymbols.insert(Name);
  1018. }
  1019. if (NewSymbols.empty())
  1020. break;
  1021. #ifdef _MSC_VER
  1022. using ExpectedLookupResult =
  1023. MSVCPExpected<JITSymbolResolver::LookupResult>;
  1024. #else
  1025. using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
  1026. #endif
  1027. auto NewSymbolsP = std::make_shared<std::promise<ExpectedLookupResult>>();
  1028. auto NewSymbolsF = NewSymbolsP->get_future();
  1029. Resolver.lookup(NewSymbols,
  1030. [=](Expected<JITSymbolResolver::LookupResult> Result) {
  1031. NewSymbolsP->set_value(std::move(Result));
  1032. });
  1033. auto NewResolverResults = NewSymbolsF.get();
  1034. if (!NewResolverResults)
  1035. return NewResolverResults.takeError();
  1036. assert(NewResolverResults->size() == NewSymbols.size() &&
  1037. "Should have errored on unresolved symbols");
  1038. for (auto &RRKV : *NewResolverResults) {
  1039. assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");
  1040. ExternalSymbolMap.insert(RRKV);
  1041. ResolvedSymbols.insert(RRKV.first);
  1042. }
  1043. }
  1044. }
  1045. applyExternalSymbolRelocations(ExternalSymbolMap);
  1046. return Error::success();
  1047. }
  1048. void RuntimeDyldImpl::finalizeAsync(
  1049. std::unique_ptr<RuntimeDyldImpl> This,
  1050. unique_function<void(object::OwningBinary<object::ObjectFile>,
  1051. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
  1052. OnEmitted,
  1053. object::OwningBinary<object::ObjectFile> O,
  1054. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info) {
  1055. auto SharedThis = std::shared_ptr<RuntimeDyldImpl>(std::move(This));
  1056. auto PostResolveContinuation =
  1057. [SharedThis, OnEmitted = std::move(OnEmitted), O = std::move(O),
  1058. Info = std::move(Info)](
  1059. Expected<JITSymbolResolver::LookupResult> Result) mutable {
  1060. if (!Result) {
  1061. OnEmitted(std::move(O), std::move(Info), Result.takeError());
  1062. return;
  1063. }
  1064. /// Copy the result into a StringMap, where the keys are held by value.
  1065. StringMap<JITEvaluatedSymbol> Resolved;
  1066. for (auto &KV : *Result)
  1067. Resolved[KV.first] = KV.second;
  1068. SharedThis->applyExternalSymbolRelocations(Resolved);
  1069. SharedThis->resolveLocalRelocations();
  1070. SharedThis->registerEHFrames();
  1071. std::string ErrMsg;
  1072. if (SharedThis->MemMgr.finalizeMemory(&ErrMsg))
  1073. OnEmitted(std::move(O), std::move(Info),
  1074. make_error<StringError>(std::move(ErrMsg),
  1075. inconvertibleErrorCode()));
  1076. else
  1077. OnEmitted(std::move(O), std::move(Info), Error::success());
  1078. };
  1079. JITSymbolResolver::LookupSet Symbols;
  1080. for (auto &RelocKV : SharedThis->ExternalSymbolRelocations) {
  1081. StringRef Name = RelocKV.first();
  1082. if (Name.empty()) // Skip absolute symbol relocations.
  1083. continue;
  1084. assert(!SharedThis->GlobalSymbolTable.count(Name) &&
  1085. "Name already processed. RuntimeDyld instances can not be re-used "
  1086. "when finalizing with finalizeAsync.");
  1087. Symbols.insert(Name);
  1088. }
  1089. if (!Symbols.empty()) {
  1090. SharedThis->Resolver.lookup(Symbols, std::move(PostResolveContinuation));
  1091. } else
  1092. PostResolveContinuation(std::map<StringRef, JITEvaluatedSymbol>());
  1093. }
  1094. //===----------------------------------------------------------------------===//
  1095. // RuntimeDyld class implementation
  1096. uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
  1097. const object::SectionRef &Sec) const {
  1098. auto I = ObjSecToIDMap.find(Sec);
  1099. if (I != ObjSecToIDMap.end())
  1100. return RTDyld.Sections[I->second].getLoadAddress();
  1101. return 0;
  1102. }
  1103. RuntimeDyld::MemoryManager::TLSSection
  1104. RuntimeDyld::MemoryManager::allocateTLSSection(uintptr_t Size,
  1105. unsigned Alignment,
  1106. unsigned SectionID,
  1107. StringRef SectionName) {
  1108. report_fatal_error("allocation of TLS not implemented");
  1109. }
  1110. void RuntimeDyld::MemoryManager::anchor() {}
  1111. void JITSymbolResolver::anchor() {}
  1112. void LegacyJITSymbolResolver::anchor() {}
  1113. RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
  1114. JITSymbolResolver &Resolver)
  1115. : MemMgr(MemMgr), Resolver(Resolver) {
  1116. // FIXME: There's a potential issue lurking here if a single instance of
  1117. // RuntimeDyld is used to load multiple objects. The current implementation
  1118. // associates a single memory manager with a RuntimeDyld instance. Even
  1119. // though the public class spawns a new 'impl' instance for each load,
  1120. // they share a single memory manager. This can become a problem when page
  1121. // permissions are applied.
  1122. Dyld = nullptr;
  1123. ProcessAllSections = false;
  1124. }
  1125. RuntimeDyld::~RuntimeDyld() = default;
  1126. static std::unique_ptr<RuntimeDyldCOFF>
  1127. createRuntimeDyldCOFF(
  1128. Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  1129. JITSymbolResolver &Resolver, bool ProcessAllSections,
  1130. RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
  1131. std::unique_ptr<RuntimeDyldCOFF> Dyld =
  1132. RuntimeDyldCOFF::create(Arch, MM, Resolver);
  1133. Dyld->setProcessAllSections(ProcessAllSections);
  1134. Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
  1135. return Dyld;
  1136. }
  1137. static std::unique_ptr<RuntimeDyldELF>
  1138. createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  1139. JITSymbolResolver &Resolver, bool ProcessAllSections,
  1140. RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
  1141. std::unique_ptr<RuntimeDyldELF> Dyld =
  1142. RuntimeDyldELF::create(Arch, MM, Resolver);
  1143. Dyld->setProcessAllSections(ProcessAllSections);
  1144. Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
  1145. return Dyld;
  1146. }
  1147. static std::unique_ptr<RuntimeDyldMachO>
  1148. createRuntimeDyldMachO(
  1149. Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  1150. JITSymbolResolver &Resolver,
  1151. bool ProcessAllSections,
  1152. RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
  1153. std::unique_ptr<RuntimeDyldMachO> Dyld =
  1154. RuntimeDyldMachO::create(Arch, MM, Resolver);
  1155. Dyld->setProcessAllSections(ProcessAllSections);
  1156. Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
  1157. return Dyld;
  1158. }
  1159. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
  1160. RuntimeDyld::loadObject(const ObjectFile &Obj) {
  1161. if (!Dyld) {
  1162. if (Obj.isELF())
  1163. Dyld =
  1164. createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),
  1165. MemMgr, Resolver, ProcessAllSections,
  1166. std::move(NotifyStubEmitted));
  1167. else if (Obj.isMachO())
  1168. Dyld = createRuntimeDyldMachO(
  1169. static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
  1170. ProcessAllSections, std::move(NotifyStubEmitted));
  1171. else if (Obj.isCOFF())
  1172. Dyld = createRuntimeDyldCOFF(
  1173. static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
  1174. ProcessAllSections, std::move(NotifyStubEmitted));
  1175. else
  1176. report_fatal_error("Incompatible object format!");
  1177. }
  1178. if (!Dyld->isCompatibleFile(Obj))
  1179. report_fatal_error("Incompatible object format!");
  1180. auto LoadedObjInfo = Dyld->loadObject(Obj);
  1181. MemMgr.notifyObjectLoaded(*this, Obj);
  1182. return LoadedObjInfo;
  1183. }
  1184. void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
  1185. if (!Dyld)
  1186. return nullptr;
  1187. return Dyld->getSymbolLocalAddress(Name);
  1188. }
  1189. unsigned RuntimeDyld::getSymbolSectionID(StringRef Name) const {
  1190. assert(Dyld && "No RuntimeDyld instance attached");
  1191. return Dyld->getSymbolSectionID(Name);
  1192. }
  1193. JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {
  1194. if (!Dyld)
  1195. return nullptr;
  1196. return Dyld->getSymbol(Name);
  1197. }
  1198. std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {
  1199. if (!Dyld)
  1200. return std::map<StringRef, JITEvaluatedSymbol>();
  1201. return Dyld->getSymbolTable();
  1202. }
  1203. void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
  1204. void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
  1205. Dyld->reassignSectionAddress(SectionID, Addr);
  1206. }
  1207. void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
  1208. uint64_t TargetAddress) {
  1209. Dyld->mapSectionAddress(LocalAddress, TargetAddress);
  1210. }
  1211. bool RuntimeDyld::hasError() { return Dyld->hasError(); }
  1212. StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
  1213. void RuntimeDyld::finalizeWithMemoryManagerLocking() {
  1214. bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
  1215. MemMgr.FinalizationLocked = true;
  1216. resolveRelocations();
  1217. registerEHFrames();
  1218. if (!MemoryFinalizationLocked) {
  1219. MemMgr.finalizeMemory();
  1220. MemMgr.FinalizationLocked = false;
  1221. }
  1222. }
  1223. StringRef RuntimeDyld::getSectionContent(unsigned SectionID) const {
  1224. assert(Dyld && "No Dyld instance attached");
  1225. return Dyld->getSectionContent(SectionID);
  1226. }
  1227. uint64_t RuntimeDyld::getSectionLoadAddress(unsigned SectionID) const {
  1228. assert(Dyld && "No Dyld instance attached");
  1229. return Dyld->getSectionLoadAddress(SectionID);
  1230. }
  1231. void RuntimeDyld::registerEHFrames() {
  1232. if (Dyld)
  1233. Dyld->registerEHFrames();
  1234. }
  1235. void RuntimeDyld::deregisterEHFrames() {
  1236. if (Dyld)
  1237. Dyld->deregisterEHFrames();
  1238. }
  1239. // FIXME: Kill this with fire once we have a new JIT linker: this is only here
  1240. // so that we can re-use RuntimeDyld's implementation without twisting the
  1241. // interface any further for ORC's purposes.
  1242. void jitLinkForORC(
  1243. object::OwningBinary<object::ObjectFile> O,
  1244. RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
  1245. bool ProcessAllSections,
  1246. unique_function<Error(const object::ObjectFile &Obj,
  1247. RuntimeDyld::LoadedObjectInfo &LoadedObj,
  1248. std::map<StringRef, JITEvaluatedSymbol>)>
  1249. OnLoaded,
  1250. unique_function<void(object::OwningBinary<object::ObjectFile>,
  1251. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
  1252. OnEmitted) {
  1253. RuntimeDyld RTDyld(MemMgr, Resolver);
  1254. RTDyld.setProcessAllSections(ProcessAllSections);
  1255. auto Info = RTDyld.loadObject(*O.getBinary());
  1256. if (RTDyld.hasError()) {
  1257. OnEmitted(std::move(O), std::move(Info),
  1258. make_error<StringError>(RTDyld.getErrorString(),
  1259. inconvertibleErrorCode()));
  1260. return;
  1261. }
  1262. if (auto Err = OnLoaded(*O.getBinary(), *Info, RTDyld.getSymbolTable()))
  1263. OnEmitted(std::move(O), std::move(Info), std::move(Err));
  1264. RuntimeDyldImpl::finalizeAsync(std::move(RTDyld.Dyld), std::move(OnEmitted),
  1265. std::move(O), std::move(Info));
  1266. }
  1267. } // end namespace llvm